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