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