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