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