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