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