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