blob: 0162420861281450d7852ce2114279b685143333 [file] [log] [blame]
Chris Lattnerde4aa4c2002-12-23 23:50:16 +00001//===- Miscompilation.cpp - Debug program miscompilations -----------------===//
Misha Brukman650ba8e2005-04-22 00:00:37 +00002//
John Criswell09344dc2003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner345353d2007-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 Brukman650ba8e2005-04-22 00:00:37 +00007//
John Criswell09344dc2003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerde4aa4c2002-12-23 23:50:16 +00009//
Chris Lattnerbf791612004-04-05 22:58:16 +000010// This file implements optimizer and code generation miscompilation debugging
11// support.
Chris Lattnerde4aa4c2002-12-23 23:50:16 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "BugDriver.h"
Chris Lattner9f5a1972003-04-24 20:16:29 +000016#include "ListReducer.h"
Daniel Dunbar8575a602009-08-18 03:35:57 +000017#include "ToolRunner.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000018#include "llvm/Config/config.h" // for HAVE_LINK_R
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/Constants.h"
20#include "llvm/IR/DerivedTypes.h"
21#include "llvm/IR/Instructions.h"
22#include "llvm/IR/Module.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000023#include "llvm/IR/Verifier.h"
Chandler Carruth6cc07df2014-03-06 03:42:23 +000024#include "llvm/Linker/Linker.h"
Misha Brukman0c2305b2003-08-07 21:19:30 +000025#include "llvm/Pass.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/FileUtilities.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000028#include "llvm/Transforms/Utils/Cloning.h"
Chris Lattner2f1aa112004-01-14 03:38:37 +000029using namespace llvm;
Chris Lattnerde4aa4c2002-12-23 23:50:16 +000030
Chris Lattnerbf791612004-04-05 22:58:16 +000031namespace llvm {
Daniel Dunbara53337f2009-09-07 19:26:11 +000032 extern cl::opt<std::string> OutputPrefix;
Chris Lattnerbf791612004-04-05 22:58:16 +000033 extern cl::list<std::string> InputArgv;
34}
35
Chris Lattnerfd72bed2004-03-14 20:50:42 +000036namespace {
Michael J. Spencer3df5c042011-03-31 13:06:39 +000037 static llvm::cl::opt<bool>
38 DisableLoopExtraction("disable-loop-extraction",
Reid Spencer471bcb72006-11-11 19:05:02 +000039 cl::desc("Don't extract loops when searching for miscompilations"),
40 cl::init(false));
Michael J. Spencer3df5c042011-03-31 13:06:39 +000041 static llvm::cl::opt<bool>
42 DisableBlockExtraction("disable-block-extraction",
David Goodwin2c04ff62009-07-28 23:08:36 +000043 cl::desc("Don't extract blocks when searching for miscompilations"),
44 cl::init(false));
Reid Spencer471bcb72006-11-11 19:05:02 +000045
Rafael Espindola33e81a82010-08-08 03:55:08 +000046 class ReduceMiscompilingPasses : public ListReducer<std::string> {
Chris Lattner2f1aa112004-01-14 03:38:37 +000047 BugDriver &BD;
48 public:
49 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +000050
Craig Toppere56917c2014-03-08 08:27:28 +000051 TestResult doTest(std::vector<std::string> &Prefix,
52 std::vector<std::string> &Suffix,
53 std::string &Error) override;
Chris Lattner2f1aa112004-01-14 03:38:37 +000054 };
55}
Chris Lattner16a41312003-04-24 17:02:17 +000056
Misha Brukman0784a602004-04-21 18:36:43 +000057/// TestResult - After passes have been split into a test group and a control
58/// group, see if they still break the program.
59///
Chris Lattner16a41312003-04-24 17:02:17 +000060ReduceMiscompilingPasses::TestResult
Rafael Espindola33e81a82010-08-08 03:55:08 +000061ReduceMiscompilingPasses::doTest(std::vector<std::string> &Prefix,
62 std::vector<std::string> &Suffix,
Nick Lewycky6ba630b2010-04-12 05:08:25 +000063 std::string &Error) {
Chris Lattner4a1a9d22003-04-25 03:16:05 +000064 // First, run the program with just the Suffix passes. If it is still broken
Chris Lattner16a41312003-04-24 17:02:17 +000065 // with JUST the kept passes, discard the prefix passes.
Dan Gohmanee051522009-07-16 15:30:09 +000066 outs() << "Checking to see if '" << getPassesString(Suffix)
67 << "' compiles correctly: ";
Chris Lattner16a41312003-04-24 17:02:17 +000068
Gabor Greif0e535c3c2007-07-04 21:55:50 +000069 std::string BitcodeResult;
Rafael Espindola315190b2010-08-05 00:29:04 +000070 if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false/*delete*/,
71 true/*quiet*/)) {
Dan Gohmand8db3762009-07-15 16:35:29 +000072 errs() << " Error running this sequence of passes"
73 << " on the input program!\n";
Chris Lattner92a9f7a2003-10-17 23:07:47 +000074 BD.setPassesToRun(Suffix);
Rafael Espindola594994a2010-07-28 18:12:30 +000075 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
Chris Lattneread1dff2004-02-18 21:02:04 +000076 exit(BD.debugOptimizerCrash());
Chris Lattner16a41312003-04-24 17:02:17 +000077 }
Michael J. Spencer3df5c042011-03-31 13:06:39 +000078
Chris Lattner16a41312003-04-24 17:02:17 +000079 // Check to see if the finished program matches the reference output...
Rafael Espindolac89b1ef2010-07-30 14:19:00 +000080 bool Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
81 true /*delete bitcode*/, &Error);
Nick Lewycky6ba630b2010-04-12 05:08:25 +000082 if (!Error.empty())
83 return InternalError;
84 if (Diff) {
Dan Gohmanee051522009-07-16 15:30:09 +000085 outs() << " nope.\n";
Chris Lattnerea2fa462005-01-15 00:07:19 +000086 if (Suffix.empty()) {
Dan Gohmand8db3762009-07-15 16:35:29 +000087 errs() << BD.getToolName() << ": I'm confused: the test fails when "
88 << "no passes are run, nondeterministic program?\n";
Chris Lattnerea2fa462005-01-15 00:07:19 +000089 exit(1);
90 }
Misha Brukman324e9e02004-04-22 20:02:09 +000091 return KeepSuffix; // Miscompilation detected!
Chris Lattner16a41312003-04-24 17:02:17 +000092 }
Dan Gohmanee051522009-07-16 15:30:09 +000093 outs() << " yup.\n"; // No miscompilation!
Chris Lattner16a41312003-04-24 17:02:17 +000094
95 if (Prefix.empty()) return NoFailure;
96
Chris Lattner4a1a9d22003-04-25 03:16:05 +000097 // Next, see if the program is broken if we run the "prefix" passes first,
Misha Brukman7fdaab42003-07-14 17:20:40 +000098 // then separately run the "kept" passes.
Dan Gohmanee051522009-07-16 15:30:09 +000099 outs() << "Checking to see if '" << getPassesString(Prefix)
100 << "' compiles correctly: ";
Chris Lattner16a41312003-04-24 17:02:17 +0000101
102 // If it is not broken with the kept passes, it's possible that the prefix
103 // passes must be run before the kept passes to break it. If the program
104 // WORKS after the prefix passes, but then fails if running the prefix AND
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000105 // kept passes, we can update our bitcode file to include the result of the
Chris Lattner16a41312003-04-24 17:02:17 +0000106 // prefix passes, then discard the prefix passes.
107 //
Rafael Espindola315190b2010-08-05 00:29:04 +0000108 if (BD.runPasses(BD.getProgram(), Prefix, BitcodeResult, false/*delete*/,
109 true/*quiet*/)) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000110 errs() << " Error running this sequence of passes"
111 << " on the input program!\n";
Chris Lattner7d147ae2003-10-17 23:03:16 +0000112 BD.setPassesToRun(Prefix);
Rafael Espindola594994a2010-07-28 18:12:30 +0000113 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
Chris Lattneread1dff2004-02-18 21:02:04 +0000114 exit(BD.debugOptimizerCrash());
Chris Lattner16a41312003-04-24 17:02:17 +0000115 }
116
117 // If the prefix maintains the predicate by itself, only keep the prefix!
Rafael Espindolac89b1ef2010-07-30 14:19:00 +0000118 Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "", false, &Error);
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000119 if (!Error.empty())
120 return InternalError;
121 if (Diff) {
Dan Gohmanee051522009-07-16 15:30:09 +0000122 outs() << " nope.\n";
Rafael Espindola18079582013-06-17 21:50:28 +0000123 sys::fs::remove(BitcodeResult);
Chris Lattner16a41312003-04-24 17:02:17 +0000124 return KeepPrefix;
125 }
Dan Gohmanee051522009-07-16 15:30:09 +0000126 outs() << " yup.\n"; // No miscompilation!
Chris Lattner16a41312003-04-24 17:02:17 +0000127
128 // Ok, so now we know that the prefix passes work, try running the suffix
129 // passes on the result of the prefix passes.
130 //
Rafael Espindola28b351a2014-08-26 17:19:03 +0000131 std::unique_ptr<Module> PrefixOutput =
132 parseInputFile(BitcodeResult, BD.getContext());
David Blaikie041f1aa2013-05-15 07:36:59 +0000133 if (!PrefixOutput) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000134 errs() << BD.getToolName() << ": Error reading bitcode file '"
135 << BitcodeResult << "'!\n";
Chris Lattner16a41312003-04-24 17:02:17 +0000136 exit(1);
137 }
Rafael Espindola18079582013-06-17 21:50:28 +0000138 sys::fs::remove(BitcodeResult);
Chris Lattner02cea4a2004-04-23 20:36:51 +0000139
140 // Don't check if there are no passes in the suffix.
141 if (Suffix.empty())
142 return NoFailure;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000143
Dan Gohmanee051522009-07-16 15:30:09 +0000144 outs() << "Checking to see if '" << getPassesString(Suffix)
Chris Lattner16a41312003-04-24 17:02:17 +0000145 << "' passes compile correctly after the '"
146 << getPassesString(Prefix) << "' passes: ";
147
Ahmed Charles56440fd2014-03-06 05:51:42 +0000148 std::unique_ptr<Module> OriginalInput(
149 BD.swapProgramIn(PrefixOutput.release()));
Rafael Espindola315190b2010-08-05 00:29:04 +0000150 if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false/*delete*/,
151 true/*quiet*/)) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000152 errs() << " Error running this sequence of passes"
153 << " on the input program!\n";
Chris Lattner92a9f7a2003-10-17 23:07:47 +0000154 BD.setPassesToRun(Suffix);
Rafael Espindola594994a2010-07-28 18:12:30 +0000155 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
Chris Lattneread1dff2004-02-18 21:02:04 +0000156 exit(BD.debugOptimizerCrash());
Chris Lattner16a41312003-04-24 17:02:17 +0000157 }
158
159 // Run the result...
Rafael Espindolac89b1ef2010-07-30 14:19:00 +0000160 Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
161 true /*delete bitcode*/, &Error);
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000162 if (!Error.empty())
163 return InternalError;
164 if (Diff) {
Dan Gohmanee051522009-07-16 15:30:09 +0000165 outs() << " nope.\n";
Chris Lattner4a1a9d22003-04-25 03:16:05 +0000166 return KeepSuffix;
Chris Lattner16a41312003-04-24 17:02:17 +0000167 }
168
169 // Otherwise, we must not be running the bad pass anymore.
Dan Gohmanee051522009-07-16 15:30:09 +0000170 outs() << " yup.\n"; // No miscompilation!
Jeffrey Yasskine476fa02010-05-11 23:25:16 +0000171 // Restore orig program & free test.
Ahmed Charles96c9d952014-03-05 10:19:29 +0000172 delete BD.swapProgramIn(OriginalInput.release());
Chris Lattner16a41312003-04-24 17:02:17 +0000173 return NoFailure;
174}
175
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000176namespace {
Chris Lattner2f1aa112004-01-14 03:38:37 +0000177 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
178 BugDriver &BD;
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000179 bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000180 public:
Chris Lattner0434ba32004-04-05 21:37:38 +0000181 ReduceMiscompilingFunctions(BugDriver &bd,
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000182 bool (*F)(BugDriver &, Module *, Module *,
183 std::string &))
Chris Lattner0434ba32004-04-05 21:37:38 +0000184 : BD(bd), TestFn(F) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000185
Craig Toppere56917c2014-03-08 08:27:28 +0000186 TestResult doTest(std::vector<Function*> &Prefix,
187 std::vector<Function*> &Suffix,
188 std::string &Error) override {
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000189 if (!Suffix.empty()) {
190 bool Ret = TestFuncs(Suffix, Error);
191 if (!Error.empty())
192 return InternalError;
193 if (Ret)
194 return KeepSuffix;
195 }
196 if (!Prefix.empty()) {
197 bool Ret = TestFuncs(Prefix, Error);
198 if (!Error.empty())
199 return InternalError;
200 if (Ret)
201 return KeepPrefix;
202 }
Chris Lattner2f1aa112004-01-14 03:38:37 +0000203 return NoFailure;
204 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000205
Rafael Espindola235457c2010-07-26 00:07:51 +0000206 bool TestFuncs(const std::vector<Function*> &Prefix, std::string &Error);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000207 };
208}
Chris Lattner16a41312003-04-24 17:02:17 +0000209
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000210/// TestMergedProgram - Given two modules, link them together and run the
Rafael Espindolae4904602010-07-31 14:34:49 +0000211/// program, checking to see if the program matches the diff. If there is
212/// an error, return NULL. If not, return the merged module. The Broken argument
213/// will be set to true if the output is different. If the DeleteInputs
214/// argument is set to true then this function deletes both input
215/// modules before it returns.
Misha Brukman0784a602004-04-21 18:36:43 +0000216///
Rafael Espindolae4904602010-07-31 14:34:49 +0000217static Module *TestMergedProgram(const BugDriver &BD, Module *M1, Module *M2,
218 bool DeleteInputs, std::string &Error,
219 bool &Broken) {
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000220 // Link the two portions of the program back to together.
221 std::string ErrorMsg;
Chris Lattnerd3087972004-11-16 06:31:38 +0000222 if (!DeleteInputs) {
223 M1 = CloneModule(M1);
224 M2 = CloneModule(M2);
225 }
Tanya Lattnercbb91402011-10-11 00:24:54 +0000226 if (Linker::LinkModules(M1, M2, Linker::DestroySource, &ErrorMsg)) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000227 errs() << BD.getToolName() << ": Error linking modules together:"
228 << ErrorMsg << '\n';
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000229 exit(1);
230 }
Chris Lattnerd3087972004-11-16 06:31:38 +0000231 delete M2; // We are done with this module.
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000232
Rafael Espindolae4904602010-07-31 14:34:49 +0000233 // Execute the program.
234 Broken = BD.diffProgram(M1, "", "", false, &Error);
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000235 if (!Error.empty()) {
Rafael Espindolac89b1ef2010-07-30 14:19:00 +0000236 // Delete the linked module
237 delete M1;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000238 return nullptr;
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000239 }
Rafael Espindolae4904602010-07-31 14:34:49 +0000240 return M1;
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000241}
242
Misha Brukman0784a602004-04-21 18:36:43 +0000243/// TestFuncs - split functions in a Module into two groups: those that are
244/// under consideration for miscompilation vs. those that are not, and test
245/// accordingly. Each group of functions becomes a separate Module.
246///
Rafael Espindola235457c2010-07-26 00:07:51 +0000247bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*> &Funcs,
248 std::string &Error) {
Chris Lattner16a41312003-04-24 17:02:17 +0000249 // Test to see if the function is misoptimized if we ONLY run it on the
250 // functions listed in Funcs.
Dan Gohmanee051522009-07-16 15:30:09 +0000251 outs() << "Checking to see if the program is misoptimized when "
252 << (Funcs.size()==1 ? "this function is" : "these functions are")
253 << " run through the pass"
254 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000255 PrintFunctionList(Funcs);
Dan Gohmanee051522009-07-16 15:30:09 +0000256 outs() << '\n';
Chris Lattner16a41312003-04-24 17:02:17 +0000257
Rafael Espindola235457c2010-07-26 00:07:51 +0000258 // Create a clone for two reasons:
259 // * If the optimization passes delete any function, the deleted function
260 // will be in the clone and Funcs will still point to valid memory
261 // * If the optimization passes use interprocedural information to break
262 // a function, we want to continue with the original function. Otherwise
263 // we can conclude that a function triggers the bug when in fact one
264 // needs a larger set of original functions to do so.
Rafael Espindola229e38f2010-10-13 01:36:30 +0000265 ValueToValueMapTy VMap;
Rafael Espindola235457c2010-07-26 00:07:51 +0000266 Module *Clone = CloneModule(BD.getProgram(), VMap);
267 Module *Orig = BD.swapProgramIn(Clone);
268
269 std::vector<Function*> FuncsOnClone;
270 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
271 Function *F = cast<Function>(VMap[Funcs[i]]);
272 FuncsOnClone.push_back(F);
273 }
274
275 // Split the module into the two halves of the program we want.
276 VMap.clear();
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000277 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
Rafael Espindola235457c2010-07-26 00:07:51 +0000278 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, FuncsOnClone,
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000279 VMap);
Chris Lattner16a41312003-04-24 17:02:17 +0000280
Nick Lewyckyc6243022007-11-14 06:47:06 +0000281 // Run the predicate, note that the predicate will delete both input modules.
Rafael Espindola235457c2010-07-26 00:07:51 +0000282 bool Broken = TestFn(BD, ToOptimize, ToNotOptimize, Error);
283
284 delete BD.swapProgramIn(Orig);
285
286 return Broken;
Chris Lattner16a41312003-04-24 17:02:17 +0000287}
288
Chris Lattnerdc2cb5a2010-01-16 21:34:01 +0000289/// DisambiguateGlobalSymbols - Give anonymous global values names.
Misha Brukman0784a602004-04-21 18:36:43 +0000290///
Chris Lattnerdfbb1d12004-04-11 23:52:35 +0000291static void DisambiguateGlobalSymbols(Module *M) {
Chris Lattner34d26c32006-05-04 23:35:31 +0000292 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
Chris Lattner6a941f02010-01-16 21:34:51 +0000293 I != E; ++I)
Chris Lattnerdc2cb5a2010-01-16 21:34:01 +0000294 if (!I->hasName())
295 I->setName("anon_global");
Chris Lattner6a941f02010-01-16 21:34:51 +0000296 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattnerdc2cb5a2010-01-16 21:34:01 +0000297 if (!I->hasName())
298 I->setName("anon_fn");
Chris Lattnerdfbb1d12004-04-11 23:52:35 +0000299}
300
Chris Lattnerbcec7872004-03-14 22:08:00 +0000301/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
302/// check to see if we can extract the loops in the region without obscuring the
303/// bug. If so, it reduces the amount of code identified.
Misha Brukman0784a602004-04-21 18:36:43 +0000304///
Chris Lattner0434ba32004-04-05 21:37:38 +0000305static bool ExtractLoops(BugDriver &BD,
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000306 bool (*TestFn)(BugDriver &, Module *, Module *,
307 std::string &),
308 std::vector<Function*> &MiscompiledFunctions,
309 std::string &Error) {
Chris Lattnerbcec7872004-03-14 22:08:00 +0000310 bool MadeChange = false;
311 while (1) {
Chris Lattnerbd615f52005-08-02 23:25:56 +0000312 if (BugpointIsInterrupted) return MadeChange;
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000313
Rafael Espindola229e38f2010-10-13 01:36:30 +0000314 ValueToValueMapTy VMap;
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000315 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
Chris Lattnerbcec7872004-03-14 22:08:00 +0000316 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohman956ae9d2009-04-22 15:57:18 +0000317 MiscompiledFunctions,
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000318 VMap);
Rafael Espindola28b351a2014-08-26 17:19:03 +0000319 Module *ToOptimizeLoopExtracted = BD.extractLoop(ToOptimize).release();
Chris Lattnerbcec7872004-03-14 22:08:00 +0000320 if (!ToOptimizeLoopExtracted) {
321 // If the loop extractor crashed or if there were no extractible loops,
322 // then this chapter of our odyssey is over with.
323 delete ToNotOptimize;
324 delete ToOptimize;
325 return MadeChange;
326 }
327
Dan Gohmand8db3762009-07-15 16:35:29 +0000328 errs() << "Extracted a loop from the breaking portion of the program.\n";
Chris Lattnerbcec7872004-03-14 22:08:00 +0000329
330 // Bugpoint is intentionally not very trusting of LLVM transformations. In
331 // particular, we're not going to assume that the loop extractor works, so
332 // we're going to test the newly loop extracted program to make sure nothing
333 // has broken. If something broke, then we'll inform the user and stop
334 // extraction.
Dan Gohman414cf502008-12-08 04:02:47 +0000335 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
Rafael Espindolae4904602010-07-31 14:34:49 +0000336 bool Failure;
Rafael Espindola28b351a2014-08-26 17:19:03 +0000337 Module *New = TestMergedProgram(BD, ToOptimizeLoopExtracted,
338 ToNotOptimize, false, Error, Failure);
Rafael Espindolae4904602010-07-31 14:34:49 +0000339 if (!New)
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000340 return false;
Hal Finkele9efbf12013-08-02 21:13:42 +0000341
Rafael Espindolae4904602010-07-31 14:34:49 +0000342 // Delete the original and set the new program.
Hal Finkele9efbf12013-08-02 21:13:42 +0000343 Module *Old = BD.swapProgramIn(New);
344 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
345 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
346 delete Old;
347
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000348 if (Failure) {
Chris Lattnerbf791612004-04-05 22:58:16 +0000349 BD.switchToInterpreter(AI);
350
Chris Lattnerbcec7872004-03-14 22:08:00 +0000351 // Merged program doesn't work anymore!
Dan Gohmand8db3762009-07-15 16:35:29 +0000352 errs() << " *** ERROR: Loop extraction broke the program. :("
353 << " Please report a bug!\n";
354 errs() << " Continuing on with un-loop-extracted version.\n";
Chris Lattner257008b2005-05-08 21:54:56 +0000355
Daniel Dunbara53337f2009-09-07 19:26:11 +0000356 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
357 ToNotOptimize);
358 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
359 ToOptimize);
360 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
Chris Lattner257008b2005-05-08 21:54:56 +0000361 ToOptimizeLoopExtracted);
362
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000363 errs() << "Please submit the "
Daniel Dunbara53337f2009-09-07 19:26:11 +0000364 << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
Chris Lattner257008b2005-05-08 21:54:56 +0000365 delete ToOptimize;
Chris Lattnerbcec7872004-03-14 22:08:00 +0000366 delete ToNotOptimize;
Chris Lattnerbcec7872004-03-14 22:08:00 +0000367 return MadeChange;
368 }
Chris Lattner257008b2005-05-08 21:54:56 +0000369 delete ToOptimize;
Chris Lattnerbf791612004-04-05 22:58:16 +0000370 BD.switchToInterpreter(AI);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000371
Dan Gohmanee051522009-07-16 15:30:09 +0000372 outs() << " Testing after loop extraction:\n";
Chris Lattner0434ba32004-04-05 21:37:38 +0000373 // Clone modules, the tester function will free them.
Hal Finkele9efbf12013-08-02 21:13:42 +0000374 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted, VMap);
375 Module *TNOBackup = CloneModule(ToNotOptimize, VMap);
376
377 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
378 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
379
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000380 Failure = TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize, Error);
381 if (!Error.empty())
382 return false;
Hal Finkele9efbf12013-08-02 21:13:42 +0000383
384 ToOptimizeLoopExtracted = TOLEBackup;
385 ToNotOptimize = TNOBackup;
386
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000387 if (!Failure) {
Dan Gohmanee051522009-07-16 15:30:09 +0000388 outs() << "*** Loop extraction masked the problem. Undoing.\n";
Chris Lattnerbcec7872004-03-14 22:08:00 +0000389 // If the program is not still broken, then loop extraction did something
390 // that masked the error. Stop loop extraction now.
Hal Finkele9efbf12013-08-02 21:13:42 +0000391
392 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
393 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i) {
394 Function *F = MiscompiledFunctions[i];
395 MisCompFunctions.push_back(std::make_pair(F->getName(),
396 F->getFunctionType()));
397 }
398
399 std::string ErrorMsg;
400 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted,
401 Linker::DestroySource, &ErrorMsg)){
402 errs() << BD.getToolName() << ": Error linking modules together:"
403 << ErrorMsg << '\n';
404 exit(1);
405 }
406
407 MiscompiledFunctions.clear();
408 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
409 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
410
411 assert(NewF && "Function not found??");
412 MiscompiledFunctions.push_back(NewF);
413 }
414
415 delete ToOptimizeLoopExtracted;
416 BD.setNewProgram(ToNotOptimize);
Chris Lattnerbcec7872004-03-14 22:08:00 +0000417 return MadeChange;
418 }
Chris Lattner0434ba32004-04-05 21:37:38 +0000419
Dan Gohmanee051522009-07-16 15:30:09 +0000420 outs() << "*** Loop extraction successful!\n";
Chris Lattnerbcec7872004-03-14 22:08:00 +0000421
Chris Lattner229907c2011-07-18 04:54:35 +0000422 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
Chris Lattnerd3087972004-11-16 06:31:38 +0000423 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
424 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
Reid Spencer5301e7c2007-01-30 20:08:39 +0000425 if (!I->isDeclaration())
Chris Lattnerdad18232004-11-19 07:09:40 +0000426 MisCompFunctions.push_back(std::make_pair(I->getName(),
427 I->getFunctionType()));
Chris Lattnerd3087972004-11-16 06:31:38 +0000428
Chris Lattnerbcec7872004-03-14 22:08:00 +0000429 // Okay, great! Now we know that we extracted a loop and that loop
430 // extraction both didn't break the program, and didn't mask the problem.
431 // Replace the current program with the loop extracted version, and try to
432 // extract another loop.
433 std::string ErrorMsg;
Tanya Lattnercbb91402011-10-11 00:24:54 +0000434 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted,
435 Linker::DestroySource, &ErrorMsg)){
Dan Gohmand8db3762009-07-15 16:35:29 +0000436 errs() << BD.getToolName() << ": Error linking modules together:"
437 << ErrorMsg << '\n';
Chris Lattnerbcec7872004-03-14 22:08:00 +0000438 exit(1);
439 }
Chris Lattnerd3087972004-11-16 06:31:38 +0000440 delete ToOptimizeLoopExtracted;
Chris Lattnerb38cc9c2004-03-17 17:42:09 +0000441
442 // All of the Function*'s in the MiscompiledFunctions list are in the old
Chris Lattnera413b082004-04-02 06:32:17 +0000443 // module. Update this list to include all of the functions in the
444 // optimized and loop extracted module.
445 MiscompiledFunctions.clear();
Chris Lattnerd3087972004-11-16 06:31:38 +0000446 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000447 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000448
Chris Lattnerd3087972004-11-16 06:31:38 +0000449 assert(NewF && "Function not found??");
450 MiscompiledFunctions.push_back(NewF);
Chris Lattnerb38cc9c2004-03-17 17:42:09 +0000451 }
452
Chris Lattnerbcec7872004-03-14 22:08:00 +0000453 BD.setNewProgram(ToNotOptimize);
454 MadeChange = true;
455 }
456}
457
Chris Lattnera060b102004-05-11 21:54:13 +0000458namespace {
459 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
460 BugDriver &BD;
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000461 bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
Chris Lattnera060b102004-05-11 21:54:13 +0000462 std::vector<Function*> FunctionsBeingTested;
463 public:
464 ReduceMiscompiledBlocks(BugDriver &bd,
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000465 bool (*F)(BugDriver &, Module *, Module *,
466 std::string &),
Chris Lattnera060b102004-05-11 21:54:13 +0000467 const std::vector<Function*> &Fns)
468 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000469
Craig Toppere56917c2014-03-08 08:27:28 +0000470 TestResult doTest(std::vector<BasicBlock*> &Prefix,
471 std::vector<BasicBlock*> &Suffix,
472 std::string &Error) override {
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000473 if (!Suffix.empty()) {
474 bool Ret = TestFuncs(Suffix, Error);
475 if (!Error.empty())
476 return InternalError;
477 if (Ret)
478 return KeepSuffix;
479 }
480 if (!Prefix.empty()) {
481 bool Ret = TestFuncs(Prefix, Error);
482 if (!Error.empty())
483 return InternalError;
484 if (Ret)
485 return KeepPrefix;
486 }
Chris Lattnera060b102004-05-11 21:54:13 +0000487 return NoFailure;
488 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000489
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000490 bool TestFuncs(const std::vector<BasicBlock*> &BBs, std::string &Error);
Chris Lattnera060b102004-05-11 21:54:13 +0000491 };
492}
493
494/// TestFuncs - Extract all blocks for the miscompiled functions except for the
495/// specified blocks. If the problem still exists, return true.
496///
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000497bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs,
498 std::string &Error) {
Chris Lattnera060b102004-05-11 21:54:13 +0000499 // Test to see if the function is misoptimized if we ONLY run it on the
500 // functions listed in Funcs.
Dan Gohmanee051522009-07-16 15:30:09 +0000501 outs() << "Checking to see if the program is misoptimized when all ";
Chris Lattner6c0c3132004-05-12 16:08:01 +0000502 if (!BBs.empty()) {
Dan Gohmanee051522009-07-16 15:30:09 +0000503 outs() << "but these " << BBs.size() << " blocks are extracted: ";
Chris Lattner6c0c3132004-05-12 16:08:01 +0000504 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
Dan Gohmanee051522009-07-16 15:30:09 +0000505 outs() << BBs[i]->getName() << " ";
506 if (BBs.size() > 10) outs() << "...";
Chris Lattner6c0c3132004-05-12 16:08:01 +0000507 } else {
Dan Gohmanee051522009-07-16 15:30:09 +0000508 outs() << "blocks are extracted.";
Chris Lattner6c0c3132004-05-12 16:08:01 +0000509 }
Dan Gohmanee051522009-07-16 15:30:09 +0000510 outs() << '\n';
Chris Lattnera060b102004-05-11 21:54:13 +0000511
512 // Split the module into the two halves of the program we want.
Rafael Espindola229e38f2010-10-13 01:36:30 +0000513 ValueToValueMapTy VMap;
Rafael Espindola07035e62010-07-29 14:20:59 +0000514 Module *Clone = CloneModule(BD.getProgram(), VMap);
515 Module *Orig = BD.swapProgramIn(Clone);
516 std::vector<Function*> FuncsOnClone;
517 std::vector<BasicBlock*> BBsOnClone;
518 for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
519 Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
520 FuncsOnClone.push_back(F);
521 }
522 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
523 BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
524 BBsOnClone.push_back(BB);
525 }
526 VMap.clear();
527
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000528 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
Chris Lattnera060b102004-05-11 21:54:13 +0000529 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Rafael Espindola07035e62010-07-29 14:20:59 +0000530 FuncsOnClone,
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000531 VMap);
Chris Lattnera060b102004-05-11 21:54:13 +0000532
533 // Try the extraction. If it doesn't work, then the block extractor crashed
534 // or something, in which case bugpoint can't chase down this possibility.
Rafael Espindola28b351a2014-08-26 17:19:03 +0000535 if (std::unique_ptr<Module> New =
536 BD.extractMappedBlocksFromModule(BBsOnClone, ToOptimize)) {
Chris Lattnera060b102004-05-11 21:54:13 +0000537 delete ToOptimize;
Rafael Espindola07035e62010-07-29 14:20:59 +0000538 // Run the predicate,
539 // note that the predicate will delete both input modules.
Rafael Espindola28b351a2014-08-26 17:19:03 +0000540 bool Ret = TestFn(BD, New.get(), ToNotOptimize, Error);
Rafael Espindola07035e62010-07-29 14:20:59 +0000541 delete BD.swapProgramIn(Orig);
542 return Ret;
Chris Lattnera060b102004-05-11 21:54:13 +0000543 }
Rafael Espindola07035e62010-07-29 14:20:59 +0000544 delete BD.swapProgramIn(Orig);
Chris Lattnera060b102004-05-11 21:54:13 +0000545 delete ToOptimize;
546 delete ToNotOptimize;
547 return false;
548}
549
550
551/// ExtractBlocks - Given a reduced list of functions that still expose the bug,
552/// extract as many basic blocks from the region as possible without obscuring
553/// the bug.
554///
555static bool ExtractBlocks(BugDriver &BD,
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000556 bool (*TestFn)(BugDriver &, Module *, Module *,
557 std::string &),
558 std::vector<Function*> &MiscompiledFunctions,
559 std::string &Error) {
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000560 if (BugpointIsInterrupted) return false;
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000561
Chris Lattnera060b102004-05-11 21:54:13 +0000562 std::vector<BasicBlock*> Blocks;
563 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
564 for (Function::iterator I = MiscompiledFunctions[i]->begin(),
565 E = MiscompiledFunctions[i]->end(); I != E; ++I)
566 Blocks.push_back(I);
567
568 // Use the list reducer to identify blocks that can be extracted without
569 // obscuring the bug. The Blocks list will end up containing blocks that must
570 // be retained from the original program.
571 unsigned OldSize = Blocks.size();
Chris Lattner6c0c3132004-05-12 16:08:01 +0000572
573 // Check to see if all blocks are extractible first.
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000574 bool Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
575 .TestFuncs(std::vector<BasicBlock*>(), Error);
576 if (!Error.empty())
577 return false;
578 if (Ret) {
Chris Lattner6c0c3132004-05-12 16:08:01 +0000579 Blocks.clear();
580 } else {
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000581 ReduceMiscompiledBlocks(BD, TestFn,
582 MiscompiledFunctions).reduceList(Blocks, Error);
583 if (!Error.empty())
584 return false;
Chris Lattner6c0c3132004-05-12 16:08:01 +0000585 if (Blocks.size() == OldSize)
586 return false;
587 }
Chris Lattnera060b102004-05-11 21:54:13 +0000588
Rafael Espindola229e38f2010-10-13 01:36:30 +0000589 ValueToValueMapTy VMap;
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000590 Module *ProgClone = CloneModule(BD.getProgram(), VMap);
Chris Lattner49e4a332004-05-12 02:43:24 +0000591 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
Dan Gohman956ae9d2009-04-22 15:57:18 +0000592 MiscompiledFunctions,
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000593 VMap);
Rafael Espindola28b351a2014-08-26 17:19:03 +0000594 std::unique_ptr<Module> Extracted =
595 BD.extractMappedBlocksFromModule(Blocks, ToExtract);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000596 if (!Extracted) {
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000597 // Weird, extraction should have worked.
Dan Gohmand8db3762009-07-15 16:35:29 +0000598 errs() << "Nondeterministic problem extracting blocks??\n";
Chris Lattner49e4a332004-05-12 02:43:24 +0000599 delete ProgClone;
600 delete ToExtract;
601 return false;
602 }
Chris Lattnera060b102004-05-11 21:54:13 +0000603
Chris Lattner49e4a332004-05-12 02:43:24 +0000604 // Otherwise, block extraction succeeded. Link the two program fragments back
605 // together.
606 delete ToExtract;
Chris Lattnera060b102004-05-11 21:54:13 +0000607
Chris Lattner229907c2011-07-18 04:54:35 +0000608 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
Chris Lattnerd3087972004-11-16 06:31:38 +0000609 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
610 I != E; ++I)
Reid Spencer5301e7c2007-01-30 20:08:39 +0000611 if (!I->isDeclaration())
Chris Lattnerdad18232004-11-19 07:09:40 +0000612 MisCompFunctions.push_back(std::make_pair(I->getName(),
613 I->getFunctionType()));
Chris Lattnerd3087972004-11-16 06:31:38 +0000614
Chris Lattner49e4a332004-05-12 02:43:24 +0000615 std::string ErrorMsg;
Rafael Espindola28b351a2014-08-26 17:19:03 +0000616 if (Linker::LinkModules(ProgClone, Extracted.get(), Linker::DestroySource,
Tanya Lattnercbb91402011-10-11 00:24:54 +0000617 &ErrorMsg)) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000618 errs() << BD.getToolName() << ": Error linking modules together:"
619 << ErrorMsg << '\n';
Chris Lattner49e4a332004-05-12 02:43:24 +0000620 exit(1);
621 }
Chris Lattnera060b102004-05-11 21:54:13 +0000622
Chris Lattner49e4a332004-05-12 02:43:24 +0000623 // Set the new program and delete the old one.
624 BD.setNewProgram(ProgClone);
Chris Lattnera060b102004-05-11 21:54:13 +0000625
Chris Lattner49e4a332004-05-12 02:43:24 +0000626 // Update the list of miscompiled functions.
627 MiscompiledFunctions.clear();
Chris Lattnera060b102004-05-11 21:54:13 +0000628
Chris Lattnerd3087972004-11-16 06:31:38 +0000629 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000630 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
Chris Lattnerd3087972004-11-16 06:31:38 +0000631 assert(NewF && "Function not found??");
632 MiscompiledFunctions.push_back(NewF);
633 }
Chris Lattner49e4a332004-05-12 02:43:24 +0000634
635 return true;
Chris Lattnera060b102004-05-11 21:54:13 +0000636}
637
638
Chris Lattner0434ba32004-04-05 21:37:38 +0000639/// DebugAMiscompilation - This is a generic driver to narrow down
640/// miscompilations, either in an optimization or a code generator.
Misha Brukman0784a602004-04-21 18:36:43 +0000641///
Chris Lattner0434ba32004-04-05 21:37:38 +0000642static std::vector<Function*>
643DebugAMiscompilation(BugDriver &BD,
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000644 bool (*TestFn)(BugDriver &, Module *, Module *,
645 std::string &),
646 std::string &Error) {
Chris Lattner0434ba32004-04-05 21:37:38 +0000647 // Okay, now that we have reduced the list of passes which are causing the
648 // failure, see if we can pin down which functions are being
649 // miscompiled... first build a list of all of the non-external functions in
650 // the program.
651 std::vector<Function*> MiscompiledFunctions;
652 Module *Prog = BD.getProgram();
653 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
Reid Spencer5301e7c2007-01-30 20:08:39 +0000654 if (!I->isDeclaration())
Chris Lattner0434ba32004-04-05 21:37:38 +0000655 MiscompiledFunctions.push_back(I);
656
657 // Do the reduction...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000658 if (!BugpointIsInterrupted)
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000659 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
660 Error);
Andrew Trick55aeb552011-05-11 16:31:24 +0000661 if (!Error.empty()) {
662 errs() << "\n***Cannot reduce functions: ";
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000663 return MiscompiledFunctions;
Andrew Trick55aeb552011-05-11 16:31:24 +0000664 }
Dan Gohmanee051522009-07-16 15:30:09 +0000665 outs() << "\n*** The following function"
666 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
667 << " being miscompiled: ";
Chris Lattner0434ba32004-04-05 21:37:38 +0000668 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanee051522009-07-16 15:30:09 +0000669 outs() << '\n';
Chris Lattner0434ba32004-04-05 21:37:38 +0000670
671 // See if we can rip any loops out of the miscompiled functions and still
672 // trigger the problem.
Reid Spencer471bcb72006-11-11 19:05:02 +0000673
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000674 if (!BugpointIsInterrupted && !DisableLoopExtraction) {
675 bool Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions, Error);
676 if (!Error.empty())
677 return MiscompiledFunctions;
678 if (Ret) {
679 // Okay, we extracted some loops and the problem still appears. See if
680 // we can eliminate some of the created functions from being candidates.
681 DisambiguateGlobalSymbols(BD.getProgram());
Chris Lattnerdfbb1d12004-04-11 23:52:35 +0000682
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000683 // Do the reduction...
684 if (!BugpointIsInterrupted)
685 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
686 Error);
687 if (!Error.empty())
688 return MiscompiledFunctions;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000689
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000690 outs() << "\n*** The following function"
691 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
692 << " being miscompiled: ";
693 PrintFunctionList(MiscompiledFunctions);
694 outs() << '\n';
695 }
Chris Lattner0434ba32004-04-05 21:37:38 +0000696 }
697
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000698 if (!BugpointIsInterrupted && !DisableBlockExtraction) {
699 bool Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions, Error);
700 if (!Error.empty())
701 return MiscompiledFunctions;
702 if (Ret) {
703 // Okay, we extracted some blocks and the problem still appears. See if
704 // we can eliminate some of the created functions from being candidates.
705 DisambiguateGlobalSymbols(BD.getProgram());
Chris Lattnera060b102004-05-11 21:54:13 +0000706
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000707 // Do the reduction...
708 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
709 Error);
710 if (!Error.empty())
711 return MiscompiledFunctions;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000712
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000713 outs() << "\n*** The following function"
714 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
715 << " being miscompiled: ";
716 PrintFunctionList(MiscompiledFunctions);
717 outs() << '\n';
718 }
Chris Lattnera060b102004-05-11 21:54:13 +0000719 }
720
Chris Lattner0434ba32004-04-05 21:37:38 +0000721 return MiscompiledFunctions;
722}
723
Chris Lattnerbf791612004-04-05 22:58:16 +0000724/// TestOptimizer - This is the predicate function used to check to see if the
725/// "Test" portion of the program is misoptimized. If so, return true. In any
726/// case, both module arguments are deleted.
Misha Brukman0784a602004-04-21 18:36:43 +0000727///
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000728static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe,
729 std::string &Error) {
Chris Lattner0434ba32004-04-05 21:37:38 +0000730 // Run the optimization passes on ToOptimize, producing a transformed version
731 // of the functions being tested.
Dan Gohmanee051522009-07-16 15:30:09 +0000732 outs() << " Optimizing functions being tested: ";
Rafael Espindola28b351a2014-08-26 17:19:03 +0000733 std::unique_ptr<Module> Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
734 /*AutoDebugCrashes*/ true);
Dan Gohmanee051522009-07-16 15:30:09 +0000735 outs() << "done.\n";
Chris Lattner0434ba32004-04-05 21:37:38 +0000736 delete Test;
737
Dan Gohmanee051522009-07-16 15:30:09 +0000738 outs() << " Checking to see if the merged program executes correctly: ";
Rafael Espindolae4904602010-07-31 14:34:49 +0000739 bool Broken;
Rafael Espindola28b351a2014-08-26 17:19:03 +0000740 Module *New =
741 TestMergedProgram(BD, Optimized.get(), Safe, true, Error, Broken);
Rafael Espindolae4904602010-07-31 14:34:49 +0000742 if (New) {
743 outs() << (Broken ? " nope.\n" : " yup.\n");
744 // Delete the original and set the new program.
745 delete BD.swapProgramIn(New);
746 }
Chris Lattner0434ba32004-04-05 21:37:38 +0000747 return Broken;
748}
749
750
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000751/// debugMiscompilation - This method is used when the passes selected are not
752/// crashing, but the generated output is semantically different from the
753/// input.
754///
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000755void BugDriver::debugMiscompilation(std::string *Error) {
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000756 // Make sure something was miscompiled...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000757 if (!BugpointIsInterrupted)
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000758 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun, *Error)) {
759 if (Error->empty())
760 errs() << "*** Optimized program matches reference output! No problem"
761 << " detected...\nbugpoint can't help you with your problem!\n";
762 return;
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000763 }
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000764
Dan Gohmanee051522009-07-16 15:30:09 +0000765 outs() << "\n*** Found miscompiling pass"
766 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
767 << getPassesString(getPassesToRun()) << '\n';
Rafael Espindola594994a2010-07-28 18:12:30 +0000768 EmitProgressBitcode(Program, "passinput");
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000769
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000770 std::vector<Function *> MiscompiledFunctions =
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000771 DebugAMiscompilation(*this, TestOptimizer, *Error);
772 if (!Error->empty())
773 return;
Chris Lattnerbcec7872004-03-14 22:08:00 +0000774
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000775 // Output a bunch of bitcode files for the user...
Dan Gohmanee051522009-07-16 15:30:09 +0000776 outs() << "Outputting reduced bitcode files which expose the problem:\n";
Rafael Espindola229e38f2010-10-13 01:36:30 +0000777 ValueToValueMapTy VMap;
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000778 Module *ToNotOptimize = CloneModule(getProgram(), VMap);
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000779 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohman956ae9d2009-04-22 15:57:18 +0000780 MiscompiledFunctions,
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000781 VMap);
Chris Lattner567543f2004-03-14 19:27:19 +0000782
Dan Gohmanee051522009-07-16 15:30:09 +0000783 outs() << " Non-optimized portion: ";
Rafael Espindola594994a2010-07-28 18:12:30 +0000784 EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true);
785 delete ToNotOptimize; // Delete hacked module.
Misha Brukman650ba8e2005-04-22 00:00:37 +0000786
Dan Gohmanee051522009-07-16 15:30:09 +0000787 outs() << " Portion that is input to optimizer: ";
Rafael Espindola594994a2010-07-28 18:12:30 +0000788 EmitProgressBitcode(ToOptimize, "tooptimize");
789 delete ToOptimize; // Delete hacked module.
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000790
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000791 return;
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000792}
Brian Gaeke960707c2003-11-11 22:41:34 +0000793
Chris Lattnerbf791612004-04-05 22:58:16 +0000794/// CleanupAndPrepareModules - Get the specified modules ready for code
795/// generator testing.
Misha Brukman0784a602004-04-21 18:36:43 +0000796///
Chris Lattnerbf791612004-04-05 22:58:16 +0000797static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
798 Module *Safe) {
799 // Clean up the modules, removing extra cruft that we don't need anymore...
Rafael Espindola28b351a2014-08-26 17:19:03 +0000800 Test = BD.performFinalCleanups(Test).release();
Chris Lattnerbf791612004-04-05 22:58:16 +0000801
802 // If we are executing the JIT, we have several nasty issues to take care of.
803 if (!BD.isExecutingJIT()) return;
804
805 // First, if the main function is in the Safe module, we must add a stub to
806 // the Test module to call into it. Thus, we create a new function `main'
807 // which just calls the old one.
Reid Spencer1241d6d2007-02-05 21:19:13 +0000808 if (Function *oldMain = Safe->getFunction("main"))
Reid Spencer5301e7c2007-01-30 20:08:39 +0000809 if (!oldMain->isDeclaration()) {
Chris Lattnerbf791612004-04-05 22:58:16 +0000810 // Rename it
811 oldMain->setName("llvm_bugpoint_old_main");
812 // Create a NEW `main' function with same type in the test module.
Gabor Greife9ecc682008-04-06 20:25:17 +0000813 Function *newMain = Function::Create(oldMain->getFunctionType(),
814 GlobalValue::ExternalLinkage,
815 "main", Test);
Chris Lattnerbf791612004-04-05 22:58:16 +0000816 // Create an `oldmain' prototype in the test module, which will
817 // corresponds to the real main function in the same module.
Gabor Greife9ecc682008-04-06 20:25:17 +0000818 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
819 GlobalValue::ExternalLinkage,
820 oldMain->getName(), Test);
Chris Lattnerbf791612004-04-05 22:58:16 +0000821 // Set up and remember the argument list for the main function.
822 std::vector<Value*> args;
Alkis Evlogimenosa67bafa2005-03-15 07:02:26 +0000823 for (Function::arg_iterator
824 I = newMain->arg_begin(), E = newMain->arg_end(),
825 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
Owen Anderson7629b712008-04-14 17:38:21 +0000826 I->setName(OI->getName()); // Copy argument names from oldMain
Chris Lattnerbf791612004-04-05 22:58:16 +0000827 args.push_back(I);
828 }
829
830 // Call the old main function and return its result
Owen Anderson55f1c092009-08-13 21:58:54 +0000831 BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
Jay Foad5bd375a2011-07-15 08:37:34 +0000832 CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000833
Chris Lattnerbf791612004-04-05 22:58:16 +0000834 // If the type of old function wasn't void, return value of call
Owen Anderson55f1c092009-08-13 21:58:54 +0000835 ReturnInst::Create(Safe->getContext(), call, BB);
Chris Lattnerbf791612004-04-05 22:58:16 +0000836 }
837
838 // The second nasty issue we must deal with in the JIT is that the Safe
839 // module cannot directly reference any functions defined in the test
840 // module. Instead, we use a JIT API call to dynamically resolve the
841 // symbol.
Misha Brukman650ba8e2005-04-22 00:00:37 +0000842
Chris Lattnerbf791612004-04-05 22:58:16 +0000843 // Add the resolver to the Safe module.
844 // Prototype: void *getPointerToNamedFunction(const char* Name)
Chris Lattner7b864c02007-01-07 08:13:39 +0000845 Constant *resolverFunc =
Chris Lattnerbf791612004-04-05 22:58:16 +0000846 Safe->getOrInsertFunction("getPointerToNamedFunction",
Duncan Sands9ed7b162009-10-06 15:40:36 +0000847 Type::getInt8PtrTy(Safe->getContext()),
848 Type::getInt8PtrTy(Safe->getContext()),
Craig Toppere6cb63e2014-04-25 04:24:47 +0000849 (Type *)nullptr);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000850
Chris Lattnerbf791612004-04-05 22:58:16 +0000851 // Use the function we just added to get addresses of functions we need.
Misha Brukman83018642004-04-19 01:12:01 +0000852 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
Reid Spencer5301e7c2007-01-30 20:08:39 +0000853 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
Duncan Sands38ef3a82007-12-03 20:06:50 +0000854 !F->isIntrinsic() /* ignore intrinsics */) {
Reid Spencer1241d6d2007-02-05 21:19:13 +0000855 Function *TestFn = Test->getFunction(F->getName());
Chris Lattnerbf791612004-04-05 22:58:16 +0000856
857 // Don't forward functions which are external in the test module too.
Reid Spencer5301e7c2007-01-30 20:08:39 +0000858 if (TestFn && !TestFn->isDeclaration()) {
Chris Lattnerbf791612004-04-05 22:58:16 +0000859 // 1. Add a string constant with its name to the global file
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000860 Constant *InitArray =
861 ConstantDataArray::getString(F->getContext(), F->getName());
Chris Lattnerbf791612004-04-05 22:58:16 +0000862 GlobalVariable *funcName =
Owen Andersonb17f3292009-07-08 19:03:57 +0000863 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
Misha Brukman650ba8e2005-04-22 00:00:37 +0000864 GlobalValue::InternalLinkage, InitArray,
Owen Andersonb17f3292009-07-08 19:03:57 +0000865 F->getName() + "_name");
Chris Lattnerbf791612004-04-05 22:58:16 +0000866
867 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
868 // sbyte* so it matches the signature of the resolver function.
869
870 // GetElementPtr *funcName, ulong 0, ulong 0
Owen Anderson55f1c092009-08-13 21:58:54 +0000871 std::vector<Constant*> GEPargs(2,
872 Constant::getNullValue(Type::getInt32Ty(F->getContext())));
Jay Foaded8db7d2011-07-21 14:31:17 +0000873 Value *GEP = ConstantExpr::getGetElementPtr(funcName, GEPargs);
Chris Lattnerbf791612004-04-05 22:58:16 +0000874 std::vector<Value*> ResolverArgs;
875 ResolverArgs.push_back(GEP);
876
Misha Brukmance89b392004-04-19 03:36:47 +0000877 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
878 // function that dynamically resolves the calls to F via our JIT API
Chris Lattner986675c2005-07-12 01:00:32 +0000879 if (!F->use_empty()) {
880 // Create a new global to hold the cached function pointer.
Owen Andersonb292b8c2009-07-30 23:03:37 +0000881 Constant *NullPtr = ConstantPointerNull::get(F->getType());
Chris Lattner986675c2005-07-12 01:00:32 +0000882 GlobalVariable *Cache =
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000883 new GlobalVariable(*F->getParent(), F->getType(),
Owen Andersonb17f3292009-07-08 19:03:57 +0000884 false, GlobalValue::InternalLinkage,
885 NullPtr,F->getName()+".fpcache");
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000886
Misha Brukmance89b392004-04-19 03:36:47 +0000887 // Construct a new stub function that will re-route calls to F
Chris Lattner229907c2011-07-18 04:54:35 +0000888 FunctionType *FuncTy = F->getFunctionType();
Gabor Greife9ecc682008-04-06 20:25:17 +0000889 Function *FuncWrapper = Function::Create(FuncTy,
890 GlobalValue::InternalLinkage,
891 F->getName() + "_wrapper",
892 F->getParent());
Owen Anderson55f1c092009-08-13 21:58:54 +0000893 BasicBlock *EntryBB = BasicBlock::Create(F->getContext(),
894 "entry", FuncWrapper);
895 BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
896 "usecache", FuncWrapper);
897 BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
898 "lookupfp", FuncWrapper);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000899
Chris Lattner986675c2005-07-12 01:00:32 +0000900 // Check to see if we already looked up the value.
901 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000902 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
903 NullPtr, "isNull");
Gabor Greife9ecc682008-04-06 20:25:17 +0000904 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000905
Misha Brukmance89b392004-04-19 03:36:47 +0000906 // Resolve the call to function F via the JIT API:
907 //
908 // call resolver(GetElementPtr...)
Gabor Greif697e94c2008-05-15 10:04:30 +0000909 CallInst *Resolver =
Jay Foad5bd375a2011-07-15 08:37:34 +0000910 CallInst::Create(resolverFunc, ResolverArgs, "resolver", LookupBB);
Gabor Greif697e94c2008-05-15 10:04:30 +0000911
912 // Cast the result from the resolver to correctly-typed function.
913 CastInst *CastedResolver =
914 new BitCastInst(Resolver,
Owen Anderson4056ca92009-07-29 22:17:13 +0000915 PointerType::getUnqual(F->getFunctionType()),
Gabor Greif697e94c2008-05-15 10:04:30 +0000916 "resolverCast", LookupBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000917
Chris Lattner986675c2005-07-12 01:00:32 +0000918 // Save the value in our cache.
919 new StoreInst(CastedResolver, Cache, LookupBB);
Gabor Greife9ecc682008-04-06 20:25:17 +0000920 BranchInst::Create(DoCallBB, LookupBB);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000921
Jay Foad52131342011-03-30 11:28:46 +0000922 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(), 2,
Gabor Greif697e94c2008-05-15 10:04:30 +0000923 "fp", DoCallBB);
Chris Lattner986675c2005-07-12 01:00:32 +0000924 FuncPtr->addIncoming(CastedResolver, LookupBB);
925 FuncPtr->addIncoming(CachedVal, EntryBB);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000926
Chris Lattner986675c2005-07-12 01:00:32 +0000927 // Save the argument list.
Misha Brukman83018642004-04-19 01:12:01 +0000928 std::vector<Value*> Args;
Alkis Evlogimenosa67bafa2005-03-15 07:02:26 +0000929 for (Function::arg_iterator i = FuncWrapper->arg_begin(),
930 e = FuncWrapper->arg_end(); i != e; ++i)
Misha Brukman83018642004-04-19 01:12:01 +0000931 Args.push_back(i);
932
933 // Pass on the arguments to the real function, return its result
Dan Gohman34a22492010-06-07 20:19:26 +0000934 if (F->getReturnType()->isVoidTy()) {
Jay Foad5bd375a2011-07-15 08:37:34 +0000935 CallInst::Create(FuncPtr, Args, "", DoCallBB);
Owen Anderson55f1c092009-08-13 21:58:54 +0000936 ReturnInst::Create(F->getContext(), DoCallBB);
Misha Brukman83018642004-04-19 01:12:01 +0000937 } else {
Jay Foad5bd375a2011-07-15 08:37:34 +0000938 CallInst *Call = CallInst::Create(FuncPtr, Args,
Gabor Greife9ecc682008-04-06 20:25:17 +0000939 "retval", DoCallBB);
Owen Anderson55f1c092009-08-13 21:58:54 +0000940 ReturnInst::Create(F->getContext(),Call, DoCallBB);
Misha Brukman83018642004-04-19 01:12:01 +0000941 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000942
Misha Brukmance89b392004-04-19 03:36:47 +0000943 // Use the wrapper function instead of the old function
944 F->replaceAllUsesWith(FuncWrapper);
Misha Brukman83018642004-04-19 01:12:01 +0000945 }
Chris Lattnerbf791612004-04-05 22:58:16 +0000946 }
947 }
948 }
949
950 if (verifyModule(*Test) || verifyModule(*Safe)) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000951 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
Chris Lattnerbf791612004-04-05 22:58:16 +0000952 abort();
953 }
954}
955
956
957
958/// TestCodeGenerator - This is the predicate function used to check to see if
959/// the "Test" portion of the program is miscompiled by the code generator under
960/// test. If so, return true. In any case, both module arguments are deleted.
Misha Brukman0784a602004-04-21 18:36:43 +0000961///
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000962static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe,
963 std::string &Error) {
Chris Lattnerbf791612004-04-05 22:58:16 +0000964 CleanupAndPrepareModules(BD, Test, Safe);
965
Rafael Espindola302c0da2013-06-18 15:29:32 +0000966 SmallString<128> TestModuleBC;
967 int TestModuleFD;
Rafael Espindola4453e42942014-06-13 03:07:50 +0000968 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
969 TestModuleFD, TestModuleBC);
Rafael Espindola302c0da2013-06-18 15:29:32 +0000970 if (EC) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000971 errs() << BD.getToolName() << "Error making unique filename: "
Rafael Espindola302c0da2013-06-18 15:29:32 +0000972 << EC.message() << "\n";
Reid Spencere4ca7222006-08-23 20:34:57 +0000973 exit(1);
974 }
Rafael Espindola302c0da2013-06-18 15:29:32 +0000975 if (BD.writeProgramToFile(TestModuleBC.str(), TestModuleFD, Test)) {
Chris Lattnerc521f542009-08-23 22:45:37 +0000976 errs() << "Error writing bitcode to `" << TestModuleBC.str()
977 << "'\nExiting.";
Chris Lattnerbf791612004-04-05 22:58:16 +0000978 exit(1);
979 }
980 delete Test;
981
Michael J. Spencerc60223e2011-03-31 13:04:19 +0000982 FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
Rafael Espindola720f49e2010-06-21 02:17:36 +0000983
Chris Lattnerbf791612004-04-05 22:58:16 +0000984 // Make the shared library
Rafael Espindola302c0da2013-06-18 15:29:32 +0000985 SmallString<128> SafeModuleBC;
986 int SafeModuleFD;
Rafael Espindola155cf0f2013-07-05 20:14:52 +0000987 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
988 SafeModuleBC);
Rafael Espindola302c0da2013-06-18 15:29:32 +0000989 if (EC) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000990 errs() << BD.getToolName() << "Error making unique filename: "
Rafael Espindola302c0da2013-06-18 15:29:32 +0000991 << EC.message() << "\n";
Reid Spencere4ca7222006-08-23 20:34:57 +0000992 exit(1);
993 }
Chris Lattnerbf791612004-04-05 22:58:16 +0000994
Rafael Espindola302c0da2013-06-18 15:29:32 +0000995 if (BD.writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, Safe)) {
Chris Lattnerc521f542009-08-23 22:45:37 +0000996 errs() << "Error writing bitcode to `" << SafeModuleBC.str()
997 << "'\nExiting.";
Chris Lattnerbf791612004-04-05 22:58:16 +0000998 exit(1);
999 }
Rafael Espindola720f49e2010-06-21 02:17:36 +00001000
Michael J. Spencerc60223e2011-03-31 13:04:19 +00001001 FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
Rafael Espindola720f49e2010-06-21 02:17:36 +00001002
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001003 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str(), Error);
1004 if (!Error.empty())
Benjamin Kramer1f336da2010-04-12 12:22:19 +00001005 return false;
Chris Lattnerbf791612004-04-05 22:58:16 +00001006 delete Safe;
1007
Michael J. Spencerc60223e2011-03-31 13:04:19 +00001008 FileRemover SharedObjectRemover(SharedObject, !SaveTemps);
Rafael Espindola720f49e2010-06-21 02:17:36 +00001009
Chris Lattnerbf791612004-04-05 22:58:16 +00001010 // Run the code generator on the `Test' code, loading the shared library.
1011 // The function returns whether or not the new output differs from reference.
Rafael Espindolac89b1ef2010-07-30 14:19:00 +00001012 bool Result = BD.diffProgram(BD.getProgram(), TestModuleBC.str(),
1013 SharedObject, false, &Error);
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001014 if (!Error.empty())
1015 return false;
Chris Lattnerbf791612004-04-05 22:58:16 +00001016
1017 if (Result)
Dan Gohmand8db3762009-07-15 16:35:29 +00001018 errs() << ": still failing!\n";
Chris Lattnerbf791612004-04-05 22:58:16 +00001019 else
Dan Gohmand8db3762009-07-15 16:35:29 +00001020 errs() << ": didn't fail.\n";
Chris Lattnerbf791612004-04-05 22:58:16 +00001021
1022 return Result;
1023}
1024
1025
Misha Brukman0784a602004-04-21 18:36:43 +00001026/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
1027///
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001028bool BugDriver::debugCodeGenerator(std::string *Error) {
Dan Gohman414cf502008-12-08 04:02:47 +00001029 if ((void*)SafeInterpreter == (void*)Interpreter) {
Rafael Espindolac89b1ef2010-07-30 14:19:00 +00001030 std::string Result = executeProgramSafely(Program, "bugpoint.safe.out",
1031 Error);
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001032 if (Error->empty()) {
1033 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
1034 << "the reference diff. This may be due to a\n front-end "
1035 << "bug or a bug in the original program, but this can also "
1036 << "happen if bugpoint isn't running the program with the "
1037 << "right flags or input.\n I left the result of executing "
1038 << "the program with the \"safe\" backend in this file for "
1039 << "you: '"
1040 << Result << "'.\n";
1041 }
Chris Lattnerbf791612004-04-05 22:58:16 +00001042 return true;
1043 }
1044
1045 DisambiguateGlobalSymbols(Program);
1046
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001047 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator,
1048 *Error);
1049 if (!Error->empty())
1050 return true;
Chris Lattnerbf791612004-04-05 22:58:16 +00001051
1052 // Split the module into the two halves of the program we want.
Rafael Espindola229e38f2010-10-13 01:36:30 +00001053 ValueToValueMapTy VMap;
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001054 Module *ToNotCodeGen = CloneModule(getProgram(), VMap);
1055 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, VMap);
Chris Lattnerbf791612004-04-05 22:58:16 +00001056
1057 // Condition the modules
1058 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
1059
Rafael Espindola302c0da2013-06-18 15:29:32 +00001060 SmallString<128> TestModuleBC;
1061 int TestModuleFD;
Rafael Espindola4453e42942014-06-13 03:07:50 +00001062 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
1063 TestModuleFD, TestModuleBC);
Rafael Espindola302c0da2013-06-18 15:29:32 +00001064 if (EC) {
Dan Gohmand8db3762009-07-15 16:35:29 +00001065 errs() << getToolName() << "Error making unique filename: "
Rafael Espindola302c0da2013-06-18 15:29:32 +00001066 << EC.message() << "\n";
Reid Spencere4ca7222006-08-23 20:34:57 +00001067 exit(1);
1068 }
Reid Spencer30067f12004-12-15 01:53:08 +00001069
Rafael Espindola302c0da2013-06-18 15:29:32 +00001070 if (writeProgramToFile(TestModuleBC.str(), TestModuleFD, ToCodeGen)) {
Chris Lattnerc521f542009-08-23 22:45:37 +00001071 errs() << "Error writing bitcode to `" << TestModuleBC.str()
1072 << "'\nExiting.";
Chris Lattnerbf791612004-04-05 22:58:16 +00001073 exit(1);
1074 }
1075 delete ToCodeGen;
1076
1077 // Make the shared library
Rafael Espindola302c0da2013-06-18 15:29:32 +00001078 SmallString<128> SafeModuleBC;
1079 int SafeModuleFD;
Rafael Espindola155cf0f2013-07-05 20:14:52 +00001080 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
1081 SafeModuleBC);
Rafael Espindola302c0da2013-06-18 15:29:32 +00001082 if (EC) {
Dan Gohmand8db3762009-07-15 16:35:29 +00001083 errs() << getToolName() << "Error making unique filename: "
Rafael Espindola302c0da2013-06-18 15:29:32 +00001084 << EC.message() << "\n";
Reid Spencere4ca7222006-08-23 20:34:57 +00001085 exit(1);
1086 }
Reid Spencer30067f12004-12-15 01:53:08 +00001087
Rafael Espindola302c0da2013-06-18 15:29:32 +00001088 if (writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, ToNotCodeGen)) {
Chris Lattnerc521f542009-08-23 22:45:37 +00001089 errs() << "Error writing bitcode to `" << SafeModuleBC.str()
1090 << "'\nExiting.";
Chris Lattnerbf791612004-04-05 22:58:16 +00001091 exit(1);
1092 }
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001093 std::string SharedObject = compileSharedObject(SafeModuleBC.str(), *Error);
1094 if (!Error->empty())
1095 return true;
Chris Lattnerbf791612004-04-05 22:58:16 +00001096 delete ToNotCodeGen;
1097
Dan Gohmanee051522009-07-16 15:30:09 +00001098 outs() << "You can reproduce the problem with the command line: \n";
Chris Lattnerbf791612004-04-05 22:58:16 +00001099 if (isExecutingJIT()) {
Chris Lattnerc521f542009-08-23 22:45:37 +00001100 outs() << " lli -load " << SharedObject << " " << TestModuleBC.str();
Chris Lattnerbf791612004-04-05 22:58:16 +00001101 } else {
Nick Lewycky83e30602010-04-29 23:37:44 +00001102 outs() << " llc " << TestModuleBC.str() << " -o " << TestModuleBC.str()
Chris Lattnerc521f542009-08-23 22:45:37 +00001103 << ".s\n";
1104 outs() << " gcc " << SharedObject << " " << TestModuleBC.str()
1105 << ".s -o " << TestModuleBC.str() << ".exe";
Chris Lattnerea2fa462005-01-15 00:07:19 +00001106#if defined (HAVE_LINK_R)
Dan Gohmanee051522009-07-16 15:30:09 +00001107 outs() << " -Wl,-R.";
Chris Lattnerea2fa462005-01-15 00:07:19 +00001108#endif
Dan Gohmanee051522009-07-16 15:30:09 +00001109 outs() << "\n";
Chris Lattnerc521f542009-08-23 22:45:37 +00001110 outs() << " " << TestModuleBC.str() << ".exe";
Chris Lattnerbf791612004-04-05 22:58:16 +00001111 }
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001112 for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
Dan Gohmanee051522009-07-16 15:30:09 +00001113 outs() << " " << InputArgv[i];
1114 outs() << '\n';
1115 outs() << "The shared object was created with:\n llc -march=c "
Chris Lattnerc521f542009-08-23 22:45:37 +00001116 << SafeModuleBC.str() << " -o temporary.c\n"
Daniel Dunbar8575a602009-08-18 03:35:57 +00001117 << " gcc -xc temporary.c -O2 -o " << SharedObject;
1118 if (TargetTriple.getArch() == Triple::sparc)
1119 outs() << " -G"; // Compile a shared library, `-G' for Sparc
1120 else
1121 outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
1122
1123 outs() << " -fno-strict-aliasing\n";
Chris Lattnerbf791612004-04-05 22:58:16 +00001124
1125 return false;
1126}