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