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