Driver.cpp revision 195341
1178825Sdfr//===--- Driver.cpp - Clang GCC Compatible Driver -----------------------*-===// 2178825Sdfr// 3178825Sdfr// The LLVM Compiler Infrastructure 4178825Sdfr// 5178825Sdfr// This file is distributed under the University of Illinois Open Source 6178825Sdfr// License. See LICENSE.TXT for details. 7178825Sdfr// 8178825Sdfr//===----------------------------------------------------------------------===// 9178825Sdfr 10233294Sstas#include "clang/Driver/Driver.h" 11178825Sdfr 12178825Sdfr#include "clang/Driver/Action.h" 13178825Sdfr#include "clang/Driver/Arg.h" 14178825Sdfr#include "clang/Driver/ArgList.h" 15178825Sdfr#include "clang/Driver/Compilation.h" 16178825Sdfr#include "clang/Driver/DriverDiagnostic.h" 17178825Sdfr#include "clang/Driver/HostInfo.h" 18178825Sdfr#include "clang/Driver/Job.h" 19178825Sdfr#include "clang/Driver/Option.h" 20178825Sdfr#include "clang/Driver/Options.h" 21178825Sdfr#include "clang/Driver/Tool.h" 22178825Sdfr#include "clang/Driver/ToolChain.h" 23178825Sdfr#include "clang/Driver/Types.h" 24233294Sstas 25178825Sdfr#include "clang/Basic/Version.h" 26178825Sdfr 27178825Sdfr#include "llvm/ADT/StringSet.h" 28178825Sdfr#include "llvm/Support/PrettyStackTrace.h" 29178825Sdfr#include "llvm/Support/raw_ostream.h" 30178825Sdfr#include "llvm/System/Path.h" 31178825Sdfr#include "llvm/System/Program.h" 32178825Sdfr 33178825Sdfr#include "InputInfo.h" 34178825Sdfr 35233294Sstas#include <map> 36178825Sdfr 37178825Sdfrusing namespace clang::driver; 38178825Sdfrusing namespace clang; 39178825Sdfr 40233294SstasDriver::Driver(const char *_Name, const char *_Dir, 41178825Sdfr const char *_DefaultHostTriple, 42178825Sdfr const char *_DefaultImageName, 43178825Sdfr Diagnostic &_Diags) 44178825Sdfr : Opts(new OptTable()), Diags(_Diags), 45178825Sdfr Name(_Name), Dir(_Dir), DefaultHostTriple(_DefaultHostTriple), 46178825Sdfr DefaultImageName(_DefaultImageName), 47233294Sstas Host(0), 48178825Sdfr CCCIsCXX(false), CCCEcho(false), CCCPrintBindings(false), 49178825Sdfr CCCGenericGCCName("gcc"), CCCUseClang(true), CCCUseClangCXX(false), 50178825Sdfr CCCUseClangCPP(true), CCCUsePCH(true), 51178825Sdfr SuppressMissingInputWarning(false) 52178825Sdfr{ 53178825Sdfr // Only use clang on i386 and x86_64 by default. 54233294Sstas CCCClangArchs.insert("i386"); 55178825Sdfr CCCClangArchs.insert("x86_64"); 56178825Sdfr} 57178825Sdfr 58178825SdfrDriver::~Driver() { 59178825Sdfr delete Opts; 60233294Sstas delete Host; 61178825Sdfr} 62178825Sdfr 63178825SdfrInputArgList *Driver::ParseArgStrings(const char **ArgBegin, 64178825Sdfr const char **ArgEnd) { 65178825Sdfr llvm::PrettyStackTraceString CrashInfo("Command line argument parsing"); 66233294Sstas InputArgList *Args = new InputArgList(ArgBegin, ArgEnd); 67178825Sdfr 68178825Sdfr // FIXME: Handle '@' args (or at least error on them). 69178825Sdfr 70178825Sdfr unsigned Index = 0, End = ArgEnd - ArgBegin; 71178825Sdfr while (Index < End) { 72178825Sdfr // gcc's handling of empty arguments doesn't make 73233294Sstas // sense, but this is not a common use case. :) 74178825Sdfr // 75178825Sdfr // We just ignore them here (note that other things may 76178825Sdfr // still take them as arguments). 77178825Sdfr if (Args->getArgString(Index)[0] == '\0') { 78178825Sdfr ++Index; 79233294Sstas continue; 80233294Sstas } 81233294Sstas 82233294Sstas unsigned Prev = Index; 83233294Sstas Arg *A = getOpts().ParseOneArg(*Args, Index); 84233294Sstas assert(Index > Prev && "Parser failed to consume argument."); 85233294Sstas 86178825Sdfr // Check for missing argument error. 87178825Sdfr if (!A) { 88178825Sdfr assert(Index >= End && "Unexpected parser error."); 89178825Sdfr Diag(clang::diag::err_drv_missing_argument) 90178825Sdfr << Args->getArgString(Prev) 91233294Sstas << (Index - Prev - 1); 92178825Sdfr break; 93178825Sdfr } 94178825Sdfr 95178825Sdfr if (A->getOption().isUnsupported()) { 96178825Sdfr Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args); 97233294Sstas continue; 98178825Sdfr } 99178825Sdfr Args->append(A); 100178825Sdfr } 101178825Sdfr 102178825Sdfr return Args; 103178825Sdfr} 104178825Sdfr 105233294SstasCompilation *Driver::BuildCompilation(int argc, const char **argv) { 106233294Sstas llvm::PrettyStackTraceString CrashInfo("Compilation construction"); 107233294Sstas 108233294Sstas // FIXME: Handle environment options which effect driver behavior, 109233294Sstas // somewhere (client?). GCC_EXEC_PREFIX, COMPILER_PATH, 110233294Sstas // LIBRARY_PATH, LPATH, CC_PRINT_OPTIONS, QA_OVERRIDE_GCC3_OPTIONS. 111233294Sstas 112178825Sdfr // FIXME: What are we going to do with -V and -b? 113178825Sdfr 114178825Sdfr // FIXME: This stuff needs to go into the Compilation, not the 115178825Sdfr // driver. 116178825Sdfr bool CCCPrintOptions = false, CCCPrintActions = false; 117178825Sdfr 118233294Sstas const char **Start = argv + 1, **End = argv + argc; 119178825Sdfr const char *HostTriple = DefaultHostTriple.c_str(); 120178825Sdfr 121178825Sdfr // Read -ccc args. 122178825Sdfr // 123178825Sdfr // FIXME: We need to figure out where this behavior should 124233294Sstas // live. Most of it should be outside in the client; the parts that 125178825Sdfr // aren't should have proper options, either by introducing new ones 126178825Sdfr // or by overloading gcc ones like -V or -b. 127178825Sdfr for (; Start != End && memcmp(*Start, "-ccc-", 5) == 0; ++Start) { 128178825Sdfr const char *Opt = *Start + 5; 129178825Sdfr 130233294Sstas if (!strcmp(Opt, "print-options")) { 131178825Sdfr CCCPrintOptions = true; 132178825Sdfr } else if (!strcmp(Opt, "print-phases")) { 133178825Sdfr CCCPrintActions = true; 134233294Sstas } else if (!strcmp(Opt, "print-bindings")) { 135178825Sdfr CCCPrintBindings = true; 136178825Sdfr } else if (!strcmp(Opt, "cxx")) { 137178825Sdfr CCCIsCXX = true; 138178825Sdfr } else if (!strcmp(Opt, "echo")) { 139178825Sdfr CCCEcho = true; 140178825Sdfr 141178825Sdfr } else if (!strcmp(Opt, "gcc-name")) { 142178825Sdfr assert(Start+1 < End && "FIXME: -ccc- argument handling."); 143178825Sdfr CCCGenericGCCName = *++Start; 144178825Sdfr 145178825Sdfr } else if (!strcmp(Opt, "clang-cxx")) { 146178825Sdfr CCCUseClangCXX = true; 147178825Sdfr } else if (!strcmp(Opt, "pch-is-pch")) { 148178825Sdfr CCCUsePCH = true; 149178825Sdfr } else if (!strcmp(Opt, "pch-is-pth")) { 150233294Sstas CCCUsePCH = false; 151178825Sdfr } else if (!strcmp(Opt, "no-clang")) { 152178825Sdfr CCCUseClang = false; 153178825Sdfr } else if (!strcmp(Opt, "no-clang-cpp")) { 154178825Sdfr CCCUseClangCPP = false; 155178825Sdfr } else if (!strcmp(Opt, "clang-archs")) { 156178825Sdfr assert(Start+1 < End && "FIXME: -ccc- argument handling."); 157178825Sdfr const char *Cur = *++Start; 158178825Sdfr 159178825Sdfr CCCClangArchs.clear(); 160178825Sdfr for (;;) { 161178825Sdfr const char *Next = strchr(Cur, ','); 162233294Sstas 163178825Sdfr if (Next) { 164178825Sdfr if (Cur != Next) 165178825Sdfr CCCClangArchs.insert(std::string(Cur, Next)); 166178825Sdfr Cur = Next + 1; 167178825Sdfr } else { 168178825Sdfr if (*Cur != '\0') 169178825Sdfr CCCClangArchs.insert(std::string(Cur)); 170178825Sdfr break; 171233294Sstas } 172178825Sdfr } 173178825Sdfr 174178825Sdfr } else if (!strcmp(Opt, "host-triple")) { 175178825Sdfr assert(Start+1 < End && "FIXME: -ccc- argument handling."); 176178825Sdfr HostTriple = *++Start; 177178825Sdfr 178178825Sdfr } else { 179178825Sdfr // FIXME: Error handling. 180178825Sdfr llvm::errs() << "invalid option: " << *Start << "\n"; 181233294Sstas exit(1); 182178825Sdfr } 183178825Sdfr } 184178825Sdfr 185178825Sdfr InputArgList *Args = ParseArgStrings(Start, End); 186178825Sdfr 187178825Sdfr Host = GetHostInfo(HostTriple); 188233294Sstas 189178825Sdfr // The compilation takes ownership of Args. 190178825Sdfr Compilation *C = new Compilation(*this, *Host->getToolChain(*Args), Args); 191178825Sdfr 192178825Sdfr // FIXME: This behavior shouldn't be here. 193178825Sdfr if (CCCPrintOptions) { 194233294Sstas PrintOptions(C->getArgs()); 195178825Sdfr return C; 196178825Sdfr } 197178825Sdfr 198178825Sdfr if (!HandleImmediateArgs(*C)) 199178825Sdfr return C; 200233294Sstas 201178825Sdfr // Construct the list of abstract actions to perform for this 202178825Sdfr // compilation. We avoid passing a Compilation here simply to 203178825Sdfr // enforce the abstraction that pipelining is not host or toolchain 204178825Sdfr // dependent (other than the driver driver test). 205178825Sdfr if (Host->useDriverDriver()) 206178825Sdfr BuildUniversalActions(C->getArgs(), C->getActions()); 207233294Sstas else 208178825Sdfr BuildActions(C->getArgs(), C->getActions()); 209178825Sdfr 210178825Sdfr if (CCCPrintActions) { 211178825Sdfr PrintActions(*C); 212178825Sdfr return C; 213233294Sstas } 214178825Sdfr 215178825Sdfr BuildJobs(*C); 216178825Sdfr 217178825Sdfr return C; 218178825Sdfr} 219233294Sstas 220233294Sstasint Driver::ExecuteCompilation(const Compilation &C) const { 221233294Sstas // Just print if -### was present. 222233294Sstas if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 223233294Sstas C.PrintJob(llvm::errs(), C.getJobs(), "\n", true); 224233294Sstas return 0; 225233294Sstas } 226233294Sstas 227233294Sstas // If there were errors building the compilation, quit now. 228233294Sstas if (getDiags().getNumErrors()) 229178825Sdfr return 1; 230178825Sdfr 231178825Sdfr const Command *FailingCommand = 0; 232178825Sdfr int Res = C.ExecuteJob(C.getJobs(), FailingCommand); 233233294Sstas 234178825Sdfr // Remove temp files. 235178825Sdfr C.CleanupFileList(C.getTempFiles()); 236178825Sdfr 237178825Sdfr // If the compilation failed, remove result files as well. 238233294Sstas if (Res != 0 && !C.getArgs().hasArg(options::OPT_save_temps)) 239178825Sdfr C.CleanupFileList(C.getResultFiles(), true); 240178825Sdfr 241178825Sdfr // Print extra information about abnormal failures, if possible. 242178825Sdfr if (Res) { 243178825Sdfr // This is ad-hoc, but we don't want to be excessively noisy. If the result 244233294Sstas // status was 1, assume the command failed normally. In particular, if it 245233294Sstas // was the compiler then assume it gave a reasonable error code. Failures in 246233294Sstas // other tools are less common, and they generally have worse diagnostics, 247233294Sstas // so always print the diagnostic there. 248233294Sstas const Action &Source = FailingCommand->getSource(); 249233294Sstas bool IsFriendlyTool = (isa<PreprocessJobAction>(Source) || 250178825Sdfr isa<PrecompileJobAction>(Source) || 251233294Sstas isa<AnalyzeJobAction>(Source) || 252178825Sdfr isa<CompileJobAction>(Source)); 253178825Sdfr 254178825Sdfr if (!IsFriendlyTool || Res != 1) { 255178825Sdfr // FIXME: See FIXME above regarding result code interpretation. 256178825Sdfr if (Res < 0) 257178825Sdfr Diag(clang::diag::err_drv_command_signalled) 258233294Sstas << Source.getClassName() << -Res; 259178825Sdfr else 260178825Sdfr Diag(clang::diag::err_drv_command_failed) 261178825Sdfr << Source.getClassName() << Res; 262178825Sdfr } 263178825Sdfr } 264178825Sdfr 265178825Sdfr return Res; 266178825Sdfr} 267233294Sstas 268233294Sstasvoid Driver::PrintOptions(const ArgList &Args) const { 269233294Sstas unsigned i = 0; 270178825Sdfr for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); 271233294Sstas it != ie; ++it, ++i) { 272233294Sstas Arg *A = *it; 273233294Sstas llvm::errs() << "Option " << i << " - " 274233294Sstas << "Name: \"" << A->getOption().getName() << "\", " 275178825Sdfr << "Values: {"; 276233294Sstas for (unsigned j = 0; j < A->getNumValues(); ++j) { 277178825Sdfr if (j) 278178825Sdfr llvm::errs() << ", "; 279178825Sdfr llvm::errs() << '"' << A->getValue(Args, j) << '"'; 280178825Sdfr } 281178825Sdfr llvm::errs() << "}\n"; 282178825Sdfr } 283178825Sdfr} 284233294Sstas 285178825Sdfrstatic std::string getOptionHelpName(const OptTable &Opts, options::ID Id) { 286178825Sdfr std::string Name = Opts.getOptionName(Id); 287178825Sdfr 288178825Sdfr // Add metavar, if used. 289178825Sdfr switch (Opts.getOptionKind(Id)) { 290178825Sdfr case Option::GroupClass: case Option::InputClass: case Option::UnknownClass: 291178825Sdfr assert(0 && "Invalid option with help text."); 292178825Sdfr 293178825Sdfr case Option::MultiArgClass: case Option::JoinedAndSeparateClass: 294233294Sstas assert(0 && "Cannot print metavar for this kind of option."); 295233294Sstas 296233294Sstas case Option::FlagClass: 297233294Sstas break; 298233294Sstas 299233294Sstas case Option::SeparateClass: case Option::JoinedOrSeparateClass: 300233294Sstas Name += ' '; 301233294Sstas // FALLTHROUGH 302233294Sstas case Option::JoinedClass: case Option::CommaJoinedClass: 303233294Sstas Name += Opts.getOptionMetaVar(Id); 304233294Sstas break; 305233294Sstas } 306233294Sstas 307233294Sstas return Name; 308233294Sstas} 309233294Sstas 310233294Sstasvoid Driver::PrintHelp(bool ShowHidden) const { 311233294Sstas llvm::raw_ostream &OS = llvm::outs(); 312233294Sstas 313233294Sstas OS << "OVERVIEW: clang \"gcc-compatible\" driver\n"; 314233294Sstas OS << '\n'; 315178825Sdfr OS << "USAGE: " << Name << " [options] <input files>\n"; 316178825Sdfr OS << '\n'; 317178825Sdfr OS << "OPTIONS:\n"; 318178825Sdfr 319178825Sdfr // Render help text into (option, help) pairs. 320178825Sdfr std::vector< std::pair<std::string, const char*> > OptionHelp; 321178825Sdfr 322178825Sdfr for (unsigned i = options::OPT_INPUT, e = options::LastOption; i != e; ++i) { 323178825Sdfr options::ID Id = (options::ID) i; 324 if (const char *Text = getOpts().getOptionHelpText(Id)) 325 OptionHelp.push_back(std::make_pair(getOptionHelpName(getOpts(), Id), 326 Text)); 327 } 328 329 if (ShowHidden) { 330 OptionHelp.push_back(std::make_pair("\nDRIVER OPTIONS:","")); 331 OptionHelp.push_back(std::make_pair("-ccc-cxx", 332 "Act as a C++ driver")); 333 OptionHelp.push_back(std::make_pair("-ccc-gcc-name", 334 "Name for native GCC compiler")); 335 OptionHelp.push_back(std::make_pair("-ccc-clang-cxx", 336 "Use the clang compiler for C++")); 337 OptionHelp.push_back(std::make_pair("-ccc-no-clang", 338 "Never use the clang compiler")); 339 OptionHelp.push_back(std::make_pair("-ccc-no-clang-cpp", 340 "Never use the clang preprocessor")); 341 OptionHelp.push_back(std::make_pair("-ccc-clang-archs", 342 "Comma separate list of architectures " 343 "to use the clang compiler for")); 344 OptionHelp.push_back(std::make_pair("-ccc-pch-is-pch", 345 "Use lazy PCH for precompiled headers")); 346 OptionHelp.push_back(std::make_pair("-ccc-pch-is-pth", 347 "Use pretokenized headers for precompiled headers")); 348 349 OptionHelp.push_back(std::make_pair("\nDEBUG/DEVELOPMENT OPTIONS:","")); 350 OptionHelp.push_back(std::make_pair("-ccc-host-triple", 351 "Simulate running on the given target")); 352 OptionHelp.push_back(std::make_pair("-ccc-print-options", 353 "Dump parsed command line arguments")); 354 OptionHelp.push_back(std::make_pair("-ccc-print-phases", 355 "Dump list of actions to perform")); 356 OptionHelp.push_back(std::make_pair("-ccc-print-bindings", 357 "Show bindings of tools to actions")); 358 OptionHelp.push_back(std::make_pair("CCC_ADD_ARGS", 359 "(ENVIRONMENT VARIABLE) Comma separated list of " 360 "arguments to prepend to the command line")); 361 } 362 363 // Find the maximum option length. 364 unsigned OptionFieldWidth = 0; 365 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) { 366 // Skip titles. 367 if (!OptionHelp[i].second) 368 continue; 369 370 // Limit the amount of padding we are willing to give up for 371 // alignment. 372 unsigned Length = OptionHelp[i].first.size(); 373 if (Length <= 23) 374 OptionFieldWidth = std::max(OptionFieldWidth, Length); 375 } 376 377 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) { 378 const std::string &Option = OptionHelp[i].first; 379 OS << " " << Option; 380 for (int j = Option.length(), e = OptionFieldWidth; j < e; ++j) 381 OS << ' '; 382 OS << ' ' << OptionHelp[i].second << '\n'; 383 } 384 385 OS.flush(); 386} 387 388void Driver::PrintVersion(const Compilation &C) const { 389 static char buf[] = "$URL: https://ed@llvm.org/svn/llvm-project/cfe/trunk/lib/Driver/Driver.cpp $"; 390 char *zap = strstr(buf, "/lib/Driver"); 391 if (zap) 392 *zap = 0; 393 zap = strstr(buf, "/clang/tools/clang"); 394 if (zap) 395 *zap = 0; 396 const char *vers = buf+6; 397 // FIXME: Add cmake support and remove #ifdef 398#ifdef SVN_REVISION 399 const char *revision = SVN_REVISION; 400#else 401 const char *revision = ""; 402#endif 403 // FIXME: The following handlers should use a callback mechanism, we 404 // don't know what the client would like to do. 405 406 llvm::errs() << "clang version " CLANG_VERSION_STRING " (" 407 << vers << " " << revision << ")" << '\n'; 408 409 const ToolChain &TC = C.getDefaultToolChain(); 410 llvm::errs() << "Target: " << TC.getTripleString() << '\n'; 411 412 // Print the threading model. 413 // 414 // FIXME: Implement correctly. 415 llvm::errs() << "Thread model: " << "posix" << '\n'; 416} 417 418bool Driver::HandleImmediateArgs(const Compilation &C) { 419 // The order these options are handled in in gcc is all over the 420 // place, but we don't expect inconsistencies w.r.t. that to matter 421 // in practice. 422 423 if (C.getArgs().hasArg(options::OPT_dumpversion)) { 424 llvm::outs() << CLANG_VERSION_STRING "\n"; 425 return false; 426 } 427 428 if (C.getArgs().hasArg(options::OPT__help) || 429 C.getArgs().hasArg(options::OPT__help_hidden)) { 430 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden)); 431 return false; 432 } 433 434 if (C.getArgs().hasArg(options::OPT__version)) { 435 PrintVersion(C); 436 return false; 437 } 438 439 if (C.getArgs().hasArg(options::OPT_v) || 440 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 441 PrintVersion(C); 442 SuppressMissingInputWarning = true; 443 } 444 445 const ToolChain &TC = C.getDefaultToolChain(); 446 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) { 447 llvm::outs() << "programs: ="; 448 for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(), 449 ie = TC.getProgramPaths().end(); it != ie; ++it) { 450 if (it != TC.getProgramPaths().begin()) 451 llvm::outs() << ':'; 452 llvm::outs() << *it; 453 } 454 llvm::outs() << "\n"; 455 llvm::outs() << "libraries: ="; 456 for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(), 457 ie = TC.getFilePaths().end(); it != ie; ++it) { 458 if (it != TC.getFilePaths().begin()) 459 llvm::outs() << ':'; 460 llvm::outs() << *it; 461 } 462 llvm::outs() << "\n"; 463 return false; 464 } 465 466 // FIXME: The following handlers should use a callback mechanism, we 467 // don't know what the client would like to do. 468 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) { 469 llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC).toString() 470 << "\n"; 471 return false; 472 } 473 474 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) { 475 llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC).toString() 476 << "\n"; 477 return false; 478 } 479 480 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) { 481 llvm::outs() << GetFilePath("libgcc.a", TC).toString() << "\n"; 482 return false; 483 } 484 485 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) { 486 // FIXME: We need tool chain support for this. 487 llvm::outs() << ".;\n"; 488 489 switch (C.getDefaultToolChain().getTriple().getArch()) { 490 default: 491 break; 492 493 case llvm::Triple::x86_64: 494 llvm::outs() << "x86_64;@m64" << "\n"; 495 break; 496 497 case llvm::Triple::ppc64: 498 llvm::outs() << "ppc64;@m64" << "\n"; 499 break; 500 } 501 return false; 502 } 503 504 // FIXME: What is the difference between print-multi-directory and 505 // print-multi-os-directory? 506 if (C.getArgs().hasArg(options::OPT_print_multi_directory) || 507 C.getArgs().hasArg(options::OPT_print_multi_os_directory)) { 508 switch (C.getDefaultToolChain().getTriple().getArch()) { 509 default: 510 case llvm::Triple::x86: 511 case llvm::Triple::ppc: 512 llvm::outs() << "." << "\n"; 513 break; 514 515 case llvm::Triple::x86_64: 516 llvm::outs() << "x86_64" << "\n"; 517 break; 518 519 case llvm::Triple::ppc64: 520 llvm::outs() << "ppc64" << "\n"; 521 break; 522 } 523 return false; 524 } 525 526 return true; 527} 528 529static unsigned PrintActions1(const Compilation &C, 530 Action *A, 531 std::map<Action*, unsigned> &Ids) { 532 if (Ids.count(A)) 533 return Ids[A]; 534 535 std::string str; 536 llvm::raw_string_ostream os(str); 537 538 os << Action::getClassName(A->getKind()) << ", "; 539 if (InputAction *IA = dyn_cast<InputAction>(A)) { 540 os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\""; 541 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) { 542 os << '"' << (BIA->getArchName() ? BIA->getArchName() : 543 C.getDefaultToolChain().getArchName()) << '"' 544 << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}"; 545 } else { 546 os << "{"; 547 for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) { 548 os << PrintActions1(C, *it, Ids); 549 ++it; 550 if (it != ie) 551 os << ", "; 552 } 553 os << "}"; 554 } 555 556 unsigned Id = Ids.size(); 557 Ids[A] = Id; 558 llvm::errs() << Id << ": " << os.str() << ", " 559 << types::getTypeName(A->getType()) << "\n"; 560 561 return Id; 562} 563 564void Driver::PrintActions(const Compilation &C) const { 565 std::map<Action*, unsigned> Ids; 566 for (ActionList::const_iterator it = C.getActions().begin(), 567 ie = C.getActions().end(); it != ie; ++it) 568 PrintActions1(C, *it, Ids); 569} 570 571void Driver::BuildUniversalActions(const ArgList &Args, 572 ActionList &Actions) const { 573 llvm::PrettyStackTraceString CrashInfo("Building actions for universal build"); 574 // Collect the list of architectures. Duplicates are allowed, but 575 // should only be handled once (in the order seen). 576 llvm::StringSet<> ArchNames; 577 llvm::SmallVector<const char *, 4> Archs; 578 for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); 579 it != ie; ++it) { 580 Arg *A = *it; 581 582 if (A->getOption().getId() == options::OPT_arch) { 583 const char *Name = A->getValue(Args); 584 585 // FIXME: We need to handle canonicalization of the specified 586 // arch? 587 588 A->claim(); 589 if (ArchNames.insert(Name)) 590 Archs.push_back(Name); 591 } 592 } 593 594 // When there is no explicit arch for this platform, make sure we 595 // still bind the architecture (to the default) so that -Xarch_ is 596 // handled correctly. 597 if (!Archs.size()) 598 Archs.push_back(0); 599 600 // FIXME: We killed off some others but these aren't yet detected in 601 // a functional manner. If we added information to jobs about which 602 // "auxiliary" files they wrote then we could detect the conflict 603 // these cause downstream. 604 if (Archs.size() > 1) { 605 // No recovery needed, the point of this is just to prevent 606 // overwriting the same files. 607 if (const Arg *A = Args.getLastArg(options::OPT_save_temps)) 608 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs) 609 << A->getAsString(Args); 610 } 611 612 ActionList SingleActions; 613 BuildActions(Args, SingleActions); 614 615 // Add in arch binding and lipo (if necessary) for every top level 616 // action. 617 for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) { 618 Action *Act = SingleActions[i]; 619 620 // Make sure we can lipo this kind of output. If not (and it is an 621 // actual output) then we disallow, since we can't create an 622 // output file with the right name without overwriting it. We 623 // could remove this oddity by just changing the output names to 624 // include the arch, which would also fix 625 // -save-temps. Compatibility wins for now. 626 627 if (Archs.size() > 1 && !types::canLipoType(Act->getType())) 628 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs) 629 << types::getTypeName(Act->getType()); 630 631 ActionList Inputs; 632 for (unsigned i = 0, e = Archs.size(); i != e; ++i) 633 Inputs.push_back(new BindArchAction(Act, Archs[i])); 634 635 // Lipo if necessary, We do it this way because we need to set the 636 // arch flag so that -Xarch_ gets overwritten. 637 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing) 638 Actions.append(Inputs.begin(), Inputs.end()); 639 else 640 Actions.push_back(new LipoJobAction(Inputs, Act->getType())); 641 } 642} 643 644void Driver::BuildActions(const ArgList &Args, ActionList &Actions) const { 645 llvm::PrettyStackTraceString CrashInfo("Building compilation actions"); 646 // Start by constructing the list of inputs and their types. 647 648 // Track the current user specified (-x) input. We also explicitly 649 // track the argument used to set the type; we only want to claim 650 // the type when we actually use it, so we warn about unused -x 651 // arguments. 652 types::ID InputType = types::TY_Nothing; 653 Arg *InputTypeArg = 0; 654 655 llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs; 656 for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); 657 it != ie; ++it) { 658 Arg *A = *it; 659 660 if (isa<InputOption>(A->getOption())) { 661 const char *Value = A->getValue(Args); 662 types::ID Ty = types::TY_INVALID; 663 664 // Infer the input type if necessary. 665 if (InputType == types::TY_Nothing) { 666 // If there was an explicit arg for this, claim it. 667 if (InputTypeArg) 668 InputTypeArg->claim(); 669 670 // stdin must be handled specially. 671 if (memcmp(Value, "-", 2) == 0) { 672 // If running with -E, treat as a C input (this changes the 673 // builtin macros, for example). This may be overridden by 674 // -ObjC below. 675 // 676 // Otherwise emit an error but still use a valid type to 677 // avoid spurious errors (e.g., no inputs). 678 if (!Args.hasArg(options::OPT_E, false)) 679 Diag(clang::diag::err_drv_unknown_stdin_type); 680 Ty = types::TY_C; 681 } else { 682 // Otherwise lookup by extension, and fallback to ObjectType 683 // if not found. We use a host hook here because Darwin at 684 // least has its own idea of what .s is. 685 if (const char *Ext = strrchr(Value, '.')) 686 Ty = Host->lookupTypeForExtension(Ext + 1); 687 688 if (Ty == types::TY_INVALID) 689 Ty = types::TY_Object; 690 } 691 692 // -ObjC and -ObjC++ override the default language, but only for "source 693 // files". We just treat everything that isn't a linker input as a 694 // source file. 695 // 696 // FIXME: Clean this up if we move the phase sequence into the type. 697 if (Ty != types::TY_Object) { 698 if (Args.hasArg(options::OPT_ObjC)) 699 Ty = types::TY_ObjC; 700 else if (Args.hasArg(options::OPT_ObjCXX)) 701 Ty = types::TY_ObjCXX; 702 } 703 } else { 704 assert(InputTypeArg && "InputType set w/o InputTypeArg"); 705 InputTypeArg->claim(); 706 Ty = InputType; 707 } 708 709 // Check that the file exists. It isn't clear this is worth 710 // doing, since the tool presumably does this anyway, and this 711 // just adds an extra stat to the equation, but this is gcc 712 // compatible. 713 if (memcmp(Value, "-", 2) != 0 && !llvm::sys::Path(Value).exists()) 714 Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args); 715 else 716 Inputs.push_back(std::make_pair(Ty, A)); 717 718 } else if (A->getOption().isLinkerInput()) { 719 // Just treat as object type, we could make a special type for 720 // this if necessary. 721 Inputs.push_back(std::make_pair(types::TY_Object, A)); 722 723 } else if (A->getOption().getId() == options::OPT_x) { 724 InputTypeArg = A; 725 InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args)); 726 727 // Follow gcc behavior and treat as linker input for invalid -x 728 // options. Its not clear why we shouldn't just revert to 729 // unknown; but this isn't very important, we might as well be 730 // bug comatible. 731 if (!InputType) { 732 Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args); 733 InputType = types::TY_Object; 734 } 735 } 736 } 737 738 if (!SuppressMissingInputWarning && Inputs.empty()) { 739 Diag(clang::diag::err_drv_no_input_files); 740 return; 741 } 742 743 // Determine which compilation mode we are in. We look for options 744 // which affect the phase, starting with the earliest phases, and 745 // record which option we used to determine the final phase. 746 Arg *FinalPhaseArg = 0; 747 phases::ID FinalPhase; 748 749 // -{E,M,MM} only run the preprocessor. 750 if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) || 751 (FinalPhaseArg = Args.getLastArg(options::OPT_M)) || 752 (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) { 753 FinalPhase = phases::Preprocess; 754 755 // -{fsyntax-only,-analyze,emit-llvm,S} only run up to the compiler. 756 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) || 757 (FinalPhaseArg = Args.getLastArg(options::OPT__analyze, 758 options::OPT__analyze_auto)) || 759 (FinalPhaseArg = Args.getLastArg(options::OPT_S))) { 760 FinalPhase = phases::Compile; 761 762 // -c only runs up to the assembler. 763 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) { 764 FinalPhase = phases::Assemble; 765 766 // Otherwise do everything. 767 } else 768 FinalPhase = phases::Link; 769 770 // Reject -Z* at the top level, these options should never have been 771 // exposed by gcc. 772 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined)) 773 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args); 774 775 // Construct the actions to perform. 776 ActionList LinkerInputs; 777 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) { 778 types::ID InputType = Inputs[i].first; 779 const Arg *InputArg = Inputs[i].second; 780 781 unsigned NumSteps = types::getNumCompilationPhases(InputType); 782 assert(NumSteps && "Invalid number of steps!"); 783 784 // If the first step comes after the final phase we are doing as 785 // part of this compilation, warn the user about it. 786 phases::ID InitialPhase = types::getCompilationPhase(InputType, 0); 787 if (InitialPhase > FinalPhase) { 788 // Claim here to avoid the more general unused warning. 789 InputArg->claim(); 790 Diag(clang::diag::warn_drv_input_file_unused) 791 << InputArg->getAsString(Args) 792 << getPhaseName(InitialPhase) 793 << FinalPhaseArg->getOption().getName(); 794 continue; 795 } 796 797 // Build the pipeline for this file. 798 Action *Current = new InputAction(*InputArg, InputType); 799 for (unsigned i = 0; i != NumSteps; ++i) { 800 phases::ID Phase = types::getCompilationPhase(InputType, i); 801 802 // We are done if this step is past what the user requested. 803 if (Phase > FinalPhase) 804 break; 805 806 // Queue linker inputs. 807 if (Phase == phases::Link) { 808 assert(i + 1 == NumSteps && "linking must be final compilation step."); 809 LinkerInputs.push_back(Current); 810 Current = 0; 811 break; 812 } 813 814 // Some types skip the assembler phase (e.g., llvm-bc), but we 815 // can't encode this in the steps because the intermediate type 816 // depends on arguments. Just special case here. 817 if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm) 818 continue; 819 820 // Otherwise construct the appropriate action. 821 Current = ConstructPhaseAction(Args, Phase, Current); 822 if (Current->getType() == types::TY_Nothing) 823 break; 824 } 825 826 // If we ended with something, add to the output list. 827 if (Current) 828 Actions.push_back(Current); 829 } 830 831 // Add a link action if necessary. 832 if (!LinkerInputs.empty()) 833 Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image)); 834} 835 836Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase, 837 Action *Input) const { 838 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions"); 839 // Build the appropriate action. 840 switch (Phase) { 841 case phases::Link: assert(0 && "link action invalid here."); 842 case phases::Preprocess: { 843 types::ID OutputTy; 844 // -{M, MM} alter the output type. 845 if (Args.hasArg(options::OPT_M) || Args.hasArg(options::OPT_MM)) { 846 OutputTy = types::TY_Dependencies; 847 } else { 848 OutputTy = types::getPreprocessedType(Input->getType()); 849 assert(OutputTy != types::TY_INVALID && 850 "Cannot preprocess this input type!"); 851 } 852 return new PreprocessJobAction(Input, OutputTy); 853 } 854 case phases::Precompile: 855 return new PrecompileJobAction(Input, types::TY_PCH); 856 case phases::Compile: { 857 if (Args.hasArg(options::OPT_fsyntax_only)) { 858 return new CompileJobAction(Input, types::TY_Nothing); 859 } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) { 860 return new AnalyzeJobAction(Input, types::TY_Plist); 861 } else if (Args.hasArg(options::OPT_emit_llvm) || 862 Args.hasArg(options::OPT_flto) || 863 Args.hasArg(options::OPT_O4)) { 864 types::ID Output = 865 Args.hasArg(options::OPT_S) ? types::TY_LLVMAsm : types::TY_LLVMBC; 866 return new CompileJobAction(Input, Output); 867 } else { 868 return new CompileJobAction(Input, types::TY_PP_Asm); 869 } 870 } 871 case phases::Assemble: 872 return new AssembleJobAction(Input, types::TY_Object); 873 } 874 875 assert(0 && "invalid phase in ConstructPhaseAction"); 876 return 0; 877} 878 879void Driver::BuildJobs(Compilation &C) const { 880 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 881 bool SaveTemps = C.getArgs().hasArg(options::OPT_save_temps); 882 bool UsePipes = C.getArgs().hasArg(options::OPT_pipe); 883 884 // FIXME: Pipes are forcibly disabled until we support executing 885 // them. 886 if (!CCCPrintBindings) 887 UsePipes = false; 888 889 // -save-temps inhibits pipes. 890 if (SaveTemps && UsePipes) { 891 Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps); 892 UsePipes = true; 893 } 894 895 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 896 897 // It is an error to provide a -o option if we are making multiple 898 // output files. 899 if (FinalOutput) { 900 unsigned NumOutputs = 0; 901 for (ActionList::const_iterator it = C.getActions().begin(), 902 ie = C.getActions().end(); it != ie; ++it) 903 if ((*it)->getType() != types::TY_Nothing) 904 ++NumOutputs; 905 906 if (NumOutputs > 1) { 907 Diag(clang::diag::err_drv_output_argument_with_multiple_files); 908 FinalOutput = 0; 909 } 910 } 911 912 for (ActionList::const_iterator it = C.getActions().begin(), 913 ie = C.getActions().end(); it != ie; ++it) { 914 Action *A = *it; 915 916 // If we are linking an image for multiple archs then the linker 917 // wants -arch_multiple and -final_output <final image 918 // name>. Unfortunately, this doesn't fit in cleanly because we 919 // have to pass this information down. 920 // 921 // FIXME: This is a hack; find a cleaner way to integrate this 922 // into the process. 923 const char *LinkingOutput = 0; 924 if (isa<LipoJobAction>(A)) { 925 if (FinalOutput) 926 LinkingOutput = FinalOutput->getValue(C.getArgs()); 927 else 928 LinkingOutput = DefaultImageName.c_str(); 929 } 930 931 InputInfo II; 932 BuildJobsForAction(C, A, &C.getDefaultToolChain(), 933 /*CanAcceptPipe*/ true, 934 /*AtTopLevel*/ true, 935 /*LinkingOutput*/ LinkingOutput, 936 II); 937 } 938 939 // If the user passed -Qunused-arguments or there were errors, don't 940 // warn about any unused arguments. 941 if (Diags.getNumErrors() || 942 C.getArgs().hasArg(options::OPT_Qunused_arguments)) 943 return; 944 945 // Claim -### here. 946 (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH); 947 948 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end(); 949 it != ie; ++it) { 950 Arg *A = *it; 951 952 // FIXME: It would be nice to be able to send the argument to the 953 // Diagnostic, so that extra values, position, and so on could be 954 // printed. 955 if (!A->isClaimed()) { 956 if (A->getOption().hasNoArgumentUnused()) 957 continue; 958 959 // Suppress the warning automatically if this is just a flag, 960 // and it is an instance of an argument we already claimed. 961 const Option &Opt = A->getOption(); 962 if (isa<FlagOption>(Opt)) { 963 bool DuplicateClaimed = false; 964 965 // FIXME: Use iterator. 966 for (ArgList::const_iterator it = C.getArgs().begin(), 967 ie = C.getArgs().end(); it != ie; ++it) { 968 if ((*it)->isClaimed() && (*it)->getOption().matches(Opt.getId())) { 969 DuplicateClaimed = true; 970 break; 971 } 972 } 973 974 if (DuplicateClaimed) 975 continue; 976 } 977 978 Diag(clang::diag::warn_drv_unused_argument) 979 << A->getAsString(C.getArgs()); 980 } 981 } 982} 983 984void Driver::BuildJobsForAction(Compilation &C, 985 const Action *A, 986 const ToolChain *TC, 987 bool CanAcceptPipe, 988 bool AtTopLevel, 989 const char *LinkingOutput, 990 InputInfo &Result) const { 991 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs for action"); 992 993 bool UsePipes = C.getArgs().hasArg(options::OPT_pipe); 994 // FIXME: Pipes are forcibly disabled until we support executing 995 // them. 996 if (!CCCPrintBindings) 997 UsePipes = false; 998 999 if (const InputAction *IA = dyn_cast<InputAction>(A)) { 1000 // FIXME: It would be nice to not claim this here; maybe the old 1001 // scheme of just using Args was better? 1002 const Arg &Input = IA->getInputArg(); 1003 Input.claim(); 1004 if (isa<PositionalArg>(Input)) { 1005 const char *Name = Input.getValue(C.getArgs()); 1006 Result = InputInfo(Name, A->getType(), Name); 1007 } else 1008 Result = InputInfo(&Input, A->getType(), ""); 1009 return; 1010 } 1011 1012 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) { 1013 const char *ArchName = BAA->getArchName(); 1014 std::string Arch; 1015 if (!ArchName) { 1016 Arch = C.getDefaultToolChain().getArchName(); 1017 ArchName = Arch.c_str(); 1018 } 1019 BuildJobsForAction(C, 1020 *BAA->begin(), 1021 Host->getToolChain(C.getArgs(), ArchName), 1022 CanAcceptPipe, 1023 AtTopLevel, 1024 LinkingOutput, 1025 Result); 1026 return; 1027 } 1028 1029 const JobAction *JA = cast<JobAction>(A); 1030 const Tool &T = TC->SelectTool(C, *JA); 1031 1032 // See if we should use an integrated preprocessor. We do so when we 1033 // have exactly one input, since this is the only use case we care 1034 // about (irrelevant since we don't support combine yet). 1035 bool UseIntegratedCPP = false; 1036 const ActionList *Inputs = &A->getInputs(); 1037 if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin())) { 1038 if (!C.getArgs().hasArg(options::OPT_no_integrated_cpp) && 1039 !C.getArgs().hasArg(options::OPT_traditional_cpp) && 1040 !C.getArgs().hasArg(options::OPT_save_temps) && 1041 T.hasIntegratedCPP()) { 1042 UseIntegratedCPP = true; 1043 Inputs = &(*Inputs)[0]->getInputs(); 1044 } 1045 } 1046 1047 // Only use pipes when there is exactly one input. 1048 bool TryToUsePipeInput = Inputs->size() == 1 && T.acceptsPipedInput(); 1049 InputInfoList InputInfos; 1050 for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end(); 1051 it != ie; ++it) { 1052 InputInfo II; 1053 BuildJobsForAction(C, *it, TC, TryToUsePipeInput, 1054 /*AtTopLevel*/false, 1055 LinkingOutput, 1056 II); 1057 InputInfos.push_back(II); 1058 } 1059 1060 // Determine if we should output to a pipe. 1061 bool OutputToPipe = false; 1062 if (CanAcceptPipe && T.canPipeOutput()) { 1063 // Some actions default to writing to a pipe if they are the top 1064 // level phase and there was no user override. 1065 // 1066 // FIXME: Is there a better way to handle this? 1067 if (AtTopLevel) { 1068 if (isa<PreprocessJobAction>(A) && !C.getArgs().hasArg(options::OPT_o)) 1069 OutputToPipe = true; 1070 } else if (UsePipes) 1071 OutputToPipe = true; 1072 } 1073 1074 // Figure out where to put the job (pipes). 1075 Job *Dest = &C.getJobs(); 1076 if (InputInfos[0].isPipe()) { 1077 assert(TryToUsePipeInput && "Unrequested pipe!"); 1078 assert(InputInfos.size() == 1 && "Unexpected pipe with multiple inputs."); 1079 Dest = &InputInfos[0].getPipe(); 1080 } 1081 1082 // Always use the first input as the base input. 1083 const char *BaseInput = InputInfos[0].getBaseInput(); 1084 1085 // Determine the place to write output to (nothing, pipe, or 1086 // filename) and where to put the new job. 1087 if (JA->getType() == types::TY_Nothing) { 1088 Result = InputInfo(A->getType(), BaseInput); 1089 } else if (OutputToPipe) { 1090 // Append to current piped job or create a new one as appropriate. 1091 PipedJob *PJ = dyn_cast<PipedJob>(Dest); 1092 if (!PJ) { 1093 PJ = new PipedJob(); 1094 // FIXME: Temporary hack so that -ccc-print-bindings work until 1095 // we have pipe support. Please remove later. 1096 if (!CCCPrintBindings) 1097 cast<JobList>(Dest)->addJob(PJ); 1098 Dest = PJ; 1099 } 1100 Result = InputInfo(PJ, A->getType(), BaseInput); 1101 } else { 1102 Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel), 1103 A->getType(), BaseInput); 1104 } 1105 1106 if (CCCPrintBindings) { 1107 llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"' 1108 << " - \"" << T.getName() << "\", inputs: ["; 1109 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) { 1110 llvm::errs() << InputInfos[i].getAsString(); 1111 if (i + 1 != e) 1112 llvm::errs() << ", "; 1113 } 1114 llvm::errs() << "], output: " << Result.getAsString() << "\n"; 1115 } else { 1116 T.ConstructJob(C, *JA, *Dest, Result, InputInfos, 1117 C.getArgsForToolChain(TC), LinkingOutput); 1118 } 1119} 1120 1121const char *Driver::GetNamedOutputPath(Compilation &C, 1122 const JobAction &JA, 1123 const char *BaseInput, 1124 bool AtTopLevel) const { 1125 llvm::PrettyStackTraceString CrashInfo("Computing output path"); 1126 // Output to a user requested destination? 1127 if (AtTopLevel) { 1128 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) 1129 return C.addResultFile(FinalOutput->getValue(C.getArgs())); 1130 } 1131 1132 // Output to a temporary file? 1133 if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) { 1134 std::string TmpName = 1135 GetTemporaryPath(types::getTypeTempSuffix(JA.getType())); 1136 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); 1137 } 1138 1139 llvm::sys::Path BasePath(BaseInput); 1140 std::string BaseName(BasePath.getLast()); 1141 1142 // Determine what the derived output name should be. 1143 const char *NamedOutput; 1144 if (JA.getType() == types::TY_Image) { 1145 NamedOutput = DefaultImageName.c_str(); 1146 } else { 1147 const char *Suffix = types::getTypeTempSuffix(JA.getType()); 1148 assert(Suffix && "All types used for output should have a suffix."); 1149 1150 std::string::size_type End = std::string::npos; 1151 if (!types::appendSuffixForType(JA.getType())) 1152 End = BaseName.rfind('.'); 1153 std::string Suffixed(BaseName.substr(0, End)); 1154 Suffixed += '.'; 1155 Suffixed += Suffix; 1156 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str()); 1157 } 1158 1159 // As an annoying special case, PCH generation doesn't strip the 1160 // pathname. 1161 if (JA.getType() == types::TY_PCH) { 1162 BasePath.eraseComponent(); 1163 if (BasePath.isEmpty()) 1164 BasePath = NamedOutput; 1165 else 1166 BasePath.appendComponent(NamedOutput); 1167 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str())); 1168 } else { 1169 return C.addResultFile(NamedOutput); 1170 } 1171} 1172 1173llvm::sys::Path Driver::GetFilePath(const char *Name, 1174 const ToolChain &TC) const { 1175 const ToolChain::path_list &List = TC.getFilePaths(); 1176 for (ToolChain::path_list::const_iterator 1177 it = List.begin(), ie = List.end(); it != ie; ++it) { 1178 llvm::sys::Path P(*it); 1179 P.appendComponent(Name); 1180 if (P.exists()) 1181 return P; 1182 } 1183 1184 return llvm::sys::Path(Name); 1185} 1186 1187llvm::sys::Path Driver::GetProgramPath(const char *Name, 1188 const ToolChain &TC, 1189 bool WantFile) const { 1190 const ToolChain::path_list &List = TC.getProgramPaths(); 1191 for (ToolChain::path_list::const_iterator 1192 it = List.begin(), ie = List.end(); it != ie; ++it) { 1193 llvm::sys::Path P(*it); 1194 P.appendComponent(Name); 1195 if (WantFile ? P.exists() : P.canExecute()) 1196 return P; 1197 } 1198 1199 // If all else failed, search the path. 1200 llvm::sys::Path P(llvm::sys::Program::FindProgramByName(Name)); 1201 if (!P.empty()) 1202 return P; 1203 1204 return llvm::sys::Path(Name); 1205} 1206 1207std::string Driver::GetTemporaryPath(const char *Suffix) const { 1208 // FIXME: This is lame; sys::Path should provide this function (in 1209 // particular, it should know how to find the temporary files dir). 1210 std::string Error; 1211 const char *TmpDir = ::getenv("TMPDIR"); 1212 if (!TmpDir) 1213 TmpDir = ::getenv("TEMP"); 1214 if (!TmpDir) 1215 TmpDir = ::getenv("TMP"); 1216 if (!TmpDir) 1217 TmpDir = "/tmp"; 1218 llvm::sys::Path P(TmpDir); 1219 P.appendComponent("cc"); 1220 if (P.makeUnique(false, &Error)) { 1221 Diag(clang::diag::err_drv_unable_to_make_temp) << Error; 1222 return ""; 1223 } 1224 1225 // FIXME: Grumble, makeUnique sometimes leaves the file around!? 1226 // PR3837. 1227 P.eraseFromDisk(false, 0); 1228 1229 P.appendSuffix(Suffix); 1230 return P.toString(); 1231} 1232 1233const HostInfo *Driver::GetHostInfo(const char *TripleStr) const { 1234 llvm::PrettyStackTraceString CrashInfo("Constructing host"); 1235 llvm::Triple Triple(TripleStr); 1236 1237 // Normalize Arch a bit. 1238 // 1239 // FIXME: We shouldn't need to do this once everything goes through the triple 1240 // interface. 1241 if (Triple.getArchName() == "i686") 1242 Triple.setArchName("i386"); 1243 else if (Triple.getArchName() == "amd64") 1244 Triple.setArchName("x86_64"); 1245 else if (Triple.getArchName() == "ppc" || 1246 Triple.getArchName() == "Power Macintosh") 1247 Triple.setArchName("powerpc"); 1248 else if (Triple.getArchName() == "ppc64") 1249 Triple.setArchName("powerpc64"); 1250 1251 switch (Triple.getOS()) { 1252 case llvm::Triple::Darwin: 1253 return createDarwinHostInfo(*this, Triple); 1254 case llvm::Triple::DragonFly: 1255 return createDragonFlyHostInfo(*this, Triple); 1256 case llvm::Triple::OpenBSD: 1257 return createOpenBSDHostInfo(*this, Triple); 1258 case llvm::Triple::FreeBSD: 1259 return createFreeBSDHostInfo(*this, Triple); 1260 case llvm::Triple::Linux: 1261 return createLinuxHostInfo(*this, Triple); 1262 default: 1263 return createUnknownHostInfo(*this, Triple); 1264 } 1265} 1266 1267bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA, 1268 const std::string &ArchNameStr) const { 1269 // FIXME: Remove this hack. 1270 const char *ArchName = ArchNameStr.c_str(); 1271 if (ArchNameStr == "powerpc") 1272 ArchName = "ppc"; 1273 else if (ArchNameStr == "powerpc64") 1274 ArchName = "ppc64"; 1275 1276 // Check if user requested no clang, or clang doesn't understand 1277 // this type (we only handle single inputs for now). 1278 if (!CCCUseClang || JA.size() != 1 || 1279 !types::isAcceptedByClang((*JA.begin())->getType())) 1280 return false; 1281 1282 // Otherwise make sure this is an action clang understands. 1283 if (isa<PreprocessJobAction>(JA)) { 1284 if (!CCCUseClangCPP) { 1285 Diag(clang::diag::warn_drv_not_using_clang_cpp); 1286 return false; 1287 } 1288 } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA)) 1289 return false; 1290 1291 // Use clang for C++? 1292 if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) { 1293 Diag(clang::diag::warn_drv_not_using_clang_cxx); 1294 return false; 1295 } 1296 1297 // Always use clang for precompiling, regardless of archs. PTH is 1298 // platform independent, and this allows the use of the static 1299 // analyzer on platforms we don't have full IRgen support for. 1300 if (isa<PrecompileJobAction>(JA)) 1301 return true; 1302 1303 // Finally, don't use clang if this isn't one of the user specified 1304 // archs to build. 1305 if (!CCCClangArchs.empty() && !CCCClangArchs.count(ArchName)) { 1306 Diag(clang::diag::warn_drv_not_using_clang_arch) << ArchName; 1307 return false; 1308 } 1309 1310 return true; 1311} 1312 1313/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and 1314/// return the grouped values as integers. Numbers which are not 1315/// provided are set to 0. 1316/// 1317/// \return True if the entire string was parsed (9.2), or all groups 1318/// were parsed (10.3.5extrastuff). 1319bool Driver::GetReleaseVersion(const char *Str, unsigned &Major, 1320 unsigned &Minor, unsigned &Micro, 1321 bool &HadExtra) { 1322 HadExtra = false; 1323 1324 Major = Minor = Micro = 0; 1325 if (*Str == '\0') 1326 return true; 1327 1328 char *End; 1329 Major = (unsigned) strtol(Str, &End, 10); 1330 if (*Str != '\0' && *End == '\0') 1331 return true; 1332 if (*End != '.') 1333 return false; 1334 1335 Str = End+1; 1336 Minor = (unsigned) strtol(Str, &End, 10); 1337 if (*Str != '\0' && *End == '\0') 1338 return true; 1339 if (*End != '.') 1340 return false; 1341 1342 Str = End+1; 1343 Micro = (unsigned) strtol(Str, &End, 10); 1344 if (*Str != '\0' && *End == '\0') 1345 return true; 1346 if (Str == End) 1347 return false; 1348 HadExtra = true; 1349 return true; 1350} 1351