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