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