OptimizerDriver.cpp revision 03b696376219945d67caffda1995d12e3410f05b
1//===- OptimizerDriver.cpp - Allow BugPoint to run passes safely ----------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by the LLVM research group and is distributed under 6// the University of Illinois Open Source License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines an interface that allows bugpoint to run various passes 11// without the threat of a buggy pass corrupting bugpoint (of course, bugpoint 12// may have its own bugs, but that's another story...). It achieves this by 13// forking a copy of itself and having the child process do the optimizations. 14// If this client dies, we can always fork a new one. :) 15// 16//===----------------------------------------------------------------------===// 17 18// Note: as a short term hack, the old Unix-specific code and platform- 19// independent code co-exist via conditional compilation until it is verified 20// that the new code works correctly on Unix. 21 22#include "BugDriver.h" 23#include "llvm/Module.h" 24#include "llvm/PassManager.h" 25#include "llvm/Analysis/Verifier.h" 26#include "llvm/Bytecode/WriteBytecodePass.h" 27#include "llvm/Bitcode/ReaderWriter.h" 28#include "llvm/Target/TargetData.h" 29#include "llvm/Support/FileUtilities.h" 30#include "llvm/Support/CommandLine.h" 31#include "llvm/Support/Streams.h" 32#include "llvm/System/Path.h" 33#include "llvm/System/Program.h" 34#include "llvm/Config/alloca.h" 35 36#define DONT_GET_PLUGIN_LOADER_OPTION 37#include "llvm/Support/PluginLoader.h" 38 39#include <fstream> 40using namespace llvm; 41 42static bool Bitcode = false; 43 44 45namespace { 46 // ChildOutput - This option captures the name of the child output file that 47 // is set up by the parent bugpoint process 48 cl::opt<std::string> ChildOutput("child-output", cl::ReallyHidden); 49 cl::opt<bool> UseValgrind("enable-valgrind", 50 cl::desc("Run optimizations through valgrind")); 51} 52 53/// writeProgramToFile - This writes the current "Program" to the named bytecode 54/// file. If an error occurs, true is returned. 55/// 56bool BugDriver::writeProgramToFile(const std::string &Filename, 57 Module *M) const { 58 std::ios::openmode io_mode = std::ios::out | std::ios::trunc | 59 std::ios::binary; 60 std::ofstream Out(Filename.c_str(), io_mode); 61 if (!Out.good()) return true; 62 try { 63 OStream L(Out); 64 WriteBytecodeToFile(M ? M : Program, L, /*compression=*/false); 65 } catch (...) { 66 return true; 67 } 68 return false; 69} 70 71 72/// EmitProgressBytecode - This function is used to output the current Program 73/// to a file named "bugpoint-ID.bc". 74/// 75void BugDriver::EmitProgressBytecode(const std::string &ID, bool NoFlyer) { 76 // Output the input to the current pass to a bytecode file, emit a message 77 // telling the user how to reproduce it: opt -foo blah.bc 78 // 79 std::string Filename = "bugpoint-" + ID + ".bc"; 80 if (writeProgramToFile(Filename)) { 81 cerr << "Error opening file '" << Filename << "' for writing!\n"; 82 return; 83 } 84 85 cout << "Emitted bytecode to '" << Filename << "'\n"; 86 if (NoFlyer || PassesToRun.empty()) return; 87 cout << "\n*** You can reproduce the problem with: "; 88 cout << "opt " << Filename << " "; 89 cout << getPassesString(PassesToRun) << "\n"; 90} 91 92int BugDriver::runPassesAsChild(const std::vector<const PassInfo*> &Passes) { 93 94 std::ios::openmode io_mode = std::ios::out | std::ios::trunc | 95 std::ios::binary; 96 std::ofstream OutFile(ChildOutput.c_str(), io_mode); 97 if (!OutFile.good()) { 98 cerr << "Error opening bytecode file: " << ChildOutput << "\n"; 99 return 1; 100 } 101 102 PassManager PM; 103 // Make sure that the appropriate target data is always used... 104 PM.add(new TargetData(Program)); 105 106 for (unsigned i = 0, e = Passes.size(); i != e; ++i) { 107 if (Passes[i]->getNormalCtor()) 108 PM.add(Passes[i]->getNormalCtor()()); 109 else 110 cerr << "Cannot create pass yet: " << Passes[i]->getPassName() << "\n"; 111 } 112 // Check that the module is well formed on completion of optimization 113 PM.add(createVerifierPass()); 114 115 // Write bytecode out to disk as the last step... 116 OStream L(OutFile); 117 if (Bitcode) 118 PM.add(CreateBitcodeWriterPass(OutFile)); 119 else 120 PM.add(new WriteBytecodePass(&L)); 121 122 // Run all queued passes. 123 PM.run(*Program); 124 125 return 0; 126} 127 128/// runPasses - Run the specified passes on Program, outputting a bytecode file 129/// and writing the filename into OutputFile if successful. If the 130/// optimizations fail for some reason (optimizer crashes), return true, 131/// otherwise return false. If DeleteOutput is set to true, the bytecode is 132/// deleted on success, and the filename string is undefined. This prints to 133/// cout a single line message indicating whether compilation was successful or 134/// failed. 135/// 136bool BugDriver::runPasses(const std::vector<const PassInfo*> &Passes, 137 std::string &OutputFilename, bool DeleteOutput, 138 bool Quiet) const { 139 // setup the output file name 140 cout << std::flush; 141 sys::Path uniqueFilename("bugpoint-output.bc"); 142 std::string ErrMsg; 143 if (uniqueFilename.makeUnique(true, &ErrMsg)) { 144 cerr << getToolName() << ": Error making unique filename: " 145 << ErrMsg << "\n"; 146 return(1); 147 } 148 OutputFilename = uniqueFilename.toString(); 149 150 // set up the input file name 151 sys::Path inputFilename("bugpoint-input.bc"); 152 if (inputFilename.makeUnique(true, &ErrMsg)) { 153 cerr << getToolName() << ": Error making unique filename: " 154 << ErrMsg << "\n"; 155 return(1); 156 } 157 std::ios::openmode io_mode = std::ios::out | std::ios::trunc | 158 std::ios::binary; 159 std::ofstream InFile(inputFilename.c_str(), io_mode); 160 if (!InFile.good()) { 161 cerr << "Error opening bytecode file: " << inputFilename << "\n"; 162 return(1); 163 } 164 OStream L(InFile); 165 WriteBytecodeToFile(Program,L,false); 166 InFile.close(); 167 168 // setup the child process' arguments 169 const char** args = (const char**) 170 alloca(sizeof(const char*) * 171 (Passes.size()+13+2*PluginLoader::getNumPlugins())); 172 int n = 0; 173 sys::Path tool = sys::Program::FindProgramByName(ToolName); 174 if (UseValgrind) { 175 args[n++] = "valgrind"; 176 args[n++] = "--error-exitcode=1"; 177 args[n++] = "-q"; 178 args[n++] = tool.c_str(); 179 } else 180 args[n++] = ToolName.c_str(); 181 182 args[n++] = "-as-child"; 183 args[n++] = "-child-output"; 184 args[n++] = OutputFilename.c_str(); 185 std::vector<std::string> pass_args; 186 for (unsigned i = 0, e = PluginLoader::getNumPlugins(); i != e; ++i) { 187 pass_args.push_back( std::string("-load")); 188 pass_args.push_back( PluginLoader::getPlugin(i)); 189 } 190 for (std::vector<const PassInfo*>::const_iterator I = Passes.begin(), 191 E = Passes.end(); I != E; ++I ) 192 pass_args.push_back( std::string("-") + (*I)->getPassArgument() ); 193 for (std::vector<std::string>::const_iterator I = pass_args.begin(), 194 E = pass_args.end(); I != E; ++I ) 195 args[n++] = I->c_str(); 196 args[n++] = inputFilename.c_str(); 197 args[n++] = 0; 198 199 sys::Path prog; 200 if (UseValgrind) 201 prog = sys::Program::FindProgramByName("valgrind"); 202 else 203 prog = tool; 204 int result = sys::Program::ExecuteAndWait(prog, args, 0, 0, 205 Timeout, MemoryLimit, &ErrMsg); 206 207 // If we are supposed to delete the bytecode file or if the passes crashed, 208 // remove it now. This may fail if the file was never created, but that's ok. 209 if (DeleteOutput || result != 0) 210 sys::Path(OutputFilename).eraseFromDisk(); 211 212 // Remove the temporary input file as well 213 inputFilename.eraseFromDisk(); 214 215 if (!Quiet) { 216 if (result == 0) 217 cout << "Success!\n"; 218 else if (result > 0) 219 cout << "Exited with error code '" << result << "'\n"; 220 else if (result < 0) { 221 if (result == -1) 222 cout << "Execute failed: " << ErrMsg << "\n"; 223 else 224 cout << "Crashed with signal #" << abs(result) << "\n"; 225 } 226 if (result & 0x01000000) 227 cout << "Dumped core\n"; 228 } 229 230 // Was the child successful? 231 return result != 0; 232} 233 234 235/// runPassesOn - Carefully run the specified set of pass on the specified 236/// module, returning the transformed module on success, or a null pointer on 237/// failure. 238Module *BugDriver::runPassesOn(Module *M, 239 const std::vector<const PassInfo*> &Passes, 240 bool AutoDebugCrashes) { 241 Module *OldProgram = swapProgramIn(M); 242 std::string BytecodeResult; 243 if (runPasses(Passes, BytecodeResult, false/*delete*/, true/*quiet*/)) { 244 if (AutoDebugCrashes) { 245 cerr << " Error running this sequence of passes" 246 << " on the input program!\n"; 247 delete OldProgram; 248 EmitProgressBytecode("pass-error", false); 249 exit(debugOptimizerCrash()); 250 } 251 swapProgramIn(OldProgram); 252 return 0; 253 } 254 255 // Restore the current program. 256 swapProgramIn(OldProgram); 257 258 Module *Ret = ParseInputFile(BytecodeResult); 259 if (Ret == 0) { 260 cerr << getToolName() << ": Error reading bytecode file '" 261 << BytecodeResult << "'!\n"; 262 exit(1); 263 } 264 sys::Path(BytecodeResult).eraseFromDisk(); // No longer need the file on disk 265 return Ret; 266} 267