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