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 // Offload kinds active for this compilation. 3877 unsigned OffloadKinds = Action::OFK_None; 3878 if (C.hasOffloadToolChain<Action::OFK_OpenMP>()) 3879 OffloadKinds |= Action::OFK_OpenMP; 3880 3881 // Construct the actions to perform. 3882 HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr; 3883 ActionList LinkerInputs; 3884 ActionList MergerInputs; 3885 3886 for (auto &I : Inputs) { 3887 types::ID InputType = I.first; 3888 const Arg *InputArg = I.second; 3889 3890 auto PL = types::getCompilationPhases(*this, Args, InputType); 3891 if (PL.empty()) 3892 continue; 3893 3894 auto FullPL = types::getCompilationPhases(InputType); 3895 3896 // Build the pipeline for this file. 3897 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType); 3898 3899 // Use the current host action in any of the offloading actions, if 3900 // required. 3901 if (!Args.hasArg(options::OPT_fopenmp_new_driver)) 3902 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg)) 3903 break; 3904 3905 for (phases::ID Phase : PL) { 3906 3907 // Add any offload action the host action depends on. 3908 if (!Args.hasArg(options::OPT_fopenmp_new_driver)) 3909 Current = OffloadBuilder.addDeviceDependencesToHostAction( 3910 Current, InputArg, Phase, PL.back(), FullPL); 3911 if (!Current) 3912 break; 3913 3914 // Queue linker inputs. 3915 if (Phase == phases::Link) { 3916 assert(Phase == PL.back() && "linking must be final compilation step."); 3917 LinkerInputs.push_back(Current); 3918 Current = nullptr; 3919 break; 3920 } 3921 3922 // TODO: Consider removing this because the merged may not end up being 3923 // the final Phase in the pipeline. Perhaps the merged could just merge 3924 // and then pass an artifact of some sort to the Link Phase. 3925 // Queue merger inputs. 3926 if (Phase == phases::IfsMerge) { 3927 assert(Phase == PL.back() && "merging must be final compilation step."); 3928 MergerInputs.push_back(Current); 3929 Current = nullptr; 3930 break; 3931 } 3932 3933 // Each precompiled header file after a module file action is a module 3934 // header of that same module file, rather than being compiled to a 3935 // separate PCH. 3936 if (Phase == phases::Precompile && HeaderModuleAction && 3937 getPrecompiledType(InputType) == types::TY_PCH) { 3938 HeaderModuleAction->addModuleHeaderInput(Current); 3939 Current = nullptr; 3940 break; 3941 } 3942 3943 // Try to build the offloading actions and add the result as a dependency 3944 // to the host. 3945 if (Args.hasArg(options::OPT_fopenmp_new_driver)) 3946 Current = BuildOffloadingActions(C, Args, I, Current); 3947 3948 // FIXME: Should we include any prior module file outputs as inputs of 3949 // later actions in the same command line? 3950 3951 // Otherwise construct the appropriate action. 3952 Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current); 3953 3954 // We didn't create a new action, so we will just move to the next phase. 3955 if (NewCurrent == Current) 3956 continue; 3957 3958 if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent)) 3959 HeaderModuleAction = HMA; 3960 3961 Current = NewCurrent; 3962 3963 // Use the current host action in any of the offloading actions, if 3964 // required. 3965 if (!Args.hasArg(options::OPT_fopenmp_new_driver)) 3966 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg)) 3967 break; 3968 3969 if (Current->getType() == types::TY_Nothing) 3970 break; 3971 } 3972 3973 // If we ended with something, add to the output list. 3974 if (Current) 3975 Actions.push_back(Current); 3976 3977 // Add any top level actions generated for offloading. 3978 if (!Args.hasArg(options::OPT_fopenmp_new_driver)) 3979 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg); 3980 else if (Current) 3981 Current->propagateHostOffloadInfo(OffloadKinds, 3982 /*BoundArch=*/nullptr); 3983 } 3984 3985 // Add a link action if necessary. 3986 3987 if (LinkerInputs.empty()) { 3988 Arg *FinalPhaseArg; 3989 if (getFinalPhase(Args, &FinalPhaseArg) == phases::Link) 3990 OffloadBuilder.appendDeviceLinkActions(Actions); 3991 } 3992 3993 if (!LinkerInputs.empty()) { 3994 if (!Args.hasArg(options::OPT_fopenmp_new_driver)) 3995 if (Action *Wrapper = OffloadBuilder.makeHostLinkAction()) 3996 LinkerInputs.push_back(Wrapper); 3997 Action *LA; 3998 // Check if this Linker Job should emit a static library. 3999 if (ShouldEmitStaticLibrary(Args)) { 4000 LA = C.MakeAction<StaticLibJobAction>(LinkerInputs, types::TY_Image); 4001 } else if (Args.hasArg(options::OPT_fopenmp_new_driver) && 4002 OffloadKinds != Action::OFK_None) { 4003 LA = C.MakeAction<LinkerWrapperJobAction>(LinkerInputs, types::TY_Image); 4004 LA->propagateHostOffloadInfo(OffloadKinds, 4005 /*BoundArch=*/nullptr); 4006 } else { 4007 LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image); 4008 } 4009 if (!Args.hasArg(options::OPT_fopenmp_new_driver)) 4010 LA = OffloadBuilder.processHostLinkAction(LA); 4011 Actions.push_back(LA); 4012 } 4013 4014 // Add an interface stubs merge action if necessary. 4015 if (!MergerInputs.empty()) 4016 Actions.push_back( 4017 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image)); 4018 4019 if (Args.hasArg(options::OPT_emit_interface_stubs)) { 4020 auto PhaseList = types::getCompilationPhases( 4021 types::TY_IFS_CPP, 4022 Args.hasArg(options::OPT_c) ? phases::Compile : phases::IfsMerge); 4023 4024 ActionList MergerInputs; 4025 4026 for (auto &I : Inputs) { 4027 types::ID InputType = I.first; 4028 const Arg *InputArg = I.second; 4029 4030 // Currently clang and the llvm assembler do not support generating symbol 4031 // stubs from assembly, so we skip the input on asm files. For ifs files 4032 // we rely on the normal pipeline setup in the pipeline setup code above. 4033 if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm || 4034 InputType == types::TY_Asm) 4035 continue; 4036 4037 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType); 4038 4039 for (auto Phase : PhaseList) { 4040 switch (Phase) { 4041 default: 4042 llvm_unreachable( 4043 "IFS Pipeline can only consist of Compile followed by IfsMerge."); 4044 case phases::Compile: { 4045 // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs 4046 // files where the .o file is located. The compile action can not 4047 // handle this. 4048 if (InputType == types::TY_Object) 4049 break; 4050 4051 Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP); 4052 break; 4053 } 4054 case phases::IfsMerge: { 4055 assert(Phase == PhaseList.back() && 4056 "merging must be final compilation step."); 4057 MergerInputs.push_back(Current); 4058 Current = nullptr; 4059 break; 4060 } 4061 } 4062 } 4063 4064 // If we ended with something, add to the output list. 4065 if (Current) 4066 Actions.push_back(Current); 4067 } 4068 4069 // Add an interface stubs merge action if necessary. 4070 if (!MergerInputs.empty()) 4071 Actions.push_back( 4072 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image)); 4073 } 4074 4075 // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a custom 4076 // Compile phase that prints out supported cpu models and quits. 4077 if (Arg *A = Args.getLastArg(options::OPT_print_supported_cpus)) { 4078 // Use the -mcpu=? flag as the dummy input to cc1. 4079 Actions.clear(); 4080 Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C); 4081 Actions.push_back( 4082 C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing)); 4083 for (auto &I : Inputs) 4084 I.second->claim(); 4085 } 4086 4087 // Claim ignored clang-cl options. 4088 Args.ClaimAllArgs(options::OPT_cl_ignored_Group); 4089 4090 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed 4091 // to non-CUDA compilations and should not trigger warnings there. 4092 Args.ClaimAllArgs(options::OPT_cuda_host_only); 4093 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device); 4094 } 4095 4096 Action *Driver::BuildOffloadingActions(Compilation &C, 4097 llvm::opt::DerivedArgList &Args, 4098 const InputTy &Input, 4099 Action *HostAction) const { 4100 if (!isa<CompileJobAction>(HostAction)) 4101 return HostAction; 4102 4103 SmallVector<const ToolChain *, 2> ToolChains; 4104 ActionList DeviceActions; 4105 4106 types::ID InputType = Input.first; 4107 const Arg *InputArg = Input.second; 4108 4109 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>(); 4110 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE; ++TI) 4111 ToolChains.push_back(TI->second); 4112 4113 for (unsigned I = 0; I < ToolChains.size(); ++I) 4114 DeviceActions.push_back(C.MakeAction<InputAction>(*InputArg, InputType)); 4115 4116 if (DeviceActions.empty()) 4117 return HostAction; 4118 4119 auto PL = types::getCompilationPhases(*this, Args, InputType); 4120 4121 for (phases::ID Phase : PL) { 4122 if (Phase == phases::Link) { 4123 assert(Phase == PL.back() && "linking must be final compilation step."); 4124 break; 4125 } 4126 4127 auto TC = ToolChains.begin(); 4128 for (Action *&A : DeviceActions) { 4129 A = ConstructPhaseAction(C, Args, Phase, A, Action::OFK_OpenMP); 4130 4131 if (isa<CompileJobAction>(A)) { 4132 HostAction->setCannotBeCollapsedWithNextDependentAction(); 4133 OffloadAction::HostDependence HDep( 4134 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 4135 /*BourdArch=*/nullptr, Action::OFK_OpenMP); 4136 OffloadAction::DeviceDependences DDep; 4137 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP); 4138 A = C.MakeAction<OffloadAction>(HDep, DDep); 4139 } 4140 ++TC; 4141 } 4142 } 4143 4144 OffloadAction::DeviceDependences DDeps; 4145 4146 auto TC = ToolChains.begin(); 4147 for (Action *A : DeviceActions) { 4148 DDeps.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP); 4149 TC++; 4150 } 4151 4152 OffloadAction::HostDependence HDep( 4153 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 4154 /*BoundArch=*/nullptr, DDeps); 4155 return C.MakeAction<OffloadAction>(HDep, DDeps); 4156 } 4157 4158 Action *Driver::ConstructPhaseAction( 4159 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input, 4160 Action::OffloadKind TargetDeviceOffloadKind) const { 4161 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions"); 4162 4163 // Some types skip the assembler phase (e.g., llvm-bc), but we can't 4164 // encode this in the steps because the intermediate type depends on 4165 // arguments. Just special case here. 4166 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm) 4167 return Input; 4168 4169 // Build the appropriate action. 4170 switch (Phase) { 4171 case phases::Link: 4172 llvm_unreachable("link action invalid here."); 4173 case phases::IfsMerge: 4174 llvm_unreachable("ifsmerge action invalid here."); 4175 case phases::Preprocess: { 4176 types::ID OutputTy; 4177 // -M and -MM specify the dependency file name by altering the output type, 4178 // -if -MD and -MMD are not specified. 4179 if (Args.hasArg(options::OPT_M, options::OPT_MM) && 4180 !Args.hasArg(options::OPT_MD, options::OPT_MMD)) { 4181 OutputTy = types::TY_Dependencies; 4182 } else { 4183 OutputTy = Input->getType(); 4184 if (!Args.hasFlag(options::OPT_frewrite_includes, 4185 options::OPT_fno_rewrite_includes, false) && 4186 !Args.hasFlag(options::OPT_frewrite_imports, 4187 options::OPT_fno_rewrite_imports, false) && 4188 !CCGenDiagnostics) 4189 OutputTy = types::getPreprocessedType(OutputTy); 4190 assert(OutputTy != types::TY_INVALID && 4191 "Cannot preprocess this input type!"); 4192 } 4193 return C.MakeAction<PreprocessJobAction>(Input, OutputTy); 4194 } 4195 case phases::Precompile: { 4196 types::ID OutputTy = getPrecompiledType(Input->getType()); 4197 assert(OutputTy != types::TY_INVALID && 4198 "Cannot precompile this input type!"); 4199 4200 // If we're given a module name, precompile header file inputs as a 4201 // module, not as a precompiled header. 4202 const char *ModName = nullptr; 4203 if (OutputTy == types::TY_PCH) { 4204 if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ)) 4205 ModName = A->getValue(); 4206 if (ModName) 4207 OutputTy = types::TY_ModuleFile; 4208 } 4209 4210 if (Args.hasArg(options::OPT_fsyntax_only) || 4211 Args.hasArg(options::OPT_extract_api)) { 4212 // Syntax checks should not emit a PCH file 4213 OutputTy = types::TY_Nothing; 4214 } 4215 4216 if (ModName) 4217 return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy, 4218 ModName); 4219 return C.MakeAction<PrecompileJobAction>(Input, OutputTy); 4220 } 4221 case phases::Compile: { 4222 if (Args.hasArg(options::OPT_fsyntax_only)) 4223 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing); 4224 if (Args.hasArg(options::OPT_rewrite_objc)) 4225 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC); 4226 if (Args.hasArg(options::OPT_rewrite_legacy_objc)) 4227 return C.MakeAction<CompileJobAction>(Input, 4228 types::TY_RewrittenLegacyObjC); 4229 if (Args.hasArg(options::OPT__analyze)) 4230 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist); 4231 if (Args.hasArg(options::OPT__migrate)) 4232 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap); 4233 if (Args.hasArg(options::OPT_emit_ast)) 4234 return C.MakeAction<CompileJobAction>(Input, types::TY_AST); 4235 if (Args.hasArg(options::OPT_module_file_info)) 4236 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile); 4237 if (Args.hasArg(options::OPT_verify_pch)) 4238 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing); 4239 if (Args.hasArg(options::OPT_extract_api)) 4240 return C.MakeAction<CompileJobAction>(Input, types::TY_API_INFO); 4241 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC); 4242 } 4243 case phases::Backend: { 4244 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) { 4245 types::ID Output = 4246 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC; 4247 return C.MakeAction<BackendJobAction>(Input, Output); 4248 } 4249 if (isUsingLTO(/* IsOffload */ true) && 4250 TargetDeviceOffloadKind == Action::OFK_OpenMP) { 4251 types::ID Output = 4252 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC; 4253 return C.MakeAction<BackendJobAction>(Input, Output); 4254 } 4255 if (Args.hasArg(options::OPT_emit_llvm) || 4256 (TargetDeviceOffloadKind == Action::OFK_HIP && 4257 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, 4258 false))) { 4259 types::ID Output = 4260 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC; 4261 return C.MakeAction<BackendJobAction>(Input, Output); 4262 } 4263 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm); 4264 } 4265 case phases::Assemble: 4266 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object); 4267 } 4268 4269 llvm_unreachable("invalid phase in ConstructPhaseAction"); 4270 } 4271 4272 void Driver::BuildJobs(Compilation &C) const { 4273 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 4274 4275 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 4276 4277 // It is an error to provide a -o option if we are making multiple output 4278 // files. There are exceptions: 4279 // 4280 // IfsMergeJob: when generating interface stubs enabled we want to be able to 4281 // generate the stub file at the same time that we generate the real 4282 // library/a.out. So when a .o, .so, etc are the output, with clang interface 4283 // stubs there will also be a .ifs and .ifso at the same location. 4284 // 4285 // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled 4286 // and -c is passed, we still want to be able to generate a .ifs file while 4287 // we are also generating .o files. So we allow more than one output file in 4288 // this case as well. 4289 // 4290 if (FinalOutput) { 4291 unsigned NumOutputs = 0; 4292 unsigned NumIfsOutputs = 0; 4293 for (const Action *A : C.getActions()) 4294 if (A->getType() != types::TY_Nothing && 4295 !(A->getKind() == Action::IfsMergeJobClass || 4296 (A->getType() == clang::driver::types::TY_IFS_CPP && 4297 A->getKind() == clang::driver::Action::CompileJobClass && 4298 0 == NumIfsOutputs++) || 4299 (A->getKind() == Action::BindArchClass && A->getInputs().size() && 4300 A->getInputs().front()->getKind() == Action::IfsMergeJobClass))) 4301 ++NumOutputs; 4302 4303 if (NumOutputs > 1) { 4304 Diag(clang::diag::err_drv_output_argument_with_multiple_files); 4305 FinalOutput = nullptr; 4306 } 4307 } 4308 4309 const llvm::Triple &RawTriple = C.getDefaultToolChain().getTriple(); 4310 if (RawTriple.isOSAIX()) { 4311 if (Arg *A = C.getArgs().getLastArg(options::OPT_G)) 4312 Diag(diag::err_drv_unsupported_opt_for_target) 4313 << A->getSpelling() << RawTriple.str(); 4314 if (LTOMode == LTOK_Thin) 4315 Diag(diag::err_drv_clang_unsupported) << "thinLTO on AIX"; 4316 } 4317 4318 // Collect the list of architectures. 4319 llvm::StringSet<> ArchNames; 4320 if (RawTriple.isOSBinFormatMachO()) 4321 for (const Arg *A : C.getArgs()) 4322 if (A->getOption().matches(options::OPT_arch)) 4323 ArchNames.insert(A->getValue()); 4324 4325 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for. 4326 std::map<std::pair<const Action *, std::string>, InputInfoList> CachedResults; 4327 for (Action *A : C.getActions()) { 4328 // If we are linking an image for multiple archs then the linker wants 4329 // -arch_multiple and -final_output <final image name>. Unfortunately, this 4330 // doesn't fit in cleanly because we have to pass this information down. 4331 // 4332 // FIXME: This is a hack; find a cleaner way to integrate this into the 4333 // process. 4334 const char *LinkingOutput = nullptr; 4335 if (isa<LipoJobAction>(A)) { 4336 if (FinalOutput) 4337 LinkingOutput = FinalOutput->getValue(); 4338 else 4339 LinkingOutput = getDefaultImageName(); 4340 } 4341 4342 BuildJobsForAction(C, A, &C.getDefaultToolChain(), 4343 /*BoundArch*/ StringRef(), 4344 /*AtTopLevel*/ true, 4345 /*MultipleArchs*/ ArchNames.size() > 1, 4346 /*LinkingOutput*/ LinkingOutput, CachedResults, 4347 /*TargetDeviceOffloadKind*/ Action::OFK_None); 4348 } 4349 4350 // If we have more than one job, then disable integrated-cc1 for now. Do this 4351 // also when we need to report process execution statistics. 4352 if (C.getJobs().size() > 1 || CCPrintProcessStats) 4353 for (auto &J : C.getJobs()) 4354 J.InProcess = false; 4355 4356 if (CCPrintProcessStats) { 4357 C.setPostCallback([=](const Command &Cmd, int Res) { 4358 Optional<llvm::sys::ProcessStatistics> ProcStat = 4359 Cmd.getProcessStatistics(); 4360 if (!ProcStat) 4361 return; 4362 4363 const char *LinkingOutput = nullptr; 4364 if (FinalOutput) 4365 LinkingOutput = FinalOutput->getValue(); 4366 else if (!Cmd.getOutputFilenames().empty()) 4367 LinkingOutput = Cmd.getOutputFilenames().front().c_str(); 4368 else 4369 LinkingOutput = getDefaultImageName(); 4370 4371 if (CCPrintStatReportFilename.empty()) { 4372 using namespace llvm; 4373 // Human readable output. 4374 outs() << sys::path::filename(Cmd.getExecutable()) << ": " 4375 << "output=" << LinkingOutput; 4376 outs() << ", total=" 4377 << format("%.3f", ProcStat->TotalTime.count() / 1000.) << " ms" 4378 << ", user=" 4379 << format("%.3f", ProcStat->UserTime.count() / 1000.) << " ms" 4380 << ", mem=" << ProcStat->PeakMemory << " Kb\n"; 4381 } else { 4382 // CSV format. 4383 std::string Buffer; 4384 llvm::raw_string_ostream Out(Buffer); 4385 llvm::sys::printArg(Out, llvm::sys::path::filename(Cmd.getExecutable()), 4386 /*Quote*/ true); 4387 Out << ','; 4388 llvm::sys::printArg(Out, LinkingOutput, true); 4389 Out << ',' << ProcStat->TotalTime.count() << ',' 4390 << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory 4391 << '\n'; 4392 Out.flush(); 4393 std::error_code EC; 4394 llvm::raw_fd_ostream OS(CCPrintStatReportFilename, EC, 4395 llvm::sys::fs::OF_Append | 4396 llvm::sys::fs::OF_Text); 4397 if (EC) 4398 return; 4399 auto L = OS.lock(); 4400 if (!L) { 4401 llvm::errs() << "ERROR: Cannot lock file " 4402 << CCPrintStatReportFilename << ": " 4403 << toString(L.takeError()) << "\n"; 4404 return; 4405 } 4406 OS << Buffer; 4407 OS.flush(); 4408 } 4409 }); 4410 } 4411 4412 // If the user passed -Qunused-arguments or there were errors, don't warn 4413 // about any unused arguments. 4414 if (Diags.hasErrorOccurred() || 4415 C.getArgs().hasArg(options::OPT_Qunused_arguments)) 4416 return; 4417 4418 // Claim -### here. 4419 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH); 4420 4421 // Claim --driver-mode, --rsp-quoting, it was handled earlier. 4422 (void)C.getArgs().hasArg(options::OPT_driver_mode); 4423 (void)C.getArgs().hasArg(options::OPT_rsp_quoting); 4424 4425 for (Arg *A : C.getArgs()) { 4426 // FIXME: It would be nice to be able to send the argument to the 4427 // DiagnosticsEngine, so that extra values, position, and so on could be 4428 // printed. 4429 if (!A->isClaimed()) { 4430 if (A->getOption().hasFlag(options::NoArgumentUnused)) 4431 continue; 4432 4433 // Suppress the warning automatically if this is just a flag, and it is an 4434 // instance of an argument we already claimed. 4435 const Option &Opt = A->getOption(); 4436 if (Opt.getKind() == Option::FlagClass) { 4437 bool DuplicateClaimed = false; 4438 4439 for (const Arg *AA : C.getArgs().filtered(&Opt)) { 4440 if (AA->isClaimed()) { 4441 DuplicateClaimed = true; 4442 break; 4443 } 4444 } 4445 4446 if (DuplicateClaimed) 4447 continue; 4448 } 4449 4450 // In clang-cl, don't mention unknown arguments here since they have 4451 // already been warned about. 4452 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN)) 4453 Diag(clang::diag::warn_drv_unused_argument) 4454 << A->getAsString(C.getArgs()); 4455 } 4456 } 4457 } 4458 4459 namespace { 4460 /// Utility class to control the collapse of dependent actions and select the 4461 /// tools accordingly. 4462 class ToolSelector final { 4463 /// The tool chain this selector refers to. 4464 const ToolChain &TC; 4465 4466 /// The compilation this selector refers to. 4467 const Compilation &C; 4468 4469 /// The base action this selector refers to. 4470 const JobAction *BaseAction; 4471 4472 /// Set to true if the current toolchain refers to host actions. 4473 bool IsHostSelector; 4474 4475 /// Set to true if save-temps and embed-bitcode functionalities are active. 4476 bool SaveTemps; 4477 bool EmbedBitcode; 4478 4479 /// Get previous dependent action or null if that does not exist. If 4480 /// \a CanBeCollapsed is false, that action must be legal to collapse or 4481 /// null will be returned. 4482 const JobAction *getPrevDependentAction(const ActionList &Inputs, 4483 ActionList &SavedOffloadAction, 4484 bool CanBeCollapsed = true) { 4485 // An option can be collapsed only if it has a single input. 4486 if (Inputs.size() != 1) 4487 return nullptr; 4488 4489 Action *CurAction = *Inputs.begin(); 4490 if (CanBeCollapsed && 4491 !CurAction->isCollapsingWithNextDependentActionLegal()) 4492 return nullptr; 4493 4494 // If the input action is an offload action. Look through it and save any 4495 // offload action that can be dropped in the event of a collapse. 4496 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) { 4497 // If the dependent action is a device action, we will attempt to collapse 4498 // only with other device actions. Otherwise, we would do the same but 4499 // with host actions only. 4500 if (!IsHostSelector) { 4501 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) { 4502 CurAction = 4503 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true); 4504 if (CanBeCollapsed && 4505 !CurAction->isCollapsingWithNextDependentActionLegal()) 4506 return nullptr; 4507 SavedOffloadAction.push_back(OA); 4508 return dyn_cast<JobAction>(CurAction); 4509 } 4510 } else if (OA->hasHostDependence()) { 4511 CurAction = OA->getHostDependence(); 4512 if (CanBeCollapsed && 4513 !CurAction->isCollapsingWithNextDependentActionLegal()) 4514 return nullptr; 4515 SavedOffloadAction.push_back(OA); 4516 return dyn_cast<JobAction>(CurAction); 4517 } 4518 return nullptr; 4519 } 4520 4521 return dyn_cast<JobAction>(CurAction); 4522 } 4523 4524 /// Return true if an assemble action can be collapsed. 4525 bool canCollapseAssembleAction() const { 4526 return TC.useIntegratedAs() && !SaveTemps && 4527 !C.getArgs().hasArg(options::OPT_via_file_asm) && 4528 !C.getArgs().hasArg(options::OPT__SLASH_FA) && 4529 !C.getArgs().hasArg(options::OPT__SLASH_Fa); 4530 } 4531 4532 /// Return true if a preprocessor action can be collapsed. 4533 bool canCollapsePreprocessorAction() const { 4534 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) && 4535 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps && 4536 !C.getArgs().hasArg(options::OPT_rewrite_objc); 4537 } 4538 4539 /// Struct that relates an action with the offload actions that would be 4540 /// collapsed with it. 4541 struct JobActionInfo final { 4542 /// The action this info refers to. 4543 const JobAction *JA = nullptr; 4544 /// The offload actions we need to take care off if this action is 4545 /// collapsed. 4546 ActionList SavedOffloadAction; 4547 }; 4548 4549 /// Append collapsed offload actions from the give nnumber of elements in the 4550 /// action info array. 4551 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction, 4552 ArrayRef<JobActionInfo> &ActionInfo, 4553 unsigned ElementNum) { 4554 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements."); 4555 for (unsigned I = 0; I < ElementNum; ++I) 4556 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(), 4557 ActionInfo[I].SavedOffloadAction.end()); 4558 } 4559 4560 /// Functions that attempt to perform the combining. They detect if that is 4561 /// legal, and if so they update the inputs \a Inputs and the offload action 4562 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with 4563 /// the combined action is returned. If the combining is not legal or if the 4564 /// tool does not exist, null is returned. 4565 /// Currently three kinds of collapsing are supported: 4566 /// - Assemble + Backend + Compile; 4567 /// - Assemble + Backend ; 4568 /// - Backend + Compile. 4569 const Tool * 4570 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo, 4571 ActionList &Inputs, 4572 ActionList &CollapsedOffloadAction) { 4573 if (ActionInfo.size() < 3 || !canCollapseAssembleAction()) 4574 return nullptr; 4575 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA); 4576 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA); 4577 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA); 4578 if (!AJ || !BJ || !CJ) 4579 return nullptr; 4580 4581 // Get compiler tool. 4582 const Tool *T = TC.SelectTool(*CJ); 4583 if (!T) 4584 return nullptr; 4585 4586 // Can't collapse if we don't have codegen support unless we are 4587 // emitting LLVM IR. 4588 bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType()); 4589 if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR())) 4590 return nullptr; 4591 4592 // When using -fembed-bitcode, it is required to have the same tool (clang) 4593 // for both CompilerJA and BackendJA. Otherwise, combine two stages. 4594 if (EmbedBitcode) { 4595 const Tool *BT = TC.SelectTool(*BJ); 4596 if (BT == T) 4597 return nullptr; 4598 } 4599 4600 if (!T->hasIntegratedAssembler()) 4601 return nullptr; 4602 4603 Inputs = CJ->getInputs(); 4604 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, 4605 /*NumElements=*/3); 4606 return T; 4607 } 4608 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo, 4609 ActionList &Inputs, 4610 ActionList &CollapsedOffloadAction) { 4611 if (ActionInfo.size() < 2 || !canCollapseAssembleAction()) 4612 return nullptr; 4613 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA); 4614 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA); 4615 if (!AJ || !BJ) 4616 return nullptr; 4617 4618 // Get backend tool. 4619 const Tool *T = TC.SelectTool(*BJ); 4620 if (!T) 4621 return nullptr; 4622 4623 if (!T->hasIntegratedAssembler()) 4624 return nullptr; 4625 4626 Inputs = BJ->getInputs(); 4627 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, 4628 /*NumElements=*/2); 4629 return T; 4630 } 4631 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo, 4632 ActionList &Inputs, 4633 ActionList &CollapsedOffloadAction) { 4634 if (ActionInfo.size() < 2) 4635 return nullptr; 4636 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA); 4637 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA); 4638 if (!BJ || !CJ) 4639 return nullptr; 4640 4641 // Check if the initial input (to the compile job or its predessor if one 4642 // exists) is LLVM bitcode. In that case, no preprocessor step is required 4643 // and we can still collapse the compile and backend jobs when we have 4644 // -save-temps. I.e. there is no need for a separate compile job just to 4645 // emit unoptimized bitcode. 4646 bool InputIsBitcode = true; 4647 for (size_t i = 1; i < ActionInfo.size(); i++) 4648 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC && 4649 ActionInfo[i].JA->getType() != types::TY_LTO_BC) { 4650 InputIsBitcode = false; 4651 break; 4652 } 4653 if (!InputIsBitcode && !canCollapsePreprocessorAction()) 4654 return nullptr; 4655 4656 // Get compiler tool. 4657 const Tool *T = TC.SelectTool(*CJ); 4658 if (!T) 4659 return nullptr; 4660 4661 // Can't collapse if we don't have codegen support unless we are 4662 // emitting LLVM IR. 4663 bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType()); 4664 if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR())) 4665 return nullptr; 4666 4667 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode)) 4668 return nullptr; 4669 4670 Inputs = CJ->getInputs(); 4671 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, 4672 /*NumElements=*/2); 4673 return T; 4674 } 4675 4676 /// Updates the inputs if the obtained tool supports combining with 4677 /// preprocessor action, and the current input is indeed a preprocessor 4678 /// action. If combining results in the collapse of offloading actions, those 4679 /// are appended to \a CollapsedOffloadAction. 4680 void combineWithPreprocessor(const Tool *T, ActionList &Inputs, 4681 ActionList &CollapsedOffloadAction) { 4682 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP()) 4683 return; 4684 4685 // Attempt to get a preprocessor action dependence. 4686 ActionList PreprocessJobOffloadActions; 4687 ActionList NewInputs; 4688 for (Action *A : Inputs) { 4689 auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions); 4690 if (!PJ || !isa<PreprocessJobAction>(PJ)) { 4691 NewInputs.push_back(A); 4692 continue; 4693 } 4694 4695 // This is legal to combine. Append any offload action we found and add the 4696 // current input to preprocessor inputs. 4697 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(), 4698 PreprocessJobOffloadActions.end()); 4699 NewInputs.append(PJ->input_begin(), PJ->input_end()); 4700 } 4701 Inputs = NewInputs; 4702 } 4703 4704 public: 4705 ToolSelector(const JobAction *BaseAction, const ToolChain &TC, 4706 const Compilation &C, bool SaveTemps, bool EmbedBitcode) 4707 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps), 4708 EmbedBitcode(EmbedBitcode) { 4709 assert(BaseAction && "Invalid base action."); 4710 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None; 4711 } 4712 4713 /// Check if a chain of actions can be combined and return the tool that can 4714 /// handle the combination of actions. The pointer to the current inputs \a 4715 /// Inputs and the list of offload actions \a CollapsedOffloadActions 4716 /// connected to collapsed actions are updated accordingly. The latter enables 4717 /// the caller of the selector to process them afterwards instead of just 4718 /// dropping them. If no suitable tool is found, null will be returned. 4719 const Tool *getTool(ActionList &Inputs, 4720 ActionList &CollapsedOffloadAction) { 4721 // 4722 // Get the largest chain of actions that we could combine. 4723 // 4724 4725 SmallVector<JobActionInfo, 5> ActionChain(1); 4726 ActionChain.back().JA = BaseAction; 4727 while (ActionChain.back().JA) { 4728 const Action *CurAction = ActionChain.back().JA; 4729 4730 // Grow the chain by one element. 4731 ActionChain.resize(ActionChain.size() + 1); 4732 JobActionInfo &AI = ActionChain.back(); 4733 4734 // Attempt to fill it with the 4735 AI.JA = 4736 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction); 4737 } 4738 4739 // Pop the last action info as it could not be filled. 4740 ActionChain.pop_back(); 4741 4742 // 4743 // Attempt to combine actions. If all combining attempts failed, just return 4744 // the tool of the provided action. At the end we attempt to combine the 4745 // action with any preprocessor action it may depend on. 4746 // 4747 4748 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs, 4749 CollapsedOffloadAction); 4750 if (!T) 4751 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction); 4752 if (!T) 4753 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction); 4754 if (!T) { 4755 Inputs = BaseAction->getInputs(); 4756 T = TC.SelectTool(*BaseAction); 4757 } 4758 4759 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction); 4760 return T; 4761 } 4762 }; 4763 } 4764 4765 /// Return a string that uniquely identifies the result of a job. The bound arch 4766 /// is not necessarily represented in the toolchain's triple -- for example, 4767 /// armv7 and armv7s both map to the same triple -- so we need both in our map. 4768 /// Also, we need to add the offloading device kind, as the same tool chain can 4769 /// be used for host and device for some programming models, e.g. OpenMP. 4770 static std::string GetTriplePlusArchString(const ToolChain *TC, 4771 StringRef BoundArch, 4772 Action::OffloadKind OffloadKind) { 4773 std::string TriplePlusArch = TC->getTriple().normalize(); 4774 if (!BoundArch.empty()) { 4775 TriplePlusArch += "-"; 4776 TriplePlusArch += BoundArch; 4777 } 4778 TriplePlusArch += "-"; 4779 TriplePlusArch += Action::GetOffloadKindName(OffloadKind); 4780 return TriplePlusArch; 4781 } 4782 4783 InputInfoList Driver::BuildJobsForAction( 4784 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch, 4785 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 4786 std::map<std::pair<const Action *, std::string>, InputInfoList> 4787 &CachedResults, 4788 Action::OffloadKind TargetDeviceOffloadKind) const { 4789 std::pair<const Action *, std::string> ActionTC = { 4790 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)}; 4791 auto CachedResult = CachedResults.find(ActionTC); 4792 if (CachedResult != CachedResults.end()) { 4793 return CachedResult->second; 4794 } 4795 InputInfoList Result = BuildJobsForActionNoCache( 4796 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput, 4797 CachedResults, TargetDeviceOffloadKind); 4798 CachedResults[ActionTC] = Result; 4799 return Result; 4800 } 4801 4802 InputInfoList Driver::BuildJobsForActionNoCache( 4803 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch, 4804 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 4805 std::map<std::pair<const Action *, std::string>, InputInfoList> 4806 &CachedResults, 4807 Action::OffloadKind TargetDeviceOffloadKind) const { 4808 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 4809 4810 InputInfoList OffloadDependencesInputInfo; 4811 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None; 4812 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) { 4813 // The 'Darwin' toolchain is initialized only when its arguments are 4814 // computed. Get the default arguments for OFK_None to ensure that 4815 // initialization is performed before processing the offload action. 4816 // FIXME: Remove when darwin's toolchain is initialized during construction. 4817 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None); 4818 4819 // The offload action is expected to be used in four different situations. 4820 // 4821 // a) Set a toolchain/architecture/kind for a host action: 4822 // Host Action 1 -> OffloadAction -> Host Action 2 4823 // 4824 // b) Set a toolchain/architecture/kind for a device action; 4825 // Device Action 1 -> OffloadAction -> Device Action 2 4826 // 4827 // c) Specify a device dependence to a host action; 4828 // Device Action 1 _ 4829 // \ 4830 // Host Action 1 ---> OffloadAction -> Host Action 2 4831 // 4832 // d) Specify a host dependence to a device action. 4833 // Host Action 1 _ 4834 // \ 4835 // Device Action 1 ---> OffloadAction -> Device Action 2 4836 // 4837 // For a) and b), we just return the job generated for the dependence. For 4838 // c) and d) we override the current action with the host/device dependence 4839 // if the current toolchain is host/device and set the offload dependences 4840 // info with the jobs obtained from the device/host dependence(s). 4841 4842 // If there is a single device option, just generate the job for it. 4843 if (OA->hasSingleDeviceDependence()) { 4844 InputInfoList DevA; 4845 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC, 4846 const char *DepBoundArch) { 4847 DevA = 4848 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel, 4849 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, 4850 CachedResults, DepA->getOffloadingDeviceKind()); 4851 }); 4852 return DevA; 4853 } 4854 4855 // If 'Action 2' is host, we generate jobs for the device dependences and 4856 // override the current action with the host dependence. Otherwise, we 4857 // generate the host dependences and override the action with the device 4858 // dependence. The dependences can't therefore be a top-level action. 4859 OA->doOnEachDependence( 4860 /*IsHostDependence=*/BuildingForOffloadDevice, 4861 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { 4862 OffloadDependencesInputInfo.append(BuildJobsForAction( 4863 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false, 4864 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults, 4865 DepA->getOffloadingDeviceKind())); 4866 }); 4867 4868 A = BuildingForOffloadDevice 4869 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true) 4870 : OA->getHostDependence(); 4871 4872 // We may have already built this action as a part of the offloading 4873 // toolchain, return the cached input if so. 4874 std::pair<const Action *, std::string> ActionTC = { 4875 OA->getHostDependence(), 4876 GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)}; 4877 if (CachedResults.find(ActionTC) != CachedResults.end()) { 4878 InputInfoList Inputs = CachedResults[ActionTC]; 4879 Inputs.append(OffloadDependencesInputInfo); 4880 return Inputs; 4881 } 4882 } 4883 4884 if (const InputAction *IA = dyn_cast<InputAction>(A)) { 4885 // FIXME: It would be nice to not claim this here; maybe the old scheme of 4886 // just using Args was better? 4887 const Arg &Input = IA->getInputArg(); 4888 Input.claim(); 4889 if (Input.getOption().matches(options::OPT_INPUT)) { 4890 const char *Name = Input.getValue(); 4891 return {InputInfo(A, Name, /* _BaseInput = */ Name)}; 4892 } 4893 return {InputInfo(A, &Input, /* _BaseInput = */ "")}; 4894 } 4895 4896 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) { 4897 const ToolChain *TC; 4898 StringRef ArchName = BAA->getArchName(); 4899 4900 if (!ArchName.empty()) 4901 TC = &getToolChain(C.getArgs(), 4902 computeTargetTriple(*this, TargetTriple, 4903 C.getArgs(), ArchName)); 4904 else 4905 TC = &C.getDefaultToolChain(); 4906 4907 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel, 4908 MultipleArchs, LinkingOutput, CachedResults, 4909 TargetDeviceOffloadKind); 4910 } 4911 4912 4913 ActionList Inputs = A->getInputs(); 4914 4915 const JobAction *JA = cast<JobAction>(A); 4916 ActionList CollapsedOffloadActions; 4917 4918 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(), 4919 embedBitcodeInObject() && !isUsingLTO()); 4920 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions); 4921 4922 if (!T) 4923 return {InputInfo()}; 4924 4925 if (BuildingForOffloadDevice && 4926 A->getOffloadingDeviceKind() == Action::OFK_OpenMP) { 4927 if (TC->getTriple().isAMDGCN()) { 4928 // AMDGCN treats backend and assemble actions as no-op because 4929 // linker does not support object files. 4930 if (const BackendJobAction *BA = dyn_cast<BackendJobAction>(A)) { 4931 return BuildJobsForAction(C, *BA->input_begin(), TC, BoundArch, 4932 AtTopLevel, MultipleArchs, LinkingOutput, 4933 CachedResults, TargetDeviceOffloadKind); 4934 } 4935 4936 if (const AssembleJobAction *AA = dyn_cast<AssembleJobAction>(A)) { 4937 return BuildJobsForAction(C, *AA->input_begin(), TC, BoundArch, 4938 AtTopLevel, MultipleArchs, LinkingOutput, 4939 CachedResults, TargetDeviceOffloadKind); 4940 } 4941 } 4942 } 4943 4944 // If we've collapsed action list that contained OffloadAction we 4945 // need to build jobs for host/device-side inputs it may have held. 4946 for (const auto *OA : CollapsedOffloadActions) 4947 cast<OffloadAction>(OA)->doOnEachDependence( 4948 /*IsHostDependence=*/BuildingForOffloadDevice, 4949 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { 4950 OffloadDependencesInputInfo.append(BuildJobsForAction( 4951 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false, 4952 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults, 4953 DepA->getOffloadingDeviceKind())); 4954 }); 4955 4956 // Only use pipes when there is exactly one input. 4957 InputInfoList InputInfos; 4958 for (const Action *Input : Inputs) { 4959 // Treat dsymutil and verify sub-jobs as being at the top-level too, they 4960 // shouldn't get temporary output names. 4961 // FIXME: Clean this up. 4962 bool SubJobAtTopLevel = 4963 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A)); 4964 InputInfos.append(BuildJobsForAction( 4965 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput, 4966 CachedResults, A->getOffloadingDeviceKind())); 4967 } 4968 4969 // Always use the first file input as the base input. 4970 const char *BaseInput = InputInfos[0].getBaseInput(); 4971 for (auto &Info : InputInfos) { 4972 if (Info.isFilename()) { 4973 BaseInput = Info.getBaseInput(); 4974 break; 4975 } 4976 } 4977 4978 // ... except dsymutil actions, which use their actual input as the base 4979 // input. 4980 if (JA->getType() == types::TY_dSYM) 4981 BaseInput = InputInfos[0].getFilename(); 4982 4983 // ... and in header module compilations, which use the module name. 4984 if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA)) 4985 BaseInput = ModuleJA->getModuleName(); 4986 4987 // Append outputs of offload device jobs to the input list 4988 if (!OffloadDependencesInputInfo.empty()) 4989 InputInfos.append(OffloadDependencesInputInfo.begin(), 4990 OffloadDependencesInputInfo.end()); 4991 4992 // Set the effective triple of the toolchain for the duration of this job. 4993 llvm::Triple EffectiveTriple; 4994 const ToolChain &ToolTC = T->getToolChain(); 4995 const ArgList &Args = 4996 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind()); 4997 if (InputInfos.size() != 1) { 4998 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args)); 4999 } else { 5000 // Pass along the input type if it can be unambiguously determined. 5001 EffectiveTriple = llvm::Triple( 5002 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType())); 5003 } 5004 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple); 5005 5006 // Determine the place to write output to, if any. 5007 InputInfo Result; 5008 InputInfoList UnbundlingResults; 5009 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) { 5010 // If we have an unbundling job, we need to create results for all the 5011 // outputs. We also update the results cache so that other actions using 5012 // this unbundling action can get the right results. 5013 for (auto &UI : UA->getDependentActionsInfo()) { 5014 assert(UI.DependentOffloadKind != Action::OFK_None && 5015 "Unbundling with no offloading??"); 5016 5017 // Unbundling actions are never at the top level. When we generate the 5018 // offloading prefix, we also do that for the host file because the 5019 // unbundling action does not change the type of the output which can 5020 // cause a overwrite. 5021 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix( 5022 UI.DependentOffloadKind, 5023 UI.DependentToolChain->getTriple().normalize(), 5024 /*CreatePrefixForHost=*/true); 5025 auto CurI = InputInfo( 5026 UA, 5027 GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch, 5028 /*AtTopLevel=*/false, 5029 MultipleArchs || 5030 UI.DependentOffloadKind == Action::OFK_HIP, 5031 OffloadingPrefix), 5032 BaseInput); 5033 // Save the unbundling result. 5034 UnbundlingResults.push_back(CurI); 5035 5036 // Get the unique string identifier for this dependence and cache the 5037 // result. 5038 StringRef Arch; 5039 if (TargetDeviceOffloadKind == Action::OFK_HIP) { 5040 if (UI.DependentOffloadKind == Action::OFK_Host) 5041 Arch = StringRef(); 5042 else 5043 Arch = UI.DependentBoundArch; 5044 } else 5045 Arch = BoundArch; 5046 5047 CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch, 5048 UI.DependentOffloadKind)}] = { 5049 CurI}; 5050 } 5051 5052 // Now that we have all the results generated, select the one that should be 5053 // returned for the current depending action. 5054 std::pair<const Action *, std::string> ActionTC = { 5055 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)}; 5056 assert(CachedResults.find(ActionTC) != CachedResults.end() && 5057 "Result does not exist??"); 5058 Result = CachedResults[ActionTC].front(); 5059 } else if (JA->getType() == types::TY_Nothing) 5060 Result = {InputInfo(A, BaseInput)}; 5061 else { 5062 // We only have to generate a prefix for the host if this is not a top-level 5063 // action. 5064 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix( 5065 A->getOffloadingDeviceKind(), TC->getTriple().normalize(), 5066 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() && 5067 !AtTopLevel); 5068 if (isa<OffloadWrapperJobAction>(JA)) { 5069 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) 5070 BaseInput = FinalOutput->getValue(); 5071 else 5072 BaseInput = getDefaultImageName(); 5073 BaseInput = 5074 C.getArgs().MakeArgString(std::string(BaseInput) + "-wrapper"); 5075 } 5076 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch, 5077 AtTopLevel, MultipleArchs, 5078 OffloadingPrefix), 5079 BaseInput); 5080 } 5081 5082 if (CCCPrintBindings && !CCGenDiagnostics) { 5083 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"' 5084 << " - \"" << T->getName() << "\", inputs: ["; 5085 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) { 5086 llvm::errs() << InputInfos[i].getAsString(); 5087 if (i + 1 != e) 5088 llvm::errs() << ", "; 5089 } 5090 if (UnbundlingResults.empty()) 5091 llvm::errs() << "], output: " << Result.getAsString() << "\n"; 5092 else { 5093 llvm::errs() << "], outputs: ["; 5094 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) { 5095 llvm::errs() << UnbundlingResults[i].getAsString(); 5096 if (i + 1 != e) 5097 llvm::errs() << ", "; 5098 } 5099 llvm::errs() << "] \n"; 5100 } 5101 } else { 5102 if (UnbundlingResults.empty()) 5103 T->ConstructJob( 5104 C, *JA, Result, InputInfos, 5105 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()), 5106 LinkingOutput); 5107 else 5108 T->ConstructJobMultipleOutputs( 5109 C, *JA, UnbundlingResults, InputInfos, 5110 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()), 5111 LinkingOutput); 5112 } 5113 return {Result}; 5114 } 5115 5116 const char *Driver::getDefaultImageName() const { 5117 llvm::Triple Target(llvm::Triple::normalize(TargetTriple)); 5118 return Target.isOSWindows() ? "a.exe" : "a.out"; 5119 } 5120 5121 /// Create output filename based on ArgValue, which could either be a 5122 /// full filename, filename without extension, or a directory. If ArgValue 5123 /// does not provide a filename, then use BaseName, and use the extension 5124 /// suitable for FileType. 5125 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue, 5126 StringRef BaseName, 5127 types::ID FileType) { 5128 SmallString<128> Filename = ArgValue; 5129 5130 if (ArgValue.empty()) { 5131 // If the argument is empty, output to BaseName in the current dir. 5132 Filename = BaseName; 5133 } else if (llvm::sys::path::is_separator(Filename.back())) { 5134 // If the argument is a directory, output to BaseName in that dir. 5135 llvm::sys::path::append(Filename, BaseName); 5136 } 5137 5138 if (!llvm::sys::path::has_extension(ArgValue)) { 5139 // If the argument didn't provide an extension, then set it. 5140 const char *Extension = types::getTypeTempSuffix(FileType, true); 5141 5142 if (FileType == types::TY_Image && 5143 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) { 5144 // The output file is a dll. 5145 Extension = "dll"; 5146 } 5147 5148 llvm::sys::path::replace_extension(Filename, Extension); 5149 } 5150 5151 return Args.MakeArgString(Filename.c_str()); 5152 } 5153 5154 static bool HasPreprocessOutput(const Action &JA) { 5155 if (isa<PreprocessJobAction>(JA)) 5156 return true; 5157 if (isa<OffloadAction>(JA) && isa<PreprocessJobAction>(JA.getInputs()[0])) 5158 return true; 5159 if (isa<OffloadBundlingJobAction>(JA) && 5160 HasPreprocessOutput(*(JA.getInputs()[0]))) 5161 return true; 5162 return false; 5163 } 5164 5165 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA, 5166 const char *BaseInput, 5167 StringRef OrigBoundArch, bool AtTopLevel, 5168 bool MultipleArchs, 5169 StringRef OffloadingPrefix) const { 5170 std::string BoundArch = OrigBoundArch.str(); 5171 if (is_style_windows(llvm::sys::path::Style::native)) { 5172 // BoundArch may contains ':', which is invalid in file names on Windows, 5173 // therefore replace it with '%'. 5174 std::replace(BoundArch.begin(), BoundArch.end(), ':', '@'); 5175 } 5176 5177 llvm::PrettyStackTraceString CrashInfo("Computing output path"); 5178 // Output to a user requested destination? 5179 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) { 5180 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) 5181 return C.addResultFile(FinalOutput->getValue(), &JA); 5182 } 5183 5184 // For /P, preprocess to file named after BaseInput. 5185 if (C.getArgs().hasArg(options::OPT__SLASH_P)) { 5186 assert(AtTopLevel && isa<PreprocessJobAction>(JA)); 5187 StringRef BaseName = llvm::sys::path::filename(BaseInput); 5188 StringRef NameArg; 5189 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi)) 5190 NameArg = A->getValue(); 5191 return C.addResultFile( 5192 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C), 5193 &JA); 5194 } 5195 5196 // Default to writing to stdout? 5197 if (AtTopLevel && !CCGenDiagnostics && HasPreprocessOutput(JA)) { 5198 return "-"; 5199 } 5200 5201 if (JA.getType() == types::TY_ModuleFile && 5202 C.getArgs().getLastArg(options::OPT_module_file_info)) { 5203 return "-"; 5204 } 5205 5206 // Is this the assembly listing for /FA? 5207 if (JA.getType() == types::TY_PP_Asm && 5208 (C.getArgs().hasArg(options::OPT__SLASH_FA) || 5209 C.getArgs().hasArg(options::OPT__SLASH_Fa))) { 5210 // Use /Fa and the input filename to determine the asm file name. 5211 StringRef BaseName = llvm::sys::path::filename(BaseInput); 5212 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa); 5213 return C.addResultFile( 5214 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()), 5215 &JA); 5216 } 5217 5218 // Output to a temporary file? 5219 if ((!AtTopLevel && !isSaveTempsEnabled() && 5220 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) || 5221 CCGenDiagnostics) { 5222 StringRef Name = llvm::sys::path::filename(BaseInput); 5223 std::pair<StringRef, StringRef> Split = Name.split('.'); 5224 SmallString<128> TmpName; 5225 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode()); 5226 Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir); 5227 if (CCGenDiagnostics && A) { 5228 SmallString<128> CrashDirectory(A->getValue()); 5229 if (!getVFS().exists(CrashDirectory)) 5230 llvm::sys::fs::create_directories(CrashDirectory); 5231 llvm::sys::path::append(CrashDirectory, Split.first); 5232 const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%"; 5233 std::error_code EC = llvm::sys::fs::createUniqueFile( 5234 CrashDirectory + Middle + Suffix, TmpName); 5235 if (EC) { 5236 Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 5237 return ""; 5238 } 5239 } else { 5240 if (MultipleArchs && !BoundArch.empty()) { 5241 TmpName = GetTemporaryDirectory(Split.first); 5242 llvm::sys::path::append(TmpName, 5243 Split.first + "-" + BoundArch + "." + Suffix); 5244 } else { 5245 TmpName = GetTemporaryPath(Split.first, Suffix); 5246 } 5247 } 5248 return C.addTempFile(C.getArgs().MakeArgString(TmpName)); 5249 } 5250 5251 SmallString<128> BasePath(BaseInput); 5252 SmallString<128> ExternalPath(""); 5253 StringRef BaseName; 5254 5255 // Dsymutil actions should use the full path. 5256 if (isa<DsymutilJobAction>(JA) && C.getArgs().hasArg(options::OPT_dsym_dir)) { 5257 ExternalPath += C.getArgs().getLastArg(options::OPT_dsym_dir)->getValue(); 5258 // We use posix style here because the tests (specifically 5259 // darwin-dsymutil.c) demonstrate that posix style paths are acceptable 5260 // even on Windows and if we don't then the similar test covering this 5261 // fails. 5262 llvm::sys::path::append(ExternalPath, llvm::sys::path::Style::posix, 5263 llvm::sys::path::filename(BasePath)); 5264 BaseName = ExternalPath; 5265 } else if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA)) 5266 BaseName = BasePath; 5267 else 5268 BaseName = llvm::sys::path::filename(BasePath); 5269 5270 // Determine what the derived output name should be. 5271 const char *NamedOutput; 5272 5273 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) && 5274 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) { 5275 // The /Fo or /o flag decides the object filename. 5276 StringRef Val = 5277 C.getArgs() 5278 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o) 5279 ->getValue(); 5280 NamedOutput = 5281 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object); 5282 } else if (JA.getType() == types::TY_Image && 5283 C.getArgs().hasArg(options::OPT__SLASH_Fe, 5284 options::OPT__SLASH_o)) { 5285 // The /Fe or /o flag names the linked file. 5286 StringRef Val = 5287 C.getArgs() 5288 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o) 5289 ->getValue(); 5290 NamedOutput = 5291 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image); 5292 } else if (JA.getType() == types::TY_Image) { 5293 if (IsCLMode()) { 5294 // clang-cl uses BaseName for the executable name. 5295 NamedOutput = 5296 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image); 5297 } else { 5298 SmallString<128> Output(getDefaultImageName()); 5299 // HIP image for device compilation with -fno-gpu-rdc is per compilation 5300 // unit. 5301 bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP && 5302 !C.getArgs().hasFlag(options::OPT_fgpu_rdc, 5303 options::OPT_fno_gpu_rdc, false); 5304 if (IsHIPNoRDC) { 5305 Output = BaseName; 5306 llvm::sys::path::replace_extension(Output, ""); 5307 } 5308 Output += OffloadingPrefix; 5309 if (MultipleArchs && !BoundArch.empty()) { 5310 Output += "-"; 5311 Output.append(BoundArch); 5312 } 5313 if (IsHIPNoRDC) 5314 Output += ".out"; 5315 NamedOutput = C.getArgs().MakeArgString(Output.c_str()); 5316 } 5317 } else if (JA.getType() == types::TY_PCH && IsCLMode()) { 5318 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName)); 5319 } else { 5320 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode()); 5321 assert(Suffix && "All types used for output should have a suffix."); 5322 5323 std::string::size_type End = std::string::npos; 5324 if (!types::appendSuffixForType(JA.getType())) 5325 End = BaseName.rfind('.'); 5326 SmallString<128> Suffixed(BaseName.substr(0, End)); 5327 Suffixed += OffloadingPrefix; 5328 if (MultipleArchs && !BoundArch.empty()) { 5329 Suffixed += "-"; 5330 Suffixed.append(BoundArch); 5331 } 5332 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for 5333 // the unoptimized bitcode so that it does not get overwritten by the ".bc" 5334 // optimized bitcode output. 5335 auto IsHIPRDCInCompilePhase = [](const JobAction &JA, 5336 const llvm::opt::DerivedArgList &Args) { 5337 // The relocatable compilation in HIP implies -emit-llvm. Similarly, use a 5338 // ".tmp.bc" suffix for the unoptimized bitcode (generated in the compile 5339 // phase.) 5340 return isa<CompileJobAction>(JA) && 5341 JA.getOffloadingDeviceKind() == Action::OFK_HIP && 5342 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, 5343 false); 5344 }; 5345 if (!AtTopLevel && JA.getType() == types::TY_LLVM_BC && 5346 (C.getArgs().hasArg(options::OPT_emit_llvm) || 5347 IsHIPRDCInCompilePhase(JA, C.getArgs()))) 5348 Suffixed += ".tmp"; 5349 Suffixed += '.'; 5350 Suffixed += Suffix; 5351 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str()); 5352 } 5353 5354 // Prepend object file path if -save-temps=obj 5355 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) && 5356 JA.getType() != types::TY_PCH) { 5357 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 5358 SmallString<128> TempPath(FinalOutput->getValue()); 5359 llvm::sys::path::remove_filename(TempPath); 5360 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput); 5361 llvm::sys::path::append(TempPath, OutputFileName); 5362 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str()); 5363 } 5364 5365 // If we're saving temps and the temp file conflicts with the input file, 5366 // then avoid overwriting input file. 5367 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) { 5368 bool SameFile = false; 5369 SmallString<256> Result; 5370 llvm::sys::fs::current_path(Result); 5371 llvm::sys::path::append(Result, BaseName); 5372 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile); 5373 // Must share the same path to conflict. 5374 if (SameFile) { 5375 StringRef Name = llvm::sys::path::filename(BaseInput); 5376 std::pair<StringRef, StringRef> Split = Name.split('.'); 5377 std::string TmpName = GetTemporaryPath( 5378 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode())); 5379 return C.addTempFile(C.getArgs().MakeArgString(TmpName)); 5380 } 5381 } 5382 5383 // As an annoying special case, PCH generation doesn't strip the pathname. 5384 if (JA.getType() == types::TY_PCH && !IsCLMode()) { 5385 llvm::sys::path::remove_filename(BasePath); 5386 if (BasePath.empty()) 5387 BasePath = NamedOutput; 5388 else 5389 llvm::sys::path::append(BasePath, NamedOutput); 5390 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA); 5391 } else { 5392 return C.addResultFile(NamedOutput, &JA); 5393 } 5394 } 5395 5396 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const { 5397 // Search for Name in a list of paths. 5398 auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P) 5399 -> llvm::Optional<std::string> { 5400 // Respect a limited subset of the '-Bprefix' functionality in GCC by 5401 // attempting to use this prefix when looking for file paths. 5402 for (const auto &Dir : P) { 5403 if (Dir.empty()) 5404 continue; 5405 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir); 5406 llvm::sys::path::append(P, Name); 5407 if (llvm::sys::fs::exists(Twine(P))) 5408 return std::string(P); 5409 } 5410 return None; 5411 }; 5412 5413 if (auto P = SearchPaths(PrefixDirs)) 5414 return *P; 5415 5416 SmallString<128> R(ResourceDir); 5417 llvm::sys::path::append(R, Name); 5418 if (llvm::sys::fs::exists(Twine(R))) 5419 return std::string(R.str()); 5420 5421 SmallString<128> P(TC.getCompilerRTPath()); 5422 llvm::sys::path::append(P, Name); 5423 if (llvm::sys::fs::exists(Twine(P))) 5424 return std::string(P.str()); 5425 5426 SmallString<128> D(Dir); 5427 llvm::sys::path::append(D, "..", Name); 5428 if (llvm::sys::fs::exists(Twine(D))) 5429 return std::string(D.str()); 5430 5431 if (auto P = SearchPaths(TC.getLibraryPaths())) 5432 return *P; 5433 5434 if (auto P = SearchPaths(TC.getFilePaths())) 5435 return *P; 5436 5437 return std::string(Name); 5438 } 5439 5440 void Driver::generatePrefixedToolNames( 5441 StringRef Tool, const ToolChain &TC, 5442 SmallVectorImpl<std::string> &Names) const { 5443 // FIXME: Needs a better variable than TargetTriple 5444 Names.emplace_back((TargetTriple + "-" + Tool).str()); 5445 Names.emplace_back(Tool); 5446 } 5447 5448 static bool ScanDirForExecutable(SmallString<128> &Dir, StringRef Name) { 5449 llvm::sys::path::append(Dir, Name); 5450 if (llvm::sys::fs::can_execute(Twine(Dir))) 5451 return true; 5452 llvm::sys::path::remove_filename(Dir); 5453 return false; 5454 } 5455 5456 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const { 5457 SmallVector<std::string, 2> TargetSpecificExecutables; 5458 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables); 5459 5460 // Respect a limited subset of the '-Bprefix' functionality in GCC by 5461 // attempting to use this prefix when looking for program paths. 5462 for (const auto &PrefixDir : PrefixDirs) { 5463 if (llvm::sys::fs::is_directory(PrefixDir)) { 5464 SmallString<128> P(PrefixDir); 5465 if (ScanDirForExecutable(P, Name)) 5466 return std::string(P.str()); 5467 } else { 5468 SmallString<128> P((PrefixDir + Name).str()); 5469 if (llvm::sys::fs::can_execute(Twine(P))) 5470 return std::string(P.str()); 5471 } 5472 } 5473 5474 const ToolChain::path_list &List = TC.getProgramPaths(); 5475 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) { 5476 // For each possible name of the tool look for it in 5477 // program paths first, then the path. 5478 // Higher priority names will be first, meaning that 5479 // a higher priority name in the path will be found 5480 // instead of a lower priority name in the program path. 5481 // E.g. <triple>-gcc on the path will be found instead 5482 // of gcc in the program path 5483 for (const auto &Path : List) { 5484 SmallString<128> P(Path); 5485 if (ScanDirForExecutable(P, TargetSpecificExecutable)) 5486 return std::string(P.str()); 5487 } 5488 5489 // Fall back to the path 5490 if (llvm::ErrorOr<std::string> P = 5491 llvm::sys::findProgramByName(TargetSpecificExecutable)) 5492 return *P; 5493 } 5494 5495 return std::string(Name); 5496 } 5497 5498 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const { 5499 SmallString<128> Path; 5500 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path); 5501 if (EC) { 5502 Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 5503 return ""; 5504 } 5505 5506 return std::string(Path.str()); 5507 } 5508 5509 std::string Driver::GetTemporaryDirectory(StringRef Prefix) const { 5510 SmallString<128> Path; 5511 std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path); 5512 if (EC) { 5513 Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 5514 return ""; 5515 } 5516 5517 return std::string(Path.str()); 5518 } 5519 5520 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const { 5521 SmallString<128> Output; 5522 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) { 5523 // FIXME: If anybody needs it, implement this obscure rule: 5524 // "If you specify a directory without a file name, the default file name 5525 // is VCx0.pch., where x is the major version of Visual C++ in use." 5526 Output = FpArg->getValue(); 5527 5528 // "If you do not specify an extension as part of the path name, an 5529 // extension of .pch is assumed. " 5530 if (!llvm::sys::path::has_extension(Output)) 5531 Output += ".pch"; 5532 } else { 5533 if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc)) 5534 Output = YcArg->getValue(); 5535 if (Output.empty()) 5536 Output = BaseName; 5537 llvm::sys::path::replace_extension(Output, ".pch"); 5538 } 5539 return std::string(Output.str()); 5540 } 5541 5542 const ToolChain &Driver::getToolChain(const ArgList &Args, 5543 const llvm::Triple &Target) const { 5544 5545 auto &TC = ToolChains[Target.str()]; 5546 if (!TC) { 5547 switch (Target.getOS()) { 5548 case llvm::Triple::AIX: 5549 TC = std::make_unique<toolchains::AIX>(*this, Target, Args); 5550 break; 5551 case llvm::Triple::Haiku: 5552 TC = std::make_unique<toolchains::Haiku>(*this, Target, Args); 5553 break; 5554 case llvm::Triple::Ananas: 5555 TC = std::make_unique<toolchains::Ananas>(*this, Target, Args); 5556 break; 5557 case llvm::Triple::CloudABI: 5558 TC = std::make_unique<toolchains::CloudABI>(*this, Target, Args); 5559 break; 5560 case llvm::Triple::Darwin: 5561 case llvm::Triple::MacOSX: 5562 case llvm::Triple::IOS: 5563 case llvm::Triple::TvOS: 5564 case llvm::Triple::WatchOS: 5565 TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args); 5566 break; 5567 case llvm::Triple::DragonFly: 5568 TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args); 5569 break; 5570 case llvm::Triple::OpenBSD: 5571 TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args); 5572 break; 5573 case llvm::Triple::NetBSD: 5574 TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args); 5575 break; 5576 case llvm::Triple::FreeBSD: 5577 if (Target.isPPC()) 5578 TC = std::make_unique<toolchains::PPCFreeBSDToolChain>(*this, Target, 5579 Args); 5580 else 5581 TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args); 5582 break; 5583 case llvm::Triple::Minix: 5584 TC = std::make_unique<toolchains::Minix>(*this, Target, Args); 5585 break; 5586 case llvm::Triple::Linux: 5587 case llvm::Triple::ELFIAMCU: 5588 if (Target.getArch() == llvm::Triple::hexagon) 5589 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target, 5590 Args); 5591 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) && 5592 !Target.hasEnvironment()) 5593 TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target, 5594 Args); 5595 else if (Target.isPPC()) 5596 TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target, 5597 Args); 5598 else if (Target.getArch() == llvm::Triple::ve) 5599 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args); 5600 5601 else 5602 TC = std::make_unique<toolchains::Linux>(*this, Target, Args); 5603 break; 5604 case llvm::Triple::NaCl: 5605 TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args); 5606 break; 5607 case llvm::Triple::Fuchsia: 5608 TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args); 5609 break; 5610 case llvm::Triple::Solaris: 5611 TC = std::make_unique<toolchains::Solaris>(*this, Target, Args); 5612 break; 5613 case llvm::Triple::AMDHSA: 5614 TC = std::make_unique<toolchains::ROCMToolChain>(*this, Target, Args); 5615 break; 5616 case llvm::Triple::AMDPAL: 5617 case llvm::Triple::Mesa3D: 5618 TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args); 5619 break; 5620 case llvm::Triple::Win32: 5621 switch (Target.getEnvironment()) { 5622 default: 5623 if (Target.isOSBinFormatELF()) 5624 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args); 5625 else if (Target.isOSBinFormatMachO()) 5626 TC = std::make_unique<toolchains::MachO>(*this, Target, Args); 5627 else 5628 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args); 5629 break; 5630 case llvm::Triple::GNU: 5631 TC = std::make_unique<toolchains::MinGW>(*this, Target, Args); 5632 break; 5633 case llvm::Triple::Itanium: 5634 TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target, 5635 Args); 5636 break; 5637 case llvm::Triple::MSVC: 5638 case llvm::Triple::UnknownEnvironment: 5639 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ) 5640 .startswith_insensitive("bfd")) 5641 TC = std::make_unique<toolchains::CrossWindowsToolChain>( 5642 *this, Target, Args); 5643 else 5644 TC = 5645 std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args); 5646 break; 5647 } 5648 break; 5649 case llvm::Triple::PS4: 5650 TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args); 5651 break; 5652 case llvm::Triple::Contiki: 5653 TC = std::make_unique<toolchains::Contiki>(*this, Target, Args); 5654 break; 5655 case llvm::Triple::Hurd: 5656 TC = std::make_unique<toolchains::Hurd>(*this, Target, Args); 5657 break; 5658 case llvm::Triple::ZOS: 5659 TC = std::make_unique<toolchains::ZOS>(*this, Target, Args); 5660 break; 5661 default: 5662 // Of these targets, Hexagon is the only one that might have 5663 // an OS of Linux, in which case it got handled above already. 5664 switch (Target.getArch()) { 5665 case llvm::Triple::tce: 5666 TC = std::make_unique<toolchains::TCEToolChain>(*this, Target, Args); 5667 break; 5668 case llvm::Triple::tcele: 5669 TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args); 5670 break; 5671 case llvm::Triple::hexagon: 5672 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target, 5673 Args); 5674 break; 5675 case llvm::Triple::lanai: 5676 TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args); 5677 break; 5678 case llvm::Triple::xcore: 5679 TC = std::make_unique<toolchains::XCoreToolChain>(*this, Target, Args); 5680 break; 5681 case llvm::Triple::wasm32: 5682 case llvm::Triple::wasm64: 5683 TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args); 5684 break; 5685 case llvm::Triple::avr: 5686 TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args); 5687 break; 5688 case llvm::Triple::msp430: 5689 TC = 5690 std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args); 5691 break; 5692 case llvm::Triple::riscv32: 5693 case llvm::Triple::riscv64: 5694 if (toolchains::RISCVToolChain::hasGCCToolchain(*this, Args)) 5695 TC = 5696 std::make_unique<toolchains::RISCVToolChain>(*this, Target, Args); 5697 else 5698 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args); 5699 break; 5700 case llvm::Triple::ve: 5701 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args); 5702 break; 5703 case llvm::Triple::spirv32: 5704 case llvm::Triple::spirv64: 5705 TC = std::make_unique<toolchains::SPIRVToolChain>(*this, Target, Args); 5706 break; 5707 default: 5708 if (Target.getVendor() == llvm::Triple::Myriad) 5709 TC = std::make_unique<toolchains::MyriadToolChain>(*this, Target, 5710 Args); 5711 else if (toolchains::BareMetal::handlesTarget(Target)) 5712 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args); 5713 else if (Target.isOSBinFormatELF()) 5714 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args); 5715 else if (Target.isOSBinFormatMachO()) 5716 TC = std::make_unique<toolchains::MachO>(*this, Target, Args); 5717 else 5718 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args); 5719 } 5720 } 5721 } 5722 5723 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA 5724 // compiles always need two toolchains, the CUDA toolchain and the host 5725 // toolchain. So the only valid way to create a CUDA toolchain is via 5726 // CreateOffloadingDeviceToolChains. 5727 5728 return *TC; 5729 } 5730 5731 const ToolChain &Driver::getOffloadingDeviceToolChain( 5732 const ArgList &Args, const llvm::Triple &Target, const ToolChain &HostTC, 5733 const Action::OffloadKind &TargetDeviceOffloadKind) const { 5734 // Use device / host triples as the key into the ToolChains map because the 5735 // device ToolChain we create depends on both. 5736 auto &TC = ToolChains[Target.str() + "/" + HostTC.getTriple().str()]; 5737 if (!TC) { 5738 // Categorized by offload kind > arch rather than OS > arch like 5739 // the normal getToolChain call, as it seems a reasonable way to categorize 5740 // things. 5741 switch (TargetDeviceOffloadKind) { 5742 case Action::OFK_HIP: { 5743 if (Target.getArch() == llvm::Triple::amdgcn && 5744 Target.getVendor() == llvm::Triple::AMD && 5745 Target.getOS() == llvm::Triple::AMDHSA) 5746 TC = std::make_unique<toolchains::HIPAMDToolChain>(*this, Target, 5747 HostTC, Args); 5748 else if (Target.getArch() == llvm::Triple::spirv64 && 5749 Target.getVendor() == llvm::Triple::UnknownVendor && 5750 Target.getOS() == llvm::Triple::UnknownOS) 5751 TC = std::make_unique<toolchains::HIPSPVToolChain>(*this, Target, 5752 HostTC, Args); 5753 break; 5754 } 5755 default: 5756 break; 5757 } 5758 } 5759 5760 return *TC; 5761 } 5762 5763 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const { 5764 // Say "no" if there is not exactly one input of a type clang understands. 5765 if (JA.size() != 1 || 5766 !types::isAcceptedByClang((*JA.input_begin())->getType())) 5767 return false; 5768 5769 // And say "no" if this is not a kind of action clang understands. 5770 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) && 5771 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA)) 5772 return false; 5773 5774 return true; 5775 } 5776 5777 bool Driver::ShouldUseFlangCompiler(const JobAction &JA) const { 5778 // Say "no" if there is not exactly one input of a type flang understands. 5779 if (JA.size() != 1 || 5780 !types::isFortran((*JA.input_begin())->getType())) 5781 return false; 5782 5783 // And say "no" if this is not a kind of action flang understands. 5784 if (!isa<PreprocessJobAction>(JA) && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA)) 5785 return false; 5786 5787 return true; 5788 } 5789 5790 bool Driver::ShouldEmitStaticLibrary(const ArgList &Args) const { 5791 // Only emit static library if the flag is set explicitly. 5792 if (Args.hasArg(options::OPT_emit_static_lib)) 5793 return true; 5794 return false; 5795 } 5796 5797 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the 5798 /// grouped values as integers. Numbers which are not provided are set to 0. 5799 /// 5800 /// \return True if the entire string was parsed (9.2), or all groups were 5801 /// parsed (10.3.5extrastuff). 5802 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor, 5803 unsigned &Micro, bool &HadExtra) { 5804 HadExtra = false; 5805 5806 Major = Minor = Micro = 0; 5807 if (Str.empty()) 5808 return false; 5809 5810 if (Str.consumeInteger(10, Major)) 5811 return false; 5812 if (Str.empty()) 5813 return true; 5814 if (Str[0] != '.') 5815 return false; 5816 5817 Str = Str.drop_front(1); 5818 5819 if (Str.consumeInteger(10, Minor)) 5820 return false; 5821 if (Str.empty()) 5822 return true; 5823 if (Str[0] != '.') 5824 return false; 5825 Str = Str.drop_front(1); 5826 5827 if (Str.consumeInteger(10, Micro)) 5828 return false; 5829 if (!Str.empty()) 5830 HadExtra = true; 5831 return true; 5832 } 5833 5834 /// Parse digits from a string \p Str and fulfill \p Digits with 5835 /// the parsed numbers. This method assumes that the max number of 5836 /// digits to look for is equal to Digits.size(). 5837 /// 5838 /// \return True if the entire string was parsed and there are 5839 /// no extra characters remaining at the end. 5840 bool Driver::GetReleaseVersion(StringRef Str, 5841 MutableArrayRef<unsigned> Digits) { 5842 if (Str.empty()) 5843 return false; 5844 5845 unsigned CurDigit = 0; 5846 while (CurDigit < Digits.size()) { 5847 unsigned Digit; 5848 if (Str.consumeInteger(10, Digit)) 5849 return false; 5850 Digits[CurDigit] = Digit; 5851 if (Str.empty()) 5852 return true; 5853 if (Str[0] != '.') 5854 return false; 5855 Str = Str.drop_front(1); 5856 CurDigit++; 5857 } 5858 5859 // More digits than requested, bail out... 5860 return false; 5861 } 5862 5863 std::pair<unsigned, unsigned> 5864 Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const { 5865 unsigned IncludedFlagsBitmask = 0; 5866 unsigned ExcludedFlagsBitmask = options::NoDriverOption; 5867 5868 if (IsClCompatMode) { 5869 // Include CL and Core options. 5870 IncludedFlagsBitmask |= options::CLOption; 5871 IncludedFlagsBitmask |= options::CoreOption; 5872 } else { 5873 ExcludedFlagsBitmask |= options::CLOption; 5874 } 5875 5876 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask); 5877 } 5878 5879 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) { 5880 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false); 5881 } 5882 5883 bool clang::driver::willEmitRemarks(const ArgList &Args) { 5884 // -fsave-optimization-record enables it. 5885 if (Args.hasFlag(options::OPT_fsave_optimization_record, 5886 options::OPT_fno_save_optimization_record, false)) 5887 return true; 5888 5889 // -fsave-optimization-record=<format> enables it as well. 5890 if (Args.hasFlag(options::OPT_fsave_optimization_record_EQ, 5891 options::OPT_fno_save_optimization_record, false)) 5892 return true; 5893 5894 // -foptimization-record-file alone enables it too. 5895 if (Args.hasFlag(options::OPT_foptimization_record_file_EQ, 5896 options::OPT_fno_save_optimization_record, false)) 5897 return true; 5898 5899 // -foptimization-record-passes alone enables it too. 5900 if (Args.hasFlag(options::OPT_foptimization_record_passes_EQ, 5901 options::OPT_fno_save_optimization_record, false)) 5902 return true; 5903 return false; 5904 } 5905 5906 llvm::StringRef clang::driver::getDriverMode(StringRef ProgName, 5907 ArrayRef<const char *> Args) { 5908 static const std::string OptName = 5909 getDriverOptTable().getOption(options::OPT_driver_mode).getPrefixedName(); 5910 llvm::StringRef Opt; 5911 for (StringRef Arg : Args) { 5912 if (!Arg.startswith(OptName)) 5913 continue; 5914 Opt = Arg; 5915 } 5916 if (Opt.empty()) 5917 Opt = ToolChain::getTargetAndModeFromProgramName(ProgName).DriverMode; 5918 return Opt.consume_front(OptName) ? Opt : ""; 5919 } 5920 5921 bool driver::IsClangCL(StringRef DriverMode) { return DriverMode.equals("cl"); } 5922