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