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