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