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