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/Compression.h"
50#include "llvm/Support/Error.h"
51#include "llvm/Support/FileSystem.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/Path.h"
54#include "llvm/Support/Process.h"
55#include "llvm/Support/YAMLParser.h"
56#include "llvm/TargetParser/AArch64TargetParser.h"
57#include "llvm/TargetParser/ARMTargetParserCommon.h"
58#include "llvm/TargetParser/Host.h"
59#include "llvm/TargetParser/LoongArchTargetParser.h"
60#include "llvm/TargetParser/PPCTargetParser.h"
61#include "llvm/TargetParser/RISCVISAInfo.h"
62#include "llvm/TargetParser/RISCVTargetParser.h"
63#include <cctype>
64#include <iterator>
65
66using namespace clang::driver;
67using namespace clang::driver::tools;
68using namespace clang;
69using namespace llvm::opt;
70
71static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
72 if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC,
73 options::OPT_fminimize_whitespace,
74 options::OPT_fno_minimize_whitespace,
75 options::OPT_fkeep_system_includes,
76 options::OPT_fno_keep_system_includes)) {
77 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
78 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
79 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
80 << A->getBaseArg().getAsString(Args)
81 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
82 }
83 }
84}
85
86static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
87 // In gcc, only ARM checks this, but it seems reasonable to check universally.
88 if (Args.hasArg(options::OPT_static))
89 if (const Arg *A =
90 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
91 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
92 << "-static";
93}
94
95/// Apply \a Work on the current tool chain \a RegularToolChain and any other
96/// offloading tool chain that is associated with the current action \a JA.
97static void
99 const ToolChain &RegularToolChain,
100 llvm::function_ref<void(const ToolChain &)> Work) {
101 // Apply Work on the current/regular tool chain.
102 Work(RegularToolChain);
103
104 // Apply Work on all the offloading tool chains associated with the current
105 // action.
108 if (JA.isHostOffloading(Kind)) {
109 auto TCs = C.getOffloadToolChains(Kind);
110 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
111 Work(*II->second);
112 } else if (JA.isDeviceOffloading(Kind))
113 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
114 }
115}
116
117static bool
119 const llvm::Triple &Triple) {
120 // We use the zero-cost exception tables for Objective-C if the non-fragile
121 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
122 // later.
123 if (runtime.isNonFragile())
124 return true;
125
126 if (!Triple.isMacOSX())
127 return false;
128
129 return (!Triple.isMacOSXVersionLT(10, 5) &&
130 (Triple.getArch() == llvm::Triple::x86_64 ||
131 Triple.getArch() == llvm::Triple::arm));
132}
133
134/// Adds exception related arguments to the driver command arguments. There's a
135/// main flag, -fexceptions and also language specific flags to enable/disable
136/// C++ and Objective-C exceptions. This makes it possible to for example
137/// disable C++ exceptions but enable Objective-C exceptions.
138static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
139 const ToolChain &TC, bool KernelOrKext,
140 bool IsDeviceOffloadAction,
141 const ObjCRuntime &objcRuntime,
142 ArgStringList &CmdArgs) {
143 const llvm::Triple &Triple = TC.getTriple();
144
145 if (KernelOrKext) {
146 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
147 // arguments now to avoid warnings about unused arguments.
148 Args.ClaimAllArgs(options::OPT_fexceptions);
149 Args.ClaimAllArgs(options::OPT_fno_exceptions);
150 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
151 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
152 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
153 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
154 Args.ClaimAllArgs(options::OPT_fasync_exceptions);
155 Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
156 return false;
157 }
158
159 // See if the user explicitly enabled exceptions.
160 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
161 false);
162
163 // Async exceptions are Windows MSVC only.
164 if (Triple.isWindowsMSVCEnvironment()) {
165 bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
166 options::OPT_fno_async_exceptions, false);
167 if (EHa) {
168 CmdArgs.push_back("-fasync-exceptions");
169 EH = true;
170 }
171 }
172
173 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
174 // is not necessarily sensible, but follows GCC.
175 if (types::isObjC(InputType) &&
176 Args.hasFlag(options::OPT_fobjc_exceptions,
177 options::OPT_fno_objc_exceptions, true)) {
178 CmdArgs.push_back("-fobjc-exceptions");
179
180 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
181 }
182
183 if (types::isCXX(InputType)) {
184 // Disable C++ EH by default on XCore, PS4/PS5 and GPU targets.
185 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
186 !Triple.isPS() && !Triple.isDriverKit() &&
187 !(Triple.isGPU() && !IsDeviceOffloadAction);
188 Arg *ExceptionArg = Args.getLastArg(
189 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
190 options::OPT_fexceptions, options::OPT_fno_exceptions);
191 if (ExceptionArg)
192 CXXExceptionsEnabled =
193 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
194 ExceptionArg->getOption().matches(options::OPT_fexceptions);
195
196 if (CXXExceptionsEnabled) {
197 CmdArgs.push_back("-fcxx-exceptions");
198
199 EH = true;
200 }
201 }
202
203 // OPT_fignore_exceptions means exception could still be thrown,
204 // but no clean up or catch would happen in current module.
205 // So we do not set EH to false.
206 Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
207
208 Args.addOptInFlag(CmdArgs, options::OPT_fassume_nothrow_exception_dtor,
209 options::OPT_fno_assume_nothrow_exception_dtor);
210
211 if (EH)
212 CmdArgs.push_back("-fexceptions");
213 return EH;
214}
215
216static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
217 const JobAction &JA) {
218 bool Default = true;
219 if (TC.getTriple().isOSDarwin()) {
220 // The native darwin assembler doesn't support the linker_option directives,
221 // so we disable them if we think the .s file will be passed to it.
223 }
224 // The linker_option directives are intended for host compilation.
227 Default = false;
228 return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
229 Default);
230}
231
232/// Add a CC1 option to specify the debug compilation directory.
233static const char *addDebugCompDirArg(const ArgList &Args,
234 ArgStringList &CmdArgs,
235 const llvm::vfs::FileSystem &VFS) {
236 std::string DebugCompDir;
237 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
238 options::OPT_fdebug_compilation_dir_EQ))
239 DebugCompDir = A->getValue();
240
241 if (DebugCompDir.empty()) {
242 if (llvm::ErrorOr<std::string> CWD = VFS.getCurrentWorkingDirectory())
243 DebugCompDir = std::move(*CWD);
244 else
245 return nullptr;
246 }
247 CmdArgs.push_back(
248 Args.MakeArgString("-fdebug-compilation-dir=" + DebugCompDir));
249 StringRef Path(CmdArgs.back());
250 return Path.substr(Path.find('=') + 1).data();
251}
252
253static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
254 const char *DebugCompilationDir,
255 const char *OutputFileName) {
256 // No need to generate a value for -object-file-name if it was provided.
257 for (auto *Arg : Args.filtered(options::OPT_Xclang))
258 if (StringRef(Arg->getValue()).starts_with("-object-file-name"))
259 return;
260
261 if (Args.hasArg(options::OPT_object_file_name_EQ))
262 return;
263
264 SmallString<128> ObjFileNameForDebug(OutputFileName);
265 if (ObjFileNameForDebug != "-" &&
266 !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
267 (!DebugCompilationDir ||
268 llvm::sys::path::is_absolute(DebugCompilationDir))) {
269 // Make the path absolute in the debug infos like MSVC does.
270 llvm::sys::fs::make_absolute(ObjFileNameForDebug);
271 }
272 // If the object file name is a relative path, then always use Windows
273 // backslash style as -object-file-name is used for embedding object file path
274 // in codeview and it can only be generated when targeting on Windows.
275 // Otherwise, just use native absolute path.
276 llvm::sys::path::Style Style =
277 llvm::sys::path::is_absolute(ObjFileNameForDebug)
278 ? llvm::sys::path::Style::native
279 : llvm::sys::path::Style::windows_backslash;
280 llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,
281 Style);
282 CmdArgs.push_back(
283 Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
284}
285
286/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
287static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
288 const ArgList &Args, ArgStringList &CmdArgs) {
289 auto AddOneArg = [&](StringRef Map, StringRef Name) {
290 if (!Map.contains('='))
291 D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
292 else
293 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
294 };
295
296 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
297 options::OPT_fdebug_prefix_map_EQ)) {
298 AddOneArg(A->getValue(), A->getOption().getName());
299 A->claim();
300 }
301 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
302 if (GlobalRemapEntry.empty())
303 return;
304 AddOneArg(GlobalRemapEntry, "environment");
305}
306
307/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
308static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
309 ArgStringList &CmdArgs) {
310 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
311 options::OPT_fmacro_prefix_map_EQ)) {
312 StringRef Map = A->getValue();
313 if (!Map.contains('='))
314 D.Diag(diag::err_drv_invalid_argument_to_option)
315 << Map << A->getOption().getName();
316 else
317 CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
318 A->claim();
319 }
320}
321
322/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
323static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
324 ArgStringList &CmdArgs) {
325 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
326 options::OPT_fcoverage_prefix_map_EQ)) {
327 StringRef Map = A->getValue();
328 if (!Map.contains('='))
329 D.Diag(diag::err_drv_invalid_argument_to_option)
330 << Map << A->getOption().getName();
331 else
332 CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
333 A->claim();
334 }
335}
336
337/// Add -x lang to \p CmdArgs for \p Input.
338static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
339 ArgStringList &CmdArgs) {
340 // When using -verify-pch, we don't want to provide the type
341 // 'precompiled-header' if it was inferred from the file extension
342 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
343 return;
344
345 CmdArgs.push_back("-x");
346 if (Args.hasArg(options::OPT_rewrite_objc))
347 CmdArgs.push_back(types::getTypeName(types::TY_ObjCXX));
348 else {
349 // Map the driver type to the frontend type. This is mostly an identity
350 // mapping, except that the distinction between module interface units
351 // and other source files does not exist at the frontend layer.
352 const char *ClangType;
353 switch (Input.getType()) {
354 case types::TY_CXXModule:
355 case types::TY_CXXStdModule:
356 ClangType = "c++";
357 break;
358 case types::TY_PP_CXXModule:
359 ClangType = "c++-cpp-output";
360 break;
361 default:
362 ClangType = types::getTypeName(Input.getType());
363 break;
364 }
365 CmdArgs.push_back(ClangType);
366 }
367}
368
370 const JobAction &JA, const InputInfo &Output,
371 const ArgList &Args, SanitizerArgs &SanArgs,
372 ArgStringList &CmdArgs) {
373 const Driver &D = TC.getDriver();
374 const llvm::Triple &T = TC.getTriple();
375 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
376 options::OPT_fprofile_generate_EQ,
377 options::OPT_fno_profile_generate);
378 if (PGOGenerateArg &&
379 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
380 PGOGenerateArg = nullptr;
381
382 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
383
384 auto *ProfileGenerateArg = Args.getLastArg(
385 options::OPT_fprofile_instr_generate,
386 options::OPT_fprofile_instr_generate_EQ,
387 options::OPT_fno_profile_instr_generate);
388 if (ProfileGenerateArg &&
389 ProfileGenerateArg->getOption().matches(
390 options::OPT_fno_profile_instr_generate))
391 ProfileGenerateArg = nullptr;
392
393 if (PGOGenerateArg && ProfileGenerateArg)
394 D.Diag(diag::err_drv_argument_not_allowed_with)
395 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
396
397 auto *ProfileUseArg = getLastProfileUseArg(Args);
398
399 if (PGOGenerateArg && ProfileUseArg)
400 D.Diag(diag::err_drv_argument_not_allowed_with)
401 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
402
403 if (ProfileGenerateArg && ProfileUseArg)
404 D.Diag(diag::err_drv_argument_not_allowed_with)
405 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
406
407 if (CSPGOGenerateArg && PGOGenerateArg) {
408 D.Diag(diag::err_drv_argument_not_allowed_with)
409 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
410 PGOGenerateArg = nullptr;
411 }
412
413 if (TC.getTriple().isOSAIX()) {
414 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
415 D.Diag(diag::err_drv_unsupported_opt_for_target)
416 << ProfileSampleUseArg->getSpelling() << TC.getTripleString();
417 }
418
419 if (ProfileGenerateArg) {
420 if (ProfileGenerateArg->getOption().matches(
421 options::OPT_fprofile_instr_generate_EQ))
422 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
423 ProfileGenerateArg->getValue()));
424 // The default is to use Clang Instrumentation.
425 CmdArgs.push_back("-fprofile-instrument=clang");
426 if (TC.getTriple().isWindowsMSVCEnvironment() &&
427 Args.hasFlag(options::OPT_frtlib_defaultlib,
428 options::OPT_fno_rtlib_defaultlib, true)) {
429 // Add dependent lib for clang_rt.profile
430 CmdArgs.push_back(Args.MakeArgString(
431 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
432 }
433 }
434
435 if (auto *ColdFuncCoverageArg = Args.getLastArg(
436 options::OPT_fprofile_generate_cold_function_coverage,
437 options::OPT_fprofile_generate_cold_function_coverage_EQ)) {
438 SmallString<128> Path(
439 ColdFuncCoverageArg->getOption().matches(
440 options::OPT_fprofile_generate_cold_function_coverage_EQ)
441 ? ColdFuncCoverageArg->getValue()
442 : "");
443 llvm::sys::path::append(Path, "default_%m.profraw");
444 // FIXME: Idealy the file path should be passed through
445 // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is
446 // shared with other profile use path(see PGOOptions), we need to refactor
447 // PGOOptions to make it work.
448 CmdArgs.push_back("-mllvm");
449 CmdArgs.push_back(Args.MakeArgString(
450 Twine("--instrument-cold-function-only-path=") + Path));
451 CmdArgs.push_back("-mllvm");
452 CmdArgs.push_back("--pgo-instrument-cold-function-only");
453 CmdArgs.push_back("-mllvm");
454 CmdArgs.push_back("--pgo-function-entry-coverage");
455 CmdArgs.push_back("-fprofile-instrument=sample-coldcov");
456 }
457
458 if (auto *A = Args.getLastArg(options::OPT_ftemporal_profile)) {
459 if (!PGOGenerateArg && !CSPGOGenerateArg)
460 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
461 << A->getSpelling() << "-fprofile-generate or -fcs-profile-generate";
462 CmdArgs.push_back("-mllvm");
463 CmdArgs.push_back("--pgo-temporal-instrumentation");
464 }
465
466 Arg *PGOGenArg = nullptr;
467 if (PGOGenerateArg) {
468 assert(!CSPGOGenerateArg);
469 PGOGenArg = PGOGenerateArg;
470 CmdArgs.push_back("-fprofile-instrument=llvm");
471 }
472 if (CSPGOGenerateArg) {
473 assert(!PGOGenerateArg);
474 PGOGenArg = CSPGOGenerateArg;
475 CmdArgs.push_back("-fprofile-instrument=csllvm");
476 }
477 if (PGOGenArg) {
478 if (TC.getTriple().isWindowsMSVCEnvironment() &&
479 Args.hasFlag(options::OPT_frtlib_defaultlib,
480 options::OPT_fno_rtlib_defaultlib, true)) {
481 // Add dependent lib for clang_rt.profile
482 CmdArgs.push_back(Args.MakeArgString(
483 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
484 }
485 if (PGOGenArg->getOption().matches(
486 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
487 : options::OPT_fcs_profile_generate_EQ)) {
488 SmallString<128> Path(PGOGenArg->getValue());
489 llvm::sys::path::append(Path, "default_%m.profraw");
490 CmdArgs.push_back(
491 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
492 }
493 }
494
495 if (ProfileUseArg) {
496 SmallString<128> UsePathBuf;
497 StringRef UsePath;
498 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
499 UsePath = ProfileUseArg->getValue();
500 else if ((ProfileUseArg->getOption().matches(
501 options::OPT_fprofile_use_EQ) ||
502 ProfileUseArg->getOption().matches(
503 options::OPT_fprofile_instr_use))) {
504 UsePathBuf =
505 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue();
506 if (UsePathBuf.empty() || llvm::sys::fs::is_directory(UsePathBuf))
507 llvm::sys::path::append(UsePathBuf, "default.profdata");
508 UsePath = UsePathBuf;
509 }
510 auto ReaderOrErr =
511 llvm::IndexedInstrProfReader::create(UsePath, D.getVFS());
512 if (auto E = ReaderOrErr.takeError()) {
513 auto DiagID = D.getDiags().getCustomDiagID(
514 DiagnosticsEngine::Error, "Error in reading profile %0: %1");
515 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
516 D.Diag(DiagID) << UsePath.str() << EI.message();
517 });
518 } else {
519 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
520 std::move(ReaderOrErr.get());
521 StringRef UseKind;
522 // Currently memprof profiles are only added at the IR level. Mark the
523 // profile type as IR in that case as well and the subsequent matching
524 // needs to detect which is available (might be one or both).
525 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
526 if (PGOReader->hasCSIRLevelProfile())
527 UseKind = "csllvm";
528 else
529 UseKind = "llvm";
530 } else
531 UseKind = "clang";
532
533 CmdArgs.push_back(
534 Args.MakeArgString("-fprofile-instrument-use=" + UseKind));
535 CmdArgs.push_back(
536 Args.MakeArgString("-fprofile-instrument-use-path=" + UsePath));
537 }
538 }
539
540 bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
541 options::OPT_fno_test_coverage, false) ||
542 Args.hasArg(options::OPT_coverage);
543 bool EmitCovData = TC.needsGCovInstrumentation(Args);
544
545 if (Args.hasFlag(options::OPT_fcoverage_mapping,
546 options::OPT_fno_coverage_mapping, false)) {
547 if (!ProfileGenerateArg)
548 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
549 << "-fcoverage-mapping"
550 << "-fprofile-instr-generate";
551
552 CmdArgs.push_back("-fcoverage-mapping");
553 }
554
555 if (Args.hasFlag(options::OPT_fmcdc_coverage, options::OPT_fno_mcdc_coverage,
556 false)) {
557 if (!Args.hasFlag(options::OPT_fcoverage_mapping,
558 options::OPT_fno_coverage_mapping, false))
559 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
560 << "-fcoverage-mcdc"
561 << "-fcoverage-mapping";
562
563 CmdArgs.push_back("-fcoverage-mcdc");
564 }
565
566 StringRef CoverageCompDir;
567 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
568 options::OPT_fcoverage_compilation_dir_EQ))
569 CoverageCompDir = A->getValue();
570 if (CoverageCompDir.empty()) {
571 if (auto CWD = D.getVFS().getCurrentWorkingDirectory())
572 CmdArgs.push_back(
573 Args.MakeArgString(Twine("-fcoverage-compilation-dir=") + *CWD));
574 } else
575 CmdArgs.push_back(Args.MakeArgString(Twine("-fcoverage-compilation-dir=") +
576 CoverageCompDir));
577
578 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
579 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
580 if (!Args.hasArg(options::OPT_coverage))
581 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
582 << "-fprofile-exclude-files="
583 << "--coverage";
584
585 StringRef v = Arg->getValue();
586 CmdArgs.push_back(
587 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
588 }
589
590 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
591 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
592 if (!Args.hasArg(options::OPT_coverage))
593 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
594 << "-fprofile-filter-files="
595 << "--coverage";
596
597 StringRef v = Arg->getValue();
598 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
599 }
600
601 if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
602 StringRef Val = A->getValue();
603 if (Val == "atomic" || Val == "prefer-atomic")
604 CmdArgs.push_back("-fprofile-update=atomic");
605 else if (Val != "single")
606 D.Diag(diag::err_drv_unsupported_option_argument)
607 << A->getSpelling() << Val;
608 }
609 if (const auto *A = Args.getLastArg(options::OPT_fprofile_continuous)) {
610 if (!PGOGenerateArg && !CSPGOGenerateArg && !ProfileGenerateArg)
611 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
612 << A->getSpelling()
613 << "-fprofile-generate, -fprofile-instr-generate, or "
614 "-fcs-profile-generate";
615 else {
616 CmdArgs.push_back("-fprofile-continuous");
617 // Platforms that require a bias variable:
618 if (T.isOSBinFormatELF() || T.isOSAIX() || T.isOSWindows()) {
619 CmdArgs.push_back("-mllvm");
620 CmdArgs.push_back("-runtime-counter-relocation");
621 }
622 // -fprofile-instr-generate does not decide the profile file name in the
623 // FE, and so it does not define the filename symbol
624 // (__llvm_profile_filename). Instead, the runtime uses the name
625 // "default.profraw" for the profile file. When continuous mode is ON, we
626 // will create the filename symbol so that we can insert the "%c"
627 // modifier.
628 if (ProfileGenerateArg &&
629 (ProfileGenerateArg->getOption().matches(
630 options::OPT_fprofile_instr_generate) ||
631 (ProfileGenerateArg->getOption().matches(
632 options::OPT_fprofile_instr_generate_EQ) &&
633 strlen(ProfileGenerateArg->getValue()) == 0)))
634 CmdArgs.push_back("-fprofile-instrument-path=default.profraw");
635 }
636 }
637
638 int FunctionGroups = 1;
639 int SelectedFunctionGroup = 0;
640 if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
641 StringRef Val = A->getValue();
642 if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
643 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
644 }
645 if (const auto *A =
646 Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
647 StringRef Val = A->getValue();
648 if (Val.getAsInteger(0, SelectedFunctionGroup) ||
649 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
650 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
651 }
652 if (FunctionGroups != 1)
653 CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
654 Twine(FunctionGroups)));
655 if (SelectedFunctionGroup != 0)
656 CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
657 Twine(SelectedFunctionGroup)));
658
659 // Leave -fprofile-dir= an unused argument unless .gcda emission is
660 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
661 // the flag used. There is no -fno-profile-dir, so the user has no
662 // targeted way to suppress the warning.
663 Arg *FProfileDir = nullptr;
664 if (Args.hasArg(options::OPT_fprofile_arcs) ||
665 Args.hasArg(options::OPT_coverage))
666 FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
667
668 // Put the .gcno and .gcda files (if needed) next to the primary output file,
669 // or fall back to a file in the current directory for `clang -c --coverage
670 // d/a.c` in the absence of -o.
671 if (EmitCovNotes || EmitCovData) {
672 SmallString<128> CoverageFilename;
673 if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
674 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
675 // path separator.
676 CoverageFilename = DumpDir->getValue();
677 CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
678 } else if (Arg *FinalOutput =
679 C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
680 CoverageFilename = FinalOutput->getValue();
681 } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
682 CoverageFilename = FinalOutput->getValue();
683 } else {
684 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
685 }
686 if (llvm::sys::path::is_relative(CoverageFilename))
687 (void)D.getVFS().makeAbsolute(CoverageFilename);
688 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
689 if (EmitCovNotes) {
690 CmdArgs.push_back(
691 Args.MakeArgString("-coverage-notes-file=" + CoverageFilename));
692 }
693
694 if (EmitCovData) {
695 if (FProfileDir) {
696 SmallString<128> Gcno = std::move(CoverageFilename);
697 CoverageFilename = FProfileDir->getValue();
698 llvm::sys::path::append(CoverageFilename, Gcno);
699 }
700 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
701 CmdArgs.push_back(
702 Args.MakeArgString("-coverage-data-file=" + CoverageFilename));
703 }
704 }
705}
706
707static void
708RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
709 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
710 unsigned DwarfVersion,
711 llvm::DebuggerKind DebuggerTuning) {
712 addDebugInfoKind(CmdArgs, DebugInfoKind);
713 if (DwarfVersion > 0)
714 CmdArgs.push_back(
715 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
716 switch (DebuggerTuning) {
717 case llvm::DebuggerKind::GDB:
718 CmdArgs.push_back("-debugger-tuning=gdb");
719 break;
720 case llvm::DebuggerKind::LLDB:
721 CmdArgs.push_back("-debugger-tuning=lldb");
722 break;
723 case llvm::DebuggerKind::SCE:
724 CmdArgs.push_back("-debugger-tuning=sce");
725 break;
726 case llvm::DebuggerKind::DBX:
727 CmdArgs.push_back("-debugger-tuning=dbx");
728 break;
729 default:
730 break;
731 }
732}
733
734static void RenderDebugInfoCompressionArgs(const ArgList &Args,
735 ArgStringList &CmdArgs,
736 const Driver &D,
737 const ToolChain &TC) {
738 const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
739 if (!A)
740 return;
741 if (checkDebugInfoOption(A, Args, D, TC)) {
742 StringRef Value = A->getValue();
743 if (Value == "none") {
744 CmdArgs.push_back("--compress-debug-sections=none");
745 } else if (Value == "zlib") {
746 if (llvm::compression::zlib::isAvailable()) {
747 CmdArgs.push_back(
748 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
749 } else {
750 D.Diag(diag::warn_debug_compression_unavailable) << "zlib";
751 }
752 } else if (Value == "zstd") {
753 if (llvm::compression::zstd::isAvailable()) {
754 CmdArgs.push_back(
755 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
756 } else {
757 D.Diag(diag::warn_debug_compression_unavailable) << "zstd";
758 }
759 } else {
760 D.Diag(diag::err_drv_unsupported_option_argument)
761 << A->getSpelling() << Value;
762 }
763 }
764}
765
767 const ArgList &Args,
768 ArgStringList &CmdArgs,
769 bool IsCC1As = false) {
770 // If no version was requested by the user, use the default value from the
771 // back end. This is consistent with the value returned from
772 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
773 // requiring the corresponding llvm to have the AMDGPU target enabled,
774 // provided the user (e.g. front end tests) can use the default.
776 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
777 CmdArgs.insert(CmdArgs.begin() + 1,
778 Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
779 Twine(CodeObjVer)));
780 CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
781 // -cc1as does not accept -mcode-object-version option.
782 if (!IsCC1As)
783 CmdArgs.insert(CmdArgs.begin() + 1,
784 Args.MakeArgString(Twine("-mcode-object-version=") +
785 Twine(CodeObjVer)));
786 }
787}
788
789static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
790 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
791 D.getVFS().getBufferForFile(Path);
792 if (!MemBuf)
793 return false;
794 llvm::file_magic Magic = llvm::identify_magic((*MemBuf)->getBuffer());
795 if (Magic == llvm::file_magic::unknown)
796 return false;
797 // Return true for both raw Clang AST files and object files which may
798 // contain a __clangast section.
799 if (Magic == llvm::file_magic::clang_ast)
800 return true;
802 llvm::object::ObjectFile::createObjectFile(**MemBuf, Magic);
803 return !Obj.takeError();
804}
805
806static bool gchProbe(const Driver &D, StringRef Path) {
807 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
808 if (!Status)
809 return false;
810
811 if (Status->isDirectory()) {
812 std::error_code EC;
813 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Path, EC), DE;
814 !EC && DI != DE; DI = DI.increment(EC)) {
815 if (maybeHasClangPchSignature(D, DI->path()))
816 return true;
817 }
818 D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;
819 return false;
820 }
821
822 if (maybeHasClangPchSignature(D, Path))
823 return true;
824 D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;
825 return false;
826}
827
828void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
829 const Driver &D, const ArgList &Args,
830 ArgStringList &CmdArgs,
831 const InputInfo &Output,
832 const InputInfoList &Inputs) const {
833 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
834
836
837 Args.AddLastArg(CmdArgs, options::OPT_C);
838 Args.AddLastArg(CmdArgs, options::OPT_CC);
839
840 // Handle dependency file generation.
841 Arg *ArgM = Args.getLastArg(options::OPT_MM);
842 if (!ArgM)
843 ArgM = Args.getLastArg(options::OPT_M);
844 Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
845 if (!ArgMD)
846 ArgMD = Args.getLastArg(options::OPT_MD);
847
848 // -M and -MM imply -w.
849 if (ArgM)
850 CmdArgs.push_back("-w");
851 else
852 ArgM = ArgMD;
853
854 if (ArgM) {
856 // Determine the output location.
857 const char *DepFile;
858 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
859 DepFile = MF->getValue();
860 C.addFailureResultFile(DepFile, &JA);
861 } else if (Output.getType() == types::TY_Dependencies) {
862 DepFile = Output.getFilename();
863 } else if (!ArgMD) {
864 DepFile = "-";
865 } else {
866 DepFile = getDependencyFileName(Args, Inputs);
867 C.addFailureResultFile(DepFile, &JA);
868 }
869 CmdArgs.push_back("-dependency-file");
870 CmdArgs.push_back(DepFile);
871 }
872 // Cmake generates dependency files using all compilation options specified
873 // by users. Claim those not used for dependency files.
875 Args.ClaimAllArgs(options::OPT_offload_compress);
876 Args.ClaimAllArgs(options::OPT_no_offload_compress);
877 Args.ClaimAllArgs(options::OPT_offload_jobs_EQ);
878 }
879
880 bool HasTarget = false;
881 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
882 HasTarget = true;
883 A->claim();
884 if (A->getOption().matches(options::OPT_MT)) {
885 A->render(Args, CmdArgs);
886 } else {
887 CmdArgs.push_back("-MT");
888 SmallString<128> Quoted;
889 quoteMakeTarget(A->getValue(), Quoted);
890 CmdArgs.push_back(Args.MakeArgString(Quoted));
891 }
892 }
893
894 // Add a default target if one wasn't specified.
895 if (!HasTarget) {
896 const char *DepTarget;
897
898 // If user provided -o, that is the dependency target, except
899 // when we are only generating a dependency file.
900 Arg *OutputOpt = Args.getLastArg(options::OPT_o, options::OPT__SLASH_Fo);
901 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
902 DepTarget = OutputOpt->getValue();
903 } else {
904 // Otherwise derive from the base input.
905 //
906 // FIXME: This should use the computed output file location.
907 SmallString<128> P(Inputs[0].getBaseInput());
908 llvm::sys::path::replace_extension(P, "o");
909 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
910 }
911
912 CmdArgs.push_back("-MT");
913 SmallString<128> Quoted;
914 quoteMakeTarget(DepTarget, Quoted);
915 CmdArgs.push_back(Args.MakeArgString(Quoted));
916 }
917
918 if (ArgM->getOption().matches(options::OPT_M) ||
919 ArgM->getOption().matches(options::OPT_MD))
920 CmdArgs.push_back("-sys-header-deps");
921
922 // Determine module file deps mode.
923 StringRef ModuleFileDepsVal;
924 if (Arg *A = Args.getLastArg(options::OPT_fmodule_file_deps_EQ,
925 options::OPT_fmodule_file_deps,
926 options::OPT_fno_module_file_deps)) {
927 if (A->getOption().matches(options::OPT_fmodule_file_deps_EQ))
928 ModuleFileDepsVal = A->getValue();
929 else if (A->getOption().matches(options::OPT_fmodule_file_deps))
930 ModuleFileDepsVal = "all";
931 else
932 ModuleFileDepsVal = "none";
933 } else if (isa<PrecompileJobAction>(JA)) {
934 ModuleFileDepsVal = "all";
935 }
936 if (!ModuleFileDepsVal.empty() && ModuleFileDepsVal != "none")
937 CmdArgs.push_back(
938 Args.MakeArgString("-module-file-deps=" + ModuleFileDepsVal));
939 }
940
941 if (Args.hasArg(options::OPT_MG)) {
942 if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
943 ArgM->getOption().matches(options::OPT_MMD))
944 D.Diag(diag::err_drv_mg_requires_m_or_mm);
945 CmdArgs.push_back("-MG");
946 }
947
948 Args.AddLastArg(CmdArgs, options::OPT_MP);
949 Args.AddLastArg(CmdArgs, options::OPT_MV);
950
951 // Add offload include arguments specific for CUDA/HIP/SYCL. This must happen
952 // before we -I or -include anything else, because we must pick up the
953 // CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL installation,
954 // rather than from e.g. /usr/local/include.
956 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
958 getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
960 getToolChain().addSYCLIncludeArgs(Args, CmdArgs);
961
962 // If we are offloading to a target via OpenMP we need to include the
963 // openmp_wrappers folder which contains alternative system headers.
965 !Args.hasArg(options::OPT_nostdinc) &&
966 Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc,
967 true) &&
968 getToolChain().getTriple().isGPU()) {
969 if (!Args.hasArg(options::OPT_nobuiltininc)) {
970 // Add openmp_wrappers/* to our system include path. This lets us wrap
971 // standard library headers.
972 SmallString<128> P(D.ResourceDir);
973 llvm::sys::path::append(P, "include");
974 llvm::sys::path::append(P, "openmp_wrappers");
975 CmdArgs.push_back("-internal-isystem");
976 CmdArgs.push_back(Args.MakeArgString(P));
977 }
978
979 CmdArgs.push_back("-include");
980 CmdArgs.push_back("__clang_openmp_device_functions.h");
981 }
982
983 if (Args.hasArg(options::OPT_foffload_via_llvm)) {
984 // Add llvm_wrappers/* to our system include path. This lets us wrap
985 // standard library headers and other headers.
986 SmallString<128> P(D.ResourceDir);
987 llvm::sys::path::append(P, "include", "llvm_offload_wrappers");
988 CmdArgs.append({"-internal-isystem", Args.MakeArgString(P), "-include"});
990 CmdArgs.push_back("__llvm_offload_device.h");
991 else
992 CmdArgs.push_back("__llvm_offload_host.h");
993 }
994
995 // Add -i* options, and automatically translate to
996 // -include-pch/-include-pth for transparent PCH support. It's
997 // wonky, but we include looking for .gch so we can support seamless
998 // replacement into a build system already set up to be generating
999 // .gch files.
1000
1001 if (getToolChain().getDriver().IsCLMode()) {
1002 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1003 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1004 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1006 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1007 // -fpch-instantiate-templates is the default when creating
1008 // precomp using /Yc
1009 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1010 options::OPT_fno_pch_instantiate_templates, true))
1011 CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1012 }
1013 if (YcArg || YuArg) {
1014 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1015 if (!isa<PrecompileJobAction>(JA)) {
1016 CmdArgs.push_back("-include-pch");
1017 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1018 C, !ThroughHeader.empty()
1019 ? ThroughHeader
1020 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1021 }
1022
1023 if (ThroughHeader.empty()) {
1024 CmdArgs.push_back(Args.MakeArgString(
1025 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1026 } else {
1027 CmdArgs.push_back(
1028 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1029 }
1030 }
1031 }
1032
1033 bool RenderedImplicitInclude = false;
1034 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1035 if (A->getOption().matches(options::OPT_include) &&
1036 D.getProbePrecompiled()) {
1037 // Handling of gcc-style gch precompiled headers.
1038 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1039 RenderedImplicitInclude = true;
1040
1041 bool FoundPCH = false;
1042 SmallString<128> P(A->getValue());
1043 // We want the files to have a name like foo.h.pch. Add a dummy extension
1044 // so that replace_extension does the right thing.
1045 P += ".dummy";
1046 llvm::sys::path::replace_extension(P, "pch");
1047 if (D.getVFS().exists(P))
1048 FoundPCH = true;
1049
1050 if (!FoundPCH) {
1051 // For GCC compat, probe for a file or directory ending in .gch instead.
1052 llvm::sys::path::replace_extension(P, "gch");
1053 FoundPCH = gchProbe(D, P.str());
1054 }
1055
1056 if (FoundPCH) {
1057 if (IsFirstImplicitInclude) {
1058 A->claim();
1059 CmdArgs.push_back("-include-pch");
1060 CmdArgs.push_back(Args.MakeArgString(P));
1061 continue;
1062 } else {
1063 // Ignore the PCH if not first on command line and emit warning.
1064 D.Diag(diag::warn_drv_pch_not_first_include) << P
1065 << A->getAsString(Args);
1066 }
1067 }
1068 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1069 // Handling of paths which must come late. These entries are handled by
1070 // the toolchain itself after the resource dir is inserted in the right
1071 // search order.
1072 // Do not claim the argument so that the use of the argument does not
1073 // silently go unnoticed on toolchains which do not honour the option.
1074 continue;
1075 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1076 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1077 continue;
1078 } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
1079 // This is used only by the driver. No need to pass to cc1.
1080 continue;
1081 }
1082
1083 // Not translated, render as usual.
1084 A->claim();
1085 A->render(Args, CmdArgs);
1086 }
1087
1088 if (C.isOffloadingHostKind(Action::OFK_Cuda) ||
1090 // Collect all enabled NVPTX architectures.
1091 std::set<unsigned> ArchIDs;
1092 for (auto &I : llvm::make_range(C.getOffloadToolChains(Action::OFK_Cuda))) {
1093 const ToolChain *TC = I.second;
1094 for (BoundArch Arch :
1095 D.getOffloadArchs(C, C.getArgs(), Action::OFK_Cuda, *TC)) {
1096 if (IsNVIDIAOffloadArch(Arch.Arch))
1097 ArchIDs.insert(CudaArchToID(Arch.Arch));
1098 }
1099 }
1100
1101 if (!ArchIDs.empty()) {
1102 SmallString<128> List;
1103 llvm::raw_svector_ostream OS(List);
1104 llvm::interleave(ArchIDs, OS, ",");
1105 CmdArgs.push_back(Args.MakeArgString("-D__CUDA_ARCH_LIST__=" + List));
1106 }
1107 }
1108
1109 Args.addAllArgs(CmdArgs,
1110 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1111 options::OPT_F, options::OPT_embed_dir_EQ});
1112
1113 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1114
1115 // FIXME: There is a very unfortunate problem here, some troubled
1116 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1117 // really support that we would have to parse and then translate
1118 // those options. :(
1119 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1120 options::OPT_Xpreprocessor);
1121
1122 // -I- is a deprecated GCC feature, reject it.
1123 if (Arg *A = Args.getLastArg(options::OPT_I_))
1124 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1125
1126 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1127 // -isysroot to the CC1 invocation.
1128 StringRef sysroot = C.getSysRoot();
1129 if (sysroot != "") {
1130 if (!Args.hasArg(options::OPT_isysroot)) {
1131 CmdArgs.push_back("-isysroot");
1132 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1133 }
1134 }
1135
1136 // Parse additional include paths from environment variables.
1137 // FIXME: We should probably sink the logic for handling these from the
1138 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1139 // CPATH - included following the user specified includes (but prior to
1140 // builtin and standard includes).
1141 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1142 // C_INCLUDE_PATH - system includes enabled when compiling C.
1143 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1144 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1145 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1146 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1147 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1148 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1149 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1150
1151 // While adding the include arguments, we also attempt to retrieve the
1152 // arguments of related offloading toolchains or arguments that are specific
1153 // of an offloading programming model.
1154
1155 // Add C++ include arguments, if needed.
1156 if (types::isCXX(Inputs[0].getType())) {
1157 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1159 C, JA, getToolChain(),
1160 [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1161 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1162 : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1163 });
1164 }
1165
1166 // If we are compiling for a GPU target we want to override the system headers
1167 // with ones created by the 'libc' project if present.
1168 // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1169 // OffloadKind as an argument.
1170 if (!Args.hasArg(options::OPT_nostdinc) &&
1171 Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc,
1172 true) &&
1173 !Args.hasArg(options::OPT_nobuiltininc) &&
1174 (C.getActiveOffloadKinds() == Action::OFK_OpenMP)) {
1175 // TODO: CUDA / HIP include their own headers for some common functions
1176 // implemented here. We'll need to clean those up so they do not conflict.
1177 SmallString<128> P(D.ResourceDir);
1178 llvm::sys::path::append(P, "include");
1179 llvm::sys::path::append(P, "llvm_libc_wrappers");
1180 CmdArgs.push_back("-internal-isystem");
1181 CmdArgs.push_back(Args.MakeArgString(P));
1182 }
1183
1184 // Add system include arguments for all targets but IAMCU.
1185 if (!IsIAMCU)
1187 [&Args, &CmdArgs](const ToolChain &TC) {
1188 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1189 });
1190 else {
1191 // For IAMCU add special include arguments.
1192 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1193 }
1194
1195 addMacroPrefixMapArg(D, Args, CmdArgs);
1196 addCoveragePrefixMapArg(D, Args, CmdArgs);
1197
1198 Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
1199 options::OPT_fno_file_reproducible);
1200
1201 if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1202 CmdArgs.push_back("-source-date-epoch");
1203 CmdArgs.push_back(Args.MakeArgString(Epoch));
1204 }
1205
1206 Args.addOptInFlag(CmdArgs, options::OPT_fdefine_target_os_macros,
1207 options::OPT_fno_define_target_os_macros);
1208}
1209
1210// FIXME: Move to target hook.
1211static bool isSignedCharDefault(const llvm::Triple &Triple) {
1212 switch (Triple.getArch()) {
1213 default:
1214 return true;
1215
1216 case llvm::Triple::aarch64:
1217 case llvm::Triple::aarch64_32:
1218 case llvm::Triple::aarch64_be:
1219 case llvm::Triple::arm:
1220 case llvm::Triple::armeb:
1221 case llvm::Triple::thumb:
1222 case llvm::Triple::thumbeb:
1223 if (Triple.isOSDarwin() || Triple.isOSWindows())
1224 return true;
1225 return false;
1226
1227 case llvm::Triple::ppc:
1228 case llvm::Triple::ppc64:
1229 if (Triple.isOSDarwin())
1230 return true;
1231 return false;
1232
1233 case llvm::Triple::csky:
1234 case llvm::Triple::hexagon:
1235 case llvm::Triple::msp430:
1236 case llvm::Triple::ppcle:
1237 case llvm::Triple::ppc64le:
1238 case llvm::Triple::riscv32:
1239 case llvm::Triple::riscv64:
1240 case llvm::Triple::riscv32be:
1241 case llvm::Triple::riscv64be:
1242 case llvm::Triple::systemz:
1243 case llvm::Triple::xcore:
1244 case llvm::Triple::xtensa:
1245 return false;
1246 }
1247}
1248
1249static bool hasMultipleInvocations(const llvm::Triple &Triple,
1250 const ArgList &Args) {
1251 // Supported only on Darwin where we invoke the compiler multiple times
1252 // followed by an invocation to lipo.
1253 if (!Triple.isOSDarwin())
1254 return false;
1255 // If more than one "-arch <arch>" is specified, we're targeting multiple
1256 // architectures resulting in a fat binary.
1257 return Args.getAllArgValues(options::OPT_arch).size() > 1;
1258}
1259
1260static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1261 const llvm::Triple &Triple) {
1262 // When enabling remarks, we need to error if:
1263 // * The remark file is specified but we're targeting multiple architectures,
1264 // which means more than one remark file is being generated.
1266 bool hasExplicitOutputFile =
1267 Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1268 if (hasMultipleInvocations && hasExplicitOutputFile) {
1269 D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1270 << "-foptimization-record-file";
1271 return false;
1272 }
1273 return true;
1274}
1275
1276static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1277 const llvm::Triple &Triple,
1278 const InputInfo &Input,
1279 const InputInfo &Output, const JobAction &JA) {
1280 StringRef Format = "yaml";
1281 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1282 Format = A->getValue();
1283
1284 CmdArgs.push_back("-opt-record-file");
1285
1286 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1287 if (A) {
1288 CmdArgs.push_back(A->getValue());
1289 } else {
1290 bool hasMultipleArchs =
1291 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1292 Args.getAllArgValues(options::OPT_arch).size() > 1;
1293
1295
1296 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1297 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1298 F = FinalOutput->getValue();
1299 } else {
1300 if (Format != "yaml" && // For YAML, keep the original behavior.
1301 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1302 Output.isFilename())
1303 F = Output.getFilename();
1304 }
1305
1306 if (F.empty()) {
1307 // Use the input filename.
1308 F = llvm::sys::path::stem(Input.getBaseInput());
1309
1310 // If we're compiling for an offload architecture (i.e. a CUDA device),
1311 // we need to make the file name for the device compilation different
1312 // from the host compilation.
1315 llvm::sys::path::replace_extension(F, "");
1317 Triple.str());
1318 F += "-";
1319 F += JA.getOffloadingArch().ArchName;
1320 }
1321 }
1322
1323 // If we're having more than one "-arch", we should name the files
1324 // differently so that every cc1 invocation writes to a different file.
1325 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1326 // name from the triple.
1327 if (hasMultipleArchs) {
1328 // First, remember the extension.
1329 SmallString<64> OldExtension = llvm::sys::path::extension(F);
1330 // then, remove it.
1331 llvm::sys::path::replace_extension(F, "");
1332 // attach -<arch> to it.
1333 F += "-";
1334 F += Triple.getArchName();
1335 // put back the extension.
1336 llvm::sys::path::replace_extension(F, OldExtension);
1337 }
1338
1339 SmallString<32> Extension;
1340 Extension += "opt.";
1341 Extension += Format;
1342
1343 llvm::sys::path::replace_extension(F, Extension);
1344 CmdArgs.push_back(Args.MakeArgString(F));
1345 }
1346
1347 if (const Arg *A =
1348 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1349 CmdArgs.push_back("-opt-record-passes");
1350 CmdArgs.push_back(A->getValue());
1351 }
1352
1353 if (!Format.empty()) {
1354 CmdArgs.push_back("-opt-record-format");
1355 CmdArgs.push_back(Format.data());
1356 }
1357}
1358
1359void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1360 if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1361 options::OPT_fno_aapcs_bitfield_width, true))
1362 CmdArgs.push_back("-fno-aapcs-bitfield-width");
1363
1364 if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1365 CmdArgs.push_back("-faapcs-bitfield-load");
1366}
1367
1368namespace {
1369void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1370 const ArgList &Args, ArgStringList &CmdArgs) {
1371 // Select the ABI to use.
1372 // FIXME: Support -meabi.
1373 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1374 const char *ABIName = nullptr;
1375 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1376 ABIName = A->getValue();
1377 else
1378 ABIName = llvm::ARM::computeDefaultTargetABI(Triple).data();
1379
1380 CmdArgs.push_back("-target-abi");
1381 CmdArgs.push_back(ABIName);
1382}
1383
1384void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1385 auto StrictAlignIter =
1386 llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
1387 return Arg == "+strict-align" || Arg == "-strict-align";
1388 });
1389 if (StrictAlignIter != CmdArgs.rend() &&
1390 StringRef(*StrictAlignIter) == "+strict-align")
1391 CmdArgs.push_back("-Wunaligned-access");
1392}
1393}
1394
1395static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1396 ArgStringList &CmdArgs, bool isAArch64) {
1397 const llvm::Triple &Triple = TC.getEffectiveTriple();
1398 const Arg *A = isAArch64
1399 ? Args.getLastArg(options::OPT_msign_return_address_EQ,
1400 options::OPT_mbranch_protection_EQ)
1401 : Args.getLastArg(options::OPT_mbranch_protection_EQ);
1402 if (!A) {
1403 if (Triple.isOSOpenBSD() && isAArch64) {
1404 CmdArgs.push_back("-msign-return-address=non-leaf");
1405 CmdArgs.push_back("-msign-return-address-key=a_key");
1406 CmdArgs.push_back("-mbranch-target-enforce");
1407 }
1408 return;
1409 }
1410
1411 const Driver &D = TC.getDriver();
1412 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1413 D.Diag(diag::warn_incompatible_branch_protection_option)
1414 << Triple.getArchName();
1415
1416 StringRef Scope, Key;
1417 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1418
1419 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1420 Scope = A->getValue();
1421 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1422 D.Diag(diag::err_drv_unsupported_option_argument)
1423 << A->getSpelling() << Scope;
1424 Key = "a_key";
1425 IndirectBranches = Triple.isOSOpenBSD() && isAArch64;
1426 BranchProtectionPAuthLR = false;
1427 GuardedControlStack = false;
1428 } else {
1429 StringRef DiagMsg;
1430 llvm::ARM::ParsedBranchProtection PBP;
1431 bool EnablePAuthLR = false;
1432
1433 // To know if we need to enable PAuth-LR As part of the standard branch
1434 // protection option, it needs to be determined if the feature has been
1435 // activated in the `march` argument. This information is stored within the
1436 // CmdArgs variable and can be found using a search.
1437 if (isAArch64) {
1438 auto isPAuthLR = [](const char *member) {
1439 llvm::AArch64::ExtensionInfo pauthlr_extension =
1440 llvm::AArch64::getExtensionByID(llvm::AArch64::AEK_PAUTHLR);
1441 return llvm::AArch64::StrTab[pauthlr_extension.PosTargetFeature] ==
1442 member;
1443 };
1444
1445 if (llvm::any_of(CmdArgs, isPAuthLR))
1446 EnablePAuthLR = true;
1447 }
1448 if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg, Triple,
1449 EnablePAuthLR))
1450 D.Diag(diag::err_drv_unsupported_option_argument)
1451 << A->getSpelling() << DiagMsg;
1452 if (!isAArch64 && PBP.Key == "b_key")
1453 D.Diag(diag::warn_unsupported_branch_protection)
1454 << "b-key" << A->getAsString(Args);
1455 Scope = PBP.Scope;
1456 Key = PBP.Key;
1457 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1458 IndirectBranches = PBP.BranchTargetEnforcement;
1459 GuardedControlStack = PBP.GuardedControlStack;
1460 }
1461
1462 Arg *PtrauthReturnsArg = Args.getLastArg(options::OPT_fptrauth_returns,
1463 options::OPT_fno_ptrauth_returns);
1464 bool HasPtrauthReturns =
1465 PtrauthReturnsArg &&
1466 PtrauthReturnsArg->getOption().matches(options::OPT_fptrauth_returns);
1467 // GCS is currently untested with ptrauth-returns, but enabling this could be
1468 // allowed in future after testing with a suitable system.
1469 if (Scope != "none" || BranchProtectionPAuthLR || GuardedControlStack) {
1470 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1471 D.Diag(diag::err_drv_unsupported_opt_for_target)
1472 << A->getAsString(Args) << Triple.getTriple();
1473 else if (HasPtrauthReturns)
1474 D.Diag(diag::err_drv_incompatible_options)
1475 << A->getAsString(Args) << "-fptrauth-returns";
1476 }
1477
1478 CmdArgs.push_back(
1479 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1480 if (Scope != "none")
1481 CmdArgs.push_back(
1482 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1483 if (BranchProtectionPAuthLR)
1484 CmdArgs.push_back(
1485 Args.MakeArgString(Twine("-mbranch-protection-pauth-lr")));
1486 if (IndirectBranches)
1487 CmdArgs.push_back("-mbranch-target-enforce");
1488
1489 if (GuardedControlStack)
1490 CmdArgs.push_back("-mguarded-control-stack");
1491}
1492
1493void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1494 ArgStringList &CmdArgs, bool KernelOrKext) const {
1495 RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
1496
1497 // Determine floating point ABI from the options & target defaults.
1499 if (ABI == arm::FloatABI::Soft) {
1500 // Floating point operations and argument passing are soft.
1501 // FIXME: This changes CPP defines, we need -target-soft-float.
1502 CmdArgs.push_back("-msoft-float");
1503 CmdArgs.push_back("-mfloat-abi");
1504 CmdArgs.push_back("soft");
1505 } else if (ABI == arm::FloatABI::SoftFP) {
1506 // Floating point operations are hard, but argument passing is soft.
1507 CmdArgs.push_back("-mfloat-abi");
1508 CmdArgs.push_back("soft");
1509 } else {
1510 // Floating point operations and argument passing are hard.
1511 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1512 CmdArgs.push_back("-mfloat-abi");
1513 CmdArgs.push_back("hard");
1514 }
1515
1516 // Forward the -mglobal-merge option for explicit control over the pass.
1517 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1518 options::OPT_mno_global_merge)) {
1519 CmdArgs.push_back("-mllvm");
1520 if (A->getOption().matches(options::OPT_mno_global_merge))
1521 CmdArgs.push_back("-arm-global-merge=false");
1522 else
1523 CmdArgs.push_back("-arm-global-merge=true");
1524 }
1525
1526 if (!Args.hasFlag(options::OPT_mimplicit_float,
1527 options::OPT_mno_implicit_float, true))
1528 CmdArgs.push_back("-no-implicit-float");
1529
1530 if (Args.getLastArg(options::OPT_mcmse))
1531 CmdArgs.push_back("-mcmse");
1532
1533 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1534
1535 // Enable/disable return address signing and indirect branch targets.
1536 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
1537
1538 AddUnalignedAccessWarning(CmdArgs);
1539}
1540
1541void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1542 const ArgList &Args, bool KernelOrKext,
1543 ArgStringList &CmdArgs) const {
1544 const ToolChain &TC = getToolChain();
1545
1546 // Add the target features
1547 getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1548
1549 // Add target specific flags.
1550 switch (TC.getArch()) {
1551 default:
1552 break;
1553
1554 case llvm::Triple::arm:
1555 case llvm::Triple::armeb:
1556 case llvm::Triple::thumb:
1557 case llvm::Triple::thumbeb:
1558 // Use the effective triple, which takes into account the deployment target.
1559 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1560 break;
1561
1562 case llvm::Triple::aarch64:
1563 case llvm::Triple::aarch64_32:
1564 case llvm::Triple::aarch64_be:
1565 AddAArch64TargetArgs(Args, CmdArgs);
1566 break;
1567
1568 case llvm::Triple::loongarch32:
1569 case llvm::Triple::loongarch64:
1570 AddLoongArchTargetArgs(Args, CmdArgs);
1571 break;
1572
1573 case llvm::Triple::mips:
1574 case llvm::Triple::mipsel:
1575 case llvm::Triple::mips64:
1576 case llvm::Triple::mips64el:
1577 AddMIPSTargetArgs(Args, CmdArgs);
1578 break;
1579
1580 case llvm::Triple::ppc:
1581 case llvm::Triple::ppcle:
1582 case llvm::Triple::ppc64:
1583 case llvm::Triple::ppc64le:
1584 AddPPCTargetArgs(Args, CmdArgs);
1585 break;
1586
1587 case llvm::Triple::riscv32:
1588 case llvm::Triple::riscv64:
1589 case llvm::Triple::riscv32be:
1590 case llvm::Triple::riscv64be:
1591 AddRISCVTargetArgs(Args, CmdArgs);
1592 break;
1593
1594 case llvm::Triple::sparc:
1595 case llvm::Triple::sparcel:
1596 case llvm::Triple::sparcv9:
1597 AddSparcTargetArgs(Args, CmdArgs);
1598 break;
1599
1600 case llvm::Triple::systemz:
1601 AddSystemZTargetArgs(Args, CmdArgs);
1602 break;
1603
1604 case llvm::Triple::x86:
1605 case llvm::Triple::x86_64:
1606 AddX86TargetArgs(Args, CmdArgs);
1607 break;
1608
1609 case llvm::Triple::lanai:
1610 AddLanaiTargetArgs(Args, CmdArgs);
1611 break;
1612
1613 case llvm::Triple::hexagon:
1614 AddHexagonTargetArgs(Args, CmdArgs);
1615 break;
1616
1617 case llvm::Triple::wasm32:
1618 case llvm::Triple::wasm64:
1619 AddWebAssemblyTargetArgs(Args, CmdArgs);
1620 break;
1621
1622 case llvm::Triple::ve:
1623 AddVETargetArgs(Args, CmdArgs);
1624 break;
1625 }
1626}
1627
1628namespace {
1629void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1630 ArgStringList &CmdArgs) {
1631 const char *ABIName = nullptr;
1632 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1633 ABIName = A->getValue();
1634 else if (Triple.isOSDarwin())
1635 ABIName = "darwinpcs";
1636 // TODO: we probably want to have some target hook here.
1637 else if (Triple.isOSLinux() &&
1638 Triple.getEnvironment() == llvm::Triple::PAuthTest)
1639 ABIName = "pauthtest";
1640 else
1641 ABIName = "aapcs";
1642
1643 CmdArgs.push_back("-target-abi");
1644 CmdArgs.push_back(ABIName);
1645}
1646}
1647
1648void Clang::AddAArch64TargetArgs(const ArgList &Args,
1649 ArgStringList &CmdArgs) const {
1650 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1651
1652 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1653 Args.hasArg(options::OPT_mkernel) ||
1654 Args.hasArg(options::OPT_fapple_kext))
1655 CmdArgs.push_back("-disable-red-zone");
1656
1657 if (!Args.hasFlag(options::OPT_mimplicit_float,
1658 options::OPT_mno_implicit_float, true))
1659 CmdArgs.push_back("-no-implicit-float");
1660
1661 RenderAArch64ABI(Triple, Args, CmdArgs);
1662
1663 // Forward the -mglobal-merge option for explicit control over the pass.
1664 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1665 options::OPT_mno_global_merge)) {
1666 CmdArgs.push_back("-mllvm");
1667 if (A->getOption().matches(options::OPT_mno_global_merge))
1668 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1669 else
1670 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1671 }
1672
1673 // Handle -msve_vector_bits=<bits>
1674 auto HandleVectorBits = [&](Arg *A, StringRef VScaleMin,
1675 StringRef VScaleMax) {
1676 StringRef Val = A->getValue();
1677 const Driver &D = getToolChain().getDriver();
1678 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1679 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1680 Val == "1024+" || Val == "2048+") {
1681 unsigned Bits = 0;
1682 if (!Val.consume_back("+")) {
1683 bool Invalid = Val.getAsInteger(10, Bits);
1684 (void)Invalid;
1685 assert(!Invalid && "Failed to parse value");
1686 CmdArgs.push_back(
1687 Args.MakeArgString(VScaleMax + llvm::Twine(Bits / 128)));
1688 }
1689
1690 bool Invalid = Val.getAsInteger(10, Bits);
1691 (void)Invalid;
1692 assert(!Invalid && "Failed to parse value");
1693
1694 CmdArgs.push_back(
1695 Args.MakeArgString(VScaleMin + llvm::Twine(Bits / 128)));
1696 } else if (Val == "scalable") {
1697 // Silently drop requests for vector-length agnostic code as it's implied.
1698 } else {
1699 // Handle the unsupported values passed to msve-vector-bits.
1700 D.Diag(diag::err_drv_unsupported_option_argument)
1701 << A->getSpelling() << Val;
1702 }
1703 };
1704 if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ))
1705 HandleVectorBits(A, "-mvscale-min=", "-mvscale-max=");
1706 if (Arg *A = Args.getLastArg(options::OPT_msve_streaming_vector_bits_EQ))
1707 HandleVectorBits(A, "-mvscale-streaming-min=", "-mvscale-streaming-max=");
1708
1709 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1710
1711 if (auto TuneCPU = aarch64::getAArch64TargetTuneCPU(Args, Triple)) {
1712 CmdArgs.push_back("-tune-cpu");
1713 CmdArgs.push_back(Args.MakeArgString(*TuneCPU));
1714 }
1715
1716 AddUnalignedAccessWarning(CmdArgs);
1717
1718 if (Triple.isOSDarwin() ||
1719 (Triple.isOSLinux() &&
1720 Triple.getEnvironment() == llvm::Triple::PAuthTest)) {
1721 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_intrinsics,
1722 options::OPT_fno_ptrauth_intrinsics);
1723 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_calls,
1724 options::OPT_fno_ptrauth_calls);
1725 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_returns,
1726 options::OPT_fno_ptrauth_returns);
1727 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_auth_traps,
1728 options::OPT_fno_ptrauth_auth_traps);
1729 Args.addOptInFlag(
1730 CmdArgs, options::OPT_fptrauth_vtable_pointer_address_discrimination,
1731 options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1732 Args.addOptInFlag(
1733 CmdArgs, options::OPT_fptrauth_vtable_pointer_type_discrimination,
1734 options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1735 Args.addOptInFlag(
1736 CmdArgs, options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1737 options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1738 Args.addOptInFlag(
1739 CmdArgs, options::OPT_fptrauth_function_pointer_type_discrimination,
1740 options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1741 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_indirect_gotos,
1742 options::OPT_fno_ptrauth_indirect_gotos);
1743 }
1744 if (Triple.isOSLinux() &&
1745 Triple.getEnvironment() == llvm::Triple::PAuthTest) {
1746 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_init_fini,
1747 options::OPT_fno_ptrauth_init_fini);
1748 Args.addOptInFlag(
1749 CmdArgs, options::OPT_fptrauth_init_fini_address_discrimination,
1750 options::OPT_fno_ptrauth_init_fini_address_discrimination);
1751 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_elf_got,
1752 options::OPT_fno_ptrauth_elf_got);
1753 }
1754 Args.addOptInFlag(CmdArgs, options::OPT_faarch64_jump_table_hardening,
1755 options::OPT_fno_aarch64_jump_table_hardening);
1756
1757 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_isa,
1758 options::OPT_fno_ptrauth_objc_isa);
1759 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_interface_sel,
1760 options::OPT_fno_ptrauth_objc_interface_sel);
1761 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_class_ro,
1762 options::OPT_fno_ptrauth_objc_class_ro);
1763
1764 // Enable/disable return address signing and indirect branch targets.
1765 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1766}
1767
1768void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1769 ArgStringList &CmdArgs) const {
1770 const llvm::Triple &Triple = getToolChain().getTriple();
1771
1772 CmdArgs.push_back("-target-abi");
1773 CmdArgs.push_back(
1774 loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1775 .data());
1776
1777 // Handle -mtune.
1778 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1779 std::string TuneCPU = A->getValue();
1780 TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
1781 CmdArgs.push_back("-tune-cpu");
1782 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
1783 }
1784
1785 if (Arg *A = Args.getLastArg(options::OPT_mannotate_tablejump,
1786 options::OPT_mno_annotate_tablejump)) {
1787 if (A->getOption().matches(options::OPT_mannotate_tablejump)) {
1788 CmdArgs.push_back("-mllvm");
1789 CmdArgs.push_back("-loongarch-annotate-tablejump");
1790 }
1791 }
1792}
1793
1794void Clang::AddMIPSTargetArgs(const ArgList &Args,
1795 ArgStringList &CmdArgs) const {
1796 const Driver &D = getToolChain().getDriver();
1797 StringRef CPUName;
1798 StringRef ABIName;
1799 const llvm::Triple &Triple = getToolChain().getTriple();
1800 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1801
1802 CmdArgs.push_back("-target-abi");
1803 CmdArgs.push_back(ABIName.data());
1804
1805 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1806 if (ABI == mips::FloatABI::Soft) {
1807 // Floating point operations and argument passing are soft.
1808 CmdArgs.push_back("-msoft-float");
1809 CmdArgs.push_back("-mfloat-abi");
1810 CmdArgs.push_back("soft");
1811 } else {
1812 // Floating point operations and argument passing are hard.
1813 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1814 CmdArgs.push_back("-mfloat-abi");
1815 CmdArgs.push_back("hard");
1816 }
1817
1818 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1819 options::OPT_mno_ldc1_sdc1)) {
1820 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1821 CmdArgs.push_back("-mllvm");
1822 CmdArgs.push_back("-mno-ldc1-sdc1");
1823 }
1824 }
1825
1826 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1827 options::OPT_mno_check_zero_division)) {
1828 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1829 CmdArgs.push_back("-mllvm");
1830 CmdArgs.push_back("-mno-check-zero-division");
1831 }
1832 }
1833
1834 if (Args.getLastArg(options::OPT_mfix4300)) {
1835 CmdArgs.push_back("-mllvm");
1836 CmdArgs.push_back("-mfix4300");
1837 }
1838
1839 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1840 StringRef v = A->getValue();
1841 CmdArgs.push_back("-mllvm");
1842 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1843 A->claim();
1844 }
1845
1846 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1847 Arg *ABICalls =
1848 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1849
1850 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1851 // -mgpopt is the default for static, -fno-pic environments but these two
1852 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1853 // the only case where -mllvm -mgpopt is passed.
1854 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1855 // passed explicitly when compiling something with -mabicalls
1856 // (implictly) in affect. Currently the warning is in the backend.
1857 //
1858 // When the ABI in use is N64, we also need to determine the PIC mode that
1859 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1860 bool NoABICalls =
1861 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1862
1863 llvm::Reloc::Model RelocationModel;
1864 unsigned PICLevel;
1865 bool IsPIE;
1866 std::tie(RelocationModel, PICLevel, IsPIE) =
1867 ParsePICArgs(getToolChain(), Args);
1868
1869 NoABICalls = NoABICalls ||
1870 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1871
1872 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1873 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1874 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1875 CmdArgs.push_back("-mllvm");
1876 CmdArgs.push_back("-mgpopt");
1877
1878 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1879 options::OPT_mno_local_sdata);
1880 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1881 options::OPT_mno_extern_sdata);
1882 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1883 options::OPT_mno_embedded_data);
1884 if (LocalSData) {
1885 CmdArgs.push_back("-mllvm");
1886 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1887 CmdArgs.push_back("-mlocal-sdata=1");
1888 } else {
1889 CmdArgs.push_back("-mlocal-sdata=0");
1890 }
1891 LocalSData->claim();
1892 }
1893
1894 if (ExternSData) {
1895 CmdArgs.push_back("-mllvm");
1896 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1897 CmdArgs.push_back("-mextern-sdata=1");
1898 } else {
1899 CmdArgs.push_back("-mextern-sdata=0");
1900 }
1901 ExternSData->claim();
1902 }
1903
1904 if (EmbeddedData) {
1905 CmdArgs.push_back("-mllvm");
1906 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1907 CmdArgs.push_back("-membedded-data=1");
1908 } else {
1909 CmdArgs.push_back("-membedded-data=0");
1910 }
1911 EmbeddedData->claim();
1912 }
1913
1914 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1915 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1916
1917 if (GPOpt)
1918 GPOpt->claim();
1919
1920 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1921 StringRef Val = StringRef(A->getValue());
1922 if (mips::hasCompactBranches(CPUName)) {
1923 if (Val == "never" || Val == "always" || Val == "optimal") {
1924 CmdArgs.push_back("-mllvm");
1925 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1926 } else
1927 D.Diag(diag::err_drv_unsupported_option_argument)
1928 << A->getSpelling() << Val;
1929 } else
1930 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1931 }
1932
1933 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1934 options::OPT_mno_relax_pic_calls)) {
1935 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1936 CmdArgs.push_back("-mllvm");
1937 CmdArgs.push_back("-mips-jalr-reloc=0");
1938 }
1939 }
1940}
1941
1942void Clang::AddPPCTargetArgs(const ArgList &Args,
1943 ArgStringList &CmdArgs) const {
1944 const Driver &D = getToolChain().getDriver();
1945 const llvm::Triple &T = getToolChain().getTriple();
1946 if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1947 CmdArgs.push_back("-tune-cpu");
1948 StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, A->getValue());
1949 CmdArgs.push_back(Args.MakeArgString(CPU));
1950 }
1951
1952 // Select the ABI to use.
1953 const char *ABIName = nullptr;
1954 if (T.isOSBinFormatELF()) {
1955 switch (getToolChain().getArch()) {
1956 case llvm::Triple::ppc64: {
1957 if (T.isPPC64ELFv2ABI())
1958 ABIName = "elfv2";
1959 else
1960 ABIName = "elfv1";
1961 break;
1962 }
1963 case llvm::Triple::ppc64le:
1964 ABIName = "elfv2";
1965 break;
1966 default:
1967 break;
1968 }
1969 }
1970
1971 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
1972 bool VecExtabi = false;
1973 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
1974 StringRef V = A->getValue();
1975 if (V == "ieeelongdouble") {
1976 IEEELongDouble = true;
1977 A->claim();
1978 } else if (V == "ibmlongdouble") {
1979 IEEELongDouble = false;
1980 A->claim();
1981 } else if (V == "vec-default") {
1982 VecExtabi = false;
1983 A->claim();
1984 } else if (V == "vec-extabi") {
1985 VecExtabi = true;
1986 A->claim();
1987 } else if (V == "elfv1") {
1988 ABIName = "elfv1";
1989 A->claim();
1990 } else if (V == "elfv2") {
1991 ABIName = "elfv2";
1992 A->claim();
1993 } else if (V != "altivec")
1994 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1995 // the option if given as we don't have backend support for any targets
1996 // that don't use the altivec abi.
1997 ABIName = A->getValue();
1998 }
1999 if (IEEELongDouble)
2000 CmdArgs.push_back("-mabi=ieeelongdouble");
2001 if (VecExtabi) {
2002 if (!T.isOSAIX())
2003 D.Diag(diag::err_drv_unsupported_opt_for_target)
2004 << "-mabi=vec-extabi" << T.str();
2005 CmdArgs.push_back("-mabi=vec-extabi");
2006 }
2007
2008 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true))
2009 CmdArgs.push_back("-disable-red-zone");
2010
2012 if (FloatABI == ppc::FloatABI::Soft) {
2013 // Floating point operations and argument passing are soft.
2014 CmdArgs.push_back("-msoft-float");
2015 CmdArgs.push_back("-mfloat-abi");
2016 CmdArgs.push_back("soft");
2017 } else {
2018 // Floating point operations and argument passing are hard.
2019 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2020 CmdArgs.push_back("-mfloat-abi");
2021 CmdArgs.push_back("hard");
2022 }
2023
2024 if (ABIName) {
2025 CmdArgs.push_back("-target-abi");
2026 CmdArgs.push_back(ABIName);
2027 }
2028}
2029
2030void Clang::AddRISCVTargetArgs(const ArgList &Args,
2031 ArgStringList &CmdArgs) const {
2032 const llvm::Triple &Triple = getToolChain().getTriple();
2033 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2034
2035 CmdArgs.push_back("-target-abi");
2036 CmdArgs.push_back(ABIName.data());
2037
2038 if (Arg *A = Args.getLastArg(options::OPT_G)) {
2039 CmdArgs.push_back("-msmall-data-limit");
2040 CmdArgs.push_back(A->getValue());
2041 }
2042
2043 if (!Args.hasFlag(options::OPT_mimplicit_float,
2044 options::OPT_mno_implicit_float, true))
2045 CmdArgs.push_back("-no-implicit-float");
2046
2047 auto TuneCPU = riscv::getRISCVTuneCPU(getToolChain().getDriver(), Args);
2048 if (!TuneCPU)
2049 return;
2050 if (!TuneCPU->empty()) {
2051 CmdArgs.push_back("-tune-cpu");
2052 if (*TuneCPU == "native")
2053 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2054 else
2055 // TuneCPU might or might not be the original -mtune string, so we
2056 // have to create a new copy here.
2057 CmdArgs.push_back(Args.MakeArgString(*TuneCPU));
2058 }
2059
2060 // Handle -mrvv-vector-bits=<bits>
2061 if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
2062 StringRef Val = A->getValue();
2063 const Driver &D = getToolChain().getDriver();
2064
2065 // Get minimum VLen from march.
2066 unsigned MinVLen = 0;
2067 std::string Arch = riscv::getRISCVArch(Args, Triple);
2068 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2069 Arch, /*EnableExperimentalExtensions*/ true);
2070 // Ignore parsing error.
2071 if (!errorToBool(ISAInfo.takeError()))
2072 MinVLen = (*ISAInfo)->getMinVLen();
2073
2074 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2075 // as integer as long as we have a MinVLen.
2076 unsigned Bits = 0;
2077 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2078 Bits = MinVLen;
2079 } else if (!Val.getAsInteger(10, Bits)) {
2080 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2081 // at least MinVLen.
2082 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2083 Bits > 65536 || !llvm::isPowerOf2_32(Bits))
2084 Bits = 0;
2085 }
2086
2087 // If we got a valid value try to use it.
2088 if (Bits != 0) {
2089 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2090 CmdArgs.push_back(
2091 Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
2092 CmdArgs.push_back(
2093 Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
2094 } else if (Val != "scalable") {
2095 // Handle the unsupported values passed to mrvv-vector-bits.
2096 D.Diag(diag::err_drv_unsupported_option_argument)
2097 << A->getSpelling() << Val;
2098 }
2099 }
2100}
2101
2102void Clang::AddSparcTargetArgs(const ArgList &Args,
2103 ArgStringList &CmdArgs) const {
2105 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2106
2107 if (FloatABI == sparc::FloatABI::Soft) {
2108 // Floating point operations and argument passing are soft.
2109 CmdArgs.push_back("-msoft-float");
2110 CmdArgs.push_back("-mfloat-abi");
2111 CmdArgs.push_back("soft");
2112 } else {
2113 // Floating point operations and argument passing are hard.
2114 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2115 CmdArgs.push_back("-mfloat-abi");
2116 CmdArgs.push_back("hard");
2117 }
2118
2119 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2120 StringRef Name = A->getValue();
2121 std::string TuneCPU;
2122 if (Name == "native")
2123 TuneCPU = std::string(llvm::sys::getHostCPUName());
2124 else
2125 TuneCPU = std::string(Name);
2126
2127 CmdArgs.push_back("-tune-cpu");
2128 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2129 }
2130}
2131
2132void Clang::AddSystemZTargetArgs(const ArgList &Args,
2133 ArgStringList &CmdArgs) const {
2134 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2135 CmdArgs.push_back("-tune-cpu");
2136 if (strcmp(A->getValue(), "native") == 0)
2137 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2138 else
2139 CmdArgs.push_back(A->getValue());
2140 }
2141
2142 bool HasBackchain =
2143 Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2144 bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2145 options::OPT_mno_packed_stack, false);
2147 systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2148 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2149
2150 // Only hard float ABI (-mhard-float) is supported on z/OS.
2151 const Driver &D = getToolChain().getDriver();
2152 const llvm::Triple &Triple = getToolChain().getTriple();
2153 if (HasSoftFloat && Triple.isOSzOS()) {
2154 D.Diag(diag::err_drv_unsupported_opt_for_target)
2155 << "-msoft-float" << Triple.str();
2156 }
2157 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2158 D.Diag(diag::err_drv_unsupported_opt)
2159 << "-mpacked-stack -mbackchain -mhard-float";
2160 }
2161 if (HasBackchain)
2162 CmdArgs.push_back("-mbackchain");
2163 if (HasPackedStack)
2164 CmdArgs.push_back("-mpacked-stack");
2165 if (HasSoftFloat) {
2166 // Floating point operations and argument passing are soft.
2167 CmdArgs.push_back("-msoft-float");
2168 CmdArgs.push_back("-mfloat-abi");
2169 CmdArgs.push_back("soft");
2170 }
2171
2172 if (Triple.isOSzOS())
2173 Args.AddLastArg(CmdArgs, options::OPT_mzos_ppa1_name,
2174 options::OPT_mno_zos_ppa1_name);
2175}
2176
2177void Clang::AddX86TargetArgs(const ArgList &Args,
2178 ArgStringList &CmdArgs) const {
2179 const Driver &D = getToolChain().getDriver();
2180 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2181
2182 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2183 Args.hasArg(options::OPT_mkernel) ||
2184 Args.hasArg(options::OPT_fapple_kext))
2185 CmdArgs.push_back("-disable-red-zone");
2186
2187 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2188 options::OPT_mno_tls_direct_seg_refs, true))
2189 CmdArgs.push_back("-mno-tls-direct-seg-refs");
2190
2191 // Default to avoid implicit floating-point for kernel/kext code, but allow
2192 // that to be overridden with -mno-soft-float.
2193 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2194 Args.hasArg(options::OPT_fapple_kext));
2195 if (Arg *A = Args.getLastArg(
2196 options::OPT_msoft_float, options::OPT_mno_soft_float,
2197 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2198 const Option &O = A->getOption();
2199 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2200 O.matches(options::OPT_msoft_float));
2201 }
2202 if (NoImplicitFloat)
2203 CmdArgs.push_back("-no-implicit-float");
2204
2205 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2206 StringRef Value = A->getValue();
2207 if (Value == "intel" || Value == "att") {
2208 CmdArgs.push_back("-mllvm");
2209 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2210 CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
2211 } else {
2212 D.Diag(diag::err_drv_unsupported_option_argument)
2213 << A->getSpelling() << Value;
2214 }
2215 } else if (D.IsCLMode()) {
2216 CmdArgs.push_back("-mllvm");
2217 CmdArgs.push_back("-x86-asm-syntax=intel");
2218 }
2219
2220 if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2221 options::OPT_mno_skip_rax_setup))
2222 if (A->getOption().matches(options::OPT_mskip_rax_setup))
2223 CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2224
2225 // Set flags to support MCU ABI.
2226 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2227 CmdArgs.push_back("-mfloat-abi");
2228 CmdArgs.push_back("soft");
2229 CmdArgs.push_back("-mstack-alignment=4");
2230 }
2231
2232 // Handle -mtune.
2233
2234 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2235 std::string TuneCPU;
2236 if (!Args.hasArg(options::OPT_march_EQ) && !getToolChain().getTriple().isPS())
2237 TuneCPU = "generic";
2238
2239 // Override based on -mtune.
2240 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2241 StringRef Name = A->getValue();
2242
2243 if (Name == "native") {
2244 Name = llvm::sys::getHostCPUName();
2245 if (!Name.empty())
2246 TuneCPU = std::string(Name);
2247 } else
2248 TuneCPU = std::string(Name);
2249 }
2250
2251 if (!TuneCPU.empty()) {
2252 CmdArgs.push_back("-tune-cpu");
2253 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2254 }
2255}
2256
2257static StringRef getOptionName(StringRef Option, const char Delimiter = '=') {
2258 size_t Index = Option.find(Delimiter);
2259 if (Index != StringRef::npos)
2260 Option = Option.substr(0, Index);
2261 return Option;
2262}
2263
2264static void checkAndRemoveLLVMArg(ArgStringList &CmdArgs, StringRef Opt) {
2265 Opt = getOptionName(Opt);
2266 if (CmdArgs.size() < 2)
2267 return;
2268
2269 for (auto It = std::next(CmdArgs.begin()); It != CmdArgs.end(); ++It) {
2270 StringRef Option = *It;
2271 if (!Option.starts_with(Opt))
2272 continue;
2273 Option = getOptionName(Option);
2274 if (Option != Opt)
2275 continue;
2276 if (StringRef(*(It - 1)) != "-mllvm")
2277 continue;
2278
2279 It = CmdArgs.erase(It);
2280 CmdArgs.erase(It - 1);
2281 return;
2282 }
2283}
2284
2285static void pushBackLLVMArg(ArgStringList &CmdArgs, const char *A) {
2286 checkAndRemoveLLVMArg(CmdArgs, A);
2287 CmdArgs.push_back("-mllvm");
2288 CmdArgs.push_back(A);
2289}
2290
2291static void addQFloatLossyFastMathArgs(ArgStringList &CmdArgs) {
2292 for (auto It = CmdArgs.begin(), Ie = CmdArgs.end(); It != Ie;) {
2293 StringRef Option = *It;
2294 if (Option == "-fmath-errno" || Option == "-ffp-contract=on") {
2295 It = CmdArgs.erase(It);
2296 Ie = CmdArgs.end();
2297 } else {
2298 ++It;
2299 }
2300 }
2301
2302 CmdArgs.push_back("-menable-no-infs");
2303 CmdArgs.push_back("-menable-no-nans");
2304 CmdArgs.push_back("-fapprox-func");
2305 CmdArgs.push_back("-funsafe-math-optimizations");
2306 CmdArgs.push_back("-fno-signed-zeros");
2307 CmdArgs.push_back("-mreassociate");
2308 CmdArgs.push_back("-freciprocal-math");
2309 CmdArgs.push_back("-ffp-contract=fast");
2310 CmdArgs.push_back("-ffast-math");
2311 CmdArgs.push_back("-ffinite-math-only");
2312 CmdArgs.push_back("-D__FAST_MATH__");
2313 pushBackLLVMArg(CmdArgs, "-fast-math=true");
2314}
2315
2316static void addQFloatBackendArg(const Driver &D, const ArgList &Args,
2317 ArgStringList &CmdArgs) {
2318 auto HvxVerOpt = toolchains::HexagonToolChain::GetHVXVersion(Args);
2319 bool HasHVX = HvxVerOpt.has_value();
2320 std::string HvxVer = HasHVX ? *HvxVerOpt : std::string();
2321 if (!Args.hasArg(options::OPT_mhexagon_hvx, options::OPT_mhexagon_hvx_EQ,
2322 options::OPT_mhexagon_hvx_ieee_fp) ||
2323 !HasHVX)
2324 return;
2325 unsigned HvxVerNum = 0;
2326 if (StringRef(HvxVer).drop_front(1).getAsInteger(10, HvxVerNum))
2327 HvxVerNum = 0;
2328
2329 if (Arg *A = Args.getLastArg(options::OPT_mhexagon_hvx_qfloat,
2330 options::OPT_mhexagon_hvx_qfloat_EQ,
2331 options::OPT_mhexagon_hvx_ieee_fp)) {
2332 if (HvxVerNum >= 79) {
2333 if (A->getOption().matches(options::OPT_mhexagon_hvx_qfloat_EQ)) {
2334 const char *Mode =
2335 llvm::StringSwitch<const char *>(StringRef(A->getValue()).lower())
2336 .Case("strict-ieee", "-hexagon-qfloat-mode=strict-ieee")
2337 .Case("ieee", "-hexagon-qfloat-mode=ieee")
2338 .Case("lossy", "-hexagon-qfloat-mode=lossy")
2339 .Case("legacy", "-hexagon-qfloat-mode=legacy")
2340 .Default(nullptr);
2341 if (!Mode) {
2342 D.Diag(diag::err_drv_invalid_value)
2343 << A->getAsString(Args) << A->getValue();
2344 return;
2345 }
2346 pushBackLLVMArg(CmdArgs, Mode);
2347 if (strcmp(Mode, "-hexagon-qfloat-mode=lossy") == 0)
2349 } else if (A->getOption().matches(options::OPT_mhexagon_hvx_qfloat)) {
2350 pushBackLLVMArg(CmdArgs, "-hexagon-qfloat-mode=lossy");
2352 } else {
2353 pushBackLLVMArg(CmdArgs, "-hexagon-qfloat-mode=ieee");
2354 }
2355 } else {
2356 if (Arg *QFloatArg = Args.getLastArg(options::OPT_mhexagon_hvx_qfloat,
2357 options::OPT_mhexagon_hvx_qfloat_EQ,
2358 options::OPT_mno_hexagon_hvx_qfloat);
2359 QFloatArg &&
2360 QFloatArg->getOption().matches(options::OPT_mhexagon_hvx_qfloat_EQ)) {
2361 D.Diag(diag::warn_drv_unsupported_option_part_for_target)
2362 << QFloatArg->getValue() << QFloatArg->getAsString(Args)
2363 << (std::string("HVX ") + HvxVer +
2364 "; falling back to legacy qfloat mode");
2365 }
2366 }
2367 }
2368}
2369
2370void Clang::AddHexagonTargetArgs(const ArgList &Args,
2371 ArgStringList &CmdArgs) const {
2372 CmdArgs.push_back("-mqdsp6-compat");
2373 CmdArgs.push_back("-Wreturn-type");
2374
2376 CmdArgs.push_back("-mllvm");
2377 CmdArgs.push_back(
2378 Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
2379 }
2380
2381 if (!Args.hasArg(options::OPT_fno_short_enums))
2382 CmdArgs.push_back("-fshort-enums");
2383 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2384 CmdArgs.push_back("-mllvm");
2385 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2386 }
2387 CmdArgs.push_back("-mllvm");
2388 CmdArgs.push_back("-machine-sink-split=0");
2389
2390 addQFloatBackendArg(getToolChain().getDriver(), Args, CmdArgs);
2391}
2392
2393void Clang::AddLanaiTargetArgs(const ArgList &Args,
2394 ArgStringList &CmdArgs) const {
2395 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2396 StringRef CPUName = A->getValue();
2397
2398 CmdArgs.push_back("-target-cpu");
2399 CmdArgs.push_back(Args.MakeArgString(CPUName));
2400 }
2401 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2402 StringRef Value = A->getValue();
2403 // Only support mregparm=4 to support old usage. Report error for all other
2404 // cases.
2405 int Mregparm;
2406 if (Value.getAsInteger(10, Mregparm)) {
2407 if (Mregparm != 4) {
2409 diag::err_drv_unsupported_option_argument)
2410 << A->getSpelling() << Value;
2411 }
2412 }
2413 }
2414}
2415
2416void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2417 ArgStringList &CmdArgs) const {
2418 // Default to "hidden" visibility.
2419 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2420 options::OPT_fvisibility_ms_compat))
2421 CmdArgs.push_back("-fvisibility=hidden");
2422}
2423
2424void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2425 // Floating point operations and argument passing are hard.
2426 CmdArgs.push_back("-mfloat-abi");
2427 CmdArgs.push_back("hard");
2428}
2429
2430void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2431 StringRef Target, const InputInfo &Output,
2432 const InputInfo &Input, const ArgList &Args) const {
2433 // If this is a dry run, do not create the compilation database file.
2434 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2435 return;
2436
2437 using llvm::yaml::escape;
2438 const Driver &D = getToolChain().getDriver();
2439
2440 if (!CompilationDatabase) {
2441 std::error_code EC;
2442 auto File = std::make_unique<llvm::raw_fd_ostream>(
2443 Filename, EC,
2444 llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2445 if (EC) {
2446 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2447 << EC.message();
2448 return;
2449 }
2450 CompilationDatabase = std::move(File);
2451 }
2452 auto &CDB = *CompilationDatabase;
2453 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2454 if (!CWD)
2455 CWD = ".";
2456 CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2457 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2458 if (Output.isFilename())
2459 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2460 CDB << ", \"arguments\": [\"" << escape(D.DriverExecutable) << "\"";
2461 SmallString<128> Buf;
2462 Buf = "-x";
2463 Buf += types::getTypeName(Input.getType());
2464 CDB << ", \"" << escape(Buf) << "\"";
2465 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2466 Buf = "--sysroot=";
2467 Buf += D.SysRoot;
2468 CDB << ", \"" << escape(Buf) << "\"";
2469 }
2470 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2471 if (Output.isFilename())
2472 CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
2473 for (auto &A: Args) {
2474 auto &O = A->getOption();
2475 // Skip language selection, which is positional.
2476 if (O.getID() == options::OPT_x)
2477 continue;
2478 // Skip writing dependency output and the compilation database itself.
2479 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2480 continue;
2481 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2482 continue;
2483 // Skip inputs.
2484 if (O.getKind() == Option::InputClass)
2485 continue;
2486 // Skip output.
2487 if (O.getID() == options::OPT_o)
2488 continue;
2489 // All other arguments are quoted and appended.
2490 ArgStringList ASL;
2491 A->render(Args, ASL);
2492 for (auto &it: ASL)
2493 CDB << ", \"" << escape(it) << "\"";
2494 }
2495 Buf = "--target=";
2496 Buf += Target;
2497 CDB << ", \"" << escape(Buf) << "\"]},\n";
2498}
2499
2500void Clang::DumpCompilationDatabaseFragmentToDir(
2501 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2502 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2503 // If this is a dry run, do not create the compilation database file.
2504 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2505 return;
2506
2507 if (CompilationDatabase)
2508 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2509
2510 SmallString<256> Path = Dir;
2511 const auto &Driver = C.getDriver();
2512 Driver.getVFS().makeAbsolute(Path);
2513 auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2514 if (Err) {
2515 Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2516 return;
2517 }
2518
2519 llvm::sys::path::append(
2520 Path,
2521 Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2522 int FD;
2523 SmallString<256> TempPath;
2524 Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2525 llvm::sys::fs::OF_Text);
2526 if (Err) {
2527 Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2528 return;
2529 }
2530 CompilationDatabase =
2531 std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2532 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2533}
2534
2535static bool CheckARMImplicitITArg(StringRef Value) {
2536 return Value == "always" || Value == "never" || Value == "arm" ||
2537 Value == "thumb";
2538}
2539
2540static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2541 StringRef Value) {
2542 CmdArgs.push_back("-mllvm");
2543 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2544}
2545
2547 const ArgList &Args,
2548 ArgStringList &CmdArgs,
2549 const Driver &D) {
2550 // Default to -mno-relax-all.
2551 //
2552 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2553 // cannot be done by assembler branch relaxation as it needs a free temporary
2554 // register. Because of this, branch relaxation is handled by a MachineIR pass
2555 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2556 // MachineIR branch relaxation inaccurate and it will miss cases where an
2557 // indirect branch is necessary.
2558 Args.addOptInFlag(CmdArgs, options::OPT_mrelax_all,
2559 options::OPT_mno_relax_all);
2560
2561 Args.AddLastArg(CmdArgs, options::OPT_mincremental_linker_compatible,
2562 options::OPT_mno_incremental_linker_compatible);
2563
2564 Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
2565
2566 Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
2567 options::OPT_fno_emit_compact_unwind_non_canonical);
2568
2569 // If you add more args here, also add them to the block below that
2570 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2571
2572 // When passing -I arguments to the assembler we sometimes need to
2573 // unconditionally take the next argument. For example, when parsing
2574 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2575 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2576 // arg after parsing the '-I' arg.
2577 bool TakeNextArg = false;
2578
2579 const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2580 bool IsELF = Triple.isOSBinFormatELF();
2581 bool Crel = false, ExperimentalCrel = false;
2582 StringRef RelocSectionSym;
2583 bool SFrame = false, ExperimentalSFrame = false;
2584 bool ImplicitMapSyms = false;
2585 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2586 bool UseNoExecStack = false;
2587 bool Msa = false;
2588 const char *MipsTargetFeature = nullptr;
2589 llvm::SmallVector<const char *> SparcTargetFeatures;
2590 StringRef ImplicitIt;
2591 for (const Arg *A :
2592 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2593 options::OPT_mimplicit_it_EQ)) {
2594 A->claim();
2595
2596 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2597 switch (C.getDefaultToolChain().getArch()) {
2598 case llvm::Triple::arm:
2599 case llvm::Triple::armeb:
2600 case llvm::Triple::thumb:
2601 case llvm::Triple::thumbeb:
2602 // Only store the value; the last value set takes effect.
2603 ImplicitIt = A->getValue();
2604 if (!CheckARMImplicitITArg(ImplicitIt))
2605 D.Diag(diag::err_drv_unsupported_option_argument)
2606 << A->getSpelling() << ImplicitIt;
2607 continue;
2608 default:
2609 break;
2610 }
2611 }
2612
2613 for (StringRef Value : A->getValues()) {
2614 if (TakeNextArg) {
2615 CmdArgs.push_back(Value.data());
2616 TakeNextArg = false;
2617 continue;
2618 }
2619
2620 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2621 Value == "-mbig-obj")
2622 continue; // LLVM handles bigobj automatically
2623
2624 auto Equal = Value.split('=');
2625 auto checkArg = [&](bool ValidTarget,
2626 std::initializer_list<const char *> Set) {
2627 if (!ValidTarget) {
2628 D.Diag(diag::err_drv_unsupported_opt_for_target)
2629 << (Twine("-Wa,") + Equal.first + "=").str()
2630 << Triple.getTriple();
2631 } else if (!llvm::is_contained(Set, Equal.second)) {
2632 D.Diag(diag::err_drv_unsupported_option_argument)
2633 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
2634 }
2635 };
2636 switch (C.getDefaultToolChain().getArch()) {
2637 default:
2638 break;
2639 case llvm::Triple::x86:
2640 case llvm::Triple::x86_64:
2641 if (Equal.first == "-mrelax-relocations" ||
2642 Equal.first == "--mrelax-relocations") {
2643 UseRelaxRelocations = Equal.second == "yes";
2644 checkArg(IsELF, {"yes", "no"});
2645 continue;
2646 }
2647 if (Value == "-msse2avx") {
2648 CmdArgs.push_back("-msse2avx");
2649 continue;
2650 }
2651 break;
2652 case llvm::Triple::wasm32:
2653 case llvm::Triple::wasm64:
2654 if (Value == "--no-type-check") {
2655 CmdArgs.push_back("-mno-type-check");
2656 continue;
2657 }
2658 break;
2659 case llvm::Triple::thumb:
2660 case llvm::Triple::thumbeb:
2661 case llvm::Triple::arm:
2662 case llvm::Triple::armeb:
2663 if (Equal.first == "-mimplicit-it") {
2664 // Only store the value; the last value set takes effect.
2665 ImplicitIt = Equal.second;
2666 checkArg(true, {"always", "never", "arm", "thumb"});
2667 continue;
2668 }
2669 if (Value == "-mthumb")
2670 // -mthumb has already been processed in ComputeLLVMTriple()
2671 // recognize but skip over here.
2672 continue;
2673 break;
2674 case llvm::Triple::aarch64:
2675 case llvm::Triple::aarch64_be:
2676 case llvm::Triple::aarch64_32:
2677 if (Equal.first == "-mmapsyms") {
2678 ImplicitMapSyms = Equal.second == "implicit";
2679 checkArg(IsELF, {"default", "implicit"});
2680 continue;
2681 }
2682 break;
2683 case llvm::Triple::mips:
2684 case llvm::Triple::mipsel:
2685 case llvm::Triple::mips64:
2686 case llvm::Triple::mips64el:
2687 if (Value == "--trap") {
2688 CmdArgs.push_back("-target-feature");
2689 CmdArgs.push_back("+use-tcc-in-div");
2690 continue;
2691 }
2692 if (Value == "--break") {
2693 CmdArgs.push_back("-target-feature");
2694 CmdArgs.push_back("-use-tcc-in-div");
2695 continue;
2696 }
2697 if (Value.starts_with("-msoft-float")) {
2698 CmdArgs.push_back("-target-feature");
2699 CmdArgs.push_back("+soft-float");
2700 continue;
2701 }
2702 if (Value.starts_with("-mhard-float")) {
2703 CmdArgs.push_back("-target-feature");
2704 CmdArgs.push_back("-soft-float");
2705 continue;
2706 }
2707 if (Value == "-mmsa") {
2708 Msa = true;
2709 continue;
2710 }
2711 if (Value == "-mno-msa") {
2712 Msa = false;
2713 continue;
2714 }
2715 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2716 .Case("-mips1", "+mips1")
2717 .Case("-mips2", "+mips2")
2718 .Case("-mips3", "+mips3")
2719 .Case("-mips4", "+mips4")
2720 .Case("-mips5", "+mips5")
2721 .Case("-mips32", "+mips32")
2722 .Case("-mips32r2", "+mips32r2")
2723 .Case("-mips32r3", "+mips32r3")
2724 .Case("-mips32r5", "+mips32r5")
2725 .Case("-mips32r6", "+mips32r6")
2726 .Case("-mips64", "+mips64")
2727 .Case("-mips64r2", "+mips64r2")
2728 .Case("-mips64r3", "+mips64r3")
2729 .Case("-mips64r5", "+mips64r5")
2730 .Case("-mips64r6", "+mips64r6")
2731 .Default(nullptr);
2732 if (MipsTargetFeature)
2733 continue;
2734 break;
2735
2736 case llvm::Triple::sparc:
2737 case llvm::Triple::sparcel:
2738 case llvm::Triple::sparcv9:
2739 if (Value == "--undeclared-regs") {
2740 // LLVM already allows undeclared use of G registers, so this option
2741 // becomes a no-op. This solely exists for GNU compatibility.
2742 // TODO implement --no-undeclared-regs
2743 continue;
2744 }
2745 SparcTargetFeatures =
2746 llvm::StringSwitch<llvm::SmallVector<const char *>>(Value)
2747 .Case("-Av8", {"-v8plus"})
2748 .Case("-Av8plus", {"+v8plus", "+v9"})
2749 .Case("-Av8plusa", {"+v8plus", "+v9", "+vis"})
2750 .Case("-Av8plusb", {"+v8plus", "+v9", "+vis", "+vis2"})
2751 .Case("-Av8plusd", {"+v8plus", "+v9", "+vis", "+vis2", "+vis3"})
2752 .Case("-Av9", {"+v9"})
2753 .Case("-Av9a", {"+v9", "+vis"})
2754 .Case("-Av9b", {"+v9", "+vis", "+vis2"})
2755 .Case("-Av9d", {"+v9", "+vis", "+vis2", "+vis3"})
2756 .Default({});
2757 if (!SparcTargetFeatures.empty())
2758 continue;
2759 break;
2760 }
2761
2762 if (Value == "-force_cpusubtype_ALL") {
2763 // Do nothing, this is the default and we don't support anything else.
2764 } else if (Value == "-L") {
2765 CmdArgs.push_back("-msave-temp-labels");
2766 } else if (Value == "--fatal-warnings") {
2767 CmdArgs.push_back("-massembler-fatal-warnings");
2768 } else if (Value == "--no-warn" || Value == "-W") {
2769 CmdArgs.push_back("-massembler-no-warn");
2770 } else if (Value == "--noexecstack") {
2771 UseNoExecStack = true;
2772 } else if (Value.starts_with("-compress-debug-sections") ||
2773 Value.starts_with("--compress-debug-sections") ||
2774 Value == "-nocompress-debug-sections" ||
2775 Value == "--nocompress-debug-sections") {
2776 CmdArgs.push_back(Value.data());
2777 } else if (Value == "--crel") {
2778 Crel = true;
2779 } else if (Value == "--no-crel") {
2780 Crel = false;
2781 } else if (Value == "--allow-experimental-crel") {
2782 ExperimentalCrel = true;
2783 } else if (Value.starts_with("--reloc-section-sym=")) {
2784 RelocSectionSym = Value.substr(strlen("--reloc-section-sym="));
2785 } else if (Value.starts_with("-I")) {
2786 CmdArgs.push_back(Value.data());
2787 // We need to consume the next argument if the current arg is a plain
2788 // -I. The next arg will be the include directory.
2789 if (Value == "-I")
2790 TakeNextArg = true;
2791 } else if (Value.starts_with("-gdwarf-")) {
2792 // "-gdwarf-N" options are not cc1as options.
2793 unsigned DwarfVersion = DwarfVersionNum(Value);
2794 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2795 CmdArgs.push_back(Value.data());
2796 } else {
2797 RenderDebugEnablingArgs(Args, CmdArgs,
2798 llvm::codegenoptions::DebugInfoConstructor,
2799 DwarfVersion, llvm::DebuggerKind::Default);
2800 }
2801 } else if (Value == "--gsframe") {
2802 SFrame = true;
2803 } else if (Value == "--allow-experimental-sframe") {
2804 ExperimentalSFrame = true;
2805 } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
2806 Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {
2807 // Do nothing, we'll validate it later.
2808 } else if (Value == "-defsym" || Value == "--defsym") {
2809 if (A->getNumValues() != 2) {
2810 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2811 break;
2812 }
2813 const char *S = A->getValue(1);
2814 auto Pair = StringRef(S).split('=');
2815 auto Sym = Pair.first;
2816 auto SVal = Pair.second;
2817
2818 if (Sym.empty() || SVal.empty()) {
2819 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2820 break;
2821 }
2822 int64_t IVal;
2823 if (SVal.getAsInteger(0, IVal)) {
2824 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2825 break;
2826 }
2827 CmdArgs.push_back("--defsym");
2828 TakeNextArg = true;
2829 } else if (Value == "-fdebug-compilation-dir") {
2830 CmdArgs.push_back("-fdebug-compilation-dir");
2831 TakeNextArg = true;
2832 } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2833 // The flag is a -Wa / -Xassembler argument and Options doesn't
2834 // parse the argument, so this isn't automatically aliased to
2835 // -fdebug-compilation-dir (without '=') here.
2836 CmdArgs.push_back("-fdebug-compilation-dir");
2837 CmdArgs.push_back(Value.data());
2838 } else if (Value == "--version") {
2839 D.PrintVersion(C, llvm::outs());
2840 } else {
2841 D.Diag(diag::err_drv_unsupported_option_argument)
2842 << A->getSpelling() << Value;
2843 }
2844 }
2845 }
2846 if (ImplicitIt.size())
2847 AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2848 if (Crel) {
2849 if (!ExperimentalCrel)
2850 D.Diag(diag::err_drv_experimental_crel);
2851 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2852 CmdArgs.push_back("--crel");
2853 } else {
2854 D.Diag(diag::err_drv_unsupported_opt_for_target)
2855 << "-Wa,--crel" << D.getTargetTriple();
2856 }
2857 }
2858 if (!RelocSectionSym.empty()) {
2859 if (RelocSectionSym != "all" && RelocSectionSym != "internal" &&
2860 RelocSectionSym != "none")
2861 D.Diag(diag::err_drv_invalid_value)
2862 << ("-Wa,--reloc-section-sym=" + RelocSectionSym).str()
2863 << RelocSectionSym;
2864 else if (Triple.isOSBinFormatELF())
2865 CmdArgs.push_back(
2866 Args.MakeArgString("--reloc-section-sym=" + RelocSectionSym));
2867 else
2868 D.Diag(diag::err_drv_unsupported_opt_for_target)
2869 << "-Wa,--reloc-section-sym" << D.getTargetTriple();
2870 }
2871 if (SFrame) {
2872 if (Triple.isOSBinFormatELF() && Triple.isX86()) {
2873 if (!ExperimentalSFrame)
2874 D.Diag(diag::err_drv_experimental_sframe);
2875 else
2876 CmdArgs.push_back("--gsframe");
2877 } else {
2878 D.Diag(diag::err_drv_unsupported_opt_for_target)
2879 << "-Wa,--gsframe" << D.getTargetTriple();
2880 }
2881 }
2882 if (ImplicitMapSyms)
2883 CmdArgs.push_back("-mmapsyms=implicit");
2884 if (Msa)
2885 CmdArgs.push_back("-mmsa");
2886 if (!UseRelaxRelocations)
2887 CmdArgs.push_back("-mrelax-relocations=no");
2888 if (UseNoExecStack)
2889 CmdArgs.push_back("-mnoexecstack");
2890 if (MipsTargetFeature != nullptr) {
2891 CmdArgs.push_back("-target-feature");
2892 CmdArgs.push_back(MipsTargetFeature);
2893 }
2894
2895 for (const char *Feature : SparcTargetFeatures) {
2896 CmdArgs.push_back("-target-feature");
2897 CmdArgs.push_back(Feature);
2898 }
2899
2900 // forward -fembed-bitcode to assmebler
2901 if (C.getDriver().embedBitcodeEnabled() ||
2902 C.getDriver().embedBitcodeMarkerOnly())
2903 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2904
2905 if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2906 CmdArgs.push_back("-as-secure-log-file");
2907 CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2908 }
2909}
2910
2911static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2912 bool OFastEnabled, const ArgList &Args,
2913 ArgStringList &CmdArgs,
2914 const JobAction &JA) {
2915 // List of veclibs which when used with -fveclib imply -fno-math-errno.
2916 constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),
2917 llvm::StringLiteral("SLEEF")};
2918 bool NoMathErrnoWasImpliedByVecLib = false;
2919 const Arg *VecLibArg = nullptr;
2920 // Track the arg (if any) that enabled errno after -fveclib for diagnostics.
2921 const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;
2922
2923 // Handle various floating point optimization flags, mapping them to the
2924 // appropriate LLVM code generation flags. This is complicated by several
2925 // "umbrella" flags, so we do this by stepping through the flags incrementally
2926 // adjusting what we think is enabled/disabled, then at the end setting the
2927 // LLVM flags based on the final state.
2928 bool HonorINFs = true;
2929 bool HonorNaNs = true;
2930 bool ApproxFunc = false;
2931 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2932 bool MathErrno = TC.IsMathErrnoDefault();
2933 bool AssociativeMath = false;
2934 bool ReciprocalMath = false;
2935 bool SignedZeros = true;
2936 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2937 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2938 // overriden by ffp-exception-behavior?
2939 bool RoundingFPMath = false;
2940 // -ffp-model values: strict, fast, precise
2941 StringRef FPModel = "";
2942 // -ffp-exception-behavior options: strict, maytrap, ignore
2943 StringRef FPExceptionBehavior = "";
2944 // -ffp-eval-method options: double, extended, source
2945 StringRef FPEvalMethod = "";
2946 llvm::DenormalMode DenormalFPMath =
2947 TC.getDefaultDenormalModeForType(Args, JA);
2948 llvm::DenormalMode DenormalFP32Math =
2949 TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2950
2951 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2952 // If one wasn't given by the user, don't pass it here.
2953 StringRef FPContract;
2954 StringRef LastSeenFfpContractOption;
2955 StringRef LastFpContractOverrideOption;
2956 bool SeenUnsafeMathModeOption = false;
2959 FPContract = "on";
2960 bool StrictFPModel = false;
2961 StringRef Float16ExcessPrecision = "";
2962 StringRef BFloat16ExcessPrecision = "";
2964 std::string ComplexRangeStr;
2965 StringRef LastComplexRangeOption;
2966
2967 // Lambda to set fast-math options. This is also used by -ffp-model=fast
2968 auto applyFastMath = [&](bool Aggressive, StringRef CallerOption) {
2969 if (Aggressive) {
2970 HonorINFs = false;
2971 HonorNaNs = false;
2973 LastComplexRangeOption, Range);
2974 } else {
2975 HonorINFs = true;
2976 HonorNaNs = true;
2977 setComplexRange(D, CallerOption,
2979 LastComplexRangeOption, Range);
2980 }
2981 MathErrno = false;
2982 AssociativeMath = true;
2983 ReciprocalMath = true;
2984 ApproxFunc = true;
2985 SignedZeros = false;
2986 TrappingMath = false;
2987 RoundingFPMath = false;
2988 FPExceptionBehavior = "";
2989 FPContract = "fast";
2990 SeenUnsafeMathModeOption = true;
2991 };
2992
2993 // Lambda to consolidate common handling for fp-contract
2994 auto restoreFPContractState = [&]() {
2995 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2996 // For other targets, if the state has been changed by one of the
2997 // unsafe-math umbrella options a subsequent -fno-fast-math or
2998 // -fno-unsafe-math-optimizations option reverts to the last value seen for
2999 // the -ffp-contract option or "on" if we have not seen the -ffp-contract
3000 // option. If we have not seen an unsafe-math option or -ffp-contract,
3001 // we leave the FPContract state unchanged.
3004 if (LastSeenFfpContractOption != "")
3005 FPContract = LastSeenFfpContractOption;
3006 else if (SeenUnsafeMathModeOption)
3007 FPContract = "on";
3008 }
3009 // In this case, we're reverting to the last explicit fp-contract option
3010 // or the platform default
3011 LastFpContractOverrideOption = "";
3012 };
3013
3014 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3015 CmdArgs.push_back("-mlimit-float-precision");
3016 CmdArgs.push_back(A->getValue());
3017 }
3018
3019 for (const Arg *A : Args) {
3020 llvm::scope_exit CheckMathErrnoForVecLib(
3021 [&, MathErrnoBeforeArg = MathErrno] {
3022 if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)
3023 ArgThatEnabledMathErrnoAfterVecLib = A;
3024 });
3025
3026 switch (A->getOption().getID()) {
3027 // If this isn't an FP option skip the claim below
3028 default: continue;
3029
3030 case options::OPT_fcx_limited_range:
3031 setComplexRange(D, A->getSpelling(),
3033 LastComplexRangeOption, Range);
3034 break;
3035 case options::OPT_fno_cx_limited_range:
3036 setComplexRange(D, A->getSpelling(),
3038 LastComplexRangeOption, Range);
3039 break;
3040 case options::OPT_fcx_fortran_rules:
3041 setComplexRange(D, A->getSpelling(),
3043 LastComplexRangeOption, Range);
3044 break;
3045 case options::OPT_fno_cx_fortran_rules:
3046 setComplexRange(D, A->getSpelling(),
3048 LastComplexRangeOption, Range);
3049 break;
3050 case options::OPT_fcomplex_arithmetic_EQ: {
3052 StringRef Val = A->getValue();
3053 if (Val == "full")
3055 else if (Val == "improved")
3057 else if (Val == "promoted")
3059 else if (Val == "basic")
3061 else {
3062 D.Diag(diag::err_drv_unsupported_option_argument)
3063 << A->getSpelling() << Val;
3064 break;
3065 }
3066 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val), RangeVal,
3067 LastComplexRangeOption, Range);
3068 break;
3069 }
3070 case options::OPT_ffp_model_EQ: {
3071 // If -ffp-model= is seen, reset to fno-fast-math
3072 HonorINFs = true;
3073 HonorNaNs = true;
3074 ApproxFunc = false;
3075 // Turning *off* -ffast-math restores the toolchain default.
3076 MathErrno = TC.IsMathErrnoDefault();
3077 AssociativeMath = false;
3078 ReciprocalMath = false;
3079 SignedZeros = true;
3080
3081 StringRef Val = A->getValue();
3082 if (OFastEnabled && Val != "aggressive") {
3083 // Only -ffp-model=aggressive is compatible with -OFast, ignore.
3084 D.Diag(clang::diag::warn_drv_overriding_option)
3085 << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";
3086 break;
3087 }
3088 StrictFPModel = false;
3089 if (!FPModel.empty() && FPModel != Val)
3090 D.Diag(clang::diag::warn_drv_overriding_option)
3091 << Args.MakeArgString("-ffp-model=" + FPModel)
3092 << Args.MakeArgString("-ffp-model=" + Val);
3093 if (Val == "fast") {
3094 FPModel = Val;
3095 applyFastMath(false, Args.MakeArgString(A->getSpelling() + Val));
3096 // applyFastMath sets fp-contract="fast"
3097 LastFpContractOverrideOption = "-ffp-model=fast";
3098 } else if (Val == "aggressive") {
3099 FPModel = Val;
3100 applyFastMath(true, Args.MakeArgString(A->getSpelling() + Val));
3101 // applyFastMath sets fp-contract="fast"
3102 LastFpContractOverrideOption = "-ffp-model=aggressive";
3103 } else if (Val == "precise") {
3104 FPModel = Val;
3105 FPContract = "on";
3106 LastFpContractOverrideOption = "-ffp-model=precise";
3107 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val),
3109 LastComplexRangeOption, Range);
3110 } else if (Val == "strict") {
3111 StrictFPModel = true;
3112 FPExceptionBehavior = "strict";
3113 FPModel = Val;
3114 FPContract = "off";
3115 LastFpContractOverrideOption = "-ffp-model=strict";
3116 TrappingMath = true;
3117 RoundingFPMath = true;
3118 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val),
3120 LastComplexRangeOption, Range);
3121 } else
3122 D.Diag(diag::err_drv_unsupported_option_argument)
3123 << A->getSpelling() << Val;
3124 break;
3125 }
3126
3127 // Options controlling individual features
3128 case options::OPT_fhonor_infinities: HonorINFs = true; break;
3129 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
3130 case options::OPT_fhonor_nans: HonorNaNs = true; break;
3131 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
3132 case options::OPT_fapprox_func: ApproxFunc = true; break;
3133 case options::OPT_fno_approx_func: ApproxFunc = false; break;
3134 case options::OPT_fmath_errno: MathErrno = true; break;
3135 case options::OPT_fno_math_errno: MathErrno = false; break;
3136 case options::OPT_fassociative_math: AssociativeMath = true; break;
3137 case options::OPT_fno_associative_math: AssociativeMath = false; break;
3138 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
3139 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
3140 case options::OPT_fsigned_zeros: SignedZeros = true; break;
3141 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
3142 case options::OPT_ftrapping_math:
3143 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3144 FPExceptionBehavior != "strict")
3145 // Warn that previous value of option is overridden.
3146 D.Diag(clang::diag::warn_drv_overriding_option)
3147 << Args.MakeArgString("-ffp-exception-behavior=" +
3148 FPExceptionBehavior)
3149 << "-ftrapping-math";
3150 TrappingMath = true;
3151 TrappingMathPresent = true;
3152 FPExceptionBehavior = "strict";
3153 break;
3154 case options::OPT_fveclib:
3155 VecLibArg = A;
3156 NoMathErrnoWasImpliedByVecLib =
3157 llvm::is_contained(VecLibImpliesNoMathErrno, A->getValue());
3158 if (NoMathErrnoWasImpliedByVecLib)
3159 MathErrno = false;
3160 break;
3161 case options::OPT_fno_trapping_math:
3162 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3163 FPExceptionBehavior != "ignore")
3164 // Warn that previous value of option is overridden.
3165 D.Diag(clang::diag::warn_drv_overriding_option)
3166 << Args.MakeArgString("-ffp-exception-behavior=" +
3167 FPExceptionBehavior)
3168 << "-fno-trapping-math";
3169 TrappingMath = false;
3170 TrappingMathPresent = true;
3171 FPExceptionBehavior = "ignore";
3172 break;
3173
3174 case options::OPT_frounding_math:
3175 RoundingFPMath = true;
3176 break;
3177
3178 case options::OPT_fno_rounding_math:
3179 RoundingFPMath = false;
3180 break;
3181
3182 case options::OPT_fdenormal_fp_math_EQ:
3183 DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
3184 DenormalFP32Math = DenormalFPMath;
3185 if (!DenormalFPMath.isValid()) {
3186 D.Diag(diag::err_drv_invalid_value)
3187 << A->getAsString(Args) << A->getValue();
3188 }
3189 break;
3190
3191 case options::OPT_fdenormal_fp_math_f32_EQ:
3192 DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
3193 if (!DenormalFP32Math.isValid()) {
3194 D.Diag(diag::err_drv_invalid_value)
3195 << A->getAsString(Args) << A->getValue();
3196 }
3197 break;
3198
3199 // Validate and pass through -ffp-contract option.
3200 case options::OPT_ffp_contract: {
3201 StringRef Val = A->getValue();
3202 if (Val == "fast" || Val == "on" || Val == "off" ||
3203 Val == "fast-honor-pragmas") {
3204 if (Val != FPContract && LastFpContractOverrideOption != "") {
3205 D.Diag(clang::diag::warn_drv_overriding_option)
3206 << LastFpContractOverrideOption
3207 << Args.MakeArgString("-ffp-contract=" + Val);
3208 }
3209
3210 FPContract = Val;
3211 LastSeenFfpContractOption = Val;
3212 LastFpContractOverrideOption = "";
3213 } else
3214 D.Diag(diag::err_drv_unsupported_option_argument)
3215 << A->getSpelling() << Val;
3216 break;
3217 }
3218
3219 // Validate and pass through -ffp-exception-behavior option.
3220 case options::OPT_ffp_exception_behavior_EQ: {
3221 StringRef Val = A->getValue();
3222 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3223 FPExceptionBehavior != Val)
3224 // Warn that previous value of option is overridden.
3225 D.Diag(clang::diag::warn_drv_overriding_option)
3226 << Args.MakeArgString("-ffp-exception-behavior=" +
3227 FPExceptionBehavior)
3228 << Args.MakeArgString("-ffp-exception-behavior=" + Val);
3229 TrappingMath = TrappingMathPresent = false;
3230 if (Val == "ignore" || Val == "maytrap")
3231 FPExceptionBehavior = Val;
3232 else if (Val == "strict") {
3233 FPExceptionBehavior = Val;
3234 TrappingMath = TrappingMathPresent = true;
3235 } else
3236 D.Diag(diag::err_drv_unsupported_option_argument)
3237 << A->getSpelling() << Val;
3238 break;
3239 }
3240
3241 // Validate and pass through -ffp-eval-method option.
3242 case options::OPT_ffp_eval_method_EQ: {
3243 StringRef Val = A->getValue();
3244 if (Val == "double" || Val == "extended" || Val == "source")
3245 FPEvalMethod = Val;
3246 else
3247 D.Diag(diag::err_drv_unsupported_option_argument)
3248 << A->getSpelling() << Val;
3249 break;
3250 }
3251
3252 case options::OPT_fexcess_precision_EQ: {
3253 StringRef Val = A->getValue();
3254 const llvm::Triple::ArchType Arch = TC.getArch();
3255 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3256 if (Val == "standard" || Val == "fast")
3257 Float16ExcessPrecision = Val;
3258 // To make it GCC compatible, allow the value of "16" which
3259 // means disable excess precision, the same meaning than clang's
3260 // equivalent value "none".
3261 else if (Val == "16")
3262 Float16ExcessPrecision = "none";
3263 else
3264 D.Diag(diag::err_drv_unsupported_option_argument)
3265 << A->getSpelling() << Val;
3266 } else {
3267 if (!(Val == "standard" || Val == "fast"))
3268 D.Diag(diag::err_drv_unsupported_option_argument)
3269 << A->getSpelling() << Val;
3270 }
3271 BFloat16ExcessPrecision = Float16ExcessPrecision;
3272 break;
3273 }
3274 case options::OPT_ffinite_math_only:
3275 HonorINFs = false;
3276 HonorNaNs = false;
3277 break;
3278 case options::OPT_fno_finite_math_only:
3279 HonorINFs = true;
3280 HonorNaNs = true;
3281 break;
3282
3283 case options::OPT_funsafe_math_optimizations:
3284 AssociativeMath = true;
3285 ReciprocalMath = true;
3286 SignedZeros = false;
3287 ApproxFunc = true;
3288 TrappingMath = false;
3289 FPExceptionBehavior = "";
3290 FPContract = "fast";
3291 LastFpContractOverrideOption = "-funsafe-math-optimizations";
3292 SeenUnsafeMathModeOption = true;
3293 break;
3294 case options::OPT_fno_unsafe_math_optimizations:
3295 AssociativeMath = false;
3296 ReciprocalMath = false;
3297 SignedZeros = true;
3298 ApproxFunc = false;
3299 restoreFPContractState();
3300 break;
3301
3302 case options::OPT_Ofast:
3303 // If -Ofast is the optimization level, then -ffast-math should be enabled
3304 if (!OFastEnabled)
3305 continue;
3306 [[fallthrough]];
3307 case options::OPT_ffast_math:
3308 applyFastMath(true, A->getSpelling());
3309 if (A->getOption().getID() == options::OPT_Ofast)
3310 LastFpContractOverrideOption = "-Ofast";
3311 else
3312 LastFpContractOverrideOption = "-ffast-math";
3313 break;
3314 case options::OPT_fno_fast_math:
3315 HonorINFs = true;
3316 HonorNaNs = true;
3317 // Turning on -ffast-math (with either flag) removes the need for
3318 // MathErrno. However, turning *off* -ffast-math merely restores the
3319 // toolchain default (which may be false).
3320 MathErrno = TC.IsMathErrnoDefault();
3321 AssociativeMath = false;
3322 ReciprocalMath = false;
3323 ApproxFunc = false;
3324 SignedZeros = true;
3325 restoreFPContractState();
3327 setComplexRange(D, A->getSpelling(),
3329 LastComplexRangeOption, Range);
3330 else
3332 LastComplexRangeOption = "";
3333 LastFpContractOverrideOption = "";
3334 break;
3335 } // End switch (A->getOption().getID())
3336
3337 // The StrictFPModel local variable is needed to report warnings
3338 // in the way we intend. If -ffp-model=strict has been used, we
3339 // want to report a warning for the next option encountered that
3340 // takes us out of the settings described by fp-model=strict, but
3341 // we don't want to continue issuing warnings for other conflicting
3342 // options after that.
3343 if (StrictFPModel) {
3344 // If -ffp-model=strict has been specified on command line but
3345 // subsequent options conflict then emit warning diagnostic.
3346 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3347 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3348 FPContract == "off")
3349 // OK: Current Arg doesn't conflict with -ffp-model=strict
3350 ;
3351 else {
3352 StrictFPModel = false;
3353 FPModel = "";
3354 // The warning for -ffp-contract would have been reported by the
3355 // OPT_ffp_contract_EQ handler above. A special check here is needed
3356 // to avoid duplicating the warning.
3357 auto RHS = (A->getNumValues() == 0)
3358 ? A->getSpelling()
3359 : Args.MakeArgString(A->getSpelling() + A->getValue());
3360 if (A->getSpelling() != "-ffp-contract=") {
3361 if (RHS != "-ffp-model=strict")
3362 D.Diag(clang::diag::warn_drv_overriding_option)
3363 << "-ffp-model=strict" << RHS;
3364 }
3365 }
3366 }
3367
3368 // If we handled this option claim it
3369 A->claim();
3370 }
3371
3372 if (!HonorINFs)
3373 CmdArgs.push_back("-menable-no-infs");
3374
3375 if (!HonorNaNs)
3376 CmdArgs.push_back("-menable-no-nans");
3377
3378 if (ApproxFunc)
3379 CmdArgs.push_back("-fapprox-func");
3380
3381 if (MathErrno) {
3382 CmdArgs.push_back("-fmath-errno");
3383 if (NoMathErrnoWasImpliedByVecLib)
3384 D.Diag(clang::diag::warn_drv_math_errno_enabled_after_veclib)
3385 << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)
3386 << VecLibArg->getAsString(Args);
3387 }
3388
3389 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3390 !TrappingMath)
3391 CmdArgs.push_back("-funsafe-math-optimizations");
3392
3393 if (!SignedZeros)
3394 CmdArgs.push_back("-fno-signed-zeros");
3395
3396 if (AssociativeMath && !SignedZeros && !TrappingMath)
3397 CmdArgs.push_back("-mreassociate");
3398
3399 if (ReciprocalMath)
3400 CmdArgs.push_back("-freciprocal-math");
3401
3402 if (TrappingMath) {
3403 // FP Exception Behavior is also set to strict
3404 assert(FPExceptionBehavior == "strict");
3405 }
3406
3407 // The default is IEEE.
3408 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3409 llvm::SmallString<64> DenormFlag;
3410 llvm::raw_svector_ostream ArgStr(DenormFlag);
3411 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3412 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3413 }
3414
3415 // Add f32 specific denormal mode flag if it's different.
3416 if (DenormalFP32Math != DenormalFPMath) {
3417 llvm::SmallString<64> DenormFlag;
3418 llvm::raw_svector_ostream ArgStr(DenormFlag);
3419 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3420 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3421 }
3422
3423 if (!FPContract.empty())
3424 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
3425
3426 if (RoundingFPMath)
3427 CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3428 else
3429 CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3430
3431 if (!FPExceptionBehavior.empty())
3432 CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3433 FPExceptionBehavior));
3434
3435 if (!FPEvalMethod.empty())
3436 CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
3437
3438 if (!Float16ExcessPrecision.empty())
3439 CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3440 Float16ExcessPrecision));
3441 if (!BFloat16ExcessPrecision.empty())
3442 CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
3443 BFloat16ExcessPrecision));
3444
3445 StringRef Recip = parseMRecipOption(D.getDiags(), Args);
3446 if (!Recip.empty())
3447 CmdArgs.push_back(Args.MakeArgString("-mrecip=" + Recip));
3448
3449 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3450 // individual features enabled by -ffast-math instead of the option itself as
3451 // that's consistent with gcc's behaviour.
3452 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3453 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3454 CmdArgs.push_back("-ffast-math");
3455
3456 // Handle __FINITE_MATH_ONLY__ similarly.
3457 // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3458 // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3459 // -menable-no-nans are set by the user.
3460 bool shouldAddFiniteMathOnly = false;
3461 if (!HonorINFs && !HonorNaNs) {
3462 shouldAddFiniteMathOnly = true;
3463 } else {
3464 bool InfValues = true;
3465 bool NanValues = true;
3466 for (const auto *Arg : Args.filtered(options::OPT_Xclang)) {
3467 StringRef ArgValue = Arg->getValue();
3468 if (ArgValue == "-menable-no-nans")
3469 NanValues = false;
3470 else if (ArgValue == "-menable-no-infs")
3471 InfValues = false;
3472 }
3473 if (!NanValues && !InfValues)
3474 shouldAddFiniteMathOnly = true;
3475 }
3476 if (shouldAddFiniteMathOnly) {
3477 CmdArgs.push_back("-ffinite-math-only");
3478 }
3479 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3480 CmdArgs.push_back("-mfpmath");
3481 CmdArgs.push_back(A->getValue());
3482 }
3483
3484 // Disable a codegen optimization for floating-point casts.
3485 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3486 options::OPT_fstrict_float_cast_overflow, false))
3487 CmdArgs.push_back("-fno-strict-float-cast-overflow");
3488
3490 ComplexRangeStr = renderComplexRangeOption(Range);
3491 if (!ComplexRangeStr.empty()) {
3492 CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
3493 if (Args.hasArg(options::OPT_fcomplex_arithmetic_EQ))
3494 CmdArgs.push_back(Args.MakeArgString("-fcomplex-arithmetic=" +
3495 complexRangeKindToStr(Range)));
3496 }
3497 if (Args.hasArg(options::OPT_fcx_limited_range))
3498 CmdArgs.push_back("-fcx-limited-range");
3499 if (Args.hasArg(options::OPT_fcx_fortran_rules))
3500 CmdArgs.push_back("-fcx-fortran-rules");
3501 if (Args.hasArg(options::OPT_fno_cx_limited_range))
3502 CmdArgs.push_back("-fno-cx-limited-range");
3503 if (Args.hasArg(options::OPT_fno_cx_fortran_rules))
3504 CmdArgs.push_back("-fno-cx-fortran-rules");
3505}
3506
3507static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3508 const llvm::Triple &Triple,
3509 const InputInfo &Input) {
3510 // Add default argument set.
3511 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3512 CmdArgs.push_back("-analyzer-checker=core");
3513 CmdArgs.push_back("-analyzer-checker=apiModeling");
3514
3515 if (!Triple.isWindowsMSVCEnvironment()) {
3516 CmdArgs.push_back("-analyzer-checker=unix");
3517 } else {
3518 // Enable "unix" checkers that also work on Windows.
3519 CmdArgs.push_back("-analyzer-checker=unix.API");
3520 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3521 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3522 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3523 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3524 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3525 }
3526
3527 // Disable some unix checkers for PS4/PS5.
3528 if (Triple.isPS()) {
3529 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3530 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3531 }
3532
3533 if (Triple.isOSDarwin()) {
3534 CmdArgs.push_back("-analyzer-checker=osx");
3535 CmdArgs.push_back(
3536 "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3537 }
3538 else if (Triple.isOSFuchsia())
3539 CmdArgs.push_back("-analyzer-checker=fuchsia");
3540
3541 CmdArgs.push_back("-analyzer-checker=deadcode");
3542
3543 if (types::isCXX(Input.getType()))
3544 CmdArgs.push_back("-analyzer-checker=cplusplus");
3545
3546 if (!Triple.isPS()) {
3547 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3548 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3549 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3550 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3551 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3552 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3553 }
3554
3555 // Default nullability checks.
3556 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3557 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3558 }
3559
3560 // Set the output format. The default is plist, for (lame) historical reasons.
3561 CmdArgs.push_back("-analyzer-output");
3562 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3563 CmdArgs.push_back(A->getValue());
3564 else
3565 CmdArgs.push_back("plist");
3566
3567 // Disable the presentation of standard compiler warnings when using
3568 // --analyze. We only want to show static analyzer diagnostics or frontend
3569 // errors.
3570 CmdArgs.push_back("-w");
3571
3572 // Add -Xanalyzer arguments when running as analyzer.
3573 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3574}
3575
3576static bool isValidSymbolName(StringRef S) {
3577 if (S.empty())
3578 return false;
3579
3580 if (std::isdigit(S[0]))
3581 return false;
3582
3583 return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3584}
3585
3586static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3587 const ArgList &Args, ArgStringList &CmdArgs,
3588 bool KernelOrKext) {
3589 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3590
3591 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3592 // doesn't even have a stack!
3593 if (EffectiveTriple.isNVPTX())
3594 return;
3595
3596 // -stack-protector=0 is default.
3598 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3599 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3600
3601 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3602 options::OPT_fstack_protector_all,
3603 options::OPT_fstack_protector_strong,
3604 options::OPT_fstack_protector)) {
3605 if (A->getOption().matches(options::OPT_fstack_protector))
3606 StackProtectorLevel =
3607 std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3608 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3609 StackProtectorLevel = LangOptions::SSPStrong;
3610 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3611 StackProtectorLevel = LangOptions::SSPReq;
3612
3613 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3614 D.Diag(diag::warn_drv_unsupported_option_for_target)
3615 << A->getSpelling() << EffectiveTriple.getTriple();
3616 StackProtectorLevel = DefaultStackProtectorLevel;
3617 }
3618 } else {
3619 StackProtectorLevel = DefaultStackProtectorLevel;
3620 }
3621
3622 if (StackProtectorLevel) {
3623 CmdArgs.push_back("-stack-protector");
3624 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3625 }
3626
3627 // --param ssp-buffer-size=
3628 for (const Arg *A : Args.filtered(options::OPT__param)) {
3629 StringRef Str(A->getValue());
3630 if (Str.consume_front("ssp-buffer-size=")) {
3631 if (StackProtectorLevel) {
3632 CmdArgs.push_back("-stack-protector-buffer-size");
3633 // FIXME: Verify the argument is a valid integer.
3634 CmdArgs.push_back(Args.MakeArgString(Str));
3635 }
3636 A->claim();
3637 }
3638 }
3639
3640 const std::string &TripleStr = EffectiveTriple.getTriple();
3641 StringRef GuardValue;
3642 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3643 GuardValue = A->getValue();
3644 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3645 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3646 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC() &&
3647 !EffectiveTriple.isSystemZ())
3648 D.Diag(diag::err_drv_unsupported_opt_for_target)
3649 << A->getAsString(Args) << TripleStr;
3650 // z/OS only supports the tls mode.
3651 if (EffectiveTriple.isOSzOS() && GuardValue != "tls") {
3652 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3653 << A->getOption().getName() << GuardValue << "tls";
3654 return;
3655 }
3656 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3657 EffectiveTriple.isThumb() || EffectiveTriple.isSystemZ()) &&
3658 GuardValue != "tls" && GuardValue != "global") {
3659 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3660 << A->getOption().getName() << GuardValue << "tls global";
3661 return;
3662 }
3663 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3664 GuardValue == "tls") {
3665 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3666 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3667 << A->getAsString(Args);
3668 return;
3669 }
3670 // Check whether the target subarch supports the hardware TLS register
3671 if (!arm::isHardTPSupported(EffectiveTriple)) {
3672 D.Diag(diag::err_target_unsupported_tp_hard)
3673 << EffectiveTriple.getArchName();
3674 return;
3675 }
3676 // Check whether the user asked for something other than -mtp=cp15
3677 if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3678 StringRef Value = A->getValue();
3679 if (Value != "cp15") {
3680 D.Diag(diag::err_drv_argument_not_allowed_with)
3681 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3682 return;
3683 }
3684 }
3685 CmdArgs.push_back("-target-feature");
3686 CmdArgs.push_back("+read-tp-tpidruro");
3687 }
3688 if (EffectiveTriple.isAArch64() && GuardValue != "sysreg" &&
3689 GuardValue != "global") {
3690 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3691 << A->getOption().getName() << GuardValue << "sysreg global";
3692 return;
3693 }
3694 if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {
3695 if (GuardValue != "tls" && GuardValue != "global") {
3696 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3697 << A->getOption().getName() << GuardValue << "tls global";
3698 return;
3699 }
3700 if (GuardValue == "tls") {
3701 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3702 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3703 << A->getAsString(Args);
3704 return;
3705 }
3706 }
3707 }
3708 A->render(Args, CmdArgs);
3709 }
3710
3711 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3712 StringRef Value = A->getValue();
3713 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3714 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3715 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3716 D.Diag(diag::err_drv_unsupported_opt_for_target)
3717 << A->getAsString(Args) << TripleStr;
3718 int Offset;
3719 if (Value.getAsInteger(10, Offset)) {
3720 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3721 return;
3722 }
3723 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3724 (Offset < 0 || Offset > 0xfffff)) {
3725 D.Diag(diag::err_drv_invalid_int_value)
3726 << A->getOption().getName() << Value;
3727 return;
3728 }
3729 A->render(Args, CmdArgs);
3730 }
3731
3732 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3733 StringRef Value = A->getValue();
3734 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3735 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3736 D.Diag(diag::err_drv_unsupported_opt_for_target)
3737 << A->getAsString(Args) << TripleStr;
3738 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3739 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3740 << A->getOption().getName() << Value << "fs gs";
3741 return;
3742 }
3743 if (EffectiveTriple.isAArch64() &&
3744 llvm::StringSwitch<bool>(Value)
3745 .Cases({"sp_el0", "tpidrro_el0", "tpidr_el0", "tpidr_el1",
3746 "tpidr_el2", "far_el1", "far_el2"},
3747 false)
3748 .Default(true)) {
3749 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3750 << A->getOption().getName() << Value
3751 << "{sp_el0, tpidrro_el0, tpidr_el[012], far_el[12]}";
3752 return;
3753 }
3754 if (EffectiveTriple.isRISCV() && Value != "tp") {
3755 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3756 << A->getOption().getName() << Value << "tp";
3757 return;
3758 }
3759 if (EffectiveTriple.isPPC64() && Value != "r13") {
3760 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3761 << A->getOption().getName() << Value << "r13";
3762 return;
3763 }
3764 if (EffectiveTriple.isPPC32() && Value != "r2") {
3765 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3766 << A->getOption().getName() << Value << "r2";
3767 return;
3768 }
3769 A->render(Args, CmdArgs);
3770 }
3771
3772 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3773 StringRef Value = A->getValue();
3774 if (!isValidSymbolName(Value)) {
3775 D.Diag(diag::err_drv_argument_only_allowed_with)
3776 << A->getOption().getName() << "legal symbol name";
3777 return;
3778 }
3779 A->render(Args, CmdArgs);
3780 }
3781
3782 if (Arg *A =
3783 Args.getLastArg(options::OPT_mstack_protector_guard_value_width_EQ)) {
3784 if (!EffectiveTriple.isAArch64())
3785 D.Diag(diag::err_drv_unsupported_opt_for_target)
3786 << A->getAsString(Args) << TripleStr;
3787 StringRef Value = A->getValue();
3788 unsigned Width;
3789 if (Value.getAsInteger(10, Width)) {
3790 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3791 return;
3792 }
3793 if (Width != 4 && Width != 8) {
3794 D.Diag(diag::err_drv_invalid_int_value)
3795 << A->getOption().getName() << Value;
3796 }
3797 }
3798 if (Arg *A = Args.getLastArg(options::OPT_mstackprotector_guard_record)) {
3799 if (!EffectiveTriple.isSystemZ()) {
3800 D.Diag(diag::err_drv_unsupported_opt_for_target)
3801 << A->getAsString(Args) << TripleStr;
3802 return;
3803 }
3804 if (GuardValue != "global") {
3805 D.Diag(diag::err_drv_argument_only_allowed_with)
3806 << "-mstack-protector-guard-record"
3807 << "-mstack-protector-guard=global";
3808 return;
3809 }
3810 A->render(Args, CmdArgs);
3811 }
3812}
3813
3814static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3815 ArgStringList &CmdArgs) {
3816 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3817
3818 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&
3819 !EffectiveTriple.isOSFuchsia())
3820 return;
3821
3822 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3823 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&
3824 !EffectiveTriple.isRISCV() && !EffectiveTriple.isLoongArch())
3825 return;
3826
3827 Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
3828 options::OPT_fno_stack_clash_protection);
3829}
3830
3832 const ToolChain &TC,
3833 const ArgList &Args,
3834 ArgStringList &CmdArgs) {
3835 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3836 StringRef TrivialAutoVarInit = "";
3837
3838 for (const Arg *A : Args) {
3839 switch (A->getOption().getID()) {
3840 default:
3841 continue;
3842 case options::OPT_ftrivial_auto_var_init: {
3843 A->claim();
3844 StringRef Val = A->getValue();
3845 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3846 TrivialAutoVarInit = Val;
3847 else
3848 D.Diag(diag::err_drv_unsupported_option_argument)
3849 << A->getSpelling() << Val;
3850 break;
3851 }
3852 }
3853 }
3854
3855 if (TrivialAutoVarInit.empty())
3856 switch (DefaultTrivialAutoVarInit) {
3858 break;
3860 TrivialAutoVarInit = "pattern";
3861 break;
3863 TrivialAutoVarInit = "zero";
3864 break;
3865 }
3866
3867 if (!TrivialAutoVarInit.empty()) {
3868 CmdArgs.push_back(
3869 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3870 }
3871
3872 if (Arg *A =
3873 Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3874 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3875 StringRef(
3876 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3877 "uninitialized")
3878 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3879 A->claim();
3880 StringRef Val = A->getValue();
3881 if (std::stoi(Val.str()) <= 0)
3882 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3883 CmdArgs.push_back(
3884 Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3885 }
3886
3887 if (Arg *A = Args.getLastArg(options::OPT_ftrivial_auto_var_init_max_size)) {
3888 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3889 StringRef(
3890 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3891 "uninitialized")
3892 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3893 A->claim();
3894 StringRef Val = A->getValue();
3895 if (std::stoi(Val.str()) <= 0)
3896 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3897 CmdArgs.push_back(
3898 Args.MakeArgString("-ftrivial-auto-var-init-max-size=" + Val));
3899 }
3900}
3901
3902static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3903 types::ID InputType) {
3904 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3905 // for denormal flushing handling based on the target.
3906 const unsigned ForwardedArguments[] = {
3907 options::OPT_cl_opt_disable,
3908 options::OPT_cl_strict_aliasing,
3909 options::OPT_cl_single_precision_constant,
3910 options::OPT_cl_finite_math_only,
3911 options::OPT_cl_kernel_arg_info,
3912 options::OPT_cl_unsafe_math_optimizations,
3913 options::OPT_cl_fast_relaxed_math,
3914 options::OPT_cl_mad_enable,
3915 options::OPT_cl_no_signed_zeros,
3916 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3917 options::OPT_cl_uniform_work_group_size
3918 };
3919
3920 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3921 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3922 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3923 } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
3924 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3925 CmdArgs.push_back(Args.MakeArgString(CLExtStr));
3926 }
3927
3928 if (Args.hasArg(options::OPT_cl_finite_math_only)) {
3929 CmdArgs.push_back("-menable-no-infs");
3930 CmdArgs.push_back("-menable-no-nans");
3931 }
3932
3933 for (const auto &Arg : ForwardedArguments)
3934 if (const auto *A = Args.getLastArg(Arg))
3935 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3936
3937 // Only add the default headers if we are compiling OpenCL sources.
3938 if ((types::isOpenCL(InputType) ||
3939 (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3940 !Args.hasArg(options::OPT_cl_no_stdinc)) {
3941 CmdArgs.push_back("-finclude-default-header");
3942 CmdArgs.push_back("-fdeclare-opencl-builtins");
3943 }
3944}
3945
3946static void RenderHLSLOptions(const Driver &D, const ArgList &Args,
3947 ArgStringList &CmdArgs, types::ID InputType) {
3948 const unsigned ForwardedArguments[] = {
3949 options::OPT_hlsl_all_resources_bound,
3950 options::OPT_dxil_validator_version,
3951 options::OPT_res_may_alias,
3952 options::OPT_D,
3953 options::OPT_I,
3954 options::OPT_O,
3955 options::OPT_emit_llvm,
3956 options::OPT_emit_obj,
3957 options::OPT_disable_llvm_passes,
3958 options::OPT_fnative_half_type,
3959 options::OPT_fnative_int16_type,
3960 options::OPT_fmatrix_memory_layout_EQ,
3961 options::OPT_hlsl_entrypoint,
3962 options::OPT_fdx_rootsignature_define,
3963 options::OPT_fdx_rootsignature_version,
3964 options::OPT_fhlsl_spv_use_unknown_image_format,
3965 options::OPT_fhlsl_spv_enable_maximal_reconvergence,
3966 options::OPT_fhlsl_spv_preserve_interface};
3967 if (!types::isHLSL(InputType))
3968 return;
3969 for (const auto &Arg : ForwardedArguments)
3970 if (const auto *A = Args.getLastArg(Arg))
3971 A->renderAsInput(Args, CmdArgs);
3972 // Add the default headers if dxc_no_stdinc is not set.
3973 if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
3974 !Args.hasArg(options::OPT_nostdinc))
3975 CmdArgs.push_back("-finclude-default-header");
3976
3977 if (Args.hasArg(options::OPT_dxc_Zss)) {
3978 if (Args.hasArg(options::OPT_dxc_Zsb))
3979 D.Diag(diag::err_drv_dxc_invalid_shader_hash);
3980 CmdArgs.push_back("-mllvm");
3981 CmdArgs.push_back("-dx-Zss");
3982 }
3983 if (Arg *A = Args.getLastArg(options::OPT_dxc_Zsb))
3984 A->claim(); // /Zsb is the default behavior, no need to forward it to llc.
3985 if (Args.hasArg(options::OPT_dxc_source_in_debug_module)) {
3986 CmdArgs.push_back("-mllvm");
3987 CmdArgs.push_back("--dx-source-in-debug-module");
3988 }
3989 if (Args.hasArg(options::OPT_dxc_Qstrip_debug)) {
3990 CmdArgs.push_back("-mllvm");
3991 CmdArgs.push_back("--dx-strip-debug");
3992 }
3993}
3994
3995static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
3996 ArgStringList &CmdArgs, types::ID InputType) {
3997 if (!Args.hasArg(options::OPT_fopenacc))
3998 return;
3999
4000 CmdArgs.push_back("-fopenacc");
4001}
4002
4003static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
4004 const ArgList &Args, ArgStringList &CmdArgs) {
4005 // -fbuiltin is default unless -mkernel is used.
4006 bool UseBuiltins =
4007 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
4008 !Args.hasArg(options::OPT_mkernel));
4009 if (!UseBuiltins)
4010 CmdArgs.push_back("-fno-builtin");
4011
4012 // -ffreestanding implies -fno-builtin.
4013 if (Args.hasArg(options::OPT_ffreestanding))
4014 UseBuiltins = false;
4015
4016 // Process the -fno-builtin-* options.
4017 for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
4018 A->claim();
4019
4020 // If -fno-builtin is specified, then there's no need to pass the option to
4021 // the frontend.
4022 if (UseBuiltins)
4023 A->render(Args, CmdArgs);
4024 }
4025}
4026
4028 if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
4029 Twine Path{Str};
4030 Path.toVector(Result);
4031 return Path.getSingleStringRef() != "";
4032 }
4033 if (llvm::sys::path::cache_directory(Result)) {
4034 llvm::sys::path::append(Result, "clang");
4035 llvm::sys::path::append(Result, "ModuleCache");
4036 return true;
4037 }
4038 return false;
4039}
4040
4043 const char *BaseInput) {
4044 if (Arg *ModuleOutputEQ = Args.getLastArg(options::OPT_fmodule_output_EQ))
4045 return StringRef(ModuleOutputEQ->getValue());
4046
4047 SmallString<256> OutputPath;
4048 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o);
4049 FinalOutput && Args.hasArg(options::OPT_c))
4050 OutputPath = FinalOutput->getValue();
4051 else {
4052 llvm::sys::fs::current_path(OutputPath);
4053 llvm::sys::path::append(OutputPath, llvm::sys::path::filename(BaseInput));
4054 }
4055
4056 const char *Extension = types::getTypeTempSuffix(types::TY_ModuleFile);
4057 llvm::sys::path::replace_extension(OutputPath, Extension);
4058 return OutputPath;
4059}
4060
4062 const ArgList &Args, const InputInfo &Input,
4063 const InputInfo &Output, bool HaveStd20,
4064 ArgStringList &CmdArgs) {
4065 const bool IsCXX = types::isCXX(Input.getType());
4066 const bool HaveStdCXXModules = IsCXX && HaveStd20;
4067 bool HaveModules = HaveStdCXXModules;
4068
4069 // -fmodules enables the use of precompiled modules (off by default).
4070 // Users can pass -fno-cxx-modules to turn off modules support for
4071 // C++/Objective-C++ programs.
4072 const bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4073 options::OPT_fno_cxx_modules, true);
4074 bool HaveClangModules = false;
4075 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4076 if (AllowedInCXX || !IsCXX) {
4077 CmdArgs.push_back("-fmodules");
4078 HaveClangModules = true;
4079 }
4080 }
4081
4082 HaveModules |= HaveClangModules;
4083
4084 if (HaveModules && !AllowedInCXX)
4085 CmdArgs.push_back("-fno-cxx-modules");
4086
4087 // -fmodule-maps enables implicit reading of module map files. By default,
4088 // this is enabled if we are using Clang's flavor of precompiled modules.
4089 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4090 options::OPT_fno_implicit_module_maps, HaveClangModules))
4091 CmdArgs.push_back("-fimplicit-module-maps");
4092
4093 // -fmodules-decluse checks that modules used are declared so (off by default)
4094 Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
4095 options::OPT_fno_modules_decluse);
4096
4097 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4098 // all #included headers are part of modules.
4099 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4100 options::OPT_fno_modules_strict_decluse, false))
4101 CmdArgs.push_back("-fmodules-strict-decluse");
4102
4103 Args.addOptOutFlag(CmdArgs, options::OPT_fmodulemap_allow_subdirectory_search,
4104 options::OPT_fno_modulemap_allow_subdirectory_search);
4105
4106 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4107 bool ImplicitModules = false;
4108 if (!Args.hasFlag(options::OPT_fimplicit_modules,
4109 options::OPT_fno_implicit_modules, HaveClangModules)) {
4110 if (HaveModules)
4111 CmdArgs.push_back("-fno-implicit-modules");
4112 } else if (HaveModules) {
4113 ImplicitModules = true;
4114 // -fmodule-cache-path specifies where our implicitly-built module files
4115 // should be written.
4116 SmallString<128> Path;
4117 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4118 Path = A->getValue();
4119
4120 bool HasPath = true;
4121 if (C.isForDiagnostics()) {
4122 // When generating crash reports, we want to emit the modules along with
4123 // the reproduction sources, so we ignore any provided module path.
4124 Path = Output.getFilename();
4125 llvm::sys::path::replace_extension(Path, ".cache");
4126 llvm::sys::path::append(Path, "modules");
4127 } else if (Path.empty()) {
4128 // No module path was provided: use the default.
4129 HasPath = Driver::getDefaultModuleCachePath(Path);
4130 }
4131
4132 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
4133 // That being said, that failure is unlikely and not caching is harmless.
4134 if (HasPath) {
4135 const char Arg[] = "-fmodules-cache-path=";
4136 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4137 CmdArgs.push_back(Args.MakeArgString(Path));
4138 }
4139
4140 Args.AddLastArg(CmdArgs, options::OPT_fimplicit_modules_lock_timeout_EQ);
4141 }
4142
4143 if (HaveModules) {
4144 if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
4145 options::OPT_fno_prebuilt_implicit_modules, false))
4146 CmdArgs.push_back("-fprebuilt-implicit-modules");
4147 if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
4148 options::OPT_fno_modules_validate_input_files_content,
4149 false))
4150 CmdArgs.push_back("-fvalidate-ast-input-files-content");
4151 }
4152
4153 // -fmodule-name specifies the module that is currently being built (or
4154 // used for header checking by -fmodule-maps).
4155 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
4156
4157 // -fmodule-map-file can be used to specify files containing module
4158 // definitions.
4159 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4160
4161 // -fbuiltin-module-map can be used to load the clang
4162 // builtin headers modulemap file.
4163 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
4164 SmallString<128> BuiltinModuleMap(D.ResourceDir);
4165 llvm::sys::path::append(BuiltinModuleMap, "include");
4166 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
4167 if (llvm::sys::fs::exists(BuiltinModuleMap))
4168 CmdArgs.push_back(
4169 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
4170 }
4171
4172 // The -fmodule-file=<name>=<file> form specifies the mapping of module
4173 // names to precompiled module files (the module is loaded only if used).
4174 // The -fmodule-file=<file> form can be used to unconditionally load
4175 // precompiled module files (whether used or not).
4176 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
4177 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4178
4179 // -fprebuilt-module-path specifies where to load the prebuilt module files.
4180 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
4181 CmdArgs.push_back(Args.MakeArgString(
4182 std::string("-fprebuilt-module-path=") + A->getValue()));
4183 A->claim();
4184 }
4185 } else
4186 Args.ClaimAllArgs(options::OPT_fmodule_file);
4187
4188 // When building modules and generating crashdumps, we need to dump a module
4189 // dependency VFS alongside the output.
4190 if (HaveClangModules && C.isForDiagnostics()) {
4191 SmallString<128> VFSDir(Output.getFilename());
4192 llvm::sys::path::replace_extension(VFSDir, ".cache");
4193 // Add the cache directory as a temp so the crash diagnostics pick it up.
4194 C.addTempFile(Args.MakeArgString(VFSDir));
4195
4196 llvm::sys::path::append(VFSDir, "vfs");
4197 CmdArgs.push_back("-module-dependency-dir");
4198 CmdArgs.push_back(Args.MakeArgString(VFSDir));
4199 }
4200
4201 if (HaveClangModules)
4202 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4203
4204 // Pass through all -fmodules-ignore-macro arguments.
4205 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4206 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4207 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4208
4209 if (HaveClangModules) {
4210 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4211
4212 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4213 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4214 D.Diag(diag::err_drv_argument_not_allowed_with)
4215 << A->getAsString(Args) << "-fbuild-session-timestamp";
4216
4217 llvm::sys::fs::file_status Status;
4218 if (llvm::sys::fs::status(A->getValue(), Status))
4219 D.Diag(diag::err_drv_no_such_file) << A->getValue();
4220 CmdArgs.push_back(Args.MakeArgString(
4221 "-fbuild-session-timestamp=" +
4222 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
4223 Status.getLastModificationTime().time_since_epoch())
4224 .count())));
4225 }
4226
4227 if (Args.getLastArg(
4228 options::OPT_fmodules_validate_once_per_build_session)) {
4229 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4230 options::OPT_fbuild_session_file))
4231 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4232
4233 Args.AddLastArg(CmdArgs,
4234 options::OPT_fmodules_validate_once_per_build_session);
4235 }
4236
4237 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
4238 options::OPT_fno_modules_validate_system_headers,
4239 ImplicitModules))
4240 CmdArgs.push_back("-fmodules-validate-system-headers");
4241
4242 Args.AddLastArg(CmdArgs,
4243 options::OPT_fmodules_disable_diagnostic_validation);
4244 } else {
4245 Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
4246 Args.ClaimAllArgs(options::OPT_fbuild_session_file);
4247 Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
4248 Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
4249 Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
4250 Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
4251 }
4252
4253 // FIXME: We provisionally don't check ODR violations for decls in the global
4254 // module fragment.
4255 CmdArgs.push_back("-fskip-odr-check-in-gmf");
4256
4257 if (Input.getType() == driver::types::TY_CXXModule ||
4258 Input.getType() == driver::types::TY_PP_CXXModule) {
4259 if (!Args.hasArg(options::OPT_fno_modules_reduced_bmi))
4260 CmdArgs.push_back("-fmodules-reduced-bmi");
4261
4262 if (Args.hasArg(options::OPT_fmodule_output_EQ))
4263 Args.AddLastArg(CmdArgs, options::OPT_fmodule_output_EQ);
4264 else if (!(Args.hasArg(options::OPT__precompile) ||
4265 Args.hasArg(options::OPT__precompile_reduced_bmi)) ||
4266 Args.hasArg(options::OPT_fmodule_output))
4267 // If --precompile is specified, we will always generate a module file if
4268 // we're compiling an importable module unit. This is fine even if the
4269 // compilation process won't reach the point of generating the module file
4270 // (e.g., in the preprocessing mode), since the attached flag
4271 // '-fmodule-output' is useless.
4272 //
4273 // But if '--precompile' is specified, it might be annoying to always
4274 // generate the module file as '--precompile' will generate the module
4275 // file anyway.
4276 CmdArgs.push_back(Args.MakeArgString(
4277 "-fmodule-output=" +
4279 }
4280
4281 if (Args.hasArg(options::OPT_fmodules_reduced_bmi) &&
4282 Args.hasArg(options::OPT__precompile) &&
4283 (!Args.hasArg(options::OPT_o) ||
4284 Args.getLastArg(options::OPT_o)->getValue() ==
4286 D.Diag(diag::err_drv_reduced_module_output_overrided);
4287 }
4288
4289 // Noop if we see '-fmodules-reduced-bmi' or `-fno-modules-reduced-bmi` with
4290 // other translation units than module units. This is more user friendly to
4291 // allow end uers to enable this feature without asking for help from build
4292 // systems.
4293 Args.ClaimAllArgs(options::OPT_fmodules_reduced_bmi);
4294 Args.ClaimAllArgs(options::OPT_fno_modules_reduced_bmi);
4295
4296 // We need to include the case the input file is a module file here.
4297 // Since the default compilation model for C++ module interface unit will
4298 // create temporary module file and compile the temporary module file
4299 // to get the object file. Then the `-fmodule-output` flag will be
4300 // brought to the second compilation process. So we have to claim it for
4301 // the case too.
4302 if (Input.getType() == driver::types::TY_CXXModule ||
4303 Input.getType() == driver::types::TY_PP_CXXModule ||
4304 Input.getType() == driver::types::TY_ModuleFile) {
4305 Args.ClaimAllArgs(options::OPT_fmodule_output);
4306 Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
4307 }
4308
4309 if (Args.hasArg(options::OPT_fmodules_embed_all_files))
4310 CmdArgs.push_back("-fmodules-embed-all-files");
4311
4312 return HaveModules;
4313}
4314
4315static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4316 ArgStringList &CmdArgs) {
4317 // -fsigned-char is default.
4318 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
4319 options::OPT_fno_signed_char,
4320 options::OPT_funsigned_char,
4321 options::OPT_fno_unsigned_char)) {
4322 if (A->getOption().matches(options::OPT_funsigned_char) ||
4323 A->getOption().matches(options::OPT_fno_signed_char)) {
4324 CmdArgs.push_back("-fno-signed-char");
4325 }
4326 } else if (!isSignedCharDefault(T)) {
4327 CmdArgs.push_back("-fno-signed-char");
4328 }
4329
4330 // The default depends on the language standard.
4331 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
4332
4333 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4334 options::OPT_fno_short_wchar)) {
4335 if (A->getOption().matches(options::OPT_fshort_wchar)) {
4336 CmdArgs.push_back("-fwchar-type=short");
4337 CmdArgs.push_back("-fno-signed-wchar");
4338 } else {
4339 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4340 CmdArgs.push_back("-fwchar-type=int");
4341 if (T.isOSzOS() ||
4342 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4343 CmdArgs.push_back("-fno-signed-wchar");
4344 else
4345 CmdArgs.push_back("-fsigned-wchar");
4346 }
4347 } else if (T.isOSzOS())
4348 CmdArgs.push_back("-fno-signed-wchar");
4349}
4350
4351static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4352 const llvm::Triple &T, const ArgList &Args,
4353 ObjCRuntime &Runtime, bool InferCovariantReturns,
4354 const InputInfo &Input, ArgStringList &CmdArgs) {
4355 const llvm::Triple::ArchType Arch = TC.getArch();
4356
4357 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4358 // is the default. Except for deployment target of 10.5, next runtime is
4359 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4360 if (Runtime.isNonFragile()) {
4361 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4362 options::OPT_fno_objc_legacy_dispatch,
4364 if (TC.UseObjCMixedDispatch())
4365 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
4366 else
4367 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
4368 }
4369 }
4370
4371 // Forward -fobjc-direct-precondition-thunk to cc1
4372 // Defaults to false and needs explict turn on for now
4373 // TODO: switch to default true and needs explict turn off in the future.
4374 // TODO: add support for other runtimes
4375 if (Args.hasFlag(options::OPT_fobjc_direct_precondition_thunk,
4376 options::OPT_fno_objc_direct_precondition_thunk, false)) {
4377 if (Runtime.isNeXTFamily()) {
4378 CmdArgs.push_back("-fobjc-direct-precondition-thunk");
4379 } else {
4380 D.Diag(diag::warn_drv_unsupported_option_for_runtime)
4381 << "-fobjc-direct-precondition-thunk" << Runtime.getAsString();
4382 }
4383 }
4384
4385 if (types::isObjC(Input.getType())) {
4386 // Pass down -fobjc-msgsend-selector-stubs if present.
4387 if (Args.hasFlag(options::OPT_fobjc_msgsend_selector_stubs,
4388 options::OPT_fno_objc_msgsend_selector_stubs, false))
4389 CmdArgs.push_back("-fobjc-msgsend-selector-stubs");
4390
4391 // Pass down -fobjc-msgsend-class-selector-stubs if present.
4392 if (Args.hasFlag(options::OPT_fobjc_msgsend_class_selector_stubs,
4393 options::OPT_fno_objc_msgsend_class_selector_stubs, false))
4394 CmdArgs.push_back("-fobjc-msgsend-class-selector-stubs");
4395 }
4396
4397 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4398 // to do Array/Dictionary subscripting by default.
4399 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4400 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4401 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4402
4403 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4404 // NOTE: This logic is duplicated in ToolChains.cpp.
4405 if (isObjCAutoRefCount(Args)) {
4406 TC.CheckObjCARC();
4407
4408 CmdArgs.push_back("-fobjc-arc");
4409
4410 // FIXME: It seems like this entire block, and several around it should be
4411 // wrapped in isObjC, but for now we just use it here as this is where it
4412 // was being used previously.
4413 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
4415 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4416 else
4417 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4418 }
4419
4420 // Allow the user to enable full exceptions code emission.
4421 // We default off for Objective-C, on for Objective-C++.
4422 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4423 options::OPT_fno_objc_arc_exceptions,
4424 /*Default=*/types::isCXX(Input.getType())))
4425 CmdArgs.push_back("-fobjc-arc-exceptions");
4426 }
4427
4428 // Silence warning for full exception code emission options when explicitly
4429 // set to use no ARC.
4430 if (Args.hasArg(options::OPT_fno_objc_arc)) {
4431 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
4432 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
4433 }
4434
4435 // Allow the user to control whether messages can be converted to runtime
4436 // functions.
4437 if (types::isObjC(Input.getType())) {
4438 auto *Arg = Args.getLastArg(
4439 options::OPT_fobjc_convert_messages_to_runtime_calls,
4440 options::OPT_fno_objc_convert_messages_to_runtime_calls);
4441 if (Arg &&
4442 Arg->getOption().matches(
4443 options::OPT_fno_objc_convert_messages_to_runtime_calls))
4444 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
4445 }
4446
4447 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4448 // rewriter.
4449 if (InferCovariantReturns)
4450 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4451
4452 // Pass down -fobjc-weak or -fno-objc-weak if present.
4453 if (types::isObjC(Input.getType())) {
4454 auto WeakArg =
4455 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
4456 if (!WeakArg) {
4457 // nothing to do
4458 } else if (!Runtime.allowsWeak()) {
4459 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
4460 D.Diag(diag::err_objc_weak_unsupported);
4461 } else {
4462 WeakArg->render(Args, CmdArgs);
4463 }
4464 }
4465
4466 if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4467 CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
4468
4469 // Forward constant literal flags to cc1.
4470 if (types::isObjC(Input.getType())) {
4471 bool EnableConstantLiterals =
4472 Args.hasFlag(options::OPT_fobjc_constant_literals,
4473 options::OPT_fno_objc_constant_literals,
4474 /*default=*/true) &&
4475 Runtime.hasConstantLiteralClasses();
4476 if (EnableConstantLiterals)
4477 CmdArgs.push_back("-fobjc-constant-literals");
4478 if (Args.hasFlag(options::OPT_fconstant_nsnumber_literals,
4479 options::OPT_fno_constant_nsnumber_literals,
4480 /*default=*/true) &&
4481 EnableConstantLiterals)
4482 CmdArgs.push_back("-fconstant-nsnumber-literals");
4483 if (Args.hasFlag(options::OPT_fconstant_nsarray_literals,
4484 options::OPT_fno_constant_nsarray_literals,
4485 /*default=*/true) &&
4486 EnableConstantLiterals)
4487 CmdArgs.push_back("-fconstant-nsarray-literals");
4488 if (Args.hasFlag(options::OPT_fconstant_nsdictionary_literals,
4489 options::OPT_fno_constant_nsdictionary_literals,
4490 /*default=*/true) &&
4491 EnableConstantLiterals)
4492 CmdArgs.push_back("-fconstant-nsdictionary-literals");
4493 }
4494}
4495
4496static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4497 ArgStringList &CmdArgs) {
4498 bool CaretDefault = true;
4499 bool ColumnDefault = true;
4500
4501 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4502 options::OPT__SLASH_diagnostics_column,
4503 options::OPT__SLASH_diagnostics_caret)) {
4504 switch (A->getOption().getID()) {
4505 case options::OPT__SLASH_diagnostics_caret:
4506 CaretDefault = true;
4507 ColumnDefault = true;
4508 break;
4509 case options::OPT__SLASH_diagnostics_column:
4510 CaretDefault = false;
4511 ColumnDefault = true;
4512 break;
4513 case options::OPT__SLASH_diagnostics_classic:
4514 CaretDefault = false;
4515 ColumnDefault = false;
4516 break;
4517 }
4518 }
4519
4520 // -fcaret-diagnostics is default.
4521 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4522 options::OPT_fno_caret_diagnostics, CaretDefault))
4523 CmdArgs.push_back("-fno-caret-diagnostics");
4524
4525 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
4526 options::OPT_fno_diagnostics_fixit_info);
4527 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
4528 options::OPT_fno_diagnostics_show_option);
4529
4530 if (const Arg *A =
4531 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4532 CmdArgs.push_back("-fdiagnostics-show-category");
4533 CmdArgs.push_back(A->getValue());
4534 }
4535
4536 Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
4537 options::OPT_fno_diagnostics_show_hotness);
4538
4539 if (const Arg *A =
4540 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4541 std::string Opt =
4542 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4543 CmdArgs.push_back(Args.MakeArgString(Opt));
4544 }
4545
4546 if (const Arg *A =
4547 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4548 std::string Opt =
4549 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4550 CmdArgs.push_back(Args.MakeArgString(Opt));
4551 }
4552
4553 if (const Arg *A =
4554 Args.getLastArg(options::OPT_fdiagnostics_show_inlining_chain,
4555 options::OPT_fno_diagnostics_show_inlining_chain)) {
4556 if (A->getOption().matches(options::OPT_fdiagnostics_show_inlining_chain))
4557 CmdArgs.push_back("-fdiagnostics-show-inlining-chain");
4558 else
4559 CmdArgs.push_back("-fno-diagnostics-show-inlining-chain");
4560 }
4561
4562 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4563 CmdArgs.push_back("-fdiagnostics-format");
4564 CmdArgs.push_back(A->getValue());
4565 if (StringRef(A->getValue()) == "sarif" ||
4566 StringRef(A->getValue()) == "SARIF")
4567 D.Diag(diag::warn_drv_sarif_format_unstable);
4568 }
4569
4570 if (const Arg *A = Args.getLastArg(
4571 options::OPT_fdiagnostics_show_note_include_stack,
4572 options::OPT_fno_diagnostics_show_note_include_stack)) {
4573 const Option &O = A->getOption();
4574 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4575 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4576 else
4577 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4578 }
4579
4580 handleColorDiagnosticsArgs(D, Args, CmdArgs);
4581
4582 if (Args.hasArg(options::OPT_fansi_escape_codes))
4583 CmdArgs.push_back("-fansi-escape-codes");
4584
4585 Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
4586 options::OPT_fno_show_source_location);
4587
4588 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
4589 options::OPT_fno_diagnostics_show_line_numbers);
4590
4591 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4592 CmdArgs.push_back("-fdiagnostics-absolute-paths");
4593
4594 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4595 ColumnDefault))
4596 CmdArgs.push_back("-fno-show-column");
4597
4598 Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
4599 options::OPT_fno_spell_checking);
4600
4601 Args.addLastArg(CmdArgs, options::OPT_warning_suppression_mappings_EQ);
4602}
4603
4604static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4605 const ArgList &Args, ArgStringList &CmdArgs,
4606 unsigned DwarfVersion) {
4607 auto *DwarfFormatArg =
4608 Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4609 if (!DwarfFormatArg)
4610 return;
4611
4612 if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4613 if (DwarfVersion < 3)
4614 D.Diag(diag::err_drv_argument_only_allowed_with)
4615 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4616 else if (!T.isArch64Bit())
4617 D.Diag(diag::err_drv_argument_only_allowed_with)
4618 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4619 else if (!T.isOSBinFormatELF())
4620 D.Diag(diag::err_drv_argument_only_allowed_with)
4621 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4622 }
4623
4624 DwarfFormatArg->render(Args, CmdArgs);
4625}
4626
4627static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D,
4628 const ArgList &Args) {
4629 bool NeedsSimpleTemplateNames =
4630 Args.hasFlag(options::OPT_gsimple_template_names,
4631 options::OPT_gno_simple_template_names,
4633 if (!NeedsSimpleTemplateNames)
4634 return false;
4635
4636 if (const Arg *A = Args.getLastArg(options::OPT_gsimple_template_names))
4637 if (!checkDebugInfoOption(A, Args, D, TC))
4638 return false;
4639
4640 return true;
4641}
4642
4643static void
4644renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4645 const ArgList &Args, types::ID InputType,
4646 ArgStringList &CmdArgs, const InputInfo &Output,
4647 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4648 DwarfFissionKind &DwarfFission) {
4649 bool IRInput = isLLVMIR(InputType);
4650 bool PlainCOrCXX = isDerivedFromC(InputType) && !isCuda(InputType) &&
4651 !isHIP(InputType) && !isObjC(InputType) &&
4652 !isOpenCL(InputType);
4653
4654 addDebugInfoForProfilingArgs(D, TC, Args, CmdArgs);
4655
4656 if (!Args.hasFlag(options::OPT_fdebug_record_sysroot,
4657 options::OPT_fno_debug_record_sysroot, true))
4658 CmdArgs.push_back("-fno-debug-record-sysroot");
4659
4660 // The 'g' groups options involve a somewhat intricate sequence of decisions
4661 // about what to pass from the driver to the frontend, but by the time they
4662 // reach cc1 they've been factored into three well-defined orthogonal choices:
4663 // * what level of debug info to generate
4664 // * what dwarf version to write
4665 // * what debugger tuning to use
4666 // This avoids having to monkey around further in cc1 other than to disable
4667 // codeview if not running in a Windows environment. Perhaps even that
4668 // decision should be made in the driver as well though.
4669 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4670
4671 bool SplitDWARFInlining =
4672 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4673 options::OPT_fno_split_dwarf_inlining, false);
4674
4675 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4676 // object file generation and no IR generation, -gN should not be needed. So
4677 // allow -gsplit-dwarf with either -gN or IR input.
4678 if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4679 // FIXME: -gsplit-dwarf on AIX is currently unimplemented.
4680 if (TC.getTriple().isOSAIX() && Args.hasArg(options::OPT_gsplit_dwarf)) {
4681 D.Diag(diag::err_drv_unsupported_opt_for_target)
4682 << Args.getLastArg(options::OPT_gsplit_dwarf)->getSpelling()
4683 << TC.getTripleString();
4684 return;
4685 }
4686 Arg *SplitDWARFArg;
4687 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
4688 if (DwarfFission != DwarfFissionKind::None &&
4689 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
4690 DwarfFission = DwarfFissionKind::None;
4691 SplitDWARFInlining = false;
4692 }
4693 }
4694 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4695 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4696
4697 // If the last option explicitly specified a debug-info level, use it.
4698 if (checkDebugInfoOption(A, Args, D, TC) &&
4699 A->getOption().matches(options::OPT_gN_Group)) {
4700 DebugInfoKind = debugLevelToInfoKind(*A);
4701 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4702 // complicated if you've disabled inline info in the skeleton CUs
4703 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4704 // line-tables-only, so let those compose naturally in that case.
4705 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4706 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4707 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4708 SplitDWARFInlining))
4709 DwarfFission = DwarfFissionKind::None;
4710 }
4711 }
4712
4713 // If a debugger tuning argument appeared, remember it.
4714 bool HasDebuggerTuning = false;
4715 if (const Arg *A =
4716 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4717 HasDebuggerTuning = true;
4718 if (checkDebugInfoOption(A, Args, D, TC)) {
4719 if (A->getOption().matches(options::OPT_glldb))
4720 DebuggerTuning = llvm::DebuggerKind::LLDB;
4721 else if (A->getOption().matches(options::OPT_gsce))
4722 DebuggerTuning = llvm::DebuggerKind::SCE;
4723 else if (A->getOption().matches(options::OPT_gdbx))
4724 DebuggerTuning = llvm::DebuggerKind::DBX;
4725 else
4726 DebuggerTuning = llvm::DebuggerKind::GDB;
4727 }
4728 }
4729
4730 // If a -gdwarf argument appeared, remember it.
4731 bool EmitDwarf = false;
4732 if (const Arg *A = getDwarfNArg(Args))
4733 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4734
4735 bool EmitCodeView = false;
4736 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4737 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4738
4739 // If the user asked for debug info but did not explicitly specify -gcodeview
4740 // or -gdwarf, ask the toolchain for the default format.
4741 if (!EmitCodeView && !EmitDwarf &&
4742 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4743 switch (TC.getDefaultDebugFormat()) {
4744 case llvm::codegenoptions::DIF_CodeView:
4745 EmitCodeView = true;
4746 break;
4747 case llvm::codegenoptions::DIF_DWARF:
4748 EmitDwarf = true;
4749 break;
4750 }
4751 }
4752
4753 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4754 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4755 // be lower than what the user wanted.
4756 if (EmitDwarf) {
4757 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4758 // Clamp effective DWARF version to the max supported by the toolchain.
4759 EffectiveDWARFVersion =
4760 std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4761 } else {
4762 Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4763 }
4764
4765 // -gline-directives-only supported only for the DWARF debug info.
4766 if (RequestedDWARFVersion == 0 &&
4767 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4768 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4769
4770 // strict DWARF is set to false by default. But for DBX, we need it to be set
4771 // as true by default.
4772 if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4773 (void)checkDebugInfoOption(A, Args, D, TC);
4774 if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4775 DebuggerTuning == llvm::DebuggerKind::DBX))
4776 CmdArgs.push_back("-gstrict-dwarf");
4777
4778 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4779 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4780
4781 // Column info is included by default for everything except SCE and
4782 // CodeView if not use sampling PGO. Clang doesn't track end columns, just
4783 // starting columns, which, in theory, is fine for CodeView (and PDB). In
4784 // practice, however, the Microsoft debuggers don't handle missing end columns
4785 // well, and the AIX debugger DBX also doesn't handle the columns well, so
4786 // it's better not to include any column info.
4787 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4788 (void)checkDebugInfoOption(A, Args, D, TC);
4789 if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4790 !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
4791 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4792 DebuggerTuning != llvm::DebuggerKind::DBX)))
4793 CmdArgs.push_back("-gno-column-info");
4794
4795 if (!Args.hasFlag(options::OPT_gcall_site_info,
4796 options::OPT_gno_call_site_info, true))
4797 CmdArgs.push_back("-gno-call-site-info");
4798
4799 // FIXME: Move backend command line options to the module.
4800 if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4801 // If -gline-tables-only or -gline-directives-only is the last option it
4802 // wins.
4803 if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4804 TC)) {
4805 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4806 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4807 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4808 CmdArgs.push_back("-dwarf-ext-refs");
4809 CmdArgs.push_back("-fmodule-format=obj");
4810 }
4811 }
4812 }
4813
4814 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4815 CmdArgs.push_back("-fsplit-dwarf-inlining");
4816
4817 // After we've dealt with all combinations of things that could
4818 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4819 // figure out if we need to "upgrade" it to standalone debug info.
4820 // We parse these two '-f' options whether or not they will be used,
4821 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4822 bool NeedFullDebug = Args.hasFlag(
4823 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4824 DebuggerTuning == llvm::DebuggerKind::LLDB ||
4826 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4827 (void)checkDebugInfoOption(A, Args, D, TC);
4828
4829 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4830 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4831 if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4832 options::OPT_feliminate_unused_debug_types, false))
4833 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4834 else if (NeedFullDebug)
4835 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4836 }
4837
4838 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4839 false)) {
4840 // Source embedding is a vendor extension to DWARF v5. By now we have
4841 // checked if a DWARF version was stated explicitly, and have otherwise
4842 // fallen back to the target default, so if this is still not at least 5
4843 // we emit an error.
4844 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4845 if (RequestedDWARFVersion < 5)
4846 D.Diag(diag::err_drv_argument_only_allowed_with)
4847 << A->getAsString(Args) << "-gdwarf-5";
4848 else if (EffectiveDWARFVersion < 5)
4849 // The toolchain has reduced allowed dwarf version, so we can't enable
4850 // -gembed-source.
4851 D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4852 << A->getAsString(Args) << TC.getTripleString() << 5
4853 << EffectiveDWARFVersion;
4854 else if (checkDebugInfoOption(A, Args, D, TC))
4855 CmdArgs.push_back("-gembed-source");
4856 }
4857
4858 // Enable Key Instructions by default if we're emitting DWARF, the language is
4859 // plain C or C++, and optimisations are enabled.
4860 Arg *OptLevel = Args.getLastArg(options::OPT_O_Group);
4861 bool KeyInstructionsOnByDefault =
4862 EmitDwarf && PlainCOrCXX && OptLevel &&
4863 !OptLevel->getOption().matches(options::OPT_O0);
4864 if (Args.hasFlag(options::OPT_gkey_instructions,
4865 options::OPT_gno_key_instructions,
4866 KeyInstructionsOnByDefault))
4867 CmdArgs.push_back("-gkey-instructions");
4868
4869 if (!Args.hasFlag(options::OPT_gstructor_decl_linkage_names,
4870 options::OPT_gno_structor_decl_linkage_names, true))
4871 CmdArgs.push_back("-gno-structor-decl-linkage-names");
4872
4873 if (EmitCodeView) {
4874 CmdArgs.push_back("-gcodeview");
4875
4876 Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4877 options::OPT_gno_codeview_ghash);
4878
4879 Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4880 options::OPT_gno_codeview_command_line);
4881 }
4882
4883 Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4884 options::OPT_gno_inline_line_tables);
4885
4886 // When emitting remarks, we need at least debug lines in the output.
4887 if (willEmitRemarks(Args) &&
4888 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4889 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4890
4891 // Adjust the debug info kind for the given toolchain.
4892 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4893
4894 // On AIX, the debugger tuning option can be omitted if it is not explicitly
4895 // set.
4896 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4897 T.isOSAIX() && !HasDebuggerTuning
4898 ? llvm::DebuggerKind::Default
4899 : DebuggerTuning);
4900
4901 // -fdebug-macro turns on macro debug info generation.
4902 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4903 false))
4904 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4905 D, TC))
4906 CmdArgs.push_back("-debug-info-macro");
4907
4908 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4909 const auto *PubnamesArg =
4910 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4911 options::OPT_gpubnames, options::OPT_gno_pubnames);
4912 if (DwarfFission != DwarfFissionKind::None ||
4913 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC))) {
4914 const bool OptionSet =
4915 (PubnamesArg &&
4916 (PubnamesArg->getOption().matches(options::OPT_gpubnames) ||
4917 PubnamesArg->getOption().matches(options::OPT_ggnu_pubnames)));
4918 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
4919 (!PubnamesArg ||
4920 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4921 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames))))
4922 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4923 options::OPT_gpubnames)
4924 ? "-gpubnames"
4925 : "-ggnu-pubnames");
4926 }
4927
4928 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4929 if (getDebugSimpleTemplateNames(TC, D, Args)) {
4930 ForwardTemplateParams = true;
4931 CmdArgs.push_back("-gsimple-template-names=simple");
4932 }
4933
4934 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
4935 bool UseDebugTemplateAlias =
4936 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
4937 if (const auto *DebugTemplateAlias = Args.getLastArg(
4938 options::OPT_gtemplate_alias, options::OPT_gno_template_alias)) {
4939 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
4940 // asks for it we should let them have it (if the target supports it).
4941 if (checkDebugInfoOption(DebugTemplateAlias, Args, D, TC)) {
4942 const auto &Opt = DebugTemplateAlias->getOption();
4943 UseDebugTemplateAlias = Opt.matches(options::OPT_gtemplate_alias);
4944 }
4945 }
4946 if (UseDebugTemplateAlias)
4947 CmdArgs.push_back("-gtemplate-alias");
4948
4949 if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
4950 StringRef v = A->getValue();
4951 CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
4952 }
4953
4954 Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
4955 options::OPT_fno_debug_ranges_base_address);
4956
4957 // -gdwarf-aranges turns on the emission of the aranges section in the
4958 // backend.
4959 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges);
4960 A && checkDebugInfoOption(A, Args, D, TC)) {
4961 CmdArgs.push_back("-mllvm");
4962 CmdArgs.push_back("-generate-arange-section");
4963 }
4964
4965 Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
4966 options::OPT_fno_force_dwarf_frame);
4967
4968 bool EnableTypeUnits = false;
4969 if (Args.hasFlag(options::OPT_fdebug_types_section,
4970 options::OPT_fno_debug_types_section, false)) {
4971 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4972 D.Diag(diag::err_drv_unsupported_opt_for_target)
4973 << Args.getLastArg(options::OPT_fdebug_types_section)
4974 ->getAsString(Args)
4975 << T.getTriple();
4976 } else if (checkDebugInfoOption(
4977 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
4978 TC)) {
4979 EnableTypeUnits = true;
4980 CmdArgs.push_back("-mllvm");
4981 CmdArgs.push_back("-generate-type-units");
4982 }
4983 }
4984
4985 if (const Arg *A =
4986 Args.getLastArg(options::OPT_gomit_unreferenced_methods,
4987 options::OPT_gno_omit_unreferenced_methods))
4988 (void)checkDebugInfoOption(A, Args, D, TC);
4989 if (Args.hasFlag(options::OPT_gomit_unreferenced_methods,
4990 options::OPT_gno_omit_unreferenced_methods, false) &&
4991 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
4992 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
4993 !EnableTypeUnits) {
4994 CmdArgs.push_back("-gomit-unreferenced-methods");
4995 }
4996
4997 // To avoid join/split of directory+filename, the integrated assembler prefers
4998 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4999 // form before DWARF v5.
5000 if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
5001 options::OPT_fno_dwarf_directory_asm,
5002 TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
5003 CmdArgs.push_back("-fno-dwarf-directory-asm");
5004
5005 // Decide how to render forward declarations of template instantiations.
5006 // SCE wants full descriptions, others just get them in the name.
5007 if (ForwardTemplateParams)
5008 CmdArgs.push_back("-debug-forward-template-params");
5009
5010 // Do we need to explicitly import anonymous namespaces into the parent
5011 // scope?
5012 if (DebuggerTuning == llvm::DebuggerKind::SCE)
5013 CmdArgs.push_back("-dwarf-explicit-import");
5014
5015 renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
5016 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
5017
5018 // This controls whether or not we perform JustMyCode instrumentation.
5019 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
5020 if (TC.getTriple().isOSBinFormatELF() ||
5021 TC.getTriple().isWindowsMSVCEnvironment()) {
5022 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
5023 CmdArgs.push_back("-fjmc");
5024 else if (D.IsCLMode())
5025 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
5026 << "'/Zi', '/Z7'";
5027 else
5028 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
5029 << "-g";
5030 } else {
5031 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
5032 }
5033 }
5034
5035 // Add in -fdebug-compilation-dir if necessary.
5036 const char *DebugCompilationDir =
5037 addDebugCompDirArg(Args, CmdArgs, D.getVFS());
5038
5039 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
5040
5041 // Add the output path to the object file for CodeView debug infos.
5042 if (EmitCodeView && Output.isFilename())
5043 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
5044 Output.getFilename());
5045}
5046
5047static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
5048 ArgStringList &CmdArgs) {
5049 unsigned RTOptionID = options::OPT__SLASH_MT;
5050
5051 if (Args.hasArg(options::OPT__SLASH_LDd))
5052 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5053 // but defining _DEBUG is sticky.
5054 RTOptionID = options::OPT__SLASH_MTd;
5055
5056 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5057 RTOptionID = A->getOption().getID();
5058
5059 if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
5060 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
5061 .Case("static", options::OPT__SLASH_MT)
5062 .Case("static_dbg", options::OPT__SLASH_MTd)
5063 .Case("dll", options::OPT__SLASH_MD)
5064 .Case("dll_dbg", options::OPT__SLASH_MDd)
5065 .Default(options::OPT__SLASH_MT);
5066 }
5067
5068 StringRef FlagForCRT;
5069 switch (RTOptionID) {
5070 case options::OPT__SLASH_MD:
5071 if (Args.hasArg(options::OPT__SLASH_LDd))
5072 CmdArgs.push_back("-D_DEBUG");
5073 CmdArgs.push_back("-D_MT");
5074 CmdArgs.push_back("-D_DLL");
5075 FlagForCRT = "--dependent-lib=msvcrt";
5076 break;
5077 case options::OPT__SLASH_MDd:
5078 CmdArgs.push_back("-D_DEBUG");
5079 CmdArgs.push_back("-D_MT");
5080 CmdArgs.push_back("-D_DLL");
5081 FlagForCRT = "--dependent-lib=msvcrtd";
5082 break;
5083 case options::OPT__SLASH_MT:
5084 if (Args.hasArg(options::OPT__SLASH_LDd))
5085 CmdArgs.push_back("-D_DEBUG");
5086 CmdArgs.push_back("-D_MT");
5087 CmdArgs.push_back("-flto-visibility-public-std");
5088 FlagForCRT = "--dependent-lib=libcmt";
5089 break;
5090 case options::OPT__SLASH_MTd:
5091 CmdArgs.push_back("-D_DEBUG");
5092 CmdArgs.push_back("-D_MT");
5093 CmdArgs.push_back("-flto-visibility-public-std");
5094 FlagForCRT = "--dependent-lib=libcmtd";
5095 break;
5096 default:
5097 llvm_unreachable("Unexpected option ID.");
5098 }
5099
5100 if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
5101 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5102 } else {
5103 CmdArgs.push_back(FlagForCRT.data());
5104
5105 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5106 // users want. The /Za flag to cl.exe turns this off, but it's not
5107 // implemented in clang.
5108 CmdArgs.push_back("--dependent-lib=oldnames");
5109 }
5110
5111 // SYCL: Add SYCL runtime library dependency
5112 // SYCL runtime is a required dependency similar to CRT, so we use
5113 // --dependent-lib to embed it in the object file metadata
5114 if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false) &&
5115 !Args.hasArg(options::OPT_nolibsycl) &&
5116 !Args.hasArg(options::OPT_fms_omit_default_lib)) {
5117
5118 // Determine debug vs release based on CRT flags
5119 bool IsDebugBuild = false;
5120
5121 // Check -fms-runtime-lib=dll_dbg
5122 if (const Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
5123 StringRef RuntimeVal = A->getValue();
5124 if (RuntimeVal == "dll_dbg")
5125 IsDebugBuild = true;
5126 }
5127
5128 // Check for /MDd flag (dynamic debug CRT), use getLastArg to handle
5129 // overriding options (e.g., /MDd /MD -> /MD wins)
5130 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group)) {
5131 if (A->getOption().matches(options::OPT__SLASH_MDd))
5132 IsDebugBuild = true;
5133 }
5134
5135 // Add appropriate SYCL runtime library dependency
5136 CmdArgs.push_back(IsDebugBuild ? "--dependent-lib=LLVMSYCLd"
5137 : "--dependent-lib=LLVMSYCL");
5138 }
5139
5140 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
5141 // even if the file doesn't actually refer to any of the routines because
5142 // the CRT itself has incomplete dependency markings.
5143 if (TC.getTriple().isWindowsArm64EC())
5144 CmdArgs.push_back("--dependent-lib=softintrin");
5145}
5146
5148 const InputInfo &Output, const InputInfoList &Inputs,
5149 const ArgList &Args, const char *LinkingOutput) const {
5150 const auto &TC = getToolChain();
5151 const llvm::Triple &RawTriple = TC.getTriple();
5152 const llvm::Triple &Triple = TC.getEffectiveTriple();
5153 const std::string &TripleStr = Triple.getTriple();
5154
5155 bool KernelOrKext =
5156 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
5157 const Driver &D = TC.getDriver();
5158 ArgStringList CmdArgs;
5159
5160 assert(Inputs.size() >= 1 && "Must have at least one input.");
5161 // CUDA/HIP compilation may have multiple inputs (source file + results of
5162 // device-side compilations). OpenMP device jobs also take the host IR as a
5163 // second input. Module precompilation accepts a list of header files to
5164 // include as part of the module. API extraction accepts a list of header
5165 // files whose API information is emitted in the output. All other jobs are
5166 // expected to have exactly one input. SYCL compilation only expects a
5167 // single input.
5168 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
5169 bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
5170 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
5171 bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
5172 bool IsSYCL = JA.isOffloading(Action::OFK_SYCL);
5173 bool IsSYCLDevice = JA.isDeviceOffloading(Action::OFK_SYCL);
5174 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
5175 bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
5176 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
5178 bool IsHostOffloadingAction =
5181 (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
5182 Args.hasFlag(options::OPT_offload_new_driver,
5183 options::OPT_no_offload_new_driver,
5184 C.getActiveOffloadKinds() != Action::OFK_None));
5185
5186 bool IsRDCMode =
5187 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
5188
5189 auto LTOMode = TC.getLTOMode(Args, JA.getOffloadingDeviceKind());
5190 bool IsUsingLTO = LTOMode != LTOK_None;
5191
5192 // Extract API doesn't have a main input file, so invent a fake one as a
5193 // placeholder.
5194 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
5195 "extract-api");
5196
5197 const InputInfo &Input =
5198 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
5199
5200 InputInfoList ExtractAPIInputs;
5201 InputInfoList HostOffloadingInputs;
5202 const InputInfo *CudaDeviceInput = nullptr;
5203 const InputInfo *OpenMPDeviceInput = nullptr;
5204 for (const InputInfo &I : Inputs) {
5205 if (&I == &Input || I.getType() == types::TY_Nothing) {
5206 // This is the primary input or contains nothing.
5207 } else if (IsExtractAPI) {
5208 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
5209 if (I.getType() != ExpectedInputType) {
5210 D.Diag(diag::err_drv_extract_api_wrong_kind)
5211 << I.getFilename() << types::getTypeName(I.getType())
5212 << types::getTypeName(ExpectedInputType);
5213 }
5214 ExtractAPIInputs.push_back(I);
5215 } else if (IsHostOffloadingAction) {
5216 HostOffloadingInputs.push_back(I);
5217 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
5218 CudaDeviceInput = &I;
5219 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
5220 OpenMPDeviceInput = &I;
5221 } else {
5222 llvm_unreachable("unexpectedly given multiple inputs");
5223 }
5224 }
5225
5226 bool IsUEFI = RawTriple.isUEFI();
5227 bool IsIAMCU = RawTriple.isOSIAMCU();
5228
5229 // C++ is not supported for IAMCU.
5230 if (IsIAMCU && types::isCXX(Input.getType()))
5231 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
5232
5233 // Invoke ourselves in -cc1 mode.
5234 //
5235 // FIXME: Implement custom jobs for internal actions.
5236 CmdArgs.push_back("-cc1");
5237
5238 // Add the "effective" target triple.
5239 CmdArgs.push_back("-triple");
5240 CmdArgs.push_back(Args.MakeArgStringRef(TripleStr));
5241
5242 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
5243
5244 const llvm::Triple *AuxTriple = TC.getAuxTriple();
5245 if (AuxTriple) {
5246 CmdArgs.push_back("-aux-triple");
5247 CmdArgs.push_back(Args.MakeArgStringRef(AuxTriple->str()));
5248
5249 // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations. Even when compiling
5250 // in device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
5251 // Windows), we need to pass Windows-specific flags to cc1.
5252 IsWindowsMSVC |= AuxTriple->isWindowsMSVCEnvironment();
5254 // Figure out the device side triple for the host-side compilation.
5255 for (unsigned I = Action::OFK_DeviceFirst; I <= Action::OFK_DeviceLast;
5256 ++I) {
5258 C.getOffloadToolChains(static_cast<Action::OffloadKind>(I));
5259 if (OffloadToolChains.first == OffloadToolChains.second)
5260 continue;
5261
5262 const llvm::Triple &DeviceAuxTriple =
5263 OffloadToolChains.first->second->getTriple();
5264 CmdArgs.push_back("-aux-triple");
5265 CmdArgs.push_back(Args.MakeArgStringRef(DeviceAuxTriple.str()));
5266 break;
5267 }
5268 }
5269
5270 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
5271 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
5272 Args.ClaimAllArgs(options::OPT_MJ);
5273 } else if (const Arg *GenCDBFragment =
5274 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
5275 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
5276 TripleStr, Output, Input, Args);
5277 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
5278 }
5279
5280 if ((getToolChain().getTriple().isAMDGPU() ||
5281 (getToolChain().getTriple().isSPIRV() &&
5282 getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
5283 // Device side compilation printf
5284 if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
5285 CmdArgs.push_back(Args.MakeArgString(
5286 "-mprintf-kind=" +
5287 Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
5288 // Force compiler error on invalid conversion specifiers
5289 CmdArgs.push_back(
5290 Args.MakeArgStringRef("-Werror=format-invalid-specifier"));
5291 }
5292 }
5293
5294 if (IsCuda && !IsCudaDevice) {
5295 // We need to figure out which CUDA version we're compiling for, as that
5296 // determines how we load and launch GPU kernels.
5297 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
5298 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
5299 assert(CTC && "Expected valid CUDA Toolchain.");
5300 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
5301 CmdArgs.push_back(Args.MakeArgString(
5302 Twine("-target-sdk-version=") +
5303 CudaVersionToString(CTC->CudaInstallation.version())));
5304 }
5305
5306 // Optimization level for CodeGen.
5307 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5308 if (A->getOption().matches(options::OPT_O4)) {
5309 CmdArgs.push_back("-O3");
5310 D.Diag(diag::warn_O4_is_O3);
5311 } else {
5312 A->render(Args, CmdArgs);
5313 }
5314 }
5315
5316 // Unconditionally claim the printf option now to avoid unused diagnostic.
5317 if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
5318 PF->claim();
5319
5320 if (IsSYCL) {
5321 if (IsSYCLDevice) {
5322 // We want to compile sycl kernels.
5323 CmdArgs.push_back("-fsycl-is-device");
5324
5325 // Set O2 optimization level by default
5326 if (!Args.getLastArg(options::OPT_O_Group))
5327 CmdArgs.push_back("-O2");
5328 } else {
5329 // Add any options that are needed specific to SYCL offload while
5330 // performing the host side compilation.
5331
5332 // Let the front-end host compilation flow know about SYCL offload
5333 // compilation.
5334 CmdArgs.push_back("-fsycl-is-host");
5335 }
5336
5337 // Set options for both host and device.
5338 Arg *SYCLStdArg = Args.getLastArg(options::OPT_sycl_std_EQ);
5339 if (SYCLStdArg) {
5340 SYCLStdArg->render(Args, CmdArgs);
5341 } else {
5342 // Ensure the default version in SYCL mode is 2020.
5343 CmdArgs.push_back("-sycl-std=2020");
5344 }
5345 }
5346
5347 if (Args.hasArg(options::OPT_fclangir))
5348 CmdArgs.push_back("-fclangir");
5349
5350 if (IsOpenMPDevice) {
5351 // We have to pass the triple of the host if compiling for an OpenMP device.
5352 const llvm::Triple &HostTriple =
5353 C.getSingleOffloadToolChain<Action::OFK_Host>()->getTriple();
5354 CmdArgs.push_back("-aux-triple");
5355 CmdArgs.push_back(HostTriple.str().c_str());
5356 }
5357
5358 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5359 Triple.getArch() == llvm::Triple::thumb)) {
5360 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5361 unsigned Version = 0;
5362 bool Failure =
5363 Triple.getArchName().substr(Offset).consumeInteger(10, Version);
5364 if (Failure || Version < 7)
5365 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
5366 << TripleStr;
5367 }
5368
5369 // Push all default warning arguments that are specific to
5370 // the given target. These come before user provided warning options
5371 // are provided.
5372 TC.addClangWarningOptions(CmdArgs);
5373
5374 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5375 if (Triple.isSPIR() || Triple.isSPIRV())
5376 CmdArgs.push_back("-Wspir-compat");
5377
5378 // Select the appropriate action.
5379 RewriteKind rewriteKind = RK_None;
5380
5381 bool UnifiedLTO = false;
5382 if (IsUsingLTO) {
5383 UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
5384 options::OPT_fno_unified_lto, Triple.isPS());
5385 if (UnifiedLTO)
5386 CmdArgs.push_back("-funified-lto");
5387 }
5388
5389 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5390 // it claims when not running an assembler. Otherwise, clang would emit
5391 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5392 // flags while debugging something. That'd be somewhat inconvenient, and it's
5393 // also inconsistent with most other flags -- we don't warn on
5394 // -ffunction-sections not being used in -E mode either for example, even
5395 // though it's not really used either.
5396 if (!isa<AssembleJobAction>(JA)) {
5397 // The args claimed here should match the args used in
5398 // CollectArgsForIntegratedAssembler().
5399 if (TC.useIntegratedAs()) {
5400 Args.ClaimAllArgs(options::OPT_mrelax_all);
5401 Args.ClaimAllArgs(options::OPT_mno_relax_all);
5402 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
5403 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
5404 switch (C.getDefaultToolChain().getArch()) {
5405 case llvm::Triple::arm:
5406 case llvm::Triple::armeb:
5407 case llvm::Triple::thumb:
5408 case llvm::Triple::thumbeb:
5409 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
5410 break;
5411 default:
5412 break;
5413 }
5414 }
5415 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
5416 Args.ClaimAllArgs(options::OPT_Xassembler);
5417 Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
5418 }
5419
5420 bool IsAMDSPIRVForHIPDevice =
5421 IsHIPDevice && getToolChain().getTriple().isSPIRV() &&
5422 getToolChain().getTriple().getVendor() == llvm::Triple::AMD;
5423
5424 if (isa<AnalyzeJobAction>(JA)) {
5425 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5426 CmdArgs.push_back("-analyze");
5427 } else if (isa<PreprocessJobAction>(JA)) {
5428 if (Output.getType() == types::TY_Dependencies)
5429 CmdArgs.push_back("-Eonly");
5430 else {
5431 CmdArgs.push_back("-E");
5432 if (Args.hasArg(options::OPT_rewrite_objc) &&
5433 !Args.hasArg(options::OPT_g_Group))
5434 CmdArgs.push_back("-P");
5435 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5436 CmdArgs.push_back("-fdirectives-only");
5437 }
5438 } else if (isa<AssembleJobAction>(JA)) {
5439 CmdArgs.push_back("-emit-obj");
5440
5441 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5442
5443 // Also ignore explicit -force_cpusubtype_ALL option.
5444 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5445 } else if (isa<PrecompileJobAction>(JA)) {
5446 if (JA.getType() == types::TY_Nothing)
5447 CmdArgs.push_back("-fsyntax-only");
5448 else if (JA.getType() == types::TY_ModuleFile) {
5449 if (Args.hasArg(options::OPT__precompile_reduced_bmi) ||
5450 ((Input.getType() == types::TY_CXXStdModule ||
5451 Input.getType() == types::TY_PP_CXXStdModule) &&
5452 !Args.hasArg(options::OPT_fno_modules_reduced_bmi)))
5453 CmdArgs.push_back("-emit-reduced-module-interface");
5454 else
5455 CmdArgs.push_back("-emit-module-interface");
5456 } else if (JA.getType() == types::TY_HeaderUnit)
5457 CmdArgs.push_back("-emit-header-unit");
5458 else if (!Args.hasArg(options::OPT_ignore_pch))
5459 CmdArgs.push_back("-emit-pch");
5460 } else if (isa<VerifyPCHJobAction>(JA)) {
5461 CmdArgs.push_back("-verify-pch");
5462 } else if (isa<ExtractAPIJobAction>(JA)) {
5463 assert(JA.getType() == types::TY_API_INFO &&
5464 "Extract API actions must generate a API information.");
5465 CmdArgs.push_back("-extract-api");
5466
5467 if (Arg *PrettySGFArg = Args.getLastArg(options::OPT_emit_pretty_sgf))
5468 PrettySGFArg->render(Args, CmdArgs);
5469
5470 Arg *SymbolGraphDirArg = Args.getLastArg(options::OPT_symbol_graph_dir_EQ);
5471
5472 if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
5473 ProductNameArg->render(Args, CmdArgs);
5474 if (Arg *ExtractAPIIgnoresFileArg =
5475 Args.getLastArg(options::OPT_extract_api_ignores_EQ))
5476 ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
5477 if (Arg *EmitExtensionSymbolGraphs =
5478 Args.getLastArg(options::OPT_emit_extension_symbol_graphs)) {
5479 if (!SymbolGraphDirArg)
5480 D.Diag(diag::err_drv_missing_symbol_graph_dir);
5481
5482 EmitExtensionSymbolGraphs->render(Args, CmdArgs);
5483 }
5484 if (SymbolGraphDirArg)
5485 SymbolGraphDirArg->render(Args, CmdArgs);
5486 } else {
5487 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5488 "Invalid action for clang tool.");
5489 if (JA.getType() == types::TY_Nothing) {
5490 CmdArgs.push_back("-fsyntax-only");
5491 } else if (JA.getType() == types::TY_LLVM_IR ||
5492 JA.getType() == types::TY_LTO_IR) {
5493 CmdArgs.push_back("-emit-llvm");
5494 } else if (JA.getType() == types::TY_LLVM_BC ||
5495 JA.getType() == types::TY_LTO_BC) {
5496 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5497 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
5498 Args.hasArg(options::OPT_emit_llvm)) {
5499 CmdArgs.push_back("-emit-llvm");
5500 } else {
5501 CmdArgs.push_back("-emit-llvm-bc");
5502 }
5503 } else if (JA.getType() == types::TY_IFS ||
5504 JA.getType() == types::TY_IFS_CPP) {
5505 StringRef ArgStr =
5506 Args.hasArg(options::OPT_interface_stub_version_EQ)
5507 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
5508 : "ifs-v1";
5509 CmdArgs.push_back("-emit-interface-stubs");
5510 CmdArgs.push_back(
5511 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr));
5512 } else if (JA.getType() == types::TY_PP_Asm) {
5513 CmdArgs.push_back("-S");
5514 } else if (JA.getType() == types::TY_AST) {
5515 if (!Args.hasArg(options::OPT_ignore_pch))
5516 CmdArgs.push_back("-emit-pch");
5517 } else if (JA.getType() == types::TY_ModuleFile) {
5518 CmdArgs.push_back("-module-file-info");
5519 } else if (JA.getType() == types::TY_RewrittenObjC) {
5520 CmdArgs.push_back("-rewrite-objc");
5521 rewriteKind = RK_NonFragile;
5522 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5523 CmdArgs.push_back("-rewrite-objc");
5524 rewriteKind = RK_Fragile;
5525 } else if (JA.getType() == types::TY_CIR) {
5526 CmdArgs.push_back("-emit-cir");
5527 } else if (JA.getType() == types::TY_Image && IsAMDSPIRVForHIPDevice) {
5528 CmdArgs.push_back("-emit-obj");
5529 } else {
5530 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5531 }
5532
5533 // Preserve use-list order by default when emitting bitcode, so that
5534 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5535 // same result as running passes here. For LTO, we don't need to preserve
5536 // the use-list order, since serialization to bitcode is part of the flow.
5537 if (JA.getType() == types::TY_LLVM_BC)
5538 CmdArgs.push_back("-emit-llvm-uselists");
5539
5540 if (IsUsingLTO) {
5541 const Arg *LTOArg = Args.getLastArg(options::OPT_foffload_lto,
5542 options::OPT_foffload_lto_EQ);
5543 if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
5544 !Args.hasFlag(options::OPT_offload_new_driver,
5545 options::OPT_no_offload_new_driver,
5546 C.getActiveOffloadKinds() != Action::OFK_None) &&
5547 !Triple.isAMDGPU() && !Triple.isSPIRV()) {
5548 D.Diag(diag::err_drv_unsupported_opt_for_target)
5549 << (LTOArg ? LTOArg->getAsString(Args) : "-foffload-lto")
5550 << Triple.getTriple();
5551 } else if (Triple.isNVPTX() && !IsRDCMode &&
5553 D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
5554 << (LTOArg ? LTOArg->getAsString(Args) : "-foffload-lto")
5555 << "-fno-gpu-rdc";
5556 } else {
5557 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5558 CmdArgs.push_back(Args.MakeArgString(
5559 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5560 // PS4 uses the legacy LTO API, which does not support some of the
5561 // features enabled by -flto-unit.
5562 if (!RawTriple.isPS4() || (LTOMode == LTOK_Full) || !UnifiedLTO)
5563 CmdArgs.push_back("-flto-unit");
5564 }
5565 }
5566 }
5567
5568 Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
5569
5570 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
5571 if (!types::isLLVMIR(Input.getType()))
5572 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5573 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
5574 }
5575
5576 if (Triple.isPPC())
5577 Args.addOptInFlag(CmdArgs, options::OPT_mregnames,
5578 options::OPT_mno_regnames);
5579
5580 if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
5581 Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
5582
5583 if (Args.getLastArg(options::OPT_save_temps_EQ))
5584 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
5585
5586 auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
5587 options::OPT_fmemory_profile_EQ,
5588 options::OPT_fno_memory_profile);
5589 if (MemProfArg &&
5590 !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
5591 MemProfArg->render(Args, CmdArgs);
5592
5593 if (auto *MemProfUseArg =
5594 Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
5595 if (MemProfArg)
5596 D.Diag(diag::err_drv_argument_not_allowed_with)
5597 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5598 if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
5599 options::OPT_fprofile_generate_EQ))
5600 D.Diag(diag::err_drv_argument_not_allowed_with)
5601 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5602 MemProfUseArg->render(Args, CmdArgs);
5603 }
5604
5605 // Embed-bitcode option.
5606 // Only white-listed flags below are allowed to be embedded.
5607 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5609 // Add flags implied by -fembed-bitcode.
5610 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
5611 // Disable all llvm IR level optimizations.
5612 CmdArgs.push_back("-disable-llvm-passes");
5613
5614 // Render target options.
5615 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingArch(),
5617
5618 // reject options that shouldn't be supported in bitcode
5619 // also reject kernel/kext
5620 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5621 options::OPT_mkernel,
5622 options::OPT_fapple_kext,
5623 options::OPT_ffunction_sections,
5624 options::OPT_fno_function_sections,
5625 options::OPT_fdata_sections,
5626 options::OPT_fno_data_sections,
5627 options::OPT_fbasic_block_sections_EQ,
5628 options::OPT_funique_internal_linkage_names,
5629 options::OPT_fno_unique_internal_linkage_names,
5630 options::OPT_funique_section_names,
5631 options::OPT_fno_unique_section_names,
5632 options::OPT_funique_basic_block_section_names,
5633 options::OPT_fno_unique_basic_block_section_names,
5634 options::OPT_mrestrict_it,
5635 options::OPT_mno_restrict_it,
5636 options::OPT_mstackrealign,
5637 options::OPT_mno_stackrealign,
5638 options::OPT_mstack_alignment,
5639 options::OPT_mcmodel_EQ,
5640 options::OPT_mlong_calls,
5641 options::OPT_mno_long_calls,
5642 options::OPT_ggnu_pubnames,
5643 options::OPT_gdwarf_aranges,
5644 options::OPT_fdebug_types_section,
5645 options::OPT_fno_debug_types_section,
5646 options::OPT_fdwarf_directory_asm,
5647 options::OPT_fno_dwarf_directory_asm,
5648 options::OPT_mrelax_all,
5649 options::OPT_mno_relax_all,
5650 options::OPT_ftrap_function_EQ,
5651 options::OPT_ffixed_r9,
5652 options::OPT_mfix_cortex_a53_835769,
5653 options::OPT_mno_fix_cortex_a53_835769,
5654 options::OPT_ffixed_x18,
5655 options::OPT_mglobal_merge,
5656 options::OPT_mno_global_merge,
5657 options::OPT_mred_zone,
5658 options::OPT_mno_red_zone,
5659 options::OPT_Wa_COMMA,
5660 options::OPT_Xassembler,
5661 options::OPT_mllvm,
5662 options::OPT_mmlir,
5663 };
5664 for (const auto &A : Args)
5665 if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
5666 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5667
5668 // Render the CodeGen options that need to be passed.
5669 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5670 options::OPT_fno_optimize_sibling_calls);
5671
5673 CmdArgs, JA);
5674
5675 // Render ABI arguments
5676 switch (TC.getArch()) {
5677 default: break;
5678 case llvm::Triple::arm:
5679 case llvm::Triple::armeb:
5680 case llvm::Triple::thumbeb:
5681 RenderARMABI(D, Triple, Args, CmdArgs);
5682 break;
5683 case llvm::Triple::aarch64:
5684 case llvm::Triple::aarch64_32:
5685 case llvm::Triple::aarch64_be:
5686 RenderAArch64ABI(Triple, Args, CmdArgs);
5687 break;
5688 }
5689
5690 // Input/Output file.
5691 if (Output.getType() == types::TY_Dependencies) {
5692 // Handled with other dependency code.
5693 } else if (Output.isFilename()) {
5694 CmdArgs.push_back("-o");
5695 CmdArgs.push_back(Output.getFilename());
5696 } else {
5697 assert(Output.isNothing() && "Input output.");
5698 }
5699
5700 for (const auto &II : Inputs) {
5701 addDashXForInput(Args, II, CmdArgs);
5702 if (II.isFilename())
5703 CmdArgs.push_back(II.getFilename());
5704 else
5705 II.getInputArg().renderAsInput(Args, CmdArgs);
5706 }
5707
5708 C.addCommand(std::make_unique<Command>(
5710 CmdArgs, Inputs, Output, D.getPrependArg()));
5711 return;
5712 }
5713
5714 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5715 CmdArgs.push_back("-fembed-bitcode=marker");
5716
5717 // We normally speed up the clang process a bit by skipping destructors at
5718 // exit, but when we're generating diagnostics we can rely on some of the
5719 // cleanup.
5720 if (!C.isForDiagnostics())
5721 CmdArgs.push_back("-disable-free");
5722 CmdArgs.push_back("-clear-ast-before-backend");
5723
5724#ifdef NDEBUG
5725 const bool IsAssertBuild = false;
5726#else
5727 const bool IsAssertBuild = true;
5728#endif
5729
5730 // Disable the verification pass in no-asserts builds unless otherwise
5731 // specified.
5732 if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
5733 options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
5734 CmdArgs.push_back("-disable-llvm-verifier");
5735 }
5736
5737 // Discard value names in no-asserts builds unless otherwise specified.
5738 if (Args.hasFlag(options::OPT_fdiscard_value_names,
5739 options::OPT_fno_discard_value_names, !IsAssertBuild)) {
5740 if (Args.hasArg(options::OPT_fdiscard_value_names) &&
5741 llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
5742 return types::isLLVMIR(II.getType());
5743 })) {
5744 D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
5745 }
5746 CmdArgs.push_back("-discard-value-names");
5747 }
5748
5749 // Set the main file name, so that debug info works even with
5750 // -save-temps.
5751 CmdArgs.push_back("-main-file-name");
5752 CmdArgs.push_back(getBaseInputName(Args, Input));
5753
5754 // Some flags which affect the language (via preprocessor
5755 // defines).
5756 if (Args.hasArg(options::OPT_static))
5757 CmdArgs.push_back("-static-define");
5758
5759 Args.AddLastArg(CmdArgs, options::OPT_static_libclosure);
5760
5761 if (Args.hasArg(options::OPT_municode))
5762 CmdArgs.push_back("-DUNICODE");
5763
5764 if (isa<AnalyzeJobAction>(JA))
5765 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5766
5767 if (isa<AnalyzeJobAction>(JA) ||
5768 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5769 CmdArgs.push_back("-setup-static-analyzer");
5770
5771 // Enable compatilibily mode to avoid analyzer-config related errors.
5772 // Since we can't access frontend flags through hasArg, let's manually iterate
5773 // through them.
5774 bool FoundAnalyzerConfig = false;
5775 for (auto *Arg : Args.filtered(options::OPT_Xclang))
5776 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5777 FoundAnalyzerConfig = true;
5778 break;
5779 }
5780 if (!FoundAnalyzerConfig)
5781 for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5782 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5783 FoundAnalyzerConfig = true;
5784 break;
5785 }
5786 if (FoundAnalyzerConfig)
5787 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
5788
5790
5791 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5792 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5793 if (FunctionAlignment) {
5794 CmdArgs.push_back("-function-alignment");
5795 CmdArgs.push_back(Args.MakeArgString(Twine(FunctionAlignment)));
5796 }
5797
5798 if (const Arg *A =
5799 Args.getLastArg(options::OPT_fpreferred_function_alignment_EQ)) {
5800 unsigned Value = 0;
5801 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5802 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5803 << A->getAsString(Args) << A->getValue();
5804 else if (!llvm::isPowerOf2_32(Value))
5805 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5806 << A->getAsString(Args) << A->getValue();
5807
5808 CmdArgs.push_back(Args.MakeArgString("-fpreferred-function-alignment=" +
5809 Twine(std::min(Value, 65536u))));
5810 }
5811
5812 // We support -falign-loops=N where N is a power of 2. GCC supports more
5813 // forms.
5814 if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5815 unsigned Value = 0;
5816 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5817 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5818 << A->getAsString(Args) << A->getValue();
5819 else if (Value & (Value - 1))
5820 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5821 << A->getAsString(Args) << A->getValue();
5822 // Treat =0 as unspecified (use the target preference).
5823 if (Value)
5824 CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5825 Twine(std::min(Value, 65536u))));
5826 }
5827
5828 if (Triple.isOSzOS()) {
5829 // On z/OS some of the system header feature macros need to
5830 // be defined to enable most cross platform projects to build
5831 // successfully. Ths include the libc++ library. A
5832 // complicating factor is that users can define these
5833 // macros to the same or different values. We need to add
5834 // the definition for these macros to the compilation command
5835 // if the user hasn't already defined them.
5836
5837 auto findMacroDefinition = [&](const std::string &Macro) {
5838 auto MacroDefs = Args.getAllArgValues(options::OPT_D);
5839 return llvm::any_of(MacroDefs, [&](const std::string &M) {
5840 return M == Macro || M.find(Macro + '=') != std::string::npos;
5841 });
5842 };
5843
5844 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5845 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5846 CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
5847 // _OPEN_DEFAULT is required for XL compat
5848 if (!findMacroDefinition("_OPEN_DEFAULT"))
5849 CmdArgs.push_back("-D_OPEN_DEFAULT");
5850 if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
5851 // _XOPEN_SOURCE=600 is required for libcxx.
5852 if (!findMacroDefinition("_XOPEN_SOURCE"))
5853 CmdArgs.push_back("-D_XOPEN_SOURCE=600");
5854 }
5855 }
5856
5857 llvm::Reloc::Model RelocationModel;
5858 unsigned PICLevel;
5859 bool IsPIE;
5860 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5861 Arg *LastPICDataRelArg =
5862 Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5863 options::OPT_mpic_data_is_text_relative);
5864 bool NoPICDataIsTextRelative = false;
5865 if (LastPICDataRelArg) {
5866 if (LastPICDataRelArg->getOption().matches(
5867 options::OPT_mno_pic_data_is_text_relative)) {
5868 NoPICDataIsTextRelative = true;
5869 if (!PICLevel)
5870 D.Diag(diag::err_drv_argument_only_allowed_with)
5871 << "-mno-pic-data-is-text-relative"
5872 << "-fpic/-fpie";
5873 }
5874 if (!Triple.isSystemZ())
5875 D.Diag(diag::err_drv_unsupported_opt_for_target)
5876 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5877 : "-mpic-data-is-text-relative")
5878 << RawTriple.str();
5879 }
5880
5881 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5882 RelocationModel == llvm::Reloc::ROPI_RWPI;
5883 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5884 RelocationModel == llvm::Reloc::ROPI_RWPI;
5885
5886 if (Args.hasArg(options::OPT_mcmse) &&
5887 !Args.hasArg(options::OPT_fallow_unsupported)) {
5888 if (IsROPI)
5889 D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
5890 if (IsRWPI)
5891 D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5892 }
5893
5894 if (IsROPI && types::isCXX(Input.getType()) &&
5895 !Args.hasArg(options::OPT_fallow_unsupported))
5896 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
5897
5898 const char *RMName = RelocationModelName(RelocationModel);
5899 if (RMName) {
5900 CmdArgs.push_back("-mrelocation-model");
5901 CmdArgs.push_back(RMName);
5902 }
5903 if (PICLevel > 0) {
5904 CmdArgs.push_back("-pic-level");
5905 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
5906 if (IsPIE)
5907 CmdArgs.push_back("-pic-is-pie");
5908 if (NoPICDataIsTextRelative)
5909 CmdArgs.push_back("-mcmodel=medium");
5910 }
5911
5912 if (RelocationModel == llvm::Reloc::ROPI ||
5913 RelocationModel == llvm::Reloc::ROPI_RWPI)
5914 CmdArgs.push_back("-fropi");
5915 if (RelocationModel == llvm::Reloc::RWPI ||
5916 RelocationModel == llvm::Reloc::ROPI_RWPI)
5917 CmdArgs.push_back("-frwpi");
5918
5919 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
5920 CmdArgs.push_back("-meabi");
5921 CmdArgs.push_back(A->getValue());
5922 }
5923
5924 // -fsemantic-interposition is forwarded to CC1: set the
5925 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5926 // make default visibility external linkage definitions dso_preemptable.
5927 //
5928 // -fno-semantic-interposition: if the target supports .Lfoo$local local
5929 // aliases (make default visibility external linkage definitions dso_local).
5930 // This is the CC1 default for ELF to match COFF/Mach-O.
5931 //
5932 // Otherwise use Clang's traditional behavior: like
5933 // -fno-semantic-interposition but local aliases are not used. So references
5934 // can be interposed if not optimized out.
5935 if (Triple.isOSBinFormatELF()) {
5936 Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
5937 options::OPT_fno_semantic_interposition);
5938 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5939 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5940 bool SupportsLocalAlias =
5941 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5942 if (!A)
5943 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5944 else if (A->getOption().matches(options::OPT_fsemantic_interposition))
5945 A->render(Args, CmdArgs);
5946 else if (!SupportsLocalAlias)
5947 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5948 }
5949 }
5950
5951 {
5952 std::string Model;
5953 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
5954 if (!TC.isThreadModelSupported(A->getValue()))
5955 D.Diag(diag::err_drv_invalid_thread_model_for_target)
5956 << A->getValue() << A->getAsString(Args);
5957 Model = A->getValue();
5958 } else
5959 Model = TC.getThreadModel();
5960 if (Model != "posix") {
5961 CmdArgs.push_back("-mthread-model");
5962 CmdArgs.push_back(Args.MakeArgString(Model));
5963 }
5964 }
5965
5966 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
5967 StringRef Name = A->getValue();
5968 if (Name == "SVML") {
5969 if (Triple.getArch() != llvm::Triple::x86 &&
5970 Triple.getArch() != llvm::Triple::x86_64)
5971 D.Diag(diag::err_drv_unsupported_opt_for_target)
5972 << Name << Triple.getArchName();
5973 } else if (Name == "AMDLIBM") {
5974 if (Triple.getArch() != llvm::Triple::x86 &&
5975 Triple.getArch() != llvm::Triple::x86_64)
5976 D.Diag(diag::err_drv_unsupported_opt_for_target)
5977 << Name << Triple.getArchName();
5978 } else if (Name == "libmvec") {
5979 if (Triple.getArch() != llvm::Triple::x86 &&
5980 Triple.getArch() != llvm::Triple::x86_64 &&
5981 Triple.getArch() != llvm::Triple::aarch64 &&
5982 Triple.getArch() != llvm::Triple::aarch64_be)
5983 D.Diag(diag::err_drv_unsupported_opt_for_target)
5984 << Name << Triple.getArchName();
5985 } else if (Name == "SLEEF" || Name == "ArmPL") {
5986 if (Triple.getArch() != llvm::Triple::aarch64 &&
5987 Triple.getArch() != llvm::Triple::aarch64_be && !Triple.isRISCV64())
5988 D.Diag(diag::err_drv_unsupported_opt_for_target)
5989 << Name << Triple.getArchName();
5990 }
5991 A->render(Args, CmdArgs);
5992 }
5993
5994 if (Args.hasFlag(options::OPT_fmerge_all_constants,
5995 options::OPT_fno_merge_all_constants, false))
5996 CmdArgs.push_back("-fmerge-all-constants");
5997
5998 Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
5999 options::OPT_fno_delete_null_pointer_checks);
6000
6001 Args.addOptOutFlag(CmdArgs, options::OPT_flifetime_dse,
6002 options::OPT_fno_lifetime_dse);
6003
6004 // LLVM Code Generator Options.
6005
6006 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
6007 if (!Triple.isOSAIX() || Triple.isPPC32())
6008 D.Diag(diag::err_drv_unsupported_opt_for_target)
6009 << A->getSpelling() << RawTriple.str();
6010 CmdArgs.push_back("-mabi=quadword-atomics");
6011 }
6012
6013 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
6014 // Emit the unsupported option error until the Clang's library integration
6015 // support for 128-bit long double is available for AIX.
6016 if (Triple.isOSAIX())
6017 D.Diag(diag::err_drv_unsupported_opt_for_target)
6018 << A->getSpelling() << RawTriple.str();
6019 }
6020
6021 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
6022 StringRef V = A->getValue(), V1 = V;
6023 unsigned Size;
6024 if (V1.consumeInteger(10, Size) || !V1.empty())
6025 D.Diag(diag::err_drv_invalid_argument_to_option)
6026 << V << A->getOption().getName();
6027 else
6028 CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
6029 }
6030
6031 Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
6032 options::OPT_fno_jump_tables);
6033 Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
6034 options::OPT_fno_profile_sample_accurate);
6035 Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
6036 options::OPT_fno_preserve_as_comments);
6037
6038 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
6039 CmdArgs.push_back("-mregparm");
6040 CmdArgs.push_back(A->getValue());
6041 }
6042
6043 if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
6044 options::OPT_msvr4_struct_return)) {
6045 if (!TC.getTriple().isPPC32()) {
6046 D.Diag(diag::err_drv_unsupported_opt_for_target)
6047 << A->getSpelling() << RawTriple.str();
6048 } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
6049 CmdArgs.push_back("-maix-struct-return");
6050 } else {
6051 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
6052 CmdArgs.push_back("-msvr4-struct-return");
6053 }
6054 }
6055
6056 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
6057 options::OPT_freg_struct_return)) {
6058 if (TC.getArch() != llvm::Triple::x86) {
6059 D.Diag(diag::err_drv_unsupported_opt_for_target)
6060 << A->getSpelling() << RawTriple.str();
6061 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
6062 CmdArgs.push_back("-fpcc-struct-return");
6063 } else {
6064 assert(A->getOption().matches(options::OPT_freg_struct_return));
6065 CmdArgs.push_back("-freg-struct-return");
6066 }
6067 }
6068
6069 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {
6070 if (Triple.getArch() == llvm::Triple::m68k)
6071 CmdArgs.push_back("-fdefault-calling-conv=rtdcall");
6072 else
6073 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
6074 }
6075
6076 if (Args.hasArg(options::OPT_fenable_matrix)) {
6077 // enable-matrix is needed by both the LangOpts and by LLVM.
6078 CmdArgs.push_back("-fenable-matrix");
6079 CmdArgs.push_back("-mllvm");
6080 CmdArgs.push_back("-enable-matrix");
6081 // Only handle default layout if matrix is enabled
6082 if (const Arg *A = Args.getLastArg(options::OPT_fmatrix_memory_layout_EQ)) {
6083 StringRef Val = A->getValue();
6084 if (Val == "row-major" || Val == "column-major") {
6085 CmdArgs.push_back(Args.MakeArgString("-fmatrix-memory-layout=" + Val));
6086 CmdArgs.push_back("-mllvm");
6087 CmdArgs.push_back(Args.MakeArgString("-matrix-default-layout=" + Val));
6088
6089 } else {
6090 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
6091 }
6092 }
6093 }
6094
6096 getFramePointerKind(Args, RawTriple);
6097 const char *FPKeepKindStr = nullptr;
6098 switch (FPKeepKind) {
6100 FPKeepKindStr = "-mframe-pointer=none";
6101 break;
6103 FPKeepKindStr = "-mframe-pointer=reserved";
6104 break;
6106 FPKeepKindStr = "-mframe-pointer=non-leaf-no-reserve";
6107 break;
6109 FPKeepKindStr = "-mframe-pointer=non-leaf";
6110 break;
6112 FPKeepKindStr = "-mframe-pointer=all";
6113 break;
6114 }
6115 assert(FPKeepKindStr && "unknown FramePointerKind");
6116 CmdArgs.push_back(FPKeepKindStr);
6117
6118 Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
6119 options::OPT_fno_zero_initialized_in_bss);
6120
6121 bool OFastEnabled = isOptimizationLevelFast(Args);
6122 if (Args.hasArg(options::OPT_Ofast))
6123 D.Diag(diag::warn_drv_deprecated_arg_ofast);
6124 // If -Ofast is the optimization level, then -fstrict-aliasing should be
6125 // enabled. This alias option is being used to simplify the hasFlag logic.
6126 OptSpecifier StrictAliasingAliasOption =
6127 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
6128 // We turn strict aliasing off by default if we're Windows MSVC since MSVC
6129 // doesn't do any TBAA.
6130 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
6131 options::OPT_fno_strict_aliasing,
6132 !IsWindowsMSVC && !IsUEFI))
6133 CmdArgs.push_back("-relaxed-aliasing");
6134 if (Args.hasFlag(options::OPT_fno_pointer_tbaa, options::OPT_fpointer_tbaa,
6135 false))
6136 CmdArgs.push_back("-no-pointer-tbaa");
6137 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
6138 options::OPT_fno_struct_path_tbaa, true))
6139 CmdArgs.push_back("-no-struct-path-tbaa");
6140
6141 if (Arg *A = Args.getLastArg(options::OPT_fstrict_bool,
6142 options::OPT_fno_strict_bool,
6143 options::OPT_fno_strict_bool_EQ)) {
6144 StringRef BFM = "";
6145 if (A->getOption().matches(options::OPT_fstrict_bool))
6146 BFM = "strict";
6147 else if (A->getOption().matches(options::OPT_fno_strict_bool))
6148 BFM = "nonstrict";
6149 else if (A->getValue() == StringRef("truncate"))
6150 BFM = "truncate";
6151 else if (A->getValue() == StringRef("nonzero"))
6152 BFM = "nonzero";
6153 else
6154 D.Diag(diag::err_drv_invalid_value)
6155 << A->getAsString(Args) << A->getValue();
6156 CmdArgs.push_back(Args.MakeArgString("-load-bool-from-mem=" + BFM));
6157 } else if (KernelOrKext) {
6158 // If unspecified, assume -fno-strict-bool=truncate in the Darwin kernel.
6159 CmdArgs.push_back("-load-bool-from-mem=truncate");
6160 }
6161
6162 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
6163 options::OPT_fno_strict_enums);
6164 Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
6165 options::OPT_fno_strict_return);
6166 Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
6167 options::OPT_fno_allow_editor_placeholders);
6168 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
6169 options::OPT_fno_strict_vtable_pointers);
6170 Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
6171 options::OPT_fno_force_emit_vtables);
6172 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
6173 options::OPT_fno_optimize_sibling_calls);
6174 Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
6175 options::OPT_fno_escaping_block_tail_calls);
6176
6177 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
6178 options::OPT_fno_fine_grained_bitfield_accesses);
6179
6180 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6181 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6182
6183 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6184 options::OPT_fno_experimental_omit_vtable_rtti);
6185
6186 Args.AddLastArg(CmdArgs, options::OPT_fdisable_block_signature_string,
6187 options::OPT_fno_disable_block_signature_string);
6188
6189 // Handle segmented stacks.
6190 Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
6191 options::OPT_fno_split_stack);
6192
6193 // -fprotect-parens=0 is default.
6194 if (Args.hasFlag(options::OPT_fprotect_parens,
6195 options::OPT_fno_protect_parens, false))
6196 CmdArgs.push_back("-fprotect-parens");
6197
6198 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
6199
6200 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_remote_memory,
6201 options::OPT_fno_atomic_remote_memory);
6202 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_fine_grained_memory,
6203 options::OPT_fno_atomic_fine_grained_memory);
6204 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_ignore_denormal_mode,
6205 options::OPT_fno_atomic_ignore_denormal_mode);
6206
6207 if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
6208 const llvm::Triple::ArchType Arch = TC.getArch();
6209 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
6210 StringRef V = A->getValue();
6211 if (V == "64")
6212 CmdArgs.push_back("-fextend-arguments=64");
6213 else if (V != "32")
6214 D.Diag(diag::err_drv_invalid_argument_to_option)
6215 << A->getValue() << A->getOption().getName();
6216 } else
6217 D.Diag(diag::err_drv_unsupported_opt_for_target)
6218 << A->getOption().getName() << TripleStr;
6219 }
6220
6221 if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
6222 if (TC.getArch() == llvm::Triple::avr)
6223 A->render(Args, CmdArgs);
6224 else
6225 D.Diag(diag::err_drv_unsupported_opt_for_target)
6226 << A->getAsString(Args) << TripleStr;
6227 }
6228
6229 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
6230 if (TC.getTriple().isX86())
6231 A->render(Args, CmdArgs);
6232 else if (TC.getTriple().isPPC() &&
6233 (A->getOption().getID() != options::OPT_mlong_double_80))
6234 A->render(Args, CmdArgs);
6235 else
6236 D.Diag(diag::err_drv_unsupported_opt_for_target)
6237 << A->getAsString(Args) << TripleStr;
6238 }
6239
6240 // Decide whether to use verbose asm. Verbose assembly is the default on
6241 // toolchains which have the integrated assembler on by default.
6242 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
6243 if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
6244 IsIntegratedAssemblerDefault))
6245 CmdArgs.push_back("-fno-verbose-asm");
6246
6247 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
6248 // use that to indicate the MC default in the backend.
6249 if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
6250 StringRef V = A->getValue();
6251 unsigned Num;
6252 if (V == "none")
6253 A->render(Args, CmdArgs);
6254 else if (!V.consumeInteger(10, Num) && Num > 0 &&
6255 (V.empty() || (V.consume_front(".") &&
6256 !V.consumeInteger(10, Num) && V.empty())))
6257 A->render(Args, CmdArgs);
6258 else
6259 D.Diag(diag::err_drv_invalid_argument_to_option)
6260 << A->getValue() << A->getOption().getName();
6261 }
6262
6263 // If toolchain choose to use MCAsmParser for inline asm don't pass the
6264 // option to disable integrated-as explicitly.
6266 CmdArgs.push_back("-no-integrated-as");
6267
6268 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
6269 CmdArgs.push_back("-mdebug-pass");
6270 CmdArgs.push_back("Structure");
6271 }
6272 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
6273 CmdArgs.push_back("-mdebug-pass");
6274 CmdArgs.push_back("Arguments");
6275 }
6276
6277 // Enable -mconstructor-aliases except on darwin, where we have to work around
6278 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
6279 // code, where aliases aren't supported.
6280 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
6281 CmdArgs.push_back("-mconstructor-aliases");
6282
6283 // Darwin's kernel doesn't support guard variables; just die if we
6284 // try to use them.
6285 if (KernelOrKext && RawTriple.isOSDarwin())
6286 CmdArgs.push_back("-fforbid-guard-variables");
6287
6288 if (Arg *A = Args.getLastArg(options::OPT_mms_bitfields,
6289 options::OPT_mno_ms_bitfields)) {
6290 if (A->getOption().matches(options::OPT_mms_bitfields))
6291 CmdArgs.push_back("-fms-layout-compatibility=microsoft");
6292 else
6293 CmdArgs.push_back("-fms-layout-compatibility=itanium");
6294 }
6295
6296 if (Triple.isOSCygMing()) {
6297 Args.addOptOutFlag(CmdArgs, options::OPT_fauto_import,
6298 options::OPT_fno_auto_import);
6299 }
6300
6301 if (Args.hasFlag(options::OPT_fms_volatile, options::OPT_fno_ms_volatile,
6302 Triple.isX86() && IsWindowsMSVC))
6303 CmdArgs.push_back("-fms-volatile");
6304
6305 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
6306 // defaults to -fno-direct-access-external-data. Pass the option if different
6307 // from the default.
6308 if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
6309 options::OPT_fno_direct_access_external_data)) {
6310 if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
6311 (PICLevel == 0))
6312 A->render(Args, CmdArgs);
6313 } else if (PICLevel == 0 && Triple.isLoongArch()) {
6314 // Some targets default to -fno-direct-access-external-data even for
6315 // -fno-pic.
6316 CmdArgs.push_back("-fno-direct-access-external-data");
6317 }
6318
6319 if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))
6320 Args.addOptOutFlag(CmdArgs, options::OPT_fplt, options::OPT_fno_plt);
6321
6322 // -fhosted is default.
6323 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
6324 // use Freestanding.
6325 bool Freestanding =
6326 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
6327 KernelOrKext;
6328 if (Freestanding)
6329 CmdArgs.push_back("-ffreestanding");
6330
6331 Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
6332
6334 auto SanitizeArgs =
6336 Args.AddLastArg(CmdArgs,
6337 options::OPT_fallow_runtime_check_skip_hot_cutoff_EQ);
6338
6339 // This is a coarse approximation of what llvm-gcc actually does, both
6340 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
6341 // complicated ways.
6342 bool IsAsyncUnwindTablesDefault =
6344 bool IsSyncUnwindTablesDefault =
6346
6347 bool AsyncUnwindTables = Args.hasFlag(
6348 options::OPT_fasynchronous_unwind_tables,
6349 options::OPT_fno_asynchronous_unwind_tables,
6350 (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
6351 !Freestanding);
6352 bool UnwindTables =
6353 Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
6354 IsSyncUnwindTablesDefault && !Freestanding);
6355 if (AsyncUnwindTables)
6356 CmdArgs.push_back("-funwind-tables=2");
6357 else if (UnwindTables)
6358 CmdArgs.push_back("-funwind-tables=1");
6359
6360 // Sframe unwind tables are independent of the other types. Although also
6361 // defined for aarch64, only x86_64 support is implemented at the moment.
6362 if (Arg *A = Args.getLastArg(options::OPT_gsframe)) {
6363 if (Triple.isOSBinFormatELF() && Triple.isX86())
6364 CmdArgs.push_back("--gsframe");
6365 else
6366 D.Diag(diag::err_drv_unsupported_opt_for_target)
6367 << A->getOption().getName() << TripleStr;
6368 }
6369
6370 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
6371 // `--gpu-use-aux-triple-only` is specified.
6372 if (AuxTriple && !Args.getLastArg(options::OPT_gpu_use_aux_triple_only)) {
6373 const ArgList &HostArgs =
6374 C.getArgsForToolChain(nullptr, BoundArch(), Action::OFK_None);
6375 std::string HostCPU = getCPUName(D, HostArgs, *AuxTriple, /*FromAs*/ false);
6376 if (!HostCPU.empty()) {
6377 CmdArgs.push_back("-aux-target-cpu");
6378 CmdArgs.push_back(Args.MakeArgString(HostCPU));
6379 }
6380 getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
6381 /*ForAS*/ false, /*IsAux*/ true);
6382 }
6383
6384 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingArch(),
6386
6387 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
6388
6389 if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
6390 StringRef Value = A->getValue();
6391 unsigned TLSSize = 0;
6392 Value.getAsInteger(10, TLSSize);
6393 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6394 D.Diag(diag::err_drv_unsupported_opt_for_target)
6395 << A->getOption().getName() << TripleStr;
6396 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6397 D.Diag(diag::err_drv_invalid_int_value)
6398 << A->getOption().getName() << Value;
6399 Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
6400 }
6401
6402 if (isTLSDESCEnabled(TC, Args))
6403 CmdArgs.push_back("-enable-tlsdesc");
6404
6405 // Add the target cpu
6406 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
6407 if (!CPU.empty()) {
6408 CmdArgs.push_back("-target-cpu");
6409 CmdArgs.push_back(Args.MakeArgString(CPU));
6410 }
6411
6412 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
6413
6414 // Add clang-cl arguments.
6415 types::ID InputType = Input.getType();
6416 if (D.IsCLMode())
6417 AddClangCLArgs(Args, InputType, CmdArgs);
6418
6419 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
6420 llvm::codegenoptions::NoDebugInfo;
6422 renderDebugOptions(TC, D, RawTriple, Args, InputType, CmdArgs, Output,
6423 DebugInfoKind, DwarfFission);
6424
6425 // Add the split debug info name to the command lines here so we
6426 // can propagate it to the backend.
6427 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6428 (TC.getTriple().isOSBinFormatELF() ||
6429 TC.getTriple().isOSBinFormatWasm() ||
6430 TC.getTriple().isOSBinFormatCOFF()) &&
6433 if (SplitDWARF) {
6434 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
6435 CmdArgs.push_back("-split-dwarf-file");
6436 CmdArgs.push_back(SplitDWARFOut);
6437 if (DwarfFission == DwarfFissionKind::Split) {
6438 CmdArgs.push_back("-split-dwarf-output");
6439 CmdArgs.push_back(SplitDWARFOut);
6440 }
6441 }
6442
6443 // Pass the linker version in use.
6444 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6445 CmdArgs.push_back("-target-linker-version");
6446 CmdArgs.push_back(A->getValue());
6447 }
6448
6449 // Explicitly error on some things we know we don't support and can't just
6450 // ignore.
6451 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
6452 Arg *Unsupported;
6453 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
6454 TC.getArch() == llvm::Triple::x86) {
6455 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
6456 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
6457 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
6458 << Unsupported->getOption().getName();
6459 }
6460 // The faltivec option has been superseded by the maltivec option.
6461 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
6462 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6463 << Unsupported->getOption().getName()
6464 << "please use -maltivec and include altivec.h explicitly";
6465 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
6466 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6467 << Unsupported->getOption().getName() << "please use -mno-altivec";
6468 }
6469
6470 Args.AddAllArgs(CmdArgs, options::OPT_v);
6471
6472 if (Args.getLastArg(options::OPT_H)) {
6473 CmdArgs.push_back("-H");
6474 CmdArgs.push_back("-sys-header-deps");
6475 }
6476 Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
6477
6479 CmdArgs.push_back("-header-include-file");
6480 CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
6481 ? D.CCPrintHeadersFilename.c_str()
6482 : "-");
6483 CmdArgs.push_back("-sys-header-deps");
6484 CmdArgs.push_back(Args.MakeArgString(
6485 "-header-include-format=" +
6487 CmdArgs.push_back(Args.MakeArgString(
6488 "-header-include-filtering=" +
6490 }
6491 Args.AddLastArg(CmdArgs, options::OPT_P);
6492 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
6493
6494 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
6495 CmdArgs.push_back("-diagnostic-log-file");
6496 CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
6497 ? D.CCLogDiagnosticsFilename.c_str()
6498 : "-");
6499 }
6500
6501 // Give the gen diagnostics more chances to succeed, by avoiding intentional
6502 // crashes.
6503 if (D.CCGenDiagnostics)
6504 CmdArgs.push_back("-disable-pragma-debug-crash");
6505
6506 // Allow backend to put its diagnostic files in the same place as frontend
6507 // crash diagnostics files.
6508 if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
6509 StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
6510 CmdArgs.push_back("-mllvm");
6511 CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
6512 }
6513
6514 addSeparateSectionFlags(Triple, Args, CmdArgs);
6515
6516 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_address_map,
6517 options::OPT_fno_basic_block_address_map)) {
6518 if (((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) ||
6519 (Triple.isX86() && Triple.isOSBinFormatCOFF())) {
6520 if (A->getOption().matches(options::OPT_fbasic_block_address_map))
6521 A->render(Args, CmdArgs);
6522 } else {
6523 D.Diag(diag::err_drv_unsupported_opt_for_target)
6524 << A->getAsString(Args) << TripleStr;
6525 }
6526 }
6527
6528 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
6529 StringRef Val = A->getValue();
6530 if (Val == "labels") {
6531 D.Diag(diag::warn_drv_deprecated_arg)
6532 << A->getAsString(Args) << /*hasReplacement=*/true
6533 << "-fbasic-block-address-map";
6534 CmdArgs.push_back("-fbasic-block-address-map");
6535 } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {
6536 if (Val != "all" && Val != "none" && !Val.starts_with("list="))
6537 D.Diag(diag::err_drv_invalid_value)
6538 << A->getAsString(Args) << A->getValue();
6539 else
6540 A->render(Args, CmdArgs);
6541 } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
6542 // "all" is not supported on AArch64 since branch relaxation creates new
6543 // basic blocks for some cross-section branches.
6544 if (Val != "labels" && Val != "none" && !Val.starts_with("list="))
6545 D.Diag(diag::err_drv_invalid_value)
6546 << A->getAsString(Args) << A->getValue();
6547 else
6548 A->render(Args, CmdArgs);
6549 } else if (Triple.isNVPTX()) {
6550 // Do not pass the option to the GPU compilation. We still want it enabled
6551 // for the host-side compilation, so seeing it here is not an error.
6552 } else if (Val != "none") {
6553 // =none is allowed everywhere. It's useful for overriding the option
6554 // and is the same as not specifying the option.
6555 D.Diag(diag::err_drv_unsupported_opt_for_target)
6556 << A->getAsString(Args) << TripleStr;
6557 }
6558 }
6559
6560 Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
6561 options::OPT_fno_unique_section_names);
6562 Args.addOptInFlag(CmdArgs, options::OPT_fseparate_named_sections,
6563 options::OPT_fno_separate_named_sections);
6564 Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
6565 options::OPT_fno_unique_internal_linkage_names);
6566 Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
6567 options::OPT_fno_unique_basic_block_section_names);
6568
6569 if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
6570 options::OPT_fno_split_machine_functions)) {
6571 if (!A->getOption().matches(options::OPT_fno_split_machine_functions)) {
6572 // This codegen pass is only available on x86 and AArch64 ELF targets.
6573 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF())
6574 A->render(Args, CmdArgs);
6575 else
6576 D.Diag(diag::err_drv_unsupported_opt_for_target)
6577 << A->getAsString(Args) << TripleStr;
6578 }
6579 }
6580
6581 if (Arg *A =
6582 Args.getLastArg(options::OPT_fpartition_static_data_sections,
6583 options::OPT_fno_partition_static_data_sections)) {
6584 if (!A->getOption().matches(
6585 options::OPT_fno_partition_static_data_sections)) {
6586 // This codegen pass is only available on x86 and AArch64 ELF targets.
6587 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6588 A->render(Args, CmdArgs);
6589 CmdArgs.push_back("-mllvm");
6590 CmdArgs.push_back("-memprof-annotate-static-data-prefix");
6591 } else
6592 D.Diag(diag::err_drv_unsupported_opt_for_target)
6593 << A->getAsString(Args) << TripleStr;
6594 }
6595 }
6596
6597 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
6598 options::OPT_finstrument_functions_after_inlining,
6599 options::OPT_finstrument_function_entry_bare);
6600 Args.AddLastArg(CmdArgs, options::OPT_fconvergent_functions,
6601 options::OPT_fno_convergent_functions);
6602
6603 // NVPTX doesn't support PGO or coverage
6604 if (!Triple.isNVPTX())
6605 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanitizeArgs, CmdArgs);
6606
6607 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
6608
6609 if (getLastProfileSampleUseArg(Args) &&
6610 Args.hasFlag(options::OPT_fsample_profile_use_profi,
6611 options::OPT_fno_sample_profile_use_profi, true)) {
6612 CmdArgs.push_back("-mllvm");
6613 CmdArgs.push_back("-sample-profile-use-profi");
6614 }
6615
6616 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
6617 if (RawTriple.isPS() &&
6618 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
6619 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
6620 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
6621 }
6622
6623 // Pass options for controlling the default header search paths.
6624 if (Args.hasArg(options::OPT_nostdinc)) {
6625 CmdArgs.push_back("-nostdsysteminc");
6626 CmdArgs.push_back("-nobuiltininc");
6627 } else {
6628 if (Args.hasArg(options::OPT_nostdlibinc))
6629 CmdArgs.push_back("-nostdsysteminc");
6630 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
6631 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
6632 }
6633
6634 // Pass the path to compiler resource files.
6635 CmdArgs.push_back("-resource-dir");
6636 CmdArgs.push_back(D.ResourceDir.c_str());
6637
6638 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
6639
6640 // Add preprocessing options like -I, -D, etc. if we are using the
6641 // preprocessor.
6642 //
6643 // FIXME: Support -fpreprocessed
6645 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6646
6647 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6648 // that "The compiler can only warn and ignore the option if not recognized".
6649 // When building with ccache, it will pass -D options to clang even on
6650 // preprocessed inputs and configure concludes that -fPIC is not supported.
6651 Args.ClaimAllArgs(options::OPT_D);
6652
6653 // Warn about ignored options to clang.
6654 for (const Arg *A :
6655 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6656 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6657 A->claim();
6658 }
6659
6660 for (const Arg *A :
6661 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
6662 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
6663 A->claim();
6664 }
6665
6666 claimNoWarnArgs(Args);
6667
6668 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
6669
6670 for (const Arg *A :
6671 Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
6672 A->claim();
6673 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6674 unsigned WarningNumber;
6675 if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
6676 D.Diag(diag::err_drv_invalid_int_value)
6677 << A->getAsString(Args) << A->getValue();
6678 continue;
6679 }
6680
6681 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6682 CmdArgs.push_back(Args.MakeArgString(
6683 "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6684 }
6685 continue;
6686 }
6687 A->render(Args, CmdArgs);
6688 }
6689
6690 Args.AddAllArgs(CmdArgs, options::OPT_Wsystem_headers_in_module_EQ);
6691
6692 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
6693 CmdArgs.push_back("-pedantic");
6694 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
6695 Args.AddLastArg(CmdArgs, options::OPT_w);
6696
6697 Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
6698 options::OPT_fno_fixed_point);
6699
6700 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_overflow_behavior_types,
6701 options::OPT_fno_experimental_overflow_behavior_types);
6702
6703 if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
6704 A->render(Args, CmdArgs);
6705
6706 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6707 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6708
6709 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6710 options::OPT_fno_experimental_omit_vtable_rtti);
6711
6712 if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
6713 A->render(Args, CmdArgs);
6714
6715 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6716 // (-ansi is equivalent to -std=c89 or -std=c++98).
6717 //
6718 // If a std is supplied, only add -trigraphs if it follows the
6719 // option.
6720 bool ImplyVCPPCVer = false;
6721 bool ImplyVCPPCXXVer = false;
6722 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
6723 if (Std) {
6724 if (Std->getOption().matches(options::OPT_ansi))
6725 if (types::isCXX(InputType))
6726 CmdArgs.push_back("-std=c++98");
6727 else
6728 CmdArgs.push_back("-std=c89");
6729 else {
6730 if (IsSYCL) {
6731 const LangStandard *LangStd =
6732 LangStandard::getLangStandardForName(Std->getValue());
6733 if (LangStd) {
6734 // Use of -std= with 'C' is not supported for SYCL.
6735 if (LangStd->getLanguage() == Language::C)
6736 D.Diag(diag::err_drv_argument_not_allowed_with)
6737 << Std->getAsString(Args) << "-fsycl";
6738 // SYCL requires C++17 or later.
6739 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
6740 D.Diag(diag::err_drv_sycl_requires_cxx17) << Std->getAsString(Args);
6741 }
6742 }
6743 Std->render(Args, CmdArgs);
6744 }
6745
6746 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6747 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
6748 options::OPT_ftrigraphs,
6749 options::OPT_fno_trigraphs))
6750 if (A != Std)
6751 A->render(Args, CmdArgs);
6752 } else {
6753 // Honor -std-default.
6754 //
6755 // FIXME: Clang doesn't correctly handle -std= when the input language
6756 // doesn't match. For the time being just ignore this for C++ inputs;
6757 // eventually we want to do all the standard defaulting here instead of
6758 // splitting it between the driver and clang -cc1.
6759 if (!types::isCXX(InputType)) {
6760 if (!Args.hasArg(options::OPT__SLASH_std)) {
6761 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
6762 /*Joined=*/true);
6763 } else
6764 ImplyVCPPCVer = true;
6765 }
6766 else if (IsWindowsMSVC)
6767 ImplyVCPPCXXVer = true;
6768
6769 if (IsSYCL && types::isCXX(InputType) &&
6770 !Args.hasArg(options::OPT__SLASH_std) && !IsWindowsMSVC)
6771 // For SYCL, we default to -std=c++17 for all compilations. Use of -std
6772 // on the command line will override. On Windows MSVC, this is handled
6773 // by the ImplyVCPPCXXVer path below.
6774 CmdArgs.push_back("-std=c++17");
6775
6776 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
6777 options::OPT_fno_trigraphs);
6778 }
6779
6780 // GCC's behavior for -Wwrite-strings is a bit strange:
6781 // * In C, this "warning flag" changes the types of string literals from
6782 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6783 // for the discarded qualifier.
6784 // * In C++, this is just a normal warning flag.
6785 //
6786 // Implementing this warning correctly in C is hard, so we follow GCC's
6787 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6788 // a non-const char* in C, rather than using this crude hack.
6789 if (!types::isCXX(InputType)) {
6790 // FIXME: This should behave just like a warning flag, and thus should also
6791 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6792 Arg *WriteStrings =
6793 Args.getLastArg(options::OPT_Wwrite_strings,
6794 options::OPT_Wno_write_strings, options::OPT_w);
6795 if (WriteStrings &&
6796 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
6797 CmdArgs.push_back("-fconst-strings");
6798 }
6799
6800 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6801 // during C++ compilation, which it is by default. GCC keeps this define even
6802 // in the presence of '-w', match this behavior bug-for-bug.
6803 if (types::isCXX(InputType) &&
6804 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
6805 true)) {
6806 CmdArgs.push_back("-fdeprecated-macro");
6807 }
6808
6809 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6810 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
6811 if (Asm->getOption().matches(options::OPT_fasm))
6812 CmdArgs.push_back("-fgnu-keywords");
6813 else
6814 CmdArgs.push_back("-fno-gnu-keywords");
6815 }
6816
6817 if (!ShouldEnableAutolink(Args, TC, JA))
6818 CmdArgs.push_back("-fno-autolink");
6819
6820 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);
6821 Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);
6822 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);
6823 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);
6824
6825 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
6826
6827 if (CLANG_USE_EXPERIMENTAL_CONST_INTERP) {
6828 Args.ClaimAllArgs(options::OPT_fexperimental_new_constant_interpreter);
6829 Args.AddLastArg(CmdArgs,
6830 options::OPT_fno_experimental_new_constant_interpreter);
6831 } else {
6832 Args.ClaimAllArgs(options::OPT_fno_experimental_new_constant_interpreter);
6833 Args.AddLastArg(CmdArgs,
6834 options::OPT_fexperimental_new_constant_interpreter);
6835 }
6836
6837 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
6838 CmdArgs.push_back("-fbracket-depth");
6839 CmdArgs.push_back(A->getValue());
6840 }
6841
6842 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
6843 options::OPT_Wlarge_by_value_copy_def)) {
6844 if (A->getNumValues()) {
6845 StringRef bytes = A->getValue();
6846 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
6847 } else
6848 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
6849 }
6850
6851 if (Args.hasArg(options::OPT_relocatable_pch))
6852 CmdArgs.push_back("-relocatable-pch");
6853
6854 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
6855 static const char *kCFABIs[] = {
6856 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6857 };
6858
6859 if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
6860 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6861 else
6862 A->render(Args, CmdArgs);
6863 }
6864
6865 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
6866 CmdArgs.push_back("-fconstant-string-class");
6867 CmdArgs.push_back(A->getValue());
6868 }
6869
6870 if (Arg *A = Args.getLastArg(options::OPT_fconstant_array_class_EQ)) {
6871 CmdArgs.push_back("-fconstant-array-class");
6872 CmdArgs.push_back(A->getValue());
6873 }
6874 if (Arg *A = Args.getLastArg(options::OPT_fconstant_dictionary_class_EQ)) {
6875 CmdArgs.push_back("-fconstant-dictionary-class");
6876 CmdArgs.push_back(A->getValue());
6877 }
6878 if (Arg *A =
6879 Args.getLastArg(options::OPT_fconstant_integer_number_class_EQ)) {
6880 CmdArgs.push_back("-fconstant-integer-number-class");
6881 CmdArgs.push_back(A->getValue());
6882 }
6883 if (Arg *A = Args.getLastArg(options::OPT_fconstant_float_number_class_EQ)) {
6884 CmdArgs.push_back("-fconstant-float-number-class");
6885 CmdArgs.push_back(A->getValue());
6886 }
6887 if (Arg *A = Args.getLastArg(options::OPT_fconstant_double_number_class_EQ)) {
6888 CmdArgs.push_back("-fconstant-double-number-class");
6889 CmdArgs.push_back(A->getValue());
6890 }
6891
6892 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
6893 CmdArgs.push_back("-ftabstop");
6894 CmdArgs.push_back(A->getValue());
6895 }
6896
6897 if (Args.hasFlag(options::OPT_fexperimental_call_graph_section,
6898 options::OPT_fno_experimental_call_graph_section, false))
6899 CmdArgs.push_back("-fexperimental-call-graph-section");
6900
6901 Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
6902 options::OPT_fno_stack_size_section);
6903
6904 if (Args.hasArg(options::OPT_fstack_usage)) {
6905 CmdArgs.push_back("-stack-usage-file");
6906
6907 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6908 SmallString<128> OutputFilename(OutputOpt->getValue());
6909 llvm::sys::path::replace_extension(OutputFilename, "su");
6910 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
6911 } else
6912 CmdArgs.push_back(
6913 Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6914 }
6915
6916 CmdArgs.push_back("-ferror-limit");
6917 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
6918 CmdArgs.push_back(A->getValue());
6919 else
6920 CmdArgs.push_back("19");
6921
6922 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);
6923 Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
6924 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
6925 Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
6926 Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
6927
6928 // Pass -fmessage-length=.
6929 unsigned MessageLength = 0;
6930 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
6931 StringRef V(A->getValue());
6932 if (V.getAsInteger(0, MessageLength))
6933 D.Diag(diag::err_drv_invalid_argument_to_option)
6934 << V << A->getOption().getName();
6935 } else {
6936 // If -fmessage-length=N was not specified, determine whether this is a
6937 // terminal and, if so, implicitly define -fmessage-length appropriately.
6938 MessageLength = llvm::sys::Process::StandardErrColumns();
6939 }
6940 if (MessageLength != 0)
6941 CmdArgs.push_back(
6942 Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
6943
6944 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
6945 CmdArgs.push_back(
6946 Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
6947
6948 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
6949 CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
6950 Twine(A->getValue(0))));
6951
6952 // -fvisibility= and -fvisibility-ms-compat are of a piece.
6953 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
6954 options::OPT_fvisibility_ms_compat)) {
6955 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
6956 A->render(Args, CmdArgs);
6957 } else {
6958 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6959 CmdArgs.push_back("-fvisibility=hidden");
6960 CmdArgs.push_back("-ftype-visibility=default");
6961 }
6962 } else if (IsOpenMPDevice) {
6963 // When compiling for the OpenMP device we want protected visibility by
6964 // default. This prevents the device from accidentally preempting code on
6965 // the host, makes the system more robust, and improves performance.
6966 CmdArgs.push_back("-fvisibility=protected");
6967 }
6968
6969 // PS4/PS5 process these options in addClangTargetOptions.
6970 if (!RawTriple.isPS()) {
6971 if (const Arg *A =
6972 Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
6973 options::OPT_fno_visibility_from_dllstorageclass)) {
6974 if (A->getOption().matches(
6975 options::OPT_fvisibility_from_dllstorageclass)) {
6976 CmdArgs.push_back("-fvisibility-from-dllstorageclass");
6977 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
6978 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
6979 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
6980 Args.AddLastArg(CmdArgs,
6981 options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6982 }
6983 }
6984 }
6985
6986 if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
6987 options::OPT_fno_visibility_inlines_hidden, false))
6988 CmdArgs.push_back("-fvisibility-inlines-hidden");
6989
6990 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
6991 options::OPT_fno_visibility_inlines_hidden_static_local_var);
6992
6993 // -fvisibility-global-new-delete-hidden is a deprecated spelling of
6994 // -fvisibility-global-new-delete=force-hidden.
6995 if (const Arg *A =
6996 Args.getLastArg(options::OPT_fvisibility_global_new_delete_hidden)) {
6997 D.Diag(diag::warn_drv_deprecated_arg)
6998 << A->getAsString(Args) << /*hasReplacement=*/true
6999 << "-fvisibility-global-new-delete=force-hidden";
7000 }
7001
7002 if (const Arg *A =
7003 Args.getLastArg(options::OPT_fvisibility_global_new_delete_EQ,
7004 options::OPT_fvisibility_global_new_delete_hidden)) {
7005 if (A->getOption().matches(options::OPT_fvisibility_global_new_delete_EQ)) {
7006 A->render(Args, CmdArgs);
7007 } else {
7008 assert(A->getOption().matches(
7009 options::OPT_fvisibility_global_new_delete_hidden));
7010 CmdArgs.push_back("-fvisibility-global-new-delete=force-hidden");
7011 }
7012 }
7013
7014 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
7015
7016 if (Args.hasFlag(options::OPT_fnew_infallible,
7017 options::OPT_fno_new_infallible, false))
7018 CmdArgs.push_back("-fnew-infallible");
7019
7020 if (Args.hasFlag(options::OPT_fno_operator_names,
7021 options::OPT_foperator_names, false))
7022 CmdArgs.push_back("-fno-operator-names");
7023
7024 // Forward -f (flag) options which we can pass directly.
7025 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
7026 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
7027 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
7028 Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
7029 Args.AddLastArg(CmdArgs, options::OPT_fraw_string_literals,
7030 options::OPT_fno_raw_string_literals);
7031
7032 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
7033 Triple.hasDefaultEmulatedTLS()))
7034 CmdArgs.push_back("-femulated-tls");
7035
7036 Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,
7037 options::OPT_fno_check_new);
7038
7039 if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
7040 // FIXME: There's no reason for this to be restricted to some backend.
7041 // The backend code needs to be changed to include the appropriate function
7042 // calls automatically.
7043 StringRef Value = A->getValue();
7044 if (!Triple.isX86() && !Triple.isAArch64() &&
7045 !(Triple.isRISCV() && (Value == "skip" || Value.contains("gpr"))))
7046 D.Diag(diag::err_drv_unsupported_opt_for_target)
7047 << A->getAsString(Args) << TripleStr;
7048 }
7049
7050 // AltiVec-like language extensions aren't relevant for assembling.
7051 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
7052 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
7053
7054 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
7055 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
7056
7057 // Forward flags for OpenMP. We don't do this if the current action is an
7058 // device offloading action other than OpenMP.
7059 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
7060 options::OPT_fno_openmp, false) &&
7061 !Args.hasFlag(options::OPT_foffload_via_llvm,
7062 options::OPT_fno_offload_via_llvm, false) &&
7065
7066 // Determine if target-fast optimizations should be enabled
7067 bool TargetFastUsed =
7068 Args.hasFlag(options::OPT_fopenmp_target_fast,
7069 options::OPT_fno_openmp_target_fast, OFastEnabled);
7070 switch (D.getOpenMPRuntime(Args)) {
7071 case Driver::OMPRT_OMP:
7073 // Clang can generate useful OpenMP code for these two runtime libraries.
7074 CmdArgs.push_back("-fopenmp");
7075
7076 // If no option regarding the use of TLS in OpenMP codegeneration is
7077 // given, decide a default based on the target. Otherwise rely on the
7078 // options and pass the right information to the frontend.
7079 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
7080 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
7081 CmdArgs.push_back("-fnoopenmp-use-tls");
7082 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
7083 options::OPT_fno_openmp_simd);
7084 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
7085 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
7086 if (!Args.hasFlag(options::OPT_fopenmp_extensions,
7087 options::OPT_fno_openmp_extensions, /*Default=*/true))
7088 CmdArgs.push_back("-fno-openmp-extensions");
7089 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
7090 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
7091 // '-fopenmp-cuda-teams-reduction-recs-num=' is deprecated and has no
7092 // effect: the teams reduction buffer is sized at kernel launch by the
7093 // offload plugin to match the actual number of teams. Honoring a
7094 // smaller user-supplied value would silently truncate the buffer for
7095 // larger launches.
7096 if (Arg *A = Args.getLastArg(
7097 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ))
7098 D.Diag(diag::warn_drv_deprecated_custom)
7099 << A->getAsString(Args)
7100 << "the value is ignored; the teams reduction buffer is sized "
7101 "automatically at kernel launch";
7102 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
7103 options::OPT_fno_openmp_optimistic_collapse,
7104 /*Default=*/false))
7105 CmdArgs.push_back("-fopenmp-optimistic-collapse");
7106
7107 // When in OpenMP offloading mode with NVPTX target, forward
7108 // cuda-mode flag
7109 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
7110 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
7111 CmdArgs.push_back("-fopenmp-cuda-mode");
7112
7113 // When in OpenMP offloading mode, enable debugging on the device.
7114 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
7115 if (Args.hasFlag(options::OPT_fopenmp_target_debug,
7116 options::OPT_fno_openmp_target_debug, /*Default=*/false))
7117 CmdArgs.push_back("-fopenmp-target-debug");
7118
7119 // When in OpenMP offloading mode, forward assumptions information about
7120 // thread and team counts in the device.
7121 if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
7122 options::OPT_fno_openmp_assume_teams_oversubscription,
7123 /*Default=*/false))
7124 CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
7125 if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
7126 options::OPT_fno_openmp_assume_threads_oversubscription,
7127 /*Default=*/false))
7128 CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
7129
7130 // Handle -fopenmp-assume-no-thread-state (implied by target-fast)
7131 if (Args.hasFlag(options::OPT_fopenmp_assume_no_thread_state,
7132 options::OPT_fno_openmp_assume_no_thread_state,
7133 /*Default=*/TargetFastUsed))
7134 CmdArgs.push_back("-fopenmp-assume-no-thread-state");
7135
7136 // Handle -fopenmp-assume-no-nested-parallelism (implied by target-fast)
7137 if (Args.hasFlag(options::OPT_fopenmp_assume_no_nested_parallelism,
7138 options::OPT_fno_openmp_assume_no_nested_parallelism,
7139 /*Default=*/TargetFastUsed))
7140 CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
7141
7142 if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
7143 CmdArgs.push_back("-fopenmp-offload-mandatory");
7144 if (Args.hasArg(options::OPT_fopenmp_force_usm))
7145 CmdArgs.push_back("-fopenmp-force-usm");
7146 break;
7147 default:
7148 // By default, if Clang doesn't know how to generate useful OpenMP code
7149 // for a specific runtime library, we just don't pass the '-fopenmp' flag
7150 // down to the actual compilation.
7151 // FIXME: It would be better to have a mode which *only* omits IR
7152 // generation based on the OpenMP support so that we get consistent
7153 // semantic analysis, etc.
7154 break;
7155 }
7156 } else {
7157 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
7158 options::OPT_fno_openmp_simd);
7159 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
7160 Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
7161 options::OPT_fno_openmp_extensions);
7162 }
7163 // Forward the offload runtime change to code generation, liboffload implies
7164 // new driver. Otherwise, check if we should forward the new driver to change
7165 // offloading code generation.
7166 if (Args.hasFlag(options::OPT_foffload_via_llvm,
7167 options::OPT_fno_offload_via_llvm, false)) {
7168 CmdArgs.append({"--offload-new-driver", "-foffload-via-llvm"});
7169 } else if (Args.hasFlag(options::OPT_offload_new_driver,
7170 options::OPT_no_offload_new_driver,
7171 C.getActiveOffloadKinds() != Action::OFK_None)) {
7172 CmdArgs.push_back("--offload-new-driver");
7173 }
7174
7175 const XRayArgs &XRay = TC.getXRayArgs(Args);
7176 XRay.addArgs(TC, Args, CmdArgs, InputType);
7177
7178 for (const auto &Filename :
7179 Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
7180 if (D.getVFS().exists(Filename))
7181 CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
7182 else
7183 D.Diag(clang::diag::err_drv_no_such_file) << Filename;
7184 }
7185
7186 if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
7187 StringRef S0 = A->getValue(), S = S0;
7188 unsigned Size, Offset = 0;
7189 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
7190 !Triple.isX86() && !Triple.isSystemZ() &&
7191 !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
7192 Triple.getArch() == llvm::Triple::ppc64 ||
7193 Triple.getArch() == llvm::Triple::ppc64le)))
7194 D.Diag(diag::err_drv_unsupported_opt_for_target)
7195 << A->getAsString(Args) << TripleStr;
7196 else if (S.consumeInteger(10, Size) ||
7197 (!S.empty() &&
7198 (!S.consume_front(",") || S.consumeInteger(10, Offset))) ||
7199 (!S.empty() && (!S.consume_front(",") || S.empty())))
7200 D.Diag(diag::err_drv_invalid_argument_to_option)
7201 << S0 << A->getOption().getName();
7202 else if (Size < Offset)
7203 D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
7204 else {
7205 CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
7206 CmdArgs.push_back(Args.MakeArgString(
7207 "-fpatchable-function-entry-offset=" + Twine(Offset)));
7208 if (!S.empty())
7209 CmdArgs.push_back(
7210 Args.MakeArgString("-fpatchable-function-entry-section=" + S));
7211 }
7212 }
7213
7214 Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
7215
7216 if (Args.hasArg(options::OPT_fms_secure_hotpatch_functions_file))
7217 Args.AddLastArg(CmdArgs, options::OPT_fms_secure_hotpatch_functions_file);
7218
7219 for (const auto &A :
7220 Args.getAllArgValues(options::OPT_fms_secure_hotpatch_functions_list))
7221 CmdArgs.push_back(
7222 Args.MakeArgString("-fms-secure-hotpatch-functions-list=" + Twine(A)));
7223
7224 if (TC.SupportsProfiling()) {
7225 Args.AddLastArg(CmdArgs, options::OPT_pg);
7226
7227 llvm::Triple::ArchType Arch = TC.getArch();
7228 if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
7229 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
7230 A->render(Args, CmdArgs);
7231 else
7232 D.Diag(diag::err_drv_unsupported_opt_for_target)
7233 << A->getAsString(Args) << TripleStr;
7234 }
7235 if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
7236 if (Arch == llvm::Triple::systemz)
7237 A->render(Args, CmdArgs);
7238 else
7239 D.Diag(diag::err_drv_unsupported_opt_for_target)
7240 << A->getAsString(Args) << TripleStr;
7241 }
7242 if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
7243 if (Arch == llvm::Triple::systemz)
7244 A->render(Args, CmdArgs);
7245 else
7246 D.Diag(diag::err_drv_unsupported_opt_for_target)
7247 << A->getAsString(Args) << TripleStr;
7248 }
7249 }
7250
7251 if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
7252 if (TC.getTriple().isOSzOS()) {
7253 D.Diag(diag::err_drv_unsupported_opt_for_target)
7254 << A->getAsString(Args) << TripleStr;
7255 }
7256 }
7257 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
7258 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
7259 D.Diag(diag::err_drv_unsupported_opt_for_target)
7260 << A->getAsString(Args) << TripleStr;
7261 }
7262 }
7263 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
7264 if (A->getOption().matches(options::OPT_p)) {
7265 A->claim();
7266 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))
7267 CmdArgs.push_back("-pg");
7268 }
7269 }
7270
7271 // Reject AIX-specific link options on other targets.
7272 if (!TC.getTriple().isOSAIX()) {
7273 for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,
7274 options::OPT_mxcoff_build_id_EQ)) {
7275 D.Diag(diag::err_drv_unsupported_opt_for_target)
7276 << A->getSpelling() << TripleStr;
7277 }
7278 }
7279
7280 if (Args.getLastArg(options::OPT_fapple_kext) ||
7281 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
7282 CmdArgs.push_back("-fapple-kext");
7283
7284 Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
7285 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
7286 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
7287 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
7288 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
7289 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
7290 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
7291 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_json);
7292 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
7293 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
7294 Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
7295
7296 if (const char *Name = C.getTimeTraceFile(&JA)) {
7297 CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
7298 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
7299 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_verbose);
7300 }
7301
7302 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
7303 CmdArgs.push_back("-ftrapv-handler");
7304 CmdArgs.push_back(A->getValue());
7305 }
7306
7307 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
7308
7309 Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
7310 options::OPT_fno_finite_loops);
7311
7312 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
7313 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
7314 options::OPT_fno_unroll_loops);
7315 Args.AddLastArg(CmdArgs, options::OPT_floop_interchange,
7316 options::OPT_fno_loop_interchange);
7317 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_loop_fusion,
7318 options::OPT_fno_experimental_loop_fusion);
7319
7320 Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
7321
7322 Args.AddLastArg(CmdArgs, options::OPT_pthread);
7323
7324 Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
7325 options::OPT_mno_speculative_load_hardening);
7326
7327 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
7328 RenderSCPOptions(TC, Args, CmdArgs);
7329 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
7330
7331 Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
7332
7333 Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
7334 options::OPT_mno_stackrealign);
7335
7336 if (const Arg *A = Args.getLastArg(options::OPT_mstack_alignment)) {
7337 StringRef Value = A->getValue();
7338 int64_t Alignment = 0;
7339 if (Value.getAsInteger(10, Alignment) || Alignment < 0)
7340 D.Diag(diag::err_drv_invalid_argument_to_option)
7341 << Value << A->getOption().getName();
7342 else if (Alignment & (Alignment - 1))
7343 D.Diag(diag::err_drv_alignment_not_power_of_two)
7344 << A->getAsString(Args) << Value;
7345 else
7346 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + Value));
7347 }
7348
7349 if (Args.hasArg(options::OPT_mstack_probe_size)) {
7350 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
7351
7352 if (!Size.empty())
7353 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
7354 else
7355 CmdArgs.push_back("-mstack-probe-size=0");
7356 }
7357
7358 Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
7359 options::OPT_mno_stack_arg_probe);
7360
7361 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
7362 options::OPT_mno_restrict_it)) {
7363 if (A->getOption().matches(options::OPT_mrestrict_it)) {
7364 CmdArgs.push_back("-mllvm");
7365 CmdArgs.push_back("-arm-restrict-it");
7366 } else {
7367 CmdArgs.push_back("-mllvm");
7368 CmdArgs.push_back("-arm-default-it");
7369 }
7370 }
7371
7372 // Forward -cl options to -cc1
7373 RenderOpenCLOptions(Args, CmdArgs, InputType);
7374
7375 // Forward hlsl options to -cc1
7376 RenderHLSLOptions(D, Args, CmdArgs, InputType);
7377
7378 // Forward OpenACC options to -cc1
7379 RenderOpenACCOptions(D, Args, CmdArgs, InputType);
7380
7381 if (IsHIP) {
7382 if (Args.hasFlag(options::OPT_fhip_new_launch_api,
7383 options::OPT_fno_hip_new_launch_api, true))
7384 CmdArgs.push_back("-fhip-new-launch-api");
7385 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,
7386 options::OPT_fno_gpu_allow_device_init);
7387 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);
7388 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);
7389 Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
7390 options::OPT_fno_hip_kernel_arg_name);
7391 }
7392
7393 if (IsCuda || IsHIP) {
7394 if (IsRDCMode)
7395 CmdArgs.push_back("-fgpu-rdc");
7396 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_defer_diag,
7397 options::OPT_fno_gpu_defer_diag);
7398 if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
7399 options::OPT_fno_gpu_exclude_wrong_side_overloads,
7400 false)) {
7401 CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
7402 CmdArgs.push_back("-fgpu-defer-diag");
7403 }
7404 }
7405
7406 // Forward --no-offloadlib to -cc1.
7407 if (!Args.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib, true))
7408 CmdArgs.push_back("--no-offloadlib");
7409
7410 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
7411 CmdArgs.push_back(
7412 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
7413
7414 if (Arg *SA = Args.getLastArg(options::OPT_mcf_branch_label_scheme_EQ))
7415 CmdArgs.push_back(Args.MakeArgString(Twine("-mcf-branch-label-scheme=") +
7416 SA->getValue()));
7417 } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {
7418 // Emit IBT endbr64 instructions by default
7419 CmdArgs.push_back("-fcf-protection=branch");
7420 // jump-table can generate indirect jumps, which are not permitted
7421 CmdArgs.push_back("-fno-jump-tables");
7422 }
7423
7424 if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
7425 CmdArgs.push_back(
7426 Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
7427
7428 Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
7429
7430 // Forward -f options with positive and negative forms; we translate these by
7431 // hand. Do not propagate PGO options to the GPU-side compilations as the
7432 // profile info is for the host-side compilation only.
7433 if (!(IsCudaDevice || IsHIPDevice)) {
7434 if (Arg *A = getLastProfileSampleUseArg(Args)) {
7435 auto *PGOArg = Args.getLastArg(
7436 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
7437 options::OPT_fcs_profile_generate,
7438 options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
7439 options::OPT_fprofile_use_EQ);
7440 if (PGOArg)
7441 D.Diag(diag::err_drv_argument_not_allowed_with)
7442 << "SampleUse with PGO options";
7443
7444 StringRef fname = A->getValue();
7445 if (!llvm::sys::fs::exists(fname))
7446 D.Diag(diag::err_drv_no_such_file) << fname;
7447 else
7448 A->render(Args, CmdArgs);
7449 }
7450 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
7451
7452 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
7453 options::OPT_fno_pseudo_probe_for_profiling, false)) {
7454 CmdArgs.push_back("-fpseudo-probe-for-profiling");
7455 // Enforce -funique-internal-linkage-names if it's not explicitly turned
7456 // off.
7457 if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
7458 options::OPT_fno_unique_internal_linkage_names, true))
7459 CmdArgs.push_back("-funique-internal-linkage-names");
7460 }
7461 }
7462 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
7463
7464 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7465 options::OPT_fno_assume_sane_operator_new);
7466
7467 if (Args.hasFlag(options::OPT_fapinotes, options::OPT_fno_apinotes, false))
7468 CmdArgs.push_back("-fapinotes");
7469 if (Args.hasFlag(options::OPT_fapinotes_modules,
7470 options::OPT_fno_apinotes_modules, false))
7471 CmdArgs.push_back("-fapinotes-modules");
7472 Args.AddLastArg(CmdArgs, options::OPT_fapinotes_swift_version);
7473
7474 if (Args.hasFlag(options::OPT_fswift_version_independent_apinotes,
7475 options::OPT_fno_swift_version_independent_apinotes, false))
7476 CmdArgs.push_back("-fswift-version-independent-apinotes");
7477
7478 // -fblocks=0 is default.
7479 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
7480 TC.IsBlocksDefault()) ||
7481 (Args.hasArg(options::OPT_fgnu_runtime) &&
7482 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
7483 !Args.hasArg(options::OPT_fno_blocks))) {
7484 CmdArgs.push_back("-fblocks");
7485
7486 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
7487 CmdArgs.push_back("-fblocks-runtime-optional");
7488 }
7489
7490 // -fencode-extended-block-signature=1 is default.
7492 CmdArgs.push_back("-fencode-extended-block-signature");
7493
7494 if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
7495 options::OPT_fno_coro_aligned_allocation, false) &&
7496 types::isCXX(InputType))
7497 CmdArgs.push_back("-fcoro-aligned-allocation");
7498
7499 if (Args.hasFlag(options::OPT_fdefer_ts, options::OPT_fno_defer_ts,
7500 /*Default=*/false))
7501 CmdArgs.push_back("-fdefer-ts");
7502
7503 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
7504 options::OPT_fno_double_square_bracket_attributes);
7505
7506 Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
7507 options::OPT_fno_access_control);
7508 Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
7509 options::OPT_fno_elide_constructors);
7510
7511 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
7512
7513 if (KernelOrKext || (types::isCXX(InputType) &&
7514 (RTTIMode == ToolChain::RM_Disabled)))
7515 CmdArgs.push_back("-fno-rtti");
7516
7517 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
7518 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
7519 TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
7520 CmdArgs.push_back("-fshort-enums");
7521
7522 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
7523
7524 // -fuse-cxa-atexit is default.
7525 if (!Args.hasFlag(
7526 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
7527 !RawTriple.isOSAIX() &&
7528 (!RawTriple.isOSWindows() ||
7529 RawTriple.isWindowsCygwinEnvironment()) &&
7530 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
7531 RawTriple.hasEnvironment())) ||
7532 KernelOrKext)
7533 CmdArgs.push_back("-fno-use-cxa-atexit");
7534
7535 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
7536 options::OPT_fno_register_global_dtors_with_atexit,
7537 RawTriple.isOSDarwin() && !KernelOrKext))
7538 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
7539
7540 Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
7541 options::OPT_fno_use_line_directives);
7542
7543 // -fno-minimize-whitespace is default.
7544 if (Args.hasFlag(options::OPT_fminimize_whitespace,
7545 options::OPT_fno_minimize_whitespace, false)) {
7546 types::ID InputType = Inputs[0].getType();
7547 if (!isDerivedFromC(InputType))
7548 D.Diag(diag::err_drv_opt_unsupported_input_type)
7549 << "-fminimize-whitespace" << types::getTypeName(InputType);
7550 CmdArgs.push_back("-fminimize-whitespace");
7551 }
7552
7553 // -fno-keep-system-includes is default.
7554 if (Args.hasFlag(options::OPT_fkeep_system_includes,
7555 options::OPT_fno_keep_system_includes, false)) {
7556 types::ID InputType = Inputs[0].getType();
7557 if (!isDerivedFromC(InputType))
7558 D.Diag(diag::err_drv_opt_unsupported_input_type)
7559 << "-fkeep-system-includes" << types::getTypeName(InputType);
7560 CmdArgs.push_back("-fkeep-system-includes");
7561 }
7562
7563 // -fms-extensions=0 is default.
7564 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
7565 IsWindowsMSVC || IsUEFI))
7566 CmdArgs.push_back("-fms-extensions");
7567
7568 // -fms-compatibility=0 is default.
7569 bool IsMSVCCompat = Args.hasFlag(
7570 options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
7571 (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
7572 options::OPT_fno_ms_extensions, true)));
7573 if (IsMSVCCompat) {
7574 CmdArgs.push_back("-fms-compatibility");
7575 if (!types::isCXX(Input.getType()) &&
7576 Args.hasArg(options::OPT_fms_define_stdc))
7577 CmdArgs.push_back("-fms-define-stdc");
7578 }
7579
7580 // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both
7581 // clang and flang.
7582 renderCommonIntegerOverflowOptions(Args, CmdArgs, IsMSVCCompat);
7583
7584 // -fms-anonymous-structs is disabled by default.
7585 // Determine whether to enable Microsoft named anonymous struct/union support.
7586 // This implements "last flag wins" semantics for -fms-anonymous-structs,
7587 // where the feature can be:
7588 // - Explicitly enabled via -fms-anonymous-structs.
7589 // - Explicitly disabled via fno-ms-anonymous-structs
7590 // - Implicitly enabled via -fms-extensions or -fms-compatibility
7591 // - Implicitly disabled via -fno-ms-extensions or -fno-ms-compatibility
7592 //
7593 // When multiple relevent options are present, the last option on the command
7594 // line takes precedence. This allows users to selectively override implicit
7595 // enablement. Examples:
7596 // -fms-extensions -fno-ms-anonymous-structs -> disabled (explicit override)
7597 // -fno-ms-anonymous-structs -fms-extensions -> enabled (last flag wins)
7598 auto MSAnonymousStructsOptionToUseOrNull =
7599 [](const ArgList &Args) -> const char * {
7600 const char *Option = nullptr;
7601 constexpr const char *Enable = "-fms-anonymous-structs";
7602 constexpr const char *Disable = "-fno-ms-anonymous-structs";
7603
7604 // Iterate through all arguments in order to implement "last flag wins".
7605 for (const Arg *A : Args) {
7606 switch (A->getOption().getID()) {
7607 case options::OPT_fms_anonymous_structs:
7608 A->claim();
7609 Option = Enable;
7610 break;
7611 case options::OPT_fno_ms_anonymous_structs:
7612 A->claim();
7613 Option = Disable;
7614 break;
7615 // Each of -fms-extensions and -fms-compatibility implicitly enables the
7616 // feature.
7617 case options::OPT_fms_extensions:
7618 case options::OPT_fms_compatibility:
7619 Option = Enable;
7620 break;
7621 // Each of -fno-ms-extensions and -fno-ms-compatibility implicitly
7622 // disables the feature.
7623 case options::OPT_fno_ms_extensions:
7624 case options::OPT_fno_ms_compatibility:
7625 Option = Disable;
7626 break;
7627 default:
7628 break;
7629 }
7630 }
7631 return Option;
7632 };
7633
7634 // Only pass a flag to CC1 if a relevant option was seen
7635 if (auto MSAnonOpt = MSAnonymousStructsOptionToUseOrNull(Args))
7636 CmdArgs.push_back(MSAnonOpt);
7637
7638 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7639 Args.hasArg(options::OPT_fms_runtime_lib_EQ))
7640 ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
7641
7642 // Handle -fgcc-version, if present.
7643 VersionTuple GNUCVer;
7644 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
7645 // Check that the version has 1 to 3 components and the minor and patch
7646 // versions fit in two decimal digits.
7647 StringRef Val = A->getValue();
7648 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7649 bool Invalid = GNUCVer.tryParse(Val);
7650 unsigned Minor = GNUCVer.getMinor().value_or(0);
7651 unsigned Patch = GNUCVer.getSubminor().value_or(0);
7652 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7653 D.Diag(diag::err_drv_invalid_value)
7654 << A->getAsString(Args) << A->getValue();
7655 }
7656 } else if (!IsMSVCCompat) {
7657 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7658 GNUCVer = VersionTuple(4, 2, 1);
7659 }
7660 if (!GNUCVer.empty()) {
7661 CmdArgs.push_back(
7662 Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
7663 }
7664
7665 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
7666 if (!MSVT.empty())
7667 CmdArgs.push_back(
7668 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
7669
7670 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7671 if (ImplyVCPPCVer) {
7672 StringRef LanguageStandard;
7673 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7674 Std = StdArg;
7675 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7676 .Case("c11", "-std=c11")
7677 .Case("c17", "-std=c17")
7678 // If you add cases below for spellings that are
7679 // not in LangStandards.def, update
7680 // TransferableCommand::tryParseStdArg() in
7681 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7682 // to match.
7683 // TODO: add c23 when MSVC supports it.
7684 .Case("clatest", "-std=c23")
7685 .Default("");
7686 if (LanguageStandard.empty())
7687 D.Diag(clang::diag::warn_drv_unused_argument)
7688 << StdArg->getAsString(Args);
7689 }
7690 CmdArgs.push_back(LanguageStandard.data());
7691 }
7692 if (ImplyVCPPCXXVer) {
7693 StringRef LanguageStandard;
7694 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7695 Std = StdArg;
7696 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7697 .Case("c++14", "-std=c++14")
7698 .Case("c++17", "-std=c++17")
7699 .Case("c++20", "-std=c++20")
7700 // If you add cases below for spellings that are
7701 // not in LangStandards.def, update
7702 // TransferableCommand::tryParseStdArg() in
7703 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7704 // to match.
7705 // TODO add c++23, c++26, c++29 when MSVC supports
7706 // it.
7707 .Case("c++23preview", "-std=c++23")
7708 .Case("c++26preview", "-std=c++26")
7709 .Case("c++latest", "-std=c++2d")
7710 .Default("");
7711 if (IsSYCL) {
7712 const LangStandard *LangStd =
7713 LangStandard::getLangStandardForName(StdArg->getValue());
7714 if (LangStd) {
7715 // Use of /std: with 'C' is not supported for SYCL.
7716 if (LangStd->getLanguage() == Language::C)
7717 D.Diag(diag::err_drv_argument_not_allowed_with)
7718 << StdArg->getAsString(Args) << "-fsycl";
7719 // SYCL requires C++17 or later.
7720 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
7721 D.Diag(diag::err_drv_sycl_requires_cxx17)
7722 << StdArg->getAsString(Args);
7723 }
7724 }
7725 if (LanguageStandard.empty())
7726 D.Diag(clang::diag::warn_drv_unused_argument)
7727 << StdArg->getAsString(Args);
7728 }
7729
7730 if (LanguageStandard.empty()) {
7731 if (IsSYCL)
7732 // For SYCL, C++17 is the default.
7733 LanguageStandard = "-std=c++17";
7734 else if (IsMSVC2015Compatible)
7735 LanguageStandard = "-std=c++14";
7736 else
7737 LanguageStandard = "-std=c++11";
7738 }
7739
7740 CmdArgs.push_back(LanguageStandard.data());
7741 }
7742
7743 Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
7744 options::OPT_fno_borland_extensions);
7745
7746 // -fno-declspec is default, except for PS4/PS5.
7747 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
7748 RawTriple.isPS()))
7749 CmdArgs.push_back("-fdeclspec");
7750 else if (Args.hasArg(options::OPT_fno_declspec))
7751 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
7752
7753 // -fthreadsafe-static is default, except for MSVC compatibility versions less
7754 // than 19.
7755 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
7756 options::OPT_fno_threadsafe_statics,
7757 !types::isOpenCL(InputType) &&
7758 (!IsWindowsMSVC || IsMSVC2015Compatible)))
7759 CmdArgs.push_back("-fno-threadsafe-statics");
7760
7761 if (!Args.hasFlag(options::OPT_fms_tls_guards, options::OPT_fno_ms_tls_guards,
7762 true))
7763 CmdArgs.push_back("-fno-ms-tls-guards");
7764
7765 // Add -fno-assumptions, if it was specified.
7766 if (!Args.hasFlag(options::OPT_fassumptions, options::OPT_fno_assumptions,
7767 true))
7768 CmdArgs.push_back("-fno-assumptions");
7769
7770 // -fgnu-keywords default varies depending on language; only pass if
7771 // specified.
7772 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
7773 options::OPT_fno_gnu_keywords);
7774
7775 Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
7776 options::OPT_fno_gnu89_inline);
7777
7778 const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
7779 options::OPT_finline_hint_functions,
7780 options::OPT_fno_inline_functions);
7781 if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
7782 if (A->getOption().matches(options::OPT_fno_inline))
7783 A->render(Args, CmdArgs);
7784 } else if (InlineArg) {
7785 InlineArg->render(Args, CmdArgs);
7786 }
7787
7788 Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
7789
7790 // FIXME: Find a better way to determine whether we are in C++20.
7791 bool HaveCxx20 =
7792 Std &&
7793 (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
7794 Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
7795 Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
7796 Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
7797 Std->containsValue("c++23preview") || Std->containsValue("c++2c") ||
7798 Std->containsValue("gnu++2c") || Std->containsValue("c++26") ||
7799 Std->containsValue("gnu++26") || Std->containsValue("c++26preview") ||
7800 Std->containsValue("c++2d") || Std->containsValue("gnu++2d") ||
7801 Std->containsValue("c++latest") || Std->containsValue("gnu++latest"));
7802 bool HaveModules =
7803 RenderModulesOptions(C, D, Args, Input, Output, HaveCxx20, CmdArgs);
7804
7805 // -fdelayed-template-parsing is default when targeting MSVC.
7806 // Many old Windows SDK versions require this to parse.
7807 //
7808 // According to
7809 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
7810 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
7811 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
7812 // not enable -fdelayed-template-parsing by default after C++20.
7813 //
7814 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
7815 // able to disable this by default at some point.
7816 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
7817 options::OPT_fno_delayed_template_parsing,
7818 IsWindowsMSVC && !HaveCxx20)) {
7819 if (HaveCxx20)
7820 D.Diag(clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
7821
7822 CmdArgs.push_back("-fdelayed-template-parsing");
7823 }
7824
7825 if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
7826 options::OPT_fno_pch_validate_input_files_content, false))
7827 CmdArgs.push_back("-fvalidate-ast-input-files-content");
7828 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
7829 options::OPT_fno_pch_instantiate_templates, false))
7830 CmdArgs.push_back("-fpch-instantiate-templates");
7831 if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
7832 false))
7833 CmdArgs.push_back("-fmodules-codegen");
7834 if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
7835 false))
7836 CmdArgs.push_back("-fmodules-debuginfo");
7837
7838 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
7839 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
7840 Input, CmdArgs);
7841
7842 if (types::isObjC(Input.getType()) &&
7843 Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
7844 options::OPT_fno_objc_encode_cxx_class_template_spec,
7845 !Runtime.isNeXTFamily()))
7846 CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
7847
7848 if (Args.hasFlag(options::OPT_fapplication_extension,
7849 options::OPT_fno_application_extension, false))
7850 CmdArgs.push_back("-fapplication-extension");
7851
7852 // Handle GCC-style exception args.
7853 bool EH = false;
7854 if (!C.getDriver().IsCLMode())
7855 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext,
7856 IsDeviceOffloadAction, Runtime, CmdArgs);
7857
7858 // Handle exception personalities
7859 Arg *A = Args.getLastArg(
7860 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
7861 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
7862 if (A) {
7863 const Option &Opt = A->getOption();
7864 if (Opt.matches(options::OPT_fsjlj_exceptions))
7865 CmdArgs.push_back("-exception-model=sjlj");
7866 if (Opt.matches(options::OPT_fseh_exceptions))
7867 CmdArgs.push_back("-exception-model=seh");
7868 if (Opt.matches(options::OPT_fdwarf_exceptions))
7869 CmdArgs.push_back("-exception-model=dwarf");
7870 if (Opt.matches(options::OPT_fwasm_exceptions))
7871 CmdArgs.push_back("-exception-model=wasm");
7872 } else {
7873 switch (TC.GetExceptionModel(Args)) {
7874 default:
7875 break;
7876 case llvm::ExceptionHandling::DwarfCFI:
7877 CmdArgs.push_back("-exception-model=dwarf");
7878 break;
7879 case llvm::ExceptionHandling::SjLj:
7880 CmdArgs.push_back("-exception-model=sjlj");
7881 break;
7882 case llvm::ExceptionHandling::WinEH:
7883 CmdArgs.push_back("-exception-model=seh");
7884 break;
7885 }
7886 }
7887
7888 // Unwind information version for x64 Windows.
7889 // Forward the new unified flag if present, otherwise translate legacy flags.
7890 if (const Arg *A = Args.getLastArg(options::OPT_winx64_eh_unwind_EQ)) {
7891 A->claim();
7892 CmdArgs.push_back(
7893 Args.MakeArgString(Twine("-fwinx64-eh-unwind=") + A->getValue()));
7894 } else if (const Arg *A =
7895 Args.getLastArg(options::OPT_winx64_eh_unwindv2_EQ)) {
7896 A->claim();
7897 StringRef Val = A->getValue();
7898 if (Val == "best-effort")
7899 CmdArgs.push_back("-fwinx64-eh-unwind=v2-best-effort");
7900 else if (Val == "required")
7901 CmdArgs.push_back("-fwinx64-eh-unwind=v2-required");
7902 // "disabled" maps to v1 default, nothing to forward.
7903 else if (Val != "disabled")
7904 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
7905 }
7906
7907 // Control Flow Guard mechanism for Windows.
7908 Args.AddLastArg(CmdArgs, options::OPT_win_cfg_mechanism);
7909
7910 // C++ "sane" operator new.
7911 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7912 options::OPT_fno_assume_sane_operator_new);
7913
7914 // -fassume-unique-vtables is on by default.
7915 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
7916 options::OPT_fno_assume_unique_vtables);
7917
7918 // -fsized-deallocation is on by default in C++14 onwards and otherwise off
7919 // by default.
7920 Args.addLastArg(CmdArgs, options::OPT_fsized_deallocation,
7921 options::OPT_fno_sized_deallocation);
7922
7923 // -faligned-allocation is on by default in C++17 onwards and otherwise off
7924 // by default.
7925 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
7926 options::OPT_fno_aligned_allocation,
7927 options::OPT_faligned_new_EQ)) {
7928 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
7929 CmdArgs.push_back("-fno-aligned-allocation");
7930 else
7931 CmdArgs.push_back("-faligned-allocation");
7932 }
7933
7934 // The default new alignment can be specified using a dedicated option or via
7935 // a GCC-compatible option that also turns on aligned allocation.
7936 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
7937 options::OPT_faligned_new_EQ))
7938 CmdArgs.push_back(
7939 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
7940
7941 // -fconstant-cfstrings is default, and may be subject to argument translation
7942 // on Darwin.
7943 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
7944 options::OPT_fno_constant_cfstrings, true) ||
7945 !Args.hasFlag(options::OPT_mconstant_cfstrings,
7946 options::OPT_mno_constant_cfstrings, true))
7947 CmdArgs.push_back("-fno-constant-cfstrings");
7948
7949 Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
7950 options::OPT_fno_pascal_strings);
7951
7952 // Honor -fpack-struct= and -fpack-struct, if given. Note that
7953 // -fno-pack-struct doesn't apply to -fpack-struct=.
7954 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
7955 CmdArgs.push_back(
7956 Args.MakeArgString("-fpack-struct=" + Twine(A->getValue())));
7957 } else if (Args.hasFlag(options::OPT_fpack_struct,
7958 options::OPT_fno_pack_struct, false)) {
7959 CmdArgs.push_back("-fpack-struct=1");
7960 }
7961
7962 // Handle -fmax-type-align=N and -fno-type-align
7963 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
7964 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
7965 if (!SkipMaxTypeAlign) {
7966 std::string MaxTypeAlignStr = "-fmax-type-align=";
7967 MaxTypeAlignStr += A->getValue();
7968 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
7969 }
7970 } else if (RawTriple.isOSDarwin()) {
7971 if (!SkipMaxTypeAlign) {
7972 std::string MaxTypeAlignStr = "-fmax-type-align=16";
7973 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
7974 }
7975 }
7976
7977 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
7978 CmdArgs.push_back("-Qn");
7979
7980 // -fno-common is the default, set -fcommon only when that flag is set.
7981 Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
7982
7983 // -fsigned-bitfields is default, and clang doesn't yet support
7984 // -funsigned-bitfields.
7985 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
7986 options::OPT_funsigned_bitfields, true))
7987 D.Diag(diag::warn_drv_clang_unsupported)
7988 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
7989
7990 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
7991 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
7992 D.Diag(diag::err_drv_clang_unsupported)
7993 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
7994
7995 // -finput_charset=UTF-8 is default. Reject others
7996 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
7997 StringRef value = inputCharset->getValue();
7998 if (!value.equals_insensitive("utf-8"))
7999 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
8000 << value;
8001 }
8002
8003 // -fexec_charset=UTF-8 is default. Reject others
8004 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
8005 StringRef value = execCharset->getValue();
8006 if (!value.equals_insensitive("utf-8"))
8007 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
8008 << value;
8009 }
8010
8011 RenderDiagnosticsOptions(D, Args, CmdArgs);
8012
8013 Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
8014 options::OPT_fno_asm_blocks);
8015
8016 Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
8017 options::OPT_fno_gnu_inline_asm);
8018
8019 handleVectorizeLoopsArgs(Args, CmdArgs);
8020 handleVectorizeSLPArgs(Args, CmdArgs);
8021
8022 StringRef VecWidth = parseMPreferVectorWidthOption(D.getDiags(), Args);
8023 if (!VecWidth.empty())
8024 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + VecWidth));
8025
8026 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
8027 Args.AddLastArg(CmdArgs,
8028 options::OPT_fsanitize_undefined_strip_path_components_EQ);
8029
8030 // -fdollars-in-identifiers default varies depending on platform and
8031 // language; only pass if specified.
8032 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
8033 options::OPT_fno_dollars_in_identifiers)) {
8034 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
8035 CmdArgs.push_back("-fdollars-in-identifiers");
8036 else
8037 CmdArgs.push_back("-fno-dollars-in-identifiers");
8038 }
8039
8040 Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
8041 options::OPT_fno_apple_pragma_pack);
8042
8043 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
8044 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
8045 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
8046
8047 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
8048 options::OPT_fno_rewrite_imports, false);
8049 if (RewriteImports)
8050 CmdArgs.push_back("-frewrite-imports");
8051
8052 Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
8053 options::OPT_fno_directives_only);
8054
8055 // Enable rewrite includes if the user's asked for it or if we're generating
8056 // diagnostics.
8057 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
8058 // nice to enable this when doing a crashdump for modules as well.
8059 if (Args.hasFlag(options::OPT_frewrite_includes,
8060 options::OPT_fno_rewrite_includes, false) ||
8061 (C.isForDiagnostics() && !HaveModules))
8062 CmdArgs.push_back("-frewrite-includes");
8063
8064 if (Args.hasFlag(options::OPT_fzos_extensions,
8065 options::OPT_fno_zos_extensions, false))
8066 CmdArgs.push_back("-fzos-extensions");
8067 else if (Args.hasArg(options::OPT_fno_zos_extensions))
8068 CmdArgs.push_back("-fno-zos-extensions");
8069
8070 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
8071 if (Arg *A = Args.getLastArg(options::OPT_traditional,
8072 options::OPT_traditional_cpp)) {
8074 CmdArgs.push_back("-traditional-cpp");
8075 else
8076 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
8077 }
8078
8079 Args.AddLastArg(CmdArgs, options::OPT_dM);
8080 Args.AddLastArg(CmdArgs, options::OPT_dD);
8081 Args.AddLastArg(CmdArgs, options::OPT_dI);
8082
8083 Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
8084
8085 Args.AddLastArg(CmdArgs, options::OPT__ssaf_extract_summaries);
8086 Args.AddLastArg(CmdArgs, options::OPT__ssaf_tu_summary_file);
8087 Args.AddLastArg(CmdArgs, options::OPT__ssaf_compilation_unit_id);
8088 Args.AddLastArg(CmdArgs, options::OPT__ssaf_include_local_entities);
8089 Args.AddLastArg(CmdArgs, options::OPT__ssaf_no_extract_from_system_headers);
8090 Args.AddLastArg(CmdArgs, options::OPT__ssaf_source_transformation);
8091 Args.AddLastArg(CmdArgs, options::OPT__ssaf_global_scope_analysis_result);
8092 Args.AddLastArg(CmdArgs, options::OPT__ssaf_src_edit_file);
8093 Args.AddLastArg(CmdArgs, options::OPT__ssaf_transformation_report_file);
8094
8095 // Handle serialized diagnostics.
8096 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
8097 CmdArgs.push_back("-serialize-diagnostic-file");
8098 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
8099 }
8100
8101 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
8102 CmdArgs.push_back("-fretain-comments-from-system-headers");
8103
8104 if (Arg *A = Args.getLastArg(options::OPT_fextend_variable_liveness_EQ)) {
8105 A->render(Args, CmdArgs);
8106 } else if (Arg *A = Args.getLastArg(options::OPT_O_Group);
8107 A && A->containsValue("g")) {
8108 // Set -fextend-variable-liveness=all by default at -Og.
8109 CmdArgs.push_back("-fextend-variable-liveness=all");
8110 }
8111
8112 // Forward -fcomment-block-commands to -cc1.
8113 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
8114 // Forward -fparse-all-comments to -cc1.
8115 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
8116
8117 // Turn -fplugin=name.so into -load name.so
8118 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
8119 CmdArgs.push_back("-load");
8120 CmdArgs.push_back(A->getValue());
8121 A->claim();
8122 }
8123
8124 // Turn -fplugin-arg-pluginname-key=value into
8125 // -plugin-arg-pluginname key=value
8126 // GCC has an actual plugin_argument struct with key/value pairs that it
8127 // passes to its plugins, but we don't, so just pass it on as-is.
8128 //
8129 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
8130 // argument key are allowed to contain dashes. GCC therefore only
8131 // allows dashes in the key. We do the same.
8132 for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
8133 auto ArgValue = StringRef(A->getValue());
8134 auto FirstDashIndex = ArgValue.find('-');
8135 StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
8136 StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
8137
8138 A->claim();
8139 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
8140 if (PluginName.empty()) {
8141 D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
8142 } else {
8143 D.Diag(diag::warn_drv_missing_plugin_arg)
8144 << PluginName << A->getAsString(Args);
8145 }
8146 continue;
8147 }
8148
8149 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
8150 CmdArgs.push_back(Args.MakeArgString(Arg));
8151 }
8152
8153 // Forward -fpass-plugin=name.so to -cc1.
8154 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
8155 CmdArgs.push_back(
8156 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
8157 A->claim();
8158 }
8159
8160 // Forward --vfsoverlay to -cc1.
8161 for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {
8162 CmdArgs.push_back("--vfsoverlay");
8163 CmdArgs.push_back(A->getValue());
8164 A->claim();
8165 }
8166
8167 Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,
8168 options::OPT_fno_safe_buffer_usage_suggestions);
8169
8170 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_late_parse_attributes,
8171 options::OPT_fno_experimental_late_parse_attributes);
8172
8173 if (Args.hasFlag(options::OPT_funique_source_file_names,
8174 options::OPT_fno_unique_source_file_names, false)) {
8175 if (Arg *A = Args.getLastArg(options::OPT_unique_source_file_identifier_EQ))
8176 A->render(Args, CmdArgs);
8177 else
8178 CmdArgs.push_back(Args.MakeArgString(
8179 Twine("-funique-source-file-identifier=") + Input.getBaseInput()));
8180 }
8181
8182 if (Args.hasFlag(
8183 options::OPT_fexperimental_allow_pointer_field_protection_attr,
8184 options::OPT_fno_experimental_allow_pointer_field_protection_attr,
8185 false) ||
8186 Args.hasFlag(options::OPT_fexperimental_pointer_field_protection_abi,
8187 options::OPT_fno_experimental_pointer_field_protection_abi,
8188 false))
8189 CmdArgs.push_back("-fexperimental-allow-pointer-field-protection-attr");
8190
8191 if (!IsCudaDevice) {
8192 Args.addOptInFlag(
8193 CmdArgs, options::OPT_fexperimental_pointer_field_protection_abi,
8194 options::OPT_fno_experimental_pointer_field_protection_abi);
8195 Args.addOptInFlag(
8196 CmdArgs, options::OPT_fexperimental_pointer_field_protection_tagged,
8197 options::OPT_fno_experimental_pointer_field_protection_tagged);
8198 }
8199
8200 // Setup statistics file output.
8201 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
8202 if (!StatsFile.empty()) {
8203 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
8205 CmdArgs.push_back("-stats-file-append");
8206 }
8207
8208 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
8209 // parser.
8210 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
8211 Arg->claim();
8212 // -finclude-default-header flag is for preprocessor,
8213 // do not pass it to other cc1 commands when save-temps is enabled
8214 if (C.getDriver().isSaveTempsEnabled() &&
8216 if (StringRef(Arg->getValue()) == "-finclude-default-header")
8217 continue;
8218 }
8219 CmdArgs.push_back(Arg->getValue());
8220 }
8221 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
8222 A->claim();
8223
8224 // We translate this by hand to the -cc1 argument, since nightly test uses
8225 // it and developers have been trained to spell it with -mllvm. Both
8226 // spellings are now deprecated and should be removed.
8227 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
8228 CmdArgs.push_back("-disable-llvm-optzns");
8229 } else {
8230 A->render(Args, CmdArgs);
8231 }
8232 }
8233
8234 // This needs to run after -Xclang argument forwarding to pick up the target
8235 // features enabled through -Xclang -target-feature flags.
8236 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
8237
8238 Args.AddLastArg(CmdArgs, options::OPT_falloc_token_max_EQ);
8239
8240#if CLANG_ENABLE_CIR
8241 // Forward -mmlir arguments to to the MLIR option parser.
8242 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
8243 A->claim();
8244 A->render(Args, CmdArgs);
8245 }
8246#endif // CLANG_ENABLE_CIR
8247
8248 // With -save-temps, we want to save the unoptimized bitcode output from the
8249 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
8250 // by the frontend.
8251 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
8252 // has slightly different breakdown between stages.
8253 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
8254 // pristine IR generated by the frontend. Ideally, a new compile action should
8255 // be added so both IR can be captured.
8256 if ((C.getDriver().isSaveTempsEnabled() ||
8258 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
8260 CmdArgs.push_back("-disable-llvm-passes");
8261
8262 Args.AddAllArgs(CmdArgs, options::OPT_undef);
8263
8264 const char *Exec = D.getDriverProgramPath();
8265
8266 // Optionally embed the -cc1 level arguments into the debug info or a
8267 // section, for build analysis.
8268 // Also record command line arguments into the debug info if
8269 // -grecord-gcc-switches options is set on.
8270 // By default, -gno-record-gcc-switches is set on and no recording.
8271 auto GRecordSwitches = false;
8272 auto FRecordSwitches = false;
8273 bool DXRecordSwitches = false;
8274 if (shouldRecordCommandLine(TC, Args, FRecordSwitches, GRecordSwitches,
8275 DXRecordSwitches)) {
8276 auto FlagsArgString = renderEscapedCommandLine(TC, Args);
8277 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
8278 CmdArgs.push_back("-dwarf-debug-flags");
8279 CmdArgs.push_back(FlagsArgString);
8280 }
8281 if (FRecordSwitches) {
8282 CmdArgs.push_back("-record-command-line");
8283 CmdArgs.push_back(FlagsArgString);
8284 }
8285 if (DXRecordSwitches) {
8286 CmdArgs.push_back("-fdx-record-command-line");
8287 CmdArgs.push_back(FlagsArgString);
8288 }
8289 }
8290
8291 // Host-side offloading compilation receives all device-side outputs. Include
8292 // them in the host compilation depending on the target. If the host inputs
8293 // are not empty we use the new-driver scheme, otherwise use the old scheme.
8294 if ((IsCuda || IsHIP) && CudaDeviceInput) {
8295 CmdArgs.push_back("-fcuda-include-gpubinary");
8296 CmdArgs.push_back(CudaDeviceInput->getFilename());
8297 } else if (!HostOffloadingInputs.empty()) {
8298 if ((IsCuda || IsHIP) && !IsRDCMode) {
8299 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
8300 CmdArgs.push_back("-fcuda-include-gpubinary");
8301 CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
8302 } else {
8303 for (const InputInfo Input : HostOffloadingInputs)
8304 CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
8305 TC.getInputFilename(Input)));
8306 }
8307 }
8308
8309 if (IsCuda) {
8310 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
8311 options::OPT_fno_cuda_short_ptr, false))
8312 CmdArgs.push_back("-fcuda-short-ptr");
8313 }
8314
8315 if (IsCuda || IsHIP) {
8316 // Determine the original source input.
8317 const Action *SourceAction = &JA;
8318 while (SourceAction->getKind() != Action::InputClass) {
8319 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
8320 SourceAction = SourceAction->getInputs()[0];
8321 }
8322 auto CUID = cast<InputAction>(SourceAction)->getId();
8323 if (!CUID.empty())
8324 CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
8325
8326 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
8327 // be overriden by -fno-gpu-approx-transcendentals.
8328 bool UseApproxTranscendentals = Args.hasFlag(
8329 options::OPT_ffast_math, options::OPT_fno_fast_math, false);
8330 if (Args.hasFlag(options::OPT_fgpu_approx_transcendentals,
8331 options::OPT_fno_gpu_approx_transcendentals,
8332 UseApproxTranscendentals))
8333 CmdArgs.push_back("-fgpu-approx-transcendentals");
8334 } else {
8335 Args.claimAllArgs(options::OPT_fgpu_approx_transcendentals,
8336 options::OPT_fno_gpu_approx_transcendentals);
8337 }
8338
8339 if (IsHIP) {
8340 CmdArgs.push_back("-fcuda-allow-variadic-functions");
8341 Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
8342 }
8343
8344 Args.AddAllArgs(CmdArgs,
8345 options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);
8346
8347 Args.AddLastArg(CmdArgs, options::OPT_foffload_uniform_block,
8348 options::OPT_fno_offload_uniform_block);
8349
8350 Args.AddLastArg(CmdArgs, options::OPT_foffload_implicit_host_device_templates,
8351 options::OPT_fno_offload_implicit_host_device_templates);
8352
8353 if (IsCudaDevice || IsHIPDevice) {
8354 StringRef InlineThresh =
8355 Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
8356 if (!InlineThresh.empty()) {
8357 std::string ArgStr =
8358 std::string("-inline-threshold=") + InlineThresh.str();
8359 CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
8360 }
8361 }
8362
8363 if (IsHIPDevice)
8364 Args.addOptOutFlag(CmdArgs,
8365 options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
8366 options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
8367
8368 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
8369 // to specify the result of the compile phase on the host, so the meaningful
8370 // device declarations can be identified. Also, -fopenmp-is-target-device is
8371 // passed along to tell the frontend that it is generating code for a device,
8372 // so that only the relevant declarations are emitted.
8373 if (IsOpenMPDevice) {
8374 CmdArgs.push_back("-fopenmp-is-target-device");
8375 // If we are offloading cuda/hip via llvm, it's also "cuda device code".
8376 if (Args.hasArg(options::OPT_foffload_via_llvm))
8377 CmdArgs.push_back("-fcuda-is-device");
8378
8379 if (OpenMPDeviceInput) {
8380 CmdArgs.push_back("-fopenmp-host-ir-file-path");
8381 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
8382 }
8383 }
8384
8385 if (Triple.isAMDGPU() ||
8386 (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD)) {
8387 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
8388
8389 Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
8390 options::OPT_mno_unsafe_fp_atomics);
8391 Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,
8392 options::OPT_mno_amdgpu_ieee);
8393 }
8394
8395 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
8396
8397 if (Args.hasFlag(options::OPT_fdevirtualize_speculatively,
8398 options::OPT_fno_devirtualize_speculatively,
8399 /*Default value*/ false))
8400 CmdArgs.push_back("-fdevirtualize-speculatively");
8401
8402 bool VirtualFunctionElimination =
8403 Args.hasFlag(options::OPT_fvirtual_function_elimination,
8404 options::OPT_fno_virtual_function_elimination, false);
8405 if (VirtualFunctionElimination) {
8406 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
8407 // in the future).
8408 if (LTOMode != LTOK_Full)
8409 D.Diag(diag::err_drv_argument_only_allowed_with)
8410 << "-fvirtual-function-elimination"
8411 << "-flto=full";
8412
8413 CmdArgs.push_back("-fvirtual-function-elimination");
8414 }
8415
8416 // VFE requires whole-program-vtables, and enables it by default.
8417 bool WholeProgramVTables = Args.hasFlag(
8418 options::OPT_fwhole_program_vtables,
8419 options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
8420 if (VirtualFunctionElimination && !WholeProgramVTables) {
8421 D.Diag(diag::err_drv_argument_not_allowed_with)
8422 << "-fno-whole-program-vtables"
8423 << "-fvirtual-function-elimination";
8424 }
8425
8426 if (WholeProgramVTables) {
8427 // PS4 uses the legacy LTO API, which does not support this feature in
8428 // ThinLTO mode.
8429 bool IsPS4 = getToolChain().getTriple().isPS4();
8430
8431 // Check if we passed LTO options but they were suppressed because this is a
8432 // device offloading action, or we passed device offload LTO options which
8433 // were suppressed because this is not the device offload action.
8434 // Check if we are using PS4 in regular LTO mode.
8435 // Otherwise, issue an error.
8436
8437 auto OtherLTOMode = TC.getLTOMode(
8438 Args, IsDeviceOffloadAction ? Action::OFK_None
8439 : static_cast<Action::OffloadKind>(
8440 C.getActiveOffloadKinds()));
8441 auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;
8442
8443 if ((!IsUsingLTO && !OtherIsUsingLTO) ||
8444 (IsPS4 && !UnifiedLTO && (TC.getLTOMode(Args) != LTOK_Full)))
8445 D.Diag(diag::err_drv_argument_only_allowed_with)
8446 << "-fwhole-program-vtables"
8447 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
8448
8449 // Propagate -fwhole-program-vtables if this is an LTO compile.
8450 if (IsUsingLTO)
8451 CmdArgs.push_back("-fwhole-program-vtables");
8452 }
8453
8454 bool DefaultsSplitLTOUnit =
8455 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
8456 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
8457 (!Triple.isPS4() && UnifiedLTO);
8458 bool SplitLTOUnit =
8459 Args.hasFlag(options::OPT_fsplit_lto_unit,
8460 options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
8461 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
8462 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
8463 << "-fsanitize=cfi";
8464 if (SplitLTOUnit)
8465 CmdArgs.push_back("-fsplit-lto-unit");
8466
8467 if (Arg *A = Args.getLastArg(options::OPT_ffat_lto_objects,
8468 options::OPT_fno_fat_lto_objects)) {
8469 if (IsUsingLTO && A->getOption().matches(options::OPT_ffat_lto_objects)) {
8470 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
8471 if (!Triple.isOSBinFormatELF() && !Triple.isOSBinFormatCOFF()) {
8472 D.Diag(diag::err_drv_unsupported_opt_for_target)
8473 << A->getAsString(Args) << TC.getTripleString();
8474 }
8475 CmdArgs.push_back(Args.MakeArgString(
8476 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
8477 CmdArgs.push_back("-flto-unit");
8478 CmdArgs.push_back("-ffat-lto-objects");
8479 A->render(Args, CmdArgs);
8480 }
8481 }
8482
8483 renderGlobalISelOptions(D, Args, CmdArgs, Triple);
8484
8485 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
8486 options::OPT_fno_force_enable_int128)) {
8487 if (A->getOption().matches(options::OPT_fforce_enable_int128))
8488 CmdArgs.push_back("-fforce-enable-int128");
8489 }
8490
8491 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
8492 options::OPT_fno_keep_static_consts);
8493 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,
8494 options::OPT_fno_keep_persistent_storage_variables);
8495 Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
8496 options::OPT_fno_complete_member_pointers);
8497 if (Arg *A = Args.getLastArg(options::OPT_cxx_static_destructors_EQ))
8498 A->render(Args, CmdArgs);
8499
8500 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
8501
8502 addOutlineAtomicsArgs(D, getToolChain(), Args, CmdArgs, Triple);
8503
8504 if (Triple.isAArch64() &&
8505 (Args.hasArg(options::OPT_mno_fmv) ||
8506 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
8507 // Disable Function Multiversioning on AArch64 target.
8508 CmdArgs.push_back("-target-feature");
8509 CmdArgs.push_back("-fmv");
8510 }
8511
8512 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
8513 (TC.getTriple().isOSBinFormatELF() ||
8514 TC.getTriple().isOSBinFormatCOFF()) &&
8515 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
8516 !TC.getTriple().isOSNetBSD() &&
8517 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
8518 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
8519 CmdArgs.push_back("-faddrsig");
8520
8521 const bool HasDefaultDwarf2CFIASM =
8522 (Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
8523 (EH || UnwindTables || AsyncUnwindTables ||
8524 DebugInfoKind != llvm::codegenoptions::NoDebugInfo);
8525 if (Args.hasFlag(options::OPT_fdwarf2_cfi_asm,
8526 options::OPT_fno_dwarf2_cfi_asm, HasDefaultDwarf2CFIASM))
8527 CmdArgs.push_back("-fdwarf2-cfi-asm");
8528
8529 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
8530 std::string Str = A->getAsString(Args);
8531 if (!TC.getTriple().isOSBinFormatELF())
8532 D.Diag(diag::err_drv_unsupported_opt_for_target)
8533 << Str << TC.getTripleString();
8534 CmdArgs.push_back(Args.MakeArgString(Str));
8535 }
8536
8537 // Add the "-o out -x type src.c" flags last. This is done primarily to make
8538 // the -cc1 command easier to edit when reproducing compiler crashes.
8539 if (Output.getType() == types::TY_Dependencies) {
8540 // Handled with other dependency code.
8541 } else if (Output.isFilename()) {
8542 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
8543 Output.getType() == clang::driver::types::TY_IFS) {
8544 SmallString<128> OutputFilename(Output.getFilename());
8545 llvm::sys::path::replace_extension(OutputFilename, "ifs");
8546 CmdArgs.push_back("-o");
8547 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
8548 } else {
8549 CmdArgs.push_back("-o");
8550 CmdArgs.push_back(Output.getFilename());
8551 }
8552 } else {
8553 assert(Output.isNothing() && "Invalid output.");
8554 }
8555
8556 addDashXForInput(Args, Input, CmdArgs);
8557
8558 ArrayRef<InputInfo> FrontendInputs = Input;
8559 if (IsExtractAPI)
8560 FrontendInputs = ExtractAPIInputs;
8561 else if (Input.isNothing())
8562 FrontendInputs = {};
8563
8564 for (const InputInfo &Input : FrontendInputs) {
8565 if (Input.isFilename())
8566 CmdArgs.push_back(Input.getFilename());
8567 else
8568 Input.getInputArg().renderAsInput(Args, CmdArgs);
8569 }
8570
8571 if (D.CC1Main && !D.CCGenDiagnostics) {
8572 // Invoke the CC1 directly in this process
8573 C.addCommand(std::make_unique<CC1Command>(
8574 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8575 Output, D.getPrependArg()));
8576 } else {
8577 C.addCommand(std::make_unique<Command>(
8578 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8579 Output, D.getPrependArg()));
8580 }
8581
8582 // Make the compile command echo its inputs for /showFilenames.
8583 if (Output.getType() == types::TY_Object &&
8584 Args.hasFlag(options::OPT__SLASH_showFilenames,
8585 options::OPT__SLASH_showFilenames_, false)) {
8586 C.getJobs().getJobs().back()->PrintInputFilenames = true;
8587 }
8588
8589 if (Arg *A = Args.getLastArg(options::OPT_pg))
8590 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
8591 !Args.hasArg(options::OPT_mfentry))
8592 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
8593 << A->getAsString(Args);
8594
8595 // Claim some arguments which clang supports automatically.
8596
8597 // -fpch-preprocess is used with gcc to add a special marker in the output to
8598 // include the PCH file.
8599 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
8600
8601 // Claim some arguments which clang doesn't support, but we don't
8602 // care to warn the user about.
8603 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
8604 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
8605
8606 // Disable warnings for clang -E -emit-llvm foo.c
8607 Args.ClaimAllArgs(options::OPT_emit_llvm);
8608}
8609
8610Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
8611 // CAUTION! The first constructor argument ("clang") is not arbitrary,
8612 // as it is for other tools. Some operations on a Tool actually test
8613 // whether that tool is Clang based on the Tool's Name as a string.
8614 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
8615
8617
8618/// Add options related to the Objective-C runtime/ABI.
8619///
8620/// Returns true if the runtime is non-fragile.
8621ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
8622 const InputInfoList &inputs,
8623 ArgStringList &cmdArgs,
8624 RewriteKind rewriteKind) const {
8625 // Look for the controlling runtime option.
8626 Arg *runtimeArg =
8627 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
8628 options::OPT_fobjc_runtime_EQ);
8629
8630 // Just forward -fobjc-runtime= to the frontend. This supercedes
8631 // options about fragility.
8632 if (runtimeArg &&
8633 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
8634 ObjCRuntime runtime;
8635 StringRef value = runtimeArg->getValue();
8636 if (runtime.tryParse(value)) {
8637 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
8638 << value;
8639 }
8640 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
8641 (runtime.getVersion() >= VersionTuple(2, 0)))
8642 if (!getToolChain().getTriple().isOSBinFormatELF() &&
8643 !getToolChain().getTriple().isOSBinFormatCOFF()) {
8645 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
8646 << runtime.getVersion().getMajor();
8647 }
8648
8649 runtimeArg->render(args, cmdArgs);
8650 return runtime;
8651 }
8652
8653 // Otherwise, we'll need the ABI "version". Version numbers are
8654 // slightly confusing for historical reasons:
8655 // 1 - Traditional "fragile" ABI
8656 // 2 - Non-fragile ABI, version 1
8657 // 3 - Non-fragile ABI, version 2
8658 unsigned objcABIVersion = 1;
8659 // If -fobjc-abi-version= is present, use that to set the version.
8660 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
8661 StringRef value = abiArg->getValue();
8662 if (value == "1")
8663 objcABIVersion = 1;
8664 else if (value == "2")
8665 objcABIVersion = 2;
8666 else if (value == "3")
8667 objcABIVersion = 3;
8668 else
8669 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
8670 } else {
8671 // Otherwise, determine if we are using the non-fragile ABI.
8672 bool nonFragileABIIsDefault =
8673 (rewriteKind == RK_NonFragile ||
8674 (rewriteKind == RK_None &&
8676 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
8677 options::OPT_fno_objc_nonfragile_abi,
8678 nonFragileABIIsDefault)) {
8679// Determine the non-fragile ABI version to use.
8680#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
8681 unsigned nonFragileABIVersion = 1;
8682#else
8683 unsigned nonFragileABIVersion = 2;
8684#endif
8685
8686 if (Arg *abiArg =
8687 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
8688 StringRef value = abiArg->getValue();
8689 if (value == "1")
8690 nonFragileABIVersion = 1;
8691 else if (value == "2")
8692 nonFragileABIVersion = 2;
8693 else
8694 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
8695 << value;
8696 }
8697
8698 objcABIVersion = 1 + nonFragileABIVersion;
8699 } else {
8700 objcABIVersion = 1;
8701 }
8702 }
8703
8704 // We don't actually care about the ABI version other than whether
8705 // it's non-fragile.
8706 bool isNonFragile = objcABIVersion != 1;
8707
8708 // If we have no runtime argument, ask the toolchain for its default runtime.
8709 // However, the rewriter only really supports the Mac runtime, so assume that.
8710 ObjCRuntime runtime;
8711 if (!runtimeArg) {
8712 switch (rewriteKind) {
8713 case RK_None:
8714 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8715 break;
8716 case RK_Fragile:
8717 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
8718 break;
8719 case RK_NonFragile:
8720 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8721 break;
8722 }
8723
8724 // -fnext-runtime
8725 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
8726 // On Darwin, make this use the default behavior for the toolchain.
8727 if (getToolChain().getTriple().isOSDarwin()) {
8728 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8729
8730 // Otherwise, build for a generic macosx port.
8731 } else {
8732 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8733 }
8734
8735 // -fgnu-runtime
8736 } else {
8737 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
8738 // Legacy behaviour is to target the gnustep runtime if we are in
8739 // non-fragile mode or the GCC runtime in fragile mode.
8740 if (isNonFragile)
8741 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
8742 else
8743 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
8744 }
8745
8746 if (llvm::any_of(inputs, [](const InputInfo &input) {
8747 return types::isObjC(input.getType());
8748 }))
8749 cmdArgs.push_back(
8750 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
8751 return runtime;
8752}
8753
8754static bool maybeConsumeDash(const std::string &EH, size_t &I) {
8755 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
8756 I += HaveDash;
8757 return !HaveDash;
8758}
8759
8760namespace {
8761struct EHFlags {
8762 bool Synch = false;
8763 bool Asynch = false;
8764 bool NoUnwindC = false;
8765};
8766} // end anonymous namespace
8767
8768/// /EH controls whether to run destructor cleanups when exceptions are
8769/// thrown. There are three modifiers:
8770/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
8771/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
8772/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
8773/// - c: Assume that extern "C" functions are implicitly nounwind.
8774/// The default is /EHs-c-, meaning cleanups are disabled.
8775static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
8776 bool isWindowsMSVC) {
8777 EHFlags EH;
8778
8779 std::vector<std::string> EHArgs =
8780 Args.getAllArgValues(options::OPT__SLASH_EH);
8781 for (const auto &EHVal : EHArgs) {
8782 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
8783 switch (EHVal[I]) {
8784 case 'a':
8785 EH.Asynch = maybeConsumeDash(EHVal, I);
8786 if (EH.Asynch) {
8787 // Async exceptions are Windows MSVC only.
8788 if (!isWindowsMSVC) {
8789 EH.Asynch = false;
8790 D.Diag(clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
8791 continue;
8792 }
8793 EH.Synch = false;
8794 }
8795 continue;
8796 case 'c':
8797 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
8798 continue;
8799 case 's':
8800 EH.Synch = maybeConsumeDash(EHVal, I);
8801 if (EH.Synch)
8802 EH.Asynch = false;
8803 continue;
8804 default:
8805 break;
8806 }
8807 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
8808 break;
8809 }
8810 }
8811 // The /GX, /GX- flags are only processed if there are not /EH flags.
8812 // The default is that /GX is not specified.
8813 if (EHArgs.empty() &&
8814 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
8815 /*Default=*/false)) {
8816 EH.Synch = true;
8817 EH.NoUnwindC = true;
8818 }
8819
8820 if (Args.hasArg(options::OPT__SLASH_kernel)) {
8821 EH.Synch = false;
8822 EH.NoUnwindC = false;
8823 EH.Asynch = false;
8824 }
8825
8826 return EH;
8827}
8828
8829void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
8830 ArgStringList &CmdArgs) const {
8831 bool isNVPTX = getToolChain().getTriple().isNVPTX();
8832
8833 ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
8834
8835 if (Arg *ShowIncludes =
8836 Args.getLastArg(options::OPT__SLASH_showIncludes,
8837 options::OPT__SLASH_showIncludes_user)) {
8838 CmdArgs.push_back("--show-includes");
8839 if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
8840 CmdArgs.push_back("-sys-header-deps");
8841 }
8842
8843 // This controls whether or not we emit RTTI data for polymorphic types.
8844 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
8845 /*Default=*/false))
8846 CmdArgs.push_back("-fno-rtti-data");
8847
8848 // This controls whether or not we emit stack-protector instrumentation.
8849 // In MSVC, Buffer Security Check (/GS) is on by default.
8850 if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
8851 /*Default=*/true)) {
8852 CmdArgs.push_back("-stack-protector");
8853 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
8854 }
8855
8856 const Driver &D = getToolChain().getDriver();
8857
8858 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
8859 EHFlags EH = parseClangCLEHFlags(D, Args, IsWindowsMSVC);
8860 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
8861 if (types::isCXX(InputType))
8862 CmdArgs.push_back("-fcxx-exceptions");
8863 CmdArgs.push_back("-fexceptions");
8864 if (EH.Asynch)
8865 CmdArgs.push_back("-fasync-exceptions");
8866 }
8867 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
8868 CmdArgs.push_back("-fexternc-nounwind");
8869
8870 // /EP should expand to -E -P.
8871 if (Args.hasArg(options::OPT__SLASH_EP)) {
8872 CmdArgs.push_back("-E");
8873 CmdArgs.push_back("-P");
8874 }
8875
8876 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
8877 options::OPT__SLASH_Zc_dllexportInlines,
8878 false)) {
8879 CmdArgs.push_back("-fno-dllexport-inlines");
8880 }
8881
8882 if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
8883 options::OPT__SLASH_Zc_wchar_t, false)) {
8884 CmdArgs.push_back("-fno-wchar");
8885 }
8886
8887 if (Args.hasArg(options::OPT__SLASH_kernel)) {
8888 llvm::Triple::ArchType Arch = getToolChain().getArch();
8889 std::vector<std::string> Values =
8890 Args.getAllArgValues(options::OPT__SLASH_arch);
8891 if (!Values.empty()) {
8892 llvm::SmallSet<std::string, 4> SupportedArches;
8893 if (Arch == llvm::Triple::x86)
8894 SupportedArches.insert("IA32");
8895
8896 for (auto &V : Values)
8897 if (!SupportedArches.contains(V))
8898 D.Diag(diag::err_drv_argument_not_allowed_with)
8899 << std::string("/arch:").append(V) << "/kernel";
8900 }
8901
8902 CmdArgs.push_back("-fno-rtti");
8903 if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
8904 D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
8905 << "/kernel";
8906 }
8907
8908 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_vlen,
8909 options::OPT__SLASH_vlen_EQ_256,
8910 options::OPT__SLASH_vlen_EQ_512)) {
8911 llvm::Triple::ArchType AT = getToolChain().getArch();
8912 StringRef Default = AT == llvm::Triple::x86 ? "IA32" : "SSE2";
8913 StringRef Arch = Args.getLastArgValue(options::OPT__SLASH_arch, Default);
8914 llvm::SmallSet<StringRef, 4> Arch512 = {"AVX512F", "AVX512", "AVX10.1",
8915 "AVX10.2"};
8916
8917 if (A->getOption().matches(options::OPT__SLASH_vlen_EQ_512)) {
8918 if (Arch512.contains(Arch))
8919 CmdArgs.push_back("-mprefer-vector-width=512");
8920 else
8921 D.Diag(diag::warn_drv_argument_not_allowed_with)
8922 << "/vlen=512" << std::string("/arch:").append(Arch);
8923 } else if (A->getOption().matches(options::OPT__SLASH_vlen_EQ_256)) {
8924 if (Arch512.contains(Arch))
8925 CmdArgs.push_back("-mprefer-vector-width=256");
8926 else if (Arch != "AVX" && Arch != "AVX2")
8927 D.Diag(diag::warn_drv_argument_not_allowed_with)
8928 << "/vlen=256" << std::string("/arch:").append(Arch);
8929 } else {
8930 if (Arch == "AVX10.1" || Arch == "AVX10.2")
8931 CmdArgs.push_back("-mprefer-vector-width=256");
8932 }
8933 } else {
8934 StringRef Arch = Args.getLastArgValue(options::OPT__SLASH_arch);
8935 if (Arch == "AVX10.1" || Arch == "AVX10.2") {
8936 CmdArgs.push_back("-mprefer-vector-width=256");
8937 CmdArgs.push_back("-target-feature");
8938 CmdArgs.push_back("-amx-tile");
8939 }
8940 if (Arch == "AVX10.2") {
8941 CmdArgs.push_back("-target-feature");
8942 CmdArgs.push_back("+avx10.2");
8943 }
8944 }
8945
8946 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
8947 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
8948 if (MostGeneralArg && BestCaseArg)
8949 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
8950 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
8951
8952 if (MostGeneralArg) {
8953 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
8954 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
8955 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
8956
8957 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
8958 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
8959 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
8960 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
8961 << FirstConflict->getAsString(Args)
8962 << SecondConflict->getAsString(Args);
8963
8964 if (SingleArg)
8965 CmdArgs.push_back("-fms-memptr-rep=single");
8966 else if (MultipleArg)
8967 CmdArgs.push_back("-fms-memptr-rep=multiple");
8968 else
8969 CmdArgs.push_back("-fms-memptr-rep=virtual");
8970 }
8971
8972 if (Args.hasArg(options::OPT_regcall4))
8973 CmdArgs.push_back("-regcall4");
8974
8975 // Parse the default calling convention options.
8976 if (Arg *CCArg =
8977 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
8978 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
8979 options::OPT__SLASH_Gregcall)) {
8980 unsigned DCCOptId = CCArg->getOption().getID();
8981 const char *DCCFlag = nullptr;
8982 bool ArchSupported = !isNVPTX;
8983 llvm::Triple::ArchType Arch = getToolChain().getArch();
8984 switch (DCCOptId) {
8985 case options::OPT__SLASH_Gd:
8986 DCCFlag = "-fdefault-calling-conv=cdecl";
8987 break;
8988 case options::OPT__SLASH_Gr:
8989 ArchSupported = Arch == llvm::Triple::x86;
8990 DCCFlag = "-fdefault-calling-conv=fastcall";
8991 break;
8992 case options::OPT__SLASH_Gz:
8993 ArchSupported = Arch == llvm::Triple::x86;
8994 DCCFlag = "-fdefault-calling-conv=stdcall";
8995 break;
8996 case options::OPT__SLASH_Gv:
8997 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8998 DCCFlag = "-fdefault-calling-conv=vectorcall";
8999 break;
9000 case options::OPT__SLASH_Gregcall:
9001 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
9002 DCCFlag = "-fdefault-calling-conv=regcall";
9003 break;
9004 }
9005
9006 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
9007 if (ArchSupported && DCCFlag)
9008 CmdArgs.push_back(DCCFlag);
9009 }
9010
9011 if (Args.hasArg(options::OPT__SLASH_Gregcall4))
9012 CmdArgs.push_back("-regcall4");
9013
9014 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
9015
9016 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
9017 CmdArgs.push_back("-fdiagnostics-format");
9018 CmdArgs.push_back("msvc");
9019 }
9020
9021 if (Args.hasArg(options::OPT__SLASH_kernel))
9022 CmdArgs.push_back("-fms-kernel");
9023
9024 // Unwind v2 (epilog) information for x64 Windows. MSVC's behavior is not
9025 // order-dependent: /d2epilogunwindrequirev2 always wins over /d2epilogunwind.
9026 if (Args.hasArg(options::OPT__SLASH_d2epilogunwindrequirev2))
9027 CmdArgs.push_back("-fwinx64-eh-unwind=v2-required");
9028 else if (Args.hasArg(options::OPT__SLASH_d2epilogunwind))
9029 CmdArgs.push_back("-fwinx64-eh-unwind=v2-best-effort");
9030
9031 // Handle the various /guard options. We don't immediately push back clang
9032 // args since there are /d2 args that can modify the behavior of /guard:cf.
9033 bool HasCFGuard = false;
9034 bool HasCFGuardNoChecks = false;
9035 for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
9036 StringRef GuardArgs = A->getValue();
9037 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
9038 // "ehcont-".
9039 if (GuardArgs.equals_insensitive("cf")) {
9040 // Emit CFG instrumentation and the table of address-taken functions.
9041 HasCFGuard = true;
9042 HasCFGuardNoChecks = false;
9043 } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
9044 // Emit only the table of address-taken functions.
9045 HasCFGuard = false;
9046 HasCFGuardNoChecks = true;
9047 } else if (GuardArgs.equals_insensitive("ehcont")) {
9048 // Emit EH continuation table.
9049 CmdArgs.push_back("-ehcontguard");
9050 } else if (GuardArgs.equals_insensitive("cf-") ||
9051 GuardArgs.equals_insensitive("ehcont-")) {
9052 // Do nothing, but we might want to emit a security warning in future.
9053 } else {
9054 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
9055 }
9056 A->claim();
9057 }
9058
9059 // /d2guardnochecks downgrades /guard:cf to /guard:cf,nochecks (table only).
9060 // If CFG is not enabled, it is a no-op.
9061 if (Args.hasArg(options::OPT__SLASH_d2guardnochecks)) {
9062 if (HasCFGuard) {
9063 HasCFGuard = false;
9064 HasCFGuardNoChecks = true;
9065 }
9066 }
9067
9068 if (HasCFGuard)
9069 CmdArgs.push_back("-cfguard");
9070 else if (HasCFGuardNoChecks)
9071 CmdArgs.push_back("-cfguard-no-checks");
9072
9073 // Control Flow Guard mechanism for Windows.
9074 if (Args.hasArg(options::OPT__SLASH_d2guardcfgdispatch_))
9075 CmdArgs.push_back("-fwin-cfg-mechanism=check");
9076 else if (Args.hasArg(options::OPT__SLASH_d2guardcfgdispatch))
9077 CmdArgs.push_back("-fwin-cfg-mechanism=dispatch");
9078
9079 for (const auto &FuncOverride :
9080 Args.getAllArgValues(options::OPT__SLASH_funcoverride)) {
9081 CmdArgs.push_back(Args.MakeArgString(
9082 Twine("-loader-replaceable-function=") + FuncOverride));
9083 }
9084
9085 if (Args.hasArg(options::OPT__SLASH_experimental_deterministic)) {
9086 CmdArgs.push_back("-Wdate-time");
9087
9088 if (Args.hasArg(options::OPT_mincremental_linker_compatible)) {
9089 D.Diag(diag::err_drv_argument_not_allowed_with)
9090 << "/experimental:deterministic"
9091 << "/Brepro-";
9092 }
9093 // CL's sets COFF's OBJ timestamp to a hash of the source file path to get
9094 // deterministic result, but we force this timestamp to 0, which also
9095 // produces deterministic result.
9096 CmdArgs.push_back("-mno-incremental-linker-compatible");
9097 }
9098
9099 bool HasNoDateTime = Args.hasFlag(options::OPT__SLASH_d1nodatetime,
9100 options::OPT__SLASH_d1nodatetime_, false);
9101
9102 if (HasNoDateTime)
9103 CmdArgs.push_back("-init-datetime-macros=undefined");
9104
9105 // /Brepro is an alias for -mincremental-linker-compatible option.
9106 if (!Args.hasFlag(options::OPT_mincremental_linker_compatible,
9107 options::OPT_mno_incremental_linker_compatible,
9108 getToolChain()
9109 .getTriple()
9110 .isDefaultIncrementalLinkerCompatibleByDefault())) {
9111 // Redefine the date/time macros only if /d1nodatetime wasn't specified.
9112 // This option does not allow the user redefinitions for these macros.
9113 if (!HasNoDateTime)
9114 CmdArgs.push_back("-init-datetime-macros=literalone");
9115 }
9116}
9117
9118const char *Clang::getBaseInputName(const ArgList &Args,
9119 const InputInfo &Input) {
9120 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
9121}
9122
9123const char *Clang::getBaseInputStem(const ArgList &Args,
9124 const InputInfoList &Inputs) {
9125 const char *Str = getBaseInputName(Args, Inputs[0]);
9126
9127 if (const char *End = strrchr(Str, '.'))
9128 return Args.MakeArgString(std::string(Str, End));
9129
9130 return Str;
9131}
9132
9133const char *Clang::getDependencyFileName(const ArgList &Args,
9134 const InputInfoList &Inputs) {
9135 // FIXME: Think about this more.
9136
9137 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
9138 SmallString<128> OutputFilename(OutputOpt->getValue());
9139 llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
9140 return Args.MakeArgString(OutputFilename);
9141 }
9142
9143 return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
9144}
9145
9146// Begin ClangAs
9147
9148void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
9149 ArgStringList &CmdArgs) const {
9150 StringRef CPUName;
9151 StringRef ABIName;
9152 const llvm::Triple &Triple = getToolChain().getTriple();
9153 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
9154
9155 CmdArgs.push_back("-target-abi");
9156 CmdArgs.push_back(ABIName.data());
9157}
9158
9159void ClangAs::AddX86TargetArgs(const ArgList &Args,
9160 ArgStringList &CmdArgs) const {
9161 addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
9162 /*IsLTO=*/false);
9163
9164 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
9165 StringRef Value = A->getValue();
9166 if (Value == "intel" || Value == "att") {
9167 CmdArgs.push_back("-mllvm");
9168 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
9169 } else {
9170 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
9171 << A->getSpelling() << Value;
9172 }
9173 }
9174}
9175
9176void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
9177 ArgStringList &CmdArgs) const {
9178 CmdArgs.push_back("-target-abi");
9179 CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
9181 .data());
9182}
9183
9184void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
9185 ArgStringList &CmdArgs) const {
9186 const llvm::Triple &Triple = getToolChain().getTriple();
9187 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
9188
9189 CmdArgs.push_back("-target-abi");
9190 CmdArgs.push_back(ABIName.data());
9191
9192 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9193 options::OPT_mno_default_build_attributes, true)) {
9194 CmdArgs.push_back("-mllvm");
9195 CmdArgs.push_back("-riscv-add-build-attributes");
9196 }
9197}
9198
9200 const InputInfo &Output, const InputInfoList &Inputs,
9201 const ArgList &Args,
9202 const char *LinkingOutput) const {
9203 ArgStringList CmdArgs;
9204
9205 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
9206 const InputInfo &Input = Inputs[0];
9207
9208 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
9209 const std::string &TripleStr = Triple.getTriple();
9210 const auto &D = getToolChain().getDriver();
9211
9212 // Don't warn about "clang -w -c foo.s"
9213 Args.ClaimAllArgs(options::OPT_w);
9214 // and "clang -emit-llvm -c foo.s"
9215 Args.ClaimAllArgs(options::OPT_emit_llvm);
9216
9217 claimNoWarnArgs(Args);
9218
9219 // Invoke ourselves in -cc1as mode.
9220 //
9221 // FIXME: Implement custom jobs for internal actions.
9222 CmdArgs.push_back("-cc1as");
9223
9224 // Add the "effective" target triple.
9225 CmdArgs.push_back("-triple");
9226 CmdArgs.push_back(Args.MakeArgString(TripleStr));
9227
9229
9230 // Set the output mode, we currently only expect to be used as a real
9231 // assembler.
9232 CmdArgs.push_back("-filetype");
9233 CmdArgs.push_back("obj");
9234
9235 // Set the main file name, so that debug info works even with
9236 // -save-temps or preprocessed assembly.
9237 CmdArgs.push_back("-main-file-name");
9238 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
9239
9240 // Add the target cpu
9241 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
9242 if (!CPU.empty()) {
9243 CmdArgs.push_back("-target-cpu");
9244 CmdArgs.push_back(Args.MakeArgString(CPU));
9245 }
9246
9247 // Add the target features
9248 getTargetFeatures(D, Triple, Args, CmdArgs, true);
9249
9250 // Ignore explicit -force_cpusubtype_ALL option.
9251 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
9252
9253 // Pass along any -I options so we get proper .include search paths.
9254 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
9255
9256 // Pass along any --embed-dir or similar options so we get proper embed paths.
9257 Args.AddAllArgs(CmdArgs, options::OPT_embed_dir_EQ);
9258
9259 // Determine the original source input.
9260 auto FindSource = [](const Action *S) -> const Action * {
9261 while (S->getKind() != Action::InputClass) {
9262 assert(!S->getInputs().empty() && "unexpected root action!");
9263 S = S->getInputs()[0];
9264 }
9265 return S;
9266 };
9267 const Action *SourceAction = FindSource(&JA);
9268
9269 // Forward -g and handle debug info related flags, assuming we are dealing
9270 // with an actual assembly file.
9271 bool WantDebug = false;
9272 Args.ClaimAllArgs(options::OPT_g_Group);
9273 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9274 WantDebug = !A->getOption().matches(options::OPT_g0) &&
9275 !A->getOption().matches(options::OPT_ggdb0);
9276
9277 // If a -gdwarf argument appeared, remember it.
9278 bool EmitDwarf = false;
9279 if (const Arg *A = getDwarfNArg(Args))
9280 EmitDwarf = checkDebugInfoOption(A, Args, D, getToolChain());
9281
9282 bool EmitCodeView = false;
9283 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
9284 EmitCodeView = checkDebugInfoOption(A, Args, D, getToolChain());
9285
9286 // If the user asked for debug info but did not explicitly specify -gcodeview
9287 // or -gdwarf, ask the toolchain for the default format.
9288 if (!EmitCodeView && !EmitDwarf && WantDebug) {
9289 switch (getToolChain().getDefaultDebugFormat()) {
9290 case llvm::codegenoptions::DIF_CodeView:
9291 EmitCodeView = true;
9292 break;
9293 case llvm::codegenoptions::DIF_DWARF:
9294 EmitDwarf = true;
9295 break;
9296 }
9297 }
9298
9299 // If the arguments don't imply DWARF, don't emit any debug info here.
9300 if (!EmitDwarf)
9301 WantDebug = false;
9302
9303 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
9304 llvm::codegenoptions::NoDebugInfo;
9305
9306 // Add the -fdebug-compilation-dir flag if needed.
9307 const char *DebugCompilationDir =
9308 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
9309
9310 if (SourceAction->getType() == types::TY_Asm ||
9311 SourceAction->getType() == types::TY_PP_Asm) {
9312 // You might think that it would be ok to set DebugInfoKind outside of
9313 // the guard for source type, however there is a test which asserts
9314 // that some assembler invocation receives no -debug-info-kind,
9315 // and it's not clear whether that test is just overly restrictive.
9316 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
9317 : llvm::codegenoptions::NoDebugInfo);
9318
9319 addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
9320 CmdArgs);
9321
9322 // Set the AT_producer to the clang version when using the integrated
9323 // assembler on assembly source files.
9324 CmdArgs.push_back("-dwarf-debug-producer");
9325 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
9326
9327 // And pass along -I options
9328 Args.AddAllArgs(CmdArgs, options::OPT_I);
9329 }
9330 const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
9331 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
9332 llvm::DebuggerKind::Default);
9333 renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
9334 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
9335
9336 // Handle -fPIC et al -- the relocation-model affects the assembler
9337 // for some targets.
9338 llvm::Reloc::Model RelocationModel;
9339 unsigned PICLevel;
9340 bool IsPIE;
9341 std::tie(RelocationModel, PICLevel, IsPIE) =
9342 ParsePICArgs(getToolChain(), Args);
9343
9344 const char *RMName = RelocationModelName(RelocationModel);
9345 if (RMName) {
9346 CmdArgs.push_back("-mrelocation-model");
9347 CmdArgs.push_back(RMName);
9348 }
9349
9350 // Optionally embed the -cc1as level arguments into the debug info, for build
9351 // analysis.
9352 if (getToolChain().UseDwarfDebugFlags()) {
9353 ArgStringList OriginalArgs;
9354 for (const auto &Arg : Args)
9355 Arg->render(Args, OriginalArgs);
9356
9357 SmallString<256> Flags;
9358 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9359 escapeSpacesAndBackslashes(Exec, Flags);
9360 for (const char *OriginalArg : OriginalArgs) {
9361 SmallString<128> EscapedArg;
9362 escapeSpacesAndBackslashes(OriginalArg, EscapedArg);
9363 Flags += " ";
9364 Flags += EscapedArg;
9365 }
9366 CmdArgs.push_back("-dwarf-debug-flags");
9367 CmdArgs.push_back(Args.MakeArgString(Flags));
9368 }
9369
9370 // FIXME: Add -static support, once we have it.
9371
9372 // Add target specific flags.
9373 switch (getToolChain().getArch()) {
9374 default:
9375 break;
9376
9377 case llvm::Triple::mips:
9378 case llvm::Triple::mipsel:
9379 case llvm::Triple::mips64:
9380 case llvm::Triple::mips64el:
9381 AddMIPSTargetArgs(Args, CmdArgs);
9382 break;
9383
9384 case llvm::Triple::x86:
9385 case llvm::Triple::x86_64:
9386 AddX86TargetArgs(Args, CmdArgs);
9387 break;
9388
9389 case llvm::Triple::arm:
9390 case llvm::Triple::armeb:
9391 case llvm::Triple::thumb:
9392 case llvm::Triple::thumbeb:
9393 // This isn't in AddARMTargetArgs because we want to do this for assembly
9394 // only, not C/C++.
9395 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9396 options::OPT_mno_default_build_attributes, true)) {
9397 CmdArgs.push_back("-mllvm");
9398 CmdArgs.push_back("-arm-add-build-attributes");
9399 }
9400 break;
9401
9402 case llvm::Triple::aarch64:
9403 case llvm::Triple::aarch64_32:
9404 case llvm::Triple::aarch64_be:
9405 if (Args.hasArg(options::OPT_mmark_bti_property)) {
9406 CmdArgs.push_back("-mllvm");
9407 CmdArgs.push_back("-aarch64-mark-bti-property");
9408 }
9409 break;
9410
9411 case llvm::Triple::loongarch32:
9412 case llvm::Triple::loongarch64:
9413 AddLoongArchTargetArgs(Args, CmdArgs);
9414 break;
9415
9416 case llvm::Triple::riscv32:
9417 case llvm::Triple::riscv64:
9418 case llvm::Triple::riscv32be:
9419 case llvm::Triple::riscv64be:
9420 AddRISCVTargetArgs(Args, CmdArgs);
9421 break;
9422
9423 case llvm::Triple::hexagon:
9424 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9425 options::OPT_mno_default_build_attributes, true)) {
9426 CmdArgs.push_back("-mllvm");
9427 CmdArgs.push_back("-hexagon-add-build-attributes");
9428 }
9429 break;
9430 }
9431
9432 // Consume all the warning flags. Usually this would be handled more
9433 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
9434 // doesn't handle that so rather than warning about unused flags that are
9435 // actually used, we'll lie by omission instead.
9436 // FIXME: Stop lying and consume only the appropriate driver flags
9437 Args.ClaimAllArgs(options::OPT_W_Group);
9438
9439 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
9440 getToolChain().getDriver());
9441
9442 // Forward -Xclangas arguments to -cc1as
9443 for (auto Arg : Args.filtered(options::OPT_Xclangas)) {
9444 Arg->claim();
9445 CmdArgs.push_back(Arg->getValue());
9446 }
9447
9448 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
9449
9450 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
9451 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
9452 Output.getFilename());
9453
9454 // Fixup any previous commands that use -object-file-name because when we
9455 // generated them, the final .obj name wasn't yet known.
9456 for (Command &J : C.getJobs()) {
9457 if (SourceAction != FindSource(&J.getSource()))
9458 continue;
9459 auto &JArgs = J.getArguments();
9460 for (unsigned I = 0; I < JArgs.size(); ++I) {
9461 if (StringRef(JArgs[I]).starts_with("-object-file-name=") &&
9462 Output.isFilename()) {
9463 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
9464 addDebugObjectName(Args, NewArgs, DebugCompilationDir,
9465 Output.getFilename());
9466 NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
9467 J.replaceArguments(NewArgs);
9468 break;
9469 }
9470 }
9471 }
9472
9473 assert(Output.isFilename() && "Unexpected lipo output.");
9474 CmdArgs.push_back("-o");
9475 CmdArgs.push_back(Output.getFilename());
9476
9477 const llvm::Triple &T = getToolChain().getTriple();
9478 Arg *A;
9479 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
9480 T.isOSBinFormatELF()) {
9481 CmdArgs.push_back("-split-dwarf-output");
9482 CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
9483 }
9484
9485 if (Triple.isAMDGPU())
9486 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
9487
9488 assert(Input.isFilename() && "Invalid input.");
9489 CmdArgs.push_back(Input.getFilename());
9490
9491 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9492 if (D.CC1Main && !D.CCGenDiagnostics) {
9493 // Invoke cc1as directly in this process.
9494 C.addCommand(std::make_unique<CC1Command>(
9495 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
9496 Output, D.getPrependArg()));
9497 } else {
9498 C.addCommand(std::make_unique<Command>(
9499 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
9500 Output, D.getPrependArg()));
9501 }
9502}
9503
9504// Begin OffloadBundler
9506 const InputInfo &Output,
9507 const InputInfoList &Inputs,
9508 const llvm::opt::ArgList &TCArgs,
9509 const char *LinkingOutput) const {
9510 // The version with only one output is expected to refer to a bundling job.
9511 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
9512
9513 // The bundling command looks like this:
9514 // clang-offload-bundler -type=bc
9515 // -targets=host-triple,openmp-triple1,openmp-triple2
9516 // -output=output_file
9517 // -input=unbundle_file_host
9518 // -input=unbundle_file_tgt1
9519 // -input=unbundle_file_tgt2
9520
9521 ArgStringList CmdArgs;
9522
9523 // Get the type.
9524 CmdArgs.push_back(TCArgs.MakeArgString(
9525 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
9526
9527 assert(JA.getInputs().size() == Inputs.size() &&
9528 "Not have inputs for all dependence actions??");
9529
9530 // Get the targets.
9531 SmallString<128> Triples;
9532 Triples += "-targets=";
9533 for (unsigned I = 0; I < Inputs.size(); ++I) {
9534 if (I)
9535 Triples += ',';
9536
9537 // Find ToolChain for this input.
9539 const ToolChain *CurTC = &getToolChain();
9540 const Action *CurDep = JA.getInputs()[I];
9541
9542 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
9543 CurTC = nullptr;
9544 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, BoundArch BA) {
9545 assert(CurTC == nullptr && "Expected one dependence!");
9546 CurKind = A->getOffloadingDeviceKind();
9547 CurTC = TC;
9548 });
9549 }
9550 Triples += Action::GetOffloadKindName(CurKind);
9551 Triples += '-';
9552 Triples += llvm::Triple(CurTC->ComputeEffectiveClangTriple(
9553 TCArgs, CurDep->getOffloadingArch()))
9554 .normalize(llvm::Triple::CanonicalForm::FOUR_IDENT);
9555
9556 if ((CurKind != Action::OFK_Host) && !CurDep->getOffloadingArch().empty()) {
9557 Triples += '-';
9558 Triples += CurDep->getOffloadingArch().ArchName;
9559 }
9560 }
9561 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
9562
9563 // Get bundled file command.
9564 CmdArgs.push_back(
9565 TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
9566
9567 // Get unbundled files command.
9568 for (unsigned I = 0; I < Inputs.size(); ++I) {
9570 UB += "-input=";
9571
9572 // Find ToolChain for this input.
9573 const ToolChain *CurTC = &getToolChain();
9574 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
9575 CurTC = nullptr;
9576 OA->doOnEachDependence([&](Action *, const ToolChain *TC, BoundArch) {
9577 assert(CurTC == nullptr && "Expected one dependence!");
9578 CurTC = TC;
9579 });
9580 UB += C.addTempFile(
9581 C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
9582 } else {
9583 UB += CurTC->getInputFilename(Inputs[I]);
9584 }
9585 CmdArgs.push_back(TCArgs.MakeArgString(UB));
9586 }
9587 addOffloadCompressArgs(TCArgs, CmdArgs);
9588 // All the inputs are encoded as commands.
9589 C.addCommand(std::make_unique<Command>(
9590 JA, *this, ResponseFileSupport::None(),
9591 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9592 CmdArgs, ArrayRef<InputInfo>(), Output));
9593}
9594
9596 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
9597 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
9598 const char *LinkingOutput) const {
9599 // The version with multiple outputs is expected to refer to a unbundling job.
9600 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
9601
9602 // The unbundling command looks like this:
9603 // clang-offload-bundler -type=bc
9604 // -targets=host-triple,openmp-triple1,openmp-triple2
9605 // -input=input_file
9606 // -output=unbundle_file_host
9607 // -output=unbundle_file_tgt1
9608 // -output=unbundle_file_tgt2
9609 // -unbundle
9610
9611 ArgStringList CmdArgs;
9612
9613 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
9614 InputInfo Input = Inputs.front();
9615
9616 // Get the type.
9617 CmdArgs.push_back(TCArgs.MakeArgString(
9618 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
9619
9620 // Get the targets.
9621 SmallString<128> Triples;
9622 Triples += "-targets=";
9623 auto DepInfo = UA.getDependentActionsInfo();
9624 for (unsigned I = 0; I < DepInfo.size(); ++I) {
9625 if (I)
9626 Triples += ',';
9627
9628 auto &Dep = DepInfo[I];
9629 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
9630 Triples += '-';
9631 Triples += llvm::Triple(Dep.DependentToolChain->ComputeEffectiveClangTriple(
9632 TCArgs, Dep.DependentBoundArch))
9633 .normalize(llvm::Triple::CanonicalForm::FOUR_IDENT);
9634
9635 if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
9636 Dep.DependentOffloadKind == Action::OFK_Cuda) &&
9637 !Dep.DependentBoundArch.empty()) {
9638 Triples += '-';
9639 Triples += Dep.DependentBoundArch.ArchName;
9640 }
9641 }
9642
9643 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
9644
9645 // Get bundled file command.
9646 CmdArgs.push_back(
9647 TCArgs.MakeArgString(Twine("-input=") + Input.getFilename()));
9648
9649 // Get unbundled files command.
9650 for (unsigned I = 0; I < Outputs.size(); ++I) {
9652 UB += "-output=";
9653 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
9654 CmdArgs.push_back(TCArgs.MakeArgString(UB));
9655 }
9656 CmdArgs.push_back("-unbundle");
9657 CmdArgs.push_back("-allow-missing-bundles");
9658 if (TCArgs.hasArg(options::OPT_v))
9659 CmdArgs.push_back("-verbose");
9660
9661 // All the inputs are encoded as commands.
9662 C.addCommand(std::make_unique<Command>(
9663 JA, *this, ResponseFileSupport::None(),
9664 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9665 CmdArgs, ArrayRef<InputInfo>(), Outputs));
9666}
9667
9669 const InputInfo &Output,
9670 const InputInfoList &Inputs,
9671 const llvm::opt::ArgList &Args,
9672 const char *LinkingOutput) const {
9673 ArgStringList CmdArgs;
9674
9675 // Add the output file name.
9676 assert(Output.isFilename() && "Invalid output.");
9677 CmdArgs.push_back("-o");
9678 CmdArgs.push_back(Output.getFilename());
9679
9680 // Create the inputs to bundle the needed metadata.
9681 for (const InputInfo &Input : Inputs) {
9682 const Action *OffloadAction = Input.getAction();
9684 const ArgList &TCArgs =
9685 C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
9687 StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
9689 if (Arch.empty())
9690 Arch = BoundArch(TCArgs.getLastArgValue(options::OPT_march_EQ));
9691
9692 StringRef Kind =
9694
9695 ArgStringList Features;
9696 SmallVector<StringRef> FeatureArgs;
9697 getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
9698 false);
9699 llvm::copy_if(Features, std::back_inserter(FeatureArgs),
9700 [](StringRef Arg) { return !Arg.starts_with("-target"); });
9701
9702 // TODO: We need to pass in the full target-id and handle it properly in the
9703 // linker wrapper.
9705 "file=" + File.str(),
9706 "triple=" + TC->ComputeEffectiveClangTriple(TCArgs, Arch),
9707 "arch=" + (Arch.empty() ? "generic" : Arch.ArchName.str()),
9708 "kind=" + Kind.str(),
9709 };
9710
9712 for (StringRef Feature : FeatureArgs)
9713 Parts.emplace_back("feature=" + Feature.str());
9714
9715 CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
9716 }
9717
9718 C.addCommand(std::make_unique<Command>(
9720 Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9721 CmdArgs, Inputs, Output));
9722}
9723
9724// Options that need the profile compiler-rt library on the target toolchain.
9725// Coverage mapping flags require -fprofile-instr-generate, so they belong here
9726// too.
9727static bool requiresProfileRT(unsigned ID) {
9728 switch (ID) {
9729 case options::OPT_fprofile_generate:
9730 case options::OPT_fprofile_generate_EQ:
9731 case options::OPT_fprofile_instr_generate:
9732 case options::OPT_fprofile_instr_generate_EQ:
9733 case options::OPT_fcoverage_mapping:
9734 case options::OPT_fno_coverage_mapping:
9735 case options::OPT_fcoverage_compilation_dir_EQ:
9736 case options::OPT_ffile_compilation_dir_EQ:
9737 case options::OPT_fcoverage_prefix_map_EQ:
9738 return true;
9739 default:
9740 return false;
9741 }
9742}
9743
9744// Options that need the ubsan compiler-rt library on the target toolchain.
9745static bool requiresUBSanRT(unsigned ID) {
9746 switch (ID) {
9747 case options::OPT_fsanitize_EQ:
9748 case options::OPT_fno_sanitize_EQ:
9749 case options::OPT_fsanitize_minimal_runtime:
9750 case options::OPT_fno_sanitize_minimal_runtime:
9751 return true;
9752 default:
9753 return false;
9754 }
9755}
9756
9758 const InputInfo &Output,
9759 const InputInfoList &Inputs,
9760 const ArgList &Args,
9761 const char *LinkingOutput) const {
9762 using namespace options;
9763
9764 // A list of permitted options that will be forwarded to the embedded device
9765 // compilation job.
9766 const llvm::DenseSet<unsigned> CompilerOptions{
9767 OPT_v,
9768 OPT_hip_path_EQ,
9769 OPT_O_Group,
9770 OPT_g_Group,
9771 OPT_g_flags_Group,
9772 OPT_R_value_Group,
9773 OPT_R_Group,
9774 OPT_Xcuda_ptxas,
9775 OPT_ftime_report,
9776 OPT_ftime_trace,
9777 OPT_ftime_trace_EQ,
9778 OPT_ftime_trace_granularity_EQ,
9779 OPT_ftime_trace_verbose,
9780 OPT_opt_record_file,
9781 OPT_opt_record_format,
9782 OPT_opt_record_passes,
9783 OPT_fsave_optimization_record,
9784 OPT_fsave_optimization_record_EQ,
9785 OPT_fno_save_optimization_record,
9786 OPT_foptimization_record_file_EQ,
9787 OPT_foptimization_record_passes_EQ,
9788 OPT_save_temps,
9789 OPT_save_temps_EQ,
9790 OPT_mcode_object_version_EQ,
9791 OPT_load,
9792 OPT_no_canonical_prefixes,
9793 OPT_fno_lto,
9794 OPT_flto,
9795 OPT_flto_partitions_EQ,
9796 OPT_flto_EQ,
9797 OPT_hipspv_pass_plugin_EQ,
9798 OPT_use_spirv_backend,
9799 OPT_no_use_spirv_backend,
9800 OPT_fmultilib_flag,
9801 OPT_fprofile_generate,
9802 OPT_fprofile_generate_EQ,
9803 OPT_fprofile_instr_generate,
9804 OPT_fprofile_instr_generate_EQ,
9805 OPT_fcoverage_mapping,
9806 OPT_fno_coverage_mapping,
9807 OPT_fcoverage_compilation_dir_EQ,
9808 OPT_ffile_compilation_dir_EQ,
9809 OPT_fcoverage_prefix_map_EQ,
9810 OPT_fsanitize_EQ,
9811 OPT_fno_sanitize_EQ,
9812 OPT_fsanitize_minimal_runtime,
9813 OPT_fno_sanitize_minimal_runtime,
9814 OPT_fsanitize_trap_EQ,
9815 OPT_fno_sanitize_trap_EQ,
9816 OPT_fslp_vectorize,
9817 OPT_fno_slp_vectorize,
9818 OPT_hipstdpar};
9819 const llvm::DenseSet<unsigned> LinkerOptions{OPT_mllvm, OPT_Zlinker_input};
9820 auto ToolChainHasRT = [&](const ToolChain &TC, StringRef Name) {
9821 return TC.getVFS().exists(
9822 TC.getCompilerRT(Args, Name, ToolChain::FT_Static));
9823 };
9824 auto ShouldForwardForToolChain = [&](Arg *A, const ToolChain &TC) {
9825 unsigned ID = A->getOption().getID();
9826 // Don't forward profiling arguments if the toolchain doesn't support it.
9827 // Without this check using it on the host would result in linker errors.
9828 // Coverage mapping flags require -fprofile-instr-generate, so drop them
9829 // together to avoid a device cc1 diagnostic.
9830 if (requiresProfileRT(ID) && !ToolChainHasRT(TC, "profile"))
9831 return false;
9832 // Don't forward sanitizer arguments if the toolchain doesn't support it.
9833 // Without this check using it on the host would result in linker errors.
9834 if (requiresUBSanRT(ID) && !ToolChainHasRT(TC, "ubsan_minimal"))
9835 return false;
9836 // Don't forward -mllvm to toolchains that don't support LLVM.
9837 return TC.HasNativeLLVMSupport() || ID != OPT_mllvm;
9838 };
9839 auto ShouldForward = [&](const llvm::DenseSet<unsigned> &Set, Arg *A,
9840 const ToolChain &TC) {
9841 // CMake hack to avoid printing verbose informatoin for HIP non-RDC mode.
9842 if (A->getOption().matches(OPT_v) && JA.getType() == types::TY_HIP_FATBIN)
9843 return false;
9844 return (Set.contains(A->getOption().getID()) ||
9845 (A->getOption().getGroup().isValid() &&
9846 Set.contains(A->getOption().getGroup().getID()))) &&
9847 ShouldForwardForToolChain(A, TC);
9848 };
9849
9850 ArgStringList CmdArgs;
9853 auto TCRange = C.getOffloadToolChains(Kind);
9854 for (auto &I : llvm::make_range(TCRange)) {
9855 const ToolChain *TC = I.second;
9856
9857 // We do not use a bound architecture here so options passed only to a
9858 // specific architecture via -Xarch_<cpu> will not be forwarded.
9859 ArgStringList CompilerArgs;
9860 ArgStringList LinkerArgs;
9861 const DerivedArgList &ToolChainArgs =
9862 C.getArgsForToolChain(TC, /*BA=*/{}, Kind);
9863 for (Arg *A : ToolChainArgs) {
9864 if (A->getOption().matches(OPT_Zlinker_input))
9865 LinkerArgs.emplace_back(A->getValue());
9866 else if (ShouldForward(CompilerOptions, A, *TC)) {
9867 A->claim();
9868 A->render(Args, CompilerArgs);
9869 } else if (ShouldForward(LinkerOptions, A, *TC)) {
9870 A->claim();
9871 A->render(Args, LinkerArgs);
9872 }
9873 }
9874
9875 // If the user explicitly requested it via `--offload-arch` we should
9876 // extract it from any static libraries if present.
9877 for (StringRef Arg : ToolChainArgs.getAllArgValues(OPT_offload_arch_EQ))
9878 CmdArgs.emplace_back(Args.MakeArgString("--should-extract=" + Arg));
9879
9880 // If this is OpenMP the device linker will need `-lompdevice`.
9881 if (Kind == Action::OFK_OpenMP && !Args.hasArg(OPT_no_offloadlib) &&
9882 (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))
9883 LinkerArgs.emplace_back("-lompdevice");
9884
9885 // For SPIR-V, pass some extra flags to `spirv-link`, the out-of-tree
9886 // SPIR-V linker. `spirv-link` isn't called in LTO mode so restrict these
9887 // flags to normal compilation.
9888 // SPIR-V for AMD doesn't use spirv-link and therefore doesn't need these
9889 // flags. SYCL uses clang-sycl-linker instead of spirv-link, so skip it.
9890 if (TC->getTriple().isSPIRV() &&
9891 TC->getTriple().getVendor() != llvm::Triple::VendorType::AMD &&
9892 Kind != Action::OFK_SYCL && !TC->isUsingLTO(ToolChainArgs, Kind)) {
9893 // For SPIR-V some functions will be defined by the runtime so allow
9894 // unresolved symbols in `spirv-link`.
9895 LinkerArgs.emplace_back("--allow-partial-linkage");
9896 // Don't optimize out exported symbols.
9897 LinkerArgs.emplace_back("--create-library");
9898 }
9899
9900 // Forward the SYCL device image split option to clang-sycl-linker.
9901 // The driver and clang-sycl-linker share the same value vocabulary, so
9902 // the value is passed through verbatim after validation.
9903 if (Kind == Action::OFK_SYCL) {
9904 if (Arg *A =
9905 ToolChainArgs.getLastArg(OPT_fsycl_device_image_split_EQ)) {
9906 StringRef Mode = A->getValue();
9907 if (Mode != "kernel" && Mode != "translation_unit" &&
9908 Mode != "link_unit")
9909 C.getDriver().Diag(clang::diag::err_drv_invalid_value)
9910 << A->getSpelling() << Mode;
9911 else
9912 LinkerArgs.emplace_back(
9913 Args.MakeArgString("--module-split-mode=" + Mode));
9914 }
9915 }
9916
9917 // Forward all of these to the appropriate toolchain.
9918 for (StringRef Arg : CompilerArgs)
9919 CmdArgs.push_back(Args.MakeArgString(
9920 "--device-compiler=" + TC->getTripleString() + "=" + Arg));
9921 for (StringRef Arg : LinkerArgs)
9922 CmdArgs.push_back(Args.MakeArgString(
9923 "--device-linker=" + TC->getTripleString() + "=" + Arg));
9924
9925 // Forward the LTO mode for this toolchain.
9926 auto DeviceLTOMode = TC->getLTOMode(ToolChainArgs, Kind);
9927 if (DeviceLTOMode == LTOK_Full)
9928 CmdArgs.push_back(Args.MakeArgString(
9929 "--device-compiler=" + TC->getTripleString() + "=-flto=full"));
9930 else if (DeviceLTOMode == LTOK_Thin) {
9931 CmdArgs.push_back(Args.MakeArgString(
9932 "--device-compiler=" + TC->getTripleString() + "=-flto=thin"));
9933 if (TC->getTriple().isAMDGPU()) {
9934 CmdArgs.push_back(
9935 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9936 "=-plugin-opt=-force-import-all"));
9937 CmdArgs.push_back(
9938 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9939 "=-plugin-opt=-avail-extern-to-local"));
9940 CmdArgs.push_back(Args.MakeArgString(
9941 "--device-linker=" + TC->getTripleString() +
9942 "=-plugin-opt=-avail-extern-gv-in-addrspace-to-local=3"));
9943 if (Kind == Action::OFK_OpenMP) {
9944 CmdArgs.push_back(
9945 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9946 "=-plugin-opt=-amdgpu-internalize-symbols"));
9947 }
9948 }
9949 }
9950 }
9951 }
9952
9953 if (const llvm::Triple *AuxTriple = getToolChain().getAuxTriple())
9954 CmdArgs.push_back(
9955 Args.MakeArgString("--host-triple=" + AuxTriple->getTriple()));
9956 else
9957 CmdArgs.push_back(Args.MakeArgString("--host-triple=" +
9958 getToolChain().getTripleString()));
9959
9960 // CMake hack, suppress passing verbose arguments for the special-case HIP
9961 // non-RDC mode compilation. This confuses default CMake implicit linker
9962 // argument parsing when the language is set to HIP and the system linker is
9963 // also `ld.lld`.
9964 if (Args.hasArg(options::OPT_v) && JA.getType() != types::TY_HIP_FATBIN)
9965 CmdArgs.push_back("--wrapper-verbose");
9966 if (Arg *A = Args.getLastArg(options::OPT_cuda_path_EQ)) {
9967 CmdArgs.push_back(
9968 Args.MakeArgString(Twine("--cuda-path=") + A->getValue()));
9969 CmdArgs.push_back(Args.MakeArgString(
9970 Twine("--device-compiler=--cuda-path=") + A->getValue()));
9971 }
9972 if (Arg *A = Args.getLastArg(options::OPT_rocm_path_EQ)) {
9973 CmdArgs.push_back(Args.MakeArgString(
9974 Twine("--device-compiler=--rocm-path=") + A->getValue()));
9975 }
9976
9977 // Construct the link job so we can wrap around it.
9978 Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
9979 const auto &LinkCommand = C.getJobs().getJobs().back();
9980
9981 // Forward -Xoffload-{compiler,linker}<-triple> arguments to the linker
9982 // wrapper.
9983 for (Arg *A :
9984 Args.filtered(options::OPT_Xoffload_compiler, OPT_Xoffload_linker)) {
9985 StringRef Val = A->getValue(0);
9986 bool IsLinkJob = A->getOption().getID() == OPT_Xoffload_linker;
9987 auto WrapperOption =
9988 IsLinkJob ? Twine("--device-linker=") : Twine("--device-compiler=");
9989 if (Val.empty())
9990 CmdArgs.push_back(Args.MakeArgString(WrapperOption + A->getValue(1)));
9991 else
9992 CmdArgs.push_back(Args.MakeArgString(
9993 WrapperOption +
9994 ToolChain::normalizeOffloadTriple(Val.drop_front()).str() + "=" +
9995 A->getValue(1)));
9996 }
9997 Args.ClaimAllArgs(options::OPT_Xoffload_compiler);
9998 Args.ClaimAllArgs(options::OPT_Xoffload_linker);
9999
10000 // Embed bitcode instead of an object in JIT mode.
10001 if (Args.hasFlag(options::OPT_fopenmp_target_jit,
10002 options::OPT_fno_openmp_target_jit, false))
10003 CmdArgs.push_back("--embed-bitcode");
10004
10005 // Save temporary files created by the linker wrapper.
10006 if (Args.hasArg(options::OPT_save_temps_EQ) ||
10007 Args.hasArg(options::OPT_save_temps))
10008 CmdArgs.push_back("--save-temps");
10009
10010 // Pass in the C library for GPUs if present and not disabled.
10011 if (Args.hasFlag(options::OPT_offloadlib, OPT_no_offloadlib, true) &&
10012 !Args.hasArg(options::OPT_nostdlib, options::OPT_r,
10013 options::OPT_nodefaultlibs, options::OPT_nolibc,
10014 options::OPT_nogpulibc)) {
10015 forAllAssociatedToolChains(C, JA, getToolChain(), [&](const ToolChain &TC) {
10016 // The device C library is only available for NVPTX and AMDGPU targets
10017 // and we only link it by default for OpenMP currently.
10018 if ((!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU()) ||
10020 return;
10021 bool HasLibC = TC.getStdlibIncludePath().has_value();
10022 if (HasLibC) {
10023 CmdArgs.push_back(Args.MakeArgString(
10024 "--device-linker=" + TC.getTripleString() + "=" + "-lc"));
10025 CmdArgs.push_back(Args.MakeArgString(
10026 "--device-linker=" + TC.getTripleString() + "=" + "-lm"));
10027 }
10028 auto HasCompilerRT = getToolChain().getVFS().exists(
10029 TC.getCompilerRT(Args, "builtins", ToolChain::FT_Static,
10030 /*IsFortran=*/false));
10031 if (HasCompilerRT)
10032 CmdArgs.push_back(
10033 Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
10034 "-lclang_rt.builtins"));
10035
10036 bool HasFlangRT = getToolChain().getVFS().exists(
10037 TC.getCompilerRT(Args, "runtime", ToolChain::FT_Static,
10038 /*IsFortran=*/true));
10039 if (HasFlangRT && C.getDriver().IsFlangMode())
10040 CmdArgs.push_back(
10041 Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
10042 "-lflang_rt.runtime"));
10043 });
10044 }
10045
10046 // Add the linker arguments to be forwarded by the wrapper.
10047 CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
10048 LinkCommand->getExecutable()));
10049
10050 // We use action type to differentiate two use cases of the linker wrapper.
10051 // TY_Image for normal linker wrapper work.
10052 // TY_HIP_FATBIN for HIP fno-gpu-rdc emitting a fat binary without wrapping.
10053 assert(JA.getType() == types::TY_HIP_FATBIN ||
10054 JA.getType() == types::TY_Image);
10055 if (JA.getType() == types::TY_HIP_FATBIN) {
10056 CmdArgs.push_back("--emit-fatbin-only");
10057 CmdArgs.append({"-o", Output.getFilename()});
10058 for (auto Input : Inputs)
10059 CmdArgs.push_back(Input.getFilename());
10060 } else {
10061 for (const char *LinkArg : LinkCommand->getArguments())
10062 CmdArgs.push_back(LinkArg);
10063 }
10064
10065 addOffloadCompressArgs(Args, CmdArgs);
10066
10067 OffloadJobsOpt OffloadJobs = parseOffloadJobs(Args);
10068 if (OffloadJobs.A) {
10069 if (OffloadJobs.K == OffloadJobsOpt::Kind::Jobserver) {
10070 CmdArgs.push_back(Args.MakeArgString("--wrapper-jobs=jobserver"));
10071 } else if (OffloadJobs.K == OffloadJobsOpt::Kind::Fixed) {
10072 CmdArgs.push_back(Args.MakeArgString("--wrapper-jobs=" +
10073 Twine(OffloadJobs.NumThreads)));
10074 } else if (!OffloadJobs.A->isClaimed()) {
10075 C.getDriver().Diag(diag::err_drv_invalid_int_value)
10076 << OffloadJobs.A->getAsString(Args) << OffloadJobs.Value;
10077 }
10078 }
10079
10080 // Propagate -no-canonical-prefixes.
10081 if (Args.hasArg(options::OPT_no_canonical_prefixes))
10082 CmdArgs.push_back("--no-canonical-prefixes");
10083
10084 const char *Exec =
10085 Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
10086
10087 // Replace the executable and arguments of the link job with the
10088 // wrapper.
10089 LinkCommand->replaceExecutable(Exec);
10090 LinkCommand->replaceArguments(CmdArgs);
10091}
#define V(N, I)
static StringRef bytes(const std::vector< T, Allocator > &v)
static void RenderDebugInfoCompressionArgs(const ArgList &Args, ArgStringList &CmdArgs, const Driver &D, const ToolChain &TC)
Definition Clang.cpp:734
static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:3902
static bool shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime, const llvm::Triple &Triple)
Definition Clang.cpp:118
static void pushBackLLVMArg(ArgStringList &CmdArgs, const char *A)
Definition Clang.cpp:2285
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:4644
static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T, ArgStringList &CmdArgs)
Definition Clang.cpp:4315
static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind, unsigned DwarfVersion, llvm::DebuggerKind DebuggerTuning)
Definition Clang.cpp:708
static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:5047
static bool requiresProfileRT(unsigned ID)
Definition Clang.cpp:9727
static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:4496
static bool maybeHasClangPchSignature(const Driver &D, StringRef Path)
Definition Clang.cpp:789
static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args)
Definition Clang.cpp:71
void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:1359
static bool isSignedCharDefault(const llvm::Triple &Triple)
Definition Clang.cpp:1211
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:8775
static void checkAndRemoveLLVMArg(ArgStringList &CmdArgs, StringRef Opt)
Definition Clang.cpp:2264
static bool gchProbe(const Driver &D, StringRef Path)
Definition Clang.cpp:806
static void RenderOpenACCOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:3995
static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D, const ArgList &Args)
Definition Clang.cpp:4627
static bool CheckARMImplicitITArg(StringRef Value)
Definition Clang.cpp:2535
static bool hasMultipleInvocations(const llvm::Triple &Triple, const ArgList &Args)
Definition Clang.cpp:1249
static void handleAMDGPUCodeObjectVersionOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, bool IsCC1As=false)
Definition Clang.cpp:766
static void addDashXForInput(const ArgList &Args, const InputInfo &Input, ArgStringList &CmdArgs)
Add -x lang to CmdArgs for Input.
Definition Clang.cpp:338
static void renderDwarfFormat(const Driver &D, const llvm::Triple &T, const ArgList &Args, ArgStringList &CmdArgs, unsigned DwarfVersion)
Definition Clang.cpp:4604
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:4351
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:323
static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs, StringRef Value)
Definition Clang.cpp:2540
static bool checkRemarksOptions(const Driver &D, const ArgList &Args, const llvm::Triple &Triple)
Definition Clang.cpp:1260
static void addQFloatBackendArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:2316
static void CollectArgsForIntegratedAssembler(Compilation &C, const ArgList &Args, ArgStringList &CmdArgs, const Driver &D)
Definition Clang.cpp:2546
static StringRef getOptionName(StringRef Option, const char Delimiter='=')
Definition Clang.cpp:2257
static bool RenderModulesOptions(Compilation &C, const Driver &D, const ArgList &Args, const InputInfo &Input, const InputInfo &Output, bool HaveStd20, ArgStringList &CmdArgs)
Definition Clang.cpp:4061
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:98
static bool isValidSymbolName(StringRef S)
Definition Clang.cpp:3576
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:308
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:138
static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input, const InputInfo &Output, const JobAction &JA)
Definition Clang.cpp:1276
static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs, const char *DebugCompilationDir, const char *OutputFileName)
Definition Clang.cpp:253
static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, bool isAArch64)
Definition Clang.cpp:1395
static void RenderSSPOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, bool KernelOrKext)
Definition Clang.cpp:3586
static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:4003
static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3814
static void RenderTrivialAutoVarInitOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3831
static bool maybeConsumeDash(const std::string &EH, size_t &I)
Definition Clang.cpp:8754
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:233
static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args)
Definition Clang.cpp:86
static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC, const JobAction &JA)
Definition Clang.cpp:216
static bool requiresUBSanRT(unsigned ID)
Definition Clang.cpp:9745
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:287
static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input)
Definition Clang.cpp:3507
static void addQFloatLossyFastMathArgs(ArgStringList &CmdArgs)
Definition Clang.cpp:2291
static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D, bool OFastEnabled, const ArgList &Args, ArgStringList &CmdArgs, const JobAction &JA)
Definition Clang.cpp:2911
static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C, const JobAction &JA, const InputInfo &Output, const ArgList &Args, SanitizerArgs &SanArgs, ArgStringList &CmdArgs)
Definition Clang.cpp:369
static void RenderHLSLOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:3946
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:915
ComplexRangeKind
Controls the various implementations for complex multiplication and.
@ CX_Full
Implementation of complex division and multiplication using a call to runtime library functions(gener...
@ CX_Basic
Implementation of complex division and multiplication using algebraic formulas at source precision.
@ CX_Promoted
Implementation of complex division using algebraic formulas at higher precision.
@ CX_None
No range rule is enabled.
@ CX_Improved
Implementation of complex division offering an improved handling for overflow in intermediate calcula...
The basic abstraction for the target Objective-C runtime.
Definition ObjCRuntime.h:28
bool allowsWeak() const
Does this runtime allow the use of __weak?
bool isLegacyDispatchDefaultForArch(llvm::Triple::ArchType Arch)
The default dispatch mechanism to use for the specified architecture.
Kind getKind() const
Definition ObjCRuntime.h:77
bool isNeXTFamily() const
Is this runtime basically of the NeXT family of runtimes?
bool hasConstantLiteralClasses() const
Are Foundation backed constant literal classes supported?
const VersionTuple & getVersion() const
Definition ObjCRuntime.h:78
bool tryParse(StringRef input)
Try to parse an Objective-C runtime specification from the given string.
bool isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
Definition ObjCRuntime.h:82
std::string getAsString() const
@ MacOSX
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
Definition ObjCRuntime.h:35
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition ObjCRuntime.h:40
@ GNUstep
'gnustep' is the modern non-fragile GNUstep runtime.
Definition ObjCRuntime.h:56
@ GCC
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI
Definition ObjCRuntime.h:53
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Scope(Scope *Parent, unsigned ScopeFlags, DiagnosticsEngine &Diag)
Definition Scope.h:263
Action - Represent an abstract compilation step to perform.
Definition Action.h: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:4882
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:853
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:4027
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:7007
void PrintVersion(const Compilation &C, raw_ostream &OS) const
PrintVersion - Print the driver version.
Definition Driver.cpp:2436
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:905
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:897
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:892
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:9176
void AddX86TargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9159
void AddRISCVTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9184
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:9199
void AddMIPSTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9148
static const char * getBaseInputName(const llvm::opt::ArgList &Args, const InputInfo &Input)
Definition Clang.cpp:9118
Clang(const ToolChain &TC, bool HasIntegratedBackend=true)
Definition Clang.cpp:8610
static const char * getDependencyFileName(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition Clang.cpp:9133
static const char * getBaseInputStem(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition Clang.cpp:9123
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:5147
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:9757
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:9595
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:9505
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:9668
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)
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:186
StringRef parseMPreferVectorWidthOption(clang::DiagnosticsEngine &Diags, const llvm::opt::ArgList &Args)
const char * headerIncludeFilteringKindToString(HeaderIncludeFilteringKind K)
@ C
Languages that the frontend can parse and compile.
@ Asm
Assembly: we accept this only so that we can preprocess it.
@ Default
Set to the current date and time.
@ Result
The result type of a method or function.
Definition TypeBase.h:905
static bool IsNVIDIAOffloadArch(OffloadArch A)
const char * CudaVersionToString(CudaVersion V)
Definition Cuda.cpp:56
LanguageStandard
Supported language standards for parsing and formatting C++ constructs.
Definition Format.h:5800
U cast(CodeGen::Address addr)
Definition Address.h:327
StringRef parseMRecipOption(clang::DiagnosticsEngine &Diags, const llvm::opt::ArgList &Args)
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number,...
Definition Version.cpp:96
bool(*)(llvm::ArrayRef< const char * >, llvm::raw_ostream &, llvm::raw_ostream &, bool, bool) Driver
Definition Wasm.cpp:36
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