Convert more tools code from cerr and cout to errs() and outs().

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@76070 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Dan Gohman 2009-07-16 15:30:09 +00:00
parent ad60f660c6
commit ac95cc79ac
21 changed files with 278 additions and 285 deletions

View File

@ -25,7 +25,6 @@
#include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/SourceMgr.h" #include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h" #include "llvm/Support/raw_ostream.h"
#include <iostream>
#include <memory> #include <memory>
using namespace llvm; using namespace llvm;
@ -107,14 +106,14 @@ bool BugDriver::addSources(const std::vector<std::string> &Filenames) {
if (Program == 0) return true; if (Program == 0) return true;
if (!run_as_child) if (!run_as_child)
std::cout << "Read input file : '" << Filenames[0] << "'\n"; outs() << "Read input file : '" << Filenames[0] << "'\n";
for (unsigned i = 1, e = Filenames.size(); i != e; ++i) { for (unsigned i = 1, e = Filenames.size(); i != e; ++i) {
std::auto_ptr<Module> M(ParseInputFile(Filenames[i], Context)); std::auto_ptr<Module> M(ParseInputFile(Filenames[i], Context));
if (M.get() == 0) return true; if (M.get() == 0) return true;
if (!run_as_child) if (!run_as_child)
std::cout << "Linking in input file: '" << Filenames[i] << "'\n"; outs() << "Linking in input file: '" << Filenames[i] << "'\n";
std::string ErrorMessage; std::string ErrorMessage;
if (Linker::LinkModules(Program, M.get(), &ErrorMessage)) { if (Linker::LinkModules(Program, M.get(), &ErrorMessage)) {
errs() << ToolName << ": error linking in '" << Filenames[i] << "': " errs() << ToolName << ": error linking in '" << Filenames[i] << "': "
@ -128,7 +127,7 @@ bool BugDriver::addSources(const std::vector<std::string> &Filenames) {
} }
if (!run_as_child) if (!run_as_child)
std::cout << "*** All input ok\n"; outs() << "*** All input ok\n";
// All input files read successfully! // All input files read successfully!
return false; return false;
@ -162,7 +161,7 @@ bool BugDriver::run() {
// file, then we know the compiler didn't crash, so try to diagnose a // file, then we know the compiler didn't crash, so try to diagnose a
// miscompilation. // miscompilation.
if (!PassesToRun.empty()) { if (!PassesToRun.empty()) {
std::cout << "Running selected passes on program to test for crash: "; outs() << "Running selected passes on program to test for crash: ";
if (runPasses(PassesToRun)) if (runPasses(PassesToRun))
return debugOptimizerCrash(); return debugOptimizerCrash();
} }
@ -171,12 +170,12 @@ bool BugDriver::run() {
if (initializeExecutionEnvironment()) return true; if (initializeExecutionEnvironment()) return true;
// Test to see if we have a code generator crash. // Test to see if we have a code generator crash.
std::cout << "Running the code generator to test for a crash: "; outs() << "Running the code generator to test for a crash: ";
try { try {
compileProgram(Program); compileProgram(Program);
std::cout << '\n'; outs() << '\n';
} catch (ToolExecutionError &TEE) { } catch (ToolExecutionError &TEE) {
std::cout << TEE.what(); outs() << TEE.what();
return debugCodeGeneratorCrash(); return debugCodeGeneratorCrash();
} }
@ -187,7 +186,7 @@ bool BugDriver::run() {
// //
bool CreatedOutput = false; bool CreatedOutput = false;
if (ReferenceOutputFile.empty()) { if (ReferenceOutputFile.empty()) {
std::cout << "Generating reference output from raw program: "; outs() << "Generating reference output from raw program: ";
if(!createReferenceFile(Program)){ if(!createReferenceFile(Program)){
return debugCodeGeneratorCrash(); return debugCodeGeneratorCrash();
} }
@ -202,10 +201,10 @@ bool BugDriver::run() {
// Diff the output of the raw program against the reference output. If it // Diff the output of the raw program against the reference output. If it
// matches, then we assume there is a miscompilation bug and try to // matches, then we assume there is a miscompilation bug and try to
// diagnose it. // diagnose it.
std::cout << "*** Checking the code generator...\n"; outs() << "*** Checking the code generator...\n";
try { try {
if (!diffProgram()) { if (!diffProgram()) {
std::cout << "\n*** Output matches: Debugging miscompilation!\n"; outs() << "\n*** Output matches: Debugging miscompilation!\n";
return debugMiscompilation(); return debugMiscompilation();
} }
} catch (ToolExecutionError &TEE) { } catch (ToolExecutionError &TEE) {
@ -213,8 +212,8 @@ bool BugDriver::run() {
return debugCodeGeneratorCrash(); return debugCodeGeneratorCrash();
} }
std::cout << "\n*** Input program does not match reference diff!\n"; outs() << "\n*** Input program does not match reference diff!\n";
std::cout << "Debugging code generator problem!\n"; outs() << "Debugging code generator problem!\n";
try { try {
return debugCodeGenerator(); return debugCodeGenerator();
} catch (ToolExecutionError &TEE) { } catch (ToolExecutionError &TEE) {
@ -227,18 +226,18 @@ void llvm::PrintFunctionList(const std::vector<Function*> &Funcs) {
unsigned NumPrint = Funcs.size(); unsigned NumPrint = Funcs.size();
if (NumPrint > 10) NumPrint = 10; if (NumPrint > 10) NumPrint = 10;
for (unsigned i = 0; i != NumPrint; ++i) for (unsigned i = 0; i != NumPrint; ++i)
std::cout << " " << Funcs[i]->getName(); outs() << " " << Funcs[i]->getName();
if (NumPrint < Funcs.size()) if (NumPrint < Funcs.size())
std::cout << "... <" << Funcs.size() << " total>"; outs() << "... <" << Funcs.size() << " total>";
std::cout << std::flush; outs().flush();
} }
void llvm::PrintGlobalVariableList(const std::vector<GlobalVariable*> &GVs) { void llvm::PrintGlobalVariableList(const std::vector<GlobalVariable*> &GVs) {
unsigned NumPrint = GVs.size(); unsigned NumPrint = GVs.size();
if (NumPrint > 10) NumPrint = 10; if (NumPrint > 10) NumPrint = 10;
for (unsigned i = 0; i != NumPrint; ++i) for (unsigned i = 0; i != NumPrint; ++i)
std::cout << " " << GVs[i]->getName(); outs() << " " << GVs[i]->getName();
if (NumPrint < GVs.size()) if (NumPrint < GVs.size())
std::cout << "... <" << GVs.size() << " total>"; outs() << "... <" << GVs.size() << " total>";
std::cout << std::flush; outs().flush();
} }

View File

@ -248,7 +248,7 @@ public:
/// optimizations fail for some reason (optimizer crashes), return true, /// optimizations fail for some reason (optimizer crashes), return true,
/// otherwise return false. If DeleteOutput is set to true, the bitcode is /// otherwise return false. If DeleteOutput is set to true, the bitcode is
/// deleted on success, and the filename string is undefined. This prints to /// deleted on success, and the filename string is undefined. This prints to
/// cout a single line message indicating whether compilation was successful /// outs() a single line message indicating whether compilation was successful
/// or failed, unless Quiet is set. ExtraArgs specifies additional arguments /// or failed, unless Quiet is set. ExtraArgs specifies additional arguments
/// to pass to the child bugpoint instance. /// to pass to the child bugpoint instance.
/// ///

View File

@ -28,8 +28,6 @@
#include "llvm/Transforms/Utils/Cloning.h" #include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Support/FileUtilities.h" #include "llvm/Support/FileUtilities.h"
#include "llvm/Support/CommandLine.h" #include "llvm/Support/CommandLine.h"
#include <iostream>
#include <fstream>
#include <set> #include <set>
using namespace llvm; using namespace llvm;
@ -65,8 +63,8 @@ ReducePassList::doTest(std::vector<const PassInfo*> &Prefix,
sys::Path PrefixOutput; sys::Path PrefixOutput;
Module *OrigProgram = 0; Module *OrigProgram = 0;
if (!Prefix.empty()) { if (!Prefix.empty()) {
std::cout << "Checking to see if these passes crash: " outs() << "Checking to see if these passes crash: "
<< getPassesString(Prefix) << ": "; << getPassesString(Prefix) << ": ";
std::string PfxOutput; std::string PfxOutput;
if (BD.runPasses(Prefix, PfxOutput)) if (BD.runPasses(Prefix, PfxOutput))
return KeepPrefix; return KeepPrefix;
@ -83,8 +81,8 @@ ReducePassList::doTest(std::vector<const PassInfo*> &Prefix,
PrefixOutput.eraseFromDisk(); PrefixOutput.eraseFromDisk();
} }
std::cout << "Checking to see if these passes crash: " outs() << "Checking to see if these passes crash: "
<< getPassesString(Suffix) << ": "; << getPassesString(Suffix) << ": ";
if (BD.runPasses(Suffix)) { if (BD.runPasses(Suffix)) {
delete OrigProgram; // The suffix crashes alone... delete OrigProgram; // The suffix crashes alone...
@ -143,9 +141,9 @@ ReduceCrashingGlobalVariables::TestGlobalVariables(
GVSet.insert(CMGV); GVSet.insert(CMGV);
} }
std::cout << "Checking for crash with only these global variables: "; outs() << "Checking for crash with only these global variables: ";
PrintGlobalVariableList(GVs); PrintGlobalVariableList(GVs);
std::cout << ": "; outs() << ": ";
// Loop over and delete any global variables which we aren't supposed to be // Loop over and delete any global variables which we aren't supposed to be
// playing with... // playing with...
@ -217,9 +215,9 @@ bool ReduceCrashingFunctions::TestFuncs(std::vector<Function*> &Funcs) {
Functions.insert(CMF); Functions.insert(CMF);
} }
std::cout << "Checking for crash with only these functions: "; outs() << "Checking for crash with only these functions: ";
PrintFunctionList(Funcs); PrintFunctionList(Funcs);
std::cout << ": "; outs() << ": ";
// Loop over and delete any functions which we aren't supposed to be playing // Loop over and delete any functions which we aren't supposed to be playing
// with... // with...
@ -277,14 +275,14 @@ bool ReduceCrashingBlocks::TestBlocks(std::vector<const BasicBlock*> &BBs) {
for (unsigned i = 0, e = BBs.size(); i != e; ++i) for (unsigned i = 0, e = BBs.size(); i != e; ++i)
Blocks.insert(cast<BasicBlock>(ValueMap[BBs[i]])); Blocks.insert(cast<BasicBlock>(ValueMap[BBs[i]]));
std::cout << "Checking for crash with only these blocks:"; outs() << "Checking for crash with only these blocks:";
unsigned NumPrint = Blocks.size(); unsigned NumPrint = Blocks.size();
if (NumPrint > 10) NumPrint = 10; if (NumPrint > 10) NumPrint = 10;
for (unsigned i = 0, e = NumPrint; i != e; ++i) for (unsigned i = 0, e = NumPrint; i != e; ++i)
std::cout << " " << BBs[i]->getName(); outs() << " " << BBs[i]->getName();
if (NumPrint < Blocks.size()) if (NumPrint < Blocks.size())
std::cout << "... <" << Blocks.size() << " total>"; outs() << "... <" << Blocks.size() << " total>";
std::cout << ": "; outs() << ": ";
// Loop over and delete any hack up any blocks that are not listed... // Loop over and delete any hack up any blocks that are not listed...
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
@ -382,11 +380,11 @@ bool ReduceCrashingInstructions::TestInsts(std::vector<const Instruction*>
Instructions.insert(cast<Instruction>(ValueMap[Insts[i]])); Instructions.insert(cast<Instruction>(ValueMap[Insts[i]]));
} }
std::cout << "Checking for crash with only " << Instructions.size(); outs() << "Checking for crash with only " << Instructions.size();
if (Instructions.size() == 1) if (Instructions.size() == 1)
std::cout << " instruction: "; outs() << " instruction: ";
else else
std::cout << " instructions: "; outs() << " instructions: ";
for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI) for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
@ -445,13 +443,13 @@ static bool DebugACrash(BugDriver &BD, bool (*TestFn)(BugDriver &, Module *)) {
delete M; // No change made... delete M; // No change made...
} else { } else {
// See if the program still causes a crash... // See if the program still causes a crash...
std::cout << "\nChecking to see if we can delete global inits: "; outs() << "\nChecking to see if we can delete global inits: ";
if (TestFn(BD, M)) { // Still crashes? if (TestFn(BD, M)) { // Still crashes?
BD.setNewProgram(M); BD.setNewProgram(M);
std::cout << "\n*** Able to remove all global initializers!\n"; outs() << "\n*** Able to remove all global initializers!\n";
} else { // No longer crashes? } else { // No longer crashes?
std::cout << " - Removing all global inits hides problem!\n"; outs() << " - Removing all global inits hides problem!\n";
delete M; delete M;
std::vector<GlobalVariable*> GVs; std::vector<GlobalVariable*> GVs;
@ -462,7 +460,7 @@ static bool DebugACrash(BugDriver &BD, bool (*TestFn)(BugDriver &, Module *)) {
GVs.push_back(I); GVs.push_back(I);
if (GVs.size() > 1 && !BugpointIsInterrupted) { if (GVs.size() > 1 && !BugpointIsInterrupted) {
std::cout << "\n*** Attempting to reduce the number of global " outs() << "\n*** Attempting to reduce the number of global "
<< "variables in the testcase\n"; << "variables in the testcase\n";
unsigned OldSize = GVs.size(); unsigned OldSize = GVs.size();
@ -483,7 +481,7 @@ static bool DebugACrash(BugDriver &BD, bool (*TestFn)(BugDriver &, Module *)) {
Functions.push_back(I); Functions.push_back(I);
if (Functions.size() > 1 && !BugpointIsInterrupted) { if (Functions.size() > 1 && !BugpointIsInterrupted) {
std::cout << "\n*** Attempting to reduce the number of functions " outs() << "\n*** Attempting to reduce the number of functions "
"in the testcase\n"; "in the testcase\n";
unsigned OldSize = Functions.size(); unsigned OldSize = Functions.size();
@ -532,8 +530,8 @@ static bool DebugACrash(BugDriver &BD, bool (*TestFn)(BugDriver &, Module *)) {
do { do {
if (BugpointIsInterrupted) break; if (BugpointIsInterrupted) break;
--Simplification; --Simplification;
std::cout << "\n*** Attempting to reduce testcase by deleting instruc" outs() << "\n*** Attempting to reduce testcase by deleting instruc"
<< "tions: Simplification Level #" << Simplification << '\n'; << "tions: Simplification Level #" << Simplification << '\n';
// Now that we have deleted the functions that are unnecessary for the // Now that we have deleted the functions that are unnecessary for the
// program, try to remove instructions that are not necessary to cause the // program, try to remove instructions that are not necessary to cause the
@ -561,7 +559,7 @@ static bool DebugACrash(BugDriver &BD, bool (*TestFn)(BugDriver &, Module *)) {
} else { } else {
if (BugpointIsInterrupted) goto ExitLoops; if (BugpointIsInterrupted) goto ExitLoops;
std::cout << "Checking instruction: " << *I; outs() << "Checking instruction: " << *I;
Module *M = BD.deleteInstructionFromProgram(I, Simplification); Module *M = BD.deleteInstructionFromProgram(I, Simplification);
// Find out if the pass still crashes on this pass... // Find out if the pass still crashes on this pass...
@ -588,7 +586,7 @@ ExitLoops:
// Try to clean up the testcase by running funcresolve and globaldce... // Try to clean up the testcase by running funcresolve and globaldce...
if (!BugpointIsInterrupted) { if (!BugpointIsInterrupted) {
std::cout << "\n*** Attempting to perform final cleanups: "; outs() << "\n*** Attempting to perform final cleanups: ";
Module *M = CloneModule(BD.getProgram()); Module *M = CloneModule(BD.getProgram());
M = BD.performFinalCleanups(M, true); M = BD.performFinalCleanups(M, true);
@ -614,15 +612,15 @@ static bool TestForOptimizerCrash(BugDriver &BD, Module *M) {
/// out exactly which pass is crashing. /// out exactly which pass is crashing.
/// ///
bool BugDriver::debugOptimizerCrash(const std::string &ID) { bool BugDriver::debugOptimizerCrash(const std::string &ID) {
std::cout << "\n*** Debugging optimizer crash!\n"; outs() << "\n*** Debugging optimizer crash!\n";
// Reduce the list of passes which causes the optimizer to crash... // Reduce the list of passes which causes the optimizer to crash...
if (!BugpointIsInterrupted) if (!BugpointIsInterrupted)
ReducePassList(*this).reduceList(PassesToRun); ReducePassList(*this).reduceList(PassesToRun);
std::cout << "\n*** Found crashing pass" outs() << "\n*** Found crashing pass"
<< (PassesToRun.size() == 1 ? ": " : "es: ") << (PassesToRun.size() == 1 ? ": " : "es: ")
<< getPassesString(PassesToRun) << '\n'; << getPassesString(PassesToRun) << '\n';
EmitProgressBitcode(ID); EmitProgressBitcode(ID);

View File

@ -19,7 +19,6 @@
#include "llvm/Support/FileUtilities.h" #include "llvm/Support/FileUtilities.h"
#include "llvm/Support/SystemUtils.h" #include "llvm/Support/SystemUtils.h"
#include <fstream> #include <fstream>
#include <iostream>
using namespace llvm; using namespace llvm;
@ -126,7 +125,7 @@ namespace {
/// environment for executing LLVM programs. /// environment for executing LLVM programs.
/// ///
bool BugDriver::initializeExecutionEnvironment() { bool BugDriver::initializeExecutionEnvironment() {
std::cout << "Initializing execution environment: "; outs() << "Initializing execution environment: ";
// Create an instance of the AbstractInterpreter interface as specified on // Create an instance of the AbstractInterpreter interface as specified on
// the command line // the command line
@ -188,7 +187,7 @@ bool BugDriver::initializeExecutionEnvironment() {
if (!Interpreter) if (!Interpreter)
errs() << Message; errs() << Message;
else // Display informational messages on stdout instead of stderr else // Display informational messages on stdout instead of stderr
std::cout << Message; outs() << Message;
std::string Path = SafeInterpreterPath; std::string Path = SafeInterpreterPath;
if (Path.empty()) if (Path.empty())
@ -260,10 +259,10 @@ bool BugDriver::initializeExecutionEnvironment() {
"\"safe\" backend right now!\n"; "\"safe\" backend right now!\n";
break; break;
} }
if (!SafeInterpreter) { std::cout << Message << "\nExiting.\n"; exit(1); } if (!SafeInterpreter) { outs() << Message << "\nExiting.\n"; exit(1); }
gcc = GCC::create(getToolName(), Message, &GCCToolArgv); gcc = GCC::create(getToolName(), Message, &GCCToolArgv);
if (!gcc) { std::cout << Message << "\nExiting.\n"; exit(1); } if (!gcc) { outs() << Message << "\nExiting.\n"; exit(1); }
// If there was an error creating the selected interpreter, quit with error. // If there was an error creating the selected interpreter, quit with error.
return Interpreter == 0; return Interpreter == 0;
@ -355,7 +354,7 @@ std::string BugDriver::executeProgram(std::string OutputFile,
errs() << "<timeout>"; errs() << "<timeout>";
static bool FirstTimeout = true; static bool FirstTimeout = true;
if (FirstTimeout) { if (FirstTimeout) {
std::cout << "\n" outs() << "\n"
"*** Program execution timed out! This mechanism is designed to handle\n" "*** Program execution timed out! This mechanism is designed to handle\n"
" programs stuck in infinite loops gracefully. The -timeout option\n" " programs stuck in infinite loops gracefully. The -timeout option\n"
" can be used to change the timeout threshold or disable it completely\n" " can be used to change the timeout threshold or disable it completely\n"
@ -418,7 +417,7 @@ bool BugDriver::createReferenceFile(Module *M, const std::string &Filename) {
} }
try { try {
ReferenceOutputFile = executeProgramSafely(Filename); ReferenceOutputFile = executeProgramSafely(Filename);
std::cout << "\nReference output is: " << ReferenceOutputFile << "\n\n"; outs() << "\nReference output is: " << ReferenceOutputFile << "\n\n";
} catch (ToolExecutionError &TEE) { } catch (ToolExecutionError &TEE) {
errs() << TEE.what(); errs() << TEE.what();
if (Interpreter != SafeInterpreter) { if (Interpreter != SafeInterpreter) {

View File

@ -32,8 +32,6 @@
#include "llvm/System/Path.h" #include "llvm/System/Path.h"
#include "llvm/System/Signals.h" #include "llvm/System/Signals.h"
#include <set> #include <set>
#include <fstream>
#include <iostream>
using namespace llvm; using namespace llvm;
namespace llvm { namespace llvm {
@ -145,9 +143,9 @@ Module *BugDriver::ExtractLoop(Module *M) {
Module *NewM = runPassesOn(M, LoopExtractPasses); Module *NewM = runPassesOn(M, LoopExtractPasses);
if (NewM == 0) { if (NewM == 0) {
Module *Old = swapProgramIn(M); Module *Old = swapProgramIn(M);
std::cout << "*** Loop extraction failed: "; outs() << "*** Loop extraction failed: ";
EmitProgressBitcode("loopextraction", true); EmitProgressBitcode("loopextraction", true);
std::cout << "*** Sorry. :( Please report a bug!\n"; outs() << "*** Sorry. :( Please report a bug!\n";
swapProgramIn(Old); swapProgramIn(Old);
return 0; return 0;
} }
@ -327,7 +325,7 @@ Module *BugDriver::ExtractMappedBlocksFromModule(const
sys::Path uniqueFilename("bugpoint-extractblocks"); sys::Path uniqueFilename("bugpoint-extractblocks");
std::string ErrMsg; std::string ErrMsg;
if (uniqueFilename.createTemporaryFileOnDisk(true, &ErrMsg)) { if (uniqueFilename.createTemporaryFileOnDisk(true, &ErrMsg)) {
std::cout << "*** Basic Block extraction failed!\n"; outs() << "*** Basic Block extraction failed!\n";
errs() << "Error creating temporary file: " << ErrMsg << "\n"; errs() << "Error creating temporary file: " << ErrMsg << "\n";
M = swapProgramIn(M); M = swapProgramIn(M);
EmitProgressBitcode("basicblockextractfail", true); EmitProgressBitcode("basicblockextractfail", true);
@ -336,10 +334,13 @@ Module *BugDriver::ExtractMappedBlocksFromModule(const
} }
sys::RemoveFileOnSignal(uniqueFilename); sys::RemoveFileOnSignal(uniqueFilename);
std::ofstream BlocksToNotExtractFile(uniqueFilename.c_str()); std::string ErrorInfo;
if (!BlocksToNotExtractFile) { raw_fd_ostream BlocksToNotExtractFile(uniqueFilename.c_str(),
std::cout << "*** Basic Block extraction failed!\n"; /*Binary=*/false, /*Force=*/true,
errs() << "Error writing list of blocks to not extract: " << ErrMsg ErrorInfo);
if (!ErrorInfo.empty()) {
outs() << "*** Basic Block extraction failed!\n";
errs() << "Error writing list of blocks to not extract: " << ErrorInfo
<< "\n"; << "\n";
M = swapProgramIn(M); M = swapProgramIn(M);
EmitProgressBitcode("basicblockextractfail", true); EmitProgressBitcode("basicblockextractfail", true);
@ -371,7 +372,7 @@ Module *BugDriver::ExtractMappedBlocksFromModule(const
free(ExtraArg); free(ExtraArg);
if (Ret == 0) { if (Ret == 0) {
std::cout << "*** Basic Block extraction failed, please report a bug!\n"; outs() << "*** Basic Block extraction failed, please report a bug!\n";
M = swapProgramIn(M); M = swapProgramIn(M);
EmitProgressBitcode("basicblockextractfail", true); EmitProgressBitcode("basicblockextractfail", true);
swapProgramIn(M); swapProgramIn(M);

View File

@ -19,7 +19,6 @@
#include "llvm/Pass.h" #include "llvm/Pass.h"
#include <algorithm> #include <algorithm>
#include <ctime> #include <ctime>
#include <iostream>
using namespace llvm; using namespace llvm;
/// runManyPasses - Take the specified pass list and create different /// runManyPasses - Take the specified pass list and create different
@ -31,14 +30,14 @@ using namespace llvm;
/// ///
bool BugDriver::runManyPasses(const std::vector<const PassInfo*> &AllPasses) { bool BugDriver::runManyPasses(const std::vector<const PassInfo*> &AllPasses) {
setPassesToRun(AllPasses); setPassesToRun(AllPasses);
std::cout << "Starting bug finding procedure...\n\n"; outs() << "Starting bug finding procedure...\n\n";
// Creating a reference output if necessary // Creating a reference output if necessary
if (initializeExecutionEnvironment()) return false; if (initializeExecutionEnvironment()) return false;
std::cout << "\n"; outs() << "\n";
if (ReferenceOutputFile.empty()) { if (ReferenceOutputFile.empty()) {
std::cout << "Generating reference output from raw program: \n"; outs() << "Generating reference output from raw program: \n";
if (!createReferenceFile(Program)) if (!createReferenceFile(Program))
return false; return false;
} }
@ -55,31 +54,31 @@ bool BugDriver::runManyPasses(const std::vector<const PassInfo*> &AllPasses) {
// //
// Step 2: Run optimizer passes on the program and check for success. // Step 2: Run optimizer passes on the program and check for success.
// //
std::cout << "Running selected passes on program to test for crash: "; outs() << "Running selected passes on program to test for crash: ";
for(int i = 0, e = PassesToRun.size(); i != e; i++) { for(int i = 0, e = PassesToRun.size(); i != e; i++) {
std::cout << "-" << PassesToRun[i]->getPassArgument( )<< " "; outs() << "-" << PassesToRun[i]->getPassArgument( )<< " ";
} }
std::string Filename; std::string Filename;
if(runPasses(PassesToRun, Filename, false)) { if(runPasses(PassesToRun, Filename, false)) {
std::cout << "\n"; outs() << "\n";
std::cout << "Optimizer passes caused failure!\n\n"; outs() << "Optimizer passes caused failure!\n\n";
debugOptimizerCrash(); debugOptimizerCrash();
return true; return true;
} else { } else {
std::cout << "Combination " << num << " optimized successfully!\n"; outs() << "Combination " << num << " optimized successfully!\n";
} }
// //
// Step 3: Compile the optimized code. // Step 3: Compile the optimized code.
// //
std::cout << "Running the code generator to test for a crash: "; outs() << "Running the code generator to test for a crash: ";
try { try {
compileProgram(Program); compileProgram(Program);
std::cout << '\n'; outs() << '\n';
} catch (ToolExecutionError &TEE) { } catch (ToolExecutionError &TEE) {
std::cout << "\n*** compileProgram threw an exception: "; outs() << "\n*** compileProgram threw an exception: ";
std::cout << TEE.what(); outs() << TEE.what();
return debugCodeGeneratorCrash(); return debugCodeGeneratorCrash();
} }
@ -87,14 +86,14 @@ bool BugDriver::runManyPasses(const std::vector<const PassInfo*> &AllPasses) {
// Step 4: Run the program and compare its output to the reference // Step 4: Run the program and compare its output to the reference
// output (created above). // output (created above).
// //
std::cout << "*** Checking if passes caused miscompliation:\n"; outs() << "*** Checking if passes caused miscompliation:\n";
try { try {
if (diffProgram(Filename, "", false)) { if (diffProgram(Filename, "", false)) {
std::cout << "\n*** diffProgram returned true!\n"; outs() << "\n*** diffProgram returned true!\n";
debugMiscompilation(); debugMiscompilation();
return true; return true;
} else { } else {
std::cout << "\n*** diff'd output matches!\n"; outs() << "\n*** diff'd output matches!\n";
} }
} catch (ToolExecutionError &TEE) { } catch (ToolExecutionError &TEE) {
errs() << TEE.what(); errs() << TEE.what();
@ -104,7 +103,7 @@ bool BugDriver::runManyPasses(const std::vector<const PassInfo*> &AllPasses) {
sys::Path(Filename).eraseFromDisk(); sys::Path(Filename).eraseFromDisk();
std::cout << "\n\n"; outs() << "\n\n";
num++; num++;
} //end while } //end while

View File

@ -26,7 +26,6 @@
#include "llvm/Support/CommandLine.h" #include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileUtilities.h" #include "llvm/Support/FileUtilities.h"
#include "llvm/Config/config.h" // for HAVE_LINK_R #include "llvm/Config/config.h" // for HAVE_LINK_R
#include <iostream>
using namespace llvm; using namespace llvm;
namespace llvm { namespace llvm {
@ -57,8 +56,8 @@ ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
std::vector<const PassInfo*> &Suffix) { std::vector<const PassInfo*> &Suffix) {
// First, run the program with just the Suffix passes. If it is still broken // First, run the program with just the Suffix passes. If it is still broken
// with JUST the kept passes, discard the prefix passes. // with JUST the kept passes, discard the prefix passes.
std::cout << "Checking to see if '" << getPassesString(Suffix) outs() << "Checking to see if '" << getPassesString(Suffix)
<< "' compiles correctly: "; << "' compiles correctly: ";
std::string BitcodeResult; std::string BitcodeResult;
if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) { if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
@ -71,7 +70,7 @@ ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
// Check to see if the finished program matches the reference output... // Check to see if the finished program matches the reference output...
if (BD.diffProgram(BitcodeResult, "", true /*delete bitcode*/)) { if (BD.diffProgram(BitcodeResult, "", true /*delete bitcode*/)) {
std::cout << " nope.\n"; outs() << " nope.\n";
if (Suffix.empty()) { if (Suffix.empty()) {
errs() << BD.getToolName() << ": I'm confused: the test fails when " errs() << BD.getToolName() << ": I'm confused: the test fails when "
<< "no passes are run, nondeterministic program?\n"; << "no passes are run, nondeterministic program?\n";
@ -79,14 +78,14 @@ ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
} }
return KeepSuffix; // Miscompilation detected! return KeepSuffix; // Miscompilation detected!
} }
std::cout << " yup.\n"; // No miscompilation! outs() << " yup.\n"; // No miscompilation!
if (Prefix.empty()) return NoFailure; if (Prefix.empty()) return NoFailure;
// Next, see if the program is broken if we run the "prefix" passes first, // Next, see if the program is broken if we run the "prefix" passes first,
// then separately run the "kept" passes. // then separately run the "kept" passes.
std::cout << "Checking to see if '" << getPassesString(Prefix) outs() << "Checking to see if '" << getPassesString(Prefix)
<< "' compiles correctly: "; << "' compiles correctly: ";
// If it is not broken with the kept passes, it's possible that the prefix // If it is not broken with the kept passes, it's possible that the prefix
// passes must be run before the kept passes to break it. If the program // passes must be run before the kept passes to break it. If the program
@ -104,11 +103,11 @@ ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
// If the prefix maintains the predicate by itself, only keep the prefix! // If the prefix maintains the predicate by itself, only keep the prefix!
if (BD.diffProgram(BitcodeResult)) { if (BD.diffProgram(BitcodeResult)) {
std::cout << " nope.\n"; outs() << " nope.\n";
sys::Path(BitcodeResult).eraseFromDisk(); sys::Path(BitcodeResult).eraseFromDisk();
return KeepPrefix; return KeepPrefix;
} }
std::cout << " yup.\n"; // No miscompilation! outs() << " yup.\n"; // No miscompilation!
// Ok, so now we know that the prefix passes work, try running the suffix // Ok, so now we know that the prefix passes work, try running the suffix
// passes on the result of the prefix passes. // passes on the result of the prefix passes.
@ -125,7 +124,7 @@ ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
if (Suffix.empty()) if (Suffix.empty())
return NoFailure; return NoFailure;
std::cout << "Checking to see if '" << getPassesString(Suffix) outs() << "Checking to see if '" << getPassesString(Suffix)
<< "' passes compile correctly after the '" << "' passes compile correctly after the '"
<< getPassesString(Prefix) << "' passes: "; << getPassesString(Prefix) << "' passes: ";
@ -140,13 +139,13 @@ ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
// Run the result... // Run the result...
if (BD.diffProgram(BitcodeResult, "", true/*delete bitcode*/)) { if (BD.diffProgram(BitcodeResult, "", true/*delete bitcode*/)) {
std::cout << " nope.\n"; outs() << " nope.\n";
delete OriginalInput; // We pruned down the original input... delete OriginalInput; // We pruned down the original input...
return KeepSuffix; return KeepSuffix;
} }
// Otherwise, we must not be running the bad pass anymore. // Otherwise, we must not be running the bad pass anymore.
std::cout << " yup.\n"; // No miscompilation! outs() << " yup.\n"; // No miscompilation!
delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test
return NoFailure; return NoFailure;
} }
@ -213,12 +212,12 @@ static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){ bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
// Test to see if the function is misoptimized if we ONLY run it on the // Test to see if the function is misoptimized if we ONLY run it on the
// functions listed in Funcs. // functions listed in Funcs.
std::cout << "Checking to see if the program is misoptimized when " outs() << "Checking to see if the program is misoptimized when "
<< (Funcs.size()==1 ? "this function is" : "these functions are") << (Funcs.size()==1 ? "this function is" : "these functions are")
<< " run through the pass" << " run through the pass"
<< (BD.getPassesToRun().size() == 1 ? "" : "es") << ":"; << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
PrintFunctionList(Funcs); PrintFunctionList(Funcs);
std::cout << '\n'; outs() << '\n';
// Split the module into the two halves of the program we want. // Split the module into the two halves of the program we want.
DenseMap<const Value*, Value*> ValueMap; DenseMap<const Value*, Value*> ValueMap;
@ -310,12 +309,12 @@ static bool ExtractLoops(BugDriver &BD,
delete ToOptimize; delete ToOptimize;
BD.switchToInterpreter(AI); BD.switchToInterpreter(AI);
std::cout << " Testing after loop extraction:\n"; outs() << " Testing after loop extraction:\n";
// Clone modules, the tester function will free them. // Clone modules, the tester function will free them.
Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted); Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
Module *TNOBackup = CloneModule(ToNotOptimize); Module *TNOBackup = CloneModule(ToNotOptimize);
if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) { if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
std::cout << "*** Loop extraction masked the problem. Undoing.\n"; outs() << "*** Loop extraction masked the problem. Undoing.\n";
// If the program is not still broken, then loop extraction did something // If the program is not still broken, then loop extraction did something
// that masked the error. Stop loop extraction now. // that masked the error. Stop loop extraction now.
delete TOLEBackup; delete TOLEBackup;
@ -325,7 +324,7 @@ static bool ExtractLoops(BugDriver &BD,
ToOptimizeLoopExtracted = TOLEBackup; ToOptimizeLoopExtracted = TOLEBackup;
ToNotOptimize = TNOBackup; ToNotOptimize = TNOBackup;
std::cout << "*** Loop extraction successful!\n"; outs() << "*** Loop extraction successful!\n";
std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions; std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
for (Module::iterator I = ToOptimizeLoopExtracted->begin(), for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
@ -394,16 +393,16 @@ namespace {
bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) { bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) {
// Test to see if the function is misoptimized if we ONLY run it on the // Test to see if the function is misoptimized if we ONLY run it on the
// functions listed in Funcs. // functions listed in Funcs.
std::cout << "Checking to see if the program is misoptimized when all "; outs() << "Checking to see if the program is misoptimized when all ";
if (!BBs.empty()) { if (!BBs.empty()) {
std::cout << "but these " << BBs.size() << " blocks are extracted: "; outs() << "but these " << BBs.size() << " blocks are extracted: ";
for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i) for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
std::cout << BBs[i]->getName() << " "; outs() << BBs[i]->getName() << " ";
if (BBs.size() > 10) std::cout << "..."; if (BBs.size() > 10) outs() << "...";
} else { } else {
std::cout << "blocks are extracted."; outs() << "blocks are extracted.";
} }
std::cout << '\n'; outs() << '\n';
// Split the module into the two halves of the program we want. // Split the module into the two halves of the program we want.
DenseMap<const Value*, Value*> ValueMap; DenseMap<const Value*, Value*> ValueMap;
@ -526,11 +525,11 @@ DebugAMiscompilation(BugDriver &BD,
if (!BugpointIsInterrupted) if (!BugpointIsInterrupted)
ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions); ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
std::cout << "\n*** The following function" outs() << "\n*** The following function"
<< (MiscompiledFunctions.size() == 1 ? " is" : "s are") << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
<< " being miscompiled: "; << " being miscompiled: ";
PrintFunctionList(MiscompiledFunctions); PrintFunctionList(MiscompiledFunctions);
std::cout << '\n'; outs() << '\n';
// See if we can rip any loops out of the miscompiled functions and still // See if we can rip any loops out of the miscompiled functions and still
// trigger the problem. // trigger the problem.
@ -549,11 +548,11 @@ DebugAMiscompilation(BugDriver &BD,
if (!BugpointIsInterrupted) if (!BugpointIsInterrupted)
ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions); ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
std::cout << "\n*** The following function" outs() << "\n*** The following function"
<< (MiscompiledFunctions.size() == 1 ? " is" : "s are") << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
<< " being miscompiled: "; << " being miscompiled: ";
PrintFunctionList(MiscompiledFunctions); PrintFunctionList(MiscompiledFunctions);
std::cout << '\n'; outs() << '\n';
} }
if (!BugpointIsInterrupted && if (!BugpointIsInterrupted &&
@ -569,11 +568,11 @@ DebugAMiscompilation(BugDriver &BD,
// Do the reduction... // Do the reduction...
ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions); ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
std::cout << "\n*** The following function" outs() << "\n*** The following function"
<< (MiscompiledFunctions.size() == 1 ? " is" : "s are") << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
<< " being miscompiled: "; << " being miscompiled: ";
PrintFunctionList(MiscompiledFunctions); PrintFunctionList(MiscompiledFunctions);
std::cout << '\n'; outs() << '\n';
} }
return MiscompiledFunctions; return MiscompiledFunctions;
@ -586,15 +585,15 @@ DebugAMiscompilation(BugDriver &BD,
static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) { static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
// Run the optimization passes on ToOptimize, producing a transformed version // Run the optimization passes on ToOptimize, producing a transformed version
// of the functions being tested. // of the functions being tested.
std::cout << " Optimizing functions being tested: "; outs() << " Optimizing functions being tested: ";
Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(), Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
/*AutoDebugCrashes*/true); /*AutoDebugCrashes*/true);
std::cout << "done.\n"; outs() << "done.\n";
delete Test; delete Test;
std::cout << " Checking to see if the merged program executes correctly: "; outs() << " Checking to see if the merged program executes correctly: ";
bool Broken = TestMergedProgram(BD, Optimized, Safe, true); bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
std::cout << (Broken ? " nope.\n" : " yup.\n"); outs() << (Broken ? " nope.\n" : " yup.\n");
return Broken; return Broken;
} }
@ -612,28 +611,28 @@ bool BugDriver::debugMiscompilation() {
return false; return false;
} }
std::cout << "\n*** Found miscompiling pass" outs() << "\n*** Found miscompiling pass"
<< (getPassesToRun().size() == 1 ? "" : "es") << ": " << (getPassesToRun().size() == 1 ? "" : "es") << ": "
<< getPassesString(getPassesToRun()) << '\n'; << getPassesString(getPassesToRun()) << '\n';
EmitProgressBitcode("passinput"); EmitProgressBitcode("passinput");
std::vector<Function*> MiscompiledFunctions = std::vector<Function*> MiscompiledFunctions =
DebugAMiscompilation(*this, TestOptimizer); DebugAMiscompilation(*this, TestOptimizer);
// Output a bunch of bitcode files for the user... // Output a bunch of bitcode files for the user...
std::cout << "Outputting reduced bitcode files which expose the problem:\n"; outs() << "Outputting reduced bitcode files which expose the problem:\n";
DenseMap<const Value*, Value*> ValueMap; DenseMap<const Value*, Value*> ValueMap;
Module *ToNotOptimize = CloneModule(getProgram(), ValueMap); Module *ToNotOptimize = CloneModule(getProgram(), ValueMap);
Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
MiscompiledFunctions, MiscompiledFunctions,
ValueMap); ValueMap);
std::cout << " Non-optimized portion: "; outs() << " Non-optimized portion: ";
ToNotOptimize = swapProgramIn(ToNotOptimize); ToNotOptimize = swapProgramIn(ToNotOptimize);
EmitProgressBitcode("tonotoptimize", true); EmitProgressBitcode("tonotoptimize", true);
setNewProgram(ToNotOptimize); // Delete hacked module. setNewProgram(ToNotOptimize); // Delete hacked module.
std::cout << " Portion that is input to optimizer: "; outs() << " Portion that is input to optimizer: ";
ToOptimize = swapProgramIn(ToOptimize); ToOptimize = swapProgramIn(ToOptimize);
EmitProgressBitcode("tooptimize"); EmitProgressBitcode("tooptimize");
setNewProgram(ToOptimize); // Delete hacked module. setNewProgram(ToOptimize); // Delete hacked module.
@ -860,14 +859,14 @@ static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
bool BugDriver::debugCodeGenerator() { bool BugDriver::debugCodeGenerator() {
if ((void*)SafeInterpreter == (void*)Interpreter) { if ((void*)SafeInterpreter == (void*)Interpreter) {
std::string Result = executeProgramSafely("bugpoint.safe.out"); std::string Result = executeProgramSafely("bugpoint.safe.out");
std::cout << "\n*** The \"safe\" i.e. 'known good' backend cannot match " outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
<< "the reference diff. This may be due to a\n front-end " << "the reference diff. This may be due to a\n front-end "
<< "bug or a bug in the original program, but this can also " << "bug or a bug in the original program, but this can also "
<< "happen if bugpoint isn't running the program with the " << "happen if bugpoint isn't running the program with the "
<< "right flags or input.\n I left the result of executing " << "right flags or input.\n I left the result of executing "
<< "the program with the \"safe\" backend in this file for " << "the program with the \"safe\" backend in this file for "
<< "you: '" << "you: '"
<< Result << "'.\n"; << Result << "'.\n";
return true; return true;
} }
@ -912,31 +911,31 @@ bool BugDriver::debugCodeGenerator() {
std::string SharedObject = compileSharedObject(SafeModuleBC.toString()); std::string SharedObject = compileSharedObject(SafeModuleBC.toString());
delete ToNotCodeGen; delete ToNotCodeGen;
std::cout << "You can reproduce the problem with the command line: \n"; outs() << "You can reproduce the problem with the command line: \n";
if (isExecutingJIT()) { if (isExecutingJIT()) {
std::cout << " lli -load " << SharedObject << " " << TestModuleBC; outs() << " lli -load " << SharedObject << " " << TestModuleBC;
} else { } else {
std::cout << " llc -f " << TestModuleBC << " -o " << TestModuleBC<< ".s\n"; outs() << " llc -f " << TestModuleBC << " -o " << TestModuleBC<< ".s\n";
std::cout << " gcc " << SharedObject << " " << TestModuleBC outs() << " gcc " << SharedObject << " " << TestModuleBC
<< ".s -o " << TestModuleBC << ".exe"; << ".s -o " << TestModuleBC << ".exe";
#if defined (HAVE_LINK_R) #if defined (HAVE_LINK_R)
std::cout << " -Wl,-R."; outs() << " -Wl,-R.";
#endif #endif
std::cout << "\n"; outs() << "\n";
std::cout << " " << TestModuleBC << ".exe"; outs() << " " << TestModuleBC << ".exe";
} }
for (unsigned i=0, e = InputArgv.size(); i != e; ++i) for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
std::cout << " " << InputArgv[i]; outs() << " " << InputArgv[i];
std::cout << '\n'; outs() << '\n';
std::cout << "The shared object was created with:\n llc -march=c " outs() << "The shared object was created with:\n llc -march=c "
<< SafeModuleBC << " -o temporary.c\n" << SafeModuleBC << " -o temporary.c\n"
<< " gcc -xc temporary.c -O2 -o " << SharedObject << " gcc -xc temporary.c -O2 -o " << SharedObject
#if defined(sparc) || defined(__sparc__) || defined(__sparcv9) #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
<< " -G" // Compile a shared library, `-G' for Sparc << " -G" // Compile a shared library, `-G' for Sparc
#else #else
<< " -fPIC -shared" // `-shared' for Linux/X86, maybe others << " -fPIC -shared" // `-shared' for Linux/X86, maybe others
#endif #endif
<< " -fno-strict-aliasing\n"; << " -fno-strict-aliasing\n";
return false; return false;
} }

View File

@ -27,7 +27,6 @@
#include "llvm/Target/TargetData.h" #include "llvm/Target/TargetData.h"
#include "llvm/Support/FileUtilities.h" #include "llvm/Support/FileUtilities.h"
#include "llvm/Support/CommandLine.h" #include "llvm/Support/CommandLine.h"
#include "llvm/Support/Streams.h"
#include "llvm/System/Path.h" #include "llvm/System/Path.h"
#include "llvm/System/Program.h" #include "llvm/System/Program.h"
#include "llvm/Config/alloca.h" #include "llvm/Config/alloca.h"
@ -71,15 +70,15 @@ void BugDriver::EmitProgressBitcode(const std::string &ID, bool NoFlyer) {
// //
std::string Filename = "bugpoint-" + ID + ".bc"; std::string Filename = "bugpoint-" + ID + ".bc";
if (writeProgramToFile(Filename)) { if (writeProgramToFile(Filename)) {
cerr << "Error opening file '" << Filename << "' for writing!\n"; errs() << "Error opening file '" << Filename << "' for writing!\n";
return; return;
} }
cout << "Emitted bitcode to '" << Filename << "'\n"; outs() << "Emitted bitcode to '" << Filename << "'\n";
if (NoFlyer || PassesToRun.empty()) return; if (NoFlyer || PassesToRun.empty()) return;
cout << "\n*** You can reproduce the problem with: "; outs() << "\n*** You can reproduce the problem with: ";
cout << "opt " << Filename << " "; outs() << "opt " << Filename << " ";
cout << getPassesString(PassesToRun) << "\n"; outs() << getPassesString(PassesToRun) << "\n";
} }
int BugDriver::runPassesAsChild(const std::vector<const PassInfo*> &Passes) { int BugDriver::runPassesAsChild(const std::vector<const PassInfo*> &Passes) {
@ -88,7 +87,7 @@ int BugDriver::runPassesAsChild(const std::vector<const PassInfo*> &Passes) {
std::ios::binary; std::ios::binary;
std::ofstream OutFile(ChildOutput.c_str(), io_mode); std::ofstream OutFile(ChildOutput.c_str(), io_mode);
if (!OutFile.good()) { if (!OutFile.good()) {
cerr << "Error opening bitcode file: " << ChildOutput << "\n"; errs() << "Error opening bitcode file: " << ChildOutput << "\n";
return 1; return 1;
} }
@ -100,7 +99,7 @@ int BugDriver::runPassesAsChild(const std::vector<const PassInfo*> &Passes) {
if (Passes[i]->getNormalCtor()) if (Passes[i]->getNormalCtor())
PM.add(Passes[i]->getNormalCtor()()); PM.add(Passes[i]->getNormalCtor()());
else else
cerr << "Cannot create pass yet: " << Passes[i]->getPassName() << "\n"; errs() << "Cannot create pass yet: " << Passes[i]->getPassName() << "\n";
} }
// Check that the module is well formed on completion of optimization // Check that the module is well formed on completion of optimization
PM.add(createVerifierPass()); PM.add(createVerifierPass());
@ -121,20 +120,20 @@ cl::opt<bool> SilencePasses("silence-passes", cl::desc("Suppress output of runni
/// optimizations fail for some reason (optimizer crashes), return true, /// optimizations fail for some reason (optimizer crashes), return true,
/// otherwise return false. If DeleteOutput is set to true, the bitcode is /// otherwise return false. If DeleteOutput is set to true, the bitcode is
/// deleted on success, and the filename string is undefined. This prints to /// deleted on success, and the filename string is undefined. This prints to
/// cout a single line message indicating whether compilation was successful or /// outs() a single line message indicating whether compilation was successful
/// failed. /// or failed.
/// ///
bool BugDriver::runPasses(const std::vector<const PassInfo*> &Passes, bool BugDriver::runPasses(const std::vector<const PassInfo*> &Passes,
std::string &OutputFilename, bool DeleteOutput, std::string &OutputFilename, bool DeleteOutput,
bool Quiet, unsigned NumExtraArgs, bool Quiet, unsigned NumExtraArgs,
const char * const *ExtraArgs) const { const char * const *ExtraArgs) const {
// setup the output file name // setup the output file name
cout << std::flush; outs().flush();
sys::Path uniqueFilename("bugpoint-output.bc"); sys::Path uniqueFilename("bugpoint-output.bc");
std::string ErrMsg; std::string ErrMsg;
if (uniqueFilename.makeUnique(true, &ErrMsg)) { if (uniqueFilename.makeUnique(true, &ErrMsg)) {
cerr << getToolName() << ": Error making unique filename: " errs() << getToolName() << ": Error making unique filename: "
<< ErrMsg << "\n"; << ErrMsg << "\n";
return(1); return(1);
} }
OutputFilename = uniqueFilename.toString(); OutputFilename = uniqueFilename.toString();
@ -142,15 +141,15 @@ bool BugDriver::runPasses(const std::vector<const PassInfo*> &Passes,
// set up the input file name // set up the input file name
sys::Path inputFilename("bugpoint-input.bc"); sys::Path inputFilename("bugpoint-input.bc");
if (inputFilename.makeUnique(true, &ErrMsg)) { if (inputFilename.makeUnique(true, &ErrMsg)) {
cerr << getToolName() << ": Error making unique filename: " errs() << getToolName() << ": Error making unique filename: "
<< ErrMsg << "\n"; << ErrMsg << "\n";
return(1); return(1);
} }
std::ios::openmode io_mode = std::ios::out | std::ios::trunc | std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
std::ios::binary; std::ios::binary;
std::ofstream InFile(inputFilename.c_str(), io_mode); std::ofstream InFile(inputFilename.c_str(), io_mode);
if (!InFile.good()) { if (!InFile.good()) {
cerr << "Error opening bitcode file: " << inputFilename << "\n"; errs() << "Error opening bitcode file: " << inputFilename << "\n";
return(1); return(1);
} }
WriteBitcodeToFile(Program, InFile); WriteBitcodeToFile(Program, InFile);
@ -212,17 +211,17 @@ bool BugDriver::runPasses(const std::vector<const PassInfo*> &Passes,
if (!Quiet) { if (!Quiet) {
if (result == 0) if (result == 0)
cout << "Success!\n"; outs() << "Success!\n";
else if (result > 0) else if (result > 0)
cout << "Exited with error code '" << result << "'\n"; outs() << "Exited with error code '" << result << "'\n";
else if (result < 0) { else if (result < 0) {
if (result == -1) if (result == -1)
cout << "Execute failed: " << ErrMsg << "\n"; outs() << "Execute failed: " << ErrMsg << "\n";
else else
cout << "Crashed with signal #" << abs(result) << "\n"; outs() << "Crashed with signal #" << abs(result) << "\n";
} }
if (result & 0x01000000) if (result & 0x01000000)
cout << "Dumped core\n"; outs() << "Dumped core\n";
} }
// Was the child successful? // Was the child successful?
@ -242,8 +241,8 @@ Module *BugDriver::runPassesOn(Module *M,
if (runPasses(Passes, BitcodeResult, false/*delete*/, true/*quiet*/, if (runPasses(Passes, BitcodeResult, false/*delete*/, true/*quiet*/,
NumExtraArgs, ExtraArgs)) { NumExtraArgs, ExtraArgs)) {
if (AutoDebugCrashes) { if (AutoDebugCrashes) {
cerr << " Error running this sequence of passes" errs() << " Error running this sequence of passes"
<< " on the input program!\n"; << " on the input program!\n";
delete OldProgram; delete OldProgram;
EmitProgressBitcode("pass-error", false); EmitProgressBitcode("pass-error", false);
exit(debugOptimizerCrash()); exit(debugOptimizerCrash());
@ -257,8 +256,8 @@ Module *BugDriver::runPassesOn(Module *M,
Module *Ret = ParseInputFile(BitcodeResult, Context); Module *Ret = ParseInputFile(BitcodeResult, Context);
if (Ret == 0) { if (Ret == 0) {
cerr << getToolName() << ": Error reading bitcode file '" errs() << getToolName() << ": Error reading bitcode file '"
<< BitcodeResult << "'!\n"; << BitcodeResult << "'!\n";
exit(1); exit(1);
} }
sys::Path(BitcodeResult).eraseFromDisk(); // No longer need the file on disk sys::Path(BitcodeResult).eraseFromDisk(); // No longer need the file on disk

View File

@ -25,7 +25,6 @@
#include "llvm/System/Process.h" #include "llvm/System/Process.h"
#include "llvm/System/Signals.h" #include "llvm/System/Signals.h"
#include "llvm/LinkAllVMCore.h" #include "llvm/LinkAllVMCore.h"
#include <iostream>
using namespace llvm; using namespace llvm;
// AsChild - Specifies that this invocation of bugpoint is being generated // AsChild - Specifies that this invocation of bugpoint is being generated

View File

@ -24,7 +24,6 @@
#include "llvm/Support/ManagedStatic.h" #include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SourceMgr.h" #include "llvm/Support/SourceMgr.h"
#include "llvm/Support/Streams.h"
#include "llvm/Support/SystemUtils.h" #include "llvm/Support/SystemUtils.h"
#include "llvm/Support/raw_ostream.h" #include "llvm/Support/raw_ostream.h"
#include "llvm/System/Signals.h" #include "llvm/System/Signals.h"
@ -73,14 +72,14 @@ int main(int argc, char **argv) {
if (!DisableVerify) { if (!DisableVerify) {
std::string Err; std::string Err;
if (verifyModule(*M.get(), ReturnStatusAction, &Err)) { if (verifyModule(*M.get(), ReturnStatusAction, &Err)) {
cerr << argv[0] errs() << argv[0]
<< ": assembly parsed, but does not verify as correct!\n"; << ": assembly parsed, but does not verify as correct!\n";
cerr << Err; errs() << Err;
return 1; return 1;
} }
} }
if (DumpAsm) cerr << "Here's the assembly:\n" << *M.get(); if (DumpAsm) errs() << "Here's the assembly:\n" << *M.get();
if (OutputFilename != "") { // Specified an output filename? if (OutputFilename != "") { // Specified an output filename?
if (OutputFilename != "-") { // Not stdout? if (OutputFilename != "-") { // Not stdout?
@ -133,10 +132,10 @@ int main(int argc, char **argv) {
if (Force || !CheckBitcodeOutputToConsole(Out,true)) if (Force || !CheckBitcodeOutputToConsole(Out,true))
WriteBitcodeToFile(M.get(), *Out); WriteBitcodeToFile(M.get(), *Out);
} catch (const std::string& msg) { } catch (const std::string& msg) {
cerr << argv[0] << ": " << msg << "\n"; errs() << argv[0] << ": " << msg << "\n";
exitCode = 1; exitCode = 1;
} catch (...) { } catch (...) {
cerr << argv[0] << ": Unexpected unknown exception occurred.\n"; errs() << argv[0] << ": Unexpected unknown exception occurred.\n";
exitCode = 1; exitCode = 1;
} }

View File

@ -37,8 +37,6 @@
#include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/PrettyStackTrace.h"
#include "llvm/System/Signals.h" #include "llvm/System/Signals.h"
#include <map> #include <map>
#include <fstream>
#include <iostream>
#include <algorithm> #include <algorithm>
using namespace llvm; using namespace llvm;

View File

@ -25,7 +25,6 @@
#include "llvm/Support/ManagedStatic.h" #include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Streams.h"
#include "llvm/Support/raw_ostream.h" #include "llvm/Support/raw_ostream.h"
#include "llvm/System/Signals.h" #include "llvm/System/Signals.h"
#include <memory> #include <memory>
@ -66,11 +65,11 @@ int main(int argc, char **argv) {
} }
if (M.get() == 0) { if (M.get() == 0) {
cerr << argv[0] << ": "; errs() << argv[0] << ": ";
if (ErrorMessage.size()) if (ErrorMessage.size())
cerr << ErrorMessage << "\n"; errs() << ErrorMessage << "\n";
else else
cerr << "bitcode didn't read correctly.\n"; errs() << "bitcode didn't read correctly.\n";
return 1; return 1;
} }
@ -130,9 +129,9 @@ int main(int argc, char **argv) {
delete Out; delete Out;
return 0; return 0;
} catch (const std::string& msg) { } catch (const std::string& msg) {
cerr << argv[0] << ": " << msg << "\n"; errs() << argv[0] << ": " << msg << "\n";
} catch (...) { } catch (...) {
cerr << argv[0] << ": Unexpected unknown exception occurred.\n"; errs() << argv[0] << ": Unexpected unknown exception occurred.\n";
} }
return 1; return 1;

View File

@ -69,7 +69,7 @@ int main(int argc, char **argv) {
MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename); MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename);
if (Buffer == 0) { if (Buffer == 0) {
cerr << argv[0] << ": Error reading file '" + InputFilename + "'\n"; errs() << argv[0] << ": Error reading file '" + InputFilename + "'\n";
return 1; return 1;
} else { } else {
M.reset(ParseBitcodeFile(Buffer, Context)); M.reset(ParseBitcodeFile(Buffer, Context));
@ -77,7 +77,7 @@ int main(int argc, char **argv) {
delete Buffer; delete Buffer;
if (M.get() == 0) { if (M.get() == 0) {
cerr << argv[0] << ": bitcode didn't read correctly.\n"; errs() << argv[0] << ": bitcode didn't read correctly.\n";
return 1; return 1;
} }
@ -90,8 +90,8 @@ int main(int argc, char **argv) {
Function *F = M.get()->getFunction(ExtractFunc); Function *F = M.get()->getFunction(ExtractFunc);
if (F == 0 && G == 0) { if (F == 0 && G == 0) {
cerr << argv[0] << ": program doesn't contain function named '" errs() << argv[0] << ": program doesn't contain function named '"
<< ExtractFunc << "' or a global named '" << ExtractGlobal << "'!\n"; << ExtractFunc << "' or a global named '" << ExtractGlobal << "'!\n";
return 1; return 1;
} }

View File

@ -26,7 +26,6 @@
#include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Scalar.h"
#include "llvm/Support/PassNameParser.h" #include "llvm/Support/PassNameParser.h"
#include "llvm/Support/PluginLoader.h" #include "llvm/Support/PluginLoader.h"
#include <iostream>
using namespace llvm; using namespace llvm;
// Pass Name Options as generated by the PassNameParser // Pass Name Options as generated by the PassNameParser

View File

@ -34,11 +34,9 @@
#include "llvm/Support/ManagedStatic.h" #include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Streams.h"
#include "llvm/Support/SystemUtils.h" #include "llvm/Support/SystemUtils.h"
#include "llvm/System/Signals.h" #include "llvm/System/Signals.h"
#include "llvm/Config/config.h" #include "llvm/Config/config.h"
#include <fstream>
#include <memory> #include <memory>
#include <cstring> #include <cstring>
using namespace llvm; using namespace llvm;
@ -123,7 +121,7 @@ static std::string progname;
/// Message - The message to print to standard error. /// Message - The message to print to standard error.
/// ///
static void PrintAndExit(const std::string &Message, int errcode = 1) { static void PrintAndExit(const std::string &Message, int errcode = 1) {
cerr << progname << ": " << Message << "\n"; errs() << progname << ": " << Message << "\n";
llvm_shutdown(); llvm_shutdown();
exit(errcode); exit(errcode);
} }
@ -132,8 +130,8 @@ static void PrintCommand(const std::vector<const char*> &args) {
std::vector<const char*>::const_iterator I = args.begin(), E = args.end(); std::vector<const char*>::const_iterator I = args.begin(), E = args.end();
for (; I != E; ++I) for (; I != E; ++I)
if (*I) if (*I)
cout << "'" << *I << "'" << " "; outs() << "'" << *I << "'" << " ";
cout << "\n" << std::flush; outs() << "\n"; outs().flush();
} }
/// CopyEnv - This function takes an array of environment variables and makes a /// CopyEnv - This function takes an array of environment variables and makes a
@ -218,14 +216,14 @@ static void RemoveEnv(const char * name, char ** const envp) {
void GenerateBitcode(Module* M, const std::string& FileName) { void GenerateBitcode(Module* M, const std::string& FileName) {
if (Verbose) if (Verbose)
cout << "Generating Bitcode To " << FileName << '\n'; outs() << "Generating Bitcode To " << FileName << '\n';
// Create the output file. // Create the output file.
std::ios::openmode io_mode = std::ios::out | std::ios::trunc | std::string ErrorInfo;
std::ios::binary; raw_fd_ostream Out(FileName.c_str(), /*Binary=*/true, /*Force=*/true,
std::ofstream Out(FileName.c_str(), io_mode); ErrorInfo);
if (!Out.good()) if (!ErrorInfo.empty())
PrintAndExit("error opening '" + FileName + "' for writing!"); PrintAndExit(ErrorInfo);
// Ensure that the bitcode file gets removed from the disk if we get a // Ensure that the bitcode file gets removed from the disk if we get a
// terminating signal. // terminating signal.
@ -266,7 +264,7 @@ static int GenerateAssembly(const std::string &OutputFilename,
args.push_back(0); args.push_back(0);
if (Verbose) { if (Verbose) {
cout << "Generating Assembly With: \n"; outs() << "Generating Assembly With: \n";
PrintCommand(args); PrintCommand(args);
} }
@ -289,7 +287,7 @@ static int GenerateCFile(const std::string &OutputFile,
args.push_back(0); args.push_back(0);
if (Verbose) { if (Verbose) {
cout << "Generating C Source With: \n"; outs() << "Generating C Source With: \n";
PrintCommand(args); PrintCommand(args);
} }
@ -386,7 +384,7 @@ static int GenerateNative(const std::string &OutputFilename,
Args.push_back(0); Args.push_back(0);
if (Verbose) { if (Verbose) {
cout << "Generating Native Executable With:\n"; outs() << "Generating Native Executable With:\n";
PrintCommand(Args); PrintCommand(Args);
} }
@ -401,7 +399,7 @@ static int GenerateNative(const std::string &OutputFilename,
/// bitcode file for the program. /// bitcode file for the program.
static void EmitShellScript(char **argv) { static void EmitShellScript(char **argv) {
if (Verbose) if (Verbose)
cout << "Emitting Shell Script\n"; outs() << "Emitting Shell Script\n";
#if defined(_WIN32) || defined(__CYGWIN__) #if defined(_WIN32) || defined(__CYGWIN__)
// Windows doesn't support #!/bin/sh style shell scripts in .exe files. To // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
// support windows systems, we copy the llvm-stub.exe executable from the // support windows systems, we copy the llvm-stub.exe executable from the
@ -418,9 +416,11 @@ static void EmitShellScript(char **argv) {
#endif #endif
// Output the script to start the program... // Output the script to start the program...
std::ofstream Out2(OutputFilename.c_str()); std::string ErrorInfo;
if (!Out2.good()) raw_fd_ostream Out2(OutputFilename.c_str(), /*Binary=*/false, /*Force=*/true,
PrintAndExit("error opening '" + OutputFilename + "' for writing!"); ErrorInfo);
if (!ErrorInfo.empty())
PrintAndExit(ErrorInfo);
Out2 << "#!/bin/sh\n"; Out2 << "#!/bin/sh\n";
// Allow user to setenv LLVMINTERP if lli is not in their PATH. // Allow user to setenv LLVMINTERP if lli is not in their PATH.

View File

@ -21,7 +21,6 @@
#include "llvm/Support/ManagedStatic.h" #include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Streams.h"
#include "llvm/System/Signals.h" #include "llvm/System/Signals.h"
#include "llvm/System/Path.h" #include "llvm/System/Path.h"
#include <memory> #include <memory>
@ -50,13 +49,13 @@ static inline std::auto_ptr<Module> LoadFile(const std::string &FN,
LLVMContext& Context) { LLVMContext& Context) {
sys::Path Filename; sys::Path Filename;
if (!Filename.set(FN)) { if (!Filename.set(FN)) {
cerr << "Invalid file name: '" << FN << "'\n"; errs() << "Invalid file name: '" << FN << "'\n";
return std::auto_ptr<Module>(); return std::auto_ptr<Module>();
} }
std::string ErrorMessage; std::string ErrorMessage;
if (Filename.exists()) { if (Filename.exists()) {
if (Verbose) cerr << "Loading '" << Filename.c_str() << "'\n"; if (Verbose) errs() << "Loading '" << Filename.c_str() << "'\n";
Module* Result = 0; Module* Result = 0;
const std::string &FNStr = Filename.toString(); const std::string &FNStr = Filename.toString();
@ -68,12 +67,12 @@ static inline std::auto_ptr<Module> LoadFile(const std::string &FN,
if (Result) return std::auto_ptr<Module>(Result); // Load successful! if (Result) return std::auto_ptr<Module>(Result); // Load successful!
if (Verbose) { if (Verbose) {
cerr << "Error opening bitcode file: '" << Filename.c_str() << "'"; errs() << "Error opening bitcode file: '" << Filename.c_str() << "'";
if (ErrorMessage.size()) cerr << ": " << ErrorMessage; if (ErrorMessage.size()) errs() << ": " << ErrorMessage;
cerr << "\n"; errs() << "\n";
} }
} else { } else {
cerr << "Bitcode file: '" << Filename.c_str() << "' does not exist.\n"; errs() << "Bitcode file: '" << Filename.c_str() << "' does not exist.\n";
} }
return std::auto_ptr<Module>(); return std::auto_ptr<Module>();
@ -93,23 +92,23 @@ int main(int argc, char **argv) {
std::auto_ptr<Module> Composite(LoadFile(InputFilenames[BaseArg], Context)); std::auto_ptr<Module> Composite(LoadFile(InputFilenames[BaseArg], Context));
if (Composite.get() == 0) { if (Composite.get() == 0) {
cerr << argv[0] << ": error loading file '" errs() << argv[0] << ": error loading file '"
<< InputFilenames[BaseArg] << "'\n"; << InputFilenames[BaseArg] << "'\n";
return 1; return 1;
} }
for (unsigned i = BaseArg+1; i < InputFilenames.size(); ++i) { for (unsigned i = BaseArg+1; i < InputFilenames.size(); ++i) {
std::auto_ptr<Module> M(LoadFile(InputFilenames[i], Context)); std::auto_ptr<Module> M(LoadFile(InputFilenames[i], Context));
if (M.get() == 0) { if (M.get() == 0) {
cerr << argv[0] << ": error loading file '" <<InputFilenames[i]<< "'\n"; errs() << argv[0] << ": error loading file '" <<InputFilenames[i]<< "'\n";
return 1; return 1;
} }
if (Verbose) cerr << "Linking in '" << InputFilenames[i] << "'\n"; if (Verbose) errs() << "Linking in '" << InputFilenames[i] << "'\n";
if (Linker::LinkModules(Composite.get(), M.get(), &ErrorMessage)) { if (Linker::LinkModules(Composite.get(), M.get(), &ErrorMessage)) {
cerr << argv[0] << ": link error in '" << InputFilenames[i] errs() << argv[0] << ": link error in '" << InputFilenames[i]
<< "': " << ErrorMessage << "\n"; << "': " << ErrorMessage << "\n";
return 1; return 1;
} }
} }
@ -117,7 +116,7 @@ int main(int argc, char **argv) {
// TODO: Iterate over the -l list and link in any modules containing // TODO: Iterate over the -l list and link in any modules containing
// global symbols that have not been resolved so far. // global symbols that have not been resolved so far.
if (DumpAsm) cerr << "Here's the assembly:\n" << *Composite.get(); if (DumpAsm) errs() << "Here's the assembly:\n" << *Composite.get();
// FIXME: outs() is not binary! // FIXME: outs() is not binary!
raw_ostream *Out = &outs(); // Default to printing to stdout... raw_ostream *Out = &outs(); // Default to printing to stdout...
@ -139,11 +138,11 @@ int main(int argc, char **argv) {
} }
if (verifyModule(*Composite.get())) { if (verifyModule(*Composite.get())) {
cerr << argv[0] << ": linked module is broken!\n"; errs() << argv[0] << ": linked module is broken!\n";
return 1; return 1;
} }
if (Verbose) cerr << "Writing bitcode...\n"; if (Verbose) errs() << "Writing bitcode...\n";
WriteBitcodeToFile(Composite.get(), *Out); WriteBitcodeToFile(Composite.get(), *Out);
if (Out != &outs()) delete Out; if (Out != &outs()) delete Out;

View File

@ -30,7 +30,6 @@
#include <cctype> #include <cctype>
#include <cerrno> #include <cerrno>
#include <cstring> #include <cstring>
#include <iostream>
using namespace llvm; using namespace llvm;
namespace { namespace {
@ -100,31 +99,31 @@ static void DumpSymbolNameForGlobalValue(GlobalValue &GV) {
if (GV.hasLocalLinkage () && ExternalOnly) if (GV.hasLocalLinkage () && ExternalOnly)
return; return;
if (OutputFormat == posix) { if (OutputFormat == posix) {
std::cout << GV.getName () << " " << TypeCharForSymbol(GV) << " " outs() << GV.getName () << " " << TypeCharForSymbol(GV) << " "
<< SymbolAddrStr << "\n"; << SymbolAddrStr << "\n";
} else if (OutputFormat == bsd) { } else if (OutputFormat == bsd) {
std::cout << SymbolAddrStr << " " << TypeCharForSymbol(GV) << " " outs() << SymbolAddrStr << " " << TypeCharForSymbol(GV) << " "
<< GV.getName () << "\n"; << GV.getName () << "\n";
} else if (OutputFormat == sysv) { } else if (OutputFormat == sysv) {
std::string PaddedName (GV.getName ()); std::string PaddedName (GV.getName ());
while (PaddedName.length () < 20) while (PaddedName.length () < 20)
PaddedName += " "; PaddedName += " ";
std::cout << PaddedName << "|" << SymbolAddrStr << "| " outs() << PaddedName << "|" << SymbolAddrStr << "| "
<< TypeCharForSymbol(GV) << TypeCharForSymbol(GV)
<< " | | | |\n"; << " | | | |\n";
} }
} }
static void DumpSymbolNamesFromModule(Module *M) { static void DumpSymbolNamesFromModule(Module *M) {
const std::string &Filename = M->getModuleIdentifier (); const std::string &Filename = M->getModuleIdentifier ();
if (OutputFormat == posix && MultipleFiles) { if (OutputFormat == posix && MultipleFiles) {
std::cout << Filename << ":\n"; outs() << Filename << ":\n";
} else if (OutputFormat == bsd && MultipleFiles) { } else if (OutputFormat == bsd && MultipleFiles) {
std::cout << "\n" << Filename << ":\n"; outs() << "\n" << Filename << ":\n";
} else if (OutputFormat == sysv) { } else if (OutputFormat == sysv) {
std::cout << "\n\nSymbols from " << Filename << ":\n\n" outs() << "\n\nSymbols from " << Filename << ":\n\n"
<< "Name Value Class Type" << "Name Value Class Type"
<< " Size Line Section\n"; << " Size Line Section\n";
} }
std::for_each (M->begin(), M->end(), DumpSymbolNameForGlobalValue); std::for_each (M->begin(), M->end(), DumpSymbolNameForGlobalValue);
std::for_each (M->global_begin(), M->global_end(), std::for_each (M->global_begin(), M->global_end(),

View File

@ -13,13 +13,12 @@
#include "llvm/CompilerDriver/CompilationGraph.h" #include "llvm/CompilerDriver/CompilationGraph.h"
#include "llvm/CompilerDriver/Plugin.h" #include "llvm/CompilerDriver/Plugin.h"
#include "llvm/Support/raw_ostream.h"
#include <iostream>
namespace { namespace {
struct MyPlugin : public llvmc::BasePlugin { struct MyPlugin : public llvmc::BasePlugin {
void PopulateLanguageMap(llvmc::LanguageMap&) const void PopulateLanguageMap(llvmc::LanguageMap&) const
{ std::cout << "Hello!\n"; } { outs() << "Hello!\n"; }
void PopulateCompilationGraph(llvmc::CompilationGraph&) const void PopulateCompilationGraph(llvmc::CompilationGraph&) const
{} {}

View File

@ -31,8 +31,6 @@
#include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegistry.h" #include "llvm/Target/TargetRegistry.h"
#include <fstream>
using namespace llvm; using namespace llvm;
bool LTOModule::isBitcodeFile(const void* mem, size_t length) bool LTOModule::isBitcodeFile(const void* mem, size_t length)

View File

@ -29,8 +29,8 @@
#include "llvm/Module.h" #include "llvm/Module.h"
#include "llvm/Analysis/CallGraph.h" #include "llvm/Analysis/CallGraph.h"
#include "llvm/Support/CFG.h" #include "llvm/Support/CFG.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/SCCIterator.h" #include "llvm/ADT/SCCIterator.h"
#include <iostream>
using namespace llvm; using namespace llvm;
namespace { namespace {
@ -73,18 +73,18 @@ namespace {
bool CFGSCC::runOnFunction(Function &F) { bool CFGSCC::runOnFunction(Function &F) {
unsigned sccNum = 0; unsigned sccNum = 0;
std::cout << "SCCs for Function " << F.getName() << " in PostOrder:"; outs() << "SCCs for Function " << F.getName() << " in PostOrder:";
for (scc_iterator<Function*> SCCI = scc_begin(&F), for (scc_iterator<Function*> SCCI = scc_begin(&F),
E = scc_end(&F); SCCI != E; ++SCCI) { E = scc_end(&F); SCCI != E; ++SCCI) {
std::vector<BasicBlock*> &nextSCC = *SCCI; std::vector<BasicBlock*> &nextSCC = *SCCI;
std::cout << "\nSCC #" << ++sccNum << " : "; outs() << "\nSCC #" << ++sccNum << " : ";
for (std::vector<BasicBlock*>::const_iterator I = nextSCC.begin(), for (std::vector<BasicBlock*>::const_iterator I = nextSCC.begin(),
E = nextSCC.end(); I != E; ++I) E = nextSCC.end(); I != E; ++I)
std::cout << (*I)->getName() << ", "; outs() << (*I)->getName() << ", ";
if (nextSCC.size() == 1 && SCCI.hasLoop()) if (nextSCC.size() == 1 && SCCI.hasLoop())
std::cout << " (Has self-loop)."; outs() << " (Has self-loop).";
} }
std::cout << "\n"; outs() << "\n";
return true; return true;
} }
@ -94,19 +94,19 @@ bool CFGSCC::runOnFunction(Function &F) {
bool CallGraphSCC::runOnModule(Module &M) { bool CallGraphSCC::runOnModule(Module &M) {
CallGraphNode* rootNode = getAnalysis<CallGraph>().getRoot(); CallGraphNode* rootNode = getAnalysis<CallGraph>().getRoot();
unsigned sccNum = 0; unsigned sccNum = 0;
std::cout << "SCCs for the program in PostOrder:"; outs() << "SCCs for the program in PostOrder:";
for (scc_iterator<CallGraphNode*> SCCI = scc_begin(rootNode), for (scc_iterator<CallGraphNode*> SCCI = scc_begin(rootNode),
E = scc_end(rootNode); SCCI != E; ++SCCI) { E = scc_end(rootNode); SCCI != E; ++SCCI) {
const std::vector<CallGraphNode*> &nextSCC = *SCCI; const std::vector<CallGraphNode*> &nextSCC = *SCCI;
std::cout << "\nSCC #" << ++sccNum << " : "; outs() << "\nSCC #" << ++sccNum << " : ";
for (std::vector<CallGraphNode*>::const_iterator I = nextSCC.begin(), for (std::vector<CallGraphNode*>::const_iterator I = nextSCC.begin(),
E = nextSCC.end(); I != E; ++I) E = nextSCC.end(); I != E; ++I)
std::cout << ((*I)->getFunction() ? (*I)->getFunction()->getName() outs() << ((*I)->getFunction() ? (*I)->getFunction()->getName()
: std::string("Indirect CallGraph node")) << ", "; : std::string("Indirect CallGraph node")) << ", ";
if (nextSCC.size() == 1 && SCCI.hasLoop()) if (nextSCC.size() == 1 && SCCI.hasLoop())
std::cout << " (Has self-loop)."; outs() << " (Has self-loop).";
} }
std::cout << "\n"; outs() << "\n";
return true; return true;
} }

View File

@ -30,7 +30,6 @@
#include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PluginLoader.h" #include "llvm/Support/PluginLoader.h"
#include "llvm/Support/StandardPasses.h" #include "llvm/Support/StandardPasses.h"
#include "llvm/Support/Streams.h"
#include "llvm/Support/SystemUtils.h" #include "llvm/Support/SystemUtils.h"
#include "llvm/Support/raw_ostream.h" #include "llvm/Support/raw_ostream.h"
#include "llvm/LinkAllPasses.h" #include "llvm/LinkAllPasses.h"
@ -126,12 +125,15 @@ struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
virtual bool runOnSCC(const std::vector<CallGraphNode *>&SCC) { virtual bool runOnSCC(const std::vector<CallGraphNode *>&SCC) {
if (!Quiet) { if (!Quiet) {
cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n"; outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
for (unsigned i = 0, e = SCC.size(); i != e; ++i) { for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
Function *F = SCC[i]->getFunction(); Function *F = SCC[i]->getFunction();
if (F) if (F) {
outs().flush();
getAnalysisID<Pass>(PassToPrint).print(cout, F->getParent()); getAnalysisID<Pass>(PassToPrint).print(cout, F->getParent());
cout << std::flush;
}
} }
} }
// Get and print pass... // Get and print pass...
@ -156,8 +158,10 @@ struct ModulePassPrinter : public ModulePass {
virtual bool runOnModule(Module &M) { virtual bool runOnModule(Module &M) {
if (!Quiet) { if (!Quiet) {
cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n"; outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
outs().flush();
getAnalysisID<Pass>(PassToPrint).print(cout, &M); getAnalysisID<Pass>(PassToPrint).print(cout, &M);
cout << std::flush;
} }
// Get and print pass... // Get and print pass...
@ -181,11 +185,13 @@ struct FunctionPassPrinter : public FunctionPass {
virtual bool runOnFunction(Function &F) { virtual bool runOnFunction(Function &F) {
if (!Quiet) { if (!Quiet) {
cout << "Printing analysis '" << PassToPrint->getPassName() outs() << "Printing analysis '" << PassToPrint->getPassName()
<< "' for function '" << F.getName() << "':\n"; << "' for function '" << F.getName() << "':\n";
} }
// Get and print pass... // Get and print pass...
outs().flush();
getAnalysisID<Pass>(PassToPrint).print(cout, F.getParent()); getAnalysisID<Pass>(PassToPrint).print(cout, F.getParent());
cout << std::flush;
return false; return false;
} }
@ -207,9 +213,11 @@ struct LoopPassPrinter : public LoopPass {
virtual bool runOnLoop(Loop *L, LPPassManager &LPM) { virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
if (!Quiet) { if (!Quiet) {
cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n"; outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
getAnalysisID<Pass>(PassToPrint).print(cout, outs().flush();
getAnalysisID<Pass>(PassToPrint).print(cout,
L->getHeader()->getParent()->getParent()); L->getHeader()->getParent()->getParent());
cout << std::flush;
} }
// Get and print pass... // Get and print pass...
return false; return false;
@ -233,12 +241,14 @@ struct BasicBlockPassPrinter : public BasicBlockPass {
virtual bool runOnBasicBlock(BasicBlock &BB) { virtual bool runOnBasicBlock(BasicBlock &BB) {
if (!Quiet) { if (!Quiet) {
cout << "Printing Analysis info for BasicBlock '" << BB.getName() outs() << "Printing Analysis info for BasicBlock '" << BB.getName()
<< "': Pass " << PassToPrint->getPassName() << ":\n"; << "': Pass " << PassToPrint->getPassName() << ":\n";
} }
// Get and print pass... // Get and print pass...
outs().flush();
getAnalysisID<Pass>(PassToPrint).print(cout, BB.getParent()->getParent()); getAnalysisID<Pass>(PassToPrint).print(cout, BB.getParent()->getParent());
cout << std::flush;
return false; return false;
} }
@ -330,16 +340,16 @@ int main(int argc, char **argv) {
} }
if (M.get() == 0) { if (M.get() == 0) {
cerr << argv[0] << ": "; errs() << argv[0] << ": ";
if (ErrorMessage.size()) if (ErrorMessage.size())
cerr << ErrorMessage << "\n"; errs() << ErrorMessage << "\n";
else else
cerr << "bitcode didn't read correctly.\n"; errs() << "bitcode didn't read correctly.\n";
return 1; return 1;
} }
// Figure out what stream we are supposed to write to... // Figure out what stream we are supposed to write to...
// FIXME: cout is not binary! // FIXME: outs() is not binary!
raw_ostream *Out = &outs(); // Default to printing to stdout... raw_ostream *Out = &outs(); // Default to printing to stdout...
if (OutputFilename != "-") { if (OutputFilename != "-") {
std::string ErrorInfo; std::string ErrorInfo;
@ -414,8 +424,8 @@ int main(int argc, char **argv) {
if (PassInf->getNormalCtor()) if (PassInf->getNormalCtor())
P = PassInf->getNormalCtor()(); P = PassInf->getNormalCtor()();
else else
cerr << argv[0] << ": cannot create pass: " errs() << argv[0] << ": cannot create pass: "
<< PassInf->getPassName() << "\n"; << PassInf->getPassName() << "\n";
if (P) { if (P) {
bool isBBPass = dynamic_cast<BasicBlockPass*>(P) != 0; bool isBBPass = dynamic_cast<BasicBlockPass*>(P) != 0;
bool isLPass = !isBBPass && dynamic_cast<LoopPass*>(P) != 0; bool isLPass = !isBBPass && dynamic_cast<LoopPass*>(P) != 0;
@ -470,22 +480,22 @@ int main(int argc, char **argv) {
if (!NoVerify && !VerifyEach) if (!NoVerify && !VerifyEach)
Passes.add(createVerifierPass()); Passes.add(createVerifierPass());
// Write bitcode out to disk or cout as the last step... // Write bitcode out to disk or outs() as the last step...
if (!NoOutput && !AnalyzeOnly) if (!NoOutput && !AnalyzeOnly)
Passes.add(createBitcodeWriterPass(*Out)); Passes.add(createBitcodeWriterPass(*Out));
// Now that we have all of the passes ready, run them. // Now that we have all of the passes ready, run them.
Passes.run(*M.get()); Passes.run(*M.get());
// Delete the ofstream. // Delete the raw_fd_ostream.
if (Out != &outs()) if (Out != &outs())
delete Out; delete Out;
return 0; return 0;
} catch (const std::string& msg) { } catch (const std::string& msg) {
cerr << argv[0] << ": " << msg << "\n"; errs() << argv[0] << ": " << msg << "\n";
} catch (...) { } catch (...) {
cerr << argv[0] << ": Unexpected unknown exception occurred.\n"; errs() << argv[0] << ": Unexpected unknown exception occurred.\n";
} }
llvm_shutdown(); llvm_shutdown();
return 1; return 1;