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