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