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