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