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