blob: 5d60bf22452fca0cb03c7c3af0e82560597fcdb2 [file] [log] [blame]
Misha Brukman50733362003-07-24 18:17:43 +00001//===- CodeGeneratorBug.cpp - Debug code generation bugs ------------------===//
2//
3// This file implements program code generation debugging support.
4//
5//===----------------------------------------------------------------------===//
6
7#include "BugDriver.h"
8#include "SystemUtils.h"
9#include "ListReducer.h"
Misha Brukman91eabc12003-07-28 19:16:14 +000010#include "llvm/Constants.h"
11#include "llvm/DerivedTypes.h"
12#include "llvm/GlobalValue.h"
13#include "llvm/iMemory.h"
14#include "llvm/iTerminators.h"
15#include "llvm/iOther.h"
Misha Brukman50733362003-07-24 18:17:43 +000016#include "llvm/Module.h"
Misha Brukman91eabc12003-07-28 19:16:14 +000017#include "llvm/Pass.h"
18#include "llvm/Analysis/Verifier.h"
Misha Brukmanc1e39ee2003-07-28 21:07:39 +000019#include "llvm/Support/Mangler.h"
Misha Brukman91eabc12003-07-28 19:16:14 +000020#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Misha Brukman50733362003-07-24 18:17:43 +000021#include "llvm/Transforms/Utils/Cloning.h"
22#include "llvm/Transforms/Utils/Linker.h"
Misha Brukman50733362003-07-24 18:17:43 +000023#include "Support/Statistic.h"
24#include "Support/StringExtras.h"
25#include <algorithm>
26#include <set>
27
Misha Brukman50733362003-07-24 18:17:43 +000028class ReduceMisCodegenFunctions : public ListReducer<Function*> {
29 BugDriver &BD;
30public:
31 ReduceMisCodegenFunctions(BugDriver &bd) : BD(bd) {}
32
33 virtual TestResult doTest(std::vector<Function*> &Prefix,
34 std::vector<Function*> &Suffix) {
35 if (!Prefix.empty() && TestFuncs(Prefix))
36 return KeepPrefix;
37 if (!Suffix.empty() && TestFuncs(Suffix))
38 return KeepSuffix;
39 return NoFailure;
40 }
41
Misha Brukman91eabc12003-07-28 19:16:14 +000042 bool TestFuncs(const std::vector<Function*> &CodegenTest,
43 bool KeepFiles = false);
Misha Brukman50733362003-07-24 18:17:43 +000044
45 void DisambiguateGlobalSymbols(Module *M);
46};
47
48
Misha Brukman91eabc12003-07-28 19:16:14 +000049bool ReduceMisCodegenFunctions::TestFuncs(const std::vector<Function*> &Funcs,
50 bool KeepFiles)
Misha Brukman50733362003-07-24 18:17:43 +000051{
Misha Brukman91eabc12003-07-28 19:16:14 +000052 DEBUG(std::cerr << "Test functions are:\n");
53 for (std::vector<Function*>::const_iterator I = Funcs.begin(),E = Funcs.end();
54 I != E; ++I)
55 DEBUG(std::cerr << "\t" << (*I)->getName() << "\n");
56
Misha Brukman50733362003-07-24 18:17:43 +000057 // Clone the module for the two halves of the program we want.
58 Module *SafeModule = CloneModule(BD.Program);
59
60 // Make sure functions & globals are all external so that linkage
61 // between the two modules will work.
62 for (Module::iterator I = SafeModule->begin(), E = SafeModule->end();I!=E;++I)
63 I->setLinkage(GlobalValue::ExternalLinkage);
64 for (Module::giterator I=SafeModule->gbegin(),E = SafeModule->gend();I!=E;++I)
65 I->setLinkage(GlobalValue::ExternalLinkage);
66
67 DisambiguateGlobalSymbols(SafeModule);
68 Module *TestModule = CloneModule(SafeModule);
69
70 // Make sure global initializers exist only in the safe module (CBE->.so)
71 for (Module::giterator I=TestModule->gbegin(),E = TestModule->gend();I!=E;++I)
72 I->setInitializer(0); // Delete the initializer to make it external
73
Misha Brukmana259c9b2003-07-24 21:59:10 +000074 // Remove the Test functions from the Safe module
Misha Brukman50733362003-07-24 18:17:43 +000075 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
76 Function *TNOF = SafeModule->getFunction(Funcs[i]->getName(),
77 Funcs[i]->getFunctionType());
78 assert(TNOF && "Function doesn't exist in module!");
79 DeleteFunctionBody(TNOF); // Function is now external in this module!
80 }
81
Misha Brukman91eabc12003-07-28 19:16:14 +000082 // Remove the Safe functions from the Test module
83 for (Module::iterator I=TestModule->begin(),E=TestModule->end(); I!=E; ++I) {
84 bool funcFound = false;
85 for (std::vector<Function*>::const_iterator F=Funcs.begin(),Fe=Funcs.end();
86 F != Fe; ++F)
87 if (I->getName() == (*F)->getName()) funcFound = true;
88
89 if (!funcFound && !(BD.isExecutingJIT() && I->getName() == "main"))
90 DeleteFunctionBody(I);
91 }
92
93 // This is only applicable if we are debugging the JIT:
94 // Find all external functions in the Safe modules that are actually used
95 // (called or taken address of), and make them call the JIT wrapper instead
96 if (BD.isExecutingJIT()) {
97 // Must delete `main' from Safe module if it has it
Misha Brukmanc1e39ee2003-07-28 21:07:39 +000098 Function *safeMain = SafeModule->getNamedFunction("main");
99 DeleteFunctionBody(safeMain);
Misha Brukman91eabc12003-07-28 19:16:14 +0000100
101 // Add an external function "getPointerToNamedFunction" that JIT provides
102 // Prototype: void *getPointerToNamedFunction(const char* Name)
103 std::vector<const Type*> Params;
104 Params.push_back(PointerType::get(Type::SByteTy)); // std::string&
105 FunctionType *resolverTy = FunctionType::get(PointerType::get(Type::VoidTy),
106 Params, false /* isVarArg */);
Misha Brukman91eabc12003-07-28 19:16:14 +0000107 Function *resolverFunc = new Function(resolverTy,
108 GlobalValue::ExternalLinkage,
Misha Brukmanc1e39ee2003-07-28 21:07:39 +0000109 "getPointerToNamedFunction",
Misha Brukman91eabc12003-07-28 19:16:14 +0000110 SafeModule);
111
112 // Use the function we just added to get addresses of functions we need
113 // Iterate over the global declarations in the Safe module
114 for (Module::iterator F=SafeModule->begin(),E=SafeModule->end(); F!=E; ++F){
Misha Brukmanc1e39ee2003-07-28 21:07:39 +0000115 if (F->isExternal() && !F->use_empty() && &(*F) != resolverFunc) {
Misha Brukman91eabc12003-07-28 19:16:14 +0000116 // If it has a non-zero use list,
117 // 1. Add a string constant with its name to the global file
118 // The correct type is `const [ NUM x sbyte ]' where NUM is length of
119 // function name + 1
120 const std::string &Name = F->getName();
121 GlobalVariable *funcName =
122 new GlobalVariable(ArrayType::get(Type::SByteTy, Name.length()+1),
123 true /* isConstant */,
124 GlobalValue::InternalLinkage,
125 ConstantArray::get(Name),
126 Name + "_name",
127 SafeModule);
128
129 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
130 // sbyte* so it matches the signature of the resolver function.
Misha Brukmanc1e39ee2003-07-28 21:07:39 +0000131 std::vector<Constant*> GEPargs(2, Constant::getNullValue(Type::LongTy));
Misha Brukman91eabc12003-07-28 19:16:14 +0000132
133 // 3. Replace all uses of `func' with calls to resolver by:
134 // (a) Iterating through the list of uses of this function
135 // (b) Insert a cast instruction in front of each use
136 // (c) Replace use of old call with new call
137
Misha Brukmanc1e39ee2003-07-28 21:07:39 +0000138 // GetElementPtr *funcName, ulong 0, ulong 0
139 Value *GEP =
140 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(funcName),
141 GEPargs);
142 std::vector<Value*> ResolverArgs;
143 ResolverArgs.push_back(GEP);
Misha Brukman91eabc12003-07-28 19:16:14 +0000144
Misha Brukmanc1e39ee2003-07-28 21:07:39 +0000145 // Insert code at the beginning of the function
Misha Brukman91eabc12003-07-28 19:16:14 +0000146 for (Value::use_iterator i=F->use_begin(), e=F->use_end(); i!=e; ++i) {
147 if (Instruction* Inst = dyn_cast<Instruction>(*i)) {
Misha Brukman91eabc12003-07-28 19:16:14 +0000148 // call resolver(GetElementPtr...)
149 CallInst *resolve = new CallInst(resolverFunc, ResolverArgs,
150 "resolver", Inst);
151 // cast the result from the resolver to correctly-typed function
152 CastInst *castResolver =
153 new CastInst(resolve, PointerType::get(F->getFunctionType()),
154 "", Inst);
155 // actually use the resolved function
156 Inst->replaceUsesOfWith(F, castResolver);
Misha Brukmanc1e39ee2003-07-28 21:07:39 +0000157 } else {
158 // FIXME: need to take care of cases where a function is used that
159 // is not an instruction, e.g. global variable initializer...
160 std::cerr << "Non-instruction is using an external function!\n";
161 abort();
Misha Brukman91eabc12003-07-28 19:16:14 +0000162 }
163 }
164 }
165 }
166 }
167
Misha Brukmanc1e39ee2003-07-28 21:07:39 +0000168 DEBUG(std::cerr << "Safe module:\n";
169 typedef Module::iterator MI;
170 typedef Module::giterator MGI;
Misha Brukman91eabc12003-07-28 19:16:14 +0000171
Misha Brukmanc1e39ee2003-07-28 21:07:39 +0000172 for (MI I = SafeModule->begin(), E = SafeModule->end(); I != E; ++I)
173 if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
174 for (MGI I = SafeModule->gbegin(), E = SafeModule->gend(); I!=E; ++I)
175 if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
176
177 std::cerr << "Test module:\n";
178 for (MI I = TestModule->begin(), E = TestModule->end(); I != E; ++I)
179 if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
180 for (MGI I=TestModule->gbegin(),E = TestModule->gend(); I!= E; ++I)
181 if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
182 );
Misha Brukman91eabc12003-07-28 19:16:14 +0000183
Misha Brukman50733362003-07-24 18:17:43 +0000184 // Write out the bytecode to be sent to CBE
Misha Brukman91eabc12003-07-28 19:16:14 +0000185 std::string SafeModuleBC = getUniqueFilename("bugpoint.safe.bc");
186 if (verifyModule(*SafeModule)) {
187 std::cerr << "Bytecode file corrupted!\n";
188 exit(1);
189 }
Misha Brukman50733362003-07-24 18:17:43 +0000190 if (BD.writeProgramToFile(SafeModuleBC, SafeModule)) {
191 std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
192 exit(1);
193 }
194
195 // Make a shared library
196 std::string SharedObject;
197 BD.compileSharedObject(SafeModuleBC, SharedObject);
198
199 // Remove all functions from the Test module EXCEPT for the ones specified in
200 // Funcs. We know which ones these are because they are non-external in
201 // ToOptimize, but external in ToNotOptimize.
202 //
203 for (Module::iterator I = TestModule->begin(), E = TestModule->end();I!=E;++I)
204 if (!I->isExternal()) {
205 Function *TNOF = SafeModule->getFunction(I->getName(),
206 I->getFunctionType());
207 assert(TNOF && "Function doesn't exist in ToNotOptimize module??");
208 if (!TNOF->isExternal())
209 DeleteFunctionBody(I);
210 }
211
Misha Brukman91eabc12003-07-28 19:16:14 +0000212 std::string TestModuleBC = getUniqueFilename("bugpoint.test.bc");
213 if (verifyModule(*TestModule)) {
214 std::cerr << "Bytecode file corrupted!\n";
215 exit(1);
216 }
Misha Brukman50733362003-07-24 18:17:43 +0000217 if (BD.writeProgramToFile(TestModuleBC, TestModule)) {
218 std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
219 exit(1);
220 }
221
Misha Brukman91eabc12003-07-28 19:16:14 +0000222 delete SafeModule;
223 delete TestModule;
224
Misha Brukman50733362003-07-24 18:17:43 +0000225 // Run the code generator on the `Test' code, loading the shared library.
226 // The function returns whether or not the new output differs from reference.
Misha Brukmana259c9b2003-07-24 21:59:10 +0000227 int Result = BD.diffProgram(TestModuleBC, SharedObject, false);
Misha Brukman91eabc12003-07-28 19:16:14 +0000228 if (KeepFiles) {
229 std::cout << "You can reproduce the problem with the command line: \n"
Misha Brukmanc1e39ee2003-07-28 21:07:39 +0000230 << (BD.isExecutingJIT() ? "lli" : "llc")
231 << " -load " << SharedObject << " " << TestModuleBC
Misha Brukman91eabc12003-07-28 19:16:14 +0000232 << "\n";
233 } else {
234 removeFile(TestModuleBC);
235 removeFile(SafeModuleBC);
236 removeFile(SharedObject);
237 }
Misha Brukmana259c9b2003-07-24 21:59:10 +0000238 return Result;
Misha Brukman50733362003-07-24 18:17:43 +0000239}
240
241namespace {
Misha Brukmana259c9b2003-07-24 21:59:10 +0000242 struct Disambiguator {
Misha Brukman91eabc12003-07-28 19:16:14 +0000243 std::set<std::string> SymbolNames;
244 std::set<GlobalValue*> Symbols;
Misha Brukman50733362003-07-24 18:17:43 +0000245 uint64_t uniqueCounter;
246 bool externalOnly;
Misha Brukmana259c9b2003-07-24 21:59:10 +0000247 public:
Misha Brukman50733362003-07-24 18:17:43 +0000248 Disambiguator() : uniqueCounter(0), externalOnly(true) {}
249 void setExternalOnly(bool value) { externalOnly = value; }
Misha Brukmana259c9b2003-07-24 21:59:10 +0000250 void add(GlobalValue &V) {
Misha Brukman91eabc12003-07-28 19:16:14 +0000251 // If we're only processing externals and this isn't external, bail
Misha Brukman50733362003-07-24 18:17:43 +0000252 if (externalOnly && !V.isExternal()) return;
Misha Brukman91eabc12003-07-28 19:16:14 +0000253 // If we're already processed this symbol, don't add it again
254 if (Symbols.count(&V) != 0) return;
Misha Brukman50733362003-07-24 18:17:43 +0000255
Misha Brukman91eabc12003-07-28 19:16:14 +0000256 std::string SymName = V.getName();
257
Misha Brukmanc1e39ee2003-07-28 21:07:39 +0000258 // Use the Mangler facility to make symbol names that will be valid in
259 // shared objects.
260 SymName = Mangler::makeNameProper(SymName);
261 V.setName(SymName);
Misha Brukman91eabc12003-07-28 19:16:14 +0000262
263 if (SymbolNames.count(SymName) == 0) {
264 DEBUG(std::cerr << "Disambiguator: adding " << SymName
Misha Brukman50733362003-07-24 18:17:43 +0000265 << ", no conflicts.\n");
Misha Brukman91eabc12003-07-28 19:16:14 +0000266 SymbolNames.insert(SymName);
Misha Brukman50733362003-07-24 18:17:43 +0000267 } else {
268 // Mangle name before adding
269 std::string newName;
270 do {
Misha Brukman91eabc12003-07-28 19:16:14 +0000271 newName = SymName + "_" + utostr(uniqueCounter);
Misha Brukman50733362003-07-24 18:17:43 +0000272 if (SymbolNames.count(newName) == 0) break;
273 else ++uniqueCounter;
274 } while (1);
275 //while (SymbolNames.count(V->getName()+utostr(uniqueCounter++))==0);
Misha Brukman91eabc12003-07-28 19:16:14 +0000276 DEBUG(std::cerr << "Disambiguator: conflict: " << SymName
Misha Brukman50733362003-07-24 18:17:43 +0000277 << ", adding: " << newName << "\n");
278 V.setName(newName);
279 SymbolNames.insert(newName);
Misha Brukman50733362003-07-24 18:17:43 +0000280 }
Misha Brukman91eabc12003-07-28 19:16:14 +0000281 Symbols.insert(&V);
Misha Brukman50733362003-07-24 18:17:43 +0000282 }
283 };
284}
285
286void ReduceMisCodegenFunctions::DisambiguateGlobalSymbols(Module *M) {
287 // First, try not to cause collisions by minimizing chances of renaming an
288 // already-external symbol, so take in external globals and functions as-is.
Misha Brukmana259c9b2003-07-24 21:59:10 +0000289 Disambiguator D;
Misha Brukman91eabc12003-07-28 19:16:14 +0000290 DEBUG(std::cerr << "Disambiguating globals (external-only)\n");
Misha Brukmana259c9b2003-07-24 21:59:10 +0000291 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) D.add(*I);
Misha Brukman91eabc12003-07-28 19:16:14 +0000292 DEBUG(std::cerr << "Disambiguating functions (external-only)\n");
Misha Brukmana259c9b2003-07-24 21:59:10 +0000293 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) D.add(*I);
Misha Brukman50733362003-07-24 18:17:43 +0000294
295 // Now just rename functions and globals as necessary, keeping what's already
296 // in the set unique.
297 D.setExternalOnly(false);
Misha Brukman91eabc12003-07-28 19:16:14 +0000298 DEBUG(std::cerr << "Disambiguating globals\n");
Misha Brukmana259c9b2003-07-24 21:59:10 +0000299 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) D.add(*I);
Misha Brukman91eabc12003-07-28 19:16:14 +0000300 DEBUG(std::cerr << "Disambiguating globals\n");
Misha Brukmana259c9b2003-07-24 21:59:10 +0000301 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) D.add(*I);
Misha Brukman50733362003-07-24 18:17:43 +0000302}
303
304
305bool BugDriver::debugCodeGenerator() {
306 // See if we can pin down which functions are being miscompiled...
307 //First, build a list of all of the non-external functions in the program.
308 std::vector<Function*> MisCodegenFunctions;
309 for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
310 if (!I->isExternal())
311 MisCodegenFunctions.push_back(I);
312
Misha Brukman91eabc12003-07-28 19:16:14 +0000313 // If we are executing the JIT, we *must* keep the function `main' in the
314 // module that is passed in, and not the shared library. However, we still
315 // want to be able to debug the `main' function alone. Thus, we create a new
316 // function `main' which just calls the old one.
317 if (isExecutingJIT()) {
318 // Get the `main' function
319 Function *oldMain = Program->getNamedFunction("main");
320 // Rename it
321 oldMain->setName("old_main");
322 // Create a NEW `main' function with same type
323 Function *newMain = new Function(oldMain->getFunctionType(),
Misha Brukmanc1e39ee2003-07-28 21:07:39 +0000324 GlobalValue::ExternalLinkage,
Misha Brukman91eabc12003-07-28 19:16:14 +0000325 "main", Program);
326 // Call the old main function and return its result
327 BasicBlock *BB = new BasicBlock("entry", newMain);
328 std::vector<Value*> args;
329 for (Function::aiterator I=newMain->abegin(), E=newMain->aend(); I!=E; ++I)
330 args.push_back(I);
331 CallInst *call = new CallInst(oldMain, args);
332 BB->getInstList().push_back(call);
333
334 // if the type of old function wasn't void, return value of call
335 ReturnInst *ret;
336 if (oldMain->getReturnType() != Type::VoidTy) {
337 ret = new ReturnInst(call);
338 } else {
339 ret = new ReturnInst();
340 }
341
342 // Add the return instruction to the BasicBlock
343 BB->getInstList().push_back(ret);
344 }
345
Misha Brukman50733362003-07-24 18:17:43 +0000346 // Do the reduction...
347 ReduceMisCodegenFunctions(*this).reduceList(MisCodegenFunctions);
348
349 std::cout << "\n*** The following functions are being miscompiled: ";
350 PrintFunctionList(MisCodegenFunctions);
351 std::cout << "\n";
352
353 // Output a bunch of bytecode files for the user...
Misha Brukman91eabc12003-07-28 19:16:14 +0000354 ReduceMisCodegenFunctions(*this).TestFuncs(MisCodegenFunctions, true);
Misha Brukman50733362003-07-24 18:17:43 +0000355
356 return false;
357}
358