clang 19.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 "AMDGPU.h"
11#include "Arch/AArch64.h"
12#include "Arch/ARM.h"
13#include "Arch/CSKY.h"
14#include "Arch/LoongArch.h"
15#include "Arch/M68k.h"
16#include "Arch/Mips.h"
17#include "Arch/PPC.h"
18#include "Arch/RISCV.h"
19#include "Arch/Sparc.h"
20#include "Arch/SystemZ.h"
21#include "Arch/VE.h"
22#include "Arch/X86.h"
23#include "CommonArgs.h"
24#include "Hexagon.h"
25#include "MSP430.h"
26#include "PS4CPU.h"
34#include "clang/Basic/Version.h"
35#include "clang/Config/config.h"
36#include "clang/Driver/Action.h"
37#include "clang/Driver/Distro.h"
42#include "clang/Driver/Types.h"
44#include "llvm/ADT/SmallSet.h"
45#include "llvm/ADT/StringExtras.h"
46#include "llvm/BinaryFormat/Magic.h"
47#include "llvm/Config/llvm-config.h"
48#include "llvm/Frontend/Debug/Options.h"
49#include "llvm/Object/ObjectFile.h"
50#include "llvm/Option/ArgList.h"
51#include "llvm/Support/CodeGen.h"
52#include "llvm/Support/Compiler.h"
53#include "llvm/Support/Compression.h"
54#include "llvm/Support/Error.h"
55#include "llvm/Support/FileSystem.h"
56#include "llvm/Support/Path.h"
57#include "llvm/Support/Process.h"
58#include "llvm/Support/YAMLParser.h"
59#include "llvm/TargetParser/AArch64TargetParser.h"
60#include "llvm/TargetParser/ARMTargetParserCommon.h"
61#include "llvm/TargetParser/Host.h"
62#include "llvm/TargetParser/LoongArchTargetParser.h"
63#include "llvm/TargetParser/RISCVISAInfo.h"
64#include "llvm/TargetParser/RISCVTargetParser.h"
65#include <cctype>
66
67using namespace clang::driver;
68using namespace clang::driver::tools;
69using namespace clang;
70using namespace llvm::opt;
71
72static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
73 if (Arg *A = Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC,
74 options::OPT_fminimize_whitespace,
75 options::OPT_fno_minimize_whitespace,
76 options::OPT_fkeep_system_includes,
77 options::OPT_fno_keep_system_includes)) {
78 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
79 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
80 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
81 << A->getBaseArg().getAsString(Args)
82 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
83 }
84 }
85}
86
87static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
88 // In gcc, only ARM checks this, but it seems reasonable to check universally.
89 if (Args.hasArg(options::OPT_static))
90 if (const Arg *A =
91 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
92 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
93 << "-static";
94}
95
96// Add backslashes to escape spaces and other backslashes.
97// This is used for the space-separated argument list specified with
98// the -dwarf-debug-flags option.
99static void EscapeSpacesAndBackslashes(const char *Arg,
101 for (; *Arg; ++Arg) {
102 switch (*Arg) {
103 default:
104 break;
105 case ' ':
106 case '\\':
107 Res.push_back('\\');
108 break;
109 }
110 Res.push_back(*Arg);
111 }
112}
113
114/// Apply \a Work on the current tool chain \a RegularToolChain and any other
115/// offloading tool chain that is associated with the current action \a JA.
116static void
118 const ToolChain &RegularToolChain,
119 llvm::function_ref<void(const ToolChain &)> Work) {
120 // Apply Work on the current/regular tool chain.
121 Work(RegularToolChain);
122
123 // Apply Work on all the offloading tool chains associated with the current
124 // action.
126 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
128 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
130 Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
132 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
133
135 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
136 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
137 Work(*II->second);
139 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
140
141 //
142 // TODO: Add support for other offloading programming models here.
143 //
144}
145
146/// This is a helper function for validating the optional refinement step
147/// parameter in reciprocal argument strings. Return false if there is an error
148/// parsing the refinement step. Otherwise, return true and set the Position
149/// of the refinement step in the input string.
150static bool getRefinementStep(StringRef In, const Driver &D,
151 const Arg &A, size_t &Position) {
152 const char RefinementStepToken = ':';
153 Position = In.find(RefinementStepToken);
154 if (Position != StringRef::npos) {
155 StringRef Option = A.getOption().getName();
156 StringRef RefStep = In.substr(Position + 1);
157 // Allow exactly one numeric character for the additional refinement
158 // step parameter. This is reasonable for all currently-supported
159 // operations and architectures because we would expect that a larger value
160 // of refinement steps would cause the estimate "optimization" to
161 // under-perform the native operation. Also, if the estimate does not
162 // converge quickly, it probably will not ever converge, so further
163 // refinement steps will not produce a better answer.
164 if (RefStep.size() != 1) {
165 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
166 return false;
167 }
168 char RefStepChar = RefStep[0];
169 if (RefStepChar < '0' || RefStepChar > '9') {
170 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
171 return false;
172 }
173 }
174 return true;
175}
176
177/// The -mrecip flag requires processing of many optional parameters.
178static void ParseMRecip(const Driver &D, const ArgList &Args,
179 ArgStringList &OutStrings) {
180 StringRef DisabledPrefixIn = "!";
181 StringRef DisabledPrefixOut = "!";
182 StringRef EnabledPrefixOut = "";
183 StringRef Out = "-mrecip=";
184
185 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
186 if (!A)
187 return;
188
189 unsigned NumOptions = A->getNumValues();
190 if (NumOptions == 0) {
191 // No option is the same as "all".
192 OutStrings.push_back(Args.MakeArgString(Out + "all"));
193 return;
194 }
195
196 // Pass through "all", "none", or "default" with an optional refinement step.
197 if (NumOptions == 1) {
198 StringRef Val = A->getValue(0);
199 size_t RefStepLoc;
200 if (!getRefinementStep(Val, D, *A, RefStepLoc))
201 return;
202 StringRef ValBase = Val.slice(0, RefStepLoc);
203 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
204 OutStrings.push_back(Args.MakeArgString(Out + Val));
205 return;
206 }
207 }
208
209 // Each reciprocal type may be enabled or disabled individually.
210 // Check each input value for validity, concatenate them all back together,
211 // and pass through.
212
213 llvm::StringMap<bool> OptionStrings;
214 OptionStrings.insert(std::make_pair("divd", false));
215 OptionStrings.insert(std::make_pair("divf", false));
216 OptionStrings.insert(std::make_pair("divh", false));
217 OptionStrings.insert(std::make_pair("vec-divd", false));
218 OptionStrings.insert(std::make_pair("vec-divf", false));
219 OptionStrings.insert(std::make_pair("vec-divh", false));
220 OptionStrings.insert(std::make_pair("sqrtd", false));
221 OptionStrings.insert(std::make_pair("sqrtf", false));
222 OptionStrings.insert(std::make_pair("sqrth", false));
223 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
224 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
225 OptionStrings.insert(std::make_pair("vec-sqrth", false));
226
227 for (unsigned i = 0; i != NumOptions; ++i) {
228 StringRef Val = A->getValue(i);
229
230 bool IsDisabled = Val.starts_with(DisabledPrefixIn);
231 // Ignore the disablement token for string matching.
232 if (IsDisabled)
233 Val = Val.substr(1);
234
235 size_t RefStep;
236 if (!getRefinementStep(Val, D, *A, RefStep))
237 return;
238
239 StringRef ValBase = Val.slice(0, RefStep);
240 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
241 if (OptionIter == OptionStrings.end()) {
242 // Try again specifying float suffix.
243 OptionIter = OptionStrings.find(ValBase.str() + 'f');
244 if (OptionIter == OptionStrings.end()) {
245 // The input name did not match any known option string.
246 D.Diag(diag::err_drv_unknown_argument) << Val;
247 return;
248 }
249 // The option was specified without a half or float or double suffix.
250 // Make sure that the double or half entry was not already specified.
251 // The float entry will be checked below.
252 if (OptionStrings[ValBase.str() + 'd'] ||
253 OptionStrings[ValBase.str() + 'h']) {
254 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
255 return;
256 }
257 }
258
259 if (OptionIter->second == true) {
260 // Duplicate option specified.
261 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
262 return;
263 }
264
265 // Mark the matched option as found. Do not allow duplicate specifiers.
266 OptionIter->second = true;
267
268 // If the precision was not specified, also mark the double and half entry
269 // as found.
270 if (ValBase.back() != 'f' && ValBase.back() != 'd' && ValBase.back() != 'h') {
271 OptionStrings[ValBase.str() + 'd'] = true;
272 OptionStrings[ValBase.str() + 'h'] = true;
273 }
274
275 // Build the output string.
276 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
277 Out = Args.MakeArgString(Out + Prefix + Val);
278 if (i != NumOptions - 1)
279 Out = Args.MakeArgString(Out + ",");
280 }
281
282 OutStrings.push_back(Args.MakeArgString(Out));
283}
284
285/// The -mprefer-vector-width option accepts either a positive integer
286/// or the string "none".
287static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
288 ArgStringList &CmdArgs) {
289 Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
290 if (!A)
291 return;
292
293 StringRef Value = A->getValue();
294 if (Value == "none") {
295 CmdArgs.push_back("-mprefer-vector-width=none");
296 } else {
297 unsigned Width;
298 if (Value.getAsInteger(10, Width)) {
299 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
300 return;
301 }
302 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
303 }
304}
305
306static bool
308 const llvm::Triple &Triple) {
309 // We use the zero-cost exception tables for Objective-C if the non-fragile
310 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
311 // later.
312 if (runtime.isNonFragile())
313 return true;
314
315 if (!Triple.isMacOSX())
316 return false;
317
318 return (!Triple.isMacOSXVersionLT(10, 5) &&
319 (Triple.getArch() == llvm::Triple::x86_64 ||
320 Triple.getArch() == llvm::Triple::arm));
321}
322
323/// Adds exception related arguments to the driver command arguments. There's a
324/// main flag, -fexceptions and also language specific flags to enable/disable
325/// C++ and Objective-C exceptions. This makes it possible to for example
326/// disable C++ exceptions but enable Objective-C exceptions.
327static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
328 const ToolChain &TC, bool KernelOrKext,
329 const ObjCRuntime &objcRuntime,
330 ArgStringList &CmdArgs) {
331 const llvm::Triple &Triple = TC.getTriple();
332
333 if (KernelOrKext) {
334 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
335 // arguments now to avoid warnings about unused arguments.
336 Args.ClaimAllArgs(options::OPT_fexceptions);
337 Args.ClaimAllArgs(options::OPT_fno_exceptions);
338 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
339 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
340 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
341 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
342 Args.ClaimAllArgs(options::OPT_fasync_exceptions);
343 Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
344 return false;
345 }
346
347 // See if the user explicitly enabled exceptions.
348 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
349 false);
350
351 // Async exceptions are Windows MSVC only.
352 if (Triple.isWindowsMSVCEnvironment()) {
353 bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
354 options::OPT_fno_async_exceptions, false);
355 if (EHa) {
356 CmdArgs.push_back("-fasync-exceptions");
357 EH = true;
358 }
359 }
360
361 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
362 // is not necessarily sensible, but follows GCC.
363 if (types::isObjC(InputType) &&
364 Args.hasFlag(options::OPT_fobjc_exceptions,
365 options::OPT_fno_objc_exceptions, true)) {
366 CmdArgs.push_back("-fobjc-exceptions");
367
368 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
369 }
370
371 if (types::isCXX(InputType)) {
372 // Disable C++ EH by default on XCore and PS4/PS5.
373 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
374 !Triple.isPS() && !Triple.isDriverKit();
375 Arg *ExceptionArg = Args.getLastArg(
376 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
377 options::OPT_fexceptions, options::OPT_fno_exceptions);
378 if (ExceptionArg)
379 CXXExceptionsEnabled =
380 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
381 ExceptionArg->getOption().matches(options::OPT_fexceptions);
382
383 if (CXXExceptionsEnabled) {
384 CmdArgs.push_back("-fcxx-exceptions");
385
386 EH = true;
387 }
388 }
389
390 // OPT_fignore_exceptions means exception could still be thrown,
391 // but no clean up or catch would happen in current module.
392 // So we do not set EH to false.
393 Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
394
395 Args.addOptInFlag(CmdArgs, options::OPT_fassume_nothrow_exception_dtor,
396 options::OPT_fno_assume_nothrow_exception_dtor);
397
398 if (EH)
399 CmdArgs.push_back("-fexceptions");
400 return EH;
401}
402
403static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
404 const JobAction &JA) {
405 bool Default = true;
406 if (TC.getTriple().isOSDarwin()) {
407 // The native darwin assembler doesn't support the linker_option directives,
408 // so we disable them if we think the .s file will be passed to it.
410 }
411 // The linker_option directives are intended for host compilation.
414 Default = false;
415 return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
416 Default);
417}
418
419/// Add a CC1 option to specify the debug compilation directory.
420static const char *addDebugCompDirArg(const ArgList &Args,
421 ArgStringList &CmdArgs,
422 const llvm::vfs::FileSystem &VFS) {
423 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
424 options::OPT_fdebug_compilation_dir_EQ)) {
425 if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
426 CmdArgs.push_back(Args.MakeArgString(Twine("-fdebug-compilation-dir=") +
427 A->getValue()));
428 else
429 A->render(Args, CmdArgs);
430 } else if (llvm::ErrorOr<std::string> CWD =
431 VFS.getCurrentWorkingDirectory()) {
432 CmdArgs.push_back(Args.MakeArgString("-fdebug-compilation-dir=" + *CWD));
433 }
434 StringRef Path(CmdArgs.back());
435 return Path.substr(Path.find('=') + 1).data();
436}
437
438static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
439 const char *DebugCompilationDir,
440 const char *OutputFileName) {
441 // No need to generate a value for -object-file-name if it was provided.
442 for (auto *Arg : Args.filtered(options::OPT_Xclang))
443 if (StringRef(Arg->getValue()).starts_with("-object-file-name"))
444 return;
445
446 if (Args.hasArg(options::OPT_object_file_name_EQ))
447 return;
448
449 SmallString<128> ObjFileNameForDebug(OutputFileName);
450 if (ObjFileNameForDebug != "-" &&
451 !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
452 (!DebugCompilationDir ||
453 llvm::sys::path::is_absolute(DebugCompilationDir))) {
454 // Make the path absolute in the debug infos like MSVC does.
455 llvm::sys::fs::make_absolute(ObjFileNameForDebug);
456 }
457 // If the object file name is a relative path, then always use Windows
458 // backslash style as -object-file-name is used for embedding object file path
459 // in codeview and it can only be generated when targeting on Windows.
460 // Otherwise, just use native absolute path.
461 llvm::sys::path::Style Style =
462 llvm::sys::path::is_absolute(ObjFileNameForDebug)
463 ? llvm::sys::path::Style::native
464 : llvm::sys::path::Style::windows_backslash;
465 llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,
466 Style);
467 CmdArgs.push_back(
468 Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
469}
470
471/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
472static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
473 const ArgList &Args, ArgStringList &CmdArgs) {
474 auto AddOneArg = [&](StringRef Map, StringRef Name) {
475 if (!Map.contains('='))
476 D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
477 else
478 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
479 };
480
481 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
482 options::OPT_fdebug_prefix_map_EQ)) {
483 AddOneArg(A->getValue(), A->getOption().getName());
484 A->claim();
485 }
486 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
487 if (GlobalRemapEntry.empty())
488 return;
489 AddOneArg(GlobalRemapEntry, "environment");
490}
491
492/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
493static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
494 ArgStringList &CmdArgs) {
495 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
496 options::OPT_fmacro_prefix_map_EQ)) {
497 StringRef Map = A->getValue();
498 if (!Map.contains('='))
499 D.Diag(diag::err_drv_invalid_argument_to_option)
500 << Map << A->getOption().getName();
501 else
502 CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
503 A->claim();
504 }
505}
506
507/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
508static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
509 ArgStringList &CmdArgs) {
510 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
511 options::OPT_fcoverage_prefix_map_EQ)) {
512 StringRef Map = A->getValue();
513 if (!Map.contains('='))
514 D.Diag(diag::err_drv_invalid_argument_to_option)
515 << Map << A->getOption().getName();
516 else
517 CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
518 A->claim();
519 }
520}
521
522/// Vectorize at all optimization levels greater than 1 except for -Oz.
523/// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
524/// enabled.
525static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
526 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
527 if (A->getOption().matches(options::OPT_O4) ||
528 A->getOption().matches(options::OPT_Ofast))
529 return true;
530
531 if (A->getOption().matches(options::OPT_O0))
532 return false;
533
534 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
535
536 // Vectorize -Os.
537 StringRef S(A->getValue());
538 if (S == "s")
539 return true;
540
541 // Don't vectorize -Oz, unless it's the slp vectorizer.
542 if (S == "z")
543 return isSlpVec;
544
545 unsigned OptLevel = 0;
546 if (S.getAsInteger(10, OptLevel))
547 return false;
548
549 return OptLevel > 1;
550 }
551
552 return false;
553}
554
555/// Add -x lang to \p CmdArgs for \p Input.
556static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
557 ArgStringList &CmdArgs) {
558 // When using -verify-pch, we don't want to provide the type
559 // 'precompiled-header' if it was inferred from the file extension
560 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
561 return;
562
563 CmdArgs.push_back("-x");
564 if (Args.hasArg(options::OPT_rewrite_objc))
565 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
566 else {
567 // Map the driver type to the frontend type. This is mostly an identity
568 // mapping, except that the distinction between module interface units
569 // and other source files does not exist at the frontend layer.
570 const char *ClangType;
571 switch (Input.getType()) {
572 case types::TY_CXXModule:
573 ClangType = "c++";
574 break;
575 case types::TY_PP_CXXModule:
576 ClangType = "c++-cpp-output";
577 break;
578 default:
579 ClangType = types::getTypeName(Input.getType());
580 break;
581 }
582 CmdArgs.push_back(ClangType);
583 }
584}
585
587 const JobAction &JA, const InputInfo &Output,
588 const ArgList &Args, SanitizerArgs &SanArgs,
589 ArgStringList &CmdArgs) {
590 const Driver &D = TC.getDriver();
591 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
592 options::OPT_fprofile_generate_EQ,
593 options::OPT_fno_profile_generate);
594 if (PGOGenerateArg &&
595 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
596 PGOGenerateArg = nullptr;
597
598 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
599
600 auto *ProfileGenerateArg = Args.getLastArg(
601 options::OPT_fprofile_instr_generate,
602 options::OPT_fprofile_instr_generate_EQ,
603 options::OPT_fno_profile_instr_generate);
604 if (ProfileGenerateArg &&
605 ProfileGenerateArg->getOption().matches(
606 options::OPT_fno_profile_instr_generate))
607 ProfileGenerateArg = nullptr;
608
609 if (PGOGenerateArg && ProfileGenerateArg)
610 D.Diag(diag::err_drv_argument_not_allowed_with)
611 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
612
613 auto *ProfileUseArg = getLastProfileUseArg(Args);
614
615 if (PGOGenerateArg && ProfileUseArg)
616 D.Diag(diag::err_drv_argument_not_allowed_with)
617 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
618
619 if (ProfileGenerateArg && ProfileUseArg)
620 D.Diag(diag::err_drv_argument_not_allowed_with)
621 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
622
623 if (CSPGOGenerateArg && PGOGenerateArg) {
624 D.Diag(diag::err_drv_argument_not_allowed_with)
625 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
626 PGOGenerateArg = nullptr;
627 }
628
629 if (TC.getTriple().isOSAIX()) {
630 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
631 D.Diag(diag::err_drv_unsupported_opt_for_target)
632 << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
633 }
634
635 if (ProfileGenerateArg) {
636 if (ProfileGenerateArg->getOption().matches(
637 options::OPT_fprofile_instr_generate_EQ))
638 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
639 ProfileGenerateArg->getValue()));
640 // The default is to use Clang Instrumentation.
641 CmdArgs.push_back("-fprofile-instrument=clang");
642 if (TC.getTriple().isWindowsMSVCEnvironment() &&
643 Args.hasFlag(options::OPT_frtlib_defaultlib,
644 options::OPT_fno_rtlib_defaultlib, true)) {
645 // Add dependent lib for clang_rt.profile
646 CmdArgs.push_back(Args.MakeArgString(
647 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
648 }
649 }
650
651 Arg *PGOGenArg = nullptr;
652 if (PGOGenerateArg) {
653 assert(!CSPGOGenerateArg);
654 PGOGenArg = PGOGenerateArg;
655 CmdArgs.push_back("-fprofile-instrument=llvm");
656 }
657 if (CSPGOGenerateArg) {
658 assert(!PGOGenerateArg);
659 PGOGenArg = CSPGOGenerateArg;
660 CmdArgs.push_back("-fprofile-instrument=csllvm");
661 }
662 if (PGOGenArg) {
663 if (TC.getTriple().isWindowsMSVCEnvironment() &&
664 Args.hasFlag(options::OPT_frtlib_defaultlib,
665 options::OPT_fno_rtlib_defaultlib, true)) {
666 // Add dependent lib for clang_rt.profile
667 CmdArgs.push_back(Args.MakeArgString(
668 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
669 }
670 if (PGOGenArg->getOption().matches(
671 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
672 : options::OPT_fcs_profile_generate_EQ)) {
673 SmallString<128> Path(PGOGenArg->getValue());
674 llvm::sys::path::append(Path, "default_%m.profraw");
675 CmdArgs.push_back(
676 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
677 }
678 }
679
680 if (ProfileUseArg) {
681 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
682 CmdArgs.push_back(Args.MakeArgString(
683 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
684 else if ((ProfileUseArg->getOption().matches(
685 options::OPT_fprofile_use_EQ) ||
686 ProfileUseArg->getOption().matches(
687 options::OPT_fprofile_instr_use))) {
688 SmallString<128> Path(
689 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
690 if (Path.empty() || llvm::sys::fs::is_directory(Path))
691 llvm::sys::path::append(Path, "default.profdata");
692 CmdArgs.push_back(
693 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
694 }
695 }
696
697 bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
698 options::OPT_fno_test_coverage, false) ||
699 Args.hasArg(options::OPT_coverage);
700 bool EmitCovData = TC.needsGCovInstrumentation(Args);
701
702 if (Args.hasFlag(options::OPT_fcoverage_mapping,
703 options::OPT_fno_coverage_mapping, false)) {
704 if (!ProfileGenerateArg)
705 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
706 << "-fcoverage-mapping"
707 << "-fprofile-instr-generate";
708
709 CmdArgs.push_back("-fcoverage-mapping");
710 }
711
712 if (Args.hasFlag(options::OPT_fmcdc_coverage, options::OPT_fno_mcdc_coverage,
713 false)) {
714 if (!Args.hasFlag(options::OPT_fcoverage_mapping,
715 options::OPT_fno_coverage_mapping, false))
716 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
717 << "-fcoverage-mcdc"
718 << "-fcoverage-mapping";
719
720 CmdArgs.push_back("-fcoverage-mcdc");
721 }
722
723 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
724 options::OPT_fcoverage_compilation_dir_EQ)) {
725 if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
726 CmdArgs.push_back(Args.MakeArgString(
727 Twine("-fcoverage-compilation-dir=") + A->getValue()));
728 else
729 A->render(Args, CmdArgs);
730 } else if (llvm::ErrorOr<std::string> CWD =
731 D.getVFS().getCurrentWorkingDirectory()) {
732 CmdArgs.push_back(Args.MakeArgString("-fcoverage-compilation-dir=" + *CWD));
733 }
734
735 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
736 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
737 if (!Args.hasArg(options::OPT_coverage))
738 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
739 << "-fprofile-exclude-files="
740 << "--coverage";
741
742 StringRef v = Arg->getValue();
743 CmdArgs.push_back(
744 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
745 }
746
747 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
748 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
749 if (!Args.hasArg(options::OPT_coverage))
750 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
751 << "-fprofile-filter-files="
752 << "--coverage";
753
754 StringRef v = Arg->getValue();
755 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
756 }
757
758 if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
759 StringRef Val = A->getValue();
760 if (Val == "atomic" || Val == "prefer-atomic")
761 CmdArgs.push_back("-fprofile-update=atomic");
762 else if (Val != "single")
763 D.Diag(diag::err_drv_unsupported_option_argument)
764 << A->getSpelling() << Val;
765 }
766
767 int FunctionGroups = 1;
768 int SelectedFunctionGroup = 0;
769 if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
770 StringRef Val = A->getValue();
771 if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
772 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
773 }
774 if (const auto *A =
775 Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
776 StringRef Val = A->getValue();
777 if (Val.getAsInteger(0, SelectedFunctionGroup) ||
778 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
779 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
780 }
781 if (FunctionGroups != 1)
782 CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
783 Twine(FunctionGroups)));
784 if (SelectedFunctionGroup != 0)
785 CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
786 Twine(SelectedFunctionGroup)));
787
788 // Leave -fprofile-dir= an unused argument unless .gcda emission is
789 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
790 // the flag used. There is no -fno-profile-dir, so the user has no
791 // targeted way to suppress the warning.
792 Arg *FProfileDir = nullptr;
793 if (Args.hasArg(options::OPT_fprofile_arcs) ||
794 Args.hasArg(options::OPT_coverage))
795 FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
796
797 // TODO: Don't claim -c/-S to warn about -fsyntax-only -c/-S, -E -c/-S,
798 // like we warn about -fsyntax-only -E.
799 (void)(Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S));
800
801 // Put the .gcno and .gcda files (if needed) next to the primary output file,
802 // or fall back to a file in the current directory for `clang -c --coverage
803 // d/a.c` in the absence of -o.
804 if (EmitCovNotes || EmitCovData) {
805 SmallString<128> CoverageFilename;
806 if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
807 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
808 // path separator.
809 CoverageFilename = DumpDir->getValue();
810 CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
811 } else if (Arg *FinalOutput =
812 C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
813 CoverageFilename = FinalOutput->getValue();
814 } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
815 CoverageFilename = FinalOutput->getValue();
816 } else {
817 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
818 }
819 if (llvm::sys::path::is_relative(CoverageFilename))
820 (void)D.getVFS().makeAbsolute(CoverageFilename);
821 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
822 if (EmitCovNotes) {
823 CmdArgs.push_back(
824 Args.MakeArgString("-coverage-notes-file=" + CoverageFilename));
825 }
826
827 if (EmitCovData) {
828 if (FProfileDir) {
829 SmallString<128> Gcno = std::move(CoverageFilename);
830 CoverageFilename = FProfileDir->getValue();
831 llvm::sys::path::append(CoverageFilename, Gcno);
832 }
833 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
834 CmdArgs.push_back(
835 Args.MakeArgString("-coverage-data-file=" + CoverageFilename));
836 }
837 }
838}
839
840static void
841RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
842 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
843 unsigned DwarfVersion,
844 llvm::DebuggerKind DebuggerTuning) {
845 addDebugInfoKind(CmdArgs, DebugInfoKind);
846 if (DwarfVersion > 0)
847 CmdArgs.push_back(
848 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
849 switch (DebuggerTuning) {
850 case llvm::DebuggerKind::GDB:
851 CmdArgs.push_back("-debugger-tuning=gdb");
852 break;
853 case llvm::DebuggerKind::LLDB:
854 CmdArgs.push_back("-debugger-tuning=lldb");
855 break;
856 case llvm::DebuggerKind::SCE:
857 CmdArgs.push_back("-debugger-tuning=sce");
858 break;
859 case llvm::DebuggerKind::DBX:
860 CmdArgs.push_back("-debugger-tuning=dbx");
861 break;
862 default:
863 break;
864 }
865}
866
867static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
868 const Driver &D, const ToolChain &TC) {
869 assert(A && "Expected non-nullptr argument.");
870 if (TC.supportsDebugInfoOption(A))
871 return true;
872 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
873 << A->getAsString(Args) << TC.getTripleString();
874 return false;
875}
876
877static void RenderDebugInfoCompressionArgs(const ArgList &Args,
878 ArgStringList &CmdArgs,
879 const Driver &D,
880 const ToolChain &TC) {
881 const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
882 if (!A)
883 return;
884 if (checkDebugInfoOption(A, Args, D, TC)) {
885 StringRef Value = A->getValue();
886 if (Value == "none") {
887 CmdArgs.push_back("--compress-debug-sections=none");
888 } else if (Value == "zlib") {
889 if (llvm::compression::zlib::isAvailable()) {
890 CmdArgs.push_back(
891 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
892 } else {
893 D.Diag(diag::warn_debug_compression_unavailable) << "zlib";
894 }
895 } else if (Value == "zstd") {
896 if (llvm::compression::zstd::isAvailable()) {
897 CmdArgs.push_back(
898 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
899 } else {
900 D.Diag(diag::warn_debug_compression_unavailable) << "zstd";
901 }
902 } else {
903 D.Diag(diag::err_drv_unsupported_option_argument)
904 << A->getSpelling() << Value;
905 }
906 }
907}
908
910 const ArgList &Args,
911 ArgStringList &CmdArgs,
912 bool IsCC1As = false) {
913 // If no version was requested by the user, use the default value from the
914 // back end. This is consistent with the value returned from
915 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
916 // requiring the corresponding llvm to have the AMDGPU target enabled,
917 // provided the user (e.g. front end tests) can use the default.
919 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
920 CmdArgs.insert(CmdArgs.begin() + 1,
921 Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
922 Twine(CodeObjVer)));
923 CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
924 // -cc1as does not accept -mcode-object-version option.
925 if (!IsCC1As)
926 CmdArgs.insert(CmdArgs.begin() + 1,
927 Args.MakeArgString(Twine("-mcode-object-version=") +
928 Twine(CodeObjVer)));
929 }
930}
931
932static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
933 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
934 D.getVFS().getBufferForFile(Path);
935 if (!MemBuf)
936 return false;
937 llvm::file_magic Magic = llvm::identify_magic((*MemBuf)->getBuffer());
938 if (Magic == llvm::file_magic::unknown)
939 return false;
940 // Return true for both raw Clang AST files and object files which may
941 // contain a __clangast section.
942 if (Magic == llvm::file_magic::clang_ast)
943 return true;
945 llvm::object::ObjectFile::createObjectFile(**MemBuf, Magic);
946 return !Obj.takeError();
947}
948
949static bool gchProbe(const Driver &D, StringRef Path) {
950 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
951 if (!Status)
952 return false;
953
954 if (Status->isDirectory()) {
955 std::error_code EC;
956 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Path, EC), DE;
957 !EC && DI != DE; DI = DI.increment(EC)) {
958 if (maybeHasClangPchSignature(D, DI->path()))
959 return true;
960 }
961 D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;
962 return false;
963 }
964
965 if (maybeHasClangPchSignature(D, Path))
966 return true;
967 D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;
968 return false;
969}
970
971void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
972 const Driver &D, const ArgList &Args,
973 ArgStringList &CmdArgs,
974 const InputInfo &Output,
975 const InputInfoList &Inputs) const {
976 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
977
979
980 Args.AddLastArg(CmdArgs, options::OPT_C);
981 Args.AddLastArg(CmdArgs, options::OPT_CC);
982
983 // Handle dependency file generation.
984 Arg *ArgM = Args.getLastArg(options::OPT_MM);
985 if (!ArgM)
986 ArgM = Args.getLastArg(options::OPT_M);
987 Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
988 if (!ArgMD)
989 ArgMD = Args.getLastArg(options::OPT_MD);
990
991 // -M and -MM imply -w.
992 if (ArgM)
993 CmdArgs.push_back("-w");
994 else
995 ArgM = ArgMD;
996
997 if (ArgM) {
998 // Determine the output location.
999 const char *DepFile;
1000 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1001 DepFile = MF->getValue();
1002 C.addFailureResultFile(DepFile, &JA);
1003 } else if (Output.getType() == types::TY_Dependencies) {
1004 DepFile = Output.getFilename();
1005 } else if (!ArgMD) {
1006 DepFile = "-";
1007 } else {
1008 DepFile = getDependencyFileName(Args, Inputs);
1009 C.addFailureResultFile(DepFile, &JA);
1010 }
1011 CmdArgs.push_back("-dependency-file");
1012 CmdArgs.push_back(DepFile);
1013
1014 bool HasTarget = false;
1015 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1016 HasTarget = true;
1017 A->claim();
1018 if (A->getOption().matches(options::OPT_MT)) {
1019 A->render(Args, CmdArgs);
1020 } else {
1021 CmdArgs.push_back("-MT");
1023 quoteMakeTarget(A->getValue(), Quoted);
1024 CmdArgs.push_back(Args.MakeArgString(Quoted));
1025 }
1026 }
1027
1028 // Add a default target if one wasn't specified.
1029 if (!HasTarget) {
1030 const char *DepTarget;
1031
1032 // If user provided -o, that is the dependency target, except
1033 // when we are only generating a dependency file.
1034 Arg *OutputOpt = Args.getLastArg(options::OPT_o, options::OPT__SLASH_Fo);
1035 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1036 DepTarget = OutputOpt->getValue();
1037 } else {
1038 // Otherwise derive from the base input.
1039 //
1040 // FIXME: This should use the computed output file location.
1041 SmallString<128> P(Inputs[0].getBaseInput());
1042 llvm::sys::path::replace_extension(P, "o");
1043 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1044 }
1045
1046 CmdArgs.push_back("-MT");
1048 quoteMakeTarget(DepTarget, Quoted);
1049 CmdArgs.push_back(Args.MakeArgString(Quoted));
1050 }
1051
1052 if (ArgM->getOption().matches(options::OPT_M) ||
1053 ArgM->getOption().matches(options::OPT_MD))
1054 CmdArgs.push_back("-sys-header-deps");
1055 if ((isa<PrecompileJobAction>(JA) &&
1056 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1057 Args.hasArg(options::OPT_fmodule_file_deps))
1058 CmdArgs.push_back("-module-file-deps");
1059 }
1060
1061 if (Args.hasArg(options::OPT_MG)) {
1062 if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
1063 ArgM->getOption().matches(options::OPT_MMD))
1064 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1065 CmdArgs.push_back("-MG");
1066 }
1067
1068 Args.AddLastArg(CmdArgs, options::OPT_MP);
1069 Args.AddLastArg(CmdArgs, options::OPT_MV);
1070
1071 // Add offload include arguments specific for CUDA/HIP. This must happen
1072 // before we -I or -include anything else, because we must pick up the
1073 // CUDA/HIP headers from the particular CUDA/ROCm installation, rather than
1074 // from e.g. /usr/local/include.
1076 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1078 getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
1079
1080 // If we are compiling for a GPU target we want to override the system headers
1081 // with ones created by the 'libc' project if present.
1082 if (!Args.hasArg(options::OPT_nostdinc) &&
1083 !Args.hasArg(options::OPT_nogpuinc) &&
1084 !Args.hasArg(options::OPT_nobuiltininc)) {
1085 // Without an offloading language we will include these headers directly.
1086 // Offloading languages will instead only use the declarations stored in
1087 // the resource directory at clang/lib/Headers/llvm_libc_wrappers.
1088 if ((getToolChain().getTriple().isNVPTX() ||
1089 getToolChain().getTriple().isAMDGCN()) &&
1090 C.getActiveOffloadKinds() == Action::OFK_None) {
1091 SmallString<128> P(llvm::sys::path::parent_path(D.Dir));
1092 llvm::sys::path::append(P, "include");
1093 llvm::sys::path::append(P, getToolChain().getTripleString());
1094 CmdArgs.push_back("-internal-isystem");
1095 CmdArgs.push_back(Args.MakeArgString(P));
1096 } else if (C.getActiveOffloadKinds() == Action::OFK_OpenMP) {
1097 // TODO: CUDA / HIP include their own headers for some common functions
1098 // implemented here. We'll need to clean those up so they do not conflict.
1100 llvm::sys::path::append(P, "include");
1101 llvm::sys::path::append(P, "llvm_libc_wrappers");
1102 CmdArgs.push_back("-internal-isystem");
1103 CmdArgs.push_back(Args.MakeArgString(P));
1104 }
1105 }
1106
1107 // If we are offloading to a target via OpenMP we need to include the
1108 // openmp_wrappers folder which contains alternative system headers.
1110 !Args.hasArg(options::OPT_nostdinc) &&
1111 !Args.hasArg(options::OPT_nogpuinc) &&
1112 (getToolChain().getTriple().isNVPTX() ||
1113 getToolChain().getTriple().isAMDGCN())) {
1114 if (!Args.hasArg(options::OPT_nobuiltininc)) {
1115 // Add openmp_wrappers/* to our system include path. This lets us wrap
1116 // standard library headers.
1118 llvm::sys::path::append(P, "include");
1119 llvm::sys::path::append(P, "openmp_wrappers");
1120 CmdArgs.push_back("-internal-isystem");
1121 CmdArgs.push_back(Args.MakeArgString(P));
1122 }
1123
1124 CmdArgs.push_back("-include");
1125 CmdArgs.push_back("__clang_openmp_device_functions.h");
1126 }
1127
1128 // Add -i* options, and automatically translate to
1129 // -include-pch/-include-pth for transparent PCH support. It's
1130 // wonky, but we include looking for .gch so we can support seamless
1131 // replacement into a build system already set up to be generating
1132 // .gch files.
1133
1134 if (getToolChain().getDriver().IsCLMode()) {
1135 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1136 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1137 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1139 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1140 // -fpch-instantiate-templates is the default when creating
1141 // precomp using /Yc
1142 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1143 options::OPT_fno_pch_instantiate_templates, true))
1144 CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1145 }
1146 if (YcArg || YuArg) {
1147 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1148 if (!isa<PrecompileJobAction>(JA)) {
1149 CmdArgs.push_back("-include-pch");
1150 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1151 C, !ThroughHeader.empty()
1152 ? ThroughHeader
1153 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1154 }
1155
1156 if (ThroughHeader.empty()) {
1157 CmdArgs.push_back(Args.MakeArgString(
1158 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1159 } else {
1160 CmdArgs.push_back(
1161 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1162 }
1163 }
1164 }
1165
1166 bool RenderedImplicitInclude = false;
1167 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1168 if (A->getOption().matches(options::OPT_include) &&
1169 D.getProbePrecompiled()) {
1170 // Handling of gcc-style gch precompiled headers.
1171 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1172 RenderedImplicitInclude = true;
1173
1174 bool FoundPCH = false;
1175 SmallString<128> P(A->getValue());
1176 // We want the files to have a name like foo.h.pch. Add a dummy extension
1177 // so that replace_extension does the right thing.
1178 P += ".dummy";
1179 llvm::sys::path::replace_extension(P, "pch");
1180 if (D.getVFS().exists(P))
1181 FoundPCH = true;
1182
1183 if (!FoundPCH) {
1184 // For GCC compat, probe for a file or directory ending in .gch instead.
1185 llvm::sys::path::replace_extension(P, "gch");
1186 FoundPCH = gchProbe(D, P.str());
1187 }
1188
1189 if (FoundPCH) {
1190 if (IsFirstImplicitInclude) {
1191 A->claim();
1192 CmdArgs.push_back("-include-pch");
1193 CmdArgs.push_back(Args.MakeArgString(P));
1194 continue;
1195 } else {
1196 // Ignore the PCH if not first on command line and emit warning.
1197 D.Diag(diag::warn_drv_pch_not_first_include) << P
1198 << A->getAsString(Args);
1199 }
1200 }
1201 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1202 // Handling of paths which must come late. These entries are handled by
1203 // the toolchain itself after the resource dir is inserted in the right
1204 // search order.
1205 // Do not claim the argument so that the use of the argument does not
1206 // silently go unnoticed on toolchains which do not honour the option.
1207 continue;
1208 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1209 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1210 continue;
1211 } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
1212 // This is used only by the driver. No need to pass to cc1.
1213 continue;
1214 }
1215
1216 // Not translated, render as usual.
1217 A->claim();
1218 A->render(Args, CmdArgs);
1219 }
1220
1221 Args.addAllArgs(CmdArgs,
1222 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1223 options::OPT_F, options::OPT_index_header_map});
1224
1225 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1226
1227 // FIXME: There is a very unfortunate problem here, some troubled
1228 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1229 // really support that we would have to parse and then translate
1230 // those options. :(
1231 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1232 options::OPT_Xpreprocessor);
1233
1234 // -I- is a deprecated GCC feature, reject it.
1235 if (Arg *A = Args.getLastArg(options::OPT_I_))
1236 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1237
1238 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1239 // -isysroot to the CC1 invocation.
1240 StringRef sysroot = C.getSysRoot();
1241 if (sysroot != "") {
1242 if (!Args.hasArg(options::OPT_isysroot)) {
1243 CmdArgs.push_back("-isysroot");
1244 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1245 }
1246 }
1247
1248 // Parse additional include paths from environment variables.
1249 // FIXME: We should probably sink the logic for handling these from the
1250 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1251 // CPATH - included following the user specified includes (but prior to
1252 // builtin and standard includes).
1253 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1254 // C_INCLUDE_PATH - system includes enabled when compiling C.
1255 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1256 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1257 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1258 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1259 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1260 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1261 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1262
1263 // While adding the include arguments, we also attempt to retrieve the
1264 // arguments of related offloading toolchains or arguments that are specific
1265 // of an offloading programming model.
1266
1267 // Add C++ include arguments, if needed.
1268 if (types::isCXX(Inputs[0].getType())) {
1269 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1271 C, JA, getToolChain(),
1272 [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1273 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1274 : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1275 });
1276 }
1277
1278 // Add system include arguments for all targets but IAMCU.
1279 if (!IsIAMCU)
1281 [&Args, &CmdArgs](const ToolChain &TC) {
1282 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1283 });
1284 else {
1285 // For IAMCU add special include arguments.
1286 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1287 }
1288
1289 addMacroPrefixMapArg(D, Args, CmdArgs);
1290 addCoveragePrefixMapArg(D, Args, CmdArgs);
1291
1292 Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
1293 options::OPT_fno_file_reproducible);
1294
1295 if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1296 CmdArgs.push_back("-source-date-epoch");
1297 CmdArgs.push_back(Args.MakeArgString(Epoch));
1298 }
1299
1300 Args.addOptInFlag(CmdArgs, options::OPT_fdefine_target_os_macros,
1301 options::OPT_fno_define_target_os_macros);
1302}
1303
1304// FIXME: Move to target hook.
1305static bool isSignedCharDefault(const llvm::Triple &Triple) {
1306 switch (Triple.getArch()) {
1307 default:
1308 return true;
1309
1310 case llvm::Triple::aarch64:
1311 case llvm::Triple::aarch64_32:
1312 case llvm::Triple::aarch64_be:
1313 case llvm::Triple::arm:
1314 case llvm::Triple::armeb:
1315 case llvm::Triple::thumb:
1316 case llvm::Triple::thumbeb:
1317 if (Triple.isOSDarwin() || Triple.isOSWindows())
1318 return true;
1319 return false;
1320
1321 case llvm::Triple::ppc:
1322 case llvm::Triple::ppc64:
1323 if (Triple.isOSDarwin())
1324 return true;
1325 return false;
1326
1327 case llvm::Triple::hexagon:
1328 case llvm::Triple::ppcle:
1329 case llvm::Triple::ppc64le:
1330 case llvm::Triple::riscv32:
1331 case llvm::Triple::riscv64:
1332 case llvm::Triple::systemz:
1333 case llvm::Triple::xcore:
1334 return false;
1335 }
1336}
1337
1338static bool hasMultipleInvocations(const llvm::Triple &Triple,
1339 const ArgList &Args) {
1340 // Supported only on Darwin where we invoke the compiler multiple times
1341 // followed by an invocation to lipo.
1342 if (!Triple.isOSDarwin())
1343 return false;
1344 // If more than one "-arch <arch>" is specified, we're targeting multiple
1345 // architectures resulting in a fat binary.
1346 return Args.getAllArgValues(options::OPT_arch).size() > 1;
1347}
1348
1349static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1350 const llvm::Triple &Triple) {
1351 // When enabling remarks, we need to error if:
1352 // * The remark file is specified but we're targeting multiple architectures,
1353 // which means more than one remark file is being generated.
1355 bool hasExplicitOutputFile =
1356 Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1357 if (hasMultipleInvocations && hasExplicitOutputFile) {
1358 D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1359 << "-foptimization-record-file";
1360 return false;
1361 }
1362 return true;
1363}
1364
1365static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1366 const llvm::Triple &Triple,
1367 const InputInfo &Input,
1368 const InputInfo &Output, const JobAction &JA) {
1369 StringRef Format = "yaml";
1370 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1371 Format = A->getValue();
1372
1373 CmdArgs.push_back("-opt-record-file");
1374
1375 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1376 if (A) {
1377 CmdArgs.push_back(A->getValue());
1378 } else {
1379 bool hasMultipleArchs =
1380 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1381 Args.getAllArgValues(options::OPT_arch).size() > 1;
1382
1384
1385 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1386 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1387 F = FinalOutput->getValue();
1388 } else {
1389 if (Format != "yaml" && // For YAML, keep the original behavior.
1390 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1391 Output.isFilename())
1392 F = Output.getFilename();
1393 }
1394
1395 if (F.empty()) {
1396 // Use the input filename.
1397 F = llvm::sys::path::stem(Input.getBaseInput());
1398
1399 // If we're compiling for an offload architecture (i.e. a CUDA device),
1400 // we need to make the file name for the device compilation different
1401 // from the host compilation.
1404 llvm::sys::path::replace_extension(F, "");
1406 Triple.normalize());
1407 F += "-";
1408 F += JA.getOffloadingArch();
1409 }
1410 }
1411
1412 // If we're having more than one "-arch", we should name the files
1413 // differently so that every cc1 invocation writes to a different file.
1414 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1415 // name from the triple.
1416 if (hasMultipleArchs) {
1417 // First, remember the extension.
1418 SmallString<64> OldExtension = llvm::sys::path::extension(F);
1419 // then, remove it.
1420 llvm::sys::path::replace_extension(F, "");
1421 // attach -<arch> to it.
1422 F += "-";
1423 F += Triple.getArchName();
1424 // put back the extension.
1425 llvm::sys::path::replace_extension(F, OldExtension);
1426 }
1427
1428 SmallString<32> Extension;
1429 Extension += "opt.";
1430 Extension += Format;
1431
1432 llvm::sys::path::replace_extension(F, Extension);
1433 CmdArgs.push_back(Args.MakeArgString(F));
1434 }
1435
1436 if (const Arg *A =
1437 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1438 CmdArgs.push_back("-opt-record-passes");
1439 CmdArgs.push_back(A->getValue());
1440 }
1441
1442 if (!Format.empty()) {
1443 CmdArgs.push_back("-opt-record-format");
1444 CmdArgs.push_back(Format.data());
1445 }
1446}
1447
1448void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1449 if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1450 options::OPT_fno_aapcs_bitfield_width, true))
1451 CmdArgs.push_back("-fno-aapcs-bitfield-width");
1452
1453 if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1454 CmdArgs.push_back("-faapcs-bitfield-load");
1455}
1456
1457namespace {
1458void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1459 const ArgList &Args, ArgStringList &CmdArgs) {
1460 // Select the ABI to use.
1461 // FIXME: Support -meabi.
1462 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1463 const char *ABIName = nullptr;
1464 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1465 ABIName = A->getValue();
1466 } else {
1467 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
1468 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
1469 }
1470
1471 CmdArgs.push_back("-target-abi");
1472 CmdArgs.push_back(ABIName);
1473}
1474
1475void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1476 auto StrictAlignIter =
1477 llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
1478 return Arg == "+strict-align" || Arg == "-strict-align";
1479 });
1480 if (StrictAlignIter != CmdArgs.rend() &&
1481 StringRef(*StrictAlignIter) == "+strict-align")
1482 CmdArgs.push_back("-Wunaligned-access");
1483}
1484}
1485
1486static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1487 ArgStringList &CmdArgs, bool isAArch64) {
1488 const Arg *A = isAArch64
1489 ? Args.getLastArg(options::OPT_msign_return_address_EQ,
1490 options::OPT_mbranch_protection_EQ)
1491 : Args.getLastArg(options::OPT_mbranch_protection_EQ);
1492 if (!A)
1493 return;
1494
1495 const Driver &D = TC.getDriver();
1496 const llvm::Triple &Triple = TC.getEffectiveTriple();
1497 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1498 D.Diag(diag::warn_incompatible_branch_protection_option)
1499 << Triple.getArchName();
1500
1501 StringRef Scope, Key;
1502 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1503
1504 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1505 Scope = A->getValue();
1506 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1507 D.Diag(diag::err_drv_unsupported_option_argument)
1508 << A->getSpelling() << Scope;
1509 Key = "a_key";
1510 IndirectBranches = false;
1511 BranchProtectionPAuthLR = false;
1512 GuardedControlStack = false;
1513 } else {
1514 StringRef DiagMsg;
1515 llvm::ARM::ParsedBranchProtection PBP;
1516 bool EnablePAuthLR = false;
1517
1518 // To know if we need to enable PAuth-LR As part of the standard branch
1519 // protection option, it needs to be determined if the feature has been
1520 // activated in the `march` argument. This information is stored within the
1521 // CmdArgs variable and can be found using a search.
1522 if (isAArch64) {
1523 auto isPAuthLR = [](const char *member) {
1524 llvm::AArch64::ExtensionInfo pauthlr_extension =
1525 llvm::AArch64::getExtensionByID(llvm::AArch64::AEK_PAUTHLR);
1526 return pauthlr_extension.Feature == member;
1527 };
1528
1529 if (std::any_of(CmdArgs.begin(), CmdArgs.end(), isPAuthLR))
1530 EnablePAuthLR = true;
1531 }
1532 if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg,
1533 EnablePAuthLR))
1534 D.Diag(diag::err_drv_unsupported_option_argument)
1535 << A->getSpelling() << DiagMsg;
1536 if (!isAArch64 && PBP.Key == "b_key")
1537 D.Diag(diag::warn_unsupported_branch_protection)
1538 << "b-key" << A->getAsString(Args);
1539 Scope = PBP.Scope;
1540 Key = PBP.Key;
1541 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1542 IndirectBranches = PBP.BranchTargetEnforcement;
1543 GuardedControlStack = PBP.GuardedControlStack;
1544 }
1545
1546 CmdArgs.push_back(
1547 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1548 if (Scope != "none")
1549 CmdArgs.push_back(
1550 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1551 if (BranchProtectionPAuthLR)
1552 CmdArgs.push_back(
1553 Args.MakeArgString(Twine("-mbranch-protection-pauth-lr")));
1554 if (IndirectBranches)
1555 CmdArgs.push_back("-mbranch-target-enforce");
1556 if (GuardedControlStack)
1557 CmdArgs.push_back("-mguarded-control-stack");
1558}
1559
1560void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1561 ArgStringList &CmdArgs, bool KernelOrKext) const {
1562 RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
1563
1564 // Determine floating point ABI from the options & target defaults.
1566 if (ABI == arm::FloatABI::Soft) {
1567 // Floating point operations and argument passing are soft.
1568 // FIXME: This changes CPP defines, we need -target-soft-float.
1569 CmdArgs.push_back("-msoft-float");
1570 CmdArgs.push_back("-mfloat-abi");
1571 CmdArgs.push_back("soft");
1572 } else if (ABI == arm::FloatABI::SoftFP) {
1573 // Floating point operations are hard, but argument passing is soft.
1574 CmdArgs.push_back("-mfloat-abi");
1575 CmdArgs.push_back("soft");
1576 } else {
1577 // Floating point operations and argument passing are hard.
1578 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1579 CmdArgs.push_back("-mfloat-abi");
1580 CmdArgs.push_back("hard");
1581 }
1582
1583 // Forward the -mglobal-merge option for explicit control over the pass.
1584 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1585 options::OPT_mno_global_merge)) {
1586 CmdArgs.push_back("-mllvm");
1587 if (A->getOption().matches(options::OPT_mno_global_merge))
1588 CmdArgs.push_back("-arm-global-merge=false");
1589 else
1590 CmdArgs.push_back("-arm-global-merge=true");
1591 }
1592
1593 if (!Args.hasFlag(options::OPT_mimplicit_float,
1594 options::OPT_mno_implicit_float, true))
1595 CmdArgs.push_back("-no-implicit-float");
1596
1597 if (Args.getLastArg(options::OPT_mcmse))
1598 CmdArgs.push_back("-mcmse");
1599
1600 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1601
1602 // Enable/disable return address signing and indirect branch targets.
1603 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
1604
1605 AddUnalignedAccessWarning(CmdArgs);
1606}
1607
1608void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1609 const ArgList &Args, bool KernelOrKext,
1610 ArgStringList &CmdArgs) const {
1611 const ToolChain &TC = getToolChain();
1612
1613 // Add the target features
1614 getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1615
1616 // Add target specific flags.
1617 switch (TC.getArch()) {
1618 default:
1619 break;
1620
1621 case llvm::Triple::arm:
1622 case llvm::Triple::armeb:
1623 case llvm::Triple::thumb:
1624 case llvm::Triple::thumbeb:
1625 // Use the effective triple, which takes into account the deployment target.
1626 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1627 break;
1628
1629 case llvm::Triple::aarch64:
1630 case llvm::Triple::aarch64_32:
1631 case llvm::Triple::aarch64_be:
1632 AddAArch64TargetArgs(Args, CmdArgs);
1633 break;
1634
1635 case llvm::Triple::loongarch32:
1636 case llvm::Triple::loongarch64:
1637 AddLoongArchTargetArgs(Args, CmdArgs);
1638 break;
1639
1640 case llvm::Triple::mips:
1641 case llvm::Triple::mipsel:
1642 case llvm::Triple::mips64:
1643 case llvm::Triple::mips64el:
1644 AddMIPSTargetArgs(Args, CmdArgs);
1645 break;
1646
1647 case llvm::Triple::ppc:
1648 case llvm::Triple::ppcle:
1649 case llvm::Triple::ppc64:
1650 case llvm::Triple::ppc64le:
1651 AddPPCTargetArgs(Args, CmdArgs);
1652 break;
1653
1654 case llvm::Triple::riscv32:
1655 case llvm::Triple::riscv64:
1656 AddRISCVTargetArgs(Args, CmdArgs);
1657 break;
1658
1659 case llvm::Triple::sparc:
1660 case llvm::Triple::sparcel:
1661 case llvm::Triple::sparcv9:
1662 AddSparcTargetArgs(Args, CmdArgs);
1663 break;
1664
1665 case llvm::Triple::systemz:
1666 AddSystemZTargetArgs(Args, CmdArgs);
1667 break;
1668
1669 case llvm::Triple::x86:
1670 case llvm::Triple::x86_64:
1671 AddX86TargetArgs(Args, CmdArgs);
1672 break;
1673
1674 case llvm::Triple::lanai:
1675 AddLanaiTargetArgs(Args, CmdArgs);
1676 break;
1677
1678 case llvm::Triple::hexagon:
1679 AddHexagonTargetArgs(Args, CmdArgs);
1680 break;
1681
1682 case llvm::Triple::wasm32:
1683 case llvm::Triple::wasm64:
1684 AddWebAssemblyTargetArgs(Args, CmdArgs);
1685 break;
1686
1687 case llvm::Triple::ve:
1688 AddVETargetArgs(Args, CmdArgs);
1689 break;
1690 }
1691}
1692
1693namespace {
1694void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1695 ArgStringList &CmdArgs) {
1696 const char *ABIName = nullptr;
1697 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1698 ABIName = A->getValue();
1699 else if (Triple.isOSDarwin())
1700 ABIName = "darwinpcs";
1701 else
1702 ABIName = "aapcs";
1703
1704 CmdArgs.push_back("-target-abi");
1705 CmdArgs.push_back(ABIName);
1706}
1707}
1708
1709void Clang::AddAArch64TargetArgs(const ArgList &Args,
1710 ArgStringList &CmdArgs) const {
1711 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1712
1713 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1714 Args.hasArg(options::OPT_mkernel) ||
1715 Args.hasArg(options::OPT_fapple_kext))
1716 CmdArgs.push_back("-disable-red-zone");
1717
1718 if (!Args.hasFlag(options::OPT_mimplicit_float,
1719 options::OPT_mno_implicit_float, true))
1720 CmdArgs.push_back("-no-implicit-float");
1721
1722 RenderAArch64ABI(Triple, Args, CmdArgs);
1723
1724 // Forward the -mglobal-merge option for explicit control over the pass.
1725 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1726 options::OPT_mno_global_merge)) {
1727 CmdArgs.push_back("-mllvm");
1728 if (A->getOption().matches(options::OPT_mno_global_merge))
1729 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1730 else
1731 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1732 }
1733
1734 // Enable/disable return address signing and indirect branch targets.
1735 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1736
1737 // Handle -msve_vector_bits=<bits>
1738 if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
1739 StringRef Val = A->getValue();
1740 const Driver &D = getToolChain().getDriver();
1741 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1742 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1743 Val == "1024+" || Val == "2048+") {
1744 unsigned Bits = 0;
1745 if (!Val.consume_back("+")) {
1746 bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1747 assert(!Invalid && "Failed to parse value");
1748 CmdArgs.push_back(
1749 Args.MakeArgString("-mvscale-max=" + llvm::Twine(Bits / 128)));
1750 }
1751
1752 bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1753 assert(!Invalid && "Failed to parse value");
1754 CmdArgs.push_back(
1755 Args.MakeArgString("-mvscale-min=" + llvm::Twine(Bits / 128)));
1756 // Silently drop requests for vector-length agnostic code as it's implied.
1757 } else if (Val != "scalable")
1758 // Handle the unsupported values passed to msve-vector-bits.
1759 D.Diag(diag::err_drv_unsupported_option_argument)
1760 << A->getSpelling() << Val;
1761 }
1762
1763 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1764
1765 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
1766 CmdArgs.push_back("-tune-cpu");
1767 if (strcmp(A->getValue(), "native") == 0)
1768 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
1769 else
1770 CmdArgs.push_back(A->getValue());
1771 }
1772
1773 AddUnalignedAccessWarning(CmdArgs);
1774
1775 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_intrinsics,
1776 options::OPT_fno_ptrauth_intrinsics);
1777 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_calls,
1778 options::OPT_fno_ptrauth_calls);
1779 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_returns,
1780 options::OPT_fno_ptrauth_returns);
1781 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_auth_traps,
1782 options::OPT_fno_ptrauth_auth_traps);
1783 Args.addOptInFlag(
1784 CmdArgs, options::OPT_fptrauth_vtable_pointer_address_discrimination,
1785 options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1786 Args.addOptInFlag(
1787 CmdArgs, options::OPT_fptrauth_vtable_pointer_type_discrimination,
1788 options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1789 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_init_fini,
1790 options::OPT_fno_ptrauth_init_fini);
1791}
1792
1793void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1794 ArgStringList &CmdArgs) const {
1795 const llvm::Triple &Triple = getToolChain().getTriple();
1796
1797 CmdArgs.push_back("-target-abi");
1798 CmdArgs.push_back(
1799 loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1800 .data());
1801
1802 // Handle -mtune.
1803 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1804 std::string TuneCPU = A->getValue();
1805 TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
1806 CmdArgs.push_back("-tune-cpu");
1807 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
1808 }
1809}
1810
1811void Clang::AddMIPSTargetArgs(const ArgList &Args,
1812 ArgStringList &CmdArgs) const {
1813 const Driver &D = getToolChain().getDriver();
1814 StringRef CPUName;
1815 StringRef ABIName;
1816 const llvm::Triple &Triple = getToolChain().getTriple();
1817 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1818
1819 CmdArgs.push_back("-target-abi");
1820 CmdArgs.push_back(ABIName.data());
1821
1822 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1823 if (ABI == mips::FloatABI::Soft) {
1824 // Floating point operations and argument passing are soft.
1825 CmdArgs.push_back("-msoft-float");
1826 CmdArgs.push_back("-mfloat-abi");
1827 CmdArgs.push_back("soft");
1828 } else {
1829 // Floating point operations and argument passing are hard.
1830 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1831 CmdArgs.push_back("-mfloat-abi");
1832 CmdArgs.push_back("hard");
1833 }
1834
1835 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1836 options::OPT_mno_ldc1_sdc1)) {
1837 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1838 CmdArgs.push_back("-mllvm");
1839 CmdArgs.push_back("-mno-ldc1-sdc1");
1840 }
1841 }
1842
1843 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1844 options::OPT_mno_check_zero_division)) {
1845 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1846 CmdArgs.push_back("-mllvm");
1847 CmdArgs.push_back("-mno-check-zero-division");
1848 }
1849 }
1850
1851 if (Args.getLastArg(options::OPT_mfix4300)) {
1852 CmdArgs.push_back("-mllvm");
1853 CmdArgs.push_back("-mfix4300");
1854 }
1855
1856 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1857 StringRef v = A->getValue();
1858 CmdArgs.push_back("-mllvm");
1859 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1860 A->claim();
1861 }
1862
1863 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1864 Arg *ABICalls =
1865 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1866
1867 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1868 // -mgpopt is the default for static, -fno-pic environments but these two
1869 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1870 // the only case where -mllvm -mgpopt is passed.
1871 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1872 // passed explicitly when compiling something with -mabicalls
1873 // (implictly) in affect. Currently the warning is in the backend.
1874 //
1875 // When the ABI in use is N64, we also need to determine the PIC mode that
1876 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1877 bool NoABICalls =
1878 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1879
1880 llvm::Reloc::Model RelocationModel;
1881 unsigned PICLevel;
1882 bool IsPIE;
1883 std::tie(RelocationModel, PICLevel, IsPIE) =
1884 ParsePICArgs(getToolChain(), Args);
1885
1886 NoABICalls = NoABICalls ||
1887 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1888
1889 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1890 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1891 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1892 CmdArgs.push_back("-mllvm");
1893 CmdArgs.push_back("-mgpopt");
1894
1895 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1896 options::OPT_mno_local_sdata);
1897 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1898 options::OPT_mno_extern_sdata);
1899 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1900 options::OPT_mno_embedded_data);
1901 if (LocalSData) {
1902 CmdArgs.push_back("-mllvm");
1903 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1904 CmdArgs.push_back("-mlocal-sdata=1");
1905 } else {
1906 CmdArgs.push_back("-mlocal-sdata=0");
1907 }
1908 LocalSData->claim();
1909 }
1910
1911 if (ExternSData) {
1912 CmdArgs.push_back("-mllvm");
1913 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1914 CmdArgs.push_back("-mextern-sdata=1");
1915 } else {
1916 CmdArgs.push_back("-mextern-sdata=0");
1917 }
1918 ExternSData->claim();
1919 }
1920
1921 if (EmbeddedData) {
1922 CmdArgs.push_back("-mllvm");
1923 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1924 CmdArgs.push_back("-membedded-data=1");
1925 } else {
1926 CmdArgs.push_back("-membedded-data=0");
1927 }
1928 EmbeddedData->claim();
1929 }
1930
1931 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1932 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1933
1934 if (GPOpt)
1935 GPOpt->claim();
1936
1937 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1938 StringRef Val = StringRef(A->getValue());
1939 if (mips::hasCompactBranches(CPUName)) {
1940 if (Val == "never" || Val == "always" || Val == "optimal") {
1941 CmdArgs.push_back("-mllvm");
1942 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1943 } else
1944 D.Diag(diag::err_drv_unsupported_option_argument)
1945 << A->getSpelling() << Val;
1946 } else
1947 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1948 }
1949
1950 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1951 options::OPT_mno_relax_pic_calls)) {
1952 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1953 CmdArgs.push_back("-mllvm");
1954 CmdArgs.push_back("-mips-jalr-reloc=0");
1955 }
1956 }
1957}
1958
1959void Clang::AddPPCTargetArgs(const ArgList &Args,
1960 ArgStringList &CmdArgs) const {
1961 const Driver &D = getToolChain().getDriver();
1962 const llvm::Triple &T = getToolChain().getTriple();
1963 if (Args.getLastArg(options::OPT_mtune_EQ)) {
1964 CmdArgs.push_back("-tune-cpu");
1965 std::string CPU = ppc::getPPCTuneCPU(Args, T);
1966 CmdArgs.push_back(Args.MakeArgString(CPU));
1967 }
1968
1969 // Select the ABI to use.
1970 const char *ABIName = nullptr;
1971 if (T.isOSBinFormatELF()) {
1972 switch (getToolChain().getArch()) {
1973 case llvm::Triple::ppc64: {
1974 if (T.isPPC64ELFv2ABI())
1975 ABIName = "elfv2";
1976 else
1977 ABIName = "elfv1";
1978 break;
1979 }
1980 case llvm::Triple::ppc64le:
1981 ABIName = "elfv2";
1982 break;
1983 default:
1984 break;
1985 }
1986 }
1987
1988 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
1989 bool VecExtabi = false;
1990 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
1991 StringRef V = A->getValue();
1992 if (V == "ieeelongdouble") {
1993 IEEELongDouble = true;
1994 A->claim();
1995 } else if (V == "ibmlongdouble") {
1996 IEEELongDouble = false;
1997 A->claim();
1998 } else if (V == "vec-default") {
1999 VecExtabi = false;
2000 A->claim();
2001 } else if (V == "vec-extabi") {
2002 VecExtabi = true;
2003 A->claim();
2004 } else if (V == "elfv1") {
2005 ABIName = "elfv1";
2006 A->claim();
2007 } else if (V == "elfv2") {
2008 ABIName = "elfv2";
2009 A->claim();
2010 } else if (V != "altivec")
2011 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
2012 // the option if given as we don't have backend support for any targets
2013 // that don't use the altivec abi.
2014 ABIName = A->getValue();
2015 }
2016 if (IEEELongDouble)
2017 CmdArgs.push_back("-mabi=ieeelongdouble");
2018 if (VecExtabi) {
2019 if (!T.isOSAIX())
2020 D.Diag(diag::err_drv_unsupported_opt_for_target)
2021 << "-mabi=vec-extabi" << T.str();
2022 CmdArgs.push_back("-mabi=vec-extabi");
2023 }
2024
2026 if (FloatABI == ppc::FloatABI::Soft) {
2027 // Floating point operations and argument passing are soft.
2028 CmdArgs.push_back("-msoft-float");
2029 CmdArgs.push_back("-mfloat-abi");
2030 CmdArgs.push_back("soft");
2031 } else {
2032 // Floating point operations and argument passing are hard.
2033 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2034 CmdArgs.push_back("-mfloat-abi");
2035 CmdArgs.push_back("hard");
2036 }
2037
2038 if (ABIName) {
2039 CmdArgs.push_back("-target-abi");
2040 CmdArgs.push_back(ABIName);
2041 }
2042}
2043
2044static void SetRISCVSmallDataLimit(const ToolChain &TC, const ArgList &Args,
2045 ArgStringList &CmdArgs) {
2046 const Driver &D = TC.getDriver();
2047 const llvm::Triple &Triple = TC.getTriple();
2048 // Default small data limitation is eight.
2049 const char *SmallDataLimit = "8";
2050 // Get small data limitation.
2051 if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
2052 options::OPT_fPIC)) {
2053 // Not support linker relaxation for PIC.
2054 SmallDataLimit = "0";
2055 if (Args.hasArg(options::OPT_G)) {
2056 D.Diag(diag::warn_drv_unsupported_sdata);
2057 }
2058 } else if (Args.getLastArgValue(options::OPT_mcmodel_EQ)
2059 .equals_insensitive("large") &&
2060 (Triple.getArch() == llvm::Triple::riscv64)) {
2061 // Not support linker relaxation for RV64 with large code model.
2062 SmallDataLimit = "0";
2063 if (Args.hasArg(options::OPT_G)) {
2064 D.Diag(diag::warn_drv_unsupported_sdata);
2065 }
2066 } else if (Triple.isAndroid()) {
2067 // GP relaxation is not supported on Android.
2068 SmallDataLimit = "0";
2069 if (Args.hasArg(options::OPT_G)) {
2070 D.Diag(diag::warn_drv_unsupported_sdata);
2071 }
2072 } else if (Arg *A = Args.getLastArg(options::OPT_G)) {
2073 SmallDataLimit = A->getValue();
2074 }
2075 // Forward the -msmall-data-limit= option.
2076 CmdArgs.push_back("-msmall-data-limit");
2077 CmdArgs.push_back(SmallDataLimit);
2078}
2079
2080void Clang::AddRISCVTargetArgs(const ArgList &Args,
2081 ArgStringList &CmdArgs) const {
2082 const llvm::Triple &Triple = getToolChain().getTriple();
2083 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2084
2085 CmdArgs.push_back("-target-abi");
2086 CmdArgs.push_back(ABIName.data());
2087
2088 SetRISCVSmallDataLimit(getToolChain(), Args, CmdArgs);
2089
2090 if (!Args.hasFlag(options::OPT_mimplicit_float,
2091 options::OPT_mno_implicit_float, true))
2092 CmdArgs.push_back("-no-implicit-float");
2093
2094 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2095 CmdArgs.push_back("-tune-cpu");
2096 if (strcmp(A->getValue(), "native") == 0)
2097 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2098 else
2099 CmdArgs.push_back(A->getValue());
2100 }
2101
2102 // Handle -mrvv-vector-bits=<bits>
2103 if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
2104 StringRef Val = A->getValue();
2105 const Driver &D = getToolChain().getDriver();
2106
2107 // Get minimum VLen from march.
2108 unsigned MinVLen = 0;
2109 StringRef Arch = riscv::getRISCVArch(Args, Triple);
2110 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2111 Arch, /*EnableExperimentalExtensions*/ true);
2112 // Ignore parsing error.
2113 if (!errorToBool(ISAInfo.takeError()))
2114 MinVLen = (*ISAInfo)->getMinVLen();
2115
2116 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2117 // as integer as long as we have a MinVLen.
2118 unsigned Bits = 0;
2119 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2120 Bits = MinVLen;
2121 } else if (!Val.getAsInteger(10, Bits)) {
2122 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2123 // at least MinVLen.
2124 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2125 Bits > 65536 || !llvm::isPowerOf2_32(Bits))
2126 Bits = 0;
2127 }
2128
2129 // If we got a valid value try to use it.
2130 if (Bits != 0) {
2131 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2132 CmdArgs.push_back(
2133 Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
2134 CmdArgs.push_back(
2135 Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
2136 } else if (Val != "scalable") {
2137 // Handle the unsupported values passed to mrvv-vector-bits.
2138 D.Diag(diag::err_drv_unsupported_option_argument)
2139 << A->getSpelling() << Val;
2140 }
2141 }
2142}
2143
2144void Clang::AddSparcTargetArgs(const ArgList &Args,
2145 ArgStringList &CmdArgs) const {
2147 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2148
2149 if (FloatABI == sparc::FloatABI::Soft) {
2150 // Floating point operations and argument passing are soft.
2151 CmdArgs.push_back("-msoft-float");
2152 CmdArgs.push_back("-mfloat-abi");
2153 CmdArgs.push_back("soft");
2154 } else {
2155 // Floating point operations and argument passing are hard.
2156 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2157 CmdArgs.push_back("-mfloat-abi");
2158 CmdArgs.push_back("hard");
2159 }
2160
2161 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2162 StringRef Name = A->getValue();
2163 std::string TuneCPU;
2164 if (Name == "native")
2165 TuneCPU = std::string(llvm::sys::getHostCPUName());
2166 else
2167 TuneCPU = std::string(Name);
2168
2169 CmdArgs.push_back("-tune-cpu");
2170 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2171 }
2172}
2173
2174void Clang::AddSystemZTargetArgs(const ArgList &Args,
2175 ArgStringList &CmdArgs) const {
2176 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2177 CmdArgs.push_back("-tune-cpu");
2178 if (strcmp(A->getValue(), "native") == 0)
2179 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2180 else
2181 CmdArgs.push_back(A->getValue());
2182 }
2183
2184 bool HasBackchain =
2185 Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2186 bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2187 options::OPT_mno_packed_stack, false);
2189 systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2190 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2191 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2192 const Driver &D = getToolChain().getDriver();
2193 D.Diag(diag::err_drv_unsupported_opt)
2194 << "-mpacked-stack -mbackchain -mhard-float";
2195 }
2196 if (HasBackchain)
2197 CmdArgs.push_back("-mbackchain");
2198 if (HasPackedStack)
2199 CmdArgs.push_back("-mpacked-stack");
2200 if (HasSoftFloat) {
2201 // Floating point operations and argument passing are soft.
2202 CmdArgs.push_back("-msoft-float");
2203 CmdArgs.push_back("-mfloat-abi");
2204 CmdArgs.push_back("soft");
2205 }
2206}
2207
2208void Clang::AddX86TargetArgs(const ArgList &Args,
2209 ArgStringList &CmdArgs) const {
2210 const Driver &D = getToolChain().getDriver();
2211 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2212
2213 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2214 Args.hasArg(options::OPT_mkernel) ||
2215 Args.hasArg(options::OPT_fapple_kext))
2216 CmdArgs.push_back("-disable-red-zone");
2217
2218 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2219 options::OPT_mno_tls_direct_seg_refs, true))
2220 CmdArgs.push_back("-mno-tls-direct-seg-refs");
2221
2222 // Default to avoid implicit floating-point for kernel/kext code, but allow
2223 // that to be overridden with -mno-soft-float.
2224 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2225 Args.hasArg(options::OPT_fapple_kext));
2226 if (Arg *A = Args.getLastArg(
2227 options::OPT_msoft_float, options::OPT_mno_soft_float,
2228 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2229 const Option &O = A->getOption();
2230 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2231 O.matches(options::OPT_msoft_float));
2232 }
2233 if (NoImplicitFloat)
2234 CmdArgs.push_back("-no-implicit-float");
2235
2236 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2237 StringRef Value = A->getValue();
2238 if (Value == "intel" || Value == "att") {
2239 CmdArgs.push_back("-mllvm");
2240 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2241 CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
2242 } else {
2243 D.Diag(diag::err_drv_unsupported_option_argument)
2244 << A->getSpelling() << Value;
2245 }
2246 } else if (D.IsCLMode()) {
2247 CmdArgs.push_back("-mllvm");
2248 CmdArgs.push_back("-x86-asm-syntax=intel");
2249 }
2250
2251 if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2252 options::OPT_mno_skip_rax_setup))
2253 if (A->getOption().matches(options::OPT_mskip_rax_setup))
2254 CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2255
2256 // Set flags to support MCU ABI.
2257 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2258 CmdArgs.push_back("-mfloat-abi");
2259 CmdArgs.push_back("soft");
2260 CmdArgs.push_back("-mstack-alignment=4");
2261 }
2262
2263 // Handle -mtune.
2264
2265 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2266 std::string TuneCPU;
2267 if (!Args.hasArg(clang::driver::options::OPT_march_EQ) &&
2268 !getToolChain().getTriple().isPS())
2269 TuneCPU = "generic";
2270
2271 // Override based on -mtune.
2272 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2273 StringRef Name = A->getValue();
2274
2275 if (Name == "native") {
2276 Name = llvm::sys::getHostCPUName();
2277 if (!Name.empty())
2278 TuneCPU = std::string(Name);
2279 } else
2280 TuneCPU = std::string(Name);
2281 }
2282
2283 if (!TuneCPU.empty()) {
2284 CmdArgs.push_back("-tune-cpu");
2285 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2286 }
2287}
2288
2289void Clang::AddHexagonTargetArgs(const ArgList &Args,
2290 ArgStringList &CmdArgs) const {
2291 CmdArgs.push_back("-mqdsp6-compat");
2292 CmdArgs.push_back("-Wreturn-type");
2293
2295 CmdArgs.push_back("-mllvm");
2296 CmdArgs.push_back(
2297 Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
2298 }
2299
2300 if (!Args.hasArg(options::OPT_fno_short_enums))
2301 CmdArgs.push_back("-fshort-enums");
2302 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2303 CmdArgs.push_back("-mllvm");
2304 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2305 }
2306 CmdArgs.push_back("-mllvm");
2307 CmdArgs.push_back("-machine-sink-split=0");
2308}
2309
2310void Clang::AddLanaiTargetArgs(const ArgList &Args,
2311 ArgStringList &CmdArgs) const {
2312 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2313 StringRef CPUName = A->getValue();
2314
2315 CmdArgs.push_back("-target-cpu");
2316 CmdArgs.push_back(Args.MakeArgString(CPUName));
2317 }
2318 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2319 StringRef Value = A->getValue();
2320 // Only support mregparm=4 to support old usage. Report error for all other
2321 // cases.
2322 int Mregparm;
2323 if (Value.getAsInteger(10, Mregparm)) {
2324 if (Mregparm != 4) {
2326 diag::err_drv_unsupported_option_argument)
2327 << A->getSpelling() << Value;
2328 }
2329 }
2330 }
2331}
2332
2333void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2334 ArgStringList &CmdArgs) const {
2335 // Default to "hidden" visibility.
2336 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2337 options::OPT_fvisibility_ms_compat))
2338 CmdArgs.push_back("-fvisibility=hidden");
2339}
2340
2341void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2342 // Floating point operations and argument passing are hard.
2343 CmdArgs.push_back("-mfloat-abi");
2344 CmdArgs.push_back("hard");
2345}
2346
2347void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2348 StringRef Target, const InputInfo &Output,
2349 const InputInfo &Input, const ArgList &Args) const {
2350 // If this is a dry run, do not create the compilation database file.
2351 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2352 return;
2353
2354 using llvm::yaml::escape;
2355 const Driver &D = getToolChain().getDriver();
2356
2357 if (!CompilationDatabase) {
2358 std::error_code EC;
2359 auto File = std::make_unique<llvm::raw_fd_ostream>(
2360 Filename, EC,
2361 llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2362 if (EC) {
2363 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2364 << EC.message();
2365 return;
2366 }
2367 CompilationDatabase = std::move(File);
2368 }
2369 auto &CDB = *CompilationDatabase;
2370 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2371 if (!CWD)
2372 CWD = ".";
2373 CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2374 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2375 if (Output.isFilename())
2376 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2377 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2378 SmallString<128> Buf;
2379 Buf = "-x";
2380 Buf += types::getTypeName(Input.getType());
2381 CDB << ", \"" << escape(Buf) << "\"";
2382 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2383 Buf = "--sysroot=";
2384 Buf += D.SysRoot;
2385 CDB << ", \"" << escape(Buf) << "\"";
2386 }
2387 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2388 if (Output.isFilename())
2389 CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
2390 for (auto &A: Args) {
2391 auto &O = A->getOption();
2392 // Skip language selection, which is positional.
2393 if (O.getID() == options::OPT_x)
2394 continue;
2395 // Skip writing dependency output and the compilation database itself.
2396 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2397 continue;
2398 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2399 continue;
2400 // Skip inputs.
2401 if (O.getKind() == Option::InputClass)
2402 continue;
2403 // Skip output.
2404 if (O.getID() == options::OPT_o)
2405 continue;
2406 // All other arguments are quoted and appended.
2407 ArgStringList ASL;
2408 A->render(Args, ASL);
2409 for (auto &it: ASL)
2410 CDB << ", \"" << escape(it) << "\"";
2411 }
2412 Buf = "--target=";
2413 Buf += Target;
2414 CDB << ", \"" << escape(Buf) << "\"]},\n";
2415}
2416
2417void Clang::DumpCompilationDatabaseFragmentToDir(
2418 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2419 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2420 // If this is a dry run, do not create the compilation database file.
2421 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2422 return;
2423
2424 if (CompilationDatabase)
2425 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2426
2427 SmallString<256> Path = Dir;
2428 const auto &Driver = C.getDriver();
2429 Driver.getVFS().makeAbsolute(Path);
2430 auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2431 if (Err) {
2432 Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2433 return;
2434 }
2435
2436 llvm::sys::path::append(
2437 Path,
2438 Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2439 int FD;
2440 SmallString<256> TempPath;
2441 Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2442 llvm::sys::fs::OF_Text);
2443 if (Err) {
2444 Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2445 return;
2446 }
2447 CompilationDatabase =
2448 std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2449 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2450}
2451
2452static bool CheckARMImplicitITArg(StringRef Value) {
2453 return Value == "always" || Value == "never" || Value == "arm" ||
2454 Value == "thumb";
2455}
2456
2457static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2458 StringRef Value) {
2459 CmdArgs.push_back("-mllvm");
2460 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2461}
2462
2464 const ArgList &Args,
2465 ArgStringList &CmdArgs,
2466 const Driver &D) {
2467 // Default to -mno-relax-all.
2468 //
2469 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2470 // cannot be done by assembler branch relaxation as it needs a free temporary
2471 // register. Because of this, branch relaxation is handled by a MachineIR pass
2472 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2473 // MachineIR branch relaxation inaccurate and it will miss cases where an
2474 // indirect branch is necessary.
2475 Args.addOptInFlag(CmdArgs, options::OPT_mrelax_all,
2476 options::OPT_mno_relax_all);
2477
2478 // Only default to -mincremental-linker-compatible if we think we are
2479 // targeting the MSVC linker.
2480 bool DefaultIncrementalLinkerCompatible =
2481 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2482 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2483 options::OPT_mno_incremental_linker_compatible,
2484 DefaultIncrementalLinkerCompatible))
2485 CmdArgs.push_back("-mincremental-linker-compatible");
2486
2487 Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
2488
2489 Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
2490 options::OPT_fno_emit_compact_unwind_non_canonical);
2491
2492 // If you add more args here, also add them to the block below that
2493 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2494
2495 // When passing -I arguments to the assembler we sometimes need to
2496 // unconditionally take the next argument. For example, when parsing
2497 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2498 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2499 // arg after parsing the '-I' arg.
2500 bool TakeNextArg = false;
2501
2502 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2503 bool UseNoExecStack = false;
2504 const char *MipsTargetFeature = nullptr;
2505 StringRef ImplicitIt;
2506 for (const Arg *A :
2507 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2508 options::OPT_mimplicit_it_EQ)) {
2509 A->claim();
2510
2511 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2512 switch (C.getDefaultToolChain().getArch()) {
2513 case llvm::Triple::arm:
2514 case llvm::Triple::armeb:
2515 case llvm::Triple::thumb:
2516 case llvm::Triple::thumbeb:
2517 // Only store the value; the last value set takes effect.
2518 ImplicitIt = A->getValue();
2519 if (!CheckARMImplicitITArg(ImplicitIt))
2520 D.Diag(diag::err_drv_unsupported_option_argument)
2521 << A->getSpelling() << ImplicitIt;
2522 continue;
2523 default:
2524 break;
2525 }
2526 }
2527
2528 for (StringRef Value : A->getValues()) {
2529 if (TakeNextArg) {
2530 CmdArgs.push_back(Value.data());
2531 TakeNextArg = false;
2532 continue;
2533 }
2534
2535 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2536 Value == "-mbig-obj")
2537 continue; // LLVM handles bigobj automatically
2538
2539 switch (C.getDefaultToolChain().getArch()) {
2540 default:
2541 break;
2542 case llvm::Triple::wasm32:
2543 case llvm::Triple::wasm64:
2544 if (Value == "--no-type-check") {
2545 CmdArgs.push_back("-mno-type-check");
2546 continue;
2547 }
2548 break;
2549 case llvm::Triple::thumb:
2550 case llvm::Triple::thumbeb:
2551 case llvm::Triple::arm:
2552 case llvm::Triple::armeb:
2553 if (Value.starts_with("-mimplicit-it=")) {
2554 // Only store the value; the last value set takes effect.
2555 ImplicitIt = Value.split("=").second;
2556 if (CheckARMImplicitITArg(ImplicitIt))
2557 continue;
2558 }
2559 if (Value == "-mthumb")
2560 // -mthumb has already been processed in ComputeLLVMTriple()
2561 // recognize but skip over here.
2562 continue;
2563 break;
2564 case llvm::Triple::mips:
2565 case llvm::Triple::mipsel:
2566 case llvm::Triple::mips64:
2567 case llvm::Triple::mips64el:
2568 if (Value == "--trap") {
2569 CmdArgs.push_back("-target-feature");
2570 CmdArgs.push_back("+use-tcc-in-div");
2571 continue;
2572 }
2573 if (Value == "--break") {
2574 CmdArgs.push_back("-target-feature");
2575 CmdArgs.push_back("-use-tcc-in-div");
2576 continue;
2577 }
2578 if (Value.starts_with("-msoft-float")) {
2579 CmdArgs.push_back("-target-feature");
2580 CmdArgs.push_back("+soft-float");
2581 continue;
2582 }
2583 if (Value.starts_with("-mhard-float")) {
2584 CmdArgs.push_back("-target-feature");
2585 CmdArgs.push_back("-soft-float");
2586 continue;
2587 }
2588
2589 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2590 .Case("-mips1", "+mips1")
2591 .Case("-mips2", "+mips2")
2592 .Case("-mips3", "+mips3")
2593 .Case("-mips4", "+mips4")
2594 .Case("-mips5", "+mips5")
2595 .Case("-mips32", "+mips32")
2596 .Case("-mips32r2", "+mips32r2")
2597 .Case("-mips32r3", "+mips32r3")
2598 .Case("-mips32r5", "+mips32r5")
2599 .Case("-mips32r6", "+mips32r6")
2600 .Case("-mips64", "+mips64")
2601 .Case("-mips64r2", "+mips64r2")
2602 .Case("-mips64r3", "+mips64r3")
2603 .Case("-mips64r5", "+mips64r5")
2604 .Case("-mips64r6", "+mips64r6")
2605 .Default(nullptr);
2606 if (MipsTargetFeature)
2607 continue;
2608 }
2609
2610 if (Value == "-force_cpusubtype_ALL") {
2611 // Do nothing, this is the default and we don't support anything else.
2612 } else if (Value == "-L") {
2613 CmdArgs.push_back("-msave-temp-labels");
2614 } else if (Value == "--fatal-warnings") {
2615 CmdArgs.push_back("-massembler-fatal-warnings");
2616 } else if (Value == "--no-warn" || Value == "-W") {
2617 CmdArgs.push_back("-massembler-no-warn");
2618 } else if (Value == "--noexecstack") {
2619 UseNoExecStack = true;
2620 } else if (Value.starts_with("-compress-debug-sections") ||
2621 Value.starts_with("--compress-debug-sections") ||
2622 Value == "-nocompress-debug-sections" ||
2623 Value == "--nocompress-debug-sections") {
2624 CmdArgs.push_back(Value.data());
2625 } else if (Value == "-mrelax-relocations=yes" ||
2626 Value == "--mrelax-relocations=yes") {
2627 UseRelaxRelocations = true;
2628 } else if (Value == "-mrelax-relocations=no" ||
2629 Value == "--mrelax-relocations=no") {
2630 UseRelaxRelocations = false;
2631 } else if (Value.starts_with("-I")) {
2632 CmdArgs.push_back(Value.data());
2633 // We need to consume the next argument if the current arg is a plain
2634 // -I. The next arg will be the include directory.
2635 if (Value == "-I")
2636 TakeNextArg = true;
2637 } else if (Value.starts_with("-gdwarf-")) {
2638 // "-gdwarf-N" options are not cc1as options.
2639 unsigned DwarfVersion = DwarfVersionNum(Value);
2640 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2641 CmdArgs.push_back(Value.data());
2642 } else {
2643 RenderDebugEnablingArgs(Args, CmdArgs,
2644 llvm::codegenoptions::DebugInfoConstructor,
2645 DwarfVersion, llvm::DebuggerKind::Default);
2646 }
2647 } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
2648 Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {
2649 // Do nothing, we'll validate it later.
2650 } else if (Value == "-defsym") {
2651 if (A->getNumValues() != 2) {
2652 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2653 break;
2654 }
2655 const char *S = A->getValue(1);
2656 auto Pair = StringRef(S).split('=');
2657 auto Sym = Pair.first;
2658 auto SVal = Pair.second;
2659
2660 if (Sym.empty() || SVal.empty()) {
2661 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2662 break;
2663 }
2664 int64_t IVal;
2665 if (SVal.getAsInteger(0, IVal)) {
2666 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2667 break;
2668 }
2669 CmdArgs.push_back(Value.data());
2670 TakeNextArg = true;
2671 } else if (Value == "-fdebug-compilation-dir") {
2672 CmdArgs.push_back("-fdebug-compilation-dir");
2673 TakeNextArg = true;
2674 } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2675 // The flag is a -Wa / -Xassembler argument and Options doesn't
2676 // parse the argument, so this isn't automatically aliased to
2677 // -fdebug-compilation-dir (without '=') here.
2678 CmdArgs.push_back("-fdebug-compilation-dir");
2679 CmdArgs.push_back(Value.data());
2680 } else if (Value == "--version") {
2681 D.PrintVersion(C, llvm::outs());
2682 } else {
2683 D.Diag(diag::err_drv_unsupported_option_argument)
2684 << A->getSpelling() << Value;
2685 }
2686 }
2687 }
2688 if (ImplicitIt.size())
2689 AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2690 if (!UseRelaxRelocations)
2691 CmdArgs.push_back("-mrelax-relocations=no");
2692 if (UseNoExecStack)
2693 CmdArgs.push_back("-mnoexecstack");
2694 if (MipsTargetFeature != nullptr) {
2695 CmdArgs.push_back("-target-feature");
2696 CmdArgs.push_back(MipsTargetFeature);
2697 }
2698
2699 // forward -fembed-bitcode to assmebler
2700 if (C.getDriver().embedBitcodeEnabled() ||
2701 C.getDriver().embedBitcodeMarkerOnly())
2702 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2703
2704 if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2705 CmdArgs.push_back("-as-secure-log-file");
2706 CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2707 }
2708}
2709
2711 switch (Range) {
2713 return "full";
2714 break;
2716 return "basic";
2717 break;
2719 return "improved";
2720 break;
2722 return "promoted";
2723 break;
2724 default:
2725 return "";
2726 }
2727}
2728
2731 ? ""
2732 : "-fcomplex-arithmetic=" + ComplexRangeKindToStr(Range);
2733}
2734
2735static void EmitComplexRangeDiag(const Driver &D, std::string str1,
2736 std::string str2) {
2737 if ((str1.compare(str2) != 0) && !str2.empty() && !str1.empty()) {
2738 D.Diag(clang::diag::warn_drv_overriding_option) << str1 << str2;
2739 }
2740}
2741
2742static std::string
2744 std::string ComplexRangeStr = ComplexRangeKindToStr(Range);
2745 if (!ComplexRangeStr.empty())
2746 return "-complex-range=" + ComplexRangeStr;
2747 return ComplexRangeStr;
2748}
2749
2750static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2751 bool OFastEnabled, const ArgList &Args,
2752 ArgStringList &CmdArgs,
2753 const JobAction &JA) {
2754 // Handle various floating point optimization flags, mapping them to the
2755 // appropriate LLVM code generation flags. This is complicated by several
2756 // "umbrella" flags, so we do this by stepping through the flags incrementally
2757 // adjusting what we think is enabled/disabled, then at the end setting the
2758 // LLVM flags based on the final state.
2759 bool HonorINFs = true;
2760 bool HonorNaNs = true;
2761 bool ApproxFunc = false;
2762 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2763 bool MathErrno = TC.IsMathErrnoDefault();
2764 bool AssociativeMath = false;
2765 bool ReciprocalMath = false;
2766 bool SignedZeros = true;
2767 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2768 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2769 // overriden by ffp-exception-behavior?
2770 bool RoundingFPMath = false;
2771 // -ffp-model values: strict, fast, precise
2772 StringRef FPModel = "";
2773 // -ffp-exception-behavior options: strict, maytrap, ignore
2774 StringRef FPExceptionBehavior = "";
2775 // -ffp-eval-method options: double, extended, source
2776 StringRef FPEvalMethod = "";
2777 llvm::DenormalMode DenormalFPMath =
2778 TC.getDefaultDenormalModeForType(Args, JA);
2779 llvm::DenormalMode DenormalFP32Math =
2780 TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2781
2782 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2783 // If one wasn't given by the user, don't pass it here.
2784 StringRef FPContract;
2785 StringRef LastSeenFfpContractOption;
2786 bool SeenUnsafeMathModeOption = false;
2789 FPContract = "on";
2790 bool StrictFPModel = false;
2791 StringRef Float16ExcessPrecision = "";
2792 StringRef BFloat16ExcessPrecision = "";
2794 std::string ComplexRangeStr = "";
2795 std::string GccRangeComplexOption = "";
2796
2797 // Lambda to set fast-math options. This is also used by -ffp-model=fast
2798 auto applyFastMath = [&]() {
2799 HonorINFs = false;
2800 HonorNaNs = false;
2801 MathErrno = false;
2802 AssociativeMath = true;
2803 ReciprocalMath = true;
2804 ApproxFunc = true;
2805 SignedZeros = false;
2806 TrappingMath = false;
2807 RoundingFPMath = false;
2808 FPExceptionBehavior = "";
2809 // If fast-math is set then set the fp-contract mode to fast.
2810 FPContract = "fast";
2811 // ffast-math enables basic range rules for complex multiplication and
2812 // division.
2813 // Warn if user expects to perform full implementation of complex
2814 // multiplication or division in the presence of nan or ninf flags.
2820 !GccRangeComplexOption.empty()
2821 ? GccRangeComplexOption
2824 SeenUnsafeMathModeOption = true;
2825 };
2826
2827 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2828 CmdArgs.push_back("-mlimit-float-precision");
2829 CmdArgs.push_back(A->getValue());
2830 }
2831
2832 for (const Arg *A : Args) {
2833 switch (A->getOption().getID()) {
2834 // If this isn't an FP option skip the claim below
2835 default: continue;
2836
2837 case options::OPT_fcx_limited_range:
2838 if (GccRangeComplexOption.empty()) {
2841 "-fcx-limited-range");
2842 } else {
2843 if (GccRangeComplexOption != "-fno-cx-limited-range")
2844 EmitComplexRangeDiag(D, GccRangeComplexOption, "-fcx-limited-range");
2845 }
2846 GccRangeComplexOption = "-fcx-limited-range";
2848 break;
2849 case options::OPT_fno_cx_limited_range:
2850 if (GccRangeComplexOption.empty()) {
2852 "-fno-cx-limited-range");
2853 } else {
2854 if (GccRangeComplexOption.compare("-fcx-limited-range") != 0 &&
2855 GccRangeComplexOption.compare("-fno-cx-fortran-rules") != 0)
2856 EmitComplexRangeDiag(D, GccRangeComplexOption,
2857 "-fno-cx-limited-range");
2858 }
2859 GccRangeComplexOption = "-fno-cx-limited-range";
2861 break;
2862 case options::OPT_fcx_fortran_rules:
2863 if (GccRangeComplexOption.empty())
2865 "-fcx-fortran-rules");
2866 else
2867 EmitComplexRangeDiag(D, GccRangeComplexOption, "-fcx-fortran-rules");
2868 GccRangeComplexOption = "-fcx-fortran-rules";
2870 break;
2871 case options::OPT_fno_cx_fortran_rules:
2872 if (GccRangeComplexOption.empty()) {
2874 "-fno-cx-fortran-rules");
2875 } else {
2876 if (GccRangeComplexOption != "-fno-cx-limited-range")
2877 EmitComplexRangeDiag(D, GccRangeComplexOption,
2878 "-fno-cx-fortran-rules");
2879 }
2880 GccRangeComplexOption = "-fno-cx-fortran-rules";
2882 break;
2883 case options::OPT_fcomplex_arithmetic_EQ: {
2885 StringRef Val = A->getValue();
2886 if (Val == "full")
2888 else if (Val == "improved")
2890 else if (Val == "promoted")
2892 else if (Val == "basic")
2894 else {
2895 D.Diag(diag::err_drv_unsupported_option_argument)
2896 << A->getSpelling() << Val;
2897 break;
2898 }
2899 if (!GccRangeComplexOption.empty()) {
2900 if (GccRangeComplexOption.compare("-fcx-limited-range") != 0) {
2901 if (GccRangeComplexOption.compare("-fcx-fortran-rules") != 0) {
2903 EmitComplexRangeDiag(D, GccRangeComplexOption,
2904 ComplexArithmeticStr(RangeVal));
2905 } else {
2906 EmitComplexRangeDiag(D, GccRangeComplexOption,
2907 ComplexArithmeticStr(RangeVal));
2908 }
2909 } else {
2911 EmitComplexRangeDiag(D, GccRangeComplexOption,
2912 ComplexArithmeticStr(RangeVal));
2913 }
2914 }
2915 Range = RangeVal;
2916 break;
2917 }
2918 case options::OPT_ffp_model_EQ: {
2919 // If -ffp-model= is seen, reset to fno-fast-math
2920 HonorINFs = true;
2921 HonorNaNs = true;
2922 ApproxFunc = false;
2923 // Turning *off* -ffast-math restores the toolchain default.
2924 MathErrno = TC.IsMathErrnoDefault();
2925 AssociativeMath = false;
2926 ReciprocalMath = false;
2927 SignedZeros = true;
2928 FPContract = "on";
2929
2930 StringRef Val = A->getValue();
2931 if (OFastEnabled && Val != "fast") {
2932 // Only -ffp-model=fast is compatible with OFast, ignore.
2933 D.Diag(clang::diag::warn_drv_overriding_option)
2934 << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";
2935 break;
2936 }
2937 StrictFPModel = false;
2938 if (!FPModel.empty() && FPModel != Val)
2939 D.Diag(clang::diag::warn_drv_overriding_option)
2940 << Args.MakeArgString("-ffp-model=" + FPModel)
2941 << Args.MakeArgString("-ffp-model=" + Val);
2942 if (Val == "fast") {
2943 FPModel = Val;
2944 applyFastMath();
2945 } else if (Val == "precise") {
2946 FPModel = Val;
2947 FPContract = "on";
2948 } else if (Val == "strict") {
2949 StrictFPModel = true;
2950 FPExceptionBehavior = "strict";
2951 FPModel = Val;
2952 FPContract = "off";
2953 TrappingMath = true;
2954 RoundingFPMath = true;
2955 } else
2956 D.Diag(diag::err_drv_unsupported_option_argument)
2957 << A->getSpelling() << Val;
2958 break;
2959 }
2960
2961 // Options controlling individual features
2962 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2963 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2964 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2965 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2966 case options::OPT_fapprox_func: ApproxFunc = true; break;
2967 case options::OPT_fno_approx_func: ApproxFunc = false; break;
2968 case options::OPT_fmath_errno: MathErrno = true; break;
2969 case options::OPT_fno_math_errno: MathErrno = false; break;
2970 case options::OPT_fassociative_math: AssociativeMath = true; break;
2971 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2972 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2973 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2974 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2975 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2976 case options::OPT_ftrapping_math:
2977 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2978 FPExceptionBehavior != "strict")
2979 // Warn that previous value of option is overridden.
2980 D.Diag(clang::diag::warn_drv_overriding_option)
2981 << Args.MakeArgString("-ffp-exception-behavior=" +
2982 FPExceptionBehavior)
2983 << "-ftrapping-math";
2984 TrappingMath = true;
2985 TrappingMathPresent = true;
2986 FPExceptionBehavior = "strict";
2987 break;
2988 case options::OPT_fno_trapping_math:
2989 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2990 FPExceptionBehavior != "ignore")
2991 // Warn that previous value of option is overridden.
2992 D.Diag(clang::diag::warn_drv_overriding_option)
2993 << Args.MakeArgString("-ffp-exception-behavior=" +
2994 FPExceptionBehavior)
2995 << "-fno-trapping-math";
2996 TrappingMath = false;
2997 TrappingMathPresent = true;
2998 FPExceptionBehavior = "ignore";
2999 break;
3000
3001 case options::OPT_frounding_math:
3002 RoundingFPMath = true;
3003 break;
3004
3005 case options::OPT_fno_rounding_math:
3006 RoundingFPMath = false;
3007 break;
3008
3009 case options::OPT_fdenormal_fp_math_EQ:
3010 DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
3011 DenormalFP32Math = DenormalFPMath;
3012 if (!DenormalFPMath.isValid()) {
3013 D.Diag(diag::err_drv_invalid_value)
3014 << A->getAsString(Args) << A->getValue();
3015 }
3016 break;
3017
3018 case options::OPT_fdenormal_fp_math_f32_EQ:
3019 DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
3020 if (!DenormalFP32Math.isValid()) {
3021 D.Diag(diag::err_drv_invalid_value)
3022 << A->getAsString(Args) << A->getValue();
3023 }
3024 break;
3025
3026 // Validate and pass through -ffp-contract option.
3027 case options::OPT_ffp_contract: {
3028 StringRef Val = A->getValue();
3029 if (Val == "fast" || Val == "on" || Val == "off" ||
3030 Val == "fast-honor-pragmas") {
3031 FPContract = Val;
3032 LastSeenFfpContractOption = Val;
3033 } else
3034 D.Diag(diag::err_drv_unsupported_option_argument)
3035 << A->getSpelling() << Val;
3036 break;
3037 }
3038
3039 // Validate and pass through -ffp-exception-behavior option.
3040 case options::OPT_ffp_exception_behavior_EQ: {
3041 StringRef Val = A->getValue();
3042 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3043 FPExceptionBehavior != Val)
3044 // Warn that previous value of option is overridden.
3045 D.Diag(clang::diag::warn_drv_overriding_option)
3046 << Args.MakeArgString("-ffp-exception-behavior=" +
3047 FPExceptionBehavior)
3048 << Args.MakeArgString("-ffp-exception-behavior=" + Val);
3049 TrappingMath = TrappingMathPresent = false;
3050 if (Val == "ignore" || Val == "maytrap")
3051 FPExceptionBehavior = Val;
3052 else if (Val == "strict") {
3053 FPExceptionBehavior = Val;
3054 TrappingMath = TrappingMathPresent = true;
3055 } else
3056 D.Diag(diag::err_drv_unsupported_option_argument)
3057 << A->getSpelling() << Val;
3058 break;
3059 }
3060
3061 // Validate and pass through -ffp-eval-method option.
3062 case options::OPT_ffp_eval_method_EQ: {
3063 StringRef Val = A->getValue();
3064 if (Val == "double" || Val == "extended" || Val == "source")
3065 FPEvalMethod = Val;
3066 else
3067 D.Diag(diag::err_drv_unsupported_option_argument)
3068 << A->getSpelling() << Val;
3069 break;
3070 }
3071
3072 case options::OPT_fexcess_precision_EQ: {
3073 StringRef Val = A->getValue();
3074 const llvm::Triple::ArchType Arch = TC.getArch();
3075 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3076 if (Val == "standard" || Val == "fast")
3077 Float16ExcessPrecision = Val;
3078 // To make it GCC compatible, allow the value of "16" which
3079 // means disable excess precision, the same meaning than clang's
3080 // equivalent value "none".
3081 else if (Val == "16")
3082 Float16ExcessPrecision = "none";
3083 else
3084 D.Diag(diag::err_drv_unsupported_option_argument)
3085 << A->getSpelling() << Val;
3086 } else {
3087 if (!(Val == "standard" || Val == "fast"))
3088 D.Diag(diag::err_drv_unsupported_option_argument)
3089 << A->getSpelling() << Val;
3090 }
3091 BFloat16ExcessPrecision = Float16ExcessPrecision;
3092 break;
3093 }
3094 case options::OPT_ffinite_math_only:
3095 HonorINFs = false;
3096 HonorNaNs = false;
3097 break;
3098 case options::OPT_fno_finite_math_only:
3099 HonorINFs = true;
3100 HonorNaNs = true;
3101 break;
3102
3103 case options::OPT_funsafe_math_optimizations:
3104 AssociativeMath = true;
3105 ReciprocalMath = true;
3106 SignedZeros = false;
3107 ApproxFunc = true;
3108 TrappingMath = false;
3109 FPExceptionBehavior = "";
3110 FPContract = "fast";
3111 SeenUnsafeMathModeOption = true;
3112 break;
3113 case options::OPT_fno_unsafe_math_optimizations:
3114 AssociativeMath = false;
3115 ReciprocalMath = false;
3116 SignedZeros = true;
3117 ApproxFunc = false;
3118
3121 if (LastSeenFfpContractOption != "") {
3122 FPContract = LastSeenFfpContractOption;
3123 } else if (SeenUnsafeMathModeOption)
3124 FPContract = "on";
3125 }
3126 break;
3127
3128 case options::OPT_Ofast:
3129 // If -Ofast is the optimization level, then -ffast-math should be enabled
3130 if (!OFastEnabled)
3131 continue;
3132 [[fallthrough]];
3133 case options::OPT_ffast_math: {
3134 applyFastMath();
3135 break;
3136 }
3137 case options::OPT_fno_fast_math:
3138 HonorINFs = true;
3139 HonorNaNs = true;
3140 // Turning on -ffast-math (with either flag) removes the need for
3141 // MathErrno. However, turning *off* -ffast-math merely restores the
3142 // toolchain default (which may be false).
3143 MathErrno = TC.IsMathErrnoDefault();
3144 AssociativeMath = false;
3145 ReciprocalMath = false;
3146 ApproxFunc = false;
3147 SignedZeros = true;
3148 // -fno_fast_math restores default fpcontract handling
3151 if (LastSeenFfpContractOption != "") {
3152 FPContract = LastSeenFfpContractOption;
3153 } else if (SeenUnsafeMathModeOption)
3154 FPContract = "on";
3155 }
3156 break;
3157 }
3158 // The StrictFPModel local variable is needed to report warnings
3159 // in the way we intend. If -ffp-model=strict has been used, we
3160 // want to report a warning for the next option encountered that
3161 // takes us out of the settings described by fp-model=strict, but
3162 // we don't want to continue issuing warnings for other conflicting
3163 // options after that.
3164 if (StrictFPModel) {
3165 // If -ffp-model=strict has been specified on command line but
3166 // subsequent options conflict then emit warning diagnostic.
3167 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3168 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3169 FPContract == "off")
3170 // OK: Current Arg doesn't conflict with -ffp-model=strict
3171 ;
3172 else {
3173 StrictFPModel = false;
3174 FPModel = "";
3175 auto RHS = (A->getNumValues() == 0)
3176 ? A->getSpelling()
3177 : Args.MakeArgString(A->getSpelling() + A->getValue());
3178 if (RHS != "-ffp-model=strict")
3179 D.Diag(clang::diag::warn_drv_overriding_option)
3180 << "-ffp-model=strict" << RHS;
3181 }
3182 }
3183
3184 // If we handled this option claim it
3185 A->claim();
3186 }
3187
3188 if (!HonorINFs)
3189 CmdArgs.push_back("-menable-no-infs");
3190
3191 if (!HonorNaNs)
3192 CmdArgs.push_back("-menable-no-nans");
3193
3194 if (ApproxFunc)
3195 CmdArgs.push_back("-fapprox-func");
3196
3197 if (MathErrno)
3198 CmdArgs.push_back("-fmath-errno");
3199
3200 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3201 !TrappingMath)
3202 CmdArgs.push_back("-funsafe-math-optimizations");
3203
3204 if (!SignedZeros)
3205 CmdArgs.push_back("-fno-signed-zeros");
3206
3207 if (AssociativeMath && !SignedZeros && !TrappingMath)
3208 CmdArgs.push_back("-mreassociate");
3209
3210 if (ReciprocalMath)
3211 CmdArgs.push_back("-freciprocal-math");
3212
3213 if (TrappingMath) {
3214 // FP Exception Behavior is also set to strict
3215 assert(FPExceptionBehavior == "strict");
3216 }
3217
3218 // The default is IEEE.
3219 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3220 llvm::SmallString<64> DenormFlag;
3221 llvm::raw_svector_ostream ArgStr(DenormFlag);
3222 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3223 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3224 }
3225
3226 // Add f32 specific denormal mode flag if it's different.
3227 if (DenormalFP32Math != DenormalFPMath) {
3228 llvm::SmallString<64> DenormFlag;
3229 llvm::raw_svector_ostream ArgStr(DenormFlag);
3230 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3231 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3232 }
3233
3234 if (!FPContract.empty())
3235 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
3236
3237 if (RoundingFPMath)
3238 CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3239 else
3240 CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3241
3242 if (!FPExceptionBehavior.empty())
3243 CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3244 FPExceptionBehavior));
3245
3246 if (!FPEvalMethod.empty())
3247 CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
3248
3249 if (!Float16ExcessPrecision.empty())
3250 CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3251 Float16ExcessPrecision));
3252 if (!BFloat16ExcessPrecision.empty())
3253 CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
3254 BFloat16ExcessPrecision));
3255
3256 ParseMRecip(D, Args, CmdArgs);
3257
3258 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3259 // individual features enabled by -ffast-math instead of the option itself as
3260 // that's consistent with gcc's behaviour.
3261 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3262 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath) {
3263 CmdArgs.push_back("-ffast-math");
3264 if (FPModel == "fast") {
3265 if (FPContract == "fast")
3266 // All set, do nothing.
3267 ;
3268 else if (FPContract.empty())
3269 // Enable -ffp-contract=fast
3270 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3271 else
3272 D.Diag(clang::diag::warn_drv_overriding_option)
3273 << "-ffp-model=fast"
3274 << Args.MakeArgString("-ffp-contract=" + FPContract);
3275 }
3276 }
3277
3278 // Handle __FINITE_MATH_ONLY__ similarly.
3279 if (!HonorINFs && !HonorNaNs)
3280 CmdArgs.push_back("-ffinite-math-only");
3281
3282 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3283 CmdArgs.push_back("-mfpmath");
3284 CmdArgs.push_back(A->getValue());
3285 }
3286
3287 // Disable a codegen optimization for floating-point casts.
3288 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3289 options::OPT_fstrict_float_cast_overflow, false))
3290 CmdArgs.push_back("-fno-strict-float-cast-overflow");
3291
3293 ComplexRangeStr = RenderComplexRangeOption(Range);
3294 if (!ComplexRangeStr.empty()) {
3295 CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
3296 if (Args.hasArg(options::OPT_fcomplex_arithmetic_EQ))
3297 CmdArgs.push_back(Args.MakeArgString("-fcomplex-arithmetic=" +
3299 }
3300 if (Args.hasArg(options::OPT_fcx_limited_range))
3301 CmdArgs.push_back("-fcx-limited-range");
3302 if (Args.hasArg(options::OPT_fcx_fortran_rules))
3303 CmdArgs.push_back("-fcx-fortran-rules");
3304 if (Args.hasArg(options::OPT_fno_cx_limited_range))
3305 CmdArgs.push_back("-fno-cx-limited-range");
3306 if (Args.hasArg(options::OPT_fno_cx_fortran_rules))
3307 CmdArgs.push_back("-fno-cx-fortran-rules");
3308}
3309
3310static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3311 const llvm::Triple &Triple,
3312 const InputInfo &Input) {
3313 // Add default argument set.
3314 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3315 CmdArgs.push_back("-analyzer-checker=core");
3316 CmdArgs.push_back("-analyzer-checker=apiModeling");
3317
3318 if (!Triple.isWindowsMSVCEnvironment()) {
3319 CmdArgs.push_back("-analyzer-checker=unix");
3320 } else {
3321 // Enable "unix" checkers that also work on Windows.
3322 CmdArgs.push_back("-analyzer-checker=unix.API");
3323 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3324 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3325 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3326 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3327 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3328 }
3329
3330 // Disable some unix checkers for PS4/PS5.
3331 if (Triple.isPS()) {
3332 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3333 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3334 }
3335
3336 if (Triple.isOSDarwin()) {
3337 CmdArgs.push_back("-analyzer-checker=osx");
3338 CmdArgs.push_back(
3339 "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3340 }
3341 else if (Triple.isOSFuchsia())
3342 CmdArgs.push_back("-analyzer-checker=fuchsia");
3343
3344 CmdArgs.push_back("-analyzer-checker=deadcode");
3345
3346 if (types::isCXX(Input.getType()))
3347 CmdArgs.push_back("-analyzer-checker=cplusplus");
3348
3349 if (!Triple.isPS()) {
3350 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3351 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3352 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3353 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3354 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3355 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3356 }
3357
3358 // Default nullability checks.
3359 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3360 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3361 }
3362
3363 // Set the output format. The default is plist, for (lame) historical reasons.
3364 CmdArgs.push_back("-analyzer-output");
3365 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3366 CmdArgs.push_back(A->getValue());
3367 else
3368 CmdArgs.push_back("plist");
3369
3370 // Disable the presentation of standard compiler warnings when using
3371 // --analyze. We only want to show static analyzer diagnostics or frontend
3372 // errors.
3373 CmdArgs.push_back("-w");
3374
3375 // Add -Xanalyzer arguments when running as analyzer.
3376 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3377}
3378
3379static bool isValidSymbolName(StringRef S) {
3380 if (S.empty())
3381 return false;
3382
3383 if (std::isdigit(S[0]))
3384 return false;
3385
3386 return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3387}
3388
3389static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3390 const ArgList &Args, ArgStringList &CmdArgs,
3391 bool KernelOrKext) {
3392 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3393
3394 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3395 // doesn't even have a stack!
3396 if (EffectiveTriple.isNVPTX())
3397 return;
3398
3399 // -stack-protector=0 is default.
3401 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3402 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3403
3404 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3405 options::OPT_fstack_protector_all,
3406 options::OPT_fstack_protector_strong,
3407 options::OPT_fstack_protector)) {
3408 if (A->getOption().matches(options::OPT_fstack_protector))
3409 StackProtectorLevel =
3410 std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3411 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3412 StackProtectorLevel = LangOptions::SSPStrong;
3413 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3414 StackProtectorLevel = LangOptions::SSPReq;
3415
3416 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3417 D.Diag(diag::warn_drv_unsupported_option_for_target)
3418 << A->getSpelling() << EffectiveTriple.getTriple();
3419 StackProtectorLevel = DefaultStackProtectorLevel;
3420 }
3421 } else {
3422 StackProtectorLevel = DefaultStackProtectorLevel;
3423 }
3424
3425 if (StackProtectorLevel) {
3426 CmdArgs.push_back("-stack-protector");
3427 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3428 }
3429
3430 // --param ssp-buffer-size=
3431 for (const Arg *A : Args.filtered(options::OPT__param)) {
3432 StringRef Str(A->getValue());
3433 if (Str.starts_with("ssp-buffer-size=")) {
3434 if (StackProtectorLevel) {
3435 CmdArgs.push_back("-stack-protector-buffer-size");
3436 // FIXME: Verify the argument is a valid integer.
3437 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3438 }
3439 A->claim();
3440 }
3441 }
3442
3443 const std::string &TripleStr = EffectiveTriple.getTriple();
3444 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3445 StringRef Value = A->getValue();
3446 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3447 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3448 D.Diag(diag::err_drv_unsupported_opt_for_target)
3449 << A->getAsString(Args) << TripleStr;
3450 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3451 EffectiveTriple.isThumb()) &&
3452 Value != "tls" && Value != "global") {
3453 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3454 << A->getOption().getName() << Value << "tls global";
3455 return;
3456 }
3457 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3458 Value == "tls") {
3459 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3460 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3461 << A->getAsString(Args);
3462 return;
3463 }
3464 // Check whether the target subarch supports the hardware TLS register
3465 if (!arm::isHardTPSupported(EffectiveTriple)) {
3466 D.Diag(diag::err_target_unsupported_tp_hard)
3467 << EffectiveTriple.getArchName();
3468 return;
3469 }
3470 // Check whether the user asked for something other than -mtp=cp15
3471 if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3472 StringRef Value = A->getValue();
3473 if (Value != "cp15") {
3474 D.Diag(diag::err_drv_argument_not_allowed_with)
3475 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3476 return;
3477 }
3478 }
3479 CmdArgs.push_back("-target-feature");
3480 CmdArgs.push_back("+read-tp-tpidruro");
3481 }
3482 if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3483 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3484 << A->getOption().getName() << Value << "sysreg global";
3485 return;
3486 }
3487 A->render(Args, CmdArgs);
3488 }
3489
3490 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3491 StringRef Value = A->getValue();
3492 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3493 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3494 D.Diag(diag::err_drv_unsupported_opt_for_target)
3495 << A->getAsString(Args) << TripleStr;
3496 int Offset;
3497 if (Value.getAsInteger(10, Offset)) {
3498 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3499 return;
3500 }
3501 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3502 (Offset < 0 || Offset > 0xfffff)) {
3503 D.Diag(diag::err_drv_invalid_int_value)
3504 << A->getOption().getName() << Value;
3505 return;
3506 }
3507 A->render(Args, CmdArgs);
3508 }
3509
3510 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3511 StringRef Value = A->getValue();
3512 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64())
3513 D.Diag(diag::err_drv_unsupported_opt_for_target)
3514 << A->getAsString(Args) << TripleStr;
3515 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3516 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3517 << A->getOption().getName() << Value << "fs gs";
3518 return;
3519 }
3520 if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
3521 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3522 return;
3523 }
3524 A->render(Args, CmdArgs);
3525 }
3526
3527 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3528 StringRef Value = A->getValue();
3529 if (!isValidSymbolName(Value)) {
3530 D.Diag(diag::err_drv_argument_only_allowed_with)
3531 << A->getOption().getName() << "legal symbol name";
3532 return;
3533 }
3534 A->render(Args, CmdArgs);
3535 }
3536}
3537
3538static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3539 ArgStringList &CmdArgs) {
3540 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3541
3542 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux())
3543 return;
3544
3545 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3546 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64())
3547 return;
3548
3549 Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
3550 options::OPT_fno_stack_clash_protection);
3551}
3552
3554 const ToolChain &TC,
3555 const ArgList &Args,
3556 ArgStringList &CmdArgs) {
3557 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3558 StringRef TrivialAutoVarInit = "";
3559
3560 for (const Arg *A : Args) {
3561 switch (A->getOption().getID()) {
3562 default:
3563 continue;
3564 case options::OPT_ftrivial_auto_var_init: {
3565 A->claim();
3566 StringRef Val = A->getValue();
3567 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3568 TrivialAutoVarInit = Val;
3569 else
3570 D.Diag(diag::err_drv_unsupported_option_argument)
3571 << A->getSpelling() << Val;
3572 break;
3573 }
3574 }
3575 }
3576
3577 if (TrivialAutoVarInit.empty())
3578 switch (DefaultTrivialAutoVarInit) {
3580 break;
3582 TrivialAutoVarInit = "pattern";
3583 break;
3585 TrivialAutoVarInit = "zero";
3586 break;
3587 }
3588
3589 if (!TrivialAutoVarInit.empty()) {
3590 CmdArgs.push_back(
3591 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3592 }
3593
3594 if (Arg *A =
3595 Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3596 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3597 StringRef(
3598 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3599 "uninitialized")
3600 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3601 A->claim();
3602 StringRef Val = A->getValue();
3603 if (std::stoi(Val.str()) <= 0)
3604 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3605 CmdArgs.push_back(
3606 Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3607 }
3608
3609 if (Arg *A = Args.getLastArg(options::OPT_ftrivial_auto_var_init_max_size)) {
3610 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3611 StringRef(
3612 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3613 "uninitialized")
3614 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3615 A->claim();
3616 StringRef Val = A->getValue();
3617 if (std::stoi(Val.str()) <= 0)
3618 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3619 CmdArgs.push_back(
3620 Args.MakeArgString("-ftrivial-auto-var-init-max-size=" + Val));
3621 }
3622}
3623
3624static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3625 types::ID InputType) {
3626 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3627 // for denormal flushing handling based on the target.
3628 const unsigned ForwardedArguments[] = {
3629 options::OPT_cl_opt_disable,
3630 options::OPT_cl_strict_aliasing,
3631 options::OPT_cl_single_precision_constant,
3632 options::OPT_cl_finite_math_only,
3633 options::OPT_cl_kernel_arg_info,
3634 options::OPT_cl_unsafe_math_optimizations,
3635 options::OPT_cl_fast_relaxed_math,
3636 options::OPT_cl_mad_enable,
3637 options::OPT_cl_no_signed_zeros,
3638 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3639 options::OPT_cl_uniform_work_group_size
3640 };
3641
3642 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3643 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3644 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3645 } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
3646 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3647 CmdArgs.push_back(Args.MakeArgString(CLExtStr));
3648 }
3649
3650 for (const auto &Arg : ForwardedArguments)
3651 if (const auto *A = Args.getLastArg(Arg))
3652 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3653
3654 // Only add the default headers if we are compiling OpenCL sources.
3655 if ((types::isOpenCL(InputType) ||
3656 (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3657 !Args.hasArg(options::OPT_cl_no_stdinc)) {
3658 CmdArgs.push_back("-finclude-default-header");
3659 CmdArgs.push_back("-fdeclare-opencl-builtins");
3660 }
3661}
3662
3663static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3664 types::ID InputType) {
3665 const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
3666 options::OPT_D,
3667 options::OPT_I,
3668 options::OPT_S,
3669 options::OPT_O,
3670 options::OPT_emit_llvm,
3671 options::OPT_emit_obj,
3672 options::OPT_disable_llvm_passes,
3673 options::OPT_fnative_half_type,
3674 options::OPT_hlsl_entrypoint};
3675 if (!types::isHLSL(InputType))
3676 return;
3677 for (const auto &Arg : ForwardedArguments)
3678 if (const auto *A = Args.getLastArg(Arg))
3679 A->renderAsInput(Args, CmdArgs);
3680 // Add the default headers if dxc_no_stdinc is not set.
3681 if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
3682 !Args.hasArg(options::OPT_nostdinc))
3683 CmdArgs.push_back("-finclude-default-header");
3684}
3685
3686static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
3687 ArgStringList &CmdArgs, types::ID InputType) {
3688 if (!Args.hasArg(options::OPT_fopenacc))
3689 return;
3690
3691 CmdArgs.push_back("-fopenacc");
3692
3693 if (Arg *A = Args.getLastArg(options::OPT_openacc_macro_override)) {
3694 StringRef Value = A->getValue();
3695 int Version;
3696 if (!Value.getAsInteger(10, Version))
3697 A->renderAsInput(Args, CmdArgs);
3698 else
3699 D.Diag(diag::err_drv_clang_unsupported) << Value;
3700 }
3701}
3702
3703static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
3704 ArgStringList &CmdArgs) {
3705 bool ARCMTEnabled = false;
3706 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3707 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3708 options::OPT_ccc_arcmt_modify,
3709 options::OPT_ccc_arcmt_migrate)) {
3710 ARCMTEnabled = true;
3711 switch (A->getOption().getID()) {
3712 default: llvm_unreachable("missed a case");
3713 case options::OPT_ccc_arcmt_check:
3714 CmdArgs.push_back("-arcmt-action=check");
3715 break;
3716 case options::OPT_ccc_arcmt_modify:
3717 CmdArgs.push_back("-arcmt-action=modify");
3718 break;
3719 case options::OPT_ccc_arcmt_migrate:
3720 CmdArgs.push_back("-arcmt-action=migrate");
3721 CmdArgs.push_back("-mt-migrate-directory");
3722 CmdArgs.push_back(A->getValue());
3723
3724 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3725 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3726 break;
3727 }
3728 }
3729 } else {
3730 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3731 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3732 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3733 }
3734
3735 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3736 if (ARCMTEnabled)
3737 D.Diag(diag::err_drv_argument_not_allowed_with)
3738 << A->getAsString(Args) << "-ccc-arcmt-migrate";
3739
3740 CmdArgs.push_back("-mt-migrate-directory");
3741 CmdArgs.push_back(A->getValue());
3742
3743 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3744 options::OPT_objcmt_migrate_subscripting,
3745 options::OPT_objcmt_migrate_property)) {
3746 // None specified, means enable them all.
3747 CmdArgs.push_back("-objcmt-migrate-literals");
3748 CmdArgs.push_back("-objcmt-migrate-subscripting");
3749 CmdArgs.push_back("-objcmt-migrate-property");
3750 } else {
3751 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3752 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3753 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3754 }
3755 } else {
3756 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3757 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3758 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3759 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3760 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3761 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3762 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
3763 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3764 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3765 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3766 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3767 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3768 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3769 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3770 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3771 Args.AddLastArg(CmdArgs, options::OPT_objcmt_allowlist_dir_path);
3772 }
3773}
3774
3775static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3776 const ArgList &Args, ArgStringList &CmdArgs) {
3777 // -fbuiltin is default unless -mkernel is used.
3778 bool UseBuiltins =
3779 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3780 !Args.hasArg(options::OPT_mkernel));
3781 if (!UseBuiltins)
3782 CmdArgs.push_back("-fno-builtin");
3783
3784 // -ffreestanding implies -fno-builtin.
3785 if (Args.hasArg(options::OPT_ffreestanding))
3786 UseBuiltins = false;
3787
3788 // Process the -fno-builtin-* options.
3789 for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
3790 A->claim();
3791
3792 // If -fno-builtin is specified, then there's no need to pass the option to
3793 // the frontend.
3794 if (UseBuiltins)
3795 A->render(Args, CmdArgs);
3796 }
3797
3798 // le32-specific flags:
3799 // -fno-math-builtin: clang should not convert math builtins to intrinsics
3800 // by default.
3801 if (TC.getArch() == llvm::Triple::le32)
3802 CmdArgs.push_back("-fno-math-builtin");
3803}
3804
3806 if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
3807 Twine Path{Str};
3808 Path.toVector(Result);
3809 return Path.getSingleStringRef() != "";
3810 }
3811 if (llvm::sys::path::cache_directory(Result)) {
3812 llvm::sys::path::append(Result, "clang");
3813 llvm::sys::path::append(Result, "ModuleCache");
3814 return true;
3815 }
3816 return false;
3817}
3818
3821 const char *BaseInput) {
3822 if (Arg *ModuleOutputEQ = Args.getLastArg(options::OPT_fmodule_output_EQ))
3823 return StringRef(ModuleOutputEQ->getValue());
3824
3825 SmallString<256> OutputPath;
3826 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o);
3827 FinalOutput && Args.hasArg(options::OPT_c))
3828 OutputPath = FinalOutput->getValue();
3829 else
3830 OutputPath = BaseInput;
3831
3832 const char *Extension = types::getTypeTempSuffix(types::TY_ModuleFile);
3833 llvm::sys::path::replace_extension(OutputPath, Extension);
3834 return OutputPath;
3835}
3836
3838 const ArgList &Args, const InputInfo &Input,
3839 const InputInfo &Output, bool HaveStd20,
3840 ArgStringList &CmdArgs) {
3841 bool IsCXX = types::isCXX(Input.getType());
3842 bool HaveStdCXXModules = IsCXX && HaveStd20;
3843 bool HaveModules = HaveStdCXXModules;
3844
3845 // -fmodules enables the use of precompiled modules (off by default).
3846 // Users can pass -fno-cxx-modules to turn off modules support for
3847 // C++/Objective-C++ programs.
3848 bool HaveClangModules = false;
3849 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3850 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3851 options::OPT_fno_cxx_modules, true);
3852 if (AllowedInCXX || !IsCXX) {
3853 CmdArgs.push_back("-fmodules");
3854 HaveClangModules = true;
3855 }
3856 }
3857
3858 HaveModules |= HaveClangModules;
3859
3860 // -fmodule-maps enables implicit reading of module map files. By default,
3861 // this is enabled if we are using Clang's flavor of precompiled modules.
3862 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
3863 options::OPT_fno_implicit_module_maps, HaveClangModules))
3864 CmdArgs.push_back("-fimplicit-module-maps");
3865
3866 // -fmodules-decluse checks that modules used are declared so (off by default)
3867 Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
3868 options::OPT_fno_modules_decluse);
3869
3870 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3871 // all #included headers are part of modules.
3872 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3873 options::OPT_fno_modules_strict_decluse, false))
3874 CmdArgs.push_back("-fmodules-strict-decluse");
3875
3876 // -fno-implicit-modules turns off implicitly compiling modules on demand.
3877 bool ImplicitModules = false;
3878 if (!Args.hasFlag(options::OPT_fimplicit_modules,
3879 options::OPT_fno_implicit_modules, HaveClangModules)) {
3880 if (HaveModules)
3881 CmdArgs.push_back("-fno-implicit-modules");
3882 } else if (HaveModules) {
3883 ImplicitModules = true;
3884 // -fmodule-cache-path specifies where our implicitly-built module files
3885 // should be written.
3886 SmallString<128> Path;
3887 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3888 Path = A->getValue();
3889
3890 bool HasPath = true;
3891 if (C.isForDiagnostics()) {
3892 // When generating crash reports, we want to emit the modules along with
3893 // the reproduction sources, so we ignore any provided module path.
3894 Path = Output.getFilename();
3895 llvm::sys::path::replace_extension(Path, ".cache");
3896 llvm::sys::path::append(Path, "modules");
3897 } else if (Path.empty()) {
3898 // No module path was provided: use the default.
3899 HasPath = Driver::getDefaultModuleCachePath(Path);
3900 }
3901
3902 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
3903 // That being said, that failure is unlikely and not caching is harmless.
3904 if (HasPath) {
3905 const char Arg[] = "-fmodules-cache-path=";
3906 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
3907 CmdArgs.push_back(Args.MakeArgString(Path));
3908 }
3909 }
3910
3911 if (HaveModules) {
3912 if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
3913 options::OPT_fno_prebuilt_implicit_modules, false))
3914 CmdArgs.push_back("-fprebuilt-implicit-modules");
3915 if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
3916 options::OPT_fno_modules_validate_input_files_content,
3917 false))
3918 CmdArgs.push_back("-fvalidate-ast-input-files-content");
3919 }
3920
3921 // -fmodule-name specifies the module that is currently being built (or
3922 // used for header checking by -fmodule-maps).
3923 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
3924
3925 // -fmodule-map-file can be used to specify files containing module
3926 // definitions.
3927 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
3928
3929 // -fbuiltin-module-map can be used to load the clang
3930 // builtin headers modulemap file.
3931 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
3932 SmallString<128> BuiltinModuleMap(D.ResourceDir);
3933 llvm::sys::path::append(BuiltinModuleMap, "include");
3934 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
3935 if (llvm::sys::fs::exists(BuiltinModuleMap))
3936 CmdArgs.push_back(
3937 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
3938 }
3939
3940 // The -fmodule-file=<name>=<file> form specifies the mapping of module
3941 // names to precompiled module files (the module is loaded only if used).
3942 // The -fmodule-file=<file> form can be used to unconditionally load
3943 // precompiled module files (whether used or not).
3944 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
3945 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
3946
3947 // -fprebuilt-module-path specifies where to load the prebuilt module files.
3948 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
3949 CmdArgs.push_back(Args.MakeArgString(
3950 std::string("-fprebuilt-module-path=") + A->getValue()));
3951 A->claim();
3952 }
3953 } else
3954 Args.ClaimAllArgs(options::OPT_fmodule_file);
3955
3956 // When building modules and generating crashdumps, we need to dump a module
3957 // dependency VFS alongside the output.
3958 if (HaveClangModules && C.isForDiagnostics()) {
3959 SmallString<128> VFSDir(Output.getFilename());
3960 llvm::sys::path::replace_extension(VFSDir, ".cache");
3961 // Add the cache directory as a temp so the crash diagnostics pick it up.
3962 C.addTempFile(Args.MakeArgString(VFSDir));
3963
3964 llvm::sys::path::append(VFSDir, "vfs");
3965 CmdArgs.push_back("-module-dependency-dir");
3966 CmdArgs.push_back(Args.MakeArgString(VFSDir));
3967 }
3968
3969 if (HaveClangModules)
3970 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
3971
3972 // Pass through all -fmodules-ignore-macro arguments.
3973 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3974 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3975 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3976
3977 if (HaveClangModules) {
3978 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
3979
3980 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
3981 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
3982 D.Diag(diag::err_drv_argument_not_allowed_with)
3983 << A->getAsString(Args) << "-fbuild-session-timestamp";
3984
3985 llvm::sys::fs::file_status Status;
3986 if (llvm::sys::fs::status(A->getValue(), Status))
3987 D.Diag(diag::err_drv_no_such_file) << A->getValue();
3988 CmdArgs.push_back(Args.MakeArgString(
3989 "-fbuild-session-timestamp=" +
3990 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
3991 Status.getLastModificationTime().time_since_epoch())
3992 .count())));
3993 }
3994
3995 if (Args.getLastArg(
3996 options::OPT_fmodules_validate_once_per_build_session)) {
3997 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
3998 options::OPT_fbuild_session_file))
3999 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4000
4001 Args.AddLastArg(CmdArgs,
4002 options::OPT_fmodules_validate_once_per_build_session);
4003 }
4004
4005 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
4006 options::OPT_fno_modules_validate_system_headers,
4007 ImplicitModules))
4008 CmdArgs.push_back("-fmodules-validate-system-headers");
4009
4010 Args.AddLastArg(CmdArgs,
4011 options::OPT_fmodules_disable_diagnostic_validation);
4012 } else {
4013 Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
4014 Args.ClaimAllArgs(options::OPT_fbuild_session_file);
4015 Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
4016 Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
4017 Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
4018 Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
4019 }
4020
4021 // FIXME: We provisionally don't check ODR violations for decls in the global
4022 // module fragment.
4023 CmdArgs.push_back("-fskip-odr-check-in-gmf");
4024
4025 if (Args.hasArg(options::OPT_modules_reduced_bmi) &&
4026 (Input.getType() == driver::types::TY_CXXModule ||
4027 Input.getType() == driver::types::TY_PP_CXXModule)) {
4028 CmdArgs.push_back("-fexperimental-modules-reduced-bmi");
4029
4030 if (Args.hasArg(options::OPT_fmodule_output_EQ))
4031 Args.AddLastArg(CmdArgs, options::OPT_fmodule_output_EQ);
4032 else
4033 CmdArgs.push_back(Args.MakeArgString(
4034 "-fmodule-output=" +
4036 }
4037
4038 // Noop if we see '-fexperimental-modules-reduced-bmi' with other translation
4039 // units than module units. This is more user friendly to allow end uers to
4040 // enable this feature without asking for help from build systems.
4041 Args.ClaimAllArgs(options::OPT_modules_reduced_bmi);
4042
4043 // We need to include the case the input file is a module file here.
4044 // Since the default compilation model for C++ module interface unit will
4045 // create temporary module file and compile the temporary module file
4046 // to get the object file. Then the `-fmodule-output` flag will be
4047 // brought to the second compilation process. So we have to claim it for
4048 // the case too.
4049 if (Input.getType() == driver::types::TY_CXXModule ||
4050 Input.getType() == driver::types::TY_PP_CXXModule ||
4051 Input.getType() == driver::types::TY_ModuleFile) {
4052 Args.ClaimAllArgs(options::OPT_fmodule_output);
4053 Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
4054 }
4055
4056 return HaveModules;
4057}
4058
4059static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4060 ArgStringList &CmdArgs) {
4061 // -fsigned-char is default.
4062 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
4063 options::OPT_fno_signed_char,
4064 options::OPT_funsigned_char,
4065 options::OPT_fno_unsigned_char)) {
4066 if (A->getOption().matches(options::OPT_funsigned_char) ||
4067 A->getOption().matches(options::OPT_fno_signed_char)) {
4068 CmdArgs.push_back("-fno-signed-char");
4069 }
4070 } else if (!isSignedCharDefault(T)) {
4071 CmdArgs.push_back("-fno-signed-char");
4072 }
4073
4074 // The default depends on the language standard.
4075 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
4076
4077 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4078 options::OPT_fno_short_wchar)) {
4079 if (A->getOption().matches(options::OPT_fshort_wchar)) {
4080 CmdArgs.push_back("-fwchar-type=short");
4081 CmdArgs.push_back("-fno-signed-wchar");
4082 } else {
4083 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4084 CmdArgs.push_back("-fwchar-type=int");
4085 if (T.isOSzOS() ||
4086 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4087 CmdArgs.push_back("-fno-signed-wchar");
4088 else
4089 CmdArgs.push_back("-fsigned-wchar");
4090 }
4091 } else if (T.isOSzOS())
4092 CmdArgs.push_back("-fno-signed-wchar");
4093}
4094
4095static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4096 const llvm::Triple &T, const ArgList &Args,
4097 ObjCRuntime &Runtime, bool InferCovariantReturns,
4098 const InputInfo &Input, ArgStringList &CmdArgs) {
4099 const llvm::Triple::ArchType Arch = TC.getArch();
4100
4101 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4102 // is the default. Except for deployment target of 10.5, next runtime is
4103 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4104 if (Runtime.isNonFragile()) {
4105 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4106 options::OPT_fno_objc_legacy_dispatch,
4107 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
4108 if (TC.UseObjCMixedDispatch())
4109 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
4110 else
4111 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
4112 }
4113 }
4114
4115 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4116 // to do Array/Dictionary subscripting by default.
4117 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4118 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4119 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4120
4121 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4122 // NOTE: This logic is duplicated in ToolChains.cpp.
4123 if (isObjCAutoRefCount(Args)) {
4124 TC.CheckObjCARC();
4125
4126 CmdArgs.push_back("-fobjc-arc");
4127
4128 // FIXME: It seems like this entire block, and several around it should be
4129 // wrapped in isObjC, but for now we just use it here as this is where it
4130 // was being used previously.
4131 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
4133 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4134 else
4135 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4136 }
4137
4138 // Allow the user to enable full exceptions code emission.
4139 // We default off for Objective-C, on for Objective-C++.
4140 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4141 options::OPT_fno_objc_arc_exceptions,
4142 /*Default=*/types::isCXX(Input.getType())))
4143 CmdArgs.push_back("-fobjc-arc-exceptions");
4144 }
4145
4146 // Silence warning for full exception code emission options when explicitly
4147 // set to use no ARC.
4148 if (Args.hasArg(options::OPT_fno_objc_arc)) {
4149 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
4150 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
4151 }
4152
4153 // Allow the user to control whether messages can be converted to runtime
4154 // functions.
4155 if (types::isObjC(Input.getType())) {
4156 auto *Arg = Args.getLastArg(
4157 options::OPT_fobjc_convert_messages_to_runtime_calls,
4158 options::OPT_fno_objc_convert_messages_to_runtime_calls);
4159 if (Arg &&
4160 Arg->getOption().matches(
4161 options::OPT_fno_objc_convert_messages_to_runtime_calls))
4162 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
4163 }
4164
4165 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4166 // rewriter.
4167 if (InferCovariantReturns)
4168 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4169
4170 // Pass down -fobjc-weak or -fno-objc-weak if present.
4171 if (types::isObjC(Input.getType())) {
4172 auto WeakArg =
4173 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
4174 if (!WeakArg) {
4175 // nothing to do
4176 } else if (!Runtime.allowsWeak()) {
4177 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
4178 D.Diag(diag::err_objc_weak_unsupported);
4179 } else {
4180 WeakArg->render(Args, CmdArgs);
4181 }
4182 }
4183
4184 if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4185 CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
4186}
4187
4188static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4189 ArgStringList &CmdArgs) {
4190 bool CaretDefault = true;
4191 bool ColumnDefault = true;
4192
4193 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4194 options::OPT__SLASH_diagnostics_column,
4195 options::OPT__SLASH_diagnostics_caret)) {
4196 switch (A->getOption().getID()) {
4197 case options::OPT__SLASH_diagnostics_caret:
4198 CaretDefault = true;
4199 ColumnDefault = true;
4200 break;
4201 case options::OPT__SLASH_diagnostics_column:
4202 CaretDefault = false;
4203 ColumnDefault = true;
4204 break;
4205 case options::OPT__SLASH_diagnostics_classic:
4206 CaretDefault = false;
4207 ColumnDefault = false;
4208 break;
4209 }
4210 }
4211
4212 // -fcaret-diagnostics is default.
4213 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4214 options::OPT_fno_caret_diagnostics, CaretDefault))
4215 CmdArgs.push_back("-fno-caret-diagnostics");
4216
4217 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
4218 options::OPT_fno_diagnostics_fixit_info);
4219 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
4220 options::OPT_fno_diagnostics_show_option);
4221
4222 if (const Arg *A =
4223 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4224 CmdArgs.push_back("-fdiagnostics-show-category");
4225 CmdArgs.push_back(A->getValue());
4226 }
4227
4228 Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
4229 options::OPT_fno_diagnostics_show_hotness);
4230
4231 if (const Arg *A =
4232 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4233 std::string Opt =
4234 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4235 CmdArgs.push_back(Args.MakeArgString(Opt));
4236 }
4237
4238 if (const Arg *A =
4239 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4240 std::string Opt =
4241 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4242 CmdArgs.push_back(Args.MakeArgString(Opt));
4243 }
4244
4245 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4246 CmdArgs.push_back("-fdiagnostics-format");
4247 CmdArgs.push_back(A->getValue());
4248 if (StringRef(A->getValue()) == "sarif" ||
4249 StringRef(A->getValue()) == "SARIF")
4250 D.Diag(diag::warn_drv_sarif_format_unstable);
4251 }
4252
4253 if (const Arg *A = Args.getLastArg(
4254 options::OPT_fdiagnostics_show_note_include_stack,
4255 options::OPT_fno_diagnostics_show_note_include_stack)) {
4256 const Option &O = A->getOption();
4257 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4258 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4259 else
4260 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4261 }
4262
4263 // Color diagnostics are parsed by the driver directly from argv and later
4264 // re-parsed to construct this job; claim any possible color diagnostic here
4265 // to avoid warn_drv_unused_argument and diagnose bad
4266 // OPT_fdiagnostics_color_EQ values.
4267 Args.getLastArg(options::OPT_fcolor_diagnostics,
4268 options::OPT_fno_color_diagnostics);
4269 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_color_EQ)) {
4270 StringRef Value(A->getValue());
4271 if (Value != "always" && Value != "never" && Value != "auto")
4272 D.Diag(diag::err_drv_invalid_argument_to_option)
4273 << Value << A->getOption().getName();
4274 }
4275
4276 if (D.getDiags().getDiagnosticOptions().ShowColors)
4277 CmdArgs.push_back("-fcolor-diagnostics");
4278
4279 if (Args.hasArg(options::OPT_fansi_escape_codes))
4280 CmdArgs.push_back("-fansi-escape-codes");
4281
4282 Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
4283 options::OPT_fno_show_source_location);
4284
4285 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
4286 options::OPT_fno_diagnostics_show_line_numbers);
4287
4288 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4289 CmdArgs.push_back("-fdiagnostics-absolute-paths");
4290
4291 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4292 ColumnDefault))
4293 CmdArgs.push_back("-fno-show-column");
4294
4295 Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
4296 options::OPT_fno_spell_checking);
4297}
4298
4300 const ArgList &Args, Arg *&Arg) {
4301 Arg = Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ,
4302 options::OPT_gno_split_dwarf);
4303 if (!Arg || Arg->getOption().matches(options::OPT_gno_split_dwarf))
4305
4306 if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
4308
4309 StringRef Value = Arg->getValue();
4310 if (Value == "split")
4312 if (Value == "single")
4314
4315 D.Diag(diag::err_drv_unsupported_option_argument)
4316 << Arg->getSpelling() << Arg->getValue();
4318}
4319
4320static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4321 const ArgList &Args, ArgStringList &CmdArgs,
4322 unsigned DwarfVersion) {
4323 auto *DwarfFormatArg =
4324 Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4325 if (!DwarfFormatArg)
4326 return;
4327
4328 if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4329 if (DwarfVersion < 3)
4330 D.Diag(diag::err_drv_argument_only_allowed_with)
4331 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4332 else if (!T.isArch64Bit())
4333 D.Diag(diag::err_drv_argument_only_allowed_with)
4334 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4335 else if (!T.isOSBinFormatELF())
4336 D.Diag(diag::err_drv_argument_only_allowed_with)
4337 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4338 }
4339
4340 DwarfFormatArg->render(Args, CmdArgs);
4341}
4342
4343static void
4344renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4345 const ArgList &Args, bool IRInput, ArgStringList &CmdArgs,
4346 const InputInfo &Output,
4347 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4348 DwarfFissionKind &DwarfFission) {
4349 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
4350 options::OPT_fno_debug_info_for_profiling, false) &&
4352 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
4353 CmdArgs.push_back("-fdebug-info-for-profiling");
4354
4355 // The 'g' groups options involve a somewhat intricate sequence of decisions
4356 // about what to pass from the driver to the frontend, but by the time they
4357 // reach cc1 they've been factored into three well-defined orthogonal choices:
4358 // * what level of debug info to generate
4359 // * what dwarf version to write
4360 // * what debugger tuning to use
4361 // This avoids having to monkey around further in cc1 other than to disable
4362 // codeview if not running in a Windows environment. Perhaps even that
4363 // decision should be made in the driver as well though.
4364 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4365
4366 bool SplitDWARFInlining =
4367 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4368 options::OPT_fno_split_dwarf_inlining, false);
4369
4370 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4371 // object file generation and no IR generation, -gN should not be needed. So
4372 // allow -gsplit-dwarf with either -gN or IR input.
4373 if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4374 Arg *SplitDWARFArg;
4375 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
4376 if (DwarfFission != DwarfFissionKind::None &&
4377 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
4378 DwarfFission = DwarfFissionKind::None;
4379 SplitDWARFInlining = false;
4380 }
4381 }
4382 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4383 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4384
4385 // If the last option explicitly specified a debug-info level, use it.
4386 if (checkDebugInfoOption(A, Args, D, TC) &&
4387 A->getOption().matches(options::OPT_gN_Group)) {
4388 DebugInfoKind = debugLevelToInfoKind(*A);
4389 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4390 // complicated if you've disabled inline info in the skeleton CUs
4391 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4392 // line-tables-only, so let those compose naturally in that case.
4393 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4394 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4395 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4396 SplitDWARFInlining))
4397 DwarfFission = DwarfFissionKind::None;
4398 }
4399 }
4400
4401 // If a debugger tuning argument appeared, remember it.
4402 bool HasDebuggerTuning = false;
4403 if (const Arg *A =
4404 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4405 HasDebuggerTuning = true;
4406 if (checkDebugInfoOption(A, Args, D, TC)) {
4407 if (A->getOption().matches(options::OPT_glldb))
4408 DebuggerTuning = llvm::DebuggerKind::LLDB;
4409 else if (A->getOption().matches(options::OPT_gsce))
4410 DebuggerTuning = llvm::DebuggerKind::SCE;
4411 else if (A->getOption().matches(options::OPT_gdbx))
4412 DebuggerTuning = llvm::DebuggerKind::DBX;
4413 else
4414 DebuggerTuning = llvm::DebuggerKind::GDB;
4415 }
4416 }
4417
4418 // If a -gdwarf argument appeared, remember it.
4419 bool EmitDwarf = false;
4420 if (const Arg *A = getDwarfNArg(Args))
4421 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4422
4423 bool EmitCodeView = false;
4424 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4425 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4426
4427 // If the user asked for debug info but did not explicitly specify -gcodeview
4428 // or -gdwarf, ask the toolchain for the default format.
4429 if (!EmitCodeView && !EmitDwarf &&
4430 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4431 switch (TC.getDefaultDebugFormat()) {
4432 case llvm::codegenoptions::DIF_CodeView:
4433 EmitCodeView = true;
4434 break;
4435 case llvm::codegenoptions::DIF_DWARF:
4436 EmitDwarf = true;
4437 break;
4438 }
4439 }
4440
4441 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4442 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4443 // be lower than what the user wanted.
4444 if (EmitDwarf) {
4445 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4446 // Clamp effective DWARF version to the max supported by the toolchain.
4447 EffectiveDWARFVersion =
4448 std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4449 } else {
4450 Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4451 }
4452
4453 // -gline-directives-only supported only for the DWARF debug info.
4454 if (RequestedDWARFVersion == 0 &&
4455 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4456 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4457
4458 // strict DWARF is set to false by default. But for DBX, we need it to be set
4459 // as true by default.
4460 if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4461 (void)checkDebugInfoOption(A, Args, D, TC);
4462 if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4463 DebuggerTuning == llvm::DebuggerKind::DBX))
4464 CmdArgs.push_back("-gstrict-dwarf");
4465
4466 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4467 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4468
4469 // Column info is included by default for everything except SCE and
4470 // CodeView. Clang doesn't track end columns, just starting columns, which,
4471 // in theory, is fine for CodeView (and PDB). In practice, however, the
4472 // Microsoft debuggers don't handle missing end columns well, and the AIX
4473 // debugger DBX also doesn't handle the columns well, so it's better not to
4474 // include any column info.
4475 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4476 (void)checkDebugInfoOption(A, Args, D, TC);
4477 if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4478 !EmitCodeView &&
4479 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4480 DebuggerTuning != llvm::DebuggerKind::DBX)))
4481 CmdArgs.push_back("-gno-column-info");
4482
4483 // FIXME: Move backend command line options to the module.
4484 if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4485 // If -gline-tables-only or -gline-directives-only is the last option it
4486 // wins.
4487 if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4488 TC)) {
4489 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4490 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4491 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4492 CmdArgs.push_back("-dwarf-ext-refs");
4493 CmdArgs.push_back("-fmodule-format=obj");
4494 }
4495 }
4496 }
4497
4498 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4499 CmdArgs.push_back("-fsplit-dwarf-inlining");
4500
4501 // After we've dealt with all combinations of things that could
4502 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4503 // figure out if we need to "upgrade" it to standalone debug info.
4504 // We parse these two '-f' options whether or not they will be used,
4505 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4506 bool NeedFullDebug = Args.hasFlag(
4507 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4508 DebuggerTuning == llvm::DebuggerKind::LLDB ||
4510 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4511 (void)checkDebugInfoOption(A, Args, D, TC);
4512
4513 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4514 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4515 if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4516 options::OPT_feliminate_unused_debug_types, false))
4517 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4518 else if (NeedFullDebug)
4519 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4520 }
4521
4522 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4523 false)) {
4524 // Source embedding is a vendor extension to DWARF v5. By now we have
4525 // checked if a DWARF version was stated explicitly, and have otherwise
4526 // fallen back to the target default, so if this is still not at least 5
4527 // we emit an error.
4528 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4529 if (RequestedDWARFVersion < 5)
4530 D.Diag(diag::err_drv_argument_only_allowed_with)
4531 << A->getAsString(Args) << "-gdwarf-5";
4532 else if (EffectiveDWARFVersion < 5)
4533 // The toolchain has reduced allowed dwarf version, so we can't enable
4534 // -gembed-source.
4535 D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4536 << A->getAsString(Args) << TC.getTripleString() << 5
4537 << EffectiveDWARFVersion;
4538 else if (checkDebugInfoOption(A, Args, D, TC))
4539 CmdArgs.push_back("-gembed-source");
4540 }
4541
4542 if (EmitCodeView) {
4543 CmdArgs.push_back("-gcodeview");
4544
4545 Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4546 options::OPT_gno_codeview_ghash);
4547
4548 Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4549 options::OPT_gno_codeview_command_line);
4550 }
4551
4552 Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4553 options::OPT_gno_inline_line_tables);
4554
4555 // When emitting remarks, we need at least debug lines in the output.
4556 if (willEmitRemarks(Args) &&
4557 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4558 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4559
4560 // Adjust the debug info kind for the given toolchain.
4561 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4562
4563 // On AIX, the debugger tuning option can be omitted if it is not explicitly
4564 // set.
4565 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4566 T.isOSAIX() && !HasDebuggerTuning
4567 ? llvm::DebuggerKind::Default
4568 : DebuggerTuning);
4569
4570 // -fdebug-macro turns on macro debug info generation.
4571 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4572 false))
4573 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4574 D, TC))
4575 CmdArgs.push_back("-debug-info-macro");
4576
4577 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4578 const auto *PubnamesArg =
4579 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4580 options::OPT_gpubnames, options::OPT_gno_pubnames);
4581 if (DwarfFission != DwarfFissionKind::None ||
4582 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC))) {
4583 const bool OptionSet =
4584 (PubnamesArg &&
4585 (PubnamesArg->getOption().matches(options::OPT_gpubnames) ||
4586 PubnamesArg->getOption().matches(options::OPT_ggnu_pubnames)));
4587 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
4588 (!PubnamesArg ||
4589 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4590 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames))))
4591 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4592 options::OPT_gpubnames)
4593 ? "-gpubnames"
4594 : "-ggnu-pubnames");
4595 }
4596 const auto *SimpleTemplateNamesArg =
4597 Args.getLastArg(options::OPT_gsimple_template_names,
4598 options::OPT_gno_simple_template_names);
4599 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4600 if (SimpleTemplateNamesArg &&
4601 checkDebugInfoOption(SimpleTemplateNamesArg, Args, D, TC)) {
4602 const auto &Opt = SimpleTemplateNamesArg->getOption();
4603 if (Opt.matches(options::OPT_gsimple_template_names)) {
4604 ForwardTemplateParams = true;
4605 CmdArgs.push_back("-gsimple-template-names=simple");
4606 }
4607 }
4608
4609 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
4610 bool UseDebugTemplateAlias =
4611 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
4612 if (const auto *DebugTemplateAlias = Args.getLastArg(
4613 options::OPT_gtemplate_alias, options::OPT_gno_template_alias)) {
4614 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
4615 // asks for it we should let them have it (if the target supports it).
4616 if (checkDebugInfoOption(DebugTemplateAlias, Args, D, TC)) {
4617 const auto &Opt = DebugTemplateAlias->getOption();
4618 UseDebugTemplateAlias = Opt.matches(options::OPT_gtemplate_alias);
4619 }
4620 }
4621 if (UseDebugTemplateAlias)
4622 CmdArgs.push_back("-gtemplate-alias");
4623
4624 if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
4625 StringRef v = A->getValue();
4626 CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
4627 }
4628
4629 Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
4630 options::OPT_fno_debug_ranges_base_address);
4631
4632 // -gdwarf-aranges turns on the emission of the aranges section in the
4633 // backend.
4634 // Always enabled for SCE tuning.
4635 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
4636 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
4637 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
4638 if (NeedAranges) {
4639 CmdArgs.push_back("-mllvm");
4640 CmdArgs.push_back("-generate-arange-section");
4641 }
4642
4643 Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
4644 options::OPT_fno_force_dwarf_frame);
4645
4646 bool EnableTypeUnits = false;
4647 if (Args.hasFlag(options::OPT_fdebug_types_section,
4648 options::OPT_fno_debug_types_section, false)) {
4649 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4650 D.Diag(diag::err_drv_unsupported_opt_for_target)
4651 << Args.getLastArg(options::OPT_fdebug_types_section)
4652 ->getAsString(Args)
4653 << T.getTriple();
4654 } else if (checkDebugInfoOption(
4655 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
4656 TC)) {
4657 EnableTypeUnits = true;
4658 CmdArgs.push_back("-mllvm");
4659 CmdArgs.push_back("-generate-type-units");
4660 }
4661 }
4662
4663 if (const Arg *A =
4664 Args.getLastArg(options::OPT_gomit_unreferenced_methods,
4665 options::OPT_gno_omit_unreferenced_methods))
4666 (void)checkDebugInfoOption(A, Args, D, TC);
4667 if (Args.hasFlag(options::OPT_gomit_unreferenced_methods,
4668 options::OPT_gno_omit_unreferenced_methods, false) &&
4669 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
4670 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
4671 !EnableTypeUnits) {
4672 CmdArgs.push_back("-gomit-unreferenced-methods");
4673 }
4674
4675 // To avoid join/split of directory+filename, the integrated assembler prefers
4676 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4677 // form before DWARF v5.
4678 if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
4679 options::OPT_fno_dwarf_directory_asm,
4680 TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4681 CmdArgs.push_back("-fno-dwarf-directory-asm");
4682
4683 // Decide how to render forward declarations of template instantiations.
4684 // SCE wants full descriptions, others just get them in the name.
4685 if (ForwardTemplateParams)
4686 CmdArgs.push_back("-debug-forward-template-params");
4687
4688 // Do we need to explicitly import anonymous namespaces into the parent
4689 // scope?
4690 if (DebuggerTuning == llvm::DebuggerKind::SCE)
4691 CmdArgs.push_back("-dwarf-explicit-import");
4692
4693 renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
4694 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4695
4696 // This controls whether or not we perform JustMyCode instrumentation.
4697 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
4698 if (TC.getTriple().isOSBinFormatELF() || D.IsCLMode()) {
4699 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
4700 CmdArgs.push_back("-fjmc");
4701 else if (D.IsCLMode())
4702 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
4703 << "'/Zi', '/Z7'";
4704 else
4705 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
4706 << "-g";
4707 } else {
4708 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
4709 }
4710 }
4711
4712 // Add in -fdebug-compilation-dir if necessary.
4713 const char *DebugCompilationDir =
4714 addDebugCompDirArg(Args, CmdArgs, D.getVFS());
4715
4716 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
4717
4718 // Add the output path to the object file for CodeView debug infos.
4719 if (EmitCodeView && Output.isFilename())
4720 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
4721 Output.getFilename());
4722}
4723
4724static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
4725 ArgStringList &CmdArgs) {
4726 unsigned RTOptionID = options::OPT__SLASH_MT;
4727
4728 if (Args.hasArg(options::OPT__SLASH_LDd))
4729 // The /LDd option implies /MTd. The dependent lib part can be overridden,
4730 // but defining _DEBUG is sticky.
4731 RTOptionID = options::OPT__SLASH_MTd;
4732
4733 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4734 RTOptionID = A->getOption().getID();
4735
4736 if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
4737 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
4738 .Case("static", options::OPT__SLASH_MT)
4739 .Case("static_dbg", options::OPT__SLASH_MTd)
4740 .Case("dll", options::OPT__SLASH_MD)
4741 .Case("dll_dbg", options::OPT__SLASH_MDd)
4742 .Default(options::OPT__SLASH_MT);
4743 }
4744
4745 StringRef FlagForCRT;
4746 switch (RTOptionID) {
4747 case options::OPT__SLASH_MD:
4748 if (Args.hasArg(options::OPT__SLASH_LDd))
4749 CmdArgs.push_back("-D_DEBUG");
4750 CmdArgs.push_back("-D_MT");
4751 CmdArgs.push_back("-D_DLL");
4752 FlagForCRT = "--dependent-lib=msvcrt";
4753 break;
4754 case options::OPT__SLASH_MDd:
4755 CmdArgs.push_back("-D_DEBUG");
4756 CmdArgs.push_back("-D_MT");
4757 CmdArgs.push_back("-D_DLL");
4758 FlagForCRT = "--dependent-lib=msvcrtd";
4759 break;
4760 case options::OPT__SLASH_MT:
4761 if (Args.hasArg(options::OPT__SLASH_LDd))
4762 CmdArgs.push_back("-D_DEBUG");
4763 CmdArgs.push_back("-D_MT");
4764 CmdArgs.push_back("-flto-visibility-public-std");
4765 FlagForCRT = "--dependent-lib=libcmt";
4766 break;
4767 case options::OPT__SLASH_MTd:
4768 CmdArgs.push_back("-D_DEBUG");
4769 CmdArgs.push_back("-D_MT");
4770 CmdArgs.push_back("-flto-visibility-public-std");
4771 FlagForCRT = "--dependent-lib=libcmtd";
4772 break;
4773 default:
4774 llvm_unreachable("Unexpected option ID.");
4775 }
4776
4777 if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
4778 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
4779 } else {
4780 CmdArgs.push_back(FlagForCRT.data());
4781
4782 // This provides POSIX compatibility (maps 'open' to '_open'), which most
4783 // users want. The /Za flag to cl.exe turns this off, but it's not
4784 // implemented in clang.
4785 CmdArgs.push_back("--dependent-lib=oldnames");
4786 }
4787
4788 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
4789 // even if the file doesn't actually refer to any of the routines because
4790 // the CRT itself has incomplete dependency markings.
4791 if (TC.getTriple().isWindowsArm64EC())
4792 CmdArgs.push_back("--dependent-lib=softintrin");
4793}
4794
4796 const InputInfo &Output, const InputInfoList &Inputs,
4797 const ArgList &Args, const char *LinkingOutput) const {
4798 const auto &TC = getToolChain();
4799 const llvm::Triple &RawTriple = TC.getTriple();
4800 const llvm::Triple &Triple = TC.getEffectiveTriple();
4801 const std::string &TripleStr = Triple.getTriple();
4802
4803 bool KernelOrKext =
4804 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
4805 const Driver &D = TC.getDriver();
4806 ArgStringList CmdArgs;
4807
4808 assert(Inputs.size() >= 1 && "Must have at least one input.");
4809 // CUDA/HIP compilation may have multiple inputs (source file + results of
4810 // device-side compilations). OpenMP device jobs also take the host IR as a
4811 // second input. Module precompilation accepts a list of header files to
4812 // include as part of the module. API extraction accepts a list of header
4813 // files whose API information is emitted in the output. All other jobs are
4814 // expected to have exactly one input.
4815 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
4816 bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
4817 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
4818 bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
4819 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
4820 bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
4821 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
4823 bool IsHostOffloadingAction =
4825 (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
4826 Args.hasFlag(options::OPT_offload_new_driver,
4827 options::OPT_no_offload_new_driver, false));
4828
4829 bool IsRDCMode =
4830 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
4831 bool IsUsingLTO = D.isUsingLTO(IsDeviceOffloadAction);
4832 auto LTOMode = D.getLTOMode(IsDeviceOffloadAction);
4833
4834 // Extract API doesn't have a main input file, so invent a fake one as a
4835 // placeholder.
4836 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
4837 "extract-api");
4838
4839 const InputInfo &Input =
4840 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
4841
4842 InputInfoList ExtractAPIInputs;
4843 InputInfoList HostOffloadingInputs;
4844 const InputInfo *CudaDeviceInput = nullptr;
4845 const InputInfo *OpenMPDeviceInput = nullptr;
4846 for (const InputInfo &I : Inputs) {
4847 if (&I == &Input || I.getType() == types::TY_Nothing) {
4848 // This is the primary input or contains nothing.
4849 } else if (IsExtractAPI) {
4850 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
4851 if (I.getType() != ExpectedInputType) {
4852 D.Diag(diag::err_drv_extract_api_wrong_kind)
4853 << I.getFilename() << types::getTypeName(I.getType())
4854 << types::getTypeName(ExpectedInputType);
4855 }
4856 ExtractAPIInputs.push_back(I);
4857 } else if (IsHostOffloadingAction) {
4858 HostOffloadingInputs.push_back(I);
4859 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
4860 CudaDeviceInput = &I;
4861 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
4862 OpenMPDeviceInput = &I;
4863 } else {
4864 llvm_unreachable("unexpectedly given multiple inputs");
4865 }
4866 }
4867
4868 const llvm::Triple *AuxTriple =
4869 (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
4870 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
4871 bool IsIAMCU = RawTriple.isOSIAMCU();
4872
4873 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
4874 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
4875 // Windows), we need to pass Windows-specific flags to cc1.
4876 if (IsCuda || IsHIP)
4877 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
4878
4879 // C++ is not supported for IAMCU.
4880 if (IsIAMCU && types::isCXX(Input.getType()))
4881 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
4882
4883 // Invoke ourselves in -cc1 mode.
4884 //
4885 // FIXME: Implement custom jobs for internal actions.
4886 CmdArgs.push_back("-cc1");
4887
4888 // Add the "effective" target triple.
4889 CmdArgs.push_back("-triple");
4890 CmdArgs.push_back(Args.MakeArgString(TripleStr));
4891
4892 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
4893 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
4894 Args.ClaimAllArgs(options::OPT_MJ);
4895 } else if (const Arg *GenCDBFragment =
4896 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
4897 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
4898 TripleStr, Output, Input, Args);
4899 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
4900 }
4901
4902 if (IsCuda || IsHIP) {
4903 // We have to pass the triple of the host if compiling for a CUDA/HIP device
4904 // and vice-versa.
4905 std::string NormalizedTriple;
4908 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
4909 ->getTriple()
4910 .normalize();
4911 else {
4912 // Host-side compilation.
4913 NormalizedTriple =
4914 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
4915 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
4916 ->getTriple()
4917 .normalize();
4918 if (IsCuda) {
4919 // We need to figure out which CUDA version we're compiling for, as that
4920 // determines how we load and launch GPU kernels.
4921 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
4922 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
4923 assert(CTC && "Expected valid CUDA Toolchain.");
4924 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
4925 CmdArgs.push_back(Args.MakeArgString(
4926 Twine("-target-sdk-version=") +
4927 CudaVersionToString(CTC->CudaInstallation.version())));
4928 // Unsized function arguments used for variadics were introduced in
4929 // CUDA-9.0. We still do not support generating code that actually uses
4930 // variadic arguments yet, but we do need to allow parsing them as
4931 // recent CUDA headers rely on that.
4932 // https://github.com/llvm/llvm-project/issues/58410
4933 if (CTC->CudaInstallation.version() >= CudaVersion::CUDA_90)
4934 CmdArgs.push_back("-fcuda-allow-variadic-functions");
4935 }
4936 }
4937 CmdArgs.push_back("-aux-triple");
4938 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4939
4941 getToolChain().getTriple().isAMDGPU()) {
4942 // Device side compilation printf
4943 if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
4944 CmdArgs.push_back(Args.MakeArgString(
4945 "-mprintf-kind=" +
4946 Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
4947 // Force compiler error on invalid conversion specifiers
4948 CmdArgs.push_back(
4949 Args.MakeArgString("-Werror=format-invalid-specifier"));
4950 }
4951 }
4952 }
4953
4954 // Unconditionally claim the printf option now to avoid unused diagnostic.
4955 if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
4956 PF->claim();
4957
4958 if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false)) {
4959 CmdArgs.push_back("-fsycl-is-device");
4960
4961 if (Arg *A = Args.getLastArg(options::OPT_sycl_std_EQ)) {
4962 A->render(Args, CmdArgs);
4963 } else {
4964 // Ensure the default version in SYCL mode is 2020.
4965 CmdArgs.push_back("-sycl-std=2020");
4966 }
4967 }
4968
4969 if (IsOpenMPDevice) {
4970 // We have to pass the triple of the host if compiling for an OpenMP device.
4971 std::string NormalizedTriple =
4972 C.getSingleOffloadToolChain<Action::OFK_Host>()
4973 ->getTriple()
4974 .normalize();
4975 CmdArgs.push_back("-aux-triple");
4976 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4977 }
4978
4979 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
4980 Triple.getArch() == llvm::Triple::thumb)) {
4981 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
4982 unsigned Version = 0;
4983 bool Failure =
4984 Triple.getArchName().substr(Offset).consumeInteger(10, Version);
4985 if (Failure || Version < 7)
4986 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
4987 << TripleStr;
4988 }
4989
4990 // Push all default warning arguments that are specific to
4991 // the given target. These come before user provided warning options
4992 // are provided.
4993 TC.addClangWarningOptions(CmdArgs);
4994
4995 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
4996 if (Triple.isSPIR() || Triple.isSPIRV())
4997 CmdArgs.push_back("-Wspir-compat");
4998
4999 // Select the appropriate action.
5000 RewriteKind rewriteKind = RK_None;
5001
5002 bool UnifiedLTO = false;
5003 if (IsUsingLTO) {
5004 UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
5005 options::OPT_fno_unified_lto, Triple.isPS());
5006 if (UnifiedLTO)
5007 CmdArgs.push_back("-funified-lto");
5008 }
5009
5010 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5011 // it claims when not running an assembler. Otherwise, clang would emit
5012 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5013 // flags while debugging something. That'd be somewhat inconvenient, and it's
5014 // also inconsistent with most other flags -- we don't warn on
5015 // -ffunction-sections not being used in -E mode either for example, even
5016 // though it's not really used either.
5017 if (!isa<AssembleJobAction>(JA)) {
5018 // The args claimed here should match the args used in
5019 // CollectArgsForIntegratedAssembler().
5020 if (TC.useIntegratedAs()) {
5021 Args.ClaimAllArgs(options::OPT_mrelax_all);
5022 Args.ClaimAllArgs(options::OPT_mno_relax_all);
5023 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
5024 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
5025 switch (C.getDefaultToolChain().getArch()) {
5026 case llvm::Triple::arm:
5027 case llvm::Triple::armeb:
5028 case llvm::Triple::thumb:
5029 case llvm::Triple::thumbeb:
5030 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
5031 break;
5032 default:
5033 break;
5034 }
5035 }
5036 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
5037 Args.ClaimAllArgs(options::OPT_Xassembler);
5038 Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
5039 }
5040
5041 if (isa<AnalyzeJobAction>(JA)) {
5042 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5043 CmdArgs.push_back("-analyze");
5044 } else if (isa<MigrateJobAction>(JA)) {
5045 CmdArgs.push_back("-migrate");
5046 } else if (isa<PreprocessJobAction>(JA)) {
5047 if (Output.getType() == types::TY_Dependencies)
5048 CmdArgs.push_back("-Eonly");
5049 else {
5050 CmdArgs.push_back("-E");
5051 if (Args.hasArg(options::OPT_rewrite_objc) &&
5052 !Args.hasArg(options::OPT_g_Group))
5053 CmdArgs.push_back("-P");
5054 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5055 CmdArgs.push_back("-fdirectives-only");
5056 }
5057 } else if (isa<AssembleJobAction>(JA)) {
5058 CmdArgs.push_back("-emit-obj");
5059
5060 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5061
5062 // Also ignore explicit -force_cpusubtype_ALL option.
5063 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5064 } else if (isa<PrecompileJobAction>(JA)) {
5065 if (JA.getType() == types::TY_Nothing)
5066 CmdArgs.push_back("-fsyntax-only");
5067 else if (JA.getType() == types::TY_ModuleFile)
5068 CmdArgs.push_back("-emit-module-interface");
5069 else if (JA.getType() == types::TY_HeaderUnit)
5070 CmdArgs.push_back("-emit-header-unit");
5071 else
5072 CmdArgs.push_back("-emit-pch");
5073 } else if (isa<VerifyPCHJobAction>(JA)) {
5074 CmdArgs.push_back("-verify-pch");
5075 } else if (isa<ExtractAPIJobAction>(JA)) {
5076 assert(JA.getType() == types::TY_API_INFO &&
5077 "Extract API actions must generate a API information.");
5078 CmdArgs.push_back("-extract-api");
5079
5080 if (Arg *PrettySGFArg = Args.getLastArg(options::OPT_emit_pretty_sgf))
5081 PrettySGFArg->render(Args, CmdArgs);
5082
5083 Arg *SymbolGraphDirArg = Args.getLastArg(options::OPT_symbol_graph_dir_EQ);
5084
5085 if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
5086 ProductNameArg->render(Args, CmdArgs);
5087 if (Arg *ExtractAPIIgnoresFileArg =
5088 Args.getLastArg(options::OPT_extract_api_ignores_EQ))
5089 ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
5090 if (Arg *EmitExtensionSymbolGraphs =
5091 Args.getLastArg(options::OPT_emit_extension_symbol_graphs)) {
5092 if (!SymbolGraphDirArg)
5093 D.Diag(diag::err_drv_missing_symbol_graph_dir);
5094
5095 EmitExtensionSymbolGraphs->render(Args, CmdArgs);
5096 }
5097 if (SymbolGraphDirArg)
5098 SymbolGraphDirArg->render(Args, CmdArgs);
5099 } else {
5100 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5101 "Invalid action for clang tool.");
5102 if (JA.getType() == types::TY_Nothing) {
5103 CmdArgs.push_back("-fsyntax-only");
5104 } else if (JA.getType() == types::TY_LLVM_IR ||
5105 JA.getType() == types::TY_LTO_IR) {
5106 CmdArgs.push_back("-emit-llvm");
5107 } else if (JA.getType() == types::TY_LLVM_BC ||
5108 JA.getType() == types::TY_LTO_BC) {
5109 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5110 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
5111 Args.hasArg(options::OPT_emit_llvm)) {
5112 CmdArgs.push_back("-emit-llvm");
5113 } else {
5114 CmdArgs.push_back("-emit-llvm-bc");
5115 }
5116 } else if (JA.getType() == types::TY_IFS ||
5117 JA.getType() == types::TY_IFS_CPP) {
5118 StringRef ArgStr =
5119 Args.hasArg(options::OPT_interface_stub_version_EQ)
5120 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
5121 : "ifs-v1";
5122 CmdArgs.push_back("-emit-interface-stubs");
5123 CmdArgs.push_back(
5124 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
5125 } else if (JA.getType() == types::TY_PP_Asm) {
5126 CmdArgs.push_back("-S");
5127 } else if (JA.getType() == types::TY_AST) {
5128 CmdArgs.push_back("-emit-pch");
5129 } else if (JA.getType() == types::TY_ModuleFile) {
5130 CmdArgs.push_back("-module-file-info");
5131 } else if (JA.getType() == types::TY_RewrittenObjC) {
5132 CmdArgs.push_back("-rewrite-objc");
5133 rewriteKind = RK_NonFragile;
5134 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5135 CmdArgs.push_back("-rewrite-objc");
5136 rewriteKind = RK_Fragile;
5137 } else {
5138 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5139 }
5140
5141 // Preserve use-list order by default when emitting bitcode, so that
5142 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5143 // same result as running passes here. For LTO, we don't need to preserve
5144 // the use-list order, since serialization to bitcode is part of the flow.
5145 if (JA.getType() == types::TY_LLVM_BC)
5146 CmdArgs.push_back("-emit-llvm-uselists");
5147
5148 if (IsUsingLTO) {
5149 if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
5150 !Args.hasFlag(options::OPT_offload_new_driver,
5151 options::OPT_no_offload_new_driver, false) &&
5152 !Triple.isAMDGPU()) {
5153 D.Diag(diag::err_drv_unsupported_opt_for_target)
5154 << Args.getLastArg(options::OPT_foffload_lto,
5155 options::OPT_foffload_lto_EQ)
5156 ->getAsString(Args)
5157 << Triple.getTriple();
5158 } else if (Triple.isNVPTX() && !IsRDCMode &&
5160 D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
5161 << Args.getLastArg(options::OPT_foffload_lto,
5162 options::OPT_foffload_lto_EQ)
5163 ->getAsString(Args)
5164 << "-fno-gpu-rdc";
5165 } else {
5166 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5167 CmdArgs.push_back(Args.MakeArgString(
5168 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5169 // PS4 uses the legacy LTO API, which does not support some of the
5170 // features enabled by -flto-unit.
5171 if (!RawTriple.isPS4() ||
5172 (D.getLTOMode() == LTOK_Full) || !UnifiedLTO)
5173 CmdArgs.push_back("-flto-unit");
5174 }
5175 }
5176 }
5177
5178 Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
5179
5180 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
5181 if (!types::isLLVMIR(Input.getType()))
5182 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5183 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
5184 }
5185
5186 if (Triple.isPPC())
5187 Args.addOptInFlag(CmdArgs, options::OPT_mregnames,
5188 options::OPT_mno_regnames);
5189
5190 if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
5191 Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
5192
5193 if (Args.getLastArg(options::OPT_save_temps_EQ))
5194 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
5195
5196 auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
5197 options::OPT_fmemory_profile_EQ,
5198 options::OPT_fno_memory_profile);
5199 if (MemProfArg &&
5200 !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
5201 MemProfArg->render(Args, CmdArgs);
5202
5203 if (auto *MemProfUseArg =
5204 Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
5205 if (MemProfArg)
5206 D.Diag(diag::err_drv_argument_not_allowed_with)
5207 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5208 if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
5209 options::OPT_fprofile_generate_EQ))
5210 D.Diag(diag::err_drv_argument_not_allowed_with)
5211 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5212 MemProfUseArg->render(Args, CmdArgs);
5213 }
5214
5215 // Embed-bitcode option.
5216 // Only white-listed flags below are allowed to be embedded.
5217 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5218 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
5219 // Add flags implied by -fembed-bitcode.
5220 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
5221 // Disable all llvm IR level optimizations.
5222 CmdArgs.push_back("-disable-llvm-passes");
5223
5224 // Render target options.
5225 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
5226
5227 // reject options that shouldn't be supported in bitcode
5228 // also reject kernel/kext
5229 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5230 options::OPT_mkernel,
5231 options::OPT_fapple_kext,
5232 options::OPT_ffunction_sections,
5233 options::OPT_fno_function_sections,
5234 options::OPT_fdata_sections,
5235 options::OPT_fno_data_sections,
5236 options::OPT_fbasic_block_sections_EQ,
5237 options::OPT_funique_internal_linkage_names,
5238 options::OPT_fno_unique_internal_linkage_names,
5239 options::OPT_funique_section_names,
5240 options::OPT_fno_unique_section_names,
5241 options::OPT_funique_basic_block_section_names,
5242 options::OPT_fno_unique_basic_block_section_names,
5243 options::OPT_mrestrict_it,
5244 options::OPT_mno_restrict_it,
5245 options::OPT_mstackrealign,
5246 options::OPT_mno_stackrealign,
5247 options::OPT_mstack_alignment,
5248 options::OPT_mcmodel_EQ,
5249 options::OPT_mlong_calls,
5250 options::OPT_mno_long_calls,
5251 options::OPT_ggnu_pubnames,
5252 options::OPT_gdwarf_aranges,
5253 options::OPT_fdebug_types_section,
5254 options::OPT_fno_debug_types_section,
5255 options::OPT_fdwarf_directory_asm,
5256 options::OPT_fno_dwarf_directory_asm,
5257 options::OPT_mrelax_all,
5258 options::OPT_mno_relax_all,
5259 options::OPT_ftrap_function_EQ,
5260 options::OPT_ffixed_r9,
5261 options::OPT_mfix_cortex_a53_835769,
5262 options::OPT_mno_fix_cortex_a53_835769,
5263 options::OPT_ffixed_x18,
5264 options::OPT_mglobal_merge,
5265 options::OPT_mno_global_merge,
5266 options::OPT_mred_zone,
5267 options::OPT_mno_red_zone,
5268 options::OPT_Wa_COMMA,
5269 options::OPT_Xassembler,
5270 options::OPT_mllvm,
5271 };
5272 for (const auto &A : Args)
5273 if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
5274 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5275
5276 // Render the CodeGen options that need to be passed.
5277 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5278 options::OPT_fno_optimize_sibling_calls);
5279
5281 CmdArgs, JA);
5282
5283 // Render ABI arguments
5284 switch (TC.getArch()) {
5285 default: break;
5286 case llvm::Triple::arm:
5287 case llvm::Triple::armeb:
5288 case llvm::Triple::thumbeb:
5289 RenderARMABI(D, Triple, Args, CmdArgs);
5290 break;
5291 case llvm::Triple::aarch64:
5292 case llvm::Triple::aarch64_32:
5293 case llvm::Triple::aarch64_be:
5294 RenderAArch64ABI(Triple, Args, CmdArgs);
5295 break;
5296 }
5297
5298 // Optimization level for CodeGen.
5299 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5300 if (A->getOption().matches(options::OPT_O4)) {
5301 CmdArgs.push_back("-O3");
5302 D.Diag(diag::warn_O4_is_O3);
5303 } else {
5304 A->render(Args, CmdArgs);
5305 }
5306 }
5307
5308 // Input/Output file.
5309 if (Output.getType() == types::TY_Dependencies) {
5310 // Handled with other dependency code.
5311 } else if (Output.isFilename()) {
5312 CmdArgs.push_back("-o");
5313 CmdArgs.push_back(Output.getFilename());
5314 } else {
5315 assert(Output.isNothing() && "Input output.");
5316 }
5317
5318 for (const auto &II : Inputs) {
5319 addDashXForInput(Args, II, CmdArgs);
5320 if (II.isFilename())
5321 CmdArgs.push_back(II.getFilename());
5322 else
5323 II.getInputArg().renderAsInput(Args, CmdArgs);
5324 }
5325
5326 C.addCommand(std::make_unique<Command>(
5328 CmdArgs, Inputs, Output, D.getPrependArg()));
5329 return;
5330 }
5331
5332 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5333 CmdArgs.push_back("-fembed-bitcode=marker");
5334
5335 // We normally speed up the clang process a bit by skipping destructors at
5336 // exit, but when we're generating diagnostics we can rely on some of the
5337 // cleanup.
5338 if (!C.isForDiagnostics())
5339 CmdArgs.push_back("-disable-free");
5340 CmdArgs.push_back("-clear-ast-before-backend");
5341
5342#ifdef NDEBUG
5343 const bool IsAssertBuild = false;
5344#else
5345 const bool IsAssertBuild = true;
5346#endif
5347
5348 // Disable the verification pass in asserts builds unless otherwise specified.
5349 if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
5350 options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
5351 CmdArgs.push_back("-disable-llvm-verifier");
5352 }
5353
5354 // Discard value names in assert builds unless otherwise specified.
5355 if (Args.hasFlag(options::OPT_fdiscard_value_names,
5356 options::OPT_fno_discard_value_names, !IsAssertBuild)) {
5357 if (Args.hasArg(options::OPT_fdiscard_value_names) &&
5358 llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
5359 return types::isLLVMIR(II.getType());
5360 })) {
5361 D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
5362 }
5363 CmdArgs.push_back("-discard-value-names");
5364 }
5365
5366 // Set the main file name, so that debug info works even with
5367 // -save-temps.
5368 CmdArgs.push_back("-main-file-name");
5369 CmdArgs.push_back(getBaseInputName(Args, Input));
5370
5371 // Some flags which affect the language (via preprocessor
5372 // defines).
5373 if (Args.hasArg(options::OPT_static))
5374 CmdArgs.push_back("-static-define");
5375
5376 if (Args.hasArg(options::OPT_municode))
5377 CmdArgs.push_back("-DUNICODE");
5378
5379 if (isa<AnalyzeJobAction>(JA))
5380 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5381
5382 if (isa<AnalyzeJobAction>(JA) ||
5383 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5384 CmdArgs.push_back("-setup-static-analyzer");
5385
5386 // Enable compatilibily mode to avoid analyzer-config related errors.
5387 // Since we can't access frontend flags through hasArg, let's manually iterate
5388 // through them.
5389 bool FoundAnalyzerConfig = false;
5390 for (auto *Arg : Args.filtered(options::OPT_Xclang))
5391 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5392 FoundAnalyzerConfig = true;
5393 break;
5394 }
5395 if (!FoundAnalyzerConfig)
5396 for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5397 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5398 FoundAnalyzerConfig = true;
5399 break;
5400 }
5401 if (FoundAnalyzerConfig)
5402 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
5403
5405
5406 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5407 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5408 if (FunctionAlignment) {
5409 CmdArgs.push_back("-function-alignment");
5410 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
5411 }
5412
5413 // We support -falign-loops=N where N is a power of 2. GCC supports more
5414 // forms.
5415 if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5416 unsigned Value = 0;
5417 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5418 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5419 << A->getAsString(Args) << A->getValue();
5420 else if (Value & (Value - 1))
5421 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5422 << A->getAsString(Args) << A->getValue();
5423 // Treat =0 as unspecified (use the target preference).
5424 if (Value)
5425 CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5426 Twine(std::min(Value, 65536u))));
5427 }
5428
5429 if (Triple.isOSzOS()) {
5430 // On z/OS some of the system header feature macros need to
5431 // be defined to enable most cross platform projects to build
5432 // successfully. Ths include the libc++ library. A
5433 // complicating factor is that users can define these
5434 // macros to the same or different values. We need to add
5435 // the definition for these macros to the compilation command
5436 // if the user hasn't already defined them.
5437
5438 auto findMacroDefinition = [&](const std::string &Macro) {
5439 auto MacroDefs = Args.getAllArgValues(options::OPT_D);
5440 return llvm::any_of(MacroDefs, [&](const std::string &M) {
5441 return M == Macro || M.find(Macro + '=') != std::string::npos;
5442 });
5443 };
5444
5445 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5446 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5447 CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
5448 // _OPEN_DEFAULT is required for XL compat
5449 if (!findMacroDefinition("_OPEN_DEFAULT"))
5450 CmdArgs.push_back("-D_OPEN_DEFAULT");
5451 if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
5452 // _XOPEN_SOURCE=600 is required for libcxx.
5453 if (!findMacroDefinition("_XOPEN_SOURCE"))
5454 CmdArgs.push_back("-D_XOPEN_SOURCE=600");
5455 }
5456 }
5457
5458 llvm::Reloc::Model RelocationModel;
5459 unsigned PICLevel;
5460 bool IsPIE;
5461 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5462 Arg *LastPICDataRelArg =
5463 Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5464 options::OPT_mpic_data_is_text_relative);
5465 bool NoPICDataIsTextRelative = false;
5466 if (LastPICDataRelArg) {
5467 if (LastPICDataRelArg->getOption().matches(
5468 options::OPT_mno_pic_data_is_text_relative)) {
5469 NoPICDataIsTextRelative = true;
5470 if (!PICLevel)
5471 D.Diag(diag::err_drv_argument_only_allowed_with)
5472 << "-mno-pic-data-is-text-relative"
5473 << "-fpic/-fpie";
5474 }
5475 if (!Triple.isSystemZ())
5476 D.Diag(diag::err_drv_unsupported_opt_for_target)
5477 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5478 : "-mpic-data-is-text-relative")
5479 << RawTriple.str();
5480 }
5481
5482 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5483 RelocationModel == llvm::Reloc::ROPI_RWPI;
5484 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5485 RelocationModel == llvm::Reloc::ROPI_RWPI;
5486
5487 if (Args.hasArg(options::OPT_mcmse) &&
5488 !Args.hasArg(options::OPT_fallow_unsupported)) {
5489 if (IsROPI)
5490 D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
5491 if (IsRWPI)
5492 D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5493 }
5494
5495 if (IsROPI && types::isCXX(Input.getType()) &&
5496 !Args.hasArg(options::OPT_fallow_unsupported))
5497 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
5498
5499 const char *RMName = RelocationModelName(RelocationModel);
5500 if (RMName) {
5501 CmdArgs.push_back("-mrelocation-model");
5502 CmdArgs.push_back(RMName);
5503 }
5504 if (PICLevel > 0) {
5505 CmdArgs.push_back("-pic-level");
5506 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
5507 if (IsPIE)
5508 CmdArgs.push_back("-pic-is-pie");
5509 if (NoPICDataIsTextRelative)
5510 CmdArgs.push_back("-mcmodel=medium");
5511 }
5512
5513 if (RelocationModel == llvm::Reloc::ROPI ||
5514 RelocationModel == llvm::Reloc::ROPI_RWPI)
5515 CmdArgs.push_back("-fropi");
5516 if (RelocationModel == llvm::Reloc::RWPI ||
5517 RelocationModel == llvm::Reloc::ROPI_RWPI)
5518 CmdArgs.push_back("-frwpi");
5519
5520 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
5521 CmdArgs.push_back("-meabi");
5522 CmdArgs.push_back(A->getValue());
5523 }
5524
5525 // -fsemantic-interposition is forwarded to CC1: set the
5526 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5527 // make default visibility external linkage definitions dso_preemptable.
5528 //
5529 // -fno-semantic-interposition: if the target supports .Lfoo$local local
5530 // aliases (make default visibility external linkage definitions dso_local).
5531 // This is the CC1 default for ELF to match COFF/Mach-O.
5532 //
5533 // Otherwise use Clang's traditional behavior: like
5534 // -fno-semantic-interposition but local aliases are not used. So references
5535 // can be interposed if not optimized out.
5536 if (Triple.isOSBinFormatELF()) {
5537 Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
5538 options::OPT_fno_semantic_interposition);
5539 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5540 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5541 bool SupportsLocalAlias =
5542 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5543 if (!A)
5544 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5545 else if (A->getOption().matches(options::OPT_fsemantic_interposition))
5546 A->render(Args, CmdArgs);
5547 else if (!SupportsLocalAlias)
5548 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5549 }
5550 }
5551
5552 {
5553 std::string Model;
5554 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
5555 if (!TC.isThreadModelSupported(A->getValue()))
5556 D.Diag(diag::err_drv_invalid_thread_model_for_target)
5557 << A->getValue() << A->getAsString(Args);
5558 Model = A->getValue();
5559 } else
5560 Model = TC.getThreadModel();
5561 if (Model != "posix") {
5562 CmdArgs.push_back("-mthread-model");
5563 CmdArgs.push_back(Args.MakeArgString(Model));
5564 }
5565 }
5566
5567 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
5568 StringRef Name = A->getValue();
5569 if (Name == "SVML") {
5570 if (Triple.getArch() != llvm::Triple::x86 &&
5571 Triple.getArch() != llvm::Triple::x86_64)
5572 D.Diag(diag::err_drv_unsupported_opt_for_target)
5573 << Name << Triple.getArchName();
5574 } else if (Name == "LIBMVEC-X86") {
5575 if (Triple.getArch() != llvm::Triple::x86 &&
5576 Triple.getArch() != llvm::Triple::x86_64)
5577 D.Diag(diag::err_drv_unsupported_opt_for_target)
5578 << Name << Triple.getArchName();
5579 } else if (Name == "SLEEF" || Name == "ArmPL") {
5580 if (Triple.getArch() != llvm::Triple::aarch64 &&
5581 Triple.getArch() != llvm::Triple::aarch64_be)
5582 D.Diag(diag::err_drv_unsupported_opt_for_target)
5583 << Name << Triple.getArchName();
5584 }
5585 A->render(Args, CmdArgs);
5586 }
5587
5588 if (Args.hasFlag(options::OPT_fmerge_all_constants,
5589 options::OPT_fno_merge_all_constants, false))
5590 CmdArgs.push_back("-fmerge-all-constants");
5591
5592 Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
5593 options::OPT_fno_delete_null_pointer_checks);
5594
5595 // LLVM Code Generator Options.
5596
5597 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
5598 if (!Triple.isOSAIX() || Triple.isPPC32())
5599 D.Diag(diag::err_drv_unsupported_opt_for_target)
5600 << A->getSpelling() << RawTriple.str();
5601 CmdArgs.push_back("-mabi=quadword-atomics");
5602 }
5603
5604 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
5605 // Emit the unsupported option error until the Clang's library integration
5606 // support for 128-bit long double is available for AIX.
5607 if (Triple.isOSAIX())
5608 D.Diag(diag::err_drv_unsupported_opt_for_target)
5609 << A->getSpelling() << RawTriple.str();
5610 }
5611
5612 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
5613 StringRef V = A->getValue(), V1 = V;
5614 unsigned Size;
5615 if (V1.consumeInteger(10, Size) || !V1.empty())
5616 D.Diag(diag::err_drv_invalid_argument_to_option)
5617 << V << A->getOption().getName();
5618 else
5619 CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
5620 }
5621
5622 Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
5623 options::OPT_fno_jump_tables);
5624 Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
5625 options::OPT_fno_profile_sample_accurate);
5626 Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
5627 options::OPT_fno_preserve_as_comments);
5628
5629 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
5630 CmdArgs.push_back("-mregparm");
5631 CmdArgs.push_back(A->getValue());
5632 }
5633
5634 if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
5635 options::OPT_msvr4_struct_return)) {
5636 if (!TC.getTriple().isPPC32()) {
5637 D.Diag(diag::err_drv_unsupported_opt_for_target)
5638 << A->getSpelling() << RawTriple.str();
5639 } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
5640 CmdArgs.push_back("-maix-struct-return");
5641 } else {
5642 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5643 CmdArgs.push_back("-msvr4-struct-return");
5644 }
5645 }
5646
5647 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
5648 options::OPT_freg_struct_return)) {
5649 if (TC.getArch() != llvm::Triple::x86) {
5650 D.Diag(diag::err_drv_unsupported_opt_for_target)
5651 << A->getSpelling() << RawTriple.str();
5652 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
5653 CmdArgs.push_back("-fpcc-struct-return");
5654 } else {
5655 assert(A->getOption().matches(options::OPT_freg_struct_return));
5656 CmdArgs.push_back("-freg-struct-return");
5657 }
5658 }
5659
5660 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {
5661 if (Triple.getArch() == llvm::Triple::m68k)
5662 CmdArgs.push_back("-fdefault-calling-conv=rtdcall");
5663 else
5664 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
5665 }
5666
5667 if (Args.hasArg(options::OPT_fenable_matrix)) {
5668 // enable-matrix is needed by both the LangOpts and by LLVM.
5669 CmdArgs.push_back("-fenable-matrix");
5670 CmdArgs.push_back("-mllvm");
5671 CmdArgs.push_back("-enable-matrix");
5672 }
5673
5675 getFramePointerKind(Args, RawTriple);
5676 const char *FPKeepKindStr = nullptr;
5677 switch (FPKeepKind) {
5679 FPKeepKindStr = "-mframe-pointer=none";
5680 break;
5682 FPKeepKindStr = "-mframe-pointer=reserved";
5683 break;
5685 FPKeepKindStr = "-mframe-pointer=non-leaf";
5686 break;
5688 FPKeepKindStr = "-mframe-pointer=all";
5689 break;
5690 }
5691 assert(FPKeepKindStr && "unknown FramePointerKind");
5692 CmdArgs.push_back(FPKeepKindStr);
5693
5694 Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
5695 options::OPT_fno_zero_initialized_in_bss);
5696
5697 bool OFastEnabled = isOptimizationLevelFast(Args);
5698 // If -Ofast is the optimization level, then -fstrict-aliasing should be
5699 // enabled. This alias option is being used to simplify the hasFlag logic.
5700 OptSpecifier StrictAliasingAliasOption =
5701 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
5702 // We turn strict aliasing off by default if we're Windows MSVC since MSVC
5703 // doesn't do any TBAA.
5704 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
5705 options::OPT_fno_strict_aliasing, !IsWindowsMSVC))
5706 CmdArgs.push_back("-relaxed-aliasing");
5707 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
5708 options::OPT_fno_struct_path_tbaa, true))
5709 CmdArgs.push_back("-no-struct-path-tbaa");
5710 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
5711 options::OPT_fno_strict_enums);
5712 Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
5713 options::OPT_fno_strict_return);
5714 Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
5715 options::OPT_fno_allow_editor_placeholders);
5716 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
5717 options::OPT_fno_strict_vtable_pointers);
5718 Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
5719 options::OPT_fno_force_emit_vtables);
5720 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5721 options::OPT_fno_optimize_sibling_calls);
5722 Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
5723 options::OPT_fno_escaping_block_tail_calls);
5724
5725 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
5726 options::OPT_fno_fine_grained_bitfield_accesses);
5727
5728 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
5729 options::OPT_fno_experimental_relative_cxx_abi_vtables);
5730
5731 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
5732 options::OPT_fno_experimental_omit_vtable_rtti);
5733
5734 // Handle segmented stacks.
5735 Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
5736 options::OPT_fno_split_stack);
5737
5738 // -fprotect-parens=0 is default.
5739 if (Args.hasFlag(options::OPT_fprotect_parens,
5740 options::OPT_fno_protect_parens, false))
5741 CmdArgs.push_back("-fprotect-parens");
5742
5743 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
5744
5745 if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
5746 const llvm::Triple::ArchType Arch = TC.getArch();
5747 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5748 StringRef V = A->getValue();
5749 if (V == "64")
5750 CmdArgs.push_back("-fextend-arguments=64");
5751 else if (V != "32")
5752 D.Diag(diag::err_drv_invalid_argument_to_option)
5753 << A->getValue() << A->getOption().getName();
5754 } else
5755 D.Diag(diag::err_drv_unsupported_opt_for_target)
5756 << A->getOption().getName() << TripleStr;
5757 }
5758
5759 if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
5760 if (TC.getArch() == llvm::Triple::avr)
5761 A->render(Args, CmdArgs);
5762 else
5763 D.Diag(diag::err_drv_unsupported_opt_for_target)
5764 << A->getAsString(Args) << TripleStr;
5765 }
5766
5767 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
5768 if (TC.getTriple().isX86())
5769 A->render(Args, CmdArgs);
5770 else if (TC.getTriple().isPPC() &&
5771 (A->getOption().getID() != options::OPT_mlong_double_80))
5772 A->render(Args, CmdArgs);
5773 else
5774 D.Diag(diag::err_drv_unsupported_opt_for_target)
5775 << A->getAsString(Args) << TripleStr;
5776 }
5777
5778 // Decide whether to use verbose asm. Verbose assembly is the default on
5779 // toolchains which have the integrated assembler on by default.
5780 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
5781 if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
5782 IsIntegratedAssemblerDefault))
5783 CmdArgs.push_back("-fno-verbose-asm");
5784
5785 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
5786 // use that to indicate the MC default in the backend.
5787 if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
5788 StringRef V = A->getValue();
5789 unsigned Num;
5790 if (V == "none")
5791 A->render(Args, CmdArgs);
5792 else if (!V.consumeInteger(10, Num) && Num > 0 &&
5793 (V.empty() || (V.consume_front(".") &&
5794 !V.consumeInteger(10, Num) && V.empty())))
5795 A->render(Args, CmdArgs);
5796 else
5797 D.Diag(diag::err_drv_invalid_argument_to_option)
5798 << A->getValue() << A->getOption().getName();
5799 }
5800
5801 // If toolchain choose to use MCAsmParser for inline asm don't pass the
5802 // option to disable integrated-as explictly.
5804 CmdArgs.push_back("-no-integrated-as");
5805
5806 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
5807 CmdArgs.push_back("-mdebug-pass");
5808 CmdArgs.push_back("Structure");
5809 }
5810 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
5811 CmdArgs.push_back("-mdebug-pass");
5812 CmdArgs.push_back("Arguments");
5813 }
5814
5815 // Enable -mconstructor-aliases except on darwin, where we have to work around
5816 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
5817 // code, where aliases aren't supported.
5818 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
5819 CmdArgs.push_back("-mconstructor-aliases");
5820
5821 // Darwin's kernel doesn't support guard variables; just die if we
5822 // try to use them.
5823 if (KernelOrKext && RawTriple.isOSDarwin())
5824 CmdArgs.push_back("-fforbid-guard-variables");
5825
5826 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
5827 Triple.isWindowsGNUEnvironment())) {
5828 CmdArgs.push_back("-mms-bitfields");
5829 }
5830
5831 if (Triple.isWindowsGNUEnvironment()) {
5832 Args.addOptOutFlag(CmdArgs, options::OPT_fauto_import,
5833 options::OPT_fno_auto_import);
5834 }
5835
5836 if (Args.hasFlag(options::OPT_fms_volatile, options::OPT_fno_ms_volatile,
5837 Triple.isX86() && D.IsCLMode()))
5838 CmdArgs.push_back("-fms-volatile");
5839
5840 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
5841 // defaults to -fno-direct-access-external-data. Pass the option if different
5842 // from the default.
5843 if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
5844 options::OPT_fno_direct_access_external_data)) {
5845 if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
5846 (PICLevel == 0))
5847 A->render(Args, CmdArgs);
5848 } else if (PICLevel == 0 && Triple.isLoongArch()) {
5849 // Some targets default to -fno-direct-access-external-data even for
5850 // -fno-pic.
5851 CmdArgs.push_back("-fno-direct-access-external-data");
5852 }
5853
5854 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
5855 CmdArgs.push_back("-fno-plt");
5856 }
5857
5858 // -fhosted is default.
5859 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
5860 // use Freestanding.
5861 bool Freestanding =
5862 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
5863 KernelOrKext;
5864 if (Freestanding)
5865 CmdArgs.push_back("-ffreestanding");
5866
5867 Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
5868
5869 // This is a coarse approximation of what llvm-gcc actually does, both
5870 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
5871 // complicated ways.
5872 auto SanitizeArgs = TC.getSanitizerArgs(Args);
5873
5874 bool IsAsyncUnwindTablesDefault =
5876 bool IsSyncUnwindTablesDefault =
5878
5879 bool AsyncUnwindTables = Args.hasFlag(
5880 options::OPT_fasynchronous_unwind_tables,
5881 options::OPT_fno_asynchronous_unwind_tables,
5882 (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
5883 !Freestanding);
5884 bool UnwindTables =
5885 Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
5886 IsSyncUnwindTablesDefault && !Freestanding);
5887 if (AsyncUnwindTables)
5888 CmdArgs.push_back("-funwind-tables=2");
5889 else if (UnwindTables)
5890 CmdArgs.push_back("-funwind-tables=1");
5891
5892 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
5893 // `--gpu-use-aux-triple-only` is specified.
5894 if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&
5895 (IsCudaDevice || IsHIPDevice)) {
5896 const ArgList &HostArgs =
5897 C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);
5898 std::string HostCPU =
5899 getCPUName(D, HostArgs, *TC.getAuxTriple(), /*FromAs*/ false);
5900 if (!HostCPU.empty()) {
5