1 //===- OptimizerDriver.cpp - Allow BugPoint to run passes safely ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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. :)
16 //===----------------------------------------------------------------------===//
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"
30 #define DONT_GET_PLUGIN_LOADER_OPTION
31 #include "llvm/Support/PluginLoader.h"
36 #define DEBUG_TYPE "bugpoint"
39 extern cl::opt<std::string> OutputPrefix;
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);
47 static cl::opt<std::string>
48 OptCmd("opt-command", cl::init(""),
49 cl::desc("Path to opt. (default: search path "
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);
57 if (!Out.os().has_error()) {
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);
70 bool BugDriver::writeProgramToFile(int FD, const Module &M) const {
71 raw_fd_ostream OS(FD, /*shouldClose*/ false);
72 WriteBitcodeToFile(M, OS, PreserveBitcodeUseListOrder);
80 bool BugDriver::writeProgramToFile(const std::string &Filename,
81 const Module &M) const {
83 ToolOutputFile Out(Filename, EC, sys::fs::F_None);
85 return writeProgramToFileAux(Out, M);
89 /// This function is used to output the current Program to a file named
91 void BugDriver::EmitProgressBitcode(const Module &M, const std::string &ID,
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
96 std::string Filename = OutputPrefix + "-" + ID + ".bc";
97 if (writeProgramToFile(Filename, M)) {
98 errs() << "Error opening file '" << Filename << "' for writing!\n";
102 outs() << "Emitted bitcode to '" << Filename << "'\n";
103 if (NoFlyer || PassesToRun.empty())
105 outs() << "\n*** You can reproduce the problem with: ";
107 outs() << "valgrind ";
108 outs() << "opt " << Filename;
109 for (unsigned i = 0, e = PluginLoader::getNumPlugins(); i != e; ++i) {
110 outs() << " -load " << PluginLoader::getPlugin(i);
112 outs() << " " << getPassesString(PassesToRun) << "\n";
115 cl::opt<bool> SilencePasses(
117 cl::desc("Suppress output of running passes (both stdout and stderr)"));
119 static cl::list<std::string> OptArgs("opt-args", cl::Positional,
120 cl::desc("<opt arguments>..."),
121 cl::ZeroOrMore, cl::PositionalEatsArgs);
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
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
138 SmallString<128> UniqueFilename;
139 std::error_code EC = sys::fs::createUniqueFile(
140 OutputPrefix + "-output-%%%%%%%.bc", UniqueFilename);
142 errs() << getToolName()
143 << ": Error making unique filename: " << EC.message() << "\n";
146 OutputFilename = UniqueFilename.str();
148 // set up the input file name
149 Expected<sys::fs::TempFile> Temp =
150 sys::fs::TempFile::create(OutputPrefix + "-input-%%%%%%%.bc");
152 errs() << getToolName()
153 << ": Error making unique filename: " << toString(Temp.takeError())
157 DiscardTemp Discard{*Temp};
158 raw_fd_ostream OS(Temp->FD, /*shouldClose*/ false);
160 WriteBitcodeToFile(Program, OS, PreserveBitcodeUseListOrder);
162 if (OS.has_error()) {
163 errs() << "Error writing bitcode file: " << Temp->TmpName << "\n";
168 std::string tool = OptCmd;
169 if (OptCmd.empty()) {
170 if (ErrorOr<std::string> Path =
171 FindProgramByName("opt", getToolName(), &OutputPrefix))
174 errs() << Path.getError().message() << "\n";
177 errs() << "Cannot find `opt' in PATH!\n";
180 if (!sys::fs::exists(tool)) {
181 errs() << "Specified `opt' binary does not exist: " << tool << "\n";
187 if (ErrorOr<std::string> Path = sys::findProgramByName("valgrind"))
190 errs() << Path.getError().message() << "\n";
194 errs() << "Cannot find `valgrind' in PATH!\n";
198 // setup the child process' arguments
199 SmallVector<StringRef, 8> Args;
201 Args.push_back("valgrind");
202 Args.push_back("--error-exitcode=1");
203 Args.push_back("-q");
204 Args.push_back(tool);
206 Args.push_back(tool);
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));
218 for (std::vector<std::string>::const_iterator I = Passes.begin(),
221 pass_args.push_back(std::string("-") + (*I));
222 for (std::vector<std::string>::const_iterator I = pass_args.begin(),
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);
230 LLVM_DEBUG(errs() << "\nAbout to run:\t";
231 for (unsigned i = 0, e = Args.size() - 1; i != e; ++i) errs()
235 Optional<StringRef> Redirects[3] = {None, None, None};
236 // Redirect stdout and stderr to nowhere if SilencePasses is given.
243 int result = sys::ExecuteAndWait(Prog, Args, None, Redirects, Timeout,
244 MemoryLimit, &ErrMsg);
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);
253 outs() << "Success!\n";
255 outs() << "Exited with error code '" << result << "'\n";
256 else if (result < 0) {
258 outs() << "Execute failed: " << ErrMsg << "\n";
260 outs() << "Crashed: " << ErrMsg << "\n";
262 if (result & 0x01000000)
263 outs() << "Dumped core\n";
266 // Was the child successful?
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)) {
279 std::unique_ptr<Module> Ret = parseInputFile(BitcodeResult, Context);
281 errs() << getToolName() << ": Error reading bitcode file '" << BitcodeResult
285 sys::fs::remove(BitcodeResult);