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