blob: f17bfaa64a1d302b37f2d0588cc1b51c2c0569c1 [file] [log] [blame]
Chris Lattner4a106452002-12-23 23:50:16 +00001//===- Miscompilation.cpp - Debug program miscompilations -----------------===//
John Criswell7c0e0222003-10-20 17:47:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner4a106452002-12-23 23:50:16 +00009//
Chris Lattnera57d86b2004-04-05 22:58:16 +000010// This file implements optimizer and code generation miscompilation debugging
11// support.
Chris Lattner4a106452002-12-23 23:50:16 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "BugDriver.h"
Chris Lattner126840f2003-04-24 20:16:29 +000016#include "ListReducer.h"
Chris Lattnera57d86b2004-04-05 22:58:16 +000017#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Instructions.h"
Chris Lattner4a106452002-12-23 23:50:16 +000020#include "llvm/Module.h"
Misha Brukmane49603d2003-08-07 21:19:30 +000021#include "llvm/Pass.h"
Chris Lattnera57d86b2004-04-05 22:58:16 +000022#include "llvm/Analysis/Verifier.h"
23#include "llvm/Support/Mangler.h"
Chris Lattner640f22e2003-04-24 17:02:17 +000024#include "llvm/Transforms/Utils/Cloning.h"
25#include "llvm/Transforms/Utils/Linker.h"
Chris Lattnera57d86b2004-04-05 22:58:16 +000026#include "Support/CommandLine.h"
Misha Brukman3d9cafa2003-08-07 21:42:28 +000027#include "Support/FileUtilities.h"
Chris Lattnerfa761832004-01-14 03:38:37 +000028using namespace llvm;
Chris Lattner4a106452002-12-23 23:50:16 +000029
Chris Lattnera57d86b2004-04-05 22:58:16 +000030namespace llvm {
31 extern cl::list<std::string> InputArgv;
Chris Lattner5e783ab2004-05-11 21:54:13 +000032 cl::opt<bool>
33 EnableBlockExtraction("enable-block-extraction",
34 cl::desc("Enable basic block extraction for "
35 "miscompilation debugging (experimental)"));
Chris Lattnera57d86b2004-04-05 22:58:16 +000036}
37
Chris Lattnerefdc0b52004-03-14 20:50:42 +000038namespace {
Chris Lattnerfa761832004-01-14 03:38:37 +000039 class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
40 BugDriver &BD;
41 public:
42 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
43
44 virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
45 std::vector<const PassInfo*> &Suffix);
46 };
47}
Chris Lattner640f22e2003-04-24 17:02:17 +000048
Misha Brukman8c194ea2004-04-21 18:36:43 +000049/// TestResult - After passes have been split into a test group and a control
50/// group, see if they still break the program.
51///
Chris Lattner640f22e2003-04-24 17:02:17 +000052ReduceMiscompilingPasses::TestResult
Chris Lattner39aebca2003-04-24 22:24:22 +000053ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
Chris Lattner06943ad2003-04-25 03:16:05 +000054 std::vector<const PassInfo*> &Suffix) {
55 // First, run the program with just the Suffix passes. If it is still broken
Chris Lattner640f22e2003-04-24 17:02:17 +000056 // with JUST the kept passes, discard the prefix passes.
Chris Lattner06943ad2003-04-25 03:16:05 +000057 std::cout << "Checking to see if '" << getPassesString(Suffix)
Chris Lattner640f22e2003-04-24 17:02:17 +000058 << "' compile correctly: ";
59
60 std::string BytecodeResult;
Chris Lattner06943ad2003-04-25 03:16:05 +000061 if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
Chris Lattner9f71e792003-10-18 00:05:05 +000062 std::cerr << " Error running this sequence of passes"
Chris Lattner640f22e2003-04-24 17:02:17 +000063 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +000064 BD.setPassesToRun(Suffix);
65 BD.EmitProgressBytecode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +000066 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +000067 }
68
69 // Check to see if the finished program matches the reference output...
Misha Brukman50733362003-07-24 18:17:43 +000070 if (BD.diffProgram(BytecodeResult, "", true /*delete bytecode*/)) {
Misha Brukman123f8fe2004-04-22 20:02:09 +000071 std::cout << " nope.\n";
72 return KeepSuffix; // Miscompilation detected!
Chris Lattner640f22e2003-04-24 17:02:17 +000073 }
Misha Brukman123f8fe2004-04-22 20:02:09 +000074 std::cout << " yup.\n"; // No miscompilation!
Chris Lattner640f22e2003-04-24 17:02:17 +000075
76 if (Prefix.empty()) return NoFailure;
77
Chris Lattner06943ad2003-04-25 03:16:05 +000078 // Next, see if the program is broken if we run the "prefix" passes first,
Misha Brukmanbc0e9982003-07-14 17:20:40 +000079 // then separately run the "kept" passes.
Chris Lattner640f22e2003-04-24 17:02:17 +000080 std::cout << "Checking to see if '" << getPassesString(Prefix)
81 << "' compile correctly: ";
82
83 // If it is not broken with the kept passes, it's possible that the prefix
84 // passes must be run before the kept passes to break it. If the program
85 // WORKS after the prefix passes, but then fails if running the prefix AND
86 // kept passes, we can update our bytecode file to include the result of the
87 // prefix passes, then discard the prefix passes.
88 //
89 if (BD.runPasses(Prefix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
Chris Lattner9f71e792003-10-18 00:05:05 +000090 std::cerr << " Error running this sequence of passes"
Chris Lattner640f22e2003-04-24 17:02:17 +000091 << " on the input program!\n";
Chris Lattner9c6cfe12003-10-17 23:03:16 +000092 BD.setPassesToRun(Prefix);
93 BD.EmitProgressBytecode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +000094 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +000095 }
96
97 // If the prefix maintains the predicate by itself, only keep the prefix!
Misha Brukman50733362003-07-24 18:17:43 +000098 if (BD.diffProgram(BytecodeResult)) {
Misha Brukman123f8fe2004-04-22 20:02:09 +000099 std::cout << " nope.\n";
Chris Lattner640f22e2003-04-24 17:02:17 +0000100 removeFile(BytecodeResult);
101 return KeepPrefix;
102 }
Misha Brukman123f8fe2004-04-22 20:02:09 +0000103 std::cout << " yup.\n"; // No miscompilation!
Chris Lattner640f22e2003-04-24 17:02:17 +0000104
105 // Ok, so now we know that the prefix passes work, try running the suffix
106 // passes on the result of the prefix passes.
107 //
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000108 Module *PrefixOutput = ParseInputFile(BytecodeResult);
Chris Lattner640f22e2003-04-24 17:02:17 +0000109 if (PrefixOutput == 0) {
110 std::cerr << BD.getToolName() << ": Error reading bytecode file '"
111 << BytecodeResult << "'!\n";
112 exit(1);
113 }
114 removeFile(BytecodeResult); // No longer need the file on disk
Chris Lattnerf4789e62004-04-23 20:36:51 +0000115
116 // Don't check if there are no passes in the suffix.
117 if (Suffix.empty())
118 return NoFailure;
119
Chris Lattner06943ad2003-04-25 03:16:05 +0000120 std::cout << "Checking to see if '" << getPassesString(Suffix)
Chris Lattner640f22e2003-04-24 17:02:17 +0000121 << "' passes compile correctly after the '"
122 << getPassesString(Prefix) << "' passes: ";
123
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000124 Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
Chris Lattner06943ad2003-04-25 03:16:05 +0000125 if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
Chris Lattner9f71e792003-10-18 00:05:05 +0000126 std::cerr << " Error running this sequence of passes"
Chris Lattner640f22e2003-04-24 17:02:17 +0000127 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +0000128 BD.setPassesToRun(Suffix);
Chris Lattner9c6cfe12003-10-17 23:03:16 +0000129 BD.EmitProgressBytecode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +0000130 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +0000131 }
132
133 // Run the result...
Misha Brukman50733362003-07-24 18:17:43 +0000134 if (BD.diffProgram(BytecodeResult, "", true/*delete bytecode*/)) {
Misha Brukman123f8fe2004-04-22 20:02:09 +0000135 std::cout << " nope.\n";
Chris Lattner640f22e2003-04-24 17:02:17 +0000136 delete OriginalInput; // We pruned down the original input...
Chris Lattner06943ad2003-04-25 03:16:05 +0000137 return KeepSuffix;
Chris Lattner640f22e2003-04-24 17:02:17 +0000138 }
139
140 // Otherwise, we must not be running the bad pass anymore.
Misha Brukman123f8fe2004-04-22 20:02:09 +0000141 std::cout << " yup.\n"; // No miscompilation!
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000142 delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test
Chris Lattner640f22e2003-04-24 17:02:17 +0000143 return NoFailure;
144}
145
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000146namespace {
Chris Lattnerfa761832004-01-14 03:38:37 +0000147 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
148 BugDriver &BD;
Chris Lattnerb15825b2004-04-05 21:37:38 +0000149 bool (*TestFn)(BugDriver &, Module *, Module *);
Chris Lattnerfa761832004-01-14 03:38:37 +0000150 public:
Chris Lattnerb15825b2004-04-05 21:37:38 +0000151 ReduceMiscompilingFunctions(BugDriver &bd,
152 bool (*F)(BugDriver &, Module *, Module *))
153 : BD(bd), TestFn(F) {}
Chris Lattnerfa761832004-01-14 03:38:37 +0000154
155 virtual TestResult doTest(std::vector<Function*> &Prefix,
156 std::vector<Function*> &Suffix) {
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000157 if (!Suffix.empty() && TestFuncs(Suffix))
Chris Lattnerfa761832004-01-14 03:38:37 +0000158 return KeepSuffix;
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000159 if (!Prefix.empty() && TestFuncs(Prefix))
Chris Lattnerfa761832004-01-14 03:38:37 +0000160 return KeepPrefix;
161 return NoFailure;
162 }
163
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000164 bool TestFuncs(const std::vector<Function*> &Prefix);
Chris Lattnerfa761832004-01-14 03:38:37 +0000165 };
166}
Chris Lattner640f22e2003-04-24 17:02:17 +0000167
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000168/// TestMergedProgram - Given two modules, link them together and run the
169/// program, checking to see if the program matches the diff. If the diff
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000170/// matches, return false, otherwise return true. If the DeleteInputs argument
171/// is set to true then this function deletes both input modules before it
172/// returns.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000173///
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000174static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
175 bool DeleteInputs) {
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000176 // Link the two portions of the program back to together.
177 std::string ErrorMsg;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000178 if (!DeleteInputs) M1 = CloneModule(M1);
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000179 if (LinkModules(M1, M2, &ErrorMsg)) {
180 std::cerr << BD.getToolName() << ": Error linking modules together:"
181 << ErrorMsg << "\n";
182 exit(1);
183 }
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000184 if (DeleteInputs) delete M2; // We are done with this module...
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000185
186 Module *OldProgram = BD.swapProgramIn(M1);
187
188 // Execute the program. If it does not match the expected output, we must
189 // return true.
190 bool Broken = BD.diffProgram();
191
192 // Delete the linked module & restore the original
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000193 BD.swapProgramIn(OldProgram);
Chris Lattner5313f232004-04-02 06:32:17 +0000194 delete M1;
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000195 return Broken;
196}
197
Misha Brukman8c194ea2004-04-21 18:36:43 +0000198/// TestFuncs - split functions in a Module into two groups: those that are
199/// under consideration for miscompilation vs. those that are not, and test
200/// accordingly. Each group of functions becomes a separate Module.
201///
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000202bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
Chris Lattner640f22e2003-04-24 17:02:17 +0000203 // Test to see if the function is misoptimized if we ONLY run it on the
204 // functions listed in Funcs.
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000205 std::cout << "Checking to see if the program is misoptimized when "
206 << (Funcs.size()==1 ? "this function is" : "these functions are")
207 << " run through the pass"
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000208 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000209 PrintFunctionList(Funcs);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000210 std::cout << "\n";
Chris Lattner640f22e2003-04-24 17:02:17 +0000211
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000212 // Split the module into the two halves of the program we want.
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000213 Module *ToNotOptimize = CloneModule(BD.getProgram());
214 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, Funcs);
Chris Lattner640f22e2003-04-24 17:02:17 +0000215
Chris Lattnerb15825b2004-04-05 21:37:38 +0000216 // Run the predicate, not that the predicate will delete both input modules.
217 return TestFn(BD, ToOptimize, ToNotOptimize);
Chris Lattner640f22e2003-04-24 17:02:17 +0000218}
219
Misha Brukman8c194ea2004-04-21 18:36:43 +0000220/// DisambiguateGlobalSymbols - Mangle symbols to guarantee uniqueness by
221/// modifying predominantly internal symbols rather than external ones.
222///
Chris Lattner36ee07f2004-04-11 23:52:35 +0000223static void DisambiguateGlobalSymbols(Module *M) {
224 // Try not to cause collisions by minimizing chances of renaming an
225 // already-external symbol, so take in external globals and functions as-is.
226 // The code should work correctly without disambiguation (assuming the same
227 // mangler is used by the two code generators), but having symbols with the
228 // same name causes warnings to be emitted by the code generator.
229 Mangler Mang(*M);
230 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
231 I->setName(Mang.getValueName(I));
232 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
233 I->setName(Mang.getValueName(I));
234}
235
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000236/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
237/// check to see if we can extract the loops in the region without obscuring the
238/// bug. If so, it reduces the amount of code identified.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000239///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000240static bool ExtractLoops(BugDriver &BD,
241 bool (*TestFn)(BugDriver &, Module *, Module *),
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000242 std::vector<Function*> &MiscompiledFunctions) {
243 bool MadeChange = false;
244 while (1) {
245 Module *ToNotOptimize = CloneModule(BD.getProgram());
246 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
247 MiscompiledFunctions);
248 Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
249 if (!ToOptimizeLoopExtracted) {
250 // If the loop extractor crashed or if there were no extractible loops,
251 // then this chapter of our odyssey is over with.
252 delete ToNotOptimize;
253 delete ToOptimize;
254 return MadeChange;
255 }
256
257 std::cerr << "Extracted a loop from the breaking portion of the program.\n";
258 delete ToOptimize;
259
260 // Bugpoint is intentionally not very trusting of LLVM transformations. In
261 // particular, we're not going to assume that the loop extractor works, so
262 // we're going to test the newly loop extracted program to make sure nothing
263 // has broken. If something broke, then we'll inform the user and stop
264 // extraction.
Chris Lattnera57d86b2004-04-05 22:58:16 +0000265 AbstractInterpreter *AI = BD.switchToCBE();
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000266 if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000267 BD.switchToInterpreter(AI);
268
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000269 // Merged program doesn't work anymore!
270 std::cerr << " *** ERROR: Loop extraction broke the program. :("
271 << " Please report a bug!\n";
272 std::cerr << " Continuing on with un-loop-extracted version.\n";
273 delete ToNotOptimize;
274 delete ToOptimizeLoopExtracted;
275 return MadeChange;
276 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000277 BD.switchToInterpreter(AI);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000278
Chris Lattnerb15825b2004-04-05 21:37:38 +0000279 std::cout << " Testing after loop extraction:\n";
280 // Clone modules, the tester function will free them.
281 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
282 Module *TNOBackup = CloneModule(ToNotOptimize);
283 if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
284 std::cout << "*** Loop extraction masked the problem. Undoing.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000285 // If the program is not still broken, then loop extraction did something
286 // that masked the error. Stop loop extraction now.
Chris Lattnerb15825b2004-04-05 21:37:38 +0000287 delete TOLEBackup;
288 delete TNOBackup;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000289 return MadeChange;
290 }
Chris Lattnerb15825b2004-04-05 21:37:38 +0000291 ToOptimizeLoopExtracted = TOLEBackup;
292 ToNotOptimize = TNOBackup;
293
294 std::cout << "*** Loop extraction successful!\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000295
296 // Okay, great! Now we know that we extracted a loop and that loop
297 // extraction both didn't break the program, and didn't mask the problem.
298 // Replace the current program with the loop extracted version, and try to
299 // extract another loop.
300 std::string ErrorMsg;
301 if (LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)) {
302 std::cerr << BD.getToolName() << ": Error linking modules together:"
303 << ErrorMsg << "\n";
304 exit(1);
305 }
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000306
307 // All of the Function*'s in the MiscompiledFunctions list are in the old
Chris Lattner5313f232004-04-02 06:32:17 +0000308 // module. Update this list to include all of the functions in the
309 // optimized and loop extracted module.
310 MiscompiledFunctions.clear();
311 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
312 E = ToOptimizeLoopExtracted->end(); I != E; ++I) {
313 if (!I->isExternal()) {
Chris Lattner02bb4812004-04-02 06:32:45 +0000314 Function *NewF = ToNotOptimize->getFunction(I->getName(),
315 I->getFunctionType());
Chris Lattner5313f232004-04-02 06:32:17 +0000316 assert(NewF && "Function not found??");
317 MiscompiledFunctions.push_back(NewF);
318 }
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000319 }
Chris Lattner5313f232004-04-02 06:32:17 +0000320 delete ToOptimizeLoopExtracted;
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000321
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000322 BD.setNewProgram(ToNotOptimize);
323 MadeChange = true;
324 }
325}
326
Chris Lattner5e783ab2004-05-11 21:54:13 +0000327namespace {
328 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
329 BugDriver &BD;
330 bool (*TestFn)(BugDriver &, Module *, Module *);
331 std::vector<Function*> FunctionsBeingTested;
332 public:
333 ReduceMiscompiledBlocks(BugDriver &bd,
334 bool (*F)(BugDriver &, Module *, Module *),
335 const std::vector<Function*> &Fns)
336 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
337
338 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
339 std::vector<BasicBlock*> &Suffix) {
340 if (!Suffix.empty() && TestFuncs(Suffix))
341 return KeepSuffix;
342 if (TestFuncs(Prefix))
343 return KeepPrefix;
344 return NoFailure;
345 }
346
347 bool TestFuncs(const std::vector<BasicBlock*> &Prefix);
348 };
349}
350
351/// TestFuncs - Extract all blocks for the miscompiled functions except for the
352/// specified blocks. If the problem still exists, return true.
353///
354bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) {
355 // Test to see if the function is misoptimized if we ONLY run it on the
356 // functions listed in Funcs.
Chris Lattner68bee932004-05-12 16:08:01 +0000357 std::cout << "Checking to see if the program is misoptimized when all ";
358 if (!BBs.empty()) {
359 std::cout << "but these " << BBs.size() << " blocks are extracted: ";
360 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
361 std::cout << BBs[i]->getName() << " ";
362 if (BBs.size() > 10) std::cout << "...";
363 } else {
364 std::cout << "blocks are extracted.";
365 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000366 std::cout << "\n";
367
368 // Split the module into the two halves of the program we want.
369 Module *ToNotOptimize = CloneModule(BD.getProgram());
370 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
371 FunctionsBeingTested);
372
373 // Try the extraction. If it doesn't work, then the block extractor crashed
374 // or something, in which case bugpoint can't chase down this possibility.
375 if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) {
376 delete ToOptimize;
377 // Run the predicate, not that the predicate will delete both input modules.
378 return TestFn(BD, New, ToNotOptimize);
379 }
380 delete ToOptimize;
381 delete ToNotOptimize;
382 return false;
383}
384
385
386/// ExtractBlocks - Given a reduced list of functions that still expose the bug,
387/// extract as many basic blocks from the region as possible without obscuring
388/// the bug.
389///
390static bool ExtractBlocks(BugDriver &BD,
391 bool (*TestFn)(BugDriver &, Module *, Module *),
392 std::vector<Function*> &MiscompiledFunctions) {
393 // Not enabled??
394 if (!EnableBlockExtraction) return false;
395
396 std::vector<BasicBlock*> Blocks;
397 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
398 for (Function::iterator I = MiscompiledFunctions[i]->begin(),
399 E = MiscompiledFunctions[i]->end(); I != E; ++I)
400 Blocks.push_back(I);
401
402 // Use the list reducer to identify blocks that can be extracted without
403 // obscuring the bug. The Blocks list will end up containing blocks that must
404 // be retained from the original program.
405 unsigned OldSize = Blocks.size();
Chris Lattner68bee932004-05-12 16:08:01 +0000406
407 // Check to see if all blocks are extractible first.
408 if (ReduceMiscompiledBlocks(BD, TestFn,
409 MiscompiledFunctions).TestFuncs(std::vector<BasicBlock*>())) {
410 Blocks.clear();
411 } else {
412 ReduceMiscompiledBlocks(BD, TestFn,MiscompiledFunctions).reduceList(Blocks);
413 if (Blocks.size() == OldSize)
414 return false;
415 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000416
Chris Lattner2290e752004-05-12 02:43:24 +0000417 Module *ProgClone = CloneModule(BD.getProgram());
418 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
419 MiscompiledFunctions);
420 Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
421 if (Extracted == 0) {
422 // Wierd, extraction should have worked.
423 std::cerr << "Nondeterministic problem extracting blocks??\n";
424 delete ProgClone;
425 delete ToExtract;
426 return false;
427 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000428
Chris Lattner2290e752004-05-12 02:43:24 +0000429 // Otherwise, block extraction succeeded. Link the two program fragments back
430 // together.
431 delete ToExtract;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000432
Chris Lattner2290e752004-05-12 02:43:24 +0000433 std::string ErrorMsg;
434 if (LinkModules(ProgClone, Extracted, &ErrorMsg)) {
435 std::cerr << BD.getToolName() << ": Error linking modules together:"
436 << ErrorMsg << "\n";
437 exit(1);
438 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000439
Chris Lattner2290e752004-05-12 02:43:24 +0000440 // Set the new program and delete the old one.
441 BD.setNewProgram(ProgClone);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000442
Chris Lattner2290e752004-05-12 02:43:24 +0000443 // Update the list of miscompiled functions.
444 MiscompiledFunctions.clear();
Chris Lattner5e783ab2004-05-11 21:54:13 +0000445
Chris Lattner2290e752004-05-12 02:43:24 +0000446 for (Module::iterator I = Extracted->begin(), E = Extracted->end(); I != E;
447 ++I)
448 if (!I->isExternal()) {
449 Function *NF = ProgClone->getFunction(I->getName(), I->getFunctionType());
450 assert(NF && "Mapped function not found!");
451 MiscompiledFunctions.push_back(NF);
452 }
453
454 delete Extracted;
455
456 return true;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000457}
458
459
Chris Lattnerb15825b2004-04-05 21:37:38 +0000460/// DebugAMiscompilation - This is a generic driver to narrow down
461/// miscompilations, either in an optimization or a code generator.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000462///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000463static std::vector<Function*>
464DebugAMiscompilation(BugDriver &BD,
465 bool (*TestFn)(BugDriver &, Module *, Module *)) {
466 // Okay, now that we have reduced the list of passes which are causing the
467 // failure, see if we can pin down which functions are being
468 // miscompiled... first build a list of all of the non-external functions in
469 // the program.
470 std::vector<Function*> MiscompiledFunctions;
471 Module *Prog = BD.getProgram();
472 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
473 if (!I->isExternal())
474 MiscompiledFunctions.push_back(I);
475
476 // Do the reduction...
477 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
478
479 std::cout << "\n*** The following function"
480 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
481 << " being miscompiled: ";
482 PrintFunctionList(MiscompiledFunctions);
483 std::cout << "\n";
484
485 // See if we can rip any loops out of the miscompiled functions and still
486 // trigger the problem.
487 if (ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
488 // Okay, we extracted some loops and the problem still appears. See if we
489 // can eliminate some of the created functions from being candidates.
490
Chris Lattner36ee07f2004-04-11 23:52:35 +0000491 // Loop extraction can introduce functions with the same name (foo_code).
492 // Make sure to disambiguate the symbols so that when the program is split
493 // apart that we can link it back together again.
494 DisambiguateGlobalSymbols(BD.getProgram());
495
Chris Lattnerb15825b2004-04-05 21:37:38 +0000496 // Do the reduction...
497 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
498
499 std::cout << "\n*** The following function"
500 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
501 << " being miscompiled: ";
502 PrintFunctionList(MiscompiledFunctions);
503 std::cout << "\n";
504 }
505
Chris Lattner5e783ab2004-05-11 21:54:13 +0000506 if (ExtractBlocks(BD, TestFn, MiscompiledFunctions)) {
507 // Okay, we extracted some blocks and the problem still appears. See if we
508 // can eliminate some of the created functions from being candidates.
509
510 // Block extraction can introduce functions with the same name (foo_code).
511 // Make sure to disambiguate the symbols so that when the program is split
512 // apart that we can link it back together again.
513 DisambiguateGlobalSymbols(BD.getProgram());
514
515 // Do the reduction...
516 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
517
518 std::cout << "\n*** The following function"
519 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
520 << " being miscompiled: ";
521 PrintFunctionList(MiscompiledFunctions);
522 std::cout << "\n";
523 }
524
Chris Lattnerb15825b2004-04-05 21:37:38 +0000525 return MiscompiledFunctions;
526}
527
Chris Lattnera57d86b2004-04-05 22:58:16 +0000528/// TestOptimizer - This is the predicate function used to check to see if the
529/// "Test" portion of the program is misoptimized. If so, return true. In any
530/// case, both module arguments are deleted.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000531///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000532static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
533 // Run the optimization passes on ToOptimize, producing a transformed version
534 // of the functions being tested.
535 std::cout << " Optimizing functions being tested: ";
536 Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
537 /*AutoDebugCrashes*/true);
538 std::cout << "done.\n";
539 delete Test;
540
541 std::cout << " Checking to see if the merged program executes correctly: ";
Chris Lattner2423db02004-04-09 22:28:33 +0000542 bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
Chris Lattnerb15825b2004-04-05 21:37:38 +0000543 std::cout << (Broken ? " nope.\n" : " yup.\n");
544 return Broken;
545}
546
547
Chris Lattner4a106452002-12-23 23:50:16 +0000548/// debugMiscompilation - This method is used when the passes selected are not
549/// crashing, but the generated output is semantically different from the
550/// input.
551///
552bool BugDriver::debugMiscompilation() {
Chris Lattner4a106452002-12-23 23:50:16 +0000553 // Make sure something was miscompiled...
Misha Brukmanbe6bf562003-07-30 20:15:56 +0000554 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
Chris Lattner4a106452002-12-23 23:50:16 +0000555 std::cerr << "*** Optimized program matches reference output! No problem "
556 << "detected...\nbugpoint can't help you with your problem!\n";
557 return false;
558 }
559
Chris Lattner640f22e2003-04-24 17:02:17 +0000560 std::cout << "\n*** Found miscompiling pass"
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000561 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
562 << getPassesString(getPassesToRun()) << "\n";
Chris Lattner640f22e2003-04-24 17:02:17 +0000563 EmitProgressBytecode("passinput");
Chris Lattner4a106452002-12-23 23:50:16 +0000564
Chris Lattnerb15825b2004-04-05 21:37:38 +0000565 std::vector<Function*> MiscompiledFunctions =
566 DebugAMiscompilation(*this, TestOptimizer);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000567
Chris Lattner640f22e2003-04-24 17:02:17 +0000568 // Output a bunch of bytecode files for the user...
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000569 std::cout << "Outputting reduced bytecode files which expose the problem:\n";
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000570 Module *ToNotOptimize = CloneModule(getProgram());
571 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
572 MiscompiledFunctions);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000573
574 std::cout << " Non-optimized portion: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000575 ToNotOptimize = swapProgramIn(ToNotOptimize);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000576 EmitProgressBytecode("tonotoptimize", true);
577 setNewProgram(ToNotOptimize); // Delete hacked module.
578
579 std::cout << " Portion that is input to optimizer: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000580 ToOptimize = swapProgramIn(ToOptimize);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000581 EmitProgressBytecode("tooptimize");
582 setNewProgram(ToOptimize); // Delete hacked module.
Chris Lattner4a106452002-12-23 23:50:16 +0000583
Chris Lattner4a106452002-12-23 23:50:16 +0000584 return false;
585}
Brian Gaeked0fde302003-11-11 22:41:34 +0000586
Chris Lattnera57d86b2004-04-05 22:58:16 +0000587/// CleanupAndPrepareModules - Get the specified modules ready for code
588/// generator testing.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000589///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000590static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
591 Module *Safe) {
592 // Clean up the modules, removing extra cruft that we don't need anymore...
593 Test = BD.performFinalCleanups(Test);
594
595 // If we are executing the JIT, we have several nasty issues to take care of.
596 if (!BD.isExecutingJIT()) return;
597
598 // First, if the main function is in the Safe module, we must add a stub to
599 // the Test module to call into it. Thus, we create a new function `main'
600 // which just calls the old one.
601 if (Function *oldMain = Safe->getNamedFunction("main"))
602 if (!oldMain->isExternal()) {
603 // Rename it
604 oldMain->setName("llvm_bugpoint_old_main");
605 // Create a NEW `main' function with same type in the test module.
606 Function *newMain = new Function(oldMain->getFunctionType(),
607 GlobalValue::ExternalLinkage,
608 "main", Test);
609 // Create an `oldmain' prototype in the test module, which will
610 // corresponds to the real main function in the same module.
611 Function *oldMainProto = new Function(oldMain->getFunctionType(),
612 GlobalValue::ExternalLinkage,
613 oldMain->getName(), Test);
614 // Set up and remember the argument list for the main function.
615 std::vector<Value*> args;
616 for (Function::aiterator I = newMain->abegin(), E = newMain->aend(),
617 OI = oldMain->abegin(); I != E; ++I, ++OI) {
618 I->setName(OI->getName()); // Copy argument names from oldMain
619 args.push_back(I);
620 }
621
622 // Call the old main function and return its result
623 BasicBlock *BB = new BasicBlock("entry", newMain);
624 CallInst *call = new CallInst(oldMainProto, args);
625 BB->getInstList().push_back(call);
626
627 // If the type of old function wasn't void, return value of call
628 new ReturnInst(oldMain->getReturnType() != Type::VoidTy ? call : 0, BB);
629 }
630
631 // The second nasty issue we must deal with in the JIT is that the Safe
632 // module cannot directly reference any functions defined in the test
633 // module. Instead, we use a JIT API call to dynamically resolve the
634 // symbol.
635
636 // Add the resolver to the Safe module.
637 // Prototype: void *getPointerToNamedFunction(const char* Name)
638 Function *resolverFunc =
639 Safe->getOrInsertFunction("getPointerToNamedFunction",
640 PointerType::get(Type::SByteTy),
641 PointerType::get(Type::SByteTy), 0);
642
643 // Use the function we just added to get addresses of functions we need.
Misha Brukmandc7fef82004-04-19 01:12:01 +0000644 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000645 if (F->isExternal() && !F->use_empty() && &*F != resolverFunc &&
646 F->getIntrinsicID() == 0 /* ignore intrinsics */) {
Misha Brukmandc7fef82004-04-19 01:12:01 +0000647 Function *TestFn = Test->getFunction(F->getName(), F->getFunctionType());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000648
649 // Don't forward functions which are external in the test module too.
650 if (TestFn && !TestFn->isExternal()) {
651 // 1. Add a string constant with its name to the global file
652 Constant *InitArray = ConstantArray::get(F->getName());
653 GlobalVariable *funcName =
654 new GlobalVariable(InitArray->getType(), true /*isConstant*/,
655 GlobalValue::InternalLinkage, InitArray,
656 F->getName() + "_name", Safe);
657
658 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
659 // sbyte* so it matches the signature of the resolver function.
660
661 // GetElementPtr *funcName, ulong 0, ulong 0
662 std::vector<Constant*> GEPargs(2,Constant::getNullValue(Type::IntTy));
663 Value *GEP =
664 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(funcName),
665 GEPargs);
666 std::vector<Value*> ResolverArgs;
667 ResolverArgs.push_back(GEP);
668
Misha Brukmande4803d2004-04-19 03:36:47 +0000669 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
670 // function that dynamically resolves the calls to F via our JIT API
671 if (F->use_begin() != F->use_end()) {
672 // Construct a new stub function that will re-route calls to F
Misha Brukmandc7fef82004-04-19 01:12:01 +0000673 const FunctionType *FuncTy = F->getFunctionType();
Misha Brukmande4803d2004-04-19 03:36:47 +0000674 Function *FuncWrapper = new Function(FuncTy,
675 GlobalValue::InternalLinkage,
Misha Brukmandc7fef82004-04-19 01:12:01 +0000676 F->getName() + "_wrapper",
677 F->getParent());
678 BasicBlock *Header = new BasicBlock("header", FuncWrapper);
679
Misha Brukmande4803d2004-04-19 03:36:47 +0000680 // Resolve the call to function F via the JIT API:
681 //
682 // call resolver(GetElementPtr...)
683 CallInst *resolve = new CallInst(resolverFunc, ResolverArgs,
684 "resolver");
685 Header->getInstList().push_back(resolve);
686 // cast the result from the resolver to correctly-typed function
687 CastInst *castResolver =
688 new CastInst(resolve, PointerType::get(F->getFunctionType()),
689 "resolverCast");
690 Header->getInstList().push_back(castResolver);
691
Misha Brukmandc7fef82004-04-19 01:12:01 +0000692 // Save the argument list
693 std::vector<Value*> Args;
694 for (Function::aiterator i = FuncWrapper->abegin(),
695 e = FuncWrapper->aend(); i != e; ++i)
696 Args.push_back(i);
697
698 // Pass on the arguments to the real function, return its result
699 if (F->getReturnType() == Type::VoidTy) {
Misha Brukmande4803d2004-04-19 03:36:47 +0000700 CallInst *Call = new CallInst(castResolver, Args);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000701 Header->getInstList().push_back(Call);
702 ReturnInst *Ret = new ReturnInst();
703 Header->getInstList().push_back(Ret);
704 } else {
Misha Brukmande4803d2004-04-19 03:36:47 +0000705 CallInst *Call = new CallInst(castResolver, Args, "redir");
Misha Brukmandc7fef82004-04-19 01:12:01 +0000706 Header->getInstList().push_back(Call);
707 ReturnInst *Ret = new ReturnInst(Call);
708 Header->getInstList().push_back(Ret);
709 }
710
Misha Brukmande4803d2004-04-19 03:36:47 +0000711 // Use the wrapper function instead of the old function
712 F->replaceAllUsesWith(FuncWrapper);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000713 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000714 }
715 }
716 }
717
718 if (verifyModule(*Test) || verifyModule(*Safe)) {
719 std::cerr << "Bugpoint has a bug, which corrupted a module!!\n";
720 abort();
721 }
722}
723
724
725
726/// TestCodeGenerator - This is the predicate function used to check to see if
727/// the "Test" portion of the program is miscompiled by the code generator under
728/// test. If so, return true. In any case, both module arguments are deleted.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000729///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000730static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
731 CleanupAndPrepareModules(BD, Test, Safe);
732
733 std::string TestModuleBC = getUniqueFilename("bugpoint.test.bc");
734 if (BD.writeProgramToFile(TestModuleBC, Test)) {
735 std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
736 exit(1);
737 }
738 delete Test;
739
740 // Make the shared library
741 std::string SafeModuleBC = getUniqueFilename("bugpoint.safe.bc");
742
743 if (BD.writeProgramToFile(SafeModuleBC, Safe)) {
744 std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
745 exit(1);
746 }
747 std::string SharedObject = BD.compileSharedObject(SafeModuleBC);
748 delete Safe;
749
750 // Run the code generator on the `Test' code, loading the shared library.
751 // The function returns whether or not the new output differs from reference.
752 int Result = BD.diffProgram(TestModuleBC, SharedObject, false);
753
754 if (Result)
755 std::cerr << ": still failing!\n";
756 else
757 std::cerr << ": didn't fail.\n";
758 removeFile(TestModuleBC);
759 removeFile(SafeModuleBC);
760 removeFile(SharedObject);
761
762 return Result;
763}
764
765
Misha Brukman8c194ea2004-04-21 18:36:43 +0000766/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
767///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000768bool BugDriver::debugCodeGenerator() {
769 if ((void*)cbe == (void*)Interpreter) {
770 std::string Result = executeProgramWithCBE("bugpoint.cbe.out");
771 std::cout << "\n*** The C backend cannot match the reference diff, but it "
772 << "is used as the 'known good'\n code generator, so I can't"
773 << " debug it. Perhaps you have a front-end problem?\n As a"
774 << " sanity check, I left the result of executing the program "
775 << "with the C backend\n in this file for you: '"
776 << Result << "'.\n";
777 return true;
778 }
779
780 DisambiguateGlobalSymbols(Program);
781
782 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
783
784 // Split the module into the two halves of the program we want.
785 Module *ToNotCodeGen = CloneModule(getProgram());
786 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs);
787
788 // Condition the modules
789 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
790
791 std::string TestModuleBC = getUniqueFilename("bugpoint.test.bc");
792 if (writeProgramToFile(TestModuleBC, ToCodeGen)) {
793 std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
794 exit(1);
795 }
796 delete ToCodeGen;
797
798 // Make the shared library
799 std::string SafeModuleBC = getUniqueFilename("bugpoint.safe.bc");
800 if (writeProgramToFile(SafeModuleBC, ToNotCodeGen)) {
801 std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
802 exit(1);
803 }
804 std::string SharedObject = compileSharedObject(SafeModuleBC);
805 delete ToNotCodeGen;
806
807 std::cout << "You can reproduce the problem with the command line: \n";
808 if (isExecutingJIT()) {
809 std::cout << " lli -load " << SharedObject << " " << TestModuleBC;
810 } else {
811 std::cout << " llc " << TestModuleBC << " -o " << TestModuleBC << ".s\n";
812 std::cout << " gcc " << SharedObject << " " << TestModuleBC
813 << ".s -o " << TestModuleBC << ".exe -Wl,-R.\n";
814 std::cout << " " << TestModuleBC << ".exe";
815 }
816 for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
817 std::cout << " " << InputArgv[i];
818 std::cout << "\n";
819 std::cout << "The shared object was created with:\n llc -march=c "
820 << SafeModuleBC << " -o temporary.c\n"
821 << " gcc -xc temporary.c -O2 -o " << SharedObject
822#if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
823 << " -G" // Compile a shared library, `-G' for Sparc
824#else
825 << " -shared" // `-shared' for Linux/X86, maybe others
826#endif
827 << " -fno-strict-aliasing\n";
828
829 return false;
830}