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