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