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