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