blob: 0ca47e770411048a7e2992910055b3c0812c34dd [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.
Chris Lattnerd3087972004-11-16 06:31:38 +0000221 if (!DeleteInputs) {
222 M1 = CloneModule(M1);
223 M2 = CloneModule(M2);
224 }
Rafael Espindola9f8eff32014-10-28 00:24:16 +0000225 if (Linker::LinkModules(M1, M2))
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000226 exit(1);
Chris Lattnerd3087972004-11-16 06:31:38 +0000227 delete M2; // We are done with this module.
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000228
Rafael Espindolae4904602010-07-31 14:34:49 +0000229 // Execute the program.
230 Broken = BD.diffProgram(M1, "", "", false, &Error);
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000231 if (!Error.empty()) {
Rafael Espindolac89b1ef2010-07-30 14:19:00 +0000232 // Delete the linked module
233 delete M1;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000234 return nullptr;
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000235 }
Rafael Espindolae4904602010-07-31 14:34:49 +0000236 return M1;
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000237}
238
Misha Brukman0784a602004-04-21 18:36:43 +0000239/// TestFuncs - split functions in a Module into two groups: those that are
240/// under consideration for miscompilation vs. those that are not, and test
241/// accordingly. Each group of functions becomes a separate Module.
242///
Rafael Espindola235457c2010-07-26 00:07:51 +0000243bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*> &Funcs,
244 std::string &Error) {
Chris Lattner16a41312003-04-24 17:02:17 +0000245 // Test to see if the function is misoptimized if we ONLY run it on the
246 // functions listed in Funcs.
Dan Gohmanee051522009-07-16 15:30:09 +0000247 outs() << "Checking to see if the program is misoptimized when "
248 << (Funcs.size()==1 ? "this function is" : "these functions are")
249 << " run through the pass"
250 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000251 PrintFunctionList(Funcs);
Dan Gohmanee051522009-07-16 15:30:09 +0000252 outs() << '\n';
Chris Lattner16a41312003-04-24 17:02:17 +0000253
Rafael Espindola235457c2010-07-26 00:07:51 +0000254 // Create a clone for two reasons:
255 // * If the optimization passes delete any function, the deleted function
256 // will be in the clone and Funcs will still point to valid memory
257 // * If the optimization passes use interprocedural information to break
258 // a function, we want to continue with the original function. Otherwise
259 // we can conclude that a function triggers the bug when in fact one
260 // needs a larger set of original functions to do so.
Rafael Espindola229e38f2010-10-13 01:36:30 +0000261 ValueToValueMapTy VMap;
Rafael Espindola235457c2010-07-26 00:07:51 +0000262 Module *Clone = CloneModule(BD.getProgram(), VMap);
263 Module *Orig = BD.swapProgramIn(Clone);
264
265 std::vector<Function*> FuncsOnClone;
266 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
267 Function *F = cast<Function>(VMap[Funcs[i]]);
268 FuncsOnClone.push_back(F);
269 }
270
271 // Split the module into the two halves of the program we want.
272 VMap.clear();
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000273 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
Rafael Espindola235457c2010-07-26 00:07:51 +0000274 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, FuncsOnClone,
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000275 VMap);
Chris Lattner16a41312003-04-24 17:02:17 +0000276
Nick Lewyckyc6243022007-11-14 06:47:06 +0000277 // Run the predicate, note that the predicate will delete both input modules.
Rafael Espindola235457c2010-07-26 00:07:51 +0000278 bool Broken = TestFn(BD, ToOptimize, ToNotOptimize, Error);
279
280 delete BD.swapProgramIn(Orig);
281
282 return Broken;
Chris Lattner16a41312003-04-24 17:02:17 +0000283}
284
Chris Lattnerdc2cb5a2010-01-16 21:34:01 +0000285/// DisambiguateGlobalSymbols - Give anonymous global values names.
Misha Brukman0784a602004-04-21 18:36:43 +0000286///
Chris Lattnerdfbb1d12004-04-11 23:52:35 +0000287static void DisambiguateGlobalSymbols(Module *M) {
Chris Lattner34d26c32006-05-04 23:35:31 +0000288 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
Chris Lattner6a941f02010-01-16 21:34:51 +0000289 I != E; ++I)
Chris Lattnerdc2cb5a2010-01-16 21:34:01 +0000290 if (!I->hasName())
291 I->setName("anon_global");
Chris Lattner6a941f02010-01-16 21:34:51 +0000292 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattnerdc2cb5a2010-01-16 21:34:01 +0000293 if (!I->hasName())
294 I->setName("anon_fn");
Chris Lattnerdfbb1d12004-04-11 23:52:35 +0000295}
296
Chris Lattnerbcec7872004-03-14 22:08:00 +0000297/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
298/// check to see if we can extract the loops in the region without obscuring the
299/// bug. If so, it reduces the amount of code identified.
Misha Brukman0784a602004-04-21 18:36:43 +0000300///
Chris Lattner0434ba32004-04-05 21:37:38 +0000301static bool ExtractLoops(BugDriver &BD,
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000302 bool (*TestFn)(BugDriver &, Module *, Module *,
303 std::string &),
304 std::vector<Function*> &MiscompiledFunctions,
305 std::string &Error) {
Chris Lattnerbcec7872004-03-14 22:08:00 +0000306 bool MadeChange = false;
307 while (1) {
Chris Lattnerbd615f52005-08-02 23:25:56 +0000308 if (BugpointIsInterrupted) return MadeChange;
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000309
Rafael Espindola229e38f2010-10-13 01:36:30 +0000310 ValueToValueMapTy VMap;
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000311 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
Chris Lattnerbcec7872004-03-14 22:08:00 +0000312 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohman956ae9d2009-04-22 15:57:18 +0000313 MiscompiledFunctions,
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000314 VMap);
Rafael Espindola28b351a2014-08-26 17:19:03 +0000315 Module *ToOptimizeLoopExtracted = BD.extractLoop(ToOptimize).release();
Chris Lattnerbcec7872004-03-14 22:08:00 +0000316 if (!ToOptimizeLoopExtracted) {
317 // If the loop extractor crashed or if there were no extractible loops,
318 // then this chapter of our odyssey is over with.
319 delete ToNotOptimize;
320 delete ToOptimize;
321 return MadeChange;
322 }
323
Dan Gohmand8db3762009-07-15 16:35:29 +0000324 errs() << "Extracted a loop from the breaking portion of the program.\n";
Chris Lattnerbcec7872004-03-14 22:08:00 +0000325
326 // Bugpoint is intentionally not very trusting of LLVM transformations. In
327 // particular, we're not going to assume that the loop extractor works, so
328 // we're going to test the newly loop extracted program to make sure nothing
329 // has broken. If something broke, then we'll inform the user and stop
330 // extraction.
Dan Gohman414cf502008-12-08 04:02:47 +0000331 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
Rafael Espindolae4904602010-07-31 14:34:49 +0000332 bool Failure;
Rafael Espindola28b351a2014-08-26 17:19:03 +0000333 Module *New = TestMergedProgram(BD, ToOptimizeLoopExtracted,
334 ToNotOptimize, false, Error, Failure);
Rafael Espindolae4904602010-07-31 14:34:49 +0000335 if (!New)
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000336 return false;
Hal Finkele9efbf12013-08-02 21:13:42 +0000337
Rafael Espindolae4904602010-07-31 14:34:49 +0000338 // Delete the original and set the new program.
Hal Finkele9efbf12013-08-02 21:13:42 +0000339 Module *Old = BD.swapProgramIn(New);
340 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
341 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
342 delete Old;
343
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000344 if (Failure) {
Chris Lattnerbf791612004-04-05 22:58:16 +0000345 BD.switchToInterpreter(AI);
346
Chris Lattnerbcec7872004-03-14 22:08:00 +0000347 // Merged program doesn't work anymore!
Dan Gohmand8db3762009-07-15 16:35:29 +0000348 errs() << " *** ERROR: Loop extraction broke the program. :("
349 << " Please report a bug!\n";
350 errs() << " Continuing on with un-loop-extracted version.\n";
Chris Lattner257008b2005-05-08 21:54:56 +0000351
Daniel Dunbara53337f2009-09-07 19:26:11 +0000352 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
353 ToNotOptimize);
354 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
355 ToOptimize);
356 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
Chris Lattner257008b2005-05-08 21:54:56 +0000357 ToOptimizeLoopExtracted);
358
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000359 errs() << "Please submit the "
Daniel Dunbara53337f2009-09-07 19:26:11 +0000360 << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
Chris Lattner257008b2005-05-08 21:54:56 +0000361 delete ToOptimize;
Chris Lattnerbcec7872004-03-14 22:08:00 +0000362 delete ToNotOptimize;
Chris Lattnerbcec7872004-03-14 22:08:00 +0000363 return MadeChange;
364 }
Chris Lattner257008b2005-05-08 21:54:56 +0000365 delete ToOptimize;
Chris Lattnerbf791612004-04-05 22:58:16 +0000366 BD.switchToInterpreter(AI);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000367
Dan Gohmanee051522009-07-16 15:30:09 +0000368 outs() << " Testing after loop extraction:\n";
Chris Lattner0434ba32004-04-05 21:37:38 +0000369 // Clone modules, the tester function will free them.
Hal Finkele9efbf12013-08-02 21:13:42 +0000370 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted, VMap);
371 Module *TNOBackup = CloneModule(ToNotOptimize, VMap);
372
373 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
374 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
375
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000376 Failure = TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize, Error);
377 if (!Error.empty())
378 return false;
Hal Finkele9efbf12013-08-02 21:13:42 +0000379
380 ToOptimizeLoopExtracted = TOLEBackup;
381 ToNotOptimize = TNOBackup;
382
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000383 if (!Failure) {
Dan Gohmanee051522009-07-16 15:30:09 +0000384 outs() << "*** Loop extraction masked the problem. Undoing.\n";
Chris Lattnerbcec7872004-03-14 22:08:00 +0000385 // If the program is not still broken, then loop extraction did something
386 // that masked the error. Stop loop extraction now.
Hal Finkele9efbf12013-08-02 21:13:42 +0000387
388 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000389 for (Function *F : MiscompiledFunctions) {
390 MisCompFunctions.emplace_back(F->getName(), F->getFunctionType());
Hal Finkele9efbf12013-08-02 21:13:42 +0000391 }
392
Rafael Espindola9f8eff32014-10-28 00:24:16 +0000393 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted))
Hal Finkele9efbf12013-08-02 21:13:42 +0000394 exit(1);
Hal Finkele9efbf12013-08-02 21:13:42 +0000395
396 MiscompiledFunctions.clear();
397 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
398 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
399
400 assert(NewF && "Function not found??");
401 MiscompiledFunctions.push_back(NewF);
402 }
403
404 delete ToOptimizeLoopExtracted;
405 BD.setNewProgram(ToNotOptimize);
Chris Lattnerbcec7872004-03-14 22:08:00 +0000406 return MadeChange;
407 }
Chris Lattner0434ba32004-04-05 21:37:38 +0000408
Dan Gohmanee051522009-07-16 15:30:09 +0000409 outs() << "*** Loop extraction successful!\n";
Chris Lattnerbcec7872004-03-14 22:08:00 +0000410
Chris Lattner229907c2011-07-18 04:54:35 +0000411 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
Chris Lattnerd3087972004-11-16 06:31:38 +0000412 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
413 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
Reid Spencer5301e7c2007-01-30 20:08:39 +0000414 if (!I->isDeclaration())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000415 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
Chris Lattnerd3087972004-11-16 06:31:38 +0000416
Chris Lattnerbcec7872004-03-14 22:08:00 +0000417 // Okay, great! Now we know that we extracted a loop and that loop
418 // extraction both didn't break the program, and didn't mask the problem.
419 // Replace the current program with the loop extracted version, and try to
420 // extract another loop.
Rafael Espindola9f8eff32014-10-28 00:24:16 +0000421 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted))
Chris Lattnerbcec7872004-03-14 22:08:00 +0000422 exit(1);
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000423
Chris Lattnerd3087972004-11-16 06:31:38 +0000424 delete ToOptimizeLoopExtracted;
Chris Lattnerb38cc9c2004-03-17 17:42:09 +0000425
426 // All of the Function*'s in the MiscompiledFunctions list are in the old
Chris Lattnera413b082004-04-02 06:32:17 +0000427 // module. Update this list to include all of the functions in the
428 // optimized and loop extracted module.
429 MiscompiledFunctions.clear();
Chris Lattnerd3087972004-11-16 06:31:38 +0000430 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000431 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000432
Chris Lattnerd3087972004-11-16 06:31:38 +0000433 assert(NewF && "Function not found??");
434 MiscompiledFunctions.push_back(NewF);
Chris Lattnerb38cc9c2004-03-17 17:42:09 +0000435 }
436
Chris Lattnerbcec7872004-03-14 22:08:00 +0000437 BD.setNewProgram(ToNotOptimize);
438 MadeChange = true;
439 }
440}
441
Chris Lattnera060b102004-05-11 21:54:13 +0000442namespace {
443 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
444 BugDriver &BD;
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000445 bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
Chris Lattnera060b102004-05-11 21:54:13 +0000446 std::vector<Function*> FunctionsBeingTested;
447 public:
448 ReduceMiscompiledBlocks(BugDriver &bd,
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000449 bool (*F)(BugDriver &, Module *, Module *,
450 std::string &),
Chris Lattnera060b102004-05-11 21:54:13 +0000451 const std::vector<Function*> &Fns)
452 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000453
Craig Toppere56917c2014-03-08 08:27:28 +0000454 TestResult doTest(std::vector<BasicBlock*> &Prefix,
455 std::vector<BasicBlock*> &Suffix,
456 std::string &Error) override {
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000457 if (!Suffix.empty()) {
458 bool Ret = TestFuncs(Suffix, Error);
459 if (!Error.empty())
460 return InternalError;
461 if (Ret)
462 return KeepSuffix;
463 }
464 if (!Prefix.empty()) {
465 bool Ret = TestFuncs(Prefix, Error);
466 if (!Error.empty())
467 return InternalError;
468 if (Ret)
469 return KeepPrefix;
470 }
Chris Lattnera060b102004-05-11 21:54:13 +0000471 return NoFailure;
472 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000473
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000474 bool TestFuncs(const std::vector<BasicBlock*> &BBs, std::string &Error);
Chris Lattnera060b102004-05-11 21:54:13 +0000475 };
476}
477
478/// TestFuncs - Extract all blocks for the miscompiled functions except for the
479/// specified blocks. If the problem still exists, return true.
480///
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000481bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs,
482 std::string &Error) {
Chris Lattnera060b102004-05-11 21:54:13 +0000483 // Test to see if the function is misoptimized if we ONLY run it on the
484 // functions listed in Funcs.
Dan Gohmanee051522009-07-16 15:30:09 +0000485 outs() << "Checking to see if the program is misoptimized when all ";
Chris Lattner6c0c3132004-05-12 16:08:01 +0000486 if (!BBs.empty()) {
Dan Gohmanee051522009-07-16 15:30:09 +0000487 outs() << "but these " << BBs.size() << " blocks are extracted: ";
Chris Lattner6c0c3132004-05-12 16:08:01 +0000488 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
Dan Gohmanee051522009-07-16 15:30:09 +0000489 outs() << BBs[i]->getName() << " ";
490 if (BBs.size() > 10) outs() << "...";
Chris Lattner6c0c3132004-05-12 16:08:01 +0000491 } else {
Dan Gohmanee051522009-07-16 15:30:09 +0000492 outs() << "blocks are extracted.";
Chris Lattner6c0c3132004-05-12 16:08:01 +0000493 }
Dan Gohmanee051522009-07-16 15:30:09 +0000494 outs() << '\n';
Chris Lattnera060b102004-05-11 21:54:13 +0000495
496 // Split the module into the two halves of the program we want.
Rafael Espindola229e38f2010-10-13 01:36:30 +0000497 ValueToValueMapTy VMap;
Rafael Espindola07035e62010-07-29 14:20:59 +0000498 Module *Clone = CloneModule(BD.getProgram(), VMap);
499 Module *Orig = BD.swapProgramIn(Clone);
500 std::vector<Function*> FuncsOnClone;
501 std::vector<BasicBlock*> BBsOnClone;
502 for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
503 Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
504 FuncsOnClone.push_back(F);
505 }
506 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
507 BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
508 BBsOnClone.push_back(BB);
509 }
510 VMap.clear();
511
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000512 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
Chris Lattnera060b102004-05-11 21:54:13 +0000513 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Rafael Espindola07035e62010-07-29 14:20:59 +0000514 FuncsOnClone,
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000515 VMap);
Chris Lattnera060b102004-05-11 21:54:13 +0000516
517 // Try the extraction. If it doesn't work, then the block extractor crashed
518 // or something, in which case bugpoint can't chase down this possibility.
Rafael Espindola28b351a2014-08-26 17:19:03 +0000519 if (std::unique_ptr<Module> New =
520 BD.extractMappedBlocksFromModule(BBsOnClone, ToOptimize)) {
Chris Lattnera060b102004-05-11 21:54:13 +0000521 delete ToOptimize;
Rafael Espindola07035e62010-07-29 14:20:59 +0000522 // Run the predicate,
523 // note that the predicate will delete both input modules.
Rafael Espindola28b351a2014-08-26 17:19:03 +0000524 bool Ret = TestFn(BD, New.get(), ToNotOptimize, Error);
Rafael Espindola07035e62010-07-29 14:20:59 +0000525 delete BD.swapProgramIn(Orig);
526 return Ret;
Chris Lattnera060b102004-05-11 21:54:13 +0000527 }
Rafael Espindola07035e62010-07-29 14:20:59 +0000528 delete BD.swapProgramIn(Orig);
Chris Lattnera060b102004-05-11 21:54:13 +0000529 delete ToOptimize;
530 delete ToNotOptimize;
531 return false;
532}
533
534
535/// ExtractBlocks - Given a reduced list of functions that still expose the bug,
536/// extract as many basic blocks from the region as possible without obscuring
537/// the bug.
538///
539static bool ExtractBlocks(BugDriver &BD,
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000540 bool (*TestFn)(BugDriver &, Module *, Module *,
541 std::string &),
542 std::vector<Function*> &MiscompiledFunctions,
543 std::string &Error) {
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000544 if (BugpointIsInterrupted) return false;
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000545
Chris Lattnera060b102004-05-11 21:54:13 +0000546 std::vector<BasicBlock*> Blocks;
547 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000548 for (BasicBlock &BB : *MiscompiledFunctions[i])
549 Blocks.push_back(&BB);
Chris Lattnera060b102004-05-11 21:54:13 +0000550
551 // Use the list reducer to identify blocks that can be extracted without
552 // obscuring the bug. The Blocks list will end up containing blocks that must
553 // be retained from the original program.
554 unsigned OldSize = Blocks.size();
Chris Lattner6c0c3132004-05-12 16:08:01 +0000555
556 // Check to see if all blocks are extractible first.
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000557 bool Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
558 .TestFuncs(std::vector<BasicBlock*>(), Error);
559 if (!Error.empty())
560 return false;
561 if (Ret) {
Chris Lattner6c0c3132004-05-12 16:08:01 +0000562 Blocks.clear();
563 } else {
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000564 ReduceMiscompiledBlocks(BD, TestFn,
565 MiscompiledFunctions).reduceList(Blocks, Error);
566 if (!Error.empty())
567 return false;
Chris Lattner6c0c3132004-05-12 16:08:01 +0000568 if (Blocks.size() == OldSize)
569 return false;
570 }
Chris Lattnera060b102004-05-11 21:54:13 +0000571
Rafael Espindola229e38f2010-10-13 01:36:30 +0000572 ValueToValueMapTy VMap;
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000573 Module *ProgClone = CloneModule(BD.getProgram(), VMap);
Chris Lattner49e4a332004-05-12 02:43:24 +0000574 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
Dan Gohman956ae9d2009-04-22 15:57:18 +0000575 MiscompiledFunctions,
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000576 VMap);
Rafael Espindola28b351a2014-08-26 17:19:03 +0000577 std::unique_ptr<Module> Extracted =
578 BD.extractMappedBlocksFromModule(Blocks, ToExtract);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000579 if (!Extracted) {
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000580 // Weird, extraction should have worked.
Dan Gohmand8db3762009-07-15 16:35:29 +0000581 errs() << "Nondeterministic problem extracting blocks??\n";
Chris Lattner49e4a332004-05-12 02:43:24 +0000582 delete ProgClone;
583 delete ToExtract;
584 return false;
585 }
Chris Lattnera060b102004-05-11 21:54:13 +0000586
Chris Lattner49e4a332004-05-12 02:43:24 +0000587 // Otherwise, block extraction succeeded. Link the two program fragments back
588 // together.
589 delete ToExtract;
Chris Lattnera060b102004-05-11 21:54:13 +0000590
Chris Lattner229907c2011-07-18 04:54:35 +0000591 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
Chris Lattnerd3087972004-11-16 06:31:38 +0000592 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
593 I != E; ++I)
Reid Spencer5301e7c2007-01-30 20:08:39 +0000594 if (!I->isDeclaration())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000595 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
Chris Lattnerd3087972004-11-16 06:31:38 +0000596
Rafael Espindola9f8eff32014-10-28 00:24:16 +0000597 if (Linker::LinkModules(ProgClone, Extracted.get()))
Chris Lattner49e4a332004-05-12 02:43:24 +0000598 exit(1);
Chris Lattnera060b102004-05-11 21:54:13 +0000599
Chris Lattner49e4a332004-05-12 02:43:24 +0000600 // Set the new program and delete the old one.
601 BD.setNewProgram(ProgClone);
Chris Lattnera060b102004-05-11 21:54:13 +0000602
Chris Lattner49e4a332004-05-12 02:43:24 +0000603 // Update the list of miscompiled functions.
604 MiscompiledFunctions.clear();
Chris Lattnera060b102004-05-11 21:54:13 +0000605
Chris Lattnerd3087972004-11-16 06:31:38 +0000606 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000607 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
Chris Lattnerd3087972004-11-16 06:31:38 +0000608 assert(NewF && "Function not found??");
609 MiscompiledFunctions.push_back(NewF);
610 }
Chris Lattner49e4a332004-05-12 02:43:24 +0000611
612 return true;
Chris Lattnera060b102004-05-11 21:54:13 +0000613}
614
615
Chris Lattner0434ba32004-04-05 21:37:38 +0000616/// DebugAMiscompilation - This is a generic driver to narrow down
617/// miscompilations, either in an optimization or a code generator.
Misha Brukman0784a602004-04-21 18:36:43 +0000618///
Chris Lattner0434ba32004-04-05 21:37:38 +0000619static std::vector<Function*>
620DebugAMiscompilation(BugDriver &BD,
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000621 bool (*TestFn)(BugDriver &, Module *, Module *,
622 std::string &),
623 std::string &Error) {
Chris Lattner0434ba32004-04-05 21:37:38 +0000624 // Okay, now that we have reduced the list of passes which are causing the
625 // failure, see if we can pin down which functions are being
626 // miscompiled... first build a list of all of the non-external functions in
627 // the program.
628 std::vector<Function*> MiscompiledFunctions;
629 Module *Prog = BD.getProgram();
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000630 for (Function &F : *Prog)
631 if (!F.isDeclaration())
632 MiscompiledFunctions.push_back(&F);
Chris Lattner0434ba32004-04-05 21:37:38 +0000633
634 // Do the reduction...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000635 if (!BugpointIsInterrupted)
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000636 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
637 Error);
Andrew Trick55aeb552011-05-11 16:31:24 +0000638 if (!Error.empty()) {
639 errs() << "\n***Cannot reduce functions: ";
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000640 return MiscompiledFunctions;
Andrew Trick55aeb552011-05-11 16:31:24 +0000641 }
Dan Gohmanee051522009-07-16 15:30:09 +0000642 outs() << "\n*** The following function"
643 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
644 << " being miscompiled: ";
Chris Lattner0434ba32004-04-05 21:37:38 +0000645 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanee051522009-07-16 15:30:09 +0000646 outs() << '\n';
Chris Lattner0434ba32004-04-05 21:37:38 +0000647
648 // See if we can rip any loops out of the miscompiled functions and still
649 // trigger the problem.
Reid Spencer471bcb72006-11-11 19:05:02 +0000650
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000651 if (!BugpointIsInterrupted && !DisableLoopExtraction) {
652 bool Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions, Error);
653 if (!Error.empty())
654 return MiscompiledFunctions;
655 if (Ret) {
656 // Okay, we extracted some loops and the problem still appears. See if
657 // we can eliminate some of the created functions from being candidates.
658 DisambiguateGlobalSymbols(BD.getProgram());
Chris Lattnerdfbb1d12004-04-11 23:52:35 +0000659
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000660 // Do the reduction...
661 if (!BugpointIsInterrupted)
662 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
663 Error);
664 if (!Error.empty())
665 return MiscompiledFunctions;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000666
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000667 outs() << "\n*** The following function"
668 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
669 << " being miscompiled: ";
670 PrintFunctionList(MiscompiledFunctions);
671 outs() << '\n';
672 }
Chris Lattner0434ba32004-04-05 21:37:38 +0000673 }
674
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000675 if (!BugpointIsInterrupted && !DisableBlockExtraction) {
676 bool Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions, Error);
677 if (!Error.empty())
678 return MiscompiledFunctions;
679 if (Ret) {
680 // Okay, we extracted some blocks and the problem still appears. See if
681 // we can eliminate some of the created functions from being candidates.
682 DisambiguateGlobalSymbols(BD.getProgram());
Chris Lattnera060b102004-05-11 21:54:13 +0000683
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000684 // Do the reduction...
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 Lattnera060b102004-05-11 21:54:13 +0000696 }
697
Chris Lattner0434ba32004-04-05 21:37:38 +0000698 return MiscompiledFunctions;
699}
700
Chris Lattnerbf791612004-04-05 22:58:16 +0000701/// TestOptimizer - This is the predicate function used to check to see if the
702/// "Test" portion of the program is misoptimized. If so, return true. In any
703/// case, both module arguments are deleted.
Misha Brukman0784a602004-04-21 18:36:43 +0000704///
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000705static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe,
706 std::string &Error) {
Chris Lattner0434ba32004-04-05 21:37:38 +0000707 // Run the optimization passes on ToOptimize, producing a transformed version
708 // of the functions being tested.
Dan Gohmanee051522009-07-16 15:30:09 +0000709 outs() << " Optimizing functions being tested: ";
Rafael Espindola28b351a2014-08-26 17:19:03 +0000710 std::unique_ptr<Module> Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
711 /*AutoDebugCrashes*/ true);
Dan Gohmanee051522009-07-16 15:30:09 +0000712 outs() << "done.\n";
Chris Lattner0434ba32004-04-05 21:37:38 +0000713 delete Test;
714
Dan Gohmanee051522009-07-16 15:30:09 +0000715 outs() << " Checking to see if the merged program executes correctly: ";
Rafael Espindolae4904602010-07-31 14:34:49 +0000716 bool Broken;
Rafael Espindola28b351a2014-08-26 17:19:03 +0000717 Module *New =
718 TestMergedProgram(BD, Optimized.get(), Safe, true, Error, Broken);
Rafael Espindolae4904602010-07-31 14:34:49 +0000719 if (New) {
720 outs() << (Broken ? " nope.\n" : " yup.\n");
721 // Delete the original and set the new program.
722 delete BD.swapProgramIn(New);
723 }
Chris Lattner0434ba32004-04-05 21:37:38 +0000724 return Broken;
725}
726
727
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000728/// debugMiscompilation - This method is used when the passes selected are not
729/// crashing, but the generated output is semantically different from the
730/// input.
731///
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000732void BugDriver::debugMiscompilation(std::string *Error) {
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000733 // Make sure something was miscompiled...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000734 if (!BugpointIsInterrupted)
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000735 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun, *Error)) {
736 if (Error->empty())
737 errs() << "*** Optimized program matches reference output! No problem"
738 << " detected...\nbugpoint can't help you with your problem!\n";
739 return;
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000740 }
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000741
Dan Gohmanee051522009-07-16 15:30:09 +0000742 outs() << "\n*** Found miscompiling pass"
743 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
744 << getPassesString(getPassesToRun()) << '\n';
Rafael Espindola594994a2010-07-28 18:12:30 +0000745 EmitProgressBitcode(Program, "passinput");
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000746
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000747 std::vector<Function *> MiscompiledFunctions =
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000748 DebugAMiscompilation(*this, TestOptimizer, *Error);
749 if (!Error->empty())
750 return;
Chris Lattnerbcec7872004-03-14 22:08:00 +0000751
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000752 // Output a bunch of bitcode files for the user...
Dan Gohmanee051522009-07-16 15:30:09 +0000753 outs() << "Outputting reduced bitcode files which expose the problem:\n";
Rafael Espindola229e38f2010-10-13 01:36:30 +0000754 ValueToValueMapTy VMap;
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000755 Module *ToNotOptimize = CloneModule(getProgram(), VMap);
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000756 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohman956ae9d2009-04-22 15:57:18 +0000757 MiscompiledFunctions,
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000758 VMap);
Chris Lattner567543f2004-03-14 19:27:19 +0000759
Dan Gohmanee051522009-07-16 15:30:09 +0000760 outs() << " Non-optimized portion: ";
Rafael Espindola594994a2010-07-28 18:12:30 +0000761 EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true);
762 delete ToNotOptimize; // Delete hacked module.
Misha Brukman650ba8e2005-04-22 00:00:37 +0000763
Dan Gohmanee051522009-07-16 15:30:09 +0000764 outs() << " Portion that is input to optimizer: ";
Rafael Espindola594994a2010-07-28 18:12:30 +0000765 EmitProgressBitcode(ToOptimize, "tooptimize");
766 delete ToOptimize; // Delete hacked module.
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000767
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000768 return;
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000769}
Brian Gaeke960707c2003-11-11 22:41:34 +0000770
Chris Lattnerbf791612004-04-05 22:58:16 +0000771/// CleanupAndPrepareModules - Get the specified modules ready for code
772/// generator testing.
Misha Brukman0784a602004-04-21 18:36:43 +0000773///
Chris Lattnerbf791612004-04-05 22:58:16 +0000774static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
775 Module *Safe) {
776 // Clean up the modules, removing extra cruft that we don't need anymore...
Rafael Espindola28b351a2014-08-26 17:19:03 +0000777 Test = BD.performFinalCleanups(Test).release();
Chris Lattnerbf791612004-04-05 22:58:16 +0000778
779 // If we are executing the JIT, we have several nasty issues to take care of.
780 if (!BD.isExecutingJIT()) return;
781
782 // First, if the main function is in the Safe module, we must add a stub to
783 // the Test module to call into it. Thus, we create a new function `main'
784 // which just calls the old one.
Reid Spencer1241d6d2007-02-05 21:19:13 +0000785 if (Function *oldMain = Safe->getFunction("main"))
Reid Spencer5301e7c2007-01-30 20:08:39 +0000786 if (!oldMain->isDeclaration()) {
Chris Lattnerbf791612004-04-05 22:58:16 +0000787 // Rename it
788 oldMain->setName("llvm_bugpoint_old_main");
789 // Create a NEW `main' function with same type in the test module.
Gabor Greife9ecc682008-04-06 20:25:17 +0000790 Function *newMain = Function::Create(oldMain->getFunctionType(),
791 GlobalValue::ExternalLinkage,
792 "main", Test);
Chris Lattnerbf791612004-04-05 22:58:16 +0000793 // Create an `oldmain' prototype in the test module, which will
794 // corresponds to the real main function in the same module.
Gabor Greife9ecc682008-04-06 20:25:17 +0000795 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
796 GlobalValue::ExternalLinkage,
797 oldMain->getName(), Test);
Chris Lattnerbf791612004-04-05 22:58:16 +0000798 // Set up and remember the argument list for the main function.
799 std::vector<Value*> args;
Alkis Evlogimenosa67bafa2005-03-15 07:02:26 +0000800 for (Function::arg_iterator
801 I = newMain->arg_begin(), E = newMain->arg_end(),
802 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
Owen Anderson7629b712008-04-14 17:38:21 +0000803 I->setName(OI->getName()); // Copy argument names from oldMain
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000804 args.push_back(&*I);
Chris Lattnerbf791612004-04-05 22:58:16 +0000805 }
806
807 // Call the old main function and return its result
Owen Anderson55f1c092009-08-13 21:58:54 +0000808 BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
Jay Foad5bd375a2011-07-15 08:37:34 +0000809 CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000810
Chris Lattnerbf791612004-04-05 22:58:16 +0000811 // If the type of old function wasn't void, return value of call
Owen Anderson55f1c092009-08-13 21:58:54 +0000812 ReturnInst::Create(Safe->getContext(), call, BB);
Chris Lattnerbf791612004-04-05 22:58:16 +0000813 }
814
815 // The second nasty issue we must deal with in the JIT is that the Safe
816 // module cannot directly reference any functions defined in the test
817 // module. Instead, we use a JIT API call to dynamically resolve the
818 // symbol.
Misha Brukman650ba8e2005-04-22 00:00:37 +0000819
Chris Lattnerbf791612004-04-05 22:58:16 +0000820 // Add the resolver to the Safe module.
821 // Prototype: void *getPointerToNamedFunction(const char* Name)
Chris Lattner7b864c02007-01-07 08:13:39 +0000822 Constant *resolverFunc =
Chris Lattnerbf791612004-04-05 22:58:16 +0000823 Safe->getOrInsertFunction("getPointerToNamedFunction",
Duncan Sands9ed7b162009-10-06 15:40:36 +0000824 Type::getInt8PtrTy(Safe->getContext()),
825 Type::getInt8PtrTy(Safe->getContext()),
Craig Toppere6cb63e2014-04-25 04:24:47 +0000826 (Type *)nullptr);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000827
Chris Lattnerbf791612004-04-05 22:58:16 +0000828 // Use the function we just added to get addresses of functions we need.
Misha Brukman83018642004-04-19 01:12:01 +0000829 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
Reid Spencer5301e7c2007-01-30 20:08:39 +0000830 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
Duncan Sands38ef3a82007-12-03 20:06:50 +0000831 !F->isIntrinsic() /* ignore intrinsics */) {
Reid Spencer1241d6d2007-02-05 21:19:13 +0000832 Function *TestFn = Test->getFunction(F->getName());
Chris Lattnerbf791612004-04-05 22:58:16 +0000833
834 // Don't forward functions which are external in the test module too.
Reid Spencer5301e7c2007-01-30 20:08:39 +0000835 if (TestFn && !TestFn->isDeclaration()) {
Chris Lattnerbf791612004-04-05 22:58:16 +0000836 // 1. Add a string constant with its name to the global file
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000837 Constant *InitArray =
838 ConstantDataArray::getString(F->getContext(), F->getName());
Chris Lattnerbf791612004-04-05 22:58:16 +0000839 GlobalVariable *funcName =
Owen Andersonb17f3292009-07-08 19:03:57 +0000840 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
Misha Brukman650ba8e2005-04-22 00:00:37 +0000841 GlobalValue::InternalLinkage, InitArray,
Owen Andersonb17f3292009-07-08 19:03:57 +0000842 F->getName() + "_name");
Chris Lattnerbf791612004-04-05 22:58:16 +0000843
844 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
845 // sbyte* so it matches the signature of the resolver function.
846
847 // GetElementPtr *funcName, ulong 0, ulong 0
Owen Anderson55f1c092009-08-13 21:58:54 +0000848 std::vector<Constant*> GEPargs(2,
849 Constant::getNullValue(Type::getInt32Ty(F->getContext())));
David Blaikie4a2e73b2015-04-02 18:55:32 +0000850 Value *GEP = ConstantExpr::getGetElementPtr(InitArray->getType(),
851 funcName, GEPargs);
Chris Lattnerbf791612004-04-05 22:58:16 +0000852 std::vector<Value*> ResolverArgs;
853 ResolverArgs.push_back(GEP);
854
Misha Brukmance89b392004-04-19 03:36:47 +0000855 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
856 // function that dynamically resolves the calls to F via our JIT API
Chris Lattner986675c2005-07-12 01:00:32 +0000857 if (!F->use_empty()) {
858 // Create a new global to hold the cached function pointer.
Owen Andersonb292b8c2009-07-30 23:03:37 +0000859 Constant *NullPtr = ConstantPointerNull::get(F->getType());
Chris Lattner986675c2005-07-12 01:00:32 +0000860 GlobalVariable *Cache =
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000861 new GlobalVariable(*F->getParent(), F->getType(),
Owen Andersonb17f3292009-07-08 19:03:57 +0000862 false, GlobalValue::InternalLinkage,
863 NullPtr,F->getName()+".fpcache");
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000864
Misha Brukmance89b392004-04-19 03:36:47 +0000865 // Construct a new stub function that will re-route calls to F
Chris Lattner229907c2011-07-18 04:54:35 +0000866 FunctionType *FuncTy = F->getFunctionType();
Gabor Greife9ecc682008-04-06 20:25:17 +0000867 Function *FuncWrapper = Function::Create(FuncTy,
868 GlobalValue::InternalLinkage,
869 F->getName() + "_wrapper",
870 F->getParent());
Owen Anderson55f1c092009-08-13 21:58:54 +0000871 BasicBlock *EntryBB = BasicBlock::Create(F->getContext(),
872 "entry", FuncWrapper);
873 BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
874 "usecache", FuncWrapper);
875 BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
876 "lookupfp", FuncWrapper);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000877
Chris Lattner986675c2005-07-12 01:00:32 +0000878 // Check to see if we already looked up the value.
879 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000880 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
881 NullPtr, "isNull");
Gabor Greife9ecc682008-04-06 20:25:17 +0000882 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000883
Misha Brukmance89b392004-04-19 03:36:47 +0000884 // Resolve the call to function F via the JIT API:
885 //
886 // call resolver(GetElementPtr...)
Gabor Greif697e94c2008-05-15 10:04:30 +0000887 CallInst *Resolver =
Jay Foad5bd375a2011-07-15 08:37:34 +0000888 CallInst::Create(resolverFunc, ResolverArgs, "resolver", LookupBB);
Gabor Greif697e94c2008-05-15 10:04:30 +0000889
890 // Cast the result from the resolver to correctly-typed function.
891 CastInst *CastedResolver =
892 new BitCastInst(Resolver,
Owen Anderson4056ca92009-07-29 22:17:13 +0000893 PointerType::getUnqual(F->getFunctionType()),
Gabor Greif697e94c2008-05-15 10:04:30 +0000894 "resolverCast", LookupBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000895
Chris Lattner986675c2005-07-12 01:00:32 +0000896 // Save the value in our cache.
897 new StoreInst(CastedResolver, Cache, LookupBB);
Gabor Greife9ecc682008-04-06 20:25:17 +0000898 BranchInst::Create(DoCallBB, LookupBB);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000899
Jay Foad52131342011-03-30 11:28:46 +0000900 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(), 2,
Gabor Greif697e94c2008-05-15 10:04:30 +0000901 "fp", DoCallBB);
Chris Lattner986675c2005-07-12 01:00:32 +0000902 FuncPtr->addIncoming(CastedResolver, LookupBB);
903 FuncPtr->addIncoming(CachedVal, EntryBB);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000904
Chris Lattner986675c2005-07-12 01:00:32 +0000905 // Save the argument list.
Misha Brukman83018642004-04-19 01:12:01 +0000906 std::vector<Value*> Args;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000907 for (Argument &A : FuncWrapper->args())
908 Args.push_back(&A);
Misha Brukman83018642004-04-19 01:12:01 +0000909
910 // Pass on the arguments to the real function, return its result
Dan Gohman34a22492010-06-07 20:19:26 +0000911 if (F->getReturnType()->isVoidTy()) {
Jay Foad5bd375a2011-07-15 08:37:34 +0000912 CallInst::Create(FuncPtr, Args, "", DoCallBB);
Owen Anderson55f1c092009-08-13 21:58:54 +0000913 ReturnInst::Create(F->getContext(), DoCallBB);
Misha Brukman83018642004-04-19 01:12:01 +0000914 } else {
Jay Foad5bd375a2011-07-15 08:37:34 +0000915 CallInst *Call = CallInst::Create(FuncPtr, Args,
Gabor Greife9ecc682008-04-06 20:25:17 +0000916 "retval", DoCallBB);
Owen Anderson55f1c092009-08-13 21:58:54 +0000917 ReturnInst::Create(F->getContext(),Call, DoCallBB);
Misha Brukman83018642004-04-19 01:12:01 +0000918 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000919
Misha Brukmance89b392004-04-19 03:36:47 +0000920 // Use the wrapper function instead of the old function
921 F->replaceAllUsesWith(FuncWrapper);
Misha Brukman83018642004-04-19 01:12:01 +0000922 }
Chris Lattnerbf791612004-04-05 22:58:16 +0000923 }
924 }
925 }
926
927 if (verifyModule(*Test) || verifyModule(*Safe)) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000928 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
Chris Lattnerbf791612004-04-05 22:58:16 +0000929 abort();
930 }
931}
932
933
934
935/// TestCodeGenerator - This is the predicate function used to check to see if
936/// the "Test" portion of the program is miscompiled by the code generator under
937/// test. If so, return true. In any case, both module arguments are deleted.
Misha Brukman0784a602004-04-21 18:36:43 +0000938///
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000939static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe,
940 std::string &Error) {
Chris Lattnerbf791612004-04-05 22:58:16 +0000941 CleanupAndPrepareModules(BD, Test, Safe);
942
Rafael Espindola302c0da2013-06-18 15:29:32 +0000943 SmallString<128> TestModuleBC;
944 int TestModuleFD;
Rafael Espindola4453e42942014-06-13 03:07:50 +0000945 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
946 TestModuleFD, TestModuleBC);
Rafael Espindola302c0da2013-06-18 15:29:32 +0000947 if (EC) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000948 errs() << BD.getToolName() << "Error making unique filename: "
Rafael Espindola302c0da2013-06-18 15:29:32 +0000949 << EC.message() << "\n";
Reid Spencere4ca7222006-08-23 20:34:57 +0000950 exit(1);
951 }
Rafael Espindola302c0da2013-06-18 15:29:32 +0000952 if (BD.writeProgramToFile(TestModuleBC.str(), TestModuleFD, Test)) {
Chris Lattnerc521f542009-08-23 22:45:37 +0000953 errs() << "Error writing bitcode to `" << TestModuleBC.str()
954 << "'\nExiting.";
Chris Lattnerbf791612004-04-05 22:58:16 +0000955 exit(1);
956 }
957 delete Test;
958
Michael J. Spencerc60223e2011-03-31 13:04:19 +0000959 FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
Rafael Espindola720f49e2010-06-21 02:17:36 +0000960
Chris Lattnerbf791612004-04-05 22:58:16 +0000961 // Make the shared library
Rafael Espindola302c0da2013-06-18 15:29:32 +0000962 SmallString<128> SafeModuleBC;
963 int SafeModuleFD;
Rafael Espindola155cf0f2013-07-05 20:14:52 +0000964 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
965 SafeModuleBC);
Rafael Espindola302c0da2013-06-18 15:29:32 +0000966 if (EC) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000967 errs() << BD.getToolName() << "Error making unique filename: "
Rafael Espindola302c0da2013-06-18 15:29:32 +0000968 << EC.message() << "\n";
Reid Spencere4ca7222006-08-23 20:34:57 +0000969 exit(1);
970 }
Chris Lattnerbf791612004-04-05 22:58:16 +0000971
Rafael Espindola302c0da2013-06-18 15:29:32 +0000972 if (BD.writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, Safe)) {
Yaron Keren09fb7c62015-03-10 07:33:23 +0000973 errs() << "Error writing bitcode to `" << SafeModuleBC
Chris Lattnerc521f542009-08-23 22:45:37 +0000974 << "'\nExiting.";
Chris Lattnerbf791612004-04-05 22:58:16 +0000975 exit(1);
976 }
Rafael Espindola720f49e2010-06-21 02:17:36 +0000977
Michael J. Spencerc60223e2011-03-31 13:04:19 +0000978 FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
Rafael Espindola720f49e2010-06-21 02:17:36 +0000979
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000980 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str(), Error);
981 if (!Error.empty())
Benjamin Kramer1f336da2010-04-12 12:22:19 +0000982 return false;
Chris Lattnerbf791612004-04-05 22:58:16 +0000983 delete Safe;
984
Michael J. Spencerc60223e2011-03-31 13:04:19 +0000985 FileRemover SharedObjectRemover(SharedObject, !SaveTemps);
Rafael Espindola720f49e2010-06-21 02:17:36 +0000986
Chris Lattnerbf791612004-04-05 22:58:16 +0000987 // Run the code generator on the `Test' code, loading the shared library.
988 // The function returns whether or not the new output differs from reference.
Rafael Espindolac89b1ef2010-07-30 14:19:00 +0000989 bool Result = BD.diffProgram(BD.getProgram(), TestModuleBC.str(),
990 SharedObject, false, &Error);
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000991 if (!Error.empty())
992 return false;
Chris Lattnerbf791612004-04-05 22:58:16 +0000993
994 if (Result)
Dan Gohmand8db3762009-07-15 16:35:29 +0000995 errs() << ": still failing!\n";
Chris Lattnerbf791612004-04-05 22:58:16 +0000996 else
Dan Gohmand8db3762009-07-15 16:35:29 +0000997 errs() << ": didn't fail.\n";
Chris Lattnerbf791612004-04-05 22:58:16 +0000998
999 return Result;
1000}
1001
1002
Misha Brukman0784a602004-04-21 18:36:43 +00001003/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
1004///
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001005bool BugDriver::debugCodeGenerator(std::string *Error) {
Dan Gohman414cf502008-12-08 04:02:47 +00001006 if ((void*)SafeInterpreter == (void*)Interpreter) {
Rafael Espindolac89b1ef2010-07-30 14:19:00 +00001007 std::string Result = executeProgramSafely(Program, "bugpoint.safe.out",
1008 Error);
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001009 if (Error->empty()) {
1010 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
1011 << "the reference diff. This may be due to a\n front-end "
1012 << "bug or a bug in the original program, but this can also "
1013 << "happen if bugpoint isn't running the program with the "
1014 << "right flags or input.\n I left the result of executing "
1015 << "the program with the \"safe\" backend in this file for "
1016 << "you: '"
1017 << Result << "'.\n";
1018 }
Chris Lattnerbf791612004-04-05 22:58:16 +00001019 return true;
1020 }
1021
1022 DisambiguateGlobalSymbols(Program);
1023
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001024 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator,
1025 *Error);
1026 if (!Error->empty())
1027 return true;
Chris Lattnerbf791612004-04-05 22:58:16 +00001028
1029 // Split the module into the two halves of the program we want.
Rafael Espindola229e38f2010-10-13 01:36:30 +00001030 ValueToValueMapTy VMap;
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001031 Module *ToNotCodeGen = CloneModule(getProgram(), VMap);
1032 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, VMap);
Chris Lattnerbf791612004-04-05 22:58:16 +00001033
1034 // Condition the modules
1035 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
1036
Rafael Espindola302c0da2013-06-18 15:29:32 +00001037 SmallString<128> TestModuleBC;
1038 int TestModuleFD;
Rafael Espindola4453e42942014-06-13 03:07:50 +00001039 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
1040 TestModuleFD, TestModuleBC);
Rafael Espindola302c0da2013-06-18 15:29:32 +00001041 if (EC) {
Dan Gohmand8db3762009-07-15 16:35:29 +00001042 errs() << getToolName() << "Error making unique filename: "
Rafael Espindola302c0da2013-06-18 15:29:32 +00001043 << EC.message() << "\n";
Reid Spencere4ca7222006-08-23 20:34:57 +00001044 exit(1);
1045 }
Reid Spencer30067f12004-12-15 01:53:08 +00001046
Rafael Espindola302c0da2013-06-18 15:29:32 +00001047 if (writeProgramToFile(TestModuleBC.str(), TestModuleFD, ToCodeGen)) {
Yaron Keren09fb7c62015-03-10 07:33:23 +00001048 errs() << "Error writing bitcode to `" << TestModuleBC
Chris Lattnerc521f542009-08-23 22:45:37 +00001049 << "'\nExiting.";
Chris Lattnerbf791612004-04-05 22:58:16 +00001050 exit(1);
1051 }
1052 delete ToCodeGen;
1053
1054 // Make the shared library
Rafael Espindola302c0da2013-06-18 15:29:32 +00001055 SmallString<128> SafeModuleBC;
1056 int SafeModuleFD;
Rafael Espindola155cf0f2013-07-05 20:14:52 +00001057 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
1058 SafeModuleBC);
Rafael Espindola302c0da2013-06-18 15:29:32 +00001059 if (EC) {
Dan Gohmand8db3762009-07-15 16:35:29 +00001060 errs() << getToolName() << "Error making unique filename: "
Rafael Espindola302c0da2013-06-18 15:29:32 +00001061 << EC.message() << "\n";
Reid Spencere4ca7222006-08-23 20:34:57 +00001062 exit(1);
1063 }
Reid Spencer30067f12004-12-15 01:53:08 +00001064
Rafael Espindola302c0da2013-06-18 15:29:32 +00001065 if (writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, ToNotCodeGen)) {
Yaron Keren09fb7c62015-03-10 07:33:23 +00001066 errs() << "Error writing bitcode to `" << SafeModuleBC
Chris Lattnerc521f542009-08-23 22:45:37 +00001067 << "'\nExiting.";
Chris Lattnerbf791612004-04-05 22:58:16 +00001068 exit(1);
1069 }
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001070 std::string SharedObject = compileSharedObject(SafeModuleBC.str(), *Error);
1071 if (!Error->empty())
1072 return true;
Chris Lattnerbf791612004-04-05 22:58:16 +00001073 delete ToNotCodeGen;
1074
Dan Gohmanee051522009-07-16 15:30:09 +00001075 outs() << "You can reproduce the problem with the command line: \n";
Chris Lattnerbf791612004-04-05 22:58:16 +00001076 if (isExecutingJIT()) {
Yaron Keren09fb7c62015-03-10 07:33:23 +00001077 outs() << " lli -load " << SharedObject << " " << TestModuleBC;
Chris Lattnerbf791612004-04-05 22:58:16 +00001078 } else {
Yaron Keren09fb7c62015-03-10 07:33:23 +00001079 outs() << " llc " << TestModuleBC << " -o " << TestModuleBC
Chris Lattnerc521f542009-08-23 22:45:37 +00001080 << ".s\n";
Davide Italianoab256212015-10-14 20:29:54 +00001081 outs() << " cc " << SharedObject << " " << TestModuleBC.str()
Yaron Keren09fb7c62015-03-10 07:33:23 +00001082 << ".s -o " << TestModuleBC << ".exe";
Chris Lattnerea2fa462005-01-15 00:07:19 +00001083#if defined (HAVE_LINK_R)
Dan Gohmanee051522009-07-16 15:30:09 +00001084 outs() << " -Wl,-R.";
Chris Lattnerea2fa462005-01-15 00:07:19 +00001085#endif
Dan Gohmanee051522009-07-16 15:30:09 +00001086 outs() << "\n";
Yaron Keren09fb7c62015-03-10 07:33:23 +00001087 outs() << " " << TestModuleBC << ".exe";
Chris Lattnerbf791612004-04-05 22:58:16 +00001088 }
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001089 for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
Dan Gohmanee051522009-07-16 15:30:09 +00001090 outs() << " " << InputArgv[i];
1091 outs() << '\n';
1092 outs() << "The shared object was created with:\n llc -march=c "
Chris Lattnerc521f542009-08-23 22:45:37 +00001093 << SafeModuleBC.str() << " -o temporary.c\n"
Davide Italianoab256212015-10-14 20:29:54 +00001094 << " cc -xc temporary.c -O2 -o " << SharedObject;
Daniel Dunbar8575a602009-08-18 03:35:57 +00001095 if (TargetTriple.getArch() == Triple::sparc)
1096 outs() << " -G"; // Compile a shared library, `-G' for Sparc
1097 else
1098 outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
1099
1100 outs() << " -fno-strict-aliasing\n";
Chris Lattnerbf791612004-04-05 22:58:16 +00001101
1102 return false;
1103}