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.h" 13 #include "clang/Basic/Version.h" 14 #include "clang/Basic/VirtualFileSystem.h" 15 #include "clang/Config/config.h" 16 #include "clang/Driver/Action.h" 17 #include "clang/Driver/Compilation.h" 18 #include "clang/Driver/DriverDiagnostic.h" 19 #include "clang/Driver/Job.h" 20 #include "clang/Driver/Options.h" 21 #include "clang/Driver/SanitizerArgs.h" 22 #include "clang/Driver/Tool.h" 23 #include "clang/Driver/ToolChain.h" 24 #include "llvm/ADT/ArrayRef.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SmallSet.h" 27 #include "llvm/ADT/StringExtras.h" 28 #include "llvm/ADT/StringSet.h" 29 #include "llvm/ADT/StringSwitch.h" 30 #include "llvm/Option/Arg.h" 31 #include "llvm/Option/ArgList.h" 32 #include "llvm/Option/OptSpecifier.h" 33 #include "llvm/Option/OptTable.h" 34 #include "llvm/Option/Option.h" 35 #include "llvm/Support/ErrorHandling.h" 36 #include "llvm/Support/FileSystem.h" 37 #include "llvm/Support/Path.h" 38 #include "llvm/Support/PrettyStackTrace.h" 39 #include "llvm/Support/Process.h" 40 #include "llvm/Support/Program.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include <map> 43 #include <memory> 44 #include <utility> 45 46 using namespace clang::driver; 47 using namespace clang; 48 using namespace llvm::opt; 49 50 Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple, 51 DiagnosticsEngine &Diags, 52 IntrusiveRefCntPtr<vfs::FileSystem> VFS) 53 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)), 54 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), 55 LTOMode(LTOK_None), ClangExecutable(ClangExecutable), 56 SysRoot(DEFAULT_SYSROOT), UseStdLib(true), 57 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr), 58 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr), 59 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false), 60 CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple), 61 CCCGenericGCCName(""), CheckInputsExist(true), CCCUsePCH(true), 62 SuppressMissingInputWarning(false) { 63 64 // Provide a sane fallback if no VFS is specified. 65 if (!this->VFS) 66 this->VFS = vfs::getRealFileSystem(); 67 68 Name = llvm::sys::path::filename(ClangExecutable); 69 Dir = llvm::sys::path::parent_path(ClangExecutable); 70 InstalledDir = Dir; // Provide a sensible default installed dir. 71 72 // Compute the path to the resource directory. 73 StringRef ClangResourceDir(CLANG_RESOURCE_DIR); 74 SmallString<128> P(Dir); 75 if (ClangResourceDir != "") { 76 llvm::sys::path::append(P, ClangResourceDir); 77 } else { 78 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX); 79 llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang", 80 CLANG_VERSION_STRING); 81 } 82 ResourceDir = P.str(); 83 } 84 85 Driver::~Driver() { 86 delete Opts; 87 88 llvm::DeleteContainerSeconds(ToolChains); 89 } 90 91 void Driver::ParseDriverMode(StringRef ProgramName, 92 ArrayRef<const char *> Args) { 93 auto Default = ToolChain::getTargetAndModeFromProgramName(ProgramName); 94 StringRef DefaultMode(Default.second); 95 setDriverModeFromOption(DefaultMode); 96 97 for (const char *ArgPtr : Args) { 98 // Ingore nullptrs, they are response file's EOL markers 99 if (ArgPtr == nullptr) 100 continue; 101 const StringRef Arg = ArgPtr; 102 setDriverModeFromOption(Arg); 103 } 104 } 105 106 void Driver::setDriverModeFromOption(StringRef Opt) { 107 const std::string OptName = 108 getOpts().getOption(options::OPT_driver_mode).getPrefixedName(); 109 if (!Opt.startswith(OptName)) 110 return; 111 StringRef Value = Opt.drop_front(OptName.size()); 112 113 const unsigned M = llvm::StringSwitch<unsigned>(Value) 114 .Case("gcc", GCCMode) 115 .Case("g++", GXXMode) 116 .Case("cpp", CPPMode) 117 .Case("cl", CLMode) 118 .Default(~0U); 119 120 if (M != ~0U) 121 Mode = static_cast<DriverMode>(M); 122 else 123 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value; 124 } 125 126 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) { 127 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing"); 128 129 unsigned IncludedFlagsBitmask; 130 unsigned ExcludedFlagsBitmask; 131 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) = 132 getIncludeExcludeOptionFlagMasks(); 133 134 unsigned MissingArgIndex, MissingArgCount; 135 InputArgList Args = 136 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount, 137 IncludedFlagsBitmask, ExcludedFlagsBitmask); 138 139 // Check for missing argument error. 140 if (MissingArgCount) 141 Diag(clang::diag::err_drv_missing_argument) 142 << Args.getArgString(MissingArgIndex) << MissingArgCount; 143 144 // Check for unsupported options. 145 for (const Arg *A : Args) { 146 if (A->getOption().hasFlag(options::Unsupported)) { 147 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args); 148 continue; 149 } 150 151 // Warn about -mcpu= without an argument. 152 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) { 153 Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args); 154 } 155 } 156 157 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) 158 Diags.Report(IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl : 159 diag::err_drv_unknown_argument) 160 << A->getAsString(Args); 161 162 return Args; 163 } 164 165 // Determine which compilation mode we are in. We look for options which 166 // affect the phase, starting with the earliest phases, and record which 167 // option we used to determine the final phase. 168 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, 169 Arg **FinalPhaseArg) const { 170 Arg *PhaseArg = nullptr; 171 phases::ID FinalPhase; 172 173 // -{E,EP,P,M,MM} only run the preprocessor. 174 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) || 175 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) || 176 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) || 177 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) { 178 FinalPhase = phases::Preprocess; 179 180 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler. 181 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) || 182 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) || 183 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) || 184 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) || 185 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) || 186 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) || 187 (PhaseArg = DAL.getLastArg(options::OPT__analyze, 188 options::OPT__analyze_auto)) || 189 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) { 190 FinalPhase = phases::Compile; 191 192 // -S only runs up to the backend. 193 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) { 194 FinalPhase = phases::Backend; 195 196 // -c compilation only runs up to the assembler. 197 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) { 198 FinalPhase = phases::Assemble; 199 200 // Otherwise do everything. 201 } else 202 FinalPhase = phases::Link; 203 204 if (FinalPhaseArg) 205 *FinalPhaseArg = PhaseArg; 206 207 return FinalPhase; 208 } 209 210 static Arg *MakeInputArg(DerivedArgList &Args, OptTable *Opts, 211 StringRef Value) { 212 Arg *A = new Arg(Opts->getOption(options::OPT_INPUT), Value, 213 Args.getBaseArgs().MakeIndex(Value), Value.data()); 214 Args.AddSynthesizedArg(A); 215 A->claim(); 216 return A; 217 } 218 219 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const { 220 DerivedArgList *DAL = new DerivedArgList(Args); 221 222 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib); 223 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs); 224 for (Arg *A : Args) { 225 // Unfortunately, we have to parse some forwarding options (-Xassembler, 226 // -Xlinker, -Xpreprocessor) because we either integrate their functionality 227 // (assembler and preprocessor), or bypass a previous driver ('collect2'). 228 229 // Rewrite linker options, to replace --no-demangle with a custom internal 230 // option. 231 if ((A->getOption().matches(options::OPT_Wl_COMMA) || 232 A->getOption().matches(options::OPT_Xlinker)) && 233 A->containsValue("--no-demangle")) { 234 // Add the rewritten no-demangle argument. 235 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle)); 236 237 // Add the remaining values as Xlinker arguments. 238 for (StringRef Val : A->getValues()) 239 if (Val != "--no-demangle") 240 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val); 241 242 continue; 243 } 244 245 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by 246 // some build systems. We don't try to be complete here because we don't 247 // care to encourage this usage model. 248 if (A->getOption().matches(options::OPT_Wp_COMMA) && 249 (A->getValue(0) == StringRef("-MD") || 250 A->getValue(0) == StringRef("-MMD"))) { 251 // Rewrite to -MD/-MMD along with -MF. 252 if (A->getValue(0) == StringRef("-MD")) 253 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD)); 254 else 255 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD)); 256 if (A->getNumValues() == 2) 257 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF), 258 A->getValue(1)); 259 continue; 260 } 261 262 // Rewrite reserved library names. 263 if (A->getOption().matches(options::OPT_l)) { 264 StringRef Value = A->getValue(); 265 266 // Rewrite unless -nostdlib is present. 267 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") { 268 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx)); 269 continue; 270 } 271 272 // Rewrite unconditionally. 273 if (Value == "cc_kext") { 274 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext)); 275 continue; 276 } 277 } 278 279 // Pick up inputs via the -- option. 280 if (A->getOption().matches(options::OPT__DASH_DASH)) { 281 A->claim(); 282 for (StringRef Val : A->getValues()) 283 DAL->append(MakeInputArg(*DAL, Opts, Val)); 284 continue; 285 } 286 287 DAL->append(A); 288 } 289 290 // Enforce -static if -miamcu is present. 291 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) 292 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static)); 293 294 // Add a default value of -mlinker-version=, if one was given and the user 295 // didn't specify one. 296 #if defined(HOST_LINK_VERSION) 297 if (!Args.hasArg(options::OPT_mlinker_version_EQ) && 298 strlen(HOST_LINK_VERSION) > 0) { 299 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ), 300 HOST_LINK_VERSION); 301 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim(); 302 } 303 #endif 304 305 return DAL; 306 } 307 308 /// \brief Compute target triple from args. 309 /// 310 /// This routine provides the logic to compute a target triple from various 311 /// args passed to the driver and the default triple string. 312 static llvm::Triple computeTargetTriple(const Driver &D, 313 StringRef DefaultTargetTriple, 314 const ArgList &Args, 315 StringRef DarwinArchName = "") { 316 // FIXME: Already done in Compilation *Driver::BuildCompilation 317 if (const Arg *A = Args.getLastArg(options::OPT_target)) 318 DefaultTargetTriple = A->getValue(); 319 320 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple)); 321 322 // Handle Apple-specific options available here. 323 if (Target.isOSBinFormatMachO()) { 324 // If an explict Darwin arch name is given, that trumps all. 325 if (!DarwinArchName.empty()) { 326 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName); 327 return Target; 328 } 329 330 // Handle the Darwin '-arch' flag. 331 if (Arg *A = Args.getLastArg(options::OPT_arch)) { 332 StringRef ArchName = A->getValue(); 333 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName); 334 } 335 } 336 337 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and 338 // '-mbig-endian'/'-EB'. 339 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian, 340 options::OPT_mbig_endian)) { 341 if (A->getOption().matches(options::OPT_mlittle_endian)) { 342 llvm::Triple LE = Target.getLittleEndianArchVariant(); 343 if (LE.getArch() != llvm::Triple::UnknownArch) 344 Target = std::move(LE); 345 } else { 346 llvm::Triple BE = Target.getBigEndianArchVariant(); 347 if (BE.getArch() != llvm::Triple::UnknownArch) 348 Target = std::move(BE); 349 } 350 } 351 352 // Skip further flag support on OSes which don't support '-m32' or '-m64'. 353 if (Target.getArch() == llvm::Triple::tce || 354 Target.getOS() == llvm::Triple::Minix) 355 return Target; 356 357 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'. 358 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32, 359 options::OPT_m32, options::OPT_m16); 360 if (A) { 361 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch; 362 363 if (A->getOption().matches(options::OPT_m64)) { 364 AT = Target.get64BitArchVariant().getArch(); 365 if (Target.getEnvironment() == llvm::Triple::GNUX32) 366 Target.setEnvironment(llvm::Triple::GNU); 367 } else if (A->getOption().matches(options::OPT_mx32) && 368 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) { 369 AT = llvm::Triple::x86_64; 370 Target.setEnvironment(llvm::Triple::GNUX32); 371 } else if (A->getOption().matches(options::OPT_m32)) { 372 AT = Target.get32BitArchVariant().getArch(); 373 if (Target.getEnvironment() == llvm::Triple::GNUX32) 374 Target.setEnvironment(llvm::Triple::GNU); 375 } else if (A->getOption().matches(options::OPT_m16) && 376 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) { 377 AT = llvm::Triple::x86; 378 Target.setEnvironment(llvm::Triple::CODE16); 379 } 380 381 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) 382 Target.setArch(AT); 383 } 384 385 // Handle -miamcu flag. 386 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) { 387 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86) 388 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu" 389 << Target.str(); 390 391 if (A && !A->getOption().matches(options::OPT_m32)) 392 D.Diag(diag::err_drv_argument_not_allowed_with) 393 << "-miamcu" << A->getBaseArg().getAsString(Args); 394 395 Target.setArch(llvm::Triple::x86); 396 Target.setArchName("i586"); 397 Target.setEnvironment(llvm::Triple::UnknownEnvironment); 398 Target.setEnvironmentName(""); 399 Target.setOS(llvm::Triple::ELFIAMCU); 400 Target.setVendor(llvm::Triple::UnknownVendor); 401 Target.setVendorName("intel"); 402 } 403 404 return Target; 405 } 406 407 // \brief Parse the LTO options and record the type of LTO compilation 408 // based on which -f(no-)?lto(=.*)? option occurs last. 409 void Driver::setLTOMode(const llvm::opt::ArgList &Args) { 410 LTOMode = LTOK_None; 411 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ, 412 options::OPT_fno_lto, false)) 413 return; 414 415 StringRef LTOName("full"); 416 417 const Arg *A = Args.getLastArg(options::OPT_flto_EQ); 418 if (A) 419 LTOName = A->getValue(); 420 421 LTOMode = llvm::StringSwitch<LTOKind>(LTOName) 422 .Case("full", LTOK_Full) 423 .Case("thin", LTOK_Thin) 424 .Default(LTOK_Unknown); 425 426 if (LTOMode == LTOK_Unknown) { 427 assert(A); 428 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName() 429 << A->getValue(); 430 } 431 } 432 433 void Driver::CreateOffloadingDeviceToolChains(Compilation &C, 434 InputList &Inputs) { 435 436 // 437 // CUDA 438 // 439 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type. 440 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) { 441 return types::isCuda(I.first); 442 })) { 443 const ToolChain &TC = getToolChain( 444 C.getInputArgs(), 445 llvm::Triple(C.getSingleOffloadToolChain<Action::OFK_Host>() 446 ->getTriple() 447 .isArch64Bit() 448 ? "nvptx64-nvidia-cuda" 449 : "nvptx-nvidia-cuda")); 450 C.addOffloadDeviceToolChain(&TC, Action::OFK_Cuda); 451 } 452 453 // 454 // TODO: Add support for other offloading programming models here. 455 // 456 457 return; 458 } 459 460 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) { 461 llvm::PrettyStackTraceString CrashInfo("Compilation construction"); 462 463 // FIXME: Handle environment options which affect driver behavior, somewhere 464 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS. 465 466 if (Optional<std::string> CompilerPathValue = 467 llvm::sys::Process::GetEnv("COMPILER_PATH")) { 468 StringRef CompilerPath = *CompilerPathValue; 469 while (!CompilerPath.empty()) { 470 std::pair<StringRef, StringRef> Split = 471 CompilerPath.split(llvm::sys::EnvPathSeparator); 472 PrefixDirs.push_back(Split.first); 473 CompilerPath = Split.second; 474 } 475 } 476 477 // We look for the driver mode option early, because the mode can affect 478 // how other options are parsed. 479 ParseDriverMode(ClangExecutable, ArgList.slice(1)); 480 481 // FIXME: What are we going to do with -V and -b? 482 483 // FIXME: This stuff needs to go into the Compilation, not the driver. 484 bool CCCPrintPhases; 485 486 InputArgList Args = ParseArgStrings(ArgList.slice(1)); 487 488 // Silence driver warnings if requested 489 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w)); 490 491 // -no-canonical-prefixes is used very early in main. 492 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes); 493 494 // Ignore -pipe. 495 Args.ClaimAllArgs(options::OPT_pipe); 496 497 // Extract -ccc args. 498 // 499 // FIXME: We need to figure out where this behavior should live. Most of it 500 // should be outside in the client; the parts that aren't should have proper 501 // options, either by introducing new ones or by overloading gcc ones like -V 502 // or -b. 503 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases); 504 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings); 505 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name)) 506 CCCGenericGCCName = A->getValue(); 507 CCCUsePCH = 508 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth); 509 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld 510 // and getToolChain is const. 511 if (IsCLMode()) { 512 // clang-cl targets MSVC-style Win32. 513 llvm::Triple T(DefaultTargetTriple); 514 T.setOS(llvm::Triple::Win32); 515 T.setVendor(llvm::Triple::PC); 516 T.setEnvironment(llvm::Triple::MSVC); 517 DefaultTargetTriple = T.str(); 518 } 519 if (const Arg *A = Args.getLastArg(options::OPT_target)) 520 DefaultTargetTriple = A->getValue(); 521 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir)) 522 Dir = InstalledDir = A->getValue(); 523 for (const Arg *A : Args.filtered(options::OPT_B)) { 524 A->claim(); 525 PrefixDirs.push_back(A->getValue(0)); 526 } 527 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ)) 528 SysRoot = A->getValue(); 529 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ)) 530 DyldPrefix = A->getValue(); 531 if (Args.hasArg(options::OPT_nostdlib)) 532 UseStdLib = false; 533 534 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir)) 535 ResourceDir = A->getValue(); 536 537 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) { 538 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue()) 539 .Case("cwd", SaveTempsCwd) 540 .Case("obj", SaveTempsObj) 541 .Default(SaveTempsCwd); 542 } 543 544 setLTOMode(Args); 545 546 // Ignore -fembed-bitcode options with LTO 547 // since the output will be bitcode anyway. 548 if (getLTOMode() == LTOK_None) { 549 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) { 550 StringRef Name = A->getValue(); 551 unsigned Model = llvm::StringSwitch<unsigned>(Name) 552 .Case("off", EmbedNone) 553 .Case("all", EmbedBitcode) 554 .Case("bitcode", EmbedBitcode) 555 .Case("marker", EmbedMarker) 556 .Default(~0U); 557 if (Model == ~0U) { 558 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) 559 << Name; 560 } else 561 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model); 562 } 563 } else { 564 // claim the bitcode option under LTO so no warning is issued. 565 Args.ClaimAllArgs(options::OPT_fembed_bitcode_EQ); 566 } 567 568 std::unique_ptr<llvm::opt::InputArgList> UArgs = 569 llvm::make_unique<InputArgList>(std::move(Args)); 570 571 // Perform the default argument translations. 572 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs); 573 574 // Owned by the host. 575 const ToolChain &TC = getToolChain( 576 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs)); 577 578 // The compilation takes ownership of Args. 579 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs); 580 581 if (!HandleImmediateArgs(*C)) 582 return C; 583 584 // Construct the list of inputs. 585 InputList Inputs; 586 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs); 587 588 // Populate the tool chains for the offloading devices, if any. 589 CreateOffloadingDeviceToolChains(*C, Inputs); 590 591 // Construct the list of abstract actions to perform for this compilation. On 592 // MachO targets this uses the driver-driver and universal actions. 593 if (TC.getTriple().isOSBinFormatMachO()) 594 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs); 595 else 596 BuildActions(*C, C->getArgs(), Inputs, C->getActions()); 597 598 if (CCCPrintPhases) { 599 PrintActions(*C); 600 return C; 601 } 602 603 BuildJobs(*C); 604 605 return C; 606 } 607 608 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) { 609 llvm::opt::ArgStringList ASL; 610 for (const auto *A : Args) 611 A->render(Args, ASL); 612 613 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) { 614 if (I != ASL.begin()) 615 OS << ' '; 616 Command::printArg(OS, *I, true); 617 } 618 OS << '\n'; 619 } 620 621 // When clang crashes, produce diagnostic information including the fully 622 // preprocessed source file(s). Request that the developer attach the 623 // diagnostic information to a bug report. 624 void Driver::generateCompilationDiagnostics(Compilation &C, 625 const Command &FailingCommand) { 626 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics)) 627 return; 628 629 // Don't try to generate diagnostics for link or dsymutil jobs. 630 if (FailingCommand.getCreator().isLinkJob() || 631 FailingCommand.getCreator().isDsymutilJob()) 632 return; 633 634 // Print the version of the compiler. 635 PrintVersion(C, llvm::errs()); 636 637 Diag(clang::diag::note_drv_command_failed_diag_msg) 638 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the " 639 "crash backtrace, preprocessed source, and associated run script."; 640 641 // Suppress driver output and emit preprocessor output to temp file. 642 Mode = CPPMode; 643 CCGenDiagnostics = true; 644 645 // Save the original job command(s). 646 Command Cmd = FailingCommand; 647 648 // Keep track of whether we produce any errors while trying to produce 649 // preprocessed sources. 650 DiagnosticErrorTrap Trap(Diags); 651 652 // Suppress tool output. 653 C.initCompilationForDiagnostics(); 654 655 // Construct the list of inputs. 656 InputList Inputs; 657 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs); 658 659 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) { 660 bool IgnoreInput = false; 661 662 // Ignore input from stdin or any inputs that cannot be preprocessed. 663 // Check type first as not all linker inputs have a value. 664 if (types::getPreprocessedType(it->first) == types::TY_INVALID) { 665 IgnoreInput = true; 666 } else if (!strcmp(it->second->getValue(), "-")) { 667 Diag(clang::diag::note_drv_command_failed_diag_msg) 668 << "Error generating preprocessed source(s) - " 669 "ignoring input from stdin."; 670 IgnoreInput = true; 671 } 672 673 if (IgnoreInput) { 674 it = Inputs.erase(it); 675 ie = Inputs.end(); 676 } else { 677 ++it; 678 } 679 } 680 681 if (Inputs.empty()) { 682 Diag(clang::diag::note_drv_command_failed_diag_msg) 683 << "Error generating preprocessed source(s) - " 684 "no preprocessable inputs."; 685 return; 686 } 687 688 // Don't attempt to generate preprocessed files if multiple -arch options are 689 // used, unless they're all duplicates. 690 llvm::StringSet<> ArchNames; 691 for (const Arg *A : C.getArgs()) { 692 if (A->getOption().matches(options::OPT_arch)) { 693 StringRef ArchName = A->getValue(); 694 ArchNames.insert(ArchName); 695 } 696 } 697 if (ArchNames.size() > 1) { 698 Diag(clang::diag::note_drv_command_failed_diag_msg) 699 << "Error generating preprocessed source(s) - cannot generate " 700 "preprocessed source with multiple -arch options."; 701 return; 702 } 703 704 // Construct the list of abstract actions to perform for this compilation. On 705 // Darwin OSes this uses the driver-driver and builds universal actions. 706 const ToolChain &TC = C.getDefaultToolChain(); 707 if (TC.getTriple().isOSBinFormatMachO()) 708 BuildUniversalActions(C, TC, Inputs); 709 else 710 BuildActions(C, C.getArgs(), Inputs, C.getActions()); 711 712 BuildJobs(C); 713 714 // If there were errors building the compilation, quit now. 715 if (Trap.hasErrorOccurred()) { 716 Diag(clang::diag::note_drv_command_failed_diag_msg) 717 << "Error generating preprocessed source(s)."; 718 return; 719 } 720 721 // Generate preprocessed output. 722 SmallVector<std::pair<int, const Command *>, 4> FailingCommands; 723 C.ExecuteJobs(C.getJobs(), FailingCommands); 724 725 // If any of the preprocessing commands failed, clean up and exit. 726 if (!FailingCommands.empty()) { 727 if (!isSaveTempsEnabled()) 728 C.CleanupFileList(C.getTempFiles(), true); 729 730 Diag(clang::diag::note_drv_command_failed_diag_msg) 731 << "Error generating preprocessed source(s)."; 732 return; 733 } 734 735 const ArgStringList &TempFiles = C.getTempFiles(); 736 if (TempFiles.empty()) { 737 Diag(clang::diag::note_drv_command_failed_diag_msg) 738 << "Error generating preprocessed source(s)."; 739 return; 740 } 741 742 Diag(clang::diag::note_drv_command_failed_diag_msg) 743 << "\n********************\n\n" 744 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n" 745 "Preprocessed source(s) and associated run script(s) are located at:"; 746 747 SmallString<128> VFS; 748 for (const char *TempFile : TempFiles) { 749 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile; 750 if (StringRef(TempFile).endswith(".cache")) { 751 // In some cases (modules) we'll dump extra data to help with reproducing 752 // the crash into a directory next to the output. 753 VFS = llvm::sys::path::filename(TempFile); 754 llvm::sys::path::append(VFS, "vfs", "vfs.yaml"); 755 } 756 } 757 758 // Assume associated files are based off of the first temporary file. 759 CrashReportInfo CrashInfo(TempFiles[0], VFS); 760 761 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh"; 762 std::error_code EC; 763 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl); 764 if (EC) { 765 Diag(clang::diag::note_drv_command_failed_diag_msg) 766 << "Error generating run script: " + Script + " " + EC.message(); 767 } else { 768 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n" 769 << "# Driver args: "; 770 printArgList(ScriptOS, C.getInputArgs()); 771 ScriptOS << "# Original command: "; 772 Cmd.Print(ScriptOS, "\n", /*Quote=*/true); 773 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo); 774 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script; 775 } 776 777 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file, 778 options::OPT_frewrite_map_file_EQ)) 779 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue(); 780 781 Diag(clang::diag::note_drv_command_failed_diag_msg) 782 << "\n\n********************"; 783 } 784 785 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) { 786 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity 787 // if the tool does not support response files, there is a chance/ that things 788 // will just work without a response file, so we silently just skip it. 789 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None || 790 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments())) 791 return; 792 793 std::string TmpName = GetTemporaryPath("response", "txt"); 794 Cmd.setResponseFile( 795 C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()))); 796 } 797 798 int Driver::ExecuteCompilation( 799 Compilation &C, 800 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) { 801 // Just print if -### was present. 802 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 803 C.getJobs().Print(llvm::errs(), "\n", true); 804 return 0; 805 } 806 807 // If there were errors building the compilation, quit now. 808 if (Diags.hasErrorOccurred()) 809 return 1; 810 811 // Set up response file names for each command, if necessary 812 for (auto &Job : C.getJobs()) 813 setUpResponseFiles(C, Job); 814 815 C.ExecuteJobs(C.getJobs(), FailingCommands); 816 817 // Remove temp files. 818 C.CleanupFileList(C.getTempFiles()); 819 820 // If the command succeeded, we are done. 821 if (FailingCommands.empty()) 822 return 0; 823 824 // Otherwise, remove result files and print extra information about abnormal 825 // failures. 826 for (const auto &CmdPair : FailingCommands) { 827 int Res = CmdPair.first; 828 const Command *FailingCommand = CmdPair.second; 829 830 // Remove result files if we're not saving temps. 831 if (!isSaveTempsEnabled()) { 832 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource()); 833 C.CleanupFileMap(C.getResultFiles(), JA, true); 834 835 // Failure result files are valid unless we crashed. 836 if (Res < 0) 837 C.CleanupFileMap(C.getFailureResultFiles(), JA, true); 838 } 839 840 // Print extra information about abnormal failures, if possible. 841 // 842 // This is ad-hoc, but we don't want to be excessively noisy. If the result 843 // status was 1, assume the command failed normally. In particular, if it 844 // was the compiler then assume it gave a reasonable error code. Failures 845 // in other tools are less common, and they generally have worse 846 // diagnostics, so always print the diagnostic there. 847 const Tool &FailingTool = FailingCommand->getCreator(); 848 849 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) { 850 // FIXME: See FIXME above regarding result code interpretation. 851 if (Res < 0) 852 Diag(clang::diag::err_drv_command_signalled) 853 << FailingTool.getShortName(); 854 else 855 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName() 856 << Res; 857 } 858 } 859 return 0; 860 } 861 862 void Driver::PrintHelp(bool ShowHidden) const { 863 unsigned IncludedFlagsBitmask; 864 unsigned ExcludedFlagsBitmask; 865 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) = 866 getIncludeExcludeOptionFlagMasks(); 867 868 ExcludedFlagsBitmask |= options::NoDriverOption; 869 if (!ShowHidden) 870 ExcludedFlagsBitmask |= HelpHidden; 871 872 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(), 873 IncludedFlagsBitmask, ExcludedFlagsBitmask); 874 } 875 876 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const { 877 // FIXME: The following handlers should use a callback mechanism, we don't 878 // know what the client would like to do. 879 OS << getClangFullVersion() << '\n'; 880 const ToolChain &TC = C.getDefaultToolChain(); 881 OS << "Target: " << TC.getTripleString() << '\n'; 882 883 // Print the threading model. 884 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) { 885 // Don't print if the ToolChain would have barfed on it already 886 if (TC.isThreadModelSupported(A->getValue())) 887 OS << "Thread model: " << A->getValue(); 888 } else 889 OS << "Thread model: " << TC.getThreadModel(); 890 OS << '\n'; 891 892 // Print out the install directory. 893 OS << "InstalledDir: " << InstalledDir << '\n'; 894 } 895 896 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories 897 /// option. 898 static void PrintDiagnosticCategories(raw_ostream &OS) { 899 // Skip the empty category. 900 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max; 901 ++i) 902 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n'; 903 } 904 905 bool Driver::HandleImmediateArgs(const Compilation &C) { 906 // The order these options are handled in gcc is all over the place, but we 907 // don't expect inconsistencies w.r.t. that to matter in practice. 908 909 if (C.getArgs().hasArg(options::OPT_dumpmachine)) { 910 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n'; 911 return false; 912 } 913 914 if (C.getArgs().hasArg(options::OPT_dumpversion)) { 915 // Since -dumpversion is only implemented for pedantic GCC compatibility, we 916 // return an answer which matches our definition of __VERSION__. 917 // 918 // If we want to return a more correct answer some day, then we should 919 // introduce a non-pedantically GCC compatible mode to Clang in which we 920 // provide sensible definitions for -dumpversion, __VERSION__, etc. 921 llvm::outs() << "4.2.1\n"; 922 return false; 923 } 924 925 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) { 926 PrintDiagnosticCategories(llvm::outs()); 927 return false; 928 } 929 930 if (C.getArgs().hasArg(options::OPT_help) || 931 C.getArgs().hasArg(options::OPT__help_hidden)) { 932 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden)); 933 return false; 934 } 935 936 if (C.getArgs().hasArg(options::OPT__version)) { 937 // Follow gcc behavior and use stdout for --version and stderr for -v. 938 PrintVersion(C, llvm::outs()); 939 return false; 940 } 941 942 if (C.getArgs().hasArg(options::OPT_v) || 943 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 944 PrintVersion(C, llvm::errs()); 945 SuppressMissingInputWarning = true; 946 } 947 948 const ToolChain &TC = C.getDefaultToolChain(); 949 950 if (C.getArgs().hasArg(options::OPT_v)) 951 TC.printVerboseInfo(llvm::errs()); 952 953 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) { 954 llvm::outs() << "programs: ="; 955 bool separator = false; 956 for (const std::string &Path : TC.getProgramPaths()) { 957 if (separator) 958 llvm::outs() << ':'; 959 llvm::outs() << Path; 960 separator = true; 961 } 962 llvm::outs() << "\n"; 963 llvm::outs() << "libraries: =" << ResourceDir; 964 965 StringRef sysroot = C.getSysRoot(); 966 967 for (const std::string &Path : TC.getFilePaths()) { 968 // Always print a separator. ResourceDir was the first item shown. 969 llvm::outs() << ':'; 970 // Interpretation of leading '=' is needed only for NetBSD. 971 if (Path[0] == '=') 972 llvm::outs() << sysroot << Path.substr(1); 973 else 974 llvm::outs() << Path; 975 } 976 llvm::outs() << "\n"; 977 return false; 978 } 979 980 // FIXME: The following handlers should use a callback mechanism, we don't 981 // know what the client would like to do. 982 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) { 983 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n"; 984 return false; 985 } 986 987 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) { 988 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n"; 989 return false; 990 } 991 992 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) { 993 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n"; 994 return false; 995 } 996 997 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) { 998 for (const Multilib &Multilib : TC.getMultilibs()) 999 llvm::outs() << Multilib << "\n"; 1000 return false; 1001 } 1002 1003 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) { 1004 for (const Multilib &Multilib : TC.getMultilibs()) { 1005 if (Multilib.gccSuffix().empty()) 1006 llvm::outs() << ".\n"; 1007 else { 1008 StringRef Suffix(Multilib.gccSuffix()); 1009 assert(Suffix.front() == '/'); 1010 llvm::outs() << Suffix.substr(1) << "\n"; 1011 } 1012 } 1013 return false; 1014 } 1015 return true; 1016 } 1017 1018 // Display an action graph human-readably. Action A is the "sink" node 1019 // and latest-occuring action. Traversal is in pre-order, visiting the 1020 // inputs to each action before printing the action itself. 1021 static unsigned PrintActions1(const Compilation &C, Action *A, 1022 std::map<Action *, unsigned> &Ids) { 1023 if (Ids.count(A)) // A was already visited. 1024 return Ids[A]; 1025 1026 std::string str; 1027 llvm::raw_string_ostream os(str); 1028 1029 os << Action::getClassName(A->getKind()) << ", "; 1030 if (InputAction *IA = dyn_cast<InputAction>(A)) { 1031 os << "\"" << IA->getInputArg().getValue() << "\""; 1032 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) { 1033 os << '"' << BIA->getArchName() << '"' << ", {" 1034 << PrintActions1(C, *BIA->input_begin(), Ids) << "}"; 1035 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) { 1036 bool IsFirst = true; 1037 OA->doOnEachDependence( 1038 [&](Action *A, const ToolChain *TC, const char *BoundArch) { 1039 // E.g. for two CUDA device dependences whose bound arch is sm_20 and 1040 // sm_35 this will generate: 1041 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device" 1042 // (nvptx64-nvidia-cuda:sm_35) {#ID} 1043 if (!IsFirst) 1044 os << ", "; 1045 os << '"'; 1046 if (TC) 1047 os << A->getOffloadingKindPrefix(); 1048 else 1049 os << "host"; 1050 os << " ("; 1051 os << TC->getTriple().normalize(); 1052 1053 if (BoundArch) 1054 os << ":" << BoundArch; 1055 os << ")"; 1056 os << '"'; 1057 os << " {" << PrintActions1(C, A, Ids) << "}"; 1058 IsFirst = false; 1059 }); 1060 } else { 1061 const ActionList *AL = &A->getInputs(); 1062 1063 if (AL->size()) { 1064 const char *Prefix = "{"; 1065 for (Action *PreRequisite : *AL) { 1066 os << Prefix << PrintActions1(C, PreRequisite, Ids); 1067 Prefix = ", "; 1068 } 1069 os << "}"; 1070 } else 1071 os << "{}"; 1072 } 1073 1074 // Append offload info for all options other than the offloading action 1075 // itself (e.g. (cuda-device, sm_20) or (cuda-host)). 1076 std::string offload_str; 1077 llvm::raw_string_ostream offload_os(offload_str); 1078 if (!isa<OffloadAction>(A)) { 1079 auto S = A->getOffloadingKindPrefix(); 1080 if (!S.empty()) { 1081 offload_os << ", (" << S; 1082 if (A->getOffloadingArch()) 1083 offload_os << ", " << A->getOffloadingArch(); 1084 offload_os << ")"; 1085 } 1086 } 1087 1088 unsigned Id = Ids.size(); 1089 Ids[A] = Id; 1090 llvm::errs() << Id << ": " << os.str() << ", " 1091 << types::getTypeName(A->getType()) << offload_os.str() << "\n"; 1092 1093 return Id; 1094 } 1095 1096 // Print the action graphs in a compilation C. 1097 // For example "clang -c file1.c file2.c" is composed of two subgraphs. 1098 void Driver::PrintActions(const Compilation &C) const { 1099 std::map<Action *, unsigned> Ids; 1100 for (Action *A : C.getActions()) 1101 PrintActions1(C, A, Ids); 1102 } 1103 1104 /// \brief Check whether the given input tree contains any compilation or 1105 /// assembly actions. 1106 static bool ContainsCompileOrAssembleAction(const Action *A) { 1107 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) || 1108 isa<AssembleJobAction>(A)) 1109 return true; 1110 1111 for (const Action *Input : A->inputs()) 1112 if (ContainsCompileOrAssembleAction(Input)) 1113 return true; 1114 1115 return false; 1116 } 1117 1118 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC, 1119 const InputList &BAInputs) const { 1120 DerivedArgList &Args = C.getArgs(); 1121 ActionList &Actions = C.getActions(); 1122 llvm::PrettyStackTraceString CrashInfo("Building universal build actions"); 1123 // Collect the list of architectures. Duplicates are allowed, but should only 1124 // be handled once (in the order seen). 1125 llvm::StringSet<> ArchNames; 1126 SmallVector<const char *, 4> Archs; 1127 for (Arg *A : Args) { 1128 if (A->getOption().matches(options::OPT_arch)) { 1129 // Validate the option here; we don't save the type here because its 1130 // particular spelling may participate in other driver choices. 1131 llvm::Triple::ArchType Arch = 1132 tools::darwin::getArchTypeForMachOArchName(A->getValue()); 1133 if (Arch == llvm::Triple::UnknownArch) { 1134 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args); 1135 continue; 1136 } 1137 1138 A->claim(); 1139 if (ArchNames.insert(A->getValue()).second) 1140 Archs.push_back(A->getValue()); 1141 } 1142 } 1143 1144 // When there is no explicit arch for this platform, make sure we still bind 1145 // the architecture (to the default) so that -Xarch_ is handled correctly. 1146 if (!Archs.size()) 1147 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName())); 1148 1149 ActionList SingleActions; 1150 BuildActions(C, Args, BAInputs, SingleActions); 1151 1152 // Add in arch bindings for every top level action, as well as lipo and 1153 // dsymutil steps if needed. 1154 for (Action* Act : SingleActions) { 1155 // Make sure we can lipo this kind of output. If not (and it is an actual 1156 // output) then we disallow, since we can't create an output file with the 1157 // right name without overwriting it. We could remove this oddity by just 1158 // changing the output names to include the arch, which would also fix 1159 // -save-temps. Compatibility wins for now. 1160 1161 if (Archs.size() > 1 && !types::canLipoType(Act->getType())) 1162 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs) 1163 << types::getTypeName(Act->getType()); 1164 1165 ActionList Inputs; 1166 for (unsigned i = 0, e = Archs.size(); i != e; ++i) 1167 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i])); 1168 1169 // Lipo if necessary, we do it this way because we need to set the arch flag 1170 // so that -Xarch_ gets overwritten. 1171 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing) 1172 Actions.append(Inputs.begin(), Inputs.end()); 1173 else 1174 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType())); 1175 1176 // Handle debug info queries. 1177 Arg *A = Args.getLastArg(options::OPT_g_Group); 1178 if (A && !A->getOption().matches(options::OPT_g0) && 1179 !A->getOption().matches(options::OPT_gstabs) && 1180 ContainsCompileOrAssembleAction(Actions.back())) { 1181 1182 // Add a 'dsymutil' step if necessary, when debug info is enabled and we 1183 // have a compile input. We need to run 'dsymutil' ourselves in such cases 1184 // because the debug info will refer to a temporary object file which 1185 // will be removed at the end of the compilation process. 1186 if (Act->getType() == types::TY_Image) { 1187 ActionList Inputs; 1188 Inputs.push_back(Actions.back()); 1189 Actions.pop_back(); 1190 Actions.push_back( 1191 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM)); 1192 } 1193 1194 // Verify the debug info output. 1195 if (Args.hasArg(options::OPT_verify_debug_info)) { 1196 Action* LastAction = Actions.back(); 1197 Actions.pop_back(); 1198 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>( 1199 LastAction, types::TY_Nothing)); 1200 } 1201 } 1202 } 1203 } 1204 1205 /// \brief Check that the file referenced by Value exists. If it doesn't, 1206 /// issue a diagnostic and return false. 1207 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args, 1208 StringRef Value, types::ID Ty) { 1209 if (!D.getCheckInputsExist()) 1210 return true; 1211 1212 // stdin always exists. 1213 if (Value == "-") 1214 return true; 1215 1216 SmallString<64> Path(Value); 1217 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) { 1218 if (!llvm::sys::path::is_absolute(Path)) { 1219 SmallString<64> Directory(WorkDir->getValue()); 1220 llvm::sys::path::append(Directory, Value); 1221 Path.assign(Directory); 1222 } 1223 } 1224 1225 if (llvm::sys::fs::exists(Twine(Path))) 1226 return true; 1227 1228 if (D.IsCLMode()) { 1229 if (!llvm::sys::path::is_absolute(Twine(Path)) && 1230 llvm::sys::Process::FindInEnvPath("LIB", Value)) 1231 return true; 1232 1233 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) { 1234 // Arguments to the /link flag might cause the linker to search for object 1235 // and library files in paths we don't know about. Don't error in such 1236 // cases. 1237 return true; 1238 } 1239 } 1240 1241 D.Diag(clang::diag::err_drv_no_such_file) << Path; 1242 return false; 1243 } 1244 1245 // Construct a the list of inputs and their types. 1246 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args, 1247 InputList &Inputs) const { 1248 // Track the current user specified (-x) input. We also explicitly track the 1249 // argument used to set the type; we only want to claim the type when we 1250 // actually use it, so we warn about unused -x arguments. 1251 types::ID InputType = types::TY_Nothing; 1252 Arg *InputTypeArg = nullptr; 1253 1254 // The last /TC or /TP option sets the input type to C or C++ globally. 1255 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC, 1256 options::OPT__SLASH_TP)) { 1257 InputTypeArg = TCTP; 1258 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC) 1259 ? types::TY_C 1260 : types::TY_CXX; 1261 1262 arg_iterator it = 1263 Args.filtered_begin(options::OPT__SLASH_TC, options::OPT__SLASH_TP); 1264 const arg_iterator ie = Args.filtered_end(); 1265 Arg *Previous = *it++; 1266 bool ShowNote = false; 1267 while (it != ie) { 1268 Diag(clang::diag::warn_drv_overriding_flag_option) 1269 << Previous->getSpelling() << (*it)->getSpelling(); 1270 Previous = *it++; 1271 ShowNote = true; 1272 } 1273 if (ShowNote) 1274 Diag(clang::diag::note_drv_t_option_is_global); 1275 1276 // No driver mode exposes -x and /TC or /TP; we don't support mixing them. 1277 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed"); 1278 } 1279 1280 for (Arg *A : Args) { 1281 if (A->getOption().getKind() == Option::InputClass) { 1282 const char *Value = A->getValue(); 1283 types::ID Ty = types::TY_INVALID; 1284 1285 // Infer the input type if necessary. 1286 if (InputType == types::TY_Nothing) { 1287 // If there was an explicit arg for this, claim it. 1288 if (InputTypeArg) 1289 InputTypeArg->claim(); 1290 1291 // stdin must be handled specially. 1292 if (memcmp(Value, "-", 2) == 0) { 1293 // If running with -E, treat as a C input (this changes the builtin 1294 // macros, for example). This may be overridden by -ObjC below. 1295 // 1296 // Otherwise emit an error but still use a valid type to avoid 1297 // spurious errors (e.g., no inputs). 1298 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP()) 1299 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl 1300 : clang::diag::err_drv_unknown_stdin_type); 1301 Ty = types::TY_C; 1302 } else { 1303 // Otherwise lookup by extension. 1304 // Fallback is C if invoked as C preprocessor or Object otherwise. 1305 // We use a host hook here because Darwin at least has its own 1306 // idea of what .s is. 1307 if (const char *Ext = strrchr(Value, '.')) 1308 Ty = TC.LookupTypeForExtension(Ext + 1); 1309 1310 if (Ty == types::TY_INVALID) { 1311 if (CCCIsCPP()) 1312 Ty = types::TY_C; 1313 else 1314 Ty = types::TY_Object; 1315 } 1316 1317 // If the driver is invoked as C++ compiler (like clang++ or c++) it 1318 // should autodetect some input files as C++ for g++ compatibility. 1319 if (CCCIsCXX()) { 1320 types::ID OldTy = Ty; 1321 Ty = types::lookupCXXTypeForCType(Ty); 1322 1323 if (Ty != OldTy) 1324 Diag(clang::diag::warn_drv_treating_input_as_cxx) 1325 << getTypeName(OldTy) << getTypeName(Ty); 1326 } 1327 } 1328 1329 // -ObjC and -ObjC++ override the default language, but only for "source 1330 // files". We just treat everything that isn't a linker input as a 1331 // source file. 1332 // 1333 // FIXME: Clean this up if we move the phase sequence into the type. 1334 if (Ty != types::TY_Object) { 1335 if (Args.hasArg(options::OPT_ObjC)) 1336 Ty = types::TY_ObjC; 1337 else if (Args.hasArg(options::OPT_ObjCXX)) 1338 Ty = types::TY_ObjCXX; 1339 } 1340 } else { 1341 assert(InputTypeArg && "InputType set w/o InputTypeArg"); 1342 if (!InputTypeArg->getOption().matches(options::OPT_x)) { 1343 // If emulating cl.exe, make sure that /TC and /TP don't affect input 1344 // object files. 1345 const char *Ext = strrchr(Value, '.'); 1346 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object) 1347 Ty = types::TY_Object; 1348 } 1349 if (Ty == types::TY_INVALID) { 1350 Ty = InputType; 1351 InputTypeArg->claim(); 1352 } 1353 } 1354 1355 if (DiagnoseInputExistence(*this, Args, Value, Ty)) 1356 Inputs.push_back(std::make_pair(Ty, A)); 1357 1358 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) { 1359 StringRef Value = A->getValue(); 1360 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) { 1361 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue()); 1362 Inputs.push_back(std::make_pair(types::TY_C, InputArg)); 1363 } 1364 A->claim(); 1365 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) { 1366 StringRef Value = A->getValue(); 1367 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) { 1368 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue()); 1369 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg)); 1370 } 1371 A->claim(); 1372 } else if (A->getOption().hasFlag(options::LinkerInput)) { 1373 // Just treat as object type, we could make a special type for this if 1374 // necessary. 1375 Inputs.push_back(std::make_pair(types::TY_Object, A)); 1376 1377 } else if (A->getOption().matches(options::OPT_x)) { 1378 InputTypeArg = A; 1379 InputType = types::lookupTypeForTypeSpecifier(A->getValue()); 1380 A->claim(); 1381 1382 // Follow gcc behavior and treat as linker input for invalid -x 1383 // options. Its not clear why we shouldn't just revert to unknown; but 1384 // this isn't very important, we might as well be bug compatible. 1385 if (!InputType) { 1386 Diag(clang::diag::err_drv_unknown_language) << A->getValue(); 1387 InputType = types::TY_Object; 1388 } 1389 } 1390 } 1391 if (CCCIsCPP() && Inputs.empty()) { 1392 // If called as standalone preprocessor, stdin is processed 1393 // if no other input is present. 1394 Arg *A = MakeInputArg(Args, Opts, "-"); 1395 Inputs.push_back(std::make_pair(types::TY_C, A)); 1396 } 1397 } 1398 1399 // For each unique --cuda-gpu-arch= argument creates a TY_CUDA_DEVICE 1400 // input action and then wraps each in CudaDeviceAction paired with 1401 // appropriate GPU arch name. In case of partial (i.e preprocessing 1402 // only) or device-only compilation, each device action is added to /p 1403 // Actions and /p Current is released. Otherwise the function creates 1404 // and returns a new CudaHostAction which wraps /p Current and device 1405 // side actions. 1406 static Action *buildCudaActions(Compilation &C, DerivedArgList &Args, 1407 const Arg *InputArg, Action *HostAction, 1408 ActionList &Actions) { 1409 Arg *PartialCompilationArg = Args.getLastArg( 1410 options::OPT_cuda_host_only, options::OPT_cuda_device_only, 1411 options::OPT_cuda_compile_host_device); 1412 bool CompileHostOnly = 1413 PartialCompilationArg && 1414 PartialCompilationArg->getOption().matches(options::OPT_cuda_host_only); 1415 bool CompileDeviceOnly = 1416 PartialCompilationArg && 1417 PartialCompilationArg->getOption().matches(options::OPT_cuda_device_only); 1418 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>(); 1419 assert(HostTC && "No toolchain for host compilation."); 1420 if (HostTC->getTriple().isNVPTX()) { 1421 // We do not support targeting NVPTX for host compilation. Throw 1422 // an error and abort pipeline construction early so we don't trip 1423 // asserts that assume device-side compilation. 1424 C.getDriver().Diag(diag::err_drv_cuda_nvptx_host); 1425 return nullptr; 1426 } 1427 1428 if (CompileHostOnly) { 1429 OffloadAction::HostDependence HDep(*HostAction, *HostTC, 1430 /*BoundArch=*/nullptr, Action::OFK_Cuda); 1431 return C.MakeAction<OffloadAction>(HDep); 1432 } 1433 1434 // Collect all cuda_gpu_arch parameters, removing duplicates. 1435 SmallVector<CudaArch, 4> GpuArchList; 1436 llvm::SmallSet<CudaArch, 4> GpuArchs; 1437 for (Arg *A : Args) { 1438 if (!A->getOption().matches(options::OPT_cuda_gpu_arch_EQ)) 1439 continue; 1440 A->claim(); 1441 1442 const auto &ArchStr = A->getValue(); 1443 CudaArch Arch = StringToCudaArch(ArchStr); 1444 if (Arch == CudaArch::UNKNOWN) 1445 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr; 1446 else if (GpuArchs.insert(Arch).second) 1447 GpuArchList.push_back(Arch); 1448 } 1449 1450 // Default to sm_20 which is the lowest common denominator for supported GPUs. 1451 // sm_20 code should work correctly, if suboptimally, on all newer GPUs. 1452 if (GpuArchList.empty()) 1453 GpuArchList.push_back(CudaArch::SM_20); 1454 1455 // Replicate inputs for each GPU architecture. 1456 Driver::InputList CudaDeviceInputs; 1457 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) 1458 CudaDeviceInputs.push_back(std::make_pair(types::TY_CUDA_DEVICE, InputArg)); 1459 1460 // Build actions for all device inputs. 1461 ActionList CudaDeviceActions; 1462 C.getDriver().BuildActions(C, Args, CudaDeviceInputs, CudaDeviceActions); 1463 assert(GpuArchList.size() == CudaDeviceActions.size() && 1464 "Failed to create actions for all devices"); 1465 1466 // Check whether any of device actions stopped before they could generate PTX. 1467 bool PartialCompilation = 1468 llvm::any_of(CudaDeviceActions, [](const Action *a) { 1469 return a->getKind() != Action::AssembleJobClass; 1470 }); 1471 1472 const ToolChain *CudaTC = C.getSingleOffloadToolChain<Action::OFK_Cuda>(); 1473 1474 // Figure out what to do with device actions -- pass them as inputs to the 1475 // host action or run each of them independently. 1476 if (PartialCompilation || CompileDeviceOnly) { 1477 // In case of partial or device-only compilation results of device actions 1478 // are not consumed by the host action device actions have to be added to 1479 // top-level actions list with AtTopLevel=true and run independently. 1480 1481 // -o is ambiguous if we have more than one top-level action. 1482 if (Args.hasArg(options::OPT_o) && 1483 (!CompileDeviceOnly || GpuArchList.size() > 1)) { 1484 C.getDriver().Diag( 1485 clang::diag::err_drv_output_argument_with_multiple_files); 1486 return nullptr; 1487 } 1488 1489 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 1490 OffloadAction::DeviceDependences DDep; 1491 DDep.add(*CudaDeviceActions[I], *CudaTC, CudaArchToString(GpuArchList[I]), 1492 Action::OFK_Cuda); 1493 Actions.push_back( 1494 C.MakeAction<OffloadAction>(DDep, CudaDeviceActions[I]->getType())); 1495 } 1496 // Kill host action in case of device-only compilation. 1497 if (CompileDeviceOnly) 1498 return nullptr; 1499 return HostAction; 1500 } 1501 1502 // If we're not a partial or device-only compilation, we compile each arch to 1503 // ptx and assemble to cubin, then feed the cubin *and* the ptx into a device 1504 // "link" action, which uses fatbinary to combine these cubins into one 1505 // fatbin. The fatbin is then an input to the host compilation. 1506 ActionList DeviceActions; 1507 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 1508 Action* AssembleAction = CudaDeviceActions[I]; 1509 assert(AssembleAction->getType() == types::TY_Object); 1510 assert(AssembleAction->getInputs().size() == 1); 1511 1512 Action* BackendAction = AssembleAction->getInputs()[0]; 1513 assert(BackendAction->getType() == types::TY_PP_Asm); 1514 1515 for (auto &A : {AssembleAction, BackendAction}) { 1516 OffloadAction::DeviceDependences DDep; 1517 DDep.add(*A, *CudaTC, CudaArchToString(GpuArchList[I]), Action::OFK_Cuda); 1518 DeviceActions.push_back(C.MakeAction<OffloadAction>(DDep, A->getType())); 1519 } 1520 } 1521 auto FatbinAction = 1522 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN); 1523 1524 // Return a new host action that incorporates original host action and all 1525 // device actions. 1526 OffloadAction::HostDependence HDep(*HostAction, *HostTC, 1527 /*BoundArch=*/nullptr, Action::OFK_Cuda); 1528 OffloadAction::DeviceDependences DDep; 1529 DDep.add(*FatbinAction, *CudaTC, /*BoundArch=*/nullptr, Action::OFK_Cuda); 1530 return C.MakeAction<OffloadAction>(HDep, DDep); 1531 } 1532 1533 void Driver::BuildActions(Compilation &C, DerivedArgList &Args, 1534 const InputList &Inputs, ActionList &Actions) const { 1535 llvm::PrettyStackTraceString CrashInfo("Building compilation actions"); 1536 1537 if (!SuppressMissingInputWarning && Inputs.empty()) { 1538 Diag(clang::diag::err_drv_no_input_files); 1539 return; 1540 } 1541 1542 Arg *FinalPhaseArg; 1543 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg); 1544 1545 if (FinalPhase == phases::Link && Args.hasArg(options::OPT_emit_llvm)) { 1546 Diag(clang::diag::err_drv_emit_llvm_link); 1547 } 1548 1549 // Reject -Z* at the top level, these options should never have been exposed 1550 // by gcc. 1551 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined)) 1552 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args); 1553 1554 // Diagnose misuse of /Fo. 1555 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) { 1556 StringRef V = A->getValue(); 1557 if (Inputs.size() > 1 && !V.empty() && 1558 !llvm::sys::path::is_separator(V.back())) { 1559 // Check whether /Fo tries to name an output file for multiple inputs. 1560 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources) 1561 << A->getSpelling() << V; 1562 Args.eraseArg(options::OPT__SLASH_Fo); 1563 } 1564 } 1565 1566 // Diagnose misuse of /Fa. 1567 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) { 1568 StringRef V = A->getValue(); 1569 if (Inputs.size() > 1 && !V.empty() && 1570 !llvm::sys::path::is_separator(V.back())) { 1571 // Check whether /Fa tries to name an asm file for multiple inputs. 1572 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources) 1573 << A->getSpelling() << V; 1574 Args.eraseArg(options::OPT__SLASH_Fa); 1575 } 1576 } 1577 1578 // Diagnose misuse of /o. 1579 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) { 1580 if (A->getValue()[0] == '\0') { 1581 // It has to have a value. 1582 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1; 1583 Args.eraseArg(options::OPT__SLASH_o); 1584 } 1585 } 1586 1587 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if: 1588 // * no filename after it 1589 // * both /Yc and /Yu passed but with different filenames 1590 // * corresponding file not also passed as /FI 1591 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc); 1592 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu); 1593 if (YcArg && YcArg->getValue()[0] == '\0') { 1594 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling(); 1595 Args.eraseArg(options::OPT__SLASH_Yc); 1596 YcArg = nullptr; 1597 } 1598 if (YuArg && YuArg->getValue()[0] == '\0') { 1599 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling(); 1600 Args.eraseArg(options::OPT__SLASH_Yu); 1601 YuArg = nullptr; 1602 } 1603 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) { 1604 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl); 1605 Args.eraseArg(options::OPT__SLASH_Yc); 1606 Args.eraseArg(options::OPT__SLASH_Yu); 1607 YcArg = YuArg = nullptr; 1608 } 1609 if (YcArg || YuArg) { 1610 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue(); 1611 bool FoundMatchingInclude = false; 1612 for (const Arg *Inc : Args.filtered(options::OPT_include)) { 1613 // FIXME: Do case-insensitive matching and consider / and \ as equal. 1614 if (Inc->getValue() == Val) 1615 FoundMatchingInclude = true; 1616 } 1617 if (!FoundMatchingInclude) { 1618 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl) 1619 << (YcArg ? YcArg : YuArg)->getSpelling(); 1620 Args.eraseArg(options::OPT__SLASH_Yc); 1621 Args.eraseArg(options::OPT__SLASH_Yu); 1622 YcArg = YuArg = nullptr; 1623 } 1624 } 1625 if (YcArg && Inputs.size() > 1) { 1626 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl); 1627 Args.eraseArg(options::OPT__SLASH_Yc); 1628 YcArg = nullptr; 1629 } 1630 if (Args.hasArg(options::OPT__SLASH_Y_)) { 1631 // /Y- disables all pch handling. Rather than check for it everywhere, 1632 // just remove clang-cl pch-related flags here. 1633 Args.eraseArg(options::OPT__SLASH_Fp); 1634 Args.eraseArg(options::OPT__SLASH_Yc); 1635 Args.eraseArg(options::OPT__SLASH_Yu); 1636 YcArg = YuArg = nullptr; 1637 } 1638 1639 // Track the host offload kinds used on this compilation. 1640 unsigned CompilationActiveOffloadHostKinds = 0u; 1641 1642 // Construct the actions to perform. 1643 ActionList LinkerInputs; 1644 1645 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL; 1646 for (auto &I : Inputs) { 1647 types::ID InputType = I.first; 1648 const Arg *InputArg = I.second; 1649 1650 PL.clear(); 1651 types::getCompilationPhases(InputType, PL); 1652 1653 // If the first step comes after the final phase we are doing as part of 1654 // this compilation, warn the user about it. 1655 phases::ID InitialPhase = PL[0]; 1656 if (InitialPhase > FinalPhase) { 1657 // Claim here to avoid the more general unused warning. 1658 InputArg->claim(); 1659 1660 // Suppress all unused style warnings with -Qunused-arguments 1661 if (Args.hasArg(options::OPT_Qunused_arguments)) 1662 continue; 1663 1664 // Special case when final phase determined by binary name, rather than 1665 // by a command-line argument with a corresponding Arg. 1666 if (CCCIsCPP()) 1667 Diag(clang::diag::warn_drv_input_file_unused_by_cpp) 1668 << InputArg->getAsString(Args) << getPhaseName(InitialPhase); 1669 // Special case '-E' warning on a previously preprocessed file to make 1670 // more sense. 1671 else if (InitialPhase == phases::Compile && 1672 FinalPhase == phases::Preprocess && 1673 getPreprocessedType(InputType) == types::TY_INVALID) 1674 Diag(clang::diag::warn_drv_preprocessed_input_file_unused) 1675 << InputArg->getAsString(Args) << !!FinalPhaseArg 1676 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""); 1677 else 1678 Diag(clang::diag::warn_drv_input_file_unused) 1679 << InputArg->getAsString(Args) << getPhaseName(InitialPhase) 1680 << !!FinalPhaseArg 1681 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""); 1682 continue; 1683 } 1684 1685 if (YcArg) { 1686 // Add a separate precompile phase for the compile phase. 1687 if (FinalPhase >= phases::Compile) { 1688 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL; 1689 types::getCompilationPhases(types::TY_CXXHeader, PCHPL); 1690 Arg *PchInputArg = MakeInputArg(Args, Opts, YcArg->getValue()); 1691 1692 // Build the pipeline for the pch file. 1693 Action *ClangClPch = C.MakeAction<InputAction>(*PchInputArg, InputType); 1694 for (phases::ID Phase : PCHPL) 1695 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch); 1696 assert(ClangClPch); 1697 Actions.push_back(ClangClPch); 1698 // The driver currently exits after the first failed command. This 1699 // relies on that behavior, to make sure if the pch generation fails, 1700 // the main compilation won't run. 1701 } 1702 } 1703 1704 phases::ID CudaInjectionPhase = 1705 (phases::Compile < FinalPhase && 1706 llvm::find(PL, phases::Compile) != PL.end()) 1707 ? phases::Compile 1708 : FinalPhase; 1709 1710 // Track the host offload kinds used on this input. 1711 unsigned InputActiveOffloadHostKinds = 0u; 1712 1713 // Build the pipeline for this file. 1714 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType); 1715 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end(); 1716 i != e; ++i) { 1717 phases::ID Phase = *i; 1718 1719 // We are done if this step is past what the user requested. 1720 if (Phase > FinalPhase) 1721 break; 1722 1723 // Queue linker inputs. 1724 if (Phase == phases::Link) { 1725 assert((i + 1) == e && "linking must be final compilation step."); 1726 LinkerInputs.push_back(Current); 1727 Current = nullptr; 1728 break; 1729 } 1730 1731 // Some types skip the assembler phase (e.g., llvm-bc), but we can't 1732 // encode this in the steps because the intermediate type depends on 1733 // arguments. Just special case here. 1734 if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm) 1735 continue; 1736 1737 // Otherwise construct the appropriate action. 1738 Current = ConstructPhaseAction(C, Args, Phase, Current); 1739 1740 if (InputType == types::TY_CUDA && Phase == CudaInjectionPhase) { 1741 Current = buildCudaActions(C, Args, InputArg, Current, Actions); 1742 if (!Current) 1743 break; 1744 1745 // We produced a CUDA action for this input, so the host has to support 1746 // CUDA. 1747 InputActiveOffloadHostKinds |= Action::OFK_Cuda; 1748 CompilationActiveOffloadHostKinds |= Action::OFK_Cuda; 1749 } 1750 1751 if (Current->getType() == types::TY_Nothing) 1752 break; 1753 } 1754 1755 // If we ended with something, add to the output list. Also, propagate the 1756 // offload information to the top-level host action related with the current 1757 // input. 1758 if (Current) { 1759 if (InputActiveOffloadHostKinds) 1760 Current->propagateHostOffloadInfo(InputActiveOffloadHostKinds, 1761 /*BoundArch=*/nullptr); 1762 Actions.push_back(Current); 1763 } 1764 } 1765 1766 // Add a link action if necessary and propagate the offload information for 1767 // the current compilation. 1768 if (!LinkerInputs.empty()) { 1769 Actions.push_back( 1770 C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image)); 1771 Actions.back()->propagateHostOffloadInfo(CompilationActiveOffloadHostKinds, 1772 /*BoundArch=*/nullptr); 1773 } 1774 1775 // If we are linking, claim any options which are obviously only used for 1776 // compilation. 1777 if (FinalPhase == phases::Link && PL.size() == 1) { 1778 Args.ClaimAllArgs(options::OPT_CompileOnly_Group); 1779 Args.ClaimAllArgs(options::OPT_cl_compile_Group); 1780 } 1781 1782 // Claim ignored clang-cl options. 1783 Args.ClaimAllArgs(options::OPT_cl_ignored_Group); 1784 1785 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed 1786 // to non-CUDA compilations and should not trigger warnings there. 1787 Args.ClaimAllArgs(options::OPT_cuda_host_only); 1788 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device); 1789 } 1790 1791 Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args, 1792 phases::ID Phase, Action *Input) const { 1793 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions"); 1794 // Build the appropriate action. 1795 switch (Phase) { 1796 case phases::Link: 1797 llvm_unreachable("link action invalid here."); 1798 case phases::Preprocess: { 1799 types::ID OutputTy; 1800 // -{M, MM} alter the output type. 1801 if (Args.hasArg(options::OPT_M, options::OPT_MM)) { 1802 OutputTy = types::TY_Dependencies; 1803 } else { 1804 OutputTy = Input->getType(); 1805 if (!Args.hasFlag(options::OPT_frewrite_includes, 1806 options::OPT_fno_rewrite_includes, false) && 1807 !CCGenDiagnostics) 1808 OutputTy = types::getPreprocessedType(OutputTy); 1809 assert(OutputTy != types::TY_INVALID && 1810 "Cannot preprocess this input type!"); 1811 } 1812 return C.MakeAction<PreprocessJobAction>(Input, OutputTy); 1813 } 1814 case phases::Precompile: { 1815 types::ID OutputTy = types::TY_PCH; 1816 if (Args.hasArg(options::OPT_fsyntax_only)) { 1817 // Syntax checks should not emit a PCH file 1818 OutputTy = types::TY_Nothing; 1819 } 1820 return C.MakeAction<PrecompileJobAction>(Input, OutputTy); 1821 } 1822 case phases::Compile: { 1823 if (Args.hasArg(options::OPT_fsyntax_only)) 1824 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing); 1825 if (Args.hasArg(options::OPT_rewrite_objc)) 1826 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC); 1827 if (Args.hasArg(options::OPT_rewrite_legacy_objc)) 1828 return C.MakeAction<CompileJobAction>(Input, 1829 types::TY_RewrittenLegacyObjC); 1830 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) 1831 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist); 1832 if (Args.hasArg(options::OPT__migrate)) 1833 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap); 1834 if (Args.hasArg(options::OPT_emit_ast)) 1835 return C.MakeAction<CompileJobAction>(Input, types::TY_AST); 1836 if (Args.hasArg(options::OPT_module_file_info)) 1837 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile); 1838 if (Args.hasArg(options::OPT_verify_pch)) 1839 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing); 1840 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC); 1841 } 1842 case phases::Backend: { 1843 if (isUsingLTO()) { 1844 types::ID Output = 1845 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC; 1846 return C.MakeAction<BackendJobAction>(Input, Output); 1847 } 1848 if (Args.hasArg(options::OPT_emit_llvm)) { 1849 types::ID Output = 1850 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC; 1851 return C.MakeAction<BackendJobAction>(Input, Output); 1852 } 1853 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm); 1854 } 1855 case phases::Assemble: 1856 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object); 1857 } 1858 1859 llvm_unreachable("invalid phase in ConstructPhaseAction"); 1860 } 1861 1862 void Driver::BuildJobs(Compilation &C) const { 1863 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 1864 1865 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 1866 1867 // It is an error to provide a -o option if we are making multiple output 1868 // files. 1869 if (FinalOutput) { 1870 unsigned NumOutputs = 0; 1871 for (const Action *A : C.getActions()) 1872 if (A->getType() != types::TY_Nothing) 1873 ++NumOutputs; 1874 1875 if (NumOutputs > 1) { 1876 Diag(clang::diag::err_drv_output_argument_with_multiple_files); 1877 FinalOutput = nullptr; 1878 } 1879 } 1880 1881 // Collect the list of architectures. 1882 llvm::StringSet<> ArchNames; 1883 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO()) 1884 for (const Arg *A : C.getArgs()) 1885 if (A->getOption().matches(options::OPT_arch)) 1886 ArchNames.insert(A->getValue()); 1887 1888 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for. 1889 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults; 1890 for (Action *A : C.getActions()) { 1891 // If we are linking an image for multiple archs then the linker wants 1892 // -arch_multiple and -final_output <final image name>. Unfortunately, this 1893 // doesn't fit in cleanly because we have to pass this information down. 1894 // 1895 // FIXME: This is a hack; find a cleaner way to integrate this into the 1896 // process. 1897 const char *LinkingOutput = nullptr; 1898 if (isa<LipoJobAction>(A)) { 1899 if (FinalOutput) 1900 LinkingOutput = FinalOutput->getValue(); 1901 else 1902 LinkingOutput = getDefaultImageName(); 1903 } 1904 1905 BuildJobsForAction(C, A, &C.getDefaultToolChain(), 1906 /*BoundArch*/ nullptr, 1907 /*AtTopLevel*/ true, 1908 /*MultipleArchs*/ ArchNames.size() > 1, 1909 /*LinkingOutput*/ LinkingOutput, CachedResults, 1910 /*BuildForOffloadDevice*/ false); 1911 } 1912 1913 // If the user passed -Qunused-arguments or there were errors, don't warn 1914 // about any unused arguments. 1915 if (Diags.hasErrorOccurred() || 1916 C.getArgs().hasArg(options::OPT_Qunused_arguments)) 1917 return; 1918 1919 // Claim -### here. 1920 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH); 1921 1922 // Claim --driver-mode, --rsp-quoting, it was handled earlier. 1923 (void)C.getArgs().hasArg(options::OPT_driver_mode); 1924 (void)C.getArgs().hasArg(options::OPT_rsp_quoting); 1925 1926 for (Arg *A : C.getArgs()) { 1927 // FIXME: It would be nice to be able to send the argument to the 1928 // DiagnosticsEngine, so that extra values, position, and so on could be 1929 // printed. 1930 if (!A->isClaimed()) { 1931 if (A->getOption().hasFlag(options::NoArgumentUnused)) 1932 continue; 1933 1934 // Suppress the warning automatically if this is just a flag, and it is an 1935 // instance of an argument we already claimed. 1936 const Option &Opt = A->getOption(); 1937 if (Opt.getKind() == Option::FlagClass) { 1938 bool DuplicateClaimed = false; 1939 1940 for (const Arg *AA : C.getArgs().filtered(&Opt)) { 1941 if (AA->isClaimed()) { 1942 DuplicateClaimed = true; 1943 break; 1944 } 1945 } 1946 1947 if (DuplicateClaimed) 1948 continue; 1949 } 1950 1951 // In clang-cl, don't mention unknown arguments here since they have 1952 // already been warned about. 1953 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN)) 1954 Diag(clang::diag::warn_drv_unused_argument) 1955 << A->getAsString(C.getArgs()); 1956 } 1957 } 1958 } 1959 /// Collapse an offloading action looking for a job of the given type. The input 1960 /// action is changed to the input of the collapsed sequence. If we effectively 1961 /// had a collapse return the corresponding offloading action, otherwise return 1962 /// null. 1963 template <typename T> 1964 static OffloadAction *collapseOffloadingAction(Action *&CurAction) { 1965 if (!CurAction) 1966 return nullptr; 1967 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) { 1968 if (OA->hasHostDependence()) 1969 if (auto *HDep = dyn_cast<T>(OA->getHostDependence())) { 1970 CurAction = HDep; 1971 return OA; 1972 } 1973 if (OA->hasSingleDeviceDependence()) 1974 if (auto *DDep = dyn_cast<T>(OA->getSingleDeviceDependence())) { 1975 CurAction = DDep; 1976 return OA; 1977 } 1978 } 1979 return nullptr; 1980 } 1981 // Returns a Tool for a given JobAction. In case the action and its 1982 // predecessors can be combined, updates Inputs with the inputs of the 1983 // first combined action. If one of the collapsed actions is a 1984 // CudaHostAction, updates CollapsedCHA with the pointer to it so the 1985 // caller can deal with extra handling such action requires. 1986 static const Tool *selectToolForJob(Compilation &C, bool SaveTemps, 1987 bool EmbedBitcode, const ToolChain *TC, 1988 const JobAction *JA, 1989 const ActionList *&Inputs, 1990 ActionList &CollapsedOffloadAction) { 1991 const Tool *ToolForJob = nullptr; 1992 CollapsedOffloadAction.clear(); 1993 1994 // See if we should look for a compiler with an integrated assembler. We match 1995 // bottom up, so what we are actually looking for is an assembler job with a 1996 // compiler input. 1997 1998 // Look through offload actions between assembler and backend actions. 1999 Action *BackendJA = (isa<AssembleJobAction>(JA) && Inputs->size() == 1) 2000 ? *Inputs->begin() 2001 : nullptr; 2002 auto *BackendOA = collapseOffloadingAction<BackendJobAction>(BackendJA); 2003 2004 if (TC->useIntegratedAs() && !SaveTemps && 2005 !C.getArgs().hasArg(options::OPT_via_file_asm) && 2006 !C.getArgs().hasArg(options::OPT__SLASH_FA) && 2007 !C.getArgs().hasArg(options::OPT__SLASH_Fa) && BackendJA && 2008 isa<BackendJobAction>(BackendJA)) { 2009 // A BackendJob is always preceded by a CompileJob, and without -save-temps 2010 // or -fembed-bitcode, they will always get combined together, so instead of 2011 // checking the backend tool, check if the tool for the CompileJob has an 2012 // integrated assembler. For -fembed-bitcode, CompileJob is still used to 2013 // look up tools for BackendJob, but they need to match before we can split 2014 // them. 2015 2016 // Look through offload actions between backend and compile actions. 2017 Action *CompileJA = *BackendJA->getInputs().begin(); 2018 auto *CompileOA = collapseOffloadingAction<CompileJobAction>(CompileJA); 2019 2020 assert(CompileJA && isa<CompileJobAction>(CompileJA) && 2021 "Backend job is not preceeded by compile job."); 2022 const Tool *Compiler = TC->SelectTool(*cast<CompileJobAction>(CompileJA)); 2023 if (!Compiler) 2024 return nullptr; 2025 // When using -fembed-bitcode, it is required to have the same tool (clang) 2026 // for both CompilerJA and BackendJA. Otherwise, combine two stages. 2027 if (EmbedBitcode) { 2028 JobAction *InputJA = cast<JobAction>(*Inputs->begin()); 2029 const Tool *BackendTool = TC->SelectTool(*InputJA); 2030 if (BackendTool == Compiler) 2031 CompileJA = InputJA; 2032 } 2033 if (Compiler->hasIntegratedAssembler()) { 2034 Inputs = &CompileJA->getInputs(); 2035 ToolForJob = Compiler; 2036 // Save the collapsed offload actions because they may still contain 2037 // device actions. 2038 if (CompileOA) 2039 CollapsedOffloadAction.push_back(CompileOA); 2040 if (BackendOA) 2041 CollapsedOffloadAction.push_back(BackendOA); 2042 } 2043 } 2044 2045 // A backend job should always be combined with the preceding compile job 2046 // unless OPT_save_temps or OPT_fembed_bitcode is enabled and the compiler is 2047 // capable of emitting LLVM IR as an intermediate output. 2048 if (isa<BackendJobAction>(JA)) { 2049 // Check if the compiler supports emitting LLVM IR. 2050 assert(Inputs->size() == 1); 2051 2052 // Look through offload actions between backend and compile actions. 2053 Action *CompileJA = *JA->getInputs().begin(); 2054 auto *CompileOA = collapseOffloadingAction<CompileJobAction>(CompileJA); 2055 2056 assert(CompileJA && isa<CompileJobAction>(CompileJA) && 2057 "Backend job is not preceeded by compile job."); 2058 const Tool *Compiler = TC->SelectTool(*cast<CompileJobAction>(CompileJA)); 2059 if (!Compiler) 2060 return nullptr; 2061 if (!Compiler->canEmitIR() || 2062 (!SaveTemps && !EmbedBitcode)) { 2063 Inputs = &CompileJA->getInputs(); 2064 ToolForJob = Compiler; 2065 2066 if (CompileOA) 2067 CollapsedOffloadAction.push_back(CompileOA); 2068 } 2069 } 2070 2071 // Otherwise use the tool for the current job. 2072 if (!ToolForJob) 2073 ToolForJob = TC->SelectTool(*JA); 2074 2075 // See if we should use an integrated preprocessor. We do so when we have 2076 // exactly one input, since this is the only use case we care about 2077 // (irrelevant since we don't support combine yet). 2078 2079 // Look through offload actions after preprocessing. 2080 Action *PreprocessJA = (Inputs->size() == 1) ? *Inputs->begin() : nullptr; 2081 auto *PreprocessOA = 2082 collapseOffloadingAction<PreprocessJobAction>(PreprocessJA); 2083 2084 if (PreprocessJA && isa<PreprocessJobAction>(PreprocessJA) && 2085 !C.getArgs().hasArg(options::OPT_no_integrated_cpp) && 2086 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps && 2087 !C.getArgs().hasArg(options::OPT_rewrite_objc) && 2088 ToolForJob->hasIntegratedCPP()) { 2089 Inputs = &PreprocessJA->getInputs(); 2090 if (PreprocessOA) 2091 CollapsedOffloadAction.push_back(PreprocessOA); 2092 } 2093 2094 return ToolForJob; 2095 } 2096 2097 InputInfo Driver::BuildJobsForAction( 2098 Compilation &C, const Action *A, const ToolChain *TC, const char *BoundArch, 2099 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 2100 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults, 2101 bool BuildForOffloadDevice) const { 2102 // The bound arch is not necessarily represented in the toolchain's triple -- 2103 // for example, armv7 and armv7s both map to the same triple -- so we need 2104 // both in our map. 2105 std::string TriplePlusArch = TC->getTriple().normalize(); 2106 if (BoundArch) { 2107 TriplePlusArch += "-"; 2108 TriplePlusArch += BoundArch; 2109 } 2110 std::pair<const Action *, std::string> ActionTC = {A, TriplePlusArch}; 2111 auto CachedResult = CachedResults.find(ActionTC); 2112 if (CachedResult != CachedResults.end()) { 2113 return CachedResult->second; 2114 } 2115 InputInfo Result = BuildJobsForActionNoCache( 2116 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput, 2117 CachedResults, BuildForOffloadDevice); 2118 CachedResults[ActionTC] = Result; 2119 return Result; 2120 } 2121 2122 InputInfo Driver::BuildJobsForActionNoCache( 2123 Compilation &C, const Action *A, const ToolChain *TC, const char *BoundArch, 2124 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 2125 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults, 2126 bool BuildForOffloadDevice) const { 2127 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 2128 2129 InputInfoList OffloadDependencesInputInfo; 2130 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) { 2131 // The offload action is expected to be used in four different situations. 2132 // 2133 // a) Set a toolchain/architecture/kind for a host action: 2134 // Host Action 1 -> OffloadAction -> Host Action 2 2135 // 2136 // b) Set a toolchain/architecture/kind for a device action; 2137 // Device Action 1 -> OffloadAction -> Device Action 2 2138 // 2139 // c) Specify a device dependences to a host action; 2140 // Device Action 1 _ 2141 // \ 2142 // Host Action 1 ---> OffloadAction -> Host Action 2 2143 // 2144 // d) Specify a host dependence to a device action. 2145 // Host Action 1 _ 2146 // \ 2147 // Device Action 1 ---> OffloadAction -> Device Action 2 2148 // 2149 // For a) and b), we just return the job generated for the dependence. For 2150 // c) and d) we override the current action with the host/device dependence 2151 // if the current toolchain is host/device and set the offload dependences 2152 // info with the jobs obtained from the device/host dependence(s). 2153 2154 // If there is a single device option, just generate the job for it. 2155 if (OA->hasSingleDeviceDependence()) { 2156 InputInfo DevA; 2157 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC, 2158 const char *DepBoundArch) { 2159 DevA = 2160 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel, 2161 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, 2162 CachedResults, /*BuildForOffloadDevice=*/true); 2163 }); 2164 return DevA; 2165 } 2166 2167 // If 'Action 2' is host, we generate jobs for the device dependences and 2168 // override the current action with the host dependence. Otherwise, we 2169 // generate the host dependences and override the action with the device 2170 // dependence. The dependences can't therefore be a top-level action. 2171 OA->doOnEachDependence( 2172 /*IsHostDependence=*/BuildForOffloadDevice, 2173 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { 2174 OffloadDependencesInputInfo.push_back(BuildJobsForAction( 2175 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false, 2176 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults, 2177 /*BuildForOffloadDevice=*/DepA->getOffloadingDeviceKind() != 2178 Action::OFK_None)); 2179 }); 2180 2181 A = BuildForOffloadDevice 2182 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true) 2183 : OA->getHostDependence(); 2184 } 2185 2186 if (const InputAction *IA = dyn_cast<InputAction>(A)) { 2187 // FIXME: It would be nice to not claim this here; maybe the old scheme of 2188 // just using Args was better? 2189 const Arg &Input = IA->getInputArg(); 2190 Input.claim(); 2191 if (Input.getOption().matches(options::OPT_INPUT)) { 2192 const char *Name = Input.getValue(); 2193 return InputInfo(A, Name, /* BaseInput = */ Name); 2194 } 2195 return InputInfo(A, &Input, /* BaseInput = */ ""); 2196 } 2197 2198 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) { 2199 const ToolChain *TC; 2200 const char *ArchName = BAA->getArchName(); 2201 2202 if (ArchName) 2203 TC = &getToolChain(C.getArgs(), 2204 computeTargetTriple(*this, DefaultTargetTriple, 2205 C.getArgs(), ArchName)); 2206 else 2207 TC = &C.getDefaultToolChain(); 2208 2209 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel, 2210 MultipleArchs, LinkingOutput, CachedResults, 2211 BuildForOffloadDevice); 2212 } 2213 2214 2215 const ActionList *Inputs = &A->getInputs(); 2216 2217 const JobAction *JA = cast<JobAction>(A); 2218 ActionList CollapsedOffloadActions; 2219 2220 const Tool *T = 2221 selectToolForJob(C, isSaveTempsEnabled(), embedBitcodeEnabled(), TC, JA, 2222 Inputs, CollapsedOffloadActions); 2223 if (!T) 2224 return InputInfo(); 2225 2226 // If we've collapsed action list that contained OffloadAction we 2227 // need to build jobs for host/device-side inputs it may have held. 2228 for (const auto *OA : CollapsedOffloadActions) 2229 cast<OffloadAction>(OA)->doOnEachDependence( 2230 /*IsHostDependence=*/BuildForOffloadDevice, 2231 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { 2232 OffloadDependencesInputInfo.push_back(BuildJobsForAction( 2233 C, DepA, DepTC, DepBoundArch, AtTopLevel, 2234 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults, 2235 /*BuildForOffloadDevice=*/DepA->getOffloadingDeviceKind() != 2236 Action::OFK_None)); 2237 }); 2238 2239 // Only use pipes when there is exactly one input. 2240 InputInfoList InputInfos; 2241 for (const Action *Input : *Inputs) { 2242 // Treat dsymutil and verify sub-jobs as being at the top-level too, they 2243 // shouldn't get temporary output names. 2244 // FIXME: Clean this up. 2245 bool SubJobAtTopLevel = 2246 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A)); 2247 InputInfos.push_back(BuildJobsForAction( 2248 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput, 2249 CachedResults, BuildForOffloadDevice)); 2250 } 2251 2252 // Always use the first input as the base input. 2253 const char *BaseInput = InputInfos[0].getBaseInput(); 2254 2255 // ... except dsymutil actions, which use their actual input as the base 2256 // input. 2257 if (JA->getType() == types::TY_dSYM) 2258 BaseInput = InputInfos[0].getFilename(); 2259 2260 // Append outputs of offload device jobs to the input list 2261 if (!OffloadDependencesInputInfo.empty()) 2262 InputInfos.append(OffloadDependencesInputInfo.begin(), 2263 OffloadDependencesInputInfo.end()); 2264 2265 // Set the effective triple of the toolchain for the duration of this job. 2266 llvm::Triple EffectiveTriple; 2267 const ToolChain &ToolTC = T->getToolChain(); 2268 const ArgList &Args = C.getArgsForToolChain(TC, BoundArch); 2269 if (InputInfos.size() != 1) { 2270 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args)); 2271 } else { 2272 // Pass along the input type if it can be unambiguously determined. 2273 EffectiveTriple = llvm::Triple( 2274 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType())); 2275 } 2276 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple); 2277 2278 // Determine the place to write output to, if any. 2279 InputInfo Result; 2280 if (JA->getType() == types::TY_Nothing) 2281 Result = InputInfo(A, BaseInput); 2282 else 2283 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch, 2284 AtTopLevel, MultipleArchs, 2285 TC->getTriple().normalize()), 2286 BaseInput); 2287 2288 if (CCCPrintBindings && !CCGenDiagnostics) { 2289 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"' 2290 << " - \"" << T->getName() << "\", inputs: ["; 2291 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) { 2292 llvm::errs() << InputInfos[i].getAsString(); 2293 if (i + 1 != e) 2294 llvm::errs() << ", "; 2295 } 2296 llvm::errs() << "], output: " << Result.getAsString() << "\n"; 2297 } else { 2298 T->ConstructJob(C, *JA, Result, InputInfos, 2299 C.getArgsForToolChain(TC, BoundArch), LinkingOutput); 2300 } 2301 return Result; 2302 } 2303 2304 const char *Driver::getDefaultImageName() const { 2305 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple)); 2306 return Target.isOSWindows() ? "a.exe" : "a.out"; 2307 } 2308 2309 /// \brief Create output filename based on ArgValue, which could either be a 2310 /// full filename, filename without extension, or a directory. If ArgValue 2311 /// does not provide a filename, then use BaseName, and use the extension 2312 /// suitable for FileType. 2313 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue, 2314 StringRef BaseName, 2315 types::ID FileType) { 2316 SmallString<128> Filename = ArgValue; 2317 2318 if (ArgValue.empty()) { 2319 // If the argument is empty, output to BaseName in the current dir. 2320 Filename = BaseName; 2321 } else if (llvm::sys::path::is_separator(Filename.back())) { 2322 // If the argument is a directory, output to BaseName in that dir. 2323 llvm::sys::path::append(Filename, BaseName); 2324 } 2325 2326 if (!llvm::sys::path::has_extension(ArgValue)) { 2327 // If the argument didn't provide an extension, then set it. 2328 const char *Extension = types::getTypeTempSuffix(FileType, true); 2329 2330 if (FileType == types::TY_Image && 2331 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) { 2332 // The output file is a dll. 2333 Extension = "dll"; 2334 } 2335 2336 llvm::sys::path::replace_extension(Filename, Extension); 2337 } 2338 2339 return Args.MakeArgString(Filename.c_str()); 2340 } 2341 2342 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA, 2343 const char *BaseInput, 2344 const char *BoundArch, bool AtTopLevel, 2345 bool MultipleArchs, 2346 StringRef NormalizedTriple) const { 2347 llvm::PrettyStackTraceString CrashInfo("Computing output path"); 2348 // Output to a user requested destination? 2349 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) { 2350 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) 2351 return C.addResultFile(FinalOutput->getValue(), &JA); 2352 } 2353 2354 // For /P, preprocess to file named after BaseInput. 2355 if (C.getArgs().hasArg(options::OPT__SLASH_P)) { 2356 assert(AtTopLevel && isa<PreprocessJobAction>(JA)); 2357 StringRef BaseName = llvm::sys::path::filename(BaseInput); 2358 StringRef NameArg; 2359 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi)) 2360 NameArg = A->getValue(); 2361 return C.addResultFile( 2362 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C), 2363 &JA); 2364 } 2365 2366 // Default to writing to stdout? 2367 if (AtTopLevel && !CCGenDiagnostics && 2368 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile)) 2369 return "-"; 2370 2371 // Is this the assembly listing for /FA? 2372 if (JA.getType() == types::TY_PP_Asm && 2373 (C.getArgs().hasArg(options::OPT__SLASH_FA) || 2374 C.getArgs().hasArg(options::OPT__SLASH_Fa))) { 2375 // Use /Fa and the input filename to determine the asm file name. 2376 StringRef BaseName = llvm::sys::path::filename(BaseInput); 2377 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa); 2378 return C.addResultFile( 2379 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()), 2380 &JA); 2381 } 2382 2383 // Output to a temporary file? 2384 if ((!AtTopLevel && !isSaveTempsEnabled() && 2385 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) || 2386 CCGenDiagnostics) { 2387 StringRef Name = llvm::sys::path::filename(BaseInput); 2388 std::pair<StringRef, StringRef> Split = Name.split('.'); 2389 std::string TmpName = GetTemporaryPath( 2390 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode())); 2391 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); 2392 } 2393 2394 SmallString<128> BasePath(BaseInput); 2395 StringRef BaseName; 2396 2397 // Dsymutil actions should use the full path. 2398 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA)) 2399 BaseName = BasePath; 2400 else 2401 BaseName = llvm::sys::path::filename(BasePath); 2402 2403 // Determine what the derived output name should be. 2404 const char *NamedOutput; 2405 2406 if (JA.getType() == types::TY_Object && 2407 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) { 2408 // The /Fo or /o flag decides the object filename. 2409 StringRef Val = 2410 C.getArgs() 2411 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o) 2412 ->getValue(); 2413 NamedOutput = 2414 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object); 2415 } else if (JA.getType() == types::TY_Image && 2416 C.getArgs().hasArg(options::OPT__SLASH_Fe, 2417 options::OPT__SLASH_o)) { 2418 // The /Fe or /o flag names the linked file. 2419 StringRef Val = 2420 C.getArgs() 2421 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o) 2422 ->getValue(); 2423 NamedOutput = 2424 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image); 2425 } else if (JA.getType() == types::TY_Image) { 2426 if (IsCLMode()) { 2427 // clang-cl uses BaseName for the executable name. 2428 NamedOutput = 2429 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image); 2430 } else if (MultipleArchs && BoundArch) { 2431 SmallString<128> Output(getDefaultImageName()); 2432 Output += JA.getOffloadingFileNamePrefix(NormalizedTriple); 2433 Output += "-"; 2434 Output.append(BoundArch); 2435 NamedOutput = C.getArgs().MakeArgString(Output.c_str()); 2436 } else { 2437 NamedOutput = getDefaultImageName(); 2438 } 2439 } else if (JA.getType() == types::TY_PCH && IsCLMode()) { 2440 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName).c_str()); 2441 } else { 2442 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode()); 2443 assert(Suffix && "All types used for output should have a suffix."); 2444 2445 std::string::size_type End = std::string::npos; 2446 if (!types::appendSuffixForType(JA.getType())) 2447 End = BaseName.rfind('.'); 2448 SmallString<128> Suffixed(BaseName.substr(0, End)); 2449 Suffixed += JA.getOffloadingFileNamePrefix(NormalizedTriple); 2450 if (MultipleArchs && BoundArch) { 2451 Suffixed += "-"; 2452 Suffixed.append(BoundArch); 2453 } 2454 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for 2455 // the unoptimized bitcode so that it does not get overwritten by the ".bc" 2456 // optimized bitcode output. 2457 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) && 2458 JA.getType() == types::TY_LLVM_BC) 2459 Suffixed += ".tmp"; 2460 Suffixed += '.'; 2461 Suffixed += Suffix; 2462 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str()); 2463 } 2464 2465 // Prepend object file path if -save-temps=obj 2466 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) && 2467 JA.getType() != types::TY_PCH) { 2468 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 2469 SmallString<128> TempPath(FinalOutput->getValue()); 2470 llvm::sys::path::remove_filename(TempPath); 2471 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput); 2472 llvm::sys::path::append(TempPath, OutputFileName); 2473 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str()); 2474 } 2475 2476 // If we're saving temps and the temp file conflicts with the input file, 2477 // then avoid overwriting input file. 2478 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) { 2479 bool SameFile = false; 2480 SmallString<256> Result; 2481 llvm::sys::fs::current_path(Result); 2482 llvm::sys::path::append(Result, BaseName); 2483 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile); 2484 // Must share the same path to conflict. 2485 if (SameFile) { 2486 StringRef Name = llvm::sys::path::filename(BaseInput); 2487 std::pair<StringRef, StringRef> Split = Name.split('.'); 2488 std::string TmpName = GetTemporaryPath( 2489 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode())); 2490 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); 2491 } 2492 } 2493 2494 // As an annoying special case, PCH generation doesn't strip the pathname. 2495 if (JA.getType() == types::TY_PCH && !IsCLMode()) { 2496 llvm::sys::path::remove_filename(BasePath); 2497 if (BasePath.empty()) 2498 BasePath = NamedOutput; 2499 else 2500 llvm::sys::path::append(BasePath, NamedOutput); 2501 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA); 2502 } else { 2503 return C.addResultFile(NamedOutput, &JA); 2504 } 2505 } 2506 2507 std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const { 2508 // Respect a limited subset of the '-Bprefix' functionality in GCC by 2509 // attempting to use this prefix when looking for file paths. 2510 for (const std::string &Dir : PrefixDirs) { 2511 if (Dir.empty()) 2512 continue; 2513 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir); 2514 llvm::sys::path::append(P, Name); 2515 if (llvm::sys::fs::exists(Twine(P))) 2516 return P.str(); 2517 } 2518 2519 SmallString<128> P(ResourceDir); 2520 llvm::sys::path::append(P, Name); 2521 if (llvm::sys::fs::exists(Twine(P))) 2522 return P.str(); 2523 2524 for (const std::string &Dir : TC.getFilePaths()) { 2525 if (Dir.empty()) 2526 continue; 2527 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir); 2528 llvm::sys::path::append(P, Name); 2529 if (llvm::sys::fs::exists(Twine(P))) 2530 return P.str(); 2531 } 2532 2533 return Name; 2534 } 2535 2536 void Driver::generatePrefixedToolNames( 2537 const char *Tool, const ToolChain &TC, 2538 SmallVectorImpl<std::string> &Names) const { 2539 // FIXME: Needs a better variable than DefaultTargetTriple 2540 Names.emplace_back(DefaultTargetTriple + "-" + Tool); 2541 Names.emplace_back(Tool); 2542 2543 // Allow the discovery of tools prefixed with LLVM's default target triple. 2544 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple(); 2545 if (LLVMDefaultTargetTriple != DefaultTargetTriple) 2546 Names.emplace_back(LLVMDefaultTargetTriple + "-" + Tool); 2547 } 2548 2549 static bool ScanDirForExecutable(SmallString<128> &Dir, 2550 ArrayRef<std::string> Names) { 2551 for (const auto &Name : Names) { 2552 llvm::sys::path::append(Dir, Name); 2553 if (llvm::sys::fs::can_execute(Twine(Dir))) 2554 return true; 2555 llvm::sys::path::remove_filename(Dir); 2556 } 2557 return false; 2558 } 2559 2560 std::string Driver::GetProgramPath(const char *Name, 2561 const ToolChain &TC) const { 2562 SmallVector<std::string, 2> TargetSpecificExecutables; 2563 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables); 2564 2565 // Respect a limited subset of the '-Bprefix' functionality in GCC by 2566 // attempting to use this prefix when looking for program paths. 2567 for (const auto &PrefixDir : PrefixDirs) { 2568 if (llvm::sys::fs::is_directory(PrefixDir)) { 2569 SmallString<128> P(PrefixDir); 2570 if (ScanDirForExecutable(P, TargetSpecificExecutables)) 2571 return P.str(); 2572 } else { 2573 SmallString<128> P(PrefixDir + Name); 2574 if (llvm::sys::fs::can_execute(Twine(P))) 2575 return P.str(); 2576 } 2577 } 2578 2579 const ToolChain::path_list &List = TC.getProgramPaths(); 2580 for (const auto &Path : List) { 2581 SmallString<128> P(Path); 2582 if (ScanDirForExecutable(P, TargetSpecificExecutables)) 2583 return P.str(); 2584 } 2585 2586 // If all else failed, search the path. 2587 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) 2588 if (llvm::ErrorOr<std::string> P = 2589 llvm::sys::findProgramByName(TargetSpecificExecutable)) 2590 return *P; 2591 2592 return Name; 2593 } 2594 2595 std::string Driver::GetTemporaryPath(StringRef Prefix, 2596 const char *Suffix) const { 2597 SmallString<128> Path; 2598 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path); 2599 if (EC) { 2600 Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 2601 return ""; 2602 } 2603 2604 return Path.str(); 2605 } 2606 2607 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const { 2608 SmallString<128> Output; 2609 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) { 2610 // FIXME: If anybody needs it, implement this obscure rule: 2611 // "If you specify a directory without a file name, the default file name 2612 // is VCx0.pch., where x is the major version of Visual C++ in use." 2613 Output = FpArg->getValue(); 2614 2615 // "If you do not specify an extension as part of the path name, an 2616 // extension of .pch is assumed. " 2617 if (!llvm::sys::path::has_extension(Output)) 2618 Output += ".pch"; 2619 } else { 2620 Output = BaseName; 2621 llvm::sys::path::replace_extension(Output, ".pch"); 2622 } 2623 return Output.str(); 2624 } 2625 2626 const ToolChain &Driver::getToolChain(const ArgList &Args, 2627 const llvm::Triple &Target) const { 2628 2629 ToolChain *&TC = ToolChains[Target.str()]; 2630 if (!TC) { 2631 switch (Target.getOS()) { 2632 case llvm::Triple::Haiku: 2633 TC = new toolchains::Haiku(*this, Target, Args); 2634 break; 2635 case llvm::Triple::CloudABI: 2636 TC = new toolchains::CloudABI(*this, Target, Args); 2637 break; 2638 case llvm::Triple::Darwin: 2639 case llvm::Triple::MacOSX: 2640 case llvm::Triple::IOS: 2641 case llvm::Triple::TvOS: 2642 case llvm::Triple::WatchOS: 2643 TC = new toolchains::DarwinClang(*this, Target, Args); 2644 break; 2645 case llvm::Triple::DragonFly: 2646 TC = new toolchains::DragonFly(*this, Target, Args); 2647 break; 2648 case llvm::Triple::OpenBSD: 2649 TC = new toolchains::OpenBSD(*this, Target, Args); 2650 break; 2651 case llvm::Triple::Bitrig: 2652 TC = new toolchains::Bitrig(*this, Target, Args); 2653 break; 2654 case llvm::Triple::NetBSD: 2655 TC = new toolchains::NetBSD(*this, Target, Args); 2656 break; 2657 case llvm::Triple::FreeBSD: 2658 TC = new toolchains::FreeBSD(*this, Target, Args); 2659 break; 2660 case llvm::Triple::Minix: 2661 TC = new toolchains::Minix(*this, Target, Args); 2662 break; 2663 case llvm::Triple::Linux: 2664 case llvm::Triple::ELFIAMCU: 2665 if (Target.getArch() == llvm::Triple::hexagon) 2666 TC = new toolchains::HexagonToolChain(*this, Target, Args); 2667 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) && 2668 !Target.hasEnvironment()) 2669 TC = new toolchains::MipsLLVMToolChain(*this, Target, Args); 2670 else 2671 TC = new toolchains::Linux(*this, Target, Args); 2672 break; 2673 case llvm::Triple::NaCl: 2674 TC = new toolchains::NaClToolChain(*this, Target, Args); 2675 break; 2676 case llvm::Triple::Solaris: 2677 TC = new toolchains::Solaris(*this, Target, Args); 2678 break; 2679 case llvm::Triple::AMDHSA: 2680 TC = new toolchains::AMDGPUToolChain(*this, Target, Args); 2681 break; 2682 case llvm::Triple::Win32: 2683 switch (Target.getEnvironment()) { 2684 default: 2685 if (Target.isOSBinFormatELF()) 2686 TC = new toolchains::Generic_ELF(*this, Target, Args); 2687 else if (Target.isOSBinFormatMachO()) 2688 TC = new toolchains::MachO(*this, Target, Args); 2689 else 2690 TC = new toolchains::Generic_GCC(*this, Target, Args); 2691 break; 2692 case llvm::Triple::GNU: 2693 TC = new toolchains::MinGW(*this, Target, Args); 2694 break; 2695 case llvm::Triple::Itanium: 2696 TC = new toolchains::CrossWindowsToolChain(*this, Target, Args); 2697 break; 2698 case llvm::Triple::MSVC: 2699 case llvm::Triple::UnknownEnvironment: 2700 TC = new toolchains::MSVCToolChain(*this, Target, Args); 2701 break; 2702 } 2703 break; 2704 case llvm::Triple::CUDA: 2705 TC = new toolchains::CudaToolChain(*this, Target, Args); 2706 break; 2707 case llvm::Triple::PS4: 2708 TC = new toolchains::PS4CPU(*this, Target, Args); 2709 break; 2710 default: 2711 // Of these targets, Hexagon is the only one that might have 2712 // an OS of Linux, in which case it got handled above already. 2713 switch (Target.getArch()) { 2714 case llvm::Triple::tce: 2715 TC = new toolchains::TCEToolChain(*this, Target, Args); 2716 break; 2717 case llvm::Triple::hexagon: 2718 TC = new toolchains::HexagonToolChain(*this, Target, Args); 2719 break; 2720 case llvm::Triple::lanai: 2721 TC = new toolchains::LanaiToolChain(*this, Target, Args); 2722 break; 2723 case llvm::Triple::xcore: 2724 TC = new toolchains::XCoreToolChain(*this, Target, Args); 2725 break; 2726 case llvm::Triple::wasm32: 2727 case llvm::Triple::wasm64: 2728 TC = new toolchains::WebAssembly(*this, Target, Args); 2729 break; 2730 default: 2731 if (Target.getVendor() == llvm::Triple::Myriad) 2732 TC = new toolchains::MyriadToolChain(*this, Target, Args); 2733 else if (Target.isOSBinFormatELF()) 2734 TC = new toolchains::Generic_ELF(*this, Target, Args); 2735 else if (Target.isOSBinFormatMachO()) 2736 TC = new toolchains::MachO(*this, Target, Args); 2737 else 2738 TC = new toolchains::Generic_GCC(*this, Target, Args); 2739 } 2740 } 2741 } 2742 return *TC; 2743 } 2744 2745 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const { 2746 // Say "no" if there is not exactly one input of a type clang understands. 2747 if (JA.size() != 1 || 2748 !types::isAcceptedByClang((*JA.input_begin())->getType())) 2749 return false; 2750 2751 // And say "no" if this is not a kind of action clang understands. 2752 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) && 2753 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA)) 2754 return false; 2755 2756 return true; 2757 } 2758 2759 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the 2760 /// grouped values as integers. Numbers which are not provided are set to 0. 2761 /// 2762 /// \return True if the entire string was parsed (9.2), or all groups were 2763 /// parsed (10.3.5extrastuff). 2764 bool Driver::GetReleaseVersion(const char *Str, unsigned &Major, 2765 unsigned &Minor, unsigned &Micro, 2766 bool &HadExtra) { 2767 HadExtra = false; 2768 2769 Major = Minor = Micro = 0; 2770 if (*Str == '\0') 2771 return false; 2772 2773 char *End; 2774 Major = (unsigned)strtol(Str, &End, 10); 2775 if (*Str != '\0' && *End == '\0') 2776 return true; 2777 if (*End != '.') 2778 return false; 2779 2780 Str = End + 1; 2781 Minor = (unsigned)strtol(Str, &End, 10); 2782 if (*Str != '\0' && *End == '\0') 2783 return true; 2784 if (*End != '.') 2785 return false; 2786 2787 Str = End + 1; 2788 Micro = (unsigned)strtol(Str, &End, 10); 2789 if (*Str != '\0' && *End == '\0') 2790 return true; 2791 if (Str == End) 2792 return false; 2793 HadExtra = true; 2794 return true; 2795 } 2796 2797 /// Parse digits from a string \p Str and fulfill \p Digits with 2798 /// the parsed numbers. This method assumes that the max number of 2799 /// digits to look for is equal to Digits.size(). 2800 /// 2801 /// \return True if the entire string was parsed and there are 2802 /// no extra characters remaining at the end. 2803 bool Driver::GetReleaseVersion(const char *Str, 2804 MutableArrayRef<unsigned> Digits) { 2805 if (*Str == '\0') 2806 return false; 2807 2808 char *End; 2809 unsigned CurDigit = 0; 2810 while (CurDigit < Digits.size()) { 2811 unsigned Digit = (unsigned)strtol(Str, &End, 10); 2812 Digits[CurDigit] = Digit; 2813 if (*Str != '\0' && *End == '\0') 2814 return true; 2815 if (*End != '.' || Str == End) 2816 return false; 2817 Str = End + 1; 2818 CurDigit++; 2819 } 2820 2821 // More digits than requested, bail out... 2822 return false; 2823 } 2824 2825 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const { 2826 unsigned IncludedFlagsBitmask = 0; 2827 unsigned ExcludedFlagsBitmask = options::NoDriverOption; 2828 2829 if (Mode == CLMode) { 2830 // Include CL and Core options. 2831 IncludedFlagsBitmask |= options::CLOption; 2832 IncludedFlagsBitmask |= options::CoreOption; 2833 } else { 2834 ExcludedFlagsBitmask |= options::CLOption; 2835 } 2836 2837 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask); 2838 } 2839 2840 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) { 2841 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false); 2842 } 2843