1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===// 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/Driver/Driver.h" 10 #include "ToolChains/AIX.h" 11 #include "ToolChains/AMDGPU.h" 12 #include "ToolChains/AMDGPUOpenMP.h" 13 #include "ToolChains/AVR.h" 14 #include "ToolChains/Arch/RISCV.h" 15 #include "ToolChains/BareMetal.h" 16 #include "ToolChains/CSKYToolChain.h" 17 #include "ToolChains/Clang.h" 18 #include "ToolChains/CrossWindows.h" 19 #include "ToolChains/Cuda.h" 20 #include "ToolChains/Darwin.h" 21 #include "ToolChains/DragonFly.h" 22 #include "ToolChains/FreeBSD.h" 23 #include "ToolChains/Fuchsia.h" 24 #include "ToolChains/Gnu.h" 25 #include "ToolChains/HIPAMD.h" 26 #include "ToolChains/HIPSPV.h" 27 #include "ToolChains/HLSL.h" 28 #include "ToolChains/Haiku.h" 29 #include "ToolChains/Hexagon.h" 30 #include "ToolChains/Hurd.h" 31 #include "ToolChains/Lanai.h" 32 #include "ToolChains/Linux.h" 33 #include "ToolChains/MSP430.h" 34 #include "ToolChains/MSVC.h" 35 #include "ToolChains/MinGW.h" 36 #include "ToolChains/MipsLinux.h" 37 #include "ToolChains/NaCl.h" 38 #include "ToolChains/NetBSD.h" 39 #include "ToolChains/OHOS.h" 40 #include "ToolChains/OpenBSD.h" 41 #include "ToolChains/PPCFreeBSD.h" 42 #include "ToolChains/PPCLinux.h" 43 #include "ToolChains/PS4CPU.h" 44 #include "ToolChains/RISCVToolchain.h" 45 #include "ToolChains/SPIRV.h" 46 #include "ToolChains/Solaris.h" 47 #include "ToolChains/TCE.h" 48 #include "ToolChains/VEToolchain.h" 49 #include "ToolChains/WebAssembly.h" 50 #include "ToolChains/XCore.h" 51 #include "ToolChains/ZOS.h" 52 #include "clang/Basic/TargetID.h" 53 #include "clang/Basic/Version.h" 54 #include "clang/Config/config.h" 55 #include "clang/Driver/Action.h" 56 #include "clang/Driver/Compilation.h" 57 #include "clang/Driver/DriverDiagnostic.h" 58 #include "clang/Driver/InputInfo.h" 59 #include "clang/Driver/Job.h" 60 #include "clang/Driver/Options.h" 61 #include "clang/Driver/Phases.h" 62 #include "clang/Driver/SanitizerArgs.h" 63 #include "clang/Driver/Tool.h" 64 #include "clang/Driver/ToolChain.h" 65 #include "clang/Driver/Types.h" 66 #include "llvm/ADT/ArrayRef.h" 67 #include "llvm/ADT/STLExtras.h" 68 #include "llvm/ADT/StringExtras.h" 69 #include "llvm/ADT/StringRef.h" 70 #include "llvm/ADT/StringSet.h" 71 #include "llvm/ADT/StringSwitch.h" 72 #include "llvm/Config/llvm-config.h" 73 #include "llvm/MC/TargetRegistry.h" 74 #include "llvm/Option/Arg.h" 75 #include "llvm/Option/ArgList.h" 76 #include "llvm/Option/OptSpecifier.h" 77 #include "llvm/Option/OptTable.h" 78 #include "llvm/Option/Option.h" 79 #include "llvm/Support/CommandLine.h" 80 #include "llvm/Support/ErrorHandling.h" 81 #include "llvm/Support/ExitCodes.h" 82 #include "llvm/Support/FileSystem.h" 83 #include "llvm/Support/FormatVariadic.h" 84 #include "llvm/Support/MD5.h" 85 #include "llvm/Support/Path.h" 86 #include "llvm/Support/PrettyStackTrace.h" 87 #include "llvm/Support/Process.h" 88 #include "llvm/Support/Program.h" 89 #include "llvm/Support/RISCVISAInfo.h" 90 #include "llvm/Support/StringSaver.h" 91 #include "llvm/Support/VirtualFileSystem.h" 92 #include "llvm/Support/raw_ostream.h" 93 #include "llvm/TargetParser/Host.h" 94 #include <cstdlib> // ::getenv 95 #include <map> 96 #include <memory> 97 #include <optional> 98 #include <set> 99 #include <utility> 100 #if LLVM_ON_UNIX 101 #include <unistd.h> // getpid 102 #endif 103 104 using namespace clang::driver; 105 using namespace clang; 106 using namespace llvm::opt; 107 108 static std::optional<llvm::Triple> getOffloadTargetTriple(const Driver &D, 109 const ArgList &Args) { 110 auto OffloadTargets = Args.getAllArgValues(options::OPT_offload_EQ); 111 // Offload compilation flow does not support multiple targets for now. We 112 // need the HIPActionBuilder (and possibly the CudaActionBuilder{,Base}too) 113 // to support multiple tool chains first. 114 switch (OffloadTargets.size()) { 115 default: 116 D.Diag(diag::err_drv_only_one_offload_target_supported); 117 return std::nullopt; 118 case 0: 119 D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << ""; 120 return std::nullopt; 121 case 1: 122 break; 123 } 124 return llvm::Triple(OffloadTargets[0]); 125 } 126 127 static std::optional<llvm::Triple> 128 getNVIDIAOffloadTargetTriple(const Driver &D, const ArgList &Args, 129 const llvm::Triple &HostTriple) { 130 if (!Args.hasArg(options::OPT_offload_EQ)) { 131 return llvm::Triple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda" 132 : "nvptx-nvidia-cuda"); 133 } 134 auto TT = getOffloadTargetTriple(D, Args); 135 if (TT && (TT->getArch() == llvm::Triple::spirv32 || 136 TT->getArch() == llvm::Triple::spirv64)) { 137 if (Args.hasArg(options::OPT_emit_llvm)) 138 return TT; 139 D.Diag(diag::err_drv_cuda_offload_only_emit_bc); 140 return std::nullopt; 141 } 142 D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << TT->str(); 143 return std::nullopt; 144 } 145 static std::optional<llvm::Triple> 146 getHIPOffloadTargetTriple(const Driver &D, const ArgList &Args) { 147 if (!Args.hasArg(options::OPT_offload_EQ)) { 148 return llvm::Triple("amdgcn-amd-amdhsa"); // Default HIP triple. 149 } 150 auto TT = getOffloadTargetTriple(D, Args); 151 if (!TT) 152 return std::nullopt; 153 if (TT->getArch() == llvm::Triple::amdgcn && 154 TT->getVendor() == llvm::Triple::AMD && 155 TT->getOS() == llvm::Triple::AMDHSA) 156 return TT; 157 if (TT->getArch() == llvm::Triple::spirv64) 158 return TT; 159 D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << TT->str(); 160 return std::nullopt; 161 } 162 163 // static 164 std::string Driver::GetResourcesPath(StringRef BinaryPath, 165 StringRef CustomResourceDir) { 166 // Since the resource directory is embedded in the module hash, it's important 167 // that all places that need it call this function, so that they get the 168 // exact same string ("a/../b/" and "b/" get different hashes, for example). 169 170 // Dir is bin/ or lib/, depending on where BinaryPath is. 171 std::string Dir = std::string(llvm::sys::path::parent_path(BinaryPath)); 172 173 SmallString<128> P(Dir); 174 if (CustomResourceDir != "") { 175 llvm::sys::path::append(P, CustomResourceDir); 176 } else { 177 // On Windows, libclang.dll is in bin/. 178 // On non-Windows, libclang.so/.dylib is in lib/. 179 // With a static-library build of libclang, LibClangPath will contain the 180 // path of the embedding binary, which for LLVM binaries will be in bin/. 181 // ../lib gets us to lib/ in both cases. 182 P = llvm::sys::path::parent_path(Dir); 183 // This search path is also created in the COFF driver of lld, so any 184 // changes here also needs to happen in lld/COFF/Driver.cpp 185 llvm::sys::path::append(P, CLANG_INSTALL_LIBDIR_BASENAME, "clang", 186 CLANG_VERSION_MAJOR_STRING); 187 } 188 189 return std::string(P); 190 } 191 192 Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple, 193 DiagnosticsEngine &Diags, std::string Title, 194 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) 195 : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode), 196 SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), 197 Offload(OffloadHostDevice), CXX20HeaderType(HeaderMode_None), 198 ModulesModeCXX20(false), LTOMode(LTOK_None), 199 ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT), 200 DriverTitle(Title), CCCPrintBindings(false), CCPrintOptions(false), 201 CCLogDiagnostics(false), CCGenDiagnostics(false), 202 CCPrintProcessStats(false), CCPrintInternalStats(false), 203 TargetTriple(TargetTriple), Saver(Alloc), PrependArg(nullptr), 204 CheckInputsExist(true), ProbePrecompiled(true), 205 SuppressMissingInputWarning(false) { 206 // Provide a sane fallback if no VFS is specified. 207 if (!this->VFS) 208 this->VFS = llvm::vfs::getRealFileSystem(); 209 210 Name = std::string(llvm::sys::path::filename(ClangExecutable)); 211 Dir = std::string(llvm::sys::path::parent_path(ClangExecutable)); 212 InstalledDir = Dir; // Provide a sensible default installed dir. 213 214 if ((!SysRoot.empty()) && llvm::sys::path::is_relative(SysRoot)) { 215 // Prepend InstalledDir if SysRoot is relative 216 SmallString<128> P(InstalledDir); 217 llvm::sys::path::append(P, SysRoot); 218 SysRoot = std::string(P); 219 } 220 221 #if defined(CLANG_CONFIG_FILE_SYSTEM_DIR) 222 SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR; 223 #endif 224 #if defined(CLANG_CONFIG_FILE_USER_DIR) 225 { 226 SmallString<128> P; 227 llvm::sys::fs::expand_tilde(CLANG_CONFIG_FILE_USER_DIR, P); 228 UserConfigDir = static_cast<std::string>(P); 229 } 230 #endif 231 232 // Compute the path to the resource directory. 233 ResourceDir = GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR); 234 } 235 236 void Driver::setDriverMode(StringRef Value) { 237 static StringRef OptName = 238 getOpts().getOption(options::OPT_driver_mode).getPrefixedName(); 239 if (auto M = llvm::StringSwitch<std::optional<DriverMode>>(Value) 240 .Case("gcc", GCCMode) 241 .Case("g++", GXXMode) 242 .Case("cpp", CPPMode) 243 .Case("cl", CLMode) 244 .Case("flang", FlangMode) 245 .Case("dxc", DXCMode) 246 .Default(std::nullopt)) 247 Mode = *M; 248 else 249 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value; 250 } 251 252 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings, 253 bool UseDriverMode, bool &ContainsError) { 254 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing"); 255 ContainsError = false; 256 257 llvm::opt::Visibility VisibilityMask = getOptionVisibilityMask(UseDriverMode); 258 unsigned MissingArgIndex, MissingArgCount; 259 InputArgList Args = getOpts().ParseArgs(ArgStrings, MissingArgIndex, 260 MissingArgCount, VisibilityMask); 261 262 // Check for missing argument error. 263 if (MissingArgCount) { 264 Diag(diag::err_drv_missing_argument) 265 << Args.getArgString(MissingArgIndex) << MissingArgCount; 266 ContainsError |= 267 Diags.getDiagnosticLevel(diag::err_drv_missing_argument, 268 SourceLocation()) > DiagnosticsEngine::Warning; 269 } 270 271 // Check for unsupported options. 272 for (const Arg *A : Args) { 273 if (A->getOption().hasFlag(options::Unsupported)) { 274 Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args); 275 ContainsError |= Diags.getDiagnosticLevel(diag::err_drv_unsupported_opt, 276 SourceLocation()) > 277 DiagnosticsEngine::Warning; 278 continue; 279 } 280 281 // Warn about -mcpu= without an argument. 282 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) { 283 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args); 284 ContainsError |= Diags.getDiagnosticLevel( 285 diag::warn_drv_empty_joined_argument, 286 SourceLocation()) > DiagnosticsEngine::Warning; 287 } 288 } 289 290 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) { 291 unsigned DiagID; 292 auto ArgString = A->getAsString(Args); 293 std::string Nearest; 294 if (getOpts().findNearest(ArgString, Nearest, VisibilityMask) > 1) { 295 if (!IsCLMode() && 296 getOpts().findExact(ArgString, Nearest, 297 llvm::opt::Visibility(options::CC1Option))) { 298 DiagID = diag::err_drv_unknown_argument_with_suggestion; 299 Diags.Report(DiagID) << ArgString << "-Xclang " + Nearest; 300 } else { 301 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl 302 : diag::err_drv_unknown_argument; 303 Diags.Report(DiagID) << ArgString; 304 } 305 } else { 306 DiagID = IsCLMode() 307 ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion 308 : diag::err_drv_unknown_argument_with_suggestion; 309 Diags.Report(DiagID) << ArgString << Nearest; 310 } 311 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) > 312 DiagnosticsEngine::Warning; 313 } 314 315 for (const Arg *A : Args.filtered(options::OPT_o)) { 316 if (ArgStrings[A->getIndex()] == A->getSpelling()) 317 continue; 318 319 // Warn on joined arguments that are similar to a long argument. 320 std::string ArgString = ArgStrings[A->getIndex()]; 321 std::string Nearest; 322 if (getOpts().findExact("-" + ArgString, Nearest, VisibilityMask)) 323 Diags.Report(diag::warn_drv_potentially_misspelled_joined_argument) 324 << A->getAsString(Args) << Nearest; 325 } 326 327 return Args; 328 } 329 330 // Determine which compilation mode we are in. We look for options which 331 // affect the phase, starting with the earliest phases, and record which 332 // option we used to determine the final phase. 333 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, 334 Arg **FinalPhaseArg) const { 335 Arg *PhaseArg = nullptr; 336 phases::ID FinalPhase; 337 338 // -{E,EP,P,M,MM} only run the preprocessor. 339 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) || 340 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) || 341 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) || 342 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P)) || 343 CCGenDiagnostics) { 344 FinalPhase = phases::Preprocess; 345 346 // --precompile only runs up to precompilation. 347 // Options that cause the output of C++20 compiled module interfaces or 348 // header units have the same effect. 349 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile)) || 350 (PhaseArg = DAL.getLastArg(options::OPT_extract_api)) || 351 (PhaseArg = DAL.getLastArg(options::OPT_fmodule_header, 352 options::OPT_fmodule_header_EQ))) { 353 FinalPhase = phases::Precompile; 354 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler. 355 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) || 356 (PhaseArg = DAL.getLastArg(options::OPT_print_supported_cpus)) || 357 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) || 358 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) || 359 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) || 360 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) || 361 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) || 362 (PhaseArg = DAL.getLastArg(options::OPT__analyze)) || 363 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) { 364 FinalPhase = phases::Compile; 365 366 // -S only runs up to the backend. 367 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) { 368 FinalPhase = phases::Backend; 369 370 // -c compilation only runs up to the assembler. 371 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) { 372 FinalPhase = phases::Assemble; 373 374 } else if ((PhaseArg = DAL.getLastArg(options::OPT_emit_interface_stubs))) { 375 FinalPhase = phases::IfsMerge; 376 377 // Otherwise do everything. 378 } else 379 FinalPhase = phases::Link; 380 381 if (FinalPhaseArg) 382 *FinalPhaseArg = PhaseArg; 383 384 return FinalPhase; 385 } 386 387 static Arg *MakeInputArg(DerivedArgList &Args, const OptTable &Opts, 388 StringRef Value, bool Claim = true) { 389 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value, 390 Args.getBaseArgs().MakeIndex(Value), Value.data()); 391 Args.AddSynthesizedArg(A); 392 if (Claim) 393 A->claim(); 394 return A; 395 } 396 397 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const { 398 const llvm::opt::OptTable &Opts = getOpts(); 399 DerivedArgList *DAL = new DerivedArgList(Args); 400 401 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib); 402 bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx); 403 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs); 404 bool IgnoreUnused = false; 405 for (Arg *A : Args) { 406 if (IgnoreUnused) 407 A->claim(); 408 409 if (A->getOption().matches(options::OPT_start_no_unused_arguments)) { 410 IgnoreUnused = true; 411 continue; 412 } 413 if (A->getOption().matches(options::OPT_end_no_unused_arguments)) { 414 IgnoreUnused = false; 415 continue; 416 } 417 418 // Unfortunately, we have to parse some forwarding options (-Xassembler, 419 // -Xlinker, -Xpreprocessor) because we either integrate their functionality 420 // (assembler and preprocessor), or bypass a previous driver ('collect2'). 421 422 // Rewrite linker options, to replace --no-demangle with a custom internal 423 // option. 424 if ((A->getOption().matches(options::OPT_Wl_COMMA) || 425 A->getOption().matches(options::OPT_Xlinker)) && 426 A->containsValue("--no-demangle")) { 427 // Add the rewritten no-demangle argument. 428 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_Xlinker__no_demangle)); 429 430 // Add the remaining values as Xlinker arguments. 431 for (StringRef Val : A->getValues()) 432 if (Val != "--no-demangle") 433 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_Xlinker), Val); 434 435 continue; 436 } 437 438 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by 439 // some build systems. We don't try to be complete here because we don't 440 // care to encourage this usage model. 441 if (A->getOption().matches(options::OPT_Wp_COMMA) && 442 (A->getValue(0) == StringRef("-MD") || 443 A->getValue(0) == StringRef("-MMD"))) { 444 // Rewrite to -MD/-MMD along with -MF. 445 if (A->getValue(0) == StringRef("-MD")) 446 DAL->AddFlagArg(A, Opts.getOption(options::OPT_MD)); 447 else 448 DAL->AddFlagArg(A, Opts.getOption(options::OPT_MMD)); 449 if (A->getNumValues() == 2) 450 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue(1)); 451 continue; 452 } 453 454 // Rewrite reserved library names. 455 if (A->getOption().matches(options::OPT_l)) { 456 StringRef Value = A->getValue(); 457 458 // Rewrite unless -nostdlib is present. 459 if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx && 460 Value == "stdc++") { 461 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_stdcxx)); 462 continue; 463 } 464 465 // Rewrite unconditionally. 466 if (Value == "cc_kext") { 467 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_cckext)); 468 continue; 469 } 470 } 471 472 // Pick up inputs via the -- option. 473 if (A->getOption().matches(options::OPT__DASH_DASH)) { 474 A->claim(); 475 for (StringRef Val : A->getValues()) 476 DAL->append(MakeInputArg(*DAL, Opts, Val, false)); 477 continue; 478 } 479 480 DAL->append(A); 481 } 482 483 // DXC mode quits before assembly if an output object file isn't specified. 484 if (IsDXCMode() && !Args.hasArg(options::OPT_dxc_Fo)) 485 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_S)); 486 487 // Enforce -static if -miamcu is present. 488 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) 489 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_static)); 490 491 // Add a default value of -mlinker-version=, if one was given and the user 492 // didn't specify one. 493 #if defined(HOST_LINK_VERSION) 494 if (!Args.hasArg(options::OPT_mlinker_version_EQ) && 495 strlen(HOST_LINK_VERSION) > 0) { 496 DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mlinker_version_EQ), 497 HOST_LINK_VERSION); 498 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim(); 499 } 500 #endif 501 502 return DAL; 503 } 504 505 /// Compute target triple from args. 506 /// 507 /// This routine provides the logic to compute a target triple from various 508 /// args passed to the driver and the default triple string. 509 static llvm::Triple computeTargetTriple(const Driver &D, 510 StringRef TargetTriple, 511 const ArgList &Args, 512 StringRef DarwinArchName = "") { 513 // FIXME: Already done in Compilation *Driver::BuildCompilation 514 if (const Arg *A = Args.getLastArg(options::OPT_target)) 515 TargetTriple = A->getValue(); 516 517 llvm::Triple Target(llvm::Triple::normalize(TargetTriple)); 518 519 // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made 520 // -gnu* only, and we can not change this, so we have to detect that case as 521 // being the Hurd OS. 522 if (TargetTriple.contains("-unknown-gnu") || TargetTriple.contains("-pc-gnu")) 523 Target.setOSName("hurd"); 524 525 // Handle Apple-specific options available here. 526 if (Target.isOSBinFormatMachO()) { 527 // If an explicit Darwin arch name is given, that trumps all. 528 if (!DarwinArchName.empty()) { 529 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName, 530 Args); 531 return Target; 532 } 533 534 // Handle the Darwin '-arch' flag. 535 if (Arg *A = Args.getLastArg(options::OPT_arch)) { 536 StringRef ArchName = A->getValue(); 537 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName, Args); 538 } 539 } 540 541 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and 542 // '-mbig-endian'/'-EB'. 543 if (Arg *A = Args.getLastArgNoClaim(options::OPT_mlittle_endian, 544 options::OPT_mbig_endian)) { 545 llvm::Triple T = A->getOption().matches(options::OPT_mlittle_endian) 546 ? Target.getLittleEndianArchVariant() 547 : Target.getBigEndianArchVariant(); 548 if (T.getArch() != llvm::Triple::UnknownArch) { 549 Target = std::move(T); 550 Args.claimAllArgs(options::OPT_mlittle_endian, options::OPT_mbig_endian); 551 } 552 } 553 554 // Skip further flag support on OSes which don't support '-m32' or '-m64'. 555 if (Target.getArch() == llvm::Triple::tce) 556 return Target; 557 558 // On AIX, the env OBJECT_MODE may affect the resulting arch variant. 559 if (Target.isOSAIX()) { 560 if (std::optional<std::string> ObjectModeValue = 561 llvm::sys::Process::GetEnv("OBJECT_MODE")) { 562 StringRef ObjectMode = *ObjectModeValue; 563 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch; 564 565 if (ObjectMode.equals("64")) { 566 AT = Target.get64BitArchVariant().getArch(); 567 } else if (ObjectMode.equals("32")) { 568 AT = Target.get32BitArchVariant().getArch(); 569 } else { 570 D.Diag(diag::err_drv_invalid_object_mode) << ObjectMode; 571 } 572 573 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) 574 Target.setArch(AT); 575 } 576 } 577 578 // The `-maix[32|64]` flags are only valid for AIX targets. 579 if (Arg *A = Args.getLastArgNoClaim(options::OPT_maix32, options::OPT_maix64); 580 A && !Target.isOSAIX()) 581 D.Diag(diag::err_drv_unsupported_opt_for_target) 582 << A->getAsString(Args) << Target.str(); 583 584 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'. 585 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32, 586 options::OPT_m32, options::OPT_m16, 587 options::OPT_maix32, options::OPT_maix64); 588 if (A) { 589 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch; 590 591 if (A->getOption().matches(options::OPT_m64) || 592 A->getOption().matches(options::OPT_maix64)) { 593 AT = Target.get64BitArchVariant().getArch(); 594 if (Target.getEnvironment() == llvm::Triple::GNUX32) 595 Target.setEnvironment(llvm::Triple::GNU); 596 else if (Target.getEnvironment() == llvm::Triple::MuslX32) 597 Target.setEnvironment(llvm::Triple::Musl); 598 } else if (A->getOption().matches(options::OPT_mx32) && 599 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) { 600 AT = llvm::Triple::x86_64; 601 if (Target.getEnvironment() == llvm::Triple::Musl) 602 Target.setEnvironment(llvm::Triple::MuslX32); 603 else 604 Target.setEnvironment(llvm::Triple::GNUX32); 605 } else if (A->getOption().matches(options::OPT_m32) || 606 A->getOption().matches(options::OPT_maix32)) { 607 AT = Target.get32BitArchVariant().getArch(); 608 if (Target.getEnvironment() == llvm::Triple::GNUX32) 609 Target.setEnvironment(llvm::Triple::GNU); 610 else if (Target.getEnvironment() == llvm::Triple::MuslX32) 611 Target.setEnvironment(llvm::Triple::Musl); 612 } else if (A->getOption().matches(options::OPT_m16) && 613 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) { 614 AT = llvm::Triple::x86; 615 Target.setEnvironment(llvm::Triple::CODE16); 616 } 617 618 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) { 619 Target.setArch(AT); 620 if (Target.isWindowsGNUEnvironment()) 621 toolchains::MinGW::fixTripleArch(D, Target, Args); 622 } 623 } 624 625 // Handle -miamcu flag. 626 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) { 627 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86) 628 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu" 629 << Target.str(); 630 631 if (A && !A->getOption().matches(options::OPT_m32)) 632 D.Diag(diag::err_drv_argument_not_allowed_with) 633 << "-miamcu" << A->getBaseArg().getAsString(Args); 634 635 Target.setArch(llvm::Triple::x86); 636 Target.setArchName("i586"); 637 Target.setEnvironment(llvm::Triple::UnknownEnvironment); 638 Target.setEnvironmentName(""); 639 Target.setOS(llvm::Triple::ELFIAMCU); 640 Target.setVendor(llvm::Triple::UnknownVendor); 641 Target.setVendorName("intel"); 642 } 643 644 // If target is MIPS adjust the target triple 645 // accordingly to provided ABI name. 646 if (Target.isMIPS()) { 647 if ((A = Args.getLastArg(options::OPT_mabi_EQ))) { 648 StringRef ABIName = A->getValue(); 649 if (ABIName == "32") { 650 Target = Target.get32BitArchVariant(); 651 if (Target.getEnvironment() == llvm::Triple::GNUABI64 || 652 Target.getEnvironment() == llvm::Triple::GNUABIN32) 653 Target.setEnvironment(llvm::Triple::GNU); 654 } else if (ABIName == "n32") { 655 Target = Target.get64BitArchVariant(); 656 if (Target.getEnvironment() == llvm::Triple::GNU || 657 Target.getEnvironment() == llvm::Triple::GNUABI64) 658 Target.setEnvironment(llvm::Triple::GNUABIN32); 659 } else if (ABIName == "64") { 660 Target = Target.get64BitArchVariant(); 661 if (Target.getEnvironment() == llvm::Triple::GNU || 662 Target.getEnvironment() == llvm::Triple::GNUABIN32) 663 Target.setEnvironment(llvm::Triple::GNUABI64); 664 } 665 } 666 } 667 668 // If target is RISC-V adjust the target triple according to 669 // provided architecture name 670 if (Target.isRISCV()) { 671 if (Args.hasArg(options::OPT_march_EQ) || 672 Args.hasArg(options::OPT_mcpu_EQ)) { 673 StringRef ArchName = tools::riscv::getRISCVArch(Args, Target); 674 auto ISAInfo = llvm::RISCVISAInfo::parseArchString( 675 ArchName, /*EnableExperimentalExtensions=*/true); 676 if (!llvm::errorToBool(ISAInfo.takeError())) { 677 unsigned XLen = (*ISAInfo)->getXLen(); 678 if (XLen == 32) 679 Target.setArch(llvm::Triple::riscv32); 680 else if (XLen == 64) 681 Target.setArch(llvm::Triple::riscv64); 682 } 683 } 684 } 685 686 return Target; 687 } 688 689 // Parse the LTO options and record the type of LTO compilation 690 // based on which -f(no-)?lto(=.*)? or -f(no-)?offload-lto(=.*)? 691 // option occurs last. 692 static driver::LTOKind parseLTOMode(Driver &D, const llvm::opt::ArgList &Args, 693 OptSpecifier OptEq, OptSpecifier OptNeg) { 694 if (!Args.hasFlag(OptEq, OptNeg, false)) 695 return LTOK_None; 696 697 const Arg *A = Args.getLastArg(OptEq); 698 StringRef LTOName = A->getValue(); 699 700 driver::LTOKind LTOMode = llvm::StringSwitch<LTOKind>(LTOName) 701 .Case("full", LTOK_Full) 702 .Case("thin", LTOK_Thin) 703 .Default(LTOK_Unknown); 704 705 if (LTOMode == LTOK_Unknown) { 706 D.Diag(diag::err_drv_unsupported_option_argument) 707 << A->getSpelling() << A->getValue(); 708 return LTOK_None; 709 } 710 return LTOMode; 711 } 712 713 // Parse the LTO options. 714 void Driver::setLTOMode(const llvm::opt::ArgList &Args) { 715 LTOMode = 716 parseLTOMode(*this, Args, options::OPT_flto_EQ, options::OPT_fno_lto); 717 718 OffloadLTOMode = parseLTOMode(*this, Args, options::OPT_foffload_lto_EQ, 719 options::OPT_fno_offload_lto); 720 721 // Try to enable `-foffload-lto=full` if `-fopenmp-target-jit` is on. 722 if (Args.hasFlag(options::OPT_fopenmp_target_jit, 723 options::OPT_fno_openmp_target_jit, false)) { 724 if (Arg *A = Args.getLastArg(options::OPT_foffload_lto_EQ, 725 options::OPT_fno_offload_lto)) 726 if (OffloadLTOMode != LTOK_Full) 727 Diag(diag::err_drv_incompatible_options) 728 << A->getSpelling() << "-fopenmp-target-jit"; 729 OffloadLTOMode = LTOK_Full; 730 } 731 } 732 733 /// Compute the desired OpenMP runtime from the flags provided. 734 Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const { 735 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME); 736 737 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ); 738 if (A) 739 RuntimeName = A->getValue(); 740 741 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName) 742 .Case("libomp", OMPRT_OMP) 743 .Case("libgomp", OMPRT_GOMP) 744 .Case("libiomp5", OMPRT_IOMP5) 745 .Default(OMPRT_Unknown); 746 747 if (RT == OMPRT_Unknown) { 748 if (A) 749 Diag(diag::err_drv_unsupported_option_argument) 750 << A->getSpelling() << A->getValue(); 751 else 752 // FIXME: We could use a nicer diagnostic here. 753 Diag(diag::err_drv_unsupported_opt) << "-fopenmp"; 754 } 755 756 return RT; 757 } 758 759 void Driver::CreateOffloadingDeviceToolChains(Compilation &C, 760 InputList &Inputs) { 761 762 // 763 // CUDA/HIP 764 // 765 // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA 766 // or HIP type. However, mixed CUDA/HIP compilation is not supported. 767 bool IsCuda = 768 llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) { 769 return types::isCuda(I.first); 770 }); 771 bool IsHIP = 772 llvm::any_of(Inputs, 773 [](std::pair<types::ID, const llvm::opt::Arg *> &I) { 774 return types::isHIP(I.first); 775 }) || 776 C.getInputArgs().hasArg(options::OPT_hip_link) || 777 C.getInputArgs().hasArg(options::OPT_hipstdpar); 778 if (IsCuda && IsHIP) { 779 Diag(clang::diag::err_drv_mix_cuda_hip); 780 return; 781 } 782 if (IsCuda) { 783 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>(); 784 const llvm::Triple &HostTriple = HostTC->getTriple(); 785 auto OFK = Action::OFK_Cuda; 786 auto CudaTriple = 787 getNVIDIAOffloadTargetTriple(*this, C.getInputArgs(), HostTriple); 788 if (!CudaTriple) 789 return; 790 // Use the CUDA and host triples as the key into the ToolChains map, 791 // because the device toolchain we create depends on both. 792 auto &CudaTC = ToolChains[CudaTriple->str() + "/" + HostTriple.str()]; 793 if (!CudaTC) { 794 CudaTC = std::make_unique<toolchains::CudaToolChain>( 795 *this, *CudaTriple, *HostTC, C.getInputArgs()); 796 797 // Emit a warning if the detected CUDA version is too new. 798 CudaInstallationDetector &CudaInstallation = 799 static_cast<toolchains::CudaToolChain &>(*CudaTC).CudaInstallation; 800 if (CudaInstallation.isValid()) 801 CudaInstallation.WarnIfUnsupportedVersion(); 802 } 803 C.addOffloadDeviceToolChain(CudaTC.get(), OFK); 804 } else if (IsHIP) { 805 if (auto *OMPTargetArg = 806 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) { 807 Diag(clang::diag::err_drv_unsupported_opt_for_language_mode) 808 << OMPTargetArg->getSpelling() << "HIP"; 809 return; 810 } 811 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>(); 812 auto OFK = Action::OFK_HIP; 813 auto HIPTriple = getHIPOffloadTargetTriple(*this, C.getInputArgs()); 814 if (!HIPTriple) 815 return; 816 auto *HIPTC = &getOffloadingDeviceToolChain(C.getInputArgs(), *HIPTriple, 817 *HostTC, OFK); 818 assert(HIPTC && "Could not create offloading device tool chain."); 819 C.addOffloadDeviceToolChain(HIPTC, OFK); 820 } 821 822 // 823 // OpenMP 824 // 825 // We need to generate an OpenMP toolchain if the user specified targets with 826 // the -fopenmp-targets option or used --offload-arch with OpenMP enabled. 827 bool IsOpenMPOffloading = 828 C.getInputArgs().hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ, 829 options::OPT_fno_openmp, false) && 830 (C.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ) || 831 C.getInputArgs().hasArg(options::OPT_offload_arch_EQ)); 832 if (IsOpenMPOffloading) { 833 // We expect that -fopenmp-targets is always used in conjunction with the 834 // option -fopenmp specifying a valid runtime with offloading support, i.e. 835 // libomp or libiomp. 836 OpenMPRuntimeKind RuntimeKind = getOpenMPRuntime(C.getInputArgs()); 837 if (RuntimeKind != OMPRT_OMP && RuntimeKind != OMPRT_IOMP5) { 838 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets); 839 return; 840 } 841 842 llvm::StringMap<llvm::DenseSet<StringRef>> DerivedArchs; 843 llvm::StringMap<StringRef> FoundNormalizedTriples; 844 std::multiset<StringRef> OpenMPTriples; 845 846 // If the user specified -fopenmp-targets= we create a toolchain for each 847 // valid triple. Otherwise, if only --offload-arch= was specified we instead 848 // attempt to derive the appropriate toolchains from the arguments. 849 if (Arg *OpenMPTargets = 850 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) { 851 if (OpenMPTargets && !OpenMPTargets->getNumValues()) { 852 Diag(clang::diag::warn_drv_empty_joined_argument) 853 << OpenMPTargets->getAsString(C.getInputArgs()); 854 return; 855 } 856 for (StringRef T : OpenMPTargets->getValues()) 857 OpenMPTriples.insert(T); 858 } else if (C.getInputArgs().hasArg(options::OPT_offload_arch_EQ) && 859 !IsHIP && !IsCuda) { 860 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>(); 861 auto AMDTriple = getHIPOffloadTargetTriple(*this, C.getInputArgs()); 862 auto NVPTXTriple = getNVIDIAOffloadTargetTriple(*this, C.getInputArgs(), 863 HostTC->getTriple()); 864 865 // Attempt to deduce the offloading triple from the set of architectures. 866 // We can only correctly deduce NVPTX / AMDGPU triples currently. We need 867 // to temporarily create these toolchains so that we can access tools for 868 // inferring architectures. 869 llvm::DenseSet<StringRef> Archs; 870 if (NVPTXTriple) { 871 auto TempTC = std::make_unique<toolchains::CudaToolChain>( 872 *this, *NVPTXTriple, *HostTC, C.getInputArgs()); 873 for (StringRef Arch : getOffloadArchs( 874 C, C.getArgs(), Action::OFK_OpenMP, &*TempTC, true)) 875 Archs.insert(Arch); 876 } 877 if (AMDTriple) { 878 auto TempTC = std::make_unique<toolchains::AMDGPUOpenMPToolChain>( 879 *this, *AMDTriple, *HostTC, C.getInputArgs()); 880 for (StringRef Arch : getOffloadArchs( 881 C, C.getArgs(), Action::OFK_OpenMP, &*TempTC, true)) 882 Archs.insert(Arch); 883 } 884 if (!AMDTriple && !NVPTXTriple) { 885 for (StringRef Arch : 886 getOffloadArchs(C, C.getArgs(), Action::OFK_OpenMP, nullptr, true)) 887 Archs.insert(Arch); 888 } 889 890 for (StringRef Arch : Archs) { 891 if (NVPTXTriple && IsNVIDIAGpuArch(StringToCudaArch( 892 getProcessorFromTargetID(*NVPTXTriple, Arch)))) { 893 DerivedArchs[NVPTXTriple->getTriple()].insert(Arch); 894 } else if (AMDTriple && 895 IsAMDGpuArch(StringToCudaArch( 896 getProcessorFromTargetID(*AMDTriple, Arch)))) { 897 DerivedArchs[AMDTriple->getTriple()].insert(Arch); 898 } else { 899 Diag(clang::diag::err_drv_failed_to_deduce_target_from_arch) << Arch; 900 return; 901 } 902 } 903 904 // If the set is empty then we failed to find a native architecture. 905 if (Archs.empty()) { 906 Diag(clang::diag::err_drv_failed_to_deduce_target_from_arch) 907 << "native"; 908 return; 909 } 910 911 for (const auto &TripleAndArchs : DerivedArchs) 912 OpenMPTriples.insert(TripleAndArchs.first()); 913 } 914 915 for (StringRef Val : OpenMPTriples) { 916 llvm::Triple TT(ToolChain::getOpenMPTriple(Val)); 917 std::string NormalizedName = TT.normalize(); 918 919 // Make sure we don't have a duplicate triple. 920 auto Duplicate = FoundNormalizedTriples.find(NormalizedName); 921 if (Duplicate != FoundNormalizedTriples.end()) { 922 Diag(clang::diag::warn_drv_omp_offload_target_duplicate) 923 << Val << Duplicate->second; 924 continue; 925 } 926 927 // Store the current triple so that we can check for duplicates in the 928 // following iterations. 929 FoundNormalizedTriples[NormalizedName] = Val; 930 931 // If the specified target is invalid, emit a diagnostic. 932 if (TT.getArch() == llvm::Triple::UnknownArch) 933 Diag(clang::diag::err_drv_invalid_omp_target) << Val; 934 else { 935 const ToolChain *TC; 936 // Device toolchains have to be selected differently. They pair host 937 // and device in their implementation. 938 if (TT.isNVPTX() || TT.isAMDGCN()) { 939 const ToolChain *HostTC = 940 C.getSingleOffloadToolChain<Action::OFK_Host>(); 941 assert(HostTC && "Host toolchain should be always defined."); 942 auto &DeviceTC = 943 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()]; 944 if (!DeviceTC) { 945 if (TT.isNVPTX()) 946 DeviceTC = std::make_unique<toolchains::CudaToolChain>( 947 *this, TT, *HostTC, C.getInputArgs()); 948 else if (TT.isAMDGCN()) 949 DeviceTC = std::make_unique<toolchains::AMDGPUOpenMPToolChain>( 950 *this, TT, *HostTC, C.getInputArgs()); 951 else 952 assert(DeviceTC && "Device toolchain not defined."); 953 } 954 955 TC = DeviceTC.get(); 956 } else 957 TC = &getToolChain(C.getInputArgs(), TT); 958 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP); 959 if (DerivedArchs.contains(TT.getTriple())) 960 KnownArchs[TC] = DerivedArchs[TT.getTriple()]; 961 } 962 } 963 } else if (C.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ)) { 964 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets); 965 return; 966 } 967 968 // 969 // TODO: Add support for other offloading programming models here. 970 // 971 } 972 973 static void appendOneArg(InputArgList &Args, const Arg *Opt, 974 const Arg *BaseArg) { 975 // The args for config files or /clang: flags belong to different InputArgList 976 // objects than Args. This copies an Arg from one of those other InputArgLists 977 // to the ownership of Args. 978 unsigned Index = Args.MakeIndex(Opt->getSpelling()); 979 Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Args.getArgString(Index), 980 Index, BaseArg); 981 Copy->getValues() = Opt->getValues(); 982 if (Opt->isClaimed()) 983 Copy->claim(); 984 Copy->setOwnsValues(Opt->getOwnsValues()); 985 Opt->setOwnsValues(false); 986 Args.append(Copy); 987 } 988 989 bool Driver::readConfigFile(StringRef FileName, 990 llvm::cl::ExpansionContext &ExpCtx) { 991 // Try opening the given file. 992 auto Status = getVFS().status(FileName); 993 if (!Status) { 994 Diag(diag::err_drv_cannot_open_config_file) 995 << FileName << Status.getError().message(); 996 return true; 997 } 998 if (Status->getType() != llvm::sys::fs::file_type::regular_file) { 999 Diag(diag::err_drv_cannot_open_config_file) 1000 << FileName << "not a regular file"; 1001 return true; 1002 } 1003 1004 // Try reading the given file. 1005 SmallVector<const char *, 32> NewCfgArgs; 1006 if (llvm::Error Err = ExpCtx.readConfigFile(FileName, NewCfgArgs)) { 1007 Diag(diag::err_drv_cannot_read_config_file) 1008 << FileName << toString(std::move(Err)); 1009 return true; 1010 } 1011 1012 // Read options from config file. 1013 llvm::SmallString<128> CfgFileName(FileName); 1014 llvm::sys::path::native(CfgFileName); 1015 bool ContainErrors; 1016 std::unique_ptr<InputArgList> NewOptions = std::make_unique<InputArgList>( 1017 ParseArgStrings(NewCfgArgs, /*UseDriverMode=*/true, ContainErrors)); 1018 if (ContainErrors) 1019 return true; 1020 1021 // Claim all arguments that come from a configuration file so that the driver 1022 // does not warn on any that is unused. 1023 for (Arg *A : *NewOptions) 1024 A->claim(); 1025 1026 if (!CfgOptions) 1027 CfgOptions = std::move(NewOptions); 1028 else { 1029 // If this is a subsequent config file, append options to the previous one. 1030 for (auto *Opt : *NewOptions) { 1031 const Arg *BaseArg = &Opt->getBaseArg(); 1032 if (BaseArg == Opt) 1033 BaseArg = nullptr; 1034 appendOneArg(*CfgOptions, Opt, BaseArg); 1035 } 1036 } 1037 ConfigFiles.push_back(std::string(CfgFileName)); 1038 return false; 1039 } 1040 1041 bool Driver::loadConfigFiles() { 1042 llvm::cl::ExpansionContext ExpCtx(Saver.getAllocator(), 1043 llvm::cl::tokenizeConfigFile); 1044 ExpCtx.setVFS(&getVFS()); 1045 1046 // Process options that change search path for config files. 1047 if (CLOptions) { 1048 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) { 1049 SmallString<128> CfgDir; 1050 CfgDir.append( 1051 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ)); 1052 if (CfgDir.empty() || getVFS().makeAbsolute(CfgDir)) 1053 SystemConfigDir.clear(); 1054 else 1055 SystemConfigDir = static_cast<std::string>(CfgDir); 1056 } 1057 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) { 1058 SmallString<128> CfgDir; 1059 llvm::sys::fs::expand_tilde( 1060 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ), CfgDir); 1061 if (CfgDir.empty() || getVFS().makeAbsolute(CfgDir)) 1062 UserConfigDir.clear(); 1063 else 1064 UserConfigDir = static_cast<std::string>(CfgDir); 1065 } 1066 } 1067 1068 // Prepare list of directories where config file is searched for. 1069 StringRef CfgFileSearchDirs[] = {UserConfigDir, SystemConfigDir, Dir}; 1070 ExpCtx.setSearchDirs(CfgFileSearchDirs); 1071 1072 // First try to load configuration from the default files, return on error. 1073 if (loadDefaultConfigFiles(ExpCtx)) 1074 return true; 1075 1076 // Then load configuration files specified explicitly. 1077 SmallString<128> CfgFilePath; 1078 if (CLOptions) { 1079 for (auto CfgFileName : CLOptions->getAllArgValues(options::OPT_config)) { 1080 // If argument contains directory separator, treat it as a path to 1081 // configuration file. 1082 if (llvm::sys::path::has_parent_path(CfgFileName)) { 1083 CfgFilePath.assign(CfgFileName); 1084 if (llvm::sys::path::is_relative(CfgFilePath)) { 1085 if (getVFS().makeAbsolute(CfgFilePath)) { 1086 Diag(diag::err_drv_cannot_open_config_file) 1087 << CfgFilePath << "cannot get absolute path"; 1088 return true; 1089 } 1090 } 1091 } else if (!ExpCtx.findConfigFile(CfgFileName, CfgFilePath)) { 1092 // Report an error that the config file could not be found. 1093 Diag(diag::err_drv_config_file_not_found) << CfgFileName; 1094 for (const StringRef &SearchDir : CfgFileSearchDirs) 1095 if (!SearchDir.empty()) 1096 Diag(diag::note_drv_config_file_searched_in) << SearchDir; 1097 return true; 1098 } 1099 1100 // Try to read the config file, return on error. 1101 if (readConfigFile(CfgFilePath, ExpCtx)) 1102 return true; 1103 } 1104 } 1105 1106 // No error occurred. 1107 return false; 1108 } 1109 1110 bool Driver::loadDefaultConfigFiles(llvm::cl::ExpansionContext &ExpCtx) { 1111 // Disable default config if CLANG_NO_DEFAULT_CONFIG is set to a non-empty 1112 // value. 1113 if (const char *NoConfigEnv = ::getenv("CLANG_NO_DEFAULT_CONFIG")) { 1114 if (*NoConfigEnv) 1115 return false; 1116 } 1117 if (CLOptions && CLOptions->hasArg(options::OPT_no_default_config)) 1118 return false; 1119 1120 std::string RealMode = getExecutableForDriverMode(Mode); 1121 std::string Triple; 1122 1123 // If name prefix is present, no --target= override was passed via CLOptions 1124 // and the name prefix is not a valid triple, force it for backwards 1125 // compatibility. 1126 if (!ClangNameParts.TargetPrefix.empty() && 1127 computeTargetTriple(*this, "/invalid/", *CLOptions).str() == 1128 "/invalid/") { 1129 llvm::Triple PrefixTriple{ClangNameParts.TargetPrefix}; 1130 if (PrefixTriple.getArch() == llvm::Triple::UnknownArch || 1131 PrefixTriple.isOSUnknown()) 1132 Triple = PrefixTriple.str(); 1133 } 1134 1135 // Otherwise, use the real triple as used by the driver. 1136 if (Triple.empty()) { 1137 llvm::Triple RealTriple = 1138 computeTargetTriple(*this, TargetTriple, *CLOptions); 1139 Triple = RealTriple.str(); 1140 assert(!Triple.empty()); 1141 } 1142 1143 // Search for config files in the following order: 1144 // 1. <triple>-<mode>.cfg using real driver mode 1145 // (e.g. i386-pc-linux-gnu-clang++.cfg). 1146 // 2. <triple>-<mode>.cfg using executable suffix 1147 // (e.g. i386-pc-linux-gnu-clang-g++.cfg for *clang-g++). 1148 // 3. <triple>.cfg + <mode>.cfg using real driver mode 1149 // (e.g. i386-pc-linux-gnu.cfg + clang++.cfg). 1150 // 4. <triple>.cfg + <mode>.cfg using executable suffix 1151 // (e.g. i386-pc-linux-gnu.cfg + clang-g++.cfg for *clang-g++). 1152 1153 // Try loading <triple>-<mode>.cfg, and return if we find a match. 1154 SmallString<128> CfgFilePath; 1155 std::string CfgFileName = Triple + '-' + RealMode + ".cfg"; 1156 if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath)) 1157 return readConfigFile(CfgFilePath, ExpCtx); 1158 1159 bool TryModeSuffix = !ClangNameParts.ModeSuffix.empty() && 1160 ClangNameParts.ModeSuffix != RealMode; 1161 if (TryModeSuffix) { 1162 CfgFileName = Triple + '-' + ClangNameParts.ModeSuffix + ".cfg"; 1163 if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath)) 1164 return readConfigFile(CfgFilePath, ExpCtx); 1165 } 1166 1167 // Try loading <mode>.cfg, and return if loading failed. If a matching file 1168 // was not found, still proceed on to try <triple>.cfg. 1169 CfgFileName = RealMode + ".cfg"; 1170 if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath)) { 1171 if (readConfigFile(CfgFilePath, ExpCtx)) 1172 return true; 1173 } else if (TryModeSuffix) { 1174 CfgFileName = ClangNameParts.ModeSuffix + ".cfg"; 1175 if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath) && 1176 readConfigFile(CfgFilePath, ExpCtx)) 1177 return true; 1178 } 1179 1180 // Try loading <triple>.cfg and return if we find a match. 1181 CfgFileName = Triple + ".cfg"; 1182 if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath)) 1183 return readConfigFile(CfgFilePath, ExpCtx); 1184 1185 // If we were unable to find a config file deduced from executable name, 1186 // that is not an error. 1187 return false; 1188 } 1189 1190 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) { 1191 llvm::PrettyStackTraceString CrashInfo("Compilation construction"); 1192 1193 // FIXME: Handle environment options which affect driver behavior, somewhere 1194 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS. 1195 1196 // We look for the driver mode option early, because the mode can affect 1197 // how other options are parsed. 1198 1199 auto DriverMode = getDriverMode(ClangExecutable, ArgList.slice(1)); 1200 if (!DriverMode.empty()) 1201 setDriverMode(DriverMode); 1202 1203 // FIXME: What are we going to do with -V and -b? 1204 1205 // Arguments specified in command line. 1206 bool ContainsError; 1207 CLOptions = std::make_unique<InputArgList>( 1208 ParseArgStrings(ArgList.slice(1), /*UseDriverMode=*/true, ContainsError)); 1209 1210 // Try parsing configuration file. 1211 if (!ContainsError) 1212 ContainsError = loadConfigFiles(); 1213 bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr); 1214 1215 // All arguments, from both config file and command line. 1216 InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions) 1217 : std::move(*CLOptions)); 1218 1219 if (HasConfigFile) 1220 for (auto *Opt : *CLOptions) { 1221 if (Opt->getOption().matches(options::OPT_config)) 1222 continue; 1223 const Arg *BaseArg = &Opt->getBaseArg(); 1224 if (BaseArg == Opt) 1225 BaseArg = nullptr; 1226 appendOneArg(Args, Opt, BaseArg); 1227 } 1228 1229 // In CL mode, look for any pass-through arguments 1230 if (IsCLMode() && !ContainsError) { 1231 SmallVector<const char *, 16> CLModePassThroughArgList; 1232 for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) { 1233 A->claim(); 1234 CLModePassThroughArgList.push_back(A->getValue()); 1235 } 1236 1237 if (!CLModePassThroughArgList.empty()) { 1238 // Parse any pass through args using default clang processing rather 1239 // than clang-cl processing. 1240 auto CLModePassThroughOptions = std::make_unique<InputArgList>( 1241 ParseArgStrings(CLModePassThroughArgList, /*UseDriverMode=*/false, 1242 ContainsError)); 1243 1244 if (!ContainsError) 1245 for (auto *Opt : *CLModePassThroughOptions) { 1246 appendOneArg(Args, Opt, nullptr); 1247 } 1248 } 1249 } 1250 1251 // Check for working directory option before accessing any files 1252 if (Arg *WD = Args.getLastArg(options::OPT_working_directory)) 1253 if (VFS->setCurrentWorkingDirectory(WD->getValue())) 1254 Diag(diag::err_drv_unable_to_set_working_directory) << WD->getValue(); 1255 1256 // FIXME: This stuff needs to go into the Compilation, not the driver. 1257 bool CCCPrintPhases; 1258 1259 // -canonical-prefixes, -no-canonical-prefixes are used very early in main. 1260 Args.ClaimAllArgs(options::OPT_canonical_prefixes); 1261 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes); 1262 1263 // f(no-)integated-cc1 is also used very early in main. 1264 Args.ClaimAllArgs(options::OPT_fintegrated_cc1); 1265 Args.ClaimAllArgs(options::OPT_fno_integrated_cc1); 1266 1267 // Ignore -pipe. 1268 Args.ClaimAllArgs(options::OPT_pipe); 1269 1270 // Extract -ccc args. 1271 // 1272 // FIXME: We need to figure out where this behavior should live. Most of it 1273 // should be outside in the client; the parts that aren't should have proper 1274 // options, either by introducing new ones or by overloading gcc ones like -V 1275 // or -b. 1276 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases); 1277 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings); 1278 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name)) 1279 CCCGenericGCCName = A->getValue(); 1280 1281 // Process -fproc-stat-report options. 1282 if (const Arg *A = Args.getLastArg(options::OPT_fproc_stat_report_EQ)) { 1283 CCPrintProcessStats = true; 1284 CCPrintStatReportFilename = A->getValue(); 1285 } 1286 if (Args.hasArg(options::OPT_fproc_stat_report)) 1287 CCPrintProcessStats = true; 1288 1289 // FIXME: TargetTriple is used by the target-prefixed calls to as/ld 1290 // and getToolChain is const. 1291 if (IsCLMode()) { 1292 // clang-cl targets MSVC-style Win32. 1293 llvm::Triple T(TargetTriple); 1294 T.setOS(llvm::Triple::Win32); 1295 T.setVendor(llvm::Triple::PC); 1296 T.setEnvironment(llvm::Triple::MSVC); 1297 T.setObjectFormat(llvm::Triple::COFF); 1298 if (Args.hasArg(options::OPT__SLASH_arm64EC)) 1299 T.setArch(llvm::Triple::aarch64, llvm::Triple::AArch64SubArch_arm64ec); 1300 TargetTriple = T.str(); 1301 } else if (IsDXCMode()) { 1302 // Build TargetTriple from target_profile option for clang-dxc. 1303 if (const Arg *A = Args.getLastArg(options::OPT_target_profile)) { 1304 StringRef TargetProfile = A->getValue(); 1305 if (auto Triple = 1306 toolchains::HLSLToolChain::parseTargetProfile(TargetProfile)) 1307 TargetTriple = *Triple; 1308 else 1309 Diag(diag::err_drv_invalid_directx_shader_module) << TargetProfile; 1310 1311 A->claim(); 1312 1313 if (Args.hasArg(options::OPT_spirv)) { 1314 llvm::Triple T(TargetTriple); 1315 T.setArch(llvm::Triple::spirv); 1316 T.setOS(llvm::Triple::Vulkan); 1317 1318 // Set specific Vulkan version if applicable. 1319 if (const Arg *A = Args.getLastArg(options::OPT_fspv_target_env_EQ)) { 1320 const llvm::StringSet<> ValidValues = {"vulkan1.2", "vulkan1.3"}; 1321 if (ValidValues.contains(A->getValue())) { 1322 T.setOSName(A->getValue()); 1323 } else { 1324 Diag(diag::err_drv_invalid_value) 1325 << A->getAsString(Args) << A->getValue(); 1326 } 1327 A->claim(); 1328 } 1329 1330 TargetTriple = T.str(); 1331 } 1332 } else { 1333 Diag(diag::err_drv_dxc_missing_target_profile); 1334 } 1335 } 1336 1337 if (const Arg *A = Args.getLastArg(options::OPT_target)) 1338 TargetTriple = A->getValue(); 1339 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir)) 1340 Dir = InstalledDir = A->getValue(); 1341 for (const Arg *A : Args.filtered(options::OPT_B)) { 1342 A->claim(); 1343 PrefixDirs.push_back(A->getValue(0)); 1344 } 1345 if (std::optional<std::string> CompilerPathValue = 1346 llvm::sys::Process::GetEnv("COMPILER_PATH")) { 1347 StringRef CompilerPath = *CompilerPathValue; 1348 while (!CompilerPath.empty()) { 1349 std::pair<StringRef, StringRef> Split = 1350 CompilerPath.split(llvm::sys::EnvPathSeparator); 1351 PrefixDirs.push_back(std::string(Split.first)); 1352 CompilerPath = Split.second; 1353 } 1354 } 1355 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ)) 1356 SysRoot = A->getValue(); 1357 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ)) 1358 DyldPrefix = A->getValue(); 1359 1360 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir)) 1361 ResourceDir = A->getValue(); 1362 1363 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) { 1364 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue()) 1365 .Case("cwd", SaveTempsCwd) 1366 .Case("obj", SaveTempsObj) 1367 .Default(SaveTempsCwd); 1368 } 1369 1370 if (const Arg *A = Args.getLastArg(options::OPT_offload_host_only, 1371 options::OPT_offload_device_only, 1372 options::OPT_offload_host_device)) { 1373 if (A->getOption().matches(options::OPT_offload_host_only)) 1374 Offload = OffloadHost; 1375 else if (A->getOption().matches(options::OPT_offload_device_only)) 1376 Offload = OffloadDevice; 1377 else 1378 Offload = OffloadHostDevice; 1379 } 1380 1381 setLTOMode(Args); 1382 1383 // Process -fembed-bitcode= flags. 1384 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) { 1385 StringRef Name = A->getValue(); 1386 unsigned Model = llvm::StringSwitch<unsigned>(Name) 1387 .Case("off", EmbedNone) 1388 .Case("all", EmbedBitcode) 1389 .Case("bitcode", EmbedBitcode) 1390 .Case("marker", EmbedMarker) 1391 .Default(~0U); 1392 if (Model == ~0U) { 1393 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) 1394 << Name; 1395 } else 1396 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model); 1397 } 1398 1399 // Remove existing compilation database so that each job can append to it. 1400 if (Arg *A = Args.getLastArg(options::OPT_MJ)) 1401 llvm::sys::fs::remove(A->getValue()); 1402 1403 // Setting up the jobs for some precompile cases depends on whether we are 1404 // treating them as PCH, implicit modules or C++20 ones. 1405 // TODO: inferring the mode like this seems fragile (it meets the objective 1406 // of not requiring anything new for operation, however). 1407 const Arg *Std = Args.getLastArg(options::OPT_std_EQ); 1408 ModulesModeCXX20 = 1409 !Args.hasArg(options::OPT_fmodules) && Std && 1410 (Std->containsValue("c++20") || Std->containsValue("c++2a") || 1411 Std->containsValue("c++23") || Std->containsValue("c++2b") || 1412 Std->containsValue("c++26") || Std->containsValue("c++2c") || 1413 Std->containsValue("c++latest")); 1414 1415 // Process -fmodule-header{=} flags. 1416 if (Arg *A = Args.getLastArg(options::OPT_fmodule_header_EQ, 1417 options::OPT_fmodule_header)) { 1418 // These flags force C++20 handling of headers. 1419 ModulesModeCXX20 = true; 1420 if (A->getOption().matches(options::OPT_fmodule_header)) 1421 CXX20HeaderType = HeaderMode_Default; 1422 else { 1423 StringRef ArgName = A->getValue(); 1424 unsigned Kind = llvm::StringSwitch<unsigned>(ArgName) 1425 .Case("user", HeaderMode_User) 1426 .Case("system", HeaderMode_System) 1427 .Default(~0U); 1428 if (Kind == ~0U) { 1429 Diags.Report(diag::err_drv_invalid_value) 1430 << A->getAsString(Args) << ArgName; 1431 } else 1432 CXX20HeaderType = static_cast<ModuleHeaderMode>(Kind); 1433 } 1434 } 1435 1436 std::unique_ptr<llvm::opt::InputArgList> UArgs = 1437 std::make_unique<InputArgList>(std::move(Args)); 1438 1439 // Perform the default argument translations. 1440 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs); 1441 1442 // Owned by the host. 1443 const ToolChain &TC = getToolChain( 1444 *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs)); 1445 1446 if (TC.getTriple().isAndroid()) { 1447 llvm::Triple Triple = TC.getTriple(); 1448 StringRef TripleVersionName = Triple.getEnvironmentVersionString(); 1449 1450 if (Triple.getEnvironmentVersion().empty() && TripleVersionName != "") { 1451 Diags.Report(diag::err_drv_triple_version_invalid) 1452 << TripleVersionName << TC.getTripleString(); 1453 ContainsError = true; 1454 } 1455 } 1456 1457 // Report warning when arm64EC option is overridden by specified target 1458 if ((TC.getTriple().getArch() != llvm::Triple::aarch64 || 1459 TC.getTriple().getSubArch() != llvm::Triple::AArch64SubArch_arm64ec) && 1460 UArgs->hasArg(options::OPT__SLASH_arm64EC)) { 1461 getDiags().Report(clang::diag::warn_target_override_arm64ec) 1462 << TC.getTriple().str(); 1463 } 1464 1465 // A common user mistake is specifying a target of aarch64-none-eabi or 1466 // arm-none-elf whereas the correct names are aarch64-none-elf & 1467 // arm-none-eabi. Detect these cases and issue a warning. 1468 if (TC.getTriple().getOS() == llvm::Triple::UnknownOS && 1469 TC.getTriple().getVendor() == llvm::Triple::UnknownVendor) { 1470 switch (TC.getTriple().getArch()) { 1471 case llvm::Triple::arm: 1472 case llvm::Triple::armeb: 1473 case llvm::Triple::thumb: 1474 case llvm::Triple::thumbeb: 1475 if (TC.getTriple().getEnvironmentName() == "elf") { 1476 Diag(diag::warn_target_unrecognized_env) 1477 << TargetTriple 1478 << (TC.getTriple().getArchName().str() + "-none-eabi"); 1479 } 1480 break; 1481 case llvm::Triple::aarch64: 1482 case llvm::Triple::aarch64_be: 1483 case llvm::Triple::aarch64_32: 1484 if (TC.getTriple().getEnvironmentName().starts_with("eabi")) { 1485 Diag(diag::warn_target_unrecognized_env) 1486 << TargetTriple 1487 << (TC.getTriple().getArchName().str() + "-none-elf"); 1488 } 1489 break; 1490 default: 1491 break; 1492 } 1493 } 1494 1495 // The compilation takes ownership of Args. 1496 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs, 1497 ContainsError); 1498 1499 if (!HandleImmediateArgs(*C)) 1500 return C; 1501 1502 // Construct the list of inputs. 1503 InputList Inputs; 1504 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs); 1505 1506 // Populate the tool chains for the offloading devices, if any. 1507 CreateOffloadingDeviceToolChains(*C, Inputs); 1508 1509 // Construct the list of abstract actions to perform for this compilation. On 1510 // MachO targets this uses the driver-driver and universal actions. 1511 if (TC.getTriple().isOSBinFormatMachO()) 1512 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs); 1513 else 1514 BuildActions(*C, C->getArgs(), Inputs, C->getActions()); 1515 1516 if (CCCPrintPhases) { 1517 PrintActions(*C); 1518 return C; 1519 } 1520 1521 BuildJobs(*C); 1522 1523 return C; 1524 } 1525 1526 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) { 1527 llvm::opt::ArgStringList ASL; 1528 for (const auto *A : Args) { 1529 // Use user's original spelling of flags. For example, use 1530 // `/source-charset:utf-8` instead of `-finput-charset=utf-8` if the user 1531 // wrote the former. 1532 while (A->getAlias()) 1533 A = A->getAlias(); 1534 A->render(Args, ASL); 1535 } 1536 1537 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) { 1538 if (I != ASL.begin()) 1539 OS << ' '; 1540 llvm::sys::printArg(OS, *I, true); 1541 } 1542 OS << '\n'; 1543 } 1544 1545 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename, 1546 SmallString<128> &CrashDiagDir) { 1547 using namespace llvm::sys; 1548 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() && 1549 "Only knows about .crash files on Darwin"); 1550 1551 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/ 1552 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern 1553 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash. 1554 path::home_directory(CrashDiagDir); 1555 if (CrashDiagDir.starts_with("/var/root")) 1556 CrashDiagDir = "/"; 1557 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports"); 1558 int PID = 1559 #if LLVM_ON_UNIX 1560 getpid(); 1561 #else 1562 0; 1563 #endif 1564 std::error_code EC; 1565 fs::file_status FileStatus; 1566 TimePoint<> LastAccessTime; 1567 SmallString<128> CrashFilePath; 1568 // Lookup the .crash files and get the one generated by a subprocess spawned 1569 // by this driver invocation. 1570 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd; 1571 File != FileEnd && !EC; File.increment(EC)) { 1572 StringRef FileName = path::filename(File->path()); 1573 if (!FileName.starts_with(Name)) 1574 continue; 1575 if (fs::status(File->path(), FileStatus)) 1576 continue; 1577 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile = 1578 llvm::MemoryBuffer::getFile(File->path()); 1579 if (!CrashFile) 1580 continue; 1581 // The first line should start with "Process:", otherwise this isn't a real 1582 // .crash file. 1583 StringRef Data = CrashFile.get()->getBuffer(); 1584 if (!Data.starts_with("Process:")) 1585 continue; 1586 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]" 1587 size_t ParentProcPos = Data.find("Parent Process:"); 1588 if (ParentProcPos == StringRef::npos) 1589 continue; 1590 size_t LineEnd = Data.find_first_of("\n", ParentProcPos); 1591 if (LineEnd == StringRef::npos) 1592 continue; 1593 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim(); 1594 int OpenBracket = -1, CloseBracket = -1; 1595 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) { 1596 if (ParentProcess[i] == '[') 1597 OpenBracket = i; 1598 if (ParentProcess[i] == ']') 1599 CloseBracket = i; 1600 } 1601 // Extract the parent process PID from the .crash file and check whether 1602 // it matches this driver invocation pid. 1603 int CrashPID; 1604 if (OpenBracket < 0 || CloseBracket < 0 || 1605 ParentProcess.slice(OpenBracket + 1, CloseBracket) 1606 .getAsInteger(10, CrashPID) || CrashPID != PID) { 1607 continue; 1608 } 1609 1610 // Found a .crash file matching the driver pid. To avoid getting an older 1611 // and misleading crash file, continue looking for the most recent. 1612 // FIXME: the driver can dispatch multiple cc1 invocations, leading to 1613 // multiple crashes poiting to the same parent process. Since the driver 1614 // does not collect pid information for the dispatched invocation there's 1615 // currently no way to distinguish among them. 1616 const auto FileAccessTime = FileStatus.getLastModificationTime(); 1617 if (FileAccessTime > LastAccessTime) { 1618 CrashFilePath.assign(File->path()); 1619 LastAccessTime = FileAccessTime; 1620 } 1621 } 1622 1623 // If found, copy it over to the location of other reproducer files. 1624 if (!CrashFilePath.empty()) { 1625 EC = fs::copy_file(CrashFilePath, ReproCrashFilename); 1626 if (EC) 1627 return false; 1628 return true; 1629 } 1630 1631 return false; 1632 } 1633 1634 static const char BugReporMsg[] = 1635 "\n********************\n\n" 1636 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n" 1637 "Preprocessed source(s) and associated run script(s) are located at:"; 1638 1639 // When clang crashes, produce diagnostic information including the fully 1640 // preprocessed source file(s). Request that the developer attach the 1641 // diagnostic information to a bug report. 1642 void Driver::generateCompilationDiagnostics( 1643 Compilation &C, const Command &FailingCommand, 1644 StringRef AdditionalInformation, CompilationDiagnosticReport *Report) { 1645 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics)) 1646 return; 1647 1648 unsigned Level = 1; 1649 if (Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_EQ)) { 1650 Level = llvm::StringSwitch<unsigned>(A->getValue()) 1651 .Case("off", 0) 1652 .Case("compiler", 1) 1653 .Case("all", 2) 1654 .Default(1); 1655 } 1656 if (!Level) 1657 return; 1658 1659 // Don't try to generate diagnostics for dsymutil jobs. 1660 if (FailingCommand.getCreator().isDsymutilJob()) 1661 return; 1662 1663 bool IsLLD = false; 1664 ArgStringList SavedTemps; 1665 if (FailingCommand.getCreator().isLinkJob()) { 1666 C.getDefaultToolChain().GetLinkerPath(&IsLLD); 1667 if (!IsLLD || Level < 2) 1668 return; 1669 1670 // If lld crashed, we will re-run the same command with the input it used 1671 // to have. In that case we should not remove temp files in 1672 // initCompilationForDiagnostics yet. They will be added back and removed 1673 // later. 1674 SavedTemps = std::move(C.getTempFiles()); 1675 assert(!C.getTempFiles().size()); 1676 } 1677 1678 // Print the version of the compiler. 1679 PrintVersion(C, llvm::errs()); 1680 1681 // Suppress driver output and emit preprocessor output to temp file. 1682 CCGenDiagnostics = true; 1683 1684 // Save the original job command(s). 1685 Command Cmd = FailingCommand; 1686 1687 // Keep track of whether we produce any errors while trying to produce 1688 // preprocessed sources. 1689 DiagnosticErrorTrap Trap(Diags); 1690 1691 // Suppress tool output. 1692 C.initCompilationForDiagnostics(); 1693 1694 // If lld failed, rerun it again with --reproduce. 1695 if (IsLLD) { 1696 const char *TmpName = CreateTempFile(C, "linker-crash", "tar"); 1697 Command NewLLDInvocation = Cmd; 1698 llvm::opt::ArgStringList ArgList = NewLLDInvocation.getArguments(); 1699 StringRef ReproduceOption = 1700 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment() 1701 ? "/reproduce:" 1702 : "--reproduce="; 1703 ArgList.push_back(Saver.save(Twine(ReproduceOption) + TmpName).data()); 1704 NewLLDInvocation.replaceArguments(std::move(ArgList)); 1705 1706 // Redirect stdout/stderr to /dev/null. 1707 NewLLDInvocation.Execute({std::nullopt, {""}, {""}}, nullptr, nullptr); 1708 Diag(clang::diag::note_drv_command_failed_diag_msg) << BugReporMsg; 1709 Diag(clang::diag::note_drv_command_failed_diag_msg) << TmpName; 1710 Diag(clang::diag::note_drv_command_failed_diag_msg) 1711 << "\n\n********************"; 1712 if (Report) 1713 Report->TemporaryFiles.push_back(TmpName); 1714 return; 1715 } 1716 1717 // Construct the list of inputs. 1718 InputList Inputs; 1719 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs); 1720 1721 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) { 1722 bool IgnoreInput = false; 1723 1724 // Ignore input from stdin or any inputs that cannot be preprocessed. 1725 // Check type first as not all linker inputs have a value. 1726 if (types::getPreprocessedType(it->first) == types::TY_INVALID) { 1727 IgnoreInput = true; 1728 } else if (!strcmp(it->second->getValue(), "-")) { 1729 Diag(clang::diag::note_drv_command_failed_diag_msg) 1730 << "Error generating preprocessed source(s) - " 1731 "ignoring input from stdin."; 1732 IgnoreInput = true; 1733 } 1734 1735 if (IgnoreInput) { 1736 it = Inputs.erase(it); 1737 ie = Inputs.end(); 1738 } else { 1739 ++it; 1740 } 1741 } 1742 1743 if (Inputs.empty()) { 1744 Diag(clang::diag::note_drv_command_failed_diag_msg) 1745 << "Error generating preprocessed source(s) - " 1746 "no preprocessable inputs."; 1747 return; 1748 } 1749 1750 // Don't attempt to generate preprocessed files if multiple -arch options are 1751 // used, unless they're all duplicates. 1752 llvm::StringSet<> ArchNames; 1753 for (const Arg *A : C.getArgs()) { 1754 if (A->getOption().matches(options::OPT_arch)) { 1755 StringRef ArchName = A->getValue(); 1756 ArchNames.insert(ArchName); 1757 } 1758 } 1759 if (ArchNames.size() > 1) { 1760 Diag(clang::diag::note_drv_command_failed_diag_msg) 1761 << "Error generating preprocessed source(s) - cannot generate " 1762 "preprocessed source with multiple -arch options."; 1763 return; 1764 } 1765 1766 // Construct the list of abstract actions to perform for this compilation. On 1767 // Darwin OSes this uses the driver-driver and builds universal actions. 1768 const ToolChain &TC = C.getDefaultToolChain(); 1769 if (TC.getTriple().isOSBinFormatMachO()) 1770 BuildUniversalActions(C, TC, Inputs); 1771 else 1772 BuildActions(C, C.getArgs(), Inputs, C.getActions()); 1773 1774 BuildJobs(C); 1775 1776 // If there were errors building the compilation, quit now. 1777 if (Trap.hasErrorOccurred()) { 1778 Diag(clang::diag::note_drv_command_failed_diag_msg) 1779 << "Error generating preprocessed source(s)."; 1780 return; 1781 } 1782 1783 // Generate preprocessed output. 1784 SmallVector<std::pair<int, const Command *>, 4> FailingCommands; 1785 C.ExecuteJobs(C.getJobs(), FailingCommands); 1786 1787 // If any of the preprocessing commands failed, clean up and exit. 1788 if (!FailingCommands.empty()) { 1789 Diag(clang::diag::note_drv_command_failed_diag_msg) 1790 << "Error generating preprocessed source(s)."; 1791 return; 1792 } 1793 1794 const ArgStringList &TempFiles = C.getTempFiles(); 1795 if (TempFiles.empty()) { 1796 Diag(clang::diag::note_drv_command_failed_diag_msg) 1797 << "Error generating preprocessed source(s)."; 1798 return; 1799 } 1800 1801 Diag(clang::diag::note_drv_command_failed_diag_msg) << BugReporMsg; 1802 1803 SmallString<128> VFS; 1804 SmallString<128> ReproCrashFilename; 1805 for (const char *TempFile : TempFiles) { 1806 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile; 1807 if (Report) 1808 Report->TemporaryFiles.push_back(TempFile); 1809 if (ReproCrashFilename.empty()) { 1810 ReproCrashFilename = TempFile; 1811 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash"); 1812 } 1813 if (StringRef(TempFile).ends_with(".cache")) { 1814 // In some cases (modules) we'll dump extra data to help with reproducing 1815 // the crash into a directory next to the output. 1816 VFS = llvm::sys::path::filename(TempFile); 1817 llvm::sys::path::append(VFS, "vfs", "vfs.yaml"); 1818 } 1819 } 1820 1821 for (const char *TempFile : SavedTemps) 1822 C.addTempFile(TempFile); 1823 1824 // Assume associated files are based off of the first temporary file. 1825 CrashReportInfo CrashInfo(TempFiles[0], VFS); 1826 1827 llvm::SmallString<128> Script(CrashInfo.Filename); 1828 llvm::sys::path::replace_extension(Script, "sh"); 1829 std::error_code EC; 1830 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew, 1831 llvm::sys::fs::FA_Write, 1832 llvm::sys::fs::OF_Text); 1833 if (EC) { 1834 Diag(clang::diag::note_drv_command_failed_diag_msg) 1835 << "Error generating run script: " << Script << " " << EC.message(); 1836 } else { 1837 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n" 1838 << "# Driver args: "; 1839 printArgList(ScriptOS, C.getInputArgs()); 1840 ScriptOS << "# Original command: "; 1841 Cmd.Print(ScriptOS, "\n", /*Quote=*/true); 1842 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo); 1843 if (!AdditionalInformation.empty()) 1844 ScriptOS << "\n# Additional information: " << AdditionalInformation 1845 << "\n"; 1846 if (Report) 1847 Report->TemporaryFiles.push_back(std::string(Script)); 1848 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script; 1849 } 1850 1851 // On darwin, provide information about the .crash diagnostic report. 1852 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) { 1853 SmallString<128> CrashDiagDir; 1854 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) { 1855 Diag(clang::diag::note_drv_command_failed_diag_msg) 1856 << ReproCrashFilename.str(); 1857 } else { // Suggest a directory for the user to look for .crash files. 1858 llvm::sys::path::append(CrashDiagDir, Name); 1859 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash"; 1860 Diag(clang::diag::note_drv_command_failed_diag_msg) 1861 << "Crash backtrace is located in"; 1862 Diag(clang::diag::note_drv_command_failed_diag_msg) 1863 << CrashDiagDir.str(); 1864 Diag(clang::diag::note_drv_command_failed_diag_msg) 1865 << "(choose the .crash file that corresponds to your crash)"; 1866 } 1867 } 1868 1869 Diag(clang::diag::note_drv_command_failed_diag_msg) 1870 << "\n\n********************"; 1871 } 1872 1873 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) { 1874 // Since commandLineFitsWithinSystemLimits() may underestimate system's 1875 // capacity if the tool does not support response files, there is a chance/ 1876 // that things will just work without a response file, so we silently just 1877 // skip it. 1878 if (Cmd.getResponseFileSupport().ResponseKind == 1879 ResponseFileSupport::RF_None || 1880 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), 1881 Cmd.getArguments())) 1882 return; 1883 1884 std::string TmpName = GetTemporaryPath("response", "txt"); 1885 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName))); 1886 } 1887 1888 int Driver::ExecuteCompilation( 1889 Compilation &C, 1890 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) { 1891 if (C.getArgs().hasArg(options::OPT_fdriver_only)) { 1892 if (C.getArgs().hasArg(options::OPT_v)) 1893 C.getJobs().Print(llvm::errs(), "\n", true); 1894 1895 C.ExecuteJobs(C.getJobs(), FailingCommands, /*LogOnly=*/true); 1896 1897 // If there were errors building the compilation, quit now. 1898 if (!FailingCommands.empty() || Diags.hasErrorOccurred()) 1899 return 1; 1900 1901 return 0; 1902 } 1903 1904 // Just print if -### was present. 1905 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 1906 C.getJobs().Print(llvm::errs(), "\n", true); 1907 return Diags.hasErrorOccurred() ? 1 : 0; 1908 } 1909 1910 // If there were errors building the compilation, quit now. 1911 if (Diags.hasErrorOccurred()) 1912 return 1; 1913 1914 // Set up response file names for each command, if necessary. 1915 for (auto &Job : C.getJobs()) 1916 setUpResponseFiles(C, Job); 1917 1918 C.ExecuteJobs(C.getJobs(), FailingCommands); 1919 1920 // If the command succeeded, we are done. 1921 if (FailingCommands.empty()) 1922 return 0; 1923 1924 // Otherwise, remove result files and print extra information about abnormal 1925 // failures. 1926 int Res = 0; 1927 for (const auto &CmdPair : FailingCommands) { 1928 int CommandRes = CmdPair.first; 1929 const Command *FailingCommand = CmdPair.second; 1930 1931 // Remove result files if we're not saving temps. 1932 if (!isSaveTempsEnabled()) { 1933 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource()); 1934 C.CleanupFileMap(C.getResultFiles(), JA, true); 1935 1936 // Failure result files are valid unless we crashed. 1937 if (CommandRes < 0) 1938 C.CleanupFileMap(C.getFailureResultFiles(), JA, true); 1939 } 1940 1941 // llvm/lib/Support/*/Signals.inc will exit with a special return code 1942 // for SIGPIPE. Do not print diagnostics for this case. 1943 if (CommandRes == EX_IOERR) { 1944 Res = CommandRes; 1945 continue; 1946 } 1947 1948 // Print extra information about abnormal failures, if possible. 1949 // 1950 // This is ad-hoc, but we don't want to be excessively noisy. If the result 1951 // status was 1, assume the command failed normally. In particular, if it 1952 // was the compiler then assume it gave a reasonable error code. Failures 1953 // in other tools are less common, and they generally have worse 1954 // diagnostics, so always print the diagnostic there. 1955 const Tool &FailingTool = FailingCommand->getCreator(); 1956 1957 if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) { 1958 // FIXME: See FIXME above regarding result code interpretation. 1959 if (CommandRes < 0) 1960 Diag(clang::diag::err_drv_command_signalled) 1961 << FailingTool.getShortName(); 1962 else 1963 Diag(clang::diag::err_drv_command_failed) 1964 << FailingTool.getShortName() << CommandRes; 1965 } 1966 } 1967 return Res; 1968 } 1969 1970 void Driver::PrintHelp(bool ShowHidden) const { 1971 llvm::opt::Visibility VisibilityMask = getOptionVisibilityMask(); 1972 1973 std::string Usage = llvm::formatv("{0} [options] file...", Name).str(); 1974 getOpts().printHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(), 1975 ShowHidden, /*ShowAllAliases=*/false, 1976 VisibilityMask); 1977 } 1978 1979 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const { 1980 if (IsFlangMode()) { 1981 OS << getClangToolFullVersion("flang-new") << '\n'; 1982 } else { 1983 // FIXME: The following handlers should use a callback mechanism, we don't 1984 // know what the client would like to do. 1985 OS << getClangFullVersion() << '\n'; 1986 } 1987 const ToolChain &TC = C.getDefaultToolChain(); 1988 OS << "Target: " << TC.getTripleString() << '\n'; 1989 1990 // Print the threading model. 1991 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) { 1992 // Don't print if the ToolChain would have barfed on it already 1993 if (TC.isThreadModelSupported(A->getValue())) 1994 OS << "Thread model: " << A->getValue(); 1995 } else 1996 OS << "Thread model: " << TC.getThreadModel(); 1997 OS << '\n'; 1998 1999 // Print out the install directory. 2000 OS << "InstalledDir: " << InstalledDir << '\n'; 2001 2002 // If configuration files were used, print their paths. 2003 for (auto ConfigFile : ConfigFiles) 2004 OS << "Configuration file: " << ConfigFile << '\n'; 2005 } 2006 2007 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories 2008 /// option. 2009 static void PrintDiagnosticCategories(raw_ostream &OS) { 2010 // Skip the empty category. 2011 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max; 2012 ++i) 2013 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n'; 2014 } 2015 2016 void Driver::HandleAutocompletions(StringRef PassedFlags) const { 2017 if (PassedFlags == "") 2018 return; 2019 // Print out all options that start with a given argument. This is used for 2020 // shell autocompletion. 2021 std::vector<std::string> SuggestedCompletions; 2022 std::vector<std::string> Flags; 2023 2024 llvm::opt::Visibility VisibilityMask(options::ClangOption); 2025 2026 // Make sure that Flang-only options don't pollute the Clang output 2027 // TODO: Make sure that Clang-only options don't pollute Flang output 2028 if (IsFlangMode()) 2029 VisibilityMask = llvm::opt::Visibility(options::FlangOption); 2030 2031 // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag," 2032 // because the latter indicates that the user put space before pushing tab 2033 // which should end up in a file completion. 2034 const bool HasSpace = PassedFlags.ends_with(","); 2035 2036 // Parse PassedFlags by "," as all the command-line flags are passed to this 2037 // function separated by "," 2038 StringRef TargetFlags = PassedFlags; 2039 while (TargetFlags != "") { 2040 StringRef CurFlag; 2041 std::tie(CurFlag, TargetFlags) = TargetFlags.split(","); 2042 Flags.push_back(std::string(CurFlag)); 2043 } 2044 2045 // We want to show cc1-only options only when clang is invoked with -cc1 or 2046 // -Xclang. 2047 if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1")) 2048 VisibilityMask = llvm::opt::Visibility(options::CC1Option); 2049 2050 const llvm::opt::OptTable &Opts = getOpts(); 2051 StringRef Cur; 2052 Cur = Flags.at(Flags.size() - 1); 2053 StringRef Prev; 2054 if (Flags.size() >= 2) { 2055 Prev = Flags.at(Flags.size() - 2); 2056 SuggestedCompletions = Opts.suggestValueCompletions(Prev, Cur); 2057 } 2058 2059 if (SuggestedCompletions.empty()) 2060 SuggestedCompletions = Opts.suggestValueCompletions(Cur, ""); 2061 2062 // If Flags were empty, it means the user typed `clang [tab]` where we should 2063 // list all possible flags. If there was no value completion and the user 2064 // pressed tab after a space, we should fall back to a file completion. 2065 // We're printing a newline to be consistent with what we print at the end of 2066 // this function. 2067 if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) { 2068 llvm::outs() << '\n'; 2069 return; 2070 } 2071 2072 // When flag ends with '=' and there was no value completion, return empty 2073 // string and fall back to the file autocompletion. 2074 if (SuggestedCompletions.empty() && !Cur.ends_with("=")) { 2075 // If the flag is in the form of "--autocomplete=-foo", 2076 // we were requested to print out all option names that start with "-foo". 2077 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only". 2078 SuggestedCompletions = Opts.findByPrefix( 2079 Cur, VisibilityMask, 2080 /*DisableFlags=*/options::Unsupported | options::Ignored); 2081 2082 // We have to query the -W flags manually as they're not in the OptTable. 2083 // TODO: Find a good way to add them to OptTable instead and them remove 2084 // this code. 2085 for (StringRef S : DiagnosticIDs::getDiagnosticFlags()) 2086 if (S.starts_with(Cur)) 2087 SuggestedCompletions.push_back(std::string(S)); 2088 } 2089 2090 // Sort the autocomplete candidates so that shells print them out in a 2091 // deterministic order. We could sort in any way, but we chose 2092 // case-insensitive sorting for consistency with the -help option 2093 // which prints out options in the case-insensitive alphabetical order. 2094 llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) { 2095 if (int X = A.compare_insensitive(B)) 2096 return X < 0; 2097 return A.compare(B) > 0; 2098 }); 2099 2100 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n'; 2101 } 2102 2103 bool Driver::HandleImmediateArgs(const Compilation &C) { 2104 // The order these options are handled in gcc is all over the place, but we 2105 // don't expect inconsistencies w.r.t. that to matter in practice. 2106 2107 if (C.getArgs().hasArg(options::OPT_dumpmachine)) { 2108 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n'; 2109 return false; 2110 } 2111 2112 if (C.getArgs().hasArg(options::OPT_dumpversion)) { 2113 // Since -dumpversion is only implemented for pedantic GCC compatibility, we 2114 // return an answer which matches our definition of __VERSION__. 2115 llvm::outs() << CLANG_VERSION_STRING << "\n"; 2116 return false; 2117 } 2118 2119 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) { 2120 PrintDiagnosticCategories(llvm::outs()); 2121 return false; 2122 } 2123 2124 if (C.getArgs().hasArg(options::OPT_help) || 2125 C.getArgs().hasArg(options::OPT__help_hidden)) { 2126 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden)); 2127 return false; 2128 } 2129 2130 if (C.getArgs().hasArg(options::OPT__version)) { 2131 // Follow gcc behavior and use stdout for --version and stderr for -v. 2132 PrintVersion(C, llvm::outs()); 2133 return false; 2134 } 2135 2136 if (C.getArgs().hasArg(options::OPT_v) || 2137 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH) || 2138 C.getArgs().hasArg(options::OPT_print_supported_cpus) || 2139 C.getArgs().hasArg(options::OPT_print_supported_extensions)) { 2140 PrintVersion(C, llvm::errs()); 2141 SuppressMissingInputWarning = true; 2142 } 2143 2144 if (C.getArgs().hasArg(options::OPT_v)) { 2145 if (!SystemConfigDir.empty()) 2146 llvm::errs() << "System configuration file directory: " 2147 << SystemConfigDir << "\n"; 2148 if (!UserConfigDir.empty()) 2149 llvm::errs() << "User configuration file directory: " 2150 << UserConfigDir << "\n"; 2151 } 2152 2153 const ToolChain &TC = C.getDefaultToolChain(); 2154 2155 if (C.getArgs().hasArg(options::OPT_v)) 2156 TC.printVerboseInfo(llvm::errs()); 2157 2158 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) { 2159 llvm::outs() << ResourceDir << '\n'; 2160 return false; 2161 } 2162 2163 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) { 2164 llvm::outs() << "programs: ="; 2165 bool separator = false; 2166 // Print -B and COMPILER_PATH. 2167 for (const std::string &Path : PrefixDirs) { 2168 if (separator) 2169 llvm::outs() << llvm::sys::EnvPathSeparator; 2170 llvm::outs() << Path; 2171 separator = true; 2172 } 2173 for (const std::string &Path : TC.getProgramPaths()) { 2174 if (separator) 2175 llvm::outs() << llvm::sys::EnvPathSeparator; 2176 llvm::outs() << Path; 2177 separator = true; 2178 } 2179 llvm::outs() << "\n"; 2180 llvm::outs() << "libraries: =" << ResourceDir; 2181 2182 StringRef sysroot = C.getSysRoot(); 2183 2184 for (const std::string &Path : TC.getFilePaths()) { 2185 // Always print a separator. ResourceDir was the first item shown. 2186 llvm::outs() << llvm::sys::EnvPathSeparator; 2187 // Interpretation of leading '=' is needed only for NetBSD. 2188 if (Path[0] == '=') 2189 llvm::outs() << sysroot << Path.substr(1); 2190 else 2191 llvm::outs() << Path; 2192 } 2193 llvm::outs() << "\n"; 2194 return false; 2195 } 2196 2197 if (C.getArgs().hasArg(options::OPT_print_runtime_dir)) { 2198 if (std::optional<std::string> RuntimePath = TC.getRuntimePath()) 2199 llvm::outs() << *RuntimePath << '\n'; 2200 else 2201 llvm::outs() << TC.getCompilerRTPath() << '\n'; 2202 return false; 2203 } 2204 2205 if (C.getArgs().hasArg(options::OPT_print_diagnostic_options)) { 2206 std::vector<std::string> Flags = DiagnosticIDs::getDiagnosticFlags(); 2207 for (std::size_t I = 0; I != Flags.size(); I += 2) 2208 llvm::outs() << " " << Flags[I] << "\n " << Flags[I + 1] << "\n\n"; 2209 return false; 2210 } 2211 2212 // FIXME: The following handlers should use a callback mechanism, we don't 2213 // know what the client would like to do. 2214 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) { 2215 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n"; 2216 return false; 2217 } 2218 2219 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) { 2220 StringRef ProgName = A->getValue(); 2221 2222 // Null program name cannot have a path. 2223 if (! ProgName.empty()) 2224 llvm::outs() << GetProgramPath(ProgName, TC); 2225 2226 llvm::outs() << "\n"; 2227 return false; 2228 } 2229 2230 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) { 2231 StringRef PassedFlags = A->getValue(); 2232 HandleAutocompletions(PassedFlags); 2233 return false; 2234 } 2235 2236 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) { 2237 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs()); 2238 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs())); 2239 RegisterEffectiveTriple TripleRAII(TC, Triple); 2240 switch (RLT) { 2241 case ToolChain::RLT_CompilerRT: 2242 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n"; 2243 break; 2244 case ToolChain::RLT_Libgcc: 2245 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n"; 2246 break; 2247 } 2248 return false; 2249 } 2250 2251 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) { 2252 for (const Multilib &Multilib : TC.getMultilibs()) 2253 llvm::outs() << Multilib << "\n"; 2254 return false; 2255 } 2256 2257 if (C.getArgs().hasArg(options::OPT_print_multi_flags)) { 2258 Multilib::flags_list ArgFlags = TC.getMultilibFlags(C.getArgs()); 2259 llvm::StringSet<> ExpandedFlags = TC.getMultilibs().expandFlags(ArgFlags); 2260 std::set<llvm::StringRef> SortedFlags; 2261 for (const auto &FlagEntry : ExpandedFlags) 2262 SortedFlags.insert(FlagEntry.getKey()); 2263 for (auto Flag : SortedFlags) 2264 llvm::outs() << Flag << '\n'; 2265 return false; 2266 } 2267 2268 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) { 2269 for (const Multilib &Multilib : TC.getSelectedMultilibs()) { 2270 if (Multilib.gccSuffix().empty()) 2271 llvm::outs() << ".\n"; 2272 else { 2273 StringRef Suffix(Multilib.gccSuffix()); 2274 assert(Suffix.front() == '/'); 2275 llvm::outs() << Suffix.substr(1) << "\n"; 2276 } 2277 } 2278 return false; 2279 } 2280 2281 if (C.getArgs().hasArg(options::OPT_print_target_triple)) { 2282 llvm::outs() << TC.getTripleString() << "\n"; 2283 return false; 2284 } 2285 2286 if (C.getArgs().hasArg(options::OPT_print_effective_triple)) { 2287 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs())); 2288 llvm::outs() << Triple.getTriple() << "\n"; 2289 return false; 2290 } 2291 2292 if (C.getArgs().hasArg(options::OPT_print_targets)) { 2293 llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs()); 2294 return false; 2295 } 2296 2297 return true; 2298 } 2299 2300 enum { 2301 TopLevelAction = 0, 2302 HeadSibAction = 1, 2303 OtherSibAction = 2, 2304 }; 2305 2306 // Display an action graph human-readably. Action A is the "sink" node 2307 // and latest-occuring action. Traversal is in pre-order, visiting the 2308 // inputs to each action before printing the action itself. 2309 static unsigned PrintActions1(const Compilation &C, Action *A, 2310 std::map<Action *, unsigned> &Ids, 2311 Twine Indent = {}, int Kind = TopLevelAction) { 2312 if (Ids.count(A)) // A was already visited. 2313 return Ids[A]; 2314 2315 std::string str; 2316 llvm::raw_string_ostream os(str); 2317 2318 auto getSibIndent = [](int K) -> Twine { 2319 return (K == HeadSibAction) ? " " : (K == OtherSibAction) ? "| " : ""; 2320 }; 2321 2322 Twine SibIndent = Indent + getSibIndent(Kind); 2323 int SibKind = HeadSibAction; 2324 os << Action::getClassName(A->getKind()) << ", "; 2325 if (InputAction *IA = dyn_cast<InputAction>(A)) { 2326 os << "\"" << IA->getInputArg().getValue() << "\""; 2327 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) { 2328 os << '"' << BIA->getArchName() << '"' << ", {" 2329 << PrintActions1(C, *BIA->input_begin(), Ids, SibIndent, SibKind) << "}"; 2330 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) { 2331 bool IsFirst = true; 2332 OA->doOnEachDependence( 2333 [&](Action *A, const ToolChain *TC, const char *BoundArch) { 2334 assert(TC && "Unknown host toolchain"); 2335 // E.g. for two CUDA device dependences whose bound arch is sm_20 and 2336 // sm_35 this will generate: 2337 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device" 2338 // (nvptx64-nvidia-cuda:sm_35) {#ID} 2339 if (!IsFirst) 2340 os << ", "; 2341 os << '"'; 2342 os << A->getOffloadingKindPrefix(); 2343 os << " ("; 2344 os << TC->getTriple().normalize(); 2345 if (BoundArch) 2346 os << ":" << BoundArch; 2347 os << ")"; 2348 os << '"'; 2349 os << " {" << PrintActions1(C, A, Ids, SibIndent, SibKind) << "}"; 2350 IsFirst = false; 2351 SibKind = OtherSibAction; 2352 }); 2353 } else { 2354 const ActionList *AL = &A->getInputs(); 2355 2356 if (AL->size()) { 2357 const char *Prefix = "{"; 2358 for (Action *PreRequisite : *AL) { 2359 os << Prefix << PrintActions1(C, PreRequisite, Ids, SibIndent, SibKind); 2360 Prefix = ", "; 2361 SibKind = OtherSibAction; 2362 } 2363 os << "}"; 2364 } else 2365 os << "{}"; 2366 } 2367 2368 // Append offload info for all options other than the offloading action 2369 // itself (e.g. (cuda-device, sm_20) or (cuda-host)). 2370 std::string offload_str; 2371 llvm::raw_string_ostream offload_os(offload_str); 2372 if (!isa<OffloadAction>(A)) { 2373 auto S = A->getOffloadingKindPrefix(); 2374 if (!S.empty()) { 2375 offload_os << ", (" << S; 2376 if (A->getOffloadingArch()) 2377 offload_os << ", " << A->getOffloadingArch(); 2378 offload_os << ")"; 2379 } 2380 } 2381 2382 auto getSelfIndent = [](int K) -> Twine { 2383 return (K == HeadSibAction) ? "+- " : (K == OtherSibAction) ? "|- " : ""; 2384 }; 2385 2386 unsigned Id = Ids.size(); 2387 Ids[A] = Id; 2388 llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", " 2389 << types::getTypeName(A->getType()) << offload_os.str() << "\n"; 2390 2391 return Id; 2392 } 2393 2394 // Print the action graphs in a compilation C. 2395 // For example "clang -c file1.c file2.c" is composed of two subgraphs. 2396 void Driver::PrintActions(const Compilation &C) const { 2397 std::map<Action *, unsigned> Ids; 2398 for (Action *A : C.getActions()) 2399 PrintActions1(C, A, Ids); 2400 } 2401 2402 /// Check whether the given input tree contains any compilation or 2403 /// assembly actions. 2404 static bool ContainsCompileOrAssembleAction(const Action *A) { 2405 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) || 2406 isa<AssembleJobAction>(A)) 2407 return true; 2408 2409 return llvm::any_of(A->inputs(), ContainsCompileOrAssembleAction); 2410 } 2411 2412 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC, 2413 const InputList &BAInputs) const { 2414 DerivedArgList &Args = C.getArgs(); 2415 ActionList &Actions = C.getActions(); 2416 llvm::PrettyStackTraceString CrashInfo("Building universal build actions"); 2417 // Collect the list of architectures. Duplicates are allowed, but should only 2418 // be handled once (in the order seen). 2419 llvm::StringSet<> ArchNames; 2420 SmallVector<const char *, 4> Archs; 2421 for (Arg *A : Args) { 2422 if (A->getOption().matches(options::OPT_arch)) { 2423 // Validate the option here; we don't save the type here because its 2424 // particular spelling may participate in other driver choices. 2425 llvm::Triple::ArchType Arch = 2426 tools::darwin::getArchTypeForMachOArchName(A->getValue()); 2427 if (Arch == llvm::Triple::UnknownArch) { 2428 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args); 2429 continue; 2430 } 2431 2432 A->claim(); 2433 if (ArchNames.insert(A->getValue()).second) 2434 Archs.push_back(A->getValue()); 2435 } 2436 } 2437 2438 // When there is no explicit arch for this platform, make sure we still bind 2439 // the architecture (to the default) so that -Xarch_ is handled correctly. 2440 if (!Archs.size()) 2441 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName())); 2442 2443 ActionList SingleActions; 2444 BuildActions(C, Args, BAInputs, SingleActions); 2445 2446 // Add in arch bindings for every top level action, as well as lipo and 2447 // dsymutil steps if needed. 2448 for (Action* Act : SingleActions) { 2449 // Make sure we can lipo this kind of output. If not (and it is an actual 2450 // output) then we disallow, since we can't create an output file with the 2451 // right name without overwriting it. We could remove this oddity by just 2452 // changing the output names to include the arch, which would also fix 2453 // -save-temps. Compatibility wins for now. 2454 2455 if (Archs.size() > 1 && !types::canLipoType(Act->getType())) 2456 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs) 2457 << types::getTypeName(Act->getType()); 2458 2459 ActionList Inputs; 2460 for (unsigned i = 0, e = Archs.size(); i != e; ++i) 2461 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i])); 2462 2463 // Lipo if necessary, we do it this way because we need to set the arch flag 2464 // so that -Xarch_ gets overwritten. 2465 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing) 2466 Actions.append(Inputs.begin(), Inputs.end()); 2467 else 2468 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType())); 2469 2470 // Handle debug info queries. 2471 Arg *A = Args.getLastArg(options::OPT_g_Group); 2472 bool enablesDebugInfo = A && !A->getOption().matches(options::OPT_g0) && 2473 !A->getOption().matches(options::OPT_gstabs); 2474 if ((enablesDebugInfo || willEmitRemarks(Args)) && 2475 ContainsCompileOrAssembleAction(Actions.back())) { 2476 2477 // Add a 'dsymutil' step if necessary, when debug info is enabled and we 2478 // have a compile input. We need to run 'dsymutil' ourselves in such cases 2479 // because the debug info will refer to a temporary object file which 2480 // will be removed at the end of the compilation process. 2481 if (Act->getType() == types::TY_Image) { 2482 ActionList Inputs; 2483 Inputs.push_back(Actions.back()); 2484 Actions.pop_back(); 2485 Actions.push_back( 2486 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM)); 2487 } 2488 2489 // Verify the debug info output. 2490 if (Args.hasArg(options::OPT_verify_debug_info)) { 2491 Action* LastAction = Actions.back(); 2492 Actions.pop_back(); 2493 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>( 2494 LastAction, types::TY_Nothing)); 2495 } 2496 } 2497 } 2498 } 2499 2500 bool Driver::DiagnoseInputExistence(const DerivedArgList &Args, StringRef Value, 2501 types::ID Ty, bool TypoCorrect) const { 2502 if (!getCheckInputsExist()) 2503 return true; 2504 2505 // stdin always exists. 2506 if (Value == "-") 2507 return true; 2508 2509 // If it's a header to be found in the system or user search path, then defer 2510 // complaints about its absence until those searches can be done. When we 2511 // are definitely processing headers for C++20 header units, extend this to 2512 // allow the user to put "-fmodule-header -xc++-header vector" for example. 2513 if (Ty == types::TY_CXXSHeader || Ty == types::TY_CXXUHeader || 2514 (ModulesModeCXX20 && Ty == types::TY_CXXHeader)) 2515 return true; 2516 2517 if (getVFS().exists(Value)) 2518 return true; 2519 2520 if (TypoCorrect) { 2521 // Check if the filename is a typo for an option flag. OptTable thinks 2522 // that all args that are not known options and that start with / are 2523 // filenames, but e.g. `/diagnostic:caret` is more likely a typo for 2524 // the option `/diagnostics:caret` than a reference to a file in the root 2525 // directory. 2526 std::string Nearest; 2527 if (getOpts().findNearest(Value, Nearest, getOptionVisibilityMask()) <= 1) { 2528 Diag(clang::diag::err_drv_no_such_file_with_suggestion) 2529 << Value << Nearest; 2530 return false; 2531 } 2532 } 2533 2534 // In CL mode, don't error on apparently non-existent linker inputs, because 2535 // they can be influenced by linker flags the clang driver might not 2536 // understand. 2537 // Examples: 2538 // - `clang-cl main.cc ole32.lib` in a non-MSVC shell will make the driver 2539 // module look for an MSVC installation in the registry. (We could ask 2540 // the MSVCToolChain object if it can find `ole32.lib`, but the logic to 2541 // look in the registry might move into lld-link in the future so that 2542 // lld-link invocations in non-MSVC shells just work too.) 2543 // - `clang-cl ... /link ...` can pass arbitrary flags to the linker, 2544 // including /libpath:, which is used to find .lib and .obj files. 2545 // So do not diagnose this on the driver level. Rely on the linker diagnosing 2546 // it. (If we don't end up invoking the linker, this means we'll emit a 2547 // "'linker' input unused [-Wunused-command-line-argument]" warning instead 2548 // of an error.) 2549 // 2550 // Only do this skip after the typo correction step above. `/Brepo` is treated 2551 // as TY_Object, but it's clearly a typo for `/Brepro`. It seems fine to emit 2552 // an error if we have a flag that's within an edit distance of 1 from a 2553 // flag. (Users can use `-Wl,` or `/linker` to launder the flag past the 2554 // driver in the unlikely case they run into this.) 2555 // 2556 // Don't do this for inputs that start with a '/', else we'd pass options 2557 // like /libpath: through to the linker silently. 2558 // 2559 // Emitting an error for linker inputs can also cause incorrect diagnostics 2560 // with the gcc driver. The command 2561 // clang -fuse-ld=lld -Wl,--chroot,some/dir /file.o 2562 // will make lld look for some/dir/file.o, while we will diagnose here that 2563 // `/file.o` does not exist. However, configure scripts check if 2564 // `clang /GR-` compiles without error to see if the compiler is cl.exe, 2565 // so we can't downgrade diagnostics for `/GR-` from an error to a warning 2566 // in cc mode. (We can in cl mode because cl.exe itself only warns on 2567 // unknown flags.) 2568 if (IsCLMode() && Ty == types::TY_Object && !Value.starts_with("/")) 2569 return true; 2570 2571 Diag(clang::diag::err_drv_no_such_file) << Value; 2572 return false; 2573 } 2574 2575 // Get the C++20 Header Unit type corresponding to the input type. 2576 static types::ID CXXHeaderUnitType(ModuleHeaderMode HM) { 2577 switch (HM) { 2578 case HeaderMode_User: 2579 return types::TY_CXXUHeader; 2580 case HeaderMode_System: 2581 return types::TY_CXXSHeader; 2582 case HeaderMode_Default: 2583 break; 2584 case HeaderMode_None: 2585 llvm_unreachable("should not be called in this case"); 2586 } 2587 return types::TY_CXXHUHeader; 2588 } 2589 2590 // Construct a the list of inputs and their types. 2591 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args, 2592 InputList &Inputs) const { 2593 const llvm::opt::OptTable &Opts = getOpts(); 2594 // Track the current user specified (-x) input. We also explicitly track the 2595 // argument used to set the type; we only want to claim the type when we 2596 // actually use it, so we warn about unused -x arguments. 2597 types::ID InputType = types::TY_Nothing; 2598 Arg *InputTypeArg = nullptr; 2599 2600 // The last /TC or /TP option sets the input type to C or C++ globally. 2601 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC, 2602 options::OPT__SLASH_TP)) { 2603 InputTypeArg = TCTP; 2604 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC) 2605 ? types::TY_C 2606 : types::TY_CXX; 2607 2608 Arg *Previous = nullptr; 2609 bool ShowNote = false; 2610 for (Arg *A : 2611 Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) { 2612 if (Previous) { 2613 Diag(clang::diag::warn_drv_overriding_option) 2614 << Previous->getSpelling() << A->getSpelling(); 2615 ShowNote = true; 2616 } 2617 Previous = A; 2618 } 2619 if (ShowNote) 2620 Diag(clang::diag::note_drv_t_option_is_global); 2621 } 2622 2623 // CUDA/HIP and their preprocessor expansions can be accepted by CL mode. 2624 // Warn -x after last input file has no effect 2625 auto LastXArg = Args.getLastArgValue(options::OPT_x); 2626 const llvm::StringSet<> ValidXArgs = {"cuda", "hip", "cui", "hipi"}; 2627 if (!IsCLMode() || ValidXArgs.contains(LastXArg)) { 2628 Arg *LastXArg = Args.getLastArgNoClaim(options::OPT_x); 2629 Arg *LastInputArg = Args.getLastArgNoClaim(options::OPT_INPUT); 2630 if (LastXArg && LastInputArg && 2631 LastInputArg->getIndex() < LastXArg->getIndex()) 2632 Diag(clang::diag::warn_drv_unused_x) << LastXArg->getValue(); 2633 } else { 2634 // In CL mode suggest /TC or /TP since -x doesn't make sense if passed via 2635 // /clang:. 2636 if (auto *A = Args.getLastArg(options::OPT_x)) 2637 Diag(diag::err_drv_unsupported_opt_with_suggestion) 2638 << A->getAsString(Args) << "/TC' or '/TP"; 2639 } 2640 2641 for (Arg *A : Args) { 2642 if (A->getOption().getKind() == Option::InputClass) { 2643 const char *Value = A->getValue(); 2644 types::ID Ty = types::TY_INVALID; 2645 2646 // Infer the input type if necessary. 2647 if (InputType == types::TY_Nothing) { 2648 // If there was an explicit arg for this, claim it. 2649 if (InputTypeArg) 2650 InputTypeArg->claim(); 2651 2652 // stdin must be handled specially. 2653 if (memcmp(Value, "-", 2) == 0) { 2654 if (IsFlangMode()) { 2655 Ty = types::TY_Fortran; 2656 } else if (IsDXCMode()) { 2657 Ty = types::TY_HLSL; 2658 } else { 2659 // If running with -E, treat as a C input (this changes the 2660 // builtin macros, for example). This may be overridden by -ObjC 2661 // below. 2662 // 2663 // Otherwise emit an error but still use a valid type to avoid 2664 // spurious errors (e.g., no inputs). 2665 assert(!CCGenDiagnostics && "stdin produces no crash reproducer"); 2666 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP()) 2667 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl 2668 : clang::diag::err_drv_unknown_stdin_type); 2669 Ty = types::TY_C; 2670 } 2671 } else { 2672 // Otherwise lookup by extension. 2673 // Fallback is C if invoked as C preprocessor, C++ if invoked with 2674 // clang-cl /E, or Object otherwise. 2675 // We use a host hook here because Darwin at least has its own 2676 // idea of what .s is. 2677 if (const char *Ext = strrchr(Value, '.')) 2678 Ty = TC.LookupTypeForExtension(Ext + 1); 2679 2680 if (Ty == types::TY_INVALID) { 2681 if (IsCLMode() && (Args.hasArgNoClaim(options::OPT_E) || CCGenDiagnostics)) 2682 Ty = types::TY_CXX; 2683 else if (CCCIsCPP() || CCGenDiagnostics) 2684 Ty = types::TY_C; 2685 else 2686 Ty = types::TY_Object; 2687 } 2688 2689 // If the driver is invoked as C++ compiler (like clang++ or c++) it 2690 // should autodetect some input files as C++ for g++ compatibility. 2691 if (CCCIsCXX()) { 2692 types::ID OldTy = Ty; 2693 Ty = types::lookupCXXTypeForCType(Ty); 2694 2695 // Do not complain about foo.h, when we are known to be processing 2696 // it as a C++20 header unit. 2697 if (Ty != OldTy && !(OldTy == types::TY_CHeader && hasHeaderMode())) 2698 Diag(clang::diag::warn_drv_treating_input_as_cxx) 2699 << getTypeName(OldTy) << getTypeName(Ty); 2700 } 2701 2702 // If running with -fthinlto-index=, extensions that normally identify 2703 // native object files actually identify LLVM bitcode files. 2704 if (Args.hasArgNoClaim(options::OPT_fthinlto_index_EQ) && 2705 Ty == types::TY_Object) 2706 Ty = types::TY_LLVM_BC; 2707 } 2708 2709 // -ObjC and -ObjC++ override the default language, but only for "source 2710 // files". We just treat everything that isn't a linker input as a 2711 // source file. 2712 // 2713 // FIXME: Clean this up if we move the phase sequence into the type. 2714 if (Ty != types::TY_Object) { 2715 if (Args.hasArg(options::OPT_ObjC)) 2716 Ty = types::TY_ObjC; 2717 else if (Args.hasArg(options::OPT_ObjCXX)) 2718 Ty = types::TY_ObjCXX; 2719 } 2720 2721 // Disambiguate headers that are meant to be header units from those 2722 // intended to be PCH. Avoid missing '.h' cases that are counted as 2723 // C headers by default - we know we are in C++ mode and we do not 2724 // want to issue a complaint about compiling things in the wrong mode. 2725 if ((Ty == types::TY_CXXHeader || Ty == types::TY_CHeader) && 2726 hasHeaderMode()) 2727 Ty = CXXHeaderUnitType(CXX20HeaderType); 2728 } else { 2729 assert(InputTypeArg && "InputType set w/o InputTypeArg"); 2730 if (!InputTypeArg->getOption().matches(options::OPT_x)) { 2731 // If emulating cl.exe, make sure that /TC and /TP don't affect input 2732 // object files. 2733 const char *Ext = strrchr(Value, '.'); 2734 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object) 2735 Ty = types::TY_Object; 2736 } 2737 if (Ty == types::TY_INVALID) { 2738 Ty = InputType; 2739 InputTypeArg->claim(); 2740 } 2741 } 2742 2743 if ((Ty == types::TY_C || Ty == types::TY_CXX) && 2744 Args.hasArgNoClaim(options::OPT_hipstdpar)) 2745 Ty = types::TY_HIP; 2746 2747 if (DiagnoseInputExistence(Args, Value, Ty, /*TypoCorrect=*/true)) 2748 Inputs.push_back(std::make_pair(Ty, A)); 2749 2750 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) { 2751 StringRef Value = A->getValue(); 2752 if (DiagnoseInputExistence(Args, Value, types::TY_C, 2753 /*TypoCorrect=*/false)) { 2754 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue()); 2755 Inputs.push_back(std::make_pair(types::TY_C, InputArg)); 2756 } 2757 A->claim(); 2758 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) { 2759 StringRef Value = A->getValue(); 2760 if (DiagnoseInputExistence(Args, Value, types::TY_CXX, 2761 /*TypoCorrect=*/false)) { 2762 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue()); 2763 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg)); 2764 } 2765 A->claim(); 2766 } else if (A->getOption().hasFlag(options::LinkerInput)) { 2767 // Just treat as object type, we could make a special type for this if 2768 // necessary. 2769 Inputs.push_back(std::make_pair(types::TY_Object, A)); 2770 2771 } else if (A->getOption().matches(options::OPT_x)) { 2772 InputTypeArg = A; 2773 InputType = types::lookupTypeForTypeSpecifier(A->getValue()); 2774 A->claim(); 2775 2776 // Follow gcc behavior and treat as linker input for invalid -x 2777 // options. Its not clear why we shouldn't just revert to unknown; but 2778 // this isn't very important, we might as well be bug compatible. 2779 if (!InputType) { 2780 Diag(clang::diag::err_drv_unknown_language) << A->getValue(); 2781 InputType = types::TY_Object; 2782 } 2783 2784 // If the user has put -fmodule-header{,=} then we treat C++ headers as 2785 // header unit inputs. So we 'promote' -xc++-header appropriately. 2786 if (InputType == types::TY_CXXHeader && hasHeaderMode()) 2787 InputType = CXXHeaderUnitType(CXX20HeaderType); 2788 } else if (A->getOption().getID() == options::OPT_U) { 2789 assert(A->getNumValues() == 1 && "The /U option has one value."); 2790 StringRef Val = A->getValue(0); 2791 if (Val.find_first_of("/\\") != StringRef::npos) { 2792 // Warn about e.g. "/Users/me/myfile.c". 2793 Diag(diag::warn_slash_u_filename) << Val; 2794 Diag(diag::note_use_dashdash); 2795 } 2796 } 2797 } 2798 if (CCCIsCPP() && Inputs.empty()) { 2799 // If called as standalone preprocessor, stdin is processed 2800 // if no other input is present. 2801 Arg *A = MakeInputArg(Args, Opts, "-"); 2802 Inputs.push_back(std::make_pair(types::TY_C, A)); 2803 } 2804 } 2805 2806 namespace { 2807 /// Provides a convenient interface for different programming models to generate 2808 /// the required device actions. 2809 class OffloadingActionBuilder final { 2810 /// Flag used to trace errors in the builder. 2811 bool IsValid = false; 2812 2813 /// The compilation that is using this builder. 2814 Compilation &C; 2815 2816 /// Map between an input argument and the offload kinds used to process it. 2817 std::map<const Arg *, unsigned> InputArgToOffloadKindMap; 2818 2819 /// Map between a host action and its originating input argument. 2820 std::map<Action *, const Arg *> HostActionToInputArgMap; 2821 2822 /// Builder interface. It doesn't build anything or keep any state. 2823 class DeviceActionBuilder { 2824 public: 2825 typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy; 2826 2827 enum ActionBuilderReturnCode { 2828 // The builder acted successfully on the current action. 2829 ABRT_Success, 2830 // The builder didn't have to act on the current action. 2831 ABRT_Inactive, 2832 // The builder was successful and requested the host action to not be 2833 // generated. 2834 ABRT_Ignore_Host, 2835 }; 2836 2837 protected: 2838 /// Compilation associated with this builder. 2839 Compilation &C; 2840 2841 /// Tool chains associated with this builder. The same programming 2842 /// model may have associated one or more tool chains. 2843 SmallVector<const ToolChain *, 2> ToolChains; 2844 2845 /// The derived arguments associated with this builder. 2846 DerivedArgList &Args; 2847 2848 /// The inputs associated with this builder. 2849 const Driver::InputList &Inputs; 2850 2851 /// The associated offload kind. 2852 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None; 2853 2854 public: 2855 DeviceActionBuilder(Compilation &C, DerivedArgList &Args, 2856 const Driver::InputList &Inputs, 2857 Action::OffloadKind AssociatedOffloadKind) 2858 : C(C), Args(Args), Inputs(Inputs), 2859 AssociatedOffloadKind(AssociatedOffloadKind) {} 2860 virtual ~DeviceActionBuilder() {} 2861 2862 /// Fill up the array \a DA with all the device dependences that should be 2863 /// added to the provided host action \a HostAction. By default it is 2864 /// inactive. 2865 virtual ActionBuilderReturnCode 2866 getDeviceDependences(OffloadAction::DeviceDependences &DA, 2867 phases::ID CurPhase, phases::ID FinalPhase, 2868 PhasesTy &Phases) { 2869 return ABRT_Inactive; 2870 } 2871 2872 /// Update the state to include the provided host action \a HostAction as a 2873 /// dependency of the current device action. By default it is inactive. 2874 virtual ActionBuilderReturnCode addDeviceDependences(Action *HostAction) { 2875 return ABRT_Inactive; 2876 } 2877 2878 /// Append top level actions generated by the builder. 2879 virtual void appendTopLevelActions(ActionList &AL) {} 2880 2881 /// Append linker device actions generated by the builder. 2882 virtual void appendLinkDeviceActions(ActionList &AL) {} 2883 2884 /// Append linker host action generated by the builder. 2885 virtual Action* appendLinkHostActions(ActionList &AL) { return nullptr; } 2886 2887 /// Append linker actions generated by the builder. 2888 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {} 2889 2890 /// Initialize the builder. Return true if any initialization errors are 2891 /// found. 2892 virtual bool initialize() { return false; } 2893 2894 /// Return true if the builder can use bundling/unbundling. 2895 virtual bool canUseBundlerUnbundler() const { return false; } 2896 2897 /// Return true if this builder is valid. We have a valid builder if we have 2898 /// associated device tool chains. 2899 bool isValid() { return !ToolChains.empty(); } 2900 2901 /// Return the associated offload kind. 2902 Action::OffloadKind getAssociatedOffloadKind() { 2903 return AssociatedOffloadKind; 2904 } 2905 }; 2906 2907 /// Base class for CUDA/HIP action builder. It injects device code in 2908 /// the host backend action. 2909 class CudaActionBuilderBase : public DeviceActionBuilder { 2910 protected: 2911 /// Flags to signal if the user requested host-only or device-only 2912 /// compilation. 2913 bool CompileHostOnly = false; 2914 bool CompileDeviceOnly = false; 2915 bool EmitLLVM = false; 2916 bool EmitAsm = false; 2917 2918 /// ID to identify each device compilation. For CUDA it is simply the 2919 /// GPU arch string. For HIP it is either the GPU arch string or GPU 2920 /// arch string plus feature strings delimited by a plus sign, e.g. 2921 /// gfx906+xnack. 2922 struct TargetID { 2923 /// Target ID string which is persistent throughout the compilation. 2924 const char *ID; 2925 TargetID(CudaArch Arch) { ID = CudaArchToString(Arch); } 2926 TargetID(const char *ID) : ID(ID) {} 2927 operator const char *() { return ID; } 2928 operator StringRef() { return StringRef(ID); } 2929 }; 2930 /// List of GPU architectures to use in this compilation. 2931 SmallVector<TargetID, 4> GpuArchList; 2932 2933 /// The CUDA actions for the current input. 2934 ActionList CudaDeviceActions; 2935 2936 /// The CUDA fat binary if it was generated for the current input. 2937 Action *CudaFatBinary = nullptr; 2938 2939 /// Flag that is set to true if this builder acted on the current input. 2940 bool IsActive = false; 2941 2942 /// Flag for -fgpu-rdc. 2943 bool Relocatable = false; 2944 2945 /// Default GPU architecture if there's no one specified. 2946 CudaArch DefaultCudaArch = CudaArch::UNKNOWN; 2947 2948 /// Method to generate compilation unit ID specified by option 2949 /// '-fuse-cuid='. 2950 enum UseCUIDKind { CUID_Hash, CUID_Random, CUID_None, CUID_Invalid }; 2951 UseCUIDKind UseCUID = CUID_Hash; 2952 2953 /// Compilation unit ID specified by option '-cuid='. 2954 StringRef FixedCUID; 2955 2956 public: 2957 CudaActionBuilderBase(Compilation &C, DerivedArgList &Args, 2958 const Driver::InputList &Inputs, 2959 Action::OffloadKind OFKind) 2960 : DeviceActionBuilder(C, Args, Inputs, OFKind) { 2961 2962 CompileDeviceOnly = C.getDriver().offloadDeviceOnly(); 2963 Relocatable = Args.hasFlag(options::OPT_fgpu_rdc, 2964 options::OPT_fno_gpu_rdc, /*Default=*/false); 2965 } 2966 2967 ActionBuilderReturnCode addDeviceDependences(Action *HostAction) override { 2968 // While generating code for CUDA, we only depend on the host input action 2969 // to trigger the creation of all the CUDA device actions. 2970 2971 // If we are dealing with an input action, replicate it for each GPU 2972 // architecture. If we are in host-only mode we return 'success' so that 2973 // the host uses the CUDA offload kind. 2974 if (auto *IA = dyn_cast<InputAction>(HostAction)) { 2975 assert(!GpuArchList.empty() && 2976 "We should have at least one GPU architecture."); 2977 2978 // If the host input is not CUDA or HIP, we don't need to bother about 2979 // this input. 2980 if (!(IA->getType() == types::TY_CUDA || 2981 IA->getType() == types::TY_HIP || 2982 IA->getType() == types::TY_PP_HIP)) { 2983 // The builder will ignore this input. 2984 IsActive = false; 2985 return ABRT_Inactive; 2986 } 2987 2988 // Set the flag to true, so that the builder acts on the current input. 2989 IsActive = true; 2990 2991 if (CompileHostOnly) 2992 return ABRT_Success; 2993 2994 // Replicate inputs for each GPU architecture. 2995 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE 2996 : types::TY_CUDA_DEVICE; 2997 std::string CUID = FixedCUID.str(); 2998 if (CUID.empty()) { 2999 if (UseCUID == CUID_Random) 3000 CUID = llvm::utohexstr(llvm::sys::Process::GetRandomNumber(), 3001 /*LowerCase=*/true); 3002 else if (UseCUID == CUID_Hash) { 3003 llvm::MD5 Hasher; 3004 llvm::MD5::MD5Result Hash; 3005 SmallString<256> RealPath; 3006 llvm::sys::fs::real_path(IA->getInputArg().getValue(), RealPath, 3007 /*expand_tilde=*/true); 3008 Hasher.update(RealPath); 3009 for (auto *A : Args) { 3010 if (A->getOption().matches(options::OPT_INPUT)) 3011 continue; 3012 Hasher.update(A->getAsString(Args)); 3013 } 3014 Hasher.final(Hash); 3015 CUID = llvm::utohexstr(Hash.low(), /*LowerCase=*/true); 3016 } 3017 } 3018 IA->setId(CUID); 3019 3020 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 3021 CudaDeviceActions.push_back( 3022 C.MakeAction<InputAction>(IA->getInputArg(), Ty, IA->getId())); 3023 } 3024 3025 return ABRT_Success; 3026 } 3027 3028 // If this is an unbundling action use it as is for each CUDA toolchain. 3029 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) { 3030 3031 // If -fgpu-rdc is disabled, should not unbundle since there is no 3032 // device code to link. 3033 if (UA->getType() == types::TY_Object && !Relocatable) 3034 return ABRT_Inactive; 3035 3036 CudaDeviceActions.clear(); 3037 auto *IA = cast<InputAction>(UA->getInputs().back()); 3038 std::string FileName = IA->getInputArg().getAsString(Args); 3039 // Check if the type of the file is the same as the action. Do not 3040 // unbundle it if it is not. Do not unbundle .so files, for example, 3041 // which are not object files. Files with extension ".lib" is classified 3042 // as TY_Object but they are actually archives, therefore should not be 3043 // unbundled here as objects. They will be handled at other places. 3044 const StringRef LibFileExt = ".lib"; 3045 if (IA->getType() == types::TY_Object && 3046 (!llvm::sys::path::has_extension(FileName) || 3047 types::lookupTypeForExtension( 3048 llvm::sys::path::extension(FileName).drop_front()) != 3049 types::TY_Object || 3050 llvm::sys::path::extension(FileName) == LibFileExt)) 3051 return ABRT_Inactive; 3052 3053 for (auto Arch : GpuArchList) { 3054 CudaDeviceActions.push_back(UA); 3055 UA->registerDependentActionInfo(ToolChains[0], Arch, 3056 AssociatedOffloadKind); 3057 } 3058 IsActive = true; 3059 return ABRT_Success; 3060 } 3061 3062 return IsActive ? ABRT_Success : ABRT_Inactive; 3063 } 3064 3065 void appendTopLevelActions(ActionList &AL) override { 3066 // Utility to append actions to the top level list. 3067 auto AddTopLevel = [&](Action *A, TargetID TargetID) { 3068 OffloadAction::DeviceDependences Dep; 3069 Dep.add(*A, *ToolChains.front(), TargetID, AssociatedOffloadKind); 3070 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType())); 3071 }; 3072 3073 // If we have a fat binary, add it to the list. 3074 if (CudaFatBinary) { 3075 AddTopLevel(CudaFatBinary, CudaArch::UNUSED); 3076 CudaDeviceActions.clear(); 3077 CudaFatBinary = nullptr; 3078 return; 3079 } 3080 3081 if (CudaDeviceActions.empty()) 3082 return; 3083 3084 // If we have CUDA actions at this point, that's because we have a have 3085 // partial compilation, so we should have an action for each GPU 3086 // architecture. 3087 assert(CudaDeviceActions.size() == GpuArchList.size() && 3088 "Expecting one action per GPU architecture."); 3089 assert(ToolChains.size() == 1 && 3090 "Expecting to have a single CUDA toolchain."); 3091 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) 3092 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]); 3093 3094 CudaDeviceActions.clear(); 3095 } 3096 3097 /// Get canonicalized offload arch option. \returns empty StringRef if the 3098 /// option is invalid. 3099 virtual StringRef getCanonicalOffloadArch(StringRef Arch) = 0; 3100 3101 virtual std::optional<std::pair<llvm::StringRef, llvm::StringRef>> 3102 getConflictOffloadArchCombination(const std::set<StringRef> &GpuArchs) = 0; 3103 3104 bool initialize() override { 3105 assert(AssociatedOffloadKind == Action::OFK_Cuda || 3106 AssociatedOffloadKind == Action::OFK_HIP); 3107 3108 // We don't need to support CUDA. 3109 if (AssociatedOffloadKind == Action::OFK_Cuda && 3110 !C.hasOffloadToolChain<Action::OFK_Cuda>()) 3111 return false; 3112 3113 // We don't need to support HIP. 3114 if (AssociatedOffloadKind == Action::OFK_HIP && 3115 !C.hasOffloadToolChain<Action::OFK_HIP>()) 3116 return false; 3117 3118 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>(); 3119 assert(HostTC && "No toolchain for host compilation."); 3120 if (HostTC->getTriple().isNVPTX() || 3121 HostTC->getTriple().getArch() == llvm::Triple::amdgcn) { 3122 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw 3123 // an error and abort pipeline construction early so we don't trip 3124 // asserts that assume device-side compilation. 3125 C.getDriver().Diag(diag::err_drv_cuda_host_arch) 3126 << HostTC->getTriple().getArchName(); 3127 return true; 3128 } 3129 3130 ToolChains.push_back( 3131 AssociatedOffloadKind == Action::OFK_Cuda 3132 ? C.getSingleOffloadToolChain<Action::OFK_Cuda>() 3133 : C.getSingleOffloadToolChain<Action::OFK_HIP>()); 3134 3135 CompileHostOnly = C.getDriver().offloadHostOnly(); 3136 EmitLLVM = Args.getLastArg(options::OPT_emit_llvm); 3137 EmitAsm = Args.getLastArg(options::OPT_S); 3138 FixedCUID = Args.getLastArgValue(options::OPT_cuid_EQ); 3139 if (Arg *A = Args.getLastArg(options::OPT_fuse_cuid_EQ)) { 3140 StringRef UseCUIDStr = A->getValue(); 3141 UseCUID = llvm::StringSwitch<UseCUIDKind>(UseCUIDStr) 3142 .Case("hash", CUID_Hash) 3143 .Case("random", CUID_Random) 3144 .Case("none", CUID_None) 3145 .Default(CUID_Invalid); 3146 if (UseCUID == CUID_Invalid) { 3147 C.getDriver().Diag(diag::err_drv_invalid_value) 3148 << A->getAsString(Args) << UseCUIDStr; 3149 C.setContainsError(); 3150 return true; 3151 } 3152 } 3153 3154 // --offload and --offload-arch options are mutually exclusive. 3155 if (Args.hasArgNoClaim(options::OPT_offload_EQ) && 3156 Args.hasArgNoClaim(options::OPT_offload_arch_EQ, 3157 options::OPT_no_offload_arch_EQ)) { 3158 C.getDriver().Diag(diag::err_opt_not_valid_with_opt) << "--offload-arch" 3159 << "--offload"; 3160 } 3161 3162 // Collect all offload arch parameters, removing duplicates. 3163 std::set<StringRef> GpuArchs; 3164 bool Error = false; 3165 for (Arg *A : Args) { 3166 if (!(A->getOption().matches(options::OPT_offload_arch_EQ) || 3167 A->getOption().matches(options::OPT_no_offload_arch_EQ))) 3168 continue; 3169 A->claim(); 3170 3171 for (StringRef ArchStr : llvm::split(A->getValue(), ",")) { 3172 if (A->getOption().matches(options::OPT_no_offload_arch_EQ) && 3173 ArchStr == "all") { 3174 GpuArchs.clear(); 3175 } else if (ArchStr == "native") { 3176 const ToolChain &TC = *ToolChains.front(); 3177 auto GPUsOrErr = ToolChains.front()->getSystemGPUArchs(Args); 3178 if (!GPUsOrErr) { 3179 TC.getDriver().Diag(diag::err_drv_undetermined_gpu_arch) 3180 << llvm::Triple::getArchTypeName(TC.getArch()) 3181 << llvm::toString(GPUsOrErr.takeError()) << "--offload-arch"; 3182 continue; 3183 } 3184 3185 for (auto GPU : *GPUsOrErr) { 3186 GpuArchs.insert(Args.MakeArgString(GPU)); 3187 } 3188 } else { 3189 ArchStr = getCanonicalOffloadArch(ArchStr); 3190 if (ArchStr.empty()) { 3191 Error = true; 3192 } else if (A->getOption().matches(options::OPT_offload_arch_EQ)) 3193 GpuArchs.insert(ArchStr); 3194 else if (A->getOption().matches(options::OPT_no_offload_arch_EQ)) 3195 GpuArchs.erase(ArchStr); 3196 else 3197 llvm_unreachable("Unexpected option."); 3198 } 3199 } 3200 } 3201 3202 auto &&ConflictingArchs = getConflictOffloadArchCombination(GpuArchs); 3203 if (ConflictingArchs) { 3204 C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo) 3205 << ConflictingArchs->first << ConflictingArchs->second; 3206 C.setContainsError(); 3207 return true; 3208 } 3209 3210 // Collect list of GPUs remaining in the set. 3211 for (auto Arch : GpuArchs) 3212 GpuArchList.push_back(Arch.data()); 3213 3214 // Default to sm_20 which is the lowest common denominator for 3215 // supported GPUs. sm_20 code should work correctly, if 3216 // suboptimally, on all newer GPUs. 3217 if (GpuArchList.empty()) { 3218 if (ToolChains.front()->getTriple().isSPIRV()) 3219 GpuArchList.push_back(CudaArch::Generic); 3220 else 3221 GpuArchList.push_back(DefaultCudaArch); 3222 } 3223 3224 return Error; 3225 } 3226 }; 3227 3228 /// \brief CUDA action builder. It injects device code in the host backend 3229 /// action. 3230 class CudaActionBuilder final : public CudaActionBuilderBase { 3231 public: 3232 CudaActionBuilder(Compilation &C, DerivedArgList &Args, 3233 const Driver::InputList &Inputs) 3234 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) { 3235 DefaultCudaArch = CudaArch::SM_35; 3236 } 3237 3238 StringRef getCanonicalOffloadArch(StringRef ArchStr) override { 3239 CudaArch Arch = StringToCudaArch(ArchStr); 3240 if (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch)) { 3241 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr; 3242 return StringRef(); 3243 } 3244 return CudaArchToString(Arch); 3245 } 3246 3247 std::optional<std::pair<llvm::StringRef, llvm::StringRef>> 3248 getConflictOffloadArchCombination( 3249 const std::set<StringRef> &GpuArchs) override { 3250 return std::nullopt; 3251 } 3252 3253 ActionBuilderReturnCode 3254 getDeviceDependences(OffloadAction::DeviceDependences &DA, 3255 phases::ID CurPhase, phases::ID FinalPhase, 3256 PhasesTy &Phases) override { 3257 if (!IsActive) 3258 return ABRT_Inactive; 3259 3260 // If we don't have more CUDA actions, we don't have any dependences to 3261 // create for the host. 3262 if (CudaDeviceActions.empty()) 3263 return ABRT_Success; 3264 3265 assert(CudaDeviceActions.size() == GpuArchList.size() && 3266 "Expecting one action per GPU architecture."); 3267 assert(!CompileHostOnly && 3268 "Not expecting CUDA actions in host-only compilation."); 3269 3270 // If we are generating code for the device or we are in a backend phase, 3271 // we attempt to generate the fat binary. We compile each arch to ptx and 3272 // assemble to cubin, then feed the cubin *and* the ptx into a device 3273 // "link" action, which uses fatbinary to combine these cubins into one 3274 // fatbin. The fatbin is then an input to the host action if not in 3275 // device-only mode. 3276 if (CompileDeviceOnly || CurPhase == phases::Backend) { 3277 ActionList DeviceActions; 3278 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 3279 // Produce the device action from the current phase up to the assemble 3280 // phase. 3281 for (auto Ph : Phases) { 3282 // Skip the phases that were already dealt with. 3283 if (Ph < CurPhase) 3284 continue; 3285 // We have to be consistent with the host final phase. 3286 if (Ph > FinalPhase) 3287 break; 3288 3289 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction( 3290 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda); 3291 3292 if (Ph == phases::Assemble) 3293 break; 3294 } 3295 3296 // If we didn't reach the assemble phase, we can't generate the fat 3297 // binary. We don't need to generate the fat binary if we are not in 3298 // device-only mode. 3299 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) || 3300 CompileDeviceOnly) 3301 continue; 3302 3303 Action *AssembleAction = CudaDeviceActions[I]; 3304 assert(AssembleAction->getType() == types::TY_Object); 3305 assert(AssembleAction->getInputs().size() == 1); 3306 3307 Action *BackendAction = AssembleAction->getInputs()[0]; 3308 assert(BackendAction->getType() == types::TY_PP_Asm); 3309 3310 for (auto &A : {AssembleAction, BackendAction}) { 3311 OffloadAction::DeviceDependences DDep; 3312 DDep.add(*A, *ToolChains.front(), GpuArchList[I], Action::OFK_Cuda); 3313 DeviceActions.push_back( 3314 C.MakeAction<OffloadAction>(DDep, A->getType())); 3315 } 3316 } 3317 3318 // We generate the fat binary if we have device input actions. 3319 if (!DeviceActions.empty()) { 3320 CudaFatBinary = 3321 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN); 3322 3323 if (!CompileDeviceOnly) { 3324 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr, 3325 Action::OFK_Cuda); 3326 // Clear the fat binary, it is already a dependence to an host 3327 // action. 3328 CudaFatBinary = nullptr; 3329 } 3330 3331 // Remove the CUDA actions as they are already connected to an host 3332 // action or fat binary. 3333 CudaDeviceActions.clear(); 3334 } 3335 3336 // We avoid creating host action in device-only mode. 3337 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success; 3338 } else if (CurPhase > phases::Backend) { 3339 // If we are past the backend phase and still have a device action, we 3340 // don't have to do anything as this action is already a device 3341 // top-level action. 3342 return ABRT_Success; 3343 } 3344 3345 assert(CurPhase < phases::Backend && "Generating single CUDA " 3346 "instructions should only occur " 3347 "before the backend phase!"); 3348 3349 // By default, we produce an action for each device arch. 3350 for (Action *&A : CudaDeviceActions) 3351 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A); 3352 3353 return ABRT_Success; 3354 } 3355 }; 3356 /// \brief HIP action builder. It injects device code in the host backend 3357 /// action. 3358 class HIPActionBuilder final : public CudaActionBuilderBase { 3359 /// The linker inputs obtained for each device arch. 3360 SmallVector<ActionList, 8> DeviceLinkerInputs; 3361 // The default bundling behavior depends on the type of output, therefore 3362 // BundleOutput needs to be tri-value: None, true, or false. 3363 // Bundle code objects except --no-gpu-output is specified for device 3364 // only compilation. Bundle other type of output files only if 3365 // --gpu-bundle-output is specified for device only compilation. 3366 std::optional<bool> BundleOutput; 3367 std::optional<bool> EmitReloc; 3368 3369 public: 3370 HIPActionBuilder(Compilation &C, DerivedArgList &Args, 3371 const Driver::InputList &Inputs) 3372 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) { 3373 3374 DefaultCudaArch = CudaArch::GFX906; 3375 3376 if (Args.hasArg(options::OPT_fhip_emit_relocatable, 3377 options::OPT_fno_hip_emit_relocatable)) { 3378 EmitReloc = Args.hasFlag(options::OPT_fhip_emit_relocatable, 3379 options::OPT_fno_hip_emit_relocatable, false); 3380 3381 if (*EmitReloc) { 3382 if (Relocatable) { 3383 C.getDriver().Diag(diag::err_opt_not_valid_with_opt) 3384 << "-fhip-emit-relocatable" 3385 << "-fgpu-rdc"; 3386 } 3387 3388 if (!CompileDeviceOnly) { 3389 C.getDriver().Diag(diag::err_opt_not_valid_without_opt) 3390 << "-fhip-emit-relocatable" 3391 << "--cuda-device-only"; 3392 } 3393 } 3394 } 3395 3396 if (Args.hasArg(options::OPT_gpu_bundle_output, 3397 options::OPT_no_gpu_bundle_output)) 3398 BundleOutput = Args.hasFlag(options::OPT_gpu_bundle_output, 3399 options::OPT_no_gpu_bundle_output, true) && 3400 (!EmitReloc || !*EmitReloc); 3401 } 3402 3403 bool canUseBundlerUnbundler() const override { return true; } 3404 3405 StringRef getCanonicalOffloadArch(StringRef IdStr) override { 3406 llvm::StringMap<bool> Features; 3407 // getHIPOffloadTargetTriple() is known to return valid value as it has 3408 // been called successfully in the CreateOffloadingDeviceToolChains(). 3409 auto ArchStr = parseTargetID( 3410 *getHIPOffloadTargetTriple(C.getDriver(), C.getInputArgs()), IdStr, 3411 &Features); 3412 if (!ArchStr) { 3413 C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << IdStr; 3414 C.setContainsError(); 3415 return StringRef(); 3416 } 3417 auto CanId = getCanonicalTargetID(*ArchStr, Features); 3418 return Args.MakeArgStringRef(CanId); 3419 }; 3420 3421 std::optional<std::pair<llvm::StringRef, llvm::StringRef>> 3422 getConflictOffloadArchCombination( 3423 const std::set<StringRef> &GpuArchs) override { 3424 return getConflictTargetIDCombination(GpuArchs); 3425 } 3426 3427 ActionBuilderReturnCode 3428 getDeviceDependences(OffloadAction::DeviceDependences &DA, 3429 phases::ID CurPhase, phases::ID FinalPhase, 3430 PhasesTy &Phases) override { 3431 if (!IsActive) 3432 return ABRT_Inactive; 3433 3434 // amdgcn does not support linking of object files, therefore we skip 3435 // backend and assemble phases to output LLVM IR. Except for generating 3436 // non-relocatable device code, where we generate fat binary for device 3437 // code and pass to host in Backend phase. 3438 if (CudaDeviceActions.empty()) 3439 return ABRT_Success; 3440 3441 assert(((CurPhase == phases::Link && Relocatable) || 3442 CudaDeviceActions.size() == GpuArchList.size()) && 3443 "Expecting one action per GPU architecture."); 3444 assert(!CompileHostOnly && 3445 "Not expecting HIP actions in host-only compilation."); 3446 3447 bool ShouldLink = !EmitReloc || !*EmitReloc; 3448 3449 if (!Relocatable && CurPhase == phases::Backend && !EmitLLVM && 3450 !EmitAsm && ShouldLink) { 3451 // If we are in backend phase, we attempt to generate the fat binary. 3452 // We compile each arch to IR and use a link action to generate code 3453 // object containing ISA. Then we use a special "link" action to create 3454 // a fat binary containing all the code objects for different GPU's. 3455 // The fat binary is then an input to the host action. 3456 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 3457 if (C.getDriver().isUsingLTO(/*IsOffload=*/true)) { 3458 // When LTO is enabled, skip the backend and assemble phases and 3459 // use lld to link the bitcode. 3460 ActionList AL; 3461 AL.push_back(CudaDeviceActions[I]); 3462 // Create a link action to link device IR with device library 3463 // and generate ISA. 3464 CudaDeviceActions[I] = 3465 C.MakeAction<LinkJobAction>(AL, types::TY_Image); 3466 } else { 3467 // When LTO is not enabled, we follow the conventional 3468 // compiler phases, including backend and assemble phases. 3469 ActionList AL; 3470 Action *BackendAction = nullptr; 3471 if (ToolChains.front()->getTriple().isSPIRV()) { 3472 // Emit LLVM bitcode for SPIR-V targets. SPIR-V device tool chain 3473 // (HIPSPVToolChain) runs post-link LLVM IR passes. 3474 types::ID Output = Args.hasArg(options::OPT_S) 3475 ? types::TY_LLVM_IR 3476 : types::TY_LLVM_BC; 3477 BackendAction = 3478 C.MakeAction<BackendJobAction>(CudaDeviceActions[I], Output); 3479 } else 3480 BackendAction = C.getDriver().ConstructPhaseAction( 3481 C, Args, phases::Backend, CudaDeviceActions[I], 3482 AssociatedOffloadKind); 3483 auto AssembleAction = C.getDriver().ConstructPhaseAction( 3484 C, Args, phases::Assemble, BackendAction, 3485 AssociatedOffloadKind); 3486 AL.push_back(AssembleAction); 3487 // Create a link action to link device IR with device library 3488 // and generate ISA. 3489 CudaDeviceActions[I] = 3490 C.MakeAction<LinkJobAction>(AL, types::TY_Image); 3491 } 3492 3493 // OffloadingActionBuilder propagates device arch until an offload 3494 // action. Since the next action for creating fatbin does 3495 // not have device arch, whereas the above link action and its input 3496 // have device arch, an offload action is needed to stop the null 3497 // device arch of the next action being propagated to the above link 3498 // action. 3499 OffloadAction::DeviceDependences DDep; 3500 DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I], 3501 AssociatedOffloadKind); 3502 CudaDeviceActions[I] = C.MakeAction<OffloadAction>( 3503 DDep, CudaDeviceActions[I]->getType()); 3504 } 3505 3506 if (!CompileDeviceOnly || !BundleOutput || *BundleOutput) { 3507 // Create HIP fat binary with a special "link" action. 3508 CudaFatBinary = C.MakeAction<LinkJobAction>(CudaDeviceActions, 3509 types::TY_HIP_FATBIN); 3510 3511 if (!CompileDeviceOnly) { 3512 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr, 3513 AssociatedOffloadKind); 3514 // Clear the fat binary, it is already a dependence to an host 3515 // action. 3516 CudaFatBinary = nullptr; 3517 } 3518 3519 // Remove the CUDA actions as they are already connected to an host 3520 // action or fat binary. 3521 CudaDeviceActions.clear(); 3522 } 3523 3524 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success; 3525 } else if (CurPhase == phases::Link) { 3526 if (!ShouldLink) 3527 return ABRT_Success; 3528 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch. 3529 // This happens to each device action originated from each input file. 3530 // Later on, device actions in DeviceLinkerInputs are used to create 3531 // device link actions in appendLinkDependences and the created device 3532 // link actions are passed to the offload action as device dependence. 3533 DeviceLinkerInputs.resize(CudaDeviceActions.size()); 3534 auto LI = DeviceLinkerInputs.begin(); 3535 for (auto *A : CudaDeviceActions) { 3536 LI->push_back(A); 3537 ++LI; 3538 } 3539 3540 // We will pass the device action as a host dependence, so we don't 3541 // need to do anything else with them. 3542 CudaDeviceActions.clear(); 3543 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success; 3544 } 3545 3546 // By default, we produce an action for each device arch. 3547 for (Action *&A : CudaDeviceActions) 3548 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A, 3549 AssociatedOffloadKind); 3550 3551 if (CompileDeviceOnly && CurPhase == FinalPhase && BundleOutput && 3552 *BundleOutput) { 3553 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 3554 OffloadAction::DeviceDependences DDep; 3555 DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I], 3556 AssociatedOffloadKind); 3557 CudaDeviceActions[I] = C.MakeAction<OffloadAction>( 3558 DDep, CudaDeviceActions[I]->getType()); 3559 } 3560 CudaFatBinary = 3561 C.MakeAction<OffloadBundlingJobAction>(CudaDeviceActions); 3562 CudaDeviceActions.clear(); 3563 } 3564 3565 return (CompileDeviceOnly && 3566 (CurPhase == FinalPhase || 3567 (!ShouldLink && CurPhase == phases::Assemble))) 3568 ? ABRT_Ignore_Host 3569 : ABRT_Success; 3570 } 3571 3572 void appendLinkDeviceActions(ActionList &AL) override { 3573 if (DeviceLinkerInputs.size() == 0) 3574 return; 3575 3576 assert(DeviceLinkerInputs.size() == GpuArchList.size() && 3577 "Linker inputs and GPU arch list sizes do not match."); 3578 3579 ActionList Actions; 3580 unsigned I = 0; 3581 // Append a new link action for each device. 3582 // Each entry in DeviceLinkerInputs corresponds to a GPU arch. 3583 for (auto &LI : DeviceLinkerInputs) { 3584 3585 types::ID Output = Args.hasArg(options::OPT_emit_llvm) 3586 ? types::TY_LLVM_BC 3587 : types::TY_Image; 3588 3589 auto *DeviceLinkAction = C.MakeAction<LinkJobAction>(LI, Output); 3590 // Linking all inputs for the current GPU arch. 3591 // LI contains all the inputs for the linker. 3592 OffloadAction::DeviceDependences DeviceLinkDeps; 3593 DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0], 3594 GpuArchList[I], AssociatedOffloadKind); 3595 Actions.push_back(C.MakeAction<OffloadAction>( 3596 DeviceLinkDeps, DeviceLinkAction->getType())); 3597 ++I; 3598 } 3599 DeviceLinkerInputs.clear(); 3600 3601 // If emitting LLVM, do not generate final host/device compilation action 3602 if (Args.hasArg(options::OPT_emit_llvm)) { 3603 AL.append(Actions); 3604 return; 3605 } 3606 3607 // Create a host object from all the device images by embedding them 3608 // in a fat binary for mixed host-device compilation. For device-only 3609 // compilation, creates a fat binary. 3610 OffloadAction::DeviceDependences DDeps; 3611 if (!CompileDeviceOnly || !BundleOutput || *BundleOutput) { 3612 auto *TopDeviceLinkAction = C.MakeAction<LinkJobAction>( 3613 Actions, 3614 CompileDeviceOnly ? types::TY_HIP_FATBIN : types::TY_Object); 3615 DDeps.add(*TopDeviceLinkAction, *ToolChains[0], nullptr, 3616 AssociatedOffloadKind); 3617 // Offload the host object to the host linker. 3618 AL.push_back( 3619 C.MakeAction<OffloadAction>(DDeps, TopDeviceLinkAction->getType())); 3620 } else { 3621 AL.append(Actions); 3622 } 3623 } 3624 3625 Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); } 3626 3627 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {} 3628 }; 3629 3630 /// 3631 /// TODO: Add the implementation for other specialized builders here. 3632 /// 3633 3634 /// Specialized builders being used by this offloading action builder. 3635 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders; 3636 3637 /// Flag set to true if all valid builders allow file bundling/unbundling. 3638 bool CanUseBundler; 3639 3640 public: 3641 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args, 3642 const Driver::InputList &Inputs) 3643 : C(C) { 3644 // Create a specialized builder for each device toolchain. 3645 3646 IsValid = true; 3647 3648 // Create a specialized builder for CUDA. 3649 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs)); 3650 3651 // Create a specialized builder for HIP. 3652 SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs)); 3653 3654 // 3655 // TODO: Build other specialized builders here. 3656 // 3657 3658 // Initialize all the builders, keeping track of errors. If all valid 3659 // builders agree that we can use bundling, set the flag to true. 3660 unsigned ValidBuilders = 0u; 3661 unsigned ValidBuildersSupportingBundling = 0u; 3662 for (auto *SB : SpecializedBuilders) { 3663 IsValid = IsValid && !SB->initialize(); 3664 3665 // Update the counters if the builder is valid. 3666 if (SB->isValid()) { 3667 ++ValidBuilders; 3668 if (SB->canUseBundlerUnbundler()) 3669 ++ValidBuildersSupportingBundling; 3670 } 3671 } 3672 CanUseBundler = 3673 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling; 3674 } 3675 3676 ~OffloadingActionBuilder() { 3677 for (auto *SB : SpecializedBuilders) 3678 delete SB; 3679 } 3680 3681 /// Record a host action and its originating input argument. 3682 void recordHostAction(Action *HostAction, const Arg *InputArg) { 3683 assert(HostAction && "Invalid host action"); 3684 assert(InputArg && "Invalid input argument"); 3685 auto Loc = HostActionToInputArgMap.find(HostAction); 3686 if (Loc == HostActionToInputArgMap.end()) 3687 HostActionToInputArgMap[HostAction] = InputArg; 3688 assert(HostActionToInputArgMap[HostAction] == InputArg && 3689 "host action mapped to multiple input arguments"); 3690 } 3691 3692 /// Generate an action that adds device dependences (if any) to a host action. 3693 /// If no device dependence actions exist, just return the host action \a 3694 /// HostAction. If an error is found or if no builder requires the host action 3695 /// to be generated, return nullptr. 3696 Action * 3697 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg, 3698 phases::ID CurPhase, phases::ID FinalPhase, 3699 DeviceActionBuilder::PhasesTy &Phases) { 3700 if (!IsValid) 3701 return nullptr; 3702 3703 if (SpecializedBuilders.empty()) 3704 return HostAction; 3705 3706 assert(HostAction && "Invalid host action!"); 3707 recordHostAction(HostAction, InputArg); 3708 3709 OffloadAction::DeviceDependences DDeps; 3710 // Check if all the programming models agree we should not emit the host 3711 // action. Also, keep track of the offloading kinds employed. 3712 auto &OffloadKind = InputArgToOffloadKindMap[InputArg]; 3713 unsigned InactiveBuilders = 0u; 3714 unsigned IgnoringBuilders = 0u; 3715 for (auto *SB : SpecializedBuilders) { 3716 if (!SB->isValid()) { 3717 ++InactiveBuilders; 3718 continue; 3719 } 3720 auto RetCode = 3721 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases); 3722 3723 // If the builder explicitly says the host action should be ignored, 3724 // we need to increment the variable that tracks the builders that request 3725 // the host object to be ignored. 3726 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host) 3727 ++IgnoringBuilders; 3728 3729 // Unless the builder was inactive for this action, we have to record the 3730 // offload kind because the host will have to use it. 3731 if (RetCode != DeviceActionBuilder::ABRT_Inactive) 3732 OffloadKind |= SB->getAssociatedOffloadKind(); 3733 } 3734 3735 // If all builders agree that the host object should be ignored, just return 3736 // nullptr. 3737 if (IgnoringBuilders && 3738 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders)) 3739 return nullptr; 3740 3741 if (DDeps.getActions().empty()) 3742 return HostAction; 3743 3744 // We have dependences we need to bundle together. We use an offload action 3745 // for that. 3746 OffloadAction::HostDependence HDep( 3747 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 3748 /*BoundArch=*/nullptr, DDeps); 3749 return C.MakeAction<OffloadAction>(HDep, DDeps); 3750 } 3751 3752 /// Generate an action that adds a host dependence to a device action. The 3753 /// results will be kept in this action builder. Return true if an error was 3754 /// found. 3755 bool addHostDependenceToDeviceActions(Action *&HostAction, 3756 const Arg *InputArg) { 3757 if (!IsValid) 3758 return true; 3759 3760 recordHostAction(HostAction, InputArg); 3761 3762 // If we are supporting bundling/unbundling and the current action is an 3763 // input action of non-source file, we replace the host action by the 3764 // unbundling action. The bundler tool has the logic to detect if an input 3765 // is a bundle or not and if the input is not a bundle it assumes it is a 3766 // host file. Therefore it is safe to create an unbundling action even if 3767 // the input is not a bundle. 3768 if (CanUseBundler && isa<InputAction>(HostAction) && 3769 InputArg->getOption().getKind() == llvm::opt::Option::InputClass && 3770 (!types::isSrcFile(HostAction->getType()) || 3771 HostAction->getType() == types::TY_PP_HIP)) { 3772 auto UnbundlingHostAction = 3773 C.MakeAction<OffloadUnbundlingJobAction>(HostAction); 3774 UnbundlingHostAction->registerDependentActionInfo( 3775 C.getSingleOffloadToolChain<Action::OFK_Host>(), 3776 /*BoundArch=*/StringRef(), Action::OFK_Host); 3777 HostAction = UnbundlingHostAction; 3778 recordHostAction(HostAction, InputArg); 3779 } 3780 3781 assert(HostAction && "Invalid host action!"); 3782 3783 // Register the offload kinds that are used. 3784 auto &OffloadKind = InputArgToOffloadKindMap[InputArg]; 3785 for (auto *SB : SpecializedBuilders) { 3786 if (!SB->isValid()) 3787 continue; 3788 3789 auto RetCode = SB->addDeviceDependences(HostAction); 3790 3791 // Host dependences for device actions are not compatible with that same 3792 // action being ignored. 3793 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host && 3794 "Host dependence not expected to be ignored.!"); 3795 3796 // Unless the builder was inactive for this action, we have to record the 3797 // offload kind because the host will have to use it. 3798 if (RetCode != DeviceActionBuilder::ABRT_Inactive) 3799 OffloadKind |= SB->getAssociatedOffloadKind(); 3800 } 3801 3802 // Do not use unbundler if the Host does not depend on device action. 3803 if (OffloadKind == Action::OFK_None && CanUseBundler) 3804 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) 3805 HostAction = UA->getInputs().back(); 3806 3807 return false; 3808 } 3809 3810 /// Add the offloading top level actions to the provided action list. This 3811 /// function can replace the host action by a bundling action if the 3812 /// programming models allow it. 3813 bool appendTopLevelActions(ActionList &AL, Action *HostAction, 3814 const Arg *InputArg) { 3815 if (HostAction) 3816 recordHostAction(HostAction, InputArg); 3817 3818 // Get the device actions to be appended. 3819 ActionList OffloadAL; 3820 for (auto *SB : SpecializedBuilders) { 3821 if (!SB->isValid()) 3822 continue; 3823 SB->appendTopLevelActions(OffloadAL); 3824 } 3825 3826 // If we can use the bundler, replace the host action by the bundling one in 3827 // the resulting list. Otherwise, just append the device actions. For 3828 // device only compilation, HostAction is a null pointer, therefore only do 3829 // this when HostAction is not a null pointer. 3830 if (CanUseBundler && HostAction && 3831 HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) { 3832 // Add the host action to the list in order to create the bundling action. 3833 OffloadAL.push_back(HostAction); 3834 3835 // We expect that the host action was just appended to the action list 3836 // before this method was called. 3837 assert(HostAction == AL.back() && "Host action not in the list??"); 3838 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL); 3839 recordHostAction(HostAction, InputArg); 3840 AL.back() = HostAction; 3841 } else 3842 AL.append(OffloadAL.begin(), OffloadAL.end()); 3843 3844 // Propagate to the current host action (if any) the offload information 3845 // associated with the current input. 3846 if (HostAction) 3847 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg], 3848 /*BoundArch=*/nullptr); 3849 return false; 3850 } 3851 3852 void appendDeviceLinkActions(ActionList &AL) { 3853 for (DeviceActionBuilder *SB : SpecializedBuilders) { 3854 if (!SB->isValid()) 3855 continue; 3856 SB->appendLinkDeviceActions(AL); 3857 } 3858 } 3859 3860 Action *makeHostLinkAction() { 3861 // Build a list of device linking actions. 3862 ActionList DeviceAL; 3863 appendDeviceLinkActions(DeviceAL); 3864 if (DeviceAL.empty()) 3865 return nullptr; 3866 3867 // Let builders add host linking actions. 3868 Action* HA = nullptr; 3869 for (DeviceActionBuilder *SB : SpecializedBuilders) { 3870 if (!SB->isValid()) 3871 continue; 3872 HA = SB->appendLinkHostActions(DeviceAL); 3873 // This created host action has no originating input argument, therefore 3874 // needs to set its offloading kind directly. 3875 if (HA) 3876 HA->propagateHostOffloadInfo(SB->getAssociatedOffloadKind(), 3877 /*BoundArch=*/nullptr); 3878 } 3879 return HA; 3880 } 3881 3882 /// Processes the host linker action. This currently consists of replacing it 3883 /// with an offload action if there are device link objects and propagate to 3884 /// the host action all the offload kinds used in the current compilation. The 3885 /// resulting action is returned. 3886 Action *processHostLinkAction(Action *HostAction) { 3887 // Add all the dependences from the device linking actions. 3888 OffloadAction::DeviceDependences DDeps; 3889 for (auto *SB : SpecializedBuilders) { 3890 if (!SB->isValid()) 3891 continue; 3892 3893 SB->appendLinkDependences(DDeps); 3894 } 3895 3896 // Calculate all the offload kinds used in the current compilation. 3897 unsigned ActiveOffloadKinds = 0u; 3898 for (auto &I : InputArgToOffloadKindMap) 3899 ActiveOffloadKinds |= I.second; 3900 3901 // If we don't have device dependencies, we don't have to create an offload 3902 // action. 3903 if (DDeps.getActions().empty()) { 3904 // Set all the active offloading kinds to the link action. Given that it 3905 // is a link action it is assumed to depend on all actions generated so 3906 // far. 3907 HostAction->setHostOffloadInfo(ActiveOffloadKinds, 3908 /*BoundArch=*/nullptr); 3909 // Propagate active offloading kinds for each input to the link action. 3910 // Each input may have different active offloading kind. 3911 for (auto *A : HostAction->inputs()) { 3912 auto ArgLoc = HostActionToInputArgMap.find(A); 3913 if (ArgLoc == HostActionToInputArgMap.end()) 3914 continue; 3915 auto OFKLoc = InputArgToOffloadKindMap.find(ArgLoc->second); 3916 if (OFKLoc == InputArgToOffloadKindMap.end()) 3917 continue; 3918 A->propagateHostOffloadInfo(OFKLoc->second, /*BoundArch=*/nullptr); 3919 } 3920 return HostAction; 3921 } 3922 3923 // Create the offload action with all dependences. When an offload action 3924 // is created the kinds are propagated to the host action, so we don't have 3925 // to do that explicitly here. 3926 OffloadAction::HostDependence HDep( 3927 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 3928 /*BoundArch*/ nullptr, ActiveOffloadKinds); 3929 return C.MakeAction<OffloadAction>(HDep, DDeps); 3930 } 3931 }; 3932 } // anonymous namespace. 3933 3934 void Driver::handleArguments(Compilation &C, DerivedArgList &Args, 3935 const InputList &Inputs, 3936 ActionList &Actions) const { 3937 3938 // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames. 3939 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc); 3940 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu); 3941 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) { 3942 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl); 3943 Args.eraseArg(options::OPT__SLASH_Yc); 3944 Args.eraseArg(options::OPT__SLASH_Yu); 3945 YcArg = YuArg = nullptr; 3946 } 3947 if (YcArg && Inputs.size() > 1) { 3948 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl); 3949 Args.eraseArg(options::OPT__SLASH_Yc); 3950 YcArg = nullptr; 3951 } 3952 3953 Arg *FinalPhaseArg; 3954 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg); 3955 3956 if (FinalPhase == phases::Link) { 3957 if (Args.hasArgNoClaim(options::OPT_hipstdpar)) { 3958 Args.AddFlagArg(nullptr, getOpts().getOption(options::OPT_hip_link)); 3959 Args.AddFlagArg(nullptr, 3960 getOpts().getOption(options::OPT_frtlib_add_rpath)); 3961 } 3962 // Emitting LLVM while linking disabled except in HIPAMD Toolchain 3963 if (Args.hasArg(options::OPT_emit_llvm) && !Args.hasArg(options::OPT_hip_link)) 3964 Diag(clang::diag::err_drv_emit_llvm_link); 3965 if (IsCLMode() && LTOMode != LTOK_None && 3966 !Args.getLastArgValue(options::OPT_fuse_ld_EQ) 3967 .equals_insensitive("lld")) 3968 Diag(clang::diag::err_drv_lto_without_lld); 3969 3970 // If -dumpdir is not specified, give a default prefix derived from the link 3971 // output filename. For example, `clang -g -gsplit-dwarf a.c -o x` passes 3972 // `-dumpdir x-` to cc1. If -o is unspecified, use 3973 // stem(getDefaultImageName()) (usually stem("a.out") = "a"). 3974 if (!Args.hasArg(options::OPT_dumpdir)) { 3975 Arg *FinalOutput = Args.getLastArg(options::OPT_o, options::OPT__SLASH_o); 3976 Arg *Arg = Args.MakeSeparateArg( 3977 nullptr, getOpts().getOption(options::OPT_dumpdir), 3978 Args.MakeArgString( 3979 (FinalOutput ? FinalOutput->getValue() 3980 : llvm::sys::path::stem(getDefaultImageName())) + 3981 "-")); 3982 Arg->claim(); 3983 Args.append(Arg); 3984 } 3985 } 3986 3987 if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) { 3988 // If only preprocessing or /Y- is used, all pch handling is disabled. 3989 // Rather than check for it everywhere, just remove clang-cl pch-related 3990 // flags here. 3991 Args.eraseArg(options::OPT__SLASH_Fp); 3992 Args.eraseArg(options::OPT__SLASH_Yc); 3993 Args.eraseArg(options::OPT__SLASH_Yu); 3994 YcArg = YuArg = nullptr; 3995 } 3996 3997 unsigned LastPLSize = 0; 3998 for (auto &I : Inputs) { 3999 types::ID InputType = I.first; 4000 const Arg *InputArg = I.second; 4001 4002 auto PL = types::getCompilationPhases(InputType); 4003 LastPLSize = PL.size(); 4004 4005 // If the first step comes after the final phase we are doing as part of 4006 // this compilation, warn the user about it. 4007 phases::ID InitialPhase = PL[0]; 4008 if (InitialPhase > FinalPhase) { 4009 if (InputArg->isClaimed()) 4010 continue; 4011 4012 // Claim here to avoid the more general unused warning. 4013 InputArg->claim(); 4014 4015 // Suppress all unused style warnings with -Qunused-arguments 4016 if (Args.hasArg(options::OPT_Qunused_arguments)) 4017 continue; 4018 4019 // Special case when final phase determined by binary name, rather than 4020 // by a command-line argument with a corresponding Arg. 4021 if (CCCIsCPP()) 4022 Diag(clang::diag::warn_drv_input_file_unused_by_cpp) 4023 << InputArg->getAsString(Args) << getPhaseName(InitialPhase); 4024 // Special case '-E' warning on a previously preprocessed file to make 4025 // more sense. 4026 else if (InitialPhase == phases::Compile && 4027 (Args.getLastArg(options::OPT__SLASH_EP, 4028 options::OPT__SLASH_P) || 4029 Args.getLastArg(options::OPT_E) || 4030 Args.getLastArg(options::OPT_M, options::OPT_MM)) && 4031 getPreprocessedType(InputType) == types::TY_INVALID) 4032 Diag(clang::diag::warn_drv_preprocessed_input_file_unused) 4033 << InputArg->getAsString(Args) << !!FinalPhaseArg 4034 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""); 4035 else 4036 Diag(clang::diag::warn_drv_input_file_unused) 4037 << InputArg->getAsString(Args) << getPhaseName(InitialPhase) 4038 << !!FinalPhaseArg 4039 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""); 4040 continue; 4041 } 4042 4043 if (YcArg) { 4044 // Add a separate precompile phase for the compile phase. 4045 if (FinalPhase >= phases::Compile) { 4046 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType); 4047 // Build the pipeline for the pch file. 4048 Action *ClangClPch = C.MakeAction<InputAction>(*InputArg, HeaderType); 4049 for (phases::ID Phase : types::getCompilationPhases(HeaderType)) 4050 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch); 4051 assert(ClangClPch); 4052 Actions.push_back(ClangClPch); 4053 // The driver currently exits after the first failed command. This 4054 // relies on that behavior, to make sure if the pch generation fails, 4055 // the main compilation won't run. 4056 // FIXME: If the main compilation fails, the PCH generation should 4057 // probably not be considered successful either. 4058 } 4059 } 4060 } 4061 4062 // If we are linking, claim any options which are obviously only used for 4063 // compilation. 4064 // FIXME: Understand why the last Phase List length is used here. 4065 if (FinalPhase == phases::Link && LastPLSize == 1) { 4066 Args.ClaimAllArgs(options::OPT_CompileOnly_Group); 4067 Args.ClaimAllArgs(options::OPT_cl_compile_Group); 4068 } 4069 } 4070 4071 void Driver::BuildActions(Compilation &C, DerivedArgList &Args, 4072 const InputList &Inputs, ActionList &Actions) const { 4073 llvm::PrettyStackTraceString CrashInfo("Building compilation actions"); 4074 4075 if (!SuppressMissingInputWarning && Inputs.empty()) { 4076 Diag(clang::diag::err_drv_no_input_files); 4077 return; 4078 } 4079 4080 // Diagnose misuse of /Fo. 4081 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) { 4082 StringRef V = A->getValue(); 4083 if (Inputs.size() > 1 && !V.empty() && 4084 !llvm::sys::path::is_separator(V.back())) { 4085 // Check whether /Fo tries to name an output file for multiple inputs. 4086 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources) 4087 << A->getSpelling() << V; 4088 Args.eraseArg(options::OPT__SLASH_Fo); 4089 } 4090 } 4091 4092 // Diagnose misuse of /Fa. 4093 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) { 4094 StringRef V = A->getValue(); 4095 if (Inputs.size() > 1 && !V.empty() && 4096 !llvm::sys::path::is_separator(V.back())) { 4097 // Check whether /Fa tries to name an asm file for multiple inputs. 4098 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources) 4099 << A->getSpelling() << V; 4100 Args.eraseArg(options::OPT__SLASH_Fa); 4101 } 4102 } 4103 4104 // Diagnose misuse of /o. 4105 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) { 4106 if (A->getValue()[0] == '\0') { 4107 // It has to have a value. 4108 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1; 4109 Args.eraseArg(options::OPT__SLASH_o); 4110 } 4111 } 4112 4113 handleArguments(C, Args, Inputs, Actions); 4114 4115 bool UseNewOffloadingDriver = 4116 C.isOffloadingHostKind(Action::OFK_OpenMP) || 4117 Args.hasFlag(options::OPT_offload_new_driver, 4118 options::OPT_no_offload_new_driver, false); 4119 4120 // Builder to be used to build offloading actions. 4121 std::unique_ptr<OffloadingActionBuilder> OffloadBuilder = 4122 !UseNewOffloadingDriver 4123 ? std::make_unique<OffloadingActionBuilder>(C, Args, Inputs) 4124 : nullptr; 4125 4126 // Construct the actions to perform. 4127 ExtractAPIJobAction *ExtractAPIAction = nullptr; 4128 ActionList LinkerInputs; 4129 ActionList MergerInputs; 4130 4131 for (auto &I : Inputs) { 4132 types::ID InputType = I.first; 4133 const Arg *InputArg = I.second; 4134 4135 auto PL = types::getCompilationPhases(*this, Args, InputType); 4136 if (PL.empty()) 4137 continue; 4138 4139 auto FullPL = types::getCompilationPhases(InputType); 4140 4141 // Build the pipeline for this file. 4142 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType); 4143 4144 // Use the current host action in any of the offloading actions, if 4145 // required. 4146 if (!UseNewOffloadingDriver) 4147 if (OffloadBuilder->addHostDependenceToDeviceActions(Current, InputArg)) 4148 break; 4149 4150 for (phases::ID Phase : PL) { 4151 4152 // Add any offload action the host action depends on. 4153 if (!UseNewOffloadingDriver) 4154 Current = OffloadBuilder->addDeviceDependencesToHostAction( 4155 Current, InputArg, Phase, PL.back(), FullPL); 4156 if (!Current) 4157 break; 4158 4159 // Queue linker inputs. 4160 if (Phase == phases::Link) { 4161 assert(Phase == PL.back() && "linking must be final compilation step."); 4162 // We don't need to generate additional link commands if emitting AMD 4163 // bitcode or compiling only for the offload device 4164 if (!(C.getInputArgs().hasArg(options::OPT_hip_link) && 4165 (C.getInputArgs().hasArg(options::OPT_emit_llvm))) && 4166 !offloadDeviceOnly()) 4167 LinkerInputs.push_back(Current); 4168 Current = nullptr; 4169 break; 4170 } 4171 4172 // TODO: Consider removing this because the merged may not end up being 4173 // the final Phase in the pipeline. Perhaps the merged could just merge 4174 // and then pass an artifact of some sort to the Link Phase. 4175 // Queue merger inputs. 4176 if (Phase == phases::IfsMerge) { 4177 assert(Phase == PL.back() && "merging must be final compilation step."); 4178 MergerInputs.push_back(Current); 4179 Current = nullptr; 4180 break; 4181 } 4182 4183 if (Phase == phases::Precompile && ExtractAPIAction) { 4184 ExtractAPIAction->addHeaderInput(Current); 4185 Current = nullptr; 4186 break; 4187 } 4188 4189 // FIXME: Should we include any prior module file outputs as inputs of 4190 // later actions in the same command line? 4191 4192 // Otherwise construct the appropriate action. 4193 Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current); 4194 4195 // We didn't create a new action, so we will just move to the next phase. 4196 if (NewCurrent == Current) 4197 continue; 4198 4199 if (auto *EAA = dyn_cast<ExtractAPIJobAction>(NewCurrent)) 4200 ExtractAPIAction = EAA; 4201 4202 Current = NewCurrent; 4203 4204 // Try to build the offloading actions and add the result as a dependency 4205 // to the host. 4206 if (UseNewOffloadingDriver) 4207 Current = BuildOffloadingActions(C, Args, I, Current); 4208 // Use the current host action in any of the offloading actions, if 4209 // required. 4210 else if (OffloadBuilder->addHostDependenceToDeviceActions(Current, 4211 InputArg)) 4212 break; 4213 4214 if (Current->getType() == types::TY_Nothing) 4215 break; 4216 } 4217 4218 // If we ended with something, add to the output list. 4219 if (Current) 4220 Actions.push_back(Current); 4221 4222 // Add any top level actions generated for offloading. 4223 if (!UseNewOffloadingDriver) 4224 OffloadBuilder->appendTopLevelActions(Actions, Current, InputArg); 4225 else if (Current) 4226 Current->propagateHostOffloadInfo(C.getActiveOffloadKinds(), 4227 /*BoundArch=*/nullptr); 4228 } 4229 4230 // Add a link action if necessary. 4231 4232 if (LinkerInputs.empty()) { 4233 Arg *FinalPhaseArg; 4234 if (getFinalPhase(Args, &FinalPhaseArg) == phases::Link) 4235 if (!UseNewOffloadingDriver) 4236 OffloadBuilder->appendDeviceLinkActions(Actions); 4237 } 4238 4239 if (!LinkerInputs.empty()) { 4240 if (!UseNewOffloadingDriver) 4241 if (Action *Wrapper = OffloadBuilder->makeHostLinkAction()) 4242 LinkerInputs.push_back(Wrapper); 4243 Action *LA; 4244 // Check if this Linker Job should emit a static library. 4245 if (ShouldEmitStaticLibrary(Args)) { 4246 LA = C.MakeAction<StaticLibJobAction>(LinkerInputs, types::TY_Image); 4247 } else if (UseNewOffloadingDriver || 4248 Args.hasArg(options::OPT_offload_link)) { 4249 LA = C.MakeAction<LinkerWrapperJobAction>(LinkerInputs, types::TY_Image); 4250 LA->propagateHostOffloadInfo(C.getActiveOffloadKinds(), 4251 /*BoundArch=*/nullptr); 4252 } else { 4253 LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image); 4254 } 4255 if (!UseNewOffloadingDriver) 4256 LA = OffloadBuilder->processHostLinkAction(LA); 4257 Actions.push_back(LA); 4258 } 4259 4260 // Add an interface stubs merge action if necessary. 4261 if (!MergerInputs.empty()) 4262 Actions.push_back( 4263 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image)); 4264 4265 if (Args.hasArg(options::OPT_emit_interface_stubs)) { 4266 auto PhaseList = types::getCompilationPhases( 4267 types::TY_IFS_CPP, 4268 Args.hasArg(options::OPT_c) ? phases::Compile : phases::IfsMerge); 4269 4270 ActionList MergerInputs; 4271 4272 for (auto &I : Inputs) { 4273 types::ID InputType = I.first; 4274 const Arg *InputArg = I.second; 4275 4276 // Currently clang and the llvm assembler do not support generating symbol 4277 // stubs from assembly, so we skip the input on asm files. For ifs files 4278 // we rely on the normal pipeline setup in the pipeline setup code above. 4279 if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm || 4280 InputType == types::TY_Asm) 4281 continue; 4282 4283 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType); 4284 4285 for (auto Phase : PhaseList) { 4286 switch (Phase) { 4287 default: 4288 llvm_unreachable( 4289 "IFS Pipeline can only consist of Compile followed by IfsMerge."); 4290 case phases::Compile: { 4291 // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs 4292 // files where the .o file is located. The compile action can not 4293 // handle this. 4294 if (InputType == types::TY_Object) 4295 break; 4296 4297 Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP); 4298 break; 4299 } 4300 case phases::IfsMerge: { 4301 assert(Phase == PhaseList.back() && 4302 "merging must be final compilation step."); 4303 MergerInputs.push_back(Current); 4304 Current = nullptr; 4305 break; 4306 } 4307 } 4308 } 4309 4310 // If we ended with something, add to the output list. 4311 if (Current) 4312 Actions.push_back(Current); 4313 } 4314 4315 // Add an interface stubs merge action if necessary. 4316 if (!MergerInputs.empty()) 4317 Actions.push_back( 4318 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image)); 4319 } 4320 4321 for (auto Opt : {options::OPT_print_supported_cpus, 4322 options::OPT_print_supported_extensions}) { 4323 // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a 4324 // custom Compile phase that prints out supported cpu models and quits. 4325 // 4326 // If --print-supported-extensions is specified, call the helper function 4327 // RISCVMarchHelp in RISCVISAInfo.cpp that prints out supported extensions 4328 // and quits. 4329 if (Arg *A = Args.getLastArg(Opt)) { 4330 if (Opt == options::OPT_print_supported_extensions && 4331 !C.getDefaultToolChain().getTriple().isRISCV() && 4332 !C.getDefaultToolChain().getTriple().isAArch64() && 4333 !C.getDefaultToolChain().getTriple().isARM()) { 4334 C.getDriver().Diag(diag::err_opt_not_valid_on_target) 4335 << "--print-supported-extensions"; 4336 return; 4337 } 4338 4339 // Use the -mcpu=? flag as the dummy input to cc1. 4340 Actions.clear(); 4341 Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C); 4342 Actions.push_back( 4343 C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing)); 4344 for (auto &I : Inputs) 4345 I.second->claim(); 4346 } 4347 } 4348 4349 // Call validator for dxil when -Vd not in Args. 4350 if (C.getDefaultToolChain().getTriple().isDXIL()) { 4351 // Only add action when needValidation. 4352 const auto &TC = 4353 static_cast<const toolchains::HLSLToolChain &>(C.getDefaultToolChain()); 4354 if (TC.requiresValidation(Args)) { 4355 Action *LastAction = Actions.back(); 4356 Actions.push_back(C.MakeAction<BinaryAnalyzeJobAction>( 4357 LastAction, types::TY_DX_CONTAINER)); 4358 } 4359 } 4360 4361 // Claim ignored clang-cl options. 4362 Args.ClaimAllArgs(options::OPT_cl_ignored_Group); 4363 } 4364 4365 /// Returns the canonical name for the offloading architecture when using a HIP 4366 /// or CUDA architecture. 4367 static StringRef getCanonicalArchString(Compilation &C, 4368 const llvm::opt::DerivedArgList &Args, 4369 StringRef ArchStr, 4370 const llvm::Triple &Triple, 4371 bool SuppressError = false) { 4372 // Lookup the CUDA / HIP architecture string. Only report an error if we were 4373 // expecting the triple to be only NVPTX / AMDGPU. 4374 CudaArch Arch = StringToCudaArch(getProcessorFromTargetID(Triple, ArchStr)); 4375 if (!SuppressError && Triple.isNVPTX() && 4376 (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch))) { 4377 C.getDriver().Diag(clang::diag::err_drv_offload_bad_gpu_arch) 4378 << "CUDA" << ArchStr; 4379 return StringRef(); 4380 } else if (!SuppressError && Triple.isAMDGPU() && 4381 (Arch == CudaArch::UNKNOWN || !IsAMDGpuArch(Arch))) { 4382 C.getDriver().Diag(clang::diag::err_drv_offload_bad_gpu_arch) 4383 << "HIP" << ArchStr; 4384 return StringRef(); 4385 } 4386 4387 if (IsNVIDIAGpuArch(Arch)) 4388 return Args.MakeArgStringRef(CudaArchToString(Arch)); 4389 4390 if (IsAMDGpuArch(Arch)) { 4391 llvm::StringMap<bool> Features; 4392 auto HIPTriple = getHIPOffloadTargetTriple(C.getDriver(), C.getInputArgs()); 4393 if (!HIPTriple) 4394 return StringRef(); 4395 auto Arch = parseTargetID(*HIPTriple, ArchStr, &Features); 4396 if (!Arch) { 4397 C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << ArchStr; 4398 C.setContainsError(); 4399 return StringRef(); 4400 } 4401 return Args.MakeArgStringRef(getCanonicalTargetID(*Arch, Features)); 4402 } 4403 4404 // If the input isn't CUDA or HIP just return the architecture. 4405 return ArchStr; 4406 } 4407 4408 /// Checks if the set offloading architectures does not conflict. Returns the 4409 /// incompatible pair if a conflict occurs. 4410 static std::optional<std::pair<llvm::StringRef, llvm::StringRef>> 4411 getConflictOffloadArchCombination(const llvm::DenseSet<StringRef> &Archs, 4412 llvm::Triple Triple) { 4413 if (!Triple.isAMDGPU()) 4414 return std::nullopt; 4415 4416 std::set<StringRef> ArchSet; 4417 llvm::copy(Archs, std::inserter(ArchSet, ArchSet.begin())); 4418 return getConflictTargetIDCombination(ArchSet); 4419 } 4420 4421 llvm::DenseSet<StringRef> 4422 Driver::getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args, 4423 Action::OffloadKind Kind, const ToolChain *TC, 4424 bool SuppressError) const { 4425 if (!TC) 4426 TC = &C.getDefaultToolChain(); 4427 4428 // --offload and --offload-arch options are mutually exclusive. 4429 if (Args.hasArgNoClaim(options::OPT_offload_EQ) && 4430 Args.hasArgNoClaim(options::OPT_offload_arch_EQ, 4431 options::OPT_no_offload_arch_EQ)) { 4432 C.getDriver().Diag(diag::err_opt_not_valid_with_opt) 4433 << "--offload" 4434 << (Args.hasArgNoClaim(options::OPT_offload_arch_EQ) 4435 ? "--offload-arch" 4436 : "--no-offload-arch"); 4437 } 4438 4439 if (KnownArchs.contains(TC)) 4440 return KnownArchs.lookup(TC); 4441 4442 llvm::DenseSet<StringRef> Archs; 4443 for (auto *Arg : Args) { 4444 // Extract any '--[no-]offload-arch' arguments intended for this toolchain. 4445 std::unique_ptr<llvm::opt::Arg> ExtractedArg = nullptr; 4446 if (Arg->getOption().matches(options::OPT_Xopenmp_target_EQ) && 4447 ToolChain::getOpenMPTriple(Arg->getValue(0)) == TC->getTriple()) { 4448 Arg->claim(); 4449 unsigned Index = Args.getBaseArgs().MakeIndex(Arg->getValue(1)); 4450 ExtractedArg = getOpts().ParseOneArg(Args, Index); 4451 Arg = ExtractedArg.get(); 4452 } 4453 4454 // Add or remove the seen architectures in order of appearance. If an 4455 // invalid architecture is given we simply exit. 4456 if (Arg->getOption().matches(options::OPT_offload_arch_EQ)) { 4457 for (StringRef Arch : llvm::split(Arg->getValue(), ",")) { 4458 if (Arch == "native" || Arch.empty()) { 4459 auto GPUsOrErr = TC->getSystemGPUArchs(Args); 4460 if (!GPUsOrErr) { 4461 if (SuppressError) 4462 llvm::consumeError(GPUsOrErr.takeError()); 4463 else 4464 TC->getDriver().Diag(diag::err_drv_undetermined_gpu_arch) 4465 << llvm::Triple::getArchTypeName(TC->getArch()) 4466 << llvm::toString(GPUsOrErr.takeError()) << "--offload-arch"; 4467 continue; 4468 } 4469 4470 for (auto ArchStr : *GPUsOrErr) { 4471 Archs.insert( 4472 getCanonicalArchString(C, Args, Args.MakeArgString(ArchStr), 4473 TC->getTriple(), SuppressError)); 4474 } 4475 } else { 4476 StringRef ArchStr = getCanonicalArchString( 4477 C, Args, Arch, TC->getTriple(), SuppressError); 4478 if (ArchStr.empty()) 4479 return Archs; 4480 Archs.insert(ArchStr); 4481 } 4482 } 4483 } else if (Arg->getOption().matches(options::OPT_no_offload_arch_EQ)) { 4484 for (StringRef Arch : llvm::split(Arg->getValue(), ",")) { 4485 if (Arch == "all") { 4486 Archs.clear(); 4487 } else { 4488 StringRef ArchStr = getCanonicalArchString( 4489 C, Args, Arch, TC->getTriple(), SuppressError); 4490 if (ArchStr.empty()) 4491 return Archs; 4492 Archs.erase(ArchStr); 4493 } 4494 } 4495 } 4496 } 4497 4498 if (auto ConflictingArchs = 4499 getConflictOffloadArchCombination(Archs, TC->getTriple())) { 4500 C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo) 4501 << ConflictingArchs->first << ConflictingArchs->second; 4502 C.setContainsError(); 4503 } 4504 4505 // Skip filling defaults if we're just querying what is availible. 4506 if (SuppressError) 4507 return Archs; 4508 4509 if (Archs.empty()) { 4510 if (Kind == Action::OFK_Cuda) 4511 Archs.insert(CudaArchToString(CudaArch::CudaDefault)); 4512 else if (Kind == Action::OFK_HIP) 4513 Archs.insert(CudaArchToString(CudaArch::HIPDefault)); 4514 else if (Kind == Action::OFK_OpenMP) 4515 Archs.insert(StringRef()); 4516 } else { 4517 Args.ClaimAllArgs(options::OPT_offload_arch_EQ); 4518 Args.ClaimAllArgs(options::OPT_no_offload_arch_EQ); 4519 } 4520 4521 return Archs; 4522 } 4523 4524 Action *Driver::BuildOffloadingActions(Compilation &C, 4525 llvm::opt::DerivedArgList &Args, 4526 const InputTy &Input, 4527 Action *HostAction) const { 4528 // Don't build offloading actions if explicitly disabled or we do not have a 4529 // valid source input and compile action to embed it in. If preprocessing only 4530 // ignore embedding. 4531 if (offloadHostOnly() || !types::isSrcFile(Input.first) || 4532 !(isa<CompileJobAction>(HostAction) || 4533 getFinalPhase(Args) == phases::Preprocess)) 4534 return HostAction; 4535 4536 ActionList OffloadActions; 4537 OffloadAction::DeviceDependences DDeps; 4538 4539 const Action::OffloadKind OffloadKinds[] = { 4540 Action::OFK_OpenMP, Action::OFK_Cuda, Action::OFK_HIP}; 4541 4542 for (Action::OffloadKind Kind : OffloadKinds) { 4543 SmallVector<const ToolChain *, 2> ToolChains; 4544 ActionList DeviceActions; 4545 4546 auto TCRange = C.getOffloadToolChains(Kind); 4547 for (auto TI = TCRange.first, TE = TCRange.second; TI != TE; ++TI) 4548 ToolChains.push_back(TI->second); 4549 4550 if (ToolChains.empty()) 4551 continue; 4552 4553 types::ID InputType = Input.first; 4554 const Arg *InputArg = Input.second; 4555 4556 // The toolchain can be active for unsupported file types. 4557 if ((Kind == Action::OFK_Cuda && !types::isCuda(InputType)) || 4558 (Kind == Action::OFK_HIP && !types::isHIP(InputType))) 4559 continue; 4560 4561 // Get the product of all bound architectures and toolchains. 4562 SmallVector<std::pair<const ToolChain *, StringRef>> TCAndArchs; 4563 for (const ToolChain *TC : ToolChains) 4564 for (StringRef Arch : getOffloadArchs(C, Args, Kind, TC)) 4565 TCAndArchs.push_back(std::make_pair(TC, Arch)); 4566 4567 for (unsigned I = 0, E = TCAndArchs.size(); I != E; ++I) 4568 DeviceActions.push_back(C.MakeAction<InputAction>(*InputArg, InputType)); 4569 4570 if (DeviceActions.empty()) 4571 return HostAction; 4572 4573 auto PL = types::getCompilationPhases(*this, Args, InputType); 4574 4575 for (phases::ID Phase : PL) { 4576 if (Phase == phases::Link) { 4577 assert(Phase == PL.back() && "linking must be final compilation step."); 4578 break; 4579 } 4580 4581 auto TCAndArch = TCAndArchs.begin(); 4582 for (Action *&A : DeviceActions) { 4583 if (A->getType() == types::TY_Nothing) 4584 continue; 4585 4586 // Propagate the ToolChain so we can use it in ConstructPhaseAction. 4587 A->propagateDeviceOffloadInfo(Kind, TCAndArch->second.data(), 4588 TCAndArch->first); 4589 A = ConstructPhaseAction(C, Args, Phase, A, Kind); 4590 4591 if (isa<CompileJobAction>(A) && isa<CompileJobAction>(HostAction) && 4592 Kind == Action::OFK_OpenMP && 4593 HostAction->getType() != types::TY_Nothing) { 4594 // OpenMP offloading has a dependency on the host compile action to 4595 // identify which declarations need to be emitted. This shouldn't be 4596 // collapsed with any other actions so we can use it in the device. 4597 HostAction->setCannotBeCollapsedWithNextDependentAction(); 4598 OffloadAction::HostDependence HDep( 4599 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 4600 TCAndArch->second.data(), Kind); 4601 OffloadAction::DeviceDependences DDep; 4602 DDep.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind); 4603 A = C.MakeAction<OffloadAction>(HDep, DDep); 4604 } 4605 4606 ++TCAndArch; 4607 } 4608 } 4609 4610 // Compiling HIP in non-RDC mode requires linking each action individually. 4611 for (Action *&A : DeviceActions) { 4612 if ((A->getType() != types::TY_Object && 4613 A->getType() != types::TY_LTO_BC) || 4614 Kind != Action::OFK_HIP || 4615 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)) 4616 continue; 4617 ActionList LinkerInput = {A}; 4618 A = C.MakeAction<LinkJobAction>(LinkerInput, types::TY_Image); 4619 } 4620 4621 auto TCAndArch = TCAndArchs.begin(); 4622 for (Action *A : DeviceActions) { 4623 DDeps.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind); 4624 OffloadAction::DeviceDependences DDep; 4625 DDep.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind); 4626 OffloadActions.push_back(C.MakeAction<OffloadAction>(DDep, A->getType())); 4627 ++TCAndArch; 4628 } 4629 } 4630 4631 if (offloadDeviceOnly()) 4632 return C.MakeAction<OffloadAction>(DDeps, types::TY_Nothing); 4633 4634 if (OffloadActions.empty()) 4635 return HostAction; 4636 4637 OffloadAction::DeviceDependences DDep; 4638 if (C.isOffloadingHostKind(Action::OFK_Cuda) && 4639 !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)) { 4640 // If we are not in RDC-mode we just emit the final CUDA fatbinary for 4641 // each translation unit without requiring any linking. 4642 Action *FatbinAction = 4643 C.MakeAction<LinkJobAction>(OffloadActions, types::TY_CUDA_FATBIN); 4644 DDep.add(*FatbinAction, *C.getSingleOffloadToolChain<Action::OFK_Cuda>(), 4645 nullptr, Action::OFK_Cuda); 4646 } else if (C.isOffloadingHostKind(Action::OFK_HIP) && 4647 !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, 4648 false)) { 4649 // If we are not in RDC-mode we just emit the final HIP fatbinary for each 4650 // translation unit, linking each input individually. 4651 Action *FatbinAction = 4652 C.MakeAction<LinkJobAction>(OffloadActions, types::TY_HIP_FATBIN); 4653 DDep.add(*FatbinAction, *C.getSingleOffloadToolChain<Action::OFK_HIP>(), 4654 nullptr, Action::OFK_HIP); 4655 } else { 4656 // Package all the offloading actions into a single output that can be 4657 // embedded in the host and linked. 4658 Action *PackagerAction = 4659 C.MakeAction<OffloadPackagerJobAction>(OffloadActions, types::TY_Image); 4660 DDep.add(*PackagerAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 4661 nullptr, C.getActiveOffloadKinds()); 4662 } 4663 4664 // If we are unable to embed a single device output into the host, we need to 4665 // add each device output as a host dependency to ensure they are still built. 4666 bool SingleDeviceOutput = !llvm::any_of(OffloadActions, [](Action *A) { 4667 return A->getType() == types::TY_Nothing; 4668 }) && isa<CompileJobAction>(HostAction); 4669 OffloadAction::HostDependence HDep( 4670 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 4671 /*BoundArch=*/nullptr, SingleDeviceOutput ? DDep : DDeps); 4672 return C.MakeAction<OffloadAction>(HDep, SingleDeviceOutput ? DDep : DDeps); 4673 } 4674 4675 Action *Driver::ConstructPhaseAction( 4676 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input, 4677 Action::OffloadKind TargetDeviceOffloadKind) const { 4678 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions"); 4679 4680 // Some types skip the assembler phase (e.g., llvm-bc), but we can't 4681 // encode this in the steps because the intermediate type depends on 4682 // arguments. Just special case here. 4683 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm) 4684 return Input; 4685 4686 // Build the appropriate action. 4687 switch (Phase) { 4688 case phases::Link: 4689 llvm_unreachable("link action invalid here."); 4690 case phases::IfsMerge: 4691 llvm_unreachable("ifsmerge action invalid here."); 4692 case phases::Preprocess: { 4693 types::ID OutputTy; 4694 // -M and -MM specify the dependency file name by altering the output type, 4695 // -if -MD and -MMD are not specified. 4696 if (Args.hasArg(options::OPT_M, options::OPT_MM) && 4697 !Args.hasArg(options::OPT_MD, options::OPT_MMD)) { 4698 OutputTy = types::TY_Dependencies; 4699 } else { 4700 OutputTy = Input->getType(); 4701 // For these cases, the preprocessor is only translating forms, the Output 4702 // still needs preprocessing. 4703 if (!Args.hasFlag(options::OPT_frewrite_includes, 4704 options::OPT_fno_rewrite_includes, false) && 4705 !Args.hasFlag(options::OPT_frewrite_imports, 4706 options::OPT_fno_rewrite_imports, false) && 4707 !Args.hasFlag(options::OPT_fdirectives_only, 4708 options::OPT_fno_directives_only, false) && 4709 !CCGenDiagnostics) 4710 OutputTy = types::getPreprocessedType(OutputTy); 4711 assert(OutputTy != types::TY_INVALID && 4712 "Cannot preprocess this input type!"); 4713 } 4714 return C.MakeAction<PreprocessJobAction>(Input, OutputTy); 4715 } 4716 case phases::Precompile: { 4717 // API extraction should not generate an actual precompilation action. 4718 if (Args.hasArg(options::OPT_extract_api)) 4719 return C.MakeAction<ExtractAPIJobAction>(Input, types::TY_API_INFO); 4720 4721 types::ID OutputTy = getPrecompiledType(Input->getType()); 4722 assert(OutputTy != types::TY_INVALID && 4723 "Cannot precompile this input type!"); 4724 4725 // If we're given a module name, precompile header file inputs as a 4726 // module, not as a precompiled header. 4727 const char *ModName = nullptr; 4728 if (OutputTy == types::TY_PCH) { 4729 if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ)) 4730 ModName = A->getValue(); 4731 if (ModName) 4732 OutputTy = types::TY_ModuleFile; 4733 } 4734 4735 if (Args.hasArg(options::OPT_fsyntax_only)) { 4736 // Syntax checks should not emit a PCH file 4737 OutputTy = types::TY_Nothing; 4738 } 4739 4740 return C.MakeAction<PrecompileJobAction>(Input, OutputTy); 4741 } 4742 case phases::Compile: { 4743 if (Args.hasArg(options::OPT_fsyntax_only)) 4744 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing); 4745 if (Args.hasArg(options::OPT_rewrite_objc)) 4746 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC); 4747 if (Args.hasArg(options::OPT_rewrite_legacy_objc)) 4748 return C.MakeAction<CompileJobAction>(Input, 4749 types::TY_RewrittenLegacyObjC); 4750 if (Args.hasArg(options::OPT__analyze)) 4751 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist); 4752 if (Args.hasArg(options::OPT__migrate)) 4753 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap); 4754 if (Args.hasArg(options::OPT_emit_ast)) 4755 return C.MakeAction<CompileJobAction>(Input, types::TY_AST); 4756 if (Args.hasArg(options::OPT_module_file_info)) 4757 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile); 4758 if (Args.hasArg(options::OPT_verify_pch)) 4759 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing); 4760 if (Args.hasArg(options::OPT_extract_api)) 4761 return C.MakeAction<ExtractAPIJobAction>(Input, types::TY_API_INFO); 4762 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC); 4763 } 4764 case phases::Backend: { 4765 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) { 4766 types::ID Output; 4767 if (Args.hasArg(options::OPT_ffat_lto_objects) && 4768 !Args.hasArg(options::OPT_emit_llvm)) 4769 Output = types::TY_PP_Asm; 4770 else if (Args.hasArg(options::OPT_S)) 4771 Output = types::TY_LTO_IR; 4772 else 4773 Output = types::TY_LTO_BC; 4774 return C.MakeAction<BackendJobAction>(Input, Output); 4775 } 4776 if (isUsingLTO(/* IsOffload */ true) && 4777 TargetDeviceOffloadKind != Action::OFK_None) { 4778 types::ID Output = 4779 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC; 4780 return C.MakeAction<BackendJobAction>(Input, Output); 4781 } 4782 if (Args.hasArg(options::OPT_emit_llvm) || 4783 (((Input->getOffloadingToolChain() && 4784 Input->getOffloadingToolChain()->getTriple().isAMDGPU()) || 4785 TargetDeviceOffloadKind == Action::OFK_HIP) && 4786 (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, 4787 false) || 4788 TargetDeviceOffloadKind == Action::OFK_OpenMP))) { 4789 types::ID Output = 4790 Args.hasArg(options::OPT_S) && 4791 (TargetDeviceOffloadKind == Action::OFK_None || 4792 offloadDeviceOnly() || 4793 (TargetDeviceOffloadKind == Action::OFK_HIP && 4794 !Args.hasFlag(options::OPT_offload_new_driver, 4795 options::OPT_no_offload_new_driver, false))) 4796 ? types::TY_LLVM_IR 4797 : types::TY_LLVM_BC; 4798 return C.MakeAction<BackendJobAction>(Input, Output); 4799 } 4800 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm); 4801 } 4802 case phases::Assemble: 4803 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object); 4804 } 4805 4806 llvm_unreachable("invalid phase in ConstructPhaseAction"); 4807 } 4808 4809 void Driver::BuildJobs(Compilation &C) const { 4810 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 4811 4812 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 4813 4814 // It is an error to provide a -o option if we are making multiple output 4815 // files. There are exceptions: 4816 // 4817 // IfsMergeJob: when generating interface stubs enabled we want to be able to 4818 // generate the stub file at the same time that we generate the real 4819 // library/a.out. So when a .o, .so, etc are the output, with clang interface 4820 // stubs there will also be a .ifs and .ifso at the same location. 4821 // 4822 // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled 4823 // and -c is passed, we still want to be able to generate a .ifs file while 4824 // we are also generating .o files. So we allow more than one output file in 4825 // this case as well. 4826 // 4827 // OffloadClass of type TY_Nothing: device-only output will place many outputs 4828 // into a single offloading action. We should count all inputs to the action 4829 // as outputs. Also ignore device-only outputs if we're compiling with 4830 // -fsyntax-only. 4831 if (FinalOutput) { 4832 unsigned NumOutputs = 0; 4833 unsigned NumIfsOutputs = 0; 4834 for (const Action *A : C.getActions()) { 4835 if (A->getType() != types::TY_Nothing && 4836 A->getType() != types::TY_DX_CONTAINER && 4837 !(A->getKind() == Action::IfsMergeJobClass || 4838 (A->getType() == clang::driver::types::TY_IFS_CPP && 4839 A->getKind() == clang::driver::Action::CompileJobClass && 4840 0 == NumIfsOutputs++) || 4841 (A->getKind() == Action::BindArchClass && A->getInputs().size() && 4842 A->getInputs().front()->getKind() == Action::IfsMergeJobClass))) 4843 ++NumOutputs; 4844 else if (A->getKind() == Action::OffloadClass && 4845 A->getType() == types::TY_Nothing && 4846 !C.getArgs().hasArg(options::OPT_fsyntax_only)) 4847 NumOutputs += A->size(); 4848 } 4849 4850 if (NumOutputs > 1) { 4851 Diag(clang::diag::err_drv_output_argument_with_multiple_files); 4852 FinalOutput = nullptr; 4853 } 4854 } 4855 4856 const llvm::Triple &RawTriple = C.getDefaultToolChain().getTriple(); 4857 4858 // Collect the list of architectures. 4859 llvm::StringSet<> ArchNames; 4860 if (RawTriple.isOSBinFormatMachO()) 4861 for (const Arg *A : C.getArgs()) 4862 if (A->getOption().matches(options::OPT_arch)) 4863 ArchNames.insert(A->getValue()); 4864 4865 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for. 4866 std::map<std::pair<const Action *, std::string>, InputInfoList> CachedResults; 4867 for (Action *A : C.getActions()) { 4868 // If we are linking an image for multiple archs then the linker wants 4869 // -arch_multiple and -final_output <final image name>. Unfortunately, this 4870 // doesn't fit in cleanly because we have to pass this information down. 4871 // 4872 // FIXME: This is a hack; find a cleaner way to integrate this into the 4873 // process. 4874 const char *LinkingOutput = nullptr; 4875 if (isa<LipoJobAction>(A)) { 4876 if (FinalOutput) 4877 LinkingOutput = FinalOutput->getValue(); 4878 else 4879 LinkingOutput = getDefaultImageName(); 4880 } 4881 4882 BuildJobsForAction(C, A, &C.getDefaultToolChain(), 4883 /*BoundArch*/ StringRef(), 4884 /*AtTopLevel*/ true, 4885 /*MultipleArchs*/ ArchNames.size() > 1, 4886 /*LinkingOutput*/ LinkingOutput, CachedResults, 4887 /*TargetDeviceOffloadKind*/ Action::OFK_None); 4888 } 4889 4890 // If we have more than one job, then disable integrated-cc1 for now. Do this 4891 // also when we need to report process execution statistics. 4892 if (C.getJobs().size() > 1 || CCPrintProcessStats) 4893 for (auto &J : C.getJobs()) 4894 J.InProcess = false; 4895 4896 if (CCPrintProcessStats) { 4897 C.setPostCallback([=](const Command &Cmd, int Res) { 4898 std::optional<llvm::sys::ProcessStatistics> ProcStat = 4899 Cmd.getProcessStatistics(); 4900 if (!ProcStat) 4901 return; 4902 4903 const char *LinkingOutput = nullptr; 4904 if (FinalOutput) 4905 LinkingOutput = FinalOutput->getValue(); 4906 else if (!Cmd.getOutputFilenames().empty()) 4907 LinkingOutput = Cmd.getOutputFilenames().front().c_str(); 4908 else 4909 LinkingOutput = getDefaultImageName(); 4910 4911 if (CCPrintStatReportFilename.empty()) { 4912 using namespace llvm; 4913 // Human readable output. 4914 outs() << sys::path::filename(Cmd.getExecutable()) << ": " 4915 << "output=" << LinkingOutput; 4916 outs() << ", total=" 4917 << format("%.3f", ProcStat->TotalTime.count() / 1000.) << " ms" 4918 << ", user=" 4919 << format("%.3f", ProcStat->UserTime.count() / 1000.) << " ms" 4920 << ", mem=" << ProcStat->PeakMemory << " Kb\n"; 4921 } else { 4922 // CSV format. 4923 std::string Buffer; 4924 llvm::raw_string_ostream Out(Buffer); 4925 llvm::sys::printArg(Out, llvm::sys::path::filename(Cmd.getExecutable()), 4926 /*Quote*/ true); 4927 Out << ','; 4928 llvm::sys::printArg(Out, LinkingOutput, true); 4929 Out << ',' << ProcStat->TotalTime.count() << ',' 4930 << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory 4931 << '\n'; 4932 Out.flush(); 4933 std::error_code EC; 4934 llvm::raw_fd_ostream OS(CCPrintStatReportFilename, EC, 4935 llvm::sys::fs::OF_Append | 4936 llvm::sys::fs::OF_Text); 4937 if (EC) 4938 return; 4939 auto L = OS.lock(); 4940 if (!L) { 4941 llvm::errs() << "ERROR: Cannot lock file " 4942 << CCPrintStatReportFilename << ": " 4943 << toString(L.takeError()) << "\n"; 4944 return; 4945 } 4946 OS << Buffer; 4947 OS.flush(); 4948 } 4949 }); 4950 } 4951 4952 // If the user passed -Qunused-arguments or there were errors, don't warn 4953 // about any unused arguments. 4954 if (Diags.hasErrorOccurred() || 4955 C.getArgs().hasArg(options::OPT_Qunused_arguments)) 4956 return; 4957 4958 // Claim -fdriver-only here. 4959 (void)C.getArgs().hasArg(options::OPT_fdriver_only); 4960 // Claim -### here. 4961 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH); 4962 4963 // Claim --driver-mode, --rsp-quoting, it was handled earlier. 4964 (void)C.getArgs().hasArg(options::OPT_driver_mode); 4965 (void)C.getArgs().hasArg(options::OPT_rsp_quoting); 4966 4967 bool HasAssembleJob = llvm::any_of(C.getJobs(), [](auto &J) { 4968 // Match ClangAs and other derived assemblers of Tool. ClangAs uses a 4969 // longer ShortName "clang integrated assembler" while other assemblers just 4970 // use "assembler". 4971 return strstr(J.getCreator().getShortName(), "assembler"); 4972 }); 4973 for (Arg *A : C.getArgs()) { 4974 // FIXME: It would be nice to be able to send the argument to the 4975 // DiagnosticsEngine, so that extra values, position, and so on could be 4976 // printed. 4977 if (!A->isClaimed()) { 4978 if (A->getOption().hasFlag(options::NoArgumentUnused)) 4979 continue; 4980 4981 // Suppress the warning automatically if this is just a flag, and it is an 4982 // instance of an argument we already claimed. 4983 const Option &Opt = A->getOption(); 4984 if (Opt.getKind() == Option::FlagClass) { 4985 bool DuplicateClaimed = false; 4986 4987 for (const Arg *AA : C.getArgs().filtered(&Opt)) { 4988 if (AA->isClaimed()) { 4989 DuplicateClaimed = true; 4990 break; 4991 } 4992 } 4993 4994 if (DuplicateClaimed) 4995 continue; 4996 } 4997 4998 // In clang-cl, don't mention unknown arguments here since they have 4999 // already been warned about. 5000 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN)) { 5001 if (A->getOption().hasFlag(options::TargetSpecific) && 5002 !A->isIgnoredTargetSpecific() && !HasAssembleJob && 5003 // When for example -### or -v is used 5004 // without a file, target specific options are not 5005 // consumed/validated. 5006 // Instead emitting an error emit a warning instead. 5007 !C.getActions().empty()) { 5008 Diag(diag::err_drv_unsupported_opt_for_target) 5009 << A->getSpelling() << getTargetTriple(); 5010 } else { 5011 Diag(clang::diag::warn_drv_unused_argument) 5012 << A->getAsString(C.getArgs()); 5013 } 5014 } 5015 } 5016 } 5017 } 5018 5019 namespace { 5020 /// Utility class to control the collapse of dependent actions and select the 5021 /// tools accordingly. 5022 class ToolSelector final { 5023 /// The tool chain this selector refers to. 5024 const ToolChain &TC; 5025 5026 /// The compilation this selector refers to. 5027 const Compilation &C; 5028 5029 /// The base action this selector refers to. 5030 const JobAction *BaseAction; 5031 5032 /// Set to true if the current toolchain refers to host actions. 5033 bool IsHostSelector; 5034 5035 /// Set to true if save-temps and embed-bitcode functionalities are active. 5036 bool SaveTemps; 5037 bool EmbedBitcode; 5038 5039 /// Get previous dependent action or null if that does not exist. If 5040 /// \a CanBeCollapsed is false, that action must be legal to collapse or 5041 /// null will be returned. 5042 const JobAction *getPrevDependentAction(const ActionList &Inputs, 5043 ActionList &SavedOffloadAction, 5044 bool CanBeCollapsed = true) { 5045 // An option can be collapsed only if it has a single input. 5046 if (Inputs.size() != 1) 5047 return nullptr; 5048 5049 Action *CurAction = *Inputs.begin(); 5050 if (CanBeCollapsed && 5051 !CurAction->isCollapsingWithNextDependentActionLegal()) 5052 return nullptr; 5053 5054 // If the input action is an offload action. Look through it and save any 5055 // offload action that can be dropped in the event of a collapse. 5056 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) { 5057 // If the dependent action is a device action, we will attempt to collapse 5058 // only with other device actions. Otherwise, we would do the same but 5059 // with host actions only. 5060 if (!IsHostSelector) { 5061 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) { 5062 CurAction = 5063 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true); 5064 if (CanBeCollapsed && 5065 !CurAction->isCollapsingWithNextDependentActionLegal()) 5066 return nullptr; 5067 SavedOffloadAction.push_back(OA); 5068 return dyn_cast<JobAction>(CurAction); 5069 } 5070 } else if (OA->hasHostDependence()) { 5071 CurAction = OA->getHostDependence(); 5072 if (CanBeCollapsed && 5073 !CurAction->isCollapsingWithNextDependentActionLegal()) 5074 return nullptr; 5075 SavedOffloadAction.push_back(OA); 5076 return dyn_cast<JobAction>(CurAction); 5077 } 5078 return nullptr; 5079 } 5080 5081 return dyn_cast<JobAction>(CurAction); 5082 } 5083 5084 /// Return true if an assemble action can be collapsed. 5085 bool canCollapseAssembleAction() const { 5086 return TC.useIntegratedAs() && !SaveTemps && 5087 !C.getArgs().hasArg(options::OPT_via_file_asm) && 5088 !C.getArgs().hasArg(options::OPT__SLASH_FA) && 5089 !C.getArgs().hasArg(options::OPT__SLASH_Fa) && 5090 !C.getArgs().hasArg(options::OPT_dxc_Fc); 5091 } 5092 5093 /// Return true if a preprocessor action can be collapsed. 5094 bool canCollapsePreprocessorAction() const { 5095 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) && 5096 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps && 5097 !C.getArgs().hasArg(options::OPT_rewrite_objc); 5098 } 5099 5100 /// Struct that relates an action with the offload actions that would be 5101 /// collapsed with it. 5102 struct JobActionInfo final { 5103 /// The action this info refers to. 5104 const JobAction *JA = nullptr; 5105 /// The offload actions we need to take care off if this action is 5106 /// collapsed. 5107 ActionList SavedOffloadAction; 5108 }; 5109 5110 /// Append collapsed offload actions from the give nnumber of elements in the 5111 /// action info array. 5112 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction, 5113 ArrayRef<JobActionInfo> &ActionInfo, 5114 unsigned ElementNum) { 5115 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements."); 5116 for (unsigned I = 0; I < ElementNum; ++I) 5117 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(), 5118 ActionInfo[I].SavedOffloadAction.end()); 5119 } 5120 5121 /// Functions that attempt to perform the combining. They detect if that is 5122 /// legal, and if so they update the inputs \a Inputs and the offload action 5123 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with 5124 /// the combined action is returned. If the combining is not legal or if the 5125 /// tool does not exist, null is returned. 5126 /// Currently three kinds of collapsing are supported: 5127 /// - Assemble + Backend + Compile; 5128 /// - Assemble + Backend ; 5129 /// - Backend + Compile. 5130 const Tool * 5131 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo, 5132 ActionList &Inputs, 5133 ActionList &CollapsedOffloadAction) { 5134 if (ActionInfo.size() < 3 || !canCollapseAssembleAction()) 5135 return nullptr; 5136 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA); 5137 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA); 5138 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA); 5139 if (!AJ || !BJ || !CJ) 5140 return nullptr; 5141 5142 // Get compiler tool. 5143 const Tool *T = TC.SelectTool(*CJ); 5144 if (!T) 5145 return nullptr; 5146 5147 // Can't collapse if we don't have codegen support unless we are 5148 // emitting LLVM IR. 5149 bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType()); 5150 if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR())) 5151 return nullptr; 5152 5153 // When using -fembed-bitcode, it is required to have the same tool (clang) 5154 // for both CompilerJA and BackendJA. Otherwise, combine two stages. 5155 if (EmbedBitcode) { 5156 const Tool *BT = TC.SelectTool(*BJ); 5157 if (BT == T) 5158 return nullptr; 5159 } 5160 5161 if (!T->hasIntegratedAssembler()) 5162 return nullptr; 5163 5164 Inputs = CJ->getInputs(); 5165 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, 5166 /*NumElements=*/3); 5167 return T; 5168 } 5169 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo, 5170 ActionList &Inputs, 5171 ActionList &CollapsedOffloadAction) { 5172 if (ActionInfo.size() < 2 || !canCollapseAssembleAction()) 5173 return nullptr; 5174 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA); 5175 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA); 5176 if (!AJ || !BJ) 5177 return nullptr; 5178 5179 // Get backend tool. 5180 const Tool *T = TC.SelectTool(*BJ); 5181 if (!T) 5182 return nullptr; 5183 5184 if (!T->hasIntegratedAssembler()) 5185 return nullptr; 5186 5187 Inputs = BJ->getInputs(); 5188 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, 5189 /*NumElements=*/2); 5190 return T; 5191 } 5192 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo, 5193 ActionList &Inputs, 5194 ActionList &CollapsedOffloadAction) { 5195 if (ActionInfo.size() < 2) 5196 return nullptr; 5197 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA); 5198 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA); 5199 if (!BJ || !CJ) 5200 return nullptr; 5201 5202 // Check if the initial input (to the compile job or its predessor if one 5203 // exists) is LLVM bitcode. In that case, no preprocessor step is required 5204 // and we can still collapse the compile and backend jobs when we have 5205 // -save-temps. I.e. there is no need for a separate compile job just to 5206 // emit unoptimized bitcode. 5207 bool InputIsBitcode = true; 5208 for (size_t i = 1; i < ActionInfo.size(); i++) 5209 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC && 5210 ActionInfo[i].JA->getType() != types::TY_LTO_BC) { 5211 InputIsBitcode = false; 5212 break; 5213 } 5214 if (!InputIsBitcode && !canCollapsePreprocessorAction()) 5215 return nullptr; 5216 5217 // Get compiler tool. 5218 const Tool *T = TC.SelectTool(*CJ); 5219 if (!T) 5220 return nullptr; 5221 5222 // Can't collapse if we don't have codegen support unless we are 5223 // emitting LLVM IR. 5224 bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType()); 5225 if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR())) 5226 return nullptr; 5227 5228 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode)) 5229 return nullptr; 5230 5231 Inputs = CJ->getInputs(); 5232 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, 5233 /*NumElements=*/2); 5234 return T; 5235 } 5236 5237 /// Updates the inputs if the obtained tool supports combining with 5238 /// preprocessor action, and the current input is indeed a preprocessor 5239 /// action. If combining results in the collapse of offloading actions, those 5240 /// are appended to \a CollapsedOffloadAction. 5241 void combineWithPreprocessor(const Tool *T, ActionList &Inputs, 5242 ActionList &CollapsedOffloadAction) { 5243 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP()) 5244 return; 5245 5246 // Attempt to get a preprocessor action dependence. 5247 ActionList PreprocessJobOffloadActions; 5248 ActionList NewInputs; 5249 for (Action *A : Inputs) { 5250 auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions); 5251 if (!PJ || !isa<PreprocessJobAction>(PJ)) { 5252 NewInputs.push_back(A); 5253 continue; 5254 } 5255 5256 // This is legal to combine. Append any offload action we found and add the 5257 // current input to preprocessor inputs. 5258 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(), 5259 PreprocessJobOffloadActions.end()); 5260 NewInputs.append(PJ->input_begin(), PJ->input_end()); 5261 } 5262 Inputs = NewInputs; 5263 } 5264 5265 public: 5266 ToolSelector(const JobAction *BaseAction, const ToolChain &TC, 5267 const Compilation &C, bool SaveTemps, bool EmbedBitcode) 5268 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps), 5269 EmbedBitcode(EmbedBitcode) { 5270 assert(BaseAction && "Invalid base action."); 5271 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None; 5272 } 5273 5274 /// Check if a chain of actions can be combined and return the tool that can 5275 /// handle the combination of actions. The pointer to the current inputs \a 5276 /// Inputs and the list of offload actions \a CollapsedOffloadActions 5277 /// connected to collapsed actions are updated accordingly. The latter enables 5278 /// the caller of the selector to process them afterwards instead of just 5279 /// dropping them. If no suitable tool is found, null will be returned. 5280 const Tool *getTool(ActionList &Inputs, 5281 ActionList &CollapsedOffloadAction) { 5282 // 5283 // Get the largest chain of actions that we could combine. 5284 // 5285 5286 SmallVector<JobActionInfo, 5> ActionChain(1); 5287 ActionChain.back().JA = BaseAction; 5288 while (ActionChain.back().JA) { 5289 const Action *CurAction = ActionChain.back().JA; 5290 5291 // Grow the chain by one element. 5292 ActionChain.resize(ActionChain.size() + 1); 5293 JobActionInfo &AI = ActionChain.back(); 5294 5295 // Attempt to fill it with the 5296 AI.JA = 5297 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction); 5298 } 5299 5300 // Pop the last action info as it could not be filled. 5301 ActionChain.pop_back(); 5302 5303 // 5304 // Attempt to combine actions. If all combining attempts failed, just return 5305 // the tool of the provided action. At the end we attempt to combine the 5306 // action with any preprocessor action it may depend on. 5307 // 5308 5309 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs, 5310 CollapsedOffloadAction); 5311 if (!T) 5312 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction); 5313 if (!T) 5314 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction); 5315 if (!T) { 5316 Inputs = BaseAction->getInputs(); 5317 T = TC.SelectTool(*BaseAction); 5318 } 5319 5320 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction); 5321 return T; 5322 } 5323 }; 5324 } 5325 5326 /// Return a string that uniquely identifies the result of a job. The bound arch 5327 /// is not necessarily represented in the toolchain's triple -- for example, 5328 /// armv7 and armv7s both map to the same triple -- so we need both in our map. 5329 /// Also, we need to add the offloading device kind, as the same tool chain can 5330 /// be used for host and device for some programming models, e.g. OpenMP. 5331 static std::string GetTriplePlusArchString(const ToolChain *TC, 5332 StringRef BoundArch, 5333 Action::OffloadKind OffloadKind) { 5334 std::string TriplePlusArch = TC->getTriple().normalize(); 5335 if (!BoundArch.empty()) { 5336 TriplePlusArch += "-"; 5337 TriplePlusArch += BoundArch; 5338 } 5339 TriplePlusArch += "-"; 5340 TriplePlusArch += Action::GetOffloadKindName(OffloadKind); 5341 return TriplePlusArch; 5342 } 5343 5344 InputInfoList Driver::BuildJobsForAction( 5345 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch, 5346 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 5347 std::map<std::pair<const Action *, std::string>, InputInfoList> 5348 &CachedResults, 5349 Action::OffloadKind TargetDeviceOffloadKind) const { 5350 std::pair<const Action *, std::string> ActionTC = { 5351 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)}; 5352 auto CachedResult = CachedResults.find(ActionTC); 5353 if (CachedResult != CachedResults.end()) { 5354 return CachedResult->second; 5355 } 5356 InputInfoList Result = BuildJobsForActionNoCache( 5357 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput, 5358 CachedResults, TargetDeviceOffloadKind); 5359 CachedResults[ActionTC] = Result; 5360 return Result; 5361 } 5362 5363 static void handleTimeTrace(Compilation &C, const ArgList &Args, 5364 const JobAction *JA, const char *BaseInput, 5365 const InputInfo &Result) { 5366 Arg *A = 5367 Args.getLastArg(options::OPT_ftime_trace, options::OPT_ftime_trace_EQ); 5368 if (!A) 5369 return; 5370 SmallString<128> Path; 5371 if (A->getOption().matches(options::OPT_ftime_trace_EQ)) { 5372 Path = A->getValue(); 5373 if (llvm::sys::fs::is_directory(Path)) { 5374 SmallString<128> Tmp(Result.getFilename()); 5375 llvm::sys::path::replace_extension(Tmp, "json"); 5376 llvm::sys::path::append(Path, llvm::sys::path::filename(Tmp)); 5377 } 5378 } else { 5379 if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) { 5380 // The trace file is ${dumpdir}${basename}.json. Note that dumpdir may not 5381 // end with a path separator. 5382 Path = DumpDir->getValue(); 5383 Path += llvm::sys::path::filename(BaseInput); 5384 } else { 5385 Path = Result.getFilename(); 5386 } 5387 llvm::sys::path::replace_extension(Path, "json"); 5388 } 5389 const char *ResultFile = C.getArgs().MakeArgString(Path); 5390 C.addTimeTraceFile(ResultFile, JA); 5391 C.addResultFile(ResultFile, JA); 5392 } 5393 5394 InputInfoList Driver::BuildJobsForActionNoCache( 5395 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch, 5396 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 5397 std::map<std::pair<const Action *, std::string>, InputInfoList> 5398 &CachedResults, 5399 Action::OffloadKind TargetDeviceOffloadKind) const { 5400 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 5401 5402 InputInfoList OffloadDependencesInputInfo; 5403 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None; 5404 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) { 5405 // The 'Darwin' toolchain is initialized only when its arguments are 5406 // computed. Get the default arguments for OFK_None to ensure that 5407 // initialization is performed before processing the offload action. 5408 // FIXME: Remove when darwin's toolchain is initialized during construction. 5409 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None); 5410 5411 // The offload action is expected to be used in four different situations. 5412 // 5413 // a) Set a toolchain/architecture/kind for a host action: 5414 // Host Action 1 -> OffloadAction -> Host Action 2 5415 // 5416 // b) Set a toolchain/architecture/kind for a device action; 5417 // Device Action 1 -> OffloadAction -> Device Action 2 5418 // 5419 // c) Specify a device dependence to a host action; 5420 // Device Action 1 _ 5421 // \ 5422 // Host Action 1 ---> OffloadAction -> Host Action 2 5423 // 5424 // d) Specify a host dependence to a device action. 5425 // Host Action 1 _ 5426 // \ 5427 // Device Action 1 ---> OffloadAction -> Device Action 2 5428 // 5429 // For a) and b), we just return the job generated for the dependences. For 5430 // c) and d) we override the current action with the host/device dependence 5431 // if the current toolchain is host/device and set the offload dependences 5432 // info with the jobs obtained from the device/host dependence(s). 5433 5434 // If there is a single device option or has no host action, just generate 5435 // the job for it. 5436 if (OA->hasSingleDeviceDependence() || !OA->hasHostDependence()) { 5437 InputInfoList DevA; 5438 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC, 5439 const char *DepBoundArch) { 5440 DevA.append(BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel, 5441 /*MultipleArchs*/ !!DepBoundArch, 5442 LinkingOutput, CachedResults, 5443 DepA->getOffloadingDeviceKind())); 5444 }); 5445 return DevA; 5446 } 5447 5448 // If 'Action 2' is host, we generate jobs for the device dependences and 5449 // override the current action with the host dependence. Otherwise, we 5450 // generate the host dependences and override the action with the device 5451 // dependence. The dependences can't therefore be a top-level action. 5452 OA->doOnEachDependence( 5453 /*IsHostDependence=*/BuildingForOffloadDevice, 5454 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { 5455 OffloadDependencesInputInfo.append(BuildJobsForAction( 5456 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false, 5457 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults, 5458 DepA->getOffloadingDeviceKind())); 5459 }); 5460 5461 A = BuildingForOffloadDevice 5462 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true) 5463 : OA->getHostDependence(); 5464 5465 // We may have already built this action as a part of the offloading 5466 // toolchain, return the cached input if so. 5467 std::pair<const Action *, std::string> ActionTC = { 5468 OA->getHostDependence(), 5469 GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)}; 5470 if (CachedResults.find(ActionTC) != CachedResults.end()) { 5471 InputInfoList Inputs = CachedResults[ActionTC]; 5472 Inputs.append(OffloadDependencesInputInfo); 5473 return Inputs; 5474 } 5475 } 5476 5477 if (const InputAction *IA = dyn_cast<InputAction>(A)) { 5478 // FIXME: It would be nice to not claim this here; maybe the old scheme of 5479 // just using Args was better? 5480 const Arg &Input = IA->getInputArg(); 5481 Input.claim(); 5482 if (Input.getOption().matches(options::OPT_INPUT)) { 5483 const char *Name = Input.getValue(); 5484 return {InputInfo(A, Name, /* _BaseInput = */ Name)}; 5485 } 5486 return {InputInfo(A, &Input, /* _BaseInput = */ "")}; 5487 } 5488 5489 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) { 5490 const ToolChain *TC; 5491 StringRef ArchName = BAA->getArchName(); 5492 5493 if (!ArchName.empty()) 5494 TC = &getToolChain(C.getArgs(), 5495 computeTargetTriple(*this, TargetTriple, 5496 C.getArgs(), ArchName)); 5497 else 5498 TC = &C.getDefaultToolChain(); 5499 5500 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel, 5501 MultipleArchs, LinkingOutput, CachedResults, 5502 TargetDeviceOffloadKind); 5503 } 5504 5505 5506 ActionList Inputs = A->getInputs(); 5507 5508 const JobAction *JA = cast<JobAction>(A); 5509 ActionList CollapsedOffloadActions; 5510 5511 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(), 5512 embedBitcodeInObject() && !isUsingLTO()); 5513 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions); 5514 5515 if (!T) 5516 return {InputInfo()}; 5517 5518 // If we've collapsed action list that contained OffloadAction we 5519 // need to build jobs for host/device-side inputs it may have held. 5520 for (const auto *OA : CollapsedOffloadActions) 5521 cast<OffloadAction>(OA)->doOnEachDependence( 5522 /*IsHostDependence=*/BuildingForOffloadDevice, 5523 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { 5524 OffloadDependencesInputInfo.append(BuildJobsForAction( 5525 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false, 5526 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults, 5527 DepA->getOffloadingDeviceKind())); 5528 }); 5529 5530 // Only use pipes when there is exactly one input. 5531 InputInfoList InputInfos; 5532 for (const Action *Input : Inputs) { 5533 // Treat dsymutil and verify sub-jobs as being at the top-level too, they 5534 // shouldn't get temporary output names. 5535 // FIXME: Clean this up. 5536 bool SubJobAtTopLevel = 5537 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A)); 5538 InputInfos.append(BuildJobsForAction( 5539 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput, 5540 CachedResults, A->getOffloadingDeviceKind())); 5541 } 5542 5543 // Always use the first file input as the base input. 5544 const char *BaseInput = InputInfos[0].getBaseInput(); 5545 for (auto &Info : InputInfos) { 5546 if (Info.isFilename()) { 5547 BaseInput = Info.getBaseInput(); 5548 break; 5549 } 5550 } 5551 5552 // ... except dsymutil actions, which use their actual input as the base 5553 // input. 5554 if (JA->getType() == types::TY_dSYM) 5555 BaseInput = InputInfos[0].getFilename(); 5556 5557 // Append outputs of offload device jobs to the input list 5558 if (!OffloadDependencesInputInfo.empty()) 5559 InputInfos.append(OffloadDependencesInputInfo.begin(), 5560 OffloadDependencesInputInfo.end()); 5561 5562 // Set the effective triple of the toolchain for the duration of this job. 5563 llvm::Triple EffectiveTriple; 5564 const ToolChain &ToolTC = T->getToolChain(); 5565 const ArgList &Args = 5566 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind()); 5567 if (InputInfos.size() != 1) { 5568 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args)); 5569 } else { 5570 // Pass along the input type if it can be unambiguously determined. 5571 EffectiveTriple = llvm::Triple( 5572 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType())); 5573 } 5574 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple); 5575 5576 // Determine the place to write output to, if any. 5577 InputInfo Result; 5578 InputInfoList UnbundlingResults; 5579 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) { 5580 // If we have an unbundling job, we need to create results for all the 5581 // outputs. We also update the results cache so that other actions using 5582 // this unbundling action can get the right results. 5583 for (auto &UI : UA->getDependentActionsInfo()) { 5584 assert(UI.DependentOffloadKind != Action::OFK_None && 5585 "Unbundling with no offloading??"); 5586 5587 // Unbundling actions are never at the top level. When we generate the 5588 // offloading prefix, we also do that for the host file because the 5589 // unbundling action does not change the type of the output which can 5590 // cause a overwrite. 5591 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix( 5592 UI.DependentOffloadKind, 5593 UI.DependentToolChain->getTriple().normalize(), 5594 /*CreatePrefixForHost=*/true); 5595 auto CurI = InputInfo( 5596 UA, 5597 GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch, 5598 /*AtTopLevel=*/false, 5599 MultipleArchs || 5600 UI.DependentOffloadKind == Action::OFK_HIP, 5601 OffloadingPrefix), 5602 BaseInput); 5603 // Save the unbundling result. 5604 UnbundlingResults.push_back(CurI); 5605 5606 // Get the unique string identifier for this dependence and cache the 5607 // result. 5608 StringRef Arch; 5609 if (TargetDeviceOffloadKind == Action::OFK_HIP) { 5610 if (UI.DependentOffloadKind == Action::OFK_Host) 5611 Arch = StringRef(); 5612 else 5613 Arch = UI.DependentBoundArch; 5614 } else 5615 Arch = BoundArch; 5616 5617 CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch, 5618 UI.DependentOffloadKind)}] = { 5619 CurI}; 5620 } 5621 5622 // Now that we have all the results generated, select the one that should be 5623 // returned for the current depending action. 5624 std::pair<const Action *, std::string> ActionTC = { 5625 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)}; 5626 assert(CachedResults.find(ActionTC) != CachedResults.end() && 5627 "Result does not exist??"); 5628 Result = CachedResults[ActionTC].front(); 5629 } else if (JA->getType() == types::TY_Nothing) 5630 Result = {InputInfo(A, BaseInput)}; 5631 else { 5632 // We only have to generate a prefix for the host if this is not a top-level 5633 // action. 5634 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix( 5635 A->getOffloadingDeviceKind(), TC->getTriple().normalize(), 5636 /*CreatePrefixForHost=*/isa<OffloadPackagerJobAction>(A) || 5637 !(A->getOffloadingHostActiveKinds() == Action::OFK_None || 5638 AtTopLevel)); 5639 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch, 5640 AtTopLevel, MultipleArchs, 5641 OffloadingPrefix), 5642 BaseInput); 5643 if (T->canEmitIR() && OffloadingPrefix.empty()) 5644 handleTimeTrace(C, Args, JA, BaseInput, Result); 5645 } 5646 5647 if (CCCPrintBindings && !CCGenDiagnostics) { 5648 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"' 5649 << " - \"" << T->getName() << "\", inputs: ["; 5650 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) { 5651 llvm::errs() << InputInfos[i].getAsString(); 5652 if (i + 1 != e) 5653 llvm::errs() << ", "; 5654 } 5655 if (UnbundlingResults.empty()) 5656 llvm::errs() << "], output: " << Result.getAsString() << "\n"; 5657 else { 5658 llvm::errs() << "], outputs: ["; 5659 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) { 5660 llvm::errs() << UnbundlingResults[i].getAsString(); 5661 if (i + 1 != e) 5662 llvm::errs() << ", "; 5663 } 5664 llvm::errs() << "] \n"; 5665 } 5666 } else { 5667 if (UnbundlingResults.empty()) 5668 T->ConstructJob( 5669 C, *JA, Result, InputInfos, 5670 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()), 5671 LinkingOutput); 5672 else 5673 T->ConstructJobMultipleOutputs( 5674 C, *JA, UnbundlingResults, InputInfos, 5675 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()), 5676 LinkingOutput); 5677 } 5678 return {Result}; 5679 } 5680 5681 const char *Driver::getDefaultImageName() const { 5682 llvm::Triple Target(llvm::Triple::normalize(TargetTriple)); 5683 return Target.isOSWindows() ? "a.exe" : "a.out"; 5684 } 5685 5686 /// Create output filename based on ArgValue, which could either be a 5687 /// full filename, filename without extension, or a directory. If ArgValue 5688 /// does not provide a filename, then use BaseName, and use the extension 5689 /// suitable for FileType. 5690 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue, 5691 StringRef BaseName, 5692 types::ID FileType) { 5693 SmallString<128> Filename = ArgValue; 5694 5695 if (ArgValue.empty()) { 5696 // If the argument is empty, output to BaseName in the current dir. 5697 Filename = BaseName; 5698 } else if (llvm::sys::path::is_separator(Filename.back())) { 5699 // If the argument is a directory, output to BaseName in that dir. 5700 llvm::sys::path::append(Filename, BaseName); 5701 } 5702 5703 if (!llvm::sys::path::has_extension(ArgValue)) { 5704 // If the argument didn't provide an extension, then set it. 5705 const char *Extension = types::getTypeTempSuffix(FileType, true); 5706 5707 if (FileType == types::TY_Image && 5708 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) { 5709 // The output file is a dll. 5710 Extension = "dll"; 5711 } 5712 5713 llvm::sys::path::replace_extension(Filename, Extension); 5714 } 5715 5716 return Args.MakeArgString(Filename.c_str()); 5717 } 5718 5719 static bool HasPreprocessOutput(const Action &JA) { 5720 if (isa<PreprocessJobAction>(JA)) 5721 return true; 5722 if (isa<OffloadAction>(JA) && isa<PreprocessJobAction>(JA.getInputs()[0])) 5723 return true; 5724 if (isa<OffloadBundlingJobAction>(JA) && 5725 HasPreprocessOutput(*(JA.getInputs()[0]))) 5726 return true; 5727 return false; 5728 } 5729 5730 const char *Driver::CreateTempFile(Compilation &C, StringRef Prefix, 5731 StringRef Suffix, bool MultipleArchs, 5732 StringRef BoundArch, 5733 bool NeedUniqueDirectory) const { 5734 SmallString<128> TmpName; 5735 Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir); 5736 std::optional<std::string> CrashDirectory = 5737 CCGenDiagnostics && A 5738 ? std::string(A->getValue()) 5739 : llvm::sys::Process::GetEnv("CLANG_CRASH_DIAGNOSTICS_DIR"); 5740 if (CrashDirectory) { 5741 if (!getVFS().exists(*CrashDirectory)) 5742 llvm::sys::fs::create_directories(*CrashDirectory); 5743 SmallString<128> Path(*CrashDirectory); 5744 llvm::sys::path::append(Path, Prefix); 5745 const char *Middle = !Suffix.empty() ? "-%%%%%%." : "-%%%%%%"; 5746 if (std::error_code EC = 5747 llvm::sys::fs::createUniqueFile(Path + Middle + Suffix, TmpName)) { 5748 Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 5749 return ""; 5750 } 5751 } else { 5752 if (MultipleArchs && !BoundArch.empty()) { 5753 if (NeedUniqueDirectory) { 5754 TmpName = GetTemporaryDirectory(Prefix); 5755 llvm::sys::path::append(TmpName, 5756 Twine(Prefix) + "-" + BoundArch + "." + Suffix); 5757 } else { 5758 TmpName = 5759 GetTemporaryPath((Twine(Prefix) + "-" + BoundArch).str(), Suffix); 5760 } 5761 5762 } else { 5763 TmpName = GetTemporaryPath(Prefix, Suffix); 5764 } 5765 } 5766 return C.addTempFile(C.getArgs().MakeArgString(TmpName)); 5767 } 5768 5769 // Calculate the output path of the module file when compiling a module unit 5770 // with the `-fmodule-output` option or `-fmodule-output=` option specified. 5771 // The behavior is: 5772 // - If `-fmodule-output=` is specfied, then the module file is 5773 // writing to the value. 5774 // - Otherwise if the output object file of the module unit is specified, the 5775 // output path 5776 // of the module file should be the same with the output object file except 5777 // the corresponding suffix. This requires both `-o` and `-c` are specified. 5778 // - Otherwise, the output path of the module file will be the same with the 5779 // input with the corresponding suffix. 5780 static const char *GetModuleOutputPath(Compilation &C, const JobAction &JA, 5781 const char *BaseInput) { 5782 assert(isa<PrecompileJobAction>(JA) && JA.getType() == types::TY_ModuleFile && 5783 (C.getArgs().hasArg(options::OPT_fmodule_output) || 5784 C.getArgs().hasArg(options::OPT_fmodule_output_EQ))); 5785 5786 if (Arg *ModuleOutputEQ = 5787 C.getArgs().getLastArg(options::OPT_fmodule_output_EQ)) 5788 return C.addResultFile(ModuleOutputEQ->getValue(), &JA); 5789 5790 SmallString<64> OutputPath; 5791 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 5792 if (FinalOutput && C.getArgs().hasArg(options::OPT_c)) 5793 OutputPath = FinalOutput->getValue(); 5794 else 5795 OutputPath = BaseInput; 5796 5797 const char *Extension = types::getTypeTempSuffix(JA.getType()); 5798 llvm::sys::path::replace_extension(OutputPath, Extension); 5799 return C.addResultFile(C.getArgs().MakeArgString(OutputPath.c_str()), &JA); 5800 } 5801 5802 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA, 5803 const char *BaseInput, 5804 StringRef OrigBoundArch, bool AtTopLevel, 5805 bool MultipleArchs, 5806 StringRef OffloadingPrefix) const { 5807 std::string BoundArch = OrigBoundArch.str(); 5808 if (is_style_windows(llvm::sys::path::Style::native)) { 5809 // BoundArch may contains ':', which is invalid in file names on Windows, 5810 // therefore replace it with '%'. 5811 std::replace(BoundArch.begin(), BoundArch.end(), ':', '@'); 5812 } 5813 5814 llvm::PrettyStackTraceString CrashInfo("Computing output path"); 5815 // Output to a user requested destination? 5816 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) { 5817 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) 5818 return C.addResultFile(FinalOutput->getValue(), &JA); 5819 } 5820 5821 // For /P, preprocess to file named after BaseInput. 5822 if (C.getArgs().hasArg(options::OPT__SLASH_P)) { 5823 assert(AtTopLevel && isa<PreprocessJobAction>(JA)); 5824 StringRef BaseName = llvm::sys::path::filename(BaseInput); 5825 StringRef NameArg; 5826 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi)) 5827 NameArg = A->getValue(); 5828 return C.addResultFile( 5829 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C), 5830 &JA); 5831 } 5832 5833 // Default to writing to stdout? 5834 if (AtTopLevel && !CCGenDiagnostics && HasPreprocessOutput(JA)) { 5835 return "-"; 5836 } 5837 5838 if (JA.getType() == types::TY_ModuleFile && 5839 C.getArgs().getLastArg(options::OPT_module_file_info)) { 5840 return "-"; 5841 } 5842 5843 if (JA.getType() == types::TY_PP_Asm && 5844 C.getArgs().hasArg(options::OPT_dxc_Fc)) { 5845 StringRef FcValue = C.getArgs().getLastArgValue(options::OPT_dxc_Fc); 5846 // TODO: Should we use `MakeCLOutputFilename` here? If so, we can probably 5847 // handle this as part of the SLASH_Fa handling below. 5848 return C.addResultFile(C.getArgs().MakeArgString(FcValue.str()), &JA); 5849 } 5850 5851 if (JA.getType() == types::TY_Object && 5852 C.getArgs().hasArg(options::OPT_dxc_Fo)) { 5853 StringRef FoValue = C.getArgs().getLastArgValue(options::OPT_dxc_Fo); 5854 // TODO: Should we use `MakeCLOutputFilename` here? If so, we can probably 5855 // handle this as part of the SLASH_Fo handling below. 5856 return C.addResultFile(C.getArgs().MakeArgString(FoValue.str()), &JA); 5857 } 5858 5859 // Is this the assembly listing for /FA? 5860 if (JA.getType() == types::TY_PP_Asm && 5861 (C.getArgs().hasArg(options::OPT__SLASH_FA) || 5862 C.getArgs().hasArg(options::OPT__SLASH_Fa))) { 5863 // Use /Fa and the input filename to determine the asm file name. 5864 StringRef BaseName = llvm::sys::path::filename(BaseInput); 5865 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa); 5866 return C.addResultFile( 5867 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()), 5868 &JA); 5869 } 5870 5871 // DXC defaults to standard out when generating assembly. We check this after 5872 // any DXC flags that might specify a file. 5873 if (AtTopLevel && JA.getType() == types::TY_PP_Asm && IsDXCMode()) 5874 return "-"; 5875 5876 bool SpecifiedModuleOutput = 5877 C.getArgs().hasArg(options::OPT_fmodule_output) || 5878 C.getArgs().hasArg(options::OPT_fmodule_output_EQ); 5879 if (MultipleArchs && SpecifiedModuleOutput) 5880 Diag(clang::diag::err_drv_module_output_with_multiple_arch); 5881 5882 // If we're emitting a module output with the specified option 5883 // `-fmodule-output`. 5884 if (!AtTopLevel && isa<PrecompileJobAction>(JA) && 5885 JA.getType() == types::TY_ModuleFile && SpecifiedModuleOutput) 5886 return GetModuleOutputPath(C, JA, BaseInput); 5887 5888 // Output to a temporary file? 5889 if ((!AtTopLevel && !isSaveTempsEnabled() && 5890 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) || 5891 CCGenDiagnostics) { 5892 StringRef Name = llvm::sys::path::filename(BaseInput); 5893 std::pair<StringRef, StringRef> Split = Name.split('.'); 5894 const char *Suffix = 5895 types::getTypeTempSuffix(JA.getType(), IsCLMode() || IsDXCMode()); 5896 // The non-offloading toolchain on Darwin requires deterministic input 5897 // file name for binaries to be deterministic, therefore it needs unique 5898 // directory. 5899 llvm::Triple Triple(C.getDriver().getTargetTriple()); 5900 bool NeedUniqueDirectory = 5901 (JA.getOffloadingDeviceKind() == Action::OFK_None || 5902 JA.getOffloadingDeviceKind() == Action::OFK_Host) && 5903 Triple.isOSDarwin(); 5904 return CreateTempFile(C, Split.first, Suffix, MultipleArchs, BoundArch, 5905 NeedUniqueDirectory); 5906 } 5907 5908 SmallString<128> BasePath(BaseInput); 5909 SmallString<128> ExternalPath(""); 5910 StringRef BaseName; 5911 5912 // Dsymutil actions should use the full path. 5913 if (isa<DsymutilJobAction>(JA) && C.getArgs().hasArg(options::OPT_dsym_dir)) { 5914 ExternalPath += C.getArgs().getLastArg(options::OPT_dsym_dir)->getValue(); 5915 // We use posix style here because the tests (specifically 5916 // darwin-dsymutil.c) demonstrate that posix style paths are acceptable 5917 // even on Windows and if we don't then the similar test covering this 5918 // fails. 5919 llvm::sys::path::append(ExternalPath, llvm::sys::path::Style::posix, 5920 llvm::sys::path::filename(BasePath)); 5921 BaseName = ExternalPath; 5922 } else if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA)) 5923 BaseName = BasePath; 5924 else 5925 BaseName = llvm::sys::path::filename(BasePath); 5926 5927 // Determine what the derived output name should be. 5928 const char *NamedOutput; 5929 5930 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) && 5931 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) { 5932 // The /Fo or /o flag decides the object filename. 5933 StringRef Val = 5934 C.getArgs() 5935 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o) 5936 ->getValue(); 5937 NamedOutput = 5938 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object); 5939 } else if (JA.getType() == types::TY_Image && 5940 C.getArgs().hasArg(options::OPT__SLASH_Fe, 5941 options::OPT__SLASH_o)) { 5942 // The /Fe or /o flag names the linked file. 5943 StringRef Val = 5944 C.getArgs() 5945 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o) 5946 ->getValue(); 5947 NamedOutput = 5948 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image); 5949 } else if (JA.getType() == types::TY_Image) { 5950 if (IsCLMode()) { 5951 // clang-cl uses BaseName for the executable name. 5952 NamedOutput = 5953 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image); 5954 } else { 5955 SmallString<128> Output(getDefaultImageName()); 5956 // HIP image for device compilation with -fno-gpu-rdc is per compilation 5957 // unit. 5958 bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP && 5959 !C.getArgs().hasFlag(options::OPT_fgpu_rdc, 5960 options::OPT_fno_gpu_rdc, false); 5961 bool UseOutExtension = IsHIPNoRDC || isa<OffloadPackagerJobAction>(JA); 5962 if (UseOutExtension) { 5963 Output = BaseName; 5964 llvm::sys::path::replace_extension(Output, ""); 5965 } 5966 Output += OffloadingPrefix; 5967 if (MultipleArchs && !BoundArch.empty()) { 5968 Output += "-"; 5969 Output.append(BoundArch); 5970 } 5971 if (UseOutExtension) 5972 Output += ".out"; 5973 NamedOutput = C.getArgs().MakeArgString(Output.c_str()); 5974 } 5975 } else if (JA.getType() == types::TY_PCH && IsCLMode()) { 5976 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName)); 5977 } else if ((JA.getType() == types::TY_Plist || JA.getType() == types::TY_AST) && 5978 C.getArgs().hasArg(options::OPT__SLASH_o)) { 5979 StringRef Val = 5980 C.getArgs() 5981 .getLastArg(options::OPT__SLASH_o) 5982 ->getValue(); 5983 NamedOutput = 5984 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object); 5985 } else { 5986 const char *Suffix = 5987 types::getTypeTempSuffix(JA.getType(), IsCLMode() || IsDXCMode()); 5988 assert(Suffix && "All types used for output should have a suffix."); 5989 5990 std::string::size_type End = std::string::npos; 5991 if (!types::appendSuffixForType(JA.getType())) 5992 End = BaseName.rfind('.'); 5993 SmallString<128> Suffixed(BaseName.substr(0, End)); 5994 Suffixed += OffloadingPrefix; 5995 if (MultipleArchs && !BoundArch.empty()) { 5996 Suffixed += "-"; 5997 Suffixed.append(BoundArch); 5998 } 5999 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for 6000 // the unoptimized bitcode so that it does not get overwritten by the ".bc" 6001 // optimized bitcode output. 6002 auto IsAMDRDCInCompilePhase = [](const JobAction &JA, 6003 const llvm::opt::DerivedArgList &Args) { 6004 // The relocatable compilation in HIP and OpenMP implies -emit-llvm. 6005 // Similarly, use a ".tmp.bc" suffix for the unoptimized bitcode 6006 // (generated in the compile phase.) 6007 const ToolChain *TC = JA.getOffloadingToolChain(); 6008 return isa<CompileJobAction>(JA) && 6009 ((JA.getOffloadingDeviceKind() == Action::OFK_HIP && 6010 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, 6011 false)) || 6012 (JA.getOffloadingDeviceKind() == Action::OFK_OpenMP && TC && 6013 TC->getTriple().isAMDGPU())); 6014 }; 6015 if (!AtTopLevel && JA.getType() == types::TY_LLVM_BC && 6016 (C.getArgs().hasArg(options::OPT_emit_llvm) || 6017 IsAMDRDCInCompilePhase(JA, C.getArgs()))) 6018 Suffixed += ".tmp"; 6019 Suffixed += '.'; 6020 Suffixed += Suffix; 6021 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str()); 6022 } 6023 6024 // Prepend object file path if -save-temps=obj 6025 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) && 6026 JA.getType() != types::TY_PCH) { 6027 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 6028 SmallString<128> TempPath(FinalOutput->getValue()); 6029 llvm::sys::path::remove_filename(TempPath); 6030 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput); 6031 llvm::sys::path::append(TempPath, OutputFileName); 6032 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str()); 6033 } 6034 6035 // If we're saving temps and the temp file conflicts with the input file, 6036 // then avoid overwriting input file. 6037 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) { 6038 bool SameFile = false; 6039 SmallString<256> Result; 6040 llvm::sys::fs::current_path(Result); 6041 llvm::sys::path::append(Result, BaseName); 6042 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile); 6043 // Must share the same path to conflict. 6044 if (SameFile) { 6045 StringRef Name = llvm::sys::path::filename(BaseInput); 6046 std::pair<StringRef, StringRef> Split = Name.split('.'); 6047 std::string TmpName = GetTemporaryPath( 6048 Split.first, 6049 types::getTypeTempSuffix(JA.getType(), IsCLMode() || IsDXCMode())); 6050 return C.addTempFile(C.getArgs().MakeArgString(TmpName)); 6051 } 6052 } 6053 6054 // As an annoying special case, PCH generation doesn't strip the pathname. 6055 if (JA.getType() == types::TY_PCH && !IsCLMode()) { 6056 llvm::sys::path::remove_filename(BasePath); 6057 if (BasePath.empty()) 6058 BasePath = NamedOutput; 6059 else 6060 llvm::sys::path::append(BasePath, NamedOutput); 6061 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA); 6062 } 6063 6064 return C.addResultFile(NamedOutput, &JA); 6065 } 6066 6067 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const { 6068 // Search for Name in a list of paths. 6069 auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P) 6070 -> std::optional<std::string> { 6071 // Respect a limited subset of the '-Bprefix' functionality in GCC by 6072 // attempting to use this prefix when looking for file paths. 6073 for (const auto &Dir : P) { 6074 if (Dir.empty()) 6075 continue; 6076 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir); 6077 llvm::sys::path::append(P, Name); 6078 if (llvm::sys::fs::exists(Twine(P))) 6079 return std::string(P); 6080 } 6081 return std::nullopt; 6082 }; 6083 6084 if (auto P = SearchPaths(PrefixDirs)) 6085 return *P; 6086 6087 SmallString<128> R(ResourceDir); 6088 llvm::sys::path::append(R, Name); 6089 if (llvm::sys::fs::exists(Twine(R))) 6090 return std::string(R); 6091 6092 SmallString<128> P(TC.getCompilerRTPath()); 6093 llvm::sys::path::append(P, Name); 6094 if (llvm::sys::fs::exists(Twine(P))) 6095 return std::string(P); 6096 6097 SmallString<128> D(Dir); 6098 llvm::sys::path::append(D, "..", Name); 6099 if (llvm::sys::fs::exists(Twine(D))) 6100 return std::string(D); 6101 6102 if (auto P = SearchPaths(TC.getLibraryPaths())) 6103 return *P; 6104 6105 if (auto P = SearchPaths(TC.getFilePaths())) 6106 return *P; 6107 6108 return std::string(Name); 6109 } 6110 6111 void Driver::generatePrefixedToolNames( 6112 StringRef Tool, const ToolChain &TC, 6113 SmallVectorImpl<std::string> &Names) const { 6114 // FIXME: Needs a better variable than TargetTriple 6115 Names.emplace_back((TargetTriple + "-" + Tool).str()); 6116 Names.emplace_back(Tool); 6117 } 6118 6119 static bool ScanDirForExecutable(SmallString<128> &Dir, StringRef Name) { 6120 llvm::sys::path::append(Dir, Name); 6121 if (llvm::sys::fs::can_execute(Twine(Dir))) 6122 return true; 6123 llvm::sys::path::remove_filename(Dir); 6124 return false; 6125 } 6126 6127 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const { 6128 SmallVector<std::string, 2> TargetSpecificExecutables; 6129 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables); 6130 6131 // Respect a limited subset of the '-Bprefix' functionality in GCC by 6132 // attempting to use this prefix when looking for program paths. 6133 for (const auto &PrefixDir : PrefixDirs) { 6134 if (llvm::sys::fs::is_directory(PrefixDir)) { 6135 SmallString<128> P(PrefixDir); 6136 if (ScanDirForExecutable(P, Name)) 6137 return std::string(P); 6138 } else { 6139 SmallString<128> P((PrefixDir + Name).str()); 6140 if (llvm::sys::fs::can_execute(Twine(P))) 6141 return std::string(P); 6142 } 6143 } 6144 6145 const ToolChain::path_list &List = TC.getProgramPaths(); 6146 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) { 6147 // For each possible name of the tool look for it in 6148 // program paths first, then the path. 6149 // Higher priority names will be first, meaning that 6150 // a higher priority name in the path will be found 6151 // instead of a lower priority name in the program path. 6152 // E.g. <triple>-gcc on the path will be found instead 6153 // of gcc in the program path 6154 for (const auto &Path : List) { 6155 SmallString<128> P(Path); 6156 if (ScanDirForExecutable(P, TargetSpecificExecutable)) 6157 return std::string(P); 6158 } 6159 6160 // Fall back to the path 6161 if (llvm::ErrorOr<std::string> P = 6162 llvm::sys::findProgramByName(TargetSpecificExecutable)) 6163 return *P; 6164 } 6165 6166 return std::string(Name); 6167 } 6168 6169 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const { 6170 SmallString<128> Path; 6171 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path); 6172 if (EC) { 6173 Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 6174 return ""; 6175 } 6176 6177 return std::string(Path); 6178 } 6179 6180 std::string Driver::GetTemporaryDirectory(StringRef Prefix) const { 6181 SmallString<128> Path; 6182 std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path); 6183 if (EC) { 6184 Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 6185 return ""; 6186 } 6187 6188 return std::string(Path); 6189 } 6190 6191 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const { 6192 SmallString<128> Output; 6193 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) { 6194 // FIXME: If anybody needs it, implement this obscure rule: 6195 // "If you specify a directory without a file name, the default file name 6196 // is VCx0.pch., where x is the major version of Visual C++ in use." 6197 Output = FpArg->getValue(); 6198 6199 // "If you do not specify an extension as part of the path name, an 6200 // extension of .pch is assumed. " 6201 if (!llvm::sys::path::has_extension(Output)) 6202 Output += ".pch"; 6203 } else { 6204 if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc)) 6205 Output = YcArg->getValue(); 6206 if (Output.empty()) 6207 Output = BaseName; 6208 llvm::sys::path::replace_extension(Output, ".pch"); 6209 } 6210 return std::string(Output); 6211 } 6212 6213 const ToolChain &Driver::getToolChain(const ArgList &Args, 6214 const llvm::Triple &Target) const { 6215 6216 auto &TC = ToolChains[Target.str()]; 6217 if (!TC) { 6218 switch (Target.getOS()) { 6219 case llvm::Triple::AIX: 6220 TC = std::make_unique<toolchains::AIX>(*this, Target, Args); 6221 break; 6222 case llvm::Triple::Haiku: 6223 TC = std::make_unique<toolchains::Haiku>(*this, Target, Args); 6224 break; 6225 case llvm::Triple::Darwin: 6226 case llvm::Triple::MacOSX: 6227 case llvm::Triple::IOS: 6228 case llvm::Triple::TvOS: 6229 case llvm::Triple::WatchOS: 6230 case llvm::Triple::XROS: 6231 case llvm::Triple::DriverKit: 6232 TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args); 6233 break; 6234 case llvm::Triple::DragonFly: 6235 TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args); 6236 break; 6237 case llvm::Triple::OpenBSD: 6238 TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args); 6239 break; 6240 case llvm::Triple::NetBSD: 6241 TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args); 6242 break; 6243 case llvm::Triple::FreeBSD: 6244 if (Target.isPPC()) 6245 TC = std::make_unique<toolchains::PPCFreeBSDToolChain>(*this, Target, 6246 Args); 6247 else 6248 TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args); 6249 break; 6250 case llvm::Triple::Linux: 6251 case llvm::Triple::ELFIAMCU: 6252 if (Target.getArch() == llvm::Triple::hexagon) 6253 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target, 6254 Args); 6255 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) && 6256 !Target.hasEnvironment()) 6257 TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target, 6258 Args); 6259 else if (Target.isPPC()) 6260 TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target, 6261 Args); 6262 else if (Target.getArch() == llvm::Triple::ve) 6263 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args); 6264 else if (Target.isOHOSFamily()) 6265 TC = std::make_unique<toolchains::OHOS>(*this, Target, Args); 6266 else 6267 TC = std::make_unique<toolchains::Linux>(*this, Target, Args); 6268 break; 6269 case llvm::Triple::NaCl: 6270 TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args); 6271 break; 6272 case llvm::Triple::Fuchsia: 6273 TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args); 6274 break; 6275 case llvm::Triple::Solaris: 6276 TC = std::make_unique<toolchains::Solaris>(*this, Target, Args); 6277 break; 6278 case llvm::Triple::CUDA: 6279 TC = std::make_unique<toolchains::NVPTXToolChain>(*this, Target, Args); 6280 break; 6281 case llvm::Triple::AMDHSA: 6282 TC = std::make_unique<toolchains::ROCMToolChain>(*this, Target, Args); 6283 break; 6284 case llvm::Triple::AMDPAL: 6285 case llvm::Triple::Mesa3D: 6286 TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args); 6287 break; 6288 case llvm::Triple::Win32: 6289 switch (Target.getEnvironment()) { 6290 default: 6291 if (Target.isOSBinFormatELF()) 6292 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args); 6293 else if (Target.isOSBinFormatMachO()) 6294 TC = std::make_unique<toolchains::MachO>(*this, Target, Args); 6295 else 6296 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args); 6297 break; 6298 case llvm::Triple::GNU: 6299 TC = std::make_unique<toolchains::MinGW>(*this, Target, Args); 6300 break; 6301 case llvm::Triple::Itanium: 6302 TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target, 6303 Args); 6304 break; 6305 case llvm::Triple::MSVC: 6306 case llvm::Triple::UnknownEnvironment: 6307 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ) 6308 .starts_with_insensitive("bfd")) 6309 TC = std::make_unique<toolchains::CrossWindowsToolChain>( 6310 *this, Target, Args); 6311 else 6312 TC = 6313 std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args); 6314 break; 6315 } 6316 break; 6317 case llvm::Triple::PS4: 6318 TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args); 6319 break; 6320 case llvm::Triple::PS5: 6321 TC = std::make_unique<toolchains::PS5CPU>(*this, Target, Args); 6322 break; 6323 case llvm::Triple::Hurd: 6324 TC = std::make_unique<toolchains::Hurd>(*this, Target, Args); 6325 break; 6326 case llvm::Triple::LiteOS: 6327 TC = std::make_unique<toolchains::OHOS>(*this, Target, Args); 6328 break; 6329 case llvm::Triple::ZOS: 6330 TC = std::make_unique<toolchains::ZOS>(*this, Target, Args); 6331 break; 6332 case llvm::Triple::ShaderModel: 6333 TC = std::make_unique<toolchains::HLSLToolChain>(*this, Target, Args); 6334 break; 6335 default: 6336 // Of these targets, Hexagon is the only one that might have 6337 // an OS of Linux, in which case it got handled above already. 6338 switch (Target.getArch()) { 6339 case llvm::Triple::tce: 6340 TC = std::make_unique<toolchains::TCEToolChain>(*this, Target, Args); 6341 break; 6342 case llvm::Triple::tcele: 6343 TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args); 6344 break; 6345 case llvm::Triple::hexagon: 6346 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target, 6347 Args); 6348 break; 6349 case llvm::Triple::lanai: 6350 TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args); 6351 break; 6352 case llvm::Triple::xcore: 6353 TC = std::make_unique<toolchains::XCoreToolChain>(*this, Target, Args); 6354 break; 6355 case llvm::Triple::wasm32: 6356 case llvm::Triple::wasm64: 6357 TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args); 6358 break; 6359 case llvm::Triple::avr: 6360 TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args); 6361 break; 6362 case llvm::Triple::msp430: 6363 TC = 6364 std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args); 6365 break; 6366 case llvm::Triple::riscv32: 6367 case llvm::Triple::riscv64: 6368 if (toolchains::RISCVToolChain::hasGCCToolchain(*this, Args)) 6369 TC = 6370 std::make_unique<toolchains::RISCVToolChain>(*this, Target, Args); 6371 else 6372 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args); 6373 break; 6374 case llvm::Triple::ve: 6375 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args); 6376 break; 6377 case llvm::Triple::spirv32: 6378 case llvm::Triple::spirv64: 6379 TC = std::make_unique<toolchains::SPIRVToolChain>(*this, Target, Args); 6380 break; 6381 case llvm::Triple::csky: 6382 TC = std::make_unique<toolchains::CSKYToolChain>(*this, Target, Args); 6383 break; 6384 default: 6385 if (toolchains::BareMetal::handlesTarget(Target)) 6386 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args); 6387 else if (Target.isOSBinFormatELF()) 6388 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args); 6389 else if (Target.isOSBinFormatMachO()) 6390 TC = std::make_unique<toolchains::MachO>(*this, Target, Args); 6391 else 6392 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args); 6393 } 6394 } 6395 } 6396 6397 return *TC; 6398 } 6399 6400 const ToolChain &Driver::getOffloadingDeviceToolChain( 6401 const ArgList &Args, const llvm::Triple &Target, const ToolChain &HostTC, 6402 const Action::OffloadKind &TargetDeviceOffloadKind) const { 6403 // Use device / host triples as the key into the ToolChains map because the 6404 // device ToolChain we create depends on both. 6405 auto &TC = ToolChains[Target.str() + "/" + HostTC.getTriple().str()]; 6406 if (!TC) { 6407 // Categorized by offload kind > arch rather than OS > arch like 6408 // the normal getToolChain call, as it seems a reasonable way to categorize 6409 // things. 6410 switch (TargetDeviceOffloadKind) { 6411 case Action::OFK_HIP: { 6412 if (Target.getArch() == llvm::Triple::amdgcn && 6413 Target.getVendor() == llvm::Triple::AMD && 6414 Target.getOS() == llvm::Triple::AMDHSA) 6415 TC = std::make_unique<toolchains::HIPAMDToolChain>(*this, Target, 6416 HostTC, Args); 6417 else if (Target.getArch() == llvm::Triple::spirv64 && 6418 Target.getVendor() == llvm::Triple::UnknownVendor && 6419 Target.getOS() == llvm::Triple::UnknownOS) 6420 TC = std::make_unique<toolchains::HIPSPVToolChain>(*this, Target, 6421 HostTC, Args); 6422 break; 6423 } 6424 default: 6425 break; 6426 } 6427 } 6428 6429 return *TC; 6430 } 6431 6432 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const { 6433 // Say "no" if there is not exactly one input of a type clang understands. 6434 if (JA.size() != 1 || 6435 !types::isAcceptedByClang((*JA.input_begin())->getType())) 6436 return false; 6437 6438 // And say "no" if this is not a kind of action clang understands. 6439 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) && 6440 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA) && 6441 !isa<ExtractAPIJobAction>(JA)) 6442 return false; 6443 6444 return true; 6445 } 6446 6447 bool Driver::ShouldUseFlangCompiler(const JobAction &JA) const { 6448 // Say "no" if there is not exactly one input of a type flang understands. 6449 if (JA.size() != 1 || 6450 !types::isAcceptedByFlang((*JA.input_begin())->getType())) 6451 return false; 6452 6453 // And say "no" if this is not a kind of action flang understands. 6454 if (!isa<PreprocessJobAction>(JA) && !isa<CompileJobAction>(JA) && 6455 !isa<BackendJobAction>(JA)) 6456 return false; 6457 6458 return true; 6459 } 6460 6461 bool Driver::ShouldEmitStaticLibrary(const ArgList &Args) const { 6462 // Only emit static library if the flag is set explicitly. 6463 if (Args.hasArg(options::OPT_emit_static_lib)) 6464 return true; 6465 return false; 6466 } 6467 6468 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the 6469 /// grouped values as integers. Numbers which are not provided are set to 0. 6470 /// 6471 /// \return True if the entire string was parsed (9.2), or all groups were 6472 /// parsed (10.3.5extrastuff). 6473 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor, 6474 unsigned &Micro, bool &HadExtra) { 6475 HadExtra = false; 6476 6477 Major = Minor = Micro = 0; 6478 if (Str.empty()) 6479 return false; 6480 6481 if (Str.consumeInteger(10, Major)) 6482 return false; 6483 if (Str.empty()) 6484 return true; 6485 if (Str[0] != '.') 6486 return false; 6487 6488 Str = Str.drop_front(1); 6489 6490 if (Str.consumeInteger(10, Minor)) 6491 return false; 6492 if (Str.empty()) 6493 return true; 6494 if (Str[0] != '.') 6495 return false; 6496 Str = Str.drop_front(1); 6497 6498 if (Str.consumeInteger(10, Micro)) 6499 return false; 6500 if (!Str.empty()) 6501 HadExtra = true; 6502 return true; 6503 } 6504 6505 /// Parse digits from a string \p Str and fulfill \p Digits with 6506 /// the parsed numbers. This method assumes that the max number of 6507 /// digits to look for is equal to Digits.size(). 6508 /// 6509 /// \return True if the entire string was parsed and there are 6510 /// no extra characters remaining at the end. 6511 bool Driver::GetReleaseVersion(StringRef Str, 6512 MutableArrayRef<unsigned> Digits) { 6513 if (Str.empty()) 6514 return false; 6515 6516 unsigned CurDigit = 0; 6517 while (CurDigit < Digits.size()) { 6518 unsigned Digit; 6519 if (Str.consumeInteger(10, Digit)) 6520 return false; 6521 Digits[CurDigit] = Digit; 6522 if (Str.empty()) 6523 return true; 6524 if (Str[0] != '.') 6525 return false; 6526 Str = Str.drop_front(1); 6527 CurDigit++; 6528 } 6529 6530 // More digits than requested, bail out... 6531 return false; 6532 } 6533 6534 llvm::opt::Visibility 6535 Driver::getOptionVisibilityMask(bool UseDriverMode) const { 6536 if (!UseDriverMode) 6537 return llvm::opt::Visibility(options::ClangOption); 6538 if (IsCLMode()) 6539 return llvm::opt::Visibility(options::CLOption); 6540 if (IsDXCMode()) 6541 return llvm::opt::Visibility(options::DXCOption); 6542 if (IsFlangMode()) { 6543 return llvm::opt::Visibility(options::FlangOption); 6544 } 6545 return llvm::opt::Visibility(options::ClangOption); 6546 } 6547 6548 const char *Driver::getExecutableForDriverMode(DriverMode Mode) { 6549 switch (Mode) { 6550 case GCCMode: 6551 return "clang"; 6552 case GXXMode: 6553 return "clang++"; 6554 case CPPMode: 6555 return "clang-cpp"; 6556 case CLMode: 6557 return "clang-cl"; 6558 case FlangMode: 6559 return "flang"; 6560 case DXCMode: 6561 return "clang-dxc"; 6562 } 6563 6564 llvm_unreachable("Unhandled Mode"); 6565 } 6566 6567 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) { 6568 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false); 6569 } 6570 6571 bool clang::driver::willEmitRemarks(const ArgList &Args) { 6572 // -fsave-optimization-record enables it. 6573 if (Args.hasFlag(options::OPT_fsave_optimization_record, 6574 options::OPT_fno_save_optimization_record, false)) 6575 return true; 6576 6577 // -fsave-optimization-record=<format> enables it as well. 6578 if (Args.hasFlag(options::OPT_fsave_optimization_record_EQ, 6579 options::OPT_fno_save_optimization_record, false)) 6580 return true; 6581 6582 // -foptimization-record-file alone enables it too. 6583 if (Args.hasFlag(options::OPT_foptimization_record_file_EQ, 6584 options::OPT_fno_save_optimization_record, false)) 6585 return true; 6586 6587 // -foptimization-record-passes alone enables it too. 6588 if (Args.hasFlag(options::OPT_foptimization_record_passes_EQ, 6589 options::OPT_fno_save_optimization_record, false)) 6590 return true; 6591 return false; 6592 } 6593 6594 llvm::StringRef clang::driver::getDriverMode(StringRef ProgName, 6595 ArrayRef<const char *> Args) { 6596 static StringRef OptName = 6597 getDriverOptTable().getOption(options::OPT_driver_mode).getPrefixedName(); 6598 llvm::StringRef Opt; 6599 for (StringRef Arg : Args) { 6600 if (!Arg.starts_with(OptName)) 6601 continue; 6602 Opt = Arg; 6603 } 6604 if (Opt.empty()) 6605 Opt = ToolChain::getTargetAndModeFromProgramName(ProgName).DriverMode; 6606 return Opt.consume_front(OptName) ? Opt : ""; 6607 } 6608 6609 bool driver::IsClangCL(StringRef DriverMode) { return DriverMode.equals("cl"); } 6610 6611 llvm::Error driver::expandResponseFiles(SmallVectorImpl<const char *> &Args, 6612 bool ClangCLMode, 6613 llvm::BumpPtrAllocator &Alloc, 6614 llvm::vfs::FileSystem *FS) { 6615 // Parse response files using the GNU syntax, unless we're in CL mode. There 6616 // are two ways to put clang in CL compatibility mode: ProgName is either 6617 // clang-cl or cl, or --driver-mode=cl is on the command line. The normal 6618 // command line parsing can't happen until after response file parsing, so we 6619 // have to manually search for a --driver-mode=cl argument the hard way. 6620 // Finally, our -cc1 tools don't care which tokenization mode we use because 6621 // response files written by clang will tokenize the same way in either mode. 6622 enum { Default, POSIX, Windows } RSPQuoting = Default; 6623 for (const char *F : Args) { 6624 if (strcmp(F, "--rsp-quoting=posix") == 0) 6625 RSPQuoting = POSIX; 6626 else if (strcmp(F, "--rsp-quoting=windows") == 0) 6627 RSPQuoting = Windows; 6628 } 6629 6630 // Determines whether we want nullptr markers in Args to indicate response 6631 // files end-of-lines. We only use this for the /LINK driver argument with 6632 // clang-cl.exe on Windows. 6633 bool MarkEOLs = ClangCLMode; 6634 6635 llvm::cl::TokenizerCallback Tokenizer; 6636 if (RSPQuoting == Windows || (RSPQuoting == Default && ClangCLMode)) 6637 Tokenizer = &llvm::cl::TokenizeWindowsCommandLine; 6638 else 6639 Tokenizer = &llvm::cl::TokenizeGNUCommandLine; 6640 6641 if (MarkEOLs && Args.size() > 1 && StringRef(Args[1]).starts_with("-cc1")) 6642 MarkEOLs = false; 6643 6644 llvm::cl::ExpansionContext ECtx(Alloc, Tokenizer); 6645 ECtx.setMarkEOLs(MarkEOLs); 6646 if (FS) 6647 ECtx.setVFS(FS); 6648 6649 if (llvm::Error Err = ECtx.expandResponseFiles(Args)) 6650 return Err; 6651 6652 // If -cc1 came from a response file, remove the EOL sentinels. 6653 auto FirstArg = llvm::find_if(llvm::drop_begin(Args), 6654 [](const char *A) { return A != nullptr; }); 6655 if (FirstArg != Args.end() && StringRef(*FirstArg).starts_with("-cc1")) { 6656 // If -cc1 came from a response file, remove the EOL sentinels. 6657 if (MarkEOLs) { 6658 auto newEnd = std::remove(Args.begin(), Args.end(), nullptr); 6659 Args.resize(newEnd - Args.begin()); 6660 } 6661 } 6662 6663 return llvm::Error::success(); 6664 } 6665