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