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