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