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