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 ToolChain &TC, const ArgList &Args, 2988 ArgStringList &CmdArgs, bool KernelOrKext) { 2989 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple(); 2990 2991 // NVPTX doesn't support stack protectors; from the compiler's perspective, it 2992 // doesn't even have a stack! 2993 if (EffectiveTriple.isNVPTX()) 2994 return; 2995 2996 // -stack-protector=0 is default. 2997 unsigned StackProtectorLevel = 0; 2998 unsigned DefaultStackProtectorLevel = 2999 TC.GetDefaultStackProtectorLevel(KernelOrKext); 3000 3001 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector, 3002 options::OPT_fstack_protector_all, 3003 options::OPT_fstack_protector_strong, 3004 options::OPT_fstack_protector)) { 3005 if (A->getOption().matches(options::OPT_fstack_protector)) 3006 StackProtectorLevel = 3007 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel); 3008 else if (A->getOption().matches(options::OPT_fstack_protector_strong)) 3009 StackProtectorLevel = LangOptions::SSPStrong; 3010 else if (A->getOption().matches(options::OPT_fstack_protector_all)) 3011 StackProtectorLevel = LangOptions::SSPReq; 3012 } else { 3013 StackProtectorLevel = DefaultStackProtectorLevel; 3014 } 3015 3016 if (StackProtectorLevel) { 3017 CmdArgs.push_back("-stack-protector"); 3018 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel))); 3019 } 3020 3021 // --param ssp-buffer-size= 3022 for (const Arg *A : Args.filtered(options::OPT__param)) { 3023 StringRef Str(A->getValue()); 3024 if (Str.startswith("ssp-buffer-size=")) { 3025 if (StackProtectorLevel) { 3026 CmdArgs.push_back("-stack-protector-buffer-size"); 3027 // FIXME: Verify the argument is a valid integer. 3028 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16))); 3029 } 3030 A->claim(); 3031 } 3032 } 3033 } 3034 3035 static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args, 3036 ArgStringList &CmdArgs) { 3037 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple(); 3038 3039 if (!EffectiveTriple.isOSLinux()) 3040 return; 3041 3042 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() && 3043 !EffectiveTriple.isPPC64()) 3044 return; 3045 3046 if (Args.hasFlag(options::OPT_fstack_clash_protection, 3047 options::OPT_fno_stack_clash_protection, false)) 3048 CmdArgs.push_back("-fstack-clash-protection"); 3049 } 3050 3051 static void RenderTrivialAutoVarInitOptions(const Driver &D, 3052 const ToolChain &TC, 3053 const ArgList &Args, 3054 ArgStringList &CmdArgs) { 3055 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit(); 3056 StringRef TrivialAutoVarInit = ""; 3057 3058 for (const Arg *A : Args) { 3059 switch (A->getOption().getID()) { 3060 default: 3061 continue; 3062 case options::OPT_ftrivial_auto_var_init: { 3063 A->claim(); 3064 StringRef Val = A->getValue(); 3065 if (Val == "uninitialized" || Val == "zero" || Val == "pattern") 3066 TrivialAutoVarInit = Val; 3067 else 3068 D.Diag(diag::err_drv_unsupported_option_argument) 3069 << A->getOption().getName() << Val; 3070 break; 3071 } 3072 } 3073 } 3074 3075 if (TrivialAutoVarInit.empty()) 3076 switch (DefaultTrivialAutoVarInit) { 3077 case LangOptions::TrivialAutoVarInitKind::Uninitialized: 3078 break; 3079 case LangOptions::TrivialAutoVarInitKind::Pattern: 3080 TrivialAutoVarInit = "pattern"; 3081 break; 3082 case LangOptions::TrivialAutoVarInitKind::Zero: 3083 TrivialAutoVarInit = "zero"; 3084 break; 3085 } 3086 3087 if (!TrivialAutoVarInit.empty()) { 3088 if (TrivialAutoVarInit == "zero" && !Args.hasArg(options::OPT_enable_trivial_var_init_zero)) 3089 D.Diag(diag::err_drv_trivial_auto_var_init_zero_disabled); 3090 CmdArgs.push_back( 3091 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit)); 3092 } 3093 3094 if (Arg *A = 3095 Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) { 3096 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) || 3097 StringRef( 3098 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) == 3099 "uninitialized") 3100 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency); 3101 A->claim(); 3102 StringRef Val = A->getValue(); 3103 if (std::stoi(Val.str()) <= 0) 3104 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value); 3105 CmdArgs.push_back( 3106 Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val)); 3107 } 3108 } 3109 3110 static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) { 3111 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag 3112 // for denormal flushing handling based on the target. 3113 const unsigned ForwardedArguments[] = { 3114 options::OPT_cl_opt_disable, 3115 options::OPT_cl_strict_aliasing, 3116 options::OPT_cl_single_precision_constant, 3117 options::OPT_cl_finite_math_only, 3118 options::OPT_cl_kernel_arg_info, 3119 options::OPT_cl_unsafe_math_optimizations, 3120 options::OPT_cl_fast_relaxed_math, 3121 options::OPT_cl_mad_enable, 3122 options::OPT_cl_no_signed_zeros, 3123 options::OPT_cl_fp32_correctly_rounded_divide_sqrt, 3124 options::OPT_cl_uniform_work_group_size 3125 }; 3126 3127 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) { 3128 std::string CLStdStr = std::string("-cl-std=") + A->getValue(); 3129 CmdArgs.push_back(Args.MakeArgString(CLStdStr)); 3130 } 3131 3132 for (const auto &Arg : ForwardedArguments) 3133 if (const auto *A = Args.getLastArg(Arg)) 3134 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName())); 3135 } 3136 3137 static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args, 3138 ArgStringList &CmdArgs) { 3139 bool ARCMTEnabled = false; 3140 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) { 3141 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check, 3142 options::OPT_ccc_arcmt_modify, 3143 options::OPT_ccc_arcmt_migrate)) { 3144 ARCMTEnabled = true; 3145 switch (A->getOption().getID()) { 3146 default: llvm_unreachable("missed a case"); 3147 case options::OPT_ccc_arcmt_check: 3148 CmdArgs.push_back("-arcmt-check"); 3149 break; 3150 case options::OPT_ccc_arcmt_modify: 3151 CmdArgs.push_back("-arcmt-modify"); 3152 break; 3153 case options::OPT_ccc_arcmt_migrate: 3154 CmdArgs.push_back("-arcmt-migrate"); 3155 CmdArgs.push_back("-mt-migrate-directory"); 3156 CmdArgs.push_back(A->getValue()); 3157 3158 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output); 3159 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors); 3160 break; 3161 } 3162 } 3163 } else { 3164 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check); 3165 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify); 3166 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate); 3167 } 3168 3169 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) { 3170 if (ARCMTEnabled) 3171 D.Diag(diag::err_drv_argument_not_allowed_with) 3172 << A->getAsString(Args) << "-ccc-arcmt-migrate"; 3173 3174 CmdArgs.push_back("-mt-migrate-directory"); 3175 CmdArgs.push_back(A->getValue()); 3176 3177 if (!Args.hasArg(options::OPT_objcmt_migrate_literals, 3178 options::OPT_objcmt_migrate_subscripting, 3179 options::OPT_objcmt_migrate_property)) { 3180 // None specified, means enable them all. 3181 CmdArgs.push_back("-objcmt-migrate-literals"); 3182 CmdArgs.push_back("-objcmt-migrate-subscripting"); 3183 CmdArgs.push_back("-objcmt-migrate-property"); 3184 } else { 3185 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals); 3186 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting); 3187 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property); 3188 } 3189 } else { 3190 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals); 3191 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting); 3192 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property); 3193 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all); 3194 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property); 3195 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property); 3196 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax); 3197 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation); 3198 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype); 3199 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros); 3200 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance); 3201 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property); 3202 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property); 3203 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly); 3204 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init); 3205 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path); 3206 } 3207 } 3208 3209 static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T, 3210 const ArgList &Args, ArgStringList &CmdArgs) { 3211 // -fbuiltin is default unless -mkernel is used. 3212 bool UseBuiltins = 3213 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin, 3214 !Args.hasArg(options::OPT_mkernel)); 3215 if (!UseBuiltins) 3216 CmdArgs.push_back("-fno-builtin"); 3217 3218 // -ffreestanding implies -fno-builtin. 3219 if (Args.hasArg(options::OPT_ffreestanding)) 3220 UseBuiltins = false; 3221 3222 // Process the -fno-builtin-* options. 3223 for (const auto &Arg : Args) { 3224 const Option &O = Arg->getOption(); 3225 if (!O.matches(options::OPT_fno_builtin_)) 3226 continue; 3227 3228 Arg->claim(); 3229 3230 // If -fno-builtin is specified, then there's no need to pass the option to 3231 // the frontend. 3232 if (!UseBuiltins) 3233 continue; 3234 3235 StringRef FuncName = Arg->getValue(); 3236 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName)); 3237 } 3238 3239 // le32-specific flags: 3240 // -fno-math-builtin: clang should not convert math builtins to intrinsics 3241 // by default. 3242 if (TC.getArch() == llvm::Triple::le32) 3243 CmdArgs.push_back("-fno-math-builtin"); 3244 } 3245 3246 bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) { 3247 if (llvm::sys::path::cache_directory(Result)) { 3248 llvm::sys::path::append(Result, "clang"); 3249 llvm::sys::path::append(Result, "ModuleCache"); 3250 return true; 3251 } 3252 return false; 3253 } 3254 3255 static void RenderModulesOptions(Compilation &C, const Driver &D, 3256 const ArgList &Args, const InputInfo &Input, 3257 const InputInfo &Output, 3258 ArgStringList &CmdArgs, bool &HaveModules) { 3259 // -fmodules enables the use of precompiled modules (off by default). 3260 // Users can pass -fno-cxx-modules to turn off modules support for 3261 // C++/Objective-C++ programs. 3262 bool HaveClangModules = false; 3263 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) { 3264 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules, 3265 options::OPT_fno_cxx_modules, true); 3266 if (AllowedInCXX || !types::isCXX(Input.getType())) { 3267 CmdArgs.push_back("-fmodules"); 3268 HaveClangModules = true; 3269 } 3270 } 3271 3272 HaveModules |= HaveClangModules; 3273 if (Args.hasArg(options::OPT_fmodules_ts)) { 3274 CmdArgs.push_back("-fmodules-ts"); 3275 HaveModules = true; 3276 } 3277 3278 // -fmodule-maps enables implicit reading of module map files. By default, 3279 // this is enabled if we are using Clang's flavor of precompiled modules. 3280 if (Args.hasFlag(options::OPT_fimplicit_module_maps, 3281 options::OPT_fno_implicit_module_maps, HaveClangModules)) 3282 CmdArgs.push_back("-fimplicit-module-maps"); 3283 3284 // -fmodules-decluse checks that modules used are declared so (off by default) 3285 if (Args.hasFlag(options::OPT_fmodules_decluse, 3286 options::OPT_fno_modules_decluse, false)) 3287 CmdArgs.push_back("-fmodules-decluse"); 3288 3289 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that 3290 // all #included headers are part of modules. 3291 if (Args.hasFlag(options::OPT_fmodules_strict_decluse, 3292 options::OPT_fno_modules_strict_decluse, false)) 3293 CmdArgs.push_back("-fmodules-strict-decluse"); 3294 3295 // -fno-implicit-modules turns off implicitly compiling modules on demand. 3296 bool ImplicitModules = false; 3297 if (!Args.hasFlag(options::OPT_fimplicit_modules, 3298 options::OPT_fno_implicit_modules, HaveClangModules)) { 3299 if (HaveModules) 3300 CmdArgs.push_back("-fno-implicit-modules"); 3301 } else if (HaveModules) { 3302 ImplicitModules = true; 3303 // -fmodule-cache-path specifies where our implicitly-built module files 3304 // should be written. 3305 SmallString<128> Path; 3306 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path)) 3307 Path = A->getValue(); 3308 3309 bool HasPath = true; 3310 if (C.isForDiagnostics()) { 3311 // When generating crash reports, we want to emit the modules along with 3312 // the reproduction sources, so we ignore any provided module path. 3313 Path = Output.getFilename(); 3314 llvm::sys::path::replace_extension(Path, ".cache"); 3315 llvm::sys::path::append(Path, "modules"); 3316 } else if (Path.empty()) { 3317 // No module path was provided: use the default. 3318 HasPath = Driver::getDefaultModuleCachePath(Path); 3319 } 3320 3321 // `HasPath` will only be false if getDefaultModuleCachePath() fails. 3322 // That being said, that failure is unlikely and not caching is harmless. 3323 if (HasPath) { 3324 const char Arg[] = "-fmodules-cache-path="; 3325 Path.insert(Path.begin(), Arg, Arg + strlen(Arg)); 3326 CmdArgs.push_back(Args.MakeArgString(Path)); 3327 } 3328 } 3329 3330 if (HaveModules) { 3331 // -fprebuilt-module-path specifies where to load the prebuilt module files. 3332 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) { 3333 CmdArgs.push_back(Args.MakeArgString( 3334 std::string("-fprebuilt-module-path=") + A->getValue())); 3335 A->claim(); 3336 } 3337 if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content, 3338 options::OPT_fno_modules_validate_input_files_content, 3339 false)) 3340 CmdArgs.push_back("-fvalidate-ast-input-files-content"); 3341 } 3342 3343 // -fmodule-name specifies the module that is currently being built (or 3344 // used for header checking by -fmodule-maps). 3345 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ); 3346 3347 // -fmodule-map-file can be used to specify files containing module 3348 // definitions. 3349 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file); 3350 3351 // -fbuiltin-module-map can be used to load the clang 3352 // builtin headers modulemap file. 3353 if (Args.hasArg(options::OPT_fbuiltin_module_map)) { 3354 SmallString<128> BuiltinModuleMap(D.ResourceDir); 3355 llvm::sys::path::append(BuiltinModuleMap, "include"); 3356 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap"); 3357 if (llvm::sys::fs::exists(BuiltinModuleMap)) 3358 CmdArgs.push_back( 3359 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap)); 3360 } 3361 3362 // The -fmodule-file=<name>=<file> form specifies the mapping of module 3363 // names to precompiled module files (the module is loaded only if used). 3364 // The -fmodule-file=<file> form can be used to unconditionally load 3365 // precompiled module files (whether used or not). 3366 if (HaveModules) 3367 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file); 3368 else 3369 Args.ClaimAllArgs(options::OPT_fmodule_file); 3370 3371 // When building modules and generating crashdumps, we need to dump a module 3372 // dependency VFS alongside the output. 3373 if (HaveClangModules && C.isForDiagnostics()) { 3374 SmallString<128> VFSDir(Output.getFilename()); 3375 llvm::sys::path::replace_extension(VFSDir, ".cache"); 3376 // Add the cache directory as a temp so the crash diagnostics pick it up. 3377 C.addTempFile(Args.MakeArgString(VFSDir)); 3378 3379 llvm::sys::path::append(VFSDir, "vfs"); 3380 CmdArgs.push_back("-module-dependency-dir"); 3381 CmdArgs.push_back(Args.MakeArgString(VFSDir)); 3382 } 3383 3384 if (HaveClangModules) 3385 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path); 3386 3387 // Pass through all -fmodules-ignore-macro arguments. 3388 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro); 3389 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval); 3390 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after); 3391 3392 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp); 3393 3394 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) { 3395 if (Args.hasArg(options::OPT_fbuild_session_timestamp)) 3396 D.Diag(diag::err_drv_argument_not_allowed_with) 3397 << A->getAsString(Args) << "-fbuild-session-timestamp"; 3398 3399 llvm::sys::fs::file_status Status; 3400 if (llvm::sys::fs::status(A->getValue(), Status)) 3401 D.Diag(diag::err_drv_no_such_file) << A->getValue(); 3402 CmdArgs.push_back( 3403 Args.MakeArgString("-fbuild-session-timestamp=" + 3404 Twine((uint64_t)Status.getLastModificationTime() 3405 .time_since_epoch() 3406 .count()))); 3407 } 3408 3409 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) { 3410 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp, 3411 options::OPT_fbuild_session_file)) 3412 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp); 3413 3414 Args.AddLastArg(CmdArgs, 3415 options::OPT_fmodules_validate_once_per_build_session); 3416 } 3417 3418 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers, 3419 options::OPT_fno_modules_validate_system_headers, 3420 ImplicitModules)) 3421 CmdArgs.push_back("-fmodules-validate-system-headers"); 3422 3423 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation); 3424 } 3425 3426 static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T, 3427 ArgStringList &CmdArgs) { 3428 // -fsigned-char is default. 3429 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char, 3430 options::OPT_fno_signed_char, 3431 options::OPT_funsigned_char, 3432 options::OPT_fno_unsigned_char)) { 3433 if (A->getOption().matches(options::OPT_funsigned_char) || 3434 A->getOption().matches(options::OPT_fno_signed_char)) { 3435 CmdArgs.push_back("-fno-signed-char"); 3436 } 3437 } else if (!isSignedCharDefault(T)) { 3438 CmdArgs.push_back("-fno-signed-char"); 3439 } 3440 3441 // The default depends on the language standard. 3442 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t); 3443 3444 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar, 3445 options::OPT_fno_short_wchar)) { 3446 if (A->getOption().matches(options::OPT_fshort_wchar)) { 3447 CmdArgs.push_back("-fwchar-type=short"); 3448 CmdArgs.push_back("-fno-signed-wchar"); 3449 } else { 3450 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64(); 3451 CmdArgs.push_back("-fwchar-type=int"); 3452 if (T.isOSzOS() || 3453 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD()))) 3454 CmdArgs.push_back("-fno-signed-wchar"); 3455 else 3456 CmdArgs.push_back("-fsigned-wchar"); 3457 } 3458 } 3459 } 3460 3461 static void RenderObjCOptions(const ToolChain &TC, const Driver &D, 3462 const llvm::Triple &T, const ArgList &Args, 3463 ObjCRuntime &Runtime, bool InferCovariantReturns, 3464 const InputInfo &Input, ArgStringList &CmdArgs) { 3465 const llvm::Triple::ArchType Arch = TC.getArch(); 3466 3467 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy 3468 // is the default. Except for deployment target of 10.5, next runtime is 3469 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently. 3470 if (Runtime.isNonFragile()) { 3471 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch, 3472 options::OPT_fno_objc_legacy_dispatch, 3473 Runtime.isLegacyDispatchDefaultForArch(Arch))) { 3474 if (TC.UseObjCMixedDispatch()) 3475 CmdArgs.push_back("-fobjc-dispatch-method=mixed"); 3476 else 3477 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy"); 3478 } 3479 } 3480 3481 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option 3482 // to do Array/Dictionary subscripting by default. 3483 if (Arch == llvm::Triple::x86 && T.isMacOSX() && 3484 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily()) 3485 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime"); 3486 3487 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc. 3488 // NOTE: This logic is duplicated in ToolChains.cpp. 3489 if (isObjCAutoRefCount(Args)) { 3490 TC.CheckObjCARC(); 3491 3492 CmdArgs.push_back("-fobjc-arc"); 3493 3494 // FIXME: It seems like this entire block, and several around it should be 3495 // wrapped in isObjC, but for now we just use it here as this is where it 3496 // was being used previously. 3497 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) { 3498 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) 3499 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++"); 3500 else 3501 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++"); 3502 } 3503 3504 // Allow the user to enable full exceptions code emission. 3505 // We default off for Objective-C, on for Objective-C++. 3506 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions, 3507 options::OPT_fno_objc_arc_exceptions, 3508 /*Default=*/types::isCXX(Input.getType()))) 3509 CmdArgs.push_back("-fobjc-arc-exceptions"); 3510 } 3511 3512 // Silence warning for full exception code emission options when explicitly 3513 // set to use no ARC. 3514 if (Args.hasArg(options::OPT_fno_objc_arc)) { 3515 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions); 3516 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions); 3517 } 3518 3519 // Allow the user to control whether messages can be converted to runtime 3520 // functions. 3521 if (types::isObjC(Input.getType())) { 3522 auto *Arg = Args.getLastArg( 3523 options::OPT_fobjc_convert_messages_to_runtime_calls, 3524 options::OPT_fno_objc_convert_messages_to_runtime_calls); 3525 if (Arg && 3526 Arg->getOption().matches( 3527 options::OPT_fno_objc_convert_messages_to_runtime_calls)) 3528 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls"); 3529 } 3530 3531 // -fobjc-infer-related-result-type is the default, except in the Objective-C 3532 // rewriter. 3533 if (InferCovariantReturns) 3534 CmdArgs.push_back("-fno-objc-infer-related-result-type"); 3535 3536 // Pass down -fobjc-weak or -fno-objc-weak if present. 3537 if (types::isObjC(Input.getType())) { 3538 auto WeakArg = 3539 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak); 3540 if (!WeakArg) { 3541 // nothing to do 3542 } else if (!Runtime.allowsWeak()) { 3543 if (WeakArg->getOption().matches(options::OPT_fobjc_weak)) 3544 D.Diag(diag::err_objc_weak_unsupported); 3545 } else { 3546 WeakArg->render(Args, CmdArgs); 3547 } 3548 } 3549 } 3550 3551 static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args, 3552 ArgStringList &CmdArgs) { 3553 bool CaretDefault = true; 3554 bool ColumnDefault = true; 3555 3556 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic, 3557 options::OPT__SLASH_diagnostics_column, 3558 options::OPT__SLASH_diagnostics_caret)) { 3559 switch (A->getOption().getID()) { 3560 case options::OPT__SLASH_diagnostics_caret: 3561 CaretDefault = true; 3562 ColumnDefault = true; 3563 break; 3564 case options::OPT__SLASH_diagnostics_column: 3565 CaretDefault = false; 3566 ColumnDefault = true; 3567 break; 3568 case options::OPT__SLASH_diagnostics_classic: 3569 CaretDefault = false; 3570 ColumnDefault = false; 3571 break; 3572 } 3573 } 3574 3575 // -fcaret-diagnostics is default. 3576 if (!Args.hasFlag(options::OPT_fcaret_diagnostics, 3577 options::OPT_fno_caret_diagnostics, CaretDefault)) 3578 CmdArgs.push_back("-fno-caret-diagnostics"); 3579 3580 // -fdiagnostics-fixit-info is default, only pass non-default. 3581 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info, 3582 options::OPT_fno_diagnostics_fixit_info)) 3583 CmdArgs.push_back("-fno-diagnostics-fixit-info"); 3584 3585 // Enable -fdiagnostics-show-option by default. 3586 if (!Args.hasFlag(options::OPT_fdiagnostics_show_option, 3587 options::OPT_fno_diagnostics_show_option, true)) 3588 CmdArgs.push_back("-fno-diagnostics-show-option"); 3589 3590 if (const Arg *A = 3591 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) { 3592 CmdArgs.push_back("-fdiagnostics-show-category"); 3593 CmdArgs.push_back(A->getValue()); 3594 } 3595 3596 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness, 3597 options::OPT_fno_diagnostics_show_hotness, false)) 3598 CmdArgs.push_back("-fdiagnostics-show-hotness"); 3599 3600 if (const Arg *A = 3601 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) { 3602 std::string Opt = 3603 std::string("-fdiagnostics-hotness-threshold=") + A->getValue(); 3604 CmdArgs.push_back(Args.MakeArgString(Opt)); 3605 } 3606 3607 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) { 3608 CmdArgs.push_back("-fdiagnostics-format"); 3609 CmdArgs.push_back(A->getValue()); 3610 } 3611 3612 if (const Arg *A = Args.getLastArg( 3613 options::OPT_fdiagnostics_show_note_include_stack, 3614 options::OPT_fno_diagnostics_show_note_include_stack)) { 3615 const Option &O = A->getOption(); 3616 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack)) 3617 CmdArgs.push_back("-fdiagnostics-show-note-include-stack"); 3618 else 3619 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack"); 3620 } 3621 3622 // Color diagnostics are parsed by the driver directly from argv and later 3623 // re-parsed to construct this job; claim any possible color diagnostic here 3624 // to avoid warn_drv_unused_argument and diagnose bad 3625 // OPT_fdiagnostics_color_EQ values. 3626 for (const Arg *A : Args) { 3627 const Option &O = A->getOption(); 3628 if (!O.matches(options::OPT_fcolor_diagnostics) && 3629 !O.matches(options::OPT_fdiagnostics_color) && 3630 !O.matches(options::OPT_fno_color_diagnostics) && 3631 !O.matches(options::OPT_fno_diagnostics_color) && 3632 !O.matches(options::OPT_fdiagnostics_color_EQ)) 3633 continue; 3634 3635 if (O.matches(options::OPT_fdiagnostics_color_EQ)) { 3636 StringRef Value(A->getValue()); 3637 if (Value != "always" && Value != "never" && Value != "auto") 3638 D.Diag(diag::err_drv_clang_unsupported) 3639 << ("-fdiagnostics-color=" + Value).str(); 3640 } 3641 A->claim(); 3642 } 3643 3644 if (D.getDiags().getDiagnosticOptions().ShowColors) 3645 CmdArgs.push_back("-fcolor-diagnostics"); 3646 3647 if (Args.hasArg(options::OPT_fansi_escape_codes)) 3648 CmdArgs.push_back("-fansi-escape-codes"); 3649 3650 if (!Args.hasFlag(options::OPT_fshow_source_location, 3651 options::OPT_fno_show_source_location)) 3652 CmdArgs.push_back("-fno-show-source-location"); 3653 3654 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths)) 3655 CmdArgs.push_back("-fdiagnostics-absolute-paths"); 3656 3657 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column, 3658 ColumnDefault)) 3659 CmdArgs.push_back("-fno-show-column"); 3660 3661 if (!Args.hasFlag(options::OPT_fspell_checking, 3662 options::OPT_fno_spell_checking)) 3663 CmdArgs.push_back("-fno-spell-checking"); 3664 } 3665 3666 enum class DwarfFissionKind { None, Split, Single }; 3667 3668 static DwarfFissionKind getDebugFissionKind(const Driver &D, 3669 const ArgList &Args, Arg *&Arg) { 3670 Arg = 3671 Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ); 3672 if (!Arg) 3673 return DwarfFissionKind::None; 3674 3675 if (Arg->getOption().matches(options::OPT_gsplit_dwarf)) 3676 return DwarfFissionKind::Split; 3677 3678 StringRef Value = Arg->getValue(); 3679 if (Value == "split") 3680 return DwarfFissionKind::Split; 3681 if (Value == "single") 3682 return DwarfFissionKind::Single; 3683 3684 D.Diag(diag::err_drv_unsupported_option_argument) 3685 << Arg->getOption().getName() << Arg->getValue(); 3686 return DwarfFissionKind::None; 3687 } 3688 3689 static void RenderDebugOptions(const ToolChain &TC, const Driver &D, 3690 const llvm::Triple &T, const ArgList &Args, 3691 bool EmitCodeView, ArgStringList &CmdArgs, 3692 codegenoptions::DebugInfoKind &DebugInfoKind, 3693 DwarfFissionKind &DwarfFission) { 3694 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling, 3695 options::OPT_fno_debug_info_for_profiling, false) && 3696 checkDebugInfoOption( 3697 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC)) 3698 CmdArgs.push_back("-fdebug-info-for-profiling"); 3699 3700 // The 'g' groups options involve a somewhat intricate sequence of decisions 3701 // about what to pass from the driver to the frontend, but by the time they 3702 // reach cc1 they've been factored into three well-defined orthogonal choices: 3703 // * what level of debug info to generate 3704 // * what dwarf version to write 3705 // * what debugger tuning to use 3706 // This avoids having to monkey around further in cc1 other than to disable 3707 // codeview if not running in a Windows environment. Perhaps even that 3708 // decision should be made in the driver as well though. 3709 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning(); 3710 3711 bool SplitDWARFInlining = 3712 Args.hasFlag(options::OPT_fsplit_dwarf_inlining, 3713 options::OPT_fno_split_dwarf_inlining, false); 3714 3715 Args.ClaimAllArgs(options::OPT_g_Group); 3716 3717 Arg* SplitDWARFArg; 3718 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg); 3719 3720 if (DwarfFission != DwarfFissionKind::None && 3721 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) { 3722 DwarfFission = DwarfFissionKind::None; 3723 SplitDWARFInlining = false; 3724 } 3725 3726 if (const Arg *A = 3727 Args.getLastArg(options::OPT_g_Group, options::OPT_gsplit_dwarf, 3728 options::OPT_gsplit_dwarf_EQ)) { 3729 DebugInfoKind = codegenoptions::LimitedDebugInfo; 3730 3731 // If the last option explicitly specified a debug-info level, use it. 3732 if (checkDebugInfoOption(A, Args, D, TC) && 3733 A->getOption().matches(options::OPT_gN_Group)) { 3734 DebugInfoKind = DebugLevelToInfoKind(*A); 3735 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more 3736 // complicated if you've disabled inline info in the skeleton CUs 3737 // (SplitDWARFInlining) - then there's value in composing split-dwarf and 3738 // line-tables-only, so let those compose naturally in that case. 3739 if (DebugInfoKind == codegenoptions::NoDebugInfo || 3740 DebugInfoKind == codegenoptions::DebugDirectivesOnly || 3741 (DebugInfoKind == codegenoptions::DebugLineTablesOnly && 3742 SplitDWARFInlining)) 3743 DwarfFission = DwarfFissionKind::None; 3744 } 3745 } 3746 3747 // If a debugger tuning argument appeared, remember it. 3748 if (const Arg *A = 3749 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) { 3750 if (checkDebugInfoOption(A, Args, D, TC)) { 3751 if (A->getOption().matches(options::OPT_glldb)) 3752 DebuggerTuning = llvm::DebuggerKind::LLDB; 3753 else if (A->getOption().matches(options::OPT_gsce)) 3754 DebuggerTuning = llvm::DebuggerKind::SCE; 3755 else 3756 DebuggerTuning = llvm::DebuggerKind::GDB; 3757 } 3758 } 3759 3760 // If a -gdwarf argument appeared, remember it. 3761 const Arg *GDwarfN = Args.getLastArg( 3762 options::OPT_gdwarf_2, options::OPT_gdwarf_3, options::OPT_gdwarf_4, 3763 options::OPT_gdwarf_5, options::OPT_gdwarf); 3764 bool EmitDwarf = false; 3765 if (GDwarfN) { 3766 if (checkDebugInfoOption(GDwarfN, Args, D, TC)) 3767 EmitDwarf = true; 3768 else 3769 GDwarfN = nullptr; 3770 } 3771 3772 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) { 3773 if (checkDebugInfoOption(A, Args, D, TC)) 3774 EmitCodeView = true; 3775 } 3776 3777 // If the user asked for debug info but did not explicitly specify -gcodeview 3778 // or -gdwarf, ask the toolchain for the default format. 3779 if (!EmitCodeView && !EmitDwarf && 3780 DebugInfoKind != codegenoptions::NoDebugInfo) { 3781 switch (TC.getDefaultDebugFormat()) { 3782 case codegenoptions::DIF_CodeView: 3783 EmitCodeView = true; 3784 break; 3785 case codegenoptions::DIF_DWARF: 3786 EmitDwarf = true; 3787 break; 3788 } 3789 } 3790 3791 unsigned DWARFVersion = 0; 3792 unsigned DefaultDWARFVersion = ParseDebugDefaultVersion(TC, Args); 3793 if (EmitDwarf) { 3794 // Start with the platform default DWARF version 3795 DWARFVersion = TC.GetDefaultDwarfVersion(); 3796 assert(DWARFVersion && "toolchain default DWARF version must be nonzero"); 3797 3798 // If the user specified a default DWARF version, that takes precedence 3799 // over the platform default. 3800 if (DefaultDWARFVersion) 3801 DWARFVersion = DefaultDWARFVersion; 3802 3803 // Override with a user-specified DWARF version 3804 if (GDwarfN) 3805 if (auto ExplicitVersion = DwarfVersionNum(GDwarfN->getSpelling())) 3806 DWARFVersion = ExplicitVersion; 3807 } 3808 3809 // -gline-directives-only supported only for the DWARF debug info. 3810 if (DWARFVersion == 0 && DebugInfoKind == codegenoptions::DebugDirectivesOnly) 3811 DebugInfoKind = codegenoptions::NoDebugInfo; 3812 3813 // We ignore flag -gstrict-dwarf for now. 3814 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags. 3815 Args.ClaimAllArgs(options::OPT_g_flags_Group); 3816 3817 // Column info is included by default for everything except SCE and 3818 // CodeView. Clang doesn't track end columns, just starting columns, which, 3819 // in theory, is fine for CodeView (and PDB). In practice, however, the 3820 // Microsoft debuggers don't handle missing end columns well, so it's better 3821 // not to include any column info. 3822 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info)) 3823 (void)checkDebugInfoOption(A, Args, D, TC); 3824 if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info, 3825 !EmitCodeView && DebuggerTuning != llvm::DebuggerKind::SCE)) 3826 CmdArgs.push_back("-gno-column-info"); 3827 3828 // FIXME: Move backend command line options to the module. 3829 // If -gline-tables-only or -gline-directives-only is the last option it wins. 3830 if (const Arg *A = Args.getLastArg(options::OPT_gmodules)) 3831 if (checkDebugInfoOption(A, Args, D, TC)) { 3832 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly && 3833 DebugInfoKind != codegenoptions::DebugDirectivesOnly) { 3834 DebugInfoKind = codegenoptions::LimitedDebugInfo; 3835 CmdArgs.push_back("-dwarf-ext-refs"); 3836 CmdArgs.push_back("-fmodule-format=obj"); 3837 } 3838 } 3839 3840 if (T.isOSBinFormatELF() && !SplitDWARFInlining) 3841 CmdArgs.push_back("-fno-split-dwarf-inlining"); 3842 3843 // After we've dealt with all combinations of things that could 3844 // make DebugInfoKind be other than None or DebugLineTablesOnly, 3845 // figure out if we need to "upgrade" it to standalone debug info. 3846 // We parse these two '-f' options whether or not they will be used, 3847 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only" 3848 bool NeedFullDebug = Args.hasFlag( 3849 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug, 3850 DebuggerTuning == llvm::DebuggerKind::LLDB || 3851 TC.GetDefaultStandaloneDebug()); 3852 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug)) 3853 (void)checkDebugInfoOption(A, Args, D, TC); 3854 3855 if (DebugInfoKind == codegenoptions::LimitedDebugInfo) { 3856 if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types, 3857 options::OPT_feliminate_unused_debug_types, false)) 3858 DebugInfoKind = codegenoptions::UnusedTypeInfo; 3859 else if (NeedFullDebug) 3860 DebugInfoKind = codegenoptions::FullDebugInfo; 3861 } 3862 3863 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source, 3864 false)) { 3865 // Source embedding is a vendor extension to DWARF v5. By now we have 3866 // checked if a DWARF version was stated explicitly, and have otherwise 3867 // fallen back to the target default, so if this is still not at least 5 3868 // we emit an error. 3869 const Arg *A = Args.getLastArg(options::OPT_gembed_source); 3870 if (DWARFVersion < 5) 3871 D.Diag(diag::err_drv_argument_only_allowed_with) 3872 << A->getAsString(Args) << "-gdwarf-5"; 3873 else if (checkDebugInfoOption(A, Args, D, TC)) 3874 CmdArgs.push_back("-gembed-source"); 3875 } 3876 3877 if (EmitCodeView) { 3878 CmdArgs.push_back("-gcodeview"); 3879 3880 // Emit codeview type hashes if requested. 3881 if (Args.hasFlag(options::OPT_gcodeview_ghash, 3882 options::OPT_gno_codeview_ghash, false)) { 3883 CmdArgs.push_back("-gcodeview-ghash"); 3884 } 3885 } 3886 3887 // Omit inline line tables if requested. 3888 if (Args.hasFlag(options::OPT_gno_inline_line_tables, 3889 options::OPT_ginline_line_tables, false)) { 3890 CmdArgs.push_back("-gno-inline-line-tables"); 3891 } 3892 3893 // Adjust the debug info kind for the given toolchain. 3894 TC.adjustDebugInfoKind(DebugInfoKind, Args); 3895 3896 // When emitting remarks, we need at least debug lines in the output. 3897 if (willEmitRemarks(Args) && 3898 DebugInfoKind <= codegenoptions::DebugDirectivesOnly) 3899 DebugInfoKind = codegenoptions::DebugLineTablesOnly; 3900 3901 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion, 3902 DebuggerTuning); 3903 3904 // -fdebug-macro turns on macro debug info generation. 3905 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro, 3906 false)) 3907 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args, 3908 D, TC)) 3909 CmdArgs.push_back("-debug-info-macro"); 3910 3911 // -ggnu-pubnames turns on gnu style pubnames in the backend. 3912 const auto *PubnamesArg = 3913 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames, 3914 options::OPT_gpubnames, options::OPT_gno_pubnames); 3915 if (DwarfFission != DwarfFissionKind::None || 3916 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC))) 3917 if (!PubnamesArg || 3918 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) && 3919 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames))) 3920 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches( 3921 options::OPT_gpubnames) 3922 ? "-gpubnames" 3923 : "-ggnu-pubnames"); 3924 3925 if (Args.hasFlag(options::OPT_fdebug_ranges_base_address, 3926 options::OPT_fno_debug_ranges_base_address, false)) { 3927 CmdArgs.push_back("-fdebug-ranges-base-address"); 3928 } 3929 3930 // -gdwarf-aranges turns on the emission of the aranges section in the 3931 // backend. 3932 // Always enabled for SCE tuning. 3933 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE; 3934 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges)) 3935 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges; 3936 if (NeedAranges) { 3937 CmdArgs.push_back("-mllvm"); 3938 CmdArgs.push_back("-generate-arange-section"); 3939 } 3940 3941 if (Args.hasFlag(options::OPT_fforce_dwarf_frame, 3942 options::OPT_fno_force_dwarf_frame, false)) 3943 CmdArgs.push_back("-fforce-dwarf-frame"); 3944 3945 if (Args.hasFlag(options::OPT_fdebug_types_section, 3946 options::OPT_fno_debug_types_section, false)) { 3947 if (!T.isOSBinFormatELF()) { 3948 D.Diag(diag::err_drv_unsupported_opt_for_target) 3949 << Args.getLastArg(options::OPT_fdebug_types_section) 3950 ->getAsString(Args) 3951 << T.getTriple(); 3952 } else if (checkDebugInfoOption( 3953 Args.getLastArg(options::OPT_fdebug_types_section), Args, D, 3954 TC)) { 3955 CmdArgs.push_back("-mllvm"); 3956 CmdArgs.push_back("-generate-type-units"); 3957 } 3958 } 3959 3960 // Decide how to render forward declarations of template instantiations. 3961 // SCE wants full descriptions, others just get them in the name. 3962 if (DebuggerTuning == llvm::DebuggerKind::SCE) 3963 CmdArgs.push_back("-debug-forward-template-params"); 3964 3965 // Do we need to explicitly import anonymous namespaces into the parent 3966 // scope? 3967 if (DebuggerTuning == llvm::DebuggerKind::SCE) 3968 CmdArgs.push_back("-dwarf-explicit-import"); 3969 3970 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC); 3971 } 3972 3973 void Clang::ConstructJob(Compilation &C, const JobAction &JA, 3974 const InputInfo &Output, const InputInfoList &Inputs, 3975 const ArgList &Args, const char *LinkingOutput) const { 3976 const auto &TC = getToolChain(); 3977 const llvm::Triple &RawTriple = TC.getTriple(); 3978 const llvm::Triple &Triple = TC.getEffectiveTriple(); 3979 const std::string &TripleStr = Triple.getTriple(); 3980 3981 bool KernelOrKext = 3982 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext); 3983 const Driver &D = TC.getDriver(); 3984 ArgStringList CmdArgs; 3985 3986 // Check number of inputs for sanity. We need at least one input. 3987 assert(Inputs.size() >= 1 && "Must have at least one input."); 3988 // CUDA/HIP compilation may have multiple inputs (source file + results of 3989 // device-side compilations). OpenMP device jobs also take the host IR as a 3990 // second input. Module precompilation accepts a list of header files to 3991 // include as part of the module. All other jobs are expected to have exactly 3992 // one input. 3993 bool IsCuda = JA.isOffloading(Action::OFK_Cuda); 3994 bool IsHIP = JA.isOffloading(Action::OFK_HIP); 3995 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP); 3996 bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA); 3997 3998 // A header module compilation doesn't have a main input file, so invent a 3999 // fake one as a placeholder. 4000 const char *ModuleName = [&]{ 4001 auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ); 4002 return ModuleNameArg ? ModuleNameArg->getValue() : ""; 4003 }(); 4004 InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName); 4005 4006 const InputInfo &Input = 4007 IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0]; 4008 4009 InputInfoList ModuleHeaderInputs; 4010 const InputInfo *CudaDeviceInput = nullptr; 4011 const InputInfo *OpenMPDeviceInput = nullptr; 4012 for (const InputInfo &I : Inputs) { 4013 if (&I == &Input) { 4014 // This is the primary input. 4015 } else if (IsHeaderModulePrecompile && 4016 types::getPrecompiledType(I.getType()) == types::TY_PCH) { 4017 types::ID Expected = HeaderModuleInput.getType(); 4018 if (I.getType() != Expected) { 4019 D.Diag(diag::err_drv_module_header_wrong_kind) 4020 << I.getFilename() << types::getTypeName(I.getType()) 4021 << types::getTypeName(Expected); 4022 } 4023 ModuleHeaderInputs.push_back(I); 4024 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) { 4025 CudaDeviceInput = &I; 4026 } else if (IsOpenMPDevice && !OpenMPDeviceInput) { 4027 OpenMPDeviceInput = &I; 4028 } else { 4029 llvm_unreachable("unexpectedly given multiple inputs"); 4030 } 4031 } 4032 4033 const llvm::Triple *AuxTriple = 4034 (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr; 4035 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment(); 4036 bool IsIAMCU = RawTriple.isOSIAMCU(); 4037 4038 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in 4039 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not 4040 // Windows), we need to pass Windows-specific flags to cc1. 4041 if (IsCuda || IsHIP) 4042 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment(); 4043 4044 // C++ is not supported for IAMCU. 4045 if (IsIAMCU && types::isCXX(Input.getType())) 4046 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU"; 4047 4048 // Invoke ourselves in -cc1 mode. 4049 // 4050 // FIXME: Implement custom jobs for internal actions. 4051 CmdArgs.push_back("-cc1"); 4052 4053 // Add the "effective" target triple. 4054 CmdArgs.push_back("-triple"); 4055 CmdArgs.push_back(Args.MakeArgString(TripleStr)); 4056 4057 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) { 4058 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args); 4059 Args.ClaimAllArgs(options::OPT_MJ); 4060 } else if (const Arg *GenCDBFragment = 4061 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) { 4062 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C, 4063 TripleStr, Output, Input, Args); 4064 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path); 4065 } 4066 4067 if (IsCuda || IsHIP) { 4068 // We have to pass the triple of the host if compiling for a CUDA/HIP device 4069 // and vice-versa. 4070 std::string NormalizedTriple; 4071 if (JA.isDeviceOffloading(Action::OFK_Cuda) || 4072 JA.isDeviceOffloading(Action::OFK_HIP)) 4073 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>() 4074 ->getTriple() 4075 .normalize(); 4076 else { 4077 // Host-side compilation. 4078 NormalizedTriple = 4079 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>() 4080 : C.getSingleOffloadToolChain<Action::OFK_HIP>()) 4081 ->getTriple() 4082 .normalize(); 4083 if (IsCuda) { 4084 // We need to figure out which CUDA version we're compiling for, as that 4085 // determines how we load and launch GPU kernels. 4086 auto *CTC = static_cast<const toolchains::CudaToolChain *>( 4087 C.getSingleOffloadToolChain<Action::OFK_Cuda>()); 4088 assert(CTC && "Expected valid CUDA Toolchain."); 4089 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN) 4090 CmdArgs.push_back(Args.MakeArgString( 4091 Twine("-target-sdk-version=") + 4092 CudaVersionToString(CTC->CudaInstallation.version()))); 4093 } 4094 } 4095 CmdArgs.push_back("-aux-triple"); 4096 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple)); 4097 } 4098 4099 if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false)) { 4100 CmdArgs.push_back("-fsycl"); 4101 CmdArgs.push_back("-fsycl-is-device"); 4102 4103 if (Arg *A = Args.getLastArg(options::OPT_sycl_std_EQ)) { 4104 A->render(Args, CmdArgs); 4105 } else { 4106 // Ensure the default version in SYCL mode is 1.2.1 (aka 2017) 4107 CmdArgs.push_back("-sycl-std=2017"); 4108 } 4109 } 4110 4111 if (IsOpenMPDevice) { 4112 // We have to pass the triple of the host if compiling for an OpenMP device. 4113 std::string NormalizedTriple = 4114 C.getSingleOffloadToolChain<Action::OFK_Host>() 4115 ->getTriple() 4116 .normalize(); 4117 CmdArgs.push_back("-aux-triple"); 4118 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple)); 4119 } 4120 4121 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm || 4122 Triple.getArch() == llvm::Triple::thumb)) { 4123 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6; 4124 unsigned Version = 0; 4125 bool Failure = 4126 Triple.getArchName().substr(Offset).consumeInteger(10, Version); 4127 if (Failure || Version < 7) 4128 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName() 4129 << TripleStr; 4130 } 4131 4132 // Push all default warning arguments that are specific to 4133 // the given target. These come before user provided warning options 4134 // are provided. 4135 TC.addClangWarningOptions(CmdArgs); 4136 4137 // Select the appropriate action. 4138 RewriteKind rewriteKind = RK_None; 4139 4140 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args 4141 // it claims when not running an assembler. Otherwise, clang would emit 4142 // "argument unused" warnings for assembler flags when e.g. adding "-E" to 4143 // flags while debugging something. That'd be somewhat inconvenient, and it's 4144 // also inconsistent with most other flags -- we don't warn on 4145 // -ffunction-sections not being used in -E mode either for example, even 4146 // though it's not really used either. 4147 if (!isa<AssembleJobAction>(JA)) { 4148 // The args claimed here should match the args used in 4149 // CollectArgsForIntegratedAssembler(). 4150 if (TC.useIntegratedAs()) { 4151 Args.ClaimAllArgs(options::OPT_mrelax_all); 4152 Args.ClaimAllArgs(options::OPT_mno_relax_all); 4153 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible); 4154 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible); 4155 switch (C.getDefaultToolChain().getArch()) { 4156 case llvm::Triple::arm: 4157 case llvm::Triple::armeb: 4158 case llvm::Triple::thumb: 4159 case llvm::Triple::thumbeb: 4160 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ); 4161 break; 4162 default: 4163 break; 4164 } 4165 } 4166 Args.ClaimAllArgs(options::OPT_Wa_COMMA); 4167 Args.ClaimAllArgs(options::OPT_Xassembler); 4168 } 4169 4170 if (isa<AnalyzeJobAction>(JA)) { 4171 assert(JA.getType() == types::TY_Plist && "Invalid output type."); 4172 CmdArgs.push_back("-analyze"); 4173 } else if (isa<MigrateJobAction>(JA)) { 4174 CmdArgs.push_back("-migrate"); 4175 } else if (isa<PreprocessJobAction>(JA)) { 4176 if (Output.getType() == types::TY_Dependencies) 4177 CmdArgs.push_back("-Eonly"); 4178 else { 4179 CmdArgs.push_back("-E"); 4180 if (Args.hasArg(options::OPT_rewrite_objc) && 4181 !Args.hasArg(options::OPT_g_Group)) 4182 CmdArgs.push_back("-P"); 4183 } 4184 } else if (isa<AssembleJobAction>(JA)) { 4185 CmdArgs.push_back("-emit-obj"); 4186 4187 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D); 4188 4189 // Also ignore explicit -force_cpusubtype_ALL option. 4190 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL); 4191 } else if (isa<PrecompileJobAction>(JA)) { 4192 if (JA.getType() == types::TY_Nothing) 4193 CmdArgs.push_back("-fsyntax-only"); 4194 else if (JA.getType() == types::TY_ModuleFile) 4195 CmdArgs.push_back(IsHeaderModulePrecompile 4196 ? "-emit-header-module" 4197 : "-emit-module-interface"); 4198 else 4199 CmdArgs.push_back("-emit-pch"); 4200 } else if (isa<VerifyPCHJobAction>(JA)) { 4201 CmdArgs.push_back("-verify-pch"); 4202 } else { 4203 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) && 4204 "Invalid action for clang tool."); 4205 if (JA.getType() == types::TY_Nothing) { 4206 CmdArgs.push_back("-fsyntax-only"); 4207 } else if (JA.getType() == types::TY_LLVM_IR || 4208 JA.getType() == types::TY_LTO_IR) { 4209 CmdArgs.push_back("-emit-llvm"); 4210 } else if (JA.getType() == types::TY_LLVM_BC || 4211 JA.getType() == types::TY_LTO_BC) { 4212 CmdArgs.push_back("-emit-llvm-bc"); 4213 } else if (JA.getType() == types::TY_IFS || 4214 JA.getType() == types::TY_IFS_CPP) { 4215 StringRef ArgStr = 4216 Args.hasArg(options::OPT_interface_stub_version_EQ) 4217 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ) 4218 : "experimental-ifs-v2"; 4219 CmdArgs.push_back("-emit-interface-stubs"); 4220 CmdArgs.push_back( 4221 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str())); 4222 } else if (JA.getType() == types::TY_PP_Asm) { 4223 CmdArgs.push_back("-S"); 4224 } else if (JA.getType() == types::TY_AST) { 4225 CmdArgs.push_back("-emit-pch"); 4226 } else if (JA.getType() == types::TY_ModuleFile) { 4227 CmdArgs.push_back("-module-file-info"); 4228 } else if (JA.getType() == types::TY_RewrittenObjC) { 4229 CmdArgs.push_back("-rewrite-objc"); 4230 rewriteKind = RK_NonFragile; 4231 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) { 4232 CmdArgs.push_back("-rewrite-objc"); 4233 rewriteKind = RK_Fragile; 4234 } else { 4235 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!"); 4236 } 4237 4238 // Preserve use-list order by default when emitting bitcode, so that 4239 // loading the bitcode up in 'opt' or 'llc' and running passes gives the 4240 // same result as running passes here. For LTO, we don't need to preserve 4241 // the use-list order, since serialization to bitcode is part of the flow. 4242 if (JA.getType() == types::TY_LLVM_BC) 4243 CmdArgs.push_back("-emit-llvm-uselists"); 4244 4245 // Device-side jobs do not support LTO. 4246 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) || 4247 JA.isDeviceOffloading(Action::OFK_Host)); 4248 4249 if (D.isUsingLTO() && !isDeviceOffloadAction) { 4250 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ); 4251 CmdArgs.push_back("-flto-unit"); 4252 } 4253 } 4254 4255 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) { 4256 if (!types::isLLVMIR(Input.getType())) 4257 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args); 4258 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ); 4259 } 4260 4261 if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ)) 4262 Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ); 4263 4264 if (Args.getLastArg(options::OPT_save_temps_EQ)) 4265 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ); 4266 4267 if (Args.hasFlag(options::OPT_fmemory_profile, 4268 options::OPT_fno_memory_profile, false)) 4269 Args.AddLastArg(CmdArgs, options::OPT_fmemory_profile); 4270 4271 // Embed-bitcode option. 4272 // Only white-listed flags below are allowed to be embedded. 4273 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() && 4274 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) { 4275 // Add flags implied by -fembed-bitcode. 4276 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ); 4277 // Disable all llvm IR level optimizations. 4278 CmdArgs.push_back("-disable-llvm-passes"); 4279 4280 // Render target options. 4281 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind()); 4282 4283 // reject options that shouldn't be supported in bitcode 4284 // also reject kernel/kext 4285 static const constexpr unsigned kBitcodeOptionBlacklist[] = { 4286 options::OPT_mkernel, 4287 options::OPT_fapple_kext, 4288 options::OPT_ffunction_sections, 4289 options::OPT_fno_function_sections, 4290 options::OPT_fdata_sections, 4291 options::OPT_fno_data_sections, 4292 options::OPT_fbasic_block_sections_EQ, 4293 options::OPT_funique_internal_linkage_names, 4294 options::OPT_fno_unique_internal_linkage_names, 4295 options::OPT_funique_section_names, 4296 options::OPT_fno_unique_section_names, 4297 options::OPT_funique_basic_block_section_names, 4298 options::OPT_fno_unique_basic_block_section_names, 4299 options::OPT_mrestrict_it, 4300 options::OPT_mno_restrict_it, 4301 options::OPT_mstackrealign, 4302 options::OPT_mno_stackrealign, 4303 options::OPT_mstack_alignment, 4304 options::OPT_mcmodel_EQ, 4305 options::OPT_mlong_calls, 4306 options::OPT_mno_long_calls, 4307 options::OPT_ggnu_pubnames, 4308 options::OPT_gdwarf_aranges, 4309 options::OPT_fdebug_types_section, 4310 options::OPT_fno_debug_types_section, 4311 options::OPT_fdwarf_directory_asm, 4312 options::OPT_fno_dwarf_directory_asm, 4313 options::OPT_mrelax_all, 4314 options::OPT_mno_relax_all, 4315 options::OPT_ftrap_function_EQ, 4316 options::OPT_ffixed_r9, 4317 options::OPT_mfix_cortex_a53_835769, 4318 options::OPT_mno_fix_cortex_a53_835769, 4319 options::OPT_ffixed_x18, 4320 options::OPT_mglobal_merge, 4321 options::OPT_mno_global_merge, 4322 options::OPT_mred_zone, 4323 options::OPT_mno_red_zone, 4324 options::OPT_Wa_COMMA, 4325 options::OPT_Xassembler, 4326 options::OPT_mllvm, 4327 }; 4328 for (const auto &A : Args) 4329 if (llvm::find(kBitcodeOptionBlacklist, A->getOption().getID()) != 4330 std::end(kBitcodeOptionBlacklist)) 4331 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling(); 4332 4333 // Render the CodeGen options that need to be passed. 4334 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls, 4335 options::OPT_fno_optimize_sibling_calls)) 4336 CmdArgs.push_back("-mdisable-tail-calls"); 4337 4338 RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args, 4339 CmdArgs, JA); 4340 4341 // Render ABI arguments 4342 switch (TC.getArch()) { 4343 default: break; 4344 case llvm::Triple::arm: 4345 case llvm::Triple::armeb: 4346 case llvm::Triple::thumbeb: 4347 RenderARMABI(Triple, Args, CmdArgs); 4348 break; 4349 case llvm::Triple::aarch64: 4350 case llvm::Triple::aarch64_32: 4351 case llvm::Triple::aarch64_be: 4352 RenderAArch64ABI(Triple, Args, CmdArgs); 4353 break; 4354 } 4355 4356 // Optimization level for CodeGen. 4357 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) { 4358 if (A->getOption().matches(options::OPT_O4)) { 4359 CmdArgs.push_back("-O3"); 4360 D.Diag(diag::warn_O4_is_O3); 4361 } else { 4362 A->render(Args, CmdArgs); 4363 } 4364 } 4365 4366 // Input/Output file. 4367 if (Output.getType() == types::TY_Dependencies) { 4368 // Handled with other dependency code. 4369 } else if (Output.isFilename()) { 4370 CmdArgs.push_back("-o"); 4371 CmdArgs.push_back(Output.getFilename()); 4372 } else { 4373 assert(Output.isNothing() && "Input output."); 4374 } 4375 4376 for (const auto &II : Inputs) { 4377 addDashXForInput(Args, II, CmdArgs); 4378 if (II.isFilename()) 4379 CmdArgs.push_back(II.getFilename()); 4380 else 4381 II.getInputArg().renderAsInput(Args, CmdArgs); 4382 } 4383 4384 C.addCommand(std::make_unique<Command>( 4385 JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(), 4386 CmdArgs, Inputs, Output)); 4387 return; 4388 } 4389 4390 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO()) 4391 CmdArgs.push_back("-fembed-bitcode=marker"); 4392 4393 // We normally speed up the clang process a bit by skipping destructors at 4394 // exit, but when we're generating diagnostics we can rely on some of the 4395 // cleanup. 4396 if (!C.isForDiagnostics()) 4397 CmdArgs.push_back("-disable-free"); 4398 4399 #ifdef NDEBUG 4400 const bool IsAssertBuild = false; 4401 #else 4402 const bool IsAssertBuild = true; 4403 #endif 4404 4405 // Disable the verification pass in -asserts builds. 4406 if (!IsAssertBuild) 4407 CmdArgs.push_back("-disable-llvm-verifier"); 4408 4409 // Discard value names in assert builds unless otherwise specified. 4410 if (Args.hasFlag(options::OPT_fdiscard_value_names, 4411 options::OPT_fno_discard_value_names, !IsAssertBuild)) { 4412 if (Args.hasArg(options::OPT_fdiscard_value_names) && 4413 (std::any_of(Inputs.begin(), Inputs.end(), 4414 [](const clang::driver::InputInfo &II) { 4415 return types::isLLVMIR(II.getType()); 4416 }))) { 4417 D.Diag(diag::warn_ignoring_fdiscard_for_bitcode); 4418 } 4419 CmdArgs.push_back("-discard-value-names"); 4420 } 4421 4422 // Set the main file name, so that debug info works even with 4423 // -save-temps. 4424 CmdArgs.push_back("-main-file-name"); 4425 CmdArgs.push_back(getBaseInputName(Args, Input)); 4426 4427 // Some flags which affect the language (via preprocessor 4428 // defines). 4429 if (Args.hasArg(options::OPT_static)) 4430 CmdArgs.push_back("-static-define"); 4431 4432 if (Args.hasArg(options::OPT_municode)) 4433 CmdArgs.push_back("-DUNICODE"); 4434 4435 if (isa<AnalyzeJobAction>(JA)) 4436 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input); 4437 4438 if (isa<AnalyzeJobAction>(JA) || 4439 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze))) 4440 CmdArgs.push_back("-setup-static-analyzer"); 4441 4442 // Enable compatilibily mode to avoid analyzer-config related errors. 4443 // Since we can't access frontend flags through hasArg, let's manually iterate 4444 // through them. 4445 bool FoundAnalyzerConfig = false; 4446 for (auto Arg : Args.filtered(options::OPT_Xclang)) 4447 if (StringRef(Arg->getValue()) == "-analyzer-config") { 4448 FoundAnalyzerConfig = true; 4449 break; 4450 } 4451 if (!FoundAnalyzerConfig) 4452 for (auto Arg : Args.filtered(options::OPT_Xanalyzer)) 4453 if (StringRef(Arg->getValue()) == "-analyzer-config") { 4454 FoundAnalyzerConfig = true; 4455 break; 4456 } 4457 if (FoundAnalyzerConfig) 4458 CmdArgs.push_back("-analyzer-config-compatibility-mode=true"); 4459 4460 CheckCodeGenerationOptions(D, Args); 4461 4462 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args); 4463 assert(FunctionAlignment <= 31 && "function alignment will be truncated!"); 4464 if (FunctionAlignment) { 4465 CmdArgs.push_back("-function-alignment"); 4466 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment))); 4467 } 4468 4469 llvm::Reloc::Model RelocationModel; 4470 unsigned PICLevel; 4471 bool IsPIE; 4472 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args); 4473 4474 bool IsROPI = RelocationModel == llvm::Reloc::ROPI || 4475 RelocationModel == llvm::Reloc::ROPI_RWPI; 4476 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI || 4477 RelocationModel == llvm::Reloc::ROPI_RWPI; 4478 4479 if (Args.hasArg(options::OPT_mcmse) && 4480 !Args.hasArg(options::OPT_fallow_unsupported)) { 4481 if (IsROPI) 4482 D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI; 4483 if (IsRWPI) 4484 D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI; 4485 } 4486 4487 if (IsROPI && types::isCXX(Input.getType()) && 4488 !Args.hasArg(options::OPT_fallow_unsupported)) 4489 D.Diag(diag::err_drv_ropi_incompatible_with_cxx); 4490 4491 const char *RMName = RelocationModelName(RelocationModel); 4492 if (RMName) { 4493 CmdArgs.push_back("-mrelocation-model"); 4494 CmdArgs.push_back(RMName); 4495 } 4496 if (PICLevel > 0) { 4497 CmdArgs.push_back("-pic-level"); 4498 CmdArgs.push_back(PICLevel == 1 ? "1" : "2"); 4499 if (IsPIE) 4500 CmdArgs.push_back("-pic-is-pie"); 4501 } 4502 4503 if (RelocationModel == llvm::Reloc::ROPI || 4504 RelocationModel == llvm::Reloc::ROPI_RWPI) 4505 CmdArgs.push_back("-fropi"); 4506 if (RelocationModel == llvm::Reloc::RWPI || 4507 RelocationModel == llvm::Reloc::ROPI_RWPI) 4508 CmdArgs.push_back("-frwpi"); 4509 4510 if (Arg *A = Args.getLastArg(options::OPT_meabi)) { 4511 CmdArgs.push_back("-meabi"); 4512 CmdArgs.push_back(A->getValue()); 4513 } 4514 4515 // The default is -fno-semantic-interposition. We render it just because we 4516 // require explicit -fno-semantic-interposition to infer dso_local. 4517 if (Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition, 4518 options::OPT_fno_semantic_interposition)) 4519 if (RelocationModel != llvm::Reloc::Static && !IsPIE) 4520 A->render(Args, CmdArgs); 4521 4522 { 4523 std::string Model; 4524 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) { 4525 if (!TC.isThreadModelSupported(A->getValue())) 4526 D.Diag(diag::err_drv_invalid_thread_model_for_target) 4527 << A->getValue() << A->getAsString(Args); 4528 Model = A->getValue(); 4529 } else 4530 Model = TC.getThreadModel(); 4531 if (Model != "posix") { 4532 CmdArgs.push_back("-mthread-model"); 4533 CmdArgs.push_back(Args.MakeArgString(Model)); 4534 } 4535 } 4536 4537 Args.AddLastArg(CmdArgs, options::OPT_fveclib); 4538 4539 if (Args.hasFlag(options::OPT_fmerge_all_constants, 4540 options::OPT_fno_merge_all_constants, false)) 4541 CmdArgs.push_back("-fmerge-all-constants"); 4542 4543 if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks, 4544 options::OPT_fdelete_null_pointer_checks, false)) 4545 CmdArgs.push_back("-fno-delete-null-pointer-checks"); 4546 4547 // LLVM Code Generator Options. 4548 4549 if (Args.hasArg(options::OPT_frewrite_map_file) || 4550 Args.hasArg(options::OPT_frewrite_map_file_EQ)) { 4551 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file, 4552 options::OPT_frewrite_map_file_EQ)) { 4553 StringRef Map = A->getValue(); 4554 if (!llvm::sys::fs::exists(Map)) { 4555 D.Diag(diag::err_drv_no_such_file) << Map; 4556 } else { 4557 CmdArgs.push_back("-frewrite-map-file"); 4558 CmdArgs.push_back(A->getValue()); 4559 A->claim(); 4560 } 4561 } 4562 } 4563 4564 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) { 4565 StringRef v = A->getValue(); 4566 CmdArgs.push_back("-mllvm"); 4567 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v)); 4568 A->claim(); 4569 } 4570 4571 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables, 4572 true)) 4573 CmdArgs.push_back("-fno-jump-tables"); 4574 4575 if (Args.hasFlag(options::OPT_fprofile_sample_accurate, 4576 options::OPT_fno_profile_sample_accurate, false)) 4577 CmdArgs.push_back("-fprofile-sample-accurate"); 4578 4579 if (!Args.hasFlag(options::OPT_fpreserve_as_comments, 4580 options::OPT_fno_preserve_as_comments, true)) 4581 CmdArgs.push_back("-fno-preserve-as-comments"); 4582 4583 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) { 4584 CmdArgs.push_back("-mregparm"); 4585 CmdArgs.push_back(A->getValue()); 4586 } 4587 4588 if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return, 4589 options::OPT_msvr4_struct_return)) { 4590 if (TC.getArch() != llvm::Triple::ppc) { 4591 D.Diag(diag::err_drv_unsupported_opt_for_target) 4592 << A->getSpelling() << RawTriple.str(); 4593 } else if (A->getOption().matches(options::OPT_maix_struct_return)) { 4594 CmdArgs.push_back("-maix-struct-return"); 4595 } else { 4596 assert(A->getOption().matches(options::OPT_msvr4_struct_return)); 4597 CmdArgs.push_back("-msvr4-struct-return"); 4598 } 4599 } 4600 4601 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return, 4602 options::OPT_freg_struct_return)) { 4603 if (TC.getArch() != llvm::Triple::x86) { 4604 D.Diag(diag::err_drv_unsupported_opt_for_target) 4605 << A->getSpelling() << RawTriple.str(); 4606 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) { 4607 CmdArgs.push_back("-fpcc-struct-return"); 4608 } else { 4609 assert(A->getOption().matches(options::OPT_freg_struct_return)); 4610 CmdArgs.push_back("-freg-struct-return"); 4611 } 4612 } 4613 4614 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) 4615 CmdArgs.push_back("-fdefault-calling-conv=stdcall"); 4616 4617 if (Args.hasArg(options::OPT_fenable_matrix)) { 4618 // enable-matrix is needed by both the LangOpts and by LLVM. 4619 CmdArgs.push_back("-fenable-matrix"); 4620 CmdArgs.push_back("-mllvm"); 4621 CmdArgs.push_back("-enable-matrix"); 4622 } 4623 4624 CodeGenOptions::FramePointerKind FPKeepKind = 4625 getFramePointerKind(Args, RawTriple); 4626 const char *FPKeepKindStr = nullptr; 4627 switch (FPKeepKind) { 4628 case CodeGenOptions::FramePointerKind::None: 4629 FPKeepKindStr = "-mframe-pointer=none"; 4630 break; 4631 case CodeGenOptions::FramePointerKind::NonLeaf: 4632 FPKeepKindStr = "-mframe-pointer=non-leaf"; 4633 break; 4634 case CodeGenOptions::FramePointerKind::All: 4635 FPKeepKindStr = "-mframe-pointer=all"; 4636 break; 4637 } 4638 assert(FPKeepKindStr && "unknown FramePointerKind"); 4639 CmdArgs.push_back(FPKeepKindStr); 4640 4641 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss, 4642 options::OPT_fno_zero_initialized_in_bss, true)) 4643 CmdArgs.push_back("-fno-zero-initialized-in-bss"); 4644 4645 bool OFastEnabled = isOptimizationLevelFast(Args); 4646 // If -Ofast is the optimization level, then -fstrict-aliasing should be 4647 // enabled. This alias option is being used to simplify the hasFlag logic. 4648 OptSpecifier StrictAliasingAliasOption = 4649 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing; 4650 // We turn strict aliasing off by default if we're in CL mode, since MSVC 4651 // doesn't do any TBAA. 4652 bool TBAAOnByDefault = !D.IsCLMode(); 4653 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption, 4654 options::OPT_fno_strict_aliasing, TBAAOnByDefault)) 4655 CmdArgs.push_back("-relaxed-aliasing"); 4656 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa, 4657 options::OPT_fno_struct_path_tbaa)) 4658 CmdArgs.push_back("-no-struct-path-tbaa"); 4659 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums, 4660 false)) 4661 CmdArgs.push_back("-fstrict-enums"); 4662 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return, 4663 true)) 4664 CmdArgs.push_back("-fno-strict-return"); 4665 if (Args.hasFlag(options::OPT_fallow_editor_placeholders, 4666 options::OPT_fno_allow_editor_placeholders, false)) 4667 CmdArgs.push_back("-fallow-editor-placeholders"); 4668 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers, 4669 options::OPT_fno_strict_vtable_pointers, 4670 false)) 4671 CmdArgs.push_back("-fstrict-vtable-pointers"); 4672 if (Args.hasFlag(options::OPT_fforce_emit_vtables, 4673 options::OPT_fno_force_emit_vtables, 4674 false)) 4675 CmdArgs.push_back("-fforce-emit-vtables"); 4676 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls, 4677 options::OPT_fno_optimize_sibling_calls)) 4678 CmdArgs.push_back("-mdisable-tail-calls"); 4679 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls, 4680 options::OPT_fescaping_block_tail_calls, false)) 4681 CmdArgs.push_back("-fno-escaping-block-tail-calls"); 4682 4683 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses, 4684 options::OPT_fno_fine_grained_bitfield_accesses); 4685 4686 // Handle segmented stacks. 4687 if (Args.hasArg(options::OPT_fsplit_stack)) 4688 CmdArgs.push_back("-split-stacks"); 4689 4690 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA); 4691 4692 if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) { 4693 if (TC.getArch() == llvm::Triple::avr) 4694 A->render(Args, CmdArgs); 4695 else 4696 D.Diag(diag::err_drv_unsupported_opt_for_target) 4697 << A->getAsString(Args) << TripleStr; 4698 } 4699 4700 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) { 4701 if (TC.getTriple().isX86()) 4702 A->render(Args, CmdArgs); 4703 else if ((TC.getArch() == llvm::Triple::ppc || TC.getTriple().isPPC64()) && 4704 (A->getOption().getID() != options::OPT_mlong_double_80)) 4705 A->render(Args, CmdArgs); 4706 else 4707 D.Diag(diag::err_drv_unsupported_opt_for_target) 4708 << A->getAsString(Args) << TripleStr; 4709 } 4710 4711 // Decide whether to use verbose asm. Verbose assembly is the default on 4712 // toolchains which have the integrated assembler on by default. 4713 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault(); 4714 if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm, 4715 IsIntegratedAssemblerDefault)) 4716 CmdArgs.push_back("-fno-verbose-asm"); 4717 4718 if (!TC.useIntegratedAs()) 4719 CmdArgs.push_back("-no-integrated-as"); 4720 4721 if (Args.hasArg(options::OPT_fdebug_pass_structure)) { 4722 CmdArgs.push_back("-mdebug-pass"); 4723 CmdArgs.push_back("Structure"); 4724 } 4725 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) { 4726 CmdArgs.push_back("-mdebug-pass"); 4727 CmdArgs.push_back("Arguments"); 4728 } 4729 4730 // Enable -mconstructor-aliases except on darwin, where we have to work around 4731 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where 4732 // aliases aren't supported. Similarly, aliases aren't yet supported for AIX. 4733 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX() && !RawTriple.isOSAIX()) 4734 CmdArgs.push_back("-mconstructor-aliases"); 4735 4736 // Darwin's kernel doesn't support guard variables; just die if we 4737 // try to use them. 4738 if (KernelOrKext && RawTriple.isOSDarwin()) 4739 CmdArgs.push_back("-fforbid-guard-variables"); 4740 4741 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields, 4742 Triple.isWindowsGNUEnvironment())) { 4743 CmdArgs.push_back("-mms-bitfields"); 4744 } 4745 4746 if (Args.hasFlag(options::OPT_mpie_copy_relocations, 4747 options::OPT_mno_pie_copy_relocations, 4748 false)) { 4749 CmdArgs.push_back("-mpie-copy-relocations"); 4750 } 4751 4752 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) { 4753 CmdArgs.push_back("-fno-plt"); 4754 } 4755 4756 // -fhosted is default. 4757 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to 4758 // use Freestanding. 4759 bool Freestanding = 4760 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) || 4761 KernelOrKext; 4762 if (Freestanding) 4763 CmdArgs.push_back("-ffreestanding"); 4764 4765 // This is a coarse approximation of what llvm-gcc actually does, both 4766 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more 4767 // complicated ways. 4768 bool AsynchronousUnwindTables = 4769 Args.hasFlag(options::OPT_fasynchronous_unwind_tables, 4770 options::OPT_fno_asynchronous_unwind_tables, 4771 (TC.IsUnwindTablesDefault(Args) || 4772 TC.getSanitizerArgs().needsUnwindTables()) && 4773 !Freestanding); 4774 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables, 4775 AsynchronousUnwindTables)) 4776 CmdArgs.push_back("-munwind-tables"); 4777 4778 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless 4779 // `--gpu-use-aux-triple-only` is specified. 4780 if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) && 4781 ((IsCuda && JA.isDeviceOffloading(Action::OFK_Cuda)) || 4782 (IsHIP && JA.isDeviceOffloading(Action::OFK_HIP)))) { 4783 const ArgList &HostArgs = 4784 C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None); 4785 std::string HostCPU = 4786 getCPUName(HostArgs, *TC.getAuxTriple(), /*FromAs*/ false); 4787 if (!HostCPU.empty()) { 4788 CmdArgs.push_back("-aux-target-cpu"); 4789 CmdArgs.push_back(Args.MakeArgString(HostCPU)); 4790 } 4791 getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs, 4792 /*ForAS*/ false, /*IsAux*/ true); 4793 } 4794 4795 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind()); 4796 4797 // FIXME: Handle -mtune=. 4798 (void)Args.hasArg(options::OPT_mtune_EQ); 4799 4800 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) { 4801 StringRef CM = A->getValue(); 4802 if (CM == "small" || CM == "kernel" || CM == "medium" || CM == "large" || 4803 CM == "tiny") 4804 A->render(Args, CmdArgs); 4805 else 4806 D.Diag(diag::err_drv_invalid_argument_to_option) 4807 << CM << A->getOption().getName(); 4808 } 4809 4810 if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) { 4811 StringRef Value = A->getValue(); 4812 unsigned TLSSize = 0; 4813 Value.getAsInteger(10, TLSSize); 4814 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF()) 4815 D.Diag(diag::err_drv_unsupported_opt_for_target) 4816 << A->getOption().getName() << TripleStr; 4817 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48) 4818 D.Diag(diag::err_drv_invalid_int_value) 4819 << A->getOption().getName() << Value; 4820 Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ); 4821 } 4822 4823 // Add the target cpu 4824 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false); 4825 if (!CPU.empty()) { 4826 CmdArgs.push_back("-target-cpu"); 4827 CmdArgs.push_back(Args.MakeArgString(CPU)); 4828 } 4829 4830 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs); 4831 4832 // These two are potentially updated by AddClangCLArgs. 4833 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo; 4834 bool EmitCodeView = false; 4835 4836 // Add clang-cl arguments. 4837 types::ID InputType = Input.getType(); 4838 if (D.IsCLMode()) 4839 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView); 4840 4841 DwarfFissionKind DwarfFission; 4842 RenderDebugOptions(TC, D, RawTriple, Args, EmitCodeView, CmdArgs, 4843 DebugInfoKind, DwarfFission); 4844 4845 // Add the split debug info name to the command lines here so we 4846 // can propagate it to the backend. 4847 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) && 4848 (TC.getTriple().isOSBinFormatELF() || 4849 TC.getTriple().isOSBinFormatWasm()) && 4850 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) || 4851 isa<BackendJobAction>(JA)); 4852 if (SplitDWARF) { 4853 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output); 4854 CmdArgs.push_back("-split-dwarf-file"); 4855 CmdArgs.push_back(SplitDWARFOut); 4856 if (DwarfFission == DwarfFissionKind::Split) { 4857 CmdArgs.push_back("-split-dwarf-output"); 4858 CmdArgs.push_back(SplitDWARFOut); 4859 } 4860 } 4861 4862 // Pass the linker version in use. 4863 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) { 4864 CmdArgs.push_back("-target-linker-version"); 4865 CmdArgs.push_back(A->getValue()); 4866 } 4867 4868 // Explicitly error on some things we know we don't support and can't just 4869 // ignore. 4870 if (!Args.hasArg(options::OPT_fallow_unsupported)) { 4871 Arg *Unsupported; 4872 if (types::isCXX(InputType) && RawTriple.isOSDarwin() && 4873 TC.getArch() == llvm::Triple::x86) { 4874 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) || 4875 (Unsupported = Args.getLastArg(options::OPT_mkernel))) 4876 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386) 4877 << Unsupported->getOption().getName(); 4878 } 4879 // The faltivec option has been superseded by the maltivec option. 4880 if ((Unsupported = Args.getLastArg(options::OPT_faltivec))) 4881 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec) 4882 << Unsupported->getOption().getName() 4883 << "please use -maltivec and include altivec.h explicitly"; 4884 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec))) 4885 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec) 4886 << Unsupported->getOption().getName() << "please use -mno-altivec"; 4887 } 4888 4889 Args.AddAllArgs(CmdArgs, options::OPT_v); 4890 4891 if (Args.getLastArg(options::OPT_H)) { 4892 CmdArgs.push_back("-H"); 4893 CmdArgs.push_back("-sys-header-deps"); 4894 } 4895 4896 if (D.CCPrintHeaders && !D.CCGenDiagnostics) { 4897 CmdArgs.push_back("-header-include-file"); 4898 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename 4899 : "-"); 4900 CmdArgs.push_back("-sys-header-deps"); 4901 } 4902 Args.AddLastArg(CmdArgs, options::OPT_P); 4903 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout); 4904 4905 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) { 4906 CmdArgs.push_back("-diagnostic-log-file"); 4907 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename 4908 : "-"); 4909 } 4910 4911 // Give the gen diagnostics more chances to succeed, by avoiding intentional 4912 // crashes. 4913 if (D.CCGenDiagnostics) 4914 CmdArgs.push_back("-disable-pragma-debug-crash"); 4915 4916 bool UseSeparateSections = isUseSeparateSections(Triple); 4917 4918 if (Args.hasFlag(options::OPT_ffunction_sections, 4919 options::OPT_fno_function_sections, UseSeparateSections)) { 4920 CmdArgs.push_back("-ffunction-sections"); 4921 } 4922 4923 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) { 4924 if (Triple.isX86() && Triple.isOSBinFormatELF()) { 4925 StringRef Val = A->getValue(); 4926 if (Val != "all" && Val != "labels" && Val != "none" && 4927 !Val.startswith("list=")) 4928 D.Diag(diag::err_drv_invalid_value) 4929 << A->getAsString(Args) << A->getValue(); 4930 else 4931 A->render(Args, CmdArgs); 4932 } else { 4933 D.Diag(diag::err_drv_unsupported_opt_for_target) 4934 << A->getAsString(Args) << TripleStr; 4935 } 4936 } 4937 4938 bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF(); 4939 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections, 4940 UseSeparateSections || HasDefaultDataSections)) { 4941 CmdArgs.push_back("-fdata-sections"); 4942 } 4943 4944 if (!Args.hasFlag(options::OPT_funique_section_names, 4945 options::OPT_fno_unique_section_names, true)) 4946 CmdArgs.push_back("-fno-unique-section-names"); 4947 4948 if (Args.hasFlag(options::OPT_funique_internal_linkage_names, 4949 options::OPT_fno_unique_internal_linkage_names, false)) 4950 CmdArgs.push_back("-funique-internal-linkage-names"); 4951 4952 if (Args.hasFlag(options::OPT_funique_basic_block_section_names, 4953 options::OPT_fno_unique_basic_block_section_names, false)) 4954 CmdArgs.push_back("-funique-basic-block-section-names"); 4955 4956 if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions, 4957 options::OPT_fno_split_machine_functions)) { 4958 // This codegen pass is only available on x86-elf targets. 4959 if (Triple.isX86() && Triple.isOSBinFormatELF()) { 4960 if (A->getOption().matches(options::OPT_fsplit_machine_functions)) 4961 A->render(Args, CmdArgs); 4962 } else { 4963 D.Diag(diag::err_drv_unsupported_opt_for_target) 4964 << A->getAsString(Args) << TripleStr; 4965 } 4966 } 4967 4968 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions, 4969 options::OPT_finstrument_functions_after_inlining, 4970 options::OPT_finstrument_function_entry_bare); 4971 4972 // NVPTX/AMDGCN doesn't support PGO or coverage. There's no runtime support 4973 // for sampling, overhead of call arc collection is way too high and there's 4974 // no way to collect the output. 4975 if (!Triple.isNVPTX() && !Triple.isAMDGCN()) 4976 addPGOAndCoverageFlags(TC, C, D, Output, Args, CmdArgs); 4977 4978 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ); 4979 4980 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled. 4981 if (RawTriple.isPS4CPU() && 4982 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) { 4983 PS4cpu::addProfileRTArgs(TC, Args, CmdArgs); 4984 PS4cpu::addSanitizerArgs(TC, CmdArgs); 4985 } 4986 4987 // Pass options for controlling the default header search paths. 4988 if (Args.hasArg(options::OPT_nostdinc)) { 4989 CmdArgs.push_back("-nostdsysteminc"); 4990 CmdArgs.push_back("-nobuiltininc"); 4991 } else { 4992 if (Args.hasArg(options::OPT_nostdlibinc)) 4993 CmdArgs.push_back("-nostdsysteminc"); 4994 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx); 4995 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc); 4996 } 4997 4998 // Pass the path to compiler resource files. 4999 CmdArgs.push_back("-resource-dir"); 5000 CmdArgs.push_back(D.ResourceDir.c_str()); 5001 5002 Args.AddLastArg(CmdArgs, options::OPT_working_directory); 5003 5004 RenderARCMigrateToolOptions(D, Args, CmdArgs); 5005 5006 // Add preprocessing options like -I, -D, etc. if we are using the 5007 // preprocessor. 5008 // 5009 // FIXME: Support -fpreprocessed 5010 if (types::getPreprocessedType(InputType) != types::TY_INVALID) 5011 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs); 5012 5013 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes 5014 // that "The compiler can only warn and ignore the option if not recognized". 5015 // When building with ccache, it will pass -D options to clang even on 5016 // preprocessed inputs and configure concludes that -fPIC is not supported. 5017 Args.ClaimAllArgs(options::OPT_D); 5018 5019 // Manually translate -O4 to -O3; let clang reject others. 5020 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 5021 if (A->getOption().matches(options::OPT_O4)) { 5022 CmdArgs.push_back("-O3"); 5023 D.Diag(diag::warn_O4_is_O3); 5024 } else { 5025 A->render(Args, CmdArgs); 5026 } 5027 } 5028 5029 // Warn about ignored options to clang. 5030 for (const Arg *A : 5031 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) { 5032 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args); 5033 A->claim(); 5034 } 5035 5036 for (const Arg *A : 5037 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) { 5038 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args); 5039 A->claim(); 5040 } 5041 5042 claimNoWarnArgs(Args); 5043 5044 Args.AddAllArgs(CmdArgs, options::OPT_R_Group); 5045 5046 Args.AddAllArgs(CmdArgs, options::OPT_W_Group); 5047 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false)) 5048 CmdArgs.push_back("-pedantic"); 5049 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors); 5050 Args.AddLastArg(CmdArgs, options::OPT_w); 5051 5052 // Fixed point flags 5053 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point, 5054 /*Default=*/false)) 5055 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point); 5056 5057 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi} 5058 // (-ansi is equivalent to -std=c89 or -std=c++98). 5059 // 5060 // If a std is supplied, only add -trigraphs if it follows the 5061 // option. 5062 bool ImplyVCPPCXXVer = false; 5063 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi); 5064 if (Std) { 5065 if (Std->getOption().matches(options::OPT_ansi)) 5066 if (types::isCXX(InputType)) 5067 CmdArgs.push_back("-std=c++98"); 5068 else 5069 CmdArgs.push_back("-std=c89"); 5070 else 5071 Std->render(Args, CmdArgs); 5072 5073 // If -f(no-)trigraphs appears after the language standard flag, honor it. 5074 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi, 5075 options::OPT_ftrigraphs, 5076 options::OPT_fno_trigraphs)) 5077 if (A != Std) 5078 A->render(Args, CmdArgs); 5079 } else { 5080 // Honor -std-default. 5081 // 5082 // FIXME: Clang doesn't correctly handle -std= when the input language 5083 // doesn't match. For the time being just ignore this for C++ inputs; 5084 // eventually we want to do all the standard defaulting here instead of 5085 // splitting it between the driver and clang -cc1. 5086 if (!types::isCXX(InputType)) 5087 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=", 5088 /*Joined=*/true); 5089 else if (IsWindowsMSVC) 5090 ImplyVCPPCXXVer = true; 5091 5092 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs, 5093 options::OPT_fno_trigraphs); 5094 5095 // HIP headers has minimum C++ standard requirements. Therefore set the 5096 // default language standard. 5097 if (IsHIP) 5098 CmdArgs.push_back(IsWindowsMSVC ? "-std=c++14" : "-std=c++11"); 5099 } 5100 5101 // GCC's behavior for -Wwrite-strings is a bit strange: 5102 // * In C, this "warning flag" changes the types of string literals from 5103 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning 5104 // for the discarded qualifier. 5105 // * In C++, this is just a normal warning flag. 5106 // 5107 // Implementing this warning correctly in C is hard, so we follow GCC's 5108 // behavior for now. FIXME: Directly diagnose uses of a string literal as 5109 // a non-const char* in C, rather than using this crude hack. 5110 if (!types::isCXX(InputType)) { 5111 // FIXME: This should behave just like a warning flag, and thus should also 5112 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on. 5113 Arg *WriteStrings = 5114 Args.getLastArg(options::OPT_Wwrite_strings, 5115 options::OPT_Wno_write_strings, options::OPT_w); 5116 if (WriteStrings && 5117 WriteStrings->getOption().matches(options::OPT_Wwrite_strings)) 5118 CmdArgs.push_back("-fconst-strings"); 5119 } 5120 5121 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active 5122 // during C++ compilation, which it is by default. GCC keeps this define even 5123 // in the presence of '-w', match this behavior bug-for-bug. 5124 if (types::isCXX(InputType) && 5125 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated, 5126 true)) { 5127 CmdArgs.push_back("-fdeprecated-macro"); 5128 } 5129 5130 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'. 5131 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) { 5132 if (Asm->getOption().matches(options::OPT_fasm)) 5133 CmdArgs.push_back("-fgnu-keywords"); 5134 else 5135 CmdArgs.push_back("-fno-gnu-keywords"); 5136 } 5137 5138 if (ShouldDisableDwarfDirectory(Args, TC)) 5139 CmdArgs.push_back("-fno-dwarf-directory-asm"); 5140 5141 if (!ShouldEnableAutolink(Args, TC, JA)) 5142 CmdArgs.push_back("-fno-autolink"); 5143 5144 // Add in -fdebug-compilation-dir if necessary. 5145 addDebugCompDirArg(Args, CmdArgs, D.getVFS()); 5146 5147 addDebugPrefixMapArg(D, Args, CmdArgs); 5148 5149 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_, 5150 options::OPT_ftemplate_depth_EQ)) { 5151 CmdArgs.push_back("-ftemplate-depth"); 5152 CmdArgs.push_back(A->getValue()); 5153 } 5154 5155 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) { 5156 CmdArgs.push_back("-foperator-arrow-depth"); 5157 CmdArgs.push_back(A->getValue()); 5158 } 5159 5160 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) { 5161 CmdArgs.push_back("-fconstexpr-depth"); 5162 CmdArgs.push_back(A->getValue()); 5163 } 5164 5165 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) { 5166 CmdArgs.push_back("-fconstexpr-steps"); 5167 CmdArgs.push_back(A->getValue()); 5168 } 5169 5170 if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter)) 5171 CmdArgs.push_back("-fexperimental-new-constant-interpreter"); 5172 5173 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) { 5174 CmdArgs.push_back("-fbracket-depth"); 5175 CmdArgs.push_back(A->getValue()); 5176 } 5177 5178 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ, 5179 options::OPT_Wlarge_by_value_copy_def)) { 5180 if (A->getNumValues()) { 5181 StringRef bytes = A->getValue(); 5182 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes)); 5183 } else 5184 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value 5185 } 5186 5187 if (Args.hasArg(options::OPT_relocatable_pch)) 5188 CmdArgs.push_back("-relocatable-pch"); 5189 5190 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) { 5191 static const char *kCFABIs[] = { 5192 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1", 5193 }; 5194 5195 if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs)) 5196 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue(); 5197 else 5198 A->render(Args, CmdArgs); 5199 } 5200 5201 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) { 5202 CmdArgs.push_back("-fconstant-string-class"); 5203 CmdArgs.push_back(A->getValue()); 5204 } 5205 5206 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) { 5207 CmdArgs.push_back("-ftabstop"); 5208 CmdArgs.push_back(A->getValue()); 5209 } 5210 5211 if (Args.hasFlag(options::OPT_fstack_size_section, 5212 options::OPT_fno_stack_size_section, RawTriple.isPS4())) 5213 CmdArgs.push_back("-fstack-size-section"); 5214 5215 CmdArgs.push_back("-ferror-limit"); 5216 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ)) 5217 CmdArgs.push_back(A->getValue()); 5218 else 5219 CmdArgs.push_back("19"); 5220 5221 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) { 5222 CmdArgs.push_back("-fmacro-backtrace-limit"); 5223 CmdArgs.push_back(A->getValue()); 5224 } 5225 5226 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) { 5227 CmdArgs.push_back("-ftemplate-backtrace-limit"); 5228 CmdArgs.push_back(A->getValue()); 5229 } 5230 5231 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) { 5232 CmdArgs.push_back("-fconstexpr-backtrace-limit"); 5233 CmdArgs.push_back(A->getValue()); 5234 } 5235 5236 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) { 5237 CmdArgs.push_back("-fspell-checking-limit"); 5238 CmdArgs.push_back(A->getValue()); 5239 } 5240 5241 // Pass -fmessage-length=. 5242 unsigned MessageLength = 0; 5243 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) { 5244 StringRef V(A->getValue()); 5245 if (V.getAsInteger(0, MessageLength)) 5246 D.Diag(diag::err_drv_invalid_argument_to_option) 5247 << V << A->getOption().getName(); 5248 } else { 5249 // If -fmessage-length=N was not specified, determine whether this is a 5250 // terminal and, if so, implicitly define -fmessage-length appropriately. 5251 MessageLength = llvm::sys::Process::StandardErrColumns(); 5252 } 5253 if (MessageLength != 0) 5254 CmdArgs.push_back( 5255 Args.MakeArgString("-fmessage-length=" + Twine(MessageLength))); 5256 5257 // -fvisibility= and -fvisibility-ms-compat are of a piece. 5258 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ, 5259 options::OPT_fvisibility_ms_compat)) { 5260 if (A->getOption().matches(options::OPT_fvisibility_EQ)) { 5261 CmdArgs.push_back("-fvisibility"); 5262 CmdArgs.push_back(A->getValue()); 5263 } else { 5264 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat)); 5265 CmdArgs.push_back("-fvisibility"); 5266 CmdArgs.push_back("hidden"); 5267 CmdArgs.push_back("-ftype-visibility"); 5268 CmdArgs.push_back("default"); 5269 } 5270 } 5271 5272 if (const Arg *A = Args.getLastArg(options::OPT_mignore_xcoff_visibility)) { 5273 if (Triple.isOSAIX()) 5274 CmdArgs.push_back("-mignore-xcoff-visibility"); 5275 else 5276 D.Diag(diag::err_drv_unsupported_opt_for_target) 5277 << A->getAsString(Args) << TripleStr; 5278 } 5279 5280 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden); 5281 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var, 5282 options::OPT_fno_visibility_inlines_hidden_static_local_var); 5283 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden); 5284 5285 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ); 5286 5287 // Forward -f (flag) options which we can pass directly. 5288 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls); 5289 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions); 5290 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs); 5291 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names); 5292 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls, 5293 options::OPT_fno_emulated_tls); 5294 5295 // AltiVec-like language extensions aren't relevant for assembling. 5296 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) 5297 Args.AddLastArg(CmdArgs, options::OPT_fzvector); 5298 5299 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree); 5300 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type); 5301 5302 // Forward flags for OpenMP. We don't do this if the current action is an 5303 // device offloading action other than OpenMP. 5304 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ, 5305 options::OPT_fno_openmp, false) && 5306 (JA.isDeviceOffloading(Action::OFK_None) || 5307 JA.isDeviceOffloading(Action::OFK_OpenMP))) { 5308 switch (D.getOpenMPRuntime(Args)) { 5309 case Driver::OMPRT_OMP: 5310 case Driver::OMPRT_IOMP5: 5311 // Clang can generate useful OpenMP code for these two runtime libraries. 5312 CmdArgs.push_back("-fopenmp"); 5313 5314 // If no option regarding the use of TLS in OpenMP codegeneration is 5315 // given, decide a default based on the target. Otherwise rely on the 5316 // options and pass the right information to the frontend. 5317 if (!Args.hasFlag(options::OPT_fopenmp_use_tls, 5318 options::OPT_fnoopenmp_use_tls, /*Default=*/true)) 5319 CmdArgs.push_back("-fnoopenmp-use-tls"); 5320 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd, 5321 options::OPT_fno_openmp_simd); 5322 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder); 5323 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ); 5324 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ); 5325 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ); 5326 Args.AddAllArgs(CmdArgs, 5327 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ); 5328 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse, 5329 options::OPT_fno_openmp_optimistic_collapse, 5330 /*Default=*/false)) 5331 CmdArgs.push_back("-fopenmp-optimistic-collapse"); 5332 5333 // When in OpenMP offloading mode with NVPTX target, forward 5334 // cuda-mode flag 5335 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode, 5336 options::OPT_fno_openmp_cuda_mode, /*Default=*/false)) 5337 CmdArgs.push_back("-fopenmp-cuda-mode"); 5338 5339 // When in OpenMP offloading mode with NVPTX target, forward 5340 // cuda-parallel-target-regions flag 5341 if (Args.hasFlag(options::OPT_fopenmp_cuda_parallel_target_regions, 5342 options::OPT_fno_openmp_cuda_parallel_target_regions, 5343 /*Default=*/true)) 5344 CmdArgs.push_back("-fopenmp-cuda-parallel-target-regions"); 5345 5346 // When in OpenMP offloading mode with NVPTX target, check if full runtime 5347 // is required. 5348 if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime, 5349 options::OPT_fno_openmp_cuda_force_full_runtime, 5350 /*Default=*/false)) 5351 CmdArgs.push_back("-fopenmp-cuda-force-full-runtime"); 5352 break; 5353 default: 5354 // By default, if Clang doesn't know how to generate useful OpenMP code 5355 // for a specific runtime library, we just don't pass the '-fopenmp' flag 5356 // down to the actual compilation. 5357 // FIXME: It would be better to have a mode which *only* omits IR 5358 // generation based on the OpenMP support so that we get consistent 5359 // semantic analysis, etc. 5360 break; 5361 } 5362 } else { 5363 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd, 5364 options::OPT_fno_openmp_simd); 5365 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ); 5366 } 5367 5368 const SanitizerArgs &Sanitize = TC.getSanitizerArgs(); 5369 Sanitize.addArgs(TC, Args, CmdArgs, InputType); 5370 5371 const XRayArgs &XRay = TC.getXRayArgs(); 5372 XRay.addArgs(TC, Args, CmdArgs, InputType); 5373 5374 if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) { 5375 StringRef S0 = A->getValue(), S = S0; 5376 unsigned Size, Offset = 0; 5377 if (!Triple.isAArch64() && Triple.getArch() != llvm::Triple::x86 && 5378 Triple.getArch() != llvm::Triple::x86_64) 5379 D.Diag(diag::err_drv_unsupported_opt_for_target) 5380 << A->getAsString(Args) << TripleStr; 5381 else if (S.consumeInteger(10, Size) || 5382 (!S.empty() && (!S.consume_front(",") || 5383 S.consumeInteger(10, Offset) || !S.empty()))) 5384 D.Diag(diag::err_drv_invalid_argument_to_option) 5385 << S0 << A->getOption().getName(); 5386 else if (Size < Offset) 5387 D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument); 5388 else { 5389 CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size))); 5390 CmdArgs.push_back(Args.MakeArgString( 5391 "-fpatchable-function-entry-offset=" + Twine(Offset))); 5392 } 5393 } 5394 5395 if (TC.SupportsProfiling()) { 5396 Args.AddLastArg(CmdArgs, options::OPT_pg); 5397 5398 llvm::Triple::ArchType Arch = TC.getArch(); 5399 if (Arg *A = Args.getLastArg(options::OPT_mfentry)) { 5400 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86()) 5401 A->render(Args, CmdArgs); 5402 else 5403 D.Diag(diag::err_drv_unsupported_opt_for_target) 5404 << A->getAsString(Args) << TripleStr; 5405 } 5406 if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) { 5407 if (Arch == llvm::Triple::systemz) 5408 A->render(Args, CmdArgs); 5409 else 5410 D.Diag(diag::err_drv_unsupported_opt_for_target) 5411 << A->getAsString(Args) << TripleStr; 5412 } 5413 if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) { 5414 if (Arch == llvm::Triple::systemz) 5415 A->render(Args, CmdArgs); 5416 else 5417 D.Diag(diag::err_drv_unsupported_opt_for_target) 5418 << A->getAsString(Args) << TripleStr; 5419 } 5420 } 5421 5422 if (Args.getLastArg(options::OPT_fapple_kext) || 5423 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType))) 5424 CmdArgs.push_back("-fapple-kext"); 5425 5426 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ); 5427 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch); 5428 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info); 5429 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits); 5430 Args.AddLastArg(CmdArgs, options::OPT_ftime_report); 5431 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace); 5432 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ); 5433 Args.AddLastArg(CmdArgs, options::OPT_ftrapv); 5434 Args.AddLastArg(CmdArgs, options::OPT_malign_double); 5435 Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file); 5436 5437 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) { 5438 CmdArgs.push_back("-ftrapv-handler"); 5439 CmdArgs.push_back(A->getValue()); 5440 } 5441 5442 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ); 5443 5444 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but 5445 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv. 5446 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) { 5447 if (A->getOption().matches(options::OPT_fwrapv)) 5448 CmdArgs.push_back("-fwrapv"); 5449 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow, 5450 options::OPT_fno_strict_overflow)) { 5451 if (A->getOption().matches(options::OPT_fno_strict_overflow)) 5452 CmdArgs.push_back("-fwrapv"); 5453 } 5454 5455 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops, 5456 options::OPT_fno_reroll_loops)) 5457 if (A->getOption().matches(options::OPT_freroll_loops)) 5458 CmdArgs.push_back("-freroll-loops"); 5459 5460 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings); 5461 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops, 5462 options::OPT_fno_unroll_loops); 5463 5464 Args.AddLastArg(CmdArgs, options::OPT_pthread); 5465 5466 if (Args.hasFlag(options::OPT_mspeculative_load_hardening, 5467 options::OPT_mno_speculative_load_hardening, false)) 5468 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening")); 5469 5470 RenderSSPOptions(TC, Args, CmdArgs, KernelOrKext); 5471 RenderSCPOptions(TC, Args, CmdArgs); 5472 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs); 5473 5474 // Translate -mstackrealign 5475 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign, 5476 false)) 5477 CmdArgs.push_back(Args.MakeArgString("-mstackrealign")); 5478 5479 if (Args.hasArg(options::OPT_mstack_alignment)) { 5480 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment); 5481 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment)); 5482 } 5483 5484 if (Args.hasArg(options::OPT_mstack_probe_size)) { 5485 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size); 5486 5487 if (!Size.empty()) 5488 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size)); 5489 else 5490 CmdArgs.push_back("-mstack-probe-size=0"); 5491 } 5492 5493 if (!Args.hasFlag(options::OPT_mstack_arg_probe, 5494 options::OPT_mno_stack_arg_probe, true)) 5495 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe")); 5496 5497 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it, 5498 options::OPT_mno_restrict_it)) { 5499 if (A->getOption().matches(options::OPT_mrestrict_it)) { 5500 CmdArgs.push_back("-mllvm"); 5501 CmdArgs.push_back("-arm-restrict-it"); 5502 } else { 5503 CmdArgs.push_back("-mllvm"); 5504 CmdArgs.push_back("-arm-no-restrict-it"); 5505 } 5506 } else if (Triple.isOSWindows() && 5507 (Triple.getArch() == llvm::Triple::arm || 5508 Triple.getArch() == llvm::Triple::thumb)) { 5509 // Windows on ARM expects restricted IT blocks 5510 CmdArgs.push_back("-mllvm"); 5511 CmdArgs.push_back("-arm-restrict-it"); 5512 } 5513 5514 // Forward -cl options to -cc1 5515 RenderOpenCLOptions(Args, CmdArgs); 5516 5517 if (IsHIP) { 5518 if (Args.hasFlag(options::OPT_fhip_new_launch_api, 5519 options::OPT_fno_hip_new_launch_api, true)) 5520 CmdArgs.push_back("-fhip-new-launch-api"); 5521 if (Args.hasFlag(options::OPT_fgpu_allow_device_init, 5522 options::OPT_fno_gpu_allow_device_init, false)) 5523 CmdArgs.push_back("-fgpu-allow-device-init"); 5524 } 5525 5526 if (IsCuda || IsHIP) { 5527 if (Args.hasFlag(options::OPT_fgpu_defer_diag, 5528 options::OPT_fno_gpu_defer_diag, false)) 5529 CmdArgs.push_back("-fgpu-defer-diag"); 5530 } 5531 5532 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) { 5533 CmdArgs.push_back( 5534 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue())); 5535 } 5536 5537 // Forward -f options with positive and negative forms; we translate 5538 // these by hand. 5539 if (Arg *A = getLastProfileSampleUseArg(Args)) { 5540 auto *PGOArg = Args.getLastArg( 5541 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ, 5542 options::OPT_fcs_profile_generate, options::OPT_fcs_profile_generate_EQ, 5543 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ); 5544 if (PGOArg) 5545 D.Diag(diag::err_drv_argument_not_allowed_with) 5546 << "SampleUse with PGO options"; 5547 5548 StringRef fname = A->getValue(); 5549 if (!llvm::sys::fs::exists(fname)) 5550 D.Diag(diag::err_drv_no_such_file) << fname; 5551 else 5552 A->render(Args, CmdArgs); 5553 } 5554 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ); 5555 5556 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs); 5557 5558 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new, 5559 options::OPT_fno_assume_sane_operator_new)) 5560 CmdArgs.push_back("-fno-assume-sane-operator-new"); 5561 5562 // -fblocks=0 is default. 5563 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks, 5564 TC.IsBlocksDefault()) || 5565 (Args.hasArg(options::OPT_fgnu_runtime) && 5566 Args.hasArg(options::OPT_fobjc_nonfragile_abi) && 5567 !Args.hasArg(options::OPT_fno_blocks))) { 5568 CmdArgs.push_back("-fblocks"); 5569 5570 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime()) 5571 CmdArgs.push_back("-fblocks-runtime-optional"); 5572 } 5573 5574 // -fencode-extended-block-signature=1 is default. 5575 if (TC.IsEncodeExtendedBlockSignatureDefault()) 5576 CmdArgs.push_back("-fencode-extended-block-signature"); 5577 5578 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts, 5579 false) && 5580 types::isCXX(InputType)) { 5581 CmdArgs.push_back("-fcoroutines-ts"); 5582 } 5583 5584 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes, 5585 options::OPT_fno_double_square_bracket_attributes); 5586 5587 // -faccess-control is default. 5588 if (Args.hasFlag(options::OPT_fno_access_control, 5589 options::OPT_faccess_control, false)) 5590 CmdArgs.push_back("-fno-access-control"); 5591 5592 // -felide-constructors is the default. 5593 if (Args.hasFlag(options::OPT_fno_elide_constructors, 5594 options::OPT_felide_constructors, false)) 5595 CmdArgs.push_back("-fno-elide-constructors"); 5596 5597 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode(); 5598 5599 if (KernelOrKext || (types::isCXX(InputType) && 5600 (RTTIMode == ToolChain::RM_Disabled))) 5601 CmdArgs.push_back("-fno-rtti"); 5602 5603 // -fshort-enums=0 is default for all architectures except Hexagon. 5604 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums, 5605 TC.getArch() == llvm::Triple::hexagon)) 5606 CmdArgs.push_back("-fshort-enums"); 5607 5608 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs); 5609 5610 // -fuse-cxa-atexit is default. 5611 if (!Args.hasFlag( 5612 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit, 5613 !RawTriple.isOSAIX() && !RawTriple.isOSWindows() && 5614 TC.getArch() != llvm::Triple::xcore && 5615 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) || 5616 RawTriple.hasEnvironment())) || 5617 KernelOrKext) 5618 CmdArgs.push_back("-fno-use-cxa-atexit"); 5619 5620 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit, 5621 options::OPT_fno_register_global_dtors_with_atexit, 5622 RawTriple.isOSDarwin() && !KernelOrKext)) 5623 CmdArgs.push_back("-fregister-global-dtors-with-atexit"); 5624 5625 // -fno-use-line-directives is default. 5626 if (Args.hasFlag(options::OPT_fuse_line_directives, 5627 options::OPT_fno_use_line_directives, false)) 5628 CmdArgs.push_back("-fuse-line-directives"); 5629 5630 // -fms-extensions=0 is default. 5631 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions, 5632 IsWindowsMSVC)) 5633 CmdArgs.push_back("-fms-extensions"); 5634 5635 // -fms-compatibility=0 is default. 5636 bool IsMSVCCompat = Args.hasFlag( 5637 options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility, 5638 (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions, 5639 options::OPT_fno_ms_extensions, true))); 5640 if (IsMSVCCompat) 5641 CmdArgs.push_back("-fms-compatibility"); 5642 5643 // Handle -fgcc-version, if present. 5644 VersionTuple GNUCVer; 5645 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) { 5646 // Check that the version has 1 to 3 components and the minor and patch 5647 // versions fit in two decimal digits. 5648 StringRef Val = A->getValue(); 5649 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable. 5650 bool Invalid = GNUCVer.tryParse(Val); 5651 unsigned Minor = GNUCVer.getMinor().getValueOr(0); 5652 unsigned Patch = GNUCVer.getSubminor().getValueOr(0); 5653 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) { 5654 D.Diag(diag::err_drv_invalid_value) 5655 << A->getAsString(Args) << A->getValue(); 5656 } 5657 } else if (!IsMSVCCompat) { 5658 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect. 5659 GNUCVer = VersionTuple(4, 2, 1); 5660 } 5661 if (!GNUCVer.empty()) { 5662 CmdArgs.push_back( 5663 Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString())); 5664 } 5665 5666 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args); 5667 if (!MSVT.empty()) 5668 CmdArgs.push_back( 5669 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString())); 5670 5671 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19; 5672 if (ImplyVCPPCXXVer) { 5673 StringRef LanguageStandard; 5674 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) { 5675 Std = StdArg; 5676 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue()) 5677 .Case("c++14", "-std=c++14") 5678 .Case("c++17", "-std=c++17") 5679 .Case("c++latest", "-std=c++20") 5680 .Default(""); 5681 if (LanguageStandard.empty()) 5682 D.Diag(clang::diag::warn_drv_unused_argument) 5683 << StdArg->getAsString(Args); 5684 } 5685 5686 if (LanguageStandard.empty()) { 5687 if (IsMSVC2015Compatible) 5688 LanguageStandard = "-std=c++14"; 5689 else 5690 LanguageStandard = "-std=c++11"; 5691 } 5692 5693 CmdArgs.push_back(LanguageStandard.data()); 5694 } 5695 5696 // -fno-borland-extensions is default. 5697 if (Args.hasFlag(options::OPT_fborland_extensions, 5698 options::OPT_fno_borland_extensions, false)) 5699 CmdArgs.push_back("-fborland-extensions"); 5700 5701 // -fno-declspec is default, except for PS4. 5702 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec, 5703 RawTriple.isPS4())) 5704 CmdArgs.push_back("-fdeclspec"); 5705 else if (Args.hasArg(options::OPT_fno_declspec)) 5706 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec. 5707 5708 // -fthreadsafe-static is default, except for MSVC compatibility versions less 5709 // than 19. 5710 if (!Args.hasFlag(options::OPT_fthreadsafe_statics, 5711 options::OPT_fno_threadsafe_statics, 5712 !IsWindowsMSVC || IsMSVC2015Compatible)) 5713 CmdArgs.push_back("-fno-threadsafe-statics"); 5714 5715 // -fno-delayed-template-parsing is default, except when targeting MSVC. 5716 // Many old Windows SDK versions require this to parse. 5717 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their 5718 // compiler. We should be able to disable this by default at some point. 5719 if (Args.hasFlag(options::OPT_fdelayed_template_parsing, 5720 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC)) 5721 CmdArgs.push_back("-fdelayed-template-parsing"); 5722 5723 // -fgnu-keywords default varies depending on language; only pass if 5724 // specified. 5725 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords, 5726 options::OPT_fno_gnu_keywords); 5727 5728 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline, 5729 false)) 5730 CmdArgs.push_back("-fgnu89-inline"); 5731 5732 if (Args.hasArg(options::OPT_fno_inline)) 5733 CmdArgs.push_back("-fno-inline"); 5734 5735 Args.AddLastArg(CmdArgs, options::OPT_finline_functions, 5736 options::OPT_finline_hint_functions, 5737 options::OPT_fno_inline_functions); 5738 5739 // FIXME: Find a better way to determine whether the language has modules 5740 // support by default, or just assume that all languages do. 5741 bool HaveModules = 5742 Std && (Std->containsValue("c++2a") || Std->containsValue("c++20") || 5743 Std->containsValue("c++latest")); 5744 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules); 5745 5746 if (Args.hasFlag(options::OPT_fpch_validate_input_files_content, 5747 options::OPT_fno_pch_validate_input_files_content, false)) 5748 CmdArgs.push_back("-fvalidate-ast-input-files-content"); 5749 if (Args.hasFlag(options::OPT_fpch_instantiate_templates, 5750 options::OPT_fno_pch_instantiate_templates, false)) 5751 CmdArgs.push_back("-fpch-instantiate-templates"); 5752 if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen, 5753 false)) 5754 CmdArgs.push_back("-fmodules-codegen"); 5755 if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo, 5756 false)) 5757 CmdArgs.push_back("-fmodules-debuginfo"); 5758 5759 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager, 5760 options::OPT_fno_experimental_new_pass_manager); 5761 5762 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind); 5763 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None, 5764 Input, CmdArgs); 5765 5766 if (Args.hasFlag(options::OPT_fapplication_extension, 5767 options::OPT_fno_application_extension, false)) 5768 CmdArgs.push_back("-fapplication-extension"); 5769 5770 // Handle GCC-style exception args. 5771 if (!C.getDriver().IsCLMode()) 5772 addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs); 5773 5774 // Handle exception personalities 5775 Arg *A = Args.getLastArg( 5776 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions, 5777 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions); 5778 if (A) { 5779 const Option &Opt = A->getOption(); 5780 if (Opt.matches(options::OPT_fsjlj_exceptions)) 5781 CmdArgs.push_back("-fsjlj-exceptions"); 5782 if (Opt.matches(options::OPT_fseh_exceptions)) 5783 CmdArgs.push_back("-fseh-exceptions"); 5784 if (Opt.matches(options::OPT_fdwarf_exceptions)) 5785 CmdArgs.push_back("-fdwarf-exceptions"); 5786 if (Opt.matches(options::OPT_fwasm_exceptions)) 5787 CmdArgs.push_back("-fwasm-exceptions"); 5788 } else { 5789 switch (TC.GetExceptionModel(Args)) { 5790 default: 5791 break; 5792 case llvm::ExceptionHandling::DwarfCFI: 5793 CmdArgs.push_back("-fdwarf-exceptions"); 5794 break; 5795 case llvm::ExceptionHandling::SjLj: 5796 CmdArgs.push_back("-fsjlj-exceptions"); 5797 break; 5798 case llvm::ExceptionHandling::WinEH: 5799 CmdArgs.push_back("-fseh-exceptions"); 5800 break; 5801 } 5802 } 5803 5804 // C++ "sane" operator new. 5805 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new, 5806 options::OPT_fno_assume_sane_operator_new)) 5807 CmdArgs.push_back("-fno-assume-sane-operator-new"); 5808 5809 // -frelaxed-template-template-args is off by default, as it is a severe 5810 // breaking change until a corresponding change to template partial ordering 5811 // is provided. 5812 if (Args.hasFlag(options::OPT_frelaxed_template_template_args, 5813 options::OPT_fno_relaxed_template_template_args, false)) 5814 CmdArgs.push_back("-frelaxed-template-template-args"); 5815 5816 // -fsized-deallocation is off by default, as it is an ABI-breaking change for 5817 // most platforms. 5818 if (Args.hasFlag(options::OPT_fsized_deallocation, 5819 options::OPT_fno_sized_deallocation, false)) 5820 CmdArgs.push_back("-fsized-deallocation"); 5821 5822 // -faligned-allocation is on by default in C++17 onwards and otherwise off 5823 // by default. 5824 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation, 5825 options::OPT_fno_aligned_allocation, 5826 options::OPT_faligned_new_EQ)) { 5827 if (A->getOption().matches(options::OPT_fno_aligned_allocation)) 5828 CmdArgs.push_back("-fno-aligned-allocation"); 5829 else 5830 CmdArgs.push_back("-faligned-allocation"); 5831 } 5832 5833 // The default new alignment can be specified using a dedicated option or via 5834 // a GCC-compatible option that also turns on aligned allocation. 5835 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ, 5836 options::OPT_faligned_new_EQ)) 5837 CmdArgs.push_back( 5838 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue())); 5839 5840 // -fconstant-cfstrings is default, and may be subject to argument translation 5841 // on Darwin. 5842 if (!Args.hasFlag(options::OPT_fconstant_cfstrings, 5843 options::OPT_fno_constant_cfstrings) || 5844 !Args.hasFlag(options::OPT_mconstant_cfstrings, 5845 options::OPT_mno_constant_cfstrings)) 5846 CmdArgs.push_back("-fno-constant-cfstrings"); 5847 5848 // -fno-pascal-strings is default, only pass non-default. 5849 if (Args.hasFlag(options::OPT_fpascal_strings, 5850 options::OPT_fno_pascal_strings, false)) 5851 CmdArgs.push_back("-fpascal-strings"); 5852 5853 // Honor -fpack-struct= and -fpack-struct, if given. Note that 5854 // -fno-pack-struct doesn't apply to -fpack-struct=. 5855 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) { 5856 std::string PackStructStr = "-fpack-struct="; 5857 PackStructStr += A->getValue(); 5858 CmdArgs.push_back(Args.MakeArgString(PackStructStr)); 5859 } else if (Args.hasFlag(options::OPT_fpack_struct, 5860 options::OPT_fno_pack_struct, false)) { 5861 CmdArgs.push_back("-fpack-struct=1"); 5862 } 5863 5864 // Handle -fmax-type-align=N and -fno-type-align 5865 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align); 5866 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) { 5867 if (!SkipMaxTypeAlign) { 5868 std::string MaxTypeAlignStr = "-fmax-type-align="; 5869 MaxTypeAlignStr += A->getValue(); 5870 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr)); 5871 } 5872 } else if (RawTriple.isOSDarwin()) { 5873 if (!SkipMaxTypeAlign) { 5874 std::string MaxTypeAlignStr = "-fmax-type-align=16"; 5875 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr)); 5876 } 5877 } 5878 5879 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true)) 5880 CmdArgs.push_back("-Qn"); 5881 5882 // -fno-common is the default, set -fcommon only when that flag is set. 5883 if (Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common, false)) 5884 CmdArgs.push_back("-fcommon"); 5885 5886 // -fsigned-bitfields is default, and clang doesn't yet support 5887 // -funsigned-bitfields. 5888 if (!Args.hasFlag(options::OPT_fsigned_bitfields, 5889 options::OPT_funsigned_bitfields)) 5890 D.Diag(diag::warn_drv_clang_unsupported) 5891 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args); 5892 5893 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope. 5894 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope)) 5895 D.Diag(diag::err_drv_clang_unsupported) 5896 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args); 5897 5898 // -finput_charset=UTF-8 is default. Reject others 5899 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) { 5900 StringRef value = inputCharset->getValue(); 5901 if (!value.equals_lower("utf-8")) 5902 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args) 5903 << value; 5904 } 5905 5906 // -fexec_charset=UTF-8 is default. Reject others 5907 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) { 5908 StringRef value = execCharset->getValue(); 5909 if (!value.equals_lower("utf-8")) 5910 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args) 5911 << value; 5912 } 5913 5914 RenderDiagnosticsOptions(D, Args, CmdArgs); 5915 5916 // -fno-asm-blocks is default. 5917 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks, 5918 false)) 5919 CmdArgs.push_back("-fasm-blocks"); 5920 5921 // -fgnu-inline-asm is default. 5922 if (!Args.hasFlag(options::OPT_fgnu_inline_asm, 5923 options::OPT_fno_gnu_inline_asm, true)) 5924 CmdArgs.push_back("-fno-gnu-inline-asm"); 5925 5926 // Enable vectorization per default according to the optimization level 5927 // selected. For optimization levels that want vectorization we use the alias 5928 // option to simplify the hasFlag logic. 5929 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false); 5930 OptSpecifier VectorizeAliasOption = 5931 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize; 5932 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption, 5933 options::OPT_fno_vectorize, EnableVec)) 5934 CmdArgs.push_back("-vectorize-loops"); 5935 5936 // -fslp-vectorize is enabled based on the optimization level selected. 5937 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true); 5938 OptSpecifier SLPVectAliasOption = 5939 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize; 5940 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption, 5941 options::OPT_fno_slp_vectorize, EnableSLPVec)) 5942 CmdArgs.push_back("-vectorize-slp"); 5943 5944 ParseMPreferVectorWidth(D, Args, CmdArgs); 5945 5946 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ); 5947 Args.AddLastArg(CmdArgs, 5948 options::OPT_fsanitize_undefined_strip_path_components_EQ); 5949 5950 // -fdollars-in-identifiers default varies depending on platform and 5951 // language; only pass if specified. 5952 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers, 5953 options::OPT_fno_dollars_in_identifiers)) { 5954 if (A->getOption().matches(options::OPT_fdollars_in_identifiers)) 5955 CmdArgs.push_back("-fdollars-in-identifiers"); 5956 else 5957 CmdArgs.push_back("-fno-dollars-in-identifiers"); 5958 } 5959 5960 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for 5961 // practical purposes. 5962 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time, 5963 options::OPT_fno_unit_at_a_time)) { 5964 if (A->getOption().matches(options::OPT_fno_unit_at_a_time)) 5965 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args); 5966 } 5967 5968 if (Args.hasFlag(options::OPT_fapple_pragma_pack, 5969 options::OPT_fno_apple_pragma_pack, false)) 5970 CmdArgs.push_back("-fapple-pragma-pack"); 5971 5972 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags. 5973 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple)) 5974 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA); 5975 5976 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports, 5977 options::OPT_fno_rewrite_imports, false); 5978 if (RewriteImports) 5979 CmdArgs.push_back("-frewrite-imports"); 5980 5981 // Enable rewrite includes if the user's asked for it or if we're generating 5982 // diagnostics. 5983 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be 5984 // nice to enable this when doing a crashdump for modules as well. 5985 if (Args.hasFlag(options::OPT_frewrite_includes, 5986 options::OPT_fno_rewrite_includes, false) || 5987 (C.isForDiagnostics() && !HaveModules)) 5988 CmdArgs.push_back("-frewrite-includes"); 5989 5990 // Only allow -traditional or -traditional-cpp outside in preprocessing modes. 5991 if (Arg *A = Args.getLastArg(options::OPT_traditional, 5992 options::OPT_traditional_cpp)) { 5993 if (isa<PreprocessJobAction>(JA)) 5994 CmdArgs.push_back("-traditional-cpp"); 5995 else 5996 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args); 5997 } 5998 5999 Args.AddLastArg(CmdArgs, options::OPT_dM); 6000 Args.AddLastArg(CmdArgs, options::OPT_dD); 6001 6002 Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ); 6003 6004 // Handle serialized diagnostics. 6005 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) { 6006 CmdArgs.push_back("-serialize-diagnostic-file"); 6007 CmdArgs.push_back(Args.MakeArgString(A->getValue())); 6008 } 6009 6010 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers)) 6011 CmdArgs.push_back("-fretain-comments-from-system-headers"); 6012 6013 // Forward -fcomment-block-commands to -cc1. 6014 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands); 6015 // Forward -fparse-all-comments to -cc1. 6016 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments); 6017 6018 // Turn -fplugin=name.so into -load name.so 6019 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) { 6020 CmdArgs.push_back("-load"); 6021 CmdArgs.push_back(A->getValue()); 6022 A->claim(); 6023 } 6024 6025 // Forward -fpass-plugin=name.so to -cc1. 6026 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) { 6027 CmdArgs.push_back( 6028 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue())); 6029 A->claim(); 6030 } 6031 6032 // Setup statistics file output. 6033 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D); 6034 if (!StatsFile.empty()) 6035 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile)); 6036 6037 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option 6038 // parser. 6039 // -finclude-default-header flag is for preprocessor, 6040 // do not pass it to other cc1 commands when save-temps is enabled 6041 if (C.getDriver().isSaveTempsEnabled() && 6042 !isa<PreprocessJobAction>(JA)) { 6043 for (auto Arg : Args.filtered(options::OPT_Xclang)) { 6044 Arg->claim(); 6045 if (StringRef(Arg->getValue()) != "-finclude-default-header") 6046 CmdArgs.push_back(Arg->getValue()); 6047 } 6048 } 6049 else { 6050 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang); 6051 } 6052 for (const Arg *A : Args.filtered(options::OPT_mllvm)) { 6053 A->claim(); 6054 6055 // We translate this by hand to the -cc1 argument, since nightly test uses 6056 // it and developers have been trained to spell it with -mllvm. Both 6057 // spellings are now deprecated and should be removed. 6058 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") { 6059 CmdArgs.push_back("-disable-llvm-optzns"); 6060 } else { 6061 A->render(Args, CmdArgs); 6062 } 6063 } 6064 6065 // With -save-temps, we want to save the unoptimized bitcode output from the 6066 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated 6067 // by the frontend. 6068 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it 6069 // has slightly different breakdown between stages. 6070 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of 6071 // pristine IR generated by the frontend. Ideally, a new compile action should 6072 // be added so both IR can be captured. 6073 if ((C.getDriver().isSaveTempsEnabled() || 6074 JA.isHostOffloading(Action::OFK_OpenMP)) && 6075 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) && 6076 isa<CompileJobAction>(JA)) 6077 CmdArgs.push_back("-disable-llvm-passes"); 6078 6079 Args.AddAllArgs(CmdArgs, options::OPT_undef); 6080 6081 const char *Exec = D.getClangProgramPath(); 6082 6083 // Optionally embed the -cc1 level arguments into the debug info or a 6084 // section, for build analysis. 6085 // Also record command line arguments into the debug info if 6086 // -grecord-gcc-switches options is set on. 6087 // By default, -gno-record-gcc-switches is set on and no recording. 6088 auto GRecordSwitches = 6089 Args.hasFlag(options::OPT_grecord_command_line, 6090 options::OPT_gno_record_command_line, false); 6091 auto FRecordSwitches = 6092 Args.hasFlag(options::OPT_frecord_command_line, 6093 options::OPT_fno_record_command_line, false); 6094 if (FRecordSwitches && !Triple.isOSBinFormatELF()) 6095 D.Diag(diag::err_drv_unsupported_opt_for_target) 6096 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args) 6097 << TripleStr; 6098 if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) { 6099 ArgStringList OriginalArgs; 6100 for (const auto &Arg : Args) 6101 Arg->render(Args, OriginalArgs); 6102 6103 SmallString<256> Flags; 6104 EscapeSpacesAndBackslashes(Exec, Flags); 6105 for (const char *OriginalArg : OriginalArgs) { 6106 SmallString<128> EscapedArg; 6107 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg); 6108 Flags += " "; 6109 Flags += EscapedArg; 6110 } 6111 auto FlagsArgString = Args.MakeArgString(Flags); 6112 if (TC.UseDwarfDebugFlags() || GRecordSwitches) { 6113 CmdArgs.push_back("-dwarf-debug-flags"); 6114 CmdArgs.push_back(FlagsArgString); 6115 } 6116 if (FRecordSwitches) { 6117 CmdArgs.push_back("-record-command-line"); 6118 CmdArgs.push_back(FlagsArgString); 6119 } 6120 } 6121 6122 // Host-side cuda compilation receives all device-side outputs in a single 6123 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary. 6124 if ((IsCuda || IsHIP) && CudaDeviceInput) { 6125 CmdArgs.push_back("-fcuda-include-gpubinary"); 6126 CmdArgs.push_back(CudaDeviceInput->getFilename()); 6127 if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)) 6128 CmdArgs.push_back("-fgpu-rdc"); 6129 } 6130 6131 if (IsCuda) { 6132 if (Args.hasFlag(options::OPT_fcuda_short_ptr, 6133 options::OPT_fno_cuda_short_ptr, false)) 6134 CmdArgs.push_back("-fcuda-short-ptr"); 6135 } 6136 6137 if (IsHIP) 6138 CmdArgs.push_back("-fcuda-allow-variadic-functions"); 6139 6140 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path 6141 // to specify the result of the compile phase on the host, so the meaningful 6142 // device declarations can be identified. Also, -fopenmp-is-device is passed 6143 // along to tell the frontend that it is generating code for a device, so that 6144 // only the relevant declarations are emitted. 6145 if (IsOpenMPDevice) { 6146 CmdArgs.push_back("-fopenmp-is-device"); 6147 if (OpenMPDeviceInput) { 6148 CmdArgs.push_back("-fopenmp-host-ir-file-path"); 6149 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename())); 6150 } 6151 } 6152 6153 HandleAmdgcnLegacyOptions(D, Args, CmdArgs); 6154 6155 // For all the host OpenMP offloading compile jobs we need to pass the targets 6156 // information using -fopenmp-targets= option. 6157 if (JA.isHostOffloading(Action::OFK_OpenMP)) { 6158 SmallString<128> TargetInfo("-fopenmp-targets="); 6159 6160 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ); 6161 assert(Tgts && Tgts->getNumValues() && 6162 "OpenMP offloading has to have targets specified."); 6163 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) { 6164 if (i) 6165 TargetInfo += ','; 6166 // We need to get the string from the triple because it may be not exactly 6167 // the same as the one we get directly from the arguments. 6168 llvm::Triple T(Tgts->getValue(i)); 6169 TargetInfo += T.getTriple(); 6170 } 6171 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str())); 6172 } 6173 6174 bool VirtualFunctionElimination = 6175 Args.hasFlag(options::OPT_fvirtual_function_elimination, 6176 options::OPT_fno_virtual_function_elimination, false); 6177 if (VirtualFunctionElimination) { 6178 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO 6179 // in the future). 6180 if (D.getLTOMode() != LTOK_Full) 6181 D.Diag(diag::err_drv_argument_only_allowed_with) 6182 << "-fvirtual-function-elimination" 6183 << "-flto=full"; 6184 6185 CmdArgs.push_back("-fvirtual-function-elimination"); 6186 } 6187 6188 // VFE requires whole-program-vtables, and enables it by default. 6189 bool WholeProgramVTables = Args.hasFlag( 6190 options::OPT_fwhole_program_vtables, 6191 options::OPT_fno_whole_program_vtables, VirtualFunctionElimination); 6192 if (VirtualFunctionElimination && !WholeProgramVTables) { 6193 D.Diag(diag::err_drv_argument_not_allowed_with) 6194 << "-fno-whole-program-vtables" 6195 << "-fvirtual-function-elimination"; 6196 } 6197 6198 if (WholeProgramVTables) { 6199 if (!D.isUsingLTO()) 6200 D.Diag(diag::err_drv_argument_only_allowed_with) 6201 << "-fwhole-program-vtables" 6202 << "-flto"; 6203 CmdArgs.push_back("-fwhole-program-vtables"); 6204 } 6205 6206 bool DefaultsSplitLTOUnit = 6207 (WholeProgramVTables || Sanitize.needsLTO()) && 6208 (D.getLTOMode() == LTOK_Full || TC.canSplitThinLTOUnit()); 6209 bool SplitLTOUnit = 6210 Args.hasFlag(options::OPT_fsplit_lto_unit, 6211 options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit); 6212 if (Sanitize.needsLTO() && !SplitLTOUnit) 6213 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit" 6214 << "-fsanitize=cfi"; 6215 if (SplitLTOUnit) 6216 CmdArgs.push_back("-fsplit-lto-unit"); 6217 6218 if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel, 6219 options::OPT_fno_global_isel)) { 6220 CmdArgs.push_back("-mllvm"); 6221 if (A->getOption().matches(options::OPT_fglobal_isel)) { 6222 CmdArgs.push_back("-global-isel=1"); 6223 6224 // GISel is on by default on AArch64 -O0, so don't bother adding 6225 // the fallback remarks for it. Other combinations will add a warning of 6226 // some kind. 6227 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64; 6228 bool IsOptLevelSupported = false; 6229 6230 Arg *A = Args.getLastArg(options::OPT_O_Group); 6231 if (Triple.getArch() == llvm::Triple::aarch64) { 6232 if (!A || A->getOption().matches(options::OPT_O0)) 6233 IsOptLevelSupported = true; 6234 } 6235 if (!IsArchSupported || !IsOptLevelSupported) { 6236 CmdArgs.push_back("-mllvm"); 6237 CmdArgs.push_back("-global-isel-abort=2"); 6238 6239 if (!IsArchSupported) 6240 D.Diag(diag::warn_drv_global_isel_incomplete) << Triple.getArchName(); 6241 else 6242 D.Diag(diag::warn_drv_global_isel_incomplete_opt); 6243 } 6244 } else { 6245 CmdArgs.push_back("-global-isel=0"); 6246 } 6247 } 6248 6249 if (Args.hasArg(options::OPT_forder_file_instrumentation)) { 6250 CmdArgs.push_back("-forder-file-instrumentation"); 6251 // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is 6252 // on, we need to pass these flags as linker flags and that will be handled 6253 // outside of the compiler. 6254 if (!D.isUsingLTO()) { 6255 CmdArgs.push_back("-mllvm"); 6256 CmdArgs.push_back("-enable-order-file-instrumentation"); 6257 } 6258 } 6259 6260 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128, 6261 options::OPT_fno_force_enable_int128)) { 6262 if (A->getOption().matches(options::OPT_fforce_enable_int128)) 6263 CmdArgs.push_back("-fforce-enable-int128"); 6264 } 6265 6266 if (Args.hasFlag(options::OPT_fkeep_static_consts, 6267 options::OPT_fno_keep_static_consts, false)) 6268 CmdArgs.push_back("-fkeep-static-consts"); 6269 6270 if (Args.hasFlag(options::OPT_fcomplete_member_pointers, 6271 options::OPT_fno_complete_member_pointers, false)) 6272 CmdArgs.push_back("-fcomplete-member-pointers"); 6273 6274 if (!Args.hasFlag(options::OPT_fcxx_static_destructors, 6275 options::OPT_fno_cxx_static_destructors, true)) 6276 CmdArgs.push_back("-fno-c++-static-destructors"); 6277 6278 if (Arg *A = Args.getLastArg(options::OPT_moutline, 6279 options::OPT_mno_outline)) { 6280 if (A->getOption().matches(options::OPT_moutline)) { 6281 // We only support -moutline in AArch64 and ARM targets right now. If 6282 // we're not compiling for these, emit a warning and ignore the flag. 6283 // Otherwise, add the proper mllvm flags. 6284 if (!(Triple.isARM() || Triple.isThumb() || 6285 Triple.getArch() == llvm::Triple::aarch64 || 6286 Triple.getArch() == llvm::Triple::aarch64_32)) { 6287 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName(); 6288 } else { 6289 CmdArgs.push_back("-mllvm"); 6290 CmdArgs.push_back("-enable-machine-outliner"); 6291 } 6292 } else { 6293 // Disable all outlining behaviour. 6294 CmdArgs.push_back("-mllvm"); 6295 CmdArgs.push_back("-enable-machine-outliner=never"); 6296 } 6297 } 6298 6299 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig, 6300 (TC.getTriple().isOSBinFormatELF() || 6301 TC.getTriple().isOSBinFormatCOFF()) && 6302 !TC.getTriple().isPS4() && 6303 !TC.getTriple().isOSNetBSD() && 6304 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() && 6305 !TC.getTriple().isAndroid() && 6306 TC.useIntegratedAs())) 6307 CmdArgs.push_back("-faddrsig"); 6308 6309 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) { 6310 std::string Str = A->getAsString(Args); 6311 if (!TC.getTriple().isOSBinFormatELF()) 6312 D.Diag(diag::err_drv_unsupported_opt_for_target) 6313 << Str << TC.getTripleString(); 6314 CmdArgs.push_back(Args.MakeArgString(Str)); 6315 } 6316 6317 // Add the "-o out -x type src.c" flags last. This is done primarily to make 6318 // the -cc1 command easier to edit when reproducing compiler crashes. 6319 if (Output.getType() == types::TY_Dependencies) { 6320 // Handled with other dependency code. 6321 } else if (Output.isFilename()) { 6322 if (Output.getType() == clang::driver::types::TY_IFS_CPP || 6323 Output.getType() == clang::driver::types::TY_IFS) { 6324 SmallString<128> OutputFilename(Output.getFilename()); 6325 llvm::sys::path::replace_extension(OutputFilename, "ifs"); 6326 CmdArgs.push_back("-o"); 6327 CmdArgs.push_back(Args.MakeArgString(OutputFilename)); 6328 } else { 6329 CmdArgs.push_back("-o"); 6330 CmdArgs.push_back(Output.getFilename()); 6331 } 6332 } else { 6333 assert(Output.isNothing() && "Invalid output."); 6334 } 6335 6336 addDashXForInput(Args, Input, CmdArgs); 6337 6338 ArrayRef<InputInfo> FrontendInputs = Input; 6339 if (IsHeaderModulePrecompile) 6340 FrontendInputs = ModuleHeaderInputs; 6341 else if (Input.isNothing()) 6342 FrontendInputs = {}; 6343 6344 for (const InputInfo &Input : FrontendInputs) { 6345 if (Input.isFilename()) 6346 CmdArgs.push_back(Input.getFilename()); 6347 else 6348 Input.getInputArg().renderAsInput(Args, CmdArgs); 6349 } 6350 6351 // Finally add the compile command to the compilation. 6352 if (Args.hasArg(options::OPT__SLASH_fallback) && 6353 Output.getType() == types::TY_Object && 6354 (InputType == types::TY_C || InputType == types::TY_CXX)) { 6355 auto CLCommand = 6356 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput); 6357 C.addCommand(std::make_unique<FallbackCommand>( 6358 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs, 6359 Output, std::move(CLCommand))); 6360 } else if (Args.hasArg(options::OPT__SLASH_fallback) && 6361 isa<PrecompileJobAction>(JA)) { 6362 // In /fallback builds, run the main compilation even if the pch generation 6363 // fails, so that the main compilation's fallback to cl.exe runs. 6364 C.addCommand(std::make_unique<ForceSuccessCommand>( 6365 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs, 6366 Output)); 6367 } else if (D.CC1Main && !D.CCGenDiagnostics) { 6368 // Invoke the CC1 directly in this process 6369 C.addCommand(std::make_unique<CC1Command>(JA, *this, 6370 ResponseFileSupport::AtFileUTF8(), 6371 Exec, CmdArgs, Inputs, Output)); 6372 } else { 6373 C.addCommand(std::make_unique<Command>(JA, *this, 6374 ResponseFileSupport::AtFileUTF8(), 6375 Exec, CmdArgs, Inputs, Output)); 6376 } 6377 6378 // Make the compile command echo its inputs for /showFilenames. 6379 if (Output.getType() == types::TY_Object && 6380 Args.hasFlag(options::OPT__SLASH_showFilenames, 6381 options::OPT__SLASH_showFilenames_, false)) { 6382 C.getJobs().getJobs().back()->PrintInputFilenames = true; 6383 } 6384 6385 if (Arg *A = Args.getLastArg(options::OPT_pg)) 6386 if (FPKeepKind == CodeGenOptions::FramePointerKind::None && 6387 !Args.hasArg(options::OPT_mfentry)) 6388 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer" 6389 << A->getAsString(Args); 6390 6391 // Claim some arguments which clang supports automatically. 6392 6393 // -fpch-preprocess is used with gcc to add a special marker in the output to 6394 // include the PCH file. 6395 Args.ClaimAllArgs(options::OPT_fpch_preprocess); 6396 6397 // Claim some arguments which clang doesn't support, but we don't 6398 // care to warn the user about. 6399 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group); 6400 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group); 6401 6402 // Disable warnings for clang -E -emit-llvm foo.c 6403 Args.ClaimAllArgs(options::OPT_emit_llvm); 6404 } 6405 6406 Clang::Clang(const ToolChain &TC) 6407 // CAUTION! The first constructor argument ("clang") is not arbitrary, 6408 // as it is for other tools. Some operations on a Tool actually test 6409 // whether that tool is Clang based on the Tool's Name as a string. 6410 : Tool("clang", "clang frontend", TC) {} 6411 6412 Clang::~Clang() {} 6413 6414 /// Add options related to the Objective-C runtime/ABI. 6415 /// 6416 /// Returns true if the runtime is non-fragile. 6417 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args, 6418 const InputInfoList &inputs, 6419 ArgStringList &cmdArgs, 6420 RewriteKind rewriteKind) const { 6421 // Look for the controlling runtime option. 6422 Arg *runtimeArg = 6423 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime, 6424 options::OPT_fobjc_runtime_EQ); 6425 6426 // Just forward -fobjc-runtime= to the frontend. This supercedes 6427 // options about fragility. 6428 if (runtimeArg && 6429 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) { 6430 ObjCRuntime runtime; 6431 StringRef value = runtimeArg->getValue(); 6432 if (runtime.tryParse(value)) { 6433 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime) 6434 << value; 6435 } 6436 if ((runtime.getKind() == ObjCRuntime::GNUstep) && 6437 (runtime.getVersion() >= VersionTuple(2, 0))) 6438 if (!getToolChain().getTriple().isOSBinFormatELF() && 6439 !getToolChain().getTriple().isOSBinFormatCOFF()) { 6440 getToolChain().getDriver().Diag( 6441 diag::err_drv_gnustep_objc_runtime_incompatible_binary) 6442 << runtime.getVersion().getMajor(); 6443 } 6444 6445 runtimeArg->render(args, cmdArgs); 6446 return runtime; 6447 } 6448 6449 // Otherwise, we'll need the ABI "version". Version numbers are 6450 // slightly confusing for historical reasons: 6451 // 1 - Traditional "fragile" ABI 6452 // 2 - Non-fragile ABI, version 1 6453 // 3 - Non-fragile ABI, version 2 6454 unsigned objcABIVersion = 1; 6455 // If -fobjc-abi-version= is present, use that to set the version. 6456 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) { 6457 StringRef value = abiArg->getValue(); 6458 if (value == "1") 6459 objcABIVersion = 1; 6460 else if (value == "2") 6461 objcABIVersion = 2; 6462 else if (value == "3") 6463 objcABIVersion = 3; 6464 else 6465 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value; 6466 } else { 6467 // Otherwise, determine if we are using the non-fragile ABI. 6468 bool nonFragileABIIsDefault = 6469 (rewriteKind == RK_NonFragile || 6470 (rewriteKind == RK_None && 6471 getToolChain().IsObjCNonFragileABIDefault())); 6472 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi, 6473 options::OPT_fno_objc_nonfragile_abi, 6474 nonFragileABIIsDefault)) { 6475 // Determine the non-fragile ABI version to use. 6476 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO 6477 unsigned nonFragileABIVersion = 1; 6478 #else 6479 unsigned nonFragileABIVersion = 2; 6480 #endif 6481 6482 if (Arg *abiArg = 6483 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) { 6484 StringRef value = abiArg->getValue(); 6485 if (value == "1") 6486 nonFragileABIVersion = 1; 6487 else if (value == "2") 6488 nonFragileABIVersion = 2; 6489 else 6490 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) 6491 << value; 6492 } 6493 6494 objcABIVersion = 1 + nonFragileABIVersion; 6495 } else { 6496 objcABIVersion = 1; 6497 } 6498 } 6499 6500 // We don't actually care about the ABI version other than whether 6501 // it's non-fragile. 6502 bool isNonFragile = objcABIVersion != 1; 6503 6504 // If we have no runtime argument, ask the toolchain for its default runtime. 6505 // However, the rewriter only really supports the Mac runtime, so assume that. 6506 ObjCRuntime runtime; 6507 if (!runtimeArg) { 6508 switch (rewriteKind) { 6509 case RK_None: 6510 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile); 6511 break; 6512 case RK_Fragile: 6513 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple()); 6514 break; 6515 case RK_NonFragile: 6516 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple()); 6517 break; 6518 } 6519 6520 // -fnext-runtime 6521 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) { 6522 // On Darwin, make this use the default behavior for the toolchain. 6523 if (getToolChain().getTriple().isOSDarwin()) { 6524 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile); 6525 6526 // Otherwise, build for a generic macosx port. 6527 } else { 6528 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple()); 6529 } 6530 6531 // -fgnu-runtime 6532 } else { 6533 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime)); 6534 // Legacy behaviour is to target the gnustep runtime if we are in 6535 // non-fragile mode or the GCC runtime in fragile mode. 6536 if (isNonFragile) 6537 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0)); 6538 else 6539 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple()); 6540 } 6541 6542 if (llvm::any_of(inputs, [](const InputInfo &input) { 6543 return types::isObjC(input.getType()); 6544 })) 6545 cmdArgs.push_back( 6546 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString())); 6547 return runtime; 6548 } 6549 6550 static bool maybeConsumeDash(const std::string &EH, size_t &I) { 6551 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-'); 6552 I += HaveDash; 6553 return !HaveDash; 6554 } 6555 6556 namespace { 6557 struct EHFlags { 6558 bool Synch = false; 6559 bool Asynch = false; 6560 bool NoUnwindC = false; 6561 }; 6562 } // end anonymous namespace 6563 6564 /// /EH controls whether to run destructor cleanups when exceptions are 6565 /// thrown. There are three modifiers: 6566 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions. 6567 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions. 6568 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR. 6569 /// - c: Assume that extern "C" functions are implicitly nounwind. 6570 /// The default is /EHs-c-, meaning cleanups are disabled. 6571 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) { 6572 EHFlags EH; 6573 6574 std::vector<std::string> EHArgs = 6575 Args.getAllArgValues(options::OPT__SLASH_EH); 6576 for (auto EHVal : EHArgs) { 6577 for (size_t I = 0, E = EHVal.size(); I != E; ++I) { 6578 switch (EHVal[I]) { 6579 case 'a': 6580 EH.Asynch = maybeConsumeDash(EHVal, I); 6581 if (EH.Asynch) 6582 EH.Synch = false; 6583 continue; 6584 case 'c': 6585 EH.NoUnwindC = maybeConsumeDash(EHVal, I); 6586 continue; 6587 case 's': 6588 EH.Synch = maybeConsumeDash(EHVal, I); 6589 if (EH.Synch) 6590 EH.Asynch = false; 6591 continue; 6592 default: 6593 break; 6594 } 6595 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal; 6596 break; 6597 } 6598 } 6599 // The /GX, /GX- flags are only processed if there are not /EH flags. 6600 // The default is that /GX is not specified. 6601 if (EHArgs.empty() && 6602 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_, 6603 /*Default=*/false)) { 6604 EH.Synch = true; 6605 EH.NoUnwindC = true; 6606 } 6607 6608 return EH; 6609 } 6610 6611 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType, 6612 ArgStringList &CmdArgs, 6613 codegenoptions::DebugInfoKind *DebugInfoKind, 6614 bool *EmitCodeView) const { 6615 unsigned RTOptionID = options::OPT__SLASH_MT; 6616 bool isNVPTX = getToolChain().getTriple().isNVPTX(); 6617 6618 if (Args.hasArg(options::OPT__SLASH_LDd)) 6619 // The /LDd option implies /MTd. The dependent lib part can be overridden, 6620 // but defining _DEBUG is sticky. 6621 RTOptionID = options::OPT__SLASH_MTd; 6622 6623 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group)) 6624 RTOptionID = A->getOption().getID(); 6625 6626 StringRef FlagForCRT; 6627 switch (RTOptionID) { 6628 case options::OPT__SLASH_MD: 6629 if (Args.hasArg(options::OPT__SLASH_LDd)) 6630 CmdArgs.push_back("-D_DEBUG"); 6631 CmdArgs.push_back("-D_MT"); 6632 CmdArgs.push_back("-D_DLL"); 6633 FlagForCRT = "--dependent-lib=msvcrt"; 6634 break; 6635 case options::OPT__SLASH_MDd: 6636 CmdArgs.push_back("-D_DEBUG"); 6637 CmdArgs.push_back("-D_MT"); 6638 CmdArgs.push_back("-D_DLL"); 6639 FlagForCRT = "--dependent-lib=msvcrtd"; 6640 break; 6641 case options::OPT__SLASH_MT: 6642 if (Args.hasArg(options::OPT__SLASH_LDd)) 6643 CmdArgs.push_back("-D_DEBUG"); 6644 CmdArgs.push_back("-D_MT"); 6645 CmdArgs.push_back("-flto-visibility-public-std"); 6646 FlagForCRT = "--dependent-lib=libcmt"; 6647 break; 6648 case options::OPT__SLASH_MTd: 6649 CmdArgs.push_back("-D_DEBUG"); 6650 CmdArgs.push_back("-D_MT"); 6651 CmdArgs.push_back("-flto-visibility-public-std"); 6652 FlagForCRT = "--dependent-lib=libcmtd"; 6653 break; 6654 default: 6655 llvm_unreachable("Unexpected option ID."); 6656 } 6657 6658 if (Args.hasArg(options::OPT__SLASH_Zl)) { 6659 CmdArgs.push_back("-D_VC_NODEFAULTLIB"); 6660 } else { 6661 CmdArgs.push_back(FlagForCRT.data()); 6662 6663 // This provides POSIX compatibility (maps 'open' to '_open'), which most 6664 // users want. The /Za flag to cl.exe turns this off, but it's not 6665 // implemented in clang. 6666 CmdArgs.push_back("--dependent-lib=oldnames"); 6667 } 6668 6669 if (Arg *ShowIncludes = 6670 Args.getLastArg(options::OPT__SLASH_showIncludes, 6671 options::OPT__SLASH_showIncludes_user)) { 6672 CmdArgs.push_back("--show-includes"); 6673 if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes)) 6674 CmdArgs.push_back("-sys-header-deps"); 6675 } 6676 6677 // This controls whether or not we emit RTTI data for polymorphic types. 6678 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR, 6679 /*Default=*/false)) 6680 CmdArgs.push_back("-fno-rtti-data"); 6681 6682 // This controls whether or not we emit stack-protector instrumentation. 6683 // In MSVC, Buffer Security Check (/GS) is on by default. 6684 if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_, 6685 /*Default=*/true)) { 6686 CmdArgs.push_back("-stack-protector"); 6687 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong))); 6688 } 6689 6690 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present. 6691 if (Arg *DebugInfoArg = 6692 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd, 6693 options::OPT_gline_tables_only)) { 6694 *EmitCodeView = true; 6695 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7)) 6696 *DebugInfoKind = codegenoptions::LimitedDebugInfo; 6697 else 6698 *DebugInfoKind = codegenoptions::DebugLineTablesOnly; 6699 } else { 6700 *EmitCodeView = false; 6701 } 6702 6703 const Driver &D = getToolChain().getDriver(); 6704 EHFlags EH = parseClangCLEHFlags(D, Args); 6705 if (!isNVPTX && (EH.Synch || EH.Asynch)) { 6706 if (types::isCXX(InputType)) 6707 CmdArgs.push_back("-fcxx-exceptions"); 6708 CmdArgs.push_back("-fexceptions"); 6709 } 6710 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC) 6711 CmdArgs.push_back("-fexternc-nounwind"); 6712 6713 // /EP should expand to -E -P. 6714 if (Args.hasArg(options::OPT__SLASH_EP)) { 6715 CmdArgs.push_back("-E"); 6716 CmdArgs.push_back("-P"); 6717 } 6718 6719 unsigned VolatileOptionID; 6720 if (getToolChain().getTriple().isX86()) 6721 VolatileOptionID = options::OPT__SLASH_volatile_ms; 6722 else 6723 VolatileOptionID = options::OPT__SLASH_volatile_iso; 6724 6725 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group)) 6726 VolatileOptionID = A->getOption().getID(); 6727 6728 if (VolatileOptionID == options::OPT__SLASH_volatile_ms) 6729 CmdArgs.push_back("-fms-volatile"); 6730 6731 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_, 6732 options::OPT__SLASH_Zc_dllexportInlines, 6733 false)) { 6734 if (Args.hasArg(options::OPT__SLASH_fallback)) { 6735 D.Diag(clang::diag::err_drv_dllexport_inlines_and_fallback); 6736 } else { 6737 CmdArgs.push_back("-fno-dllexport-inlines"); 6738 } 6739 } 6740 6741 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg); 6742 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb); 6743 if (MostGeneralArg && BestCaseArg) 6744 D.Diag(clang::diag::err_drv_argument_not_allowed_with) 6745 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args); 6746 6747 if (MostGeneralArg) { 6748 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms); 6749 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm); 6750 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv); 6751 6752 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg; 6753 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg; 6754 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict) 6755 D.Diag(clang::diag::err_drv_argument_not_allowed_with) 6756 << FirstConflict->getAsString(Args) 6757 << SecondConflict->getAsString(Args); 6758 6759 if (SingleArg) 6760 CmdArgs.push_back("-fms-memptr-rep=single"); 6761 else if (MultipleArg) 6762 CmdArgs.push_back("-fms-memptr-rep=multiple"); 6763 else 6764 CmdArgs.push_back("-fms-memptr-rep=virtual"); 6765 } 6766 6767 // Parse the default calling convention options. 6768 if (Arg *CCArg = 6769 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr, 6770 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv, 6771 options::OPT__SLASH_Gregcall)) { 6772 unsigned DCCOptId = CCArg->getOption().getID(); 6773 const char *DCCFlag = nullptr; 6774 bool ArchSupported = !isNVPTX; 6775 llvm::Triple::ArchType Arch = getToolChain().getArch(); 6776 switch (DCCOptId) { 6777 case options::OPT__SLASH_Gd: 6778 DCCFlag = "-fdefault-calling-conv=cdecl"; 6779 break; 6780 case options::OPT__SLASH_Gr: 6781 ArchSupported = Arch == llvm::Triple::x86; 6782 DCCFlag = "-fdefault-calling-conv=fastcall"; 6783 break; 6784 case options::OPT__SLASH_Gz: 6785 ArchSupported = Arch == llvm::Triple::x86; 6786 DCCFlag = "-fdefault-calling-conv=stdcall"; 6787 break; 6788 case options::OPT__SLASH_Gv: 6789 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64; 6790 DCCFlag = "-fdefault-calling-conv=vectorcall"; 6791 break; 6792 case options::OPT__SLASH_Gregcall: 6793 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64; 6794 DCCFlag = "-fdefault-calling-conv=regcall"; 6795 break; 6796 } 6797 6798 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either. 6799 if (ArchSupported && DCCFlag) 6800 CmdArgs.push_back(DCCFlag); 6801 } 6802 6803 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ); 6804 6805 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) { 6806 CmdArgs.push_back("-fdiagnostics-format"); 6807 if (Args.hasArg(options::OPT__SLASH_fallback)) 6808 CmdArgs.push_back("msvc-fallback"); 6809 else 6810 CmdArgs.push_back("msvc"); 6811 } 6812 6813 if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) { 6814 StringRef GuardArgs = A->getValue(); 6815 // The only valid options are "cf", "cf,nochecks", and "cf-". 6816 if (GuardArgs.equals_lower("cf")) { 6817 // Emit CFG instrumentation and the table of address-taken functions. 6818 CmdArgs.push_back("-cfguard"); 6819 } else if (GuardArgs.equals_lower("cf,nochecks")) { 6820 // Emit only the table of address-taken functions. 6821 CmdArgs.push_back("-cfguard-no-checks"); 6822 } else if (GuardArgs.equals_lower("cf-")) { 6823 // Do nothing, but we might want to emit a security warning in future. 6824 } else { 6825 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs; 6826 } 6827 } 6828 } 6829 6830 visualstudio::Compiler *Clang::getCLFallback() const { 6831 if (!CLFallback) 6832 CLFallback.reset(new visualstudio::Compiler(getToolChain())); 6833 return CLFallback.get(); 6834 } 6835 6836 6837 const char *Clang::getBaseInputName(const ArgList &Args, 6838 const InputInfo &Input) { 6839 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput())); 6840 } 6841 6842 const char *Clang::getBaseInputStem(const ArgList &Args, 6843 const InputInfoList &Inputs) { 6844 const char *Str = getBaseInputName(Args, Inputs[0]); 6845 6846 if (const char *End = strrchr(Str, '.')) 6847 return Args.MakeArgString(std::string(Str, End)); 6848 6849 return Str; 6850 } 6851 6852 const char *Clang::getDependencyFileName(const ArgList &Args, 6853 const InputInfoList &Inputs) { 6854 // FIXME: Think about this more. 6855 6856 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) { 6857 SmallString<128> OutputFilename(OutputOpt->getValue()); 6858 llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d')); 6859 return Args.MakeArgString(OutputFilename); 6860 } 6861 6862 return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d"); 6863 } 6864 6865 // Begin ClangAs 6866 6867 void ClangAs::AddMIPSTargetArgs(const ArgList &Args, 6868 ArgStringList &CmdArgs) const { 6869 StringRef CPUName; 6870 StringRef ABIName; 6871 const llvm::Triple &Triple = getToolChain().getTriple(); 6872 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName); 6873 6874 CmdArgs.push_back("-target-abi"); 6875 CmdArgs.push_back(ABIName.data()); 6876 } 6877 6878 void ClangAs::AddX86TargetArgs(const ArgList &Args, 6879 ArgStringList &CmdArgs) const { 6880 addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs, 6881 /*IsLTO=*/false); 6882 6883 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) { 6884 StringRef Value = A->getValue(); 6885 if (Value == "intel" || Value == "att") { 6886 CmdArgs.push_back("-mllvm"); 6887 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value)); 6888 } else { 6889 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument) 6890 << A->getOption().getName() << Value; 6891 } 6892 } 6893 } 6894 6895 void ClangAs::AddRISCVTargetArgs(const ArgList &Args, 6896 ArgStringList &CmdArgs) const { 6897 const llvm::Triple &Triple = getToolChain().getTriple(); 6898 StringRef ABIName = riscv::getRISCVABI(Args, Triple); 6899 6900 CmdArgs.push_back("-target-abi"); 6901 CmdArgs.push_back(ABIName.data()); 6902 } 6903 6904 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA, 6905 const InputInfo &Output, const InputInfoList &Inputs, 6906 const ArgList &Args, 6907 const char *LinkingOutput) const { 6908 ArgStringList CmdArgs; 6909 6910 assert(Inputs.size() == 1 && "Unexpected number of inputs."); 6911 const InputInfo &Input = Inputs[0]; 6912 6913 const llvm::Triple &Triple = getToolChain().getEffectiveTriple(); 6914 const std::string &TripleStr = Triple.getTriple(); 6915 const auto &D = getToolChain().getDriver(); 6916 6917 // Don't warn about "clang -w -c foo.s" 6918 Args.ClaimAllArgs(options::OPT_w); 6919 // and "clang -emit-llvm -c foo.s" 6920 Args.ClaimAllArgs(options::OPT_emit_llvm); 6921 6922 claimNoWarnArgs(Args); 6923 6924 // Invoke ourselves in -cc1as mode. 6925 // 6926 // FIXME: Implement custom jobs for internal actions. 6927 CmdArgs.push_back("-cc1as"); 6928 6929 // Add the "effective" target triple. 6930 CmdArgs.push_back("-triple"); 6931 CmdArgs.push_back(Args.MakeArgString(TripleStr)); 6932 6933 // Set the output mode, we currently only expect to be used as a real 6934 // assembler. 6935 CmdArgs.push_back("-filetype"); 6936 CmdArgs.push_back("obj"); 6937 6938 // Set the main file name, so that debug info works even with 6939 // -save-temps or preprocessed assembly. 6940 CmdArgs.push_back("-main-file-name"); 6941 CmdArgs.push_back(Clang::getBaseInputName(Args, Input)); 6942 6943 // Add the target cpu 6944 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true); 6945 if (!CPU.empty()) { 6946 CmdArgs.push_back("-target-cpu"); 6947 CmdArgs.push_back(Args.MakeArgString(CPU)); 6948 } 6949 6950 // Add the target features 6951 getTargetFeatures(D, Triple, Args, CmdArgs, true); 6952 6953 // Ignore explicit -force_cpusubtype_ALL option. 6954 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL); 6955 6956 // Pass along any -I options so we get proper .include search paths. 6957 Args.AddAllArgs(CmdArgs, options::OPT_I_Group); 6958 6959 // Determine the original source input. 6960 const Action *SourceAction = &JA; 6961 while (SourceAction->getKind() != Action::InputClass) { 6962 assert(!SourceAction->getInputs().empty() && "unexpected root action!"); 6963 SourceAction = SourceAction->getInputs()[0]; 6964 } 6965 6966 // Forward -g and handle debug info related flags, assuming we are dealing 6967 // with an actual assembly file. 6968 bool WantDebug = false; 6969 unsigned DwarfVersion = 0; 6970 Args.ClaimAllArgs(options::OPT_g_Group); 6971 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) { 6972 WantDebug = !A->getOption().matches(options::OPT_g0) && 6973 !A->getOption().matches(options::OPT_ggdb0); 6974 if (WantDebug) 6975 DwarfVersion = DwarfVersionNum(A->getSpelling()); 6976 } 6977 6978 unsigned DefaultDwarfVersion = ParseDebugDefaultVersion(getToolChain(), Args); 6979 if (DwarfVersion == 0) 6980 DwarfVersion = DefaultDwarfVersion; 6981 6982 if (DwarfVersion == 0) 6983 DwarfVersion = getToolChain().GetDefaultDwarfVersion(); 6984 6985 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo; 6986 6987 if (SourceAction->getType() == types::TY_Asm || 6988 SourceAction->getType() == types::TY_PP_Asm) { 6989 // You might think that it would be ok to set DebugInfoKind outside of 6990 // the guard for source type, however there is a test which asserts 6991 // that some assembler invocation receives no -debug-info-kind, 6992 // and it's not clear whether that test is just overly restrictive. 6993 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo 6994 : codegenoptions::NoDebugInfo); 6995 // Add the -fdebug-compilation-dir flag if needed. 6996 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS()); 6997 6998 addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs); 6999 7000 // Set the AT_producer to the clang version when using the integrated 7001 // assembler on assembly source files. 7002 CmdArgs.push_back("-dwarf-debug-producer"); 7003 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion())); 7004 7005 // And pass along -I options 7006 Args.AddAllArgs(CmdArgs, options::OPT_I); 7007 } 7008 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion, 7009 llvm::DebuggerKind::Default); 7010 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain()); 7011 7012 7013 // Handle -fPIC et al -- the relocation-model affects the assembler 7014 // for some targets. 7015 llvm::Reloc::Model RelocationModel; 7016 unsigned PICLevel; 7017 bool IsPIE; 7018 std::tie(RelocationModel, PICLevel, IsPIE) = 7019 ParsePICArgs(getToolChain(), Args); 7020 7021 const char *RMName = RelocationModelName(RelocationModel); 7022 if (RMName) { 7023 CmdArgs.push_back("-mrelocation-model"); 7024 CmdArgs.push_back(RMName); 7025 } 7026 7027 // Optionally embed the -cc1as level arguments into the debug info, for build 7028 // analysis. 7029 if (getToolChain().UseDwarfDebugFlags()) { 7030 ArgStringList OriginalArgs; 7031 for (const auto &Arg : Args) 7032 Arg->render(Args, OriginalArgs); 7033 7034 SmallString<256> Flags; 7035 const char *Exec = getToolChain().getDriver().getClangProgramPath(); 7036 EscapeSpacesAndBackslashes(Exec, Flags); 7037 for (const char *OriginalArg : OriginalArgs) { 7038 SmallString<128> EscapedArg; 7039 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg); 7040 Flags += " "; 7041 Flags += EscapedArg; 7042 } 7043 CmdArgs.push_back("-dwarf-debug-flags"); 7044 CmdArgs.push_back(Args.MakeArgString(Flags)); 7045 } 7046 7047 // FIXME: Add -static support, once we have it. 7048 7049 // Add target specific flags. 7050 switch (getToolChain().getArch()) { 7051 default: 7052 break; 7053 7054 case llvm::Triple::mips: 7055 case llvm::Triple::mipsel: 7056 case llvm::Triple::mips64: 7057 case llvm::Triple::mips64el: 7058 AddMIPSTargetArgs(Args, CmdArgs); 7059 break; 7060 7061 case llvm::Triple::x86: 7062 case llvm::Triple::x86_64: 7063 AddX86TargetArgs(Args, CmdArgs); 7064 break; 7065 7066 case llvm::Triple::arm: 7067 case llvm::Triple::armeb: 7068 case llvm::Triple::thumb: 7069 case llvm::Triple::thumbeb: 7070 // This isn't in AddARMTargetArgs because we want to do this for assembly 7071 // only, not C/C++. 7072 if (Args.hasFlag(options::OPT_mdefault_build_attributes, 7073 options::OPT_mno_default_build_attributes, true)) { 7074 CmdArgs.push_back("-mllvm"); 7075 CmdArgs.push_back("-arm-add-build-attributes"); 7076 } 7077 break; 7078 7079 case llvm::Triple::aarch64: 7080 case llvm::Triple::aarch64_32: 7081 case llvm::Triple::aarch64_be: 7082 if (Args.hasArg(options::OPT_mmark_bti_property)) { 7083 CmdArgs.push_back("-mllvm"); 7084 CmdArgs.push_back("-aarch64-mark-bti-property"); 7085 } 7086 break; 7087 7088 case llvm::Triple::riscv32: 7089 case llvm::Triple::riscv64: 7090 AddRISCVTargetArgs(Args, CmdArgs); 7091 break; 7092 } 7093 7094 // Consume all the warning flags. Usually this would be handled more 7095 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as 7096 // doesn't handle that so rather than warning about unused flags that are 7097 // actually used, we'll lie by omission instead. 7098 // FIXME: Stop lying and consume only the appropriate driver flags 7099 Args.ClaimAllArgs(options::OPT_W_Group); 7100 7101 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, 7102 getToolChain().getDriver()); 7103 7104 Args.AddAllArgs(CmdArgs, options::OPT_mllvm); 7105 7106 assert(Output.isFilename() && "Unexpected lipo output."); 7107 CmdArgs.push_back("-o"); 7108 CmdArgs.push_back(Output.getFilename()); 7109 7110 const llvm::Triple &T = getToolChain().getTriple(); 7111 Arg *A; 7112 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split && 7113 T.isOSBinFormatELF()) { 7114 CmdArgs.push_back("-split-dwarf-output"); 7115 CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output)); 7116 } 7117 7118 HandleAmdgcnLegacyOptions(D, Args, CmdArgs); 7119 7120 assert(Input.isFilename() && "Invalid input."); 7121 CmdArgs.push_back(Input.getFilename()); 7122 7123 const char *Exec = getToolChain().getDriver().getClangProgramPath(); 7124 C.addCommand(std::make_unique<Command>(JA, *this, 7125 ResponseFileSupport::AtFileUTF8(), 7126 Exec, CmdArgs, Inputs, Output)); 7127 } 7128 7129 // Begin OffloadBundler 7130 7131 void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA, 7132 const InputInfo &Output, 7133 const InputInfoList &Inputs, 7134 const llvm::opt::ArgList &TCArgs, 7135 const char *LinkingOutput) const { 7136 // The version with only one output is expected to refer to a bundling job. 7137 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!"); 7138 7139 // The bundling command looks like this: 7140 // clang-offload-bundler -type=bc 7141 // -targets=host-triple,openmp-triple1,openmp-triple2 7142 // -outputs=input_file 7143 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2" 7144 7145 ArgStringList CmdArgs; 7146 7147 // Get the type. 7148 CmdArgs.push_back(TCArgs.MakeArgString( 7149 Twine("-type=") + types::getTypeTempSuffix(Output.getType()))); 7150 7151 assert(JA.getInputs().size() == Inputs.size() && 7152 "Not have inputs for all dependence actions??"); 7153 7154 // Get the targets. 7155 SmallString<128> Triples; 7156 Triples += "-targets="; 7157 for (unsigned I = 0; I < Inputs.size(); ++I) { 7158 if (I) 7159 Triples += ','; 7160 7161 // Find ToolChain for this input. 7162 Action::OffloadKind CurKind = Action::OFK_Host; 7163 const ToolChain *CurTC = &getToolChain(); 7164 const Action *CurDep = JA.getInputs()[I]; 7165 7166 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) { 7167 CurTC = nullptr; 7168 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) { 7169 assert(CurTC == nullptr && "Expected one dependence!"); 7170 CurKind = A->getOffloadingDeviceKind(); 7171 CurTC = TC; 7172 }); 7173 } 7174 Triples += Action::GetOffloadKindName(CurKind); 7175 Triples += '-'; 7176 Triples += CurTC->getTriple().normalize(); 7177 if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) { 7178 Triples += '-'; 7179 Triples += CurDep->getOffloadingArch(); 7180 } 7181 } 7182 CmdArgs.push_back(TCArgs.MakeArgString(Triples)); 7183 7184 // Get bundled file command. 7185 CmdArgs.push_back( 7186 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename())); 7187 7188 // Get unbundled files command. 7189 SmallString<128> UB; 7190 UB += "-inputs="; 7191 for (unsigned I = 0; I < Inputs.size(); ++I) { 7192 if (I) 7193 UB += ','; 7194 7195 // Find ToolChain for this input. 7196 const ToolChain *CurTC = &getToolChain(); 7197 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) { 7198 CurTC = nullptr; 7199 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) { 7200 assert(CurTC == nullptr && "Expected one dependence!"); 7201 CurTC = TC; 7202 }); 7203 } 7204 UB += CurTC->getInputFilename(Inputs[I]); 7205 } 7206 CmdArgs.push_back(TCArgs.MakeArgString(UB)); 7207 7208 // All the inputs are encoded as commands. 7209 C.addCommand(std::make_unique<Command>( 7210 JA, *this, ResponseFileSupport::None(), 7211 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())), 7212 CmdArgs, None, Output)); 7213 } 7214 7215 void OffloadBundler::ConstructJobMultipleOutputs( 7216 Compilation &C, const JobAction &JA, const InputInfoList &Outputs, 7217 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, 7218 const char *LinkingOutput) const { 7219 // The version with multiple outputs is expected to refer to a unbundling job. 7220 auto &UA = cast<OffloadUnbundlingJobAction>(JA); 7221 7222 // The unbundling command looks like this: 7223 // clang-offload-bundler -type=bc 7224 // -targets=host-triple,openmp-triple1,openmp-triple2 7225 // -inputs=input_file 7226 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2" 7227 // -unbundle 7228 7229 ArgStringList CmdArgs; 7230 7231 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!"); 7232 InputInfo Input = Inputs.front(); 7233 7234 // Get the type. 7235 CmdArgs.push_back(TCArgs.MakeArgString( 7236 Twine("-type=") + types::getTypeTempSuffix(Input.getType()))); 7237 7238 // Get the targets. 7239 SmallString<128> Triples; 7240 Triples += "-targets="; 7241 auto DepInfo = UA.getDependentActionsInfo(); 7242 for (unsigned I = 0; I < DepInfo.size(); ++I) { 7243 if (I) 7244 Triples += ','; 7245 7246 auto &Dep = DepInfo[I]; 7247 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind); 7248 Triples += '-'; 7249 Triples += Dep.DependentToolChain->getTriple().normalize(); 7250 if (Dep.DependentOffloadKind == Action::OFK_HIP && 7251 !Dep.DependentBoundArch.empty()) { 7252 Triples += '-'; 7253 Triples += Dep.DependentBoundArch; 7254 } 7255 } 7256 7257 CmdArgs.push_back(TCArgs.MakeArgString(Triples)); 7258 7259 // Get bundled file command. 7260 CmdArgs.push_back( 7261 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename())); 7262 7263 // Get unbundled files command. 7264 SmallString<128> UB; 7265 UB += "-outputs="; 7266 for (unsigned I = 0; I < Outputs.size(); ++I) { 7267 if (I) 7268 UB += ','; 7269 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]); 7270 } 7271 CmdArgs.push_back(TCArgs.MakeArgString(UB)); 7272 CmdArgs.push_back("-unbundle"); 7273 7274 // All the inputs are encoded as commands. 7275 C.addCommand(std::make_unique<Command>( 7276 JA, *this, ResponseFileSupport::None(), 7277 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())), 7278 CmdArgs, None, Outputs)); 7279 } 7280 7281 void OffloadWrapper::ConstructJob(Compilation &C, const JobAction &JA, 7282 const InputInfo &Output, 7283 const InputInfoList &Inputs, 7284 const ArgList &Args, 7285 const char *LinkingOutput) const { 7286 ArgStringList CmdArgs; 7287 7288 const llvm::Triple &Triple = getToolChain().getEffectiveTriple(); 7289 7290 // Add the "effective" target triple. 7291 CmdArgs.push_back("-target"); 7292 CmdArgs.push_back(Args.MakeArgString(Triple.getTriple())); 7293 7294 // Add the output file name. 7295 assert(Output.isFilename() && "Invalid output."); 7296 CmdArgs.push_back("-o"); 7297 CmdArgs.push_back(Output.getFilename()); 7298 7299 // Add inputs. 7300 for (const InputInfo &I : Inputs) { 7301 assert(I.isFilename() && "Invalid input."); 7302 CmdArgs.push_back(I.getFilename()); 7303 } 7304 7305 C.addCommand(std::make_unique<Command>( 7306 JA, *this, ResponseFileSupport::None(), 7307 Args.MakeArgString(getToolChain().GetProgramPath(getShortName())), 7308 CmdArgs, Inputs, Output)); 7309 } 7310