blob: 75a3283c9f4b47d9262b80566a7cea9135b09d75 [file] [log] [blame]
Chris Lattner5aa9e3e2002-05-24 20:42:13 +00001//===- FunctionResolution.cpp - Resolve declarations to implementations ---===//
2//
3// Loop over the functions that are in the module and look for functions that
4// have the same name. More often than not, there will be things like:
5//
6// declare void %foo(...)
7// void %foo(int, int) { ... }
8//
9// because of the way things are declared in C. If this is the case, patch
10// things up.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattner5afe2f22002-07-23 22:04:02 +000014#include "llvm/Transforms/IPO.h"
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000015#include "llvm/Module.h"
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000016#include "llvm/SymbolTable.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/Pass.h"
19#include "llvm/iOther.h"
Chris Lattner013eca002002-10-09 21:10:06 +000020#include "llvm/Constants.h"
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +000021#include "llvm/Assembly/Writer.h" // FIXME: remove when varargs implemented
Chris Lattnerbf3a0992002-10-01 22:38:41 +000022#include "Support/Statistic.h"
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000023#include <algorithm>
24
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000025namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000026 Statistic<>NumResolved("funcresolve", "Number of varargs functions resolved");
Chris Lattner013eca002002-10-09 21:10:06 +000027 Statistic<> NumGlobals("funcresolve", "Number of global variables resolved");
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000028
29 struct FunctionResolvingPass : public Pass {
Chris Lattner113f4f42002-06-25 16:13:24 +000030 bool run(Module &M);
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000031 };
Chris Lattnera2c09852002-07-26 21:12:44 +000032 RegisterOpt<FunctionResolvingPass> X("funcresolve", "Resolve Functions");
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000033}
34
35Pass *createFunctionResolvingPass() {
36 return new FunctionResolvingPass();
37}
38
39// ConvertCallTo - Convert a call to a varargs function with no arg types
40// specified to a concrete nonvarargs function.
41//
42static void ConvertCallTo(CallInst *CI, Function *Dest) {
43 const FunctionType::ParamTypes &ParamTys =
44 Dest->getFunctionType()->getParamTypes();
45 BasicBlock *BB = CI->getParent();
46
Chris Lattner113f4f42002-06-25 16:13:24 +000047 // Keep an iterator to where we want to insert cast instructions if the
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000048 // argument types don't agree.
49 //
Chris Lattner113f4f42002-06-25 16:13:24 +000050 BasicBlock::iterator BBI = CI;
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +000051 if (CI->getNumOperands()-1 != ParamTys.size()) {
52 std::cerr << "WARNING: Call arguments do not match expected number of"
53 << " parameters.\n";
54 std::cerr << "WARNING: In function '"
55 << CI->getParent()->getParent()->getName() << "': call: " << *CI;
56 std::cerr << "Function resolved to: ";
57 WriteAsOperand(std::cerr, Dest);
58 std::cerr << "\n";
59 }
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000060
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +000061 std::vector<Value*> Params;
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000062
63 // Convert all of the call arguments over... inserting cast instructions if
64 // the types are not compatible.
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +000065 for (unsigned i = 1; i <= ParamTys.size(); ++i) {
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000066 Value *V = CI->getOperand(i);
67
Chris Lattner5c447862002-09-10 17:03:06 +000068 if (V->getType() != ParamTys[i-1]) // Must insert a cast...
69 V = new CastInst(V, ParamTys[i-1], "argcast", BBI);
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000070
71 Params.push_back(V);
72 }
73
74 // Replace the old call instruction with a new call instruction that calls
75 // the real function.
76 //
Chris Lattner5c447862002-09-10 17:03:06 +000077 Instruction *NewCall = new CallInst(Dest, Params, "", BBI);
Chris Lattner1eb9e6c2002-05-24 21:33:26 +000078
79 // Remove the old call instruction from the program...
80 BB->getInstList().remove(BBI);
81
Chris Lattneraacadd12002-07-30 00:50:49 +000082 // Transfer the name over...
Chris Lattnered378562002-07-30 02:42:49 +000083 if (NewCall->getType() != Type::VoidTy)
84 NewCall->setName(CI->getName());
Chris Lattneraacadd12002-07-30 00:50:49 +000085
Chris Lattner1eb9e6c2002-05-24 21:33:26 +000086 // Replace uses of the old instruction with the appropriate values...
87 //
88 if (NewCall->getType() == CI->getType()) {
89 CI->replaceAllUsesWith(NewCall);
90 NewCall->setName(CI->getName());
91
92 } else if (NewCall->getType() == Type::VoidTy) {
93 // Resolved function does not return a value but the prototype does. This
94 // often occurs because undefined functions default to returning integers.
95 // Just replace uses of the call (which are broken anyway) with dummy
96 // values.
97 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
98 } else if (CI->getType() == Type::VoidTy) {
99 // If we are gaining a new return value, we don't have to do anything
Chris Lattneraacadd12002-07-30 00:50:49 +0000100 // special here, because it will automatically be ignored.
Chris Lattner1eb9e6c2002-05-24 21:33:26 +0000101 } else {
Chris Lattneraacadd12002-07-30 00:50:49 +0000102 // Insert a cast instruction to convert the return value of the function
103 // into it's new type. Of course we only need to do this if the return
104 // value of the function is actually USED.
105 //
106 if (!CI->use_empty()) {
Chris Lattneraacadd12002-07-30 00:50:49 +0000107 // Insert the new cast instruction...
Chris Lattner5c447862002-09-10 17:03:06 +0000108 CastInst *NewCast = new CastInst(NewCall, CI->getType(),
109 NewCall->getName(), BBI);
110 CI->replaceAllUsesWith(NewCast);
Chris Lattneraacadd12002-07-30 00:50:49 +0000111 }
Chris Lattner1eb9e6c2002-05-24 21:33:26 +0000112 }
113
114 // The old instruction is no longer needed, destroy it!
115 delete CI;
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000116}
117
118
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000119static bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,
Chris Lattner013eca002002-10-09 21:10:06 +0000120 Function *Concrete) {
121 bool Changed = false;
122 for (unsigned i = 0; i != Globals.size(); ++i)
123 if (Globals[i] != Concrete) {
124 Function *Old = cast<Function>(Globals[i]);
125 const FunctionType *OldMT = Old->getFunctionType();
126 const FunctionType *ConcreteMT = Concrete->getFunctionType();
127
128 assert(OldMT->getParamTypes().size() <=
129 ConcreteMT->getParamTypes().size() &&
130 "Concrete type must have more specified parameters!");
131
132 // Check to make sure that if there are specified types, that they
133 // match...
134 //
135 for (unsigned i = 0; i < OldMT->getParamTypes().size(); ++i)
136 if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i]) {
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000137 std::cerr << "Parameter types conflict for: '" << OldMT
138 << "' and '" << ConcreteMT << "'\n";
Chris Lattner013eca002002-10-09 21:10:06 +0000139 return Changed;
140 }
141
142 // Attempt to convert all of the uses of the old function to the
143 // concrete form of the function. If there is a use of the fn that
144 // we don't understand here we punt to avoid making a bad
145 // transformation.
146 //
147 // At this point, we know that the return values are the same for
148 // our two functions and that the Old function has no varargs fns
149 // specified. In otherwords it's just <retty> (...)
150 //
151 for (unsigned i = 0; i < Old->use_size(); ) {
152 User *U = *(Old->use_begin()+i);
153 if (CastInst *CI = dyn_cast<CastInst>(U)) {
154 // Convert casts directly
155 assert(CI->getOperand(0) == Old);
156 CI->setOperand(0, Concrete);
157 Changed = true;
158 ++NumResolved;
159 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
160 // Can only fix up calls TO the argument, not args passed in.
161 if (CI->getCalledValue() == Old) {
162 ConvertCallTo(CI, Concrete);
163 Changed = true;
164 ++NumResolved;
165 } else {
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000166 std::cerr << "Couldn't cleanup this function call, must be an"
167 << " argument or something!" << CI;
Chris Lattner013eca002002-10-09 21:10:06 +0000168 ++i;
169 }
170 } else {
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000171 std::cerr << "Cannot convert use of function: " << U << "\n";
Chris Lattner013eca002002-10-09 21:10:06 +0000172 ++i;
173 }
174 }
175 }
176 return Changed;
177}
178
179
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000180static bool ResolveGlobalVariables(Module &M,
181 std::vector<GlobalValue*> &Globals,
Chris Lattner013eca002002-10-09 21:10:06 +0000182 GlobalVariable *Concrete) {
183 bool Changed = false;
184 assert(isa<ArrayType>(Concrete->getType()->getElementType()) &&
185 "Concrete version should be an array type!");
186
187 // Get the type of the things that may be resolved to us...
188 const Type *AETy =
189 cast<ArrayType>(Concrete->getType()->getElementType())->getElementType();
190
191 std::vector<Constant*> Args;
192 Args.push_back(Constant::getNullValue(Type::LongTy));
193 Args.push_back(Constant::getNullValue(Type::LongTy));
194 ConstantExpr *Replacement =
195 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(Concrete), Args);
196
197 for (unsigned i = 0; i != Globals.size(); ++i)
198 if (Globals[i] != Concrete) {
199 GlobalVariable *Old = cast<GlobalVariable>(Globals[i]);
200 if (Old->getType()->getElementType() != AETy) {
201 std::cerr << "WARNING: Two global variables exist with the same name "
202 << "that cannot be resolved!\n";
203 return false;
204 }
205
206 // In this case, Old is a pointer to T, Concrete is a pointer to array of
207 // T. Because of this, replace all uses of Old with a constantexpr
208 // getelementptr that returns the address of the first element of the
209 // array.
210 //
211 Old->replaceAllUsesWith(Replacement);
212 // Since there are no uses of Old anymore, remove it from the module.
213 M.getGlobalList().erase(Old);
214
215 ++NumGlobals;
216 Changed = true;
217 }
218 return Changed;
219}
220
221static bool ProcessGlobalsWithSameName(Module &M,
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000222 std::vector<GlobalValue*> &Globals) {
Chris Lattner013eca002002-10-09 21:10:06 +0000223 assert(!Globals.empty() && "Globals list shouldn't be empty here!");
224
225 bool isFunction = isa<Function>(Globals[0]); // Is this group all functions?
226 bool Changed = false;
227 GlobalValue *Concrete = 0; // The most concrete implementation to resolve to
228
229 assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&
230 "Should either be function or gvar!");
231
232 for (unsigned i = 0; i != Globals.size(); ) {
233 if (isa<Function>(Globals[i]) != isFunction) {
234 std::cerr << "WARNING: Found function and global variable with the "
235 << "same name: '" << Globals[i]->getName() << "'.\n";
236 return false; // Don't know how to handle this, bail out!
237 }
238
Chris Lattner52b8fc02002-11-10 03:36:55 +0000239 if (isFunction) {
Chris Lattner013eca002002-10-09 21:10:06 +0000240 // For functions, we look to merge functions definitions of "int (...)"
241 // to 'int (int)' or 'int ()' or whatever else is not completely generic.
242 //
243 Function *F = cast<Function>(Globals[i]);
Chris Lattner5997c3d2002-11-08 00:38:20 +0000244 if (!F->isExternal()) {
Chris Lattner52b8fc02002-11-10 03:36:55 +0000245 if (Concrete && !Concrete->isExternal())
Chris Lattner013eca002002-10-09 21:10:06 +0000246 return false; // Found two different functions types. Can't choose!
247
248 Concrete = Globals[i];
Chris Lattner52b8fc02002-11-10 03:36:55 +0000249 } else if (Concrete) {
250 if (Concrete->isExternal()) // If we have multiple external symbols...x
251 if (F->getFunctionType()->getNumParams() >
252 cast<Function>(Concrete)->getFunctionType()->getNumParams())
253 Concrete = F; // We are more concrete than "Concrete"!
254
255 } else {
256 Concrete = F;
Chris Lattner013eca002002-10-09 21:10:06 +0000257 }
258 ++i;
259 } else {
260 // For global variables, we have to merge C definitions int A[][4] with
261 // int[6][4]
262 GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
263 if (Concrete == 0) {
264 if (isa<ArrayType>(GV->getType()->getElementType()))
265 Concrete = GV;
266 } else { // Must have different types... one is an array of the other?
267 const ArrayType *AT =
268 dyn_cast<ArrayType>(GV->getType()->getElementType());
269
270 // If GV is an array of Concrete, then GV is the array.
271 if (AT && AT->getElementType() == Concrete->getType()->getElementType())
272 Concrete = GV;
273 else {
274 // Concrete must be an array type, check to see if the element type of
275 // concrete is already GV.
276 AT = cast<ArrayType>(Concrete->getType()->getElementType());
277 if (AT->getElementType() != GV->getType()->getElementType())
278 Concrete = 0; // Don't know how to handle it!
279 }
280 }
281
282 ++i;
283 }
284 }
285
286 if (Globals.size() > 1) { // Found a multiply defined global...
287 // We should find exactly one concrete function definition, which is
288 // probably the implementation. Change all of the function definitions and
289 // uses to use it instead.
290 //
291 if (!Concrete) {
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000292 std::cerr << "WARNING: Found function types that are not compatible:\n";
Chris Lattner013eca002002-10-09 21:10:06 +0000293 for (unsigned i = 0; i < Globals.size(); ++i) {
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000294 std::cerr << "\t" << Globals[i]->getType()->getDescription() << " %"
295 << Globals[i]->getName() << "\n";
Chris Lattner013eca002002-10-09 21:10:06 +0000296 }
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000297 std::cerr << " No linkage of globals named '" << Globals[0]->getName()
298 << "' performed!\n";
Chris Lattner013eca002002-10-09 21:10:06 +0000299 return Changed;
300 }
301
302 if (isFunction)
303 return Changed | ResolveFunctions(M, Globals, cast<Function>(Concrete));
304 else
305 return Changed | ResolveGlobalVariables(M, Globals,
306 cast<GlobalVariable>(Concrete));
307 }
308 return Changed;
309}
310
Chris Lattner113f4f42002-06-25 16:13:24 +0000311bool FunctionResolvingPass::run(Module &M) {
Chris Lattner98cf1f52002-11-20 18:36:02 +0000312 SymbolTable &ST = M.getSymbolTable();
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000313
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000314 std::map<std::string, std::vector<GlobalValue*> > Globals;
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000315
316 // Loop over the entries in the symbol table. If an entry is a func pointer,
317 // then add it to the Functions map. We do a two pass algorithm here to avoid
318 // problems with iterators getting invalidated if we did a one pass scheme.
319 //
Chris Lattner98cf1f52002-11-20 18:36:02 +0000320 for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)
Chris Lattner013eca002002-10-09 21:10:06 +0000321 if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {
322 SymbolTable::VarMap &Plane = I->second;
323 for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
324 PI != PE; ++PI) {
325 GlobalValue *GV = cast<GlobalValue>(PI->second);
326 assert(PI->first == GV->getName() &&
327 "Global name and symbol table do not agree!");
328 if (GV->hasExternalLinkage()) // Only resolve decls to external fns
329 Globals[PI->first].push_back(GV);
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000330 }
Chris Lattner013eca002002-10-09 21:10:06 +0000331 }
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000332
333 bool Changed = false;
334
335 // Now we have a list of all functions with a particular name. If there is
336 // more than one entry in a list, merge the functions together.
337 //
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000338 for (std::map<std::string, std::vector<GlobalValue*> >::iterator
339 I = Globals.begin(), E = Globals.end(); I != E; ++I)
Chris Lattner013eca002002-10-09 21:10:06 +0000340 Changed |= ProcessGlobalsWithSameName(M, I->second);
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000341
Chris Lattner52b8fc02002-11-10 03:36:55 +0000342 // Now loop over all of the globals, checking to see if any are trivially
343 // dead. If so, remove them now.
344
345 for (Module::iterator I = M.begin(), E = M.end(); I != E; )
346 if (I->isExternal() && I->use_empty()) {
347 Function *F = I;
348 ++I;
349 M.getFunctionList().erase(F);
350 ++NumResolved;
351 Changed = true;
352 } else {
353 ++I;
354 }
355
356 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )
357 if (I->isExternal() && I->use_empty()) {
358 GlobalVariable *GV = I;
359 ++I;
360 M.getGlobalList().erase(GV);
361 ++NumGlobals;
362 Changed = true;
363 } else {
364 ++I;
365 }
366
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000367 return Changed;
368}