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