1 //===- OptimizerDriver.cpp - Allow BugPoint to run passes safely ----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // 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 #include "BugDriver.h" 19 #include "ToolRunner.h" 20 #include "llvm/Bitcode/BitcodeWriter.h" 21 #include "llvm/IR/DataLayout.h" 22 #include "llvm/IR/Module.h" 23 #include "llvm/Support/CommandLine.h" 24 #include "llvm/Support/Debug.h" 25 #include "llvm/Support/FileUtilities.h" 26 #include "llvm/Support/Path.h" 27 #include "llvm/Support/Program.h" 28 #include "llvm/Support/ToolOutputFile.h" 29 30 #define DONT_GET_PLUGIN_LOADER_OPTION 31 #include "llvm/Support/PluginLoader.h" 32 33 34 using namespace llvm; 35 36 #define DEBUG_TYPE "bugpoint" 37 38 namespace llvm { 39 extern cl::opt<std::string> OutputPrefix; 40 } 41 42 static cl::opt<bool> PreserveBitcodeUseListOrder( 43 "preserve-bc-uselistorder", 44 cl::desc("Preserve use-list order when writing LLVM bitcode."), 45 cl::init(true), cl::Hidden); 46 47 static cl::opt<std::string> 48 OptCmd("opt-command", cl::init(""), 49 cl::desc("Path to opt. (default: search path " 50 "for 'opt'.)")); 51 52 /// This writes the current "Program" to the named bitcode file. If an error 53 /// occurs, true is returned. 54 static bool writeProgramToFileAux(ToolOutputFile &Out, const Module &M) { 55 WriteBitcodeToFile(M, Out.os(), PreserveBitcodeUseListOrder); 56 Out.os().close(); 57 if (!Out.os().has_error()) { 58 Out.keep(); 59 return false; 60 } 61 return true; 62 } 63 64 bool BugDriver::writeProgramToFile(const std::string &Filename, int FD, 65 const Module &M) const { 66 ToolOutputFile Out(Filename, FD); 67 return writeProgramToFileAux(Out, M); 68 } 69 70 bool BugDriver::writeProgramToFile(int FD, const Module &M) const { 71 raw_fd_ostream OS(FD, /*shouldClose*/ false); 72 WriteBitcodeToFile(M, OS, PreserveBitcodeUseListOrder); 73 OS.flush(); 74 if (!OS.has_error()) 75 return false; 76 OS.clear_error(); 77 return true; 78 } 79 80 bool BugDriver::writeProgramToFile(const std::string &Filename, 81 const Module &M) const { 82 std::error_code EC; 83 ToolOutputFile Out(Filename, EC, sys::fs::F_None); 84 if (!EC) 85 return writeProgramToFileAux(Out, M); 86 return true; 87 } 88 89 /// This function is used to output the current Program to a file named 90 /// "bugpoint-ID.bc". 91 void BugDriver::EmitProgressBitcode(const Module &M, const std::string &ID, 92 bool NoFlyer) const { 93 // Output the input to the current pass to a bitcode file, emit a message 94 // telling the user how to reproduce it: opt -foo blah.bc 95 // 96 std::string Filename = OutputPrefix + "-" + ID + ".bc"; 97 if (writeProgramToFile(Filename, M)) { 98 errs() << "Error opening file '" << Filename << "' for writing!\n"; 99 return; 100 } 101 102 outs() << "Emitted bitcode to '" << Filename << "'\n"; 103 if (NoFlyer || PassesToRun.empty()) 104 return; 105 outs() << "\n*** You can reproduce the problem with: "; 106 if (UseValgrind) 107 outs() << "valgrind "; 108 outs() << "opt " << Filename; 109 for (unsigned i = 0, e = PluginLoader::getNumPlugins(); i != e; ++i) { 110 outs() << " -load " << PluginLoader::getPlugin(i); 111 } 112 outs() << " " << getPassesString(PassesToRun) << "\n"; 113 } 114 115 cl::opt<bool> SilencePasses( 116 "silence-passes", 117 cl::desc("Suppress output of running passes (both stdout and stderr)")); 118 119 static cl::list<std::string> OptArgs("opt-args", cl::Positional, 120 cl::desc("<opt arguments>..."), 121 cl::ZeroOrMore, cl::PositionalEatsArgs); 122 123 /// runPasses - Run the specified passes on Program, outputting a bitcode file 124 /// and writing the filename into OutputFile if successful. If the 125 /// optimizations fail for some reason (optimizer crashes), return true, 126 /// otherwise return false. If DeleteOutput is set to true, the bitcode is 127 /// deleted on success, and the filename string is undefined. This prints to 128 /// outs() a single line message indicating whether compilation was successful 129 /// or failed. 130 /// 131 bool BugDriver::runPasses(Module &Program, 132 const std::vector<std::string> &Passes, 133 std::string &OutputFilename, bool DeleteOutput, 134 bool Quiet, unsigned NumExtraArgs, 135 const char *const *ExtraArgs) const { 136 // setup the output file name 137 outs().flush(); 138 SmallString<128> UniqueFilename; 139 std::error_code EC = sys::fs::createUniqueFile( 140 OutputPrefix + "-output-%%%%%%%.bc", UniqueFilename); 141 if (EC) { 142 errs() << getToolName() 143 << ": Error making unique filename: " << EC.message() << "\n"; 144 return 1; 145 } 146 OutputFilename = UniqueFilename.str(); 147 148 // set up the input file name 149 Expected<sys::fs::TempFile> Temp = 150 sys::fs::TempFile::create(OutputPrefix + "-input-%%%%%%%.bc"); 151 if (!Temp) { 152 errs() << getToolName() 153 << ": Error making unique filename: " << toString(Temp.takeError()) 154 << "\n"; 155 return 1; 156 } 157 DiscardTemp Discard{*Temp}; 158 raw_fd_ostream OS(Temp->FD, /*shouldClose*/ false); 159 160 WriteBitcodeToFile(Program, OS, PreserveBitcodeUseListOrder); 161 OS.flush(); 162 if (OS.has_error()) { 163 errs() << "Error writing bitcode file: " << Temp->TmpName << "\n"; 164 OS.clear_error(); 165 return 1; 166 } 167 168 std::string tool = OptCmd; 169 if (OptCmd.empty()) { 170 if (ErrorOr<std::string> Path = 171 FindProgramByName("opt", getToolName(), &OutputPrefix)) 172 tool = *Path; 173 else 174 errs() << Path.getError().message() << "\n"; 175 } 176 if (tool.empty()) { 177 errs() << "Cannot find `opt' in PATH!\n"; 178 return 1; 179 } 180 if (!sys::fs::exists(tool)) { 181 errs() << "Specified `opt' binary does not exist: " << tool << "\n"; 182 return 1; 183 } 184 185 std::string Prog; 186 if (UseValgrind) { 187 if (ErrorOr<std::string> Path = sys::findProgramByName("valgrind")) 188 Prog = *Path; 189 else 190 errs() << Path.getError().message() << "\n"; 191 } else 192 Prog = tool; 193 if (Prog.empty()) { 194 errs() << "Cannot find `valgrind' in PATH!\n"; 195 return 1; 196 } 197 198 // setup the child process' arguments 199 SmallVector<StringRef, 8> Args; 200 if (UseValgrind) { 201 Args.push_back("valgrind"); 202 Args.push_back("--error-exitcode=1"); 203 Args.push_back("-q"); 204 Args.push_back(tool); 205 } else 206 Args.push_back(tool); 207 208 for (unsigned i = 0, e = OptArgs.size(); i != e; ++i) 209 Args.push_back(OptArgs[i]); 210 Args.push_back("-disable-symbolication"); 211 Args.push_back("-o"); 212 Args.push_back(OutputFilename); 213 std::vector<std::string> pass_args; 214 for (unsigned i = 0, e = PluginLoader::getNumPlugins(); i != e; ++i) { 215 pass_args.push_back(std::string("-load")); 216 pass_args.push_back(PluginLoader::getPlugin(i)); 217 } 218 for (std::vector<std::string>::const_iterator I = Passes.begin(), 219 E = Passes.end(); 220 I != E; ++I) 221 pass_args.push_back(std::string("-") + (*I)); 222 for (std::vector<std::string>::const_iterator I = pass_args.begin(), 223 E = pass_args.end(); 224 I != E; ++I) 225 Args.push_back(I->c_str()); 226 Args.push_back(Temp->TmpName.c_str()); 227 for (unsigned i = 0; i < NumExtraArgs; ++i) 228 Args.push_back(*ExtraArgs); 229 230 LLVM_DEBUG(errs() << "\nAbout to run:\t"; 231 for (unsigned i = 0, e = Args.size() - 1; i != e; ++i) errs() 232 << " " << Args[i]; 233 errs() << "\n";); 234 235 Optional<StringRef> Redirects[3] = {None, None, None}; 236 // Redirect stdout and stderr to nowhere if SilencePasses is given. 237 if (SilencePasses) { 238 Redirects[1] = ""; 239 Redirects[2] = ""; 240 } 241 242 std::string ErrMsg; 243 int result = sys::ExecuteAndWait(Prog, Args, None, Redirects, Timeout, 244 MemoryLimit, &ErrMsg); 245 246 // If we are supposed to delete the bitcode file or if the passes crashed, 247 // remove it now. This may fail if the file was never created, but that's ok. 248 if (DeleteOutput || result != 0) 249 sys::fs::remove(OutputFilename); 250 251 if (!Quiet) { 252 if (result == 0) 253 outs() << "Success!\n"; 254 else if (result > 0) 255 outs() << "Exited with error code '" << result << "'\n"; 256 else if (result < 0) { 257 if (result == -1) 258 outs() << "Execute failed: " << ErrMsg << "\n"; 259 else 260 outs() << "Crashed: " << ErrMsg << "\n"; 261 } 262 if (result & 0x01000000) 263 outs() << "Dumped core\n"; 264 } 265 266 // Was the child successful? 267 return result != 0; 268 } 269 270 std::unique_ptr<Module> 271 BugDriver::runPassesOn(Module *M, const std::vector<std::string> &Passes, 272 unsigned NumExtraArgs, const char *const *ExtraArgs) { 273 std::string BitcodeResult; 274 if (runPasses(*M, Passes, BitcodeResult, false /*delete*/, true /*quiet*/, 275 NumExtraArgs, ExtraArgs)) { 276 return nullptr; 277 } 278 279 std::unique_ptr<Module> Ret = parseInputFile(BitcodeResult, Context); 280 if (!Ret) { 281 errs() << getToolName() << ": Error reading bitcode file '" << BitcodeResult 282 << "'!\n"; 283 exit(1); 284 } 285 sys::fs::remove(BitcodeResult); 286 return Ret; 287 } 288