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