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