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