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