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