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