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