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 (TypoCorrect) { 2134 // Check if the filename is a typo for an option flag. OptTable thinks 2135 // that all args that are not known options and that start with / are 2136 // filenames, but e.g. `/diagnostic:caret` is more likely a typo for 2137 // the option `/diagnostics:caret` than a reference to a file in the root 2138 // directory. 2139 unsigned IncludedFlagsBitmask; 2140 unsigned ExcludedFlagsBitmask; 2141 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) = 2142 getIncludeExcludeOptionFlagMasks(IsCLMode()); 2143 std::string Nearest; 2144 if (getOpts().findNearest(Value, Nearest, IncludedFlagsBitmask, 2145 ExcludedFlagsBitmask) <= 1) { 2146 Diag(clang::diag::err_drv_no_such_file_with_suggestion) 2147 << Value << Nearest; 2148 return false; 2149 } 2150 } 2151 2152 // Don't error on apparently non-existent linker inputs, because they 2153 // can be influenced by linker flags the clang driver might not understand. 2154 // Examples: 2155 // - `clang -fuse-ld=lld -Wl,--chroot,some/dir /file.o` will make lld look 2156 // for some/dir/file.o 2157 // - `clang-cl main.cc ole32.lib` in a a non-MSVC shell will make the driver 2158 // module look for an MSVC installation in the registry. (We could ask 2159 // the MSVCToolChain object if it can find `ole32.lib`, but the logic to 2160 // look in the registry might move into lld-link in the future so that 2161 // lld-link invocations in non-MSVC shells just work too.) 2162 // - `clang-cl ... /link ...` can pass arbitrary flags to the linker, 2163 // including /libpath:, which is used to find .lib and .obj files. 2164 // So do not diagnose this on the driver level. Rely on the linker diagnosing 2165 // it. (If we don't end up invoking the linker, this means we'll emit a 2166 // "'linker' input unused [-Wunused-command-line-argument]" warning instead 2167 // of an error.) 2168 // 2169 // Only do this skip after the typo correction step above. `/Brepo` is treated 2170 // as TY_Object, but it's clearly a typo for `/Brepro`. It seems fine to emit 2171 // an error if we have a flag that's within an edit distance of 1 from a 2172 // flag. (Users can use `-Wl,` or `/linker` to launder the flag past the 2173 // driver in the unlikely case they run into this.) 2174 // 2175 // Don't do this skip in clang-cl mode for inputs that start with a '/' -- 2176 // else we'd pass options like /libpath: through to the linker silently. 2177 if (Ty == types::TY_Object && !(IsCLMode() && Value.startswith("/"))) 2178 return true; 2179 2180 Diag(clang::diag::err_drv_no_such_file) << Value; 2181 return false; 2182 } 2183 2184 // Construct a the list of inputs and their types. 2185 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args, 2186 InputList &Inputs) const { 2187 const llvm::opt::OptTable &Opts = getOpts(); 2188 // Track the current user specified (-x) input. We also explicitly track the 2189 // argument used to set the type; we only want to claim the type when we 2190 // actually use it, so we warn about unused -x arguments. 2191 types::ID InputType = types::TY_Nothing; 2192 Arg *InputTypeArg = nullptr; 2193 2194 // The last /TC or /TP option sets the input type to C or C++ globally. 2195 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC, 2196 options::OPT__SLASH_TP)) { 2197 InputTypeArg = TCTP; 2198 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC) 2199 ? types::TY_C 2200 : types::TY_CXX; 2201 2202 Arg *Previous = nullptr; 2203 bool ShowNote = false; 2204 for (Arg *A : 2205 Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) { 2206 if (Previous) { 2207 Diag(clang::diag::warn_drv_overriding_flag_option) 2208 << Previous->getSpelling() << A->getSpelling(); 2209 ShowNote = true; 2210 } 2211 Previous = A; 2212 } 2213 if (ShowNote) 2214 Diag(clang::diag::note_drv_t_option_is_global); 2215 2216 // No driver mode exposes -x and /TC or /TP; we don't support mixing them. 2217 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed"); 2218 } 2219 2220 for (Arg *A : Args) { 2221 if (A->getOption().getKind() == Option::InputClass) { 2222 const char *Value = A->getValue(); 2223 types::ID Ty = types::TY_INVALID; 2224 2225 // Infer the input type if necessary. 2226 if (InputType == types::TY_Nothing) { 2227 // If there was an explicit arg for this, claim it. 2228 if (InputTypeArg) 2229 InputTypeArg->claim(); 2230 2231 // stdin must be handled specially. 2232 if (memcmp(Value, "-", 2) == 0) { 2233 if (IsFlangMode()) { 2234 Ty = types::TY_Fortran; 2235 } else { 2236 // If running with -E, treat as a C input (this changes the 2237 // builtin macros, for example). This may be overridden by -ObjC 2238 // below. 2239 // 2240 // Otherwise emit an error but still use a valid type to avoid 2241 // spurious errors (e.g., no inputs). 2242 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP()) 2243 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl 2244 : clang::diag::err_drv_unknown_stdin_type); 2245 Ty = types::TY_C; 2246 } 2247 } else { 2248 // Otherwise lookup by extension. 2249 // Fallback is C if invoked as C preprocessor, C++ if invoked with 2250 // clang-cl /E, or Object otherwise. 2251 // We use a host hook here because Darwin at least has its own 2252 // idea of what .s is. 2253 if (const char *Ext = strrchr(Value, '.')) 2254 Ty = TC.LookupTypeForExtension(Ext + 1); 2255 2256 if (Ty == types::TY_INVALID) { 2257 if (CCCIsCPP()) 2258 Ty = types::TY_C; 2259 else if (IsCLMode() && Args.hasArgNoClaim(options::OPT_E)) 2260 Ty = types::TY_CXX; 2261 else 2262 Ty = types::TY_Object; 2263 } 2264 2265 // If the driver is invoked as C++ compiler (like clang++ or c++) it 2266 // should autodetect some input files as C++ for g++ compatibility. 2267 if (CCCIsCXX()) { 2268 types::ID OldTy = Ty; 2269 Ty = types::lookupCXXTypeForCType(Ty); 2270 2271 if (Ty != OldTy) 2272 Diag(clang::diag::warn_drv_treating_input_as_cxx) 2273 << getTypeName(OldTy) << getTypeName(Ty); 2274 } 2275 2276 // If running with -fthinlto-index=, extensions that normally identify 2277 // native object files actually identify LLVM bitcode files. 2278 if (Args.hasArgNoClaim(options::OPT_fthinlto_index_EQ) && 2279 Ty == types::TY_Object) 2280 Ty = types::TY_LLVM_BC; 2281 } 2282 2283 // -ObjC and -ObjC++ override the default language, but only for "source 2284 // files". We just treat everything that isn't a linker input as a 2285 // source file. 2286 // 2287 // FIXME: Clean this up if we move the phase sequence into the type. 2288 if (Ty != types::TY_Object) { 2289 if (Args.hasArg(options::OPT_ObjC)) 2290 Ty = types::TY_ObjC; 2291 else if (Args.hasArg(options::OPT_ObjCXX)) 2292 Ty = types::TY_ObjCXX; 2293 } 2294 } else { 2295 assert(InputTypeArg && "InputType set w/o InputTypeArg"); 2296 if (!InputTypeArg->getOption().matches(options::OPT_x)) { 2297 // If emulating cl.exe, make sure that /TC and /TP don't affect input 2298 // object files. 2299 const char *Ext = strrchr(Value, '.'); 2300 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object) 2301 Ty = types::TY_Object; 2302 } 2303 if (Ty == types::TY_INVALID) { 2304 Ty = InputType; 2305 InputTypeArg->claim(); 2306 } 2307 } 2308 2309 if (DiagnoseInputExistence(Args, Value, Ty, /*TypoCorrect=*/true)) 2310 Inputs.push_back(std::make_pair(Ty, A)); 2311 2312 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) { 2313 StringRef Value = A->getValue(); 2314 if (DiagnoseInputExistence(Args, Value, types::TY_C, 2315 /*TypoCorrect=*/false)) { 2316 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue()); 2317 Inputs.push_back(std::make_pair(types::TY_C, InputArg)); 2318 } 2319 A->claim(); 2320 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) { 2321 StringRef Value = A->getValue(); 2322 if (DiagnoseInputExistence(Args, Value, types::TY_CXX, 2323 /*TypoCorrect=*/false)) { 2324 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue()); 2325 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg)); 2326 } 2327 A->claim(); 2328 } else if (A->getOption().hasFlag(options::LinkerInput)) { 2329 // Just treat as object type, we could make a special type for this if 2330 // necessary. 2331 Inputs.push_back(std::make_pair(types::TY_Object, A)); 2332 2333 } else if (A->getOption().matches(options::OPT_x)) { 2334 InputTypeArg = A; 2335 InputType = types::lookupTypeForTypeSpecifier(A->getValue()); 2336 A->claim(); 2337 2338 // Follow gcc behavior and treat as linker input for invalid -x 2339 // options. Its not clear why we shouldn't just revert to unknown; but 2340 // this isn't very important, we might as well be bug compatible. 2341 if (!InputType) { 2342 Diag(clang::diag::err_drv_unknown_language) << A->getValue(); 2343 InputType = types::TY_Object; 2344 } 2345 } else if (A->getOption().getID() == options::OPT_U) { 2346 assert(A->getNumValues() == 1 && "The /U option has one value."); 2347 StringRef Val = A->getValue(0); 2348 if (Val.find_first_of("/\\") != StringRef::npos) { 2349 // Warn about e.g. "/Users/me/myfile.c". 2350 Diag(diag::warn_slash_u_filename) << Val; 2351 Diag(diag::note_use_dashdash); 2352 } 2353 } 2354 } 2355 if (CCCIsCPP() && Inputs.empty()) { 2356 // If called as standalone preprocessor, stdin is processed 2357 // if no other input is present. 2358 Arg *A = MakeInputArg(Args, Opts, "-"); 2359 Inputs.push_back(std::make_pair(types::TY_C, A)); 2360 } 2361 } 2362 2363 namespace { 2364 /// Provides a convenient interface for different programming models to generate 2365 /// the required device actions. 2366 class OffloadingActionBuilder final { 2367 /// Flag used to trace errors in the builder. 2368 bool IsValid = false; 2369 2370 /// The compilation that is using this builder. 2371 Compilation &C; 2372 2373 /// Map between an input argument and the offload kinds used to process it. 2374 std::map<const Arg *, unsigned> InputArgToOffloadKindMap; 2375 2376 /// Builder interface. It doesn't build anything or keep any state. 2377 class DeviceActionBuilder { 2378 public: 2379 typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy; 2380 2381 enum ActionBuilderReturnCode { 2382 // The builder acted successfully on the current action. 2383 ABRT_Success, 2384 // The builder didn't have to act on the current action. 2385 ABRT_Inactive, 2386 // The builder was successful and requested the host action to not be 2387 // generated. 2388 ABRT_Ignore_Host, 2389 }; 2390 2391 protected: 2392 /// Compilation associated with this builder. 2393 Compilation &C; 2394 2395 /// Tool chains associated with this builder. The same programming 2396 /// model may have associated one or more tool chains. 2397 SmallVector<const ToolChain *, 2> ToolChains; 2398 2399 /// The derived arguments associated with this builder. 2400 DerivedArgList &Args; 2401 2402 /// The inputs associated with this builder. 2403 const Driver::InputList &Inputs; 2404 2405 /// The associated offload kind. 2406 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None; 2407 2408 public: 2409 DeviceActionBuilder(Compilation &C, DerivedArgList &Args, 2410 const Driver::InputList &Inputs, 2411 Action::OffloadKind AssociatedOffloadKind) 2412 : C(C), Args(Args), Inputs(Inputs), 2413 AssociatedOffloadKind(AssociatedOffloadKind) {} 2414 virtual ~DeviceActionBuilder() {} 2415 2416 /// Fill up the array \a DA with all the device dependences that should be 2417 /// added to the provided host action \a HostAction. By default it is 2418 /// inactive. 2419 virtual ActionBuilderReturnCode 2420 getDeviceDependences(OffloadAction::DeviceDependences &DA, 2421 phases::ID CurPhase, phases::ID FinalPhase, 2422 PhasesTy &Phases) { 2423 return ABRT_Inactive; 2424 } 2425 2426 /// Update the state to include the provided host action \a HostAction as a 2427 /// dependency of the current device action. By default it is inactive. 2428 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) { 2429 return ABRT_Inactive; 2430 } 2431 2432 /// Append top level actions generated by the builder. 2433 virtual void appendTopLevelActions(ActionList &AL) {} 2434 2435 /// Append linker device actions generated by the builder. 2436 virtual void appendLinkDeviceActions(ActionList &AL) {} 2437 2438 /// Append linker host action generated by the builder. 2439 virtual Action* appendLinkHostActions(ActionList &AL) { return nullptr; } 2440 2441 /// Append linker actions generated by the builder. 2442 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {} 2443 2444 /// Initialize the builder. Return true if any initialization errors are 2445 /// found. 2446 virtual bool initialize() { return false; } 2447 2448 /// Return true if the builder can use bundling/unbundling. 2449 virtual bool canUseBundlerUnbundler() const { return false; } 2450 2451 /// Return true if this builder is valid. We have a valid builder if we have 2452 /// associated device tool chains. 2453 bool isValid() { return !ToolChains.empty(); } 2454 2455 /// Return the associated offload kind. 2456 Action::OffloadKind getAssociatedOffloadKind() { 2457 return AssociatedOffloadKind; 2458 } 2459 }; 2460 2461 /// Base class for CUDA/HIP action builder. It injects device code in 2462 /// the host backend action. 2463 class CudaActionBuilderBase : public DeviceActionBuilder { 2464 protected: 2465 /// Flags to signal if the user requested host-only or device-only 2466 /// compilation. 2467 bool CompileHostOnly = false; 2468 bool CompileDeviceOnly = false; 2469 bool EmitLLVM = false; 2470 bool EmitAsm = false; 2471 2472 /// ID to identify each device compilation. For CUDA it is simply the 2473 /// GPU arch string. For HIP it is either the GPU arch string or GPU 2474 /// arch string plus feature strings delimited by a plus sign, e.g. 2475 /// gfx906+xnack. 2476 struct TargetID { 2477 /// Target ID string which is persistent throughout the compilation. 2478 const char *ID; 2479 TargetID(CudaArch Arch) { ID = CudaArchToString(Arch); } 2480 TargetID(const char *ID) : ID(ID) {} 2481 operator const char *() { return ID; } 2482 operator StringRef() { return StringRef(ID); } 2483 }; 2484 /// List of GPU architectures to use in this compilation. 2485 SmallVector<TargetID, 4> GpuArchList; 2486 2487 /// The CUDA actions for the current input. 2488 ActionList CudaDeviceActions; 2489 2490 /// The CUDA fat binary if it was generated for the current input. 2491 Action *CudaFatBinary = nullptr; 2492 2493 /// Flag that is set to true if this builder acted on the current input. 2494 bool IsActive = false; 2495 2496 /// Flag for -fgpu-rdc. 2497 bool Relocatable = false; 2498 2499 /// Default GPU architecture if there's no one specified. 2500 CudaArch DefaultCudaArch = CudaArch::UNKNOWN; 2501 2502 /// Method to generate compilation unit ID specified by option 2503 /// '-fuse-cuid='. 2504 enum UseCUIDKind { CUID_Hash, CUID_Random, CUID_None, CUID_Invalid }; 2505 UseCUIDKind UseCUID = CUID_Hash; 2506 2507 /// Compilation unit ID specified by option '-cuid='. 2508 StringRef FixedCUID; 2509 2510 public: 2511 CudaActionBuilderBase(Compilation &C, DerivedArgList &Args, 2512 const Driver::InputList &Inputs, 2513 Action::OffloadKind OFKind) 2514 : DeviceActionBuilder(C, Args, Inputs, OFKind) {} 2515 2516 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override { 2517 // While generating code for CUDA, we only depend on the host input action 2518 // to trigger the creation of all the CUDA device actions. 2519 2520 // If we are dealing with an input action, replicate it for each GPU 2521 // architecture. If we are in host-only mode we return 'success' so that 2522 // the host uses the CUDA offload kind. 2523 if (auto *IA = dyn_cast<InputAction>(HostAction)) { 2524 assert(!GpuArchList.empty() && 2525 "We should have at least one GPU architecture."); 2526 2527 // If the host input is not CUDA or HIP, we don't need to bother about 2528 // this input. 2529 if (!(IA->getType() == types::TY_CUDA || 2530 IA->getType() == types::TY_HIP || 2531 IA->getType() == types::TY_PP_HIP)) { 2532 // The builder will ignore this input. 2533 IsActive = false; 2534 return ABRT_Inactive; 2535 } 2536 2537 // Set the flag to true, so that the builder acts on the current input. 2538 IsActive = true; 2539 2540 if (CompileHostOnly) 2541 return ABRT_Success; 2542 2543 // Replicate inputs for each GPU architecture. 2544 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE 2545 : types::TY_CUDA_DEVICE; 2546 std::string CUID = FixedCUID.str(); 2547 if (CUID.empty()) { 2548 if (UseCUID == CUID_Random) 2549 CUID = llvm::utohexstr(llvm::sys::Process::GetRandomNumber(), 2550 /*LowerCase=*/true); 2551 else if (UseCUID == CUID_Hash) { 2552 llvm::MD5 Hasher; 2553 llvm::MD5::MD5Result Hash; 2554 SmallString<256> RealPath; 2555 llvm::sys::fs::real_path(IA->getInputArg().getValue(), RealPath, 2556 /*expand_tilde=*/true); 2557 Hasher.update(RealPath); 2558 for (auto *A : Args) { 2559 if (A->getOption().matches(options::OPT_INPUT)) 2560 continue; 2561 Hasher.update(A->getAsString(Args)); 2562 } 2563 Hasher.final(Hash); 2564 CUID = llvm::utohexstr(Hash.low(), /*LowerCase=*/true); 2565 } 2566 } 2567 IA->setId(CUID); 2568 2569 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 2570 CudaDeviceActions.push_back( 2571 C.MakeAction<InputAction>(IA->getInputArg(), Ty, IA->getId())); 2572 } 2573 2574 return ABRT_Success; 2575 } 2576 2577 // If this is an unbundling action use it as is for each CUDA toolchain. 2578 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) { 2579 2580 // If -fgpu-rdc is disabled, should not unbundle since there is no 2581 // device code to link. 2582 if (UA->getType() == types::TY_Object && !Relocatable) 2583 return ABRT_Inactive; 2584 2585 CudaDeviceActions.clear(); 2586 auto *IA = cast<InputAction>(UA->getInputs().back()); 2587 std::string FileName = IA->getInputArg().getAsString(Args); 2588 // Check if the type of the file is the same as the action. Do not 2589 // unbundle it if it is not. Do not unbundle .so files, for example, 2590 // which are not object files. 2591 if (IA->getType() == types::TY_Object && 2592 (!llvm::sys::path::has_extension(FileName) || 2593 types::lookupTypeForExtension( 2594 llvm::sys::path::extension(FileName).drop_front()) != 2595 types::TY_Object)) 2596 return ABRT_Inactive; 2597 2598 for (auto Arch : GpuArchList) { 2599 CudaDeviceActions.push_back(UA); 2600 UA->registerDependentActionInfo(ToolChains[0], Arch, 2601 AssociatedOffloadKind); 2602 } 2603 return ABRT_Success; 2604 } 2605 2606 return IsActive ? ABRT_Success : ABRT_Inactive; 2607 } 2608 2609 void appendTopLevelActions(ActionList &AL) override { 2610 // Utility to append actions to the top level list. 2611 auto AddTopLevel = [&](Action *A, TargetID TargetID) { 2612 OffloadAction::DeviceDependences Dep; 2613 Dep.add(*A, *ToolChains.front(), TargetID, AssociatedOffloadKind); 2614 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType())); 2615 }; 2616 2617 // If we have a fat binary, add it to the list. 2618 if (CudaFatBinary) { 2619 AddTopLevel(CudaFatBinary, CudaArch::UNUSED); 2620 CudaDeviceActions.clear(); 2621 CudaFatBinary = nullptr; 2622 return; 2623 } 2624 2625 if (CudaDeviceActions.empty()) 2626 return; 2627 2628 // If we have CUDA actions at this point, that's because we have a have 2629 // partial compilation, so we should have an action for each GPU 2630 // architecture. 2631 assert(CudaDeviceActions.size() == GpuArchList.size() && 2632 "Expecting one action per GPU architecture."); 2633 assert(ToolChains.size() == 1 && 2634 "Expecting to have a single CUDA toolchain."); 2635 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) 2636 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]); 2637 2638 CudaDeviceActions.clear(); 2639 } 2640 2641 /// Get canonicalized offload arch option. \returns empty StringRef if the 2642 /// option is invalid. 2643 virtual StringRef getCanonicalOffloadArch(StringRef Arch) = 0; 2644 2645 virtual llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>> 2646 getConflictOffloadArchCombination(const std::set<StringRef> &GpuArchs) = 0; 2647 2648 bool initialize() override { 2649 assert(AssociatedOffloadKind == Action::OFK_Cuda || 2650 AssociatedOffloadKind == Action::OFK_HIP); 2651 2652 // We don't need to support CUDA. 2653 if (AssociatedOffloadKind == Action::OFK_Cuda && 2654 !C.hasOffloadToolChain<Action::OFK_Cuda>()) 2655 return false; 2656 2657 // We don't need to support HIP. 2658 if (AssociatedOffloadKind == Action::OFK_HIP && 2659 !C.hasOffloadToolChain<Action::OFK_HIP>()) 2660 return false; 2661 2662 Relocatable = Args.hasFlag(options::OPT_fgpu_rdc, 2663 options::OPT_fno_gpu_rdc, /*Default=*/false); 2664 2665 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>(); 2666 assert(HostTC && "No toolchain for host compilation."); 2667 if (HostTC->getTriple().isNVPTX() || 2668 HostTC->getTriple().getArch() == llvm::Triple::amdgcn) { 2669 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw 2670 // an error and abort pipeline construction early so we don't trip 2671 // asserts that assume device-side compilation. 2672 C.getDriver().Diag(diag::err_drv_cuda_host_arch) 2673 << HostTC->getTriple().getArchName(); 2674 return true; 2675 } 2676 2677 ToolChains.push_back( 2678 AssociatedOffloadKind == Action::OFK_Cuda 2679 ? C.getSingleOffloadToolChain<Action::OFK_Cuda>() 2680 : C.getSingleOffloadToolChain<Action::OFK_HIP>()); 2681 2682 Arg *PartialCompilationArg = Args.getLastArg( 2683 options::OPT_cuda_host_only, options::OPT_cuda_device_only, 2684 options::OPT_cuda_compile_host_device); 2685 CompileHostOnly = PartialCompilationArg && 2686 PartialCompilationArg->getOption().matches( 2687 options::OPT_cuda_host_only); 2688 CompileDeviceOnly = PartialCompilationArg && 2689 PartialCompilationArg->getOption().matches( 2690 options::OPT_cuda_device_only); 2691 EmitLLVM = Args.getLastArg(options::OPT_emit_llvm); 2692 EmitAsm = Args.getLastArg(options::OPT_S); 2693 FixedCUID = Args.getLastArgValue(options::OPT_cuid_EQ); 2694 if (Arg *A = Args.getLastArg(options::OPT_fuse_cuid_EQ)) { 2695 StringRef UseCUIDStr = A->getValue(); 2696 UseCUID = llvm::StringSwitch<UseCUIDKind>(UseCUIDStr) 2697 .Case("hash", CUID_Hash) 2698 .Case("random", CUID_Random) 2699 .Case("none", CUID_None) 2700 .Default(CUID_Invalid); 2701 if (UseCUID == CUID_Invalid) { 2702 C.getDriver().Diag(diag::err_drv_invalid_value) 2703 << A->getAsString(Args) << UseCUIDStr; 2704 C.setContainsError(); 2705 return true; 2706 } 2707 } 2708 2709 // Collect all cuda_gpu_arch parameters, removing duplicates. 2710 std::set<StringRef> GpuArchs; 2711 bool Error = false; 2712 for (Arg *A : Args) { 2713 if (!(A->getOption().matches(options::OPT_offload_arch_EQ) || 2714 A->getOption().matches(options::OPT_no_offload_arch_EQ))) 2715 continue; 2716 A->claim(); 2717 2718 StringRef ArchStr = A->getValue(); 2719 if (A->getOption().matches(options::OPT_no_offload_arch_EQ) && 2720 ArchStr == "all") { 2721 GpuArchs.clear(); 2722 continue; 2723 } 2724 ArchStr = getCanonicalOffloadArch(ArchStr); 2725 if (ArchStr.empty()) { 2726 Error = true; 2727 } else if (A->getOption().matches(options::OPT_offload_arch_EQ)) 2728 GpuArchs.insert(ArchStr); 2729 else if (A->getOption().matches(options::OPT_no_offload_arch_EQ)) 2730 GpuArchs.erase(ArchStr); 2731 else 2732 llvm_unreachable("Unexpected option."); 2733 } 2734 2735 auto &&ConflictingArchs = getConflictOffloadArchCombination(GpuArchs); 2736 if (ConflictingArchs) { 2737 C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo) 2738 << ConflictingArchs.getValue().first 2739 << ConflictingArchs.getValue().second; 2740 C.setContainsError(); 2741 return true; 2742 } 2743 2744 // Collect list of GPUs remaining in the set. 2745 for (auto Arch : GpuArchs) 2746 GpuArchList.push_back(Arch.data()); 2747 2748 // Default to sm_20 which is the lowest common denominator for 2749 // supported GPUs. sm_20 code should work correctly, if 2750 // suboptimally, on all newer GPUs. 2751 if (GpuArchList.empty()) 2752 GpuArchList.push_back(DefaultCudaArch); 2753 2754 return Error; 2755 } 2756 }; 2757 2758 /// \brief CUDA action builder. It injects device code in the host backend 2759 /// action. 2760 class CudaActionBuilder final : public CudaActionBuilderBase { 2761 public: 2762 CudaActionBuilder(Compilation &C, DerivedArgList &Args, 2763 const Driver::InputList &Inputs) 2764 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) { 2765 DefaultCudaArch = CudaArch::SM_35; 2766 } 2767 2768 StringRef getCanonicalOffloadArch(StringRef ArchStr) override { 2769 CudaArch Arch = StringToCudaArch(ArchStr); 2770 if (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch)) { 2771 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr; 2772 return StringRef(); 2773 } 2774 return CudaArchToString(Arch); 2775 } 2776 2777 llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>> 2778 getConflictOffloadArchCombination( 2779 const std::set<StringRef> &GpuArchs) override { 2780 return llvm::None; 2781 } 2782 2783 ActionBuilderReturnCode 2784 getDeviceDependences(OffloadAction::DeviceDependences &DA, 2785 phases::ID CurPhase, phases::ID FinalPhase, 2786 PhasesTy &Phases) override { 2787 if (!IsActive) 2788 return ABRT_Inactive; 2789 2790 // If we don't have more CUDA actions, we don't have any dependences to 2791 // create for the host. 2792 if (CudaDeviceActions.empty()) 2793 return ABRT_Success; 2794 2795 assert(CudaDeviceActions.size() == GpuArchList.size() && 2796 "Expecting one action per GPU architecture."); 2797 assert(!CompileHostOnly && 2798 "Not expecting CUDA actions in host-only compilation."); 2799 2800 // If we are generating code for the device or we are in a backend phase, 2801 // we attempt to generate the fat binary. We compile each arch to ptx and 2802 // assemble to cubin, then feed the cubin *and* the ptx into a device 2803 // "link" action, which uses fatbinary to combine these cubins into one 2804 // fatbin. The fatbin is then an input to the host action if not in 2805 // device-only mode. 2806 if (CompileDeviceOnly || CurPhase == phases::Backend) { 2807 ActionList DeviceActions; 2808 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 2809 // Produce the device action from the current phase up to the assemble 2810 // phase. 2811 for (auto Ph : Phases) { 2812 // Skip the phases that were already dealt with. 2813 if (Ph < CurPhase) 2814 continue; 2815 // We have to be consistent with the host final phase. 2816 if (Ph > FinalPhase) 2817 break; 2818 2819 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction( 2820 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda); 2821 2822 if (Ph == phases::Assemble) 2823 break; 2824 } 2825 2826 // If we didn't reach the assemble phase, we can't generate the fat 2827 // binary. We don't need to generate the fat binary if we are not in 2828 // device-only mode. 2829 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) || 2830 CompileDeviceOnly) 2831 continue; 2832 2833 Action *AssembleAction = CudaDeviceActions[I]; 2834 assert(AssembleAction->getType() == types::TY_Object); 2835 assert(AssembleAction->getInputs().size() == 1); 2836 2837 Action *BackendAction = AssembleAction->getInputs()[0]; 2838 assert(BackendAction->getType() == types::TY_PP_Asm); 2839 2840 for (auto &A : {AssembleAction, BackendAction}) { 2841 OffloadAction::DeviceDependences DDep; 2842 DDep.add(*A, *ToolChains.front(), GpuArchList[I], Action::OFK_Cuda); 2843 DeviceActions.push_back( 2844 C.MakeAction<OffloadAction>(DDep, A->getType())); 2845 } 2846 } 2847 2848 // We generate the fat binary if we have device input actions. 2849 if (!DeviceActions.empty()) { 2850 CudaFatBinary = 2851 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN); 2852 2853 if (!CompileDeviceOnly) { 2854 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr, 2855 Action::OFK_Cuda); 2856 // Clear the fat binary, it is already a dependence to an host 2857 // action. 2858 CudaFatBinary = nullptr; 2859 } 2860 2861 // Remove the CUDA actions as they are already connected to an host 2862 // action or fat binary. 2863 CudaDeviceActions.clear(); 2864 } 2865 2866 // We avoid creating host action in device-only mode. 2867 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success; 2868 } else if (CurPhase > phases::Backend) { 2869 // If we are past the backend phase and still have a device action, we 2870 // don't have to do anything as this action is already a device 2871 // top-level action. 2872 return ABRT_Success; 2873 } 2874 2875 assert(CurPhase < phases::Backend && "Generating single CUDA " 2876 "instructions should only occur " 2877 "before the backend phase!"); 2878 2879 // By default, we produce an action for each device arch. 2880 for (Action *&A : CudaDeviceActions) 2881 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A); 2882 2883 return ABRT_Success; 2884 } 2885 }; 2886 /// \brief HIP action builder. It injects device code in the host backend 2887 /// action. 2888 class HIPActionBuilder final : public CudaActionBuilderBase { 2889 /// The linker inputs obtained for each device arch. 2890 SmallVector<ActionList, 8> DeviceLinkerInputs; 2891 bool GPUSanitize; 2892 // The default bundling behavior depends on the type of output, therefore 2893 // BundleOutput needs to be tri-value: None, true, or false. 2894 // Bundle code objects except --no-gpu-output is specified for device 2895 // only compilation. Bundle other type of output files only if 2896 // --gpu-bundle-output is specified for device only compilation. 2897 Optional<bool> BundleOutput; 2898 2899 public: 2900 HIPActionBuilder(Compilation &C, DerivedArgList &Args, 2901 const Driver::InputList &Inputs) 2902 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) { 2903 DefaultCudaArch = CudaArch::GFX803; 2904 GPUSanitize = Args.hasFlag(options::OPT_fgpu_sanitize, 2905 options::OPT_fno_gpu_sanitize, false); 2906 if (Args.hasArg(options::OPT_gpu_bundle_output, 2907 options::OPT_no_gpu_bundle_output)) 2908 BundleOutput = Args.hasFlag(options::OPT_gpu_bundle_output, 2909 options::OPT_no_gpu_bundle_output); 2910 } 2911 2912 bool canUseBundlerUnbundler() const override { return true; } 2913 2914 StringRef getCanonicalOffloadArch(StringRef IdStr) override { 2915 llvm::StringMap<bool> Features; 2916 auto ArchStr = 2917 parseTargetID(getHIPOffloadTargetTriple(), IdStr, &Features); 2918 if (!ArchStr) { 2919 C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << IdStr; 2920 C.setContainsError(); 2921 return StringRef(); 2922 } 2923 auto CanId = getCanonicalTargetID(ArchStr.getValue(), Features); 2924 return Args.MakeArgStringRef(CanId); 2925 }; 2926 2927 llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>> 2928 getConflictOffloadArchCombination( 2929 const std::set<StringRef> &GpuArchs) override { 2930 return getConflictTargetIDCombination(GpuArchs); 2931 } 2932 2933 ActionBuilderReturnCode 2934 getDeviceDependences(OffloadAction::DeviceDependences &DA, 2935 phases::ID CurPhase, phases::ID FinalPhase, 2936 PhasesTy &Phases) override { 2937 // amdgcn does not support linking of object files, therefore we skip 2938 // backend and assemble phases to output LLVM IR. Except for generating 2939 // non-relocatable device coee, where we generate fat binary for device 2940 // code and pass to host in Backend phase. 2941 if (CudaDeviceActions.empty()) 2942 return ABRT_Success; 2943 2944 assert(((CurPhase == phases::Link && Relocatable) || 2945 CudaDeviceActions.size() == GpuArchList.size()) && 2946 "Expecting one action per GPU architecture."); 2947 assert(!CompileHostOnly && 2948 "Not expecting CUDA actions in host-only compilation."); 2949 2950 if (!Relocatable && CurPhase == phases::Backend && !EmitLLVM && 2951 !EmitAsm) { 2952 // If we are in backend phase, we attempt to generate the fat binary. 2953 // We compile each arch to IR and use a link action to generate code 2954 // object containing ISA. Then we use a special "link" action to create 2955 // a fat binary containing all the code objects for different GPU's. 2956 // The fat binary is then an input to the host action. 2957 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 2958 if (C.getDriver().isUsingLTO(/*IsOffload=*/true)) { 2959 // When LTO is enabled, skip the backend and assemble phases and 2960 // use lld to link the bitcode. 2961 ActionList AL; 2962 AL.push_back(CudaDeviceActions[I]); 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 } else { 2968 // When LTO is not enabled, we follow the conventional 2969 // compiler phases, including backend and assemble phases. 2970 ActionList AL; 2971 auto BackendAction = C.getDriver().ConstructPhaseAction( 2972 C, Args, phases::Backend, CudaDeviceActions[I], 2973 AssociatedOffloadKind); 2974 auto AssembleAction = C.getDriver().ConstructPhaseAction( 2975 C, Args, phases::Assemble, BackendAction, 2976 AssociatedOffloadKind); 2977 AL.push_back(AssembleAction); 2978 // Create a link action to link device IR with device library 2979 // and generate ISA. 2980 CudaDeviceActions[I] = 2981 C.MakeAction<LinkJobAction>(AL, types::TY_Image); 2982 } 2983 2984 // OffloadingActionBuilder propagates device arch until an offload 2985 // action. Since the next action for creating fatbin does 2986 // not have device arch, whereas the above link action and its input 2987 // have device arch, an offload action is needed to stop the null 2988 // device arch of the next action being propagated to the above link 2989 // action. 2990 OffloadAction::DeviceDependences DDep; 2991 DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I], 2992 AssociatedOffloadKind); 2993 CudaDeviceActions[I] = C.MakeAction<OffloadAction>( 2994 DDep, CudaDeviceActions[I]->getType()); 2995 } 2996 2997 if (!CompileDeviceOnly || !BundleOutput.hasValue() || 2998 BundleOutput.getValue()) { 2999 // Create HIP fat binary with a special "link" action. 3000 CudaFatBinary = C.MakeAction<LinkJobAction>(CudaDeviceActions, 3001 types::TY_HIP_FATBIN); 3002 3003 if (!CompileDeviceOnly) { 3004 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr, 3005 AssociatedOffloadKind); 3006 // Clear the fat binary, it is already a dependence to an host 3007 // action. 3008 CudaFatBinary = nullptr; 3009 } 3010 3011 // Remove the CUDA actions as they are already connected to an host 3012 // action or fat binary. 3013 CudaDeviceActions.clear(); 3014 } 3015 3016 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success; 3017 } else if (CurPhase == phases::Link) { 3018 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch. 3019 // This happens to each device action originated from each input file. 3020 // Later on, device actions in DeviceLinkerInputs are used to create 3021 // device link actions in appendLinkDependences and the created device 3022 // link actions are passed to the offload action as device dependence. 3023 DeviceLinkerInputs.resize(CudaDeviceActions.size()); 3024 auto LI = DeviceLinkerInputs.begin(); 3025 for (auto *A : CudaDeviceActions) { 3026 LI->push_back(A); 3027 ++LI; 3028 } 3029 3030 // We will pass the device action as a host dependence, so we don't 3031 // need to do anything else with them. 3032 CudaDeviceActions.clear(); 3033 return ABRT_Success; 3034 } 3035 3036 // By default, we produce an action for each device arch. 3037 for (Action *&A : CudaDeviceActions) 3038 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A, 3039 AssociatedOffloadKind); 3040 3041 if (CompileDeviceOnly && CurPhase == FinalPhase && 3042 BundleOutput.hasValue() && BundleOutput.getValue()) { 3043 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 3044 OffloadAction::DeviceDependences DDep; 3045 DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I], 3046 AssociatedOffloadKind); 3047 CudaDeviceActions[I] = C.MakeAction<OffloadAction>( 3048 DDep, CudaDeviceActions[I]->getType()); 3049 } 3050 CudaFatBinary = 3051 C.MakeAction<OffloadBundlingJobAction>(CudaDeviceActions); 3052 CudaDeviceActions.clear(); 3053 } 3054 3055 return (CompileDeviceOnly && CurPhase == FinalPhase) ? ABRT_Ignore_Host 3056 : ABRT_Success; 3057 } 3058 3059 void appendLinkDeviceActions(ActionList &AL) override { 3060 if (DeviceLinkerInputs.size() == 0) 3061 return; 3062 3063 assert(DeviceLinkerInputs.size() == GpuArchList.size() && 3064 "Linker inputs and GPU arch list sizes do not match."); 3065 3066 // Append a new link action for each device. 3067 unsigned I = 0; 3068 for (auto &LI : DeviceLinkerInputs) { 3069 // Each entry in DeviceLinkerInputs corresponds to a GPU arch. 3070 auto *DeviceLinkAction = 3071 C.MakeAction<LinkJobAction>(LI, types::TY_Image); 3072 // Linking all inputs for the current GPU arch. 3073 // LI contains all the inputs for the linker. 3074 OffloadAction::DeviceDependences DeviceLinkDeps; 3075 DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0], 3076 GpuArchList[I], AssociatedOffloadKind); 3077 AL.push_back(C.MakeAction<OffloadAction>(DeviceLinkDeps, 3078 DeviceLinkAction->getType())); 3079 ++I; 3080 } 3081 DeviceLinkerInputs.clear(); 3082 3083 // Create a host object from all the device images by embedding them 3084 // in a fat binary. 3085 OffloadAction::DeviceDependences DDeps; 3086 auto *TopDeviceLinkAction = 3087 C.MakeAction<LinkJobAction>(AL, types::TY_Object); 3088 DDeps.add(*TopDeviceLinkAction, *ToolChains[0], 3089 nullptr, AssociatedOffloadKind); 3090 3091 // Offload the host object to the host linker. 3092 AL.push_back(C.MakeAction<OffloadAction>(DDeps, TopDeviceLinkAction->getType())); 3093 } 3094 3095 Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); } 3096 3097 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {} 3098 }; 3099 3100 /// OpenMP action builder. The host bitcode is passed to the device frontend 3101 /// and all the device linked images are passed to the host link phase. 3102 class OpenMPActionBuilder final : public DeviceActionBuilder { 3103 /// The OpenMP actions for the current input. 3104 ActionList OpenMPDeviceActions; 3105 3106 /// The linker inputs obtained for each toolchain. 3107 SmallVector<ActionList, 8> DeviceLinkerInputs; 3108 3109 public: 3110 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args, 3111 const Driver::InputList &Inputs) 3112 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {} 3113 3114 ActionBuilderReturnCode 3115 getDeviceDependences(OffloadAction::DeviceDependences &DA, 3116 phases::ID CurPhase, phases::ID FinalPhase, 3117 PhasesTy &Phases) override { 3118 if (OpenMPDeviceActions.empty()) 3119 return ABRT_Inactive; 3120 3121 // We should always have an action for each input. 3122 assert(OpenMPDeviceActions.size() == ToolChains.size() && 3123 "Number of OpenMP actions and toolchains do not match."); 3124 3125 // The host only depends on device action in the linking phase, when all 3126 // the device images have to be embedded in the host image. 3127 if (CurPhase == phases::Link) { 3128 assert(ToolChains.size() == DeviceLinkerInputs.size() && 3129 "Toolchains and linker inputs sizes do not match."); 3130 auto LI = DeviceLinkerInputs.begin(); 3131 for (auto *A : OpenMPDeviceActions) { 3132 LI->push_back(A); 3133 ++LI; 3134 } 3135 3136 // We passed the device action as a host dependence, so we don't need to 3137 // do anything else with them. 3138 OpenMPDeviceActions.clear(); 3139 return ABRT_Success; 3140 } 3141 3142 // By default, we produce an action for each device arch. 3143 for (Action *&A : OpenMPDeviceActions) 3144 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A); 3145 3146 return ABRT_Success; 3147 } 3148 3149 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override { 3150 3151 // If this is an input action replicate it for each OpenMP toolchain. 3152 if (auto *IA = dyn_cast<InputAction>(HostAction)) { 3153 OpenMPDeviceActions.clear(); 3154 for (unsigned I = 0; I < ToolChains.size(); ++I) 3155 OpenMPDeviceActions.push_back( 3156 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType())); 3157 return ABRT_Success; 3158 } 3159 3160 // If this is an unbundling action use it as is for each OpenMP toolchain. 3161 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) { 3162 OpenMPDeviceActions.clear(); 3163 auto *IA = cast<InputAction>(UA->getInputs().back()); 3164 std::string FileName = IA->getInputArg().getAsString(Args); 3165 // Check if the type of the file is the same as the action. Do not 3166 // unbundle it if it is not. Do not unbundle .so files, for example, 3167 // which are not object files. 3168 if (IA->getType() == types::TY_Object && 3169 (!llvm::sys::path::has_extension(FileName) || 3170 types::lookupTypeForExtension( 3171 llvm::sys::path::extension(FileName).drop_front()) != 3172 types::TY_Object)) 3173 return ABRT_Inactive; 3174 for (unsigned I = 0; I < ToolChains.size(); ++I) { 3175 OpenMPDeviceActions.push_back(UA); 3176 UA->registerDependentActionInfo( 3177 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP); 3178 } 3179 return ABRT_Success; 3180 } 3181 3182 // When generating code for OpenMP we use the host compile phase result as 3183 // a dependence to the device compile phase so that it can learn what 3184 // declarations should be emitted. However, this is not the only use for 3185 // the host action, so we prevent it from being collapsed. 3186 if (isa<CompileJobAction>(HostAction)) { 3187 HostAction->setCannotBeCollapsedWithNextDependentAction(); 3188 assert(ToolChains.size() == OpenMPDeviceActions.size() && 3189 "Toolchains and device action sizes do not match."); 3190 OffloadAction::HostDependence HDep( 3191 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 3192 /*BoundArch=*/nullptr, Action::OFK_OpenMP); 3193 auto TC = ToolChains.begin(); 3194 for (Action *&A : OpenMPDeviceActions) { 3195 assert(isa<CompileJobAction>(A)); 3196 OffloadAction::DeviceDependences DDep; 3197 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP); 3198 A = C.MakeAction<OffloadAction>(HDep, DDep); 3199 ++TC; 3200 } 3201 } 3202 return ABRT_Success; 3203 } 3204 3205 void appendTopLevelActions(ActionList &AL) override { 3206 if (OpenMPDeviceActions.empty()) 3207 return; 3208 3209 // We should always have an action for each input. 3210 assert(OpenMPDeviceActions.size() == ToolChains.size() && 3211 "Number of OpenMP actions and toolchains do not match."); 3212 3213 // Append all device actions followed by the proper offload action. 3214 auto TI = ToolChains.begin(); 3215 for (auto *A : OpenMPDeviceActions) { 3216 OffloadAction::DeviceDependences Dep; 3217 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP); 3218 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType())); 3219 ++TI; 3220 } 3221 // We no longer need the action stored in this builder. 3222 OpenMPDeviceActions.clear(); 3223 } 3224 3225 void appendLinkDeviceActions(ActionList &AL) override { 3226 assert(ToolChains.size() == DeviceLinkerInputs.size() && 3227 "Toolchains and linker inputs sizes do not match."); 3228 3229 // Append a new link action for each device. 3230 auto TC = ToolChains.begin(); 3231 for (auto &LI : DeviceLinkerInputs) { 3232 auto *DeviceLinkAction = 3233 C.MakeAction<LinkJobAction>(LI, types::TY_Image); 3234 OffloadAction::DeviceDependences DeviceLinkDeps; 3235 DeviceLinkDeps.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr, 3236 Action::OFK_OpenMP); 3237 AL.push_back(C.MakeAction<OffloadAction>(DeviceLinkDeps, 3238 DeviceLinkAction->getType())); 3239 ++TC; 3240 } 3241 DeviceLinkerInputs.clear(); 3242 } 3243 3244 Action* appendLinkHostActions(ActionList &AL) override { 3245 // Create wrapper bitcode from the result of device link actions and compile 3246 // it to an object which will be added to the host link command. 3247 auto *BC = C.MakeAction<OffloadWrapperJobAction>(AL, types::TY_LLVM_BC); 3248 auto *ASM = C.MakeAction<BackendJobAction>(BC, types::TY_PP_Asm); 3249 return C.MakeAction<AssembleJobAction>(ASM, types::TY_Object); 3250 } 3251 3252 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {} 3253 3254 bool initialize() override { 3255 // Get the OpenMP toolchains. If we don't get any, the action builder will 3256 // know there is nothing to do related to OpenMP offloading. 3257 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>(); 3258 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE; 3259 ++TI) 3260 ToolChains.push_back(TI->second); 3261 3262 DeviceLinkerInputs.resize(ToolChains.size()); 3263 return false; 3264 } 3265 3266 bool canUseBundlerUnbundler() const override { 3267 // OpenMP should use bundled files whenever possible. 3268 return true; 3269 } 3270 }; 3271 3272 /// 3273 /// TODO: Add the implementation for other specialized builders here. 3274 /// 3275 3276 /// Specialized builders being used by this offloading action builder. 3277 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders; 3278 3279 /// Flag set to true if all valid builders allow file bundling/unbundling. 3280 bool CanUseBundler; 3281 3282 public: 3283 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args, 3284 const Driver::InputList &Inputs) 3285 : C(C) { 3286 // Create a specialized builder for each device toolchain. 3287 3288 IsValid = true; 3289 3290 // Create a specialized builder for CUDA. 3291 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs)); 3292 3293 // Create a specialized builder for HIP. 3294 SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs)); 3295 3296 // Create a specialized builder for OpenMP. 3297 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs)); 3298 3299 // 3300 // TODO: Build other specialized builders here. 3301 // 3302 3303 // Initialize all the builders, keeping track of errors. If all valid 3304 // builders agree that we can use bundling, set the flag to true. 3305 unsigned ValidBuilders = 0u; 3306 unsigned ValidBuildersSupportingBundling = 0u; 3307 for (auto *SB : SpecializedBuilders) { 3308 IsValid = IsValid && !SB->initialize(); 3309 3310 // Update the counters if the builder is valid. 3311 if (SB->isValid()) { 3312 ++ValidBuilders; 3313 if (SB->canUseBundlerUnbundler()) 3314 ++ValidBuildersSupportingBundling; 3315 } 3316 } 3317 CanUseBundler = 3318 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling; 3319 } 3320 3321 ~OffloadingActionBuilder() { 3322 for (auto *SB : SpecializedBuilders) 3323 delete SB; 3324 } 3325 3326 /// Generate an action that adds device dependences (if any) to a host action. 3327 /// If no device dependence actions exist, just return the host action \a 3328 /// HostAction. If an error is found or if no builder requires the host action 3329 /// to be generated, return nullptr. 3330 Action * 3331 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg, 3332 phases::ID CurPhase, phases::ID FinalPhase, 3333 DeviceActionBuilder::PhasesTy &Phases) { 3334 if (!IsValid) 3335 return nullptr; 3336 3337 if (SpecializedBuilders.empty()) 3338 return HostAction; 3339 3340 assert(HostAction && "Invalid host action!"); 3341 3342 OffloadAction::DeviceDependences DDeps; 3343 // Check if all the programming models agree we should not emit the host 3344 // action. Also, keep track of the offloading kinds employed. 3345 auto &OffloadKind = InputArgToOffloadKindMap[InputArg]; 3346 unsigned InactiveBuilders = 0u; 3347 unsigned IgnoringBuilders = 0u; 3348 for (auto *SB : SpecializedBuilders) { 3349 if (!SB->isValid()) { 3350 ++InactiveBuilders; 3351 continue; 3352 } 3353 3354 auto RetCode = 3355 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases); 3356 3357 // If the builder explicitly says the host action should be ignored, 3358 // we need to increment the variable that tracks the builders that request 3359 // the host object to be ignored. 3360 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host) 3361 ++IgnoringBuilders; 3362 3363 // Unless the builder was inactive for this action, we have to record the 3364 // offload kind because the host will have to use it. 3365 if (RetCode != DeviceActionBuilder::ABRT_Inactive) 3366 OffloadKind |= SB->getAssociatedOffloadKind(); 3367 } 3368 3369 // If all builders agree that the host object should be ignored, just return 3370 // nullptr. 3371 if (IgnoringBuilders && 3372 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders)) 3373 return nullptr; 3374 3375 if (DDeps.getActions().empty()) 3376 return HostAction; 3377 3378 // We have dependences we need to bundle together. We use an offload action 3379 // for that. 3380 OffloadAction::HostDependence HDep( 3381 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 3382 /*BoundArch=*/nullptr, DDeps); 3383 return C.MakeAction<OffloadAction>(HDep, DDeps); 3384 } 3385 3386 /// Generate an action that adds a host dependence to a device action. The 3387 /// results will be kept in this action builder. Return true if an error was 3388 /// found. 3389 bool addHostDependenceToDeviceActions(Action *&HostAction, 3390 const Arg *InputArg) { 3391 if (!IsValid) 3392 return true; 3393 3394 // If we are supporting bundling/unbundling and the current action is an 3395 // input action of non-source file, we replace the host action by the 3396 // unbundling action. The bundler tool has the logic to detect if an input 3397 // is a bundle or not and if the input is not a bundle it assumes it is a 3398 // host file. Therefore it is safe to create an unbundling action even if 3399 // the input is not a bundle. 3400 if (CanUseBundler && isa<InputAction>(HostAction) && 3401 InputArg->getOption().getKind() == llvm::opt::Option::InputClass && 3402 (!types::isSrcFile(HostAction->getType()) || 3403 HostAction->getType() == types::TY_PP_HIP)) { 3404 auto UnbundlingHostAction = 3405 C.MakeAction<OffloadUnbundlingJobAction>(HostAction); 3406 UnbundlingHostAction->registerDependentActionInfo( 3407 C.getSingleOffloadToolChain<Action::OFK_Host>(), 3408 /*BoundArch=*/StringRef(), Action::OFK_Host); 3409 HostAction = UnbundlingHostAction; 3410 } 3411 3412 assert(HostAction && "Invalid host action!"); 3413 3414 // Register the offload kinds that are used. 3415 auto &OffloadKind = InputArgToOffloadKindMap[InputArg]; 3416 for (auto *SB : SpecializedBuilders) { 3417 if (!SB->isValid()) 3418 continue; 3419 3420 auto RetCode = SB->addDeviceDepences(HostAction); 3421 3422 // Host dependences for device actions are not compatible with that same 3423 // action being ignored. 3424 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host && 3425 "Host dependence not expected to be ignored.!"); 3426 3427 // Unless the builder was inactive for this action, we have to record the 3428 // offload kind because the host will have to use it. 3429 if (RetCode != DeviceActionBuilder::ABRT_Inactive) 3430 OffloadKind |= SB->getAssociatedOffloadKind(); 3431 } 3432 3433 // Do not use unbundler if the Host does not depend on device action. 3434 if (OffloadKind == Action::OFK_None && CanUseBundler) 3435 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) 3436 HostAction = UA->getInputs().back(); 3437 3438 return false; 3439 } 3440 3441 /// Add the offloading top level actions to the provided action list. This 3442 /// function can replace the host action by a bundling action if the 3443 /// programming models allow it. 3444 bool appendTopLevelActions(ActionList &AL, Action *HostAction, 3445 const Arg *InputArg) { 3446 // Get the device actions to be appended. 3447 ActionList OffloadAL; 3448 for (auto *SB : SpecializedBuilders) { 3449 if (!SB->isValid()) 3450 continue; 3451 SB->appendTopLevelActions(OffloadAL); 3452 } 3453 3454 // If we can use the bundler, replace the host action by the bundling one in 3455 // the resulting list. Otherwise, just append the device actions. For 3456 // device only compilation, HostAction is a null pointer, therefore only do 3457 // this when HostAction is not a null pointer. 3458 if (CanUseBundler && HostAction && 3459 HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) { 3460 // Add the host action to the list in order to create the bundling action. 3461 OffloadAL.push_back(HostAction); 3462 3463 // We expect that the host action was just appended to the action list 3464 // before this method was called. 3465 assert(HostAction == AL.back() && "Host action not in the list??"); 3466 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL); 3467 AL.back() = HostAction; 3468 } else 3469 AL.append(OffloadAL.begin(), OffloadAL.end()); 3470 3471 // Propagate to the current host action (if any) the offload information 3472 // associated with the current input. 3473 if (HostAction) 3474 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg], 3475 /*BoundArch=*/nullptr); 3476 return false; 3477 } 3478 3479 Action* makeHostLinkAction() { 3480 // Build a list of device linking actions. 3481 ActionList DeviceAL; 3482 for (DeviceActionBuilder *SB : SpecializedBuilders) { 3483 if (!SB->isValid()) 3484 continue; 3485 SB->appendLinkDeviceActions(DeviceAL); 3486 } 3487 3488 if (DeviceAL.empty()) 3489 return nullptr; 3490 3491 // Let builders add host linking actions. 3492 Action* HA = nullptr; 3493 for (DeviceActionBuilder *SB : SpecializedBuilders) { 3494 if (!SB->isValid()) 3495 continue; 3496 HA = SB->appendLinkHostActions(DeviceAL); 3497 } 3498 return HA; 3499 } 3500 3501 /// Processes the host linker action. This currently consists of replacing it 3502 /// with an offload action if there are device link objects and propagate to 3503 /// the host action all the offload kinds used in the current compilation. The 3504 /// resulting action is returned. 3505 Action *processHostLinkAction(Action *HostAction) { 3506 // Add all the dependences from the device linking actions. 3507 OffloadAction::DeviceDependences DDeps; 3508 for (auto *SB : SpecializedBuilders) { 3509 if (!SB->isValid()) 3510 continue; 3511 3512 SB->appendLinkDependences(DDeps); 3513 } 3514 3515 // Calculate all the offload kinds used in the current compilation. 3516 unsigned ActiveOffloadKinds = 0u; 3517 for (auto &I : InputArgToOffloadKindMap) 3518 ActiveOffloadKinds |= I.second; 3519 3520 // If we don't have device dependencies, we don't have to create an offload 3521 // action. 3522 if (DDeps.getActions().empty()) { 3523 // Propagate all the active kinds to host action. Given that it is a link 3524 // action it is assumed to depend on all actions generated so far. 3525 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds, 3526 /*BoundArch=*/nullptr); 3527 return HostAction; 3528 } 3529 3530 // Create the offload action with all dependences. When an offload action 3531 // is created the kinds are propagated to the host action, so we don't have 3532 // to do that explicitly here. 3533 OffloadAction::HostDependence HDep( 3534 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 3535 /*BoundArch*/ nullptr, ActiveOffloadKinds); 3536 return C.MakeAction<OffloadAction>(HDep, DDeps); 3537 } 3538 }; 3539 } // anonymous namespace. 3540 3541 void Driver::handleArguments(Compilation &C, DerivedArgList &Args, 3542 const InputList &Inputs, 3543 ActionList &Actions) const { 3544 3545 // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames. 3546 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc); 3547 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu); 3548 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) { 3549 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl); 3550 Args.eraseArg(options::OPT__SLASH_Yc); 3551 Args.eraseArg(options::OPT__SLASH_Yu); 3552 YcArg = YuArg = nullptr; 3553 } 3554 if (YcArg && Inputs.size() > 1) { 3555 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl); 3556 Args.eraseArg(options::OPT__SLASH_Yc); 3557 YcArg = nullptr; 3558 } 3559 3560 Arg *FinalPhaseArg; 3561 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg); 3562 3563 if (FinalPhase == phases::Link) { 3564 if (Args.hasArg(options::OPT_emit_llvm)) 3565 Diag(clang::diag::err_drv_emit_llvm_link); 3566 if (IsCLMode() && LTOMode != LTOK_None && 3567 !Args.getLastArgValue(options::OPT_fuse_ld_EQ) 3568 .equals_insensitive("lld")) 3569 Diag(clang::diag::err_drv_lto_without_lld); 3570 } 3571 3572 if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) { 3573 // If only preprocessing or /Y- is used, all pch handling is disabled. 3574 // Rather than check for it everywhere, just remove clang-cl pch-related 3575 // flags here. 3576 Args.eraseArg(options::OPT__SLASH_Fp); 3577 Args.eraseArg(options::OPT__SLASH_Yc); 3578 Args.eraseArg(options::OPT__SLASH_Yu); 3579 YcArg = YuArg = nullptr; 3580 } 3581 3582 unsigned LastPLSize = 0; 3583 for (auto &I : Inputs) { 3584 types::ID InputType = I.first; 3585 const Arg *InputArg = I.second; 3586 3587 auto PL = types::getCompilationPhases(InputType); 3588 LastPLSize = PL.size(); 3589 3590 // If the first step comes after the final phase we are doing as part of 3591 // this compilation, warn the user about it. 3592 phases::ID InitialPhase = PL[0]; 3593 if (InitialPhase > FinalPhase) { 3594 if (InputArg->isClaimed()) 3595 continue; 3596 3597 // Claim here to avoid the more general unused warning. 3598 InputArg->claim(); 3599 3600 // Suppress all unused style warnings with -Qunused-arguments 3601 if (Args.hasArg(options::OPT_Qunused_arguments)) 3602 continue; 3603 3604 // Special case when final phase determined by binary name, rather than 3605 // by a command-line argument with a corresponding Arg. 3606 if (CCCIsCPP()) 3607 Diag(clang::diag::warn_drv_input_file_unused_by_cpp) 3608 << InputArg->getAsString(Args) << getPhaseName(InitialPhase); 3609 // Special case '-E' warning on a previously preprocessed file to make 3610 // more sense. 3611 else if (InitialPhase == phases::Compile && 3612 (Args.getLastArg(options::OPT__SLASH_EP, 3613 options::OPT__SLASH_P) || 3614 Args.getLastArg(options::OPT_E) || 3615 Args.getLastArg(options::OPT_M, options::OPT_MM)) && 3616 getPreprocessedType(InputType) == types::TY_INVALID) 3617 Diag(clang::diag::warn_drv_preprocessed_input_file_unused) 3618 << InputArg->getAsString(Args) << !!FinalPhaseArg 3619 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""); 3620 else 3621 Diag(clang::diag::warn_drv_input_file_unused) 3622 << InputArg->getAsString(Args) << getPhaseName(InitialPhase) 3623 << !!FinalPhaseArg 3624 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""); 3625 continue; 3626 } 3627 3628 if (YcArg) { 3629 // Add a separate precompile phase for the compile phase. 3630 if (FinalPhase >= phases::Compile) { 3631 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType); 3632 // Build the pipeline for the pch file. 3633 Action *ClangClPch = C.MakeAction<InputAction>(*InputArg, HeaderType); 3634 for (phases::ID Phase : types::getCompilationPhases(HeaderType)) 3635 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch); 3636 assert(ClangClPch); 3637 Actions.push_back(ClangClPch); 3638 // The driver currently exits after the first failed command. This 3639 // relies on that behavior, to make sure if the pch generation fails, 3640 // the main compilation won't run. 3641 // FIXME: If the main compilation fails, the PCH generation should 3642 // probably not be considered successful either. 3643 } 3644 } 3645 } 3646 3647 // If we are linking, claim any options which are obviously only used for 3648 // compilation. 3649 // FIXME: Understand why the last Phase List length is used here. 3650 if (FinalPhase == phases::Link && LastPLSize == 1) { 3651 Args.ClaimAllArgs(options::OPT_CompileOnly_Group); 3652 Args.ClaimAllArgs(options::OPT_cl_compile_Group); 3653 } 3654 } 3655 3656 void Driver::BuildActions(Compilation &C, DerivedArgList &Args, 3657 const InputList &Inputs, ActionList &Actions) const { 3658 llvm::PrettyStackTraceString CrashInfo("Building compilation actions"); 3659 3660 if (!SuppressMissingInputWarning && Inputs.empty()) { 3661 Diag(clang::diag::err_drv_no_input_files); 3662 return; 3663 } 3664 3665 // Reject -Z* at the top level, these options should never have been exposed 3666 // by gcc. 3667 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined)) 3668 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args); 3669 3670 // Diagnose misuse of /Fo. 3671 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) { 3672 StringRef V = A->getValue(); 3673 if (Inputs.size() > 1 && !V.empty() && 3674 !llvm::sys::path::is_separator(V.back())) { 3675 // Check whether /Fo tries to name an output file for multiple inputs. 3676 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources) 3677 << A->getSpelling() << V; 3678 Args.eraseArg(options::OPT__SLASH_Fo); 3679 } 3680 } 3681 3682 // Diagnose misuse of /Fa. 3683 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) { 3684 StringRef V = A->getValue(); 3685 if (Inputs.size() > 1 && !V.empty() && 3686 !llvm::sys::path::is_separator(V.back())) { 3687 // Check whether /Fa tries to name an asm file for multiple inputs. 3688 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources) 3689 << A->getSpelling() << V; 3690 Args.eraseArg(options::OPT__SLASH_Fa); 3691 } 3692 } 3693 3694 // Diagnose misuse of /o. 3695 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) { 3696 if (A->getValue()[0] == '\0') { 3697 // It has to have a value. 3698 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1; 3699 Args.eraseArg(options::OPT__SLASH_o); 3700 } 3701 } 3702 3703 handleArguments(C, Args, Inputs, Actions); 3704 3705 // Builder to be used to build offloading actions. 3706 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs); 3707 3708 // Construct the actions to perform. 3709 HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr; 3710 ActionList LinkerInputs; 3711 ActionList MergerInputs; 3712 3713 for (auto &I : Inputs) { 3714 types::ID InputType = I.first; 3715 const Arg *InputArg = I.second; 3716 3717 auto PL = types::getCompilationPhases(*this, Args, InputType); 3718 if (PL.empty()) 3719 continue; 3720 3721 auto FullPL = types::getCompilationPhases(InputType); 3722 3723 // Build the pipeline for this file. 3724 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType); 3725 3726 // Use the current host action in any of the offloading actions, if 3727 // required. 3728 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg)) 3729 break; 3730 3731 for (phases::ID Phase : PL) { 3732 3733 // Add any offload action the host action depends on. 3734 Current = OffloadBuilder.addDeviceDependencesToHostAction( 3735 Current, InputArg, Phase, PL.back(), FullPL); 3736 if (!Current) 3737 break; 3738 3739 // Queue linker inputs. 3740 if (Phase == phases::Link) { 3741 assert(Phase == PL.back() && "linking must be final compilation step."); 3742 LinkerInputs.push_back(Current); 3743 Current = nullptr; 3744 break; 3745 } 3746 3747 // TODO: Consider removing this because the merged may not end up being 3748 // the final Phase in the pipeline. Perhaps the merged could just merge 3749 // and then pass an artifact of some sort to the Link Phase. 3750 // Queue merger inputs. 3751 if (Phase == phases::IfsMerge) { 3752 assert(Phase == PL.back() && "merging must be final compilation step."); 3753 MergerInputs.push_back(Current); 3754 Current = nullptr; 3755 break; 3756 } 3757 3758 // Each precompiled header file after a module file action is a module 3759 // header of that same module file, rather than being compiled to a 3760 // separate PCH. 3761 if (Phase == phases::Precompile && HeaderModuleAction && 3762 getPrecompiledType(InputType) == types::TY_PCH) { 3763 HeaderModuleAction->addModuleHeaderInput(Current); 3764 Current = nullptr; 3765 break; 3766 } 3767 3768 // FIXME: Should we include any prior module file outputs as inputs of 3769 // later actions in the same command line? 3770 3771 // Otherwise construct the appropriate action. 3772 Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current); 3773 3774 // We didn't create a new action, so we will just move to the next phase. 3775 if (NewCurrent == Current) 3776 continue; 3777 3778 if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent)) 3779 HeaderModuleAction = HMA; 3780 3781 Current = NewCurrent; 3782 3783 // Use the current host action in any of the offloading actions, if 3784 // required. 3785 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg)) 3786 break; 3787 3788 if (Current->getType() == types::TY_Nothing) 3789 break; 3790 } 3791 3792 // If we ended with something, add to the output list. 3793 if (Current) 3794 Actions.push_back(Current); 3795 3796 // Add any top level actions generated for offloading. 3797 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg); 3798 } 3799 3800 // Add a link action if necessary. 3801 if (!LinkerInputs.empty()) { 3802 if (Action *Wrapper = OffloadBuilder.makeHostLinkAction()) 3803 LinkerInputs.push_back(Wrapper); 3804 Action *LA; 3805 // Check if this Linker Job should emit a static library. 3806 if (ShouldEmitStaticLibrary(Args)) { 3807 LA = C.MakeAction<StaticLibJobAction>(LinkerInputs, types::TY_Image); 3808 } else { 3809 LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image); 3810 } 3811 LA = OffloadBuilder.processHostLinkAction(LA); 3812 Actions.push_back(LA); 3813 } 3814 3815 // Add an interface stubs merge action if necessary. 3816 if (!MergerInputs.empty()) 3817 Actions.push_back( 3818 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image)); 3819 3820 if (Args.hasArg(options::OPT_emit_interface_stubs)) { 3821 auto PhaseList = types::getCompilationPhases( 3822 types::TY_IFS_CPP, 3823 Args.hasArg(options::OPT_c) ? phases::Compile : phases::LastPhase); 3824 3825 ActionList MergerInputs; 3826 3827 for (auto &I : Inputs) { 3828 types::ID InputType = I.first; 3829 const Arg *InputArg = I.second; 3830 3831 // Currently clang and the llvm assembler do not support generating symbol 3832 // stubs from assembly, so we skip the input on asm files. For ifs files 3833 // we rely on the normal pipeline setup in the pipeline setup code above. 3834 if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm || 3835 InputType == types::TY_Asm) 3836 continue; 3837 3838 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType); 3839 3840 for (auto Phase : PhaseList) { 3841 switch (Phase) { 3842 default: 3843 llvm_unreachable( 3844 "IFS Pipeline can only consist of Compile followed by IfsMerge."); 3845 case phases::Compile: { 3846 // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs 3847 // files where the .o file is located. The compile action can not 3848 // handle this. 3849 if (InputType == types::TY_Object) 3850 break; 3851 3852 Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP); 3853 break; 3854 } 3855 case phases::IfsMerge: { 3856 assert(Phase == PhaseList.back() && 3857 "merging must be final compilation step."); 3858 MergerInputs.push_back(Current); 3859 Current = nullptr; 3860 break; 3861 } 3862 } 3863 } 3864 3865 // If we ended with something, add to the output list. 3866 if (Current) 3867 Actions.push_back(Current); 3868 } 3869 3870 // Add an interface stubs merge action if necessary. 3871 if (!MergerInputs.empty()) 3872 Actions.push_back( 3873 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image)); 3874 } 3875 3876 // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a custom 3877 // Compile phase that prints out supported cpu models and quits. 3878 if (Arg *A = Args.getLastArg(options::OPT_print_supported_cpus)) { 3879 // Use the -mcpu=? flag as the dummy input to cc1. 3880 Actions.clear(); 3881 Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C); 3882 Actions.push_back( 3883 C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing)); 3884 for (auto &I : Inputs) 3885 I.second->claim(); 3886 } 3887 3888 // Claim ignored clang-cl options. 3889 Args.ClaimAllArgs(options::OPT_cl_ignored_Group); 3890 3891 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed 3892 // to non-CUDA compilations and should not trigger warnings there. 3893 Args.ClaimAllArgs(options::OPT_cuda_host_only); 3894 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device); 3895 } 3896 3897 Action *Driver::ConstructPhaseAction( 3898 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input, 3899 Action::OffloadKind TargetDeviceOffloadKind) const { 3900 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions"); 3901 3902 // Some types skip the assembler phase (e.g., llvm-bc), but we can't 3903 // encode this in the steps because the intermediate type depends on 3904 // arguments. Just special case here. 3905 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm) 3906 return Input; 3907 3908 // Build the appropriate action. 3909 switch (Phase) { 3910 case phases::Link: 3911 llvm_unreachable("link action invalid here."); 3912 case phases::IfsMerge: 3913 llvm_unreachable("ifsmerge action invalid here."); 3914 case phases::Preprocess: { 3915 types::ID OutputTy; 3916 // -M and -MM specify the dependency file name by altering the output type, 3917 // -if -MD and -MMD are not specified. 3918 if (Args.hasArg(options::OPT_M, options::OPT_MM) && 3919 !Args.hasArg(options::OPT_MD, options::OPT_MMD)) { 3920 OutputTy = types::TY_Dependencies; 3921 } else { 3922 OutputTy = Input->getType(); 3923 if (!Args.hasFlag(options::OPT_frewrite_includes, 3924 options::OPT_fno_rewrite_includes, false) && 3925 !Args.hasFlag(options::OPT_frewrite_imports, 3926 options::OPT_fno_rewrite_imports, false) && 3927 !CCGenDiagnostics) 3928 OutputTy = types::getPreprocessedType(OutputTy); 3929 assert(OutputTy != types::TY_INVALID && 3930 "Cannot preprocess this input type!"); 3931 } 3932 return C.MakeAction<PreprocessJobAction>(Input, OutputTy); 3933 } 3934 case phases::Precompile: { 3935 types::ID OutputTy = getPrecompiledType(Input->getType()); 3936 assert(OutputTy != types::TY_INVALID && 3937 "Cannot precompile this input type!"); 3938 3939 // If we're given a module name, precompile header file inputs as a 3940 // module, not as a precompiled header. 3941 const char *ModName = nullptr; 3942 if (OutputTy == types::TY_PCH) { 3943 if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ)) 3944 ModName = A->getValue(); 3945 if (ModName) 3946 OutputTy = types::TY_ModuleFile; 3947 } 3948 3949 if (Args.hasArg(options::OPT_fsyntax_only)) { 3950 // Syntax checks should not emit a PCH file 3951 OutputTy = types::TY_Nothing; 3952 } 3953 3954 if (ModName) 3955 return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy, 3956 ModName); 3957 return C.MakeAction<PrecompileJobAction>(Input, OutputTy); 3958 } 3959 case phases::Compile: { 3960 if (Args.hasArg(options::OPT_fsyntax_only)) 3961 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing); 3962 if (Args.hasArg(options::OPT_rewrite_objc)) 3963 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC); 3964 if (Args.hasArg(options::OPT_rewrite_legacy_objc)) 3965 return C.MakeAction<CompileJobAction>(Input, 3966 types::TY_RewrittenLegacyObjC); 3967 if (Args.hasArg(options::OPT__analyze)) 3968 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist); 3969 if (Args.hasArg(options::OPT__migrate)) 3970 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap); 3971 if (Args.hasArg(options::OPT_emit_ast)) 3972 return C.MakeAction<CompileJobAction>(Input, types::TY_AST); 3973 if (Args.hasArg(options::OPT_module_file_info)) 3974 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile); 3975 if (Args.hasArg(options::OPT_verify_pch)) 3976 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing); 3977 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC); 3978 } 3979 case phases::Backend: { 3980 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) { 3981 types::ID Output = 3982 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC; 3983 return C.MakeAction<BackendJobAction>(Input, Output); 3984 } 3985 if (Args.hasArg(options::OPT_emit_llvm) || 3986 (TargetDeviceOffloadKind == Action::OFK_HIP && 3987 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, 3988 false))) { 3989 types::ID Output = 3990 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC; 3991 return C.MakeAction<BackendJobAction>(Input, Output); 3992 } 3993 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm); 3994 } 3995 case phases::Assemble: 3996 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object); 3997 } 3998 3999 llvm_unreachable("invalid phase in ConstructPhaseAction"); 4000 } 4001 4002 void Driver::BuildJobs(Compilation &C) const { 4003 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 4004 4005 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 4006 4007 // It is an error to provide a -o option if we are making multiple output 4008 // files. There are exceptions: 4009 // 4010 // IfsMergeJob: when generating interface stubs enabled we want to be able to 4011 // generate the stub file at the same time that we generate the real 4012 // library/a.out. So when a .o, .so, etc are the output, with clang interface 4013 // stubs there will also be a .ifs and .ifso at the same location. 4014 // 4015 // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled 4016 // and -c is passed, we still want to be able to generate a .ifs file while 4017 // we are also generating .o files. So we allow more than one output file in 4018 // this case as well. 4019 // 4020 if (FinalOutput) { 4021 unsigned NumOutputs = 0; 4022 unsigned NumIfsOutputs = 0; 4023 for (const Action *A : C.getActions()) 4024 if (A->getType() != types::TY_Nothing && 4025 !(A->getKind() == Action::IfsMergeJobClass || 4026 (A->getType() == clang::driver::types::TY_IFS_CPP && 4027 A->getKind() == clang::driver::Action::CompileJobClass && 4028 0 == NumIfsOutputs++) || 4029 (A->getKind() == Action::BindArchClass && A->getInputs().size() && 4030 A->getInputs().front()->getKind() == Action::IfsMergeJobClass))) 4031 ++NumOutputs; 4032 4033 if (NumOutputs > 1) { 4034 Diag(clang::diag::err_drv_output_argument_with_multiple_files); 4035 FinalOutput = nullptr; 4036 } 4037 } 4038 4039 const llvm::Triple &RawTriple = C.getDefaultToolChain().getTriple(); 4040 if (RawTriple.isOSAIX()) { 4041 if (Arg *A = C.getArgs().getLastArg(options::OPT_G)) 4042 Diag(diag::err_drv_unsupported_opt_for_target) 4043 << A->getSpelling() << RawTriple.str(); 4044 if (LTOMode == LTOK_Thin) 4045 Diag(diag::err_drv_clang_unsupported) << "thinLTO on AIX"; 4046 } 4047 4048 // Collect the list of architectures. 4049 llvm::StringSet<> ArchNames; 4050 if (RawTriple.isOSBinFormatMachO()) 4051 for (const Arg *A : C.getArgs()) 4052 if (A->getOption().matches(options::OPT_arch)) 4053 ArchNames.insert(A->getValue()); 4054 4055 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for. 4056 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults; 4057 for (Action *A : C.getActions()) { 4058 // If we are linking an image for multiple archs then the linker wants 4059 // -arch_multiple and -final_output <final image name>. Unfortunately, this 4060 // doesn't fit in cleanly because we have to pass this information down. 4061 // 4062 // FIXME: This is a hack; find a cleaner way to integrate this into the 4063 // process. 4064 const char *LinkingOutput = nullptr; 4065 if (isa<LipoJobAction>(A)) { 4066 if (FinalOutput) 4067 LinkingOutput = FinalOutput->getValue(); 4068 else 4069 LinkingOutput = getDefaultImageName(); 4070 } 4071 4072 BuildJobsForAction(C, A, &C.getDefaultToolChain(), 4073 /*BoundArch*/ StringRef(), 4074 /*AtTopLevel*/ true, 4075 /*MultipleArchs*/ ArchNames.size() > 1, 4076 /*LinkingOutput*/ LinkingOutput, CachedResults, 4077 /*TargetDeviceOffloadKind*/ Action::OFK_None); 4078 } 4079 4080 // If we have more than one job, then disable integrated-cc1 for now. Do this 4081 // also when we need to report process execution statistics. 4082 if (C.getJobs().size() > 1 || CCPrintProcessStats) 4083 for (auto &J : C.getJobs()) 4084 J.InProcess = false; 4085 4086 if (CCPrintProcessStats) { 4087 C.setPostCallback([=](const Command &Cmd, int Res) { 4088 Optional<llvm::sys::ProcessStatistics> ProcStat = 4089 Cmd.getProcessStatistics(); 4090 if (!ProcStat) 4091 return; 4092 4093 const char *LinkingOutput = nullptr; 4094 if (FinalOutput) 4095 LinkingOutput = FinalOutput->getValue(); 4096 else if (!Cmd.getOutputFilenames().empty()) 4097 LinkingOutput = Cmd.getOutputFilenames().front().c_str(); 4098 else 4099 LinkingOutput = getDefaultImageName(); 4100 4101 if (CCPrintStatReportFilename.empty()) { 4102 using namespace llvm; 4103 // Human readable output. 4104 outs() << sys::path::filename(Cmd.getExecutable()) << ": " 4105 << "output=" << LinkingOutput; 4106 outs() << ", total=" 4107 << format("%.3f", ProcStat->TotalTime.count() / 1000.) << " ms" 4108 << ", user=" 4109 << format("%.3f", ProcStat->UserTime.count() / 1000.) << " ms" 4110 << ", mem=" << ProcStat->PeakMemory << " Kb\n"; 4111 } else { 4112 // CSV format. 4113 std::string Buffer; 4114 llvm::raw_string_ostream Out(Buffer); 4115 llvm::sys::printArg(Out, llvm::sys::path::filename(Cmd.getExecutable()), 4116 /*Quote*/ true); 4117 Out << ','; 4118 llvm::sys::printArg(Out, LinkingOutput, true); 4119 Out << ',' << ProcStat->TotalTime.count() << ',' 4120 << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory 4121 << '\n'; 4122 Out.flush(); 4123 std::error_code EC; 4124 llvm::raw_fd_ostream OS(CCPrintStatReportFilename, EC, 4125 llvm::sys::fs::OF_Append | 4126 llvm::sys::fs::OF_Text); 4127 if (EC) 4128 return; 4129 auto L = OS.lock(); 4130 if (!L) { 4131 llvm::errs() << "ERROR: Cannot lock file " 4132 << CCPrintStatReportFilename << ": " 4133 << toString(L.takeError()) << "\n"; 4134 return; 4135 } 4136 OS << Buffer; 4137 OS.flush(); 4138 } 4139 }); 4140 } 4141 4142 // If the user passed -Qunused-arguments or there were errors, don't warn 4143 // about any unused arguments. 4144 if (Diags.hasErrorOccurred() || 4145 C.getArgs().hasArg(options::OPT_Qunused_arguments)) 4146 return; 4147 4148 // Claim -### here. 4149 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH); 4150 4151 // Claim --driver-mode, --rsp-quoting, it was handled earlier. 4152 (void)C.getArgs().hasArg(options::OPT_driver_mode); 4153 (void)C.getArgs().hasArg(options::OPT_rsp_quoting); 4154 4155 for (Arg *A : C.getArgs()) { 4156 // FIXME: It would be nice to be able to send the argument to the 4157 // DiagnosticsEngine, so that extra values, position, and so on could be 4158 // printed. 4159 if (!A->isClaimed()) { 4160 if (A->getOption().hasFlag(options::NoArgumentUnused)) 4161 continue; 4162 4163 // Suppress the warning automatically if this is just a flag, and it is an 4164 // instance of an argument we already claimed. 4165 const Option &Opt = A->getOption(); 4166 if (Opt.getKind() == Option::FlagClass) { 4167 bool DuplicateClaimed = false; 4168 4169 for (const Arg *AA : C.getArgs().filtered(&Opt)) { 4170 if (AA->isClaimed()) { 4171 DuplicateClaimed = true; 4172 break; 4173 } 4174 } 4175 4176 if (DuplicateClaimed) 4177 continue; 4178 } 4179 4180 // In clang-cl, don't mention unknown arguments here since they have 4181 // already been warned about. 4182 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN)) 4183 Diag(clang::diag::warn_drv_unused_argument) 4184 << A->getAsString(C.getArgs()); 4185 } 4186 } 4187 } 4188 4189 namespace { 4190 /// Utility class to control the collapse of dependent actions and select the 4191 /// tools accordingly. 4192 class ToolSelector final { 4193 /// The tool chain this selector refers to. 4194 const ToolChain &TC; 4195 4196 /// The compilation this selector refers to. 4197 const Compilation &C; 4198 4199 /// The base action this selector refers to. 4200 const JobAction *BaseAction; 4201 4202 /// Set to true if the current toolchain refers to host actions. 4203 bool IsHostSelector; 4204 4205 /// Set to true if save-temps and embed-bitcode functionalities are active. 4206 bool SaveTemps; 4207 bool EmbedBitcode; 4208 4209 /// Get previous dependent action or null if that does not exist. If 4210 /// \a CanBeCollapsed is false, that action must be legal to collapse or 4211 /// null will be returned. 4212 const JobAction *getPrevDependentAction(const ActionList &Inputs, 4213 ActionList &SavedOffloadAction, 4214 bool CanBeCollapsed = true) { 4215 // An option can be collapsed only if it has a single input. 4216 if (Inputs.size() != 1) 4217 return nullptr; 4218 4219 Action *CurAction = *Inputs.begin(); 4220 if (CanBeCollapsed && 4221 !CurAction->isCollapsingWithNextDependentActionLegal()) 4222 return nullptr; 4223 4224 // If the input action is an offload action. Look through it and save any 4225 // offload action that can be dropped in the event of a collapse. 4226 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) { 4227 // If the dependent action is a device action, we will attempt to collapse 4228 // only with other device actions. Otherwise, we would do the same but 4229 // with host actions only. 4230 if (!IsHostSelector) { 4231 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) { 4232 CurAction = 4233 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true); 4234 if (CanBeCollapsed && 4235 !CurAction->isCollapsingWithNextDependentActionLegal()) 4236 return nullptr; 4237 SavedOffloadAction.push_back(OA); 4238 return dyn_cast<JobAction>(CurAction); 4239 } 4240 } else if (OA->hasHostDependence()) { 4241 CurAction = OA->getHostDependence(); 4242 if (CanBeCollapsed && 4243 !CurAction->isCollapsingWithNextDependentActionLegal()) 4244 return nullptr; 4245 SavedOffloadAction.push_back(OA); 4246 return dyn_cast<JobAction>(CurAction); 4247 } 4248 return nullptr; 4249 } 4250 4251 return dyn_cast<JobAction>(CurAction); 4252 } 4253 4254 /// Return true if an assemble action can be collapsed. 4255 bool canCollapseAssembleAction() const { 4256 return TC.useIntegratedAs() && !SaveTemps && 4257 !C.getArgs().hasArg(options::OPT_via_file_asm) && 4258 !C.getArgs().hasArg(options::OPT__SLASH_FA) && 4259 !C.getArgs().hasArg(options::OPT__SLASH_Fa); 4260 } 4261 4262 /// Return true if a preprocessor action can be collapsed. 4263 bool canCollapsePreprocessorAction() const { 4264 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) && 4265 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps && 4266 !C.getArgs().hasArg(options::OPT_rewrite_objc); 4267 } 4268 4269 /// Struct that relates an action with the offload actions that would be 4270 /// collapsed with it. 4271 struct JobActionInfo final { 4272 /// The action this info refers to. 4273 const JobAction *JA = nullptr; 4274 /// The offload actions we need to take care off if this action is 4275 /// collapsed. 4276 ActionList SavedOffloadAction; 4277 }; 4278 4279 /// Append collapsed offload actions from the give nnumber of elements in the 4280 /// action info array. 4281 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction, 4282 ArrayRef<JobActionInfo> &ActionInfo, 4283 unsigned ElementNum) { 4284 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements."); 4285 for (unsigned I = 0; I < ElementNum; ++I) 4286 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(), 4287 ActionInfo[I].SavedOffloadAction.end()); 4288 } 4289 4290 /// Functions that attempt to perform the combining. They detect if that is 4291 /// legal, and if so they update the inputs \a Inputs and the offload action 4292 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with 4293 /// the combined action is returned. If the combining is not legal or if the 4294 /// tool does not exist, null is returned. 4295 /// Currently three kinds of collapsing are supported: 4296 /// - Assemble + Backend + Compile; 4297 /// - Assemble + Backend ; 4298 /// - Backend + Compile. 4299 const Tool * 4300 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo, 4301 ActionList &Inputs, 4302 ActionList &CollapsedOffloadAction) { 4303 if (ActionInfo.size() < 3 || !canCollapseAssembleAction()) 4304 return nullptr; 4305 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA); 4306 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA); 4307 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA); 4308 if (!AJ || !BJ || !CJ) 4309 return nullptr; 4310 4311 // Get compiler tool. 4312 const Tool *T = TC.SelectTool(*CJ); 4313 if (!T) 4314 return nullptr; 4315 4316 // When using -fembed-bitcode, it is required to have the same tool (clang) 4317 // for both CompilerJA and BackendJA. Otherwise, combine two stages. 4318 if (EmbedBitcode) { 4319 const Tool *BT = TC.SelectTool(*BJ); 4320 if (BT == T) 4321 return nullptr; 4322 } 4323 4324 if (!T->hasIntegratedAssembler()) 4325 return nullptr; 4326 4327 Inputs = CJ->getInputs(); 4328 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, 4329 /*NumElements=*/3); 4330 return T; 4331 } 4332 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo, 4333 ActionList &Inputs, 4334 ActionList &CollapsedOffloadAction) { 4335 if (ActionInfo.size() < 2 || !canCollapseAssembleAction()) 4336 return nullptr; 4337 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA); 4338 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA); 4339 if (!AJ || !BJ) 4340 return nullptr; 4341 4342 // Get backend tool. 4343 const Tool *T = TC.SelectTool(*BJ); 4344 if (!T) 4345 return nullptr; 4346 4347 if (!T->hasIntegratedAssembler()) 4348 return nullptr; 4349 4350 Inputs = BJ->getInputs(); 4351 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, 4352 /*NumElements=*/2); 4353 return T; 4354 } 4355 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo, 4356 ActionList &Inputs, 4357 ActionList &CollapsedOffloadAction) { 4358 if (ActionInfo.size() < 2) 4359 return nullptr; 4360 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA); 4361 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA); 4362 if (!BJ || !CJ) 4363 return nullptr; 4364 4365 // Check if the initial input (to the compile job or its predessor if one 4366 // exists) is LLVM bitcode. In that case, no preprocessor step is required 4367 // and we can still collapse the compile and backend jobs when we have 4368 // -save-temps. I.e. there is no need for a separate compile job just to 4369 // emit unoptimized bitcode. 4370 bool InputIsBitcode = true; 4371 for (size_t i = 1; i < ActionInfo.size(); i++) 4372 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC && 4373 ActionInfo[i].JA->getType() != types::TY_LTO_BC) { 4374 InputIsBitcode = false; 4375 break; 4376 } 4377 if (!InputIsBitcode && !canCollapsePreprocessorAction()) 4378 return nullptr; 4379 4380 // Get compiler tool. 4381 const Tool *T = TC.SelectTool(*CJ); 4382 if (!T) 4383 return nullptr; 4384 4385 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode)) 4386 return nullptr; 4387 4388 Inputs = CJ->getInputs(); 4389 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, 4390 /*NumElements=*/2); 4391 return T; 4392 } 4393 4394 /// Updates the inputs if the obtained tool supports combining with 4395 /// preprocessor action, and the current input is indeed a preprocessor 4396 /// action. If combining results in the collapse of offloading actions, those 4397 /// are appended to \a CollapsedOffloadAction. 4398 void combineWithPreprocessor(const Tool *T, ActionList &Inputs, 4399 ActionList &CollapsedOffloadAction) { 4400 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP()) 4401 return; 4402 4403 // Attempt to get a preprocessor action dependence. 4404 ActionList PreprocessJobOffloadActions; 4405 ActionList NewInputs; 4406 for (Action *A : Inputs) { 4407 auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions); 4408 if (!PJ || !isa<PreprocessJobAction>(PJ)) { 4409 NewInputs.push_back(A); 4410 continue; 4411 } 4412 4413 // This is legal to combine. Append any offload action we found and add the 4414 // current input to preprocessor inputs. 4415 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(), 4416 PreprocessJobOffloadActions.end()); 4417 NewInputs.append(PJ->input_begin(), PJ->input_end()); 4418 } 4419 Inputs = NewInputs; 4420 } 4421 4422 public: 4423 ToolSelector(const JobAction *BaseAction, const ToolChain &TC, 4424 const Compilation &C, bool SaveTemps, bool EmbedBitcode) 4425 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps), 4426 EmbedBitcode(EmbedBitcode) { 4427 assert(BaseAction && "Invalid base action."); 4428 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None; 4429 } 4430 4431 /// Check if a chain of actions can be combined and return the tool that can 4432 /// handle the combination of actions. The pointer to the current inputs \a 4433 /// Inputs and the list of offload actions \a CollapsedOffloadActions 4434 /// connected to collapsed actions are updated accordingly. The latter enables 4435 /// the caller of the selector to process them afterwards instead of just 4436 /// dropping them. If no suitable tool is found, null will be returned. 4437 const Tool *getTool(ActionList &Inputs, 4438 ActionList &CollapsedOffloadAction) { 4439 // 4440 // Get the largest chain of actions that we could combine. 4441 // 4442 4443 SmallVector<JobActionInfo, 5> ActionChain(1); 4444 ActionChain.back().JA = BaseAction; 4445 while (ActionChain.back().JA) { 4446 const Action *CurAction = ActionChain.back().JA; 4447 4448 // Grow the chain by one element. 4449 ActionChain.resize(ActionChain.size() + 1); 4450 JobActionInfo &AI = ActionChain.back(); 4451 4452 // Attempt to fill it with the 4453 AI.JA = 4454 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction); 4455 } 4456 4457 // Pop the last action info as it could not be filled. 4458 ActionChain.pop_back(); 4459 4460 // 4461 // Attempt to combine actions. If all combining attempts failed, just return 4462 // the tool of the provided action. At the end we attempt to combine the 4463 // action with any preprocessor action it may depend on. 4464 // 4465 4466 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs, 4467 CollapsedOffloadAction); 4468 if (!T) 4469 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction); 4470 if (!T) 4471 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction); 4472 if (!T) { 4473 Inputs = BaseAction->getInputs(); 4474 T = TC.SelectTool(*BaseAction); 4475 } 4476 4477 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction); 4478 return T; 4479 } 4480 }; 4481 } 4482 4483 /// Return a string that uniquely identifies the result of a job. The bound arch 4484 /// is not necessarily represented in the toolchain's triple -- for example, 4485 /// armv7 and armv7s both map to the same triple -- so we need both in our map. 4486 /// Also, we need to add the offloading device kind, as the same tool chain can 4487 /// be used for host and device for some programming models, e.g. OpenMP. 4488 static std::string GetTriplePlusArchString(const ToolChain *TC, 4489 StringRef BoundArch, 4490 Action::OffloadKind OffloadKind) { 4491 std::string TriplePlusArch = TC->getTriple().normalize(); 4492 if (!BoundArch.empty()) { 4493 TriplePlusArch += "-"; 4494 TriplePlusArch += BoundArch; 4495 } 4496 TriplePlusArch += "-"; 4497 TriplePlusArch += Action::GetOffloadKindName(OffloadKind); 4498 return TriplePlusArch; 4499 } 4500 4501 InputInfo Driver::BuildJobsForAction( 4502 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch, 4503 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 4504 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults, 4505 Action::OffloadKind TargetDeviceOffloadKind) const { 4506 std::pair<const Action *, std::string> ActionTC = { 4507 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)}; 4508 auto CachedResult = CachedResults.find(ActionTC); 4509 if (CachedResult != CachedResults.end()) { 4510 return CachedResult->second; 4511 } 4512 InputInfo Result = BuildJobsForActionNoCache( 4513 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput, 4514 CachedResults, TargetDeviceOffloadKind); 4515 CachedResults[ActionTC] = Result; 4516 return Result; 4517 } 4518 4519 InputInfo Driver::BuildJobsForActionNoCache( 4520 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch, 4521 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 4522 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults, 4523 Action::OffloadKind TargetDeviceOffloadKind) const { 4524 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 4525 4526 InputInfoList OffloadDependencesInputInfo; 4527 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None; 4528 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) { 4529 // The 'Darwin' toolchain is initialized only when its arguments are 4530 // computed. Get the default arguments for OFK_None to ensure that 4531 // initialization is performed before processing the offload action. 4532 // FIXME: Remove when darwin's toolchain is initialized during construction. 4533 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None); 4534 4535 // The offload action is expected to be used in four different situations. 4536 // 4537 // a) Set a toolchain/architecture/kind for a host action: 4538 // Host Action 1 -> OffloadAction -> Host Action 2 4539 // 4540 // b) Set a toolchain/architecture/kind for a device action; 4541 // Device Action 1 -> OffloadAction -> Device Action 2 4542 // 4543 // c) Specify a device dependence to a host action; 4544 // Device Action 1 _ 4545 // \ 4546 // Host Action 1 ---> OffloadAction -> Host Action 2 4547 // 4548 // d) Specify a host dependence to a device action. 4549 // Host Action 1 _ 4550 // \ 4551 // Device Action 1 ---> OffloadAction -> Device Action 2 4552 // 4553 // For a) and b), we just return the job generated for the dependence. For 4554 // c) and d) we override the current action with the host/device dependence 4555 // if the current toolchain is host/device and set the offload dependences 4556 // info with the jobs obtained from the device/host dependence(s). 4557 4558 // If there is a single device option, just generate the job for it. 4559 if (OA->hasSingleDeviceDependence()) { 4560 InputInfo DevA; 4561 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC, 4562 const char *DepBoundArch) { 4563 DevA = 4564 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel, 4565 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, 4566 CachedResults, DepA->getOffloadingDeviceKind()); 4567 }); 4568 return DevA; 4569 } 4570 4571 // If 'Action 2' is host, we generate jobs for the device dependences and 4572 // override the current action with the host dependence. Otherwise, we 4573 // generate the host dependences and override the action with the device 4574 // dependence. The dependences can't therefore be a top-level action. 4575 OA->doOnEachDependence( 4576 /*IsHostDependence=*/BuildingForOffloadDevice, 4577 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { 4578 OffloadDependencesInputInfo.push_back(BuildJobsForAction( 4579 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false, 4580 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults, 4581 DepA->getOffloadingDeviceKind())); 4582 }); 4583 4584 A = BuildingForOffloadDevice 4585 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true) 4586 : OA->getHostDependence(); 4587 } 4588 4589 if (const InputAction *IA = dyn_cast<InputAction>(A)) { 4590 // FIXME: It would be nice to not claim this here; maybe the old scheme of 4591 // just using Args was better? 4592 const Arg &Input = IA->getInputArg(); 4593 Input.claim(); 4594 if (Input.getOption().matches(options::OPT_INPUT)) { 4595 const char *Name = Input.getValue(); 4596 return InputInfo(A, Name, /* _BaseInput = */ Name); 4597 } 4598 return InputInfo(A, &Input, /* _BaseInput = */ ""); 4599 } 4600 4601 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) { 4602 const ToolChain *TC; 4603 StringRef ArchName = BAA->getArchName(); 4604 4605 if (!ArchName.empty()) 4606 TC = &getToolChain(C.getArgs(), 4607 computeTargetTriple(*this, TargetTriple, 4608 C.getArgs(), ArchName)); 4609 else 4610 TC = &C.getDefaultToolChain(); 4611 4612 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel, 4613 MultipleArchs, LinkingOutput, CachedResults, 4614 TargetDeviceOffloadKind); 4615 } 4616 4617 4618 ActionList Inputs = A->getInputs(); 4619 4620 const JobAction *JA = cast<JobAction>(A); 4621 ActionList CollapsedOffloadActions; 4622 4623 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(), 4624 embedBitcodeInObject() && !isUsingLTO()); 4625 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions); 4626 4627 if (!T) 4628 return InputInfo(); 4629 4630 if (BuildingForOffloadDevice && 4631 A->getOffloadingDeviceKind() == Action::OFK_OpenMP) { 4632 if (TC->getTriple().isAMDGCN()) { 4633 // AMDGCN treats backend and assemble actions as no-op because 4634 // linker does not support object files. 4635 if (const BackendJobAction *BA = dyn_cast<BackendJobAction>(A)) { 4636 return BuildJobsForAction(C, *BA->input_begin(), TC, BoundArch, 4637 AtTopLevel, MultipleArchs, LinkingOutput, 4638 CachedResults, TargetDeviceOffloadKind); 4639 } 4640 4641 if (const AssembleJobAction *AA = dyn_cast<AssembleJobAction>(A)) { 4642 return BuildJobsForAction(C, *AA->input_begin(), TC, BoundArch, 4643 AtTopLevel, MultipleArchs, LinkingOutput, 4644 CachedResults, TargetDeviceOffloadKind); 4645 } 4646 } 4647 } 4648 4649 // If we've collapsed action list that contained OffloadAction we 4650 // need to build jobs for host/device-side inputs it may have held. 4651 for (const auto *OA : CollapsedOffloadActions) 4652 cast<OffloadAction>(OA)->doOnEachDependence( 4653 /*IsHostDependence=*/BuildingForOffloadDevice, 4654 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { 4655 OffloadDependencesInputInfo.push_back(BuildJobsForAction( 4656 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false, 4657 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults, 4658 DepA->getOffloadingDeviceKind())); 4659 }); 4660 4661 // Only use pipes when there is exactly one input. 4662 InputInfoList InputInfos; 4663 for (const Action *Input : Inputs) { 4664 // Treat dsymutil and verify sub-jobs as being at the top-level too, they 4665 // shouldn't get temporary output names. 4666 // FIXME: Clean this up. 4667 bool SubJobAtTopLevel = 4668 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A)); 4669 InputInfos.push_back(BuildJobsForAction( 4670 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput, 4671 CachedResults, A->getOffloadingDeviceKind())); 4672 } 4673 4674 // Always use the first input as the base input. 4675 const char *BaseInput = InputInfos[0].getBaseInput(); 4676 4677 // ... except dsymutil actions, which use their actual input as the base 4678 // input. 4679 if (JA->getType() == types::TY_dSYM) 4680 BaseInput = InputInfos[0].getFilename(); 4681 4682 // ... and in header module compilations, which use the module name. 4683 if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA)) 4684 BaseInput = ModuleJA->getModuleName(); 4685 4686 // Append outputs of offload device jobs to the input list 4687 if (!OffloadDependencesInputInfo.empty()) 4688 InputInfos.append(OffloadDependencesInputInfo.begin(), 4689 OffloadDependencesInputInfo.end()); 4690 4691 // Set the effective triple of the toolchain for the duration of this job. 4692 llvm::Triple EffectiveTriple; 4693 const ToolChain &ToolTC = T->getToolChain(); 4694 const ArgList &Args = 4695 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind()); 4696 if (InputInfos.size() != 1) { 4697 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args)); 4698 } else { 4699 // Pass along the input type if it can be unambiguously determined. 4700 EffectiveTriple = llvm::Triple( 4701 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType())); 4702 } 4703 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple); 4704 4705 // Determine the place to write output to, if any. 4706 InputInfo Result; 4707 InputInfoList UnbundlingResults; 4708 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) { 4709 // If we have an unbundling job, we need to create results for all the 4710 // outputs. We also update the results cache so that other actions using 4711 // this unbundling action can get the right results. 4712 for (auto &UI : UA->getDependentActionsInfo()) { 4713 assert(UI.DependentOffloadKind != Action::OFK_None && 4714 "Unbundling with no offloading??"); 4715 4716 // Unbundling actions are never at the top level. When we generate the 4717 // offloading prefix, we also do that for the host file because the 4718 // unbundling action does not change the type of the output which can 4719 // cause a overwrite. 4720 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix( 4721 UI.DependentOffloadKind, 4722 UI.DependentToolChain->getTriple().normalize(), 4723 /*CreatePrefixForHost=*/true); 4724 auto CurI = InputInfo( 4725 UA, 4726 GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch, 4727 /*AtTopLevel=*/false, 4728 MultipleArchs || 4729 UI.DependentOffloadKind == Action::OFK_HIP, 4730 OffloadingPrefix), 4731 BaseInput); 4732 // Save the unbundling result. 4733 UnbundlingResults.push_back(CurI); 4734 4735 // Get the unique string identifier for this dependence and cache the 4736 // result. 4737 StringRef Arch; 4738 if (TargetDeviceOffloadKind == Action::OFK_HIP) { 4739 if (UI.DependentOffloadKind == Action::OFK_Host) 4740 Arch = StringRef(); 4741 else 4742 Arch = UI.DependentBoundArch; 4743 } else 4744 Arch = BoundArch; 4745 4746 CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch, 4747 UI.DependentOffloadKind)}] = 4748 CurI; 4749 } 4750 4751 // Now that we have all the results generated, select the one that should be 4752 // returned for the current depending action. 4753 std::pair<const Action *, std::string> ActionTC = { 4754 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)}; 4755 assert(CachedResults.find(ActionTC) != CachedResults.end() && 4756 "Result does not exist??"); 4757 Result = CachedResults[ActionTC]; 4758 } else if (JA->getType() == types::TY_Nothing) 4759 Result = InputInfo(A, BaseInput); 4760 else { 4761 // We only have to generate a prefix for the host if this is not a top-level 4762 // action. 4763 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix( 4764 A->getOffloadingDeviceKind(), TC->getTriple().normalize(), 4765 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() && 4766 !AtTopLevel); 4767 if (isa<OffloadWrapperJobAction>(JA)) { 4768 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) 4769 BaseInput = FinalOutput->getValue(); 4770 else 4771 BaseInput = getDefaultImageName(); 4772 BaseInput = 4773 C.getArgs().MakeArgString(std::string(BaseInput) + "-wrapper"); 4774 } 4775 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch, 4776 AtTopLevel, MultipleArchs, 4777 OffloadingPrefix), 4778 BaseInput); 4779 } 4780 4781 if (CCCPrintBindings && !CCGenDiagnostics) { 4782 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"' 4783 << " - \"" << T->getName() << "\", inputs: ["; 4784 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) { 4785 llvm::errs() << InputInfos[i].getAsString(); 4786 if (i + 1 != e) 4787 llvm::errs() << ", "; 4788 } 4789 if (UnbundlingResults.empty()) 4790 llvm::errs() << "], output: " << Result.getAsString() << "\n"; 4791 else { 4792 llvm::errs() << "], outputs: ["; 4793 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) { 4794 llvm::errs() << UnbundlingResults[i].getAsString(); 4795 if (i + 1 != e) 4796 llvm::errs() << ", "; 4797 } 4798 llvm::errs() << "] \n"; 4799 } 4800 } else { 4801 if (UnbundlingResults.empty()) 4802 T->ConstructJob( 4803 C, *JA, Result, InputInfos, 4804 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()), 4805 LinkingOutput); 4806 else 4807 T->ConstructJobMultipleOutputs( 4808 C, *JA, UnbundlingResults, InputInfos, 4809 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()), 4810 LinkingOutput); 4811 } 4812 return Result; 4813 } 4814 4815 const char *Driver::getDefaultImageName() const { 4816 llvm::Triple Target(llvm::Triple::normalize(TargetTriple)); 4817 return Target.isOSWindows() ? "a.exe" : "a.out"; 4818 } 4819 4820 /// Create output filename based on ArgValue, which could either be a 4821 /// full filename, filename without extension, or a directory. If ArgValue 4822 /// does not provide a filename, then use BaseName, and use the extension 4823 /// suitable for FileType. 4824 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue, 4825 StringRef BaseName, 4826 types::ID FileType) { 4827 SmallString<128> Filename = ArgValue; 4828 4829 if (ArgValue.empty()) { 4830 // If the argument is empty, output to BaseName in the current dir. 4831 Filename = BaseName; 4832 } else if (llvm::sys::path::is_separator(Filename.back())) { 4833 // If the argument is a directory, output to BaseName in that dir. 4834 llvm::sys::path::append(Filename, BaseName); 4835 } 4836 4837 if (!llvm::sys::path::has_extension(ArgValue)) { 4838 // If the argument didn't provide an extension, then set it. 4839 const char *Extension = types::getTypeTempSuffix(FileType, true); 4840 4841 if (FileType == types::TY_Image && 4842 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) { 4843 // The output file is a dll. 4844 Extension = "dll"; 4845 } 4846 4847 llvm::sys::path::replace_extension(Filename, Extension); 4848 } 4849 4850 return Args.MakeArgString(Filename.c_str()); 4851 } 4852 4853 static bool HasPreprocessOutput(const Action &JA) { 4854 if (isa<PreprocessJobAction>(JA)) 4855 return true; 4856 if (isa<OffloadAction>(JA) && isa<PreprocessJobAction>(JA.getInputs()[0])) 4857 return true; 4858 if (isa<OffloadBundlingJobAction>(JA) && 4859 HasPreprocessOutput(*(JA.getInputs()[0]))) 4860 return true; 4861 return false; 4862 } 4863 4864 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA, 4865 const char *BaseInput, 4866 StringRef OrigBoundArch, bool AtTopLevel, 4867 bool MultipleArchs, 4868 StringRef OffloadingPrefix) const { 4869 std::string BoundArch = OrigBoundArch.str(); 4870 #if defined(_WIN32) 4871 // BoundArch may contains ':', which is invalid in file names on Windows, 4872 // therefore replace it with '%'. 4873 std::replace(BoundArch.begin(), BoundArch.end(), ':', '@'); 4874 #endif 4875 4876 llvm::PrettyStackTraceString CrashInfo("Computing output path"); 4877 // Output to a user requested destination? 4878 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) { 4879 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) 4880 return C.addResultFile(FinalOutput->getValue(), &JA); 4881 } 4882 4883 // For /P, preprocess to file named after BaseInput. 4884 if (C.getArgs().hasArg(options::OPT__SLASH_P)) { 4885 assert(AtTopLevel && isa<PreprocessJobAction>(JA)); 4886 StringRef BaseName = llvm::sys::path::filename(BaseInput); 4887 StringRef NameArg; 4888 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi)) 4889 NameArg = A->getValue(); 4890 return C.addResultFile( 4891 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C), 4892 &JA); 4893 } 4894 4895 // Default to writing to stdout? 4896 if (AtTopLevel && !CCGenDiagnostics && HasPreprocessOutput(JA)) { 4897 return "-"; 4898 } 4899 4900 if (JA.getType() == types::TY_ModuleFile && 4901 C.getArgs().getLastArg(options::OPT_module_file_info)) { 4902 return "-"; 4903 } 4904 4905 // Is this the assembly listing for /FA? 4906 if (JA.getType() == types::TY_PP_Asm && 4907 (C.getArgs().hasArg(options::OPT__SLASH_FA) || 4908 C.getArgs().hasArg(options::OPT__SLASH_Fa))) { 4909 // Use /Fa and the input filename to determine the asm file name. 4910 StringRef BaseName = llvm::sys::path::filename(BaseInput); 4911 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa); 4912 return C.addResultFile( 4913 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()), 4914 &JA); 4915 } 4916 4917 // Output to a temporary file? 4918 if ((!AtTopLevel && !isSaveTempsEnabled() && 4919 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) || 4920 CCGenDiagnostics) { 4921 StringRef Name = llvm::sys::path::filename(BaseInput); 4922 std::pair<StringRef, StringRef> Split = Name.split('.'); 4923 SmallString<128> TmpName; 4924 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode()); 4925 Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir); 4926 if (CCGenDiagnostics && A) { 4927 SmallString<128> CrashDirectory(A->getValue()); 4928 if (!getVFS().exists(CrashDirectory)) 4929 llvm::sys::fs::create_directories(CrashDirectory); 4930 llvm::sys::path::append(CrashDirectory, Split.first); 4931 const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%"; 4932 std::error_code EC = llvm::sys::fs::createUniqueFile( 4933 CrashDirectory + Middle + Suffix, TmpName); 4934 if (EC) { 4935 Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 4936 return ""; 4937 } 4938 } else { 4939 TmpName = GetTemporaryPath(Split.first, Suffix); 4940 } 4941 return C.addTempFile(C.getArgs().MakeArgString(TmpName)); 4942 } 4943 4944 SmallString<128> BasePath(BaseInput); 4945 SmallString<128> ExternalPath(""); 4946 StringRef BaseName; 4947 4948 // Dsymutil actions should use the full path. 4949 if (isa<DsymutilJobAction>(JA) && C.getArgs().hasArg(options::OPT_dsym_dir)) { 4950 ExternalPath += C.getArgs().getLastArg(options::OPT_dsym_dir)->getValue(); 4951 // We use posix style here because the tests (specifically 4952 // darwin-dsymutil.c) demonstrate that posix style paths are acceptable 4953 // even on Windows and if we don't then the similar test covering this 4954 // fails. 4955 llvm::sys::path::append(ExternalPath, llvm::sys::path::Style::posix, 4956 llvm::sys::path::filename(BasePath)); 4957 BaseName = ExternalPath; 4958 } else if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA)) 4959 BaseName = BasePath; 4960 else 4961 BaseName = llvm::sys::path::filename(BasePath); 4962 4963 // Determine what the derived output name should be. 4964 const char *NamedOutput; 4965 4966 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) && 4967 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) { 4968 // The /Fo or /o flag decides the object filename. 4969 StringRef Val = 4970 C.getArgs() 4971 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o) 4972 ->getValue(); 4973 NamedOutput = 4974 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object); 4975 } else if (JA.getType() == types::TY_Image && 4976 C.getArgs().hasArg(options::OPT__SLASH_Fe, 4977 options::OPT__SLASH_o)) { 4978 // The /Fe or /o flag names the linked file. 4979 StringRef Val = 4980 C.getArgs() 4981 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o) 4982 ->getValue(); 4983 NamedOutput = 4984 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image); 4985 } else if (JA.getType() == types::TY_Image) { 4986 if (IsCLMode()) { 4987 // clang-cl uses BaseName for the executable name. 4988 NamedOutput = 4989 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image); 4990 } else { 4991 SmallString<128> Output(getDefaultImageName()); 4992 // HIP image for device compilation with -fno-gpu-rdc is per compilation 4993 // unit. 4994 bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP && 4995 !C.getArgs().hasFlag(options::OPT_fgpu_rdc, 4996 options::OPT_fno_gpu_rdc, false); 4997 if (IsHIPNoRDC) { 4998 Output = BaseName; 4999 llvm::sys::path::replace_extension(Output, ""); 5000 } 5001 Output += OffloadingPrefix; 5002 if (MultipleArchs && !BoundArch.empty()) { 5003 Output += "-"; 5004 Output.append(BoundArch); 5005 } 5006 if (IsHIPNoRDC) 5007 Output += ".out"; 5008 NamedOutput = C.getArgs().MakeArgString(Output.c_str()); 5009 } 5010 } else if (JA.getType() == types::TY_PCH && IsCLMode()) { 5011 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName)); 5012 } else { 5013 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode()); 5014 assert(Suffix && "All types used for output should have a suffix."); 5015 5016 std::string::size_type End = std::string::npos; 5017 if (!types::appendSuffixForType(JA.getType())) 5018 End = BaseName.rfind('.'); 5019 SmallString<128> Suffixed(BaseName.substr(0, End)); 5020 Suffixed += OffloadingPrefix; 5021 if (MultipleArchs && !BoundArch.empty()) { 5022 Suffixed += "-"; 5023 Suffixed.append(BoundArch); 5024 } 5025 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for 5026 // the unoptimized bitcode so that it does not get overwritten by the ".bc" 5027 // optimized bitcode output. 5028 auto IsHIPRDCInCompilePhase = [](const JobAction &JA, 5029 const llvm::opt::DerivedArgList &Args) { 5030 // The relocatable compilation in HIP implies -emit-llvm. Similarly, use a 5031 // ".tmp.bc" suffix for the unoptimized bitcode (generated in the compile 5032 // phase.) 5033 return isa<CompileJobAction>(JA) && 5034 JA.getOffloadingDeviceKind() == Action::OFK_HIP && 5035 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, 5036 false); 5037 }; 5038 if (!AtTopLevel && JA.getType() == types::TY_LLVM_BC && 5039 (C.getArgs().hasArg(options::OPT_emit_llvm) || 5040 IsHIPRDCInCompilePhase(JA, C.getArgs()))) 5041 Suffixed += ".tmp"; 5042 Suffixed += '.'; 5043 Suffixed += Suffix; 5044 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str()); 5045 } 5046 5047 // Prepend object file path if -save-temps=obj 5048 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) && 5049 JA.getType() != types::TY_PCH) { 5050 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 5051 SmallString<128> TempPath(FinalOutput->getValue()); 5052 llvm::sys::path::remove_filename(TempPath); 5053 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput); 5054 llvm::sys::path::append(TempPath, OutputFileName); 5055 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str()); 5056 } 5057 5058 // If we're saving temps and the temp file conflicts with the input file, 5059 // then avoid overwriting input file. 5060 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) { 5061 bool SameFile = false; 5062 SmallString<256> Result; 5063 llvm::sys::fs::current_path(Result); 5064 llvm::sys::path::append(Result, BaseName); 5065 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile); 5066 // Must share the same path to conflict. 5067 if (SameFile) { 5068 StringRef Name = llvm::sys::path::filename(BaseInput); 5069 std::pair<StringRef, StringRef> Split = Name.split('.'); 5070 std::string TmpName = GetTemporaryPath( 5071 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode())); 5072 return C.addTempFile(C.getArgs().MakeArgString(TmpName)); 5073 } 5074 } 5075 5076 // As an annoying special case, PCH generation doesn't strip the pathname. 5077 if (JA.getType() == types::TY_PCH && !IsCLMode()) { 5078 llvm::sys::path::remove_filename(BasePath); 5079 if (BasePath.empty()) 5080 BasePath = NamedOutput; 5081 else 5082 llvm::sys::path::append(BasePath, NamedOutput); 5083 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA); 5084 } else { 5085 return C.addResultFile(NamedOutput, &JA); 5086 } 5087 } 5088 5089 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const { 5090 // Search for Name in a list of paths. 5091 auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P) 5092 -> llvm::Optional<std::string> { 5093 // Respect a limited subset of the '-Bprefix' functionality in GCC by 5094 // attempting to use this prefix when looking for file paths. 5095 for (const auto &Dir : P) { 5096 if (Dir.empty()) 5097 continue; 5098 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir); 5099 llvm::sys::path::append(P, Name); 5100 if (llvm::sys::fs::exists(Twine(P))) 5101 return std::string(P); 5102 } 5103 return None; 5104 }; 5105 5106 if (auto P = SearchPaths(PrefixDirs)) 5107 return *P; 5108 5109 SmallString<128> R(ResourceDir); 5110 llvm::sys::path::append(R, Name); 5111 if (llvm::sys::fs::exists(Twine(R))) 5112 return std::string(R.str()); 5113 5114 SmallString<128> P(TC.getCompilerRTPath()); 5115 llvm::sys::path::append(P, Name); 5116 if (llvm::sys::fs::exists(Twine(P))) 5117 return std::string(P.str()); 5118 5119 SmallString<128> D(Dir); 5120 llvm::sys::path::append(D, "..", Name); 5121 if (llvm::sys::fs::exists(Twine(D))) 5122 return std::string(D.str()); 5123 5124 if (auto P = SearchPaths(TC.getLibraryPaths())) 5125 return *P; 5126 5127 if (auto P = SearchPaths(TC.getFilePaths())) 5128 return *P; 5129 5130 return std::string(Name); 5131 } 5132 5133 void Driver::generatePrefixedToolNames( 5134 StringRef Tool, const ToolChain &TC, 5135 SmallVectorImpl<std::string> &Names) const { 5136 // FIXME: Needs a better variable than TargetTriple 5137 Names.emplace_back((TargetTriple + "-" + Tool).str()); 5138 Names.emplace_back(Tool); 5139 } 5140 5141 static bool ScanDirForExecutable(SmallString<128> &Dir, StringRef Name) { 5142 llvm::sys::path::append(Dir, Name); 5143 if (llvm::sys::fs::can_execute(Twine(Dir))) 5144 return true; 5145 llvm::sys::path::remove_filename(Dir); 5146 return false; 5147 } 5148 5149 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const { 5150 SmallVector<std::string, 2> TargetSpecificExecutables; 5151 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables); 5152 5153 // Respect a limited subset of the '-Bprefix' functionality in GCC by 5154 // attempting to use this prefix when looking for program paths. 5155 for (const auto &PrefixDir : PrefixDirs) { 5156 if (llvm::sys::fs::is_directory(PrefixDir)) { 5157 SmallString<128> P(PrefixDir); 5158 if (ScanDirForExecutable(P, Name)) 5159 return std::string(P.str()); 5160 } else { 5161 SmallString<128> P((PrefixDir + Name).str()); 5162 if (llvm::sys::fs::can_execute(Twine(P))) 5163 return std::string(P.str()); 5164 } 5165 } 5166 5167 const ToolChain::path_list &List = TC.getProgramPaths(); 5168 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) { 5169 // For each possible name of the tool look for it in 5170 // program paths first, then the path. 5171 // Higher priority names will be first, meaning that 5172 // a higher priority name in the path will be found 5173 // instead of a lower priority name in the program path. 5174 // E.g. <triple>-gcc on the path will be found instead 5175 // of gcc in the program path 5176 for (const auto &Path : List) { 5177 SmallString<128> P(Path); 5178 if (ScanDirForExecutable(P, TargetSpecificExecutable)) 5179 return std::string(P.str()); 5180 } 5181 5182 // Fall back to the path 5183 if (llvm::ErrorOr<std::string> P = 5184 llvm::sys::findProgramByName(TargetSpecificExecutable)) 5185 return *P; 5186 } 5187 5188 return std::string(Name); 5189 } 5190 5191 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const { 5192 SmallString<128> Path; 5193 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path); 5194 if (EC) { 5195 Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 5196 return ""; 5197 } 5198 5199 return std::string(Path.str()); 5200 } 5201 5202 std::string Driver::GetTemporaryDirectory(StringRef Prefix) const { 5203 SmallString<128> Path; 5204 std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path); 5205 if (EC) { 5206 Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 5207 return ""; 5208 } 5209 5210 return std::string(Path.str()); 5211 } 5212 5213 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const { 5214 SmallString<128> Output; 5215 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) { 5216 // FIXME: If anybody needs it, implement this obscure rule: 5217 // "If you specify a directory without a file name, the default file name 5218 // is VCx0.pch., where x is the major version of Visual C++ in use." 5219 Output = FpArg->getValue(); 5220 5221 // "If you do not specify an extension as part of the path name, an 5222 // extension of .pch is assumed. " 5223 if (!llvm::sys::path::has_extension(Output)) 5224 Output += ".pch"; 5225 } else { 5226 if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc)) 5227 Output = YcArg->getValue(); 5228 if (Output.empty()) 5229 Output = BaseName; 5230 llvm::sys::path::replace_extension(Output, ".pch"); 5231 } 5232 return std::string(Output.str()); 5233 } 5234 5235 const ToolChain &Driver::getToolChain(const ArgList &Args, 5236 const llvm::Triple &Target) const { 5237 5238 auto &TC = ToolChains[Target.str()]; 5239 if (!TC) { 5240 switch (Target.getOS()) { 5241 case llvm::Triple::AIX: 5242 TC = std::make_unique<toolchains::AIX>(*this, Target, Args); 5243 break; 5244 case llvm::Triple::Haiku: 5245 TC = std::make_unique<toolchains::Haiku>(*this, Target, Args); 5246 break; 5247 case llvm::Triple::Ananas: 5248 TC = std::make_unique<toolchains::Ananas>(*this, Target, Args); 5249 break; 5250 case llvm::Triple::CloudABI: 5251 TC = std::make_unique<toolchains::CloudABI>(*this, Target, Args); 5252 break; 5253 case llvm::Triple::Darwin: 5254 case llvm::Triple::MacOSX: 5255 case llvm::Triple::IOS: 5256 case llvm::Triple::TvOS: 5257 case llvm::Triple::WatchOS: 5258 TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args); 5259 break; 5260 case llvm::Triple::DragonFly: 5261 TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args); 5262 break; 5263 case llvm::Triple::OpenBSD: 5264 TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args); 5265 break; 5266 case llvm::Triple::NetBSD: 5267 TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args); 5268 break; 5269 case llvm::Triple::FreeBSD: 5270 TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args); 5271 break; 5272 case llvm::Triple::Minix: 5273 TC = std::make_unique<toolchains::Minix>(*this, Target, Args); 5274 break; 5275 case llvm::Triple::Linux: 5276 case llvm::Triple::ELFIAMCU: 5277 if (Target.getArch() == llvm::Triple::hexagon) 5278 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target, 5279 Args); 5280 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) && 5281 !Target.hasEnvironment()) 5282 TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target, 5283 Args); 5284 else if (Target.isPPC()) 5285 TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target, 5286 Args); 5287 else if (Target.getArch() == llvm::Triple::ve) 5288 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args); 5289 5290 else 5291 TC = std::make_unique<toolchains::Linux>(*this, Target, Args); 5292 break; 5293 case llvm::Triple::NaCl: 5294 TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args); 5295 break; 5296 case llvm::Triple::Fuchsia: 5297 TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args); 5298 break; 5299 case llvm::Triple::Solaris: 5300 TC = std::make_unique<toolchains::Solaris>(*this, Target, Args); 5301 break; 5302 case llvm::Triple::AMDHSA: 5303 TC = std::make_unique<toolchains::ROCMToolChain>(*this, Target, Args); 5304 break; 5305 case llvm::Triple::AMDPAL: 5306 case llvm::Triple::Mesa3D: 5307 TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args); 5308 break; 5309 case llvm::Triple::Win32: 5310 switch (Target.getEnvironment()) { 5311 default: 5312 if (Target.isOSBinFormatELF()) 5313 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args); 5314 else if (Target.isOSBinFormatMachO()) 5315 TC = std::make_unique<toolchains::MachO>(*this, Target, Args); 5316 else 5317 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args); 5318 break; 5319 case llvm::Triple::GNU: 5320 TC = std::make_unique<toolchains::MinGW>(*this, Target, Args); 5321 break; 5322 case llvm::Triple::Itanium: 5323 TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target, 5324 Args); 5325 break; 5326 case llvm::Triple::MSVC: 5327 case llvm::Triple::UnknownEnvironment: 5328 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ) 5329 .startswith_insensitive("bfd")) 5330 TC = std::make_unique<toolchains::CrossWindowsToolChain>( 5331 *this, Target, Args); 5332 else 5333 TC = 5334 std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args); 5335 break; 5336 } 5337 break; 5338 case llvm::Triple::PS4: 5339 TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args); 5340 break; 5341 case llvm::Triple::Contiki: 5342 TC = std::make_unique<toolchains::Contiki>(*this, Target, Args); 5343 break; 5344 case llvm::Triple::Hurd: 5345 TC = std::make_unique<toolchains::Hurd>(*this, Target, Args); 5346 break; 5347 case llvm::Triple::ZOS: 5348 TC = std::make_unique<toolchains::ZOS>(*this, Target, Args); 5349 break; 5350 default: 5351 // Of these targets, Hexagon is the only one that might have 5352 // an OS of Linux, in which case it got handled above already. 5353 switch (Target.getArch()) { 5354 case llvm::Triple::tce: 5355 TC = std::make_unique<toolchains::TCEToolChain>(*this, Target, Args); 5356 break; 5357 case llvm::Triple::tcele: 5358 TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args); 5359 break; 5360 case llvm::Triple::hexagon: 5361 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target, 5362 Args); 5363 break; 5364 case llvm::Triple::lanai: 5365 TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args); 5366 break; 5367 case llvm::Triple::xcore: 5368 TC = std::make_unique<toolchains::XCoreToolChain>(*this, Target, Args); 5369 break; 5370 case llvm::Triple::wasm32: 5371 case llvm::Triple::wasm64: 5372 TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args); 5373 break; 5374 case llvm::Triple::avr: 5375 TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args); 5376 break; 5377 case llvm::Triple::msp430: 5378 TC = 5379 std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args); 5380 break; 5381 case llvm::Triple::riscv32: 5382 case llvm::Triple::riscv64: 5383 if (toolchains::RISCVToolChain::hasGCCToolchain(*this, Args)) 5384 TC = 5385 std::make_unique<toolchains::RISCVToolChain>(*this, Target, Args); 5386 else 5387 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args); 5388 break; 5389 case llvm::Triple::ve: 5390 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args); 5391 break; 5392 default: 5393 if (Target.getVendor() == llvm::Triple::Myriad) 5394 TC = std::make_unique<toolchains::MyriadToolChain>(*this, Target, 5395 Args); 5396 else if (toolchains::BareMetal::handlesTarget(Target)) 5397 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args); 5398 else if (Target.isOSBinFormatELF()) 5399 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args); 5400 else if (Target.isOSBinFormatMachO()) 5401 TC = std::make_unique<toolchains::MachO>(*this, Target, Args); 5402 else 5403 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args); 5404 } 5405 } 5406 } 5407 5408 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA 5409 // compiles always need two toolchains, the CUDA toolchain and the host 5410 // toolchain. So the only valid way to create a CUDA toolchain is via 5411 // CreateOffloadingDeviceToolChains. 5412 5413 return *TC; 5414 } 5415 5416 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const { 5417 // Say "no" if there is not exactly one input of a type clang understands. 5418 if (JA.size() != 1 || 5419 !types::isAcceptedByClang((*JA.input_begin())->getType())) 5420 return false; 5421 5422 // And say "no" if this is not a kind of action clang understands. 5423 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) && 5424 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA)) 5425 return false; 5426 5427 return true; 5428 } 5429 5430 bool Driver::ShouldUseFlangCompiler(const JobAction &JA) const { 5431 // Say "no" if there is not exactly one input of a type flang understands. 5432 if (JA.size() != 1 || 5433 !types::isFortran((*JA.input_begin())->getType())) 5434 return false; 5435 5436 // And say "no" if this is not a kind of action flang understands. 5437 if (!isa<PreprocessJobAction>(JA) && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA)) 5438 return false; 5439 5440 return true; 5441 } 5442 5443 bool Driver::ShouldEmitStaticLibrary(const ArgList &Args) const { 5444 // Only emit static library if the flag is set explicitly. 5445 if (Args.hasArg(options::OPT_emit_static_lib)) 5446 return true; 5447 return false; 5448 } 5449 5450 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the 5451 /// grouped values as integers. Numbers which are not provided are set to 0. 5452 /// 5453 /// \return True if the entire string was parsed (9.2), or all groups were 5454 /// parsed (10.3.5extrastuff). 5455 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor, 5456 unsigned &Micro, bool &HadExtra) { 5457 HadExtra = false; 5458 5459 Major = Minor = Micro = 0; 5460 if (Str.empty()) 5461 return false; 5462 5463 if (Str.consumeInteger(10, Major)) 5464 return false; 5465 if (Str.empty()) 5466 return true; 5467 if (Str[0] != '.') 5468 return false; 5469 5470 Str = Str.drop_front(1); 5471 5472 if (Str.consumeInteger(10, Minor)) 5473 return false; 5474 if (Str.empty()) 5475 return true; 5476 if (Str[0] != '.') 5477 return false; 5478 Str = Str.drop_front(1); 5479 5480 if (Str.consumeInteger(10, Micro)) 5481 return false; 5482 if (!Str.empty()) 5483 HadExtra = true; 5484 return true; 5485 } 5486 5487 /// Parse digits from a string \p Str and fulfill \p Digits with 5488 /// the parsed numbers. This method assumes that the max number of 5489 /// digits to look for is equal to Digits.size(). 5490 /// 5491 /// \return True if the entire string was parsed and there are 5492 /// no extra characters remaining at the end. 5493 bool Driver::GetReleaseVersion(StringRef Str, 5494 MutableArrayRef<unsigned> Digits) { 5495 if (Str.empty()) 5496 return false; 5497 5498 unsigned CurDigit = 0; 5499 while (CurDigit < Digits.size()) { 5500 unsigned Digit; 5501 if (Str.consumeInteger(10, Digit)) 5502 return false; 5503 Digits[CurDigit] = Digit; 5504 if (Str.empty()) 5505 return true; 5506 if (Str[0] != '.') 5507 return false; 5508 Str = Str.drop_front(1); 5509 CurDigit++; 5510 } 5511 5512 // More digits than requested, bail out... 5513 return false; 5514 } 5515 5516 std::pair<unsigned, unsigned> 5517 Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const { 5518 unsigned IncludedFlagsBitmask = 0; 5519 unsigned ExcludedFlagsBitmask = options::NoDriverOption; 5520 5521 if (IsClCompatMode) { 5522 // Include CL and Core options. 5523 IncludedFlagsBitmask |= options::CLOption; 5524 IncludedFlagsBitmask |= options::CoreOption; 5525 } else { 5526 ExcludedFlagsBitmask |= options::CLOption; 5527 } 5528 5529 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask); 5530 } 5531 5532 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) { 5533 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false); 5534 } 5535 5536 bool clang::driver::willEmitRemarks(const ArgList &Args) { 5537 // -fsave-optimization-record enables it. 5538 if (Args.hasFlag(options::OPT_fsave_optimization_record, 5539 options::OPT_fno_save_optimization_record, false)) 5540 return true; 5541 5542 // -fsave-optimization-record=<format> enables it as well. 5543 if (Args.hasFlag(options::OPT_fsave_optimization_record_EQ, 5544 options::OPT_fno_save_optimization_record, false)) 5545 return true; 5546 5547 // -foptimization-record-file alone enables it too. 5548 if (Args.hasFlag(options::OPT_foptimization_record_file_EQ, 5549 options::OPT_fno_save_optimization_record, false)) 5550 return true; 5551 5552 // -foptimization-record-passes alone enables it too. 5553 if (Args.hasFlag(options::OPT_foptimization_record_passes_EQ, 5554 options::OPT_fno_save_optimization_record, false)) 5555 return true; 5556 return false; 5557 } 5558 5559 llvm::StringRef clang::driver::getDriverMode(StringRef ProgName, 5560 ArrayRef<const char *> Args) { 5561 static const std::string OptName = 5562 getDriverOptTable().getOption(options::OPT_driver_mode).getPrefixedName(); 5563 llvm::StringRef Opt; 5564 for (StringRef Arg : Args) { 5565 if (!Arg.startswith(OptName)) 5566 continue; 5567 Opt = Arg; 5568 } 5569 if (Opt.empty()) 5570 Opt = ToolChain::getTargetAndModeFromProgramName(ProgName).DriverMode; 5571 return Opt.consume_front(OptName) ? Opt : ""; 5572 } 5573 5574 bool driver::IsClangCL(StringRef DriverMode) { return DriverMode.equals("cl"); } 5575