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