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