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"
28#include "clang/Basic/Version.h"
29#include "clang/Config/config.h"
30#include "clang/Driver/Action.h"
32#include "clang/Driver/Distro.h"
35#include "clang/Driver/Types.h"
39#include "llvm/ADT/ScopeExit.h"
40#include "llvm/ADT/SmallSet.h"
41#include "llvm/ADT/StringExtras.h"
42#include "llvm/BinaryFormat/Magic.h"
43#include "llvm/Config/llvm-config.h"
44#include "llvm/Frontend/Debug/Options.h"
45#include "llvm/Object/ObjectFile.h"
46#include "llvm/Option/ArgList.h"
47#include "llvm/ProfileData/InstrProfReader.h"
48#include "llvm/Support/CodeGen.h"
49#include "llvm/Support/Compiler.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 case types::TY_CIRBC:
362 ClangType = "cir";
363 break;
364 default:
365 ClangType = types::getTypeName(Input.getType());
366 break;
367 }
368 CmdArgs.push_back(ClangType);
369 }
370}
371
373 const JobAction &JA, const InputInfo &Output,
374 const ArgList &Args, SanitizerArgs &SanArgs,
375 ArgStringList &CmdArgs) {
376 const Driver &D = TC.getDriver();
377 const llvm::Triple &T = TC.getTriple();
378 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
379 options::OPT_fprofile_generate_EQ,
380 options::OPT_fno_profile_generate);
381 if (PGOGenerateArg &&
382 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
383 PGOGenerateArg = nullptr;
384
385 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
386
387 auto *ProfileGenerateArg = Args.getLastArg(
388 options::OPT_fprofile_instr_generate,
389 options::OPT_fprofile_instr_generate_EQ,
390 options::OPT_fno_profile_instr_generate);
391 if (ProfileGenerateArg &&
392 ProfileGenerateArg->getOption().matches(
393 options::OPT_fno_profile_instr_generate))
394 ProfileGenerateArg = nullptr;
395
396 if (PGOGenerateArg && ProfileGenerateArg)
397 D.Diag(diag::err_drv_argument_not_allowed_with)
398 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
399
400 auto *ProfileUseArg = getLastProfileUseArg(Args);
401
402 if (PGOGenerateArg && ProfileUseArg)
403 D.Diag(diag::err_drv_argument_not_allowed_with)
404 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
405
406 if (ProfileGenerateArg && ProfileUseArg)
407 D.Diag(diag::err_drv_argument_not_allowed_with)
408 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
409
410 if (CSPGOGenerateArg && PGOGenerateArg) {
411 D.Diag(diag::err_drv_argument_not_allowed_with)
412 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
413 PGOGenerateArg = nullptr;
414 }
415
416 if (TC.getTriple().isOSAIX()) {
417 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
418 D.Diag(diag::err_drv_unsupported_opt_for_target)
419 << ProfileSampleUseArg->getSpelling() << TC.getTripleString();
420 }
421
422 if (ProfileGenerateArg) {
423 if (ProfileGenerateArg->getOption().matches(
424 options::OPT_fprofile_instr_generate_EQ))
425 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
426 ProfileGenerateArg->getValue()));
427 // The default is to use Clang Instrumentation.
428 CmdArgs.push_back("-fprofile-instrument=clang");
429 if (TC.getTriple().isWindowsMSVCEnvironment() &&
430 Args.hasFlag(options::OPT_frtlib_defaultlib,
431 options::OPT_fno_rtlib_defaultlib, true)) {
432 // Add dependent lib for clang_rt.profile
433 CmdArgs.push_back(Args.MakeArgString(
434 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
435 }
436 }
437
438 if (auto *ColdFuncCoverageArg = Args.getLastArg(
439 options::OPT_fprofile_generate_cold_function_coverage,
440 options::OPT_fprofile_generate_cold_function_coverage_EQ)) {
441 SmallString<128> Path(
442 ColdFuncCoverageArg->getOption().matches(
443 options::OPT_fprofile_generate_cold_function_coverage_EQ)
444 ? ColdFuncCoverageArg->getValue()
445 : "");
446 llvm::sys::path::append(Path, "default_%m.profraw");
447 // FIXME: Idealy the file path should be passed through
448 // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is
449 // shared with other profile use path(see PGOOptions), we need to refactor
450 // PGOOptions to make it work.
451 CmdArgs.push_back("-mllvm");
452 CmdArgs.push_back(Args.MakeArgString(
453 Twine("--instrument-cold-function-only-path=") + Path));
454 CmdArgs.push_back("-mllvm");
455 CmdArgs.push_back("--pgo-instrument-cold-function-only");
456 CmdArgs.push_back("-mllvm");
457 CmdArgs.push_back("--pgo-function-entry-coverage");
458 CmdArgs.push_back("-fprofile-instrument=sample-coldcov");
459 }
460
461 if (auto *A = Args.getLastArg(options::OPT_ftemporal_profile)) {
462 if (!PGOGenerateArg && !CSPGOGenerateArg)
463 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
464 << A->getSpelling() << "-fprofile-generate or -fcs-profile-generate";
465 CmdArgs.push_back("-mllvm");
466 CmdArgs.push_back("--pgo-temporal-instrumentation");
467 }
468
469 Arg *PGOGenArg = nullptr;
470 if (PGOGenerateArg) {
471 assert(!CSPGOGenerateArg);
472 PGOGenArg = PGOGenerateArg;
473 CmdArgs.push_back("-fprofile-instrument=llvm");
474 }
475 if (CSPGOGenerateArg) {
476 assert(!PGOGenerateArg);
477 PGOGenArg = CSPGOGenerateArg;
478 CmdArgs.push_back("-fprofile-instrument=csllvm");
479 }
480 if (PGOGenArg) {
481 if (TC.getTriple().isWindowsMSVCEnvironment() &&
482 Args.hasFlag(options::OPT_frtlib_defaultlib,
483 options::OPT_fno_rtlib_defaultlib, true)) {
484 // Add dependent lib for clang_rt.profile
485 CmdArgs.push_back(Args.MakeArgString(
486 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
487 }
488 if (PGOGenArg->getOption().matches(
489 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
490 : options::OPT_fcs_profile_generate_EQ)) {
491 SmallString<128> Path(PGOGenArg->getValue());
492 llvm::sys::path::append(Path, "default_%m.profraw");
493 CmdArgs.push_back(
494 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
495 }
496 }
497
498 if (ProfileUseArg) {
499 SmallString<128> UsePathBuf;
500 StringRef UsePath;
501 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
502 UsePath = ProfileUseArg->getValue();
503 else if ((ProfileUseArg->getOption().matches(
504 options::OPT_fprofile_use_EQ) ||
505 ProfileUseArg->getOption().matches(
506 options::OPT_fprofile_instr_use))) {
507 UsePathBuf =
508 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue();
509 if (UsePathBuf.empty() || llvm::sys::fs::is_directory(UsePathBuf))
510 llvm::sys::path::append(UsePathBuf, "default.profdata");
511 UsePath = UsePathBuf;
512 }
513 auto ReaderOrErr =
514 llvm::IndexedInstrProfReader::create(UsePath, D.getVFS());
515 if (auto E = ReaderOrErr.takeError()) {
516 auto DiagID = D.getDiags().getCustomDiagID(
517 DiagnosticsEngine::Error, "Error in reading profile %0: %1");
518 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
519 D.Diag(DiagID) << UsePath.str() << EI.message();
520 });
521 } else {
522 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
523 std::move(ReaderOrErr.get());
524 StringRef UseKind;
525 // Currently memprof profiles are only added at the IR level. Mark the
526 // profile type as IR in that case as well and the subsequent matching
527 // needs to detect which is available (might be one or both).
528 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
529 if (PGOReader->hasCSIRLevelProfile())
530 UseKind = "csllvm";
531 else
532 UseKind = "llvm";
533 } else
534 UseKind = "clang";
535
536 CmdArgs.push_back(
537 Args.MakeArgString("-fprofile-instrument-use=" + UseKind));
538 CmdArgs.push_back(
539 Args.MakeArgString("-fprofile-instrument-use-path=" + UsePath));
540 }
541 }
542
543 bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
544 options::OPT_fno_test_coverage, false) ||
545 Args.hasArg(options::OPT_coverage);
546 bool EmitCovData = TC.needsGCovInstrumentation(Args);
547
548 if (Args.hasFlag(options::OPT_fcoverage_mapping,
549 options::OPT_fno_coverage_mapping, false)) {
550 if (!ProfileGenerateArg)
551 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
552 << "-fcoverage-mapping"
553 << "-fprofile-instr-generate";
554
555 CmdArgs.push_back("-fcoverage-mapping");
556 }
557
558 if (Args.hasFlag(options::OPT_fmcdc_coverage, options::OPT_fno_mcdc_coverage,
559 false)) {
560 if (!Args.hasFlag(options::OPT_fcoverage_mapping,
561 options::OPT_fno_coverage_mapping, false))
562 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
563 << "-fcoverage-mcdc"
564 << "-fcoverage-mapping";
565
566 CmdArgs.push_back("-fcoverage-mcdc");
567 }
568
569 StringRef CoverageCompDir;
570 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
571 options::OPT_fcoverage_compilation_dir_EQ))
572 CoverageCompDir = A->getValue();
573 if (CoverageCompDir.empty()) {
574 if (auto CWD = D.getVFS().getCurrentWorkingDirectory())
575 CmdArgs.push_back(
576 Args.MakeArgString(Twine("-fcoverage-compilation-dir=") + *CWD));
577 } else
578 CmdArgs.push_back(Args.MakeArgString(Twine("-fcoverage-compilation-dir=") +
579 CoverageCompDir));
580
581 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
582 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
583 if (!Args.hasArg(options::OPT_coverage))
584 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
585 << "-fprofile-exclude-files="
586 << "--coverage";
587
588 StringRef v = Arg->getValue();
589 CmdArgs.push_back(
590 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
591 }
592
593 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
594 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
595 if (!Args.hasArg(options::OPT_coverage))
596 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
597 << "-fprofile-filter-files="
598 << "--coverage";
599
600 StringRef v = Arg->getValue();
601 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
602 }
603
604 if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
605 StringRef Val = A->getValue();
606 if (Val == "atomic" || Val == "prefer-atomic")
607 CmdArgs.push_back("-fprofile-update=atomic");
608 else if (Val != "single")
609 D.Diag(diag::err_drv_unsupported_option_argument)
610 << A->getSpelling() << Val;
611 }
612 if (const auto *A = Args.getLastArg(options::OPT_fprofile_continuous)) {
613 if (!PGOGenerateArg && !CSPGOGenerateArg && !ProfileGenerateArg)
614 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
615 << A->getSpelling()
616 << "-fprofile-generate, -fprofile-instr-generate, or "
617 "-fcs-profile-generate";
618 else {
619 CmdArgs.push_back("-fprofile-continuous");
620 // Platforms that require a bias variable:
621 if (T.isOSBinFormatELF() || T.isOSAIX() || T.isOSWindows()) {
622 CmdArgs.push_back("-mllvm");
623 CmdArgs.push_back("-runtime-counter-relocation");
624 }
625 // -fprofile-instr-generate does not decide the profile file name in the
626 // FE, and so it does not define the filename symbol
627 // (__llvm_profile_filename). Instead, the runtime uses the name
628 // "default.profraw" for the profile file. When continuous mode is ON, we
629 // will create the filename symbol so that we can insert the "%c"
630 // modifier.
631 if (ProfileGenerateArg &&
632 (ProfileGenerateArg->getOption().matches(
633 options::OPT_fprofile_instr_generate) ||
634 (ProfileGenerateArg->getOption().matches(
635 options::OPT_fprofile_instr_generate_EQ) &&
636 strlen(ProfileGenerateArg->getValue()) == 0)))
637 CmdArgs.push_back("-fprofile-instrument-path=default.profraw");
638 }
639 }
640
641 int FunctionGroups = 1;
642 int SelectedFunctionGroup = 0;
643 if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
644 StringRef Val = A->getValue();
645 if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
646 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
647 }
648 if (const auto *A =
649 Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
650 StringRef Val = A->getValue();
651 if (Val.getAsInteger(0, SelectedFunctionGroup) ||
652 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
653 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
654 }
655 if (FunctionGroups != 1)
656 CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
657 Twine(FunctionGroups)));
658 if (SelectedFunctionGroup != 0)
659 CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
660 Twine(SelectedFunctionGroup)));
661
662 // Leave -fprofile-dir= an unused argument unless .gcda emission is
663 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
664 // the flag used. There is no -fno-profile-dir, so the user has no
665 // targeted way to suppress the warning.
666 Arg *FProfileDir = nullptr;
667 if (Args.hasArg(options::OPT_fprofile_arcs) ||
668 Args.hasArg(options::OPT_coverage))
669 FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
670
671 // Put the .gcno and .gcda files (if needed) next to the primary output file,
672 // or fall back to a file in the current directory for `clang -c --coverage
673 // d/a.c` in the absence of -o.
674 if (EmitCovNotes || EmitCovData) {
675 SmallString<128> CoverageFilename;
676 if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
677 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
678 // path separator.
679 CoverageFilename = DumpDir->getValue();
680 CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
681 } else if (Arg *FinalOutput =
682 C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
683 CoverageFilename = FinalOutput->getValue();
684 } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
685 CoverageFilename = FinalOutput->getValue();
686 } else {
687 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
688 }
689 if (llvm::sys::path::is_relative(CoverageFilename))
690 (void)D.getVFS().makeAbsolute(CoverageFilename);
691 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
692 if (EmitCovNotes) {
693 CmdArgs.push_back(
694 Args.MakeArgString("-coverage-notes-file=" + CoverageFilename));
695
696 bool UseAbsolutePathsInNotes =
697 Args.hasFlag(options::OPT_fprofile_abs_path,
698 options::OPT_fno_profile_abs_path, false);
699 if (UseAbsolutePathsInNotes)
700 CmdArgs.push_back(Args.MakeArgString("-coverage-notes-abs-paths"));
701 }
702
703 if (EmitCovData) {
704 if (FProfileDir) {
705 SmallString<128> Gcno = std::move(CoverageFilename);
706 CoverageFilename = FProfileDir->getValue();
707 llvm::sys::path::append(CoverageFilename, Gcno);
708 }
709 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
710 CmdArgs.push_back(
711 Args.MakeArgString("-coverage-data-file=" + CoverageFilename));
712 }
713 }
714}
715
716static void
717RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
718 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
719 unsigned DwarfVersion,
720 llvm::DebuggerKind DebuggerTuning) {
721 addDebugInfoKind(CmdArgs, DebugInfoKind);
722 if (DwarfVersion > 0)
723 CmdArgs.push_back(
724 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
725 switch (DebuggerTuning) {
726 case llvm::DebuggerKind::GDB:
727 CmdArgs.push_back("-debugger-tuning=gdb");
728 break;
729 case llvm::DebuggerKind::LLDB:
730 CmdArgs.push_back("-debugger-tuning=lldb");
731 break;
732 case llvm::DebuggerKind::SCE:
733 CmdArgs.push_back("-debugger-tuning=sce");
734 break;
735 case llvm::DebuggerKind::DBX:
736 CmdArgs.push_back("-debugger-tuning=dbx");
737 break;
738 default:
739 break;
740 }
741}
742
744 const ArgList &Args,
745 ArgStringList &CmdArgs,
746 bool IsCC1As = false) {
747 // If no version was requested by the user, use the default value from the
748 // back end. This is consistent with the value returned from
749 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
750 // requiring the corresponding llvm to have the AMDGPU target enabled,
751 // provided the user (e.g. front end tests) can use the default.
753 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
754 CmdArgs.insert(CmdArgs.begin() + 1,
755 Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
756 Twine(CodeObjVer)));
757 CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
758 // -cc1as does not accept -mcode-object-version option.
759 if (!IsCC1As)
760 CmdArgs.insert(CmdArgs.begin() + 1,
761 Args.MakeArgString(Twine("-mcode-object-version=") +
762 Twine(CodeObjVer)));
763 }
764}
765
766static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
767 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
768 D.getVFS().getBufferForFile(Path);
769 if (!MemBuf)
770 return false;
771 llvm::file_magic Magic = llvm::identify_magic((*MemBuf)->getBuffer());
772 if (Magic == llvm::file_magic::unknown)
773 return false;
774 // Return true for both raw Clang AST files and object files which may
775 // contain a __clangast section.
776 if (Magic == llvm::file_magic::clang_ast)
777 return true;
779 llvm::object::ObjectFile::createObjectFile(**MemBuf, Magic);
780 return !Obj.takeError();
781}
782
783static bool gchProbe(const Driver &D, StringRef Path) {
784 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
785 if (!Status)
786 return false;
787
788 if (Status->isDirectory()) {
789 std::error_code EC;
790 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Path, EC), DE;
791 !EC && DI != DE; DI = DI.increment(EC)) {
792 if (maybeHasClangPchSignature(D, DI->path()))
793 return true;
794 }
795 D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;
796 return false;
797 }
798
799 if (maybeHasClangPchSignature(D, Path))
800 return true;
801 D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;
802 return false;
803}
804
805void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
806 const Driver &D, const ArgList &Args,
807 ArgStringList &CmdArgs,
808 const InputInfo &Output,
809 const InputInfoList &Inputs) const {
810 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
811
813
814 Args.AddLastArg(CmdArgs, options::OPT_C);
815 Args.AddLastArg(CmdArgs, options::OPT_CC);
816
817 // Handle dependency file generation.
818 Arg *ArgM = Args.getLastArg(options::OPT_MM);
819 if (!ArgM)
820 ArgM = Args.getLastArg(options::OPT_M);
821 Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
822 if (!ArgMD)
823 ArgMD = Args.getLastArg(options::OPT_MD);
824
825 // -M and -MM imply -w.
826 if (ArgM)
827 CmdArgs.push_back("-w");
828 else
829 ArgM = ArgMD;
830
831 if (ArgM) {
833 // Determine the output location.
834 const char *DepFile;
835 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
836 DepFile = MF->getValue();
837 C.addFailureResultFile(DepFile, &JA);
838 } else if (Output.getType() == types::TY_Dependencies) {
839 DepFile = Output.getFilename();
840 } else if (!ArgMD) {
841 DepFile = "-";
842 } else {
843 DepFile = getDependencyFileName(Args, Inputs);
844 C.addFailureResultFile(DepFile, &JA);
845 }
846 CmdArgs.push_back("-dependency-file");
847 CmdArgs.push_back(DepFile);
848 }
849 // Cmake generates dependency files using all compilation options specified
850 // by users. Claim those not used for dependency files.
852 Args.ClaimAllArgs(options::OPT_offload_compress);
853 Args.ClaimAllArgs(options::OPT_no_offload_compress);
854 Args.ClaimAllArgs(options::OPT_offload_jobs_EQ);
855 }
856
857 bool HasTarget = false;
858 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
859 HasTarget = true;
860 A->claim();
861 if (A->getOption().matches(options::OPT_MT)) {
862 A->render(Args, CmdArgs);
863 } else {
864 CmdArgs.push_back("-MT");
865 SmallString<128> Quoted;
866 quoteMakeTarget(A->getValue(), Quoted);
867 CmdArgs.push_back(Args.MakeArgString(Quoted));
868 }
869 }
870
871 // Add a default target if one wasn't specified.
872 if (!HasTarget) {
873 const char *DepTarget;
874
875 // If user provided -o, that is the dependency target, except
876 // when we are only generating a dependency file.
877 Arg *OutputOpt = Args.getLastArg(options::OPT_o, options::OPT__SLASH_Fo);
878 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
879 DepTarget = OutputOpt->getValue();
880 } else {
881 // Otherwise derive from the base input.
882 //
883 // FIXME: This should use the computed output file location.
884 SmallString<128> P(Inputs[0].getBaseInput());
885 llvm::sys::path::replace_extension(P, "o");
886 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
887 }
888
889 CmdArgs.push_back("-MT");
890 SmallString<128> Quoted;
891 quoteMakeTarget(DepTarget, Quoted);
892 CmdArgs.push_back(Args.MakeArgString(Quoted));
893 }
894
895 if (ArgM->getOption().matches(options::OPT_M) ||
896 ArgM->getOption().matches(options::OPT_MD))
897 CmdArgs.push_back("-sys-header-deps");
898
899 // Determine module file deps mode.
900 StringRef ModuleFileDepsVal;
901 if (Arg *A = Args.getLastArg(options::OPT_fmodule_file_deps_EQ,
902 options::OPT_fmodule_file_deps,
903 options::OPT_fno_module_file_deps)) {
904 if (A->getOption().matches(options::OPT_fmodule_file_deps_EQ))
905 ModuleFileDepsVal = A->getValue();
906 else if (A->getOption().matches(options::OPT_fmodule_file_deps))
907 ModuleFileDepsVal = "all";
908 else
909 ModuleFileDepsVal = "none";
910 } else if (isa<PrecompileJobAction>(JA)) {
911 ModuleFileDepsVal = "all";
912 }
913 if (!ModuleFileDepsVal.empty() && ModuleFileDepsVal != "none")
914 CmdArgs.push_back(
915 Args.MakeArgString("-module-file-deps=" + ModuleFileDepsVal));
916 }
917
918 if (Args.hasArg(options::OPT_MG)) {
919 if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
920 ArgM->getOption().matches(options::OPT_MMD))
921 D.Diag(diag::err_drv_mg_requires_m_or_mm);
922 CmdArgs.push_back("-MG");
923 }
924
925 Args.AddLastArg(CmdArgs, options::OPT_MP);
926 Args.AddLastArg(CmdArgs, options::OPT_MV);
927
928 bool UsesLLVMOffloading = Args.hasFlag(
929 options::OPT_foffload_via_llvm, options::OPT_fno_offload_via_llvm, false);
930 bool UsesOffloadInclude =
931 Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc, true);
932 bool NoBuiltinInc = Args.hasArg(options::OPT_nobuiltininc);
933
934 // Add offload include arguments for CUDA/HIP when using LLVM offloading. We
935 // want to pull in our wrappers instead of the vendor headers.
936 if (UsesLLVMOffloading) {
937 if (UsesOffloadInclude && !NoBuiltinInc) {
938 auto AddOffloadHeadersInclude = [&](StringRef IncludeSubdir,
939 StringRef RuntimeHeader) {
940 SmallString<128> OffloadInclude(D.Dir);
941 llvm::sys::path::append(OffloadInclude, "..", "include", "offload");
942 if (!IncludeSubdir.empty())
943 llvm::sys::path::append(OffloadInclude, IncludeSubdir);
944 CmdArgs.append({"-internal-isystem", Args.MakeArgString(OffloadInclude),
945 "-include", Args.MakeArgString(RuntimeHeader)});
946 };
947 auto AddForcedInclude = [&](StringRef Header) {
948 CmdArgs.push_back("-include");
949 CmdArgs.push_back(Args.MakeArgString(Header));
950 };
951 AddForcedInclude("__clang_gpu_runtime_wrapper.h");
952 AddForcedInclude("__clang_gpu_builtin_vars.h");
953 AddForcedInclude("__clang_gpu_device_functions.h");
954 AddForcedInclude("__clang_gpu_intrinsics.h");
956 AddOffloadHeadersInclude("cuda", "cuda_runtime.h");
958 !Args.hasArg(options::OPT_nohipwrapperinc)) {
959 // HIP code commonly includes this as "hip/hip_runtime.h".
960 AddOffloadHeadersInclude("", "hip/hip_runtime.h");
961 }
962 }
963 } else {
964 // Add offload include arguments specific for CUDA/HIP/SYCL. This must
965 // happen before we -I or -include anything else, because we must pick up
966 // the CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL
967 // installation, rather than from e.g. /usr/local/include.
969 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
971 getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
973 getToolChain().addSYCLIncludeArgs(Args, CmdArgs);
974
975 // If we are offloading to a target via OpenMP we need to include the
976 // openmp_wrappers folder which contains alternative system headers.
978 !Args.hasArg(options::OPT_nostdinc) && UsesOffloadInclude &&
979 getToolChain().getTriple().isGPU()) {
980 if (!NoBuiltinInc) {
981 // Add openmp_wrappers/* to our system include path. This lets us
982 // wrap standard library headers.
983 SmallString<128> P(D.ResourceDir);
984 llvm::sys::path::append(P, "include");
985 llvm::sys::path::append(P, "openmp_wrappers");
986 CmdArgs.push_back("-internal-isystem");
987 CmdArgs.push_back(Args.MakeArgString(P));
988 }
989
990 CmdArgs.push_back("-include");
991 CmdArgs.push_back("__clang_openmp_device_functions.h");
992 }
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 (Arch.Arch.isNVPTX())
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 with the LLVM environment we want to
1167 // override the system headers with ones created by the 'libc' project if
1168 // present.
1169 // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1170 // OffloadKind as an argument.
1171 bool OffloadUsesLLVMLibc =
1172 C.getActiveOffloadKinds() == Action::OFK_OpenMP ||
1173 (C.getActiveOffloadKinds() != Action::OFK_None &&
1174 getToolChain().getTriple().getEnvironment() == llvm::Triple::LLVM);
1175 if (!Args.hasArg(options::OPT_nostdinc) &&
1176 Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc,
1177 true) &&
1178 !Args.hasArg(options::OPT_nobuiltininc) && OffloadUsesLLVMLibc) {
1179 SmallString<128> P(D.ResourceDir);
1180 llvm::sys::path::append(P, "include");
1181 llvm::sys::path::append(P, "llvm_libc_wrappers");
1182 CmdArgs.push_back("-internal-isystem");
1183 CmdArgs.push_back(Args.MakeArgString(P));
1184 }
1185
1186 // Add system include arguments for all targets but IAMCU.
1187 if (!IsIAMCU)
1189 [&Args, &CmdArgs](const ToolChain &TC) {
1190 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1191 });
1192 else {
1193 // For IAMCU add special include arguments.
1194 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1195 }
1196
1197 addMacroPrefixMapArg(D, Args, CmdArgs);
1198 addCoveragePrefixMapArg(D, Args, CmdArgs);
1199
1200 Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
1201 options::OPT_fno_file_reproducible);
1202
1203 if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1204 CmdArgs.push_back("-source-date-epoch");
1205 CmdArgs.push_back(Args.MakeArgString(Epoch));
1206 }
1207
1208 Args.addOptInFlag(CmdArgs, options::OPT_fdefine_target_os_macros,
1209 options::OPT_fno_define_target_os_macros);
1210}
1211
1212// FIXME: Move to target hook.
1213static bool isSignedCharDefault(const llvm::Triple &Triple) {
1214 switch (Triple.getArch()) {
1215 default:
1216 return true;
1217
1218 case llvm::Triple::aarch64:
1219 case llvm::Triple::aarch64_32:
1220 case llvm::Triple::aarch64_be:
1221 case llvm::Triple::arm:
1222 case llvm::Triple::armeb:
1223 case llvm::Triple::thumb:
1224 case llvm::Triple::thumbeb:
1225 if (Triple.isOSDarwin() || Triple.isOSWindowsOrUEFI())
1226 return true;
1227 return false;
1228
1229 case llvm::Triple::ppc:
1230 case llvm::Triple::ppc64:
1231 if (Triple.isOSDarwin())
1232 return true;
1233 return false;
1234
1235 case llvm::Triple::csky:
1236 case llvm::Triple::hexagon:
1237 case llvm::Triple::msp430:
1238 case llvm::Triple::ppcle:
1239 case llvm::Triple::ppc64le:
1240 case llvm::Triple::riscv32:
1241 case llvm::Triple::riscv64:
1242 case llvm::Triple::riscv32be:
1243 case llvm::Triple::riscv64be:
1244 case llvm::Triple::systemz:
1245 case llvm::Triple::xcore:
1246 case llvm::Triple::xtensa:
1247 return false;
1248 }
1249}
1250
1251static bool hasMultipleInvocations(const llvm::Triple &Triple,
1252 const ArgList &Args) {
1253 // Supported only on Darwin where we invoke the compiler multiple times
1254 // followed by an invocation to lipo.
1255 if (!Triple.isOSDarwin())
1256 return false;
1257 // If more than one "-arch <arch>" is specified, we're targeting multiple
1258 // architectures resulting in a fat binary.
1259 return Args.getAllArgValues(options::OPT_arch).size() > 1;
1260}
1261
1262static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1263 const llvm::Triple &Triple) {
1264 // When enabling remarks, we need to error if:
1265 // * The remark file is specified but we're targeting multiple architectures,
1266 // which means more than one remark file is being generated.
1268 bool hasExplicitOutputFile =
1269 Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1270 if (hasMultipleInvocations && hasExplicitOutputFile) {
1271 D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1272 << "-foptimization-record-file";
1273 return false;
1274 }
1275 return true;
1276}
1277
1278static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1279 const llvm::Triple &Triple,
1280 const InputInfo &Input,
1281 const InputInfo &Output, const JobAction &JA) {
1282 StringRef Format = "yaml";
1283 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1284 Format = A->getValue();
1285
1286 CmdArgs.push_back("-opt-record-file");
1287
1288 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1289 if (A) {
1290 CmdArgs.push_back(A->getValue());
1291 } else {
1292 bool hasMultipleArchs =
1293 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1294 Args.getAllArgValues(options::OPT_arch).size() > 1;
1295
1297
1298 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1299 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1300 F = FinalOutput->getValue();
1301 } else {
1302 if (Format != "yaml" && // For YAML, keep the original behavior.
1303 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1304 Output.isFilename())
1305 F = Output.getFilename();
1306 }
1307
1308 if (F.empty()) {
1309 // Use the input filename.
1310 F = llvm::sys::path::stem(Input.getBaseInput());
1311
1312 // If we're compiling for an offload architecture (i.e. a CUDA device),
1313 // we need to make the file name for the device compilation different
1314 // from the host compilation.
1317 llvm::sys::path::replace_extension(F, "");
1319 Triple.str());
1320 F += "-";
1321 F += JA.getOffloadingArch().ArchName;
1322 }
1323 }
1324
1325 // If we're having more than one "-arch", we should name the files
1326 // differently so that every cc1 invocation writes to a different file.
1327 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1328 // name from the triple.
1329 if (hasMultipleArchs) {
1330 // First, remember the extension.
1331 SmallString<64> OldExtension = llvm::sys::path::extension(F);
1332 // then, remove it.
1333 llvm::sys::path::replace_extension(F, "");
1334 // attach -<arch> to it.
1335 F += "-";
1336 F += Triple.getArchName();
1337 // put back the extension.
1338 llvm::sys::path::replace_extension(F, OldExtension);
1339 }
1340
1341 SmallString<32> Extension;
1342 Extension += "opt.";
1343 Extension += Format;
1344
1345 llvm::sys::path::replace_extension(F, Extension);
1346 CmdArgs.push_back(Args.MakeArgString(F));
1347 }
1348
1349 if (const Arg *A =
1350 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1351 CmdArgs.push_back("-opt-record-passes");
1352 CmdArgs.push_back(A->getValue());
1353 }
1354
1355 if (!Format.empty()) {
1356 CmdArgs.push_back("-opt-record-format");
1357 CmdArgs.push_back(Format.data());
1358 }
1359}
1360
1361void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1362 if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1363 options::OPT_fno_aapcs_bitfield_width, true))
1364 CmdArgs.push_back("-fno-aapcs-bitfield-width");
1365
1366 if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1367 CmdArgs.push_back("-faapcs-bitfield-load");
1368}
1369
1370namespace {
1371void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1372 const ArgList &Args, ArgStringList &CmdArgs) {
1373 // Select the ABI to use.
1374 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1375 const char *ABIName = nullptr;
1376 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1377 ABIName = A->getValue();
1378 else
1379 ABIName = llvm::ARM::computeDefaultTargetABI(Triple).data();
1380
1381 CmdArgs.push_back("-target-abi");
1382 CmdArgs.push_back(ABIName);
1383}
1384
1385void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1386 auto StrictAlignIter =
1387 llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
1388 return Arg == "+strict-align" || Arg == "-strict-align";
1389 });
1390 if (StrictAlignIter != CmdArgs.rend() &&
1391 StringRef(*StrictAlignIter) == "+strict-align")
1392 CmdArgs.push_back("-Wunaligned-access");
1393}
1394}
1395
1396static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1397 ArgStringList &CmdArgs, bool isAArch64) {
1398 const llvm::Triple &Triple = TC.getEffectiveTriple();
1399 const Arg *A = isAArch64
1400 ? Args.getLastArg(options::OPT_msign_return_address_EQ,
1401 options::OPT_mbranch_protection_EQ)
1402 : Args.getLastArg(options::OPT_mbranch_protection_EQ);
1403 const Arg *HardenPACRetArg = Args.getLastArg(options::OPT_mharden_pac_ret_EQ);
1404 const Driver &D = TC.getDriver();
1405
1406 if (HardenPACRetArg) {
1407 if (!isAArch64) {
1408 D.Diag(diag::err_drv_unsupported_opt_for_target)
1409 << HardenPACRetArg->getSpelling() << TC.getTriple().str();
1410 return;
1411 }
1412 StringRef ArgValue = HardenPACRetArg->getValue();
1413 if (ArgValue != "none" && ArgValue != "load-return-address") {
1414 D.Diag(diag::err_drv_unsupported_option_argument)
1415 << HardenPACRetArg->getSpelling() << ArgValue;
1416 return;
1417 }
1418 if (ArgValue != "none" &&
1419 Args.hasFlagNoClaim(options::OPT_mexecute_only,
1420 options::OPT_mno_execute_only, false)) {
1421 D.Diag(diag::err_drv_incompatible_options)
1422 << HardenPACRetArg->getAsString(Args) << "-mexecute-only";
1423 return;
1424 }
1425 }
1426
1427 // Check CmdArgs because some toolchains bypass the driver args and add to
1428 // the frontend args directly.
1429 bool HasPtrauthReturns =
1430 llvm::is_contained(CmdArgs, StringRef("-fptrauth-returns")) ||
1431 Args.hasFlagNoClaim(options::OPT_fptrauth_returns,
1432 options::OPT_fno_ptrauth_returns, false);
1433
1434 auto RenderHardenPACRet = [&](StringRef Scope) {
1435 if (!HardenPACRetArg)
1436 return;
1437 if (Scope == "none" && !HasPtrauthReturns)
1438 D.Diag(diag::warn_harden_pac_ret_requires_pac_ret);
1439 else
1440 CmdArgs.push_back(Args.MakeArgString(Twine("-mharden-pac-ret=") +
1441 HardenPACRetArg->getValue()));
1442 };
1443
1444 if (!A) {
1445 if ((Triple.isOSOpenBSD() || Triple.isAndroid()) && isAArch64) {
1446 CmdArgs.push_back("-msign-return-address=non-leaf");
1447 CmdArgs.push_back("-msign-return-address-key=a_key");
1448 CmdArgs.push_back("-mbranch-target-enforce");
1449 RenderHardenPACRet("non-leaf");
1450 } else {
1451 RenderHardenPACRet("none");
1452 }
1453 return;
1454 }
1455
1456 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1457 D.Diag(diag::warn_incompatible_branch_protection_option)
1458 << Triple.getArchName();
1459
1460 StringRef Scope, Key;
1461 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1462
1463 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1464 Scope = A->getValue();
1465 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1466 D.Diag(diag::err_drv_unsupported_option_argument)
1467 << A->getSpelling() << Scope;
1468 // This spelling cannot express a key, and AArch64 Windows and UEFI only
1469 // support B-key, so default to it there as parseBranchProtection() does.
1470 Key = isAArch64 && Triple.isOSWindowsOrUEFI() ? "b_key" : "a_key";
1471 IndirectBranches =
1472 (Triple.isOSOpenBSD() || Triple.isAndroid()) && isAArch64;
1473 BranchProtectionPAuthLR = false;
1474 GuardedControlStack = false;
1475 } else {
1476 StringRef DiagMsg;
1477 llvm::ARM::ParsedBranchProtection PBP;
1478 bool EnablePAuthLR = false;
1479
1480 // To know if we need to enable PAuth-LR As part of the standard branch
1481 // protection option, it needs to be determined if the feature has been
1482 // activated in the `march` argument. This information is stored within the
1483 // CmdArgs variable and can be found using a search.
1484 if (isAArch64) {
1485 auto isPAuthLR = [](const char *member) {
1486 llvm::AArch64::ExtensionInfo pauthlr_extension =
1487 llvm::AArch64::getExtensionByID(llvm::AArch64::AEK_PAUTHLR);
1488 return llvm::AArch64::StrTab[pauthlr_extension.PosTargetFeature] ==
1489 member;
1490 };
1491
1492 if (llvm::any_of(CmdArgs, isPAuthLR))
1493 EnablePAuthLR = true;
1494 }
1495 if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg, Triple,
1496 EnablePAuthLR))
1497 D.Diag(diag::err_drv_unsupported_option_argument)
1498 << A->getSpelling() << DiagMsg;
1499 if (!isAArch64 && PBP.Key == "b_key")
1500 D.Diag(diag::warn_unsupported_branch_protection)
1501 << "b-key" << A->getAsString(Args);
1502 Scope = PBP.Scope;
1503 Key = PBP.Key;
1504 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1505 IndirectBranches = PBP.BranchTargetEnforcement;
1506 GuardedControlStack = PBP.GuardedControlStack;
1507 }
1508
1509 // GCS is currently untested with ptrauth-returns, but enabling this could be
1510 // allowed in future after testing with a suitable system.
1511 if (Scope != "none" || BranchProtectionPAuthLR || GuardedControlStack) {
1512 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1513 D.Diag(diag::err_drv_unsupported_opt_for_target)
1514 << A->getAsString(Args) << Triple.getTriple();
1515 else if (HasPtrauthReturns)
1516 D.Diag(diag::err_drv_incompatible_options)
1517 << A->getAsString(Args) << "-fptrauth-returns";
1518 }
1519
1520 CmdArgs.push_back(
1521 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1522 if (Scope != "none")
1523 CmdArgs.push_back(
1524 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1525 if (BranchProtectionPAuthLR)
1526 CmdArgs.push_back(
1527 Args.MakeArgString(Twine("-mbranch-protection-pauth-lr")));
1528 if (IndirectBranches)
1529 CmdArgs.push_back("-mbranch-target-enforce");
1530
1531 if (GuardedControlStack)
1532 CmdArgs.push_back("-mguarded-control-stack");
1533
1534 RenderHardenPACRet(Scope);
1535}
1536
1537void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1538 ArgStringList &CmdArgs, bool KernelOrKext) const {
1539 RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
1540
1541 // Determine floating point ABI from the options & target defaults.
1543 if (ABI == arm::FloatABI::Soft) {
1544 // Floating point operations and argument passing are soft.
1545 // FIXME: This changes CPP defines, we need -target-soft-float.
1546 CmdArgs.push_back("-msoft-float");
1547 CmdArgs.push_back("-mfloat-abi");
1548 CmdArgs.push_back("soft");
1549 } else if (ABI == arm::FloatABI::SoftFP) {
1550 // Floating point operations are hard, but argument passing is soft.
1551 CmdArgs.push_back("-mfloat-abi");
1552 CmdArgs.push_back("soft");
1553 } else {
1554 // Floating point operations and argument passing are hard.
1555 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1556 CmdArgs.push_back("-mfloat-abi");
1557 CmdArgs.push_back("hard");
1558 }
1559
1560 // Forward the -mglobal-merge option for explicit control over the pass.
1561 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1562 options::OPT_mno_global_merge)) {
1563 CmdArgs.push_back("-mllvm");
1564 if (A->getOption().matches(options::OPT_mno_global_merge))
1565 CmdArgs.push_back("-arm-global-merge=false");
1566 else
1567 CmdArgs.push_back("-arm-global-merge=true");
1568 }
1569
1570 if (!Args.hasFlag(options::OPT_mimplicit_float,
1571 options::OPT_mno_implicit_float, true))
1572 CmdArgs.push_back("-no-implicit-float");
1573
1574 if (Args.getLastArg(options::OPT_mcmse))
1575 CmdArgs.push_back("-mcmse");
1576
1577 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1578
1579 // Enable/disable return address signing and indirect branch targets.
1580 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
1581
1582 AddUnalignedAccessWarning(CmdArgs);
1583}
1584
1585void Clang::AddAMDGPUTargetArgs(const ArgList &Args,
1586 ArgStringList &CmdArgs) const {
1587 // Pass through -mxnack/-mno-xnack and -msramecc/-mno-sramecc flags to cc1.
1588 if (Arg *A = Args.getLastArg(options::OPT_mxnack, options::OPT_mno_xnack))
1589 A->render(Args, CmdArgs);
1590 if (Arg *A = Args.getLastArg(options::OPT_msramecc, options::OPT_mno_sramecc))
1591 A->render(Args, CmdArgs);
1592}
1593
1594void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1595 const ArgList &Args, bool KernelOrKext,
1596 ArgStringList &CmdArgs) const {
1597 const ToolChain &TC = getToolChain();
1598
1599 // Add the target features
1600 getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1601
1602 // Add target specific flags.
1603 switch (TC.getArch()) {
1604 default:
1605 break;
1606
1607 case llvm::Triple::arm:
1608 case llvm::Triple::armeb:
1609 case llvm::Triple::thumb:
1610 case llvm::Triple::thumbeb:
1611 // Use the effective triple, which takes into account the deployment target.
1612 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1613 break;
1614
1615 case llvm::Triple::aarch64:
1616 case llvm::Triple::aarch64_32:
1617 case llvm::Triple::aarch64_be:
1618 AddAArch64TargetArgs(Args, CmdArgs);
1619 break;
1620
1621 case llvm::Triple::amdgpu:
1622 AddAMDGPUTargetArgs(Args, CmdArgs);
1623 break;
1624
1625 case llvm::Triple::loongarch32:
1626 case llvm::Triple::loongarch64:
1627 AddLoongArchTargetArgs(Args, CmdArgs);
1628 break;
1629
1630 case llvm::Triple::mips:
1631 case llvm::Triple::mipsel:
1632 case llvm::Triple::mips64:
1633 case llvm::Triple::mips64el:
1634 AddMIPSTargetArgs(Args, CmdArgs);
1635 break;
1636
1637 case llvm::Triple::ppc:
1638 case llvm::Triple::ppcle:
1639 case llvm::Triple::ppc64:
1640 case llvm::Triple::ppc64le:
1641 AddPPCTargetArgs(Args, CmdArgs);
1642 break;
1643
1644 case llvm::Triple::riscv32:
1645 case llvm::Triple::riscv64:
1646 case llvm::Triple::riscv32be:
1647 case llvm::Triple::riscv64be:
1648 AddRISCVTargetArgs(Args, CmdArgs);
1649 break;
1650
1651 case llvm::Triple::sparc:
1652 case llvm::Triple::sparcel:
1653 case llvm::Triple::sparcv9:
1654 AddSparcTargetArgs(Args, CmdArgs);
1655 break;
1656
1657 case llvm::Triple::systemz:
1658 AddSystemZTargetArgs(Args, CmdArgs);
1659 break;
1660
1661 case llvm::Triple::x86:
1662 case llvm::Triple::x86_64:
1663 AddX86TargetArgs(Args, CmdArgs);
1664 break;
1665
1666 case llvm::Triple::lanai:
1667 AddLanaiTargetArgs(Args, CmdArgs);
1668 break;
1669
1670 case llvm::Triple::hexagon:
1671 AddHexagonTargetArgs(Args, CmdArgs);
1672 break;
1673
1674 case llvm::Triple::wasm32:
1675 case llvm::Triple::wasm64:
1676 AddWebAssemblyTargetArgs(Args, CmdArgs);
1677 break;
1678
1679 case llvm::Triple::ve:
1680 AddVETargetArgs(Args, CmdArgs);
1681 break;
1682 }
1683}
1684
1685namespace {
1686void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1687 ArgStringList &CmdArgs) {
1688 const char *ABIName = nullptr;
1689 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1690 ABIName = A->getValue();
1691 else if (Triple.isOSDarwin())
1692 ABIName = "darwinpcs";
1693 // TODO: we probably want to have some target hook here.
1694 else if (Triple.isOSLinux() &&
1695 Triple.getEnvironment() == llvm::Triple::PAuthTest)
1696 ABIName = "pauthtest";
1697 else
1698 ABIName = "aapcs";
1699
1700 CmdArgs.push_back("-target-abi");
1701 CmdArgs.push_back(ABIName);
1702}
1703}
1704
1705void Clang::AddAArch64TargetArgs(const ArgList &Args,
1706 ArgStringList &CmdArgs) const {
1707 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1708
1709 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1710 Args.hasArg(options::OPT_mkernel) ||
1711 Args.hasArg(options::OPT_fapple_kext))
1712 CmdArgs.push_back("-disable-red-zone");
1713
1714 if (!Args.hasFlag(options::OPT_mimplicit_float,
1715 options::OPT_mno_implicit_float, true))
1716 CmdArgs.push_back("-no-implicit-float");
1717
1718 RenderAArch64ABI(Triple, Args, CmdArgs);
1719
1720 // Forward the -mglobal-merge option for explicit control over the pass.
1721 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1722 options::OPT_mno_global_merge)) {
1723 CmdArgs.push_back("-mllvm");
1724 if (A->getOption().matches(options::OPT_mno_global_merge))
1725 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1726 else
1727 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1728 }
1729
1730 // Handle -msve_vector_bits=<bits>
1731 auto HandleVectorBits = [&](Arg *A, StringRef VScaleMin,
1732 StringRef VScaleMax) {
1733 StringRef Val = A->getValue();
1734 const Driver &D = getToolChain().getDriver();
1735 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1736 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1737 Val == "1024+" || Val == "2048+") {
1738 unsigned Bits = 0;
1739 if (!Val.consume_back("+")) {
1740 bool Invalid = Val.getAsInteger(10, Bits);
1741 (void)Invalid;
1742 assert(!Invalid && "Failed to parse value");
1743 CmdArgs.push_back(
1744 Args.MakeArgString(VScaleMax + llvm::Twine(Bits / 128)));
1745 }
1746
1747 bool Invalid = Val.getAsInteger(10, Bits);
1748 (void)Invalid;
1749 assert(!Invalid && "Failed to parse value");
1750
1751 CmdArgs.push_back(
1752 Args.MakeArgString(VScaleMin + llvm::Twine(Bits / 128)));
1753 } else if (Val == "scalable") {
1754 // Silently drop requests for vector-length agnostic code as it's implied.
1755 } else {
1756 // Handle the unsupported values passed to msve-vector-bits.
1757 D.Diag(diag::err_drv_unsupported_option_argument)
1758 << A->getSpelling() << Val;
1759 }
1760 };
1761 if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ))
1762 HandleVectorBits(A, "-mvscale-min=", "-mvscale-max=");
1763 if (Arg *A = Args.getLastArg(options::OPT_msve_streaming_vector_bits_EQ))
1764 HandleVectorBits(A, "-mvscale-streaming-min=", "-mvscale-streaming-max=");
1765
1766 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1767
1768 if (auto TuneCPU = aarch64::getAArch64TargetTuneCPU(Args, Triple)) {
1769 CmdArgs.push_back("-tune-cpu");
1770 CmdArgs.push_back(Args.MakeArgString(*TuneCPU));
1771 }
1772
1773 AddUnalignedAccessWarning(CmdArgs);
1774
1775 if (Triple.isOSDarwin() ||
1776 (Triple.isOSLinux() &&
1777 Triple.getEnvironment() == llvm::Triple::PAuthTest)) {
1778 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_intrinsics,
1779 options::OPT_fno_ptrauth_intrinsics);
1780 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_calls,
1781 options::OPT_fno_ptrauth_calls);
1782 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_returns,
1783 options::OPT_fno_ptrauth_returns);
1784 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_auth_traps,
1785 options::OPT_fno_ptrauth_auth_traps);
1786 Args.addOptInFlag(
1787 CmdArgs, options::OPT_fptrauth_vtable_pointer_address_discrimination,
1788 options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1789 Args.addOptInFlag(
1790 CmdArgs, options::OPT_fptrauth_vtable_pointer_type_discrimination,
1791 options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1792 Args.addOptInFlag(
1793 CmdArgs, options::OPT_fptrauth_vtt_vtable_pointer_discrimination,
1794 options::OPT_fno_ptrauth_vtt_vtable_pointer_discrimination);
1795 Args.addOptInFlag(
1796 CmdArgs, options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1797 options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1798 Args.addOptInFlag(
1799 CmdArgs, options::OPT_fptrauth_function_pointer_type_discrimination,
1800 options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1801 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_indirect_gotos,
1802 options::OPT_fno_ptrauth_indirect_gotos);
1803 }
1804 if (Triple.isOSLinux() &&
1805 Triple.getEnvironment() == llvm::Triple::PAuthTest) {
1806 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_init_fini,
1807 options::OPT_fno_ptrauth_init_fini);
1808 Args.addOptInFlag(
1809 CmdArgs, options::OPT_fptrauth_init_fini_address_discrimination,
1810 options::OPT_fno_ptrauth_init_fini_address_discrimination);
1811 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_elf_got,
1812 options::OPT_fno_ptrauth_elf_got);
1813 }
1814 Args.addOptInFlag(CmdArgs, options::OPT_faarch64_jump_table_hardening,
1815 options::OPT_fno_aarch64_jump_table_hardening);
1816
1817 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_isa,
1818 options::OPT_fno_ptrauth_objc_isa);
1819 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_interface_sel,
1820 options::OPT_fno_ptrauth_objc_interface_sel);
1821 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_class_ro,
1822 options::OPT_fno_ptrauth_objc_class_ro);
1823
1824 // Enable/disable return address signing and indirect branch targets.
1825 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1826}
1827
1828void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1829 ArgStringList &CmdArgs) const {
1830 const llvm::Triple &Triple = getToolChain().getTriple();
1831
1832 CmdArgs.push_back("-target-abi");
1833 CmdArgs.push_back(
1834 loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1835 .data());
1836
1837 // Handle -mtune.
1838 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1839 std::string TuneCPU = A->getValue();
1840 TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
1841 CmdArgs.push_back("-tune-cpu");
1842 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
1843 }
1844
1845 if (Arg *A = Args.getLastArg(options::OPT_mannotate_tablejump,
1846 options::OPT_mno_annotate_tablejump)) {
1847 if (A->getOption().matches(options::OPT_mannotate_tablejump)) {
1848 CmdArgs.push_back("-mllvm");
1849 CmdArgs.push_back("-loongarch-annotate-tablejump");
1850 }
1851 }
1852}
1853
1854void Clang::AddMIPSTargetArgs(const ArgList &Args,
1855 ArgStringList &CmdArgs) const {
1856 const Driver &D = getToolChain().getDriver();
1857 StringRef CPUName;
1858 StringRef ABIName;
1859 const llvm::Triple &Triple = getToolChain().getTriple();
1860 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1861
1862 CmdArgs.push_back("-target-abi");
1863 CmdArgs.push_back(ABIName.data());
1864
1865 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1866 if (ABI == mips::FloatABI::Soft) {
1867 // Floating point operations and argument passing are soft.
1868 CmdArgs.push_back("-msoft-float");
1869 CmdArgs.push_back("-mfloat-abi");
1870 CmdArgs.push_back("soft");
1871 } else {
1872 // Floating point operations and argument passing are hard.
1873 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1874 CmdArgs.push_back("-mfloat-abi");
1875 CmdArgs.push_back("hard");
1876 }
1877
1878 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1879 options::OPT_mno_ldc1_sdc1)) {
1880 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1881 CmdArgs.push_back("-mllvm");
1882 CmdArgs.push_back("-mno-ldc1-sdc1");
1883 }
1884 }
1885
1886 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1887 options::OPT_mno_check_zero_division)) {
1888 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1889 CmdArgs.push_back("-mllvm");
1890 CmdArgs.push_back("-mno-check-zero-division");
1891 }
1892 }
1893
1894 if (Args.getLastArg(options::OPT_mfix4300)) {
1895 CmdArgs.push_back("-mllvm");
1896 CmdArgs.push_back("-mfix4300");
1897 }
1898
1899 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1900 StringRef v = A->getValue();
1901 CmdArgs.push_back("-mllvm");
1902 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1903 A->claim();
1904 }
1905
1906 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1907 Arg *ABICalls =
1908 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1909
1910 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1911 // -mgpopt is the default for static, -fno-pic environments but these two
1912 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1913 // the only case where -mllvm -mgpopt is passed.
1914 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1915 // passed explicitly when compiling something with -mabicalls
1916 // (implictly) in affect. Currently the warning is in the backend.
1917 //
1918 // When the ABI in use is N64, we also need to determine the PIC mode that
1919 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1920 bool NoABICalls =
1921 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1922
1923 llvm::Reloc::Model RelocationModel;
1924 unsigned PICLevel;
1925 bool IsPIE;
1926 std::tie(RelocationModel, PICLevel, IsPIE) =
1927 ParsePICArgs(getToolChain(), Args);
1928
1929 NoABICalls = NoABICalls ||
1930 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1931
1932 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1933 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1934 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1935 CmdArgs.push_back("-mllvm");
1936 CmdArgs.push_back("-mgpopt");
1937
1938 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1939 options::OPT_mno_local_sdata);
1940 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1941 options::OPT_mno_extern_sdata);
1942 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1943 options::OPT_mno_embedded_data);
1944 if (LocalSData) {
1945 CmdArgs.push_back("-mllvm");
1946 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1947 CmdArgs.push_back("-mlocal-sdata=1");
1948 } else {
1949 CmdArgs.push_back("-mlocal-sdata=0");
1950 }
1951 LocalSData->claim();
1952 }
1953
1954 if (ExternSData) {
1955 CmdArgs.push_back("-mllvm");
1956 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1957 CmdArgs.push_back("-mextern-sdata=1");
1958 } else {
1959 CmdArgs.push_back("-mextern-sdata=0");
1960 }
1961 ExternSData->claim();
1962 }
1963
1964 if (EmbeddedData) {
1965 CmdArgs.push_back("-mllvm");
1966 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1967 CmdArgs.push_back("-membedded-data=1");
1968 } else {
1969 CmdArgs.push_back("-membedded-data=0");
1970 }
1971 EmbeddedData->claim();
1972 }
1973
1974 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1975 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1976
1977 if (GPOpt)
1978 GPOpt->claim();
1979
1980 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1981 StringRef Val = StringRef(A->getValue());
1982 if (mips::hasCompactBranches(CPUName)) {
1983 if (Val == "never" || Val == "always" || Val == "optimal") {
1984 CmdArgs.push_back("-mllvm");
1985 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1986 } else
1987 D.Diag(diag::err_drv_unsupported_option_argument)
1988 << A->getSpelling() << Val;
1989 } else
1990 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1991 }
1992
1993 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1994 options::OPT_mno_relax_pic_calls)) {
1995 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1996 CmdArgs.push_back("-mllvm");
1997 CmdArgs.push_back("-mips-jalr-reloc=0");
1998 }
1999 }
2000}
2001
2002void Clang::AddPPCTargetArgs(const ArgList &Args,
2003 ArgStringList &CmdArgs) const {
2004 const Driver &D = getToolChain().getDriver();
2005 const llvm::Triple &T = getToolChain().getTriple();
2006 if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2007 CmdArgs.push_back("-tune-cpu");
2008 StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, A->getValue());
2009 CmdArgs.push_back(Args.MakeArgString(CPU));
2010 }
2011
2012 // Select the ABI to use.
2013 const char *ABIName = nullptr;
2014 if (T.isOSBinFormatELF()) {
2015 switch (getToolChain().getArch()) {
2016 case llvm::Triple::ppc64: {
2017 if (T.isPPC64ELFv2ABI())
2018 ABIName = "elfv2";
2019 else
2020 ABIName = "elfv1";
2021 break;
2022 }
2023 case llvm::Triple::ppc64le:
2024 ABIName = "elfv2";
2025 break;
2026 default:
2027 break;
2028 }
2029 }
2030
2031 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
2032 bool VecExtabi = false;
2033 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
2034 StringRef V = A->getValue();
2035 if (V == "ieeelongdouble") {
2036 IEEELongDouble = true;
2037 A->claim();
2038 } else if (V == "ibmlongdouble") {
2039 IEEELongDouble = false;
2040 A->claim();
2041 } else if (V == "vec-default") {
2042 VecExtabi = false;
2043 A->claim();
2044 } else if (V == "vec-extabi") {
2045 VecExtabi = true;
2046 A->claim();
2047 } else if (V == "elfv1") {
2048 ABIName = "elfv1";
2049 A->claim();
2050 } else if (V == "elfv2") {
2051 ABIName = "elfv2";
2052 A->claim();
2053 } else if (V != "altivec")
2054 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
2055 // the option if given as we don't have backend support for any targets
2056 // that don't use the altivec abi.
2057 ABIName = A->getValue();
2058 }
2059 if (IEEELongDouble)
2060 CmdArgs.push_back("-mabi=ieeelongdouble");
2061 if (VecExtabi) {
2062 if (!T.isOSAIX())
2063 D.Diag(diag::err_drv_unsupported_opt_for_target)
2064 << "-mabi=vec-extabi" << T.str();
2065 CmdArgs.push_back("-mabi=vec-extabi");
2066 }
2067
2068 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true))
2069 CmdArgs.push_back("-disable-red-zone");
2070
2072 if (FloatABI == ppc::FloatABI::Soft) {
2073 // Floating point operations and argument passing are soft.
2074 CmdArgs.push_back("-msoft-float");
2075 CmdArgs.push_back("-mfloat-abi");
2076 CmdArgs.push_back("soft");
2077 } else {
2078 // Floating point operations and argument passing are hard.
2079 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2080 CmdArgs.push_back("-mfloat-abi");
2081 CmdArgs.push_back("hard");
2082 }
2083
2084 if (ABIName) {
2085 CmdArgs.push_back("-target-abi");
2086 CmdArgs.push_back(ABIName);
2087 }
2088}
2089
2090void Clang::AddRISCVTargetArgs(const ArgList &Args,
2091 ArgStringList &CmdArgs) const {
2092 const llvm::Triple &Triple = getToolChain().getTriple();
2093 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2094
2095 CmdArgs.push_back("-target-abi");
2096 CmdArgs.push_back(ABIName.data());
2097
2098 if (Arg *A = Args.getLastArg(options::OPT_G)) {
2099 CmdArgs.push_back("-msmall-data-limit");
2100 CmdArgs.push_back(A->getValue());
2101 }
2102
2103 if (!Args.hasFlag(options::OPT_mimplicit_float,
2104 options::OPT_mno_implicit_float, true))
2105 CmdArgs.push_back("-no-implicit-float");
2106
2107 auto TuneCPU = riscv::getRISCVTuneCPU(getToolChain().getDriver(), Args);
2108 if (!TuneCPU)
2109 return;
2110 if (!TuneCPU->empty()) {
2111 CmdArgs.push_back("-tune-cpu");
2112 // TuneCPU might or might not be the original -mtune string, so we
2113 // have to create a new copy here.
2114 CmdArgs.push_back(Args.MakeArgString(*TuneCPU));
2115 }
2116
2117 // Handle -mrvv-vector-bits=<bits>
2118 if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
2119 StringRef Val = A->getValue();
2120 const Driver &D = getToolChain().getDriver();
2121
2122 // Get minimum VLen from march.
2123 unsigned MinVLen = 0;
2124 std::string Arch = riscv::getRISCVArch(Args, Triple);
2125 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2126 Arch, /*EnableExperimentalExtensions*/ true);
2127 // Ignore parsing error.
2128 if (!errorToBool(ISAInfo.takeError()))
2129 MinVLen = (*ISAInfo)->getMinVLen();
2130
2131 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2132 // as integer as long as we have a MinVLen.
2133 unsigned Bits = 0;
2134 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2135 Bits = MinVLen;
2136 } else if (!Val.getAsInteger(10, Bits)) {
2137 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2138 // at least MinVLen.
2139 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2140 Bits > 65536 || !llvm::isPowerOf2_32(Bits))
2141 Bits = 0;
2142 }
2143
2144 // If we got a valid value try to use it.
2145 if (Bits != 0) {
2146 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2147 CmdArgs.push_back(
2148 Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
2149 CmdArgs.push_back(
2150 Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
2151 } else if (Val != "scalable") {
2152 // Handle the unsupported values passed to mrvv-vector-bits.
2153 D.Diag(diag::err_drv_unsupported_option_argument)
2154 << A->getSpelling() << Val;
2155 }
2156 }
2157}
2158
2159void Clang::AddSparcTargetArgs(const ArgList &Args,
2160 ArgStringList &CmdArgs) const {
2162 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2163
2164 if (FloatABI == sparc::FloatABI::Soft) {
2165 // Floating point operations and argument passing are soft.
2166 CmdArgs.push_back("-msoft-float");
2167 CmdArgs.push_back("-mfloat-abi");
2168 CmdArgs.push_back("soft");
2169 } else {
2170 // Floating point operations and argument passing are hard.
2171 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2172 CmdArgs.push_back("-mfloat-abi");
2173 CmdArgs.push_back("hard");
2174 }
2175
2176 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2177 StringRef Name = A->getValue();
2178 std::string TuneCPU;
2179 if (Name == "native")
2180 TuneCPU = std::string(llvm::sys::getHostCPUName());
2181 else
2182 TuneCPU = std::string(Name);
2183
2184 CmdArgs.push_back("-tune-cpu");
2185 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2186 }
2187}
2188
2189void Clang::AddSystemZTargetArgs(const ArgList &Args,
2190 ArgStringList &CmdArgs) const {
2191 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2192 CmdArgs.push_back("-tune-cpu");
2193 if (strcmp(A->getValue(), "native") == 0)
2194 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2195 else
2196 CmdArgs.push_back(A->getValue());
2197 }
2198
2199 bool HasBackchain =
2200 Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2201 bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2202 options::OPT_mno_packed_stack, false);
2204 systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2205 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2206
2207 // Only hard float ABI (-mhard-float) is supported on z/OS.
2208 const Driver &D = getToolChain().getDriver();
2209 const llvm::Triple &Triple = getToolChain().getTriple();
2210 if (HasSoftFloat && Triple.isOSzOS()) {
2211 D.Diag(diag::err_drv_unsupported_opt_for_target)
2212 << "-msoft-float" << Triple.str();
2213 }
2214 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2215 D.Diag(diag::err_drv_unsupported_opt)
2216 << "-mpacked-stack -mbackchain -mhard-float";
2217 }
2218 if (HasBackchain)
2219 CmdArgs.push_back("-mbackchain");
2220 if (HasPackedStack)
2221 CmdArgs.push_back("-mpacked-stack");
2222 if (HasSoftFloat) {
2223 // Floating point operations and argument passing are soft.
2224 CmdArgs.push_back("-msoft-float");
2225 CmdArgs.push_back("-mfloat-abi");
2226 CmdArgs.push_back("soft");
2227 }
2228
2229 if (Triple.isOSzOS())
2230 Args.AddLastArg(CmdArgs, options::OPT_mzos_ppa1_name,
2231 options::OPT_mno_zos_ppa1_name);
2232}
2233
2234void Clang::AddX86TargetArgs(const ArgList &Args,
2235 ArgStringList &CmdArgs) const {
2236 const Driver &D = getToolChain().getDriver();
2237 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2238
2239 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2240 Args.hasArg(options::OPT_mkernel) ||
2241 Args.hasArg(options::OPT_fapple_kext))
2242 CmdArgs.push_back("-disable-red-zone");
2243
2244 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2245 options::OPT_mno_tls_direct_seg_refs, true))
2246 CmdArgs.push_back("-mno-tls-direct-seg-refs");
2247
2248 // Default to avoid implicit floating-point for kernel/kext code, but allow
2249 // that to be overridden with -mno-soft-float.
2250 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2251 Args.hasArg(options::OPT_fapple_kext));
2252 if (Arg *A = Args.getLastArg(
2253 options::OPT_msoft_float, options::OPT_mno_soft_float,
2254 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2255 const Option &O = A->getOption();
2256 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2257 O.matches(options::OPT_msoft_float));
2258 }
2259 if (NoImplicitFloat)
2260 CmdArgs.push_back("-no-implicit-float");
2261
2262 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2263 StringRef Value = A->getValue();
2264 if (Value == "intel" || Value == "att") {
2265 CmdArgs.push_back("-mllvm");
2266 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2267 CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
2268 } else {
2269 D.Diag(diag::err_drv_unsupported_option_argument)
2270 << A->getSpelling() << Value;
2271 }
2272 } else if (D.IsCLMode()) {
2273 CmdArgs.push_back("-mllvm");
2274 CmdArgs.push_back("-x86-asm-syntax=intel");
2275 }
2276
2277 if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2278 options::OPT_mno_skip_rax_setup))
2279 if (A->getOption().matches(options::OPT_mskip_rax_setup))
2280 CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2281
2282 // Set flags to support MCU ABI.
2283 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2284 CmdArgs.push_back("-mfloat-abi");
2285 CmdArgs.push_back("soft");
2286 CmdArgs.push_back("-mstack-alignment=4");
2287 }
2288
2289 // Handle -mtune.
2290
2291 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2292 std::string TuneCPU;
2293 if (!Args.hasArg(options::OPT_march_EQ) && !getToolChain().getTriple().isPS())
2294 TuneCPU = "generic";
2295
2296 // Override based on -mtune.
2297 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2298 StringRef Name = A->getValue();
2299
2300 if (Name == "native") {
2301 Name = llvm::sys::getHostCPUName();
2302 if (!Name.empty())
2303 TuneCPU = std::string(Name);
2304 } else
2305 TuneCPU = std::string(Name);
2306 }
2307
2308 if (!TuneCPU.empty()) {
2309 CmdArgs.push_back("-tune-cpu");
2310 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2311 }
2312}
2313
2314static StringRef getOptionName(StringRef Option, const char Delimiter = '=') {
2315 size_t Index = Option.find(Delimiter);
2316 if (Index != StringRef::npos)
2317 Option = Option.substr(0, Index);
2318 return Option;
2319}
2320
2321static void checkAndRemoveLLVMArg(ArgStringList &CmdArgs, StringRef Opt) {
2322 Opt = getOptionName(Opt);
2323 if (CmdArgs.size() < 2)
2324 return;
2325
2326 for (auto It = std::next(CmdArgs.begin()); It != CmdArgs.end(); ++It) {
2327 StringRef Option = *It;
2328 if (!Option.starts_with(Opt))
2329 continue;
2330 Option = getOptionName(Option);
2331 if (Option != Opt)
2332 continue;
2333 if (StringRef(*(It - 1)) != "-mllvm")
2334 continue;
2335
2336 It = CmdArgs.erase(It);
2337 CmdArgs.erase(It - 1);
2338 return;
2339 }
2340}
2341
2342static void pushBackLLVMArg(ArgStringList &CmdArgs, const char *A) {
2343 checkAndRemoveLLVMArg(CmdArgs, A);
2344 CmdArgs.push_back("-mllvm");
2345 CmdArgs.push_back(A);
2346}
2347
2348static void addQFloatLossyFastMathArgs(ArgStringList &CmdArgs) {
2349 for (auto It = CmdArgs.begin(), Ie = CmdArgs.end(); It != Ie;) {
2350 StringRef Option = *It;
2351 if (Option == "-fmath-errno" || Option == "-ffp-contract=on") {
2352 It = CmdArgs.erase(It);
2353 Ie = CmdArgs.end();
2354 } else {
2355 ++It;
2356 }
2357 }
2358
2359 CmdArgs.push_back("-menable-no-infs");
2360 CmdArgs.push_back("-menable-no-nans");
2361 CmdArgs.push_back("-fapprox-func");
2362 CmdArgs.push_back("-funsafe-math-optimizations");
2363 CmdArgs.push_back("-fno-signed-zeros");
2364 CmdArgs.push_back("-mreassociate");
2365 CmdArgs.push_back("-freciprocal-math");
2366 CmdArgs.push_back("-ffp-contract=fast");
2367 CmdArgs.push_back("-ffast-math");
2368 CmdArgs.push_back("-ffinite-math-only");
2369 CmdArgs.push_back("-D__FAST_MATH__");
2370 pushBackLLVMArg(CmdArgs, "-fast-math=true");
2371}
2372
2373static void addQFloatBackendArg(const Driver &D, const ArgList &Args,
2374 ArgStringList &CmdArgs) {
2375 auto HvxVerOpt = toolchains::HexagonToolChain::GetHVXVersion(Args);
2376 bool HasHVX = HvxVerOpt.has_value();
2377 std::string HvxVer = HasHVX ? *HvxVerOpt : std::string();
2378 if (!Args.hasArg(options::OPT_mhexagon_hvx, options::OPT_mhexagon_hvx_EQ,
2379 options::OPT_mhexagon_hvx_ieee_fp) ||
2380 !HasHVX)
2381 return;
2382 unsigned HvxVerNum = 0;
2383 if (StringRef(HvxVer).drop_front(1).getAsInteger(10, HvxVerNum))
2384 HvxVerNum = 0;
2385
2386 if (Arg *A = Args.getLastArg(options::OPT_mhexagon_hvx_qfloat,
2387 options::OPT_mhexagon_hvx_qfloat_EQ,
2388 options::OPT_mhexagon_hvx_ieee_fp)) {
2389 if (HvxVerNum >= 79) {
2390 if (A->getOption().matches(options::OPT_mhexagon_hvx_qfloat_EQ)) {
2391 const char *Mode =
2392 llvm::StringSwitch<const char *>(StringRef(A->getValue()).lower())
2393 .Case("strict-ieee", "-hexagon-qfloat-mode=strict-ieee")
2394 .Case("ieee", "-hexagon-qfloat-mode=ieee")
2395 .Case("lossy", "-hexagon-qfloat-mode=lossy")
2396 .Case("legacy", "-hexagon-qfloat-mode=legacy")
2397 .Default(nullptr);
2398 if (!Mode) {
2399 D.Diag(diag::err_drv_invalid_value)
2400 << A->getAsString(Args) << A->getValue();
2401 return;
2402 }
2403 pushBackLLVMArg(CmdArgs, Mode);
2404 if (strcmp(Mode, "-hexagon-qfloat-mode=lossy") == 0)
2406 } else if (A->getOption().matches(options::OPT_mhexagon_hvx_qfloat)) {
2407 pushBackLLVMArg(CmdArgs, "-hexagon-qfloat-mode=lossy");
2409 } else {
2410 pushBackLLVMArg(CmdArgs, "-hexagon-qfloat-mode=ieee");
2411 }
2412 } else {
2413 if (Arg *QFloatArg = Args.getLastArg(options::OPT_mhexagon_hvx_qfloat,
2414 options::OPT_mhexagon_hvx_qfloat_EQ,
2415 options::OPT_mno_hexagon_hvx_qfloat);
2416 QFloatArg &&
2417 QFloatArg->getOption().matches(options::OPT_mhexagon_hvx_qfloat_EQ)) {
2418 D.Diag(diag::warn_drv_unsupported_option_part_for_target)
2419 << QFloatArg->getValue() << QFloatArg->getAsString(Args)
2420 << (std::string("HVX ") + HvxVer +
2421 "; falling back to legacy qfloat mode");
2422 }
2423 }
2424 }
2425}
2426
2427void Clang::AddHexagonTargetArgs(const ArgList &Args,
2428 ArgStringList &CmdArgs) const {
2429 CmdArgs.push_back("-mqdsp6-compat");
2430 CmdArgs.push_back("-Wreturn-type");
2431
2433 CmdArgs.push_back("-mllvm");
2434 CmdArgs.push_back(
2435 Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
2436 }
2437
2438 if (!Args.hasArg(options::OPT_fno_short_enums))
2439 CmdArgs.push_back("-fshort-enums");
2440 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2441 CmdArgs.push_back("-mllvm");
2442 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2443 }
2444 CmdArgs.push_back("-mllvm");
2445 CmdArgs.push_back("-machine-sink-split=0");
2446
2447 addQFloatBackendArg(getToolChain().getDriver(), Args, CmdArgs);
2448}
2449
2450void Clang::AddLanaiTargetArgs(const ArgList &Args,
2451 ArgStringList &CmdArgs) const {
2452 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2453 StringRef CPUName = A->getValue();
2454
2455 CmdArgs.push_back("-target-cpu");
2456 CmdArgs.push_back(Args.MakeArgString(CPUName));
2457 }
2458 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2459 StringRef Value = A->getValue();
2460 // Only support mregparm=4 to support old usage. Report error for all other
2461 // cases.
2462 int Mregparm;
2463 if (Value.getAsInteger(10, Mregparm)) {
2464 if (Mregparm != 4) {
2466 diag::err_drv_unsupported_option_argument)
2467 << A->getSpelling() << Value;
2468 }
2469 }
2470 }
2471}
2472
2473void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2474 ArgStringList &CmdArgs) const {
2475 // Default to "hidden" visibility.
2476 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2477 options::OPT_fvisibility_ms_compat))
2478 CmdArgs.push_back("-fvisibility=hidden");
2479}
2480
2481void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2482 // Floating point operations and argument passing are hard.
2483 CmdArgs.push_back("-mfloat-abi");
2484 CmdArgs.push_back("hard");
2485}
2486
2487void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2488 StringRef Target, const InputInfo &Output,
2489 const InputInfo &Input, const ArgList &Args) const {
2490 // If this is a dry run, do not create the compilation database file.
2491 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2492 return;
2493
2494 using llvm::yaml::escape;
2495 const Driver &D = getToolChain().getDriver();
2496
2497 if (!CompilationDatabase) {
2498 std::error_code EC;
2499 auto File = std::make_unique<llvm::raw_fd_ostream>(
2500 Filename, EC,
2501 llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2502 if (EC) {
2503 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2504 << EC.message();
2505 return;
2506 }
2507 CompilationDatabase = std::move(File);
2508 }
2509 auto &CDB = *CompilationDatabase;
2510 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2511 if (!CWD)
2512 CWD = ".";
2513 CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2514 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2515 if (Output.isFilename())
2516 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2517 CDB << ", \"arguments\": [\"" << escape(D.DriverExecutable) << "\"";
2518 SmallString<128> Buf;
2519 Buf = "-x";
2520 Buf += types::getTypeName(Input.getType());
2521 CDB << ", \"" << escape(Buf) << "\"";
2522 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2523 Buf = "--sysroot=";
2524 Buf += D.SysRoot;
2525 CDB << ", \"" << escape(Buf) << "\"";
2526 }
2527 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2528 if (Output.isFilename())
2529 CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
2530 for (auto &A: Args) {
2531 auto &O = A->getOption();
2532 // Skip language selection, which is positional.
2533 if (O.getID() == options::OPT_x)
2534 continue;
2535 // Skip writing dependency output and the compilation database itself.
2536 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2537 continue;
2538 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2539 continue;
2540 // Skip inputs.
2541 if (O.getKind() == Option::InputClass)
2542 continue;
2543 // Skip output.
2544 if (O.getID() == options::OPT_o)
2545 continue;
2546 // All other arguments are quoted and appended.
2547 ArgStringList ASL;
2548 A->render(Args, ASL);
2549 for (auto &it: ASL)
2550 CDB << ", \"" << escape(it) << "\"";
2551 }
2552 Buf = "--target=";
2553 Buf += Target;
2554 CDB << ", \"" << escape(Buf) << "\"]},\n";
2555}
2556
2557void Clang::DumpCompilationDatabaseFragmentToDir(
2558 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2559 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2560 // If this is a dry run, do not create the compilation database file.
2561 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2562 return;
2563
2564 if (CompilationDatabase)
2565 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2566
2567 SmallString<256> Path = Dir;
2568 const auto &Driver = C.getDriver();
2569 Driver.getVFS().makeAbsolute(Path);
2570 auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2571 if (Err) {
2572 Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2573 return;
2574 }
2575
2576 llvm::sys::path::append(
2577 Path,
2578 Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2579 int FD;
2580 SmallString<256> TempPath;
2581 Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2582 llvm::sys::fs::OF_Text);
2583 if (Err) {
2584 Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2585 return;
2586 }
2587 CompilationDatabase =
2588 std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2589 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2590}
2591
2592static bool CheckARMImplicitITArg(StringRef Value) {
2593 return Value == "always" || Value == "never" || Value == "arm" ||
2594 Value == "thumb";
2595}
2596
2597static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2598 StringRef Value) {
2599 CmdArgs.push_back("-mllvm");
2600 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2601}
2602
2604 const ArgList &Args,
2605 ArgStringList &CmdArgs,
2606 const Driver &D) {
2607 // Default to -mno-relax-all.
2608 //
2609 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2610 // cannot be done by assembler branch relaxation as it needs a free temporary
2611 // register. Because of this, branch relaxation is handled by a MachineIR pass
2612 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2613 // MachineIR branch relaxation inaccurate and it will miss cases where an
2614 // indirect branch is necessary.
2615 Args.addOptInFlag(CmdArgs, options::OPT_mrelax_all,
2616 options::OPT_mno_relax_all);
2617
2618 Args.AddLastArg(CmdArgs, options::OPT_mincremental_linker_compatible,
2619 options::OPT_mno_incremental_linker_compatible);
2620
2621 Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
2622
2623 Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
2624 options::OPT_fno_emit_compact_unwind_non_canonical);
2625
2626 // If you add more args here, also add them to the block below that
2627 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2628
2629 // When passing -I arguments to the assembler we sometimes need to
2630 // unconditionally take the next argument. For example, when parsing
2631 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2632 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2633 // arg after parsing the '-I' arg.
2634 bool TakeNextArg = false;
2635
2636 const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2637 bool IsELF = Triple.isOSBinFormatELF();
2638 bool Crel = false, ExperimentalCrel = false;
2639 StringRef RelocSectionSym;
2640 bool SFrame = false, ExperimentalSFrame = false;
2641 bool ImplicitMapSyms = false;
2642 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2643 bool UseNoExecStack = false;
2644 bool Msa = false;
2645 const char *MipsTargetFeature = nullptr;
2646 llvm::SmallVector<const char *> SparcTargetFeatures;
2647 StringRef ImplicitIt;
2648 for (const Arg *A :
2649 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2650 options::OPT_mimplicit_it_EQ)) {
2651 A->claim();
2652
2653 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2654 switch (C.getDefaultToolChain().getArch()) {
2655 case llvm::Triple::arm:
2656 case llvm::Triple::armeb:
2657 case llvm::Triple::thumb:
2658 case llvm::Triple::thumbeb:
2659 // Only store the value; the last value set takes effect.
2660 ImplicitIt = A->getValue();
2661 if (!CheckARMImplicitITArg(ImplicitIt))
2662 D.Diag(diag::err_drv_unsupported_option_argument)
2663 << A->getSpelling() << ImplicitIt;
2664 continue;
2665 default:
2666 break;
2667 }
2668 }
2669
2670 for (StringRef Value : A->getValues()) {
2671 if (TakeNextArg) {
2672 CmdArgs.push_back(Value.data());
2673 TakeNextArg = false;
2674 continue;
2675 }
2676
2677 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2678 Value == "-mbig-obj")
2679 continue; // LLVM handles bigobj automatically
2680
2681 auto Equal = Value.split('=');
2682 auto checkArg = [&](bool ValidTarget,
2683 std::initializer_list<const char *> Set) {
2684 if (!ValidTarget) {
2685 D.Diag(diag::err_drv_unsupported_opt_for_target)
2686 << (Twine("-Wa,") + Equal.first + "=").str()
2687 << Triple.getTriple();
2688 } else if (!llvm::is_contained(Set, Equal.second)) {
2689 D.Diag(diag::err_drv_unsupported_option_argument)
2690 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
2691 }
2692 };
2693 switch (C.getDefaultToolChain().getArch()) {
2694 default:
2695 break;
2696 case llvm::Triple::x86:
2697 case llvm::Triple::x86_64:
2698 if (Equal.first == "-mrelax-relocations" ||
2699 Equal.first == "--mrelax-relocations") {
2700 UseRelaxRelocations = Equal.second == "yes";
2701 checkArg(IsELF, {"yes", "no"});
2702 continue;
2703 }
2704 if (Value == "-msse2avx") {
2705 CmdArgs.push_back("-msse2avx");
2706 continue;
2707 }
2708 break;
2709 case llvm::Triple::wasm32:
2710 case llvm::Triple::wasm64:
2711 if (Value == "--no-type-check") {
2712 CmdArgs.push_back("-mno-type-check");
2713 continue;
2714 }
2715 break;
2716 case llvm::Triple::thumb:
2717 case llvm::Triple::thumbeb:
2718 case llvm::Triple::arm:
2719 case llvm::Triple::armeb:
2720 if (Equal.first == "-mimplicit-it") {
2721 // Only store the value; the last value set takes effect.
2722 ImplicitIt = Equal.second;
2723 checkArg(true, {"always", "never", "arm", "thumb"});
2724 continue;
2725 }
2726 if (Value == "-mthumb")
2727 // -mthumb has already been processed in ComputeLLVMTriple()
2728 // recognize but skip over here.
2729 continue;
2730 break;
2731 case llvm::Triple::aarch64:
2732 case llvm::Triple::aarch64_be:
2733 case llvm::Triple::aarch64_32:
2734 if (Equal.first == "-mmapsyms") {
2735 ImplicitMapSyms = Equal.second == "implicit";
2736 checkArg(IsELF, {"default", "implicit"});
2737 continue;
2738 }
2739 break;
2740 case llvm::Triple::mips:
2741 case llvm::Triple::mipsel:
2742 case llvm::Triple::mips64:
2743 case llvm::Triple::mips64el:
2744 if (Value == "--trap") {
2745 CmdArgs.push_back("-target-feature");
2746 CmdArgs.push_back("+use-tcc-in-div");
2747 continue;
2748 }
2749 if (Value == "--break") {
2750 CmdArgs.push_back("-target-feature");
2751 CmdArgs.push_back("-use-tcc-in-div");
2752 continue;
2753 }
2754 if (Value.starts_with("-msoft-float")) {
2755 CmdArgs.push_back("-target-feature");
2756 CmdArgs.push_back("+soft-float");
2757 continue;
2758 }
2759 if (Value.starts_with("-mhard-float")) {
2760 CmdArgs.push_back("-target-feature");
2761 CmdArgs.push_back("-soft-float");
2762 continue;
2763 }
2764 if (Value == "-mmsa") {
2765 Msa = true;
2766 continue;
2767 }
2768 if (Value == "-mno-msa") {
2769 Msa = false;
2770 continue;
2771 }
2772 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2773 .Case("-mips1", "+mips1")
2774 .Case("-mips2", "+mips2")
2775 .Case("-mips3", "+mips3")
2776 .Case("-mips4", "+mips4")
2777 .Case("-mips5", "+mips5")
2778 .Case("-mips32", "+mips32")
2779 .Case("-mips32r2", "+mips32r2")
2780 .Case("-mips32r3", "+mips32r3")
2781 .Case("-mips32r5", "+mips32r5")
2782 .Case("-mips32r6", "+mips32r6")
2783 .Case("-mips64", "+mips64")
2784 .Case("-mips64r2", "+mips64r2")
2785 .Case("-mips64r3", "+mips64r3")
2786 .Case("-mips64r5", "+mips64r5")
2787 .Case("-mips64r6", "+mips64r6")
2788 .Default(nullptr);
2789 if (MipsTargetFeature)
2790 continue;
2791 break;
2792
2793 case llvm::Triple::sparc:
2794 case llvm::Triple::sparcel:
2795 case llvm::Triple::sparcv9:
2796 if (Value == "--undeclared-regs") {
2797 // LLVM already allows undeclared use of G registers, so this option
2798 // becomes a no-op. This solely exists for GNU compatibility.
2799 // TODO implement --no-undeclared-regs
2800 continue;
2801 }
2802 SparcTargetFeatures =
2803 llvm::StringSwitch<llvm::SmallVector<const char *>>(Value)
2804 .Case("-Av8", {"-v8plus"})
2805 .Case("-Av8plus", {"+v8plus", "+v9"})
2806 .Case("-Av8plusa", {"+v8plus", "+v9", "+vis"})
2807 .Case("-Av8plusb", {"+v8plus", "+v9", "+vis", "+vis2"})
2808 .Case("-Av8plusd", {"+v8plus", "+v9", "+vis", "+vis2", "+vis3",
2809 "+ua2005", "+ua2007"})
2810 .Case("-Av9", {"+v9"})
2811 .Case("-Av9a", {"+v9", "+vis"})
2812 .Case("-Av9b", {"+v9", "+vis", "+vis2"})
2813 .Case("-Av9d",
2814 {"+v9", "+vis", "+vis2", "+vis3", "+ua2005", "+ua2007"})
2815 .Default({});
2816 if (!SparcTargetFeatures.empty())
2817 continue;
2818 break;
2819 }
2820
2821 if (Value == "-force_cpusubtype_ALL") {
2822 // Do nothing, this is the default and we don't support anything else.
2823 } else if (Value == "-L") {
2824 CmdArgs.push_back("-msave-temp-labels");
2825 } else if (Value == "--fatal-warnings") {
2826 CmdArgs.push_back("-massembler-fatal-warnings");
2827 } else if (Value == "--no-warn" || Value == "-W") {
2828 CmdArgs.push_back("-massembler-no-warn");
2829 } else if (Value == "--noexecstack") {
2830 UseNoExecStack = true;
2831 } else if (Value.starts_with("-compress-debug-sections") ||
2832 Value.starts_with("--compress-debug-sections") ||
2833 Value == "-nocompress-debug-sections" ||
2834 Value == "--nocompress-debug-sections") {
2835 CmdArgs.push_back(Value.data());
2836 } else if (Value == "--crel") {
2837 Crel = true;
2838 } else if (Value == "--no-crel") {
2839 Crel = false;
2840 } else if (Value == "--allow-experimental-crel") {
2841 ExperimentalCrel = true;
2842 } else if (Value.starts_with("--reloc-section-sym=")) {
2843 RelocSectionSym = Value.substr(strlen("--reloc-section-sym="));
2844 } else if (Value.starts_with("-I")) {
2845 CmdArgs.push_back(Value.data());
2846 // We need to consume the next argument if the current arg is a plain
2847 // -I. The next arg will be the include directory.
2848 if (Value == "-I")
2849 TakeNextArg = true;
2850 } else if (Value.starts_with("-gdwarf-")) {
2851 // "-gdwarf-N" options are not cc1as options.
2852 unsigned DwarfVersion = DwarfVersionNum(Value);
2853 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2854 CmdArgs.push_back(Value.data());
2855 } else {
2856 RenderDebugEnablingArgs(Args, CmdArgs,
2857 llvm::codegenoptions::DebugInfoConstructor,
2858 DwarfVersion, llvm::DebuggerKind::Default);
2859 }
2860 } else if (Value == "--gsframe") {
2861 SFrame = true;
2862 } else if (Value == "--allow-experimental-sframe") {
2863 ExperimentalSFrame = true;
2864 } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
2865 Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {
2866 // Do nothing, we'll validate it later.
2867 } else if (Value == "-defsym" || Value == "--defsym") {
2868 if (A->getNumValues() != 2) {
2869 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2870 break;
2871 }
2872 const char *S = A->getValue(1);
2873 auto Pair = StringRef(S).split('=');
2874 auto Sym = Pair.first;
2875 auto SVal = Pair.second;
2876
2877 if (Sym.empty() || SVal.empty()) {
2878 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2879 break;
2880 }
2881 int64_t IVal;
2882 if (SVal.getAsInteger(0, IVal)) {
2883 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2884 break;
2885 }
2886 CmdArgs.push_back("--defsym");
2887 TakeNextArg = true;
2888 } else if (Value == "-fdebug-compilation-dir") {
2889 CmdArgs.push_back("-fdebug-compilation-dir");
2890 TakeNextArg = true;
2891 } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2892 // The flag is a -Wa / -Xassembler argument and Options doesn't
2893 // parse the argument, so this isn't automatically aliased to
2894 // -fdebug-compilation-dir (without '=') here.
2895 CmdArgs.push_back("-fdebug-compilation-dir");
2896 CmdArgs.push_back(Value.data());
2897 } else if (Value == "--version") {
2898 D.PrintVersion(C, llvm::outs());
2899 } else {
2900 D.Diag(diag::err_drv_unsupported_option_argument)
2901 << A->getSpelling() << Value;
2902 }
2903 }
2904 }
2905 if (ImplicitIt.size())
2906 AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2907 if (Crel) {
2908 if (!ExperimentalCrel)
2909 D.Diag(diag::err_drv_experimental_crel);
2910 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2911 CmdArgs.push_back("--crel");
2912 } else {
2913 D.Diag(diag::err_drv_unsupported_opt_for_target)
2914 << "-Wa,--crel" << D.getTargetTriple();
2915 }
2916 }
2917 if (!RelocSectionSym.empty()) {
2918 if (RelocSectionSym != "all" && RelocSectionSym != "internal" &&
2919 RelocSectionSym != "none")
2920 D.Diag(diag::err_drv_invalid_value)
2921 << ("-Wa,--reloc-section-sym=" + RelocSectionSym).str()
2922 << RelocSectionSym;
2923 else if (Triple.isOSBinFormatELF())
2924 CmdArgs.push_back(
2925 Args.MakeArgString("--reloc-section-sym=" + RelocSectionSym));
2926 else
2927 D.Diag(diag::err_drv_unsupported_opt_for_target)
2928 << "-Wa,--reloc-section-sym" << D.getTargetTriple();
2929 }
2930 if (SFrame) {
2931 if (Triple.isOSBinFormatELF() && Triple.isX86()) {
2932 if (!ExperimentalSFrame)
2933 D.Diag(diag::err_drv_experimental_sframe);
2934 else
2935 CmdArgs.push_back("--gsframe");
2936 } else {
2937 D.Diag(diag::err_drv_unsupported_opt_for_target)
2938 << "-Wa,--gsframe" << D.getTargetTriple();
2939 }
2940 }
2941 if (ImplicitMapSyms)
2942 CmdArgs.push_back("-mmapsyms=implicit");
2943 if (Msa)
2944 CmdArgs.push_back("-mmsa");
2945 if (!UseRelaxRelocations)
2946 CmdArgs.push_back("-mrelax-relocations=no");
2947 if (UseNoExecStack)
2948 CmdArgs.push_back("-mnoexecstack");
2949 if (MipsTargetFeature != nullptr) {
2950 CmdArgs.push_back("-target-feature");
2951 CmdArgs.push_back(MipsTargetFeature);
2952 }
2953
2954 for (const char *Feature : SparcTargetFeatures) {
2955 CmdArgs.push_back("-target-feature");
2956 CmdArgs.push_back(Feature);
2957 }
2958
2959 // forward -fembed-bitcode to assmebler
2960 if (C.getDriver().embedBitcodeEnabled() ||
2961 C.getDriver().embedBitcodeMarkerOnly())
2962 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2963
2964 if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2965 CmdArgs.push_back("-as-secure-log-file");
2966 CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2967 }
2968}
2969
2970static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2971 bool OFastEnabled, const ArgList &Args,
2972 ArgStringList &CmdArgs,
2973 const JobAction &JA) {
2974 // List of veclibs which when used with -fveclib imply -fno-math-errno.
2975 constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),
2976 llvm::StringLiteral("SLEEF")};
2977 bool NoMathErrnoWasImpliedByVecLib = false;
2978 const Arg *VecLibArg = nullptr;
2979 // Track the arg (if any) that enabled errno after -fveclib for diagnostics.
2980 const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;
2981
2982 // Handle various floating point optimization flags, mapping them to the
2983 // appropriate LLVM code generation flags. This is complicated by several
2984 // "umbrella" flags, so we do this by stepping through the flags incrementally
2985 // adjusting what we think is enabled/disabled, then at the end setting the
2986 // LLVM flags based on the final state.
2987 bool HonorINFs = true;
2988 bool HonorNaNs = true;
2989 bool ApproxFunc = false;
2990 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2991 bool MathErrno = TC.IsMathErrnoDefault();
2992 bool AssociativeMath = false;
2993 bool ReciprocalMath = false;
2994 bool SignedZeros = true;
2995 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2996 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2997 // overriden by ffp-exception-behavior?
2998 bool RoundingFPMath = false;
2999 // -ffp-model values: strict, fast, precise
3000 StringRef FPModel = "";
3001 // -ffp-exception-behavior options: strict, maytrap, ignore
3002 StringRef FPExceptionBehavior = "";
3003 // -ffp-eval-method options: double, extended, source
3004 StringRef FPEvalMethod = "";
3005 llvm::DenormalMode DenormalFPMath =
3006 TC.getDefaultDenormalModeForType(Args, JA);
3007 llvm::DenormalMode DenormalFP32Math =
3008 TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
3009
3010 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
3011 // If one wasn't given by the user, don't pass it here.
3012 StringRef FPContract;
3013 StringRef LastSeenFfpContractOption;
3014 StringRef LastFpContractOverrideOption;
3015 bool SeenUnsafeMathModeOption = false;
3018 FPContract = "on";
3019 bool StrictFPModel = false;
3020 StringRef Float16ExcessPrecision = "";
3021 StringRef BFloat16ExcessPrecision = "";
3023 std::string ComplexRangeStr;
3024 StringRef LastComplexRangeOption;
3025
3026 // Lambda to set fast-math options. This is also used by -ffp-model=fast
3027 auto applyFastMath = [&](bool Aggressive, StringRef CallerOption) {
3028 if (Aggressive) {
3029 HonorINFs = false;
3030 HonorNaNs = false;
3032 LastComplexRangeOption, Range);
3033 } else {
3034 HonorINFs = true;
3035 HonorNaNs = true;
3036 setComplexRange(D, CallerOption,
3038 LastComplexRangeOption, Range);
3039 }
3040 MathErrno = false;
3041 AssociativeMath = true;
3042 ReciprocalMath = true;
3043 ApproxFunc = true;
3044 SignedZeros = false;
3045 TrappingMath = false;
3046 RoundingFPMath = false;
3047 FPExceptionBehavior = "";
3048 FPContract = "fast";
3049 SeenUnsafeMathModeOption = true;
3050 };
3051
3052 // Lambda to consolidate common handling for fp-contract
3053 auto restoreFPContractState = [&]() {
3054 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
3055 // For other targets, if the state has been changed by one of the
3056 // unsafe-math umbrella options a subsequent -fno-fast-math or
3057 // -fno-unsafe-math-optimizations option reverts to the last value seen for
3058 // the -ffp-contract option or "on" if we have not seen the -ffp-contract
3059 // option. If we have not seen an unsafe-math option or -ffp-contract,
3060 // we leave the FPContract state unchanged.
3063 if (LastSeenFfpContractOption != "")
3064 FPContract = LastSeenFfpContractOption;
3065 else if (SeenUnsafeMathModeOption)
3066 FPContract = "on";
3067 }
3068 // In this case, we're reverting to the last explicit fp-contract option
3069 // or the platform default
3070 LastFpContractOverrideOption = "";
3071 };
3072
3073 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3074 CmdArgs.push_back("-mlimit-float-precision");
3075 CmdArgs.push_back(A->getValue());
3076 }
3077
3078 for (const Arg *A : Args) {
3079 llvm::scope_exit CheckMathErrnoForVecLib(
3080 [&, MathErrnoBeforeArg = MathErrno] {
3081 if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)
3082 ArgThatEnabledMathErrnoAfterVecLib = A;
3083 });
3084
3085 switch (A->getOption().getID()) {
3086 // If this isn't an FP option skip the claim below
3087 default: continue;
3088
3089 case options::OPT_fcx_limited_range:
3090 setComplexRange(D, A->getSpelling(),
3092 LastComplexRangeOption, Range);
3093 break;
3094 case options::OPT_fno_cx_limited_range:
3095 setComplexRange(D, A->getSpelling(),
3097 LastComplexRangeOption, Range);
3098 break;
3099 case options::OPT_fcx_fortran_rules:
3100 setComplexRange(D, A->getSpelling(),
3102 LastComplexRangeOption, Range);
3103 break;
3104 case options::OPT_fno_cx_fortran_rules:
3105 setComplexRange(D, A->getSpelling(),
3107 LastComplexRangeOption, Range);
3108 break;
3109 case options::OPT_fcomplex_arithmetic_EQ: {
3111 StringRef Val = A->getValue();
3112 if (Val == "full")
3114 else if (Val == "improved")
3116 else if (Val == "promoted")
3118 else if (Val == "basic")
3120 else {
3121 D.Diag(diag::err_drv_unsupported_option_argument)
3122 << A->getSpelling() << Val;
3123 break;
3124 }
3125 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val), RangeVal,
3126 LastComplexRangeOption, Range);
3127 break;
3128 }
3129 case options::OPT_ffp_model_EQ: {
3130 // If -ffp-model= is seen, reset to fno-fast-math
3131 HonorINFs = true;
3132 HonorNaNs = true;
3133 ApproxFunc = false;
3134 // Turning *off* -ffast-math restores the toolchain default.
3135 MathErrno = TC.IsMathErrnoDefault();
3136 AssociativeMath = false;
3137 ReciprocalMath = false;
3138 SignedZeros = true;
3139
3140 StringRef Val = A->getValue();
3141 if (OFastEnabled && Val != "aggressive") {
3142 // Only -ffp-model=aggressive is compatible with -OFast, ignore.
3143 D.Diag(clang::diag::warn_drv_overriding_option)
3144 << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";
3145 break;
3146 }
3147 StrictFPModel = false;
3148 if (!FPModel.empty() && FPModel != Val)
3149 D.Diag(clang::diag::warn_drv_overriding_option)
3150 << Args.MakeArgString("-ffp-model=" + FPModel)
3151 << Args.MakeArgString("-ffp-model=" + Val);
3152 if (Val == "fast") {
3153 FPModel = Val;
3154 applyFastMath(false, Args.MakeArgString(A->getSpelling() + Val));
3155 // applyFastMath sets fp-contract="fast"
3156 LastFpContractOverrideOption = "-ffp-model=fast";
3157 } else if (Val == "aggressive") {
3158 FPModel = Val;
3159 applyFastMath(true, Args.MakeArgString(A->getSpelling() + Val));
3160 // applyFastMath sets fp-contract="fast"
3161 LastFpContractOverrideOption = "-ffp-model=aggressive";
3162 } else if (Val == "precise") {
3163 FPModel = Val;
3164 FPContract = "on";
3165 LastFpContractOverrideOption = "-ffp-model=precise";
3166 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val),
3168 LastComplexRangeOption, Range);
3169 } else if (Val == "strict") {
3170 StrictFPModel = true;
3171 FPExceptionBehavior = "strict";
3172 FPModel = Val;
3173 FPContract = "off";
3174 LastFpContractOverrideOption = "-ffp-model=strict";
3175 TrappingMath = true;
3176 RoundingFPMath = true;
3177 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val),
3179 LastComplexRangeOption, Range);
3180 } else
3181 D.Diag(diag::err_drv_unsupported_option_argument)
3182 << A->getSpelling() << Val;
3183 break;
3184 }
3185
3186 // Options controlling individual features
3187 case options::OPT_fhonor_infinities: HonorINFs = true; break;
3188 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
3189 case options::OPT_fhonor_nans: HonorNaNs = true; break;
3190 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
3191 case options::OPT_fapprox_func: ApproxFunc = true; break;
3192 case options::OPT_fno_approx_func: ApproxFunc = false; break;
3193 case options::OPT_fmath_errno: MathErrno = true; break;
3194 case options::OPT_fno_math_errno: MathErrno = false; break;
3195 case options::OPT_fassociative_math: AssociativeMath = true; break;
3196 case options::OPT_fno_associative_math: AssociativeMath = false; break;
3197 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
3198 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
3199 case options::OPT_fsigned_zeros: SignedZeros = true; break;
3200 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
3201 case options::OPT_ftrapping_math:
3202 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3203 FPExceptionBehavior != "strict")
3204 // Warn that previous value of option is overridden.
3205 D.Diag(clang::diag::warn_drv_overriding_option)
3206 << Args.MakeArgString("-ffp-exception-behavior=" +
3207 FPExceptionBehavior)
3208 << "-ftrapping-math";
3209 TrappingMath = true;
3210 TrappingMathPresent = true;
3211 FPExceptionBehavior = "strict";
3212 break;
3213 case options::OPT_fveclib:
3214 VecLibArg = A;
3215 NoMathErrnoWasImpliedByVecLib =
3216 llvm::is_contained(VecLibImpliesNoMathErrno, A->getValue());
3217 if (NoMathErrnoWasImpliedByVecLib)
3218 MathErrno = false;
3219 break;
3220 case options::OPT_fno_trapping_math:
3221 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3222 FPExceptionBehavior != "ignore")
3223 // Warn that previous value of option is overridden.
3224 D.Diag(clang::diag::warn_drv_overriding_option)
3225 << Args.MakeArgString("-ffp-exception-behavior=" +
3226 FPExceptionBehavior)
3227 << "-fno-trapping-math";
3228 TrappingMath = false;
3229 TrappingMathPresent = true;
3230 FPExceptionBehavior = "ignore";
3231 break;
3232
3233 case options::OPT_frounding_math:
3234 RoundingFPMath = true;
3235 break;
3236
3237 case options::OPT_fno_rounding_math:
3238 RoundingFPMath = false;
3239 break;
3240
3241 case options::OPT_fdenormal_fp_math_EQ:
3242 DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
3243 DenormalFP32Math = DenormalFPMath;
3244 if (!DenormalFPMath.isValid()) {
3245 D.Diag(diag::err_drv_invalid_value)
3246 << A->getAsString(Args) << A->getValue();
3247 }
3248 break;
3249
3250 case options::OPT_fdenormal_fp_math_f32_EQ:
3251 DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
3252 if (!DenormalFP32Math.isValid()) {
3253 D.Diag(diag::err_drv_invalid_value)
3254 << A->getAsString(Args) << A->getValue();
3255 }
3256 break;
3257
3258 // Validate and pass through -ffp-contract option.
3259 case options::OPT_ffp_contract: {
3260 StringRef Val = A->getValue();
3261 if (Val == "fast" || Val == "on" || Val == "off" ||
3262 Val == "fast-honor-pragmas") {
3263 if (Val != FPContract && LastFpContractOverrideOption != "") {
3264 D.Diag(clang::diag::warn_drv_overriding_option)
3265 << LastFpContractOverrideOption
3266 << Args.MakeArgString("-ffp-contract=" + Val);
3267 }
3268
3269 FPContract = Val;
3270 LastSeenFfpContractOption = Val;
3271 LastFpContractOverrideOption = "";
3272 } else
3273 D.Diag(diag::err_drv_unsupported_option_argument)
3274 << A->getSpelling() << Val;
3275 break;
3276 }
3277
3278 // Validate and pass through -ffp-exception-behavior option.
3279 case options::OPT_ffp_exception_behavior_EQ: {
3280 StringRef Val = A->getValue();
3281 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3282 FPExceptionBehavior != Val)
3283 // Warn that previous value of option is overridden.
3284 D.Diag(clang::diag::warn_drv_overriding_option)
3285 << Args.MakeArgString("-ffp-exception-behavior=" +
3286 FPExceptionBehavior)
3287 << Args.MakeArgString("-ffp-exception-behavior=" + Val);
3288 TrappingMath = TrappingMathPresent = false;
3289 if (Val == "ignore" || Val == "maytrap")
3290 FPExceptionBehavior = Val;
3291 else if (Val == "strict") {
3292 FPExceptionBehavior = Val;
3293 TrappingMath = TrappingMathPresent = true;
3294 } else
3295 D.Diag(diag::err_drv_unsupported_option_argument)
3296 << A->getSpelling() << Val;
3297 break;
3298 }
3299
3300 // Validate and pass through -ffp-eval-method option.
3301 case options::OPT_ffp_eval_method_EQ: {
3302 StringRef Val = A->getValue();
3303 if (Val == "double" || Val == "extended" || Val == "source")
3304 FPEvalMethod = Val;
3305 else
3306 D.Diag(diag::err_drv_unsupported_option_argument)
3307 << A->getSpelling() << Val;
3308 break;
3309 }
3310
3311 case options::OPT_fexcess_precision_EQ: {
3312 StringRef Val = A->getValue();
3313 const llvm::Triple::ArchType Arch = TC.getArch();
3314 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3315 if (Val == "standard" || Val == "fast")
3316 Float16ExcessPrecision = Val;
3317 // To make it GCC compatible, allow the value of "16" which
3318 // means disable excess precision, the same meaning than clang's
3319 // equivalent value "none".
3320 else if (Val == "16")
3321 Float16ExcessPrecision = "none";
3322 else
3323 D.Diag(diag::err_drv_unsupported_option_argument)
3324 << A->getSpelling() << Val;
3325 } else {
3326 if (!(Val == "standard" || Val == "fast"))
3327 D.Diag(diag::err_drv_unsupported_option_argument)
3328 << A->getSpelling() << Val;
3329 }
3330 BFloat16ExcessPrecision = Float16ExcessPrecision;
3331 break;
3332 }
3333 case options::OPT_ffinite_math_only:
3334 HonorINFs = false;
3335 HonorNaNs = false;
3336 break;
3337 case options::OPT_fno_finite_math_only:
3338 HonorINFs = true;
3339 HonorNaNs = true;
3340 break;
3341
3342 case options::OPT_funsafe_math_optimizations:
3343 AssociativeMath = true;
3344 ReciprocalMath = true;
3345 SignedZeros = false;
3346 ApproxFunc = true;
3347 TrappingMath = false;
3348 FPExceptionBehavior = "";
3349 FPContract = "fast";
3350 LastFpContractOverrideOption = "-funsafe-math-optimizations";
3351 SeenUnsafeMathModeOption = true;
3352 break;
3353 case options::OPT_fno_unsafe_math_optimizations:
3354 AssociativeMath = false;
3355 ReciprocalMath = false;
3356 SignedZeros = true;
3357 ApproxFunc = false;
3358 restoreFPContractState();
3359 break;
3360
3361 case options::OPT_cl_fast_relaxed_math:
3362 applyFastMath(true, A->getSpelling());
3363 break;
3364
3365 case options::OPT_Ofast:
3366 // If -Ofast is the optimization level, then -ffast-math should be enabled
3367 if (!OFastEnabled)
3368 continue;
3369 [[fallthrough]];
3370 case options::OPT_ffast_math:
3371 applyFastMath(true, A->getSpelling());
3372 if (A->getOption().getID() == options::OPT_Ofast)
3373 LastFpContractOverrideOption = "-Ofast";
3374 else
3375 LastFpContractOverrideOption = "-ffast-math";
3376 break;
3377 case options::OPT_fno_fast_math:
3378 HonorINFs = true;
3379 HonorNaNs = true;
3380 // Turning on -ffast-math (with either flag) removes the need for
3381 // MathErrno. However, turning *off* -ffast-math merely restores the
3382 // toolchain default (which may be false).
3383 MathErrno = TC.IsMathErrnoDefault();
3384 AssociativeMath = false;
3385 ReciprocalMath = false;
3386 ApproxFunc = false;
3387 SignedZeros = true;
3388 restoreFPContractState();
3390 setComplexRange(D, A->getSpelling(),
3392 LastComplexRangeOption, Range);
3393 else
3395 LastComplexRangeOption = "";
3396 LastFpContractOverrideOption = "";
3397 break;
3398 } // End switch (A->getOption().getID())
3399
3400 // The StrictFPModel local variable is needed to report warnings
3401 // in the way we intend. If -ffp-model=strict has been used, we
3402 // want to report a warning for the next option encountered that
3403 // takes us out of the settings described by fp-model=strict, but
3404 // we don't want to continue issuing warnings for other conflicting
3405 // options after that.
3406 if (StrictFPModel) {
3407 // If -ffp-model=strict has been specified on command line but
3408 // subsequent options conflict then emit warning diagnostic.
3409 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3410 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3411 FPContract == "off")
3412 // OK: Current Arg doesn't conflict with -ffp-model=strict
3413 ;
3414 else {
3415 StrictFPModel = false;
3416 FPModel = "";
3417 // The warning for -ffp-contract would have been reported by the
3418 // OPT_ffp_contract_EQ handler above. A special check here is needed
3419 // to avoid duplicating the warning.
3420 auto RHS = (A->getNumValues() == 0)
3421 ? A->getSpelling()
3422 : Args.MakeArgString(A->getSpelling() + A->getValue());
3423 if (A->getSpelling() != "-ffp-contract=") {
3424 if (RHS != "-ffp-model=strict")
3425 D.Diag(clang::diag::warn_drv_overriding_option)
3426 << "-ffp-model=strict" << RHS;
3427 }
3428 }
3429 }
3430
3431 // If we handled this option claim it
3432 A->claim();
3433 }
3434
3435 if (!HonorINFs)
3436 CmdArgs.push_back("-menable-no-infs");
3437
3438 if (!HonorNaNs)
3439 CmdArgs.push_back("-menable-no-nans");
3440
3441 if (ApproxFunc)
3442 CmdArgs.push_back("-fapprox-func");
3443
3444 if (MathErrno) {
3445 CmdArgs.push_back("-fmath-errno");
3446 if (NoMathErrnoWasImpliedByVecLib)
3447 D.Diag(clang::diag::warn_drv_math_errno_enabled_after_veclib)
3448 << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)
3449 << VecLibArg->getAsString(Args);
3450 }
3451
3452 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3453 !TrappingMath)
3454 CmdArgs.push_back("-funsafe-math-optimizations");
3455
3456 if (!SignedZeros)
3457 CmdArgs.push_back("-fno-signed-zeros");
3458
3459 if (AssociativeMath && !SignedZeros && !TrappingMath)
3460 CmdArgs.push_back("-mreassociate");
3461
3462 if (ReciprocalMath)
3463 CmdArgs.push_back("-freciprocal-math");
3464
3465 if (TrappingMath) {
3466 // FP Exception Behavior is also set to strict
3467 assert(FPExceptionBehavior == "strict");
3468 }
3469
3470 // The default is IEEE.
3471 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3472 llvm::SmallString<64> DenormFlag;
3473 llvm::raw_svector_ostream ArgStr(DenormFlag);
3474 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3475 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3476 }
3477
3478 // Add f32 specific denormal mode flag if it's different.
3479 if (DenormalFP32Math != DenormalFPMath) {
3480 llvm::SmallString<64> DenormFlag;
3481 llvm::raw_svector_ostream ArgStr(DenormFlag);
3482 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3483 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3484 }
3485
3486 if (!FPContract.empty())
3487 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
3488
3489 if (RoundingFPMath)
3490 CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3491 else
3492 CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3493
3494 if (!FPExceptionBehavior.empty())
3495 CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3496 FPExceptionBehavior));
3497
3498 if (!FPEvalMethod.empty())
3499 CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
3500
3501 if (!Float16ExcessPrecision.empty())
3502 CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3503 Float16ExcessPrecision));
3504 if (!BFloat16ExcessPrecision.empty())
3505 CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
3506 BFloat16ExcessPrecision));
3507
3508 StringRef Recip = parseMRecipOption(D.getDiags(), Args);
3509 if (!Recip.empty())
3510 CmdArgs.push_back(Args.MakeArgString("-mrecip=" + Recip));
3511
3512 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3513 // individual features enabled by -ffast-math instead of the option itself as
3514 // that's consistent with gcc's behaviour.
3515 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3516 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3517 CmdArgs.push_back("-ffast-math");
3518
3519 // Handle __FINITE_MATH_ONLY__ similarly.
3520 // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3521 // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3522 // -menable-no-nans are set by the user.
3523 bool shouldAddFiniteMathOnly = false;
3524 if (!HonorINFs && !HonorNaNs) {
3525 shouldAddFiniteMathOnly = true;
3526 } else {
3527 bool InfValues = true;
3528 bool NanValues = true;
3529 for (const auto *Arg : Args.filtered(options::OPT_Xclang)) {
3530 StringRef ArgValue = Arg->getValue();
3531 if (ArgValue == "-menable-no-nans")
3532 NanValues = false;
3533 else if (ArgValue == "-menable-no-infs")
3534 InfValues = false;
3535 }
3536 if (!NanValues && !InfValues)
3537 shouldAddFiniteMathOnly = true;
3538 }
3539 if (shouldAddFiniteMathOnly) {
3540 CmdArgs.push_back("-ffinite-math-only");
3541 }
3542 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3543 CmdArgs.push_back("-mfpmath");
3544 CmdArgs.push_back(A->getValue());
3545 }
3546
3547 // Disable a codegen optimization for floating-point casts.
3548 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3549 options::OPT_fstrict_float_cast_overflow, false))
3550 CmdArgs.push_back("-fno-strict-float-cast-overflow");
3551
3553 ComplexRangeStr = renderComplexRangeOption(Range);
3554 if (!ComplexRangeStr.empty()) {
3555 CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
3556 if (Args.hasArg(options::OPT_fcomplex_arithmetic_EQ))
3557 CmdArgs.push_back(Args.MakeArgString("-fcomplex-arithmetic=" +
3558 complexRangeKindToStr(Range)));
3559 }
3560 if (Args.hasArg(options::OPT_fcx_limited_range))
3561 CmdArgs.push_back("-fcx-limited-range");
3562 if (Args.hasArg(options::OPT_fcx_fortran_rules))
3563 CmdArgs.push_back("-fcx-fortran-rules");
3564 if (Args.hasArg(options::OPT_fno_cx_limited_range))
3565 CmdArgs.push_back("-fno-cx-limited-range");
3566 if (Args.hasArg(options::OPT_fno_cx_fortran_rules))
3567 CmdArgs.push_back("-fno-cx-fortran-rules");
3568}
3569
3570static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3571 const llvm::Triple &Triple,
3572 const InputInfo &Input) {
3573 // Add default argument set.
3574 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3575 CmdArgs.push_back("-analyzer-checker=core");
3576 CmdArgs.push_back("-analyzer-checker=apiModeling");
3577
3578 if (!Triple.isWindowsMSVCEnvironment()) {
3579 CmdArgs.push_back("-analyzer-checker=unix");
3580 } else {
3581 // Enable "unix" checkers that also work on Windows.
3582 CmdArgs.push_back("-analyzer-checker=unix.API");
3583 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3584 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3585 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3586 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3587 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3588 }
3589
3590 // Disable some unix checkers for PS4/PS5.
3591 if (Triple.isPS()) {
3592 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3593 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3594 }
3595
3596 if (Triple.isOSDarwin()) {
3597 CmdArgs.push_back("-analyzer-checker=osx");
3598 CmdArgs.push_back(
3599 "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3600 }
3601 else if (Triple.isOSFuchsia())
3602 CmdArgs.push_back("-analyzer-checker=fuchsia");
3603
3604 CmdArgs.push_back("-analyzer-checker=deadcode");
3605
3606 if (types::isCXX(Input.getType()))
3607 CmdArgs.push_back("-analyzer-checker=cplusplus");
3608
3609 if (!Triple.isPS()) {
3610 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3611 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3612 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3613 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3614 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3615 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3616 }
3617
3618 // Default nullability checks.
3619 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3620 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3621 }
3622
3623 // Set the output format. The default is plist, for (lame) historical reasons.
3624 CmdArgs.push_back("-analyzer-output");
3625 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3626 CmdArgs.push_back(A->getValue());
3627 else
3628 CmdArgs.push_back("plist");
3629
3630 // Disable the presentation of standard compiler warnings when using
3631 // --analyze. We only want to show static analyzer diagnostics or frontend
3632 // errors.
3633 CmdArgs.push_back("-w");
3634
3635 // Add -Xanalyzer arguments when running as analyzer.
3636 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3637}
3638
3639static bool isValidSymbolName(StringRef S) {
3640 if (S.empty())
3641 return false;
3642
3643 if (std::isdigit(S[0]))
3644 return false;
3645
3646 return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3647}
3648
3649static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3650 const ArgList &Args, ArgStringList &CmdArgs,
3651 bool KernelOrKext) {
3652 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3653
3654 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3655 // doesn't even have a stack!
3656 if (EffectiveTriple.isNVPTX())
3657 return;
3658
3659 // -stack-protector=0 is default.
3661 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3662 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3663
3664 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3665 options::OPT_fstack_protector_all,
3666 options::OPT_fstack_protector_strong,
3667 options::OPT_fstack_protector)) {
3668 if (A->getOption().matches(options::OPT_fstack_protector))
3669 StackProtectorLevel =
3670 std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3671 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3672 StackProtectorLevel = LangOptions::SSPStrong;
3673 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3674 StackProtectorLevel = LangOptions::SSPReq;
3675
3676 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3677 D.Diag(diag::warn_drv_unsupported_option_for_target)
3678 << A->getSpelling() << EffectiveTriple.getTriple();
3679 StackProtectorLevel = DefaultStackProtectorLevel;
3680 }
3681 } else {
3682 StackProtectorLevel = DefaultStackProtectorLevel;
3683 }
3684
3685 if (StackProtectorLevel) {
3686 CmdArgs.push_back("-stack-protector");
3687 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3688 }
3689
3690 // --param ssp-buffer-size=
3691 for (const Arg *A : Args.filtered(options::OPT__param)) {
3692 StringRef Str(A->getValue());
3693 if (Str.consume_front("ssp-buffer-size=")) {
3694 if (StackProtectorLevel) {
3695 CmdArgs.push_back("-stack-protector-buffer-size");
3696 // FIXME: Verify the argument is a valid integer.
3697 CmdArgs.push_back(Args.MakeArgString(Str));
3698 }
3699 A->claim();
3700 }
3701 }
3702
3703 const std::string &TripleStr = EffectiveTriple.getTriple();
3704 StringRef GuardValue;
3705 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3706 GuardValue = A->getValue();
3707 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3708 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3709 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC() &&
3710 !EffectiveTriple.isSystemZ())
3711 D.Diag(diag::err_drv_unsupported_opt_for_target)
3712 << A->getAsString(Args) << TripleStr;
3713 // z/OS only supports the tls mode.
3714 if (EffectiveTriple.isOSzOS() && GuardValue != "tls") {
3715 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3716 << A->getOption().getName() << GuardValue << "tls";
3717 return;
3718 }
3719 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3720 EffectiveTriple.isThumb() || EffectiveTriple.isSystemZ()) &&
3721 GuardValue != "tls" && GuardValue != "global") {
3722 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3723 << A->getOption().getName() << GuardValue << "tls global";
3724 return;
3725 }
3726 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3727 GuardValue == "tls") {
3728 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3729 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3730 << A->getAsString(Args);
3731 return;
3732 }
3733 // Check whether the target subarch supports the hardware TLS register
3734 if (!arm::isHardTPSupported(EffectiveTriple)) {
3735 D.Diag(diag::err_target_unsupported_tp_hard)
3736 << EffectiveTriple.getArchName();
3737 return;
3738 }
3739 // Check whether the user asked for something other than -mtp=cp15
3740 if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3741 StringRef Value = A->getValue();
3742 if (Value != "cp15") {
3743 D.Diag(diag::err_drv_argument_not_allowed_with)
3744 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3745 return;
3746 }
3747 }
3748 CmdArgs.push_back("-target-feature");
3749 CmdArgs.push_back("+read-tp-tpidruro");
3750 }
3751 if (EffectiveTriple.isAArch64() && GuardValue != "sysreg" &&
3752 GuardValue != "global") {
3753 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3754 << A->getOption().getName() << GuardValue << "sysreg global";
3755 return;
3756 }
3757 if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {
3758 if (GuardValue != "tls" && GuardValue != "global") {
3759 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3760 << A->getOption().getName() << GuardValue << "tls global";
3761 return;
3762 }
3763 if (GuardValue == "tls") {
3764 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3765 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3766 << A->getAsString(Args);
3767 return;
3768 }
3769 }
3770 }
3771 A->render(Args, CmdArgs);
3772 }
3773
3774 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3775 StringRef Value = A->getValue();
3776 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3777 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3778 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3779 D.Diag(diag::err_drv_unsupported_opt_for_target)
3780 << A->getAsString(Args) << TripleStr;
3781 int Offset;
3782 if (Value.getAsInteger(10, Offset)) {
3783 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3784 return;
3785 }
3786 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3787 (Offset < 0 || Offset > 0xfffff)) {
3788 D.Diag(diag::err_drv_invalid_int_value)
3789 << A->getOption().getName() << Value;
3790 return;
3791 }
3792 A->render(Args, CmdArgs);
3793 }
3794
3795 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3796 StringRef Value = A->getValue();
3797 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3798 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3799 D.Diag(diag::err_drv_unsupported_opt_for_target)
3800 << A->getAsString(Args) << TripleStr;
3801 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3802 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3803 << A->getOption().getName() << Value << "fs gs";
3804 return;
3805 }
3806 if (EffectiveTriple.isAArch64() &&
3807 llvm::StringSwitch<bool>(Value)
3808 .Cases({"sp_el0", "tpidrro_el0", "tpidr_el0", "tpidr_el1",
3809 "tpidr_el2", "far_el1", "far_el2"},
3810 false)
3811 .Default(true)) {
3812 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3813 << A->getOption().getName() << Value
3814 << "{sp_el0, tpidrro_el0, tpidr_el[012], far_el[12]}";
3815 return;
3816 }
3817 if (EffectiveTriple.isRISCV() && Value != "tp") {
3818 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3819 << A->getOption().getName() << Value << "tp";
3820 return;
3821 }
3822 if (EffectiveTriple.isPPC64() && Value != "r13") {
3823 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3824 << A->getOption().getName() << Value << "r13";
3825 return;
3826 }
3827 if (EffectiveTriple.isPPC32() && Value != "r2") {
3828 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3829 << A->getOption().getName() << Value << "r2";
3830 return;
3831 }
3832 A->render(Args, CmdArgs);
3833 }
3834
3835 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3836 StringRef Value = A->getValue();
3837 if (!isValidSymbolName(Value)) {
3838 D.Diag(diag::err_drv_argument_only_allowed_with)
3839 << A->getOption().getName() << "legal symbol name";
3840 return;
3841 }
3842 A->render(Args, CmdArgs);
3843 }
3844
3845 if (Arg *A =
3846 Args.getLastArg(options::OPT_mstack_protector_guard_value_width_EQ)) {
3847 if (!EffectiveTriple.isAArch64())
3848 D.Diag(diag::err_drv_unsupported_opt_for_target)
3849 << A->getAsString(Args) << TripleStr;
3850 StringRef Value = A->getValue();
3851 unsigned Width;
3852 if (Value.getAsInteger(10, Width)) {
3853 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3854 return;
3855 }
3856 if (Width != 4 && Width != 8) {
3857 D.Diag(diag::err_drv_invalid_int_value)
3858 << A->getOption().getName() << Value;
3859 }
3860 }
3861 if (Arg *A = Args.getLastArg(options::OPT_mstackprotector_guard_record)) {
3862 if (!EffectiveTriple.isSystemZ()) {
3863 D.Diag(diag::err_drv_unsupported_opt_for_target)
3864 << A->getAsString(Args) << TripleStr;
3865 return;
3866 }
3867 if (GuardValue != "global") {
3868 D.Diag(diag::err_drv_argument_only_allowed_with)
3869 << "-mstack-protector-guard-record"
3870 << "-mstack-protector-guard=global";
3871 return;
3872 }
3873 A->render(Args, CmdArgs);
3874 }
3875}
3876
3877static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3878 ArgStringList &CmdArgs) {
3879 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3880
3881 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&
3882 !EffectiveTriple.isOSFuchsia())
3883 return;
3884
3885 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3886 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&
3887 !EffectiveTriple.isRISCV() && !EffectiveTriple.isLoongArch())
3888 return;
3889
3890 if (Args.hasFlag(options::OPT_fstack_clash_protection,
3891 options::OPT_fno_stack_clash_protection,
3892 EffectiveTriple.isAndroid()))
3893 CmdArgs.push_back("-fstack-clash-protection");
3894}
3895
3897 const ToolChain &TC,
3898 const ArgList &Args,
3899 ArgStringList &CmdArgs) {
3900 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3901 StringRef TrivialAutoVarInit = "";
3902
3903 for (const Arg *A : Args) {
3904 switch (A->getOption().getID()) {
3905 default:
3906 continue;
3907 case options::OPT_ftrivial_auto_var_init: {
3908 A->claim();
3909 StringRef Val = A->getValue();
3910 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3911 TrivialAutoVarInit = Val;
3912 else
3913 D.Diag(diag::err_drv_unsupported_option_argument)
3914 << A->getSpelling() << Val;
3915 break;
3916 }
3917 }
3918 }
3919
3920 if (TrivialAutoVarInit.empty())
3921 switch (DefaultTrivialAutoVarInit) {
3923 break;
3925 TrivialAutoVarInit = "pattern";
3926 break;
3928 TrivialAutoVarInit = "zero";
3929 break;
3930 }
3931
3932 if (!TrivialAutoVarInit.empty()) {
3933 CmdArgs.push_back(
3934 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3935 }
3936
3937 if (Arg *A =
3938 Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3939 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3940 StringRef(
3941 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3942 "uninitialized")
3943 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3944 A->claim();
3945 StringRef Val = A->getValue();
3946 if (std::stoi(Val.str()) <= 0)
3947 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3948 CmdArgs.push_back(
3949 Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3950 }
3951
3952 if (Arg *A = Args.getLastArg(options::OPT_ftrivial_auto_var_init_max_size)) {
3953 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3954 StringRef(
3955 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3956 "uninitialized")
3957 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3958 A->claim();
3959 StringRef Val = A->getValue();
3960 if (std::stoi(Val.str()) <= 0)
3961 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3962 CmdArgs.push_back(
3963 Args.MakeArgString("-ftrivial-auto-var-init-max-size=" + Val));
3964 }
3965}
3966
3967static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3968 types::ID InputType) {
3969 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3970 // for denormal flushing handling based on the target.
3971 const unsigned ForwardedArguments[] = {
3972 options::OPT_cl_opt_disable,
3973 options::OPT_cl_strict_aliasing,
3974 options::OPT_cl_single_precision_constant,
3975 options::OPT_cl_finite_math_only,
3976 options::OPT_cl_kernel_arg_info,
3977 options::OPT_cl_unsafe_math_optimizations,
3978 options::OPT_cl_fast_relaxed_math,
3979 options::OPT_cl_mad_enable,
3980 options::OPT_cl_no_signed_zeros,
3981 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3982 options::OPT_cl_uniform_work_group_size
3983 };
3984
3985 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3986 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3987 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3988 } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
3989 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3990 CmdArgs.push_back(Args.MakeArgString(CLExtStr));
3991 }
3992
3993 if (Args.hasArg(options::OPT_cl_finite_math_only)) {
3994 CmdArgs.push_back("-menable-no-infs");
3995 CmdArgs.push_back("-menable-no-nans");
3996 }
3997
3998 for (const auto &Arg : ForwardedArguments)
3999 if (const auto *A = Args.getLastArg(Arg))
4000 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
4001
4002 // Only add the default headers if we are compiling OpenCL sources.
4003 if ((types::isOpenCL(InputType) ||
4004 (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
4005 !Args.hasArg(options::OPT_cl_no_stdinc)) {
4006 CmdArgs.push_back("-finclude-default-header");
4007 CmdArgs.push_back("-fdeclare-opencl-builtins");
4008 }
4009}
4010
4011static void RenderHLSLOptions(const Driver &D, const ArgList &Args,
4012 ArgStringList &CmdArgs, types::ID InputType) {
4013 const unsigned ForwardedArguments[] = {
4014 options::OPT_hlsl_all_resources_bound,
4015 options::OPT_dxil_validator_version,
4016 options::OPT_res_may_alias,
4017 options::OPT_D,
4018 options::OPT_I,
4019 options::OPT_O,
4020 options::OPT_emit_llvm,
4021 options::OPT_emit_obj,
4022 options::OPT_disable_llvm_passes,
4023 options::OPT_fnative_half_type,
4024 options::OPT_fnative_int16_type,
4025 options::OPT_fmatrix_memory_layout_EQ,
4026 options::OPT_hlsl_entrypoint,
4027 options::OPT_fdx_rootsignature_define,
4028 options::OPT_fdx_rootsignature_version,
4029 options::OPT_fdx_semantic_signature_packing_mode_EQ,
4030 options::OPT_fhlsl_spv_use_unknown_image_format,
4031 options::OPT_fhlsl_spv_use_legacy_buffer_matrix_order,
4032 options::OPT_fhlsl_spv_enable_maximal_reconvergence,
4033 options::OPT_fhlsl_spv_preserve_interface};
4034 if (!types::isHLSL(InputType))
4035 return;
4036 for (const auto &Arg : ForwardedArguments)
4037 if (const auto *A = Args.getLastArg(Arg))
4038 A->renderAsInput(Args, CmdArgs);
4039 // Add the default headers if dxc_no_stdinc is not set.
4040 if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
4041 !Args.hasArg(options::OPT_nostdinc))
4042 CmdArgs.push_back("-finclude-default-header");
4043
4044 if (Args.hasArg(options::OPT_dxc_Zss)) {
4045 if (Args.hasArg(options::OPT_dxc_Zsb))
4046 D.Diag(diag::err_drv_dxc_invalid_shader_hash);
4047 CmdArgs.push_back("-mllvm");
4048 CmdArgs.push_back("-dx-Zss");
4049 }
4050 if (Arg *A = Args.getLastArg(options::OPT_dxc_Zsb))
4051 A->claim(); // /Zsb is the default behavior, no need to forward it to llc.
4052 if (Args.hasArg(options::OPT_dxc_source_in_debug_module)) {
4053 CmdArgs.push_back("-mllvm");
4054 CmdArgs.push_back("--dx-source-in-debug-module");
4055 }
4056 if (Args.hasArg(options::OPT_dxc_Qstrip_debug)) {
4057 CmdArgs.push_back("-mllvm");
4058 CmdArgs.push_back("--dx-strip-debug");
4059 }
4060 if (Args.hasArg(options::OPT_dxc_Qpdb_in_private)) {
4061 CmdArgs.push_back("-mllvm");
4062 CmdArgs.push_back("--dx-pdb-in-private");
4063 }
4064 CmdArgs.push_back("-load-bool-from-mem=nonzero");
4065}
4066
4067static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
4068 ArgStringList &CmdArgs, types::ID InputType) {
4069 if (!Args.hasArg(options::OPT_fopenacc))
4070 return;
4071
4072 CmdArgs.push_back("-fopenacc");
4073}
4074
4075static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
4076 const ArgList &Args, ArgStringList &CmdArgs) {
4077 // -fbuiltin is default unless -mkernel is used.
4078 bool UseBuiltins =
4079 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
4080 !Args.hasArg(options::OPT_mkernel));
4081 if (!UseBuiltins)
4082 CmdArgs.push_back("-fno-builtin");
4083
4084 // -ffreestanding implies -fno-builtin.
4085 if (Args.hasArg(options::OPT_ffreestanding))
4086 UseBuiltins = false;
4087
4088 // Process the -fno-builtin-* options.
4089 for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
4090 A->claim();
4091
4092 // If -fno-builtin is specified, then there's no need to pass the option to
4093 // the frontend.
4094 if (UseBuiltins)
4095 A->render(Args, CmdArgs);
4096 }
4097}
4098
4100 if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
4101 Twine Path{Str};
4102 Path.toVector(Result);
4103 return Path.getSingleStringRef() != "";
4104 }
4105 if (llvm::sys::path::cache_directory(Result)) {
4106 llvm::sys::path::append(Result, "clang");
4107 llvm::sys::path::append(Result, "ModuleCache");
4108 return true;
4109 }
4110 return false;
4111}
4112
4115 const char *BaseInput) {
4116 if (Arg *ModuleOutputEQ = Args.getLastArg(options::OPT_fmodule_output_EQ))
4117 return StringRef(ModuleOutputEQ->getValue());
4118
4119 SmallString<256> OutputPath;
4120 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o);
4121 FinalOutput && Args.hasArg(options::OPT_c))
4122 OutputPath = FinalOutput->getValue();
4123 else {
4124 llvm::sys::fs::current_path(OutputPath);
4125 llvm::sys::path::append(OutputPath, llvm::sys::path::filename(BaseInput));
4126 }
4127
4128 const char *Extension = types::getTypeTempSuffix(types::TY_ModuleFile);
4129 llvm::sys::path::replace_extension(OutputPath, Extension);
4130 return OutputPath;
4131}
4132
4134 const ArgList &Args, const InputInfo &Input,
4135 const InputInfo &Output, bool HaveStd20,
4136 ArgStringList &CmdArgs) {
4137 const bool IsCXX = types::isCXX(Input.getType());
4138 const bool HaveStdCXXModules = IsCXX && HaveStd20;
4139 bool HaveModules = HaveStdCXXModules;
4140
4141 // -fmodules enables the use of precompiled modules (off by default).
4142 // Users can pass -fno-cxx-modules to turn off modules support for
4143 // C++/Objective-C++ programs.
4144 const bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4145 options::OPT_fno_cxx_modules, true);
4146 bool HaveClangModules = false;
4147 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4148 if (AllowedInCXX || !IsCXX) {
4149 CmdArgs.push_back("-fmodules");
4150 HaveClangModules = true;
4151 }
4152 }
4153
4154 HaveModules |= HaveClangModules;
4155
4156 if (HaveModules && !AllowedInCXX)
4157 CmdArgs.push_back("-fno-cxx-modules");
4158
4159 // -fmodule-maps enables implicit reading of module map files. By default,
4160 // this is enabled if we are using Clang's flavor of precompiled modules.
4161 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4162 options::OPT_fno_implicit_module_maps, HaveClangModules))
4163 CmdArgs.push_back("-fimplicit-module-maps");
4164
4165 // -fmodules-decluse checks that modules used are declared so (off by default)
4166 Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
4167 options::OPT_fno_modules_decluse);
4168
4169 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4170 // all #included headers are part of modules.
4171 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4172 options::OPT_fno_modules_strict_decluse, false))
4173 CmdArgs.push_back("-fmodules-strict-decluse");
4174
4175 Args.addOptInFlag(CmdArgs, options::OPT_fmodulemap_allow_subdirectory_search,
4176 options::OPT_fno_modulemap_allow_subdirectory_search);
4177
4178 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4179 bool ImplicitModules = false;
4180 if (!Args.hasFlag(options::OPT_fimplicit_modules,
4181 options::OPT_fno_implicit_modules, HaveClangModules)) {
4182 if (HaveModules)
4183 CmdArgs.push_back("-fno-implicit-modules");
4184 } else if (HaveModules) {
4185 ImplicitModules = true;
4186 // -fmodule-cache-path specifies where our implicitly-built module files
4187 // should be written.
4188 SmallString<128> Path;
4189 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4190 Path = A->getValue();
4191
4192 bool HasPath = true;
4193 if (C.isForDiagnostics()) {
4194 // When generating crash reports, we want to emit the modules along with
4195 // the reproduction sources, so we ignore any provided module path.
4196 Path = Output.getFilename();
4197 llvm::sys::path::replace_extension(Path, ".cache");
4198 llvm::sys::path::append(Path, "modules");
4199 } else if (Path.empty()) {
4200 // No module path was provided: use the default.
4201 HasPath = Driver::getDefaultModuleCachePath(Path);
4202 }
4203
4204 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
4205 // That being said, that failure is unlikely and not caching is harmless.
4206 if (HasPath) {
4207 const char Arg[] = "-fmodules-cache-path=";
4208 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4209 CmdArgs.push_back(Args.MakeArgString(Path));
4210 }
4211
4212 Args.AddLastArg(CmdArgs, options::OPT_fimplicit_modules_lock_timeout_EQ);
4213 }
4214
4215 if (HaveModules) {
4216 if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
4217 options::OPT_fno_prebuilt_implicit_modules, false))
4218 CmdArgs.push_back("-fprebuilt-implicit-modules");
4219 if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
4220 options::OPT_fno_modules_validate_input_files_content,
4221 false))
4222 CmdArgs.push_back("-fvalidate-ast-input-files-content");
4223 }
4224
4225 // -fmodule-name specifies the module that is currently being built (or
4226 // used for header checking by -fmodule-maps).
4227 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
4228
4229 // -fmodule-map-file can be used to specify files containing module
4230 // definitions.
4231 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4232
4233 // -fbuiltin-module-map can be used to load the clang
4234 // builtin headers modulemap file.
4235 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
4236 SmallString<128> BuiltinModuleMap(D.ResourceDir);
4237 llvm::sys::path::append(BuiltinModuleMap, "include");
4238 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
4239 if (llvm::sys::fs::exists(BuiltinModuleMap))
4240 CmdArgs.push_back(
4241 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
4242 }
4243
4244 // The -fmodule-file=<name>=<file> form specifies the mapping of module
4245 // names to precompiled module files (the module is loaded only if used).
4246 // The -fmodule-file=<file> form can be used to unconditionally load
4247 // precompiled module files (whether used or not).
4248 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
4249 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4250
4251 // -fprebuilt-module-path specifies where to load the prebuilt module files.
4252 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
4253 CmdArgs.push_back(Args.MakeArgString(
4254 std::string("-fprebuilt-module-path=") + A->getValue()));
4255 A->claim();
4256 }
4257 } else
4258 Args.ClaimAllArgs(options::OPT_fmodule_file);
4259
4260 // When building modules and generating crashdumps, we need to dump a module
4261 // dependency VFS alongside the output.
4262 if (HaveClangModules && C.isForDiagnostics()) {
4263 SmallString<128> VFSDir(Output.getFilename());
4264 llvm::sys::path::replace_extension(VFSDir, ".cache");
4265 // Add the cache directory as a temp so the crash diagnostics pick it up.
4266 C.addTempFile(Args.MakeArgString(VFSDir));
4267
4268 llvm::sys::path::append(VFSDir, "vfs");
4269 CmdArgs.push_back("-module-dependency-dir");
4270 CmdArgs.push_back(Args.MakeArgString(VFSDir));
4271 }
4272
4273 if (HaveClangModules)
4274 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4275
4276 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4277 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_search_path);
4278 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4279 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4280
4281 if (HaveClangModules) {
4282 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4283
4284 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4285 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4286 D.Diag(diag::err_drv_argument_not_allowed_with)
4287 << A->getAsString(Args) << "-fbuild-session-timestamp";
4288
4289 llvm::sys::fs::file_status Status;
4290 if (llvm::sys::fs::status(A->getValue(), Status))
4291 D.Diag(diag::err_drv_no_such_file) << A->getValue();
4292 CmdArgs.push_back(Args.MakeArgString(
4293 "-fbuild-session-timestamp=" +
4294 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
4295 Status.getLastModificationTime().time_since_epoch())
4296 .count())));
4297 }
4298
4299 if (Args.getLastArg(
4300 options::OPT_fmodules_validate_once_per_build_session)) {
4301 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4302 options::OPT_fbuild_session_file))
4303 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4304
4305 Args.AddLastArg(CmdArgs,
4306 options::OPT_fmodules_validate_once_per_build_session);
4307 }
4308
4309 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
4310 options::OPT_fno_modules_validate_system_headers,
4311 ImplicitModules))
4312 CmdArgs.push_back("-fmodules-validate-system-headers");
4313
4314 if (Args.hasFlag(options::OPT_fmodules_validate_directory_dependencies,
4315 options::OPT_fno_modules_validate_directory_dependencies,
4316 false))
4317 CmdArgs.push_back("-fmodules-validate-directory-dependencies");
4318
4319 Args.AddLastArg(CmdArgs,
4320 options::OPT_fmodules_disable_diagnostic_validation);
4321 } else {
4322 Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
4323 Args.ClaimAllArgs(options::OPT_fbuild_session_file);
4324 Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
4325 Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
4326 Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
4327 Args.ClaimAllArgs(options::OPT_fmodules_validate_directory_dependencies);
4328 Args.ClaimAllArgs(options::OPT_fno_modules_validate_directory_dependencies);
4329 Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
4330 }
4331
4332 // FIXME: We provisionally don't check ODR violations for decls in the global
4333 // module fragment.
4334 CmdArgs.push_back("-fskip-odr-check-in-gmf");
4335
4336 if (Input.getType() == driver::types::TY_CXXModule ||
4337 Input.getType() == driver::types::TY_PP_CXXModule) {
4338 if (!Args.hasArg(options::OPT_fno_modules_reduced_bmi))
4339 CmdArgs.push_back("-fmodules-reduced-bmi");
4340
4341 if (Args.hasArg(options::OPT_fmodule_output_EQ))
4342 Args.AddLastArg(CmdArgs, options::OPT_fmodule_output_EQ);
4343 else if (!(Args.hasArg(options::OPT__precompile) ||
4344 Args.hasArg(options::OPT__precompile_reduced_bmi)) ||
4345 Args.hasArg(options::OPT_fmodule_output))
4346 // If --precompile is specified, we will always generate a module file if
4347 // we're compiling an importable module unit. This is fine even if the
4348 // compilation process won't reach the point of generating the module file
4349 // (e.g., in the preprocessing mode), since the attached flag
4350 // '-fmodule-output' is useless.
4351 //
4352 // But if '--precompile' is specified, it might be annoying to always
4353 // generate the module file as '--precompile' will generate the module
4354 // file anyway.
4355 CmdArgs.push_back(Args.MakeArgString(
4356 "-fmodule-output=" +
4358 }
4359
4360 if (Args.hasArg(options::OPT_fmodules_reduced_bmi) &&
4361 Args.hasArg(options::OPT__precompile) &&
4362 (!Args.hasArg(options::OPT_o) ||
4363 Args.getLastArg(options::OPT_o)->getValue() ==
4365 D.Diag(diag::err_drv_reduced_module_output_overrided);
4366 }
4367
4368 // Noop if we see '-fmodules-reduced-bmi' or `-fno-modules-reduced-bmi` with
4369 // other translation units than module units. This is more user friendly to
4370 // allow end uers to enable this feature without asking for help from build
4371 // systems.
4372 Args.ClaimAllArgs(options::OPT_fmodules_reduced_bmi);
4373 Args.ClaimAllArgs(options::OPT_fno_modules_reduced_bmi);
4374
4375 // We need to include the case the input file is a module file here.
4376 // Since the default compilation model for C++ module interface unit will
4377 // create temporary module file and compile the temporary module file
4378 // to get the object file. Then the `-fmodule-output` flag will be
4379 // brought to the second compilation process. So we have to claim it for
4380 // the case too.
4381 if (Input.getType() == driver::types::TY_CXXModule ||
4382 Input.getType() == driver::types::TY_PP_CXXModule ||
4383 Input.getType() == driver::types::TY_ModuleFile) {
4384 Args.ClaimAllArgs(options::OPT_fmodule_output);
4385 Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
4386 }
4387
4388 if (Args.hasArg(options::OPT_fmodules_embed_all_files))
4389 CmdArgs.push_back("-fmodules-embed-all-files");
4390
4391 return HaveModules;
4392}
4393
4394static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4395 ArgStringList &CmdArgs) {
4396 // -fsigned-char is default.
4397 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
4398 options::OPT_fno_signed_char,
4399 options::OPT_funsigned_char,
4400 options::OPT_fno_unsigned_char)) {
4401 if (A->getOption().matches(options::OPT_funsigned_char) ||
4402 A->getOption().matches(options::OPT_fno_signed_char)) {
4403 CmdArgs.push_back("-fno-signed-char");
4404 }
4405 } else if (!isSignedCharDefault(T)) {
4406 CmdArgs.push_back("-fno-signed-char");
4407 }
4408
4409 // The default depends on the language standard.
4410 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
4411
4412 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4413 options::OPT_fno_short_wchar)) {
4414 if (A->getOption().matches(options::OPT_fshort_wchar)) {
4415 CmdArgs.push_back("-fwchar-type=short");
4416 CmdArgs.push_back("-fno-signed-wchar");
4417 } else {
4418 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4419 CmdArgs.push_back("-fwchar-type=int");
4420 if (T.isOSzOS() ||
4421 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4422 CmdArgs.push_back("-fno-signed-wchar");
4423 else
4424 CmdArgs.push_back("-fsigned-wchar");
4425 }
4426 } else if (T.isOSzOS())
4427 CmdArgs.push_back("-fno-signed-wchar");
4428}
4429
4430static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4431 const llvm::Triple &T, const ArgList &Args,
4432 ObjCRuntime &Runtime, bool InferCovariantReturns,
4433 const InputInfo &Input, ArgStringList &CmdArgs) {
4434 const llvm::Triple::ArchType Arch = TC.getArch();
4435
4436 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4437 // is the default. Except for deployment target of 10.5, next runtime is
4438 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4439 if (Runtime.isNonFragile()) {
4440 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4441 options::OPT_fno_objc_legacy_dispatch,
4443 if (TC.UseObjCMixedDispatch())
4444 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
4445 else
4446 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
4447 }
4448 }
4449
4450 // Forward -fobjc-direct-precondition-thunk to cc1
4451 // Defaults to false and needs explict turn on for now
4452 // TODO: switch to default true and needs explict turn off in the future.
4453 // TODO: add support for other runtimes
4454 if (Args.hasFlag(options::OPT_fobjc_direct_precondition_thunk,
4455 options::OPT_fno_objc_direct_precondition_thunk, false)) {
4456 if (Runtime.isNeXTFamily()) {
4457 CmdArgs.push_back("-fobjc-direct-precondition-thunk");
4458 } else {
4459 D.Diag(diag::warn_drv_unsupported_option_for_runtime)
4460 << "-fobjc-direct-precondition-thunk" << Runtime.getAsString();
4461 }
4462 }
4463
4464 if (types::isObjC(Input.getType())) {
4465 // Pass down -fobjc-msgsend-selector-stubs if present.
4466 if (Args.hasFlag(options::OPT_fobjc_msgsend_selector_stubs,
4467 options::OPT_fno_objc_msgsend_selector_stubs, false))
4468 CmdArgs.push_back("-fobjc-msgsend-selector-stubs");
4469
4470 // Pass down -fobjc-msgsend-class-selector-stubs if present.
4471 if (Args.hasFlag(options::OPT_fobjc_msgsend_class_selector_stubs,
4472 options::OPT_fno_objc_msgsend_class_selector_stubs, false))
4473 CmdArgs.push_back("-fobjc-msgsend-class-selector-stubs");
4474 }
4475
4476 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4477 // to do Array/Dictionary subscripting by default.
4478 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4479 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4480 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4481
4482 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4483 // NOTE: This logic is duplicated in ToolChains.cpp.
4484 if (isObjCAutoRefCount(Args)) {
4485 TC.CheckObjCARC();
4486
4487 CmdArgs.push_back("-fobjc-arc");
4488
4489 // FIXME: It seems like this entire block, and several around it should be
4490 // wrapped in isObjC, but for now we just use it here as this is where it
4491 // was being used previously.
4492 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
4494 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4495 else
4496 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4497 }
4498
4499 // Allow the user to enable full exceptions code emission.
4500 // We default off for Objective-C, on for Objective-C++.
4501 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4502 options::OPT_fno_objc_arc_exceptions,
4503 /*Default=*/types::isCXX(Input.getType())))
4504 CmdArgs.push_back("-fobjc-arc-exceptions");
4505 }
4506
4507 // Silence warning for full exception code emission options when explicitly
4508 // set to use no ARC.
4509 if (Args.hasArg(options::OPT_fno_objc_arc)) {
4510 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
4511 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
4512 }
4513
4514 // Allow the user to control whether messages can be converted to runtime
4515 // functions.
4516 if (types::isObjC(Input.getType())) {
4517 auto *Arg = Args.getLastArg(
4518 options::OPT_fobjc_convert_messages_to_runtime_calls,
4519 options::OPT_fno_objc_convert_messages_to_runtime_calls);
4520 if (Arg &&
4521 Arg->getOption().matches(
4522 options::OPT_fno_objc_convert_messages_to_runtime_calls))
4523 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
4524 }
4525
4526 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4527 // rewriter.
4528 if (InferCovariantReturns)
4529 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4530
4531 // Pass down -fobjc-weak or -fno-objc-weak if present.
4532 if (types::isObjC(Input.getType())) {
4533 auto WeakArg =
4534 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
4535 if (!WeakArg) {
4536 // nothing to do
4537 } else if (!Runtime.allowsWeak()) {
4538 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
4539 D.Diag(diag::err_objc_weak_unsupported);
4540 } else {
4541 WeakArg->render(Args, CmdArgs);
4542 }
4543 }
4544
4545 if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4546 CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
4547
4548 // Forward constant literal flags to cc1.
4549 if (types::isObjC(Input.getType())) {
4550 bool EnableConstantLiterals =
4551 Args.hasFlag(options::OPT_fobjc_constant_literals,
4552 options::OPT_fno_objc_constant_literals,
4553 /*default=*/true) &&
4554 Runtime.hasConstantLiteralClasses();
4555 if (EnableConstantLiterals)
4556 CmdArgs.push_back("-fobjc-constant-literals");
4557 if (Args.hasFlag(options::OPT_fconstant_nsnumber_literals,
4558 options::OPT_fno_constant_nsnumber_literals,
4559 /*default=*/true) &&
4560 EnableConstantLiterals)
4561 CmdArgs.push_back("-fconstant-nsnumber-literals");
4562 if (Args.hasFlag(options::OPT_fconstant_nsarray_literals,
4563 options::OPT_fno_constant_nsarray_literals,
4564 /*default=*/true) &&
4565 EnableConstantLiterals)
4566 CmdArgs.push_back("-fconstant-nsarray-literals");
4567 if (Args.hasFlag(options::OPT_fconstant_nsdictionary_literals,
4568 options::OPT_fno_constant_nsdictionary_literals,
4569 /*default=*/true) &&
4570 EnableConstantLiterals)
4571 CmdArgs.push_back("-fconstant-nsdictionary-literals");
4572 }
4573}
4574
4575static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4576 ArgStringList &CmdArgs) {
4577 bool CaretDefault = true;
4578 bool ColumnDefault = true;
4579
4580 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4581 options::OPT__SLASH_diagnostics_column,
4582 options::OPT__SLASH_diagnostics_caret)) {
4583 switch (A->getOption().getID()) {
4584 case options::OPT__SLASH_diagnostics_caret:
4585 CaretDefault = true;
4586 ColumnDefault = true;
4587 break;
4588 case options::OPT__SLASH_diagnostics_column:
4589 CaretDefault = false;
4590 ColumnDefault = true;
4591 break;
4592 case options::OPT__SLASH_diagnostics_classic:
4593 CaretDefault = false;
4594 ColumnDefault = false;
4595 break;
4596 }
4597 }
4598
4599 // -fcaret-diagnostics is default.
4600 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4601 options::OPT_fno_caret_diagnostics, CaretDefault))
4602 CmdArgs.push_back("-fno-caret-diagnostics");
4603
4604 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
4605 options::OPT_fno_diagnostics_fixit_info);
4606 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
4607 options::OPT_fno_diagnostics_show_option);
4608
4609 if (const Arg *A =
4610 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4611 CmdArgs.push_back("-fdiagnostics-show-category");
4612 CmdArgs.push_back(A->getValue());
4613 }
4614
4615 Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
4616 options::OPT_fno_diagnostics_show_hotness);
4617
4618 Args.addOptOutFlag(CmdArgs, options::OPT_flifetime_safety_c,
4619 options::OPT_fno_lifetime_safety_c);
4620
4621 if (const Arg *A =
4622 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4623 std::string Opt =
4624 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4625 CmdArgs.push_back(Args.MakeArgString(Opt));
4626 }
4627
4628 if (const Arg *A =
4629 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4630 std::string Opt =
4631 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4632 CmdArgs.push_back(Args.MakeArgString(Opt));
4633 }
4634
4635 if (const Arg *A =
4636 Args.getLastArg(options::OPT_fdiagnostics_show_inlining_chain,
4637 options::OPT_fno_diagnostics_show_inlining_chain)) {
4638 if (A->getOption().matches(options::OPT_fdiagnostics_show_inlining_chain))
4639 CmdArgs.push_back("-fdiagnostics-show-inlining-chain");
4640 else
4641 CmdArgs.push_back("-fno-diagnostics-show-inlining-chain");
4642 }
4643
4644 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4645 CmdArgs.push_back("-fdiagnostics-format");
4646 CmdArgs.push_back(A->getValue());
4647 if (StringRef(A->getValue()) == "sarif" ||
4648 StringRef(A->getValue()) == "SARIF")
4649 D.Diag(diag::warn_drv_sarif_format_unstable);
4650 }
4651
4652 if (const Arg *A = Args.getLastArg(
4653 options::OPT_fdiagnostics_show_note_include_stack,
4654 options::OPT_fno_diagnostics_show_note_include_stack)) {
4655 const Option &O = A->getOption();
4656 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4657 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4658 else
4659 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4660 }
4661
4662 handleColorDiagnosticsArgs(D, Args, CmdArgs);
4663
4664 if (Args.hasArg(options::OPT_fansi_escape_codes))
4665 CmdArgs.push_back("-fansi-escape-codes");
4666
4667 Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
4668 options::OPT_fno_show_source_location);
4669
4670 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
4671 options::OPT_fno_diagnostics_show_line_numbers);
4672
4673 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4674 CmdArgs.push_back("-fdiagnostics-absolute-paths");
4675
4676 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4677 ColumnDefault))
4678 CmdArgs.push_back("-fno-show-column");
4679
4680 Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
4681 options::OPT_fno_spell_checking);
4682
4683 Args.addLastArg(CmdArgs, options::OPT_warning_suppression_mappings_EQ);
4684}
4685
4686static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4687 const ArgList &Args, ArgStringList &CmdArgs,
4688 unsigned DwarfVersion) {
4689 auto *DwarfFormatArg =
4690 Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4691 if (!DwarfFormatArg)
4692 return;
4693
4694 if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4695 if (DwarfVersion < 3)
4696 D.Diag(diag::err_drv_argument_only_allowed_with)
4697 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4698 else if (!T.isArch64Bit())
4699 D.Diag(diag::err_drv_argument_only_allowed_with)
4700 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4701 else if (!T.isOSBinFormatELF())
4702 D.Diag(diag::err_drv_argument_only_allowed_with)
4703 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4704 }
4705
4706 DwarfFormatArg->render(Args, CmdArgs);
4707}
4708
4709static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D,
4710 const ArgList &Args) {
4711 bool NeedsSimpleTemplateNames =
4712 Args.hasFlag(options::OPT_gsimple_template_names,
4713 options::OPT_gno_simple_template_names,
4715 if (!NeedsSimpleTemplateNames)
4716 return false;
4717
4718 if (const Arg *A = Args.getLastArg(options::OPT_gsimple_template_names))
4719 if (!checkDebugInfoOption(A, Args, D, TC))
4720 return false;
4721
4722 return true;
4723}
4724
4725static void
4726renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4727 const ArgList &Args, types::ID InputType,
4728 ArgStringList &CmdArgs, const InputInfo &Output,
4729 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4730 DwarfFissionKind &DwarfFission, bool IsUsingLTO) {
4731 bool IRInput = isLLVMIR(InputType);
4732 bool PlainCOrCXX = isDerivedFromC(InputType) && !isCuda(InputType) &&
4733 !isHIP(InputType) && !isObjC(InputType) &&
4734 !isOpenCL(InputType);
4735
4736 addDebugInfoForProfilingArgs(D, TC, Args, CmdArgs);
4737
4738 if (!Args.hasFlag(options::OPT_fdebug_record_sysroot,
4739 options::OPT_fno_debug_record_sysroot, true))
4740 CmdArgs.push_back("-fno-debug-record-sysroot");
4741
4742 // The 'g' groups options involve a somewhat intricate sequence of decisions
4743 // about what to pass from the driver to the frontend, but by the time they
4744 // reach cc1 they've been factored into three well-defined orthogonal choices:
4745 // * what level of debug info to generate
4746 // * what dwarf version to write
4747 // * what debugger tuning to use
4748 // This avoids having to monkey around further in cc1 other than to disable
4749 // codeview if not running in a Windows environment. Perhaps even that
4750 // decision should be made in the driver as well though.
4751 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4752
4753 bool SplitDWARFInlining =
4754 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4755 options::OPT_fno_split_dwarf_inlining, false);
4756
4757 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4758 // object file generation and no IR generation, -gN should not be needed. So
4759 // allow -gsplit-dwarf with either -gN or IR input.
4760 if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4761 // FIXME: -gsplit-dwarf on AIX is currently unimplemented.
4762 if (TC.getTriple().isOSAIX() && Args.hasArg(options::OPT_gsplit_dwarf)) {
4763 D.Diag(diag::err_drv_unsupported_opt_for_target)
4764 << Args.getLastArg(options::OPT_gsplit_dwarf)->getSpelling()
4765 << TC.getTripleString();
4766 return;
4767 }
4768 Arg *SplitDWARFArg;
4769 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
4770 if (DwarfFission != DwarfFissionKind::None &&
4771 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
4772 DwarfFission = DwarfFissionKind::None;
4773 SplitDWARFInlining = false;
4774 }
4775 }
4776 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4777 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4778
4779 // If the last option explicitly specified a debug-info level, use it.
4780 if (checkDebugInfoOption(A, Args, D, TC) &&
4781 A->getOption().matches(options::OPT_gN_Group)) {
4782 DebugInfoKind = debugLevelToInfoKind(*A);
4783 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4784 // complicated if you've disabled inline info in the skeleton CUs
4785 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4786 // line-tables-only, so let those compose naturally in that case.
4787 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4788 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4789 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4790 SplitDWARFInlining))
4791 DwarfFission = DwarfFissionKind::None;
4792 }
4793 }
4794
4795 // If a debugger tuning argument appeared, remember it.
4796 bool HasDebuggerTuning = false;
4797 if (const Arg *A =
4798 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4799 HasDebuggerTuning = true;
4800 if (checkDebugInfoOption(A, Args, D, TC)) {
4801 if (A->getOption().matches(options::OPT_glldb))
4802 DebuggerTuning = llvm::DebuggerKind::LLDB;
4803 else if (A->getOption().matches(options::OPT_gsce))
4804 DebuggerTuning = llvm::DebuggerKind::SCE;
4805 else if (A->getOption().matches(options::OPT_gdbx))
4806 DebuggerTuning = llvm::DebuggerKind::DBX;
4807 else
4808 DebuggerTuning = llvm::DebuggerKind::GDB;
4809 }
4810 }
4811
4812 // If a -gdwarf argument appeared, remember it.
4813 bool EmitDwarf = false;
4814 if (const Arg *A = getDwarfNArg(Args))
4815 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4816
4817 bool EmitCodeView = false;
4818 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4819 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4820
4821 // If the user asked for debug info but did not explicitly specify -gcodeview
4822 // or -gdwarf, ask the toolchain for the default format.
4823 if (!EmitCodeView && !EmitDwarf &&
4824 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4825 switch (TC.getDefaultDebugFormat()) {
4826 case llvm::codegenoptions::DIF_CodeView:
4827 EmitCodeView = true;
4828 break;
4829 case llvm::codegenoptions::DIF_DWARF:
4830 EmitDwarf = true;
4831 break;
4832 }
4833 }
4834
4835 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4836 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4837 // be lower than what the user wanted.
4838 if (EmitDwarf) {
4839 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4840 // Clamp effective DWARF version to the max supported by the toolchain.
4841 EffectiveDWARFVersion =
4842 std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4843 } else {
4844 Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4845 }
4846
4847 // -gline-directives-only supported only for the DWARF debug info.
4848 if (RequestedDWARFVersion == 0 &&
4849 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4850 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4851
4852 // strict DWARF is set to false by default. But for DBX, we need it to be set
4853 // as true by default.
4854 if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4855 (void)checkDebugInfoOption(A, Args, D, TC);
4856 if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4857 DebuggerTuning == llvm::DebuggerKind::DBX))
4858 CmdArgs.push_back("-gstrict-dwarf");
4859
4860 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4861 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4862
4863 // Column info is included by default for everything except SCE and
4864 // CodeView if not use sampling PGO. Clang doesn't track end columns, just
4865 // starting columns, which, in theory, is fine for CodeView (and PDB). In
4866 // practice, however, the Microsoft debuggers don't handle missing end columns
4867 // well, and the AIX debugger DBX also doesn't handle the columns well, so
4868 // it's better not to include any column info.
4869 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4870 (void)checkDebugInfoOption(A, Args, D, TC);
4871 if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4872 !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
4873 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4874 DebuggerTuning != llvm::DebuggerKind::DBX)))
4875 CmdArgs.push_back("-gno-column-info");
4876
4877 if (!Args.hasFlag(options::OPT_gcall_site_info,
4878 options::OPT_gno_call_site_info, true))
4879 CmdArgs.push_back("-gno-call-site-info");
4880
4881 // FIXME: Move backend command line options to the module.
4882 if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4883 // If -gline-tables-only or -gline-directives-only is the last option it
4884 // wins.
4885 if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4886 TC)) {
4887 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4888 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4889 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4890 CmdArgs.push_back("-dwarf-ext-refs");
4891 CmdArgs.push_back("-fmodule-format=obj");
4892 }
4893 }
4894 }
4895
4896 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4897 CmdArgs.push_back("-fsplit-dwarf-inlining");
4898
4899 // After we've dealt with all combinations of things that could
4900 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4901 // figure out if we need to "upgrade" it to standalone debug info.
4902 // We parse these two '-f' options whether or not they will be used,
4903 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4904 bool NeedFullDebug = Args.hasFlag(
4905 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4906 DebuggerTuning == llvm::DebuggerKind::LLDB ||
4908 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4909 (void)checkDebugInfoOption(A, Args, D, TC);
4910
4911 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4912 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4913 if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4914 options::OPT_feliminate_unused_debug_types, false))
4915 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4916 else if (NeedFullDebug)
4917 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4918 }
4919
4920 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4921 false)) {
4922 // Source embedding is a vendor extension to DWARF v5. By now we have
4923 // checked if a DWARF version was stated explicitly, and have otherwise
4924 // fallen back to the target default, so if this is still not at least 5
4925 // we emit an error.
4926 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4927 if (RequestedDWARFVersion < 5)
4928 D.Diag(diag::err_drv_argument_only_allowed_with)
4929 << A->getAsString(Args) << "-gdwarf-5";
4930 else if (EffectiveDWARFVersion < 5)
4931 // The toolchain has reduced allowed dwarf version, so we can't enable
4932 // -gembed-source.
4933 D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4934 << A->getAsString(Args) << TC.getTripleString() << 5
4935 << EffectiveDWARFVersion;
4936 else if (checkDebugInfoOption(A, Args, D, TC))
4937 CmdArgs.push_back("-gembed-source");
4938 }
4939
4940 // Enable Key Instructions by default if we're emitting DWARF, the language is
4941 // plain C or C++, and optimisations are enabled.
4942 Arg *OptLevel = Args.getLastArg(options::OPT_O_Group);
4943 bool KeyInstructionsOnByDefault =
4944 EmitDwarf && PlainCOrCXX && OptLevel &&
4945 !OptLevel->getOption().matches(options::OPT_O0);
4946 if (Args.hasFlag(options::OPT_gkey_instructions,
4947 options::OPT_gno_key_instructions,
4948 KeyInstructionsOnByDefault))
4949 CmdArgs.push_back("-gkey-instructions");
4950
4951 if (!Args.hasFlag(options::OPT_gstructor_decl_linkage_names,
4952 options::OPT_gno_structor_decl_linkage_names, true))
4953 CmdArgs.push_back("-gno-structor-decl-linkage-names");
4954
4955 if (Args.hasFlag(options::OPT_fdynamic_debugging,
4956 options::OPT_fno_dynamic_debugging, false)) {
4957 // As this is an experimental feature we can afford to be strict about
4958 // supported configurations.
4959 // NOTE on adding target support, consider adding "tail-pad-to-size"
4960 // support in `llvm::prepareForDynamicDebugging`.
4961 if (!TC.getTriple().isX86())
4962 D.Diag(diag::err_drv_unsupported_opt_for_target)
4963 << Args.getLastArg(options::OPT_fdynamic_debugging)->getAsString(Args)
4964 << T.getTriple();
4965 if (IsUsingLTO)
4966 D.Diag(diag::err_drv_dyndbg_lto);
4967 if (DwarfFission != DwarfFissionKind::None)
4968 D.Diag(diag::err_drv_dyndbg_incompatible)
4969 << Args.getLastArg(options::OPT_gsplit_dwarf)->getAsString(Args);
4970 // There's no fundamental reason why IR input should be incompatible, but
4971 // it would add some complexity, and reducing the test matrix is valuable.
4972 if (IRInput)
4973 D.Diag(diag::err_drv_dyndbg_ir);
4974
4975 // Disable composition with sanitizers for now.
4976 if (auto *San = Args.getLastArg(options::OPT_fsanitize_EQ))
4977 D.Diag(diag::err_drv_dyndbg_incompatible) << San->getAsString(Args);
4978
4979 if (!EmitDwarf)
4980 D.Diag(diag::warn_drv_dyndbg_req_debug);
4981 else
4982 CmdArgs.push_back("-fdynamic-debugging");
4983 }
4984
4985 if (EmitCodeView) {
4986 CmdArgs.push_back("-gcodeview");
4987
4988 Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4989 options::OPT_gno_codeview_ghash);
4990
4991 Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4992 options::OPT_gno_codeview_command_line);
4993 }
4994
4995 Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4996 options::OPT_gno_inline_line_tables);
4997
4998 // When emitting remarks, we need at least debug lines in the output.
4999 if (willEmitRemarks(Args) &&
5000 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
5001 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
5002
5003 // Adjust the debug info kind for the given toolchain.
5004 TC.adjustDebugInfoKind(DebugInfoKind, Args);
5005
5006 // On AIX, the debugger tuning option can be omitted if it is not explicitly
5007 // set.
5008 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
5009 T.isOSAIX() && !HasDebuggerTuning
5010 ? llvm::DebuggerKind::Default
5011 : DebuggerTuning);
5012
5013 // -fdebug-macro turns on macro debug info generation.
5014 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
5015 false))
5016 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
5017 D, TC))
5018 CmdArgs.push_back("-debug-info-macro");
5019
5020 // -ggnu-pubnames turns on gnu style pubnames in the backend.
5021 const auto *PubnamesArg =
5022 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
5023 options::OPT_gpubnames, options::OPT_gno_pubnames);
5024 if (DwarfFission != DwarfFissionKind::None ||
5025 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC))) {
5026 const bool OptionSet =
5027 (PubnamesArg &&
5028 (PubnamesArg->getOption().matches(options::OPT_gpubnames) ||
5029 PubnamesArg->getOption().matches(options::OPT_ggnu_pubnames)));
5030 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
5031 (!PubnamesArg ||
5032 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
5033 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames))))
5034 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
5035 options::OPT_gpubnames)
5036 ? "-gpubnames"
5037 : "-ggnu-pubnames");
5038 }
5039
5040 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
5041 if (getDebugSimpleTemplateNames(TC, D, Args)) {
5042 ForwardTemplateParams = true;
5043 CmdArgs.push_back("-gsimple-template-names=simple");
5044 }
5045
5046 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
5047 bool UseDebugTemplateAlias =
5048 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
5049 if (const auto *DebugTemplateAlias = Args.getLastArg(
5050 options::OPT_gtemplate_alias, options::OPT_gno_template_alias)) {
5051 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
5052 // asks for it we should let them have it (if the target supports it).
5053 if (checkDebugInfoOption(DebugTemplateAlias, Args, D, TC)) {
5054 const auto &Opt = DebugTemplateAlias->getOption();
5055 UseDebugTemplateAlias = Opt.matches(options::OPT_gtemplate_alias);
5056 }
5057 }
5058 if (UseDebugTemplateAlias)
5059 CmdArgs.push_back("-gtemplate-alias");
5060
5061 if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
5062 StringRef v = A->getValue();
5063 CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
5064 }
5065
5066 Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
5067 options::OPT_fno_debug_ranges_base_address);
5068
5069 // -gdwarf-aranges turns on the emission of the aranges section in the
5070 // backend.
5071 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges);
5072 A && checkDebugInfoOption(A, Args, D, TC)) {
5073 CmdArgs.push_back("-mllvm");
5074 CmdArgs.push_back("-generate-arange-section");
5075 }
5076
5077 Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
5078 options::OPT_fno_force_dwarf_frame);
5079
5080 bool EnableTypeUnits = false;
5081 if (Args.hasFlag(options::OPT_fdebug_types_section,
5082 options::OPT_fno_debug_types_section, false)) {
5083 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
5084 D.Diag(diag::err_drv_unsupported_opt_for_target)
5085 << Args.getLastArg(options::OPT_fdebug_types_section)
5086 ->getAsString(Args)
5087 << T.getTriple();
5088 } else if (checkDebugInfoOption(
5089 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
5090 TC)) {
5091 EnableTypeUnits = true;
5092 CmdArgs.push_back("-mllvm");
5093 CmdArgs.push_back("-generate-type-units");
5094 }
5095 }
5096
5097 if (const Arg *A =
5098 Args.getLastArg(options::OPT_gomit_unreferenced_methods,
5099 options::OPT_gno_omit_unreferenced_methods))
5100 (void)checkDebugInfoOption(A, Args, D, TC);
5101 if (Args.hasFlag(options::OPT_gomit_unreferenced_methods,
5102 options::OPT_gno_omit_unreferenced_methods, false) &&
5103 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
5104 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
5105 !EnableTypeUnits) {
5106 CmdArgs.push_back("-gomit-unreferenced-methods");
5107 }
5108
5109 // To avoid join/split of directory+filename, the integrated assembler prefers
5110 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
5111 // form before DWARF v5.
5112 if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
5113 options::OPT_fno_dwarf_directory_asm,
5114 TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
5115 CmdArgs.push_back("-fno-dwarf-directory-asm");
5116
5117 // Decide how to render forward declarations of template instantiations.
5118 // SCE wants full descriptions, others just get them in the name.
5119 if (ForwardTemplateParams)
5120 CmdArgs.push_back("-debug-forward-template-params");
5121
5122 // Do we need to explicitly import anonymous namespaces into the parent
5123 // scope?
5124 if (DebuggerTuning == llvm::DebuggerKind::SCE)
5125 CmdArgs.push_back("-dwarf-explicit-import");
5126
5127 renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
5128 renderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
5129
5130 // This controls whether or not we perform JustMyCode instrumentation.
5131 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
5132 if (TC.getTriple().isOSBinFormatELF() ||
5133 TC.getTriple().isWindowsMSVCEnvironment()) {
5134 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
5135 CmdArgs.push_back("-fjmc");
5136 else if (D.IsCLMode())
5137 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
5138 << "'/Zi', '/Z7'";
5139 else
5140 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
5141 << "-g";
5142 } else {
5143 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
5144 }
5145 }
5146
5147 // Add in -fdebug-compilation-dir if necessary.
5148 const char *DebugCompilationDir =
5149 addDebugCompDirArg(Args, CmdArgs, D.getVFS());
5150
5151 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
5152
5153 // Add the output path to the object file for CodeView debug infos.
5154 if (EmitCodeView && Output.isFilename())
5155 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
5156 Output.getFilename());
5157}
5158
5159static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
5160 ArgStringList &CmdArgs) {
5161 unsigned RTOptionID = options::OPT__SLASH_MT;
5162
5163 if (Args.hasArg(options::OPT__SLASH_LDd))
5164 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5165 // but defining _DEBUG is sticky.
5166 RTOptionID = options::OPT__SLASH_MTd;
5167
5168 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5169 RTOptionID = A->getOption().getID();
5170
5171 if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
5172 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
5173 .Case("static", options::OPT__SLASH_MT)
5174 .Case("static_dbg", options::OPT__SLASH_MTd)
5175 .Case("dll", options::OPT__SLASH_MD)
5176 .Case("dll_dbg", options::OPT__SLASH_MDd)
5177 .Default(options::OPT__SLASH_MT);
5178 }
5179
5180 StringRef FlagForCRT;
5181 switch (RTOptionID) {
5182 case options::OPT__SLASH_MD:
5183 if (Args.hasArg(options::OPT__SLASH_LDd))
5184 CmdArgs.push_back("-D_DEBUG");
5185 CmdArgs.push_back("-D_MT");
5186 CmdArgs.push_back("-D_DLL");
5187 FlagForCRT = "--dependent-lib=msvcrt";
5188 break;
5189 case options::OPT__SLASH_MDd:
5190 CmdArgs.push_back("-D_DEBUG");
5191 CmdArgs.push_back("-D_MT");
5192 CmdArgs.push_back("-D_DLL");
5193 FlagForCRT = "--dependent-lib=msvcrtd";
5194 break;
5195 case options::OPT__SLASH_MT:
5196 if (Args.hasArg(options::OPT__SLASH_LDd))
5197 CmdArgs.push_back("-D_DEBUG");
5198 CmdArgs.push_back("-D_MT");
5199 CmdArgs.push_back("-flto-visibility-public-std");
5200 FlagForCRT = "--dependent-lib=libcmt";
5201 break;
5202 case options::OPT__SLASH_MTd:
5203 CmdArgs.push_back("-D_DEBUG");
5204 CmdArgs.push_back("-D_MT");
5205 CmdArgs.push_back("-flto-visibility-public-std");
5206 FlagForCRT = "--dependent-lib=libcmtd";
5207 break;
5208 default:
5209 llvm_unreachable("Unexpected option ID.");
5210 }
5211
5212 if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
5213 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5214 } else {
5215 CmdArgs.push_back(FlagForCRT.data());
5216
5217 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5218 // users want. The /Za flag to cl.exe turns this off, but it's not
5219 // implemented in clang.
5220 CmdArgs.push_back("--dependent-lib=oldnames");
5221 }
5222
5223 // SYCL: Add SYCL runtime library dependency
5224 // SYCL runtime is a required dependency similar to CRT, so we use
5225 // --dependent-lib to embed it in the object file metadata
5226 if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false) &&
5227 !Args.hasArg(options::OPT_nolibsycl) &&
5228 !Args.hasArg(options::OPT_fms_omit_default_lib)) {
5229
5230 // Determine debug vs release based on CRT flags
5231 bool IsDebugBuild = false;
5232
5233 // Check -fms-runtime-lib=dll_dbg
5234 if (const Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
5235 StringRef RuntimeVal = A->getValue();
5236 if (RuntimeVal == "dll_dbg")
5237 IsDebugBuild = true;
5238 }
5239
5240 // Check for /MDd flag (dynamic debug CRT), use getLastArg to handle
5241 // overriding options (e.g., /MDd /MD -> /MD wins)
5242 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group)) {
5243 if (A->getOption().matches(options::OPT__SLASH_MDd))
5244 IsDebugBuild = true;
5245 }
5246
5247 // Add appropriate SYCL runtime library dependency
5248 CmdArgs.push_back(IsDebugBuild ? "--dependent-lib=LLVMSYCLd"
5249 : "--dependent-lib=LLVMSYCL");
5250 }
5251
5252 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
5253 // even if the file doesn't actually refer to any of the routines because
5254 // the CRT itself has incomplete dependency markings.
5255 if (TC.getTriple().isWindowsArm64EC())
5256 CmdArgs.push_back("--dependent-lib=softintrin");
5257}
5258
5260 const InputInfo &Output, const InputInfoList &Inputs,
5261 const ArgList &Args, const char *LinkingOutput) const {
5262 const auto &TC = getToolChain();
5263 const llvm::Triple &RawTriple = TC.getTriple();
5264 const llvm::Triple &Triple = TC.getEffectiveTriple();
5265 const std::string &TripleStr = Triple.getTriple();
5266
5267 bool KernelOrKext =
5268 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
5269 const Driver &D = TC.getDriver();
5270 ArgStringList CmdArgs;
5271
5272 assert(Inputs.size() >= 1 && "Must have at least one input.");
5273 // CUDA/HIP compilation may have multiple inputs (source file + results of
5274 // device-side compilations). OpenMP device jobs also take the host IR as a
5275 // second input. Module precompilation accepts a list of header files to
5276 // include as part of the module. API extraction accepts a list of header
5277 // files whose API information is emitted in the output. All other jobs are
5278 // expected to have exactly one input. SYCL compilation only expects a
5279 // single input.
5280 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
5281 bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
5282 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
5283 bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
5284 bool IsSYCL = JA.isOffloading(Action::OFK_SYCL);
5285 bool IsSYCLDevice = JA.isDeviceOffloading(Action::OFK_SYCL);
5286 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
5287 bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
5288 bool UsesLLVMOffloading = Args.hasFlag(
5289 options::OPT_foffload_via_llvm, options::OPT_fno_offload_via_llvm, false);
5290 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
5292 bool IsHostOffloadingAction =
5295 (JA.isHostOffloading(C.getActiveOffloadKinds()));
5296
5297 // SYCL defaults to RDC; CUDA/HIP default to non-RDC.
5298 bool IsRDCMode = Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
5299 /*Default=*/IsSYCL);
5300
5301 auto LTOMode = TC.getLTOMode(Args, JA.getOffloadingDeviceKind());
5302 bool IsUsingLTO = LTOMode != LTOK_None;
5303
5304 // Extract API doesn't have a main input file, so invent a fake one as a
5305 // placeholder.
5306 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
5307 "extract-api");
5308
5309 const InputInfo &Input =
5310 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
5311
5312 InputInfoList ExtractAPIInputs;
5313 InputInfoList HostOffloadingInputs;
5314 const InputInfo *OpenMPDeviceInput = nullptr;
5315 for (const InputInfo &I : Inputs) {
5316 if (&I == &Input || I.getType() == types::TY_Nothing) {
5317 // This is the primary input or contains nothing.
5318 } else if (IsExtractAPI) {
5319 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
5320 if (I.getType() != ExpectedInputType) {
5321 D.Diag(diag::err_drv_extract_api_wrong_kind)
5322 << I.getFilename() << types::getTypeName(I.getType())
5323 << types::getTypeName(ExpectedInputType);
5324 }
5325 ExtractAPIInputs.push_back(I);
5326 } else if (IsHostOffloadingAction) {
5327 HostOffloadingInputs.push_back(I);
5328 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
5329 OpenMPDeviceInput = &I;
5330 } else {
5331 llvm_unreachable("unexpectedly given multiple inputs");
5332 }
5333 }
5334
5335 bool IsUEFI = RawTriple.isUEFI();
5336 bool IsIAMCU = RawTriple.isOSIAMCU();
5337
5338 // C++ is not supported for IAMCU.
5339 if (IsIAMCU && types::isCXX(Input.getType()))
5340 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
5341
5342 // Invoke ourselves in -cc1 mode.
5343 //
5344 // FIXME: Implement custom jobs for internal actions.
5345 CmdArgs.push_back("-cc1");
5346
5347 // Add the "effective" target triple.
5348 CmdArgs.push_back("-triple");
5349 CmdArgs.push_back(Args.MakeArgStringRef(TripleStr));
5350
5351 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
5352
5353 const llvm::Triple *AuxTriple = TC.getAuxTriple();
5354 if (AuxTriple) {
5355 CmdArgs.push_back("-aux-triple");
5356 CmdArgs.push_back(Args.MakeArgStringRef(AuxTriple->str()));
5357
5358 // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations. Even when compiling
5359 // in device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
5360 // Windows), we need to pass Windows-specific flags to cc1.
5361 IsWindowsMSVC |= AuxTriple->isWindowsMSVCEnvironment();
5363 // Figure out the device side triple for the host-side compilation.
5364 for (unsigned I = Action::OFK_DeviceFirst; I <= Action::OFK_DeviceLast;
5365 ++I) {
5367 C.getOffloadToolChains(static_cast<Action::OffloadKind>(I));
5368 if (OffloadToolChains.first == OffloadToolChains.second)
5369 continue;
5370
5371 const llvm::Triple &DeviceAuxTriple =
5372 OffloadToolChains.first->second->getTriple();
5373 CmdArgs.push_back("-aux-triple");
5374 CmdArgs.push_back(Args.MakeArgStringRef(DeviceAuxTriple.str()));
5375 break;
5376 }
5377 }
5378
5379 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
5380 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
5381 Args.ClaimAllArgs(options::OPT_MJ);
5382 } else if (const Arg *GenCDBFragment =
5383 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
5384 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
5385 TripleStr, Output, Input, Args);
5386 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
5387 }
5388
5389 if ((getToolChain().getTriple().isAMDGPU() ||
5390 (getToolChain().getTriple().isSPIRV() &&
5391 getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
5392 // Device side compilation printf
5393 if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
5394 CmdArgs.push_back(Args.MakeArgString(
5395 "-mprintf-kind=" +
5396 Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
5397 // Force compiler error on invalid conversion specifiers
5398 CmdArgs.push_back(
5399 Args.MakeArgStringRef("-Werror=format-invalid-specifier"));
5400 }
5401 }
5402
5403 if (IsCuda && !IsCudaDevice && !UsesLLVMOffloading) {
5404 // We need to figure out which CUDA version we're compiling for, as that
5405 // determines how we load and launch GPU kernels.
5406 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
5407 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
5408 assert(CTC && "Expected valid CUDA Toolchain.");
5409 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
5410 CmdArgs.push_back(Args.MakeArgString(
5411 Twine("-target-sdk-version=") +
5412 CudaVersionToString(CTC->CudaInstallation.version())));
5413 }
5414
5415 // Optimization level for CodeGen.
5416 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5417 if (A->getOption().matches(options::OPT_O4)) {
5418 CmdArgs.push_back("-O3");
5419 D.Diag(diag::warn_O4_is_O3);
5420 } else {
5421 A->render(Args, CmdArgs);
5422 }
5423 }
5424
5425 // Unconditionally claim the printf option now to avoid unused diagnostic.
5426 if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
5427 PF->claim();
5428
5429 if (IsSYCL) {
5430 if (IsSYCLDevice) {
5431 // We want to compile sycl kernels.
5432 CmdArgs.push_back("-fsycl-is-device");
5433
5434 // Set O2 optimization level by default
5435 if (!Args.getLastArg(options::OPT_O_Group))
5436 CmdArgs.push_back("-O2");
5437 } else {
5438 // Add any options that are needed specific to SYCL offload while
5439 // performing the host side compilation.
5440
5441 // Let the front-end host compilation flow know about SYCL offload
5442 // compilation.
5443 CmdArgs.push_back("-fsycl-is-host");
5444 }
5445
5446 // Set options for both host and device.
5447 Arg *SYCLStdArg = Args.getLastArg(options::OPT_sycl_std_EQ);
5448 if (SYCLStdArg) {
5449 SYCLStdArg->render(Args, CmdArgs);
5450 } else {
5451 // Ensure the default version in SYCL mode is 2020.
5452 CmdArgs.push_back("-sycl-std=2020");
5453 }
5454 }
5455
5456 if (Args.hasFlag(options::OPT_fclangir, options::OPT_fno_clangir, false))
5457 CmdArgs.push_back("-fclangir");
5458
5459 if (IsOpenMPDevice) {
5460 // We have to pass the triple of the host if compiling for an OpenMP device.
5461 const llvm::Triple &HostTriple =
5462 C.getSingleOffloadToolChain<Action::OFK_Host>()->getTriple();
5463 CmdArgs.push_back("-aux-triple");
5464 CmdArgs.push_back(HostTriple.str().c_str());
5465 }
5466
5467 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5468 Triple.getArch() == llvm::Triple::thumb)) {
5469 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5470 unsigned Version = 0;
5471 bool Failure =
5472 Triple.getArchName().substr(Offset).consumeInteger(10, Version);
5473 if (Failure || Version < 7)
5474 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
5475 << TripleStr;
5476 }
5477
5478 // Push all default warning arguments that are specific to
5479 // the given target. These come before user provided warning options
5480 // are provided.
5481 TC.addClangWarningOptions(CmdArgs);
5482
5483 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5484 if (Triple.isSPIR() || Triple.isSPIRV())
5485 CmdArgs.push_back("-Wspir-compat");
5486
5487 // Select the appropriate action.
5488 RewriteKind rewriteKind = RK_None;
5489
5490 bool UnifiedLTO = false;
5491 if (IsUsingLTO) {
5492 UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
5493 options::OPT_fno_unified_lto, Triple.isPS());
5494 if (UnifiedLTO)
5495 CmdArgs.push_back("-funified-lto");
5496 }
5497
5498 if (Args.hasArg(options::OPT_fdefined_pointer_subtraction))
5499 CmdArgs.push_back("-fdefined-pointer-subtraction");
5500
5501 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5502 // it claims when not running an assembler. Otherwise, clang would emit
5503 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5504 // flags while debugging something. That'd be somewhat inconvenient, and it's
5505 // also inconsistent with most other flags -- we don't warn on
5506 // -ffunction-sections not being used in -E mode either for example, even
5507 // though it's not really used either.
5508 if (!isa<AssembleJobAction>(JA)) {
5509 // The args claimed here should match the args used in
5510 // CollectArgsForIntegratedAssembler().
5511 if (TC.useIntegratedAs()) {
5512 Args.ClaimAllArgs(options::OPT_mrelax_all);
5513 Args.ClaimAllArgs(options::OPT_mno_relax_all);
5514 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
5515 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
5516 switch (C.getDefaultToolChain().getArch()) {
5517 case llvm::Triple::arm:
5518 case llvm::Triple::armeb:
5519 case llvm::Triple::thumb:
5520 case llvm::Triple::thumbeb:
5521 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
5522 break;
5523 default:
5524 break;
5525 }
5526 }
5527 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
5528 Args.ClaimAllArgs(options::OPT_Xassembler);
5529 Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
5530 }
5531
5532 bool IsAMDSPIRVForHIPDevice =
5533 IsHIPDevice && getToolChain().getTriple().isSPIRV() &&
5534 getToolChain().getTriple().getVendor() == llvm::Triple::AMD;
5535
5536 if (isa<AnalyzeJobAction>(JA)) {
5537 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5538 CmdArgs.push_back("-analyze");
5539 } else if (isa<PreprocessJobAction>(JA)) {
5540 if (Output.getType() == types::TY_Dependencies)
5541 CmdArgs.push_back("-Eonly");
5542 else {
5543 CmdArgs.push_back("-E");
5544 if (Args.hasArg(options::OPT_rewrite_objc) &&
5545 !Args.hasArg(options::OPT_g_Group))
5546 CmdArgs.push_back("-P");
5547 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5548 CmdArgs.push_back("-fdirectives-only");
5549 }
5550 } else if (isa<AssembleJobAction>(JA)) {
5551 CmdArgs.push_back("-emit-obj");
5552
5553 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5554
5555 // Also ignore explicit -force_cpusubtype_ALL option.
5556 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5557 } else if (isa<PrecompileJobAction>(JA)) {
5558 if (JA.getType() == types::TY_Nothing)
5559 CmdArgs.push_back("-fsyntax-only");
5560 else if (JA.getType() == types::TY_ModuleFile) {
5561 if (Args.hasArg(options::OPT__precompile_reduced_bmi) ||
5562 ((Input.getType() == types::TY_CXXStdModule ||
5563 Input.getType() == types::TY_PP_CXXStdModule) &&
5564 !Args.hasArg(options::OPT_fno_modules_reduced_bmi)))
5565 CmdArgs.push_back("-emit-reduced-module-interface");
5566 else
5567 CmdArgs.push_back("-emit-module-interface");
5568 } else if (JA.getType() == types::TY_HeaderUnit)
5569 CmdArgs.push_back("-emit-header-unit");
5570 else if (!Args.hasArg(options::OPT_ignore_pch))
5571 CmdArgs.push_back("-emit-pch");
5572 } else if (isa<VerifyPCHJobAction>(JA)) {
5573 CmdArgs.push_back("-verify-pch");
5574 } else if (isa<ExtractAPIJobAction>(JA)) {
5575 assert(JA.getType() == types::TY_API_INFO &&
5576 "Extract API actions must generate a API information.");
5577 CmdArgs.push_back("-extract-api");
5578
5579 if (Arg *PrettySGFArg = Args.getLastArg(options::OPT_emit_pretty_sgf))
5580 PrettySGFArg->render(Args, CmdArgs);
5581
5582 Arg *SymbolGraphDirArg = Args.getLastArg(options::OPT_symbol_graph_dir_EQ);
5583
5584 if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
5585 ProductNameArg->render(Args, CmdArgs);
5586 if (Arg *ExtractAPIIgnoresFileArg =
5587 Args.getLastArg(options::OPT_extract_api_ignores_EQ))
5588 ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
5589 if (Arg *EmitExtensionSymbolGraphs =
5590 Args.getLastArg(options::OPT_emit_extension_symbol_graphs)) {
5591 if (!SymbolGraphDirArg)
5592 D.Diag(diag::err_drv_missing_symbol_graph_dir);
5593
5594 EmitExtensionSymbolGraphs->render(Args, CmdArgs);
5595 }
5596 if (SymbolGraphDirArg)
5597 SymbolGraphDirArg->render(Args, CmdArgs);
5598 } else {
5599 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5600 "Invalid action for clang tool.");
5601 if (JA.getType() == types::TY_Nothing) {
5602 CmdArgs.push_back("-fsyntax-only");
5603 } else if (JA.getType() == types::TY_LLVM_IR ||
5604 JA.getType() == types::TY_LTO_IR) {
5605 CmdArgs.push_back("-emit-llvm");
5606 } else if (JA.getType() == types::TY_LLVM_BC ||
5607 JA.getType() == types::TY_LTO_BC) {
5608 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5609 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
5610 Args.hasArg(options::OPT_emit_llvm)) {
5611 CmdArgs.push_back("-emit-llvm");
5612 } else {
5613 CmdArgs.push_back("-emit-llvm-bc");
5614 }
5615 } else if (JA.getType() == types::TY_IFS ||
5616 JA.getType() == types::TY_IFS_CPP) {
5617 StringRef ArgStr =
5618 Args.hasArg(options::OPT_interface_stub_version_EQ)
5619 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
5620 : "ifs-v1";
5621 CmdArgs.push_back("-emit-interface-stubs");
5622 CmdArgs.push_back(
5623 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr));
5624 } else if (JA.getType() == types::TY_PP_Asm) {
5625 CmdArgs.push_back("-S");
5626 } else if (JA.getType() == types::TY_AST) {
5627 if (!Args.hasArg(options::OPT_ignore_pch))
5628 CmdArgs.push_back("-emit-pch");
5629 } else if (JA.getType() == types::TY_ModuleFile) {
5630 CmdArgs.push_back("-module-file-info");
5631 } else if (JA.getType() == types::TY_RewrittenObjC) {
5632 CmdArgs.push_back("-rewrite-objc");
5633 rewriteKind = RK_NonFragile;
5634 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5635 CmdArgs.push_back("-rewrite-objc");
5636 rewriteKind = RK_Fragile;
5637 } else if (JA.getType() == types::TY_CIR) {
5638 CmdArgs.push_back("-emit-cir");
5639 } else if (JA.getType() == types::TY_CIRBC) {
5640 CmdArgs.push_back("-emit-cir-bc");
5641 } else if (JA.getType() == types::TY_Image && IsAMDSPIRVForHIPDevice) {
5642 CmdArgs.push_back("-emit-obj");
5643 } else {
5644 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5645 }
5646
5647 // Preserve use-list order by default when emitting bitcode, so that
5648 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5649 // same result as running passes here. For LTO, we don't need to preserve
5650 // the use-list order, since serialization to bitcode is part of the flow.
5651 if (JA.getType() == types::TY_LLVM_BC)
5652 CmdArgs.push_back("-emit-llvm-uselists");
5653
5654 if (IsUsingLTO) {
5655 const Arg *LTOArg = Args.getLastArg(options::OPT_foffload_lto,
5656 options::OPT_foffload_lto_EQ);
5657 if (Triple.isNVPTX() && !IsRDCMode &&
5659 D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
5660 << (LTOArg ? LTOArg->getAsString(Args) : "-foffload-lto")
5661 << "-fno-gpu-rdc";
5662 } else {
5663 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5664 CmdArgs.push_back(Args.MakeArgString(
5665 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5666 // PS4 uses the legacy LTO API, which does not support some of the
5667 // features enabled by -flto-unit.
5668 if (!RawTriple.isPS4() || (LTOMode == LTOK_Full) || !UnifiedLTO)
5669 CmdArgs.push_back("-flto-unit");
5670 }
5671 }
5672 }
5673
5674 Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
5675
5676 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
5677 if (!types::isLLVMIR(Input.getType()))
5678 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5679 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
5680 }
5681
5682 if (Triple.isPPC())
5683 Args.addOptInFlag(CmdArgs, options::OPT_mregnames,
5684 options::OPT_mno_regnames);
5685
5686 if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
5687 Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
5688
5689 if (Args.getLastArg(options::OPT_save_temps_EQ))
5690 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
5691
5692 if (Args.getLastArg(options::OPT_save_dynamic_debugging_temps))
5693 Args.AddLastArg(CmdArgs, options::OPT_save_dynamic_debugging_temps);
5694
5695 auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
5696 options::OPT_fmemory_profile_EQ,
5697 options::OPT_fno_memory_profile);
5698 if (MemProfArg &&
5699 !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
5700 MemProfArg->render(Args, CmdArgs);
5701
5702 if (auto *MemProfUseArg =
5703 Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
5704 if (MemProfArg)
5705 D.Diag(diag::err_drv_argument_not_allowed_with)
5706 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5707 if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
5708 options::OPT_fprofile_generate_EQ))
5709 D.Diag(diag::err_drv_argument_not_allowed_with)
5710 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5711 MemProfUseArg->render(Args, CmdArgs);
5712 }
5713
5714 auto *CopyProfArg =
5715 Args.getLastArg(options::OPT_fcopyprof, options::OPT_fno_copyprof);
5716 if (CopyProfArg &&
5717 !CopyProfArg->getOption().matches(options::OPT_fno_copyprof)) {
5718 CopyProfArg->render(Args, CmdArgs);
5719 Args.AddLastArg(CmdArgs, options::OPT_fcopyprof_static_size_threshold_EQ);
5720 }
5721
5722 // Embed-bitcode option.
5723 // Only white-listed flags below are allowed to be embedded.
5724 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5726 // Add flags implied by -fembed-bitcode.
5727 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
5728 // Disable all llvm IR level optimizations.
5729 CmdArgs.push_back("-disable-llvm-passes");
5730
5731 // Render target options.
5732 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingArch(),
5734
5735 // reject options that shouldn't be supported in bitcode
5736 // also reject kernel/kext
5737 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5738 options::OPT_mkernel,
5739 options::OPT_fapple_kext,
5740 options::OPT_ffunction_sections,
5741 options::OPT_fno_function_sections,
5742 options::OPT_fdata_sections,
5743 options::OPT_fno_data_sections,
5744 options::OPT_fbasic_block_sections_EQ,
5745 options::OPT_funique_internal_linkage_names,
5746 options::OPT_fno_unique_internal_linkage_names,
5747 options::OPT_funique_section_names,
5748 options::OPT_fno_unique_section_names,
5749 options::OPT_funique_basic_block_section_names,
5750 options::OPT_fno_unique_basic_block_section_names,
5751 options::OPT_mrestrict_it,
5752 options::OPT_mno_restrict_it,
5753 options::OPT_mstackrealign,
5754 options::OPT_mno_stackrealign,
5755 options::OPT_mstack_alignment,
5756 options::OPT_mcmodel_EQ,
5757 options::OPT_mlong_calls,
5758 options::OPT_mno_long_calls,
5759 options::OPT_ggnu_pubnames,
5760 options::OPT_gdwarf_aranges,
5761 options::OPT_fdebug_types_section,
5762 options::OPT_fno_debug_types_section,
5763 options::OPT_fdwarf_directory_asm,
5764 options::OPT_fno_dwarf_directory_asm,
5765 options::OPT_mrelax_all,
5766 options::OPT_mno_relax_all,
5767 options::OPT_ftrap_function_EQ,
5768 options::OPT_ffixed_r9,
5769 options::OPT_mfix_cortex_a53_835769,
5770 options::OPT_mno_fix_cortex_a53_835769,
5771 options::OPT_ffixed_x18,
5772 options::OPT_mglobal_merge,
5773 options::OPT_mno_global_merge,
5774 options::OPT_mred_zone,
5775 options::OPT_mno_red_zone,
5776 options::OPT_Wa_COMMA,
5777 options::OPT_Xassembler,
5778 options::OPT_mllvm,
5779 options::OPT_mmlir,
5780 };
5781 for (const auto &A : Args)
5782 if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
5783 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5784
5785 // Render the CodeGen options that need to be passed.
5786 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5787 options::OPT_fno_optimize_sibling_calls);
5788
5790 CmdArgs, JA);
5791
5792 // Render ABI arguments
5793 switch (TC.getArch()) {
5794 default: break;
5795 case llvm::Triple::arm:
5796 case llvm::Triple::armeb:
5797 case llvm::Triple::thumbeb:
5798 RenderARMABI(D, Triple, Args, CmdArgs);
5799 break;
5800 case llvm::Triple::aarch64:
5801 case llvm::Triple::aarch64_32:
5802 case llvm::Triple::aarch64_be:
5803 RenderAArch64ABI(Triple, Args, CmdArgs);
5804 break;
5805 }
5806
5807 // Input/Output file.
5808 if (Output.getType() == types::TY_Dependencies) {
5809 // Handled with other dependency code.
5810 } else if (Output.isFilename()) {
5811 CmdArgs.push_back("-o");
5812 CmdArgs.push_back(Output.getFilename());
5813 } else {
5814 assert(Output.isNothing() && "Input output.");
5815 }
5816
5817 for (const auto &II : Inputs) {
5818 addDashXForInput(Args, II, CmdArgs);
5819 if (II.isFilename())
5820 CmdArgs.push_back(II.getFilename());
5821 else
5822 II.getInputArg().renderAsInput(Args, CmdArgs);
5823 }
5824
5825 C.addCommand(std::make_unique<Command>(
5827 CmdArgs, Inputs, Output, D.getPrependArg()));
5828 return;
5829 }
5830
5831 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5832 CmdArgs.push_back("-fembed-bitcode=marker");
5833
5834 // We normally speed up the clang process a bit by skipping destructors at
5835 // exit, but when we're generating diagnostics we can rely on some of the
5836 // cleanup.
5837 if (!C.isForDiagnostics())
5838 CmdArgs.push_back("-disable-free");
5839 CmdArgs.push_back("-clear-ast-before-backend");
5840
5841#ifdef NDEBUG
5842 const bool IsAssertBuild = false;
5843#else
5844 const bool IsAssertBuild = true;
5845#endif
5846
5847 // Disable the verification pass in no-asserts builds unless otherwise
5848 // specified.
5849 if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
5850 options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
5851 CmdArgs.push_back("-disable-llvm-verifier");
5852 }
5853
5854 // Discard value names in no-asserts builds unless otherwise specified.
5855 if (Args.hasFlag(options::OPT_fdiscard_value_names,
5856 options::OPT_fno_discard_value_names, !IsAssertBuild))
5857 CmdArgs.push_back("-discard-value-names");
5858
5859 // Set the main file name, so that debug info works even with
5860 // -save-temps.
5861 CmdArgs.push_back("-main-file-name");
5862 CmdArgs.push_back(getBaseInputName(Args, Input));
5863
5864 // Some flags which affect the language (via preprocessor
5865 // defines).
5866 if (Args.hasArg(options::OPT_static))
5867 CmdArgs.push_back("-static-define");
5868
5869 Args.AddLastArg(CmdArgs, options::OPT_static_libclosure);
5870
5871 if (Args.hasArg(options::OPT_municode))
5872 CmdArgs.push_back("-DUNICODE");
5873
5874 if (isa<AnalyzeJobAction>(JA))
5875 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5876
5877 if (isa<AnalyzeJobAction>(JA) ||
5878 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5879 CmdArgs.push_back("-setup-static-analyzer");
5880
5881 // Enable compatilibily mode to avoid analyzer-config related errors.
5882 // Since we can't access frontend flags through hasArg, let's manually iterate
5883 // through them.
5884 bool FoundAnalyzerConfig = false;
5885 for (auto *Arg : Args.filtered(options::OPT_Xclang))
5886 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5887 FoundAnalyzerConfig = true;
5888 break;
5889 }
5890 if (!FoundAnalyzerConfig)
5891 for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5892 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5893 FoundAnalyzerConfig = true;
5894 break;
5895 }
5896 if (FoundAnalyzerConfig)
5897 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
5898
5900
5901 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5902 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5903 if (FunctionAlignment) {
5904 CmdArgs.push_back("-function-alignment");
5905 CmdArgs.push_back(Args.MakeArgString(Twine(FunctionAlignment)));
5906 }
5907
5908 if (const Arg *A =
5909 Args.getLastArg(options::OPT_fpreferred_function_alignment_EQ)) {
5910 unsigned Value = 0;
5911 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5912 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5913 << A->getAsString(Args) << A->getValue();
5914 else if (!llvm::isPowerOf2_32(Value))
5915 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5916 << A->getAsString(Args) << A->getValue();
5917
5918 CmdArgs.push_back(Args.MakeArgString("-fpreferred-function-alignment=" +
5919 Twine(std::min(Value, 65536u))));
5920 }
5921
5922 // We support -falign-loops=N where N is a power of 2. GCC supports more
5923 // forms.
5924 if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5925 unsigned Value = 0;
5926 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5927 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5928 << A->getAsString(Args) << A->getValue();
5929 else if (Value & (Value - 1))
5930 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5931 << A->getAsString(Args) << A->getValue();
5932 // Treat =0 as unspecified (use the target preference).
5933 if (Value)
5934 CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5935 Twine(std::min(Value, 65536u))));
5936 }
5937
5938 if (Triple.isOSzOS()) {
5939 // On z/OS some of the system header feature macros need to
5940 // be defined to enable most cross platform projects to build
5941 // successfully. Ths include the libc++ library. A
5942 // complicating factor is that users can define these
5943 // macros to the same or different values. We need to add
5944 // the definition for these macros to the compilation command
5945 // if the user hasn't already defined them.
5946
5947 auto findMacroDefinition = [&](const std::string &Macro) {
5948 auto MacroDefs = Args.getAllArgValues(options::OPT_D);
5949 return llvm::any_of(MacroDefs, [&](const std::string &M) {
5950 return M == Macro || M.find(Macro + '=') != std::string::npos;
5951 });
5952 };
5953
5954 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5955 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5956 CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
5957 // _OPEN_DEFAULT is required for XL compat
5958 if (!findMacroDefinition("_OPEN_DEFAULT"))
5959 CmdArgs.push_back("-D_OPEN_DEFAULT");
5960 if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
5961 // _XOPEN_SOURCE=600 is required for libcxx.
5962 if (!findMacroDefinition("_XOPEN_SOURCE"))
5963 CmdArgs.push_back("-D_XOPEN_SOURCE=600");
5964 }
5965 }
5966
5967 llvm::Reloc::Model RelocationModel;
5968 unsigned PICLevel;
5969 bool IsPIE;
5970 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5971 Arg *LastPICDataRelArg =
5972 Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5973 options::OPT_mpic_data_is_text_relative);
5974 bool NoPICDataIsTextRelative = false;
5975 if (LastPICDataRelArg) {
5976 if (LastPICDataRelArg->getOption().matches(
5977 options::OPT_mno_pic_data_is_text_relative)) {
5978 NoPICDataIsTextRelative = true;
5979 if (!PICLevel)
5980 D.Diag(diag::err_drv_argument_only_allowed_with)
5981 << "-mno-pic-data-is-text-relative"
5982 << "-fpic/-fpie";
5983 }
5984 if (!Triple.isSystemZ())
5985 D.Diag(diag::err_drv_unsupported_opt_for_target)
5986 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5987 : "-mpic-data-is-text-relative")
5988 << RawTriple.str();
5989 }
5990
5991 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5992 RelocationModel == llvm::Reloc::ROPI_RWPI;
5993 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5994 RelocationModel == llvm::Reloc::ROPI_RWPI;
5995
5996 if (Args.hasArg(options::OPT_mcmse) &&
5997 !Args.hasArg(options::OPT_fallow_unsupported)) {
5998 if (IsROPI)
5999 D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
6000 if (IsRWPI)
6001 D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
6002 }
6003
6004 if (IsROPI && types::isCXX(Input.getType()) &&
6005 !Args.hasArg(options::OPT_fallow_unsupported))
6006 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
6007
6008 const char *RMName = RelocationModelName(RelocationModel);
6009 if (RMName) {
6010 CmdArgs.push_back("-mrelocation-model");
6011 CmdArgs.push_back(RMName);
6012 }
6013 if (PICLevel > 0) {
6014 CmdArgs.push_back("-pic-level");
6015 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
6016 if (IsPIE)
6017 CmdArgs.push_back("-pic-is-pie");
6018 if (NoPICDataIsTextRelative)
6019 CmdArgs.push_back("-mcmodel=medium");
6020 }
6021
6022 if (RelocationModel == llvm::Reloc::ROPI ||
6023 RelocationModel == llvm::Reloc::ROPI_RWPI)
6024 CmdArgs.push_back("-fropi");
6025 if (RelocationModel == llvm::Reloc::RWPI ||
6026 RelocationModel == llvm::Reloc::ROPI_RWPI)
6027 CmdArgs.push_back("-frwpi");
6028
6029 // -meabi=gnu/5 are encoded in the cc1 -triple environment; forward only other
6030 // values (e.g. 4, which has no triple representation, and invalid values).
6031 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
6032 StringRef Value = A->getValue();
6033 if (Value != "gnu" && Value != "5") {
6034 CmdArgs.push_back("-meabi");
6035 CmdArgs.push_back(A->getValue());
6036 }
6037 }
6038
6039 // -fsemantic-interposition is forwarded to CC1: set the
6040 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
6041 // make default visibility external linkage definitions dso_preemptable.
6042 //
6043 // -fno-semantic-interposition: if the target supports .Lfoo$local local
6044 // aliases (make default visibility external linkage definitions dso_local).
6045 // This is the CC1 default for ELF to match COFF/Mach-O.
6046 //
6047 // Otherwise use Clang's traditional behavior: like
6048 // -fno-semantic-interposition but local aliases are not used. So references
6049 // can be interposed if not optimized out.
6050 if (Triple.isOSBinFormatELF()) {
6051 Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
6052 options::OPT_fno_semantic_interposition);
6053 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
6054 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
6055 bool SupportsLocalAlias =
6056 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
6057 if (!A)
6058 CmdArgs.push_back("-fhalf-no-semantic-interposition");
6059 else if (A->getOption().matches(options::OPT_fsemantic_interposition))
6060 A->render(Args, CmdArgs);
6061 else if (!SupportsLocalAlias)
6062 CmdArgs.push_back("-fhalf-no-semantic-interposition");
6063 }
6064 }
6065
6066 {
6067 std::string Model;
6068 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
6069 if (!TC.isThreadModelSupported(A->getValue()))
6070 D.Diag(diag::err_drv_invalid_thread_model_for_target)
6071 << A->getValue() << A->getAsString(Args);
6072 Model = A->getValue();
6073 } else
6074 Model = TC.getThreadModel();
6075 if (Model != "posix") {
6076 CmdArgs.push_back("-mthread-model");
6077 CmdArgs.push_back(Args.MakeArgString(Model));
6078 }
6079 }
6080
6081 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
6082 StringRef Name = A->getValue();
6083 if (Name == "SVML") {
6084 if (Triple.getArch() != llvm::Triple::x86 &&
6085 Triple.getArch() != llvm::Triple::x86_64)
6086 D.Diag(diag::err_drv_unsupported_opt_for_target)
6087 << Name << Triple.getArchName();
6088 } else if (Name == "AMDLIBM") {
6089 if (Triple.getArch() != llvm::Triple::x86 &&
6090 Triple.getArch() != llvm::Triple::x86_64)
6091 D.Diag(diag::err_drv_unsupported_opt_for_target)
6092 << Name << Triple.getArchName();
6093 } else if (Name == "libmvec") {
6094 if (Triple.getArch() != llvm::Triple::x86 &&
6095 Triple.getArch() != llvm::Triple::x86_64 &&
6096 Triple.getArch() != llvm::Triple::aarch64 &&
6097 Triple.getArch() != llvm::Triple::aarch64_be)
6098 D.Diag(diag::err_drv_unsupported_opt_for_target)
6099 << Name << Triple.getArchName();
6100 } else if (Name == "SLEEF" || Name == "ArmPL") {
6101 if (Triple.getArch() != llvm::Triple::aarch64 &&
6102 Triple.getArch() != llvm::Triple::aarch64_be && !Triple.isRISCV64())
6103 D.Diag(diag::err_drv_unsupported_opt_for_target)
6104 << Name << Triple.getArchName();
6105 }
6106 A->render(Args, CmdArgs);
6107 }
6108
6109 if (Args.hasFlag(options::OPT_fmerge_all_constants,
6110 options::OPT_fno_merge_all_constants, false))
6111 CmdArgs.push_back("-fmerge-all-constants");
6112
6113 Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
6114 options::OPT_fno_delete_null_pointer_checks);
6115
6116 Args.addOptOutFlag(CmdArgs, options::OPT_flifetime_dse,
6117 options::OPT_fno_lifetime_dse);
6118
6119 // LLVM Code Generator Options.
6120
6121 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
6122 if (!Triple.isOSAIX() || Triple.isPPC32())
6123 D.Diag(diag::err_drv_unsupported_opt_for_target)
6124 << A->getSpelling() << RawTriple.str();
6125 CmdArgs.push_back("-mabi=quadword-atomics");
6126 }
6127
6128 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
6129 // Emit the unsupported option error until the Clang's library integration
6130 // support for 128-bit long double is available for AIX.
6131 if (Triple.isOSAIX())
6132 D.Diag(diag::err_drv_unsupported_opt_for_target)
6133 << A->getSpelling() << RawTriple.str();
6134 }
6135
6136 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
6137 StringRef V = A->getValue(), V1 = V;
6138 unsigned Size;
6139 if (V1.consumeInteger(10, Size) || !V1.empty())
6140 D.Diag(diag::err_drv_invalid_argument_to_option)
6141 << V << A->getOption().getName();
6142 else
6143 CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
6144 }
6145
6146 Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
6147 options::OPT_fno_jump_tables);
6148 Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
6149 options::OPT_fno_profile_sample_accurate);
6150 Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
6151 options::OPT_fno_preserve_as_comments);
6152
6153 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
6154 CmdArgs.push_back("-mregparm");
6155 CmdArgs.push_back(A->getValue());
6156 }
6157
6158 if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
6159 options::OPT_msvr4_struct_return)) {
6160 if (!TC.getTriple().isPPC32()) {
6161 D.Diag(diag::err_drv_unsupported_opt_for_target)
6162 << A->getSpelling() << RawTriple.str();
6163 } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
6164 CmdArgs.push_back("-maix-struct-return");
6165 } else {
6166 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
6167 CmdArgs.push_back("-msvr4-struct-return");
6168 }
6169 }
6170
6171 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
6172 options::OPT_freg_struct_return)) {
6173 if (TC.getArch() != llvm::Triple::x86) {
6174 D.Diag(diag::err_drv_unsupported_opt_for_target)
6175 << A->getSpelling() << RawTriple.str();
6176 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
6177 CmdArgs.push_back("-fpcc-struct-return");
6178 } else {
6179 assert(A->getOption().matches(options::OPT_freg_struct_return));
6180 CmdArgs.push_back("-freg-struct-return");
6181 }
6182 }
6183
6184 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {
6185 if (Triple.getArch() == llvm::Triple::m68k)
6186 CmdArgs.push_back("-fdefault-calling-conv=rtdcall");
6187 else
6188 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
6189 }
6190
6191 if (Args.hasArg(options::OPT_fenable_matrix)) {
6192 // enable-matrix is needed by both the LangOpts and by LLVM.
6193 CmdArgs.push_back("-fenable-matrix");
6194 CmdArgs.push_back("-mllvm");
6195 CmdArgs.push_back("-enable-matrix");
6196 // Only handle default layout if matrix is enabled
6197 if (const Arg *A = Args.getLastArg(options::OPT_fmatrix_memory_layout_EQ)) {
6198 StringRef Val = A->getValue();
6199 if (Val == "row-major" || Val == "column-major") {
6200 CmdArgs.push_back(Args.MakeArgString("-fmatrix-memory-layout=" + Val));
6201 CmdArgs.push_back("-mllvm");
6202 CmdArgs.push_back(Args.MakeArgString("-matrix-default-layout=" + Val));
6203
6204 } else {
6205 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
6206 }
6207 }
6208 }
6209
6211 getFramePointerKind(Args, RawTriple);
6212 const char *FPKeepKindStr = nullptr;
6213 switch (FPKeepKind) {
6215 FPKeepKindStr = "-mframe-pointer=none";
6216 break;
6218 FPKeepKindStr = "-mframe-pointer=reserved";
6219 break;
6221 FPKeepKindStr = "-mframe-pointer=non-leaf-no-reserve";
6222 break;
6224 FPKeepKindStr = "-mframe-pointer=non-leaf";
6225 break;
6227 FPKeepKindStr = "-mframe-pointer=all";
6228 break;
6229 }
6230 assert(FPKeepKindStr && "unknown FramePointerKind");
6231 CmdArgs.push_back(FPKeepKindStr);
6232
6233 Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
6234 options::OPT_fno_zero_initialized_in_bss);
6235
6236 bool OFastEnabled = isOptimizationLevelFast(Args);
6237 if (Args.hasArg(options::OPT_Ofast))
6238 D.Diag(diag::warn_drv_deprecated_arg_ofast);
6239 // If -Ofast is the optimization level, then -fstrict-aliasing should be
6240 // enabled. This alias option is being used to simplify the hasFlag logic.
6241 OptSpecifier StrictAliasingAliasOption =
6242 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
6243 // We turn strict aliasing off by default if we're Windows MSVC since MSVC
6244 // doesn't do any TBAA.
6245 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
6246 options::OPT_fno_strict_aliasing,
6247 !IsWindowsMSVC && !IsUEFI))
6248 CmdArgs.push_back("-relaxed-aliasing");
6249 if (Args.hasFlag(options::OPT_fno_pointer_tbaa, options::OPT_fpointer_tbaa,
6250 false))
6251 CmdArgs.push_back("-no-pointer-tbaa");
6252 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
6253 options::OPT_fno_struct_path_tbaa, true))
6254 CmdArgs.push_back("-no-struct-path-tbaa");
6255
6256 if (Arg *A = Args.getLastArg(options::OPT_fstrict_bool,
6257 options::OPT_fno_strict_bool,
6258 options::OPT_fno_strict_bool_EQ)) {
6259 StringRef BFM = "";
6260 if (A->getOption().matches(options::OPT_fstrict_bool))
6261 BFM = "strict";
6262 else if (A->getOption().matches(options::OPT_fno_strict_bool))
6263 BFM = "nonstrict";
6264 else if (A->getValue() == StringRef("truncate"))
6265 BFM = "truncate";
6266 else if (A->getValue() == StringRef("nonzero"))
6267 BFM = "nonzero";
6268 else
6269 D.Diag(diag::err_drv_invalid_value)
6270 << A->getAsString(Args) << A->getValue();
6271 CmdArgs.push_back(Args.MakeArgString("-load-bool-from-mem=" + BFM));
6272 } else if (KernelOrKext) {
6273 // If unspecified, assume -fno-strict-bool=truncate in the Darwin kernel.
6274 CmdArgs.push_back("-load-bool-from-mem=truncate");
6275 }
6276
6277 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
6278 options::OPT_fno_strict_enums);
6279 Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
6280 options::OPT_fno_strict_return);
6281 Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
6282 options::OPT_fno_allow_editor_placeholders);
6283 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
6284 options::OPT_fno_strict_vtable_pointers);
6285 Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
6286 options::OPT_fno_force_emit_vtables);
6287 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
6288 options::OPT_fno_optimize_sibling_calls);
6289 Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
6290 options::OPT_fno_escaping_block_tail_calls);
6291
6292 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
6293 options::OPT_fno_fine_grained_bitfield_accesses);
6294
6295 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6296 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6297
6298 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6299 options::OPT_fno_experimental_omit_vtable_rtti);
6300
6301 Args.AddLastArg(CmdArgs, options::OPT_fdisable_block_signature_string,
6302 options::OPT_fno_disable_block_signature_string);
6303
6304 // Handle segmented stacks.
6305 Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
6306 options::OPT_fno_split_stack);
6307
6308 // -fprotect-parens=0 is default.
6309 if (Args.hasFlag(options::OPT_fprotect_parens,
6310 options::OPT_fno_protect_parens, false))
6311 CmdArgs.push_back("-fprotect-parens");
6312
6313 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
6314
6315 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_remote_memory,
6316 options::OPT_fno_atomic_remote_memory);
6317 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_fine_grained_memory,
6318 options::OPT_fno_atomic_fine_grained_memory);
6319 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_ignore_denormal_mode,
6320 options::OPT_fno_atomic_ignore_denormal_mode);
6321
6322 if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
6323 const llvm::Triple::ArchType Arch = TC.getArch();
6324 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
6325 StringRef V = A->getValue();
6326 if (V == "64")
6327 CmdArgs.push_back("-fextend-arguments=64");
6328 else if (V != "32")
6329 D.Diag(diag::err_drv_invalid_argument_to_option)
6330 << A->getValue() << A->getOption().getName();
6331 } else
6332 D.Diag(diag::err_drv_unsupported_opt_for_target)
6333 << A->getOption().getName() << TripleStr;
6334 }
6335
6336 if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
6337 if (TC.getArch() == llvm::Triple::avr)
6338 A->render(Args, CmdArgs);
6339 else
6340 D.Diag(diag::err_drv_unsupported_opt_for_target)
6341 << A->getAsString(Args) << TripleStr;
6342 }
6343
6344 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
6345 if (TC.getTriple().isX86())
6346 A->render(Args, CmdArgs);
6347 else if (TC.getTriple().isPPC() &&
6348 (A->getOption().getID() != options::OPT_mlong_double_80))
6349 A->render(Args, CmdArgs);
6350 else
6351 D.Diag(diag::err_drv_unsupported_opt_for_target)
6352 << A->getAsString(Args) << TripleStr;
6353 }
6354
6355 // Decide whether to use verbose asm. Verbose assembly is the default on
6356 // toolchains which have the integrated assembler on by default.
6357 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
6358 if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
6359 IsIntegratedAssemblerDefault))
6360 CmdArgs.push_back("-fno-verbose-asm");
6361
6362 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
6363 // use that to indicate the MC default in the backend.
6364 if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
6365 StringRef V = A->getValue();
6366 unsigned Num;
6367 if (V == "none")
6368 A->render(Args, CmdArgs);
6369 else if (!V.consumeInteger(10, Num) && Num > 0 &&
6370 (V.empty() || (V.consume_front(".") &&
6371 !V.consumeInteger(10, Num) && V.empty())))
6372 A->render(Args, CmdArgs);
6373 else
6374 D.Diag(diag::err_drv_invalid_argument_to_option)
6375 << A->getValue() << A->getOption().getName();
6376 }
6377
6378 // If toolchain choose to use MCAsmParser for inline asm don't pass the
6379 // option to disable integrated-as explicitly.
6381 CmdArgs.push_back("-no-integrated-as");
6382
6383 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
6384 CmdArgs.push_back("-mdebug-pass");
6385 CmdArgs.push_back("Structure");
6386 }
6387 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
6388 CmdArgs.push_back("-mdebug-pass");
6389 CmdArgs.push_back("Arguments");
6390 }
6391
6392 // Enable -mconstructor-aliases except on darwin, where we have to work around
6393 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
6394 // code, where aliases aren't supported.
6395 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
6396 CmdArgs.push_back("-mconstructor-aliases");
6397
6398 // Darwin's kernel doesn't support guard variables; just die if we
6399 // try to use them.
6400 if (KernelOrKext && RawTriple.isOSDarwin())
6401 CmdArgs.push_back("-fforbid-guard-variables");
6402
6403 if (Arg *A = Args.getLastArg(options::OPT_mms_bitfields,
6404 options::OPT_mno_ms_bitfields)) {
6405 if (A->getOption().matches(options::OPT_mms_bitfields))
6406 CmdArgs.push_back("-fms-layout-compatibility=microsoft");
6407 else
6408 CmdArgs.push_back("-fms-layout-compatibility=itanium");
6409 }
6410
6411 if (Triple.isOSCygMing()) {
6412 Args.addOptOutFlag(CmdArgs, options::OPT_fauto_import,
6413 options::OPT_fno_auto_import);
6414 }
6415
6416 if (Args.hasFlag(options::OPT_fms_volatile, options::OPT_fno_ms_volatile,
6417 Triple.isX86() && IsWindowsMSVC))
6418 CmdArgs.push_back("-fms-volatile");
6419
6420 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
6421 // defaults to -fno-direct-access-external-data. Pass the option if different
6422 // from the default.
6423 if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
6424 options::OPT_fno_direct_access_external_data)) {
6425 if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
6426 (PICLevel == 0))
6427 A->render(Args, CmdArgs);
6428 } else if (PICLevel == 0 && Triple.isLoongArch()) {
6429 // Some targets default to -fno-direct-access-external-data even for
6430 // -fno-pic.
6431 CmdArgs.push_back("-fno-direct-access-external-data");
6432 }
6433
6434 if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))
6435 Args.addOptOutFlag(CmdArgs, options::OPT_fplt, options::OPT_fno_plt);
6436
6437 // -fhosted is default.
6438 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
6439 // use Freestanding.
6440 bool Freestanding =
6441 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
6442 KernelOrKext;
6443 if (Freestanding)
6444 CmdArgs.push_back("-ffreestanding");
6445
6446 Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
6447
6449 auto SanitizeArgs =
6451 Args.AddLastArg(CmdArgs,
6452 options::OPT_fallow_runtime_check_skip_hot_cutoff_EQ);
6453
6454 // This is a coarse approximation of what llvm-gcc actually does, both
6455 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
6456 // complicated ways.
6457 bool IsAsyncUnwindTablesDefault =
6459 bool IsSyncUnwindTablesDefault =
6461
6462 bool AsyncUnwindTables = Args.hasFlag(
6463 options::OPT_fasynchronous_unwind_tables,
6464 options::OPT_fno_asynchronous_unwind_tables,
6465 (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
6466 !Freestanding);
6467 bool UnwindTables =
6468 Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
6469 IsSyncUnwindTablesDefault && !Freestanding);
6470 if (AsyncUnwindTables)
6471 CmdArgs.push_back("-funwind-tables=2");
6472 else if (UnwindTables)
6473 CmdArgs.push_back("-funwind-tables=1");
6474
6475 // Sframe unwind tables are independent of the other types. Although also
6476 // defined for aarch64, only x86_64 support is implemented at the moment.
6477 if (Arg *A = Args.getLastArg(options::OPT_gsframe)) {
6478 if (Triple.isOSBinFormatELF() && Triple.isX86())
6479 CmdArgs.push_back("--gsframe");
6480 else
6481 D.Diag(diag::err_drv_unsupported_opt_for_target)
6482 << A->getOption().getName() << TripleStr;
6483 }
6484
6485 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
6486 // `--gpu-use-aux-triple-only` is specified.
6487 if (AuxTriple && !Args.getLastArg(options::OPT_gpu_use_aux_triple_only)) {
6488 const ArgList &HostArgs =
6489 C.getArgsForToolChain(nullptr, BoundArch(), Action::OFK_None);
6490 std::string HostCPU = getCPUName(D, HostArgs, *AuxTriple, /*FromAs*/ false);
6491 if (!HostCPU.empty()) {
6492 CmdArgs.push_back("-aux-target-cpu");
6493 CmdArgs.push_back(Args.MakeArgString(HostCPU));
6494 }
6495 getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
6496 /*ForAS*/ false, /*IsAux*/ true);
6497 }
6498
6499 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingArch(),
6501
6502 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
6503
6504 if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
6505 StringRef Value = A->getValue();
6506 unsigned TLSSize = 0;
6507 Value.getAsInteger(10, TLSSize);
6508 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6509 D.Diag(diag::err_drv_unsupported_opt_for_target)
6510 << A->getOption().getName() << TripleStr;
6511 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6512 D.Diag(diag::err_drv_invalid_int_value)
6513 << A->getOption().getName() << Value;
6514 Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
6515 }
6516
6517 if (isTLSDESCEnabled(TC, Args))
6518 CmdArgs.push_back("-enable-tlsdesc");
6519
6520 // Add the target cpu
6521 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
6522 if (!CPU.empty()) {
6523 CmdArgs.push_back("-target-cpu");
6524 CmdArgs.push_back(Args.MakeArgString(CPU));
6525 }
6526
6527 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
6528
6529 // Add clang-cl arguments.
6530 types::ID InputType = Input.getType();
6531 if (D.IsCLMode())
6532 AddClangCLArgs(Args, InputType, CmdArgs);
6533
6534 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
6535 llvm::codegenoptions::NoDebugInfo;
6537 renderDebugOptions(TC, D, RawTriple, Args, InputType, CmdArgs, Output,
6538 DebugInfoKind, DwarfFission, IsUsingLTO);
6539
6540 // Add the split debug info name to the command lines here so we
6541 // can propagate it to the backend.
6542 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6543 (TC.getTriple().isOSBinFormatELF() ||
6544 TC.getTriple().isOSBinFormatWasm() ||
6545 TC.getTriple().isOSBinFormatCOFF()) &&
6548 if (SplitDWARF) {
6549 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
6550 CmdArgs.push_back("-split-dwarf-file");
6551 CmdArgs.push_back(SplitDWARFOut);
6552 if (DwarfFission == DwarfFissionKind::Split) {
6553 CmdArgs.push_back("-split-dwarf-output");
6554 CmdArgs.push_back(SplitDWARFOut);
6555 }
6556 }
6557
6558 // Pass the linker version in use.
6559 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6560 CmdArgs.push_back("-target-linker-version");
6561 CmdArgs.push_back(A->getValue());
6562 }
6563
6564 // Explicitly error on some things we know we don't support and can't just
6565 // ignore.
6566 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
6567 Arg *Unsupported;
6568 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
6569 TC.getArch() == llvm::Triple::x86) {
6570 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
6571 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
6572 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
6573 << Unsupported->getOption().getName();
6574 }
6575 // The faltivec option has been superseded by the maltivec option.
6576 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
6577 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6578 << Unsupported->getOption().getName()
6579 << "please use -maltivec and include altivec.h explicitly";
6580 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
6581 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6582 << Unsupported->getOption().getName() << "please use -mno-altivec";
6583 }
6584
6585 Args.AddAllArgs(CmdArgs, options::OPT_v);
6586
6587 if (Args.getLastArg(options::OPT_H)) {
6588 CmdArgs.push_back("-H");
6589 CmdArgs.push_back("-sys-header-deps");
6590 }
6591 Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
6592
6594 CmdArgs.push_back("-header-include-file");
6595 CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
6596 ? D.CCPrintHeadersFilename.c_str()
6597 : "-");
6598 CmdArgs.push_back("-sys-header-deps");
6599 CmdArgs.push_back(Args.MakeArgString(
6600 "-header-include-format=" +
6602 CmdArgs.push_back(Args.MakeArgString(
6603 "-header-include-filtering=" +
6605 }
6606 Args.AddLastArg(CmdArgs, options::OPT_P);
6607 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
6608
6609 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
6610 CmdArgs.push_back("-diagnostic-log-file");
6611 CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
6612 ? D.CCLogDiagnosticsFilename.c_str()
6613 : "-");
6614 }
6615
6616 // Give the gen diagnostics more chances to succeed, by avoiding intentional
6617 // crashes.
6618 if (D.CCGenDiagnostics)
6619 CmdArgs.push_back("-disable-pragma-debug-crash");
6620
6621 // Allow backend to put its diagnostic files in the same place as frontend
6622 // crash diagnostics files.
6623 if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
6624 StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
6625 CmdArgs.push_back("-mllvm");
6626 CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
6627 }
6628
6629 addSeparateSectionFlags(Triple, Args, CmdArgs);
6630
6631 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_address_map,
6632 options::OPT_fno_basic_block_address_map)) {
6633 if (((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) ||
6634 (Triple.isX86() && Triple.isOSBinFormatCOFF())) {
6635 if (A->getOption().matches(options::OPT_fbasic_block_address_map))
6636 A->render(Args, CmdArgs);
6637 } else {
6638 D.Diag(diag::err_drv_unsupported_opt_for_target)
6639 << A->getAsString(Args) << TripleStr;
6640 }
6641 }
6642
6643 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
6644 StringRef Val = A->getValue();
6645 if (Val == "labels") {
6646 D.Diag(diag::warn_drv_deprecated_arg)
6647 << A->getAsString(Args) << /*hasReplacement=*/true
6648 << "-fbasic-block-address-map";
6649 CmdArgs.push_back("-fbasic-block-address-map");
6650 } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {
6651 if (Val != "all" && Val != "none" && !Val.starts_with("list="))
6652 D.Diag(diag::err_drv_invalid_value)
6653 << A->getAsString(Args) << A->getValue();
6654 else
6655 A->render(Args, CmdArgs);
6656 } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
6657 // "all" is not supported on AArch64 since branch relaxation creates new
6658 // basic blocks for some cross-section branches.
6659 if (Val != "labels" && Val != "none" && !Val.starts_with("list="))
6660 D.Diag(diag::err_drv_invalid_value)
6661 << A->getAsString(Args) << A->getValue();
6662 else
6663 A->render(Args, CmdArgs);
6664 } else if (Triple.isNVPTX()) {
6665 // Do not pass the option to the GPU compilation. We still want it enabled
6666 // for the host-side compilation, so seeing it here is not an error.
6667 } else if (Val != "none") {
6668 // =none is allowed everywhere. It's useful for overriding the option
6669 // and is the same as not specifying the option.
6670 D.Diag(diag::err_drv_unsupported_opt_for_target)
6671 << A->getAsString(Args) << TripleStr;
6672 }
6673 }
6674
6675 Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
6676 options::OPT_fno_unique_section_names);
6677 Args.addOptInFlag(CmdArgs, options::OPT_fseparate_named_sections,
6678 options::OPT_fno_separate_named_sections);
6679 Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
6680 options::OPT_fno_unique_internal_linkage_names);
6681 Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
6682 options::OPT_fno_unique_basic_block_section_names);
6683
6684 addSplitMachineFunctionsArgs(D, Args, CmdArgs, Triple);
6685
6686 if (Arg *A =
6687 Args.getLastArg(options::OPT_fpartition_static_data_sections,
6688 options::OPT_fno_partition_static_data_sections)) {
6689 if (!A->getOption().matches(
6690 options::OPT_fno_partition_static_data_sections)) {
6691 // This codegen pass is only available on x86 and AArch64 ELF targets.
6692 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6693 A->render(Args, CmdArgs);
6694 CmdArgs.push_back("-mllvm");
6695 CmdArgs.push_back("-memprof-annotate-static-data-prefix");
6696 } else
6697 D.Diag(diag::err_drv_unsupported_opt_for_target)
6698 << A->getAsString(Args) << TripleStr;
6699 }
6700 }
6701
6702 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
6703 options::OPT_finstrument_functions_after_inlining,
6704 options::OPT_finstrument_function_entry_bare);
6705 Args.AddLastArg(CmdArgs, options::OPT_fconvergent_functions,
6706 options::OPT_fno_convergent_functions);
6707
6708 // NVPTX doesn't support PGO or coverage
6709 if (!Triple.isNVPTX())
6710 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanitizeArgs, CmdArgs);
6711
6712 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
6713
6714 if (getLastProfileSampleUseArg(Args) &&
6715 Args.hasFlag(options::OPT_fsample_profile_use_profi,
6716 options::OPT_fno_sample_profile_use_profi, true)) {
6717 CmdArgs.push_back("-mllvm");
6718 CmdArgs.push_back("-sample-profile-use-profi");
6719 }
6720
6721 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
6722 if (RawTriple.isPS() &&
6723 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
6724 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
6725 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
6726 }
6727
6728 // Pass options for controlling the default header search paths.
6729 if (Args.hasArg(options::OPT_nostdinc)) {
6730 CmdArgs.push_back("-nostdsysteminc");
6731 CmdArgs.push_back("-nobuiltininc");
6732 } else {
6733 if (Args.hasArg(options::OPT_nostdlibinc))
6734 CmdArgs.push_back("-nostdsysteminc");
6735 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
6736 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
6737 }
6738
6739 // Pass the path to compiler resource files.
6740 CmdArgs.push_back("-resource-dir");
6741 CmdArgs.push_back(D.ResourceDir.c_str());
6742
6743 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
6744
6745 // Add preprocessing options like -I, -D, etc. if we are using the
6746 // preprocessor.
6747 //
6748 // FIXME: Support -fpreprocessed
6750 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6751
6752 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6753 // that "The compiler can only warn and ignore the option if not recognized".
6754 // When building with ccache, it will pass -D options to clang even on
6755 // preprocessed inputs and configure concludes that -fPIC is not supported.
6756 Args.ClaimAllArgs(options::OPT_D);
6757
6758 // Warn about ignored options to clang.
6759 for (const Arg *A :
6760 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6761 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6762 A->claim();
6763 }
6764
6765 for (const Arg *A :
6766 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
6767 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
6768 A->claim();
6769 }
6770
6771 claimNoWarnArgs(Args);
6772
6773 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
6774
6775 for (const Arg *A :
6776 Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
6777 A->claim();
6778 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6779 unsigned WarningNumber;
6780 if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
6781 D.Diag(diag::err_drv_invalid_int_value)
6782 << A->getAsString(Args) << A->getValue();
6783 continue;
6784 }
6785
6786 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6787 CmdArgs.push_back(Args.MakeArgString(
6788 "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6789 }
6790 continue;
6791 }
6792 A->render(Args, CmdArgs);
6793 }
6794
6795 Args.AddAllArgs(CmdArgs, options::OPT_Wsystem_headers_in_module_EQ);
6796
6797 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
6798 CmdArgs.push_back("-pedantic");
6799 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
6800 Args.AddLastArg(CmdArgs, options::OPT_w);
6801
6802 Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
6803 options::OPT_fno_fixed_point);
6804
6805 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_overflow_behavior_types,
6806 options::OPT_fno_experimental_overflow_behavior_types);
6807
6808 if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
6809 A->render(Args, CmdArgs);
6810
6811 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6812 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6813
6814 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6815 options::OPT_fno_experimental_omit_vtable_rtti);
6816
6817 if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
6818 A->render(Args, CmdArgs);
6819
6820 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6821 // (-ansi is equivalent to -std=c89 or -std=c++98).
6822 //
6823 // If a std is supplied, only add -trigraphs if it follows the
6824 // option.
6825 bool ImplyVCPPCVer = false;
6826 bool ImplyVCPPCXXVer = false;
6827 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
6828 if (Std) {
6829 if (Std->getOption().matches(options::OPT_ansi))
6830 if (types::isCXX(InputType))
6831 CmdArgs.push_back("-std=c++98");
6832 else
6833 CmdArgs.push_back("-std=c89");
6834 else {
6835 if (IsSYCL) {
6836 const LangStandard *LangStd =
6837 LangStandard::getLangStandardForName(Std->getValue());
6838 if (LangStd) {
6839 // Use of -std= with 'C' is not supported for SYCL.
6840 if (LangStd->getLanguage() == Language::C)
6841 D.Diag(diag::err_drv_argument_not_allowed_with)
6842 << Std->getAsString(Args) << "-fsycl";
6843 // SYCL requires C++17 or later.
6844 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
6845 D.Diag(diag::err_drv_sycl_requires_cxx17) << Std->getAsString(Args);
6846 }
6847 }
6848 Std->render(Args, CmdArgs);
6849 }
6850
6851 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6852 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
6853 options::OPT_ftrigraphs,
6854 options::OPT_fno_trigraphs))
6855 if (A != Std)
6856 A->render(Args, CmdArgs);
6857 } else {
6858 // Honor -std-default.
6859 //
6860 // FIXME: Clang doesn't correctly handle -std= when the input language
6861 // doesn't match. For the time being just ignore this for C++ inputs;
6862 // eventually we want to do all the standard defaulting here instead of
6863 // splitting it between the driver and clang -cc1.
6864 if (!types::isCXX(InputType)) {
6865 if (!Args.hasArg(options::OPT__SLASH_std)) {
6866 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
6867 /*Joined=*/true);
6868 } else
6869 ImplyVCPPCVer = true;
6870 }
6871 else if (IsWindowsMSVC)
6872 ImplyVCPPCXXVer = true;
6873
6874 if (IsSYCL && types::isCXX(InputType) &&
6875 !Args.hasArg(options::OPT__SLASH_std) && !IsWindowsMSVC)
6876 // For SYCL, we default to -std=c++17 for all compilations. Use of -std
6877 // on the command line will override. On Windows MSVC, this is handled
6878 // by the ImplyVCPPCXXVer path below.
6879 CmdArgs.push_back("-std=c++17");
6880
6881 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
6882 options::OPT_fno_trigraphs);
6883 }
6884
6885 // GCC's behavior for -Wwrite-strings is a bit strange:
6886 // * In C, this "warning flag" changes the types of string literals from
6887 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6888 // for the discarded qualifier.
6889 // * In C++, this is just a normal warning flag.
6890 //
6891 // Implementing this warning correctly in C is hard, so we follow GCC's
6892 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6893 // a non-const char* in C, rather than using this crude hack.
6894 if (!types::isCXX(InputType)) {
6895 // FIXME: This should behave just like a warning flag, and thus should also
6896 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6897 Arg *WriteStrings =
6898 Args.getLastArg(options::OPT_Wwrite_strings,
6899 options::OPT_Wno_write_strings, options::OPT_w);
6900 if (WriteStrings &&
6901 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
6902 CmdArgs.push_back("-fconst-strings");
6903 }
6904
6905 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6906 // during C++ compilation, which it is by default. GCC keeps this define even
6907 // in the presence of '-w', match this behavior bug-for-bug.
6908 if (types::isCXX(InputType) &&
6909 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
6910 true)) {
6911 CmdArgs.push_back("-fdeprecated-macro");
6912 }
6913
6914 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6915 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
6916 if (Asm->getOption().matches(options::OPT_fasm))
6917 CmdArgs.push_back("-fgnu-keywords");
6918 else
6919 CmdArgs.push_back("-fno-gnu-keywords");
6920 }
6921
6922 if (!ShouldEnableAutolink(Args, TC, JA))
6923 CmdArgs.push_back("-fno-autolink");
6924
6925 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);
6926 Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);
6927 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);
6928 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);
6929
6930 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
6931
6932 if (CLANG_USE_EXPERIMENTAL_CONST_INTERP) {
6933 Args.ClaimAllArgs(options::OPT_fexperimental_new_constant_interpreter);
6934 Args.AddLastArg(CmdArgs,
6935 options::OPT_fno_experimental_new_constant_interpreter);
6936 } else {
6937 Args.ClaimAllArgs(options::OPT_fno_experimental_new_constant_interpreter);
6938 Args.AddLastArg(CmdArgs,
6939 options::OPT_fexperimental_new_constant_interpreter);
6940 }
6941
6942 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
6943 CmdArgs.push_back("-fbracket-depth");
6944 CmdArgs.push_back(A->getValue());
6945 }
6946
6947 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
6948 options::OPT_Wlarge_by_value_copy_def)) {
6949 if (A->getNumValues()) {
6950 StringRef bytes = A->getValue();
6951 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
6952 } else
6953 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
6954 }
6955
6956 if (Args.hasArg(options::OPT_relocatable_pch))
6957 CmdArgs.push_back("-relocatable-pch");
6958
6959 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
6960 static const char *kCFABIs[] = {
6961 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6962 };
6963
6964 if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
6965 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6966 else
6967 A->render(Args, CmdArgs);
6968 }
6969
6970 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
6971 CmdArgs.push_back("-fconstant-string-class");
6972 CmdArgs.push_back(A->getValue());
6973 }
6974
6975 if (Arg *A = Args.getLastArg(options::OPT_fconstant_array_class_EQ)) {
6976 CmdArgs.push_back("-fconstant-array-class");
6977 CmdArgs.push_back(A->getValue());
6978 }
6979 if (Arg *A = Args.getLastArg(options::OPT_fconstant_dictionary_class_EQ)) {
6980 CmdArgs.push_back("-fconstant-dictionary-class");
6981 CmdArgs.push_back(A->getValue());
6982 }
6983 if (Arg *A =
6984 Args.getLastArg(options::OPT_fconstant_integer_number_class_EQ)) {
6985 CmdArgs.push_back("-fconstant-integer-number-class");
6986 CmdArgs.push_back(A->getValue());
6987 }
6988 if (Arg *A = Args.getLastArg(options::OPT_fconstant_float_number_class_EQ)) {
6989 CmdArgs.push_back("-fconstant-float-number-class");
6990 CmdArgs.push_back(A->getValue());
6991 }
6992 if (Arg *A = Args.getLastArg(options::OPT_fconstant_double_number_class_EQ)) {
6993 CmdArgs.push_back("-fconstant-double-number-class");
6994 CmdArgs.push_back(A->getValue());
6995 }
6996
6997 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
6998 CmdArgs.push_back("-ftabstop");
6999 CmdArgs.push_back(A->getValue());
7000 }
7001
7002 if (Args.hasFlag(options::OPT_fexperimental_call_graph_section,
7003 options::OPT_fno_experimental_call_graph_section, false))
7004 CmdArgs.push_back("-fexperimental-call-graph-section");
7005
7006 Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
7007 options::OPT_fno_stack_size_section);
7008
7009 if (Args.hasArg(options::OPT_fstack_usage)) {
7010 CmdArgs.push_back("-stack-usage-file");
7011
7012 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
7013 SmallString<128> OutputFilename(OutputOpt->getValue());
7014 llvm::sys::path::replace_extension(OutputFilename, "su");
7015 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
7016 } else
7017 CmdArgs.push_back(
7018 Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
7019 }
7020
7021 CmdArgs.push_back("-ferror-limit");
7022 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
7023 CmdArgs.push_back(A->getValue());
7024 else
7025 CmdArgs.push_back("19");
7026
7027 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);
7028 Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
7029 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
7030 Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
7031 Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
7032
7033 // Pass -fmessage-length=.
7034 unsigned MessageLength = 0;
7035 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
7036 StringRef V(A->getValue());
7037 if (V.getAsInteger(0, MessageLength))
7038 D.Diag(diag::err_drv_invalid_argument_to_option)
7039 << V << A->getOption().getName();
7040 } else {
7041 // If -fmessage-length=N was not specified, determine whether this is a
7042 // terminal and, if so, implicitly define -fmessage-length appropriately.
7043 MessageLength = llvm::sys::Process::StandardErrColumns();
7044 }
7045 if (MessageLength != 0)
7046 CmdArgs.push_back(
7047 Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
7048
7049 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
7050 CmdArgs.push_back(
7051 Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
7052
7053 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
7054 CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
7055 Twine(A->getValue(0))));
7056
7057 // -fvisibility= and -fvisibility-ms-compat are of a piece.
7058 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
7059 options::OPT_fvisibility_ms_compat)) {
7060 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
7061 A->render(Args, CmdArgs);
7062 } else {
7063 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
7064 CmdArgs.push_back("-fvisibility=hidden");
7065 CmdArgs.push_back("-ftype-visibility=default");
7066 }
7067 } else if (IsOpenMPDevice) {
7068 // When compiling for the OpenMP device we want protected visibility by
7069 // default. This prevents the device from accidentally preempting code on
7070 // the host, makes the system more robust, and improves performance.
7071 CmdArgs.push_back("-fvisibility=protected");
7072 }
7073
7074 // PS4/PS5 process these options in addClangTargetOptions.
7075 if (!RawTriple.isPS()) {
7076 if (const Arg *A =
7077 Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
7078 options::OPT_fno_visibility_from_dllstorageclass)) {
7079 if (A->getOption().matches(
7080 options::OPT_fvisibility_from_dllstorageclass)) {
7081 CmdArgs.push_back("-fvisibility-from-dllstorageclass");
7082 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
7083 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
7084 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
7085 Args.AddLastArg(CmdArgs,
7086 options::OPT_fvisibility_externs_nodllstorageclass_EQ);
7087 }
7088 }
7089 }
7090
7091 if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
7092 options::OPT_fno_visibility_inlines_hidden, false))
7093 CmdArgs.push_back("-fvisibility-inlines-hidden");
7094
7095 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
7096 options::OPT_fno_visibility_inlines_hidden_static_local_var);
7097
7098 // -fvisibility-global-new-delete-hidden is a deprecated spelling of
7099 // -fvisibility-global-new-delete=force-hidden.
7100 if (const Arg *A =
7101 Args.getLastArg(options::OPT_fvisibility_global_new_delete_hidden)) {
7102 D.Diag(diag::warn_drv_deprecated_arg)
7103 << A->getAsString(Args) << /*hasReplacement=*/true
7104 << "-fvisibility-global-new-delete=force-hidden";
7105 }
7106
7107 if (const Arg *A =
7108 Args.getLastArg(options::OPT_fvisibility_global_new_delete_EQ,
7109 options::OPT_fvisibility_global_new_delete_hidden)) {
7110 if (A->getOption().matches(options::OPT_fvisibility_global_new_delete_EQ)) {
7111 A->render(Args, CmdArgs);
7112 } else {
7113 assert(A->getOption().matches(
7114 options::OPT_fvisibility_global_new_delete_hidden));
7115 CmdArgs.push_back("-fvisibility-global-new-delete=force-hidden");
7116 }
7117 }
7118
7119 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
7120
7121 if (Args.hasFlag(options::OPT_fnew_infallible,
7122 options::OPT_fno_new_infallible, false))
7123 CmdArgs.push_back("-fnew-infallible");
7124
7125 if (Args.hasFlag(options::OPT_fno_operator_names,
7126 options::OPT_foperator_names, false))
7127 CmdArgs.push_back("-fno-operator-names");
7128
7129 // Forward -f (flag) options which we can pass directly.
7130 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
7131 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
7132 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
7133 Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
7134 Args.AddLastArg(CmdArgs, options::OPT_fraw_string_literals,
7135 options::OPT_fno_raw_string_literals);
7136
7137 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
7138 Triple.hasDefaultEmulatedTLS()))
7139 CmdArgs.push_back("-femulated-tls");
7140
7141 Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,
7142 options::OPT_fno_check_new);
7143
7144 if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
7145 // FIXME: There's no reason for this to be restricted to some backend.
7146 // The backend code needs to be changed to include the appropriate function
7147 // calls automatically.
7148 if (!Triple.isX86() && !Triple.isAArch64() && !Triple.isRISCV())
7149 D.Diag(diag::err_drv_unsupported_opt_for_target)
7150 << A->getAsString(Args) << TripleStr;
7151 }
7152
7153 // AltiVec-like language extensions aren't relevant for assembling.
7154 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
7155 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
7156
7157 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
7158 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
7159
7160 // Forward flags for OpenMP. We don't do this if the current action is an
7161 // device offloading action other than OpenMP.
7162 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
7163 options::OPT_fno_openmp, false) &&
7164 !Args.hasFlag(options::OPT_foffload_via_llvm,
7165 options::OPT_fno_offload_via_llvm, false) &&
7168
7169 // Determine if target-fast optimizations should be enabled
7170 bool TargetFastUsed =
7171 Args.hasFlag(options::OPT_fopenmp_target_fast,
7172 options::OPT_fno_openmp_target_fast, OFastEnabled);
7173 switch (D.getOpenMPRuntime(Args)) {
7174 case Driver::OMPRT_OMP:
7176 // Clang can generate useful OpenMP code for these two runtime libraries.
7177 CmdArgs.push_back("-fopenmp");
7178
7179 // If no option regarding the use of TLS in OpenMP codegeneration is
7180 // given, decide a default based on the target. Otherwise rely on the
7181 // options and pass the right information to the frontend.
7182 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
7183 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
7184 CmdArgs.push_back("-fnoopenmp-use-tls");
7185 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
7186 options::OPT_fno_openmp_simd);
7187 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
7188 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
7189 if (!Args.hasFlag(options::OPT_fopenmp_extensions,
7190 options::OPT_fno_openmp_extensions, /*Default=*/true))
7191 CmdArgs.push_back("-fno-openmp-extensions");
7192 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
7193 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
7194 // '-fopenmp-cuda-teams-reduction-recs-num=' is deprecated and has no
7195 // effect: the teams reduction buffer is sized at kernel launch by the
7196 // offload plugin to match the actual number of teams. Honoring a
7197 // smaller user-supplied value would silently truncate the buffer for
7198 // larger launches.
7199 if (Arg *A = Args.getLastArg(
7200 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ))
7201 D.Diag(diag::warn_drv_deprecated_custom)
7202 << A->getAsString(Args)
7203 << "the value is ignored; the teams reduction buffer is sized "
7204 "automatically at kernel launch";
7205 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
7206 options::OPT_fno_openmp_optimistic_collapse,
7207 /*Default=*/false))
7208 CmdArgs.push_back("-fopenmp-optimistic-collapse");
7209
7210 // When in OpenMP offloading mode with NVPTX target, forward
7211 // cuda-mode flag
7212 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
7213 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
7214 CmdArgs.push_back("-fopenmp-cuda-mode");
7215
7216 // When in OpenMP offloading mode, enable debugging on the device.
7217 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
7218 if (Args.hasFlag(options::OPT_fopenmp_target_debug,
7219 options::OPT_fno_openmp_target_debug, /*Default=*/false))
7220 CmdArgs.push_back("-fopenmp-target-debug");
7221
7222 // When in OpenMP offloading mode, forward assumptions information about
7223 // thread and team counts in the device.
7224 if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
7225 options::OPT_fno_openmp_assume_teams_oversubscription,
7226 /*Default=*/TargetFastUsed))
7227 CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
7228 if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
7229 options::OPT_fno_openmp_assume_threads_oversubscription,
7230 /*Default=*/TargetFastUsed))
7231 CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
7232
7233 // Handle -fopenmp-assume-no-thread-state (implied by target-fast)
7234 if (Args.hasFlag(options::OPT_fopenmp_assume_no_thread_state,
7235 options::OPT_fno_openmp_assume_no_thread_state,
7236 /*Default=*/TargetFastUsed))
7237 CmdArgs.push_back("-fopenmp-assume-no-thread-state");
7238
7239 // Handle -fopenmp-assume-no-nested-parallelism (implied by target-fast)
7240 if (Args.hasFlag(options::OPT_fopenmp_assume_no_nested_parallelism,
7241 options::OPT_fno_openmp_assume_no_nested_parallelism,
7242 /*Default=*/TargetFastUsed))
7243 CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
7244
7245 // Handle -fopenmp-target-atomic-reduction.
7246 if (Args.hasFlag(options::OPT_fopenmp_target_atomic_reduction,
7247 options::OPT_fno_openmp_target_atomic_reduction,
7248 /*Default=*/false))
7249 CmdArgs.push_back("-fopenmp-target-atomic-reduction");
7250
7251 if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
7252 CmdArgs.push_back("-fopenmp-offload-mandatory");
7253 if (Args.hasArg(options::OPT_fopenmp_force_usm))
7254 CmdArgs.push_back("-fopenmp-force-usm");
7255 break;
7256 default:
7257 // By default, if Clang doesn't know how to generate useful OpenMP code
7258 // for a specific runtime library, we just don't pass the '-fopenmp' flag
7259 // down to the actual compilation.
7260 // FIXME: It would be better to have a mode which *only* omits IR
7261 // generation based on the OpenMP support so that we get consistent
7262 // semantic analysis, etc.
7263 break;
7264 }
7265 } else {
7266 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
7267 options::OPT_fno_openmp_simd);
7268 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
7269 Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
7270 options::OPT_fno_openmp_extensions);
7271 }
7272 // Forward '-foffload-via-llvm' to code generation to target the LLVM/Offload
7273 // runtime.
7274 if (Args.hasFlag(options::OPT_foffload_via_llvm,
7275 options::OPT_fno_offload_via_llvm, false))
7276 CmdArgs.push_back("-foffload-via-llvm");
7277
7278 const XRayArgs &XRay = TC.getXRayArgs(Args);
7279 XRay.addArgs(TC, Args, CmdArgs, InputType);
7280
7281 for (const auto &Filename :
7282 Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
7283 if (D.getVFS().exists(Filename))
7284 CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
7285 else
7286 D.Diag(clang::diag::err_drv_no_such_file) << Filename;
7287 }
7288
7289 if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
7290 StringRef S0 = A->getValue(), S = S0;
7291 unsigned Size, Offset = 0;
7292 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
7293 !Triple.isX86() && !Triple.isSystemZ() &&
7294 !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
7295 Triple.getArch() == llvm::Triple::ppc64 ||
7296 Triple.getArch() == llvm::Triple::ppc64le)))
7297 D.Diag(diag::err_drv_unsupported_opt_for_target)
7298 << A->getAsString(Args) << TripleStr;
7299 else if (S.consumeInteger(10, Size) ||
7300 (!S.empty() &&
7301 (!S.consume_front(",") || S.consumeInteger(10, Offset))) ||
7302 (!S.empty() && (!S.consume_front(",") || S.empty())))
7303 D.Diag(diag::err_drv_invalid_argument_to_option)
7304 << S0 << A->getOption().getName();
7305 else if (Size < Offset)
7306 D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
7307 else {
7308 CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
7309 CmdArgs.push_back(Args.MakeArgString(
7310 "-fpatchable-function-entry-offset=" + Twine(Offset)));
7311 if (!S.empty())
7312 CmdArgs.push_back(
7313 Args.MakeArgString("-fpatchable-function-entry-section=" + S));
7314 }
7315 }
7316
7317 Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
7318
7319 if (Args.hasArg(options::OPT_fms_secure_hotpatch_functions_file))
7320 Args.AddLastArg(CmdArgs, options::OPT_fms_secure_hotpatch_functions_file);
7321
7322 for (const auto &A :
7323 Args.getAllArgValues(options::OPT_fms_secure_hotpatch_functions_list))
7324 CmdArgs.push_back(
7325 Args.MakeArgString("-fms-secure-hotpatch-functions-list=" + Twine(A)));
7326
7327 if (TC.SupportsProfiling()) {
7328 Args.AddLastArg(CmdArgs, options::OPT_pg);
7329
7330 llvm::Triple::ArchType Arch = TC.getArch();
7331 if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
7332 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
7333 A->render(Args, CmdArgs);
7334 else
7335 D.Diag(diag::err_drv_unsupported_opt_for_target)
7336 << A->getAsString(Args) << TripleStr;
7337 }
7338 if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
7339 if (Arch == llvm::Triple::systemz ||
7340 (TC.getTriple().isX86() && TC.getTriple().isOSBinFormatELF()))
7341 A->render(Args, CmdArgs);
7342 else
7343 D.Diag(diag::err_drv_unsupported_opt_for_target)
7344 << A->getAsString(Args) << TripleStr;
7345 }
7346 if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
7347 if (Arch == llvm::Triple::systemz ||
7348 (TC.getTriple().isX86() && TC.getTriple().isOSBinFormatELF()))
7349 A->render(Args, CmdArgs);
7350 else
7351 D.Diag(diag::err_drv_unsupported_opt_for_target)
7352 << A->getAsString(Args) << TripleStr;
7353 }
7354 }
7355
7356 if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
7357 if (TC.getTriple().isOSzOS()) {
7358 D.Diag(diag::err_drv_unsupported_opt_for_target)
7359 << A->getAsString(Args) << TripleStr;
7360 }
7361 }
7362 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
7363 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
7364 D.Diag(diag::err_drv_unsupported_opt_for_target)
7365 << A->getAsString(Args) << TripleStr;
7366 }
7367 }
7368 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
7369 if (A->getOption().matches(options::OPT_p)) {
7370 A->claim();
7371 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))
7372 CmdArgs.push_back("-pg");
7373 }
7374 }
7375
7376 // Reject AIX-specific link options on other targets.
7377 if (!TC.getTriple().isOSAIX()) {
7378 for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,
7379 options::OPT_mxcoff_build_id_EQ)) {
7380 D.Diag(diag::err_drv_unsupported_opt_for_target)
7381 << A->getSpelling() << TripleStr;
7382 }
7383 }
7384
7385 if (Args.getLastArg(options::OPT_fapple_kext) ||
7386 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
7387 CmdArgs.push_back("-fapple-kext");
7388
7389 Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
7390 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
7391 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
7392 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
7393 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
7394 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
7395 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
7396 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_json);
7397 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
7398 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
7399 Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
7400
7401 if (const char *Name = C.getTimeTraceFile(&JA)) {
7402 CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
7403 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
7404 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_verbose);
7405 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_compress_EQ);
7406 }
7407
7408 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
7409 CmdArgs.push_back("-ftrapv-handler");
7410 CmdArgs.push_back(A->getValue());
7411 }
7412
7413 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
7414
7415 Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
7416 options::OPT_fno_finite_loops);
7417
7418 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
7419 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
7420 options::OPT_fno_unroll_loops);
7421 Args.AddLastArg(CmdArgs, options::OPT_floop_interchange,
7422 options::OPT_fno_loop_interchange);
7423 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_loop_fusion,
7424 options::OPT_fno_experimental_loop_fusion);
7425
7426 Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
7427
7428 Args.AddLastArg(CmdArgs, options::OPT_pthread);
7429
7430 Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
7431 options::OPT_mno_speculative_load_hardening);
7432
7433 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
7434 RenderSCPOptions(TC, Args, CmdArgs);
7435 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
7436
7437 Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
7438
7439 Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
7440 options::OPT_mno_stackrealign);
7441
7442 if (const Arg *A = Args.getLastArg(options::OPT_mstack_alignment)) {
7443 StringRef Value = A->getValue();
7444 int64_t Alignment = 0;
7445 if (Value.getAsInteger(10, Alignment) || Alignment < 0)
7446 D.Diag(diag::err_drv_invalid_argument_to_option)
7447 << Value << A->getOption().getName();
7448 else if (Alignment & (Alignment - 1))
7449 D.Diag(diag::err_drv_alignment_not_power_of_two)
7450 << A->getAsString(Args) << Value;
7451 else
7452 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + Value));
7453 }
7454
7455 if (Args.hasArg(options::OPT_mstack_probe_size)) {
7456 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
7457
7458 if (!Size.empty())
7459 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
7460 else
7461 CmdArgs.push_back("-mstack-probe-size=0");
7462 }
7463
7464 Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
7465 options::OPT_mno_stack_arg_probe);
7466
7467 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
7468 options::OPT_mno_restrict_it)) {
7469 if (A->getOption().matches(options::OPT_mrestrict_it)) {
7470 CmdArgs.push_back("-mllvm");
7471 CmdArgs.push_back("-arm-restrict-it");
7472 } else {
7473 CmdArgs.push_back("-mllvm");
7474 CmdArgs.push_back("-arm-default-it");
7475 }
7476 }
7477
7478 // Forward -cl options to -cc1
7479 RenderOpenCLOptions(Args, CmdArgs, InputType);
7480
7481 // Forward hlsl options to -cc1
7482 RenderHLSLOptions(D, Args, CmdArgs, InputType);
7483
7484 // Forward OpenACC options to -cc1
7485 RenderOpenACCOptions(D, Args, CmdArgs, InputType);
7486
7487 if (IsHIP) {
7488 if (Args.hasFlag(options::OPT_fhip_new_launch_api,
7489 options::OPT_fno_hip_new_launch_api, true))
7490 CmdArgs.push_back("-fhip-new-launch-api");
7491 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,
7492 options::OPT_fno_gpu_allow_device_init);
7493 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);
7494 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);
7495 Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
7496 options::OPT_fno_hip_kernel_arg_name);
7497 if (TC.getTriple().isSPIRV() &&
7498 TC.getTriple().getVendor() == llvm::Triple::VendorType::AMD)
7499 Args.addLastArg(CmdArgs, options::OPT_fenable_spirv_size_optimization);
7500 }
7501
7502 if ((IsCuda || IsHIP || IsSYCL) && IsRDCMode)
7503 CmdArgs.push_back("-fgpu-rdc");
7504
7505 if (IsCuda || IsHIP) {
7506 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_defer_diag,
7507 options::OPT_fno_gpu_defer_diag);
7508 if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
7509 options::OPT_fno_gpu_exclude_wrong_side_overloads,
7510 false)) {
7511 CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
7512 CmdArgs.push_back("-fgpu-defer-diag");
7513 }
7514 }
7515
7516 // Forward --no-offloadlib to -cc1.
7517 if (!Args.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib, true))
7518 CmdArgs.push_back("--no-offloadlib");
7519
7520 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
7521 CmdArgs.push_back(
7522 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
7523
7524 if (Arg *SA = Args.getLastArg(options::OPT_mcf_branch_label_scheme_EQ))
7525 CmdArgs.push_back(Args.MakeArgString(Twine("-mcf-branch-label-scheme=") +
7526 SA->getValue()));
7527 } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {
7528 // Emit IBT endbr64 instructions by default
7529 CmdArgs.push_back("-fcf-protection=branch");
7530 // jump-table can generate indirect jumps, which are not permitted
7531 CmdArgs.push_back("-fno-jump-tables");
7532 }
7533
7534 if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
7535 CmdArgs.push_back(
7536 Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
7537
7538 Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
7539
7540 // Forward -f options with positive and negative forms; we translate these by
7541 // hand. Do not propagate PGO options to the GPU-side compilations as the
7542 // profile info is for the host-side compilation only.
7543 if (!(IsCudaDevice || IsHIPDevice)) {
7544 if (Arg *A = getLastProfileSampleUseArg(Args)) {
7545 auto *PGOArg = Args.getLastArg(
7546 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
7547 options::OPT_fcs_profile_generate,
7548 options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
7549 options::OPT_fprofile_use_EQ);
7550 if (PGOArg)
7551 D.Diag(diag::err_drv_argument_not_allowed_with)
7552 << "SampleUse with PGO options";
7553
7554 StringRef fname = A->getValue();
7555 if (!llvm::sys::fs::exists(fname))
7556 D.Diag(diag::err_drv_no_such_file) << fname;
7557 else
7558 A->render(Args, CmdArgs);
7559 }
7560 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
7561
7562 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
7563 options::OPT_fno_pseudo_probe_for_profiling, false)) {
7564 CmdArgs.push_back("-fpseudo-probe-for-profiling");
7565 // Enforce -funique-internal-linkage-names if it's not explicitly turned
7566 // off.
7567 if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
7568 options::OPT_fno_unique_internal_linkage_names, true))
7569 CmdArgs.push_back("-funique-internal-linkage-names");
7570 }
7571 }
7572 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
7573
7574 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7575 options::OPT_fno_assume_sane_operator_new);
7576
7577 if (Args.hasFlag(options::OPT_fapinotes, options::OPT_fno_apinotes, false))
7578 CmdArgs.push_back("-fapinotes");
7579 if (Args.hasFlag(options::OPT_fapinotes_modules,
7580 options::OPT_fno_apinotes_modules, false))
7581 CmdArgs.push_back("-fapinotes-modules");
7582 Args.AddLastArg(CmdArgs, options::OPT_fapinotes_swift_version);
7583
7584 if (Args.hasFlag(options::OPT_fswift_version_independent_apinotes,
7585 options::OPT_fno_swift_version_independent_apinotes, false))
7586 CmdArgs.push_back("-fswift-version-independent-apinotes");
7587
7588 // -fblocks=0 is default.
7589 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
7590 TC.IsBlocksDefault()) ||
7591 (Args.hasArg(options::OPT_fgnu_runtime) &&
7592 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
7593 !Args.hasArg(options::OPT_fno_blocks))) {
7594 CmdArgs.push_back("-fblocks");
7595
7596 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
7597 CmdArgs.push_back("-fblocks-runtime-optional");
7598 }
7599
7600 // -fencode-extended-block-signature=1 is default.
7602 CmdArgs.push_back("-fencode-extended-block-signature");
7603
7604 if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
7605 options::OPT_fno_coro_aligned_allocation, false) &&
7606 types::isCXX(InputType))
7607 CmdArgs.push_back("-fcoro-aligned-allocation");
7608
7609 if (Args.hasFlag(options::OPT_fdefer_ts, options::OPT_fno_defer_ts,
7610 /*Default=*/false))
7611 CmdArgs.push_back("-fdefer-ts");
7612
7613 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
7614 options::OPT_fno_double_square_bracket_attributes);
7615
7616 Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
7617 options::OPT_fno_access_control);
7618 Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
7619 options::OPT_fno_elide_constructors);
7620
7621 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
7622
7623 if (KernelOrKext || (types::isCXX(InputType) &&
7624 (RTTIMode == ToolChain::RM_Disabled)))
7625 CmdArgs.push_back("-fno-rtti");
7626
7627 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
7628 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
7629 TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
7630 CmdArgs.push_back("-fshort-enums");
7631
7632 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
7633
7634 // -fuse-cxa-atexit is default.
7635 if (!Args.hasFlag(
7636 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
7637 !RawTriple.isOSAIX() &&
7638 (!RawTriple.isOSWindows() ||
7639 RawTriple.isWindowsCygwinEnvironment()) &&
7640 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
7641 RawTriple.hasEnvironment())) ||
7642 KernelOrKext)
7643 CmdArgs.push_back("-fno-use-cxa-atexit");
7644
7645 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
7646 options::OPT_fno_register_global_dtors_with_atexit,
7647 RawTriple.isOSDarwin() && !KernelOrKext))
7648 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
7649
7650 Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
7651 options::OPT_fno_use_line_directives);
7652
7653 // -fno-minimize-whitespace is default.
7654 if (Args.hasFlag(options::OPT_fminimize_whitespace,
7655 options::OPT_fno_minimize_whitespace, false)) {
7656 types::ID InputType = Inputs[0].getType();
7657 if (!isDerivedFromC(InputType))
7658 D.Diag(diag::err_drv_opt_unsupported_input_type)
7659 << "-fminimize-whitespace" << types::getTypeName(InputType);
7660 CmdArgs.push_back("-fminimize-whitespace");
7661 }
7662
7663 // -fno-keep-system-includes is default.
7664 if (Args.hasFlag(options::OPT_fkeep_system_includes,
7665 options::OPT_fno_keep_system_includes, false)) {
7666 types::ID InputType = Inputs[0].getType();
7667 if (!isDerivedFromC(InputType))
7668 D.Diag(diag::err_drv_opt_unsupported_input_type)
7669 << "-fkeep-system-includes" << types::getTypeName(InputType);
7670 CmdArgs.push_back("-fkeep-system-includes");
7671 }
7672
7673 // -fms-extensions=0 is default.
7674 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
7675 IsWindowsMSVC || IsUEFI))
7676 CmdArgs.push_back("-fms-extensions");
7677
7678 // -fms-compatibility=0 is default.
7679 bool IsMSVCCompat = Args.hasFlag(
7680 options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
7681 (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
7682 options::OPT_fno_ms_extensions, true)));
7683 if (IsMSVCCompat) {
7684 CmdArgs.push_back("-fms-compatibility");
7685 if (!types::isCXX(Input.getType()) &&
7686 Args.hasArg(options::OPT_fms_define_stdc))
7687 CmdArgs.push_back("-fms-define-stdc");
7688 }
7689
7690 // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both
7691 // clang and flang.
7692 renderCommonIntegerOverflowOptions(Args, CmdArgs, IsMSVCCompat);
7693
7694 // -fms-anonymous-structs is disabled by default.
7695 // Determine whether to enable Microsoft named anonymous struct/union support.
7696 // This implements "last flag wins" semantics for -fms-anonymous-structs,
7697 // where the feature can be:
7698 // - Explicitly enabled via -fms-anonymous-structs.
7699 // - Explicitly disabled via fno-ms-anonymous-structs
7700 // - Implicitly enabled via -fms-extensions or -fms-compatibility
7701 // - Implicitly disabled via -fno-ms-extensions or -fno-ms-compatibility
7702 //
7703 // When multiple relevent options are present, the last option on the command
7704 // line takes precedence. This allows users to selectively override implicit
7705 // enablement. Examples:
7706 // -fms-extensions -fno-ms-anonymous-structs -> disabled (explicit override)
7707 // -fno-ms-anonymous-structs -fms-extensions -> enabled (last flag wins)
7708 auto MSAnonymousStructsOptionToUseOrNull =
7709 [](const ArgList &Args) -> const char * {
7710 const char *Option = nullptr;
7711 constexpr const char *Enable = "-fms-anonymous-structs";
7712 constexpr const char *Disable = "-fno-ms-anonymous-structs";
7713
7714 // Iterate through all arguments in order to implement "last flag wins".
7715 for (const Arg *A : Args) {
7716 switch (A->getOption().getID()) {
7717 case options::OPT_fms_anonymous_structs:
7718 A->claim();
7719 Option = Enable;
7720 break;
7721 case options::OPT_fno_ms_anonymous_structs:
7722 A->claim();
7723 Option = Disable;
7724 break;
7725 // Each of -fms-extensions and -fms-compatibility implicitly enables the
7726 // feature.
7727 case options::OPT_fms_extensions:
7728 case options::OPT_fms_compatibility:
7729 Option = Enable;
7730 break;
7731 // Each of -fno-ms-extensions and -fno-ms-compatibility implicitly
7732 // disables the feature.
7733 case options::OPT_fno_ms_extensions:
7734 case options::OPT_fno_ms_compatibility:
7735 Option = Disable;
7736 break;
7737 default:
7738 break;
7739 }
7740 }
7741 return Option;
7742 };
7743
7744 // Only pass a flag to CC1 if a relevant option was seen
7745 if (auto MSAnonOpt = MSAnonymousStructsOptionToUseOrNull(Args))
7746 CmdArgs.push_back(MSAnonOpt);
7747
7748 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7749 Args.hasArg(options::OPT_fms_runtime_lib_EQ))
7750 ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
7751
7752 // Handle -fgcc-version, if present.
7753 VersionTuple GNUCVer;
7754 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
7755 // Check that the version has 1 to 3 components and the minor and patch
7756 // versions fit in two decimal digits.
7757 StringRef Val = A->getValue();
7758 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7759 bool Invalid = GNUCVer.tryParse(Val);
7760 unsigned Minor = GNUCVer.getMinor().value_or(0);
7761 unsigned Patch = GNUCVer.getSubminor().value_or(0);
7762 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7763 D.Diag(diag::err_drv_invalid_value)
7764 << A->getAsString(Args) << A->getValue();
7765 }
7766 } else if (!IsMSVCCompat) {
7767 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7768 GNUCVer = VersionTuple(4, 2, 1);
7769 }
7770 if (!GNUCVer.empty()) {
7771 CmdArgs.push_back(
7772 Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
7773 }
7774
7775 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
7776 if (!MSVT.empty())
7777 CmdArgs.push_back(
7778 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
7779
7780 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7781 if (ImplyVCPPCVer) {
7782 StringRef LanguageStandard;
7783 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7784 Std = StdArg;
7785 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7786 .Case("c11", "-std=c11")
7787 .Case("c17", "-std=c17")
7788 // If you add cases below for spellings that are
7789 // not in LangStandards.def, update
7790 // TransferableCommand::tryParseStdArg() in
7791 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7792 // to match.
7793 // TODO: add c23 when MSVC supports it.
7794 .Case("clatest", "-std=c23")
7795 .Default("");
7796 if (LanguageStandard.empty())
7797 D.Diag(clang::diag::warn_drv_unused_argument)
7798 << StdArg->getAsString(Args);
7799 }
7800 CmdArgs.push_back(LanguageStandard.data());
7801 }
7802 if (ImplyVCPPCXXVer) {
7803 StringRef LanguageStandard;
7804 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7805 Std = StdArg;
7806 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7807 .Case("c++14", "-std=c++14")
7808 .Case("c++17", "-std=c++17")
7809 .Case("c++20", "-std=c++20")
7810 .Case("c++23", "-std=c++23")
7811 // If you add cases below for spellings that are
7812 // not in LangStandards.def, update
7813 // TransferableCommand::tryParseStdArg() in
7814 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7815 // to match.
7816 // TODO add c++26, c++29 when MSVC supports
7817 // it.
7818 .Case("c++23preview", "-std=c++23")
7819 .Case("c++26preview", "-std=c++26")
7820 .Case("c++latest", "-std=c++2d")
7821 .Default("");
7822 if (IsSYCL) {
7823 const LangStandard *LangStd =
7824 LangStandard::getLangStandardForName(StdArg->getValue());
7825 if (LangStd) {
7826 // Use of /std: with 'C' is not supported for SYCL.
7827 if (LangStd->getLanguage() == Language::C)
7828 D.Diag(diag::err_drv_argument_not_allowed_with)
7829 << StdArg->getAsString(Args) << "-fsycl";
7830 // SYCL requires C++17 or later.
7831 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
7832 D.Diag(diag::err_drv_sycl_requires_cxx17)
7833 << StdArg->getAsString(Args);
7834 }
7835 }
7836 if (LanguageStandard.empty())
7837 D.Diag(clang::diag::warn_drv_unused_argument)
7838 << StdArg->getAsString(Args);
7839 }
7840
7841 if (LanguageStandard.empty()) {
7842 if (IsSYCL)
7843 // For SYCL, C++17 is the default.
7844 LanguageStandard = "-std=c++17";
7845 else if (IsMSVC2015Compatible)
7846 LanguageStandard = "-std=c++14";
7847 else
7848 LanguageStandard = "-std=c++11";
7849 }
7850
7851 CmdArgs.push_back(LanguageStandard.data());
7852 }
7853
7854 Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
7855 options::OPT_fno_borland_extensions);
7856
7857 // -fno-declspec is default, except for PS4/PS5.
7858 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
7859 RawTriple.isPS()))
7860 CmdArgs.push_back("-fdeclspec");
7861 else if (Args.hasArg(options::OPT_fno_declspec))
7862 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
7863
7864 // -fthreadsafe-static is default, except for MSVC compatibility versions less
7865 // than 19.
7866 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
7867 options::OPT_fno_threadsafe_statics,
7868 !types::isOpenCL(InputType) &&
7869 (!IsWindowsMSVC || IsMSVC2015Compatible)))
7870 CmdArgs.push_back("-fno-threadsafe-statics");
7871
7872 if (!Args.hasFlag(options::OPT_fms_tls_guards, options::OPT_fno_ms_tls_guards,
7873 true))
7874 CmdArgs.push_back("-fno-ms-tls-guards");
7875
7876 // Add -fno-assumptions, if it was specified.
7877 if (!Args.hasFlag(options::OPT_fassumptions, options::OPT_fno_assumptions,
7878 true))
7879 CmdArgs.push_back("-fno-assumptions");
7880
7881 // -fgnu-keywords default varies depending on language; only pass if
7882 // specified.
7883 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
7884 options::OPT_fno_gnu_keywords);
7885
7886 Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
7887 options::OPT_fno_gnu89_inline);
7888
7889 const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
7890 options::OPT_finline_hint_functions,
7891 options::OPT_fno_inline_functions);
7892 if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
7893 if (A->getOption().matches(options::OPT_fno_inline))
7894 A->render(Args, CmdArgs);
7895 } else if (InlineArg) {
7896 InlineArg->render(Args, CmdArgs);
7897 }
7898
7899 Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
7900
7901 // FIXME: Find a better way to determine whether we are in C++20.
7902 bool HaveCxx20 =
7903 Std &&
7904 (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
7905 Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
7906 Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
7907 Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
7908 Std->containsValue("c++23preview") || Std->containsValue("c++2c") ||
7909 Std->containsValue("gnu++2c") || Std->containsValue("c++26") ||
7910 Std->containsValue("gnu++26") || Std->containsValue("c++26preview") ||
7911 Std->containsValue("c++2d") || Std->containsValue("gnu++2d") ||
7912 Std->containsValue("c++latest") || Std->containsValue("gnu++latest"));
7913 bool HaveModules =
7914 RenderModulesOptions(C, D, Args, Input, Output, HaveCxx20, CmdArgs);
7915
7916 // -fdelayed-template-parsing is default when targeting MSVC.
7917 // Many old Windows SDK versions require this to parse.
7918 //
7919 // According to
7920 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
7921 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
7922 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
7923 // not enable -fdelayed-template-parsing by default after C++20.
7924 //
7925 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
7926 // able to disable this by default at some point.
7927 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
7928 options::OPT_fno_delayed_template_parsing,
7929 IsWindowsMSVC && !HaveCxx20)) {
7930 if (HaveCxx20)
7931 D.Diag(clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
7932
7933 CmdArgs.push_back("-fdelayed-template-parsing");
7934 }
7935
7936 if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
7937 options::OPT_fno_pch_validate_input_files_content, false))
7938 CmdArgs.push_back("-fvalidate-ast-input-files-content");
7939 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
7940 options::OPT_fno_pch_instantiate_templates, false))
7941 CmdArgs.push_back("-fpch-instantiate-templates");
7942 if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
7943 false))
7944 CmdArgs.push_back("-fmodules-codegen");
7945 if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
7946 false))
7947 CmdArgs.push_back("-fmodules-debuginfo");
7948
7949 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
7950 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
7951 Input, CmdArgs);
7952
7953 if (types::isObjC(Input.getType()) &&
7954 Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
7955 options::OPT_fno_objc_encode_cxx_class_template_spec,
7956 !Runtime.isNeXTFamily()))
7957 CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
7958
7959 if (Args.hasFlag(options::OPT_fapplication_extension,
7960 options::OPT_fno_application_extension, false))
7961 CmdArgs.push_back("-fapplication-extension");
7962
7963 // Handle GCC-style exception args.
7964 bool EH = false;
7965 if (!C.getDriver().IsCLMode())
7966 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext,
7967 IsDeviceOffloadAction, Runtime, CmdArgs);
7968
7969 // Handle exception personalities
7970 Arg *A = Args.getLastArg(
7971 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
7972 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions,
7973 options::OPT_femscripten_exceptions);
7974 if (A) {
7975 const Option &Opt = A->getOption();
7976 if (Opt.matches(options::OPT_fsjlj_exceptions))
7977 CmdArgs.push_back("-exception-model=sjlj");
7978 if (Opt.matches(options::OPT_fseh_exceptions))
7979 CmdArgs.push_back("-exception-model=seh");
7980 if (Opt.matches(options::OPT_fdwarf_exceptions))
7981 CmdArgs.push_back("-exception-model=dwarf");
7982 if (Opt.matches(options::OPT_fwasm_exceptions))
7983 CmdArgs.push_back("-exception-model=wasm");
7984 if (Opt.matches(options::OPT_femscripten_exceptions))
7985 CmdArgs.push_back("-exception-model=emscripten");
7986 } else {
7987 switch (TC.GetExceptionModel(Args)) {
7988 default:
7989 break;
7990 case llvm::ExceptionHandling::DwarfCFI:
7991 CmdArgs.push_back("-exception-model=dwarf");
7992 break;
7993 case llvm::ExceptionHandling::SjLj:
7994 CmdArgs.push_back("-exception-model=sjlj");
7995 break;
7996 case llvm::ExceptionHandling::WinEH:
7997 CmdArgs.push_back("-exception-model=seh");
7998 break;
7999 }
8000 }
8001
8002 // Unwind information version for x64 Windows.
8003 // Forward the new unified flag if present, otherwise translate legacy flags.
8004 if (const Arg *A = Args.getLastArg(options::OPT_winx64_eh_unwind_EQ)) {
8005 A->claim();
8006 CmdArgs.push_back(
8007 Args.MakeArgString(Twine("-fwinx64-eh-unwind=") + A->getValue()));
8008 } else if (const Arg *A =
8009 Args.getLastArg(options::OPT_winx64_eh_unwindv2_EQ)) {
8010 A->claim();
8011 StringRef Val = A->getValue();
8012 if (Val == "best-effort")
8013 CmdArgs.push_back("-fwinx64-eh-unwind=v2-best-effort");
8014 else if (Val == "required")
8015 CmdArgs.push_back("-fwinx64-eh-unwind=v2-required");
8016 // "disabled" maps to v1 default, nothing to forward.
8017 else if (Val != "disabled")
8018 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
8019 }
8020
8021 // Control Flow Guard mechanism for Windows.
8022 Args.AddLastArg(CmdArgs, options::OPT_win_cfg_mechanism);
8023
8024 // C++ "sane" operator new.
8025 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
8026 options::OPT_fno_assume_sane_operator_new);
8027
8028 // -fassume-unique-vtables is on by default.
8029 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
8030 options::OPT_fno_assume_unique_vtables);
8031
8032 // -fsized-deallocation is on by default in C++14 onwards and otherwise off
8033 // by default.
8034 Args.addLastArg(CmdArgs, options::OPT_fsized_deallocation,
8035 options::OPT_fno_sized_deallocation);
8036
8037 // -faligned-allocation is on by default in C++17 onwards and otherwise off
8038 // by default.
8039 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
8040 options::OPT_fno_aligned_allocation,
8041 options::OPT_faligned_new_EQ)) {
8042 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
8043 CmdArgs.push_back("-fno-aligned-allocation");
8044 else
8045 CmdArgs.push_back("-faligned-allocation");
8046 }
8047
8048 // The default new alignment can be specified using a dedicated option or via
8049 // a GCC-compatible option that also turns on aligned allocation.
8050 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
8051 options::OPT_faligned_new_EQ))
8052 CmdArgs.push_back(
8053 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
8054
8055 // -fconstant-cfstrings is default, and may be subject to argument translation
8056 // on Darwin.
8057 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
8058 options::OPT_fno_constant_cfstrings, true) ||
8059 !Args.hasFlag(options::OPT_mconstant_cfstrings,
8060 options::OPT_mno_constant_cfstrings, true))
8061 CmdArgs.push_back("-fno-constant-cfstrings");
8062
8063 Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
8064 options::OPT_fno_pascal_strings);
8065
8066 // Honor -fpack-struct= and -fpack-struct, if given. Note that
8067 // -fno-pack-struct doesn't apply to -fpack-struct=.
8068 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
8069 CmdArgs.push_back(
8070 Args.MakeArgString("-fpack-struct=" + Twine(A->getValue())));
8071 } else if (Args.hasFlag(options::OPT_fpack_struct,
8072 options::OPT_fno_pack_struct, false)) {
8073 CmdArgs.push_back("-fpack-struct=1");
8074 }
8075
8076 // Handle -fmax-type-align=N and -fno-type-align
8077 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
8078 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
8079 if (!SkipMaxTypeAlign) {
8080 std::string MaxTypeAlignStr = "-fmax-type-align=";
8081 MaxTypeAlignStr += A->getValue();
8082 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
8083 }
8084 } else if (RawTriple.isOSDarwin()) {
8085 if (!SkipMaxTypeAlign) {
8086 std::string MaxTypeAlignStr = "-fmax-type-align=16";
8087 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
8088 }
8089 }
8090
8091 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
8092 CmdArgs.push_back("-Qn");
8093
8094 // -fno-common is the default, set -fcommon only when that flag is set.
8095 Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
8096
8097 // -fsigned-bitfields is default, and clang doesn't yet support
8098 // -funsigned-bitfields.
8099 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
8100 options::OPT_funsigned_bitfields, true))
8101 D.Diag(diag::warn_drv_clang_unsupported)
8102 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
8103
8104 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
8105 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
8106 D.Diag(diag::err_drv_clang_unsupported)
8107 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
8108
8109 // -finput_charset=UTF-8 is default. Reject others
8110 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
8111 StringRef value = inputCharset->getValue();
8112 if (!value.equals_insensitive("utf-8"))
8113 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
8114 << value;
8115 }
8116
8117 // -fexec_charset=UTF-8 is default. Reject others
8118 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
8119 StringRef value = execCharset->getValue();
8120 if (!value.equals_insensitive("utf-8"))
8121 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
8122 << value;
8123 }
8124
8125 RenderDiagnosticsOptions(D, Args, CmdArgs);
8126
8127 Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
8128 options::OPT_fno_asm_blocks);
8129
8130 Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
8131 options::OPT_fno_gnu_inline_asm);
8132
8133 handleVectorizeLoopsArgs(Args, CmdArgs);
8134 handleVectorizeSLPArgs(Args, CmdArgs);
8135
8136 StringRef VecWidth = parseMPreferVectorWidthOption(D.getDiags(), Args);
8137 if (!VecWidth.empty())
8138 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + VecWidth));
8139
8140 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
8141 Args.AddLastArg(CmdArgs,
8142 options::OPT_fsanitize_undefined_strip_path_components_EQ);
8143
8144 // -fdollars-in-identifiers default varies depending on platform and
8145 // language; only pass if specified.
8146 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
8147 options::OPT_fno_dollars_in_identifiers)) {
8148 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
8149 CmdArgs.push_back("-fdollars-in-identifiers");
8150 else
8151 CmdArgs.push_back("-fno-dollars-in-identifiers");
8152 }
8153
8154 Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
8155 options::OPT_fno_apple_pragma_pack);
8156
8157 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
8158 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
8159 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
8160
8161 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
8162 options::OPT_fno_rewrite_imports, false);
8163 if (RewriteImports)
8164 CmdArgs.push_back("-frewrite-imports");
8165
8166 Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
8167 options::OPT_fno_directives_only);
8168
8169 // Enable rewrite includes if the user's asked for it or if we're generating
8170 // diagnostics.
8171 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
8172 // nice to enable this when doing a crashdump for modules as well.
8173 if (Args.hasFlag(options::OPT_frewrite_includes,
8174 options::OPT_fno_rewrite_includes, false) ||
8175 (C.isForDiagnostics() && !HaveModules))
8176 CmdArgs.push_back("-frewrite-includes");
8177
8178 if (Args.hasFlag(options::OPT_fzos_extensions,
8179 options::OPT_fno_zos_extensions, false))
8180 CmdArgs.push_back("-fzos-extensions");
8181 else if (Args.hasArg(options::OPT_fno_zos_extensions))
8182 CmdArgs.push_back("-fno-zos-extensions");
8183
8184 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
8185 if (Arg *A = Args.getLastArg(options::OPT_traditional,
8186 options::OPT_traditional_cpp)) {
8188 CmdArgs.push_back("-traditional-cpp");
8189 else
8190 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
8191 }
8192
8193 Args.AddLastArg(CmdArgs, options::OPT_dM);
8194 Args.AddLastArg(CmdArgs, options::OPT_dD);
8195 Args.AddLastArg(CmdArgs, options::OPT_dI);
8196
8197 Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
8198
8199 Args.AddLastArg(CmdArgs, options::OPT__ssaf_extract_summaries);
8200 Args.AddLastArg(CmdArgs, options::OPT__ssaf_tu_summary_file);
8201 Args.AddLastArg(CmdArgs, options::OPT__ssaf_compilation_unit_id);
8202 Args.AddLastArg(CmdArgs, options::OPT__ssaf_include_local_entities);
8203 Args.AddLastArg(CmdArgs, options::OPT__ssaf_no_extract_from_system_headers);
8204 Args.AddLastArg(CmdArgs, options::OPT__ssaf_source_transformation);
8205 Args.AddLastArg(CmdArgs, options::OPT__ssaf_global_scope_analysis_result);
8206 Args.AddLastArg(CmdArgs, options::OPT__ssaf_link_unit_id);
8207 Args.AddLastArg(CmdArgs, options::OPT__ssaf_src_edit_file);
8208 Args.AddLastArg(CmdArgs, options::OPT__ssaf_transformation_report_file);
8209
8210 // Handle serialized diagnostics.
8211 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
8212 CmdArgs.push_back("-serialize-diagnostic-file");
8213 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
8214 }
8215
8216 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
8217 CmdArgs.push_back("-fretain-comments-from-system-headers");
8218
8219 if (Arg *A = Args.getLastArg(options::OPT_fextend_variable_liveness_EQ)) {
8220 A->render(Args, CmdArgs);
8221 } else if (Arg *A = Args.getLastArg(options::OPT_O_Group);
8222 A && A->containsValue("g")) {
8223 // Set -fextend-variable-liveness=all by default at -Og.
8224 CmdArgs.push_back("-fextend-variable-liveness=all");
8225 }
8226
8227 // Forward -fcomment-block-commands to -cc1.
8228 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
8229 // Forward -fparse-all-comments to -cc1.
8230 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
8231 // Forward -fretain-comments to -cc1.
8232 Args.AddAllArgs(CmdArgs, options::OPT_fretain_comments);
8233
8234 // Turn -fplugin=name.so into -load name.so
8235 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
8236 CmdArgs.push_back("-load");
8237 CmdArgs.push_back(A->getValue());
8238 A->claim();
8239 }
8240
8241 // Turn -fplugin-arg-pluginname-key=value into
8242 // -plugin-arg-pluginname key=value
8243 // GCC has an actual plugin_argument struct with key/value pairs that it
8244 // passes to its plugins, but we don't, so just pass it on as-is.
8245 //
8246 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
8247 // argument key are allowed to contain dashes. GCC therefore only
8248 // allows dashes in the key. We do the same.
8249 for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
8250 auto ArgValue = StringRef(A->getValue());
8251 auto FirstDashIndex = ArgValue.find('-');
8252 StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
8253 StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
8254
8255 A->claim();
8256 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
8257 if (PluginName.empty()) {
8258 D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
8259 } else {
8260 D.Diag(diag::warn_drv_missing_plugin_arg)
8261 << PluginName << A->getAsString(Args);
8262 }
8263 continue;
8264 }
8265
8266 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
8267 CmdArgs.push_back(Args.MakeArgString(Arg));
8268 }
8269
8270 // Forward -fpass-plugin=name.so to -cc1.
8271 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
8272 CmdArgs.push_back(
8273 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
8274 A->claim();
8275 }
8276
8277 // Forward --vfsoverlay to -cc1.
8278 for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {
8279 CmdArgs.push_back("--vfsoverlay");
8280 CmdArgs.push_back(A->getValue());
8281 A->claim();
8282 }
8283
8284 Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,
8285 options::OPT_fno_safe_buffer_usage_suggestions);
8286
8287 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_late_parse_attributes,
8288 options::OPT_fno_experimental_late_parse_attributes);
8289
8290 if (Args.hasFlag(options::OPT_funique_source_file_names,
8291 options::OPT_fno_unique_source_file_names, false)) {
8292 if (Arg *A = Args.getLastArg(options::OPT_unique_source_file_identifier_EQ))
8293 A->render(Args, CmdArgs);
8294 else
8295 CmdArgs.push_back(Args.MakeArgString(
8296 Twine("-funique-source-file-identifier=") + Input.getBaseInput()));
8297 }
8298
8299 if (Args.hasFlag(
8300 options::OPT_fexperimental_allow_pointer_field_protection_attr,
8301 options::OPT_fno_experimental_allow_pointer_field_protection_attr,
8302 false) ||
8303 Args.hasFlag(options::OPT_fexperimental_pointer_field_protection_abi,
8304 options::OPT_fno_experimental_pointer_field_protection_abi,
8305 false))
8306 CmdArgs.push_back("-fexperimental-allow-pointer-field-protection-attr");
8307
8308 if (!IsCudaDevice) {
8309 Args.addOptInFlag(
8310 CmdArgs, options::OPT_fexperimental_pointer_field_protection_abi,
8311 options::OPT_fno_experimental_pointer_field_protection_abi);
8312 Args.addOptInFlag(
8313 CmdArgs, options::OPT_fexperimental_pointer_field_protection_tagged,
8314 options::OPT_fno_experimental_pointer_field_protection_tagged);
8315 }
8316
8317 // Setup statistics file output.
8318 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
8319 if (!StatsFile.empty()) {
8320 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
8322 CmdArgs.push_back("-stats-file-append");
8323 }
8324
8325 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
8326 // parser.
8327 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
8328 Arg->claim();
8329 // -finclude-default-header flag is for preprocessor,
8330 // do not pass it to other cc1 commands when save-temps is enabled
8331 if (C.getDriver().isSaveTempsEnabled() &&
8333 if (StringRef(Arg->getValue()) == "-finclude-default-header")
8334 continue;
8335 }
8336 CmdArgs.push_back(Arg->getValue());
8337 }
8338 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
8339 A->claim();
8340
8341 // We translate this by hand to the -cc1 argument, since nightly test uses
8342 // it and developers have been trained to spell it with -mllvm. Both
8343 // spellings are now deprecated and should be removed.
8344 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
8345 CmdArgs.push_back("-disable-llvm-optzns");
8346 } else {
8347 A->render(Args, CmdArgs);
8348 }
8349 }
8350
8351 // This needs to run after -Xclang argument forwarding to pick up the target
8352 // features enabled through -Xclang -target-feature flags.
8353 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
8354
8355 Args.AddLastArg(CmdArgs, options::OPT_falloc_token_max_EQ);
8356
8357#if CLANG_ENABLE_CIR
8358 // Forward -mmlir arguments to to the MLIR option parser.
8359 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
8360 A->claim();
8361 A->render(Args, CmdArgs);
8362 }
8363#endif // CLANG_ENABLE_CIR
8364
8365 // With -save-temps, we want to save the unoptimized bitcode output from the
8366 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
8367 // by the frontend.
8368 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
8369 // has slightly different breakdown between stages.
8370 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
8371 // pristine IR generated by the frontend. Ideally, a new compile action should
8372 // be added so both IR can be captured.
8373 if ((C.getDriver().isSaveTempsEnabled() ||
8375 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
8377 CmdArgs.push_back("-disable-llvm-passes");
8378
8379 Args.AddAllArgs(CmdArgs, options::OPT_undef);
8380
8381 const char *Exec = D.getDriverProgramPath();
8382
8383 // Optionally embed the -cc1 level arguments into the debug info or a
8384 // section, for build analysis.
8385 // Also record command line arguments into the debug info if
8386 // -grecord-gcc-switches options is set on.
8387 // By default, -gno-record-gcc-switches is set on and no recording.
8388 auto GRecordSwitches = false;
8389 auto FRecordSwitches = false;
8390 bool DXRecordSwitches = false;
8391 if (shouldRecordCommandLine(TC, Args, FRecordSwitches, GRecordSwitches,
8392 DXRecordSwitches)) {
8393 auto FlagsArgString = renderEscapedCommandLine(TC, Args);
8394 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
8395 CmdArgs.push_back("-dwarf-debug-flags");
8396 CmdArgs.push_back(FlagsArgString);
8397 }
8398 if (FRecordSwitches) {
8399 CmdArgs.push_back("-record-command-line");
8400 CmdArgs.push_back(FlagsArgString);
8401 }
8402 if (DXRecordSwitches) {
8403 CmdArgs.push_back("-fdx-record-command-line");
8404 CmdArgs.push_back(FlagsArgString);
8405 }
8406 }
8407
8408 // Host-side offloading compilation receives all device-side outputs. Include
8409 // them in the host compilation depending on the target.
8410 if (!HostOffloadingInputs.empty()) {
8411 bool UseOffloadIncludeBinary =
8412 (IsCuda || IsHIP) &&
8413 (!IsRDCMode || Args.hasArg(options::OPT_cuda_emit_nvcc_abi)) &&
8414 !UsesLLVMOffloading;
8415 UseOffloadIncludeBinary |= IsSYCL && !IsRDCMode;
8416 if (UseOffloadIncludeBinary) {
8417 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
8418 CmdArgs.push_back("-foffload-include-binary");
8419 CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
8420 } else {
8421 for (const InputInfo Input : HostOffloadingInputs)
8422 CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
8423 TC.getInputFilename(Input)));
8424 }
8425 }
8426
8427 if (IsCuda) {
8428 if (Args.hasArg(options::OPT_cuda_emit_nvcc_abi))
8429 CmdArgs.push_back("--cuda-emit-nvcc-abi");
8430 }
8431
8432 if (IsCuda || IsHIP) {
8433 // Determine the original source input.
8434 const Action *SourceAction = &JA;
8435 while (SourceAction->getKind() != Action::InputClass) {
8436 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
8437 SourceAction = SourceAction->getInputs()[0];
8438 }
8439 auto CUID = cast<InputAction>(SourceAction)->getId();
8440 if (!CUID.empty())
8441 CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
8442
8443 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
8444 // be overriden by -fno-gpu-approx-transcendentals.
8445 bool UseApproxTranscendentals = Args.hasFlag(
8446 options::OPT_ffast_math, options::OPT_fno_fast_math, false);
8447 if (Args.hasFlag(options::OPT_fgpu_approx_transcendentals,
8448 options::OPT_fno_gpu_approx_transcendentals,
8449 UseApproxTranscendentals))
8450 CmdArgs.push_back("-fgpu-approx-transcendentals");
8451 } else {
8452 Args.claimAllArgs(options::OPT_fgpu_approx_transcendentals,
8453 options::OPT_fno_gpu_approx_transcendentals);
8454 }
8455
8456 if (IsHIP) {
8457 CmdArgs.push_back("-fcuda-allow-variadic-functions");
8458 Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
8459 }
8460
8461 Args.AddAllArgs(CmdArgs,
8462 options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);
8463
8464 Args.AddLastArg(CmdArgs, options::OPT_foffload_uniform_block,
8465 options::OPT_fno_offload_uniform_block);
8466
8467 Args.AddLastArg(CmdArgs, options::OPT_foffload_implicit_host_device_templates,
8468 options::OPT_fno_offload_implicit_host_device_templates);
8469
8470 if (IsCudaDevice || IsHIPDevice) {
8471 StringRef InlineThresh =
8472 Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
8473 if (!InlineThresh.empty()) {
8474 std::string ArgStr =
8475 std::string("-inline-threshold=") + InlineThresh.str();
8476 CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
8477 }
8478 }
8479
8480 if (IsHIPDevice)
8481 Args.addOptOutFlag(CmdArgs,
8482 options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
8483 options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
8484
8485 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
8486 // to specify the result of the compile phase on the host, so the meaningful
8487 // device declarations can be identified. Also, -fopenmp-is-target-device is
8488 // passed along to tell the frontend that it is generating code for a device,
8489 // so that only the relevant declarations are emitted.
8490 if (IsOpenMPDevice) {
8491 CmdArgs.push_back("-fopenmp-is-target-device");
8492 // If we are offloading cuda/hip via llvm, it's also "cuda device code".
8493 if (Args.hasArg(options::OPT_foffload_via_llvm))
8494 CmdArgs.push_back("-fcuda-is-device");
8495
8496 if (OpenMPDeviceInput) {
8497 CmdArgs.push_back("-fopenmp-host-ir-file-path");
8498 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
8499 }
8500 }
8501
8502 if (Triple.isAMDGPU() ||
8503 (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD)) {
8504 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
8505
8506 Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
8507 options::OPT_mno_unsafe_fp_atomics);
8508 Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,
8509 options::OPT_mno_amdgpu_ieee);
8510 }
8511
8512 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
8513
8514 if (Args.hasFlag(options::OPT_fdevirtualize_speculatively,
8515 options::OPT_fno_devirtualize_speculatively,
8516 /*Default value*/ false))
8517 CmdArgs.push_back("-fdevirtualize-speculatively");
8518
8519 bool VirtualFunctionElimination =
8520 Args.hasFlag(options::OPT_fvirtual_function_elimination,
8521 options::OPT_fno_virtual_function_elimination, false);
8522 if (VirtualFunctionElimination) {
8523 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
8524 // in the future).
8525 if (LTOMode != LTOK_Full)
8526 D.Diag(diag::err_drv_argument_only_allowed_with)
8527 << "-fvirtual-function-elimination"
8528 << "-flto=full";
8529
8530 CmdArgs.push_back("-fvirtual-function-elimination");
8531 }
8532
8533 // VFE requires whole-program-vtables, and enables it by default.
8534 bool WholeProgramVTables = Args.hasFlag(
8535 options::OPT_fwhole_program_vtables,
8536 options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
8537 if (VirtualFunctionElimination && !WholeProgramVTables) {
8538 D.Diag(diag::err_drv_argument_not_allowed_with)
8539 << "-fno-whole-program-vtables"
8540 << "-fvirtual-function-elimination";
8541 }
8542
8543 if (WholeProgramVTables) {
8544 // PS4 uses the legacy LTO API, which does not support this feature in
8545 // ThinLTO mode.
8546 bool IsPS4 = getToolChain().getTriple().isPS4();
8547
8548 // Check if we passed LTO options but they were suppressed because this is a
8549 // device offloading action, or we passed device offload LTO options which
8550 // were suppressed because this is not the device offload action.
8551 // Check if we are using PS4 in regular LTO mode.
8552 // Otherwise, issue an error.
8553
8554 auto OtherLTOMode = TC.getLTOMode(
8555 Args, IsDeviceOffloadAction ? Action::OFK_None
8556 : static_cast<Action::OffloadKind>(
8557 C.getActiveOffloadKinds()));
8558 auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;
8559
8560 if ((!IsUsingLTO && !OtherIsUsingLTO) ||
8561 (IsPS4 && !UnifiedLTO && (TC.getLTOMode(Args) != LTOK_Full)))
8562 D.Diag(diag::err_drv_argument_only_allowed_with)
8563 << "-fwhole-program-vtables"
8564 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
8565
8566 // Propagate -fwhole-program-vtables if this is an LTO compile.
8567 if (IsUsingLTO)
8568 CmdArgs.push_back("-fwhole-program-vtables");
8569 }
8570
8571 bool DefaultsSplitLTOUnit =
8572 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
8573 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
8574 (!Triple.isPS4() && UnifiedLTO);
8575 bool SplitLTOUnit =
8576 Args.hasFlag(options::OPT_fsplit_lto_unit,
8577 options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
8578 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
8579 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
8580 << "-fsanitize=cfi";
8581 if (SplitLTOUnit)
8582 CmdArgs.push_back("-fsplit-lto-unit");
8583
8584 if (Arg *A = Args.getLastArg(options::OPT_ffat_lto_objects,
8585 options::OPT_fno_fat_lto_objects)) {
8586 if (IsUsingLTO && A->getOption().matches(options::OPT_ffat_lto_objects)) {
8587 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
8588 if (!Triple.isOSBinFormatELF() && !Triple.isOSBinFormatCOFF()) {
8589 D.Diag(diag::err_drv_unsupported_opt_for_target)
8590 << A->getAsString(Args) << TC.getTripleString();
8591 }
8592 CmdArgs.push_back(Args.MakeArgString(
8593 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
8594 CmdArgs.push_back("-flto-unit");
8595 CmdArgs.push_back("-ffat-lto-objects");
8596 A->render(Args, CmdArgs);
8597 }
8598 }
8599
8600 renderGlobalISelOptions(D, Args, CmdArgs, Triple);
8601
8602 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
8603 options::OPT_fno_force_enable_int128)) {
8604 if (A->getOption().matches(options::OPT_fforce_enable_int128))
8605 CmdArgs.push_back("-fforce-enable-int128");
8606 }
8607
8608 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
8609 options::OPT_fno_keep_static_consts);
8610 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,
8611 options::OPT_fno_keep_persistent_storage_variables);
8612 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_inline_functions,
8613 options::OPT_fno_keep_inline_functions);
8614 Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
8615 options::OPT_fno_complete_member_pointers);
8616 if (Arg *A = Args.getLastArg(options::OPT_cxx_static_destructors_EQ))
8617 A->render(Args, CmdArgs);
8618
8619 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
8620
8621 addOutlineAtomicsArgs(D, getToolChain(), Args, CmdArgs, Triple);
8622
8623 if (Triple.isAArch64() &&
8624 (Args.hasArg(options::OPT_mno_fmv) ||
8625 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
8626 // Disable Function Multiversioning on AArch64 target.
8627 CmdArgs.push_back("-target-feature");
8628 CmdArgs.push_back("-fmv");
8629 }
8630
8631 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
8632 (TC.getTriple().isOSBinFormatELF() ||
8633 TC.getTriple().isOSBinFormatCOFF()) &&
8634 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
8635 !TC.getTriple().isOSNetBSD() &&
8636 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
8637 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
8638 CmdArgs.push_back("-faddrsig");
8639
8640 const bool HasDefaultDwarf2CFIASM =
8641 (Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
8642 (EH || UnwindTables || AsyncUnwindTables ||
8643 DebugInfoKind != llvm::codegenoptions::NoDebugInfo);
8644 if (Args.hasFlag(options::OPT_fdwarf2_cfi_asm,
8645 options::OPT_fno_dwarf2_cfi_asm, HasDefaultDwarf2CFIASM))
8646 CmdArgs.push_back("-fdwarf2-cfi-asm");
8647
8648 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
8649 std::string Str = A->getAsString(Args);
8650 if (!TC.getTriple().isOSBinFormatELF())
8651 D.Diag(diag::err_drv_unsupported_opt_for_target)
8652 << Str << TC.getTripleString();
8653 CmdArgs.push_back(Args.MakeArgString(Str));
8654 }
8655
8656 // Add the "-o out -x type src.c" flags last. This is done primarily to make
8657 // the -cc1 command easier to edit when reproducing compiler crashes.
8658 if (Output.getType() == types::TY_Dependencies) {
8659 // Handled with other dependency code.
8660 } else if (Output.isFilename()) {
8661 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
8662 Output.getType() == clang::driver::types::TY_IFS) {
8663 SmallString<128> OutputFilename(Output.getFilename());
8664 llvm::sys::path::replace_extension(OutputFilename, "ifs");
8665 CmdArgs.push_back("-o");
8666 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
8667 } else {
8668 CmdArgs.push_back("-o");
8669 CmdArgs.push_back(Output.getFilename());
8670 }
8671 } else {
8672 assert(Output.isNothing() && "Invalid output.");
8673 }
8674
8675 addDashXForInput(Args, Input, CmdArgs);
8676
8677 ArrayRef<InputInfo> FrontendInputs = Input;
8678 if (IsExtractAPI)
8679 FrontendInputs = ExtractAPIInputs;
8680 else if (Input.isNothing())
8681 FrontendInputs = {};
8682
8683 for (const InputInfo &Input : FrontendInputs) {
8684 if (Input.isFilename())
8685 CmdArgs.push_back(Input.getFilename());
8686 else
8687 Input.getInputArg().renderAsInput(Args, CmdArgs);
8688 }
8689
8690 if (D.CC1Main && !D.CCGenDiagnostics) {
8691 // Invoke the CC1 directly in this process
8692 C.addCommand(std::make_unique<CC1Command>(
8693 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8694 Output, D.getPrependArg()));
8695 } else {
8696 C.addCommand(std::make_unique<Command>(
8697 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8698 Output, D.getPrependArg()));
8699 }
8700
8701 // Make the compile command echo its inputs for /showFilenames.
8702 if (Output.getType() == types::TY_Object &&
8703 Args.hasFlag(options::OPT__SLASH_showFilenames,
8704 options::OPT__SLASH_showFilenames_, false)) {
8705 C.getJobs().getJobs().back()->PrintInputFilenames = true;
8706 }
8707
8708 if (Arg *A = Args.getLastArg(options::OPT_pg))
8709 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
8710 !Args.hasArg(options::OPT_mfentry))
8711 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
8712 << A->getAsString(Args);
8713
8714 // Claim some arguments which clang supports automatically.
8715
8716 // -fpch-preprocess is used with gcc to add a special marker in the output to
8717 // include the PCH file.
8718 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
8719
8720 // Claim some arguments which clang doesn't support, but we don't
8721 // care to warn the user about.
8722 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
8723 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
8724
8725 // Disable warnings for clang -E -emit-llvm foo.c
8726 Args.ClaimAllArgs(options::OPT_emit_llvm);
8727}
8728
8729Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
8730 // CAUTION! The first constructor argument ("clang") is not arbitrary,
8731 // as it is for other tools. Some operations on a Tool actually test
8732 // whether that tool is Clang based on the Tool's Name as a string.
8733 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
8734
8736
8737/// Add options related to the Objective-C runtime/ABI.
8738///
8739/// Returns true if the runtime is non-fragile.
8740ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
8741 const InputInfoList &inputs,
8742 ArgStringList &cmdArgs,
8743 RewriteKind rewriteKind) const {
8744 // Look for the controlling runtime option.
8745 Arg *runtimeArg =
8746 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
8747 options::OPT_fobjc_runtime_EQ);
8748
8749 // Just forward -fobjc-runtime= to the frontend. This supercedes
8750 // options about fragility.
8751 if (runtimeArg &&
8752 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
8753 ObjCRuntime runtime;
8754 StringRef value = runtimeArg->getValue();
8755 if (runtime.tryParse(value)) {
8756 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
8757 << value;
8758 }
8759 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
8760 (runtime.getVersion() >= VersionTuple(2, 0)))
8761 if (!getToolChain().getTriple().isOSBinFormatELF() &&
8762 !getToolChain().getTriple().isOSBinFormatCOFF() &&
8763 !getToolChain().getTriple().isOSBinFormatWasm()) {
8765 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
8766 << runtime.getVersion().getMajor();
8767 }
8768
8769 runtimeArg->render(args, cmdArgs);
8770 return runtime;
8771 }
8772
8773 // Otherwise, we'll need the ABI "version". Version numbers are
8774 // slightly confusing for historical reasons:
8775 // 1 - Traditional "fragile" ABI
8776 // 2 - Non-fragile ABI, version 1
8777 // 3 - Non-fragile ABI, version 2
8778 unsigned objcABIVersion = 1;
8779 // If -fobjc-abi-version= is present, use that to set the version.
8780 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
8781 StringRef value = abiArg->getValue();
8782 if (value == "1")
8783 objcABIVersion = 1;
8784 else if (value == "2")
8785 objcABIVersion = 2;
8786 else if (value == "3")
8787 objcABIVersion = 3;
8788 else
8789 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
8790 } else {
8791 // Otherwise, determine if we are using the non-fragile ABI.
8792 bool nonFragileABIIsDefault =
8793 (rewriteKind == RK_NonFragile ||
8794 (rewriteKind == RK_None &&
8796 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
8797 options::OPT_fno_objc_nonfragile_abi,
8798 nonFragileABIIsDefault)) {
8799// Determine the non-fragile ABI version to use.
8800#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
8801 unsigned nonFragileABIVersion = 1;
8802#else
8803 unsigned nonFragileABIVersion = 2;
8804#endif
8805
8806 if (Arg *abiArg =
8807 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
8808 StringRef value = abiArg->getValue();
8809 if (value == "1")
8810 nonFragileABIVersion = 1;
8811 else if (value == "2")
8812 nonFragileABIVersion = 2;
8813 else
8814 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
8815 << value;
8816 }
8817
8818 objcABIVersion = 1 + nonFragileABIVersion;
8819 } else {
8820 objcABIVersion = 1;
8821 }
8822 }
8823
8824 // We don't actually care about the ABI version other than whether
8825 // it's non-fragile.
8826 bool isNonFragile = objcABIVersion != 1;
8827
8828 // If we have no runtime argument, ask the toolchain for its default runtime.
8829 // However, the rewriter only really supports the Mac runtime, so assume that.
8830 ObjCRuntime runtime;
8831 if (!runtimeArg) {
8832 switch (rewriteKind) {
8833 case RK_None:
8834 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8835 break;
8836 case RK_Fragile:
8837 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
8838 break;
8839 case RK_NonFragile:
8840 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8841 break;
8842 }
8843
8844 // -fnext-runtime
8845 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
8846 // On Darwin, make this use the default behavior for the toolchain.
8847 if (getToolChain().getTriple().isOSDarwin()) {
8848 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8849
8850 // Otherwise, build for a generic macosx port.
8851 } else {
8852 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8853 }
8854
8855 // -fgnu-runtime
8856 } else {
8857 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
8858 // Legacy behaviour is to target the gnustep runtime if we are in
8859 // non-fragile mode or the GCC runtime in fragile mode.
8860 if (isNonFragile)
8861 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
8862 else
8863 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
8864 }
8865
8866 if (llvm::any_of(inputs, [](const InputInfo &input) {
8867 return types::isObjC(input.getType());
8868 }))
8869 cmdArgs.push_back(
8870 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
8871 return runtime;
8872}
8873
8874static bool maybeConsumeDash(const std::string &EH, size_t &I) {
8875 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
8876 I += HaveDash;
8877 return !HaveDash;
8878}
8879
8880namespace {
8881struct EHFlags {
8882 bool Synch = false;
8883 bool Asynch = false;
8884 bool NoUnwindC = false;
8885};
8886} // end anonymous namespace
8887
8888/// /EH controls whether to run destructor cleanups when exceptions are
8889/// thrown. There are three modifiers:
8890/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
8891/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
8892/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
8893/// - c: Assume that extern "C" functions are implicitly nounwind.
8894/// The default is /EHs-c-, meaning cleanups are disabled.
8895static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
8896 bool isWindowsMSVC) {
8897 EHFlags EH;
8898
8899 std::vector<std::string> EHArgs =
8900 Args.getAllArgValues(options::OPT__SLASH_EH);
8901 for (const auto &EHVal : EHArgs) {
8902 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
8903 switch (EHVal[I]) {
8904 case 'a':
8905 EH.Asynch = maybeConsumeDash(EHVal, I);
8906 if (EH.Asynch) {
8907 // Async exceptions are Windows MSVC only.
8908 if (!isWindowsMSVC) {
8909 EH.Asynch = false;
8910 D.Diag(clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
8911 continue;
8912 }
8913 EH.Synch = false;
8914 }
8915 continue;
8916 case 'c':
8917 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
8918 continue;
8919 case 's':
8920 EH.Synch = maybeConsumeDash(EHVal, I);
8921 if (EH.Synch)
8922 EH.Asynch = false;
8923 continue;
8924 default:
8925 break;
8926 }
8927 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
8928 break;
8929 }
8930 }
8931 // The /GX, /GX- flags are only processed if there are not /EH flags.
8932 // The default is that /GX is not specified.
8933 if (EHArgs.empty() &&
8934 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
8935 /*Default=*/false)) {
8936 EH.Synch = true;
8937 EH.NoUnwindC = true;
8938 }
8939
8940 if (Args.hasArg(options::OPT__SLASH_kernel)) {
8941 EH.Synch = false;
8942 EH.NoUnwindC = false;
8943 EH.Asynch = false;
8944 }
8945
8946 return EH;
8947}
8948
8949void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
8950 ArgStringList &CmdArgs) const {
8951 bool isNVPTX = getToolChain().getTriple().isNVPTX();
8952
8953 ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
8954
8955 if (Arg *ShowIncludes =
8956 Args.getLastArg(options::OPT__SLASH_showIncludes,
8957 options::OPT__SLASH_showIncludes_user)) {
8958 CmdArgs.push_back("--show-includes");
8959 if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
8960 CmdArgs.push_back("-sys-header-deps");
8961 }
8962
8963 // This controls whether or not we emit RTTI data for polymorphic types.
8964 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
8965 /*Default=*/false))
8966 CmdArgs.push_back("-fno-rtti-data");
8967
8968 // This controls whether or not we emit stack-protector instrumentation.
8969 // In MSVC, Buffer Security Check (/GS) is on by default.
8970 if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
8971 /*Default=*/true)) {
8972 CmdArgs.push_back("-stack-protector");
8973 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
8974 }
8975
8976 const Driver &D = getToolChain().getDriver();
8977
8978 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
8979 EHFlags EH = parseClangCLEHFlags(D, Args, IsWindowsMSVC);
8980 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
8981 if (types::isCXX(InputType))
8982 CmdArgs.push_back("-fcxx-exceptions");
8983 CmdArgs.push_back("-fexceptions");
8984 if (EH.Asynch)
8985 CmdArgs.push_back("-fasync-exceptions");
8986 }
8987 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
8988 CmdArgs.push_back("-fexternc-nounwind");
8989
8990 // /EP should expand to -E -P.
8991 if (Args.hasArg(options::OPT__SLASH_EP)) {
8992 CmdArgs.push_back("-E");
8993 CmdArgs.push_back("-P");
8994 }
8995
8996 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
8997 options::OPT__SLASH_Zc_dllexportInlines,
8998 false)) {
8999 CmdArgs.push_back("-fno-dllexport-inlines");
9000 }
9001
9002 if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
9003 options::OPT__SLASH_Zc_wchar_t, false)) {
9004 CmdArgs.push_back("-fno-wchar");
9005 }
9006
9007 if (Args.hasArg(options::OPT__SLASH_kernel)) {
9008 llvm::Triple::ArchType Arch = getToolChain().getArch();
9009 std::vector<std::string> Values =
9010 Args.getAllArgValues(options::OPT__SLASH_arch);
9011 if (!Values.empty()) {
9012 llvm::SmallSet<std::string, 4> SupportedArches;
9013 if (Arch == llvm::Triple::x86)
9014 SupportedArches.insert("IA32");
9015
9016 for (auto &V : Values)
9017 if (!SupportedArches.contains(V))
9018 D.Diag(diag::err_drv_argument_not_allowed_with)
9019 << std::string("/arch:").append(V) << "/kernel";
9020 }
9021
9022 CmdArgs.push_back("-fno-rtti");
9023 if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
9024 D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
9025 << "/kernel";
9026 }
9027
9028 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_vlen,
9029 options::OPT__SLASH_vlen_EQ_256,
9030 options::OPT__SLASH_vlen_EQ_512)) {
9031 llvm::Triple::ArchType AT = getToolChain().getArch();
9032 StringRef Default = AT == llvm::Triple::x86 ? "IA32" : "SSE2";
9033 StringRef Arch = Args.getLastArgValue(options::OPT__SLASH_arch, Default);
9034 llvm::SmallSet<StringRef, 4> Arch512 = {"AVX512F", "AVX512", "AVX10.1",
9035 "AVX10.2"};
9036
9037 if (A->getOption().matches(options::OPT__SLASH_vlen_EQ_512)) {
9038 if (Arch512.contains(Arch))
9039 CmdArgs.push_back("-mprefer-vector-width=512");
9040 else
9041 D.Diag(diag::warn_drv_argument_not_allowed_with)
9042 << "/vlen=512" << std::string("/arch:").append(Arch);
9043 } else if (A->getOption().matches(options::OPT__SLASH_vlen_EQ_256)) {
9044 if (Arch512.contains(Arch))
9045 CmdArgs.push_back("-mprefer-vector-width=256");
9046 else if (Arch != "AVX" && Arch != "AVX2")
9047 D.Diag(diag::warn_drv_argument_not_allowed_with)
9048 << "/vlen=256" << std::string("/arch:").append(Arch);
9049 } else {
9050 if (Arch == "AVX10.1" || Arch == "AVX10.2")
9051 CmdArgs.push_back("-mprefer-vector-width=256");
9052 }
9053 } else {
9054 StringRef Arch = Args.getLastArgValue(options::OPT__SLASH_arch);
9055 if (Arch == "AVX10.1" || Arch == "AVX10.2") {
9056 CmdArgs.push_back("-mprefer-vector-width=256");
9057 CmdArgs.push_back("-target-feature");
9058 CmdArgs.push_back("-amx-tile");
9059 }
9060 if (Arch == "AVX10.2") {
9061 CmdArgs.push_back("-target-feature");
9062 CmdArgs.push_back("+avx10.2");
9063 }
9064 }
9065
9066 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
9067 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
9068 if (MostGeneralArg && BestCaseArg)
9069 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
9070 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
9071
9072 if (MostGeneralArg) {
9073 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
9074 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
9075 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
9076
9077 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
9078 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
9079 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
9080 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
9081 << FirstConflict->getAsString(Args)
9082 << SecondConflict->getAsString(Args);
9083
9084 if (SingleArg)
9085 CmdArgs.push_back("-fms-memptr-rep=single");
9086 else if (MultipleArg)
9087 CmdArgs.push_back("-fms-memptr-rep=multiple");
9088 else
9089 CmdArgs.push_back("-fms-memptr-rep=virtual");
9090 }
9091
9092 if (Args.hasArg(options::OPT_regcall4))
9093 CmdArgs.push_back("-regcall4");
9094
9095 // Parse the default calling convention options.
9096 if (Arg *CCArg =
9097 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
9098 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
9099 options::OPT__SLASH_Gregcall)) {
9100 unsigned DCCOptId = CCArg->getOption().getID();
9101 const char *DCCFlag = nullptr;
9102 bool ArchSupported = !isNVPTX;
9103 llvm::Triple::ArchType Arch = getToolChain().getArch();
9104 switch (DCCOptId) {
9105 case options::OPT__SLASH_Gd:
9106 DCCFlag = "-fdefault-calling-conv=cdecl";
9107 break;
9108 case options::OPT__SLASH_Gr:
9109 ArchSupported = Arch == llvm::Triple::x86;
9110 DCCFlag = "-fdefault-calling-conv=fastcall";
9111 break;
9112 case options::OPT__SLASH_Gz:
9113 ArchSupported = Arch == llvm::Triple::x86;
9114 DCCFlag = "-fdefault-calling-conv=stdcall";
9115 break;
9116 case options::OPT__SLASH_Gv:
9117 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
9118 DCCFlag = "-fdefault-calling-conv=vectorcall";
9119 break;
9120 case options::OPT__SLASH_Gregcall:
9121 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
9122 DCCFlag = "-fdefault-calling-conv=regcall";
9123 break;
9124 }
9125
9126 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
9127 if (ArchSupported && DCCFlag)
9128 CmdArgs.push_back(DCCFlag);
9129 }
9130
9131 if (Args.hasArg(options::OPT__SLASH_Gregcall4))
9132 CmdArgs.push_back("-regcall4");
9133
9134 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
9135
9136 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
9137 CmdArgs.push_back("-fdiagnostics-format");
9138 CmdArgs.push_back("msvc");
9139 }
9140
9141 if (Args.hasArg(options::OPT__SLASH_kernel))
9142 CmdArgs.push_back("-fms-kernel");
9143
9144 // Unwind v2 (epilog) information for x64 Windows. MSVC's behavior is not
9145 // order-dependent: /d2epilogunwindrequirev2 always wins over /d2epilogunwind.
9146 if (Args.hasArg(options::OPT__SLASH_d2epilogunwindrequirev2))
9147 CmdArgs.push_back("-fwinx64-eh-unwind=v2-required");
9148 else if (Args.hasArg(options::OPT__SLASH_d2epilogunwind))
9149 CmdArgs.push_back("-fwinx64-eh-unwind=v2-best-effort");
9150
9151 // Handle the various /guard options. We don't immediately push back clang
9152 // args since there are /d2 args that can modify the behavior of /guard:cf.
9153 bool HasCFGuard = false;
9154 bool HasCFGuardNoChecks = false;
9155 for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
9156 StringRef GuardArgs = A->getValue();
9157 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
9158 // "ehcont-".
9159 if (GuardArgs.equals_insensitive("cf")) {
9160 // Emit CFG instrumentation and the table of address-taken functions.
9161 HasCFGuard = true;
9162 HasCFGuardNoChecks = false;
9163 } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
9164 // Emit only the table of address-taken functions.
9165 HasCFGuard = false;
9166 HasCFGuardNoChecks = true;
9167 } else if (GuardArgs.equals_insensitive("ehcont")) {
9168 // Emit EH continuation table.
9169 CmdArgs.push_back("-ehcontguard");
9170 } else if (GuardArgs.equals_insensitive("cf-") ||
9171 GuardArgs.equals_insensitive("ehcont-")) {
9172 // Do nothing, but we might want to emit a security warning in future.
9173 } else {
9174 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
9175 }
9176 A->claim();
9177 }
9178
9179 // /d2guardnochecks downgrades /guard:cf to /guard:cf,nochecks (table only).
9180 // If CFG is not enabled, it is a no-op.
9181 if (Args.hasArg(options::OPT__SLASH_d2guardnochecks)) {
9182 if (HasCFGuard) {
9183 HasCFGuard = false;
9184 HasCFGuardNoChecks = true;
9185 }
9186 }
9187
9188 if (HasCFGuard)
9189 CmdArgs.push_back("-cfguard");
9190 else if (HasCFGuardNoChecks)
9191 CmdArgs.push_back("-cfguard-no-checks");
9192
9193 // Control Flow Guard mechanism for Windows.
9194 if (Args.hasArg(options::OPT__SLASH_d2guardcfgdispatch_))
9195 CmdArgs.push_back("-fwin-cfg-mechanism=check");
9196 else if (Args.hasArg(options::OPT__SLASH_d2guardcfgdispatch))
9197 CmdArgs.push_back("-fwin-cfg-mechanism=dispatch");
9198
9199 for (const auto &FuncOverride :
9200 Args.getAllArgValues(options::OPT__SLASH_funcoverride)) {
9201 CmdArgs.push_back(Args.MakeArgString(
9202 Twine("-loader-replaceable-function=") + FuncOverride));
9203 }
9204
9205 if (Args.hasArg(options::OPT__SLASH_experimental_deterministic)) {
9206 CmdArgs.push_back("-Wdate-time");
9207
9208 if (Args.hasArg(options::OPT_mincremental_linker_compatible)) {
9209 D.Diag(diag::err_drv_argument_not_allowed_with)
9210 << "/experimental:deterministic"
9211 << "/Brepro-";
9212 }
9213 // CL's sets COFF's OBJ timestamp to a hash of the source file path to get
9214 // deterministic result, but we force this timestamp to 0, which also
9215 // produces deterministic result.
9216 CmdArgs.push_back("-mno-incremental-linker-compatible");
9217 }
9218
9219 bool HasNoDateTime = Args.hasFlag(options::OPT__SLASH_d1nodatetime,
9220 options::OPT__SLASH_d1nodatetime_, false);
9221
9222 if (HasNoDateTime)
9223 CmdArgs.push_back("-init-datetime-macros=undefined");
9224
9225 // /Brepro is an alias for -mincremental-linker-compatible option.
9226 if (!Args.hasFlag(options::OPT_mincremental_linker_compatible,
9227 options::OPT_mno_incremental_linker_compatible,
9228 getToolChain()
9229 .getTriple()
9230 .isDefaultIncrementalLinkerCompatibleByDefault())) {
9231 // Redefine the date/time macros only if /d1nodatetime wasn't specified.
9232 // This option does not allow the user redefinitions for these macros.
9233 if (!HasNoDateTime)
9234 CmdArgs.push_back("-init-datetime-macros=literalone");
9235 }
9236}
9237
9238const char *Clang::getBaseInputName(const ArgList &Args,
9239 const InputInfo &Input) {
9240 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
9241}
9242
9243const char *Clang::getBaseInputStem(const ArgList &Args,
9244 const InputInfoList &Inputs) {
9245 const char *Str = getBaseInputName(Args, Inputs[0]);
9246
9247 if (const char *End = strrchr(Str, '.'))
9248 return Args.MakeArgString(std::string(Str, End));
9249
9250 return Str;
9251}
9252
9253const char *Clang::getDependencyFileName(const ArgList &Args,
9254 const InputInfoList &Inputs) {
9255 // FIXME: Think about this more.
9256
9257 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
9258 SmallString<128> OutputFilename(OutputOpt->getValue());
9259 llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
9260 return Args.MakeArgString(OutputFilename);
9261 }
9262
9263 return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
9264}
9265
9266// Begin ClangAs
9267
9268void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
9269 ArgStringList &CmdArgs) const {
9270 StringRef CPUName;
9271 StringRef ABIName;
9272 const llvm::Triple &Triple = getToolChain().getTriple();
9273 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
9274
9275 CmdArgs.push_back("-target-abi");
9276 CmdArgs.push_back(ABIName.data());
9277}
9278
9279void ClangAs::AddX86TargetArgs(const ArgList &Args,
9280 ArgStringList &CmdArgs) const {
9281 addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
9282 /*IsLTO=*/false);
9283
9284 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
9285 StringRef Value = A->getValue();
9286 if (Value == "intel" || Value == "att") {
9287 CmdArgs.push_back("-mllvm");
9288 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
9289 } else {
9290 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
9291 << A->getSpelling() << Value;
9292 }
9293 }
9294}
9295
9296void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
9297 ArgStringList &CmdArgs) const {
9298 CmdArgs.push_back("-target-abi");
9299 CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
9301 .data());
9302}
9303
9304void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
9305 ArgStringList &CmdArgs) const {
9306 const llvm::Triple &Triple = getToolChain().getTriple();
9307 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
9308
9309 CmdArgs.push_back("-target-abi");
9310 CmdArgs.push_back(ABIName.data());
9311
9312 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9313 options::OPT_mno_default_build_attributes, true)) {
9314 CmdArgs.push_back("-mllvm");
9315 CmdArgs.push_back("-riscv-add-build-attributes");
9316 }
9317}
9318
9320 const InputInfo &Output, const InputInfoList &Inputs,
9321 const ArgList &Args,
9322 const char *LinkingOutput) const {
9323 ArgStringList CmdArgs;
9324
9325 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
9326 const InputInfo &Input = Inputs[0];
9327
9328 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
9329 const std::string &TripleStr = Triple.getTriple();
9330 const auto &D = getToolChain().getDriver();
9331
9332 // Don't warn about "clang -w -c foo.s"
9333 Args.ClaimAllArgs(options::OPT_w);
9334 // and "clang -emit-llvm -c foo.s"
9335 Args.ClaimAllArgs(options::OPT_emit_llvm);
9336
9337 claimNoWarnArgs(Args);
9338
9339 // Invoke ourselves in -cc1as mode.
9340 //
9341 // FIXME: Implement custom jobs for internal actions.
9342 CmdArgs.push_back("-cc1as");
9343
9344 // Add the "effective" target triple.
9345 CmdArgs.push_back("-triple");
9346 CmdArgs.push_back(Args.MakeArgString(TripleStr));
9347
9349
9350 // Set the output mode, we currently only expect to be used as a real
9351 // assembler.
9352 CmdArgs.push_back("-filetype");
9353 CmdArgs.push_back("obj");
9354
9355 // Set the main file name, so that debug info works even with
9356 // -save-temps or preprocessed assembly.
9357 CmdArgs.push_back("-main-file-name");
9358 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
9359
9360 // Add the target cpu
9361 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
9362 if (!CPU.empty()) {
9363 CmdArgs.push_back("-target-cpu");
9364 CmdArgs.push_back(Args.MakeArgString(CPU));
9365 }
9366
9367 // Add the target features
9368 getTargetFeatures(D, Triple, Args, CmdArgs, true);
9369
9370 // Ignore explicit -force_cpusubtype_ALL option.
9371 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
9372
9373 // Pass along any -I options so we get proper .include search paths.
9374 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
9375
9376 // Pass along any --embed-dir or similar options so we get proper embed paths.
9377 Args.AddAllArgs(CmdArgs, options::OPT_embed_dir_EQ);
9378
9379 // Determine the original source input.
9380 auto FindSource = [](const Action *S) -> const Action * {
9381 while (S->getKind() != Action::InputClass) {
9382 assert(!S->getInputs().empty() && "unexpected root action!");
9383 S = S->getInputs()[0];
9384 }
9385 return S;
9386 };
9387 const Action *SourceAction = FindSource(&JA);
9388
9389 // Forward -g and handle debug info related flags, assuming we are dealing
9390 // with an actual assembly file.
9391 bool WantDebug = false;
9392 Args.ClaimAllArgs(options::OPT_g_Group);
9393 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9394 WantDebug = !A->getOption().matches(options::OPT_g0) &&
9395 !A->getOption().matches(options::OPT_ggdb0);
9396
9397 // If a -gdwarf argument appeared, remember it.
9398 bool EmitDwarf = false;
9399 if (const Arg *A = getDwarfNArg(Args))
9400 EmitDwarf = checkDebugInfoOption(A, Args, D, getToolChain());
9401
9402 bool EmitCodeView = false;
9403 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
9404 EmitCodeView = checkDebugInfoOption(A, Args, D, getToolChain());
9405
9406 // If the user asked for debug info but did not explicitly specify -gcodeview
9407 // or -gdwarf, ask the toolchain for the default format.
9408 if (!EmitCodeView && !EmitDwarf && WantDebug) {
9409 switch (getToolChain().getDefaultDebugFormat()) {
9410 case llvm::codegenoptions::DIF_CodeView:
9411 EmitCodeView = true;
9412 break;
9413 case llvm::codegenoptions::DIF_DWARF:
9414 EmitDwarf = true;
9415 break;
9416 }
9417 }
9418
9419 // If the arguments don't imply DWARF, don't emit any debug info here.
9420 if (!EmitDwarf)
9421 WantDebug = false;
9422
9423 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
9424 llvm::codegenoptions::NoDebugInfo;
9425
9426 // Add the -fdebug-compilation-dir flag if needed.
9427 const char *DebugCompilationDir =
9428 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
9429
9430 if (SourceAction->getType() == types::TY_Asm ||
9431 SourceAction->getType() == types::TY_PP_Asm) {
9432 // You might think that it would be ok to set DebugInfoKind outside of
9433 // the guard for source type, however there is a test which asserts
9434 // that some assembler invocation receives no -debug-info-kind,
9435 // and it's not clear whether that test is just overly restrictive.
9436 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
9437 : llvm::codegenoptions::NoDebugInfo);
9438
9439 addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
9440 CmdArgs);
9441
9442 // Set the AT_producer to the clang version when using the integrated
9443 // assembler on assembly source files.
9444 CmdArgs.push_back("-dwarf-debug-producer");
9445 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
9446
9447 // And pass along -I options
9448 Args.AddAllArgs(CmdArgs, options::OPT_I);
9449 }
9450 const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
9451 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
9452 llvm::DebuggerKind::Default);
9453 renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
9454 renderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
9455
9456 // Handle -fPIC et al -- the relocation-model affects the assembler
9457 // for some targets.
9458 llvm::Reloc::Model RelocationModel;
9459 unsigned PICLevel;
9460 bool IsPIE;
9461 std::tie(RelocationModel, PICLevel, IsPIE) =
9462 ParsePICArgs(getToolChain(), Args);
9463
9464 const char *RMName = RelocationModelName(RelocationModel);
9465 if (RMName) {
9466 CmdArgs.push_back("-mrelocation-model");
9467 CmdArgs.push_back(RMName);
9468 }
9469
9470 // Optionally embed the -cc1as level arguments into the debug info, for build
9471 // analysis.
9472 if (getToolChain().UseDwarfDebugFlags()) {
9473 ArgStringList OriginalArgs;
9474 for (const auto &Arg : Args)
9475 Arg->render(Args, OriginalArgs);
9476
9477 SmallString<256> Flags;
9478 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9479 escapeSpacesAndBackslashes(Exec, Flags);
9480 for (const char *OriginalArg : OriginalArgs) {
9481 SmallString<128> EscapedArg;
9482 escapeSpacesAndBackslashes(OriginalArg, EscapedArg);
9483 Flags += " ";
9484 Flags += EscapedArg;
9485 }
9486 CmdArgs.push_back("-dwarf-debug-flags");
9487 CmdArgs.push_back(Args.MakeArgString(Flags));
9488 }
9489
9490 // FIXME: Add -static support, once we have it.
9491
9492 // Add target specific flags.
9493 switch (getToolChain().getArch()) {
9494 default:
9495 break;
9496
9497 case llvm::Triple::mips:
9498 case llvm::Triple::mipsel:
9499 case llvm::Triple::mips64:
9500 case llvm::Triple::mips64el:
9501 AddMIPSTargetArgs(Args, CmdArgs);
9502 break;
9503
9504 case llvm::Triple::x86:
9505 case llvm::Triple::x86_64:
9506 AddX86TargetArgs(Args, CmdArgs);
9507 break;
9508
9509 case llvm::Triple::arm:
9510 case llvm::Triple::armeb:
9511 case llvm::Triple::thumb:
9512 case llvm::Triple::thumbeb:
9513 // This isn't in AddARMTargetArgs because we want to do this for assembly
9514 // only, not C/C++.
9515 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9516 options::OPT_mno_default_build_attributes, true)) {
9517 CmdArgs.push_back("-mllvm");
9518 CmdArgs.push_back("-arm-add-build-attributes");
9519 }
9520 break;
9521
9522 case llvm::Triple::aarch64:
9523 case llvm::Triple::aarch64_32:
9524 case llvm::Triple::aarch64_be:
9525 if (Args.hasArg(options::OPT_mmark_bti_property)) {
9526 CmdArgs.push_back("-mllvm");
9527 CmdArgs.push_back("-aarch64-mark-bti-property");
9528 }
9529 break;
9530
9531 case llvm::Triple::loongarch32:
9532 case llvm::Triple::loongarch64:
9533 AddLoongArchTargetArgs(Args, CmdArgs);
9534 break;
9535
9536 case llvm::Triple::riscv32:
9537 case llvm::Triple::riscv64:
9538 case llvm::Triple::riscv32be:
9539 case llvm::Triple::riscv64be:
9540 AddRISCVTargetArgs(Args, CmdArgs);
9541 break;
9542
9543 case llvm::Triple::hexagon:
9544 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9545 options::OPT_mno_default_build_attributes, true)) {
9546 CmdArgs.push_back("-mllvm");
9547 CmdArgs.push_back("-hexagon-add-build-attributes");
9548 }
9549 break;
9550 }
9551
9552 // Consume all the warning flags. Usually this would be handled more
9553 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
9554 // doesn't handle that so rather than warning about unused flags that are
9555 // actually used, we'll lie by omission instead.
9556 // FIXME: Stop lying and consume only the appropriate driver flags
9557 Args.ClaimAllArgs(options::OPT_W_Group);
9558
9559 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
9560 getToolChain().getDriver());
9561
9562 // Forward -Xclangas arguments to -cc1as
9563 for (auto Arg : Args.filtered(options::OPT_Xclangas)) {
9564 Arg->claim();
9565 CmdArgs.push_back(Arg->getValue());
9566 }
9567
9568 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
9569
9570 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
9571 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
9572 Output.getFilename());
9573
9574 // Fixup any previous commands that use -object-file-name because when we
9575 // generated them, the final .obj name wasn't yet known.
9576 for (Command &J : C.getJobs()) {
9577 if (SourceAction != FindSource(&J.getSource()))
9578 continue;
9579 auto &JArgs = J.getArguments();
9580 for (unsigned I = 0; I < JArgs.size(); ++I) {
9581 if (StringRef(JArgs[I]).starts_with("-object-file-name=") &&
9582 Output.isFilename()) {
9583 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
9584 addDebugObjectName(Args, NewArgs, DebugCompilationDir,
9585 Output.getFilename());
9586 NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
9587 J.replaceArguments(NewArgs);
9588 break;
9589 }
9590 }
9591 }
9592
9593 assert(Output.isFilename() && "Unexpected lipo output.");
9594 CmdArgs.push_back("-o");
9595 CmdArgs.push_back(Output.getFilename());
9596
9597 const llvm::Triple &T = getToolChain().getTriple();
9598 Arg *A;
9599 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
9600 T.isOSBinFormatELF()) {
9601 CmdArgs.push_back("-split-dwarf-output");
9602 CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
9603 }
9604
9605 if (Triple.isAMDGPU())
9606 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
9607
9608 assert(Input.isFilename() && "Invalid input.");
9609 CmdArgs.push_back(Input.getFilename());
9610
9611 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9612 if (D.CC1Main && !D.CCGenDiagnostics) {
9613 // Invoke cc1as directly in this process.
9614 C.addCommand(std::make_unique<CC1Command>(
9615 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
9616 Output, D.getPrependArg()));
9617 } else {
9618 C.addCommand(std::make_unique<Command>(
9619 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
9620 Output, D.getPrependArg()));
9621 }
9622}
9623
9624// Begin OffloadBundler
9626 const InputInfo &Output,
9627 const InputInfoList &Inputs,
9628 const llvm::opt::ArgList &TCArgs,
9629 const char *LinkingOutput) const {
9630 // The version with only one output is expected to refer to a bundling job.
9631 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
9632
9633 // The bundling command looks like this:
9634 // clang-offload-bundler -type=bc
9635 // -targets=host-triple,openmp-triple1,openmp-triple2
9636 // -output=output_file
9637 // -input=unbundle_file_host
9638 // -input=unbundle_file_tgt1
9639 // -input=unbundle_file_tgt2
9640
9641 ArgStringList CmdArgs;
9642
9643 // Get the type.
9644 CmdArgs.push_back(TCArgs.MakeArgString(
9645 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
9646
9647 assert(JA.getInputs().size() == Inputs.size() &&
9648 "Not have inputs for all dependence actions??");
9649
9650 // Get the targets.
9651 SmallString<128> Triples;
9652 Triples += "-targets=";
9653 for (unsigned I = 0; I < Inputs.size(); ++I) {
9654 if (I)
9655 Triples += ',';
9656
9657 // Find ToolChain for this input.
9659 const ToolChain *CurTC = &getToolChain();
9660 const Action *CurDep = JA.getInputs()[I];
9661
9662 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
9663 CurTC = nullptr;
9664 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, BoundArch BA) {
9665 assert(CurTC == nullptr && "Expected one dependence!");
9666 CurKind = A->getOffloadingDeviceKind();
9667 CurTC = TC;
9668 });
9669 }
9670 Triples += Action::GetOffloadKindName(CurKind);
9671 Triples += '-';
9672 Triples += llvm::Triple(CurTC->ComputeEffectiveClangTriple(
9673 TCArgs, CurDep->getOffloadingArch()))
9674 .normalize(llvm::Triple::CanonicalForm::FOUR_IDENT);
9675
9676 if ((CurKind != Action::OFK_Host) && !CurDep->getOffloadingArch().empty()) {
9677 Triples += '-';
9678 Triples += CurDep->getOffloadingArch().ArchName;
9679 }
9680 }
9681 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
9682
9683 // Get bundled file command.
9684 CmdArgs.push_back(
9685 TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
9686
9687 // Get unbundled files command.
9688 for (unsigned I = 0; I < Inputs.size(); ++I) {
9690 UB += "-input=";
9691
9692 // Find ToolChain for this input.
9693 const ToolChain *CurTC = &getToolChain();
9694 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
9695 CurTC = nullptr;
9696 OA->doOnEachDependence([&](Action *, const ToolChain *TC, BoundArch) {
9697 assert(CurTC == nullptr && "Expected one dependence!");
9698 CurTC = TC;
9699 });
9700 UB += C.addTempFile(
9701 C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
9702 } else {
9703 UB += CurTC->getInputFilename(Inputs[I]);
9704 }
9705 CmdArgs.push_back(TCArgs.MakeArgString(UB));
9706 }
9707 addOffloadCompressArgs(TCArgs, CmdArgs);
9708 // All the inputs are encoded as commands.
9709 C.addCommand(std::make_unique<Command>(
9710 JA, *this, ResponseFileSupport::None(),
9711 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9712 CmdArgs, ArrayRef<InputInfo>(), Output));
9713}
9714
9716 const InputInfo &Output,
9717 const InputInfoList &Inputs,
9718 const llvm::opt::ArgList &Args,
9719 const char *LinkingOutput) const {
9720 ArgStringList CmdArgs;
9721
9722 // Add the output file name.
9723 assert(Output.isFilename() && "Invalid output.");
9724 CmdArgs.push_back("-o");
9725 CmdArgs.push_back(Output.getFilename());
9726
9727 // Create the inputs to bundle the needed metadata.
9728 for (const InputInfo &Input : Inputs) {
9729 const Action *OffloadAction = Input.getAction();
9731 const ArgList &TCArgs =
9732 C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
9734 StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
9736 if (Arch.empty())
9737 Arch = BoundArch(TCArgs.getLastArgValue(options::OPT_march_EQ));
9738
9739 StringRef Kind =
9741
9742 ArgStringList Features;
9743 SmallVector<StringRef> FeatureArgs;
9744 getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
9745 false);
9746 llvm::copy_if(Features, std::back_inserter(FeatureArgs),
9747 [](StringRef Arg) { return !Arg.starts_with("-target"); });
9748
9749 // TODO: We need to pass in the full target-id and handle it properly in the
9750 // linker wrapper.
9752 "file=" + File.str(),
9753 "triple=" + TC->ComputeEffectiveClangTriple(TCArgs, Arch),
9754 "arch=" + (Arch.empty() ? "generic" : Arch.ArchName.str()),
9755 "kind=" + Kind.str(),
9756 };
9757
9759 for (StringRef Feature : FeatureArgs)
9760 Parts.emplace_back("feature=" + Feature.str());
9761
9762 CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
9763 }
9764
9765 C.addCommand(std::make_unique<Command>(
9767 Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9768 CmdArgs, Inputs, Output));
9769}
9770
9771// Options that need the profile compiler-rt library on the target toolchain.
9772// Coverage mapping flags require -fprofile-instr-generate, so they belong here
9773// too.
9774static bool requiresProfileRT(unsigned ID) {
9775 switch (ID) {
9776 case options::OPT_fprofile_generate:
9777 case options::OPT_fprofile_generate_EQ:
9778 case options::OPT_fprofile_instr_generate:
9779 case options::OPT_fprofile_instr_generate_EQ:
9780 case options::OPT_fcoverage_mapping:
9781 case options::OPT_fno_coverage_mapping:
9782 case options::OPT_fcoverage_compilation_dir_EQ:
9783 case options::OPT_ffile_compilation_dir_EQ:
9784 case options::OPT_fcoverage_prefix_map_EQ:
9785 return true;
9786 default:
9787 return false;
9788 }
9789}
9790
9791// Options that need the ubsan compiler-rt library on the target toolchain.
9792static bool requiresUBSanRT(unsigned ID) {
9793 switch (ID) {
9794 case options::OPT_fsanitize_EQ:
9795 case options::OPT_fno_sanitize_EQ:
9796 case options::OPT_fsanitize_minimal_runtime:
9797 case options::OPT_fno_sanitize_minimal_runtime:
9798 return true;
9799 default:
9800 return false;
9801 }
9802}
9803
9805 const InputInfo &Output,
9806 const InputInfoList &Inputs,
9807 const ArgList &Args,
9808 const char *LinkingOutput) const {
9809 using namespace options;
9810
9811 // A list of permitted options that will be forwarded to the embedded device
9812 // compilation job.
9813 const llvm::DenseSet<unsigned> CompilerOptions{
9814 OPT_v,
9815 OPT_hip_path_EQ,
9816 OPT_O_Group,
9817 OPT_g_Group,
9818 OPT_g_flags_Group,
9819 OPT_R_value_Group,
9820 OPT_R_Group,
9821 OPT_Xcuda_ptxas,
9822 OPT_ptxas_path_EQ,
9823 OPT_ftime_report,
9824 OPT_ftime_trace,
9825 OPT_ftime_trace_EQ,
9826 OPT_ftime_trace_granularity_EQ,
9827 OPT_ftime_trace_verbose,
9828 OPT_ftime_trace_compress_EQ,
9829 OPT_opt_record_file,
9830 OPT_opt_record_format,
9831 OPT_opt_record_passes,
9832 OPT_fsave_optimization_record,
9833 OPT_fsave_optimization_record_EQ,
9834 OPT_fno_save_optimization_record,
9835 OPT_foptimization_record_file_EQ,
9836 OPT_foptimization_record_passes_EQ,
9837 OPT_save_temps,
9838 OPT_save_temps_EQ,
9839 OPT_mcode_object_version_EQ,
9840 OPT_load,
9841 OPT_no_canonical_prefixes,
9842 OPT_fno_lto,
9843 OPT_flto,
9844 OPT_flto_partitions_EQ,
9845 OPT_flto_EQ,
9846 OPT_hipspv_pass_plugin_EQ,
9847 OPT_use_spirv_backend,
9848 OPT_no_use_spirv_backend,
9849 OPT_fmultilib_flag,
9850 OPT_fprofile_generate,
9851 OPT_fprofile_generate_EQ,
9852 OPT_fprofile_instr_generate,
9853 OPT_fprofile_instr_generate_EQ,
9854 OPT_fcoverage_mapping,
9855 OPT_fno_coverage_mapping,
9856 OPT_fcoverage_compilation_dir_EQ,
9857 OPT_ffile_compilation_dir_EQ,
9858 OPT_fcoverage_prefix_map_EQ,
9859 OPT_fsanitize_EQ,
9860 OPT_fno_sanitize_EQ,
9861 OPT_fsanitize_minimal_runtime,
9862 OPT_fno_sanitize_minimal_runtime,
9863 OPT_fsanitize_trap_EQ,
9864 OPT_fno_sanitize_trap_EQ,
9865 OPT_fslp_vectorize,
9866 OPT_fno_slp_vectorize,
9867 OPT_hipstdpar,
9868 OPT_fenable_spirv_size_optimization};
9869 const llvm::DenseSet<unsigned> LinkerOptions{OPT_mllvm, OPT_Zlinker_input};
9870 // Suppress verbose output for HIP non-RDC fat binaries because it confuses
9871 // CMake implicit linker argument parsing.
9872 bool SuppressHIPNoRDCVerbose =
9873 JA.getType() == types::TY_HIP_FATBIN &&
9874 !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
9875 auto ToolChainHasRT = [&](const ToolChain &TC, StringRef Name) {
9876 return TC.getVFS().exists(
9877 TC.getCompilerRT(Args, Name, ToolChain::FT_Static));
9878 };
9879 auto ShouldForwardForToolChain = [&](Arg *A, const ToolChain &TC) {
9880 unsigned ID = A->getOption().getID();
9881 // Don't forward profiling arguments if the toolchain doesn't support it.
9882 // Without this check using it on the host would result in linker errors.
9883 // Coverage mapping flags require -fprofile-instr-generate, so drop them
9884 // together to avoid a device cc1 diagnostic.
9885 if (requiresProfileRT(ID) && !ToolChainHasRT(TC, "profile"))
9886 return false;
9887 // Don't forward sanitizer arguments if the toolchain doesn't support it.
9888 // Without this check using it on the host would result in linker errors.
9889 if (requiresUBSanRT(ID) && !ToolChainHasRT(TC, "ubsan_minimal") &&
9890 !ToolChainHasRT(TC, "ubsan_standalone"))
9891 return false;
9892 // Don't forward -mllvm to toolchains that don't support LLVM.
9893 return TC.HasNativeLLVMSupport() || ID != OPT_mllvm;
9894 };
9895 auto ShouldForward = [&](const llvm::DenseSet<unsigned> &Set, Arg *A,
9896 const ToolChain &TC) {
9897 if (A->getOption().matches(OPT_v) && SuppressHIPNoRDCVerbose)
9898 return false;
9899 return (Set.contains(A->getOption().getID()) ||
9900 (A->getOption().getGroup().isValid() &&
9901 Set.contains(A->getOption().getGroup().getID()))) &&
9902 ShouldForwardForToolChain(A, TC);
9903 };
9904
9905 ArgStringList CmdArgs;
9908 auto TCRange = C.getOffloadToolChains(Kind);
9909 for (auto &I : llvm::make_range(TCRange)) {
9910 const ToolChain *TC = I.second;
9911
9912 // We do not use a bound architecture here so options passed only to a
9913 // specific architecture via -Xarch_<cpu> will not be forwarded.
9914 ArgStringList CompilerArgs;
9915 ArgStringList LinkerArgs;
9916 const DerivedArgList &ToolChainArgs =
9917 C.getArgsForToolChain(TC, /*BA=*/{}, Kind);
9918 for (Arg *A : ToolChainArgs) {
9919 if (A->getOption().matches(OPT_Zlinker_input))
9920 LinkerArgs.emplace_back(A->getValue());
9921 else if (ShouldForward(CompilerOptions, A, *TC)) {
9922 A->claim();
9923 A->render(Args, CompilerArgs);
9924 } else if (ShouldForward(LinkerOptions, A, *TC)) {
9925 A->claim();
9926 A->render(Args, LinkerArgs);
9927 }
9928 }
9929
9930 // If the user explicitly requested it via `--offload-arch` we should
9931 // extract it from any static libraries if present. Device images are
9932 // labeled with the canonical target ID, so request that.
9933 for (StringRef Arg : ToolChainArgs.getAllArgValues(OPT_offload_arch_EQ)) {
9934 std::optional<std::string> TargetID =
9935 getCanonicalTargetID(TC->getTriple(), Arg);
9936 CmdArgs.emplace_back(Args.MakeArgString(
9937 "--should-extract=" + (TargetID ? StringRef(*TargetID) : Arg)));
9938 }
9939
9940 // If this is OpenMP the device linker will need `-lompdevice`.
9941 if (Kind == Action::OFK_OpenMP && !Args.hasArg(OPT_no_offloadlib) &&
9942 (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))
9943 LinkerArgs.emplace_back("-lompdevice");
9944
9945 // For SPIR-V, pass some extra flags to `spirv-link`, the out-of-tree
9946 // SPIR-V linker. `spirv-link` isn't called in LTO mode so restrict these
9947 // flags to normal compilation.
9948 // SPIR-V for AMD doesn't use spirv-link and therefore doesn't need these
9949 // flags. SYCL uses clang-sycl-linker instead of spirv-link, so skip it.
9950 if (TC->getTriple().isSPIRV() &&
9951 TC->getTriple().getVendor() != llvm::Triple::VendorType::AMD &&
9952 Kind != Action::OFK_SYCL && !TC->isUsingLTO(ToolChainArgs, Kind)) {
9953 // For SPIR-V some functions will be defined by the runtime so allow
9954 // unresolved symbols in `spirv-link`.
9955 LinkerArgs.emplace_back("--allow-partial-linkage");
9956 // Don't optimize out exported symbols.
9957 LinkerArgs.emplace_back("--create-library");
9958 }
9959
9960 // Forward the SYCL device image split option to clang-sycl-linker.
9961 // The driver and clang-sycl-linker share the same value vocabulary, so
9962 // the value is passed through verbatim after validation.
9963 if (Kind == Action::OFK_SYCL) {
9964 if (Arg *A =
9965 ToolChainArgs.getLastArg(OPT_fsycl_device_image_split_EQ)) {
9966 StringRef Mode = A->getValue();
9967 if (Mode != "kernel" && Mode != "translation_unit" &&
9968 Mode != "link_unit")
9969 C.getDriver().Diag(clang::diag::err_drv_invalid_value)
9970 << A->getSpelling() << Mode;
9971 else
9972 LinkerArgs.emplace_back(
9973 Args.MakeArgString("--module-split-mode=" + Mode));
9974 }
9975 }
9976
9977 // Forward all of these to the appropriate toolchain.
9978 for (StringRef Arg : CompilerArgs)
9979 CmdArgs.push_back(Args.MakeArgString(
9980 "--device-compiler=" + TC->getTripleString() + "=" + Arg));
9981 for (StringRef Arg : LinkerArgs)
9982 CmdArgs.push_back(Args.MakeArgString(
9983 "--device-linker=" + TC->getTripleString() + "=" + Arg));
9984
9985 // Forward the LTO mode for this toolchain.
9986 auto DeviceLTOMode = TC->getLTOMode(ToolChainArgs, Kind);
9987 if (DeviceLTOMode == LTOK_Full)
9988 CmdArgs.push_back(Args.MakeArgString(
9989 "--device-compiler=" + TC->getTripleString() + "=-flto=full"));
9990 else if (DeviceLTOMode == LTOK_Thin) {
9991 CmdArgs.push_back(Args.MakeArgString(
9992 "--device-compiler=" + TC->getTripleString() + "=-flto=thin"));
9993 if (TC->getTriple().isAMDGPU()) {
9994 CmdArgs.push_back(
9995 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9996 "=-plugin-opt=-force-import-all"));
9997 CmdArgs.push_back(
9998 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9999 "=-plugin-opt=-avail-extern-to-local"));
10000 CmdArgs.push_back(Args.MakeArgString(
10001 "--device-linker=" + TC->getTripleString() +
10002 "=-plugin-opt=-avail-extern-gv-in-addrspace-to-local=3"));
10003 if (Kind == Action::OFK_OpenMP) {
10004 CmdArgs.push_back(
10005 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
10006 "=-plugin-opt=-amdgpu-internalize-symbols"));
10007 }
10008 }
10009 }
10010 }
10011 }
10012
10013 if (const llvm::Triple *AuxTriple = getToolChain().getAuxTriple())
10014 CmdArgs.push_back(
10015 Args.MakeArgString("--host-triple=" + AuxTriple->getTriple()));
10016 else
10017 CmdArgs.push_back(Args.MakeArgString("--host-triple=" +
10018 getToolChain().getTripleString()));
10019
10020 if (Args.hasArg(options::OPT_v) && !SuppressHIPNoRDCVerbose)
10021 CmdArgs.push_back("--wrapper-verbose");
10022 if (Arg *A = Args.getLastArg(options::OPT_cuda_path_EQ)) {
10023 CmdArgs.push_back(
10024 Args.MakeArgString(Twine("--cuda-path=") + A->getValue()));
10025 CmdArgs.push_back(Args.MakeArgString(
10026 Twine("--device-compiler=--cuda-path=") + A->getValue()));
10027 }
10028 if (Arg *A = Args.getLastArg(options::OPT_rocm_path_EQ)) {
10029 CmdArgs.push_back(Args.MakeArgString(
10030 Twine("--device-compiler=--rocm-path=") + A->getValue()));
10031 }
10032
10033 // Construct the link job so we can wrap around it.
10034 Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
10035 const auto &LinkCommand = C.getJobs().getJobs().back();
10036
10037 // Forward -Xoffload-{compiler,linker}<-triple> arguments to the linker
10038 // wrapper.
10039 for (Arg *A :
10040 Args.filtered(options::OPT_Xoffload_compiler, OPT_Xoffload_linker)) {
10041 StringRef Val = A->getValue(0);
10042 bool IsLinkJob = A->getOption().getID() == OPT_Xoffload_linker;
10043 auto WrapperOption =
10044 IsLinkJob ? Twine("--device-linker=") : Twine("--device-compiler=");
10045 if (Val.empty())
10046 CmdArgs.push_back(Args.MakeArgString(WrapperOption + A->getValue(1)));
10047 else
10048 CmdArgs.push_back(Args.MakeArgString(
10049 WrapperOption +
10050 ToolChain::normalizeOffloadTriple(Val.drop_front()).str() + "=" +
10051 A->getValue(1)));
10052 }
10053 Args.ClaimAllArgs(options::OPT_Xoffload_compiler);
10054 Args.ClaimAllArgs(options::OPT_Xoffload_linker);
10055
10056 // Embed bitcode instead of an object in JIT mode.
10057 if (Args.hasFlag(options::OPT_fopenmp_target_jit,
10058 options::OPT_fno_openmp_target_jit, false))
10059 CmdArgs.push_back("--embed-bitcode");
10060
10061 // Save temporary files created by the linker wrapper.
10062 if (Args.hasArg(options::OPT_save_temps_EQ) ||
10063 Args.hasArg(options::OPT_save_temps))
10064 CmdArgs.push_back("--save-temps");
10065
10066 // Pass in the C library for GPUs if present and not disabled.
10067 if (Args.hasFlag(options::OPT_offloadlib, OPT_no_offloadlib, true) &&
10068 !Args.hasArg(options::OPT_nostdlib, options::OPT_r,
10069 options::OPT_nodefaultlibs, options::OPT_nolibc,
10070 options::OPT_nogpulibc)) {
10071 forAllAssociatedToolChains(C, JA, getToolChain(), [&](const ToolChain &TC) {
10072 // The device C library is only available for NVPTX and AMDGPU targets
10073 // and we only link it by default for OpenMP currently.
10074 if ((!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU()) ||
10076 return;
10077 bool HasLibC = TC.getStdlibIncludePath().has_value();
10078 if (HasLibC) {
10079 CmdArgs.push_back(Args.MakeArgString(
10080 "--device-linker=" + TC.getTripleString() + "=" + "-lc"));
10081 CmdArgs.push_back(Args.MakeArgString(
10082 "--device-linker=" + TC.getTripleString() + "=" + "-lm"));
10083 }
10084 auto HasCompilerRT = getToolChain().getVFS().exists(
10085 TC.getCompilerRT(Args, "builtins", ToolChain::FT_Static,
10086 /*IsFortran=*/false));
10087 if (HasCompilerRT)
10088 CmdArgs.push_back(
10089 Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
10090 "-lclang_rt.builtins"));
10091
10092 bool HasFlangRT = getToolChain().getVFS().exists(
10093 TC.getCompilerRT(Args, "runtime", ToolChain::FT_Static,
10094 /*IsFortran=*/true));
10095 if (HasFlangRT && C.getDriver().IsFlangMode())
10096 CmdArgs.push_back(
10097 Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
10098 "-lflang_rt.runtime"));
10099 });
10100 }
10101
10102 // Add the linker arguments to be forwarded by the wrapper.
10103 CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
10104 LinkCommand->getExecutable()));
10105
10106 // We use action type to differentiate two use cases of the linker wrapper.
10107 // TY_Image for normal linker wrapper work.
10108 // TY_HIP_FATBIN and TY_SYCL_FATBIN for device-only links emitting a fat
10109 // binary directly.
10110 assert(JA.getType() == types::TY_HIP_FATBIN ||
10111 JA.getType() == types::TY_SYCL_FATBIN ||
10112 JA.getType() == types::TY_Image);
10113 if (JA.getType() != types::TY_Image) {
10114 CmdArgs.push_back("--emit-fatbin-only");
10115 CmdArgs.append({"-o", Output.getFilename()});
10116 for (auto Input : Inputs)
10117 CmdArgs.push_back(Input.getFilename());
10118 } else {
10119 for (const char *LinkArg : LinkCommand->getArguments())
10120 CmdArgs.push_back(LinkArg);
10121 }
10122
10123 addOffloadCompressArgs(Args, CmdArgs);
10124
10125 OffloadJobsOpt OffloadJobs = parseOffloadJobs(Args);
10126 if (OffloadJobs.A) {
10127 if (OffloadJobs.K == OffloadJobsOpt::Kind::Jobserver) {
10128 CmdArgs.push_back(Args.MakeArgString("--wrapper-jobs=jobserver"));
10129 } else if (OffloadJobs.K == OffloadJobsOpt::Kind::Fixed) {
10130 CmdArgs.push_back(Args.MakeArgString("--wrapper-jobs=" +
10131 Twine(OffloadJobs.NumThreads)));
10132 } else if (!OffloadJobs.A->isClaimed()) {
10133 C.getDriver().Diag(diag::err_drv_invalid_int_value)
10134 << OffloadJobs.A->getAsString(Args) << OffloadJobs.Value;
10135 }
10136 }
10137
10138 // Propagate -no-canonical-prefixes.
10139 if (Args.hasArg(options::OPT_no_canonical_prefixes))
10140 CmdArgs.push_back("--no-canonical-prefixes");
10141
10142 const char *Exec =
10143 Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
10144
10145 // Replace the executable and arguments of the link job with the
10146 // wrapper.
10147 LinkCommand->replaceExecutable(Exec);
10148 LinkCommand->replaceArguments(CmdArgs);
10149}
#define V(N, I)
static StringRef bytes(const std::vector< T, Allocator > &v)
static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:3967
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:2342
static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T, ArgStringList &CmdArgs)
Definition Clang.cpp:4394
static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind, unsigned DwarfVersion, llvm::DebuggerKind DebuggerTuning)
Definition Clang.cpp:717
static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:5159
static bool requiresProfileRT(unsigned ID)
Definition Clang.cpp:9774
static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:4575
static bool maybeHasClangPchSignature(const Driver &D, StringRef Path)
Definition Clang.cpp:766
static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args)
Definition Clang.cpp:71
void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:1361
static bool isSignedCharDefault(const llvm::Triple &Triple)
Definition Clang.cpp:1213
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:8895
static void checkAndRemoveLLVMArg(ArgStringList &CmdArgs, StringRef Opt)
Definition Clang.cpp:2321
static bool gchProbe(const Driver &D, StringRef Path)
Definition Clang.cpp:783
static void RenderOpenACCOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:4067
static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D, const ArgList &Args)
Definition Clang.cpp:4709
static bool CheckARMImplicitITArg(StringRef Value)
Definition Clang.cpp:2592
static bool hasMultipleInvocations(const llvm::Triple &Triple, const ArgList &Args)
Definition Clang.cpp:1251
static void handleAMDGPUCodeObjectVersionOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, bool IsCC1As=false)
Definition Clang.cpp:743
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:4686
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:4430
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:2597
static bool checkRemarksOptions(const Driver &D, const ArgList &Args, const llvm::Triple &Triple)
Definition Clang.cpp:1262
static void addQFloatBackendArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:2373
static void CollectArgsForIntegratedAssembler(Compilation &C, const ArgList &Args, ArgStringList &CmdArgs, const Driver &D)
Definition Clang.cpp:2603
static StringRef getOptionName(StringRef Option, const char Delimiter='=')
Definition Clang.cpp:2314
static bool RenderModulesOptions(Compilation &C, const Driver &D, const ArgList &Args, const InputInfo &Input, const InputInfo &Output, bool HaveStd20, ArgStringList &CmdArgs)
Definition Clang.cpp:4133
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:3639
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:1278
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:1396
static void RenderSSPOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, bool KernelOrKext)
Definition Clang.cpp:3649
static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:4075
static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3877
static void RenderTrivialAutoVarInitOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3896
static bool maybeConsumeDash(const std::string &EH, size_t &I)
Definition Clang.cpp:8874
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 void renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T, const ArgList &Args, types::ID InputType, ArgStringList &CmdArgs, const InputInfo &Output, llvm::codegenoptions::DebugInfoKind &DebugInfoKind, DwarfFissionKind &DwarfFission, bool IsUsingLTO)
Definition Clang.cpp:4726
static bool requiresUBSanRT(unsigned ID)
Definition Clang.cpp:9792
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:3570
static void addQFloatLossyFastMathArgs(ArgStringList &CmdArgs)
Definition Clang.cpp:2348
static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D, bool OFastEnabled, const ArgList &Args, ArgStringList &CmdArgs, const JobAction &JA)
Definition Clang.cpp:2970
static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C, const JobAction &JA, const InputInfo &Output, const ArgList &Args, SanitizerArgs &SanArgs, ArgStringList &CmdArgs)
Definition Clang.cpp:372
static void RenderHLSLOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:4011
clang::CodeGenOptions::FramePointerKind getFramePointerKind(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
TokenType getType() const
Returns the token's type, e.g.
Defines enums used when emitting included header information.
Defines the clang::LangOptions interface.
static StringRef getTriple(const Command &Job)
Defines types useful for describing an Objective-C runtime.
Defines version macros and version-related utility functions for Clang.
static StringRef getWarningOptionForGroup(diag::Group)
Given a group ID, returns the flag that toggles the group.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition Diagnostic.h:946
ComplexRangeKind
Controls the various implementations for complex multiplication and.
@ CX_Full
Implementation of complex division and multiplication using a call to runtime library functions(gener...
@ CX_Basic
Implementation of complex division and multiplication using algebraic formulas at source precision.
@ CX_Promoted
Implementation of complex division using algebraic formulas at higher precision.
@ CX_None
No range rule is enabled.
@ CX_Improved
Implementation of complex division offering an improved handling for overflow in intermediate calcula...
The basic abstraction for the target Objective-C runtime.
Definition ObjCRuntime.h:28
bool allowsWeak() const
Does this runtime allow the use of __weak?
bool isLegacyDispatchDefaultForArch(llvm::Triple::ArchType Arch)
The default dispatch mechanism to use for the specified architecture.
Kind getKind() const
Definition ObjCRuntime.h:77
bool isNeXTFamily() const
Is this runtime basically of the NeXT family of runtimes?
bool hasConstantLiteralClasses() const
Are Foundation backed constant literal classes supported?
const VersionTuple & getVersion() const
Definition ObjCRuntime.h:78
bool tryParse(StringRef input)
Try to parse an Objective-C runtime specification from the given string.
bool isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
Definition ObjCRuntime.h:82
std::string getAsString() const
@ MacOSX
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
Definition ObjCRuntime.h:35
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition ObjCRuntime.h:40
@ GNUstep
'gnustep' is the modern non-fragile GNUstep runtime.
Definition ObjCRuntime.h:56
@ GCC
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI
Definition ObjCRuntime.h:53
A processor an offloading action can target.
Definition OffloadArch.h:36
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Scope(Scope *Parent, unsigned ScopeFlags, DiagnosticsEngine &Diag)
Definition Scope.h:263
Action - Represent an abstract compilation step to perform.
Definition Action.h:48
types::ID getType() const
Definition Action.h:153
const ToolChain * getOffloadingToolChain() const
Definition Action.h:217
static std::string GetOffloadingFileNamePrefix(OffloadKind Kind, StringRef NormalizedTriple, bool CreatePrefixForHost=false)
Return a string that can be used as prefix in order to generate unique files for each offloading kind...
Definition Action.cpp:143
BoundArch getOffloadingArch() const
Definition Action.h:216
ActionClass getKind() const
Definition Action.h:152
static StringRef GetOffloadKindName(OffloadKind Kind)
Return a string containing a offload kind name.
Definition Action.cpp:159
OffloadKind getOffloadingDeviceKind() const
Definition Action.h:215
bool isHostOffloading(unsigned int OKind) const
Check if this action have any offload kinds.
Definition Action.h:223
bool isDeviceOffloading(OffloadKind OKind) const
Definition Action.h:226
ActionList & getInputs()
Definition Action.h:155
unsigned getOffloadingHostActiveKinds() const
Definition Action.h:211
bool isOffloading(OffloadKind OKind) const
Definition Action.h:229
Command - An executable path/name and argument vector to execute.
Definition Job.h:107
Compilation - A set of tasks to perform for a single driver invocation.
Definition Compilation.h:46
std::pair< const_offload_toolchains_iterator, const_offload_toolchains_iterator > const_offload_toolchains_range
Distro - Helper class for detecting and classifying Linux distributions.
Definition Distro.h:23
bool IsGentoo() const
Definition Distro.h:134
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:93
llvm::SmallVector< BoundArch > getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args, Action::OffloadKind Kind, const ToolChain &TC) const
Returns the set of bound architectures active for this offload kind.
Definition Driver.cpp:3989
std::string SysRoot
sysroot, if present
Definition Driver.h:193
DiagnosticsEngine & getDiags() const
Definition Driver.h:408
const char * getPrependArg() const
Definition Driver.h:419
CC1ToolFunc CC1Main
Definition Driver.h:289
OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const
Compute the desired OpenMP runtime from the flags provided.
Definition Driver.cpp:918
bool IsCLMode() const
Whether the driver should follow cl.exe like behavior.
Definition Driver.h:229
unsigned CCLogDiagnostics
Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics to CCLogDiagnosticsFilename...
Definition Driver.h:267
static bool getDefaultModuleCachePath(SmallVectorImpl< char > &Result)
Compute the default -fmodule-cache-path.
Definition Clang.cpp:4099
unsigned CCGenDiagnostics
Whether the driver is generating diagnostics for debugging purposes.
Definition Driver.h:271
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:157
unsigned CCPrintInternalStats
Set CC_PRINT_INTERNAL_STAT mode, which causes the driver to dump internal performance report to CC_PR...
Definition Driver.h:281
std::string GetClPchPath(Compilation &C, StringRef BaseName) const
Return the pathname of the pch file in clang-cl mode.
Definition Driver.cpp:6098
void PrintVersion(const Compilation &C, raw_ostream &OS) const
PrintVersion - Print the driver version.
Definition Driver.cpp:2523
const char * getDriverProgramPath() const
Get the path to the main driver executable.
Definition Driver.h:430
std::string CCLogDiagnosticsFilename
The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
Definition Driver.h:217
std::string CCPrintHeadersFilename
The file to log CC_PRINT_HEADERS output to, if enabled.
Definition Driver.h:214
std::string ResourceDir
The path to the compiler resource directory.
Definition Driver.h:177
llvm::vfs::FileSystem & getVFS() const
Definition Driver.h:410
std::string Dir
The path the driver executable was in, as invoked from the command line.
Definition Driver.h:168
@ OMPRT_IOMP5
The legacy name for the LLVM OpenMP runtime from when it was the Intel OpenMP runtime.
Definition Driver.h:153
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition Driver.h:143
HeaderIncludeFormatKind CCPrintHeadersFormat
The format of the header information that is emitted.
Definition Driver.h:250
std::string getTargetTriple() const
Definition Driver.h:427
HeaderIncludeFilteringKind CCPrintHeadersFiltering
This flag determines whether clang should filter the header information that is emitted.
Definition Driver.h:256
std::string DriverExecutable
The original path to the driver executable.
Definition Driver.h:171
bool CCCIsCPP() const
Whether the driver is just the preprocessor.
Definition Driver.h:223
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
Definition Driver.h:220
bool getProbePrecompiled() const
Definition Driver.h:416
InputInfo - Wrapper for information about an input source.
Definition InputInfo.h:22
const char * getBaseInput() const
Definition InputInfo.h:78
const llvm::opt::Arg & getInputArg() const
Definition InputInfo.h:87
const char * getFilename() const
Definition InputInfo.h:83
bool isNothing() const
Definition InputInfo.h:74
const Action * getAction() const
The action for which this InputInfo was created. May be null.
Definition InputInfo.h:80
bool isFilename() const
Definition InputInfo.h:75
types::ID getType() const
Definition InputInfo.h:77
An offload action combines host or/and device actions according to the programming model implementati...
Definition Action.h:273
ToolChain - Access to tools for a single platform.
Definition ToolChain.h:92
static void normalizeOffloadTriple(llvm::Triple &TT)
Definition ToolChain.h:907
virtual std::string GetGlobalDebugPathRemapping() const
Add an additional -fdebug-prefix-map entry.
Definition ToolChain.h:656
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:665
virtual void adjustDebugInfoKind(llvm::codegenoptions::DebugInfoKind &DebugInfoKind, const llvm::opt::ArgList &Args) const
Adjust debug information kind considering all passed options.
Definition ToolChain.h:689
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:899
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:647
virtual bool IsObjCNonFragileABIDefault() const
IsObjCNonFragileABIDefault - Does this tool chain set -fobjc-nonfragile-abi by default.
Definition ToolChain.h:519
virtual std::string ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args, BoundArch BA={}, types::ID InputType=types::TY_INVALID) const
ComputeEffectiveClangTriple - Return the Clang triple to use for this target, which may take into acc...
virtual bool isThreadModelSupported(const StringRef Model) const
isThreadModelSupported() - Does this target support a thread model?
llvm::Triple::ArchType getArch() const
Definition ToolChain.h:298
const Driver & getDriver() const
Definition ToolChain.h:282
RTTIMode getRTTIMode() const
Definition ToolChain.h:365
llvm::vfs::FileSystem & getVFS() const
static bool needsGCovInstrumentation(const llvm::opt::ArgList &Args)
Returns true if gcov instrumentation (-fprofile-arcs or –coverage) is on.
virtual std::string getCompilerRT(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static, bool IsFortran=false) const
virtual llvm::DebuggerKind getDefaultDebuggerTuning() const
Definition ToolChain.h:678
void AddClangCXXStdlibIsystemArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
AddClangCXXStdlibIsystemArgs - Add the clang -cc1 level arguments to set the specified include paths ...
virtual LTOKind getLTOMode(const llvm::opt::ArgList &Args, Action::OffloadKind Kind=Action::OFK_None) const
Resolve the requested LTO mode for this toolchain.
virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, BoundArch BA, Action::OffloadKind DeviceOffloadKind) const
Add options that need to be passed to cc1 for this target.
const llvm::Triple & getEffectiveTriple() const
Get the toolchain's effective clang triple.
Definition ToolChain.h:310
virtual LangOptions::TrivialAutoVarInitKind GetDefaultTrivialAutoVarInit() const
Get the default trivial automatic variable initialization.
Definition ToolChain.h:540
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:511
virtual std::string getThreadModel() const
getThreadModel() - Which thread model does this target use?
Definition ToolChain.h:700
virtual bool GetDefaultStandaloneDebug() const
Definition ToolChain.h:671
const llvm::Triple & getTriple() const
Definition ToolChain.h:284
bool defaultToIEEELongDouble() const
Check whether use IEEE binary128 as long double format by default.
virtual bool HasNativeLLVMSupport() const
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
virtual bool getDefaultDebugSimpleTemplateNames() const
Returns true if this toolchain adds '-gsimple-template-names=simple' by default when generating debug...
Definition ToolChain.h:675
const XRayArgs getXRayArgs(const llvm::opt::ArgList &) const
virtual void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific CUDA includes.
StringRef getTripleString() const
Definition ToolChain.h:307
virtual LangOptions::StackProtectorMode GetDefaultStackProtectorLevel(bool KernelOrKext) const
GetDefaultStackProtectorLevel - Get the default stack protector level for this tool chain.
Definition ToolChain.h:534
virtual bool hasBlocksRuntime() const
hasBlocksRuntime - Given that the user is compiling with -fblocks, does this tool chain guarantee the...
Definition ToolChain.h:740
virtual bool UseDwarfDebugFlags() const
UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf compile unit information.
Definition ToolChain.h:653
virtual bool SupportsProfiling() const
SupportsProfiling - Does this tool chain support -pg.
Definition ToolChain.h:641
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:894
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:523
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:486
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:644
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:515
virtual bool IsBlocksDefault() const
IsBlocksDefault - Does this tool chain enable -fblocks by default.
Definition ToolChain.h:482
std::string getCompilerRTBasename(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const
virtual const llvm::Triple * getAuxTriple() const
Get the toolchain's aux triple, if it has one.
Definition ToolChain.h:291
virtual bool parseInlineAsmUsingAsmParser() const
Check if the toolchain should use AsmParser to parse inlineAsm when integrated assembler is not defau...
Definition ToolChain.h:508
virtual ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const
getDefaultObjCRuntime - Return the default Objective-C runtime for this platform.
const ToolChain & getToolChain() const
Definition Tool.h:52
Tool(const char *Name, const char *ShortName, const ToolChain &TC)
Definition Tool.cpp:13
const char * getShortName() const
Definition Tool.h:50
void addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, types::ID InputType) const
Definition XRayArgs.cpp:181
static std::optional< std::string > GetHVXVersion(const llvm::opt::ArgList &Args)
Definition Hexagon.cpp:1034
static std::optional< unsigned > getSmallDataThreshold(const llvm::opt::ArgList &Args)
Definition Hexagon.cpp:658
void AddLoongArchTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9296
void AddX86TargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9279
void AddRISCVTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9304
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:9319
void AddMIPSTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9268
static const char * getBaseInputName(const llvm::opt::ArgList &Args, const InputInfo &Input)
Definition Clang.cpp:9238
Clang(const ToolChain &TC, bool HasIntegratedBackend=true)
Definition Clang.cpp:8729
static const char * getDependencyFileName(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition Clang.cpp:9253
static const char * getBaseInputStem(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition Clang.cpp:9243
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:5259
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:9804
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:9625
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:9715
void addSanitizerArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
void addProfileRTArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
std::optional< std::string > getAArch64TargetTuneCPU(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition AArch64.cpp:117
bool isHardTPSupported(const llvm::Triple &Triple)
Definition ARM.cpp:210
FloatABI getARMFloatABI(const ToolChain &TC, const llvm::opt::ArgList &Args)
StringRef getLoongArchABI(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
std::string postProcessTargetCPUString(const std::string &CPU, const llvm::Triple &Triple)
mips::FloatABI getMipsFloatABI(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
bool hasCompactBranches(StringRef &CPU)
Definition Mips.cpp:479
void getMipsCPUAndABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple, StringRef &CPUName, StringRef &ABIName)
FloatABI getPPCFloatABI(const Driver &D, const llvm::opt::ArgList &Args)
std::string getRISCVArch(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition RISCV.cpp:305
StringRef getRISCVABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
std::optional< StringRef > getRISCVTuneCPU(const Driver &D, const llvm::opt::ArgList &Args, SmallVectorImpl< std::string > *TuneFeatures=nullptr)
Return the tune CPU and optionally, the tune features.
Definition RISCV.cpp:433
FloatABI getSparcFloatABI(const Driver &D, const llvm::opt::ArgList &Args)
FloatABI getSystemZFloatABI(const Driver &D, const llvm::opt::ArgList &Args)
void addX86AlignBranchArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool IsLTO, const StringRef PluginOptPrefix="")
void addMachineOutlinerArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple, bool IsLTO, const StringRef PluginOptPrefix="")
unsigned ParseFunctionAlignment(const ToolChain &TC, const llvm::opt::ArgList &Args)
void addOffloadCompressArgs(const llvm::opt::ArgList &TCArgs, llvm::opt::ArgStringList &CmdArgs)
void addMCModel(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple, const llvm::Reloc::Model &RelocationModel, llvm::opt::ArgStringList &CmdArgs)
llvm::opt::Arg * getLastProfileSampleUseArg(const llvm::opt::ArgList &Args)
void handleVectorizeSLPArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Enable -fslp-vectorize based on the optimization level selected.
OffloadJobsOpt parseOffloadJobs(const llvm::opt::ArgList &Args)
const char * SplitDebugName(const JobAction &JA, const llvm::opt::ArgList &Args, const InputInfo &Input, const InputInfo &Output)
void addOutlineAtomicsArgs(const Driver &D, const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple)
void getTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool ForAS, bool IsAux=false)
void renderDebugInfoCompressionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const Driver &D, const ToolChain &TC)
std::string complexRangeKindToStr(LangOptions::ComplexRangeKind Range)
void handleColorDiagnosticsArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Handle the -f{no}-color-diagnostics and -f{no}-diagnostics-colors options.
std::string getCPUName(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &T, bool FromAs=false)
void addDirectoryList(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const char *ArgName, const char *EnvVar)
EnvVar is split by system delimiter for environment variables.
llvm::SmallString< 256 > getCXX20NamedModuleOutputPath(const llvm::opt::ArgList &Args, const char *BaseInput)
void setComplexRange(const Driver &D, StringRef NewOpt, LangOptions::ComplexRangeKind NewRange, StringRef &LastOpt, LangOptions::ComplexRangeKind &Range)
bool haveAMDGPUCodeObjectVersionArgument(const Driver &D, const llvm::opt::ArgList &Args)
bool isTLSDESCEnabled(const ToolChain &TC, const llvm::opt::ArgList &Args)
void addDebugInfoForProfilingArgs(const Driver &D, const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
void addDebugInfoKind(llvm::opt::ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind)
llvm::codegenoptions::DebugInfoKind debugLevelToInfoKind(const llvm::opt::Arg &A)
llvm::opt::Arg * getLastCSProfileGenerateArg(const llvm::opt::ArgList &Args)
void renderGlobalISelOptions(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple)
llvm::opt::Arg * getLastProfileUseArg(const llvm::opt::ArgList &Args)
std::string renderComplexRangeOption(LangOptions::ComplexRangeKind Range)
DwarfFissionKind getDebugFissionKind(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::Arg *&Arg)
const char * renderEscapedCommandLine(const ToolChain &TC, const llvm::opt::ArgList &Args)
Join the args in the given ArgList, escape spaces and backslashes and return the joined string.
void renderCommonIntegerOverflowOptions(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool IsMSVCCompat)
void addSplitMachineFunctionsArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple)
bool checkDebugInfoOption(const llvm::opt::Arg *A, const llvm::opt::ArgList &Args, const Driver &D, const ToolChain &TC)
std::tuple< llvm::Reloc::Model, unsigned, bool > ParsePICArgs(const ToolChain &ToolChain, const llvm::opt::ArgList &Args)
void claimNoWarnArgs(const llvm::opt::ArgList &Args)
unsigned DwarfVersionNum(StringRef ArgValue)
unsigned getDwarfVersion(const ToolChain &TC, const llvm::opt::ArgList &Args)
bool shouldRecordCommandLine(const ToolChain &TC, const llvm::opt::ArgList &Args, bool &FRecordCommandLine, bool &GRecordCommandLine, bool &DXRecordCommandLine)
Check if the command line should be recorded in the object file.
unsigned getAMDGPUCodeObjectVersion(const Driver &D, const llvm::opt::ArgList &Args)
const llvm::opt::Arg * getDwarfNArg(const llvm::opt::ArgList &Args)
SmallString< 128 > getStatsFileName(const llvm::opt::ArgList &Args, const InputInfo &Output, const InputInfo &Input, const Driver &D)
Handles the -save-stats option and returns the filename to save statistics to.
void addSeparateSectionFlags(const llvm::Triple &Triple, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Append -ffunction-sections / -fdata-sections to CmdArgs when the corresponding flags are enabled (exp...
void handleVectorizeLoopsArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Enable -fvectorize based on the optimization level selected.
void escapeSpacesAndBackslashes(const char *Arg, llvm::SmallVectorImpl< char > &Res)
Add backslashes to escape spaces and other backslashes.
bool isObjCAutoRefCount(const llvm::opt::ArgList &Args)
const char * RelocationModelName(llvm::Reloc::Model Model)
void addOpenMPHostOffloadingArgs(const Compilation &C, const JobAction &JA, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Adds offloading options for OpenMP host compilation to CmdArgs.
bool isHLSL(ID Id)
isHLSL - Is this an HLSL input.
Definition Types.cpp:329
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition Types.cpp:240
ID getPreprocessedType(ID Id)
getPreprocessedType - Get the ID of the type for this input when it has been preprocessed,...
Definition Types.cpp:53
bool isLLVMIR(ID Id)
Is this LLVM IR.
Definition Types.cpp:292
const char * getTypeName(ID Id)
getTypeName - Return the name of the type for Id.
Definition Types.cpp:49
bool isOpenCL(ID Id)
isOpenCL - Is this an "OpenCL" input.
Definition Types.cpp:253
bool isSrcFile(ID Id)
isSrcFile - Is this a source file, i.e.
Definition Types.cpp:331
const char * getTypeTempSuffix(ID Id, bool CLStyle=false)
getTypeTempSuffix - Return the suffix to use when creating a temp file of this type,...
Definition Types.cpp:81
bool isCXX(ID Id)
isCXX - Is this a "C++" input (C++ and Obj-C++ sources and headers).
Definition Types.cpp:265
SmallVector< InputInfo, 4 > InputInfoList
Definition Driver.h:49
bool isOptimizationLevelFast(const llvm::opt::ArgList &Args)
bool willEmitRemarks(const llvm::opt::ArgList &Args)
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ Quoted
'#include ""' paths, added by 'gcc -iquote'.
Top level wrappers for InstallAPI frontend operations.
std::optional< diag::Group > diagGroupFromCLWarningID(unsigned)
For cl.exe warning IDs that cleany map to clang diagnostic groups, returns the corresponding group.
bool isa(CodeGen::Address addr)
Definition Address.h:330
void quoteMakeTarget(StringRef Target, SmallVectorImpl< char > &Res)
Quote target names for inclusion in GNU Make dependency files.
const char * headerIncludeFormatKindToString(HeaderIncludeFormatKind K)
unsigned CudaArchToID(OffloadArch Arch)
Get the numeric ID (e.g. 700) of a CUDA architecture.
Definition Cuda.cpp:133
StringRef parseMPreferVectorWidthOption(clang::DiagnosticsEngine &Diags, const llvm::opt::ArgList &Args)
const char * headerIncludeFilteringKindToString(HeaderIncludeFilteringKind K)
@ C
Languages that the frontend can parse and compile.
@ Asm
Assembly: we accept this only so that we can preprocess it.
@ Default
Set to the current date and time.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
const char * CudaVersionToString(CudaVersion V)
Definition Cuda.cpp:60
std::string getCanonicalTargetID(llvm::StringRef Processor, const llvm::StringMap< bool > &Features)
Returns canonical target ID, assuming Processor is canonical and all entries in Features are valid.
Definition TargetID.cpp:146
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:39
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 int64_t
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