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