blob: 3d5991aba988864e89fdc9862d8699b6a105ee3d [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 Lattner68f63f72003-01-30 22:38:44 +000051 unsigned NumArgsToCopy = CI->getNumOperands()-1;
Chris Lattner04c92742003-02-14 19:12:29 +000052 if (NumArgsToCopy != ParamTys.size() &&
53 !(NumArgsToCopy > ParamTys.size() &&
Chris Lattner68f63f72003-01-30 22:38:44 +000054 Dest->getFunctionType()->isVarArg())) {
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +000055 std::cerr << "WARNING: Call arguments do not match expected number of"
56 << " parameters.\n";
57 std::cerr << "WARNING: In function '"
58 << CI->getParent()->getParent()->getName() << "': call: " << *CI;
59 std::cerr << "Function resolved to: ";
60 WriteAsOperand(std::cerr, Dest);
61 std::cerr << "\n";
Chris Lattner04c92742003-02-14 19:12:29 +000062 if (NumArgsToCopy > ParamTys.size())
63 NumArgsToCopy = ParamTys.size();
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +000064 }
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000065
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +000066 std::vector<Value*> Params;
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000067
68 // Convert all of the call arguments over... inserting cast instructions if
69 // the types are not compatible.
Chris Lattner68f63f72003-01-30 22:38:44 +000070 for (unsigned i = 1; i <= NumArgsToCopy; ++i) {
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000071 Value *V = CI->getOperand(i);
72
Chris Lattner68f63f72003-01-30 22:38:44 +000073 if (i-1 < ParamTys.size() && V->getType() != ParamTys[i-1]) {
74 // Must insert a cast...
Chris Lattner5c447862002-09-10 17:03:06 +000075 V = new CastInst(V, ParamTys[i-1], "argcast", BBI);
Chris Lattner68f63f72003-01-30 22:38:44 +000076 }
Chris Lattner5aa9e3e2002-05-24 20:42:13 +000077
78 Params.push_back(V);
79 }
80
81 // Replace the old call instruction with a new call instruction that calls
82 // the real function.
83 //
Chris Lattner5c447862002-09-10 17:03:06 +000084 Instruction *NewCall = new CallInst(Dest, Params, "", BBI);
Chris Lattner1eb9e6c2002-05-24 21:33:26 +000085
86 // Remove the old call instruction from the program...
87 BB->getInstList().remove(BBI);
88
Chris Lattneraacadd12002-07-30 00:50:49 +000089 // Transfer the name over...
Chris Lattnered378562002-07-30 02:42:49 +000090 if (NewCall->getType() != Type::VoidTy)
91 NewCall->setName(CI->getName());
Chris Lattneraacadd12002-07-30 00:50:49 +000092
Chris Lattner1eb9e6c2002-05-24 21:33:26 +000093 // Replace uses of the old instruction with the appropriate values...
94 //
95 if (NewCall->getType() == CI->getType()) {
96 CI->replaceAllUsesWith(NewCall);
97 NewCall->setName(CI->getName());
98
99 } else if (NewCall->getType() == Type::VoidTy) {
100 // Resolved function does not return a value but the prototype does. This
101 // often occurs because undefined functions default to returning integers.
102 // Just replace uses of the call (which are broken anyway) with dummy
103 // values.
104 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
105 } else if (CI->getType() == Type::VoidTy) {
106 // If we are gaining a new return value, we don't have to do anything
Chris Lattneraacadd12002-07-30 00:50:49 +0000107 // special here, because it will automatically be ignored.
Chris Lattner1eb9e6c2002-05-24 21:33:26 +0000108 } else {
Chris Lattneraacadd12002-07-30 00:50:49 +0000109 // Insert a cast instruction to convert the return value of the function
110 // into it's new type. Of course we only need to do this if the return
111 // value of the function is actually USED.
112 //
113 if (!CI->use_empty()) {
Chris Lattneraacadd12002-07-30 00:50:49 +0000114 // Insert the new cast instruction...
Chris Lattner5c447862002-09-10 17:03:06 +0000115 CastInst *NewCast = new CastInst(NewCall, CI->getType(),
116 NewCall->getName(), BBI);
117 CI->replaceAllUsesWith(NewCast);
Chris Lattneraacadd12002-07-30 00:50:49 +0000118 }
Chris Lattner1eb9e6c2002-05-24 21:33:26 +0000119 }
120
121 // The old instruction is no longer needed, destroy it!
122 delete CI;
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000123}
124
125
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000126static bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,
Chris Lattner013eca002002-10-09 21:10:06 +0000127 Function *Concrete) {
128 bool Changed = false;
129 for (unsigned i = 0; i != Globals.size(); ++i)
130 if (Globals[i] != Concrete) {
131 Function *Old = cast<Function>(Globals[i]);
132 const FunctionType *OldMT = Old->getFunctionType();
133 const FunctionType *ConcreteMT = Concrete->getFunctionType();
134
135 assert(OldMT->getParamTypes().size() <=
136 ConcreteMT->getParamTypes().size() &&
137 "Concrete type must have more specified parameters!");
138
139 // Check to make sure that if there are specified types, that they
140 // match...
141 //
142 for (unsigned i = 0; i < OldMT->getParamTypes().size(); ++i)
143 if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i]) {
Chris Lattner47948952003-01-30 21:33:07 +0000144 std::cerr << "funcresolve: Function [" << Old->getName()
145 << "]: Parameter types conflict for: '" << OldMT
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000146 << "' and '" << ConcreteMT << "'\n";
Chris Lattner013eca002002-10-09 21:10:06 +0000147 return Changed;
148 }
149
150 // Attempt to convert all of the uses of the old function to the
151 // concrete form of the function. If there is a use of the fn that
152 // we don't understand here we punt to avoid making a bad
153 // transformation.
154 //
155 // At this point, we know that the return values are the same for
156 // our two functions and that the Old function has no varargs fns
157 // specified. In otherwords it's just <retty> (...)
158 //
159 for (unsigned i = 0; i < Old->use_size(); ) {
160 User *U = *(Old->use_begin()+i);
161 if (CastInst *CI = dyn_cast<CastInst>(U)) {
162 // Convert casts directly
163 assert(CI->getOperand(0) == Old);
164 CI->setOperand(0, Concrete);
165 Changed = true;
166 ++NumResolved;
167 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
168 // Can only fix up calls TO the argument, not args passed in.
169 if (CI->getCalledValue() == Old) {
170 ConvertCallTo(CI, Concrete);
171 Changed = true;
172 ++NumResolved;
173 } else {
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000174 std::cerr << "Couldn't cleanup this function call, must be an"
175 << " argument or something!" << CI;
Chris Lattner013eca002002-10-09 21:10:06 +0000176 ++i;
177 }
178 } else {
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000179 std::cerr << "Cannot convert use of function: " << U << "\n";
Chris Lattner013eca002002-10-09 21:10:06 +0000180 ++i;
181 }
182 }
183 }
184 return Changed;
185}
186
187
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000188static bool ResolveGlobalVariables(Module &M,
189 std::vector<GlobalValue*> &Globals,
Chris Lattner013eca002002-10-09 21:10:06 +0000190 GlobalVariable *Concrete) {
191 bool Changed = false;
192 assert(isa<ArrayType>(Concrete->getType()->getElementType()) &&
193 "Concrete version should be an array type!");
194
195 // Get the type of the things that may be resolved to us...
196 const Type *AETy =
197 cast<ArrayType>(Concrete->getType()->getElementType())->getElementType();
198
199 std::vector<Constant*> Args;
200 Args.push_back(Constant::getNullValue(Type::LongTy));
201 Args.push_back(Constant::getNullValue(Type::LongTy));
202 ConstantExpr *Replacement =
203 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(Concrete), Args);
204
205 for (unsigned i = 0; i != Globals.size(); ++i)
206 if (Globals[i] != Concrete) {
207 GlobalVariable *Old = cast<GlobalVariable>(Globals[i]);
208 if (Old->getType()->getElementType() != AETy) {
209 std::cerr << "WARNING: Two global variables exist with the same name "
210 << "that cannot be resolved!\n";
211 return false;
212 }
213
214 // In this case, Old is a pointer to T, Concrete is a pointer to array of
215 // T. Because of this, replace all uses of Old with a constantexpr
216 // getelementptr that returns the address of the first element of the
217 // array.
218 //
219 Old->replaceAllUsesWith(Replacement);
220 // Since there are no uses of Old anymore, remove it from the module.
221 M.getGlobalList().erase(Old);
222
223 ++NumGlobals;
224 Changed = true;
225 }
226 return Changed;
227}
228
229static bool ProcessGlobalsWithSameName(Module &M,
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000230 std::vector<GlobalValue*> &Globals) {
Chris Lattner013eca002002-10-09 21:10:06 +0000231 assert(!Globals.empty() && "Globals list shouldn't be empty here!");
232
233 bool isFunction = isa<Function>(Globals[0]); // Is this group all functions?
234 bool Changed = false;
235 GlobalValue *Concrete = 0; // The most concrete implementation to resolve to
236
237 assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&
238 "Should either be function or gvar!");
239
240 for (unsigned i = 0; i != Globals.size(); ) {
241 if (isa<Function>(Globals[i]) != isFunction) {
242 std::cerr << "WARNING: Found function and global variable with the "
243 << "same name: '" << Globals[i]->getName() << "'.\n";
244 return false; // Don't know how to handle this, bail out!
245 }
246
Chris Lattner52b8fc02002-11-10 03:36:55 +0000247 if (isFunction) {
Chris Lattner013eca002002-10-09 21:10:06 +0000248 // For functions, we look to merge functions definitions of "int (...)"
249 // to 'int (int)' or 'int ()' or whatever else is not completely generic.
250 //
251 Function *F = cast<Function>(Globals[i]);
Chris Lattner5997c3d2002-11-08 00:38:20 +0000252 if (!F->isExternal()) {
Chris Lattner52b8fc02002-11-10 03:36:55 +0000253 if (Concrete && !Concrete->isExternal())
Chris Lattner013eca002002-10-09 21:10:06 +0000254 return false; // Found two different functions types. Can't choose!
255
256 Concrete = Globals[i];
Chris Lattner52b8fc02002-11-10 03:36:55 +0000257 } else if (Concrete) {
258 if (Concrete->isExternal()) // If we have multiple external symbols...x
259 if (F->getFunctionType()->getNumParams() >
260 cast<Function>(Concrete)->getFunctionType()->getNumParams())
261 Concrete = F; // We are more concrete than "Concrete"!
262
263 } else {
264 Concrete = F;
Chris Lattner013eca002002-10-09 21:10:06 +0000265 }
266 ++i;
267 } else {
268 // For global variables, we have to merge C definitions int A[][4] with
269 // int[6][4]
270 GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
271 if (Concrete == 0) {
272 if (isa<ArrayType>(GV->getType()->getElementType()))
273 Concrete = GV;
274 } else { // Must have different types... one is an array of the other?
275 const ArrayType *AT =
276 dyn_cast<ArrayType>(GV->getType()->getElementType());
277
278 // If GV is an array of Concrete, then GV is the array.
279 if (AT && AT->getElementType() == Concrete->getType()->getElementType())
280 Concrete = GV;
281 else {
282 // Concrete must be an array type, check to see if the element type of
283 // concrete is already GV.
284 AT = cast<ArrayType>(Concrete->getType()->getElementType());
285 if (AT->getElementType() != GV->getType()->getElementType())
286 Concrete = 0; // Don't know how to handle it!
287 }
288 }
289
290 ++i;
291 }
292 }
293
294 if (Globals.size() > 1) { // Found a multiply defined global...
295 // We should find exactly one concrete function definition, which is
296 // probably the implementation. Change all of the function definitions and
297 // uses to use it instead.
298 //
299 if (!Concrete) {
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000300 std::cerr << "WARNING: Found function types that are not compatible:\n";
Chris Lattner013eca002002-10-09 21:10:06 +0000301 for (unsigned i = 0; i < Globals.size(); ++i) {
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000302 std::cerr << "\t" << Globals[i]->getType()->getDescription() << " %"
303 << Globals[i]->getName() << "\n";
Chris Lattner013eca002002-10-09 21:10:06 +0000304 }
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000305 std::cerr << " No linkage of globals named '" << Globals[0]->getName()
306 << "' performed!\n";
Chris Lattner013eca002002-10-09 21:10:06 +0000307 return Changed;
308 }
309
310 if (isFunction)
311 return Changed | ResolveFunctions(M, Globals, cast<Function>(Concrete));
312 else
313 return Changed | ResolveGlobalVariables(M, Globals,
314 cast<GlobalVariable>(Concrete));
315 }
316 return Changed;
317}
318
Chris Lattner113f4f42002-06-25 16:13:24 +0000319bool FunctionResolvingPass::run(Module &M) {
Chris Lattner98cf1f52002-11-20 18:36:02 +0000320 SymbolTable &ST = M.getSymbolTable();
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000321
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000322 std::map<std::string, std::vector<GlobalValue*> > Globals;
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000323
324 // Loop over the entries in the symbol table. If an entry is a func pointer,
325 // then add it to the Functions map. We do a two pass algorithm here to avoid
326 // problems with iterators getting invalidated if we did a one pass scheme.
327 //
Chris Lattner98cf1f52002-11-20 18:36:02 +0000328 for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)
Chris Lattner013eca002002-10-09 21:10:06 +0000329 if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {
330 SymbolTable::VarMap &Plane = I->second;
331 for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
332 PI != PE; ++PI) {
333 GlobalValue *GV = cast<GlobalValue>(PI->second);
334 assert(PI->first == GV->getName() &&
335 "Global name and symbol table do not agree!");
336 if (GV->hasExternalLinkage()) // Only resolve decls to external fns
337 Globals[PI->first].push_back(GV);
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000338 }
Chris Lattner013eca002002-10-09 21:10:06 +0000339 }
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000340
341 bool Changed = false;
342
343 // Now we have a list of all functions with a particular name. If there is
344 // more than one entry in a list, merge the functions together.
345 //
Chris Lattnerb2d9f7d2003-01-30 18:22:32 +0000346 for (std::map<std::string, std::vector<GlobalValue*> >::iterator
347 I = Globals.begin(), E = Globals.end(); I != E; ++I)
Chris Lattner013eca002002-10-09 21:10:06 +0000348 Changed |= ProcessGlobalsWithSameName(M, I->second);
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000349
Chris Lattner52b8fc02002-11-10 03:36:55 +0000350 // Now loop over all of the globals, checking to see if any are trivially
351 // dead. If so, remove them now.
352
353 for (Module::iterator I = M.begin(), E = M.end(); I != E; )
354 if (I->isExternal() && I->use_empty()) {
355 Function *F = I;
356 ++I;
357 M.getFunctionList().erase(F);
358 ++NumResolved;
359 Changed = true;
360 } else {
361 ++I;
362 }
363
364 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )
365 if (I->isExternal() && I->use_empty()) {
366 GlobalVariable *GV = I;
367 ++I;
368 M.getGlobalList().erase(GV);
369 ++NumGlobals;
370 Changed = true;
371 } else {
372 ++I;
373 }
374
Chris Lattner5aa9e3e2002-05-24 20:42:13 +0000375 return Changed;
376}