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