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