blob: fac65ac91ab678528a1ad816ac7a6a0301b5f431 [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;
32}
33
Chris Lattnerefdc0b52004-03-14 20:50:42 +000034namespace {
Chris Lattnerfa761832004-01-14 03:38:37 +000035 class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
36 BugDriver &BD;
37 public:
38 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
39
40 virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
41 std::vector<const PassInfo*> &Suffix);
42 };
43}
Chris Lattner640f22e2003-04-24 17:02:17 +000044
45ReduceMiscompilingPasses::TestResult
Chris Lattner39aebca2003-04-24 22:24:22 +000046ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
Chris Lattner06943ad2003-04-25 03:16:05 +000047 std::vector<const PassInfo*> &Suffix) {
48 // First, run the program with just the Suffix passes. If it is still broken
Chris Lattner640f22e2003-04-24 17:02:17 +000049 // with JUST the kept passes, discard the prefix passes.
Chris Lattner06943ad2003-04-25 03:16:05 +000050 std::cout << "Checking to see if '" << getPassesString(Suffix)
Chris Lattner640f22e2003-04-24 17:02:17 +000051 << "' compile correctly: ";
52
53 std::string BytecodeResult;
Chris Lattner06943ad2003-04-25 03:16:05 +000054 if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
Chris Lattner9f71e792003-10-18 00:05:05 +000055 std::cerr << " Error running this sequence of passes"
Chris Lattner640f22e2003-04-24 17:02:17 +000056 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +000057 BD.setPassesToRun(Suffix);
58 BD.EmitProgressBytecode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +000059 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +000060 }
61
62 // Check to see if the finished program matches the reference output...
Misha Brukman50733362003-07-24 18:17:43 +000063 if (BD.diffProgram(BytecodeResult, "", true /*delete bytecode*/)) {
Chris Lattner640f22e2003-04-24 17:02:17 +000064 std::cout << "nope.\n";
65 return KeepSuffix; // Miscompilation detected!
66 }
67 std::cout << "yup.\n"; // No miscompilation!
68
69 if (Prefix.empty()) return NoFailure;
70
Chris Lattner06943ad2003-04-25 03:16:05 +000071 // Next, see if the program is broken if we run the "prefix" passes first,
Misha Brukmanbc0e9982003-07-14 17:20:40 +000072 // then separately run the "kept" passes.
Chris Lattner640f22e2003-04-24 17:02:17 +000073 std::cout << "Checking to see if '" << getPassesString(Prefix)
74 << "' compile correctly: ";
75
76 // If it is not broken with the kept passes, it's possible that the prefix
77 // passes must be run before the kept passes to break it. If the program
78 // WORKS after the prefix passes, but then fails if running the prefix AND
79 // kept passes, we can update our bytecode file to include the result of the
80 // prefix passes, then discard the prefix passes.
81 //
82 if (BD.runPasses(Prefix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
Chris Lattner9f71e792003-10-18 00:05:05 +000083 std::cerr << " Error running this sequence of passes"
Chris Lattner640f22e2003-04-24 17:02:17 +000084 << " on the input program!\n";
Chris Lattner9c6cfe12003-10-17 23:03:16 +000085 BD.setPassesToRun(Prefix);
86 BD.EmitProgressBytecode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +000087 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +000088 }
89
90 // If the prefix maintains the predicate by itself, only keep the prefix!
Misha Brukman50733362003-07-24 18:17:43 +000091 if (BD.diffProgram(BytecodeResult)) {
Chris Lattner640f22e2003-04-24 17:02:17 +000092 std::cout << "nope.\n";
93 removeFile(BytecodeResult);
94 return KeepPrefix;
95 }
96 std::cout << "yup.\n"; // No miscompilation!
97
98 // Ok, so now we know that the prefix passes work, try running the suffix
99 // passes on the result of the prefix passes.
100 //
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000101 Module *PrefixOutput = ParseInputFile(BytecodeResult);
Chris Lattner640f22e2003-04-24 17:02:17 +0000102 if (PrefixOutput == 0) {
103 std::cerr << BD.getToolName() << ": Error reading bytecode file '"
104 << BytecodeResult << "'!\n";
105 exit(1);
106 }
107 removeFile(BytecodeResult); // No longer need the file on disk
108
Chris Lattner06943ad2003-04-25 03:16:05 +0000109 std::cout << "Checking to see if '" << getPassesString(Suffix)
Chris Lattner640f22e2003-04-24 17:02:17 +0000110 << "' passes compile correctly after the '"
111 << getPassesString(Prefix) << "' passes: ";
112
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000113 Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
Chris Lattner06943ad2003-04-25 03:16:05 +0000114 if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
Chris Lattner9f71e792003-10-18 00:05:05 +0000115 std::cerr << " Error running this sequence of passes"
Chris Lattner640f22e2003-04-24 17:02:17 +0000116 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +0000117 BD.setPassesToRun(Suffix);
Chris Lattner9c6cfe12003-10-17 23:03:16 +0000118 BD.EmitProgressBytecode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +0000119 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +0000120 }
121
122 // Run the result...
Misha Brukman50733362003-07-24 18:17:43 +0000123 if (BD.diffProgram(BytecodeResult, "", true/*delete bytecode*/)) {
Chris Lattner640f22e2003-04-24 17:02:17 +0000124 std::cout << "nope.\n";
125 delete OriginalInput; // We pruned down the original input...
Chris Lattner06943ad2003-04-25 03:16:05 +0000126 return KeepSuffix;
Chris Lattner640f22e2003-04-24 17:02:17 +0000127 }
128
129 // Otherwise, we must not be running the bad pass anymore.
130 std::cout << "yup.\n"; // No miscompilation!
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000131 delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test
Chris Lattner640f22e2003-04-24 17:02:17 +0000132 return NoFailure;
133}
134
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000135namespace {
Chris Lattnerfa761832004-01-14 03:38:37 +0000136 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
137 BugDriver &BD;
Chris Lattnerb15825b2004-04-05 21:37:38 +0000138 bool (*TestFn)(BugDriver &, Module *, Module *);
Chris Lattnerfa761832004-01-14 03:38:37 +0000139 public:
Chris Lattnerb15825b2004-04-05 21:37:38 +0000140 ReduceMiscompilingFunctions(BugDriver &bd,
141 bool (*F)(BugDriver &, Module *, Module *))
142 : BD(bd), TestFn(F) {}
Chris Lattnerfa761832004-01-14 03:38:37 +0000143
144 virtual TestResult doTest(std::vector<Function*> &Prefix,
145 std::vector<Function*> &Suffix) {
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000146 if (!Suffix.empty() && TestFuncs(Suffix))
Chris Lattnerfa761832004-01-14 03:38:37 +0000147 return KeepSuffix;
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000148 if (!Prefix.empty() && TestFuncs(Prefix))
Chris Lattnerfa761832004-01-14 03:38:37 +0000149 return KeepPrefix;
150 return NoFailure;
151 }
152
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000153 bool TestFuncs(const std::vector<Function*> &Prefix);
Chris Lattnerfa761832004-01-14 03:38:37 +0000154 };
155}
Chris Lattner640f22e2003-04-24 17:02:17 +0000156
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000157/// TestMergedProgram - Given two modules, link them together and run the
158/// program, checking to see if the program matches the diff. If the diff
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000159/// matches, return false, otherwise return true. If the DeleteInputs argument
160/// is set to true then this function deletes both input modules before it
161/// returns.
162static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
163 bool DeleteInputs) {
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000164 // Link the two portions of the program back to together.
165 std::string ErrorMsg;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000166 if (!DeleteInputs) M1 = CloneModule(M1);
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000167 if (LinkModules(M1, M2, &ErrorMsg)) {
168 std::cerr << BD.getToolName() << ": Error linking modules together:"
169 << ErrorMsg << "\n";
170 exit(1);
171 }
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000172 if (DeleteInputs) delete M2; // We are done with this module...
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000173
174 Module *OldProgram = BD.swapProgramIn(M1);
175
176 // Execute the program. If it does not match the expected output, we must
177 // return true.
178 bool Broken = BD.diffProgram();
179
180 // Delete the linked module & restore the original
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000181 BD.swapProgramIn(OldProgram);
Chris Lattner5313f232004-04-02 06:32:17 +0000182 delete M1;
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000183 return Broken;
184}
185
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000186bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
Chris Lattner640f22e2003-04-24 17:02:17 +0000187 // Test to see if the function is misoptimized if we ONLY run it on the
188 // functions listed in Funcs.
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000189 std::cout << "Checking to see if the program is misoptimized when "
190 << (Funcs.size()==1 ? "this function is" : "these functions are")
191 << " run through the pass"
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000192 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000193 PrintFunctionList(Funcs);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000194 std::cout << "\n";
Chris Lattner640f22e2003-04-24 17:02:17 +0000195
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000196 // Split the module into the two halves of the program we want.
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000197 Module *ToNotOptimize = CloneModule(BD.getProgram());
198 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, Funcs);
Chris Lattner640f22e2003-04-24 17:02:17 +0000199
Chris Lattnerb15825b2004-04-05 21:37:38 +0000200 // Run the predicate, not that the predicate will delete both input modules.
201 return TestFn(BD, ToOptimize, ToNotOptimize);
Chris Lattner640f22e2003-04-24 17:02:17 +0000202}
203
Chris Lattner36ee07f2004-04-11 23:52:35 +0000204static void DisambiguateGlobalSymbols(Module *M) {
205 // Try not to cause collisions by minimizing chances of renaming an
206 // already-external symbol, so take in external globals and functions as-is.
207 // The code should work correctly without disambiguation (assuming the same
208 // mangler is used by the two code generators), but having symbols with the
209 // same name causes warnings to be emitted by the code generator.
210 Mangler Mang(*M);
211 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
212 I->setName(Mang.getValueName(I));
213 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
214 I->setName(Mang.getValueName(I));
215}
216
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000217/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
218/// check to see if we can extract the loops in the region without obscuring the
219/// bug. If so, it reduces the amount of code identified.
Chris Lattnerb15825b2004-04-05 21:37:38 +0000220static bool ExtractLoops(BugDriver &BD,
221 bool (*TestFn)(BugDriver &, Module *, Module *),
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000222 std::vector<Function*> &MiscompiledFunctions) {
223 bool MadeChange = false;
224 while (1) {
225 Module *ToNotOptimize = CloneModule(BD.getProgram());
226 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
227 MiscompiledFunctions);
228 Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
229 if (!ToOptimizeLoopExtracted) {
230 // If the loop extractor crashed or if there were no extractible loops,
231 // then this chapter of our odyssey is over with.
232 delete ToNotOptimize;
233 delete ToOptimize;
234 return MadeChange;
235 }
236
237 std::cerr << "Extracted a loop from the breaking portion of the program.\n";
238 delete ToOptimize;
239
240 // Bugpoint is intentionally not very trusting of LLVM transformations. In
241 // particular, we're not going to assume that the loop extractor works, so
242 // we're going to test the newly loop extracted program to make sure nothing
243 // has broken. If something broke, then we'll inform the user and stop
244 // extraction.
Chris Lattnera57d86b2004-04-05 22:58:16 +0000245 AbstractInterpreter *AI = BD.switchToCBE();
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000246 if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000247 BD.switchToInterpreter(AI);
248
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000249 // Merged program doesn't work anymore!
250 std::cerr << " *** ERROR: Loop extraction broke the program. :("
251 << " Please report a bug!\n";
252 std::cerr << " Continuing on with un-loop-extracted version.\n";
253 delete ToNotOptimize;
254 delete ToOptimizeLoopExtracted;
255 return MadeChange;
256 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000257 BD.switchToInterpreter(AI);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000258
Chris Lattnerb15825b2004-04-05 21:37:38 +0000259 std::cout << " Testing after loop extraction:\n";
260 // Clone modules, the tester function will free them.
261 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
262 Module *TNOBackup = CloneModule(ToNotOptimize);
263 if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
264 std::cout << "*** Loop extraction masked the problem. Undoing.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000265 // If the program is not still broken, then loop extraction did something
266 // that masked the error. Stop loop extraction now.
Chris Lattnerb15825b2004-04-05 21:37:38 +0000267 delete TOLEBackup;
268 delete TNOBackup;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000269 return MadeChange;
270 }
Chris Lattnerb15825b2004-04-05 21:37:38 +0000271 ToOptimizeLoopExtracted = TOLEBackup;
272 ToNotOptimize = TNOBackup;
273
274 std::cout << "*** Loop extraction successful!\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000275
276 // Okay, great! Now we know that we extracted a loop and that loop
277 // extraction both didn't break the program, and didn't mask the problem.
278 // Replace the current program with the loop extracted version, and try to
279 // extract another loop.
280 std::string ErrorMsg;
281 if (LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)) {
282 std::cerr << BD.getToolName() << ": Error linking modules together:"
283 << ErrorMsg << "\n";
284 exit(1);
285 }
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000286
287 // All of the Function*'s in the MiscompiledFunctions list are in the old
Chris Lattner5313f232004-04-02 06:32:17 +0000288 // module. Update this list to include all of the functions in the
289 // optimized and loop extracted module.
290 MiscompiledFunctions.clear();
291 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
292 E = ToOptimizeLoopExtracted->end(); I != E; ++I) {
293 if (!I->isExternal()) {
Chris Lattner02bb4812004-04-02 06:32:45 +0000294 Function *NewF = ToNotOptimize->getFunction(I->getName(),
295 I->getFunctionType());
Chris Lattner5313f232004-04-02 06:32:17 +0000296 assert(NewF && "Function not found??");
297 MiscompiledFunctions.push_back(NewF);
298 }
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000299 }
Chris Lattner5313f232004-04-02 06:32:17 +0000300 delete ToOptimizeLoopExtracted;
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000301
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000302 BD.setNewProgram(ToNotOptimize);
303 MadeChange = true;
304 }
305}
306
Chris Lattnerb15825b2004-04-05 21:37:38 +0000307/// DebugAMiscompilation - This is a generic driver to narrow down
308/// miscompilations, either in an optimization or a code generator.
309static std::vector<Function*>
310DebugAMiscompilation(BugDriver &BD,
311 bool (*TestFn)(BugDriver &, Module *, Module *)) {
312 // Okay, now that we have reduced the list of passes which are causing the
313 // failure, see if we can pin down which functions are being
314 // miscompiled... first build a list of all of the non-external functions in
315 // the program.
316 std::vector<Function*> MiscompiledFunctions;
317 Module *Prog = BD.getProgram();
318 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
319 if (!I->isExternal())
320 MiscompiledFunctions.push_back(I);
321
322 // Do the reduction...
323 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
324
325 std::cout << "\n*** The following function"
326 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
327 << " being miscompiled: ";
328 PrintFunctionList(MiscompiledFunctions);
329 std::cout << "\n";
330
331 // See if we can rip any loops out of the miscompiled functions and still
332 // trigger the problem.
333 if (ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
334 // Okay, we extracted some loops and the problem still appears. See if we
335 // can eliminate some of the created functions from being candidates.
336
Chris Lattner36ee07f2004-04-11 23:52:35 +0000337 // Loop extraction can introduce functions with the same name (foo_code).
338 // Make sure to disambiguate the symbols so that when the program is split
339 // apart that we can link it back together again.
340 DisambiguateGlobalSymbols(BD.getProgram());
341
Chris Lattnerb15825b2004-04-05 21:37:38 +0000342 // Do the reduction...
343 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
344
345 std::cout << "\n*** The following function"
346 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
347 << " being miscompiled: ";
348 PrintFunctionList(MiscompiledFunctions);
349 std::cout << "\n";
350 }
351
352 return MiscompiledFunctions;
353}
354
Chris Lattnera57d86b2004-04-05 22:58:16 +0000355/// TestOptimizer - This is the predicate function used to check to see if the
356/// "Test" portion of the program is misoptimized. If so, return true. In any
357/// case, both module arguments are deleted.
Chris Lattnerb15825b2004-04-05 21:37:38 +0000358static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
359 // Run the optimization passes on ToOptimize, producing a transformed version
360 // of the functions being tested.
361 std::cout << " Optimizing functions being tested: ";
362 Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
363 /*AutoDebugCrashes*/true);
364 std::cout << "done.\n";
365 delete Test;
366
367 std::cout << " Checking to see if the merged program executes correctly: ";
Chris Lattner2423db02004-04-09 22:28:33 +0000368 bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
Chris Lattnerb15825b2004-04-05 21:37:38 +0000369 std::cout << (Broken ? " nope.\n" : " yup.\n");
370 return Broken;
371}
372
373
Chris Lattner4a106452002-12-23 23:50:16 +0000374/// debugMiscompilation - This method is used when the passes selected are not
375/// crashing, but the generated output is semantically different from the
376/// input.
377///
378bool BugDriver::debugMiscompilation() {
Chris Lattner4a106452002-12-23 23:50:16 +0000379 // Make sure something was miscompiled...
Misha Brukmanbe6bf562003-07-30 20:15:56 +0000380 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
Chris Lattner4a106452002-12-23 23:50:16 +0000381 std::cerr << "*** Optimized program matches reference output! No problem "
382 << "detected...\nbugpoint can't help you with your problem!\n";
383 return false;
384 }
385
Chris Lattner640f22e2003-04-24 17:02:17 +0000386 std::cout << "\n*** Found miscompiling pass"
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000387 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
388 << getPassesString(getPassesToRun()) << "\n";
Chris Lattner640f22e2003-04-24 17:02:17 +0000389 EmitProgressBytecode("passinput");
Chris Lattner4a106452002-12-23 23:50:16 +0000390
Chris Lattnerb15825b2004-04-05 21:37:38 +0000391 std::vector<Function*> MiscompiledFunctions =
392 DebugAMiscompilation(*this, TestOptimizer);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000393
Chris Lattner640f22e2003-04-24 17:02:17 +0000394 // Output a bunch of bytecode files for the user...
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000395 std::cout << "Outputting reduced bytecode files which expose the problem:\n";
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000396 Module *ToNotOptimize = CloneModule(getProgram());
397 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
398 MiscompiledFunctions);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000399
400 std::cout << " Non-optimized portion: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000401 ToNotOptimize = swapProgramIn(ToNotOptimize);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000402 EmitProgressBytecode("tonotoptimize", true);
403 setNewProgram(ToNotOptimize); // Delete hacked module.
404
405 std::cout << " Portion that is input to optimizer: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000406 ToOptimize = swapProgramIn(ToOptimize);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000407 EmitProgressBytecode("tooptimize");
408 setNewProgram(ToOptimize); // Delete hacked module.
Chris Lattner4a106452002-12-23 23:50:16 +0000409
Chris Lattner4a106452002-12-23 23:50:16 +0000410 return false;
411}
Brian Gaeked0fde302003-11-11 22:41:34 +0000412
Chris Lattnera57d86b2004-04-05 22:58:16 +0000413/// CleanupAndPrepareModules - Get the specified modules ready for code
414/// generator testing.
415static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
416 Module *Safe) {
417 // Clean up the modules, removing extra cruft that we don't need anymore...
418 Test = BD.performFinalCleanups(Test);
419
420 // If we are executing the JIT, we have several nasty issues to take care of.
421 if (!BD.isExecutingJIT()) return;
422
423 // First, if the main function is in the Safe module, we must add a stub to
424 // the Test module to call into it. Thus, we create a new function `main'
425 // which just calls the old one.
426 if (Function *oldMain = Safe->getNamedFunction("main"))
427 if (!oldMain->isExternal()) {
428 // Rename it
429 oldMain->setName("llvm_bugpoint_old_main");
430 // Create a NEW `main' function with same type in the test module.
431 Function *newMain = new Function(oldMain->getFunctionType(),
432 GlobalValue::ExternalLinkage,
433 "main", Test);
434 // Create an `oldmain' prototype in the test module, which will
435 // corresponds to the real main function in the same module.
436 Function *oldMainProto = new Function(oldMain->getFunctionType(),
437 GlobalValue::ExternalLinkage,
438 oldMain->getName(), Test);
439 // Set up and remember the argument list for the main function.
440 std::vector<Value*> args;
441 for (Function::aiterator I = newMain->abegin(), E = newMain->aend(),
442 OI = oldMain->abegin(); I != E; ++I, ++OI) {
443 I->setName(OI->getName()); // Copy argument names from oldMain
444 args.push_back(I);
445 }
446
447 // Call the old main function and return its result
448 BasicBlock *BB = new BasicBlock("entry", newMain);
449 CallInst *call = new CallInst(oldMainProto, args);
450 BB->getInstList().push_back(call);
451
452 // If the type of old function wasn't void, return value of call
453 new ReturnInst(oldMain->getReturnType() != Type::VoidTy ? call : 0, BB);
454 }
455
456 // The second nasty issue we must deal with in the JIT is that the Safe
457 // module cannot directly reference any functions defined in the test
458 // module. Instead, we use a JIT API call to dynamically resolve the
459 // symbol.
460
461 // Add the resolver to the Safe module.
462 // Prototype: void *getPointerToNamedFunction(const char* Name)
463 Function *resolverFunc =
464 Safe->getOrInsertFunction("getPointerToNamedFunction",
465 PointerType::get(Type::SByteTy),
466 PointerType::get(Type::SByteTy), 0);
467
468 // Use the function we just added to get addresses of functions we need.
Misha Brukmandc7fef82004-04-19 01:12:01 +0000469 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000470 if (F->isExternal() && !F->use_empty() && &*F != resolverFunc &&
471 F->getIntrinsicID() == 0 /* ignore intrinsics */) {
Misha Brukmandc7fef82004-04-19 01:12:01 +0000472 Function *TestFn = Test->getFunction(F->getName(), F->getFunctionType());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000473
474 // Don't forward functions which are external in the test module too.
475 if (TestFn && !TestFn->isExternal()) {
476 // 1. Add a string constant with its name to the global file
477 Constant *InitArray = ConstantArray::get(F->getName());
478 GlobalVariable *funcName =
479 new GlobalVariable(InitArray->getType(), true /*isConstant*/,
480 GlobalValue::InternalLinkage, InitArray,
481 F->getName() + "_name", Safe);
482
483 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
484 // sbyte* so it matches the signature of the resolver function.
485
486 // GetElementPtr *funcName, ulong 0, ulong 0
487 std::vector<Constant*> GEPargs(2,Constant::getNullValue(Type::IntTy));
488 Value *GEP =
489 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(funcName),
490 GEPargs);
491 std::vector<Value*> ResolverArgs;
492 ResolverArgs.push_back(GEP);
493
Misha Brukmande4803d2004-04-19 03:36:47 +0000494 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
495 // function that dynamically resolves the calls to F via our JIT API
496 if (F->use_begin() != F->use_end()) {
497 // Construct a new stub function that will re-route calls to F
Misha Brukmandc7fef82004-04-19 01:12:01 +0000498 const FunctionType *FuncTy = F->getFunctionType();
Misha Brukmande4803d2004-04-19 03:36:47 +0000499 Function *FuncWrapper = new Function(FuncTy,
500 GlobalValue::InternalLinkage,
Misha Brukmandc7fef82004-04-19 01:12:01 +0000501 F->getName() + "_wrapper",
502 F->getParent());
503 BasicBlock *Header = new BasicBlock("header", FuncWrapper);
504
Misha Brukmande4803d2004-04-19 03:36:47 +0000505 // Resolve the call to function F via the JIT API:
506 //
507 // call resolver(GetElementPtr...)
508 CallInst *resolve = new CallInst(resolverFunc, ResolverArgs,
509 "resolver");
510 Header->getInstList().push_back(resolve);
511 // cast the result from the resolver to correctly-typed function
512 CastInst *castResolver =
513 new CastInst(resolve, PointerType::get(F->getFunctionType()),
514 "resolverCast");
515 Header->getInstList().push_back(castResolver);
516
Misha Brukmandc7fef82004-04-19 01:12:01 +0000517 // Save the argument list
518 std::vector<Value*> Args;
519 for (Function::aiterator i = FuncWrapper->abegin(),
520 e = FuncWrapper->aend(); i != e; ++i)
521 Args.push_back(i);
522
523 // Pass on the arguments to the real function, return its result
524 if (F->getReturnType() == Type::VoidTy) {
Misha Brukmande4803d2004-04-19 03:36:47 +0000525 CallInst *Call = new CallInst(castResolver, Args);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000526 Header->getInstList().push_back(Call);
527 ReturnInst *Ret = new ReturnInst();
528 Header->getInstList().push_back(Ret);
529 } else {
Misha Brukmande4803d2004-04-19 03:36:47 +0000530 CallInst *Call = new CallInst(castResolver, Args, "redir");
Misha Brukmandc7fef82004-04-19 01:12:01 +0000531 Header->getInstList().push_back(Call);
532 ReturnInst *Ret = new ReturnInst(Call);
533 Header->getInstList().push_back(Ret);
534 }
535
Misha Brukmande4803d2004-04-19 03:36:47 +0000536 // Use the wrapper function instead of the old function
537 F->replaceAllUsesWith(FuncWrapper);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000538 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000539 }
540 }
541 }
542
543 if (verifyModule(*Test) || verifyModule(*Safe)) {
544 std::cerr << "Bugpoint has a bug, which corrupted a module!!\n";
545 abort();
546 }
547}
548
549
550
551/// TestCodeGenerator - This is the predicate function used to check to see if
552/// the "Test" portion of the program is miscompiled by the code generator under
553/// test. If so, return true. In any case, both module arguments are deleted.
554static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
555 CleanupAndPrepareModules(BD, Test, Safe);
556
557 std::string TestModuleBC = getUniqueFilename("bugpoint.test.bc");
558 if (BD.writeProgramToFile(TestModuleBC, Test)) {
559 std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
560 exit(1);
561 }
562 delete Test;
563
564 // Make the shared library
565 std::string SafeModuleBC = getUniqueFilename("bugpoint.safe.bc");
566
567 if (BD.writeProgramToFile(SafeModuleBC, Safe)) {
568 std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
569 exit(1);
570 }
571 std::string SharedObject = BD.compileSharedObject(SafeModuleBC);
572 delete Safe;
573
574 // Run the code generator on the `Test' code, loading the shared library.
575 // The function returns whether or not the new output differs from reference.
576 int Result = BD.diffProgram(TestModuleBC, SharedObject, false);
577
578 if (Result)
579 std::cerr << ": still failing!\n";
580 else
581 std::cerr << ": didn't fail.\n";
582 removeFile(TestModuleBC);
583 removeFile(SafeModuleBC);
584 removeFile(SharedObject);
585
586 return Result;
587}
588
589
Chris Lattnera57d86b2004-04-05 22:58:16 +0000590bool BugDriver::debugCodeGenerator() {
591 if ((void*)cbe == (void*)Interpreter) {
592 std::string Result = executeProgramWithCBE("bugpoint.cbe.out");
593 std::cout << "\n*** The C backend cannot match the reference diff, but it "
594 << "is used as the 'known good'\n code generator, so I can't"
595 << " debug it. Perhaps you have a front-end problem?\n As a"
596 << " sanity check, I left the result of executing the program "
597 << "with the C backend\n in this file for you: '"
598 << Result << "'.\n";
599 return true;
600 }
601
602 DisambiguateGlobalSymbols(Program);
603
604 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
605
606 // Split the module into the two halves of the program we want.
607 Module *ToNotCodeGen = CloneModule(getProgram());
608 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs);
609
610 // Condition the modules
611 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
612
613 std::string TestModuleBC = getUniqueFilename("bugpoint.test.bc");
614 if (writeProgramToFile(TestModuleBC, ToCodeGen)) {
615 std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
616 exit(1);
617 }
618 delete ToCodeGen;
619
620 // Make the shared library
621 std::string SafeModuleBC = getUniqueFilename("bugpoint.safe.bc");
622 if (writeProgramToFile(SafeModuleBC, ToNotCodeGen)) {
623 std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
624 exit(1);
625 }
626 std::string SharedObject = compileSharedObject(SafeModuleBC);
627 delete ToNotCodeGen;
628
629 std::cout << "You can reproduce the problem with the command line: \n";
630 if (isExecutingJIT()) {
631 std::cout << " lli -load " << SharedObject << " " << TestModuleBC;
632 } else {
633 std::cout << " llc " << TestModuleBC << " -o " << TestModuleBC << ".s\n";
634 std::cout << " gcc " << SharedObject << " " << TestModuleBC
635 << ".s -o " << TestModuleBC << ".exe -Wl,-R.\n";
636 std::cout << " " << TestModuleBC << ".exe";
637 }
638 for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
639 std::cout << " " << InputArgv[i];
640 std::cout << "\n";
641 std::cout << "The shared object was created with:\n llc -march=c "
642 << SafeModuleBC << " -o temporary.c\n"
643 << " gcc -xc temporary.c -O2 -o " << SharedObject
644#if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
645 << " -G" // Compile a shared library, `-G' for Sparc
646#else
647 << " -shared" // `-shared' for Linux/X86, maybe others
648#endif
649 << " -fno-strict-aliasing\n";
650
651 return false;
652}