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