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