blob: 64fe675de20ccaf7bb1cd9e44c237f111dfd3b60 [file] [log] [blame]
Chris Lattnerafade922002-11-20 22:28:10 +00001//===- OptimizerDriver.cpp - Allow BugPoint to run passes safely ----------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
John Criswell7c0e0222003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner21c62da2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
John Criswell7c0e0222003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerafade922002-11-20 22:28:10 +00009//
10// This file defines an interface that allows bugpoint to run various passes
Misha Brukmancf00c4a2003-10-10 17:57:28 +000011// 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
Chris Lattnerafade922002-11-20 22:28:10 +000013// 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"
Brian Gesiakdcf592e2018-12-10 00:56:13 +000019#include "ToolRunner.h"
Teresa Johnsona5479192016-11-11 05:34:58 +000020#include "llvm/Bitcode/BitcodeWriter.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000021#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/Module.h"
Reid Spencerc4bb0522005-12-22 20:02:55 +000023#include "llvm/Support/CommandLine.h"
Rafael Espindola7f99f74b2010-08-07 23:03:21 +000024#include "llvm/Support/Debug.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000025#include "llvm/Support/FileUtilities.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000026#include "llvm/Support/Path.h"
27#include "llvm/Support/Program.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000028#include "llvm/Support/ToolOutputFile.h"
Andrew Lenharthe4da1dd2006-01-26 18:37:21 +000029
30#define DONT_GET_PLUGIN_LOADER_OPTION
31#include "llvm/Support/PluginLoader.h"
32
Rafael Espindola2c073ee2013-06-18 15:54:13 +000033
Chris Lattnerfa761832004-01-14 03:38:37 +000034using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000035
Chandler Carruth283b3992014-04-21 22:55:11 +000036#define DEBUG_TYPE "bugpoint"
37
Daniel Dunbar68ccdaa2009-09-07 19:26:11 +000038namespace llvm {
Justin Bogner388e8b92016-09-02 01:21:37 +000039extern cl::opt<std::string> OutputPrefix;
Daniel Dunbar68ccdaa2009-09-07 19:26:11 +000040}
Chris Lattner03b69632007-05-06 05:47:06 +000041
Duncan P. N. Exon Smith8d61ee92015-04-15 03:14:06 +000042static 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
David Blaikie4fadb112017-06-01 19:20:26 +000047static cl::opt<std::string>
48 OptCmd("opt-command", cl::init(""),
49 cl::desc("Path to opt. (default: search path "
50 "for 'opt'.)"));
Reid Spencerc4bb0522005-12-22 20:02:55 +000051
Rafael Espindolacdac12c2018-02-14 21:44:34 +000052/// This writes the current "Program" to the named bitcode file. If an error
53/// occurs, true is returned.
54static bool writeProgramToFileAux(ToolOutputFile &Out, const Module &M) {
55 WriteBitcodeToFile(M, Out.os(), PreserveBitcodeUseListOrder);
Rafael Espindola88088f42013-06-18 15:29:32 +000056 Out.os().close();
57 if (!Out.os().has_error()) {
58 Out.keep();
59 return false;
60 }
61 return true;
62}
63
64bool BugDriver::writeProgramToFile(const std::string &Filename, int FD,
Rafael Espindolacdac12c2018-02-14 21:44:34 +000065 const Module &M) const {
Reid Kleckner97ca9642017-09-23 01:03:17 +000066 ToolOutputFile Out(Filename, FD);
Rafael Espindola88088f42013-06-18 15:29:32 +000067 return writeProgramToFileAux(Out, M);
68}
69
Rafael Espindolacdac12c2018-02-14 21:44:34 +000070bool BugDriver::writeProgramToFile(int FD, const Module &M) const {
Rafael Espindolac1382282017-11-16 21:40:10 +000071 raw_fd_ostream OS(FD, /*shouldClose*/ false);
Rafael Espindolacdac12c2018-02-14 21:44:34 +000072 WriteBitcodeToFile(M, OS, PreserveBitcodeUseListOrder);
Rafael Espindolac1382282017-11-16 21:40:10 +000073 OS.flush();
74 if (!OS.has_error())
75 return false;
76 OS.clear_error();
77 return true;
78}
79
Chris Lattner218e26e2002-12-23 23:49:59 +000080bool BugDriver::writeProgramToFile(const std::string &Filename,
Rafael Espindolacdac12c2018-02-14 21:44:34 +000081 const Module &M) const {
Rafael Espindola8c968622014-08-25 18:16:47 +000082 std::error_code EC;
Reid Kleckner97ca9642017-09-23 01:03:17 +000083 ToolOutputFile Out(Filename, EC, sys::fs::F_None);
Rafael Espindola8c968622014-08-25 18:16:47 +000084 if (!EC)
Rafael Espindola88088f42013-06-18 15:29:32 +000085 return writeProgramToFileAux(Out, M);
Dan Gohmanf2914012010-08-20 16:59:15 +000086 return true;
Chris Lattnerafade922002-11-20 22:28:10 +000087}
88
Rafael Espindolacdac12c2018-02-14 21:44:34 +000089/// This function is used to output the current Program to a file named
90/// "bugpoint-ID.bc".
91void BugDriver::EmitProgressBitcode(const Module &M, const std::string &ID,
Justin Bogner388e8b92016-09-02 01:21:37 +000092 bool NoFlyer) const {
Gabor Greif8ff70c22007-07-04 21:55:50 +000093 // Output the input to the current pass to a bitcode file, emit a message
Chris Lattnerafade922002-11-20 22:28:10 +000094 // telling the user how to reproduce it: opt -foo blah.bc
95 //
Daniel Dunbar68ccdaa2009-09-07 19:26:11 +000096 std::string Filename = OutputPrefix + "-" + ID + ".bc";
Rafael Espindolabae1b712010-07-28 18:12:30 +000097 if (writeProgramToFile(Filename, M)) {
Justin Bogner388e8b92016-09-02 01:21:37 +000098 errs() << "Error opening file '" << Filename << "' for writing!\n";
Chris Lattnerafade922002-11-20 22:28:10 +000099 return;
100 }
101
Dan Gohmanac95cc72009-07-16 15:30:09 +0000102 outs() << "Emitted bitcode to '" << Filename << "'\n";
Justin Bogner388e8b92016-09-02 01:21:37 +0000103 if (NoFlyer || PassesToRun.empty())
104 return;
Dan Gohmanac95cc72009-07-16 15:30:09 +0000105 outs() << "\n*** You can reproduce the problem with: ";
Justin Bogner388e8b92016-09-02 01:21:37 +0000106 if (UseValgrind)
107 outs() << "valgrind ";
Chris Lattner1aa73cc2012-03-19 23:42:11 +0000108 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";
Chris Lattnerafade922002-11-20 22:28:10 +0000113}
114
Justin Bogner388e8b92016-09-02 01:21:37 +0000115cl::opt<bool> SilencePasses(
116 "silence-passes",
117 cl::desc("Suppress output of running passes (both stdout and stderr)"));
Matthijs Kooijmanfbea2272008-06-12 13:02:26 +0000118
Rafael Espindolaec62d532010-08-08 22:14:20 +0000119static cl::list<std::string> OptArgs("opt-args", cl::Positional,
120 cl::desc("<opt arguments>..."),
121 cl::ZeroOrMore, cl::PositionalEatsArgs);
122
Gabor Greif8ff70c22007-07-04 21:55:50 +0000123/// runPasses - Run the specified passes on Program, outputting a bitcode file
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000124/// and writing the filename into OutputFile if successful. If the
Chris Lattnerafade922002-11-20 22:28:10 +0000125/// optimizations fail for some reason (optimizer crashes), return true,
Gabor Greif8ff70c22007-07-04 21:55:50 +0000126/// otherwise return false. If DeleteOutput is set to true, the bitcode is
Chris Lattnerafade922002-11-20 22:28:10 +0000127/// deleted on success, and the filename string is undefined. This prints to
Dan Gohmanac95cc72009-07-16 15:30:09 +0000128/// outs() a single line message indicating whether compilation was successful
129/// or failed.
Chris Lattnerafade922002-11-20 22:28:10 +0000130///
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000131bool BugDriver::runPasses(Module &Program,
Rafael Espindola8261dfe2010-08-08 03:55:08 +0000132 const std::vector<std::string> &Passes,
Chris Lattner218e26e2002-12-23 23:49:59 +0000133 std::string &OutputFilename, bool DeleteOutput,
Nick Lewycky6fa98b12007-11-14 06:47:06 +0000134 bool Quiet, unsigned NumExtraArgs,
Justin Bogner388e8b92016-09-02 01:21:37 +0000135 const char *const *ExtraArgs) const {
Reid Spencerc4bb0522005-12-22 20:02:55 +0000136 // setup the output file name
Dan Gohmanac95cc72009-07-16 15:30:09 +0000137 outs().flush();
Rafael Espindola2c073ee2013-06-18 15:54:13 +0000138 SmallString<128> UniqueFilename;
Rafael Espindola1ad45022014-06-13 03:07:50 +0000139 std::error_code EC = sys::fs::createUniqueFile(
Rafael Espindola200c7482013-07-05 21:01:08 +0000140 OutputPrefix + "-output-%%%%%%%.bc", UniqueFilename);
Rafael Espindola2c073ee2013-06-18 15:54:13 +0000141 if (EC) {
Justin Bogner388e8b92016-09-02 01:21:37 +0000142 errs() << getToolName()
143 << ": Error making unique filename: " << EC.message() << "\n";
Chris Lattnerb515d752009-08-23 07:49:08 +0000144 return 1;
Chris Lattnerafade922002-11-20 22:28:10 +0000145 }
Rafael Espindola2c073ee2013-06-18 15:54:13 +0000146 OutputFilename = UniqueFilename.str();
Rafael Espindola2c073ee2013-06-18 15:54:13 +0000147
148 // set up the input file name
Rafael Espindolad0222ef2017-11-16 01:06:36 +0000149 Expected<sys::fs::TempFile> Temp =
150 sys::fs::TempFile::create(OutputPrefix + "-input-%%%%%%%.bc");
151 if (!Temp) {
Justin Bogner388e8b92016-09-02 01:21:37 +0000152 errs() << getToolName()
Rafael Espindolad0222ef2017-11-16 01:06:36 +0000153 << ": Error making unique filename: " << toString(Temp.takeError())
154 << "\n";
Rafael Espindola2c073ee2013-06-18 15:54:13 +0000155 return 1;
156 }
Rafael Espindolad0222ef2017-11-16 01:06:36 +0000157 DiscardTemp Discard{*Temp};
158 raw_fd_ostream OS(Temp->FD, /*shouldClose*/ false);
Rafael Espindola2c073ee2013-06-18 15:54:13 +0000159
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000160 WriteBitcodeToFile(Program, OS, PreserveBitcodeUseListOrder);
Rafael Espindolad0222ef2017-11-16 01:06:36 +0000161 OS.flush();
162 if (OS.has_error()) {
163 errs() << "Error writing bitcode file: " << Temp->TmpName << "\n";
164 OS.clear_error();
Dan Gohmanf2914012010-08-20 16:59:15 +0000165 return 1;
166 }
Dan Gohmancc11df02010-10-29 16:18:26 +0000167
Michael J. Spencer58206dd2014-11-04 01:29:59 +0000168 std::string tool = OptCmd;
169 if (OptCmd.empty()) {
Brian Gesiakdcf592e2018-12-10 00:56:13 +0000170 if (ErrorOr<std::string> Path =
171 FindProgramByName("opt", getToolName(), &OutputPrefix))
Michael J. Spencer58206dd2014-11-04 01:29:59 +0000172 tool = *Path;
Michael J. Spencer04936822014-11-07 21:30:36 +0000173 else
174 errs() << Path.getError().message() << "\n";
Michael J. Spencer58206dd2014-11-04 01:29:59 +0000175 }
Dan Gohmancc11df02010-10-29 16:18:26 +0000176 if (tool.empty()) {
Chris Lattner1aa73cc2012-03-19 23:42:11 +0000177 errs() << "Cannot find `opt' in PATH!\n";
Dan Gohmancc11df02010-10-29 16:18:26 +0000178 return 1;
179 }
Vedant Kumar099ec622018-02-09 06:09:15 +0000180 if (!sys::fs::exists(tool)) {
181 errs() << "Specified `opt' binary does not exist: " << tool << "\n";
182 return 1;
183 }
Dan Gohmancc11df02010-10-29 16:18:26 +0000184
Michael J. Spencer58206dd2014-11-04 01:29:59 +0000185 std::string Prog;
186 if (UseValgrind) {
Michael J. Spencer04936822014-11-07 21:30:36 +0000187 if (ErrorOr<std::string> Path = sys::findProgramByName("valgrind"))
Michael J. Spencer58206dd2014-11-04 01:29:59 +0000188 Prog = *Path;
Michael J. Spencer04936822014-11-07 21:30:36 +0000189 else
190 errs() << Path.getError().message() << "\n";
Michael J. Spencer58206dd2014-11-04 01:29:59 +0000191 } else
192 Prog = tool;
193 if (Prog.empty()) {
194 errs() << "Cannot find `valgrind' in PATH!\n";
195 return 1;
196 }
197
Reid Spencerc4bb0522005-12-22 20:02:55 +0000198 // setup the child process' arguments
Zachary Turner0dcc1152018-06-12 17:43:52 +0000199 SmallVector<StringRef, 8> Args;
Nick Lewycky40394bc2006-09-14 03:49:54 +0000200 if (UseValgrind) {
Chris Lattner74382b72009-08-23 22:45:37 +0000201 Args.push_back("valgrind");
202 Args.push_back("--error-exitcode=1");
203 Args.push_back("-q");
Zachary Turner0dcc1152018-06-12 17:43:52 +0000204 Args.push_back(tool);
Nick Lewycky40394bc2006-09-14 03:49:54 +0000205 } else
Zachary Turner0dcc1152018-06-12 17:43:52 +0000206 Args.push_back(tool);
Nick Lewycky40394bc2006-09-14 03:49:54 +0000207
Rafael Espindolaec62d532010-08-08 22:14:20 +0000208 for (unsigned i = 0, e = OptArgs.size(); i != e; ++i)
Zachary Turner0dcc1152018-06-12 17:43:52 +0000209 Args.push_back(OptArgs[i]);
David Blaikie5dc796d2017-06-09 07:29:03 +0000210 Args.push_back("-disable-symbolication");
211 Args.push_back("-o");
Zachary Turner0dcc1152018-06-12 17:43:52 +0000212 Args.push_back(OutputFilename);
Reid Spencerc4bb0522005-12-22 20:02:55 +0000213 std::vector<std::string> pass_args;
Andrew Lenharthe4da1dd2006-01-26 18:37:21 +0000214 for (unsigned i = 0, e = PluginLoader::getNumPlugins(); i != e; ++i) {
Justin Bogner388e8b92016-09-02 01:21:37 +0000215 pass_args.push_back(std::string("-load"));
216 pass_args.push_back(PluginLoader::getPlugin(i));
Andrew Lenharthe4da1dd2006-01-26 18:37:21 +0000217 }
Rafael Espindola8261dfe2010-08-08 03:55:08 +0000218 for (std::vector<std::string>::const_iterator I = Passes.begin(),
Justin Bogner388e8b92016-09-02 01:21:37 +0000219 E = Passes.end();
220 I != E; ++I)
221 pass_args.push_back(std::string("-") + (*I));
Reid Spencerc4bb0522005-12-22 20:02:55 +0000222 for (std::vector<std::string>::const_iterator I = pass_args.begin(),
Justin Bogner388e8b92016-09-02 01:21:37 +0000223 E = pass_args.end();
224 I != E; ++I)
Chris Lattner74382b72009-08-23 22:45:37 +0000225 Args.push_back(I->c_str());
Rafael Espindolad0222ef2017-11-16 01:06:36 +0000226 Args.push_back(Temp->TmpName.c_str());
Nick Lewycky6fa98b12007-11-14 06:47:06 +0000227 for (unsigned i = 0; i < NumExtraArgs; ++i)
Chris Lattner74382b72009-08-23 22:45:37 +0000228 Args.push_back(*ExtraArgs);
Chris Lattnerafade922002-11-20 22:28:10 +0000229
Nicola Zaghen0818e782018-05-14 12:53:11 +0000230 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";);
Rafael Espindola7f99f74b2010-08-07 23:03:21 +0000234
Alexander Kornienko87e117d2017-09-13 17:03:37 +0000235 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 }
Matthijs Kooijmanfbea2272008-06-12 13:02:26 +0000241
Rafael Espindola2c073ee2013-06-18 15:54:13 +0000242 std::string ErrMsg;
Zachary Turner0dcc1152018-06-12 17:43:52 +0000243 int result = sys::ExecuteAndWait(Prog, Args, None, Redirects, Timeout,
244 MemoryLimit, &ErrMsg);
Chris Lattnerb83c0f32004-05-12 02:55:45 +0000245
Gabor Greif8ff70c22007-07-04 21:55:50 +0000246 // If we are supposed to delete the bitcode file or if the passes crashed,
Chris Lattnerb83c0f32004-05-12 02:55:45 +0000247 // remove it now. This may fail if the file was never created, but that's ok.
Reid Spencerc4bb0522005-12-22 20:02:55 +0000248 if (DeleteOutput || result != 0)
Rafael Espindola366f5102013-06-18 15:33:18 +0000249 sys::fs::remove(OutputFilename);
Jeff Cohen5fb6ed42005-01-22 17:36:17 +0000250
Chris Lattner24271cf2003-06-02 04:54:16 +0000251 if (!Quiet) {
Reid Spencerc4bb0522005-12-22 20:02:55 +0000252 if (result == 0)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000253 outs() << "Success!\n";
Reid Spencerc4bb0522005-12-22 20:02:55 +0000254 else if (result > 0)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000255 outs() << "Exited with error code '" << result << "'\n";
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000256 else if (result < 0) {
257 if (result == -1)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000258 outs() << "Execute failed: " << ErrMsg << "\n";
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000259 else
Andrew Trickdc5948d2011-05-21 00:56:46 +0000260 outs() << "Crashed: " << ErrMsg << "\n";
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000261 }
Reid Spencerc4bb0522005-12-22 20:02:55 +0000262 if (result & 0x01000000)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000263 outs() << "Dumped core\n";
Chris Lattner24271cf2003-06-02 04:54:16 +0000264 }
Chris Lattnerafade922002-11-20 22:28:10 +0000265
266 // Was the child successful?
Reid Spencerc4bb0522005-12-22 20:02:55 +0000267 return result != 0;
Chris Lattnerafade922002-11-20 22:28:10 +0000268}
Brian Gaeked0fde302003-11-11 22:41:34 +0000269
Rafael Espindola1bfd87a2014-08-26 17:19:03 +0000270std::unique_ptr<Module>
271BugDriver::runPassesOn(Module *M, const std::vector<std::string> &Passes,
Justin Bogner388e8b92016-09-02 01:21:37 +0000272 unsigned NumExtraArgs, const char *const *ExtraArgs) {
Gabor Greif8ff70c22007-07-04 21:55:50 +0000273 std::string BitcodeResult;
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000274 if (runPasses(*M, Passes, BitcodeResult, false /*delete*/, true /*quiet*/,
Nick Lewycky6fa98b12007-11-14 06:47:06 +0000275 NumExtraArgs, ExtraArgs)) {
Craig Topper573faec2014-04-25 04:24:47 +0000276 return nullptr;
Chris Lattner0a002562004-03-14 21:21:57 +0000277 }
Chris Lattner3b6441e2004-03-14 21:17:03 +0000278
Rafael Espindola1bfd87a2014-08-26 17:19:03 +0000279 std::unique_ptr<Module> Ret = parseInputFile(BitcodeResult, Context);
Craig Topper573faec2014-04-25 04:24:47 +0000280 if (!Ret) {
Justin Bogner388e8b92016-09-02 01:21:37 +0000281 errs() << getToolName() << ": Error reading bitcode file '" << BitcodeResult
282 << "'!\n";
Chris Lattner3b6441e2004-03-14 21:17:03 +0000283 exit(1);
284 }
Rafael Espindola366f5102013-06-18 15:33:18 +0000285 sys::fs::remove(BitcodeResult);
Chris Lattner3b6441e2004-03-14 21:17:03 +0000286 return Ret;
287}