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