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 12 #include "clang/Driver/Action.h" 13 #include "clang/Driver/Arg.h" 14 #include "clang/Driver/ArgList.h" 15 #include "clang/Driver/Compilation.h" 16 #include "clang/Driver/DriverDiagnostic.h" 17 #include "clang/Driver/Job.h" 18 #include "clang/Driver/OptTable.h" 19 #include "clang/Driver/Option.h" 20 #include "clang/Driver/Options.h" 21 #include "clang/Driver/Tool.h" 22 #include "clang/Driver/ToolChain.h" 23 24 #include "clang/Basic/Version.h" 25 26 #include "llvm/ADT/ArrayRef.h" 27 #include "llvm/ADT/StringSet.h" 28 #include "llvm/ADT/OwningPtr.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/PrettyStackTrace.h" 31 #include "llvm/Support/raw_ostream.h" 32 #include "llvm/Support/FileSystem.h" 33 #include "llvm/Support/Path.h" 34 #include "llvm/Support/Program.h" 35 36 #include "InputInfo.h" 37 #include "ToolChains.h" 38 39 #include <map> 40 41 #include "clang/Config/config.h" 42 43 using namespace clang::driver; 44 using namespace clang; 45 46 Driver::Driver(StringRef ClangExecutable, 47 StringRef DefaultTargetTriple, 48 StringRef DefaultImageName, 49 bool IsProduction, 50 DiagnosticsEngine &Diags) 51 : Opts(createDriverOptTable()), Diags(Diags), 52 ClangExecutable(ClangExecutable), UseStdLib(true), 53 DefaultTargetTriple(DefaultTargetTriple), 54 DefaultImageName(DefaultImageName), 55 DriverTitle("clang \"gcc-compatible\" driver"), 56 CCPrintOptionsFilename(0), CCPrintHeadersFilename(0), 57 CCLogDiagnosticsFilename(0), CCCIsCXX(false), 58 CCCIsCPP(false),CCCEcho(false), CCCPrintBindings(false), 59 CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false), 60 CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true), 61 CCCUseClang(true), CCCUseClangCXX(true), CCCUseClangCPP(true), 62 CCCUsePCH(true), SuppressMissingInputWarning(false) { 63 if (IsProduction) { 64 // In a "production" build, only use clang on architectures we expect to 65 // work. 66 // 67 // During development its more convenient to always have the driver use 68 // clang, but we don't want users to be confused when things don't work, or 69 // to file bugs for things we don't support. 70 CCCClangArchs.insert(llvm::Triple::x86); 71 CCCClangArchs.insert(llvm::Triple::x86_64); 72 CCCClangArchs.insert(llvm::Triple::arm); 73 } 74 75 Name = llvm::sys::path::stem(ClangExecutable); 76 Dir = llvm::sys::path::parent_path(ClangExecutable); 77 78 // Compute the path to the resource directory. 79 StringRef ClangResourceDir(CLANG_RESOURCE_DIR); 80 SmallString<128> P(Dir); 81 if (ClangResourceDir != "") 82 llvm::sys::path::append(P, ClangResourceDir); 83 else 84 llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING); 85 ResourceDir = P.str(); 86 } 87 88 Driver::~Driver() { 89 delete Opts; 90 91 for (llvm::StringMap<ToolChain *>::iterator I = ToolChains.begin(), 92 E = ToolChains.end(); 93 I != E; ++I) 94 delete I->second; 95 } 96 97 InputArgList *Driver::ParseArgStrings(ArrayRef<const char *> ArgList) { 98 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing"); 99 unsigned MissingArgIndex, MissingArgCount; 100 InputArgList *Args = getOpts().ParseArgs(ArgList.begin(), ArgList.end(), 101 MissingArgIndex, MissingArgCount); 102 103 // Check for missing argument error. 104 if (MissingArgCount) 105 Diag(clang::diag::err_drv_missing_argument) 106 << Args->getArgString(MissingArgIndex) << MissingArgCount; 107 108 // Check for unsupported options. 109 for (ArgList::const_iterator it = Args->begin(), ie = Args->end(); 110 it != ie; ++it) { 111 Arg *A = *it; 112 if (A->getOption().isUnsupported()) { 113 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args); 114 continue; 115 } 116 } 117 118 return Args; 119 } 120 121 // Determine which compilation mode we are in. We look for options which 122 // affect the phase, starting with the earliest phases, and record which 123 // option we used to determine the final phase. 124 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, Arg **FinalPhaseArg) 125 const { 126 Arg *PhaseArg = 0; 127 phases::ID FinalPhase; 128 129 // -{E,M,MM} only run the preprocessor. 130 if (CCCIsCPP || 131 (PhaseArg = DAL.getLastArg(options::OPT_E)) || 132 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM))) { 133 FinalPhase = phases::Preprocess; 134 135 // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler. 136 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) || 137 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) || 138 (PhaseArg = DAL.getLastArg(options::OPT__analyze, 139 options::OPT__analyze_auto)) || 140 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast)) || 141 (PhaseArg = DAL.getLastArg(options::OPT_S))) { 142 FinalPhase = phases::Compile; 143 144 // -c only runs up to the assembler. 145 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) { 146 FinalPhase = phases::Assemble; 147 148 // Otherwise do everything. 149 } else 150 FinalPhase = phases::Link; 151 152 if (FinalPhaseArg) 153 *FinalPhaseArg = PhaseArg; 154 155 return FinalPhase; 156 } 157 158 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const { 159 DerivedArgList *DAL = new DerivedArgList(Args); 160 161 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib); 162 for (ArgList::const_iterator it = Args.begin(), 163 ie = Args.end(); it != ie; ++it) { 164 const Arg *A = *it; 165 166 // Unfortunately, we have to parse some forwarding options (-Xassembler, 167 // -Xlinker, -Xpreprocessor) because we either integrate their functionality 168 // (assembler and preprocessor), or bypass a previous driver ('collect2'). 169 170 // Rewrite linker options, to replace --no-demangle with a custom internal 171 // option. 172 if ((A->getOption().matches(options::OPT_Wl_COMMA) || 173 A->getOption().matches(options::OPT_Xlinker)) && 174 A->containsValue("--no-demangle")) { 175 // Add the rewritten no-demangle argument. 176 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle)); 177 178 // Add the remaining values as Xlinker arguments. 179 for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) 180 if (StringRef(A->getValue(Args, i)) != "--no-demangle") 181 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), 182 A->getValue(Args, i)); 183 184 continue; 185 } 186 187 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by 188 // some build systems. We don't try to be complete here because we don't 189 // care to encourage this usage model. 190 if (A->getOption().matches(options::OPT_Wp_COMMA) && 191 A->getNumValues() == 2 && 192 (A->getValue(Args, 0) == StringRef("-MD") || 193 A->getValue(Args, 0) == StringRef("-MMD"))) { 194 // Rewrite to -MD/-MMD along with -MF. 195 if (A->getValue(Args, 0) == StringRef("-MD")) 196 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD)); 197 else 198 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD)); 199 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF), 200 A->getValue(Args, 1)); 201 continue; 202 } 203 204 // Rewrite reserved library names. 205 if (A->getOption().matches(options::OPT_l)) { 206 StringRef Value = A->getValue(Args); 207 208 // Rewrite unless -nostdlib is present. 209 if (!HasNostdlib && Value == "stdc++") { 210 DAL->AddFlagArg(A, Opts->getOption( 211 options::OPT_Z_reserved_lib_stdcxx)); 212 continue; 213 } 214 215 // Rewrite unconditionally. 216 if (Value == "cc_kext") { 217 DAL->AddFlagArg(A, Opts->getOption( 218 options::OPT_Z_reserved_lib_cckext)); 219 continue; 220 } 221 } 222 223 DAL->append(*it); 224 } 225 226 // Add a default value of -mlinker-version=, if one was given and the user 227 // didn't specify one. 228 #if defined(HOST_LINK_VERSION) 229 if (!Args.hasArg(options::OPT_mlinker_version_EQ)) { 230 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ), 231 HOST_LINK_VERSION); 232 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim(); 233 } 234 #endif 235 236 return DAL; 237 } 238 239 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) { 240 llvm::PrettyStackTraceString CrashInfo("Compilation construction"); 241 242 // FIXME: Handle environment options which affect driver behavior, somewhere 243 // (client?). GCC_EXEC_PREFIX, LIBRARY_PATH, LPATH, CC_PRINT_OPTIONS. 244 245 if (char *env = ::getenv("COMPILER_PATH")) { 246 StringRef CompilerPath = env; 247 while (!CompilerPath.empty()) { 248 std::pair<StringRef, StringRef> Split = CompilerPath.split(':'); 249 PrefixDirs.push_back(Split.first); 250 CompilerPath = Split.second; 251 } 252 } 253 254 // FIXME: What are we going to do with -V and -b? 255 256 // FIXME: This stuff needs to go into the Compilation, not the driver. 257 bool CCCPrintOptions = false, CCCPrintActions = false; 258 259 InputArgList *Args = ParseArgStrings(ArgList.slice(1)); 260 261 // -no-canonical-prefixes is used very early in main. 262 Args->ClaimAllArgs(options::OPT_no_canonical_prefixes); 263 264 // Ignore -pipe. 265 Args->ClaimAllArgs(options::OPT_pipe); 266 267 // Extract -ccc args. 268 // 269 // FIXME: We need to figure out where this behavior should live. Most of it 270 // should be outside in the client; the parts that aren't should have proper 271 // options, either by introducing new ones or by overloading gcc ones like -V 272 // or -b. 273 CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options); 274 CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases); 275 CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings); 276 CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX; 277 CCCEcho = Args->hasArg(options::OPT_ccc_echo); 278 if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name)) 279 CCCGenericGCCName = A->getValue(*Args); 280 CCCUseClangCXX = Args->hasFlag(options::OPT_ccc_clang_cxx, 281 options::OPT_ccc_no_clang_cxx, 282 CCCUseClangCXX); 283 CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch, 284 options::OPT_ccc_pch_is_pth); 285 CCCUseClang = !Args->hasArg(options::OPT_ccc_no_clang); 286 CCCUseClangCPP = !Args->hasArg(options::OPT_ccc_no_clang_cpp); 287 if (const Arg *A = Args->getLastArg(options::OPT_ccc_clang_archs)) { 288 StringRef Cur = A->getValue(*Args); 289 290 CCCClangArchs.clear(); 291 while (!Cur.empty()) { 292 std::pair<StringRef, StringRef> Split = Cur.split(','); 293 294 if (!Split.first.empty()) { 295 llvm::Triple::ArchType Arch = 296 llvm::Triple(Split.first, "", "").getArch(); 297 298 if (Arch == llvm::Triple::UnknownArch) 299 Diag(clang::diag::err_drv_invalid_arch_name) << Split.first; 300 301 CCCClangArchs.insert(Arch); 302 } 303 304 Cur = Split.second; 305 } 306 } 307 if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir)) 308 Dir = InstalledDir = A->getValue(*Args); 309 for (arg_iterator it = Args->filtered_begin(options::OPT_B), 310 ie = Args->filtered_end(); it != ie; ++it) { 311 const Arg *A = *it; 312 A->claim(); 313 PrefixDirs.push_back(A->getValue(*Args, 0)); 314 } 315 if (const Arg *A = Args->getLastArg(options::OPT__sysroot_EQ)) 316 SysRoot = A->getValue(*Args); 317 if (Args->hasArg(options::OPT_nostdlib)) 318 UseStdLib = false; 319 320 // Perform the default argument translations. 321 DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args); 322 323 // Owned by the host. 324 const ToolChain &TC = getToolChain(*Args); 325 326 // The compilation takes ownership of Args. 327 Compilation *C = new Compilation(*this, TC, Args, TranslatedArgs); 328 329 // FIXME: This behavior shouldn't be here. 330 if (CCCPrintOptions) { 331 PrintOptions(C->getInputArgs()); 332 return C; 333 } 334 335 if (!HandleImmediateArgs(*C)) 336 return C; 337 338 // Construct the list of inputs. 339 InputList Inputs; 340 BuildInputs(C->getDefaultToolChain(), C->getArgs(), Inputs); 341 342 // Construct the list of abstract actions to perform for this compilation. On 343 // Darwin target OSes this uses the driver-driver and universal actions. 344 if (TC.getTriple().isOSDarwin()) 345 BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(), 346 Inputs, C->getActions()); 347 else 348 BuildActions(C->getDefaultToolChain(), C->getArgs(), Inputs, 349 C->getActions()); 350 351 if (CCCPrintActions) { 352 PrintActions(*C); 353 return C; 354 } 355 356 BuildJobs(*C); 357 358 return C; 359 } 360 361 // When clang crashes, produce diagnostic information including the fully 362 // preprocessed source file(s). Request that the developer attach the 363 // diagnostic information to a bug report. 364 void Driver::generateCompilationDiagnostics(Compilation &C, 365 const Command *FailingCommand) { 366 Diag(clang::diag::note_drv_command_failed_diag_msg) 367 << "Please submit a bug report to " BUG_REPORT_URL " and include command" 368 " line arguments and all diagnostic information."; 369 370 // Suppress driver output and emit preprocessor output to temp file. 371 CCCIsCPP = true; 372 CCGenDiagnostics = true; 373 374 // Save the original job command(s). 375 std::string Cmd; 376 llvm::raw_string_ostream OS(Cmd); 377 C.PrintJob(OS, C.getJobs(), "\n", false); 378 OS.flush(); 379 380 // Clear stale state and suppress tool output. 381 C.initCompilationForDiagnostics(); 382 Diags.Reset(); 383 384 // Construct the list of inputs. 385 InputList Inputs; 386 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs); 387 388 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) { 389 bool IgnoreInput = false; 390 391 // Ignore input from stdin or any inputs that cannot be preprocessed. 392 if (!strcmp(it->second->getValue(C.getArgs()), "-")) { 393 Diag(clang::diag::note_drv_command_failed_diag_msg) 394 << "Error generating preprocessed source(s) - ignoring input from stdin" 395 "."; 396 IgnoreInput = true; 397 } else if (types::getPreprocessedType(it->first) == types::TY_INVALID) { 398 IgnoreInput = true; 399 } 400 401 if (IgnoreInput) { 402 it = Inputs.erase(it); 403 ie = Inputs.end(); 404 } else { 405 ++it; 406 } 407 } 408 409 // Don't attempt to generate preprocessed files if multiple -arch options are 410 // used, unless they're all duplicates. 411 llvm::StringSet<> ArchNames; 412 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end(); 413 it != ie; ++it) { 414 Arg *A = *it; 415 if (A->getOption().matches(options::OPT_arch)) { 416 StringRef ArchName = A->getValue(C.getArgs()); 417 ArchNames.insert(ArchName); 418 } 419 } 420 if (ArchNames.size() > 1) { 421 Diag(clang::diag::note_drv_command_failed_diag_msg) 422 << "Error generating preprocessed source(s) - cannot generate " 423 "preprocessed source with multiple -arch options."; 424 return; 425 } 426 427 if (Inputs.empty()) { 428 Diag(clang::diag::note_drv_command_failed_diag_msg) 429 << "Error generating preprocessed source(s) - no preprocessable inputs."; 430 return; 431 } 432 433 // Construct the list of abstract actions to perform for this compilation. On 434 // Darwin OSes this uses the driver-driver and builds universal actions. 435 const ToolChain &TC = C.getDefaultToolChain(); 436 if (TC.getTriple().isOSDarwin()) 437 BuildUniversalActions(TC, C.getArgs(), Inputs, C.getActions()); 438 else 439 BuildActions(TC, C.getArgs(), Inputs, C.getActions()); 440 441 BuildJobs(C); 442 443 // If there were errors building the compilation, quit now. 444 if (Diags.hasErrorOccurred()) { 445 Diag(clang::diag::note_drv_command_failed_diag_msg) 446 << "Error generating preprocessed source(s)."; 447 return; 448 } 449 450 // Generate preprocessed output. 451 FailingCommand = 0; 452 int Res = C.ExecuteJob(C.getJobs(), FailingCommand); 453 454 // If the command succeeded, we are done. 455 if (Res == 0) { 456 Diag(clang::diag::note_drv_command_failed_diag_msg) 457 << "Preprocessed source(s) and associated run script(s) are located at:"; 458 ArgStringList Files = C.getTempFiles(); 459 for (ArgStringList::const_iterator it = Files.begin(), ie = Files.end(); 460 it != ie; ++it) { 461 Diag(clang::diag::note_drv_command_failed_diag_msg) << *it; 462 463 std::string Err; 464 std::string Script = StringRef(*it).rsplit('.').first; 465 Script += ".sh"; 466 llvm::raw_fd_ostream ScriptOS(Script.c_str(), Err, 467 llvm::raw_fd_ostream::F_Excl | 468 llvm::raw_fd_ostream::F_Binary); 469 if (!Err.empty()) { 470 Diag(clang::diag::note_drv_command_failed_diag_msg) 471 << "Error generating run script: " + Script + " " + Err; 472 } else { 473 ScriptOS << Cmd; 474 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script; 475 } 476 } 477 } else { 478 // Failure, remove preprocessed files. 479 if (!C.getArgs().hasArg(options::OPT_save_temps)) 480 C.CleanupFileList(C.getTempFiles(), true); 481 482 Diag(clang::diag::note_drv_command_failed_diag_msg) 483 << "Error generating preprocessed source(s)."; 484 } 485 } 486 487 int Driver::ExecuteCompilation(const Compilation &C, 488 const Command *&FailingCommand) const { 489 // Just print if -### was present. 490 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 491 C.PrintJob(llvm::errs(), C.getJobs(), "\n", true); 492 return 0; 493 } 494 495 // If there were errors building the compilation, quit now. 496 if (Diags.hasErrorOccurred()) 497 return 1; 498 499 int Res = C.ExecuteJob(C.getJobs(), FailingCommand); 500 501 // Remove temp files. 502 C.CleanupFileList(C.getTempFiles()); 503 504 // If the command succeeded, we are done. 505 if (Res == 0) 506 return Res; 507 508 // Otherwise, remove result files as well. 509 if (!C.getArgs().hasArg(options::OPT_save_temps)) { 510 C.CleanupFileList(C.getResultFiles(), true); 511 512 // Failure result files are valid unless we crashed. 513 if (Res < 0) { 514 C.CleanupFileList(C.getFailureResultFiles(), true); 515 #ifdef _WIN32 516 // Exit status should not be negative on Win32, 517 // unless abnormal termination. 518 Res = 1; 519 #endif 520 } 521 } 522 523 // Print extra information about abnormal failures, if possible. 524 // 525 // This is ad-hoc, but we don't want to be excessively noisy. If the result 526 // status was 1, assume the command failed normally. In particular, if it was 527 // the compiler then assume it gave a reasonable error code. Failures in other 528 // tools are less common, and they generally have worse diagnostics, so always 529 // print the diagnostic there. 530 const Tool &FailingTool = FailingCommand->getCreator(); 531 532 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) { 533 // FIXME: See FIXME above regarding result code interpretation. 534 if (Res < 0) 535 Diag(clang::diag::err_drv_command_signalled) 536 << FailingTool.getShortName(); 537 else 538 Diag(clang::diag::err_drv_command_failed) 539 << FailingTool.getShortName() << Res; 540 } 541 542 return Res; 543 } 544 545 void Driver::PrintOptions(const ArgList &Args) const { 546 unsigned i = 0; 547 for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); 548 it != ie; ++it, ++i) { 549 Arg *A = *it; 550 llvm::errs() << "Option " << i << " - " 551 << "Name: \"" << A->getOption().getName() << "\", " 552 << "Values: {"; 553 for (unsigned j = 0; j < A->getNumValues(); ++j) { 554 if (j) 555 llvm::errs() << ", "; 556 llvm::errs() << '"' << A->getValue(Args, j) << '"'; 557 } 558 llvm::errs() << "}\n"; 559 } 560 } 561 562 void Driver::PrintHelp(bool ShowHidden) const { 563 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(), 564 ShowHidden); 565 } 566 567 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const { 568 // FIXME: The following handlers should use a callback mechanism, we don't 569 // know what the client would like to do. 570 OS << getClangFullVersion() << '\n'; 571 const ToolChain &TC = C.getDefaultToolChain(); 572 OS << "Target: " << TC.getTripleString() << '\n'; 573 574 // Print the threading model. 575 // 576 // FIXME: Implement correctly. 577 OS << "Thread model: " << "posix" << '\n'; 578 } 579 580 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories 581 /// option. 582 static void PrintDiagnosticCategories(raw_ostream &OS) { 583 // Skip the empty category. 584 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); 585 i != max; ++i) 586 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n'; 587 } 588 589 bool Driver::HandleImmediateArgs(const Compilation &C) { 590 // The order these options are handled in gcc is all over the place, but we 591 // don't expect inconsistencies w.r.t. that to matter in practice. 592 593 if (C.getArgs().hasArg(options::OPT_dumpmachine)) { 594 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n'; 595 return false; 596 } 597 598 if (C.getArgs().hasArg(options::OPT_dumpversion)) { 599 // Since -dumpversion is only implemented for pedantic GCC compatibility, we 600 // return an answer which matches our definition of __VERSION__. 601 // 602 // If we want to return a more correct answer some day, then we should 603 // introduce a non-pedantically GCC compatible mode to Clang in which we 604 // provide sensible definitions for -dumpversion, __VERSION__, etc. 605 llvm::outs() << "4.2.1\n"; 606 return false; 607 } 608 609 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) { 610 PrintDiagnosticCategories(llvm::outs()); 611 return false; 612 } 613 614 if (C.getArgs().hasArg(options::OPT__help) || 615 C.getArgs().hasArg(options::OPT__help_hidden)) { 616 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden)); 617 return false; 618 } 619 620 if (C.getArgs().hasArg(options::OPT__version)) { 621 // Follow gcc behavior and use stdout for --version and stderr for -v. 622 PrintVersion(C, llvm::outs()); 623 return false; 624 } 625 626 if (C.getArgs().hasArg(options::OPT_v) || 627 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 628 PrintVersion(C, llvm::errs()); 629 SuppressMissingInputWarning = true; 630 } 631 632 const ToolChain &TC = C.getDefaultToolChain(); 633 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) { 634 llvm::outs() << "programs: ="; 635 for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(), 636 ie = TC.getProgramPaths().end(); it != ie; ++it) { 637 if (it != TC.getProgramPaths().begin()) 638 llvm::outs() << ':'; 639 llvm::outs() << *it; 640 } 641 llvm::outs() << "\n"; 642 llvm::outs() << "libraries: =" << ResourceDir; 643 644 std::string sysroot; 645 if (Arg *A = C.getArgs().getLastArg(options::OPT__sysroot_EQ)) 646 sysroot = A->getValue(C.getArgs()); 647 648 for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(), 649 ie = TC.getFilePaths().end(); it != ie; ++it) { 650 llvm::outs() << ':'; 651 const char *path = it->c_str(); 652 if (path[0] == '=') 653 llvm::outs() << sysroot << path + 1; 654 else 655 llvm::outs() << path; 656 } 657 llvm::outs() << "\n"; 658 return false; 659 } 660 661 // FIXME: The following handlers should use a callback mechanism, we don't 662 // know what the client would like to do. 663 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) { 664 llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC) << "\n"; 665 return false; 666 } 667 668 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) { 669 llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC) << "\n"; 670 return false; 671 } 672 673 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) { 674 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n"; 675 return false; 676 } 677 678 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) { 679 // FIXME: We need tool chain support for this. 680 llvm::outs() << ".;\n"; 681 682 switch (C.getDefaultToolChain().getTriple().getArch()) { 683 default: 684 break; 685 686 case llvm::Triple::x86_64: 687 llvm::outs() << "x86_64;@m64" << "\n"; 688 break; 689 690 case llvm::Triple::ppc64: 691 llvm::outs() << "ppc64;@m64" << "\n"; 692 break; 693 } 694 return false; 695 } 696 697 // FIXME: What is the difference between print-multi-directory and 698 // print-multi-os-directory? 699 if (C.getArgs().hasArg(options::OPT_print_multi_directory) || 700 C.getArgs().hasArg(options::OPT_print_multi_os_directory)) { 701 switch (C.getDefaultToolChain().getTriple().getArch()) { 702 default: 703 case llvm::Triple::x86: 704 case llvm::Triple::ppc: 705 llvm::outs() << "." << "\n"; 706 break; 707 708 case llvm::Triple::x86_64: 709 llvm::outs() << "x86_64" << "\n"; 710 break; 711 712 case llvm::Triple::ppc64: 713 llvm::outs() << "ppc64" << "\n"; 714 break; 715 } 716 return false; 717 } 718 719 return true; 720 } 721 722 static unsigned PrintActions1(const Compilation &C, Action *A, 723 std::map<Action*, unsigned> &Ids) { 724 if (Ids.count(A)) 725 return Ids[A]; 726 727 std::string str; 728 llvm::raw_string_ostream os(str); 729 730 os << Action::getClassName(A->getKind()) << ", "; 731 if (InputAction *IA = dyn_cast<InputAction>(A)) { 732 os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\""; 733 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) { 734 os << '"' << (BIA->getArchName() ? BIA->getArchName() : 735 C.getDefaultToolChain().getArchName()) << '"' 736 << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}"; 737 } else { 738 os << "{"; 739 for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) { 740 os << PrintActions1(C, *it, Ids); 741 ++it; 742 if (it != ie) 743 os << ", "; 744 } 745 os << "}"; 746 } 747 748 unsigned Id = Ids.size(); 749 Ids[A] = Id; 750 llvm::errs() << Id << ": " << os.str() << ", " 751 << types::getTypeName(A->getType()) << "\n"; 752 753 return Id; 754 } 755 756 void Driver::PrintActions(const Compilation &C) const { 757 std::map<Action*, unsigned> Ids; 758 for (ActionList::const_iterator it = C.getActions().begin(), 759 ie = C.getActions().end(); it != ie; ++it) 760 PrintActions1(C, *it, Ids); 761 } 762 763 /// \brief Check whether the given input tree contains any compilation or 764 /// assembly actions. 765 static bool ContainsCompileOrAssembleAction(const Action *A) { 766 if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A)) 767 return true; 768 769 for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it) 770 if (ContainsCompileOrAssembleAction(*it)) 771 return true; 772 773 return false; 774 } 775 776 void Driver::BuildUniversalActions(const ToolChain &TC, 777 const DerivedArgList &Args, 778 const InputList &BAInputs, 779 ActionList &Actions) const { 780 llvm::PrettyStackTraceString CrashInfo("Building universal build actions"); 781 // Collect the list of architectures. Duplicates are allowed, but should only 782 // be handled once (in the order seen). 783 llvm::StringSet<> ArchNames; 784 SmallVector<const char *, 4> Archs; 785 for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); 786 it != ie; ++it) { 787 Arg *A = *it; 788 789 if (A->getOption().matches(options::OPT_arch)) { 790 // Validate the option here; we don't save the type here because its 791 // particular spelling may participate in other driver choices. 792 llvm::Triple::ArchType Arch = 793 llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args)); 794 if (Arch == llvm::Triple::UnknownArch) { 795 Diag(clang::diag::err_drv_invalid_arch_name) 796 << A->getAsString(Args); 797 continue; 798 } 799 800 A->claim(); 801 if (ArchNames.insert(A->getValue(Args))) 802 Archs.push_back(A->getValue(Args)); 803 } 804 } 805 806 // When there is no explicit arch for this platform, make sure we still bind 807 // the architecture (to the default) so that -Xarch_ is handled correctly. 808 if (!Archs.size()) 809 Archs.push_back(0); 810 811 // FIXME: We killed off some others but these aren't yet detected in a 812 // functional manner. If we added information to jobs about which "auxiliary" 813 // files they wrote then we could detect the conflict these cause downstream. 814 if (Archs.size() > 1) { 815 // No recovery needed, the point of this is just to prevent 816 // overwriting the same files. 817 if (const Arg *A = Args.getLastArg(options::OPT_save_temps)) 818 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs) 819 << A->getAsString(Args); 820 } 821 822 ActionList SingleActions; 823 BuildActions(TC, Args, BAInputs, SingleActions); 824 825 // Add in arch bindings for every top level action, as well as lipo and 826 // dsymutil steps if needed. 827 for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) { 828 Action *Act = SingleActions[i]; 829 830 // Make sure we can lipo this kind of output. If not (and it is an actual 831 // output) then we disallow, since we can't create an output file with the 832 // right name without overwriting it. We could remove this oddity by just 833 // changing the output names to include the arch, which would also fix 834 // -save-temps. Compatibility wins for now. 835 836 if (Archs.size() > 1 && !types::canLipoType(Act->getType())) 837 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs) 838 << types::getTypeName(Act->getType()); 839 840 ActionList Inputs; 841 for (unsigned i = 0, e = Archs.size(); i != e; ++i) { 842 Inputs.push_back(new BindArchAction(Act, Archs[i])); 843 if (i != 0) 844 Inputs.back()->setOwnsInputs(false); 845 } 846 847 // Lipo if necessary, we do it this way because we need to set the arch flag 848 // so that -Xarch_ gets overwritten. 849 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing) 850 Actions.append(Inputs.begin(), Inputs.end()); 851 else 852 Actions.push_back(new LipoJobAction(Inputs, Act->getType())); 853 854 // Handle debug info queries. 855 Arg *A = Args.getLastArg(options::OPT_g_Group); 856 if (A && !A->getOption().matches(options::OPT_g0) && 857 !A->getOption().matches(options::OPT_gstabs) && 858 ContainsCompileOrAssembleAction(Actions.back())) { 859 860 // Add a 'dsymutil' step if necessary, when debug info is enabled and we 861 // have a compile input. We need to run 'dsymutil' ourselves in such cases 862 // because the debug info will refer to a temporary object file which is 863 // will be removed at the end of the compilation process. 864 if (Act->getType() == types::TY_Image) { 865 ActionList Inputs; 866 Inputs.push_back(Actions.back()); 867 Actions.pop_back(); 868 Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM)); 869 } 870 871 // Verify the output (debug information only) if we passed '-verify'. 872 if (Args.hasArg(options::OPT_verify)) { 873 ActionList VerifyInputs; 874 VerifyInputs.push_back(Actions.back()); 875 Actions.pop_back(); 876 Actions.push_back(new VerifyJobAction(VerifyInputs, 877 types::TY_Nothing)); 878 } 879 } 880 } 881 } 882 883 // Construct a the list of inputs and their types. 884 void Driver::BuildInputs(const ToolChain &TC, const DerivedArgList &Args, 885 InputList &Inputs) const { 886 // Track the current user specified (-x) input. We also explicitly track the 887 // argument used to set the type; we only want to claim the type when we 888 // actually use it, so we warn about unused -x arguments. 889 types::ID InputType = types::TY_Nothing; 890 Arg *InputTypeArg = 0; 891 892 for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); 893 it != ie; ++it) { 894 Arg *A = *it; 895 896 if (isa<InputOption>(A->getOption())) { 897 const char *Value = A->getValue(Args); 898 types::ID Ty = types::TY_INVALID; 899 900 // Infer the input type if necessary. 901 if (InputType == types::TY_Nothing) { 902 // If there was an explicit arg for this, claim it. 903 if (InputTypeArg) 904 InputTypeArg->claim(); 905 906 // stdin must be handled specially. 907 if (memcmp(Value, "-", 2) == 0) { 908 // If running with -E, treat as a C input (this changes the builtin 909 // macros, for example). This may be overridden by -ObjC below. 910 // 911 // Otherwise emit an error but still use a valid type to avoid 912 // spurious errors (e.g., no inputs). 913 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP) 914 Diag(clang::diag::err_drv_unknown_stdin_type); 915 Ty = types::TY_C; 916 } else { 917 // Otherwise lookup by extension. 918 // Fallback is C if invoked as C preprocessor or Object otherwise. 919 // We use a host hook here because Darwin at least has its own 920 // idea of what .s is. 921 if (const char *Ext = strrchr(Value, '.')) 922 Ty = TC.LookupTypeForExtension(Ext + 1); 923 924 if (Ty == types::TY_INVALID) { 925 if (CCCIsCPP) 926 Ty = types::TY_C; 927 else 928 Ty = types::TY_Object; 929 } 930 931 // If the driver is invoked as C++ compiler (like clang++ or c++) it 932 // should autodetect some input files as C++ for g++ compatibility. 933 if (CCCIsCXX) { 934 types::ID OldTy = Ty; 935 Ty = types::lookupCXXTypeForCType(Ty); 936 937 if (Ty != OldTy) 938 Diag(clang::diag::warn_drv_treating_input_as_cxx) 939 << getTypeName(OldTy) << getTypeName(Ty); 940 } 941 } 942 943 // -ObjC and -ObjC++ override the default language, but only for "source 944 // files". We just treat everything that isn't a linker input as a 945 // source file. 946 // 947 // FIXME: Clean this up if we move the phase sequence into the type. 948 if (Ty != types::TY_Object) { 949 if (Args.hasArg(options::OPT_ObjC)) 950 Ty = types::TY_ObjC; 951 else if (Args.hasArg(options::OPT_ObjCXX)) 952 Ty = types::TY_ObjCXX; 953 } 954 } else { 955 assert(InputTypeArg && "InputType set w/o InputTypeArg"); 956 InputTypeArg->claim(); 957 Ty = InputType; 958 } 959 960 // Check that the file exists, if enabled. 961 if (CheckInputsExist && memcmp(Value, "-", 2) != 0) { 962 SmallString<64> Path(Value); 963 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) { 964 SmallString<64> Directory(WorkDir->getValue(Args)); 965 if (llvm::sys::path::is_absolute(Directory.str())) { 966 llvm::sys::path::append(Directory, Value); 967 Path.assign(Directory); 968 } 969 } 970 971 bool exists = false; 972 if (llvm::sys::fs::exists(Path.c_str(), exists) || !exists) 973 Diag(clang::diag::err_drv_no_such_file) << Path.str(); 974 else 975 Inputs.push_back(std::make_pair(Ty, A)); 976 } else 977 Inputs.push_back(std::make_pair(Ty, A)); 978 979 } else if (A->getOption().isLinkerInput()) { 980 // Just treat as object type, we could make a special type for this if 981 // necessary. 982 Inputs.push_back(std::make_pair(types::TY_Object, A)); 983 984 } else if (A->getOption().matches(options::OPT_x)) { 985 InputTypeArg = A; 986 InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args)); 987 988 // Follow gcc behavior and treat as linker input for invalid -x 989 // options. Its not clear why we shouldn't just revert to unknown; but 990 // this isn't very important, we might as well be bug compatible. 991 if (!InputType) { 992 Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args); 993 InputType = types::TY_Object; 994 } 995 } 996 } 997 if (CCCIsCPP && Inputs.empty()) { 998 // If called as standalone preprocessor, stdin is processed 999 // if no other input is present. 1000 unsigned Index = Args.getBaseArgs().MakeIndex("-"); 1001 Arg *A = Opts->ParseOneArg(Args, Index); 1002 A->claim(); 1003 Inputs.push_back(std::make_pair(types::TY_C, A)); 1004 } 1005 } 1006 1007 void Driver::BuildActions(const ToolChain &TC, const DerivedArgList &Args, 1008 const InputList &Inputs, ActionList &Actions) const { 1009 llvm::PrettyStackTraceString CrashInfo("Building compilation actions"); 1010 1011 if (!SuppressMissingInputWarning && Inputs.empty()) { 1012 Diag(clang::diag::err_drv_no_input_files); 1013 return; 1014 } 1015 1016 Arg *FinalPhaseArg; 1017 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg); 1018 1019 // Reject -Z* at the top level, these options should never have been exposed 1020 // by gcc. 1021 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined)) 1022 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args); 1023 1024 // Construct the actions to perform. 1025 ActionList LinkerInputs; 1026 unsigned NumSteps = 0; 1027 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) { 1028 types::ID InputType = Inputs[i].first; 1029 const Arg *InputArg = Inputs[i].second; 1030 1031 NumSteps = types::getNumCompilationPhases(InputType); 1032 assert(NumSteps && "Invalid number of steps!"); 1033 1034 // If the first step comes after the final phase we are doing as part of 1035 // this compilation, warn the user about it. 1036 phases::ID InitialPhase = types::getCompilationPhase(InputType, 0); 1037 if (InitialPhase > FinalPhase) { 1038 // Claim here to avoid the more general unused warning. 1039 InputArg->claim(); 1040 1041 // Suppress all unused style warnings with -Qunused-arguments 1042 if (Args.hasArg(options::OPT_Qunused_arguments)) 1043 continue; 1044 1045 // Special case '-E' warning on a previously preprocessed file to make 1046 // more sense. 1047 if (InitialPhase == phases::Compile && FinalPhase == phases::Preprocess && 1048 getPreprocessedType(InputType) == types::TY_INVALID) 1049 Diag(clang::diag::warn_drv_preprocessed_input_file_unused) 1050 << InputArg->getAsString(Args) 1051 << FinalPhaseArg->getOption().getName(); 1052 else 1053 Diag(clang::diag::warn_drv_input_file_unused) 1054 << InputArg->getAsString(Args) 1055 << getPhaseName(InitialPhase) 1056 << FinalPhaseArg->getOption().getName(); 1057 continue; 1058 } 1059 1060 // Build the pipeline for this file. 1061 OwningPtr<Action> Current(new InputAction(*InputArg, InputType)); 1062 for (unsigned i = 0; i != NumSteps; ++i) { 1063 phases::ID Phase = types::getCompilationPhase(InputType, i); 1064 1065 // We are done if this step is past what the user requested. 1066 if (Phase > FinalPhase) 1067 break; 1068 1069 // Queue linker inputs. 1070 if (Phase == phases::Link) { 1071 assert(i + 1 == NumSteps && "linking must be final compilation step."); 1072 LinkerInputs.push_back(Current.take()); 1073 break; 1074 } 1075 1076 // Some types skip the assembler phase (e.g., llvm-bc), but we can't 1077 // encode this in the steps because the intermediate type depends on 1078 // arguments. Just special case here. 1079 if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm) 1080 continue; 1081 1082 // Otherwise construct the appropriate action. 1083 Current.reset(ConstructPhaseAction(Args, Phase, Current.take())); 1084 if (Current->getType() == types::TY_Nothing) 1085 break; 1086 } 1087 1088 // If we ended with something, add to the output list. 1089 if (Current) 1090 Actions.push_back(Current.take()); 1091 } 1092 1093 // Add a link action if necessary. 1094 if (!LinkerInputs.empty()) 1095 Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image)); 1096 1097 // If we are linking, claim any options which are obviously only used for 1098 // compilation. 1099 if (FinalPhase == phases::Link && (NumSteps == 1)) 1100 Args.ClaimAllArgs(options::OPT_CompileOnly_Group); 1101 } 1102 1103 Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase, 1104 Action *Input) const { 1105 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions"); 1106 // Build the appropriate action. 1107 switch (Phase) { 1108 case phases::Link: llvm_unreachable("link action invalid here."); 1109 case phases::Preprocess: { 1110 types::ID OutputTy; 1111 // -{M, MM} alter the output type. 1112 if (Args.hasArg(options::OPT_M, options::OPT_MM)) { 1113 OutputTy = types::TY_Dependencies; 1114 } else { 1115 OutputTy = types::getPreprocessedType(Input->getType()); 1116 assert(OutputTy != types::TY_INVALID && 1117 "Cannot preprocess this input type!"); 1118 } 1119 return new PreprocessJobAction(Input, OutputTy); 1120 } 1121 case phases::Precompile: 1122 return new PrecompileJobAction(Input, types::TY_PCH); 1123 case phases::Compile: { 1124 if (Args.hasArg(options::OPT_fsyntax_only)) { 1125 return new CompileJobAction(Input, types::TY_Nothing); 1126 } else if (Args.hasArg(options::OPT_rewrite_objc)) { 1127 return new CompileJobAction(Input, types::TY_RewrittenObjC); 1128 } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) { 1129 return new AnalyzeJobAction(Input, types::TY_Plist); 1130 } else if (Args.hasArg(options::OPT_emit_ast)) { 1131 return new CompileJobAction(Input, types::TY_AST); 1132 } else if (IsUsingLTO(Args)) { 1133 types::ID Output = 1134 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC; 1135 return new CompileJobAction(Input, Output); 1136 } else { 1137 return new CompileJobAction(Input, types::TY_PP_Asm); 1138 } 1139 } 1140 case phases::Assemble: 1141 return new AssembleJobAction(Input, types::TY_Object); 1142 } 1143 1144 llvm_unreachable("invalid phase in ConstructPhaseAction"); 1145 } 1146 1147 bool Driver::IsUsingLTO(const ArgList &Args) const { 1148 // Check for -emit-llvm or -flto. 1149 if (Args.hasArg(options::OPT_emit_llvm) || 1150 Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false)) 1151 return true; 1152 1153 // Check for -O4. 1154 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) 1155 return A->getOption().matches(options::OPT_O4); 1156 1157 return false; 1158 } 1159 1160 void Driver::BuildJobs(Compilation &C) const { 1161 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 1162 1163 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 1164 1165 // It is an error to provide a -o option if we are making multiple output 1166 // files. 1167 if (FinalOutput) { 1168 unsigned NumOutputs = 0; 1169 for (ActionList::const_iterator it = C.getActions().begin(), 1170 ie = C.getActions().end(); it != ie; ++it) 1171 if ((*it)->getType() != types::TY_Nothing) 1172 ++NumOutputs; 1173 1174 if (NumOutputs > 1) { 1175 Diag(clang::diag::err_drv_output_argument_with_multiple_files); 1176 FinalOutput = 0; 1177 } 1178 } 1179 1180 for (ActionList::const_iterator it = C.getActions().begin(), 1181 ie = C.getActions().end(); it != ie; ++it) { 1182 Action *A = *it; 1183 1184 // If we are linking an image for multiple archs then the linker wants 1185 // -arch_multiple and -final_output <final image name>. Unfortunately, this 1186 // doesn't fit in cleanly because we have to pass this information down. 1187 // 1188 // FIXME: This is a hack; find a cleaner way to integrate this into the 1189 // process. 1190 const char *LinkingOutput = 0; 1191 if (isa<LipoJobAction>(A)) { 1192 if (FinalOutput) 1193 LinkingOutput = FinalOutput->getValue(C.getArgs()); 1194 else 1195 LinkingOutput = DefaultImageName.c_str(); 1196 } 1197 1198 InputInfo II; 1199 BuildJobsForAction(C, A, &C.getDefaultToolChain(), 1200 /*BoundArch*/0, 1201 /*AtTopLevel*/ true, 1202 /*LinkingOutput*/ LinkingOutput, 1203 II); 1204 } 1205 1206 // If the user passed -Qunused-arguments or there were errors, don't warn 1207 // about any unused arguments. 1208 if (Diags.hasErrorOccurred() || 1209 C.getArgs().hasArg(options::OPT_Qunused_arguments)) 1210 return; 1211 1212 // Claim -### here. 1213 (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH); 1214 1215 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end(); 1216 it != ie; ++it) { 1217 Arg *A = *it; 1218 1219 // FIXME: It would be nice to be able to send the argument to the 1220 // DiagnosticsEngine, so that extra values, position, and so on could be 1221 // printed. 1222 if (!A->isClaimed()) { 1223 if (A->getOption().hasNoArgumentUnused()) 1224 continue; 1225 1226 // Suppress the warning automatically if this is just a flag, and it is an 1227 // instance of an argument we already claimed. 1228 const Option &Opt = A->getOption(); 1229 if (isa<FlagOption>(Opt)) { 1230 bool DuplicateClaimed = false; 1231 1232 for (arg_iterator it = C.getArgs().filtered_begin(&Opt), 1233 ie = C.getArgs().filtered_end(); it != ie; ++it) { 1234 if ((*it)->isClaimed()) { 1235 DuplicateClaimed = true; 1236 break; 1237 } 1238 } 1239 1240 if (DuplicateClaimed) 1241 continue; 1242 } 1243 1244 Diag(clang::diag::warn_drv_unused_argument) 1245 << A->getAsString(C.getArgs()); 1246 } 1247 } 1248 } 1249 1250 static const Tool &SelectToolForJob(Compilation &C, const ToolChain *TC, 1251 const JobAction *JA, 1252 const ActionList *&Inputs) { 1253 const Tool *ToolForJob = 0; 1254 1255 // See if we should look for a compiler with an integrated assembler. We match 1256 // bottom up, so what we are actually looking for is an assembler job with a 1257 // compiler input. 1258 1259 if (C.getArgs().hasFlag(options::OPT_integrated_as, 1260 options::OPT_no_integrated_as, 1261 TC->IsIntegratedAssemblerDefault()) && 1262 !C.getArgs().hasArg(options::OPT_save_temps) && 1263 isa<AssembleJobAction>(JA) && 1264 Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) { 1265 const Tool &Compiler = TC->SelectTool( 1266 C, cast<JobAction>(**Inputs->begin()), (*Inputs)[0]->getInputs()); 1267 if (Compiler.hasIntegratedAssembler()) { 1268 Inputs = &(*Inputs)[0]->getInputs(); 1269 ToolForJob = &Compiler; 1270 } 1271 } 1272 1273 // Otherwise use the tool for the current job. 1274 if (!ToolForJob) 1275 ToolForJob = &TC->SelectTool(C, *JA, *Inputs); 1276 1277 // See if we should use an integrated preprocessor. We do so when we have 1278 // exactly one input, since this is the only use case we care about 1279 // (irrelevant since we don't support combine yet). 1280 if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) && 1281 !C.getArgs().hasArg(options::OPT_no_integrated_cpp) && 1282 !C.getArgs().hasArg(options::OPT_traditional_cpp) && 1283 !C.getArgs().hasArg(options::OPT_save_temps) && 1284 ToolForJob->hasIntegratedCPP()) 1285 Inputs = &(*Inputs)[0]->getInputs(); 1286 1287 return *ToolForJob; 1288 } 1289 1290 void Driver::BuildJobsForAction(Compilation &C, 1291 const Action *A, 1292 const ToolChain *TC, 1293 const char *BoundArch, 1294 bool AtTopLevel, 1295 const char *LinkingOutput, 1296 InputInfo &Result) const { 1297 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 1298 1299 if (const InputAction *IA = dyn_cast<InputAction>(A)) { 1300 // FIXME: It would be nice to not claim this here; maybe the old scheme of 1301 // just using Args was better? 1302 const Arg &Input = IA->getInputArg(); 1303 Input.claim(); 1304 if (Input.getOption().matches(options::OPT_INPUT)) { 1305 const char *Name = Input.getValue(C.getArgs()); 1306 Result = InputInfo(Name, A->getType(), Name); 1307 } else 1308 Result = InputInfo(&Input, A->getType(), ""); 1309 return; 1310 } 1311 1312 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) { 1313 const ToolChain *TC = &C.getDefaultToolChain(); 1314 1315 if (BAA->getArchName()) 1316 TC = &getToolChain(C.getArgs(), BAA->getArchName()); 1317 1318 BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(), 1319 AtTopLevel, LinkingOutput, Result); 1320 return; 1321 } 1322 1323 const ActionList *Inputs = &A->getInputs(); 1324 1325 const JobAction *JA = cast<JobAction>(A); 1326 const Tool &T = SelectToolForJob(C, TC, JA, Inputs); 1327 1328 // Only use pipes when there is exactly one input. 1329 InputInfoList InputInfos; 1330 for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end(); 1331 it != ie; ++it) { 1332 // Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get 1333 // temporary output names. 1334 // 1335 // FIXME: Clean this up. 1336 bool SubJobAtTopLevel = false; 1337 if (AtTopLevel && isa<DsymutilJobAction>(A)) 1338 SubJobAtTopLevel = true; 1339 1340 // Also treat verify sub-jobs as being at the top-level. They don't 1341 // produce any output and so don't need temporary output names. 1342 if (AtTopLevel && isa<VerifyJobAction>(A)) 1343 SubJobAtTopLevel = true; 1344 1345 InputInfo II; 1346 BuildJobsForAction(C, *it, TC, BoundArch, 1347 SubJobAtTopLevel, LinkingOutput, II); 1348 InputInfos.push_back(II); 1349 } 1350 1351 // Always use the first input as the base input. 1352 const char *BaseInput = InputInfos[0].getBaseInput(); 1353 1354 // ... except dsymutil actions, which use their actual input as the base 1355 // input. 1356 if (JA->getType() == types::TY_dSYM) 1357 BaseInput = InputInfos[0].getFilename(); 1358 1359 // Determine the place to write output to, if any. 1360 if (JA->getType() == types::TY_Nothing) { 1361 Result = InputInfo(A->getType(), BaseInput); 1362 } else { 1363 Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel), 1364 A->getType(), BaseInput); 1365 } 1366 1367 if (CCCPrintBindings && !CCGenDiagnostics) { 1368 llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"' 1369 << " - \"" << T.getName() << "\", inputs: ["; 1370 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) { 1371 llvm::errs() << InputInfos[i].getAsString(); 1372 if (i + 1 != e) 1373 llvm::errs() << ", "; 1374 } 1375 llvm::errs() << "], output: " << Result.getAsString() << "\n"; 1376 } else { 1377 T.ConstructJob(C, *JA, Result, InputInfos, 1378 C.getArgsForToolChain(TC, BoundArch), LinkingOutput); 1379 } 1380 } 1381 1382 const char *Driver::GetNamedOutputPath(Compilation &C, 1383 const JobAction &JA, 1384 const char *BaseInput, 1385 bool AtTopLevel) const { 1386 llvm::PrettyStackTraceString CrashInfo("Computing output path"); 1387 // Output to a user requested destination? 1388 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && 1389 !isa<VerifyJobAction>(JA)) { 1390 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) 1391 return C.addResultFile(FinalOutput->getValue(C.getArgs())); 1392 } 1393 1394 // Default to writing to stdout? 1395 if (AtTopLevel && isa<PreprocessJobAction>(JA) && !CCGenDiagnostics) 1396 return "-"; 1397 1398 // Output to a temporary file? 1399 if ((!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) || 1400 CCGenDiagnostics) { 1401 StringRef Name = llvm::sys::path::filename(BaseInput); 1402 std::pair<StringRef, StringRef> Split = Name.split('.'); 1403 std::string TmpName = 1404 GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType())); 1405 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); 1406 } 1407 1408 SmallString<128> BasePath(BaseInput); 1409 StringRef BaseName; 1410 1411 // Dsymutil actions should use the full path. 1412 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA)) 1413 BaseName = BasePath; 1414 else 1415 BaseName = llvm::sys::path::filename(BasePath); 1416 1417 // Determine what the derived output name should be. 1418 const char *NamedOutput; 1419 if (JA.getType() == types::TY_Image) { 1420 NamedOutput = DefaultImageName.c_str(); 1421 } else { 1422 const char *Suffix = types::getTypeTempSuffix(JA.getType()); 1423 assert(Suffix && "All types used for output should have a suffix."); 1424 1425 std::string::size_type End = std::string::npos; 1426 if (!types::appendSuffixForType(JA.getType())) 1427 End = BaseName.rfind('.'); 1428 std::string Suffixed(BaseName.substr(0, End)); 1429 Suffixed += '.'; 1430 Suffixed += Suffix; 1431 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str()); 1432 } 1433 1434 // If we're saving temps and the temp filename conflicts with the input 1435 // filename, then avoid overwriting input file. 1436 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_save_temps) && 1437 NamedOutput == BaseName) { 1438 StringRef Name = llvm::sys::path::filename(BaseInput); 1439 std::pair<StringRef, StringRef> Split = Name.split('.'); 1440 std::string TmpName = 1441 GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType())); 1442 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); 1443 } 1444 1445 // As an annoying special case, PCH generation doesn't strip the pathname. 1446 if (JA.getType() == types::TY_PCH) { 1447 llvm::sys::path::remove_filename(BasePath); 1448 if (BasePath.empty()) 1449 BasePath = NamedOutput; 1450 else 1451 llvm::sys::path::append(BasePath, NamedOutput); 1452 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str())); 1453 } else { 1454 return C.addResultFile(NamedOutput); 1455 } 1456 } 1457 1458 std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const { 1459 // Respect a limited subset of the '-Bprefix' functionality in GCC by 1460 // attempting to use this prefix when lokup up program paths. 1461 for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(), 1462 ie = PrefixDirs.end(); it != ie; ++it) { 1463 std::string Dir(*it); 1464 if (Dir.empty()) 1465 continue; 1466 if (Dir[0] == '=') 1467 Dir = SysRoot + Dir.substr(1); 1468 llvm::sys::Path P(Dir); 1469 P.appendComponent(Name); 1470 bool Exists; 1471 if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) 1472 return P.str(); 1473 } 1474 1475 llvm::sys::Path P(ResourceDir); 1476 P.appendComponent(Name); 1477 bool Exists; 1478 if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) 1479 return P.str(); 1480 1481 const ToolChain::path_list &List = TC.getFilePaths(); 1482 for (ToolChain::path_list::const_iterator 1483 it = List.begin(), ie = List.end(); it != ie; ++it) { 1484 std::string Dir(*it); 1485 if (Dir.empty()) 1486 continue; 1487 if (Dir[0] == '=') 1488 Dir = SysRoot + Dir.substr(1); 1489 llvm::sys::Path P(Dir); 1490 P.appendComponent(Name); 1491 bool Exists; 1492 if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) 1493 return P.str(); 1494 } 1495 1496 return Name; 1497 } 1498 1499 static bool isPathExecutable(llvm::sys::Path &P, bool WantFile) { 1500 bool Exists; 1501 return (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists 1502 : P.canExecute()); 1503 } 1504 1505 std::string Driver::GetProgramPath(const char *Name, const ToolChain &TC, 1506 bool WantFile) const { 1507 std::string TargetSpecificExecutable(DefaultTargetTriple + "-" + Name); 1508 // Respect a limited subset of the '-Bprefix' functionality in GCC by 1509 // attempting to use this prefix when lokup up program paths. 1510 for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(), 1511 ie = PrefixDirs.end(); it != ie; ++it) { 1512 llvm::sys::Path P(*it); 1513 P.appendComponent(TargetSpecificExecutable); 1514 if (isPathExecutable(P, WantFile)) return P.str(); 1515 P.eraseComponent(); 1516 P.appendComponent(Name); 1517 if (isPathExecutable(P, WantFile)) return P.str(); 1518 } 1519 1520 const ToolChain::path_list &List = TC.getProgramPaths(); 1521 for (ToolChain::path_list::const_iterator 1522 it = List.begin(), ie = List.end(); it != ie; ++it) { 1523 llvm::sys::Path P(*it); 1524 P.appendComponent(TargetSpecificExecutable); 1525 if (isPathExecutable(P, WantFile)) return P.str(); 1526 P.eraseComponent(); 1527 P.appendComponent(Name); 1528 if (isPathExecutable(P, WantFile)) return P.str(); 1529 } 1530 1531 // If all else failed, search the path. 1532 llvm::sys::Path 1533 P(llvm::sys::Program::FindProgramByName(TargetSpecificExecutable)); 1534 if (!P.empty()) 1535 return P.str(); 1536 1537 P = llvm::sys::Path(llvm::sys::Program::FindProgramByName(Name)); 1538 if (!P.empty()) 1539 return P.str(); 1540 1541 return Name; 1542 } 1543 1544 std::string Driver::GetTemporaryPath(StringRef Prefix, const char *Suffix) 1545 const { 1546 // FIXME: This is lame; sys::Path should provide this function (in particular, 1547 // it should know how to find the temporary files dir). 1548 std::string Error; 1549 const char *TmpDir = ::getenv("TMPDIR"); 1550 if (!TmpDir) 1551 TmpDir = ::getenv("TEMP"); 1552 if (!TmpDir) 1553 TmpDir = ::getenv("TMP"); 1554 if (!TmpDir) 1555 TmpDir = "/tmp"; 1556 llvm::sys::Path P(TmpDir); 1557 P.appendComponent(Prefix); 1558 if (P.makeUnique(false, &Error)) { 1559 Diag(clang::diag::err_drv_unable_to_make_temp) << Error; 1560 return ""; 1561 } 1562 1563 // FIXME: Grumble, makeUnique sometimes leaves the file around!? PR3837. 1564 P.eraseFromDisk(false, 0); 1565 1566 P.appendSuffix(Suffix); 1567 return P.str(); 1568 } 1569 1570 /// \brief Compute target triple from args. 1571 /// 1572 /// This routine provides the logic to compute a target triple from various 1573 /// args passed to the driver and the default triple string. 1574 static llvm::Triple computeTargetTriple(StringRef DefaultTargetTriple, 1575 const ArgList &Args, 1576 StringRef DarwinArchName) { 1577 if (const Arg *A = Args.getLastArg(options::OPT_target)) 1578 DefaultTargetTriple = A->getValue(Args); 1579 1580 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple)); 1581 1582 // Handle Darwin-specific options available here. 1583 if (Target.isOSDarwin()) { 1584 // If an explict Darwin arch name is given, that trumps all. 1585 if (!DarwinArchName.empty()) { 1586 Target.setArch( 1587 llvm::Triple::getArchTypeForDarwinArchName(DarwinArchName)); 1588 return Target; 1589 } 1590 1591 // Handle the Darwin '-arch' flag. 1592 if (Arg *A = Args.getLastArg(options::OPT_arch)) { 1593 llvm::Triple::ArchType DarwinArch 1594 = llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args)); 1595 if (DarwinArch != llvm::Triple::UnknownArch) 1596 Target.setArch(DarwinArch); 1597 } 1598 } 1599 1600 // Skip further flag support on OSes which don't support '-m32' or '-m64'. 1601 if (Target.getArchName() == "tce" || 1602 Target.getOS() == llvm::Triple::AuroraUX || 1603 Target.getOS() == llvm::Triple::Minix) 1604 return Target; 1605 1606 // Handle pseudo-target flags '-m32' and '-m64'. 1607 // FIXME: Should this information be in llvm::Triple? 1608 if (Arg *A = Args.getLastArg(options::OPT_m32, options::OPT_m64)) { 1609 if (A->getOption().matches(options::OPT_m32)) { 1610 if (Target.getArch() == llvm::Triple::x86_64) 1611 Target.setArch(llvm::Triple::x86); 1612 if (Target.getArch() == llvm::Triple::ppc64) 1613 Target.setArch(llvm::Triple::ppc); 1614 } else { 1615 if (Target.getArch() == llvm::Triple::x86) 1616 Target.setArch(llvm::Triple::x86_64); 1617 if (Target.getArch() == llvm::Triple::ppc) 1618 Target.setArch(llvm::Triple::ppc64); 1619 } 1620 } 1621 1622 return Target; 1623 } 1624 1625 const ToolChain &Driver::getToolChain(const ArgList &Args, 1626 StringRef DarwinArchName) const { 1627 llvm::Triple Target = computeTargetTriple(DefaultTargetTriple, Args, 1628 DarwinArchName); 1629 1630 ToolChain *&TC = ToolChains[Target.str()]; 1631 if (!TC) { 1632 switch (Target.getOS()) { 1633 case llvm::Triple::AuroraUX: 1634 TC = new toolchains::AuroraUX(*this, Target, Args); 1635 break; 1636 case llvm::Triple::Darwin: 1637 case llvm::Triple::MacOSX: 1638 case llvm::Triple::IOS: 1639 if (Target.getArch() == llvm::Triple::x86 || 1640 Target.getArch() == llvm::Triple::x86_64 || 1641 Target.getArch() == llvm::Triple::arm || 1642 Target.getArch() == llvm::Triple::thumb) 1643 TC = new toolchains::DarwinClang(*this, Target); 1644 else 1645 TC = new toolchains::Darwin_Generic_GCC(*this, Target, Args); 1646 break; 1647 case llvm::Triple::DragonFly: 1648 TC = new toolchains::DragonFly(*this, Target, Args); 1649 break; 1650 case llvm::Triple::OpenBSD: 1651 TC = new toolchains::OpenBSD(*this, Target, Args); 1652 break; 1653 case llvm::Triple::NetBSD: 1654 TC = new toolchains::NetBSD(*this, Target, Args); 1655 break; 1656 case llvm::Triple::FreeBSD: 1657 TC = new toolchains::FreeBSD(*this, Target, Args); 1658 break; 1659 case llvm::Triple::Minix: 1660 TC = new toolchains::Minix(*this, Target, Args); 1661 break; 1662 case llvm::Triple::Linux: 1663 if (Target.getArch() == llvm::Triple::hexagon) 1664 TC = new toolchains::Hexagon_TC(*this, Target); 1665 else 1666 TC = new toolchains::Linux(*this, Target, Args); 1667 break; 1668 case llvm::Triple::Solaris: 1669 TC = new toolchains::Solaris(*this, Target, Args); 1670 break; 1671 case llvm::Triple::Win32: 1672 TC = new toolchains::Windows(*this, Target); 1673 break; 1674 case llvm::Triple::MinGW32: 1675 // FIXME: We need a MinGW toolchain. Fallthrough for now. 1676 default: 1677 // TCE is an OSless target 1678 if (Target.getArchName() == "tce") { 1679 TC = new toolchains::TCEToolChain(*this, Target); 1680 break; 1681 } 1682 1683 TC = new toolchains::Generic_GCC(*this, Target, Args); 1684 break; 1685 } 1686 } 1687 return *TC; 1688 } 1689 1690 bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA, 1691 const llvm::Triple &Triple) const { 1692 // Check if user requested no clang, or clang doesn't understand this type (we 1693 // only handle single inputs for now). 1694 if (!CCCUseClang || JA.size() != 1 || 1695 !types::isAcceptedByClang((*JA.begin())->getType())) 1696 return false; 1697 1698 // Otherwise make sure this is an action clang understands. 1699 if (isa<PreprocessJobAction>(JA)) { 1700 if (!CCCUseClangCPP) { 1701 Diag(clang::diag::warn_drv_not_using_clang_cpp); 1702 return false; 1703 } 1704 } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA)) 1705 return false; 1706 1707 // Use clang for C++? 1708 if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) { 1709 Diag(clang::diag::warn_drv_not_using_clang_cxx); 1710 return false; 1711 } 1712 1713 // Always use clang for precompiling, AST generation, and rewriting, 1714 // regardless of archs. 1715 if (isa<PrecompileJobAction>(JA) || 1716 types::isOnlyAcceptedByClang(JA.getType())) 1717 return true; 1718 1719 // Finally, don't use clang if this isn't one of the user specified archs to 1720 // build. 1721 if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) { 1722 Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName(); 1723 return false; 1724 } 1725 1726 return true; 1727 } 1728 1729 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the 1730 /// grouped values as integers. Numbers which are not provided are set to 0. 1731 /// 1732 /// \return True if the entire string was parsed (9.2), or all groups were 1733 /// parsed (10.3.5extrastuff). 1734 bool Driver::GetReleaseVersion(const char *Str, unsigned &Major, 1735 unsigned &Minor, unsigned &Micro, 1736 bool &HadExtra) { 1737 HadExtra = false; 1738 1739 Major = Minor = Micro = 0; 1740 if (*Str == '\0') 1741 return true; 1742 1743 char *End; 1744 Major = (unsigned) strtol(Str, &End, 10); 1745 if (*Str != '\0' && *End == '\0') 1746 return true; 1747 if (*End != '.') 1748 return false; 1749 1750 Str = End+1; 1751 Minor = (unsigned) strtol(Str, &End, 10); 1752 if (*Str != '\0' && *End == '\0') 1753 return true; 1754 if (*End != '.') 1755 return false; 1756 1757 Str = End+1; 1758 Micro = (unsigned) strtol(Str, &End, 10); 1759 if (*Str != '\0' && *End == '\0') 1760 return true; 1761 if (Str == End) 1762 return false; 1763 HadExtra = true; 1764 return true; 1765 } 1766