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