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. 463 bool CXXExceptionsEnabled = 464 Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4(); 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. 2300 std::string TuneCPU; 2301 if (!Args.hasArg(clang::driver::options::OPT_march_EQ) && 2302 !getToolChain().getTriple().isPS4()) 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. 3171 if (Triple.isPS4()) { 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.isPS4()) { 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 } 4598 } else if (isa<AssembleJobAction>(JA)) { 4599 CmdArgs.push_back("-emit-obj"); 4600 4601 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D); 4602 4603 // Also ignore explicit -force_cpusubtype_ALL option. 4604 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL); 4605 } else if (isa<PrecompileJobAction>(JA)) { 4606 if (JA.getType() == types::TY_Nothing) 4607 CmdArgs.push_back("-fsyntax-only"); 4608 else if (JA.getType() == types::TY_ModuleFile) 4609 CmdArgs.push_back(IsHeaderModulePrecompile 4610 ? "-emit-header-module" 4611 : "-emit-module-interface"); 4612 else 4613 CmdArgs.push_back("-emit-pch"); 4614 } else if (isa<VerifyPCHJobAction>(JA)) { 4615 CmdArgs.push_back("-verify-pch"); 4616 } else if (isa<ExtractAPIJobAction>(JA)) { 4617 assert(JA.getType() == types::TY_API_INFO && 4618 "Extract API actions must generate a API information."); 4619 CmdArgs.push_back("-extract-api"); 4620 if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ)) 4621 ProductNameArg->render(Args, CmdArgs); 4622 } else { 4623 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) && 4624 "Invalid action for clang tool."); 4625 if (JA.getType() == types::TY_Nothing) { 4626 CmdArgs.push_back("-fsyntax-only"); 4627 } else if (JA.getType() == types::TY_LLVM_IR || 4628 JA.getType() == types::TY_LTO_IR) { 4629 CmdArgs.push_back("-emit-llvm"); 4630 } else if (JA.getType() == types::TY_LLVM_BC || 4631 JA.getType() == types::TY_LTO_BC) { 4632 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S 4633 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) && 4634 Args.hasArg(options::OPT_emit_llvm)) { 4635 CmdArgs.push_back("-emit-llvm"); 4636 } else { 4637 CmdArgs.push_back("-emit-llvm-bc"); 4638 } 4639 } else if (JA.getType() == types::TY_IFS || 4640 JA.getType() == types::TY_IFS_CPP) { 4641 StringRef ArgStr = 4642 Args.hasArg(options::OPT_interface_stub_version_EQ) 4643 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ) 4644 : "ifs-v1"; 4645 CmdArgs.push_back("-emit-interface-stubs"); 4646 CmdArgs.push_back( 4647 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str())); 4648 } else if (JA.getType() == types::TY_PP_Asm) { 4649 CmdArgs.push_back("-S"); 4650 } else if (JA.getType() == types::TY_AST) { 4651 CmdArgs.push_back("-emit-pch"); 4652 } else if (JA.getType() == types::TY_ModuleFile) { 4653 CmdArgs.push_back("-module-file-info"); 4654 } else if (JA.getType() == types::TY_RewrittenObjC) { 4655 CmdArgs.push_back("-rewrite-objc"); 4656 rewriteKind = RK_NonFragile; 4657 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) { 4658 CmdArgs.push_back("-rewrite-objc"); 4659 rewriteKind = RK_Fragile; 4660 } else { 4661 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!"); 4662 } 4663 4664 // Preserve use-list order by default when emitting bitcode, so that 4665 // loading the bitcode up in 'opt' or 'llc' and running passes gives the 4666 // same result as running passes here. For LTO, we don't need to preserve 4667 // the use-list order, since serialization to bitcode is part of the flow. 4668 if (JA.getType() == types::TY_LLVM_BC) 4669 CmdArgs.push_back("-emit-llvm-uselists"); 4670 4671 if (IsUsingLTO && !Args.hasArg(options::OPT_fopenmp_new_driver)) { 4672 // Only AMDGPU supports device-side LTO. 4673 if (IsDeviceOffloadAction && !Triple.isAMDGPU()) { 4674 D.Diag(diag::err_drv_unsupported_opt_for_target) 4675 << Args.getLastArg(options::OPT_foffload_lto, 4676 options::OPT_foffload_lto_EQ) 4677 ->getAsString(Args) 4678 << Triple.getTriple(); 4679 } else { 4680 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin); 4681 CmdArgs.push_back(Args.MakeArgString( 4682 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full"))); 4683 CmdArgs.push_back("-flto-unit"); 4684 } 4685 } 4686 } 4687 4688 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) { 4689 if (!types::isLLVMIR(Input.getType())) 4690 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args); 4691 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ); 4692 } 4693 4694 if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ)) 4695 Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ); 4696 4697 if (Args.getLastArg(options::OPT_save_temps_EQ)) 4698 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ); 4699 4700 auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile, 4701 options::OPT_fmemory_profile_EQ, 4702 options::OPT_fno_memory_profile); 4703 if (MemProfArg && 4704 !MemProfArg->getOption().matches(options::OPT_fno_memory_profile)) 4705 MemProfArg->render(Args, CmdArgs); 4706 4707 // Embed-bitcode option. 4708 // Only white-listed flags below are allowed to be embedded. 4709 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO && 4710 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) { 4711 // Add flags implied by -fembed-bitcode. 4712 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ); 4713 // Disable all llvm IR level optimizations. 4714 CmdArgs.push_back("-disable-llvm-passes"); 4715 4716 // Render target options. 4717 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind()); 4718 4719 // reject options that shouldn't be supported in bitcode 4720 // also reject kernel/kext 4721 static const constexpr unsigned kBitcodeOptionIgnorelist[] = { 4722 options::OPT_mkernel, 4723 options::OPT_fapple_kext, 4724 options::OPT_ffunction_sections, 4725 options::OPT_fno_function_sections, 4726 options::OPT_fdata_sections, 4727 options::OPT_fno_data_sections, 4728 options::OPT_fbasic_block_sections_EQ, 4729 options::OPT_funique_internal_linkage_names, 4730 options::OPT_fno_unique_internal_linkage_names, 4731 options::OPT_funique_section_names, 4732 options::OPT_fno_unique_section_names, 4733 options::OPT_funique_basic_block_section_names, 4734 options::OPT_fno_unique_basic_block_section_names, 4735 options::OPT_mrestrict_it, 4736 options::OPT_mno_restrict_it, 4737 options::OPT_mstackrealign, 4738 options::OPT_mno_stackrealign, 4739 options::OPT_mstack_alignment, 4740 options::OPT_mcmodel_EQ, 4741 options::OPT_mlong_calls, 4742 options::OPT_mno_long_calls, 4743 options::OPT_ggnu_pubnames, 4744 options::OPT_gdwarf_aranges, 4745 options::OPT_fdebug_types_section, 4746 options::OPT_fno_debug_types_section, 4747 options::OPT_fdwarf_directory_asm, 4748 options::OPT_fno_dwarf_directory_asm, 4749 options::OPT_mrelax_all, 4750 options::OPT_mno_relax_all, 4751 options::OPT_ftrap_function_EQ, 4752 options::OPT_ffixed_r9, 4753 options::OPT_mfix_cortex_a53_835769, 4754 options::OPT_mno_fix_cortex_a53_835769, 4755 options::OPT_ffixed_x18, 4756 options::OPT_mglobal_merge, 4757 options::OPT_mno_global_merge, 4758 options::OPT_mred_zone, 4759 options::OPT_mno_red_zone, 4760 options::OPT_Wa_COMMA, 4761 options::OPT_Xassembler, 4762 options::OPT_mllvm, 4763 }; 4764 for (const auto &A : Args) 4765 if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID())) 4766 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling(); 4767 4768 // Render the CodeGen options that need to be passed. 4769 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls, 4770 options::OPT_fno_optimize_sibling_calls); 4771 4772 RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args, 4773 CmdArgs, JA); 4774 4775 // Render ABI arguments 4776 switch (TC.getArch()) { 4777 default: break; 4778 case llvm::Triple::arm: 4779 case llvm::Triple::armeb: 4780 case llvm::Triple::thumbeb: 4781 RenderARMABI(D, Triple, Args, CmdArgs); 4782 break; 4783 case llvm::Triple::aarch64: 4784 case llvm::Triple::aarch64_32: 4785 case llvm::Triple::aarch64_be: 4786 RenderAArch64ABI(Triple, Args, CmdArgs); 4787 break; 4788 } 4789 4790 // Optimization level for CodeGen. 4791 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) { 4792 if (A->getOption().matches(options::OPT_O4)) { 4793 CmdArgs.push_back("-O3"); 4794 D.Diag(diag::warn_O4_is_O3); 4795 } else { 4796 A->render(Args, CmdArgs); 4797 } 4798 } 4799 4800 // Input/Output file. 4801 if (Output.getType() == types::TY_Dependencies) { 4802 // Handled with other dependency code. 4803 } else if (Output.isFilename()) { 4804 CmdArgs.push_back("-o"); 4805 CmdArgs.push_back(Output.getFilename()); 4806 } else { 4807 assert(Output.isNothing() && "Input output."); 4808 } 4809 4810 for (const auto &II : Inputs) { 4811 addDashXForInput(Args, II, CmdArgs); 4812 if (II.isFilename()) 4813 CmdArgs.push_back(II.getFilename()); 4814 else 4815 II.getInputArg().renderAsInput(Args, CmdArgs); 4816 } 4817 4818 C.addCommand(std::make_unique<Command>( 4819 JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(), 4820 CmdArgs, Inputs, Output)); 4821 return; 4822 } 4823 4824 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO) 4825 CmdArgs.push_back("-fembed-bitcode=marker"); 4826 4827 // We normally speed up the clang process a bit by skipping destructors at 4828 // exit, but when we're generating diagnostics we can rely on some of the 4829 // cleanup. 4830 if (!C.isForDiagnostics()) 4831 CmdArgs.push_back("-disable-free"); 4832 CmdArgs.push_back("-clear-ast-before-backend"); 4833 4834 #ifdef NDEBUG 4835 const bool IsAssertBuild = false; 4836 #else 4837 const bool IsAssertBuild = true; 4838 #endif 4839 4840 // Disable the verification pass in -asserts builds. 4841 if (!IsAssertBuild) 4842 CmdArgs.push_back("-disable-llvm-verifier"); 4843 4844 // Discard value names in assert builds unless otherwise specified. 4845 if (Args.hasFlag(options::OPT_fdiscard_value_names, 4846 options::OPT_fno_discard_value_names, !IsAssertBuild)) { 4847 if (Args.hasArg(options::OPT_fdiscard_value_names) && 4848 llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) { 4849 return types::isLLVMIR(II.getType()); 4850 })) { 4851 D.Diag(diag::warn_ignoring_fdiscard_for_bitcode); 4852 } 4853 CmdArgs.push_back("-discard-value-names"); 4854 } 4855 4856 // Set the main file name, so that debug info works even with 4857 // -save-temps. 4858 CmdArgs.push_back("-main-file-name"); 4859 CmdArgs.push_back(getBaseInputName(Args, Input)); 4860 4861 // Some flags which affect the language (via preprocessor 4862 // defines). 4863 if (Args.hasArg(options::OPT_static)) 4864 CmdArgs.push_back("-static-define"); 4865 4866 if (Args.hasArg(options::OPT_municode)) 4867 CmdArgs.push_back("-DUNICODE"); 4868 4869 if (isa<AnalyzeJobAction>(JA)) 4870 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input); 4871 4872 if (isa<AnalyzeJobAction>(JA) || 4873 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze))) 4874 CmdArgs.push_back("-setup-static-analyzer"); 4875 4876 // Enable compatilibily mode to avoid analyzer-config related errors. 4877 // Since we can't access frontend flags through hasArg, let's manually iterate 4878 // through them. 4879 bool FoundAnalyzerConfig = false; 4880 for (auto Arg : Args.filtered(options::OPT_Xclang)) 4881 if (StringRef(Arg->getValue()) == "-analyzer-config") { 4882 FoundAnalyzerConfig = true; 4883 break; 4884 } 4885 if (!FoundAnalyzerConfig) 4886 for (auto Arg : Args.filtered(options::OPT_Xanalyzer)) 4887 if (StringRef(Arg->getValue()) == "-analyzer-config") { 4888 FoundAnalyzerConfig = true; 4889 break; 4890 } 4891 if (FoundAnalyzerConfig) 4892 CmdArgs.push_back("-analyzer-config-compatibility-mode=true"); 4893 4894 CheckCodeGenerationOptions(D, Args); 4895 4896 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args); 4897 assert(FunctionAlignment <= 31 && "function alignment will be truncated!"); 4898 if (FunctionAlignment) { 4899 CmdArgs.push_back("-function-alignment"); 4900 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment))); 4901 } 4902 4903 // We support -falign-loops=N where N is a power of 2. GCC supports more 4904 // forms. 4905 if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) { 4906 unsigned Value = 0; 4907 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536) 4908 TC.getDriver().Diag(diag::err_drv_invalid_int_value) 4909 << A->getAsString(Args) << A->getValue(); 4910 else if (Value & (Value - 1)) 4911 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two) 4912 << A->getAsString(Args) << A->getValue(); 4913 // Treat =0 as unspecified (use the target preference). 4914 if (Value) 4915 CmdArgs.push_back(Args.MakeArgString("-falign-loops=" + 4916 Twine(std::min(Value, 65536u)))); 4917 } 4918 4919 llvm::Reloc::Model RelocationModel; 4920 unsigned PICLevel; 4921 bool IsPIE; 4922 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args); 4923 4924 bool IsROPI = RelocationModel == llvm::Reloc::ROPI || 4925 RelocationModel == llvm::Reloc::ROPI_RWPI; 4926 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI || 4927 RelocationModel == llvm::Reloc::ROPI_RWPI; 4928 4929 if (Args.hasArg(options::OPT_mcmse) && 4930 !Args.hasArg(options::OPT_fallow_unsupported)) { 4931 if (IsROPI) 4932 D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI; 4933 if (IsRWPI) 4934 D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI; 4935 } 4936 4937 if (IsROPI && types::isCXX(Input.getType()) && 4938 !Args.hasArg(options::OPT_fallow_unsupported)) 4939 D.Diag(diag::err_drv_ropi_incompatible_with_cxx); 4940 4941 const char *RMName = RelocationModelName(RelocationModel); 4942 if (RMName) { 4943 CmdArgs.push_back("-mrelocation-model"); 4944 CmdArgs.push_back(RMName); 4945 } 4946 if (PICLevel > 0) { 4947 CmdArgs.push_back("-pic-level"); 4948 CmdArgs.push_back(PICLevel == 1 ? "1" : "2"); 4949 if (IsPIE) 4950 CmdArgs.push_back("-pic-is-pie"); 4951 } 4952 4953 if (RelocationModel == llvm::Reloc::ROPI || 4954 RelocationModel == llvm::Reloc::ROPI_RWPI) 4955 CmdArgs.push_back("-fropi"); 4956 if (RelocationModel == llvm::Reloc::RWPI || 4957 RelocationModel == llvm::Reloc::ROPI_RWPI) 4958 CmdArgs.push_back("-frwpi"); 4959 4960 if (Arg *A = Args.getLastArg(options::OPT_meabi)) { 4961 CmdArgs.push_back("-meabi"); 4962 CmdArgs.push_back(A->getValue()); 4963 } 4964 4965 // -fsemantic-interposition is forwarded to CC1: set the 4966 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and 4967 // make default visibility external linkage definitions dso_preemptable. 4968 // 4969 // -fno-semantic-interposition: if the target supports .Lfoo$local local 4970 // aliases (make default visibility external linkage definitions dso_local). 4971 // This is the CC1 default for ELF to match COFF/Mach-O. 4972 // 4973 // Otherwise use Clang's traditional behavior: like 4974 // -fno-semantic-interposition but local aliases are not used. So references 4975 // can be interposed if not optimized out. 4976 if (Triple.isOSBinFormatELF()) { 4977 Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition, 4978 options::OPT_fno_semantic_interposition); 4979 if (RelocationModel != llvm::Reloc::Static && !IsPIE) { 4980 // The supported targets need to call AsmPrinter::getSymbolPreferLocal. 4981 bool SupportsLocalAlias = 4982 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86(); 4983 if (!A) 4984 CmdArgs.push_back("-fhalf-no-semantic-interposition"); 4985 else if (A->getOption().matches(options::OPT_fsemantic_interposition)) 4986 A->render(Args, CmdArgs); 4987 else if (!SupportsLocalAlias) 4988 CmdArgs.push_back("-fhalf-no-semantic-interposition"); 4989 } 4990 } 4991 4992 { 4993 std::string Model; 4994 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) { 4995 if (!TC.isThreadModelSupported(A->getValue())) 4996 D.Diag(diag::err_drv_invalid_thread_model_for_target) 4997 << A->getValue() << A->getAsString(Args); 4998 Model = A->getValue(); 4999 } else 5000 Model = TC.getThreadModel(); 5001 if (Model != "posix") { 5002 CmdArgs.push_back("-mthread-model"); 5003 CmdArgs.push_back(Args.MakeArgString(Model)); 5004 } 5005 } 5006 5007 Args.AddLastArg(CmdArgs, options::OPT_fveclib); 5008 5009 if (Args.hasFlag(options::OPT_fmerge_all_constants, 5010 options::OPT_fno_merge_all_constants, false)) 5011 CmdArgs.push_back("-fmerge-all-constants"); 5012 5013 if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks, 5014 options::OPT_fdelete_null_pointer_checks, false)) 5015 CmdArgs.push_back("-fno-delete-null-pointer-checks"); 5016 5017 // LLVM Code Generator Options. 5018 5019 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file_EQ)) { 5020 StringRef Map = A->getValue(); 5021 if (!llvm::sys::fs::exists(Map)) { 5022 D.Diag(diag::err_drv_no_such_file) << Map; 5023 } else { 5024 A->render(Args, CmdArgs); 5025 A->claim(); 5026 } 5027 } 5028 5029 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_vec_extabi, 5030 options::OPT_mabi_EQ_vec_default)) { 5031 if (!Triple.isOSAIX()) 5032 D.Diag(diag::err_drv_unsupported_opt_for_target) 5033 << A->getSpelling() << RawTriple.str(); 5034 if (A->getOption().getID() == options::OPT_mabi_EQ_vec_extabi) 5035 CmdArgs.push_back("-mabi=vec-extabi"); 5036 else 5037 CmdArgs.push_back("-mabi=vec-default"); 5038 } 5039 5040 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) { 5041 // Emit the unsupported option error until the Clang's library integration 5042 // support for 128-bit long double is available for AIX. 5043 if (Triple.isOSAIX()) 5044 D.Diag(diag::err_drv_unsupported_opt_for_target) 5045 << A->getSpelling() << RawTriple.str(); 5046 } 5047 5048 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) { 5049 StringRef v = A->getValue(); 5050 // FIXME: Validate the argument here so we don't produce meaningless errors 5051 // about -fwarn-stack-size=. 5052 if (v.empty()) 5053 D.Diag(diag::err_drv_missing_argument) << A->getSpelling() << 1; 5054 else 5055 CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + v)); 5056 A->claim(); 5057 } 5058 5059 Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables, 5060 options::OPT_fno_jump_tables); 5061 Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate, 5062 options::OPT_fno_profile_sample_accurate); 5063 Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments, 5064 options::OPT_fno_preserve_as_comments); 5065 5066 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) { 5067 CmdArgs.push_back("-mregparm"); 5068 CmdArgs.push_back(A->getValue()); 5069 } 5070 5071 if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return, 5072 options::OPT_msvr4_struct_return)) { 5073 if (!TC.getTriple().isPPC32()) { 5074 D.Diag(diag::err_drv_unsupported_opt_for_target) 5075 << A->getSpelling() << RawTriple.str(); 5076 } else if (A->getOption().matches(options::OPT_maix_struct_return)) { 5077 CmdArgs.push_back("-maix-struct-return"); 5078 } else { 5079 assert(A->getOption().matches(options::OPT_msvr4_struct_return)); 5080 CmdArgs.push_back("-msvr4-struct-return"); 5081 } 5082 } 5083 5084 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return, 5085 options::OPT_freg_struct_return)) { 5086 if (TC.getArch() != llvm::Triple::x86) { 5087 D.Diag(diag::err_drv_unsupported_opt_for_target) 5088 << A->getSpelling() << RawTriple.str(); 5089 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) { 5090 CmdArgs.push_back("-fpcc-struct-return"); 5091 } else { 5092 assert(A->getOption().matches(options::OPT_freg_struct_return)); 5093 CmdArgs.push_back("-freg-struct-return"); 5094 } 5095 } 5096 5097 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) 5098 CmdArgs.push_back("-fdefault-calling-conv=stdcall"); 5099 5100 if (Args.hasArg(options::OPT_fenable_matrix)) { 5101 // enable-matrix is needed by both the LangOpts and by LLVM. 5102 CmdArgs.push_back("-fenable-matrix"); 5103 CmdArgs.push_back("-mllvm"); 5104 CmdArgs.push_back("-enable-matrix"); 5105 } 5106 5107 CodeGenOptions::FramePointerKind FPKeepKind = 5108 getFramePointerKind(Args, RawTriple); 5109 const char *FPKeepKindStr = nullptr; 5110 switch (FPKeepKind) { 5111 case CodeGenOptions::FramePointerKind::None: 5112 FPKeepKindStr = "-mframe-pointer=none"; 5113 break; 5114 case CodeGenOptions::FramePointerKind::NonLeaf: 5115 FPKeepKindStr = "-mframe-pointer=non-leaf"; 5116 break; 5117 case CodeGenOptions::FramePointerKind::All: 5118 FPKeepKindStr = "-mframe-pointer=all"; 5119 break; 5120 } 5121 assert(FPKeepKindStr && "unknown FramePointerKind"); 5122 CmdArgs.push_back(FPKeepKindStr); 5123 5124 Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss, 5125 options::OPT_fno_zero_initialized_in_bss); 5126 5127 bool OFastEnabled = isOptimizationLevelFast(Args); 5128 // If -Ofast is the optimization level, then -fstrict-aliasing should be 5129 // enabled. This alias option is being used to simplify the hasFlag logic. 5130 OptSpecifier StrictAliasingAliasOption = 5131 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing; 5132 // We turn strict aliasing off by default if we're in CL mode, since MSVC 5133 // doesn't do any TBAA. 5134 bool TBAAOnByDefault = !D.IsCLMode(); 5135 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption, 5136 options::OPT_fno_strict_aliasing, TBAAOnByDefault)) 5137 CmdArgs.push_back("-relaxed-aliasing"); 5138 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa, 5139 options::OPT_fno_struct_path_tbaa, true)) 5140 CmdArgs.push_back("-no-struct-path-tbaa"); 5141 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums, 5142 options::OPT_fno_strict_enums); 5143 Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return, 5144 options::OPT_fno_strict_return); 5145 Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders, 5146 options::OPT_fno_allow_editor_placeholders); 5147 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers, 5148 options::OPT_fno_strict_vtable_pointers); 5149 Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables, 5150 options::OPT_fno_force_emit_vtables); 5151 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls, 5152 options::OPT_fno_optimize_sibling_calls); 5153 Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls, 5154 options::OPT_fno_escaping_block_tail_calls); 5155 5156 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses, 5157 options::OPT_fno_fine_grained_bitfield_accesses); 5158 5159 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables, 5160 options::OPT_fno_experimental_relative_cxx_abi_vtables); 5161 5162 // Handle segmented stacks. 5163 if (Args.hasFlag(options::OPT_fsplit_stack, options::OPT_fno_split_stack, 5164 false)) 5165 CmdArgs.push_back("-fsplit-stack"); 5166 5167 // -fprotect-parens=0 is default. 5168 if (Args.hasFlag(options::OPT_fprotect_parens, 5169 options::OPT_fno_protect_parens, false)) 5170 CmdArgs.push_back("-fprotect-parens"); 5171 5172 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA); 5173 5174 if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) { 5175 const llvm::Triple::ArchType Arch = TC.getArch(); 5176 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) { 5177 StringRef V = A->getValue(); 5178 if (V == "64") 5179 CmdArgs.push_back("-fextend-arguments=64"); 5180 else if (V != "32") 5181 D.Diag(diag::err_drv_invalid_argument_to_option) 5182 << A->getValue() << A->getOption().getName(); 5183 } else 5184 D.Diag(diag::err_drv_unsupported_opt_for_target) 5185 << A->getOption().getName() << TripleStr; 5186 } 5187 5188 if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) { 5189 if (TC.getArch() == llvm::Triple::avr) 5190 A->render(Args, CmdArgs); 5191 else 5192 D.Diag(diag::err_drv_unsupported_opt_for_target) 5193 << A->getAsString(Args) << TripleStr; 5194 } 5195 5196 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) { 5197 if (TC.getTriple().isX86()) 5198 A->render(Args, CmdArgs); 5199 else if (TC.getTriple().isPPC() && 5200 (A->getOption().getID() != options::OPT_mlong_double_80)) 5201 A->render(Args, CmdArgs); 5202 else 5203 D.Diag(diag::err_drv_unsupported_opt_for_target) 5204 << A->getAsString(Args) << TripleStr; 5205 } 5206 5207 // Decide whether to use verbose asm. Verbose assembly is the default on 5208 // toolchains which have the integrated assembler on by default. 5209 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault(); 5210 if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm, 5211 IsIntegratedAssemblerDefault)) 5212 CmdArgs.push_back("-fno-verbose-asm"); 5213 5214 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we 5215 // use that to indicate the MC default in the backend. 5216 if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) { 5217 StringRef V = A->getValue(); 5218 unsigned Num; 5219 if (V == "none") 5220 A->render(Args, CmdArgs); 5221 else if (!V.consumeInteger(10, Num) && Num > 0 && 5222 (V.empty() || (V.consume_front(".") && 5223 !V.consumeInteger(10, Num) && V.empty()))) 5224 A->render(Args, CmdArgs); 5225 else 5226 D.Diag(diag::err_drv_invalid_argument_to_option) 5227 << A->getValue() << A->getOption().getName(); 5228 } 5229 5230 // If toolchain choose to use MCAsmParser for inline asm don't pass the 5231 // option to disable integrated-as explictly. 5232 if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser()) 5233 CmdArgs.push_back("-no-integrated-as"); 5234 5235 if (Args.hasArg(options::OPT_fdebug_pass_structure)) { 5236 CmdArgs.push_back("-mdebug-pass"); 5237 CmdArgs.push_back("Structure"); 5238 } 5239 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) { 5240 CmdArgs.push_back("-mdebug-pass"); 5241 CmdArgs.push_back("Arguments"); 5242 } 5243 5244 // Enable -mconstructor-aliases except on darwin, where we have to work around 5245 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where 5246 // aliases aren't supported. 5247 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX()) 5248 CmdArgs.push_back("-mconstructor-aliases"); 5249 5250 // Darwin's kernel doesn't support guard variables; just die if we 5251 // try to use them. 5252 if (KernelOrKext && RawTriple.isOSDarwin()) 5253 CmdArgs.push_back("-fforbid-guard-variables"); 5254 5255 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields, 5256 Triple.isWindowsGNUEnvironment())) { 5257 CmdArgs.push_back("-mms-bitfields"); 5258 } 5259 5260 // Non-PIC code defaults to -fdirect-access-external-data while PIC code 5261 // defaults to -fno-direct-access-external-data. Pass the option if different 5262 // from the default. 5263 if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data, 5264 options::OPT_fno_direct_access_external_data)) 5265 if (A->getOption().matches(options::OPT_fdirect_access_external_data) != 5266 (PICLevel == 0)) 5267 A->render(Args, CmdArgs); 5268 5269 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) { 5270 CmdArgs.push_back("-fno-plt"); 5271 } 5272 5273 // -fhosted is default. 5274 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to 5275 // use Freestanding. 5276 bool Freestanding = 5277 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) || 5278 KernelOrKext; 5279 if (Freestanding) 5280 CmdArgs.push_back("-ffreestanding"); 5281 5282 // This is a coarse approximation of what llvm-gcc actually does, both 5283 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more 5284 // complicated ways. 5285 auto SanitizeArgs = TC.getSanitizerArgs(Args); 5286 bool AsyncUnwindTables = Args.hasFlag( 5287 options::OPT_fasynchronous_unwind_tables, 5288 options::OPT_fno_asynchronous_unwind_tables, 5289 (TC.IsUnwindTablesDefault(Args) || SanitizeArgs.needsUnwindTables()) && 5290 !Freestanding); 5291 bool UnwindTables = Args.hasFlag(options::OPT_funwind_tables, 5292 options::OPT_fno_unwind_tables, false); 5293 if (AsyncUnwindTables) 5294 CmdArgs.push_back("-funwind-tables=2"); 5295 else if (UnwindTables) 5296 CmdArgs.push_back("-funwind-tables=1"); 5297 5298 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless 5299 // `--gpu-use-aux-triple-only` is specified. 5300 if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) && 5301 (IsCudaDevice || IsHIPDevice)) { 5302 const ArgList &HostArgs = 5303 C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None); 5304 std::string HostCPU = 5305 getCPUName(D, HostArgs, *TC.getAuxTriple(), /*FromAs*/ false); 5306 if (!HostCPU.empty()) { 5307 CmdArgs.push_back("-aux-target-cpu"); 5308 CmdArgs.push_back(Args.MakeArgString(HostCPU)); 5309 } 5310 getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs, 5311 /*ForAS*/ false, /*IsAux*/ true); 5312 } 5313 5314 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind()); 5315 5316 // FIXME: Handle -mtune=. 5317 (void)Args.hasArg(options::OPT_mtune_EQ); 5318 5319 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) { 5320 StringRef CM = A->getValue(); 5321 if (CM == "small" || CM == "kernel" || CM == "medium" || CM == "large" || 5322 CM == "tiny") { 5323 if (Triple.isOSAIX() && CM == "medium") 5324 CmdArgs.push_back("-mcmodel=large"); 5325 else 5326 A->render(Args, CmdArgs); 5327 } else { 5328 D.Diag(diag::err_drv_invalid_argument_to_option) 5329 << CM << A->getOption().getName(); 5330 } 5331 } 5332 5333 if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) { 5334 StringRef Value = A->getValue(); 5335 unsigned TLSSize = 0; 5336 Value.getAsInteger(10, TLSSize); 5337 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF()) 5338 D.Diag(diag::err_drv_unsupported_opt_for_target) 5339 << A->getOption().getName() << TripleStr; 5340 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48) 5341 D.Diag(diag::err_drv_invalid_int_value) 5342 << A->getOption().getName() << Value; 5343 Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ); 5344 } 5345 5346 // Add the target cpu 5347 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false); 5348 if (!CPU.empty()) { 5349 CmdArgs.push_back("-target-cpu"); 5350 CmdArgs.push_back(Args.MakeArgString(CPU)); 5351 } 5352 5353 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs); 5354 5355 // FIXME: For now we want to demote any errors to warnings, when they have 5356 // been raised for asking the wrong question of scalable vectors, such as 5357 // asking for the fixed number of elements. This may happen because code that 5358 // is not yet ported to work for scalable vectors uses the wrong interfaces, 5359 // whereas the behaviour is actually correct. Emitting a warning helps bring 5360 // up scalable vector support in an incremental way. When scalable vector 5361 // support is stable enough, all uses of wrong interfaces should be considered 5362 // as errors, but until then, we can live with a warning being emitted by the 5363 // compiler. This way, Clang can be used to compile code with scalable vectors 5364 // and identify possible issues. 5365 if (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) || 5366 isa<BackendJobAction>(JA)) { 5367 CmdArgs.push_back("-mllvm"); 5368 CmdArgs.push_back("-treat-scalable-fixed-error-as-warning"); 5369 } 5370 5371 // These two are potentially updated by AddClangCLArgs. 5372 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo; 5373 bool EmitCodeView = false; 5374 5375 // Add clang-cl arguments. 5376 types::ID InputType = Input.getType(); 5377 if (D.IsCLMode()) 5378 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView); 5379 5380 DwarfFissionKind DwarfFission = DwarfFissionKind::None; 5381 renderDebugOptions(TC, D, RawTriple, Args, EmitCodeView, 5382 types::isLLVMIR(InputType), CmdArgs, DebugInfoKind, 5383 DwarfFission); 5384 5385 // This controls whether or not we perform JustMyCode instrumentation. 5386 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) { 5387 if (TC.getTriple().isOSBinFormatELF()) { 5388 if (DebugInfoKind >= codegenoptions::DebugInfoConstructor) 5389 CmdArgs.push_back("-fjmc"); 5390 else 5391 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc" 5392 << "-g"; 5393 } else { 5394 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only); 5395 } 5396 } 5397 5398 // Add the split debug info name to the command lines here so we 5399 // can propagate it to the backend. 5400 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) && 5401 (TC.getTriple().isOSBinFormatELF() || 5402 TC.getTriple().isOSBinFormatWasm()) && 5403 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) || 5404 isa<BackendJobAction>(JA)); 5405 if (SplitDWARF) { 5406 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output); 5407 CmdArgs.push_back("-split-dwarf-file"); 5408 CmdArgs.push_back(SplitDWARFOut); 5409 if (DwarfFission == DwarfFissionKind::Split) { 5410 CmdArgs.push_back("-split-dwarf-output"); 5411 CmdArgs.push_back(SplitDWARFOut); 5412 } 5413 } 5414 5415 // Pass the linker version in use. 5416 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) { 5417 CmdArgs.push_back("-target-linker-version"); 5418 CmdArgs.push_back(A->getValue()); 5419 } 5420 5421 // Explicitly error on some things we know we don't support and can't just 5422 // ignore. 5423 if (!Args.hasArg(options::OPT_fallow_unsupported)) { 5424 Arg *Unsupported; 5425 if (types::isCXX(InputType) && RawTriple.isOSDarwin() && 5426 TC.getArch() == llvm::Triple::x86) { 5427 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) || 5428 (Unsupported = Args.getLastArg(options::OPT_mkernel))) 5429 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386) 5430 << Unsupported->getOption().getName(); 5431 } 5432 // The faltivec option has been superseded by the maltivec option. 5433 if ((Unsupported = Args.getLastArg(options::OPT_faltivec))) 5434 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec) 5435 << Unsupported->getOption().getName() 5436 << "please use -maltivec and include altivec.h explicitly"; 5437 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec))) 5438 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec) 5439 << Unsupported->getOption().getName() << "please use -mno-altivec"; 5440 } 5441 5442 Args.AddAllArgs(CmdArgs, options::OPT_v); 5443 5444 if (Args.getLastArg(options::OPT_H)) { 5445 CmdArgs.push_back("-H"); 5446 CmdArgs.push_back("-sys-header-deps"); 5447 } 5448 Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes); 5449 5450 if (D.CCPrintHeaders && !D.CCGenDiagnostics) { 5451 CmdArgs.push_back("-header-include-file"); 5452 CmdArgs.push_back(!D.CCPrintHeadersFilename.empty() 5453 ? D.CCPrintHeadersFilename.c_str() 5454 : "-"); 5455 CmdArgs.push_back("-sys-header-deps"); 5456 } 5457 Args.AddLastArg(CmdArgs, options::OPT_P); 5458 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout); 5459 5460 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) { 5461 CmdArgs.push_back("-diagnostic-log-file"); 5462 CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty() 5463 ? D.CCLogDiagnosticsFilename.c_str() 5464 : "-"); 5465 } 5466 5467 // Give the gen diagnostics more chances to succeed, by avoiding intentional 5468 // crashes. 5469 if (D.CCGenDiagnostics) 5470 CmdArgs.push_back("-disable-pragma-debug-crash"); 5471 5472 // Allow backend to put its diagnostic files in the same place as frontend 5473 // crash diagnostics files. 5474 if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) { 5475 StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir); 5476 CmdArgs.push_back("-mllvm"); 5477 CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir)); 5478 } 5479 5480 bool UseSeparateSections = isUseSeparateSections(Triple); 5481 5482 if (Args.hasFlag(options::OPT_ffunction_sections, 5483 options::OPT_fno_function_sections, UseSeparateSections)) { 5484 CmdArgs.push_back("-ffunction-sections"); 5485 } 5486 5487 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) { 5488 StringRef Val = A->getValue(); 5489 if (Triple.isX86() && Triple.isOSBinFormatELF()) { 5490 if (Val != "all" && Val != "labels" && Val != "none" && 5491 !Val.startswith("list=")) 5492 D.Diag(diag::err_drv_invalid_value) 5493 << A->getAsString(Args) << A->getValue(); 5494 else 5495 A->render(Args, CmdArgs); 5496 } else if (Triple.isNVPTX()) { 5497 // Do not pass the option to the GPU compilation. We still want it enabled 5498 // for the host-side compilation, so seeing it here is not an error. 5499 } else if (Val != "none") { 5500 // =none is allowed everywhere. It's useful for overriding the option 5501 // and is the same as not specifying the option. 5502 D.Diag(diag::err_drv_unsupported_opt_for_target) 5503 << A->getAsString(Args) << TripleStr; 5504 } 5505 } 5506 5507 bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF(); 5508 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections, 5509 UseSeparateSections || HasDefaultDataSections)) { 5510 CmdArgs.push_back("-fdata-sections"); 5511 } 5512 5513 Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names, 5514 options::OPT_fno_unique_section_names); 5515 Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names, 5516 options::OPT_fno_unique_internal_linkage_names); 5517 Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names, 5518 options::OPT_fno_unique_basic_block_section_names); 5519 5520 if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions, 5521 options::OPT_fno_split_machine_functions)) { 5522 // This codegen pass is only available on x86-elf targets. 5523 if (Triple.isX86() && Triple.isOSBinFormatELF()) { 5524 if (A->getOption().matches(options::OPT_fsplit_machine_functions)) 5525 A->render(Args, CmdArgs); 5526 } else { 5527 D.Diag(diag::err_drv_unsupported_opt_for_target) 5528 << A->getAsString(Args) << TripleStr; 5529 } 5530 } 5531 5532 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions, 5533 options::OPT_finstrument_functions_after_inlining, 5534 options::OPT_finstrument_function_entry_bare); 5535 5536 // NVPTX/AMDGCN doesn't support PGO or coverage. There's no runtime support 5537 // for sampling, overhead of call arc collection is way too high and there's 5538 // no way to collect the output. 5539 if (!Triple.isNVPTX() && !Triple.isAMDGCN()) 5540 addPGOAndCoverageFlags(TC, C, D, Output, Args, SanitizeArgs, CmdArgs); 5541 5542 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ); 5543 5544 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled. 5545 if (RawTriple.isPS4() && 5546 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) { 5547 PS4cpu::addProfileRTArgs(TC, Args, CmdArgs); 5548 PS4cpu::addSanitizerArgs(TC, Args, CmdArgs); 5549 } 5550 5551 // Pass options for controlling the default header search paths. 5552 if (Args.hasArg(options::OPT_nostdinc)) { 5553 CmdArgs.push_back("-nostdsysteminc"); 5554 CmdArgs.push_back("-nobuiltininc"); 5555 } else { 5556 if (Args.hasArg(options::OPT_nostdlibinc)) 5557 CmdArgs.push_back("-nostdsysteminc"); 5558 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx); 5559 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc); 5560 } 5561 5562 // Pass the path to compiler resource files. 5563 CmdArgs.push_back("-resource-dir"); 5564 CmdArgs.push_back(D.ResourceDir.c_str()); 5565 5566 Args.AddLastArg(CmdArgs, options::OPT_working_directory); 5567 5568 RenderARCMigrateToolOptions(D, Args, CmdArgs); 5569 5570 // Add preprocessing options like -I, -D, etc. if we are using the 5571 // preprocessor. 5572 // 5573 // FIXME: Support -fpreprocessed 5574 if (types::getPreprocessedType(InputType) != types::TY_INVALID) 5575 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs); 5576 5577 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes 5578 // that "The compiler can only warn and ignore the option if not recognized". 5579 // When building with ccache, it will pass -D options to clang even on 5580 // preprocessed inputs and configure concludes that -fPIC is not supported. 5581 Args.ClaimAllArgs(options::OPT_D); 5582 5583 // Manually translate -O4 to -O3; let clang reject others. 5584 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 5585 if (A->getOption().matches(options::OPT_O4)) { 5586 CmdArgs.push_back("-O3"); 5587 D.Diag(diag::warn_O4_is_O3); 5588 } else { 5589 A->render(Args, CmdArgs); 5590 } 5591 } 5592 5593 // Warn about ignored options to clang. 5594 for (const Arg *A : 5595 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) { 5596 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args); 5597 A->claim(); 5598 } 5599 5600 for (const Arg *A : 5601 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) { 5602 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args); 5603 A->claim(); 5604 } 5605 5606 claimNoWarnArgs(Args); 5607 5608 Args.AddAllArgs(CmdArgs, options::OPT_R_Group); 5609 5610 for (const Arg *A : 5611 Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) { 5612 A->claim(); 5613 if (A->getOption().getID() == options::OPT__SLASH_wd) { 5614 unsigned WarningNumber; 5615 if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) { 5616 D.Diag(diag::err_drv_invalid_int_value) 5617 << A->getAsString(Args) << A->getValue(); 5618 continue; 5619 } 5620 5621 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) { 5622 CmdArgs.push_back(Args.MakeArgString( 5623 "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group))); 5624 } 5625 continue; 5626 } 5627 A->render(Args, CmdArgs); 5628 } 5629 5630 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false)) 5631 CmdArgs.push_back("-pedantic"); 5632 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors); 5633 Args.AddLastArg(CmdArgs, options::OPT_w); 5634 5635 // Fixed point flags 5636 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point, 5637 /*Default=*/false)) 5638 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point); 5639 5640 if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ)) 5641 A->render(Args, CmdArgs); 5642 5643 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables, 5644 options::OPT_fno_experimental_relative_cxx_abi_vtables); 5645 5646 if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ)) 5647 A->render(Args, CmdArgs); 5648 5649 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi} 5650 // (-ansi is equivalent to -std=c89 or -std=c++98). 5651 // 5652 // If a std is supplied, only add -trigraphs if it follows the 5653 // option. 5654 bool ImplyVCPPCVer = false; 5655 bool ImplyVCPPCXXVer = false; 5656 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi); 5657 if (Std) { 5658 if (Std->getOption().matches(options::OPT_ansi)) 5659 if (types::isCXX(InputType)) 5660 CmdArgs.push_back("-std=c++98"); 5661 else 5662 CmdArgs.push_back("-std=c89"); 5663 else 5664 Std->render(Args, CmdArgs); 5665 5666 // If -f(no-)trigraphs appears after the language standard flag, honor it. 5667 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi, 5668 options::OPT_ftrigraphs, 5669 options::OPT_fno_trigraphs)) 5670 if (A != Std) 5671 A->render(Args, CmdArgs); 5672 } else { 5673 // Honor -std-default. 5674 // 5675 // FIXME: Clang doesn't correctly handle -std= when the input language 5676 // doesn't match. For the time being just ignore this for C++ inputs; 5677 // eventually we want to do all the standard defaulting here instead of 5678 // splitting it between the driver and clang -cc1. 5679 if (!types::isCXX(InputType)) { 5680 if (!Args.hasArg(options::OPT__SLASH_std)) { 5681 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=", 5682 /*Joined=*/true); 5683 } else 5684 ImplyVCPPCVer = true; 5685 } 5686 else if (IsWindowsMSVC) 5687 ImplyVCPPCXXVer = true; 5688 5689 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs, 5690 options::OPT_fno_trigraphs); 5691 5692 // HIP headers has minimum C++ standard requirements. Therefore set the 5693 // default language standard. 5694 if (IsHIP) 5695 CmdArgs.push_back(IsWindowsMSVC ? "-std=c++14" : "-std=c++11"); 5696 } 5697 5698 // GCC's behavior for -Wwrite-strings is a bit strange: 5699 // * In C, this "warning flag" changes the types of string literals from 5700 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning 5701 // for the discarded qualifier. 5702 // * In C++, this is just a normal warning flag. 5703 // 5704 // Implementing this warning correctly in C is hard, so we follow GCC's 5705 // behavior for now. FIXME: Directly diagnose uses of a string literal as 5706 // a non-const char* in C, rather than using this crude hack. 5707 if (!types::isCXX(InputType)) { 5708 // FIXME: This should behave just like a warning flag, and thus should also 5709 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on. 5710 Arg *WriteStrings = 5711 Args.getLastArg(options::OPT_Wwrite_strings, 5712 options::OPT_Wno_write_strings, options::OPT_w); 5713 if (WriteStrings && 5714 WriteStrings->getOption().matches(options::OPT_Wwrite_strings)) 5715 CmdArgs.push_back("-fconst-strings"); 5716 } 5717 5718 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active 5719 // during C++ compilation, which it is by default. GCC keeps this define even 5720 // in the presence of '-w', match this behavior bug-for-bug. 5721 if (types::isCXX(InputType) && 5722 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated, 5723 true)) { 5724 CmdArgs.push_back("-fdeprecated-macro"); 5725 } 5726 5727 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'. 5728 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) { 5729 if (Asm->getOption().matches(options::OPT_fasm)) 5730 CmdArgs.push_back("-fgnu-keywords"); 5731 else 5732 CmdArgs.push_back("-fno-gnu-keywords"); 5733 } 5734 5735 if (!ShouldEnableAutolink(Args, TC, JA)) 5736 CmdArgs.push_back("-fno-autolink"); 5737 5738 // Add in -fdebug-compilation-dir if necessary. 5739 const char *DebugCompilationDir = 5740 addDebugCompDirArg(Args, CmdArgs, D.getVFS()); 5741 5742 addDebugPrefixMapArg(D, TC, Args, CmdArgs); 5743 5744 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_, 5745 options::OPT_ftemplate_depth_EQ)) { 5746 CmdArgs.push_back("-ftemplate-depth"); 5747 CmdArgs.push_back(A->getValue()); 5748 } 5749 5750 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) { 5751 CmdArgs.push_back("-foperator-arrow-depth"); 5752 CmdArgs.push_back(A->getValue()); 5753 } 5754 5755 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) { 5756 CmdArgs.push_back("-fconstexpr-depth"); 5757 CmdArgs.push_back(A->getValue()); 5758 } 5759 5760 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) { 5761 CmdArgs.push_back("-fconstexpr-steps"); 5762 CmdArgs.push_back(A->getValue()); 5763 } 5764 5765 if (Args.hasArg(options::OPT_funstable)) { 5766 CmdArgs.push_back("-funstable"); 5767 if (!Args.hasArg(options::OPT_fno_coroutines_ts)) 5768 CmdArgs.push_back("-fcoroutines-ts"); 5769 CmdArgs.push_back("-fmodules-ts"); 5770 } 5771 5772 if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter)) 5773 CmdArgs.push_back("-fexperimental-new-constant-interpreter"); 5774 5775 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) { 5776 CmdArgs.push_back("-fbracket-depth"); 5777 CmdArgs.push_back(A->getValue()); 5778 } 5779 5780 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ, 5781 options::OPT_Wlarge_by_value_copy_def)) { 5782 if (A->getNumValues()) { 5783 StringRef bytes = A->getValue(); 5784 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes)); 5785 } else 5786 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value 5787 } 5788 5789 if (Args.hasArg(options::OPT_relocatable_pch)) 5790 CmdArgs.push_back("-relocatable-pch"); 5791 5792 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) { 5793 static const char *kCFABIs[] = { 5794 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1", 5795 }; 5796 5797 if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs)) 5798 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue(); 5799 else 5800 A->render(Args, CmdArgs); 5801 } 5802 5803 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) { 5804 CmdArgs.push_back("-fconstant-string-class"); 5805 CmdArgs.push_back(A->getValue()); 5806 } 5807 5808 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) { 5809 CmdArgs.push_back("-ftabstop"); 5810 CmdArgs.push_back(A->getValue()); 5811 } 5812 5813 if (Args.hasFlag(options::OPT_fstack_size_section, 5814 options::OPT_fno_stack_size_section, RawTriple.isPS4())) 5815 CmdArgs.push_back("-fstack-size-section"); 5816 5817 if (Args.hasArg(options::OPT_fstack_usage)) { 5818 CmdArgs.push_back("-stack-usage-file"); 5819 5820 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) { 5821 SmallString<128> OutputFilename(OutputOpt->getValue()); 5822 llvm::sys::path::replace_extension(OutputFilename, "su"); 5823 CmdArgs.push_back(Args.MakeArgString(OutputFilename)); 5824 } else 5825 CmdArgs.push_back( 5826 Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su")); 5827 } 5828 5829 CmdArgs.push_back("-ferror-limit"); 5830 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ)) 5831 CmdArgs.push_back(A->getValue()); 5832 else 5833 CmdArgs.push_back("19"); 5834 5835 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) { 5836 CmdArgs.push_back("-fmacro-backtrace-limit"); 5837 CmdArgs.push_back(A->getValue()); 5838 } 5839 5840 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) { 5841 CmdArgs.push_back("-ftemplate-backtrace-limit"); 5842 CmdArgs.push_back(A->getValue()); 5843 } 5844 5845 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) { 5846 CmdArgs.push_back("-fconstexpr-backtrace-limit"); 5847 CmdArgs.push_back(A->getValue()); 5848 } 5849 5850 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) { 5851 CmdArgs.push_back("-fspell-checking-limit"); 5852 CmdArgs.push_back(A->getValue()); 5853 } 5854 5855 // Pass -fmessage-length=. 5856 unsigned MessageLength = 0; 5857 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) { 5858 StringRef V(A->getValue()); 5859 if (V.getAsInteger(0, MessageLength)) 5860 D.Diag(diag::err_drv_invalid_argument_to_option) 5861 << V << A->getOption().getName(); 5862 } else { 5863 // If -fmessage-length=N was not specified, determine whether this is a 5864 // terminal and, if so, implicitly define -fmessage-length appropriately. 5865 MessageLength = llvm::sys::Process::StandardErrColumns(); 5866 } 5867 if (MessageLength != 0) 5868 CmdArgs.push_back( 5869 Args.MakeArgString("-fmessage-length=" + Twine(MessageLength))); 5870 5871 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ)) 5872 CmdArgs.push_back( 5873 Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0)))); 5874 5875 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ)) 5876 CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" + 5877 Twine(A->getValue(0)))); 5878 5879 // -fvisibility= and -fvisibility-ms-compat are of a piece. 5880 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ, 5881 options::OPT_fvisibility_ms_compat)) { 5882 if (A->getOption().matches(options::OPT_fvisibility_EQ)) { 5883 CmdArgs.push_back("-fvisibility"); 5884 CmdArgs.push_back(A->getValue()); 5885 } else { 5886 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat)); 5887 CmdArgs.push_back("-fvisibility"); 5888 CmdArgs.push_back("hidden"); 5889 CmdArgs.push_back("-ftype-visibility"); 5890 CmdArgs.push_back("default"); 5891 } 5892 } else if (IsOpenMPDevice) { 5893 // When compiling for the OpenMP device we want protected visibility by 5894 // default. This prevents the device from accidenally preempting code on the 5895 // host, makes the system more robust, and improves performance. 5896 CmdArgs.push_back("-fvisibility"); 5897 CmdArgs.push_back("protected"); 5898 } 5899 5900 if (!RawTriple.isPS4()) 5901 if (const Arg *A = 5902 Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass, 5903 options::OPT_fno_visibility_from_dllstorageclass)) { 5904 if (A->getOption().matches( 5905 options::OPT_fvisibility_from_dllstorageclass)) { 5906 CmdArgs.push_back("-fvisibility-from-dllstorageclass"); 5907 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ); 5908 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ); 5909 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ); 5910 Args.AddLastArg(CmdArgs, 5911 options::OPT_fvisibility_externs_nodllstorageclass_EQ); 5912 } 5913 } 5914 5915 if (const Arg *A = Args.getLastArg(options::OPT_mignore_xcoff_visibility)) { 5916 if (Triple.isOSAIX()) 5917 CmdArgs.push_back("-mignore-xcoff-visibility"); 5918 else 5919 D.Diag(diag::err_drv_unsupported_opt_for_target) 5920 << A->getAsString(Args) << TripleStr; 5921 } 5922 5923 5924 if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden, 5925 options::OPT_fno_visibility_inlines_hidden, false)) 5926 CmdArgs.push_back("-fvisibility-inlines-hidden"); 5927 5928 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var, 5929 options::OPT_fno_visibility_inlines_hidden_static_local_var); 5930 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden); 5931 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ); 5932 5933 if (Args.hasFlag(options::OPT_fnew_infallible, 5934 options::OPT_fno_new_infallible, false)) 5935 CmdArgs.push_back("-fnew-infallible"); 5936 5937 if (Args.hasFlag(options::OPT_fno_operator_names, 5938 options::OPT_foperator_names, false)) 5939 CmdArgs.push_back("-fno-operator-names"); 5940 5941 // Forward -f (flag) options which we can pass directly. 5942 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls); 5943 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions); 5944 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs); 5945 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls, 5946 options::OPT_fno_emulated_tls); 5947 Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ); 5948 5949 if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) { 5950 // FIXME: There's no reason for this to be restricted to X86. The backend 5951 // code needs to be changed to include the appropriate function calls 5952 // automatically. 5953 if (!Triple.isX86()) 5954 D.Diag(diag::err_drv_unsupported_opt_for_target) 5955 << A->getAsString(Args) << TripleStr; 5956 } 5957 5958 // AltiVec-like language extensions aren't relevant for assembling. 5959 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) 5960 Args.AddLastArg(CmdArgs, options::OPT_fzvector); 5961 5962 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree); 5963 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type); 5964 5965 // Forward flags for OpenMP. We don't do this if the current action is an 5966 // device offloading action other than OpenMP. 5967 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ, 5968 options::OPT_fno_openmp, false) && 5969 (JA.isDeviceOffloading(Action::OFK_None) || 5970 JA.isDeviceOffloading(Action::OFK_OpenMP))) { 5971 switch (D.getOpenMPRuntime(Args)) { 5972 case Driver::OMPRT_OMP: 5973 case Driver::OMPRT_IOMP5: 5974 // Clang can generate useful OpenMP code for these two runtime libraries. 5975 CmdArgs.push_back("-fopenmp"); 5976 5977 // If no option regarding the use of TLS in OpenMP codegeneration is 5978 // given, decide a default based on the target. Otherwise rely on the 5979 // options and pass the right information to the frontend. 5980 if (!Args.hasFlag(options::OPT_fopenmp_use_tls, 5981 options::OPT_fnoopenmp_use_tls, /*Default=*/true)) 5982 CmdArgs.push_back("-fnoopenmp-use-tls"); 5983 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd, 5984 options::OPT_fno_openmp_simd); 5985 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder); 5986 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ); 5987 if (!Args.hasFlag(options::OPT_fopenmp_extensions, 5988 options::OPT_fno_openmp_extensions, /*Default=*/true)) 5989 CmdArgs.push_back("-fno-openmp-extensions"); 5990 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ); 5991 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ); 5992 Args.AddAllArgs(CmdArgs, 5993 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ); 5994 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse, 5995 options::OPT_fno_openmp_optimistic_collapse, 5996 /*Default=*/false)) 5997 CmdArgs.push_back("-fopenmp-optimistic-collapse"); 5998 5999 // When in OpenMP offloading mode with NVPTX target, forward 6000 // cuda-mode flag 6001 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode, 6002 options::OPT_fno_openmp_cuda_mode, /*Default=*/false)) 6003 CmdArgs.push_back("-fopenmp-cuda-mode"); 6004 6005 // When in OpenMP offloading mode, enable debugging on the device. 6006 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ); 6007 if (Args.hasFlag(options::OPT_fopenmp_target_debug, 6008 options::OPT_fno_openmp_target_debug, /*Default=*/false)) 6009 CmdArgs.push_back("-fopenmp-target-debug"); 6010 6011 // When in OpenMP offloading mode with NVPTX target, check if full runtime 6012 // is required. 6013 if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime, 6014 options::OPT_fno_openmp_cuda_force_full_runtime, 6015 /*Default=*/false)) 6016 CmdArgs.push_back("-fopenmp-cuda-force-full-runtime"); 6017 6018 // When in OpenMP offloading mode, forward assumptions information about 6019 // thread and team counts in the device. 6020 if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription, 6021 options::OPT_fno_openmp_assume_teams_oversubscription, 6022 /*Default=*/false)) 6023 CmdArgs.push_back("-fopenmp-assume-teams-oversubscription"); 6024 if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription, 6025 options::OPT_fno_openmp_assume_threads_oversubscription, 6026 /*Default=*/false)) 6027 CmdArgs.push_back("-fopenmp-assume-threads-oversubscription"); 6028 if (Args.hasArg(options::OPT_fopenmp_assume_no_thread_state)) 6029 CmdArgs.push_back("-fopenmp-assume-no-thread-state"); 6030 if (Args.hasArg(options::OPT_fopenmp_offload_mandatory)) 6031 CmdArgs.push_back("-fopenmp-offload-mandatory"); 6032 break; 6033 default: 6034 // By default, if Clang doesn't know how to generate useful OpenMP code 6035 // for a specific runtime library, we just don't pass the '-fopenmp' flag 6036 // down to the actual compilation. 6037 // FIXME: It would be better to have a mode which *only* omits IR 6038 // generation based on the OpenMP support so that we get consistent 6039 // semantic analysis, etc. 6040 break; 6041 } 6042 } else { 6043 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd, 6044 options::OPT_fno_openmp_simd); 6045 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ); 6046 Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions, 6047 options::OPT_fno_openmp_extensions); 6048 } 6049 6050 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType); 6051 6052 const XRayArgs &XRay = TC.getXRayArgs(); 6053 XRay.addArgs(TC, Args, CmdArgs, InputType); 6054 6055 for (const auto &Filename : 6056 Args.getAllArgValues(options::OPT_fprofile_list_EQ)) { 6057 if (D.getVFS().exists(Filename)) 6058 CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename)); 6059 else 6060 D.Diag(clang::diag::err_drv_no_such_file) << Filename; 6061 } 6062 6063 if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) { 6064 StringRef S0 = A->getValue(), S = S0; 6065 unsigned Size, Offset = 0; 6066 if (!Triple.isAArch64() && !Triple.isRISCV() && !Triple.isX86()) 6067 D.Diag(diag::err_drv_unsupported_opt_for_target) 6068 << A->getAsString(Args) << TripleStr; 6069 else if (S.consumeInteger(10, Size) || 6070 (!S.empty() && (!S.consume_front(",") || 6071 S.consumeInteger(10, Offset) || !S.empty()))) 6072 D.Diag(diag::err_drv_invalid_argument_to_option) 6073 << S0 << A->getOption().getName(); 6074 else if (Size < Offset) 6075 D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument); 6076 else { 6077 CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size))); 6078 CmdArgs.push_back(Args.MakeArgString( 6079 "-fpatchable-function-entry-offset=" + Twine(Offset))); 6080 } 6081 } 6082 6083 Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch); 6084 6085 if (TC.SupportsProfiling()) { 6086 Args.AddLastArg(CmdArgs, options::OPT_pg); 6087 6088 llvm::Triple::ArchType Arch = TC.getArch(); 6089 if (Arg *A = Args.getLastArg(options::OPT_mfentry)) { 6090 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86()) 6091 A->render(Args, CmdArgs); 6092 else 6093 D.Diag(diag::err_drv_unsupported_opt_for_target) 6094 << A->getAsString(Args) << TripleStr; 6095 } 6096 if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) { 6097 if (Arch == llvm::Triple::systemz) 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_mrecord_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 } 6111 6112 if (Args.getLastArg(options::OPT_fapple_kext) || 6113 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType))) 6114 CmdArgs.push_back("-fapple-kext"); 6115 6116 Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat); 6117 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ); 6118 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch); 6119 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info); 6120 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits); 6121 Args.AddLastArg(CmdArgs, options::OPT_ftime_report); 6122 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ); 6123 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace); 6124 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ); 6125 Args.AddLastArg(CmdArgs, options::OPT_ftrapv); 6126 Args.AddLastArg(CmdArgs, options::OPT_malign_double); 6127 Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file); 6128 6129 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) { 6130 CmdArgs.push_back("-ftrapv-handler"); 6131 CmdArgs.push_back(A->getValue()); 6132 } 6133 6134 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ); 6135 6136 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but 6137 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv. 6138 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) { 6139 if (A->getOption().matches(options::OPT_fwrapv)) 6140 CmdArgs.push_back("-fwrapv"); 6141 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow, 6142 options::OPT_fno_strict_overflow)) { 6143 if (A->getOption().matches(options::OPT_fno_strict_overflow)) 6144 CmdArgs.push_back("-fwrapv"); 6145 } 6146 6147 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops, 6148 options::OPT_fno_reroll_loops)) 6149 if (A->getOption().matches(options::OPT_freroll_loops)) 6150 CmdArgs.push_back("-freroll-loops"); 6151 6152 Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops, 6153 options::OPT_fno_finite_loops); 6154 6155 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings); 6156 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops, 6157 options::OPT_fno_unroll_loops); 6158 6159 Args.AddLastArg(CmdArgs, options::OPT_pthread); 6160 6161 if (Args.hasFlag(options::OPT_mspeculative_load_hardening, 6162 options::OPT_mno_speculative_load_hardening, false)) 6163 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening")); 6164 6165 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext); 6166 RenderSCPOptions(TC, Args, CmdArgs); 6167 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs); 6168 6169 Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ); 6170 6171 // Translate -mstackrealign 6172 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign, 6173 false)) 6174 CmdArgs.push_back(Args.MakeArgString("-mstackrealign")); 6175 6176 if (Args.hasArg(options::OPT_mstack_alignment)) { 6177 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment); 6178 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment)); 6179 } 6180 6181 if (Args.hasArg(options::OPT_mstack_probe_size)) { 6182 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size); 6183 6184 if (!Size.empty()) 6185 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size)); 6186 else 6187 CmdArgs.push_back("-mstack-probe-size=0"); 6188 } 6189 6190 Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe, 6191 options::OPT_mno_stack_arg_probe); 6192 6193 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it, 6194 options::OPT_mno_restrict_it)) { 6195 if (A->getOption().matches(options::OPT_mrestrict_it)) { 6196 CmdArgs.push_back("-mllvm"); 6197 CmdArgs.push_back("-arm-restrict-it"); 6198 } else { 6199 CmdArgs.push_back("-mllvm"); 6200 CmdArgs.push_back("-arm-default-it"); 6201 } 6202 } 6203 6204 // Forward -cl options to -cc1 6205 RenderOpenCLOptions(Args, CmdArgs, InputType); 6206 6207 if (IsHIP) { 6208 if (Args.hasFlag(options::OPT_fhip_new_launch_api, 6209 options::OPT_fno_hip_new_launch_api, true)) 6210 CmdArgs.push_back("-fhip-new-launch-api"); 6211 if (Args.hasFlag(options::OPT_fgpu_allow_device_init, 6212 options::OPT_fno_gpu_allow_device_init, false)) 6213 CmdArgs.push_back("-fgpu-allow-device-init"); 6214 } 6215 6216 if (IsCuda || IsHIP) { 6217 if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)) 6218 CmdArgs.push_back("-fgpu-rdc"); 6219 if (Args.hasFlag(options::OPT_fgpu_defer_diag, 6220 options::OPT_fno_gpu_defer_diag, false)) 6221 CmdArgs.push_back("-fgpu-defer-diag"); 6222 if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads, 6223 options::OPT_fno_gpu_exclude_wrong_side_overloads, 6224 false)) { 6225 CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads"); 6226 CmdArgs.push_back("-fgpu-defer-diag"); 6227 } 6228 } 6229 6230 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) { 6231 CmdArgs.push_back( 6232 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue())); 6233 } 6234 6235 if (IsUsingLTO) 6236 Args.AddLastArg(CmdArgs, options::OPT_mibt_seal); 6237 6238 // Forward -f options with positive and negative forms; we translate these by 6239 // hand. Do not propagate PGO options to the GPU-side compilations as the 6240 // profile info is for the host-side compilation only. 6241 if (!(IsCudaDevice || IsHIPDevice)) { 6242 if (Arg *A = getLastProfileSampleUseArg(Args)) { 6243 auto *PGOArg = Args.getLastArg( 6244 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ, 6245 options::OPT_fcs_profile_generate, 6246 options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use, 6247 options::OPT_fprofile_use_EQ); 6248 if (PGOArg) 6249 D.Diag(diag::err_drv_argument_not_allowed_with) 6250 << "SampleUse with PGO options"; 6251 6252 StringRef fname = A->getValue(); 6253 if (!llvm::sys::fs::exists(fname)) 6254 D.Diag(diag::err_drv_no_such_file) << fname; 6255 else 6256 A->render(Args, CmdArgs); 6257 } 6258 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ); 6259 6260 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling, 6261 options::OPT_fno_pseudo_probe_for_profiling, false)) { 6262 CmdArgs.push_back("-fpseudo-probe-for-profiling"); 6263 // Enforce -funique-internal-linkage-names if it's not explicitly turned 6264 // off. 6265 if (Args.hasFlag(options::OPT_funique_internal_linkage_names, 6266 options::OPT_fno_unique_internal_linkage_names, true)) 6267 CmdArgs.push_back("-funique-internal-linkage-names"); 6268 } 6269 } 6270 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs); 6271 6272 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new, 6273 options::OPT_fno_assume_sane_operator_new); 6274 6275 // -fblocks=0 is default. 6276 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks, 6277 TC.IsBlocksDefault()) || 6278 (Args.hasArg(options::OPT_fgnu_runtime) && 6279 Args.hasArg(options::OPT_fobjc_nonfragile_abi) && 6280 !Args.hasArg(options::OPT_fno_blocks))) { 6281 CmdArgs.push_back("-fblocks"); 6282 6283 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime()) 6284 CmdArgs.push_back("-fblocks-runtime-optional"); 6285 } 6286 6287 // -fencode-extended-block-signature=1 is default. 6288 if (TC.IsEncodeExtendedBlockSignatureDefault()) 6289 CmdArgs.push_back("-fencode-extended-block-signature"); 6290 6291 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts, 6292 false) && 6293 types::isCXX(InputType)) { 6294 CmdArgs.push_back("-fcoroutines-ts"); 6295 } 6296 6297 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes, 6298 options::OPT_fno_double_square_bracket_attributes); 6299 6300 Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control, 6301 options::OPT_fno_access_control); 6302 Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors, 6303 options::OPT_fno_elide_constructors); 6304 6305 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode(); 6306 6307 if (KernelOrKext || (types::isCXX(InputType) && 6308 (RTTIMode == ToolChain::RM_Disabled))) 6309 CmdArgs.push_back("-fno-rtti"); 6310 6311 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS. 6312 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums, 6313 TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS())) 6314 CmdArgs.push_back("-fshort-enums"); 6315 6316 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs); 6317 6318 // -fuse-cxa-atexit is default. 6319 if (!Args.hasFlag( 6320 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit, 6321 !RawTriple.isOSAIX() && !RawTriple.isOSWindows() && 6322 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) || 6323 RawTriple.hasEnvironment())) || 6324 KernelOrKext) 6325 CmdArgs.push_back("-fno-use-cxa-atexit"); 6326 6327 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit, 6328 options::OPT_fno_register_global_dtors_with_atexit, 6329 RawTriple.isOSDarwin() && !KernelOrKext)) 6330 CmdArgs.push_back("-fregister-global-dtors-with-atexit"); 6331 6332 Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives, 6333 options::OPT_fno_use_line_directives); 6334 6335 // -fno-minimize-whitespace is default. 6336 if (Args.hasFlag(options::OPT_fminimize_whitespace, 6337 options::OPT_fno_minimize_whitespace, false)) { 6338 types::ID InputType = Inputs[0].getType(); 6339 if (!isDerivedFromC(InputType)) 6340 D.Diag(diag::err_drv_minws_unsupported_input_type) 6341 << types::getTypeName(InputType); 6342 CmdArgs.push_back("-fminimize-whitespace"); 6343 } 6344 6345 // -fms-extensions=0 is default. 6346 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions, 6347 IsWindowsMSVC)) 6348 CmdArgs.push_back("-fms-extensions"); 6349 6350 // -fms-compatibility=0 is default. 6351 bool IsMSVCCompat = Args.hasFlag( 6352 options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility, 6353 (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions, 6354 options::OPT_fno_ms_extensions, true))); 6355 if (IsMSVCCompat) 6356 CmdArgs.push_back("-fms-compatibility"); 6357 6358 // Handle -fgcc-version, if present. 6359 VersionTuple GNUCVer; 6360 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) { 6361 // Check that the version has 1 to 3 components and the minor and patch 6362 // versions fit in two decimal digits. 6363 StringRef Val = A->getValue(); 6364 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable. 6365 bool Invalid = GNUCVer.tryParse(Val); 6366 unsigned Minor = GNUCVer.getMinor().getValueOr(0); 6367 unsigned Patch = GNUCVer.getSubminor().getValueOr(0); 6368 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) { 6369 D.Diag(diag::err_drv_invalid_value) 6370 << A->getAsString(Args) << A->getValue(); 6371 } 6372 } else if (!IsMSVCCompat) { 6373 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect. 6374 GNUCVer = VersionTuple(4, 2, 1); 6375 } 6376 if (!GNUCVer.empty()) { 6377 CmdArgs.push_back( 6378 Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString())); 6379 } 6380 6381 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args); 6382 if (!MSVT.empty()) 6383 CmdArgs.push_back( 6384 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString())); 6385 6386 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19; 6387 if (ImplyVCPPCVer) { 6388 StringRef LanguageStandard; 6389 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) { 6390 Std = StdArg; 6391 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue()) 6392 .Case("c11", "-std=c11") 6393 .Case("c17", "-std=c17") 6394 .Default(""); 6395 if (LanguageStandard.empty()) 6396 D.Diag(clang::diag::warn_drv_unused_argument) 6397 << StdArg->getAsString(Args); 6398 } 6399 CmdArgs.push_back(LanguageStandard.data()); 6400 } 6401 if (ImplyVCPPCXXVer) { 6402 StringRef LanguageStandard; 6403 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) { 6404 Std = StdArg; 6405 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue()) 6406 .Case("c++14", "-std=c++14") 6407 .Case("c++17", "-std=c++17") 6408 .Case("c++20", "-std=c++20") 6409 .Case("c++latest", "-std=c++2b") 6410 .Default(""); 6411 if (LanguageStandard.empty()) 6412 D.Diag(clang::diag::warn_drv_unused_argument) 6413 << StdArg->getAsString(Args); 6414 } 6415 6416 if (LanguageStandard.empty()) { 6417 if (IsMSVC2015Compatible) 6418 LanguageStandard = "-std=c++14"; 6419 else 6420 LanguageStandard = "-std=c++11"; 6421 } 6422 6423 CmdArgs.push_back(LanguageStandard.data()); 6424 } 6425 6426 Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions, 6427 options::OPT_fno_borland_extensions); 6428 6429 // -fno-declspec is default, except for PS4. 6430 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec, 6431 RawTriple.isPS4())) 6432 CmdArgs.push_back("-fdeclspec"); 6433 else if (Args.hasArg(options::OPT_fno_declspec)) 6434 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec. 6435 6436 // -fthreadsafe-static is default, except for MSVC compatibility versions less 6437 // than 19. 6438 if (!Args.hasFlag(options::OPT_fthreadsafe_statics, 6439 options::OPT_fno_threadsafe_statics, 6440 !types::isOpenCL(InputType) && 6441 (!IsWindowsMSVC || IsMSVC2015Compatible))) 6442 CmdArgs.push_back("-fno-threadsafe-statics"); 6443 6444 // -fno-delayed-template-parsing is default, except when targeting MSVC. 6445 // Many old Windows SDK versions require this to parse. 6446 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their 6447 // compiler. We should be able to disable this by default at some point. 6448 if (Args.hasFlag(options::OPT_fdelayed_template_parsing, 6449 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC)) 6450 CmdArgs.push_back("-fdelayed-template-parsing"); 6451 6452 // -fgnu-keywords default varies depending on language; only pass if 6453 // specified. 6454 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords, 6455 options::OPT_fno_gnu_keywords); 6456 6457 Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline, 6458 options::OPT_fno_gnu89_inline); 6459 6460 const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions, 6461 options::OPT_finline_hint_functions, 6462 options::OPT_fno_inline_functions); 6463 if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) { 6464 if (A->getOption().matches(options::OPT_fno_inline)) 6465 A->render(Args, CmdArgs); 6466 } else if (InlineArg) { 6467 InlineArg->render(Args, CmdArgs); 6468 } 6469 6470 // FIXME: Find a better way to determine whether the language has modules 6471 // support by default, or just assume that all languages do. 6472 bool HaveModules = 6473 Std && (Std->containsValue("c++2a") || Std->containsValue("c++20") || 6474 Std->containsValue("c++latest")); 6475 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules); 6476 6477 if (Args.hasFlag(options::OPT_fpch_validate_input_files_content, 6478 options::OPT_fno_pch_validate_input_files_content, false)) 6479 CmdArgs.push_back("-fvalidate-ast-input-files-content"); 6480 if (Args.hasFlag(options::OPT_fpch_instantiate_templates, 6481 options::OPT_fno_pch_instantiate_templates, false)) 6482 CmdArgs.push_back("-fpch-instantiate-templates"); 6483 if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen, 6484 false)) 6485 CmdArgs.push_back("-fmodules-codegen"); 6486 if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo, 6487 false)) 6488 CmdArgs.push_back("-fmodules-debuginfo"); 6489 6490 if (!CLANG_ENABLE_OPAQUE_POINTERS_INTERNAL) 6491 CmdArgs.push_back("-no-opaque-pointers"); 6492 6493 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind); 6494 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None, 6495 Input, CmdArgs); 6496 6497 if (types::isObjC(Input.getType()) && 6498 Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec, 6499 options::OPT_fno_objc_encode_cxx_class_template_spec, 6500 !Runtime.isNeXTFamily())) 6501 CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec"); 6502 6503 if (Args.hasFlag(options::OPT_fapplication_extension, 6504 options::OPT_fno_application_extension, false)) 6505 CmdArgs.push_back("-fapplication-extension"); 6506 6507 // Handle GCC-style exception args. 6508 bool EH = false; 6509 if (!C.getDriver().IsCLMode()) 6510 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs); 6511 6512 // Handle exception personalities 6513 Arg *A = Args.getLastArg( 6514 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions, 6515 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions); 6516 if (A) { 6517 const Option &Opt = A->getOption(); 6518 if (Opt.matches(options::OPT_fsjlj_exceptions)) 6519 CmdArgs.push_back("-exception-model=sjlj"); 6520 if (Opt.matches(options::OPT_fseh_exceptions)) 6521 CmdArgs.push_back("-exception-model=seh"); 6522 if (Opt.matches(options::OPT_fdwarf_exceptions)) 6523 CmdArgs.push_back("-exception-model=dwarf"); 6524 if (Opt.matches(options::OPT_fwasm_exceptions)) 6525 CmdArgs.push_back("-exception-model=wasm"); 6526 } else { 6527 switch (TC.GetExceptionModel(Args)) { 6528 default: 6529 break; 6530 case llvm::ExceptionHandling::DwarfCFI: 6531 CmdArgs.push_back("-exception-model=dwarf"); 6532 break; 6533 case llvm::ExceptionHandling::SjLj: 6534 CmdArgs.push_back("-exception-model=sjlj"); 6535 break; 6536 case llvm::ExceptionHandling::WinEH: 6537 CmdArgs.push_back("-exception-model=seh"); 6538 break; 6539 } 6540 } 6541 6542 // C++ "sane" operator new. 6543 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new, 6544 options::OPT_fno_assume_sane_operator_new); 6545 6546 // -frelaxed-template-template-args is off by default, as it is a severe 6547 // breaking change until a corresponding change to template partial ordering 6548 // is provided. 6549 Args.addOptInFlag(CmdArgs, options::OPT_frelaxed_template_template_args, 6550 options::OPT_fno_relaxed_template_template_args); 6551 6552 // -fsized-deallocation is off by default, as it is an ABI-breaking change for 6553 // most platforms. 6554 Args.addOptInFlag(CmdArgs, options::OPT_fsized_deallocation, 6555 options::OPT_fno_sized_deallocation); 6556 6557 // -faligned-allocation is on by default in C++17 onwards and otherwise off 6558 // by default. 6559 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation, 6560 options::OPT_fno_aligned_allocation, 6561 options::OPT_faligned_new_EQ)) { 6562 if (A->getOption().matches(options::OPT_fno_aligned_allocation)) 6563 CmdArgs.push_back("-fno-aligned-allocation"); 6564 else 6565 CmdArgs.push_back("-faligned-allocation"); 6566 } 6567 6568 // The default new alignment can be specified using a dedicated option or via 6569 // a GCC-compatible option that also turns on aligned allocation. 6570 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ, 6571 options::OPT_faligned_new_EQ)) 6572 CmdArgs.push_back( 6573 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue())); 6574 6575 // -fconstant-cfstrings is default, and may be subject to argument translation 6576 // on Darwin. 6577 if (!Args.hasFlag(options::OPT_fconstant_cfstrings, 6578 options::OPT_fno_constant_cfstrings, true) || 6579 !Args.hasFlag(options::OPT_mconstant_cfstrings, 6580 options::OPT_mno_constant_cfstrings, true)) 6581 CmdArgs.push_back("-fno-constant-cfstrings"); 6582 6583 Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings, 6584 options::OPT_fno_pascal_strings); 6585 6586 // Honor -fpack-struct= and -fpack-struct, if given. Note that 6587 // -fno-pack-struct doesn't apply to -fpack-struct=. 6588 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) { 6589 std::string PackStructStr = "-fpack-struct="; 6590 PackStructStr += A->getValue(); 6591 CmdArgs.push_back(Args.MakeArgString(PackStructStr)); 6592 } else if (Args.hasFlag(options::OPT_fpack_struct, 6593 options::OPT_fno_pack_struct, false)) { 6594 CmdArgs.push_back("-fpack-struct=1"); 6595 } 6596 6597 // Handle -fmax-type-align=N and -fno-type-align 6598 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align); 6599 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) { 6600 if (!SkipMaxTypeAlign) { 6601 std::string MaxTypeAlignStr = "-fmax-type-align="; 6602 MaxTypeAlignStr += A->getValue(); 6603 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr)); 6604 } 6605 } else if (RawTriple.isOSDarwin()) { 6606 if (!SkipMaxTypeAlign) { 6607 std::string MaxTypeAlignStr = "-fmax-type-align=16"; 6608 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr)); 6609 } 6610 } 6611 6612 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true)) 6613 CmdArgs.push_back("-Qn"); 6614 6615 // -fno-common is the default, set -fcommon only when that flag is set. 6616 Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common); 6617 6618 // -fsigned-bitfields is default, and clang doesn't yet support 6619 // -funsigned-bitfields. 6620 if (!Args.hasFlag(options::OPT_fsigned_bitfields, 6621 options::OPT_funsigned_bitfields, true)) 6622 D.Diag(diag::warn_drv_clang_unsupported) 6623 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args); 6624 6625 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope. 6626 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true)) 6627 D.Diag(diag::err_drv_clang_unsupported) 6628 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args); 6629 6630 // -finput_charset=UTF-8 is default. Reject others 6631 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) { 6632 StringRef value = inputCharset->getValue(); 6633 if (!value.equals_insensitive("utf-8")) 6634 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args) 6635 << value; 6636 } 6637 6638 // -fexec_charset=UTF-8 is default. Reject others 6639 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) { 6640 StringRef value = execCharset->getValue(); 6641 if (!value.equals_insensitive("utf-8")) 6642 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args) 6643 << value; 6644 } 6645 6646 RenderDiagnosticsOptions(D, Args, CmdArgs); 6647 6648 Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks, 6649 options::OPT_fno_asm_blocks); 6650 6651 // -fgnu-inline-asm is default. 6652 if (!Args.hasFlag(options::OPT_fgnu_inline_asm, 6653 options::OPT_fno_gnu_inline_asm, true)) 6654 CmdArgs.push_back("-fno-gnu-inline-asm"); 6655 6656 // Enable vectorization per default according to the optimization level 6657 // selected. For optimization levels that want vectorization we use the alias 6658 // option to simplify the hasFlag logic. 6659 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false); 6660 OptSpecifier VectorizeAliasOption = 6661 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize; 6662 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption, 6663 options::OPT_fno_vectorize, EnableVec)) 6664 CmdArgs.push_back("-vectorize-loops"); 6665 6666 // -fslp-vectorize is enabled based on the optimization level selected. 6667 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true); 6668 OptSpecifier SLPVectAliasOption = 6669 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize; 6670 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption, 6671 options::OPT_fno_slp_vectorize, EnableSLPVec)) 6672 CmdArgs.push_back("-vectorize-slp"); 6673 6674 ParseMPreferVectorWidth(D, Args, CmdArgs); 6675 6676 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ); 6677 Args.AddLastArg(CmdArgs, 6678 options::OPT_fsanitize_undefined_strip_path_components_EQ); 6679 6680 // -fdollars-in-identifiers default varies depending on platform and 6681 // language; only pass if specified. 6682 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers, 6683 options::OPT_fno_dollars_in_identifiers)) { 6684 if (A->getOption().matches(options::OPT_fdollars_in_identifiers)) 6685 CmdArgs.push_back("-fdollars-in-identifiers"); 6686 else 6687 CmdArgs.push_back("-fno-dollars-in-identifiers"); 6688 } 6689 6690 Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack, 6691 options::OPT_fno_apple_pragma_pack); 6692 6693 if (Args.hasFlag(options::OPT_fxl_pragma_pack, 6694 options::OPT_fno_xl_pragma_pack, RawTriple.isOSAIX())) 6695 CmdArgs.push_back("-fxl-pragma-pack"); 6696 6697 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags. 6698 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple)) 6699 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA); 6700 6701 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports, 6702 options::OPT_fno_rewrite_imports, false); 6703 if (RewriteImports) 6704 CmdArgs.push_back("-frewrite-imports"); 6705 6706 // Enable rewrite includes if the user's asked for it or if we're generating 6707 // diagnostics. 6708 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be 6709 // nice to enable this when doing a crashdump for modules as well. 6710 if (Args.hasFlag(options::OPT_frewrite_includes, 6711 options::OPT_fno_rewrite_includes, false) || 6712 (C.isForDiagnostics() && !HaveModules)) 6713 CmdArgs.push_back("-frewrite-includes"); 6714 6715 // Only allow -traditional or -traditional-cpp outside in preprocessing modes. 6716 if (Arg *A = Args.getLastArg(options::OPT_traditional, 6717 options::OPT_traditional_cpp)) { 6718 if (isa<PreprocessJobAction>(JA)) 6719 CmdArgs.push_back("-traditional-cpp"); 6720 else 6721 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args); 6722 } 6723 6724 Args.AddLastArg(CmdArgs, options::OPT_dM); 6725 Args.AddLastArg(CmdArgs, options::OPT_dD); 6726 Args.AddLastArg(CmdArgs, options::OPT_dI); 6727 6728 Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ); 6729 6730 // Handle serialized diagnostics. 6731 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) { 6732 CmdArgs.push_back("-serialize-diagnostic-file"); 6733 CmdArgs.push_back(Args.MakeArgString(A->getValue())); 6734 } 6735 6736 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers)) 6737 CmdArgs.push_back("-fretain-comments-from-system-headers"); 6738 6739 // Forward -fcomment-block-commands to -cc1. 6740 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands); 6741 // Forward -fparse-all-comments to -cc1. 6742 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments); 6743 6744 // Turn -fplugin=name.so into -load name.so 6745 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) { 6746 CmdArgs.push_back("-load"); 6747 CmdArgs.push_back(A->getValue()); 6748 A->claim(); 6749 } 6750 6751 // Turn -fplugin-arg-pluginname-key=value into 6752 // -plugin-arg-pluginname key=value 6753 // GCC has an actual plugin_argument struct with key/value pairs that it 6754 // passes to its plugins, but we don't, so just pass it on as-is. 6755 // 6756 // The syntax for -fplugin-arg- is ambiguous if both plugin name and 6757 // argument key are allowed to contain dashes. GCC therefore only 6758 // allows dashes in the key. We do the same. 6759 for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) { 6760 auto ArgValue = StringRef(A->getValue()); 6761 auto FirstDashIndex = ArgValue.find('-'); 6762 StringRef PluginName = ArgValue.substr(0, FirstDashIndex); 6763 StringRef Arg = ArgValue.substr(FirstDashIndex + 1); 6764 6765 A->claim(); 6766 if (FirstDashIndex == StringRef::npos || Arg.empty()) { 6767 if (PluginName.empty()) { 6768 D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args); 6769 } else { 6770 D.Diag(diag::warn_drv_missing_plugin_arg) 6771 << PluginName << A->getAsString(Args); 6772 } 6773 continue; 6774 } 6775 6776 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName)); 6777 CmdArgs.push_back(Args.MakeArgString(Arg)); 6778 } 6779 6780 // Forward -fpass-plugin=name.so to -cc1. 6781 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) { 6782 CmdArgs.push_back( 6783 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue())); 6784 A->claim(); 6785 } 6786 6787 // Setup statistics file output. 6788 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D); 6789 if (!StatsFile.empty()) 6790 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile)); 6791 6792 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option 6793 // parser. 6794 // -finclude-default-header flag is for preprocessor, 6795 // do not pass it to other cc1 commands when save-temps is enabled 6796 if (C.getDriver().isSaveTempsEnabled() && 6797 !isa<PreprocessJobAction>(JA)) { 6798 for (auto Arg : Args.filtered(options::OPT_Xclang)) { 6799 Arg->claim(); 6800 if (StringRef(Arg->getValue()) != "-finclude-default-header") 6801 CmdArgs.push_back(Arg->getValue()); 6802 } 6803 } 6804 else { 6805 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang); 6806 } 6807 for (const Arg *A : Args.filtered(options::OPT_mllvm)) { 6808 A->claim(); 6809 6810 // We translate this by hand to the -cc1 argument, since nightly test uses 6811 // it and developers have been trained to spell it with -mllvm. Both 6812 // spellings are now deprecated and should be removed. 6813 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") { 6814 CmdArgs.push_back("-disable-llvm-optzns"); 6815 } else { 6816 A->render(Args, CmdArgs); 6817 } 6818 } 6819 6820 // With -save-temps, we want to save the unoptimized bitcode output from the 6821 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated 6822 // by the frontend. 6823 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it 6824 // has slightly different breakdown between stages. 6825 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of 6826 // pristine IR generated by the frontend. Ideally, a new compile action should 6827 // be added so both IR can be captured. 6828 if ((C.getDriver().isSaveTempsEnabled() || 6829 JA.isHostOffloading(Action::OFK_OpenMP)) && 6830 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) && 6831 isa<CompileJobAction>(JA)) 6832 CmdArgs.push_back("-disable-llvm-passes"); 6833 6834 Args.AddAllArgs(CmdArgs, options::OPT_undef); 6835 6836 const char *Exec = D.getClangProgramPath(); 6837 6838 // Optionally embed the -cc1 level arguments into the debug info or a 6839 // section, for build analysis. 6840 // Also record command line arguments into the debug info if 6841 // -grecord-gcc-switches options is set on. 6842 // By default, -gno-record-gcc-switches is set on and no recording. 6843 auto GRecordSwitches = 6844 Args.hasFlag(options::OPT_grecord_command_line, 6845 options::OPT_gno_record_command_line, false); 6846 auto FRecordSwitches = 6847 Args.hasFlag(options::OPT_frecord_command_line, 6848 options::OPT_fno_record_command_line, false); 6849 if (FRecordSwitches && !Triple.isOSBinFormatELF()) 6850 D.Diag(diag::err_drv_unsupported_opt_for_target) 6851 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args) 6852 << TripleStr; 6853 if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) { 6854 ArgStringList OriginalArgs; 6855 for (const auto &Arg : Args) 6856 Arg->render(Args, OriginalArgs); 6857 6858 SmallString<256> Flags; 6859 EscapeSpacesAndBackslashes(Exec, Flags); 6860 for (const char *OriginalArg : OriginalArgs) { 6861 SmallString<128> EscapedArg; 6862 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg); 6863 Flags += " "; 6864 Flags += EscapedArg; 6865 } 6866 auto FlagsArgString = Args.MakeArgString(Flags); 6867 if (TC.UseDwarfDebugFlags() || GRecordSwitches) { 6868 CmdArgs.push_back("-dwarf-debug-flags"); 6869 CmdArgs.push_back(FlagsArgString); 6870 } 6871 if (FRecordSwitches) { 6872 CmdArgs.push_back("-record-command-line"); 6873 CmdArgs.push_back(FlagsArgString); 6874 } 6875 } 6876 6877 // Host-side cuda compilation receives all device-side outputs in a single 6878 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary. 6879 if ((IsCuda || IsHIP) && CudaDeviceInput) { 6880 CmdArgs.push_back("-fcuda-include-gpubinary"); 6881 CmdArgs.push_back(CudaDeviceInput->getFilename()); 6882 if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)) 6883 CmdArgs.push_back("-fgpu-rdc"); 6884 } 6885 6886 if (IsCuda) { 6887 if (Args.hasFlag(options::OPT_fcuda_short_ptr, 6888 options::OPT_fno_cuda_short_ptr, false)) 6889 CmdArgs.push_back("-fcuda-short-ptr"); 6890 } 6891 6892 if (IsCuda || IsHIP) { 6893 // Determine the original source input. 6894 const Action *SourceAction = &JA; 6895 while (SourceAction->getKind() != Action::InputClass) { 6896 assert(!SourceAction->getInputs().empty() && "unexpected root action!"); 6897 SourceAction = SourceAction->getInputs()[0]; 6898 } 6899 auto CUID = cast<InputAction>(SourceAction)->getId(); 6900 if (!CUID.empty()) 6901 CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID))); 6902 } 6903 6904 if (IsHIP) { 6905 CmdArgs.push_back("-fcuda-allow-variadic-functions"); 6906 Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ); 6907 } 6908 6909 if (IsCudaDevice || IsHIPDevice) { 6910 StringRef InlineThresh = 6911 Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ); 6912 if (!InlineThresh.empty()) { 6913 std::string ArgStr = 6914 std::string("-inline-threshold=") + InlineThresh.str(); 6915 CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)}); 6916 } 6917 } 6918 6919 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path 6920 // to specify the result of the compile phase on the host, so the meaningful 6921 // device declarations can be identified. Also, -fopenmp-is-device is passed 6922 // along to tell the frontend that it is generating code for a device, so that 6923 // only the relevant declarations are emitted. 6924 if (IsOpenMPDevice) { 6925 CmdArgs.push_back("-fopenmp-is-device"); 6926 if (OpenMPDeviceInput) { 6927 CmdArgs.push_back("-fopenmp-host-ir-file-path"); 6928 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename())); 6929 } 6930 } 6931 6932 // Host-side OpenMP offloading recieves the device object files and embeds it 6933 // in a named section including the associated target triple and architecture. 6934 if (IsOpenMPHost && !OpenMPHostInputs.empty()) { 6935 auto InputFile = OpenMPHostInputs.begin(); 6936 auto OpenMPTCs = C.getOffloadToolChains<Action::OFK_OpenMP>(); 6937 for (auto TI = OpenMPTCs.first, TE = OpenMPTCs.second; TI != TE; 6938 ++TI, ++InputFile) { 6939 const ToolChain *TC = TI->second; 6940 const ArgList &TCArgs = C.getArgsForToolChain(TC, "", Action::OFK_OpenMP); 6941 StringRef File = 6942 C.getArgs().MakeArgString(TC->getInputFilename(*InputFile)); 6943 StringRef InputName = Clang::getBaseInputStem(Args, Inputs); 6944 6945 CmdArgs.push_back(Args.MakeArgString( 6946 "-fembed-offload-object=" + File + "," + 6947 Action::GetOffloadKindName(Action::OFK_OpenMP) + "." + 6948 TC->getTripleString() + "." + 6949 TCArgs.getLastArgValue(options::OPT_march_EQ) + "." + InputName)); 6950 } 6951 } 6952 6953 if (Triple.isAMDGPU()) { 6954 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs); 6955 6956 Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics, 6957 options::OPT_mno_unsafe_fp_atomics); 6958 } 6959 6960 // For all the host OpenMP offloading compile jobs we need to pass the targets 6961 // information using -fopenmp-targets= option. 6962 if (JA.isHostOffloading(Action::OFK_OpenMP)) { 6963 SmallString<128> TargetInfo("-fopenmp-targets="); 6964 6965 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ); 6966 assert(Tgts && Tgts->getNumValues() && 6967 "OpenMP offloading has to have targets specified."); 6968 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) { 6969 if (i) 6970 TargetInfo += ','; 6971 // We need to get the string from the triple because it may be not exactly 6972 // the same as the one we get directly from the arguments. 6973 llvm::Triple T(Tgts->getValue(i)); 6974 TargetInfo += T.getTriple(); 6975 } 6976 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str())); 6977 } 6978 6979 bool VirtualFunctionElimination = 6980 Args.hasFlag(options::OPT_fvirtual_function_elimination, 6981 options::OPT_fno_virtual_function_elimination, false); 6982 if (VirtualFunctionElimination) { 6983 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO 6984 // in the future). 6985 if (LTOMode != LTOK_Full) 6986 D.Diag(diag::err_drv_argument_only_allowed_with) 6987 << "-fvirtual-function-elimination" 6988 << "-flto=full"; 6989 6990 CmdArgs.push_back("-fvirtual-function-elimination"); 6991 } 6992 6993 // VFE requires whole-program-vtables, and enables it by default. 6994 bool WholeProgramVTables = Args.hasFlag( 6995 options::OPT_fwhole_program_vtables, 6996 options::OPT_fno_whole_program_vtables, VirtualFunctionElimination); 6997 if (VirtualFunctionElimination && !WholeProgramVTables) { 6998 D.Diag(diag::err_drv_argument_not_allowed_with) 6999 << "-fno-whole-program-vtables" 7000 << "-fvirtual-function-elimination"; 7001 } 7002 7003 if (WholeProgramVTables) { 7004 // Propagate -fwhole-program-vtables if this is an LTO compile. 7005 if (IsUsingLTO) 7006 CmdArgs.push_back("-fwhole-program-vtables"); 7007 // Check if we passed LTO options but they were suppressed because this is a 7008 // device offloading action, or we passed device offload LTO options which 7009 // were suppressed because this is not the device offload action. 7010 // Otherwise, issue an error. 7011 else if (!D.isUsingLTO(!IsDeviceOffloadAction)) 7012 D.Diag(diag::err_drv_argument_only_allowed_with) 7013 << "-fwhole-program-vtables" 7014 << "-flto"; 7015 } 7016 7017 bool DefaultsSplitLTOUnit = 7018 (WholeProgramVTables || SanitizeArgs.needsLTO()) && 7019 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit()); 7020 bool SplitLTOUnit = 7021 Args.hasFlag(options::OPT_fsplit_lto_unit, 7022 options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit); 7023 if (SanitizeArgs.needsLTO() && !SplitLTOUnit) 7024 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit" 7025 << "-fsanitize=cfi"; 7026 if (SplitLTOUnit) 7027 CmdArgs.push_back("-fsplit-lto-unit"); 7028 7029 if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel, 7030 options::OPT_fno_global_isel)) { 7031 CmdArgs.push_back("-mllvm"); 7032 if (A->getOption().matches(options::OPT_fglobal_isel)) { 7033 CmdArgs.push_back("-global-isel=1"); 7034 7035 // GISel is on by default on AArch64 -O0, so don't bother adding 7036 // the fallback remarks for it. Other combinations will add a warning of 7037 // some kind. 7038 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64; 7039 bool IsOptLevelSupported = false; 7040 7041 Arg *A = Args.getLastArg(options::OPT_O_Group); 7042 if (Triple.getArch() == llvm::Triple::aarch64) { 7043 if (!A || A->getOption().matches(options::OPT_O0)) 7044 IsOptLevelSupported = true; 7045 } 7046 if (!IsArchSupported || !IsOptLevelSupported) { 7047 CmdArgs.push_back("-mllvm"); 7048 CmdArgs.push_back("-global-isel-abort=2"); 7049 7050 if (!IsArchSupported) 7051 D.Diag(diag::warn_drv_global_isel_incomplete) << Triple.getArchName(); 7052 else 7053 D.Diag(diag::warn_drv_global_isel_incomplete_opt); 7054 } 7055 } else { 7056 CmdArgs.push_back("-global-isel=0"); 7057 } 7058 } 7059 7060 if (Args.hasArg(options::OPT_forder_file_instrumentation)) { 7061 CmdArgs.push_back("-forder-file-instrumentation"); 7062 // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is 7063 // on, we need to pass these flags as linker flags and that will be handled 7064 // outside of the compiler. 7065 if (!IsUsingLTO) { 7066 CmdArgs.push_back("-mllvm"); 7067 CmdArgs.push_back("-enable-order-file-instrumentation"); 7068 } 7069 } 7070 7071 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128, 7072 options::OPT_fno_force_enable_int128)) { 7073 if (A->getOption().matches(options::OPT_fforce_enable_int128)) 7074 CmdArgs.push_back("-fforce-enable-int128"); 7075 } 7076 7077 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts, 7078 options::OPT_fno_keep_static_consts); 7079 Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers, 7080 options::OPT_fno_complete_member_pointers); 7081 7082 if (!Args.hasFlag(options::OPT_fcxx_static_destructors, 7083 options::OPT_fno_cxx_static_destructors, true)) 7084 CmdArgs.push_back("-fno-c++-static-destructors"); 7085 7086 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false); 7087 7088 if (Arg *A = Args.getLastArg(options::OPT_moutline_atomics, 7089 options::OPT_mno_outline_atomics)) { 7090 // Option -moutline-atomics supported for AArch64 target only. 7091 if (!Triple.isAArch64()) { 7092 D.Diag(diag::warn_drv_moutline_atomics_unsupported_opt) 7093 << Triple.getArchName() << A->getOption().getName(); 7094 } else { 7095 if (A->getOption().matches(options::OPT_moutline_atomics)) { 7096 CmdArgs.push_back("-target-feature"); 7097 CmdArgs.push_back("+outline-atomics"); 7098 } else { 7099 CmdArgs.push_back("-target-feature"); 7100 CmdArgs.push_back("-outline-atomics"); 7101 } 7102 } 7103 } else if (Triple.isAArch64() && 7104 getToolChain().IsAArch64OutlineAtomicsDefault(Args)) { 7105 CmdArgs.push_back("-target-feature"); 7106 CmdArgs.push_back("+outline-atomics"); 7107 } 7108 7109 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig, 7110 (TC.getTriple().isOSBinFormatELF() || 7111 TC.getTriple().isOSBinFormatCOFF()) && 7112 !TC.getTriple().isPS4() && !TC.getTriple().isVE() && 7113 !TC.getTriple().isOSNetBSD() && 7114 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() && 7115 !TC.getTriple().isAndroid() && TC.useIntegratedAs())) 7116 CmdArgs.push_back("-faddrsig"); 7117 7118 if ((Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) && 7119 (EH || AsyncUnwindTables || UnwindTables || 7120 DebugInfoKind != codegenoptions::NoDebugInfo)) 7121 CmdArgs.push_back("-D__GCC_HAVE_DWARF2_CFI_ASM=1"); 7122 7123 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) { 7124 std::string Str = A->getAsString(Args); 7125 if (!TC.getTriple().isOSBinFormatELF()) 7126 D.Diag(diag::err_drv_unsupported_opt_for_target) 7127 << Str << TC.getTripleString(); 7128 CmdArgs.push_back(Args.MakeArgString(Str)); 7129 } 7130 7131 // Add the output path to the object file for CodeView debug infos. 7132 if (EmitCodeView && Output.isFilename()) 7133 addDebugObjectName(Args, CmdArgs, DebugCompilationDir, 7134 Output.getFilename()); 7135 7136 // Add the "-o out -x type src.c" flags last. This is done primarily to make 7137 // the -cc1 command easier to edit when reproducing compiler crashes. 7138 if (Output.getType() == types::TY_Dependencies) { 7139 // Handled with other dependency code. 7140 } else if (Output.isFilename()) { 7141 if (Output.getType() == clang::driver::types::TY_IFS_CPP || 7142 Output.getType() == clang::driver::types::TY_IFS) { 7143 SmallString<128> OutputFilename(Output.getFilename()); 7144 llvm::sys::path::replace_extension(OutputFilename, "ifs"); 7145 CmdArgs.push_back("-o"); 7146 CmdArgs.push_back(Args.MakeArgString(OutputFilename)); 7147 } else { 7148 CmdArgs.push_back("-o"); 7149 CmdArgs.push_back(Output.getFilename()); 7150 } 7151 } else { 7152 assert(Output.isNothing() && "Invalid output."); 7153 } 7154 7155 addDashXForInput(Args, Input, CmdArgs); 7156 7157 ArrayRef<InputInfo> FrontendInputs = Input; 7158 if (IsHeaderModulePrecompile) 7159 FrontendInputs = ModuleHeaderInputs; 7160 else if (IsExtractAPI) 7161 FrontendInputs = ExtractAPIInputs; 7162 else if (Input.isNothing()) 7163 FrontendInputs = {}; 7164 7165 for (const InputInfo &Input : FrontendInputs) { 7166 if (Input.isFilename()) 7167 CmdArgs.push_back(Input.getFilename()); 7168 else 7169 Input.getInputArg().renderAsInput(Args, CmdArgs); 7170 } 7171 7172 if (D.CC1Main && !D.CCGenDiagnostics) { 7173 // Invoke the CC1 directly in this process 7174 C.addCommand(std::make_unique<CC1Command>(JA, *this, 7175 ResponseFileSupport::AtFileUTF8(), 7176 Exec, CmdArgs, Inputs, Output)); 7177 } else { 7178 C.addCommand(std::make_unique<Command>(JA, *this, 7179 ResponseFileSupport::AtFileUTF8(), 7180 Exec, CmdArgs, Inputs, Output)); 7181 } 7182 7183 // Make the compile command echo its inputs for /showFilenames. 7184 if (Output.getType() == types::TY_Object && 7185 Args.hasFlag(options::OPT__SLASH_showFilenames, 7186 options::OPT__SLASH_showFilenames_, false)) { 7187 C.getJobs().getJobs().back()->PrintInputFilenames = true; 7188 } 7189 7190 if (Arg *A = Args.getLastArg(options::OPT_pg)) 7191 if (FPKeepKind == CodeGenOptions::FramePointerKind::None && 7192 !Args.hasArg(options::OPT_mfentry)) 7193 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer" 7194 << A->getAsString(Args); 7195 7196 // Claim some arguments which clang supports automatically. 7197 7198 // -fpch-preprocess is used with gcc to add a special marker in the output to 7199 // include the PCH file. 7200 Args.ClaimAllArgs(options::OPT_fpch_preprocess); 7201 7202 // Claim some arguments which clang doesn't support, but we don't 7203 // care to warn the user about. 7204 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group); 7205 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group); 7206 7207 // Disable warnings for clang -E -emit-llvm foo.c 7208 Args.ClaimAllArgs(options::OPT_emit_llvm); 7209 } 7210 7211 Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend) 7212 // CAUTION! The first constructor argument ("clang") is not arbitrary, 7213 // as it is for other tools. Some operations on a Tool actually test 7214 // whether that tool is Clang based on the Tool's Name as a string. 7215 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {} 7216 7217 Clang::~Clang() {} 7218 7219 /// Add options related to the Objective-C runtime/ABI. 7220 /// 7221 /// Returns true if the runtime is non-fragile. 7222 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args, 7223 const InputInfoList &inputs, 7224 ArgStringList &cmdArgs, 7225 RewriteKind rewriteKind) const { 7226 // Look for the controlling runtime option. 7227 Arg *runtimeArg = 7228 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime, 7229 options::OPT_fobjc_runtime_EQ); 7230 7231 // Just forward -fobjc-runtime= to the frontend. This supercedes 7232 // options about fragility. 7233 if (runtimeArg && 7234 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) { 7235 ObjCRuntime runtime; 7236 StringRef value = runtimeArg->getValue(); 7237 if (runtime.tryParse(value)) { 7238 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime) 7239 << value; 7240 } 7241 if ((runtime.getKind() == ObjCRuntime::GNUstep) && 7242 (runtime.getVersion() >= VersionTuple(2, 0))) 7243 if (!getToolChain().getTriple().isOSBinFormatELF() && 7244 !getToolChain().getTriple().isOSBinFormatCOFF()) { 7245 getToolChain().getDriver().Diag( 7246 diag::err_drv_gnustep_objc_runtime_incompatible_binary) 7247 << runtime.getVersion().getMajor(); 7248 } 7249 7250 runtimeArg->render(args, cmdArgs); 7251 return runtime; 7252 } 7253 7254 // Otherwise, we'll need the ABI "version". Version numbers are 7255 // slightly confusing for historical reasons: 7256 // 1 - Traditional "fragile" ABI 7257 // 2 - Non-fragile ABI, version 1 7258 // 3 - Non-fragile ABI, version 2 7259 unsigned objcABIVersion = 1; 7260 // If -fobjc-abi-version= is present, use that to set the version. 7261 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) { 7262 StringRef value = abiArg->getValue(); 7263 if (value == "1") 7264 objcABIVersion = 1; 7265 else if (value == "2") 7266 objcABIVersion = 2; 7267 else if (value == "3") 7268 objcABIVersion = 3; 7269 else 7270 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value; 7271 } else { 7272 // Otherwise, determine if we are using the non-fragile ABI. 7273 bool nonFragileABIIsDefault = 7274 (rewriteKind == RK_NonFragile || 7275 (rewriteKind == RK_None && 7276 getToolChain().IsObjCNonFragileABIDefault())); 7277 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi, 7278 options::OPT_fno_objc_nonfragile_abi, 7279 nonFragileABIIsDefault)) { 7280 // Determine the non-fragile ABI version to use. 7281 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO 7282 unsigned nonFragileABIVersion = 1; 7283 #else 7284 unsigned nonFragileABIVersion = 2; 7285 #endif 7286 7287 if (Arg *abiArg = 7288 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) { 7289 StringRef value = abiArg->getValue(); 7290 if (value == "1") 7291 nonFragileABIVersion = 1; 7292 else if (value == "2") 7293 nonFragileABIVersion = 2; 7294 else 7295 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) 7296 << value; 7297 } 7298 7299 objcABIVersion = 1 + nonFragileABIVersion; 7300 } else { 7301 objcABIVersion = 1; 7302 } 7303 } 7304 7305 // We don't actually care about the ABI version other than whether 7306 // it's non-fragile. 7307 bool isNonFragile = objcABIVersion != 1; 7308 7309 // If we have no runtime argument, ask the toolchain for its default runtime. 7310 // However, the rewriter only really supports the Mac runtime, so assume that. 7311 ObjCRuntime runtime; 7312 if (!runtimeArg) { 7313 switch (rewriteKind) { 7314 case RK_None: 7315 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile); 7316 break; 7317 case RK_Fragile: 7318 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple()); 7319 break; 7320 case RK_NonFragile: 7321 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple()); 7322 break; 7323 } 7324 7325 // -fnext-runtime 7326 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) { 7327 // On Darwin, make this use the default behavior for the toolchain. 7328 if (getToolChain().getTriple().isOSDarwin()) { 7329 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile); 7330 7331 // Otherwise, build for a generic macosx port. 7332 } else { 7333 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple()); 7334 } 7335 7336 // -fgnu-runtime 7337 } else { 7338 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime)); 7339 // Legacy behaviour is to target the gnustep runtime if we are in 7340 // non-fragile mode or the GCC runtime in fragile mode. 7341 if (isNonFragile) 7342 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0)); 7343 else 7344 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple()); 7345 } 7346 7347 if (llvm::any_of(inputs, [](const InputInfo &input) { 7348 return types::isObjC(input.getType()); 7349 })) 7350 cmdArgs.push_back( 7351 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString())); 7352 return runtime; 7353 } 7354 7355 static bool maybeConsumeDash(const std::string &EH, size_t &I) { 7356 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-'); 7357 I += HaveDash; 7358 return !HaveDash; 7359 } 7360 7361 namespace { 7362 struct EHFlags { 7363 bool Synch = false; 7364 bool Asynch = false; 7365 bool NoUnwindC = false; 7366 }; 7367 } // end anonymous namespace 7368 7369 /// /EH controls whether to run destructor cleanups when exceptions are 7370 /// thrown. There are three modifiers: 7371 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions. 7372 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions. 7373 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR. 7374 /// - c: Assume that extern "C" functions are implicitly nounwind. 7375 /// The default is /EHs-c-, meaning cleanups are disabled. 7376 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) { 7377 EHFlags EH; 7378 7379 std::vector<std::string> EHArgs = 7380 Args.getAllArgValues(options::OPT__SLASH_EH); 7381 for (auto EHVal : EHArgs) { 7382 for (size_t I = 0, E = EHVal.size(); I != E; ++I) { 7383 switch (EHVal[I]) { 7384 case 'a': 7385 EH.Asynch = maybeConsumeDash(EHVal, I); 7386 if (EH.Asynch) 7387 EH.Synch = false; 7388 continue; 7389 case 'c': 7390 EH.NoUnwindC = maybeConsumeDash(EHVal, I); 7391 continue; 7392 case 's': 7393 EH.Synch = maybeConsumeDash(EHVal, I); 7394 if (EH.Synch) 7395 EH.Asynch = false; 7396 continue; 7397 default: 7398 break; 7399 } 7400 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal; 7401 break; 7402 } 7403 } 7404 // The /GX, /GX- flags are only processed if there are not /EH flags. 7405 // The default is that /GX is not specified. 7406 if (EHArgs.empty() && 7407 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_, 7408 /*Default=*/false)) { 7409 EH.Synch = true; 7410 EH.NoUnwindC = true; 7411 } 7412 7413 return EH; 7414 } 7415 7416 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType, 7417 ArgStringList &CmdArgs, 7418 codegenoptions::DebugInfoKind *DebugInfoKind, 7419 bool *EmitCodeView) const { 7420 unsigned RTOptionID = options::OPT__SLASH_MT; 7421 bool isNVPTX = getToolChain().getTriple().isNVPTX(); 7422 7423 if (Args.hasArg(options::OPT__SLASH_LDd)) 7424 // The /LDd option implies /MTd. The dependent lib part can be overridden, 7425 // but defining _DEBUG is sticky. 7426 RTOptionID = options::OPT__SLASH_MTd; 7427 7428 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group)) 7429 RTOptionID = A->getOption().getID(); 7430 7431 StringRef FlagForCRT; 7432 switch (RTOptionID) { 7433 case options::OPT__SLASH_MD: 7434 if (Args.hasArg(options::OPT__SLASH_LDd)) 7435 CmdArgs.push_back("-D_DEBUG"); 7436 CmdArgs.push_back("-D_MT"); 7437 CmdArgs.push_back("-D_DLL"); 7438 FlagForCRT = "--dependent-lib=msvcrt"; 7439 break; 7440 case options::OPT__SLASH_MDd: 7441 CmdArgs.push_back("-D_DEBUG"); 7442 CmdArgs.push_back("-D_MT"); 7443 CmdArgs.push_back("-D_DLL"); 7444 FlagForCRT = "--dependent-lib=msvcrtd"; 7445 break; 7446 case options::OPT__SLASH_MT: 7447 if (Args.hasArg(options::OPT__SLASH_LDd)) 7448 CmdArgs.push_back("-D_DEBUG"); 7449 CmdArgs.push_back("-D_MT"); 7450 CmdArgs.push_back("-flto-visibility-public-std"); 7451 FlagForCRT = "--dependent-lib=libcmt"; 7452 break; 7453 case options::OPT__SLASH_MTd: 7454 CmdArgs.push_back("-D_DEBUG"); 7455 CmdArgs.push_back("-D_MT"); 7456 CmdArgs.push_back("-flto-visibility-public-std"); 7457 FlagForCRT = "--dependent-lib=libcmtd"; 7458 break; 7459 default: 7460 llvm_unreachable("Unexpected option ID."); 7461 } 7462 7463 if (Args.hasArg(options::OPT__SLASH_Zl)) { 7464 CmdArgs.push_back("-D_VC_NODEFAULTLIB"); 7465 } else { 7466 CmdArgs.push_back(FlagForCRT.data()); 7467 7468 // This provides POSIX compatibility (maps 'open' to '_open'), which most 7469 // users want. The /Za flag to cl.exe turns this off, but it's not 7470 // implemented in clang. 7471 CmdArgs.push_back("--dependent-lib=oldnames"); 7472 } 7473 7474 if (Arg *ShowIncludes = 7475 Args.getLastArg(options::OPT__SLASH_showIncludes, 7476 options::OPT__SLASH_showIncludes_user)) { 7477 CmdArgs.push_back("--show-includes"); 7478 if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes)) 7479 CmdArgs.push_back("-sys-header-deps"); 7480 } 7481 7482 // This controls whether or not we emit RTTI data for polymorphic types. 7483 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR, 7484 /*Default=*/false)) 7485 CmdArgs.push_back("-fno-rtti-data"); 7486 7487 // This controls whether or not we emit stack-protector instrumentation. 7488 // In MSVC, Buffer Security Check (/GS) is on by default. 7489 if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_, 7490 /*Default=*/true)) { 7491 CmdArgs.push_back("-stack-protector"); 7492 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong))); 7493 } 7494 7495 // Emit CodeView if -Z7 or -gline-tables-only are present. 7496 if (Arg *DebugInfoArg = Args.getLastArg(options::OPT__SLASH_Z7, 7497 options::OPT_gline_tables_only)) { 7498 *EmitCodeView = true; 7499 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7)) 7500 *DebugInfoKind = codegenoptions::DebugInfoConstructor; 7501 else 7502 *DebugInfoKind = codegenoptions::DebugLineTablesOnly; 7503 } else { 7504 *EmitCodeView = false; 7505 } 7506 7507 const Driver &D = getToolChain().getDriver(); 7508 7509 // This controls whether or not we perform JustMyCode instrumentation. 7510 if (Args.hasFlag(options::OPT__SLASH_JMC, options::OPT__SLASH_JMC_, 7511 /*Default=*/false)) { 7512 if (*EmitCodeView && *DebugInfoKind >= codegenoptions::DebugInfoConstructor) 7513 CmdArgs.push_back("-fjmc"); 7514 else 7515 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC" 7516 << "'/Zi', '/Z7'"; 7517 } 7518 7519 EHFlags EH = parseClangCLEHFlags(D, Args); 7520 if (!isNVPTX && (EH.Synch || EH.Asynch)) { 7521 if (types::isCXX(InputType)) 7522 CmdArgs.push_back("-fcxx-exceptions"); 7523 CmdArgs.push_back("-fexceptions"); 7524 } 7525 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC) 7526 CmdArgs.push_back("-fexternc-nounwind"); 7527 7528 // /EP should expand to -E -P. 7529 if (Args.hasArg(options::OPT__SLASH_EP)) { 7530 CmdArgs.push_back("-E"); 7531 CmdArgs.push_back("-P"); 7532 } 7533 7534 unsigned VolatileOptionID; 7535 if (getToolChain().getTriple().isX86()) 7536 VolatileOptionID = options::OPT__SLASH_volatile_ms; 7537 else 7538 VolatileOptionID = options::OPT__SLASH_volatile_iso; 7539 7540 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group)) 7541 VolatileOptionID = A->getOption().getID(); 7542 7543 if (VolatileOptionID == options::OPT__SLASH_volatile_ms) 7544 CmdArgs.push_back("-fms-volatile"); 7545 7546 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_, 7547 options::OPT__SLASH_Zc_dllexportInlines, 7548 false)) { 7549 CmdArgs.push_back("-fno-dllexport-inlines"); 7550 } 7551 7552 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg); 7553 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb); 7554 if (MostGeneralArg && BestCaseArg) 7555 D.Diag(clang::diag::err_drv_argument_not_allowed_with) 7556 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args); 7557 7558 if (MostGeneralArg) { 7559 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms); 7560 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm); 7561 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv); 7562 7563 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg; 7564 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg; 7565 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict) 7566 D.Diag(clang::diag::err_drv_argument_not_allowed_with) 7567 << FirstConflict->getAsString(Args) 7568 << SecondConflict->getAsString(Args); 7569 7570 if (SingleArg) 7571 CmdArgs.push_back("-fms-memptr-rep=single"); 7572 else if (MultipleArg) 7573 CmdArgs.push_back("-fms-memptr-rep=multiple"); 7574 else 7575 CmdArgs.push_back("-fms-memptr-rep=virtual"); 7576 } 7577 7578 // Parse the default calling convention options. 7579 if (Arg *CCArg = 7580 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr, 7581 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv, 7582 options::OPT__SLASH_Gregcall)) { 7583 unsigned DCCOptId = CCArg->getOption().getID(); 7584 const char *DCCFlag = nullptr; 7585 bool ArchSupported = !isNVPTX; 7586 llvm::Triple::ArchType Arch = getToolChain().getArch(); 7587 switch (DCCOptId) { 7588 case options::OPT__SLASH_Gd: 7589 DCCFlag = "-fdefault-calling-conv=cdecl"; 7590 break; 7591 case options::OPT__SLASH_Gr: 7592 ArchSupported = Arch == llvm::Triple::x86; 7593 DCCFlag = "-fdefault-calling-conv=fastcall"; 7594 break; 7595 case options::OPT__SLASH_Gz: 7596 ArchSupported = Arch == llvm::Triple::x86; 7597 DCCFlag = "-fdefault-calling-conv=stdcall"; 7598 break; 7599 case options::OPT__SLASH_Gv: 7600 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64; 7601 DCCFlag = "-fdefault-calling-conv=vectorcall"; 7602 break; 7603 case options::OPT__SLASH_Gregcall: 7604 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64; 7605 DCCFlag = "-fdefault-calling-conv=regcall"; 7606 break; 7607 } 7608 7609 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either. 7610 if (ArchSupported && DCCFlag) 7611 CmdArgs.push_back(DCCFlag); 7612 } 7613 7614 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ); 7615 7616 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) { 7617 CmdArgs.push_back("-fdiagnostics-format"); 7618 CmdArgs.push_back("msvc"); 7619 } 7620 7621 if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) { 7622 StringRef GuardArgs = A->getValue(); 7623 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and 7624 // "ehcont-". 7625 if (GuardArgs.equals_insensitive("cf")) { 7626 // Emit CFG instrumentation and the table of address-taken functions. 7627 CmdArgs.push_back("-cfguard"); 7628 } else if (GuardArgs.equals_insensitive("cf,nochecks")) { 7629 // Emit only the table of address-taken functions. 7630 CmdArgs.push_back("-cfguard-no-checks"); 7631 } else if (GuardArgs.equals_insensitive("ehcont")) { 7632 // Emit EH continuation table. 7633 CmdArgs.push_back("-ehcontguard"); 7634 } else if (GuardArgs.equals_insensitive("cf-") || 7635 GuardArgs.equals_insensitive("ehcont-")) { 7636 // Do nothing, but we might want to emit a security warning in future. 7637 } else { 7638 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs; 7639 } 7640 } 7641 } 7642 7643 const char *Clang::getBaseInputName(const ArgList &Args, 7644 const InputInfo &Input) { 7645 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput())); 7646 } 7647 7648 const char *Clang::getBaseInputStem(const ArgList &Args, 7649 const InputInfoList &Inputs) { 7650 const char *Str = getBaseInputName(Args, Inputs[0]); 7651 7652 if (const char *End = strrchr(Str, '.')) 7653 return Args.MakeArgString(std::string(Str, End)); 7654 7655 return Str; 7656 } 7657 7658 const char *Clang::getDependencyFileName(const ArgList &Args, 7659 const InputInfoList &Inputs) { 7660 // FIXME: Think about this more. 7661 7662 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) { 7663 SmallString<128> OutputFilename(OutputOpt->getValue()); 7664 llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d')); 7665 return Args.MakeArgString(OutputFilename); 7666 } 7667 7668 return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d"); 7669 } 7670 7671 // Begin ClangAs 7672 7673 void ClangAs::AddMIPSTargetArgs(const ArgList &Args, 7674 ArgStringList &CmdArgs) const { 7675 StringRef CPUName; 7676 StringRef ABIName; 7677 const llvm::Triple &Triple = getToolChain().getTriple(); 7678 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName); 7679 7680 CmdArgs.push_back("-target-abi"); 7681 CmdArgs.push_back(ABIName.data()); 7682 } 7683 7684 void ClangAs::AddX86TargetArgs(const ArgList &Args, 7685 ArgStringList &CmdArgs) const { 7686 addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs, 7687 /*IsLTO=*/false); 7688 7689 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) { 7690 StringRef Value = A->getValue(); 7691 if (Value == "intel" || Value == "att") { 7692 CmdArgs.push_back("-mllvm"); 7693 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value)); 7694 } else { 7695 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument) 7696 << A->getOption().getName() << Value; 7697 } 7698 } 7699 } 7700 7701 void ClangAs::AddRISCVTargetArgs(const ArgList &Args, 7702 ArgStringList &CmdArgs) const { 7703 const llvm::Triple &Triple = getToolChain().getTriple(); 7704 StringRef ABIName = riscv::getRISCVABI(Args, Triple); 7705 7706 CmdArgs.push_back("-target-abi"); 7707 CmdArgs.push_back(ABIName.data()); 7708 } 7709 7710 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA, 7711 const InputInfo &Output, const InputInfoList &Inputs, 7712 const ArgList &Args, 7713 const char *LinkingOutput) const { 7714 ArgStringList CmdArgs; 7715 7716 assert(Inputs.size() == 1 && "Unexpected number of inputs."); 7717 const InputInfo &Input = Inputs[0]; 7718 7719 const llvm::Triple &Triple = getToolChain().getEffectiveTriple(); 7720 const std::string &TripleStr = Triple.getTriple(); 7721 const auto &D = getToolChain().getDriver(); 7722 7723 // Don't warn about "clang -w -c foo.s" 7724 Args.ClaimAllArgs(options::OPT_w); 7725 // and "clang -emit-llvm -c foo.s" 7726 Args.ClaimAllArgs(options::OPT_emit_llvm); 7727 7728 claimNoWarnArgs(Args); 7729 7730 // Invoke ourselves in -cc1as mode. 7731 // 7732 // FIXME: Implement custom jobs for internal actions. 7733 CmdArgs.push_back("-cc1as"); 7734 7735 // Add the "effective" target triple. 7736 CmdArgs.push_back("-triple"); 7737 CmdArgs.push_back(Args.MakeArgString(TripleStr)); 7738 7739 // Set the output mode, we currently only expect to be used as a real 7740 // assembler. 7741 CmdArgs.push_back("-filetype"); 7742 CmdArgs.push_back("obj"); 7743 7744 // Set the main file name, so that debug info works even with 7745 // -save-temps or preprocessed assembly. 7746 CmdArgs.push_back("-main-file-name"); 7747 CmdArgs.push_back(Clang::getBaseInputName(Args, Input)); 7748 7749 // Add the target cpu 7750 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true); 7751 if (!CPU.empty()) { 7752 CmdArgs.push_back("-target-cpu"); 7753 CmdArgs.push_back(Args.MakeArgString(CPU)); 7754 } 7755 7756 // Add the target features 7757 getTargetFeatures(D, Triple, Args, CmdArgs, true); 7758 7759 // Ignore explicit -force_cpusubtype_ALL option. 7760 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL); 7761 7762 // Pass along any -I options so we get proper .include search paths. 7763 Args.AddAllArgs(CmdArgs, options::OPT_I_Group); 7764 7765 // Determine the original source input. 7766 auto FindSource = [](const Action *S) -> const Action * { 7767 while (S->getKind() != Action::InputClass) { 7768 assert(!S->getInputs().empty() && "unexpected root action!"); 7769 S = S->getInputs()[0]; 7770 } 7771 return S; 7772 }; 7773 const Action *SourceAction = FindSource(&JA); 7774 7775 // Forward -g and handle debug info related flags, assuming we are dealing 7776 // with an actual assembly file. 7777 bool WantDebug = false; 7778 Args.ClaimAllArgs(options::OPT_g_Group); 7779 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) 7780 WantDebug = !A->getOption().matches(options::OPT_g0) && 7781 !A->getOption().matches(options::OPT_ggdb0); 7782 7783 unsigned DwarfVersion = ParseDebugDefaultVersion(getToolChain(), Args); 7784 if (const Arg *GDwarfN = getDwarfNArg(Args)) 7785 DwarfVersion = DwarfVersionNum(GDwarfN->getSpelling()); 7786 7787 if (DwarfVersion == 0) 7788 DwarfVersion = getToolChain().GetDefaultDwarfVersion(); 7789 7790 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo; 7791 7792 // Add the -fdebug-compilation-dir flag if needed. 7793 const char *DebugCompilationDir = 7794 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS()); 7795 7796 if (SourceAction->getType() == types::TY_Asm || 7797 SourceAction->getType() == types::TY_PP_Asm) { 7798 // You might think that it would be ok to set DebugInfoKind outside of 7799 // the guard for source type, however there is a test which asserts 7800 // that some assembler invocation receives no -debug-info-kind, 7801 // and it's not clear whether that test is just overly restrictive. 7802 DebugInfoKind = (WantDebug ? codegenoptions::DebugInfoConstructor 7803 : codegenoptions::NoDebugInfo); 7804 7805 addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args, 7806 CmdArgs); 7807 7808 // Set the AT_producer to the clang version when using the integrated 7809 // assembler on assembly source files. 7810 CmdArgs.push_back("-dwarf-debug-producer"); 7811 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion())); 7812 7813 // And pass along -I options 7814 Args.AddAllArgs(CmdArgs, options::OPT_I); 7815 } 7816 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion, 7817 llvm::DebuggerKind::Default); 7818 renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion); 7819 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain()); 7820 7821 7822 // Handle -fPIC et al -- the relocation-model affects the assembler 7823 // for some targets. 7824 llvm::Reloc::Model RelocationModel; 7825 unsigned PICLevel; 7826 bool IsPIE; 7827 std::tie(RelocationModel, PICLevel, IsPIE) = 7828 ParsePICArgs(getToolChain(), Args); 7829 7830 const char *RMName = RelocationModelName(RelocationModel); 7831 if (RMName) { 7832 CmdArgs.push_back("-mrelocation-model"); 7833 CmdArgs.push_back(RMName); 7834 } 7835 7836 // Optionally embed the -cc1as level arguments into the debug info, for build 7837 // analysis. 7838 if (getToolChain().UseDwarfDebugFlags()) { 7839 ArgStringList OriginalArgs; 7840 for (const auto &Arg : Args) 7841 Arg->render(Args, OriginalArgs); 7842 7843 SmallString<256> Flags; 7844 const char *Exec = getToolChain().getDriver().getClangProgramPath(); 7845 EscapeSpacesAndBackslashes(Exec, Flags); 7846 for (const char *OriginalArg : OriginalArgs) { 7847 SmallString<128> EscapedArg; 7848 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg); 7849 Flags += " "; 7850 Flags += EscapedArg; 7851 } 7852 CmdArgs.push_back("-dwarf-debug-flags"); 7853 CmdArgs.push_back(Args.MakeArgString(Flags)); 7854 } 7855 7856 // FIXME: Add -static support, once we have it. 7857 7858 // Add target specific flags. 7859 switch (getToolChain().getArch()) { 7860 default: 7861 break; 7862 7863 case llvm::Triple::mips: 7864 case llvm::Triple::mipsel: 7865 case llvm::Triple::mips64: 7866 case llvm::Triple::mips64el: 7867 AddMIPSTargetArgs(Args, CmdArgs); 7868 break; 7869 7870 case llvm::Triple::x86: 7871 case llvm::Triple::x86_64: 7872 AddX86TargetArgs(Args, CmdArgs); 7873 break; 7874 7875 case llvm::Triple::arm: 7876 case llvm::Triple::armeb: 7877 case llvm::Triple::thumb: 7878 case llvm::Triple::thumbeb: 7879 // This isn't in AddARMTargetArgs because we want to do this for assembly 7880 // only, not C/C++. 7881 if (Args.hasFlag(options::OPT_mdefault_build_attributes, 7882 options::OPT_mno_default_build_attributes, true)) { 7883 CmdArgs.push_back("-mllvm"); 7884 CmdArgs.push_back("-arm-add-build-attributes"); 7885 } 7886 break; 7887 7888 case llvm::Triple::aarch64: 7889 case llvm::Triple::aarch64_32: 7890 case llvm::Triple::aarch64_be: 7891 if (Args.hasArg(options::OPT_mmark_bti_property)) { 7892 CmdArgs.push_back("-mllvm"); 7893 CmdArgs.push_back("-aarch64-mark-bti-property"); 7894 } 7895 break; 7896 7897 case llvm::Triple::riscv32: 7898 case llvm::Triple::riscv64: 7899 AddRISCVTargetArgs(Args, CmdArgs); 7900 break; 7901 } 7902 7903 // Consume all the warning flags. Usually this would be handled more 7904 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as 7905 // doesn't handle that so rather than warning about unused flags that are 7906 // actually used, we'll lie by omission instead. 7907 // FIXME: Stop lying and consume only the appropriate driver flags 7908 Args.ClaimAllArgs(options::OPT_W_Group); 7909 7910 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, 7911 getToolChain().getDriver()); 7912 7913 Args.AddAllArgs(CmdArgs, options::OPT_mllvm); 7914 7915 if (DebugInfoKind > codegenoptions::NoDebugInfo && Output.isFilename()) 7916 addDebugObjectName(Args, CmdArgs, DebugCompilationDir, 7917 Output.getFilename()); 7918 7919 // Fixup any previous commands that use -object-file-name because when we 7920 // generated them, the final .obj name wasn't yet known. 7921 for (Command &J : C.getJobs()) { 7922 if (SourceAction != FindSource(&J.getSource())) 7923 continue; 7924 auto &JArgs = J.getArguments(); 7925 for (unsigned I = 0; I < JArgs.size(); ++I) { 7926 if (StringRef(JArgs[I]).startswith("-object-file-name=") && 7927 Output.isFilename()) { 7928 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I); 7929 addDebugObjectName(Args, NewArgs, DebugCompilationDir, 7930 Output.getFilename()); 7931 NewArgs.append(JArgs.begin() + I + 1, JArgs.end()); 7932 J.replaceArguments(NewArgs); 7933 break; 7934 } 7935 } 7936 } 7937 7938 assert(Output.isFilename() && "Unexpected lipo output."); 7939 CmdArgs.push_back("-o"); 7940 CmdArgs.push_back(Output.getFilename()); 7941 7942 const llvm::Triple &T = getToolChain().getTriple(); 7943 Arg *A; 7944 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split && 7945 T.isOSBinFormatELF()) { 7946 CmdArgs.push_back("-split-dwarf-output"); 7947 CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output)); 7948 } 7949 7950 if (Triple.isAMDGPU()) 7951 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true); 7952 7953 assert(Input.isFilename() && "Invalid input."); 7954 CmdArgs.push_back(Input.getFilename()); 7955 7956 const char *Exec = getToolChain().getDriver().getClangProgramPath(); 7957 if (D.CC1Main && !D.CCGenDiagnostics) { 7958 // Invoke cc1as directly in this process. 7959 C.addCommand(std::make_unique<CC1Command>(JA, *this, 7960 ResponseFileSupport::AtFileUTF8(), 7961 Exec, CmdArgs, Inputs, Output)); 7962 } else { 7963 C.addCommand(std::make_unique<Command>(JA, *this, 7964 ResponseFileSupport::AtFileUTF8(), 7965 Exec, CmdArgs, Inputs, Output)); 7966 } 7967 } 7968 7969 // Begin OffloadBundler 7970 7971 void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA, 7972 const InputInfo &Output, 7973 const InputInfoList &Inputs, 7974 const llvm::opt::ArgList &TCArgs, 7975 const char *LinkingOutput) const { 7976 // The version with only one output is expected to refer to a bundling job. 7977 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!"); 7978 7979 // The bundling command looks like this: 7980 // clang-offload-bundler -type=bc 7981 // -targets=host-triple,openmp-triple1,openmp-triple2 7982 // -output=output_file 7983 // -input=unbundle_file_host 7984 // -input=unbundle_file_tgt1 7985 // -input=unbundle_file_tgt2 7986 7987 ArgStringList CmdArgs; 7988 7989 // Get the type. 7990 CmdArgs.push_back(TCArgs.MakeArgString( 7991 Twine("-type=") + types::getTypeTempSuffix(Output.getType()))); 7992 7993 assert(JA.getInputs().size() == Inputs.size() && 7994 "Not have inputs for all dependence actions??"); 7995 7996 // Get the targets. 7997 SmallString<128> Triples; 7998 Triples += "-targets="; 7999 for (unsigned I = 0; I < Inputs.size(); ++I) { 8000 if (I) 8001 Triples += ','; 8002 8003 // Find ToolChain for this input. 8004 Action::OffloadKind CurKind = Action::OFK_Host; 8005 const ToolChain *CurTC = &getToolChain(); 8006 const Action *CurDep = JA.getInputs()[I]; 8007 8008 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) { 8009 CurTC = nullptr; 8010 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) { 8011 assert(CurTC == nullptr && "Expected one dependence!"); 8012 CurKind = A->getOffloadingDeviceKind(); 8013 CurTC = TC; 8014 }); 8015 } 8016 Triples += Action::GetOffloadKindName(CurKind); 8017 Triples += '-'; 8018 Triples += CurTC->getTriple().normalize(); 8019 if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_Cuda) && 8020 !StringRef(CurDep->getOffloadingArch()).empty()) { 8021 Triples += '-'; 8022 Triples += CurDep->getOffloadingArch(); 8023 } 8024 8025 // TODO: Replace parsing of -march flag. Can be done by storing GPUArch 8026 // with each toolchain. 8027 StringRef GPUArchName; 8028 if (CurKind == Action::OFK_OpenMP) { 8029 // Extract GPUArch from -march argument in TC argument list. 8030 for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) { 8031 auto ArchStr = StringRef(TCArgs.getArgString(ArgIndex)); 8032 auto Arch = ArchStr.startswith_insensitive("-march="); 8033 if (Arch) { 8034 GPUArchName = ArchStr.substr(7); 8035 Triples += "-"; 8036 break; 8037 } 8038 } 8039 Triples += GPUArchName.str(); 8040 } 8041 } 8042 CmdArgs.push_back(TCArgs.MakeArgString(Triples)); 8043 8044 // Get bundled file command. 8045 CmdArgs.push_back( 8046 TCArgs.MakeArgString(Twine("-output=") + Output.getFilename())); 8047 8048 // Get unbundled files command. 8049 for (unsigned I = 0; I < Inputs.size(); ++I) { 8050 SmallString<128> UB; 8051 UB += "-input="; 8052 8053 // Find ToolChain for this input. 8054 const ToolChain *CurTC = &getToolChain(); 8055 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) { 8056 CurTC = nullptr; 8057 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) { 8058 assert(CurTC == nullptr && "Expected one dependence!"); 8059 CurTC = TC; 8060 }); 8061 UB += C.addTempFile( 8062 C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I]))); 8063 } else { 8064 UB += CurTC->getInputFilename(Inputs[I]); 8065 } 8066 CmdArgs.push_back(TCArgs.MakeArgString(UB)); 8067 } 8068 // All the inputs are encoded as commands. 8069 C.addCommand(std::make_unique<Command>( 8070 JA, *this, ResponseFileSupport::None(), 8071 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())), 8072 CmdArgs, None, Output)); 8073 } 8074 8075 void OffloadBundler::ConstructJobMultipleOutputs( 8076 Compilation &C, const JobAction &JA, const InputInfoList &Outputs, 8077 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, 8078 const char *LinkingOutput) const { 8079 // The version with multiple outputs is expected to refer to a unbundling job. 8080 auto &UA = cast<OffloadUnbundlingJobAction>(JA); 8081 8082 // The unbundling command looks like this: 8083 // clang-offload-bundler -type=bc 8084 // -targets=host-triple,openmp-triple1,openmp-triple2 8085 // -input=input_file 8086 // -output=unbundle_file_host 8087 // -output=unbundle_file_tgt1 8088 // -output=unbundle_file_tgt2 8089 // -unbundle 8090 8091 ArgStringList CmdArgs; 8092 8093 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!"); 8094 InputInfo Input = Inputs.front(); 8095 8096 // Get the type. 8097 CmdArgs.push_back(TCArgs.MakeArgString( 8098 Twine("-type=") + types::getTypeTempSuffix(Input.getType()))); 8099 8100 // Get the targets. 8101 SmallString<128> Triples; 8102 Triples += "-targets="; 8103 auto DepInfo = UA.getDependentActionsInfo(); 8104 for (unsigned I = 0; I < DepInfo.size(); ++I) { 8105 if (I) 8106 Triples += ','; 8107 8108 auto &Dep = DepInfo[I]; 8109 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind); 8110 Triples += '-'; 8111 Triples += Dep.DependentToolChain->getTriple().normalize(); 8112 if ((Dep.DependentOffloadKind == Action::OFK_HIP || 8113 Dep.DependentOffloadKind == Action::OFK_Cuda) && 8114 !Dep.DependentBoundArch.empty()) { 8115 Triples += '-'; 8116 Triples += Dep.DependentBoundArch; 8117 } 8118 // TODO: Replace parsing of -march flag. Can be done by storing GPUArch 8119 // with each toolchain. 8120 StringRef GPUArchName; 8121 if (Dep.DependentOffloadKind == Action::OFK_OpenMP) { 8122 // Extract GPUArch from -march argument in TC argument list. 8123 for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) { 8124 StringRef ArchStr = StringRef(TCArgs.getArgString(ArgIndex)); 8125 auto Arch = ArchStr.startswith_insensitive("-march="); 8126 if (Arch) { 8127 GPUArchName = ArchStr.substr(7); 8128 Triples += "-"; 8129 break; 8130 } 8131 } 8132 Triples += GPUArchName.str(); 8133 } 8134 } 8135 8136 CmdArgs.push_back(TCArgs.MakeArgString(Triples)); 8137 8138 // Get bundled file command. 8139 CmdArgs.push_back( 8140 TCArgs.MakeArgString(Twine("-input=") + Input.getFilename())); 8141 8142 // Get unbundled files command. 8143 for (unsigned I = 0; I < Outputs.size(); ++I) { 8144 SmallString<128> UB; 8145 UB += "-output="; 8146 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]); 8147 CmdArgs.push_back(TCArgs.MakeArgString(UB)); 8148 } 8149 CmdArgs.push_back("-unbundle"); 8150 CmdArgs.push_back("-allow-missing-bundles"); 8151 8152 // All the inputs are encoded as commands. 8153 C.addCommand(std::make_unique<Command>( 8154 JA, *this, ResponseFileSupport::None(), 8155 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())), 8156 CmdArgs, None, Outputs)); 8157 } 8158 8159 void OffloadWrapper::ConstructJob(Compilation &C, const JobAction &JA, 8160 const InputInfo &Output, 8161 const InputInfoList &Inputs, 8162 const ArgList &Args, 8163 const char *LinkingOutput) const { 8164 ArgStringList CmdArgs; 8165 8166 const llvm::Triple &Triple = getToolChain().getEffectiveTriple(); 8167 8168 // Add the "effective" target triple. 8169 CmdArgs.push_back("-target"); 8170 CmdArgs.push_back(Args.MakeArgString(Triple.getTriple())); 8171 8172 // Add the output file name. 8173 assert(Output.isFilename() && "Invalid output."); 8174 CmdArgs.push_back("-o"); 8175 CmdArgs.push_back(Output.getFilename()); 8176 8177 // Add inputs. 8178 for (const InputInfo &I : Inputs) { 8179 assert(I.isFilename() && "Invalid input."); 8180 CmdArgs.push_back(I.getFilename()); 8181 } 8182 8183 C.addCommand(std::make_unique<Command>( 8184 JA, *this, ResponseFileSupport::None(), 8185 Args.MakeArgString(getToolChain().GetProgramPath(getShortName())), 8186 CmdArgs, Inputs, Output)); 8187 } 8188 8189 void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA, 8190 const InputInfo &Output, 8191 const InputInfoList &Inputs, 8192 const ArgList &Args, 8193 const char *LinkingOutput) const { 8194 const Driver &D = getToolChain().getDriver(); 8195 const llvm::Triple TheTriple = getToolChain().getTriple(); 8196 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>(); 8197 ArgStringList CmdArgs; 8198 8199 // Pass the CUDA path to the linker wrapper tool. 8200 for (auto &I : llvm::make_range(OpenMPTCRange.first, OpenMPTCRange.second)) { 8201 const ToolChain *TC = I.second; 8202 if (TC->getTriple().isNVPTX()) { 8203 CudaInstallationDetector CudaInstallation(D, TheTriple, Args); 8204 if (CudaInstallation.isValid()) 8205 CmdArgs.push_back(Args.MakeArgString( 8206 "--cuda-path=" + CudaInstallation.getInstallPath())); 8207 break; 8208 } 8209 } 8210 8211 // Get the AMDGPU math libraries. 8212 // FIXME: This method is bad, remove once AMDGPU has a proper math library 8213 // (see AMDGCN::OpenMPLinker::constructLLVMLinkCommand). 8214 for (auto &I : llvm::make_range(OpenMPTCRange.first, OpenMPTCRange.second)) { 8215 const ToolChain *TC = I.second; 8216 8217 if (!TC->getTriple().isAMDGPU() || Args.hasArg(options::OPT_nogpulib)) 8218 continue; 8219 8220 const ArgList &TCArgs = C.getArgsForToolChain(TC, "", Action::OFK_OpenMP); 8221 StringRef Arch = TCArgs.getLastArgValue(options::OPT_march_EQ); 8222 const toolchains::ROCMToolChain RocmTC(TC->getDriver(), TC->getTriple(), 8223 TCArgs); 8224 8225 SmallVector<std::string, 12> BCLibs = 8226 RocmTC.getCommonDeviceLibNames(TCArgs, Arch.str()); 8227 8228 for (StringRef LibName : BCLibs) 8229 CmdArgs.push_back(Args.MakeArgString( 8230 "-target-library=" + Action::GetOffloadKindName(Action::OFK_OpenMP) + 8231 "-" + TC->getTripleString() + "-" + Arch + "=" + LibName)); 8232 } 8233 8234 if (D.isUsingLTO(/* IsOffload */ true)) { 8235 // Pass in target features for each toolchain. 8236 for (auto &I : 8237 llvm::make_range(OpenMPTCRange.first, OpenMPTCRange.second)) { 8238 const ToolChain *TC = I.second; 8239 const ArgList &TCArgs = C.getArgsForToolChain(TC, "", Action::OFK_OpenMP); 8240 ArgStringList FeatureArgs; 8241 TC->addClangTargetOptions(TCArgs, FeatureArgs, Action::OFK_OpenMP); 8242 auto FeatureIt = llvm::find(FeatureArgs, "-target-feature"); 8243 if (FeatureIt != FeatureArgs.end()) 8244 CmdArgs.push_back( 8245 Args.MakeArgString("-target-feature=" + TC->getTripleString() + 8246 "=" + *(FeatureIt + 1))); 8247 } 8248 8249 // Pass in the bitcode library to be linked during LTO. 8250 for (auto &I : 8251 llvm::make_range(OpenMPTCRange.first, OpenMPTCRange.second)) { 8252 const ToolChain *TC = I.second; 8253 if (!(TC->getTriple().isNVPTX() || TC->getTriple().isAMDGPU())) 8254 continue; 8255 8256 const Driver &TCDriver = TC->getDriver(); 8257 const ArgList &TCArgs = C.getArgsForToolChain(TC, "", Action::OFK_OpenMP); 8258 StringRef Arch = TCArgs.getLastArgValue(options::OPT_march_EQ); 8259 8260 ArgStringList BitcodeLibrary; 8261 addOpenMPDeviceRTL(TCDriver, TCArgs, BitcodeLibrary, Arch, 8262 TC->getTriple()); 8263 8264 if (!BitcodeLibrary.empty()) 8265 CmdArgs.push_back(Args.MakeArgString( 8266 "-target-library=" + 8267 Action::GetOffloadKindName(Action::OFK_OpenMP) + "-" + 8268 TC->getTripleString() + "-" + Arch + "=" + BitcodeLibrary.back())); 8269 } 8270 8271 // Pass in the optimization level to use for LTO. 8272 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) { 8273 StringRef OOpt; 8274 if (A->getOption().matches(options::OPT_O4) || 8275 A->getOption().matches(options::OPT_Ofast)) 8276 OOpt = "3"; 8277 else if (A->getOption().matches(options::OPT_O)) { 8278 OOpt = A->getValue(); 8279 if (OOpt == "g") 8280 OOpt = "1"; 8281 else if (OOpt == "s" || OOpt == "z") 8282 OOpt = "2"; 8283 } else if (A->getOption().matches(options::OPT_O0)) 8284 OOpt = "0"; 8285 if (!OOpt.empty()) 8286 CmdArgs.push_back(Args.MakeArgString(Twine("-opt-level=O") + OOpt)); 8287 } 8288 } 8289 8290 CmdArgs.push_back("-host-triple"); 8291 CmdArgs.push_back(Args.MakeArgString(TheTriple.getTriple())); 8292 if (Args.hasArg(options::OPT_v)) 8293 CmdArgs.push_back("-v"); 8294 8295 // Add debug information if present. 8296 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) { 8297 const Option &Opt = A->getOption(); 8298 if (Opt.matches(options::OPT_gN_Group)) { 8299 if (Opt.matches(options::OPT_gline_directives_only) || 8300 Opt.matches(options::OPT_gline_tables_only)) 8301 CmdArgs.push_back("-gline-directives-only"); 8302 } else 8303 CmdArgs.push_back("-g"); 8304 } 8305 8306 for (const auto &A : Args.getAllArgValues(options::OPT_Xcuda_ptxas)) 8307 CmdArgs.push_back(Args.MakeArgString("-ptxas-args=" + A)); 8308 8309 // Forward remarks passes to the LLVM backend in the wrapper. 8310 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ)) 8311 CmdArgs.push_back( 8312 Args.MakeArgString(Twine("-pass-remarks=") + A->getValue())); 8313 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ)) 8314 CmdArgs.push_back( 8315 Args.MakeArgString(Twine("-pass-remarks-missed=") + A->getValue())); 8316 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ)) 8317 CmdArgs.push_back( 8318 Args.MakeArgString(Twine("-pass-remarks-analysis=") + A->getValue())); 8319 if (Args.getLastArg(options::OPT_save_temps_EQ)) 8320 CmdArgs.push_back("-save-temps"); 8321 8322 // Construct the link job so we can wrap around it. 8323 Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput); 8324 const auto &LinkCommand = C.getJobs().getJobs().back(); 8325 8326 // Add the linker arguments to be forwarded by the wrapper. 8327 CmdArgs.push_back("-linker-path"); 8328 CmdArgs.push_back(LinkCommand->getExecutable()); 8329 CmdArgs.push_back("--"); 8330 for (const char *LinkArg : LinkCommand->getArguments()) 8331 CmdArgs.push_back(LinkArg); 8332 8333 const char *Exec = 8334 Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper")); 8335 8336 // Replace the executable and arguments of the link job with the 8337 // wrapper. 8338 LinkCommand->replaceExecutable(Exec); 8339 LinkCommand->replaceArguments(CmdArgs); 8340 } 8341