Driver.cpp revision e33bea4ef34598e7a4a6a3a117392268998552d4
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/HostInfo.h" 18#include "clang/Driver/Job.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#include "clang/Driver/Types.h" 24 25#include "llvm/ADT/StringSet.h" 26#include "llvm/Support/PrettyStackTrace.h" 27#include "llvm/Support/raw_ostream.h" 28#include "llvm/System/Path.h" 29#include "llvm/System/Program.h" 30 31#include "InputInfo.h" 32 33#include <map> 34 35using namespace clang::driver; 36 37Driver::Driver(const char *_Name, const char *_Dir, 38 const char *_DefaultHostTriple, 39 const char *_DefaultImageName, 40 Diagnostic &_Diags) 41 : Opts(new OptTable()), Diags(_Diags), 42 Name(_Name), Dir(_Dir), DefaultHostTriple(_DefaultHostTriple), 43 DefaultImageName(_DefaultImageName), 44 Host(0), 45 CCCIsCXX(false), CCCEcho(false), CCCPrintBindings(false), 46 CCCNoClang(false), CCCNoClangCXX(false), CCCNoClangCPP(false), 47 SuppressMissingInputWarning(false) 48{ 49} 50 51Driver::~Driver() { 52 delete Opts; 53 delete Host; 54} 55 56ArgList *Driver::ParseArgStrings(const char **ArgBegin, const char **ArgEnd) { 57 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing"); 58 ArgList *Args = new ArgList(ArgBegin, ArgEnd); 59 60 // FIXME: Handle '@' args (or at least error on them). 61 62 unsigned Index = 0, End = ArgEnd - ArgBegin; 63 while (Index < End) { 64 // gcc's handling of empty arguments doesn't make 65 // sense, but this is not a common use case. :) 66 // 67 // We just ignore them here (note that other things may 68 // still take them as arguments). 69 if (Args->getArgString(Index)[0] == '\0') { 70 ++Index; 71 continue; 72 } 73 74 unsigned Prev = Index; 75 Arg *A = getOpts().ParseOneArg(*Args, Index, End); 76 if (A) { 77 if (A->getOption().isUnsupported()) { 78 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args); 79 continue; 80 } 81 82 Args->append(A); 83 } 84 85 assert(Index > Prev && "Parser failed to consume argument."); 86 (void) Prev; 87 } 88 89 return Args; 90} 91 92Compilation *Driver::BuildCompilation(int argc, const char **argv) { 93 llvm::PrettyStackTraceString CrashInfo("Compilation construction"); 94 95 // FIXME: Handle environment options which effect driver behavior, 96 // somewhere (client?). GCC_EXEC_PREFIX, COMPILER_PATH, 97 // LIBRARY_PATH, LPATH, CC_PRINT_OPTIONS, QA_OVERRIDE_GCC3_OPTIONS. 98 99 // FIXME: What are we going to do with -V and -b? 100 101 // FIXME: Handle CCC_ADD_ARGS. 102 103 // FIXME: This stuff needs to go into the Compilation, not the 104 // driver. 105 bool CCCPrintOptions = false, CCCPrintActions = false; 106 107 const char **Start = argv + 1, **End = argv + argc; 108 const char *HostTriple = DefaultHostTriple.c_str(); 109 110 // Read -ccc args. 111 // 112 // FIXME: We need to figure out where this behavior should 113 // live. Most of it should be outside in the client; the parts that 114 // aren't should have proper options, either by introducing new ones 115 // or by overloading gcc ones like -V or -b. 116 for (; Start != End && memcmp(*Start, "-ccc-", 5) == 0; ++Start) { 117 const char *Opt = *Start + 5; 118 119 if (!strcmp(Opt, "print-options")) { 120 CCCPrintOptions = true; 121 } else if (!strcmp(Opt, "print-phases")) { 122 CCCPrintActions = true; 123 } else if (!strcmp(Opt, "print-bindings")) { 124 CCCPrintBindings = true; 125 } else if (!strcmp(Opt, "cxx")) { 126 CCCIsCXX = true; 127 } else if (!strcmp(Opt, "echo")) { 128 CCCEcho = true; 129 130 } else if (!strcmp(Opt, "no-clang")) { 131 CCCNoClang = true; 132 } else if (!strcmp(Opt, "no-clang-cxx")) { 133 CCCNoClangCXX = true; 134 } else if (!strcmp(Opt, "no-clang-cpp")) { 135 CCCNoClangCPP = true; 136 } else if (!strcmp(Opt, "clang-archs")) { 137 assert(Start+1 < End && "FIXME: -ccc- argument handling."); 138 const char *Cur = *++Start; 139 140 for (;;) { 141 const char *Next = strchr(Cur, ','); 142 143 if (Next) { 144 CCCClangArchs.insert(std::string(Cur, Next)); 145 Cur = Next + 1; 146 } else { 147 CCCClangArchs.insert(std::string(Cur)); 148 break; 149 } 150 } 151 152 } else if (!strcmp(Opt, "host-triple")) { 153 assert(Start+1 < End && "FIXME: -ccc- argument handling."); 154 HostTriple = *++Start; 155 156 } else { 157 // FIXME: Error handling. 158 llvm::errs() << "invalid option: " << *Start << "\n"; 159 exit(1); 160 } 161 } 162 163 ArgList *Args = ParseArgStrings(Start, End); 164 165 Host = GetHostInfo(HostTriple); 166 167 // The compilation takes ownership of Args. 168 Compilation *C = new Compilation(*this, *Host->getToolChain(*Args), Args); 169 170 // FIXME: This behavior shouldn't be here. 171 if (CCCPrintOptions) { 172 PrintOptions(C->getArgs()); 173 return C; 174 } 175 176 if (!HandleImmediateArgs(*C)) 177 return C; 178 179 // Construct the list of abstract actions to perform for this 180 // compilation. We avoid passing a Compilation here simply to 181 // enforce the abstraction that pipelining is not host or toolchain 182 // dependent (other than the driver driver test). 183 if (Host->useDriverDriver()) 184 BuildUniversalActions(C->getArgs(), C->getActions()); 185 else 186 BuildActions(C->getArgs(), C->getActions()); 187 188 if (CCCPrintActions) { 189 PrintActions(*C); 190 return C; 191 } 192 193 BuildJobs(*C); 194 195 return C; 196} 197 198void Driver::PrintOptions(const ArgList &Args) const { 199 unsigned i = 0; 200 for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); 201 it != ie; ++it, ++i) { 202 Arg *A = *it; 203 llvm::errs() << "Option " << i << " - " 204 << "Name: \"" << A->getOption().getName() << "\", " 205 << "Values: {"; 206 for (unsigned j = 0; j < A->getNumValues(); ++j) { 207 if (j) 208 llvm::errs() << ", "; 209 llvm::errs() << '"' << A->getValue(Args, j) << '"'; 210 } 211 llvm::errs() << "}\n"; 212 } 213} 214 215void Driver::PrintVersion() const { 216 static char buf[] = "$URL$"; 217 char *zap = strstr(buf, "/lib/Driver"); 218 if (zap) 219 *zap = 0; 220 zap = strstr(buf, "/clang/tools/clang"); 221 if (zap) 222 *zap = 0; 223 const char *vers = buf+6; 224 // FIXME: Add cmake support and remove #ifdef 225#ifdef SVN_REVISION 226 const char *revision = SVN_REVISION; 227#else 228 const char *revision = ""; 229#endif 230 // FIXME: The following handlers should use a callback mechanism, we 231 // don't know what the client would like to do. 232 llvm::errs() << "clang version 1.0 (" << vers << " " << revision << ")" << "\n"; 233 // FIXME: Add cmake support and remove #ifdef 234#ifdef TARGET_TRIPLE 235 llvm::errs() << "Target: " << TARGET_TRIPLE << "\n"; 236#endif 237} 238 239bool Driver::HandleImmediateArgs(const Compilation &C) { 240 // The order these options are handled in in gcc is all over the 241 // place, but we don't expect inconsistencies w.r.t. that to matter 242 // in practice. 243 if (C.getArgs().hasArg(options::OPT_v) || 244 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 245 PrintVersion(); 246 SuppressMissingInputWarning = true; 247 } 248 249 const ToolChain &TC = C.getDefaultToolChain(); 250 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) { 251 llvm::outs() << "programs: ="; 252 for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(), 253 ie = TC.getProgramPaths().end(); it != ie; ++it) { 254 if (it != TC.getProgramPaths().begin()) 255 llvm::outs() << ':'; 256 llvm::outs() << *it; 257 } 258 llvm::outs() << "\n"; 259 llvm::outs() << "libraries: ="; 260 for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(), 261 ie = TC.getFilePaths().end(); it != ie; ++it) { 262 if (it != TC.getFilePaths().begin()) 263 llvm::outs() << ':'; 264 llvm::outs() << *it; 265 } 266 llvm::outs() << "\n"; 267 } 268 269 // FIXME: The following handlers should use a callback mechanism, we 270 // don't know what the client would like to do. 271 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) { 272 llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC).toString() 273 << "\n"; 274 return false; 275 } 276 277 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) { 278 llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC).toString() 279 << "\n"; 280 return false; 281 } 282 283 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) { 284 llvm::outs() << GetProgramPath("libgcc.a", TC).toString() << "\n"; 285 return false; 286 } 287 288 return true; 289} 290 291static unsigned PrintActions1(const Compilation &C, 292 Action *A, 293 std::map<Action*, unsigned> &Ids) { 294 if (Ids.count(A)) 295 return Ids[A]; 296 297 std::string str; 298 llvm::raw_string_ostream os(str); 299 300 os << Action::getClassName(A->getKind()) << ", "; 301 if (InputAction *IA = dyn_cast<InputAction>(A)) { 302 os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\""; 303 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) { 304 os << '"' << (BIA->getArchName() ? BIA->getArchName() : 305 C.getDefaultToolChain().getArchName()) << '"' 306 << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}"; 307 } else { 308 os << "{"; 309 for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) { 310 os << PrintActions1(C, *it, Ids); 311 ++it; 312 if (it != ie) 313 os << ", "; 314 } 315 os << "}"; 316 } 317 318 unsigned Id = Ids.size(); 319 Ids[A] = Id; 320 llvm::errs() << Id << ": " << os.str() << ", " 321 << types::getTypeName(A->getType()) << "\n"; 322 323 return Id; 324} 325 326void Driver::PrintActions(const Compilation &C) const { 327 std::map<Action*, unsigned> Ids; 328 for (ActionList::const_iterator it = C.getActions().begin(), 329 ie = C.getActions().end(); it != ie; ++it) 330 PrintActions1(C, *it, Ids); 331} 332 333void Driver::BuildUniversalActions(const ArgList &Args, 334 ActionList &Actions) const { 335 llvm::PrettyStackTraceString CrashInfo("Building actions for universal build"); 336 // Collect the list of architectures. Duplicates are allowed, but 337 // should only be handled once (in the order seen). 338 llvm::StringSet<> ArchNames; 339 llvm::SmallVector<const char *, 4> Archs; 340 for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); 341 it != ie; ++it) { 342 Arg *A = *it; 343 344 if (A->getOption().getId() == options::OPT_arch) { 345 const char *Name = A->getValue(Args); 346 347 // FIXME: We need to handle canonicalization of the specified 348 // arch? 349 350 A->claim(); 351 if (ArchNames.insert(Name)) 352 Archs.push_back(Name); 353 } 354 } 355 356 // When there is no explicit arch for this platform, make sure we 357 // still bind the architecture (to the default) so that -Xarch_ is 358 // handled correctly. 359 if (!Archs.size()) 360 Archs.push_back(0); 361 362 // FIXME: We killed off some others but these aren't yet detected in 363 // a functional manner. If we added information to jobs about which 364 // "auxiliary" files they wrote then we could detect the conflict 365 // these cause downstream. 366 if (Archs.size() > 1) { 367 // No recovery needed, the point of this is just to prevent 368 // overwriting the same files. 369 if (const Arg *A = Args.getLastArg(options::OPT_M_Group)) 370 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs) 371 << A->getAsString(Args); 372 if (const Arg *A = Args.getLastArg(options::OPT_save_temps)) 373 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs) 374 << A->getAsString(Args); 375 } 376 377 ActionList SingleActions; 378 BuildActions(Args, SingleActions); 379 380 // Add in arch binding and lipo (if necessary) for every top level 381 // action. 382 for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) { 383 Action *Act = SingleActions[i]; 384 385 // Make sure we can lipo this kind of output. If not (and it is an 386 // actual output) then we disallow, since we can't create an 387 // output file with the right name without overwriting it. We 388 // could remove this oddity by just changing the output names to 389 // include the arch, which would also fix 390 // -save-temps. Compatibility wins for now. 391 392 if (Archs.size() > 1 && !types::canLipoType(Act->getType())) 393 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs) 394 << types::getTypeName(Act->getType()); 395 396 ActionList Inputs; 397 for (unsigned i = 0, e = Archs.size(); i != e; ++i) 398 Inputs.push_back(new BindArchAction(Act, Archs[i])); 399 400 // Lipo if necessary, We do it this way because we need to set the 401 // arch flag so that -Xarch_ gets overwritten. 402 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing) 403 Actions.append(Inputs.begin(), Inputs.end()); 404 else 405 Actions.push_back(new LipoJobAction(Inputs, Act->getType())); 406 } 407} 408 409void Driver::BuildActions(const ArgList &Args, ActionList &Actions) const { 410 llvm::PrettyStackTraceString CrashInfo("Building compilation actions"); 411 // Start by constructing the list of inputs and their types. 412 413 // Track the current user specified (-x) input. We also explicitly 414 // track the argument used to set the type; we only want to claim 415 // the type when we actually use it, so we warn about unused -x 416 // arguments. 417 types::ID InputType = types::TY_Nothing; 418 Arg *InputTypeArg = 0; 419 420 llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs; 421 for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); 422 it != ie; ++it) { 423 Arg *A = *it; 424 425 if (isa<InputOption>(A->getOption())) { 426 const char *Value = A->getValue(Args); 427 types::ID Ty = types::TY_INVALID; 428 429 // Infer the input type if necessary. 430 if (InputType == types::TY_Nothing) { 431 // If there was an explicit arg for this, claim it. 432 if (InputTypeArg) 433 InputTypeArg->claim(); 434 435 // stdin must be handled specially. 436 if (memcmp(Value, "-", 2) == 0) { 437 // If running with -E, treat as a C input (this changes the 438 // builtin macros, for example). This may be overridden by 439 // -ObjC below. 440 // 441 // Otherwise emit an error but still use a valid type to 442 // avoid spurious errors (e.g., no inputs). 443 if (!Args.hasArg(options::OPT_E, false)) 444 Diag(clang::diag::err_drv_unknown_stdin_type); 445 Ty = types::TY_C; 446 } else { 447 // Otherwise lookup by extension, and fallback to ObjectType 448 // if not found. We use a host hook here because Darwin at 449 // least has its own idea of what .s is. 450 if (const char *Ext = strrchr(Value, '.')) 451 Ty = Host->lookupTypeForExtension(Ext + 1); 452 453 if (Ty == types::TY_INVALID) 454 Ty = types::TY_Object; 455 } 456 457 // -ObjC and -ObjC++ override the default language, but only 458 // -for "source files". We just treat everything that isn't a 459 // -linker input as a source file. 460 // 461 // FIXME: Clean this up if we move the phase sequence into the 462 // type. 463 if (Ty != types::TY_Object) { 464 if (Args.hasArg(options::OPT_ObjC)) 465 Ty = types::TY_ObjC; 466 else if (Args.hasArg(options::OPT_ObjCXX)) 467 Ty = types::TY_ObjCXX; 468 } 469 } else { 470 assert(InputTypeArg && "InputType set w/o InputTypeArg"); 471 InputTypeArg->claim(); 472 Ty = InputType; 473 } 474 475 // Check that the file exists. It isn't clear this is worth 476 // doing, since the tool presumably does this anyway, and this 477 // just adds an extra stat to the equation, but this is gcc 478 // compatible. 479 if (memcmp(Value, "-", 2) != 0 && !llvm::sys::Path(Value).exists()) 480 Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args); 481 else 482 Inputs.push_back(std::make_pair(Ty, A)); 483 484 } else if (A->getOption().isLinkerInput()) { 485 // Just treat as object type, we could make a special type for 486 // this if necessary. 487 Inputs.push_back(std::make_pair(types::TY_Object, A)); 488 489 } else if (A->getOption().getId() == options::OPT_x) { 490 InputTypeArg = A; 491 InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args)); 492 493 // Follow gcc behavior and treat as linker input for invalid -x 494 // options. Its not clear why we shouldn't just revert to 495 // unknown; but this isn't very important, we might as well be 496 // bug comatible. 497 if (!InputType) { 498 Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args); 499 InputType = types::TY_Object; 500 } 501 } 502 } 503 504 if (!SuppressMissingInputWarning && Inputs.empty()) { 505 Diag(clang::diag::err_drv_no_input_files); 506 return; 507 } 508 509 // Determine which compilation mode we are in. We look for options 510 // which affect the phase, starting with the earliest phases, and 511 // record which option we used to determine the final phase. 512 Arg *FinalPhaseArg = 0; 513 phases::ID FinalPhase; 514 515 // -{E,M,MM} only run the preprocessor. 516 if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) || 517 (FinalPhaseArg = Args.getLastArg(options::OPT_M)) || 518 (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) { 519 FinalPhase = phases::Preprocess; 520 521 // -{fsyntax-only,-analyze,emit-llvm,S} only run up to the compiler. 522 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) || 523 (FinalPhaseArg = Args.getLastArg(options::OPT__analyze)) || 524 (FinalPhaseArg = Args.getLastArg(options::OPT_emit_llvm)) || 525 (FinalPhaseArg = Args.getLastArg(options::OPT_S))) { 526 FinalPhase = phases::Compile; 527 528 // -c only runs up to the assembler. 529 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) { 530 FinalPhase = phases::Assemble; 531 532 // Otherwise do everything. 533 } else 534 FinalPhase = phases::Link; 535 536 // Reject -Z* at the top level, these options should never have been 537 // exposed by gcc. 538 if (Arg *A = Args.getLastArg(options::OPT_Z)) 539 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args); 540 541 // Construct the actions to perform. 542 ActionList LinkerInputs; 543 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) { 544 types::ID InputType = Inputs[i].first; 545 const Arg *InputArg = Inputs[i].second; 546 547 unsigned NumSteps = types::getNumCompilationPhases(InputType); 548 assert(NumSteps && "Invalid number of steps!"); 549 550 // If the first step comes after the final phase we are doing as 551 // part of this compilation, warn the user about it. 552 phases::ID InitialPhase = types::getCompilationPhase(InputType, 0); 553 if (InitialPhase > FinalPhase) { 554 // Claim here to avoid the more general unused warning. 555 InputArg->claim(); 556 Diag(clang::diag::warn_drv_input_file_unused) 557 << InputArg->getAsString(Args) 558 << getPhaseName(InitialPhase) 559 << FinalPhaseArg->getOption().getName(); 560 continue; 561 } 562 563 // Build the pipeline for this file. 564 Action *Current = new InputAction(*InputArg, InputType); 565 for (unsigned i = 0; i != NumSteps; ++i) { 566 phases::ID Phase = types::getCompilationPhase(InputType, i); 567 568 // We are done if this step is past what the user requested. 569 if (Phase > FinalPhase) 570 break; 571 572 // Queue linker inputs. 573 if (Phase == phases::Link) { 574 assert(i + 1 == NumSteps && "linking must be final compilation step."); 575 LinkerInputs.push_back(Current); 576 Current = 0; 577 break; 578 } 579 580 // Otherwise construct the appropriate action. 581 Current = ConstructPhaseAction(Args, Phase, Current); 582 if (Current->getType() == types::TY_Nothing) 583 break; 584 } 585 586 // If we ended with something, add to the output list. 587 if (Current) 588 Actions.push_back(Current); 589 } 590 591 // Add a link action if necessary. 592 if (!LinkerInputs.empty()) 593 Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image)); 594} 595 596Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase, 597 Action *Input) const { 598 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions"); 599 // Build the appropriate action. 600 switch (Phase) { 601 case phases::Link: assert(0 && "link action invalid here."); 602 case phases::Preprocess: { 603 types::ID OutputTy = types::getPreprocessedType(Input->getType()); 604 assert(OutputTy != types::TY_INVALID && 605 "Cannot preprocess this input type!"); 606 return new PreprocessJobAction(Input, OutputTy); 607 } 608 case phases::Precompile: 609 return new PrecompileJobAction(Input, types::TY_PCH); 610 case phases::Compile: { 611 if (Args.hasArg(options::OPT_fsyntax_only)) { 612 return new CompileJobAction(Input, types::TY_Nothing); 613 } else if (Args.hasArg(options::OPT__analyze)) { 614 return new AnalyzeJobAction(Input, types::TY_Plist); 615 } else if (Args.hasArg(options::OPT_emit_llvm)) { 616 types::ID Output = 617 Args.hasArg(options::OPT_S) ? types::TY_LLVMAsm : types::TY_LLVMBC; 618 return new CompileJobAction(Input, Output); 619 } else { 620 return new CompileJobAction(Input, types::TY_PP_Asm); 621 } 622 } 623 case phases::Assemble: 624 return new AssembleJobAction(Input, types::TY_Object); 625 } 626 627 assert(0 && "invalid phase in ConstructPhaseAction"); 628 return 0; 629} 630 631void Driver::BuildJobs(Compilation &C) const { 632 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 633 bool SaveTemps = C.getArgs().hasArg(options::OPT_save_temps); 634 bool UsePipes = C.getArgs().hasArg(options::OPT_pipe); 635 636 // FIXME: Pipes are forcibly disabled until we support executing 637 // them. 638 if (!CCCPrintBindings) 639 UsePipes = false; 640 641 // -save-temps inhibits pipes. 642 if (SaveTemps && UsePipes) { 643 Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps); 644 UsePipes = true; 645 } 646 647 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 648 649 // It is an error to provide a -o option if we are making multiple 650 // output files. 651 if (FinalOutput) { 652 unsigned NumOutputs = 0; 653 for (ActionList::const_iterator it = C.getActions().begin(), 654 ie = C.getActions().end(); it != ie; ++it) 655 if ((*it)->getType() != types::TY_Nothing) 656 ++NumOutputs; 657 658 if (NumOutputs > 1) { 659 Diag(clang::diag::err_drv_output_argument_with_multiple_files); 660 FinalOutput = 0; 661 } 662 } 663 664 for (ActionList::const_iterator it = C.getActions().begin(), 665 ie = C.getActions().end(); it != ie; ++it) { 666 Action *A = *it; 667 668 // If we are linking an image for multiple archs then the linker 669 // wants -arch_multiple and -final_output <final image 670 // name>. Unfortunately, this doesn't fit in cleanly because we 671 // have to pass this information down. 672 // 673 // FIXME: This is a hack; find a cleaner way to integrate this 674 // into the process. 675 const char *LinkingOutput = 0; 676 if (isa<LinkJobAction>(A)) { 677 if (FinalOutput) 678 LinkingOutput = FinalOutput->getValue(C.getArgs()); 679 else 680 LinkingOutput = DefaultImageName.c_str(); 681 } 682 683 InputInfo II; 684 BuildJobsForAction(C, A, &C.getDefaultToolChain(), 685 /*CanAcceptPipe*/ true, 686 /*AtTopLevel*/ true, 687 /*LinkingOutput*/ LinkingOutput, 688 II); 689 } 690 691 // If there were errors, don't warn about any unused arguments. 692 if (Diags.getNumErrors()) 693 return; 694 695 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end(); 696 it != ie; ++it) { 697 Arg *A = *it; 698 699 // FIXME: It would be nice to be able to send the argument to the 700 // Diagnostic, so that extra values, position, and so on could be 701 // printed. 702 if (!A->isClaimed()) 703 Diag(clang::diag::warn_drv_unused_argument) 704 << A->getAsString(C.getArgs()); 705 } 706} 707 708void Driver::BuildJobsForAction(Compilation &C, 709 const Action *A, 710 const ToolChain *TC, 711 bool CanAcceptPipe, 712 bool AtTopLevel, 713 const char *LinkingOutput, 714 InputInfo &Result) const { 715 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs for action"); 716 717 bool UsePipes = C.getArgs().hasArg(options::OPT_pipe); 718 // FIXME: Pipes are forcibly disabled until we support executing 719 // them. 720 if (!CCCPrintBindings) 721 UsePipes = false; 722 723 if (const InputAction *IA = dyn_cast<InputAction>(A)) { 724 // FIXME: It would be nice to not claim this here; maybe the old 725 // scheme of just using Args was better? 726 const Arg &Input = IA->getInputArg(); 727 Input.claim(); 728 if (isa<PositionalArg>(Input)) { 729 const char *Name = Input.getValue(C.getArgs()); 730 Result = InputInfo(Name, A->getType(), Name); 731 } else 732 Result = InputInfo(&Input, A->getType(), ""); 733 return; 734 } 735 736 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) { 737 const char *ArchName = BAA->getArchName(); 738 if (!ArchName) 739 ArchName = C.getDefaultToolChain().getArchName().c_str(); 740 BuildJobsForAction(C, 741 *BAA->begin(), 742 Host->getToolChain(C.getArgs(), ArchName), 743 CanAcceptPipe, 744 AtTopLevel, 745 LinkingOutput, 746 Result); 747 return; 748 } 749 750 const JobAction *JA = cast<JobAction>(A); 751 const Tool &T = TC->SelectTool(C, *JA); 752 753 // See if we should use an integrated preprocessor. We do so when we 754 // have exactly one input, since this is the only use case we care 755 // about (irrelevant since we don't support combine yet). 756 bool UseIntegratedCPP = false; 757 const ActionList *Inputs = &A->getInputs(); 758 if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin())) { 759 if (!C.getArgs().hasArg(options::OPT_no_integrated_cpp) && 760 !C.getArgs().hasArg(options::OPT_traditional_cpp) && 761 !C.getArgs().hasArg(options::OPT_save_temps) && 762 T.hasIntegratedCPP()) { 763 UseIntegratedCPP = true; 764 Inputs = &(*Inputs)[0]->getInputs(); 765 } 766 } 767 768 // Only use pipes when there is exactly one input. 769 bool TryToUsePipeInput = Inputs->size() == 1 && T.acceptsPipedInput(); 770 InputInfoList InputInfos; 771 for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end(); 772 it != ie; ++it) { 773 InputInfo II; 774 BuildJobsForAction(C, *it, TC, TryToUsePipeInput, 775 /*AtTopLevel*/false, 776 LinkingOutput, 777 II); 778 InputInfos.push_back(II); 779 } 780 781 // Determine if we should output to a pipe. 782 bool OutputToPipe = false; 783 if (CanAcceptPipe && T.canPipeOutput()) { 784 // Some actions default to writing to a pipe if they are the top 785 // level phase and there was no user override. 786 // 787 // FIXME: Is there a better way to handle this? 788 if (AtTopLevel) { 789 if (isa<PreprocessJobAction>(A) && !C.getArgs().hasArg(options::OPT_o)) 790 OutputToPipe = true; 791 } else if (UsePipes) 792 OutputToPipe = true; 793 } 794 795 // Figure out where to put the job (pipes). 796 Job *Dest = &C.getJobs(); 797 if (InputInfos[0].isPipe()) { 798 assert(TryToUsePipeInput && "Unrequested pipe!"); 799 assert(InputInfos.size() == 1 && "Unexpected pipe with multiple inputs."); 800 Dest = &InputInfos[0].getPipe(); 801 } 802 803 // Always use the first input as the base input. 804 const char *BaseInput = InputInfos[0].getBaseInput(); 805 806 // Determine the place to write output to (nothing, pipe, or 807 // filename) and where to put the new job. 808 if (JA->getType() == types::TY_Nothing) { 809 Result = InputInfo(A->getType(), BaseInput); 810 } else if (OutputToPipe) { 811 // Append to current piped job or create a new one as appropriate. 812 PipedJob *PJ = dyn_cast<PipedJob>(Dest); 813 if (!PJ) { 814 PJ = new PipedJob(); 815 // FIXME: Temporary hack so that -ccc-print-bindings work until 816 // we have pipe support. Please remove later. 817 if (!CCCPrintBindings) 818 cast<JobList>(Dest)->addJob(PJ); 819 Dest = PJ; 820 } 821 Result = InputInfo(PJ, A->getType(), BaseInput); 822 } else { 823 Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel), 824 A->getType(), BaseInput); 825 } 826 827 if (CCCPrintBindings) { 828 llvm::errs() << "bind - \"" << T.getName() << "\", inputs: ["; 829 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) { 830 llvm::errs() << InputInfos[i].getAsString(); 831 if (i + 1 != e) 832 llvm::errs() << ", "; 833 } 834 llvm::errs() << "], output: " << Result.getAsString() << "\n"; 835 } else { 836 const ArgList &TCArgs = C.getArgsForToolChain(TC); 837 T.ConstructJob(C, *JA, *Dest, Result, InputInfos, TCArgs, LinkingOutput); 838 } 839} 840 841const char *Driver::GetNamedOutputPath(Compilation &C, 842 const JobAction &JA, 843 const char *BaseInput, 844 bool AtTopLevel) const { 845 llvm::PrettyStackTraceString CrashInfo("Computing output path"); 846 // Output to a user requested destination? 847 if (AtTopLevel) { 848 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) 849 return C.addResultFile(FinalOutput->getValue(C.getArgs())); 850 } 851 852 // Output to a temporary file? 853 if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) { 854 std::string TmpName = 855 GetTemporaryPath(types::getTypeTempSuffix(JA.getType())); 856 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); 857 } 858 859 llvm::sys::Path BasePath(BaseInput); 860 std::string BaseName(BasePath.getLast()); 861 862 // Determine what the derived output name should be. 863 const char *NamedOutput; 864 if (JA.getType() == types::TY_Image) { 865 NamedOutput = DefaultImageName.c_str(); 866 } else { 867 const char *Suffix = types::getTypeTempSuffix(JA.getType()); 868 assert(Suffix && "All types used for output should have a suffix."); 869 870 std::string::size_type End = std::string::npos; 871 if (!types::appendSuffixForType(JA.getType())) 872 End = BaseName.rfind('.'); 873 std::string Suffixed(BaseName.substr(0, End)); 874 Suffixed += '.'; 875 Suffixed += Suffix; 876 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str()); 877 } 878 879 // As an annoying special case, PCH generation doesn't strip the 880 // pathname. 881 if (JA.getType() == types::TY_PCH) { 882 BasePath.eraseComponent(); 883 if (BasePath.isEmpty()) 884 BasePath = NamedOutput; 885 else 886 BasePath.appendComponent(NamedOutput); 887 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str())); 888 } else { 889 return C.addResultFile(NamedOutput); 890 } 891} 892 893llvm::sys::Path Driver::GetFilePath(const char *Name, 894 const ToolChain &TC) const { 895 const ToolChain::path_list &List = TC.getFilePaths(); 896 for (ToolChain::path_list::const_iterator 897 it = List.begin(), ie = List.end(); it != ie; ++it) { 898 llvm::sys::Path P(*it); 899 P.appendComponent(Name); 900 if (P.exists()) 901 return P; 902 } 903 904 return llvm::sys::Path(Name); 905} 906 907llvm::sys::Path Driver::GetProgramPath(const char *Name, 908 const ToolChain &TC) const { 909 const ToolChain::path_list &List = TC.getProgramPaths(); 910 for (ToolChain::path_list::const_iterator 911 it = List.begin(), ie = List.end(); it != ie; ++it) { 912 llvm::sys::Path P(*it); 913 P.appendComponent(Name); 914 if (P.exists()) 915 return P; 916 } 917 918 // As a last resort, always search in our directory before pulling 919 // from the path. 920 llvm::sys::Path P(Dir); 921 P.appendComponent(Name); 922 if (P.exists()) 923 return P; 924 925 // Search path to increase accuracy of logging output. 926 P = llvm::sys::Program::FindProgramByName(Name); 927 if (!P.empty()) 928 return P; 929 930 return llvm::sys::Path(Name); 931} 932 933std::string Driver::GetTemporaryPath(const char *Suffix) const { 934 // FIXME: This is lame; sys::Path should provide this function (in 935 // particular, it should know how to find the temporary files dir). 936 std::string Error; 937 llvm::sys::Path P("/tmp/cc"); 938 if (P.makeUnique(false, &Error)) { 939 Diag(clang::diag::err_drv_unable_to_make_temp) << Error; 940 return ""; 941 } 942 943 // FIXME: Grumble, makeUnique sometimes leaves the file around!? 944 // PR3837. 945 P.eraseFromDisk(false, 0); 946 947 P.appendSuffix(Suffix); 948 return P.toString(); 949} 950 951const HostInfo *Driver::GetHostInfo(const char *Triple) const { 952 llvm::PrettyStackTraceString CrashInfo("Constructing host"); 953 // Dice into arch, platform, and OS. This matches 954 // arch,platform,os = '(.*?)-(.*?)-(.*?)' 955 // and missing fields are left empty. 956 std::string Arch, Platform, OS; 957 958 if (const char *ArchEnd = strchr(Triple, '-')) { 959 Arch = std::string(Triple, ArchEnd); 960 961 if (const char *PlatformEnd = strchr(ArchEnd+1, '-')) { 962 Platform = std::string(ArchEnd+1, PlatformEnd); 963 OS = PlatformEnd+1; 964 } else 965 Platform = ArchEnd+1; 966 } else 967 Arch = Triple; 968 969 // Normalize Arch a bit. 970 // 971 // FIXME: This is very incomplete. 972 if (Arch == "i686") 973 Arch = "i386"; 974 else if (Arch == "amd64") 975 Arch = "x86_64"; 976 else if (Arch == "powerpc" || Arch == "Power Macintosh") 977 Arch = "ppc"; 978 979 if (memcmp(&OS[0], "darwin", 6) == 0) 980 return createDarwinHostInfo(*this, Arch.c_str(), Platform.c_str(), 981 OS.c_str()); 982 983 return createUnknownHostInfo(*this, Arch.c_str(), Platform.c_str(), 984 OS.c_str()); 985} 986