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