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