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