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 "llvm/Bitcode/BitcodeWriter.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/FileUtilities.h"
25 #include "llvm/Support/Path.h"
26 #include "llvm/Support/Program.h"
27 #include "llvm/Support/ToolOutputFile.h"
28 
29 #define DONT_GET_PLUGIN_LOADER_OPTION
30 #include "llvm/Support/PluginLoader.h"
31 
32 
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "bugpoint"
36 
37 namespace llvm {
38 extern cl::opt<std::string> OutputPrefix;
39 }
40 
41 static cl::opt<bool> PreserveBitcodeUseListOrder(
42     "preserve-bc-uselistorder",
43     cl::desc("Preserve use-list order when writing LLVM bitcode."),
44     cl::init(true), cl::Hidden);
45 
46 // ChildOutput - This option captures the name of the child output file that
47 // is set up by the parent bugpoint process
48 static cl::opt<std::string> ChildOutput("child-output", cl::ReallyHidden);
49 static cl::opt<std::string>
50     OptCmd("opt-command", cl::init(""),
51            cl::desc("Path to opt. (default: search path "
52                     "for 'opt'.)"));
53 
54 /// writeProgramToFile - This writes the current "Program" to the named bitcode
55 /// file.  If an error occurs, true is returned.
56 ///
57 static bool writeProgramToFileAux(ToolOutputFile &Out, const Module *M) {
58   WriteBitcodeToFile(M, Out.os(), PreserveBitcodeUseListOrder);
59   Out.os().close();
60   if (!Out.os().has_error()) {
61     Out.keep();
62     return false;
63   }
64   return true;
65 }
66 
67 bool BugDriver::writeProgramToFile(const std::string &Filename, int FD,
68                                    const Module *M) const {
69   ToolOutputFile Out(Filename, FD);
70   return writeProgramToFileAux(Out, M);
71 }
72 
73 bool BugDriver::writeProgramToFile(int FD, const Module *M) const {
74   raw_fd_ostream OS(FD, /*shouldClose*/ false);
75   WriteBitcodeToFile(M, OS, PreserveBitcodeUseListOrder);
76   OS.flush();
77   if (!OS.has_error())
78     return false;
79   OS.clear_error();
80   return true;
81 }
82 
83 bool BugDriver::writeProgramToFile(const std::string &Filename,
84                                    const Module *M) const {
85   std::error_code EC;
86   ToolOutputFile Out(Filename, EC, sys::fs::F_None);
87   if (!EC)
88     return writeProgramToFileAux(Out, M);
89   return true;
90 }
91 
92 /// EmitProgressBitcode - This function is used to output the current Program
93 /// to a file named "bugpoint-ID.bc".
94 ///
95 void BugDriver::EmitProgressBitcode(const Module *M, const std::string &ID,
96                                     bool NoFlyer) const {
97   // Output the input to the current pass to a bitcode file, emit a message
98   // telling the user how to reproduce it: opt -foo blah.bc
99   //
100   std::string Filename = OutputPrefix + "-" + ID + ".bc";
101   if (writeProgramToFile(Filename, M)) {
102     errs() << "Error opening file '" << Filename << "' for writing!\n";
103     return;
104   }
105 
106   outs() << "Emitted bitcode to '" << Filename << "'\n";
107   if (NoFlyer || PassesToRun.empty())
108     return;
109   outs() << "\n*** You can reproduce the problem with: ";
110   if (UseValgrind)
111     outs() << "valgrind ";
112   outs() << "opt " << Filename;
113   for (unsigned i = 0, e = PluginLoader::getNumPlugins(); i != e; ++i) {
114     outs() << " -load " << PluginLoader::getPlugin(i);
115   }
116   outs() << " " << getPassesString(PassesToRun) << "\n";
117 }
118 
119 cl::opt<bool> SilencePasses(
120     "silence-passes",
121     cl::desc("Suppress output of running passes (both stdout and stderr)"));
122 
123 static cl::list<std::string> OptArgs("opt-args", cl::Positional,
124                                      cl::desc("<opt arguments>..."),
125                                      cl::ZeroOrMore, cl::PositionalEatsArgs);
126 
127 /// runPasses - Run the specified passes on Program, outputting a bitcode file
128 /// and writing the filename into OutputFile if successful.  If the
129 /// optimizations fail for some reason (optimizer crashes), return true,
130 /// otherwise return false.  If DeleteOutput is set to true, the bitcode is
131 /// deleted on success, and the filename string is undefined.  This prints to
132 /// outs() a single line message indicating whether compilation was successful
133 /// or failed.
134 ///
135 bool BugDriver::runPasses(Module *Program,
136                           const std::vector<std::string> &Passes,
137                           std::string &OutputFilename, bool DeleteOutput,
138                           bool Quiet, unsigned NumExtraArgs,
139                           const char *const *ExtraArgs) const {
140   // setup the output file name
141   outs().flush();
142   SmallString<128> UniqueFilename;
143   std::error_code EC = sys::fs::createUniqueFile(
144       OutputPrefix + "-output-%%%%%%%.bc", UniqueFilename);
145   if (EC) {
146     errs() << getToolName()
147            << ": Error making unique filename: " << EC.message() << "\n";
148     return 1;
149   }
150   OutputFilename = UniqueFilename.str();
151 
152   // set up the input file name
153   Expected<sys::fs::TempFile> Temp =
154       sys::fs::TempFile::create(OutputPrefix + "-input-%%%%%%%.bc");
155   if (!Temp) {
156     errs() << getToolName()
157            << ": Error making unique filename: " << toString(Temp.takeError())
158            << "\n";
159     return 1;
160   }
161   DiscardTemp Discard{*Temp};
162   raw_fd_ostream OS(Temp->FD, /*shouldClose*/ false);
163 
164   WriteBitcodeToFile(Program, OS, PreserveBitcodeUseListOrder);
165   OS.flush();
166   if (OS.has_error()) {
167     errs() << "Error writing bitcode file: " << Temp->TmpName << "\n";
168     OS.clear_error();
169     return 1;
170   }
171 
172   std::string tool = OptCmd;
173   if (OptCmd.empty()) {
174     if (ErrorOr<std::string> Path = sys::findProgramByName("opt"))
175       tool = *Path;
176     else
177       errs() << Path.getError().message() << "\n";
178   }
179   if (tool.empty()) {
180     errs() << "Cannot find `opt' in PATH!\n";
181     return 1;
182   }
183 
184   std::string Prog;
185   if (UseValgrind) {
186     if (ErrorOr<std::string> Path = sys::findProgramByName("valgrind"))
187       Prog = *Path;
188     else
189       errs() << Path.getError().message() << "\n";
190   } else
191     Prog = tool;
192   if (Prog.empty()) {
193     errs() << "Cannot find `valgrind' in PATH!\n";
194     return 1;
195   }
196 
197   // setup the child process' arguments
198   SmallVector<const char *, 8> Args;
199   if (UseValgrind) {
200     Args.push_back("valgrind");
201     Args.push_back("--error-exitcode=1");
202     Args.push_back("-q");
203     Args.push_back(tool.c_str());
204   } else
205     Args.push_back(tool.c_str());
206 
207   for (unsigned i = 0, e = OptArgs.size(); i != e; ++i)
208     Args.push_back(OptArgs[i].c_str());
209   Args.push_back("-disable-symbolication");
210   Args.push_back("-o");
211   Args.push_back(OutputFilename.c_str());
212   std::vector<std::string> pass_args;
213   for (unsigned i = 0, e = PluginLoader::getNumPlugins(); i != e; ++i) {
214     pass_args.push_back(std::string("-load"));
215     pass_args.push_back(PluginLoader::getPlugin(i));
216   }
217   for (std::vector<std::string>::const_iterator I = Passes.begin(),
218                                                 E = Passes.end();
219        I != E; ++I)
220     pass_args.push_back(std::string("-") + (*I));
221   for (std::vector<std::string>::const_iterator I = pass_args.begin(),
222                                                 E = pass_args.end();
223        I != E; ++I)
224     Args.push_back(I->c_str());
225   Args.push_back(Temp->TmpName.c_str());
226   for (unsigned i = 0; i < NumExtraArgs; ++i)
227     Args.push_back(*ExtraArgs);
228   Args.push_back(nullptr);
229 
230   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.data(), nullptr, Redirects,
244                                    Timeout, 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