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