blob: cbcfa2aba853c74070765c57ade30b5319fac846 [file] [log] [blame]
Chris Lattner22ee3eb2002-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 Lattnerff1be262002-07-23 22:04:02 +000014#include "llvm/Transforms/IPO.h"
Chris Lattner22ee3eb2002-05-24 20:42:13 +000015#include "llvm/Module.h"
Chris Lattner22ee3eb2002-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 Lattnera45ec542002-10-09 21:10:06 +000020#include "llvm/Constants.h"
Chris Lattnera92f6962002-10-01 22:38:41 +000021#include "Support/Statistic.h"
Chris Lattner22ee3eb2002-05-24 20:42:13 +000022#include <algorithm>
23
24using std::vector;
25using std::string;
26using std::cerr;
27
28namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000029 Statistic<>NumResolved("funcresolve", "Number of varargs functions resolved");
Chris Lattnera45ec542002-10-09 21:10:06 +000030 Statistic<> NumGlobals("funcresolve", "Number of global variables resolved");
Chris Lattner22ee3eb2002-05-24 20:42:13 +000031
32 struct FunctionResolvingPass : public Pass {
Chris Lattner7e708292002-06-25 16:13:24 +000033 bool run(Module &M);
Chris Lattner22ee3eb2002-05-24 20:42:13 +000034 };
Chris Lattner1e435162002-07-26 21:12:44 +000035 RegisterOpt<FunctionResolvingPass> X("funcresolve", "Resolve Functions");
Chris Lattner22ee3eb2002-05-24 20:42:13 +000036}
37
38Pass *createFunctionResolvingPass() {
39 return new FunctionResolvingPass();
40}
41
42// ConvertCallTo - Convert a call to a varargs function with no arg types
43// specified to a concrete nonvarargs function.
44//
45static void ConvertCallTo(CallInst *CI, Function *Dest) {
46 const FunctionType::ParamTypes &ParamTys =
47 Dest->getFunctionType()->getParamTypes();
48 BasicBlock *BB = CI->getParent();
49
Chris Lattner7e708292002-06-25 16:13:24 +000050 // Keep an iterator to where we want to insert cast instructions if the
Chris Lattner22ee3eb2002-05-24 20:42:13 +000051 // argument types don't agree.
52 //
Chris Lattner7e708292002-06-25 16:13:24 +000053 BasicBlock::iterator BBI = CI;
Chris Lattnerabe6c3d2002-05-24 21:33:26 +000054 assert(CI->getNumOperands()-1 == ParamTys.size() &&
Chris Lattner22ee3eb2002-05-24 20:42:13 +000055 "Function calls resolved funny somehow, incompatible number of args");
56
57 vector<Value*> Params;
58
59 // Convert all of the call arguments over... inserting cast instructions if
60 // the types are not compatible.
61 for (unsigned i = 1; i < CI->getNumOperands(); ++i) {
62 Value *V = CI->getOperand(i);
63
Chris Lattner3ea5cb02002-09-10 17:03:06 +000064 if (V->getType() != ParamTys[i-1]) // Must insert a cast...
65 V = new CastInst(V, ParamTys[i-1], "argcast", BBI);
Chris Lattner22ee3eb2002-05-24 20:42:13 +000066
67 Params.push_back(V);
68 }
69
70 // Replace the old call instruction with a new call instruction that calls
71 // the real function.
72 //
Chris Lattner3ea5cb02002-09-10 17:03:06 +000073 Instruction *NewCall = new CallInst(Dest, Params, "", BBI);
Chris Lattnerabe6c3d2002-05-24 21:33:26 +000074
75 // Remove the old call instruction from the program...
76 BB->getInstList().remove(BBI);
77
Chris Lattner9cf307f2002-07-30 00:50:49 +000078 // Transfer the name over...
Chris Lattnere902bda2002-07-30 02:42:49 +000079 if (NewCall->getType() != Type::VoidTy)
80 NewCall->setName(CI->getName());
Chris Lattner9cf307f2002-07-30 00:50:49 +000081
Chris Lattnerabe6c3d2002-05-24 21:33:26 +000082 // Replace uses of the old instruction with the appropriate values...
83 //
84 if (NewCall->getType() == CI->getType()) {
85 CI->replaceAllUsesWith(NewCall);
86 NewCall->setName(CI->getName());
87
88 } else if (NewCall->getType() == Type::VoidTy) {
89 // Resolved function does not return a value but the prototype does. This
90 // often occurs because undefined functions default to returning integers.
91 // Just replace uses of the call (which are broken anyway) with dummy
92 // values.
93 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
94 } else if (CI->getType() == Type::VoidTy) {
95 // If we are gaining a new return value, we don't have to do anything
Chris Lattner9cf307f2002-07-30 00:50:49 +000096 // special here, because it will automatically be ignored.
Chris Lattnerabe6c3d2002-05-24 21:33:26 +000097 } else {
Chris Lattner9cf307f2002-07-30 00:50:49 +000098 // Insert a cast instruction to convert the return value of the function
99 // into it's new type. Of course we only need to do this if the return
100 // value of the function is actually USED.
101 //
102 if (!CI->use_empty()) {
Chris Lattner9cf307f2002-07-30 00:50:49 +0000103 // Insert the new cast instruction...
Chris Lattner3ea5cb02002-09-10 17:03:06 +0000104 CastInst *NewCast = new CastInst(NewCall, CI->getType(),
105 NewCall->getName(), BBI);
106 CI->replaceAllUsesWith(NewCast);
Chris Lattner9cf307f2002-07-30 00:50:49 +0000107 }
Chris Lattnerabe6c3d2002-05-24 21:33:26 +0000108 }
109
110 // The old instruction is no longer needed, destroy it!
111 delete CI;
Chris Lattner22ee3eb2002-05-24 20:42:13 +0000112}
113
114
Chris Lattnera45ec542002-10-09 21:10:06 +0000115static bool ResolveFunctions(Module &M, vector<GlobalValue*> &Globals,
116 Function *Concrete) {
117 bool Changed = false;
118 for (unsigned i = 0; i != Globals.size(); ++i)
119 if (Globals[i] != Concrete) {
120 Function *Old = cast<Function>(Globals[i]);
121 const FunctionType *OldMT = Old->getFunctionType();
122 const FunctionType *ConcreteMT = Concrete->getFunctionType();
123
124 assert(OldMT->getParamTypes().size() <=
125 ConcreteMT->getParamTypes().size() &&
126 "Concrete type must have more specified parameters!");
127
128 // Check to make sure that if there are specified types, that they
129 // match...
130 //
131 for (unsigned i = 0; i < OldMT->getParamTypes().size(); ++i)
132 if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i]) {
Chris Lattnera2b8d7b2002-11-10 03:36:55 +0000133 cerr << "Parameter types conflict for: '" << OldMT
134 << "' and '" << ConcreteMT << "'\n";
Chris Lattnera45ec542002-10-09 21:10:06 +0000135 return Changed;
136 }
137
138 // Attempt to convert all of the uses of the old function to the
139 // concrete form of the function. If there is a use of the fn that
140 // we don't understand here we punt to avoid making a bad
141 // transformation.
142 //
143 // At this point, we know that the return values are the same for
144 // our two functions and that the Old function has no varargs fns
145 // specified. In otherwords it's just <retty> (...)
146 //
147 for (unsigned i = 0; i < Old->use_size(); ) {
148 User *U = *(Old->use_begin()+i);
149 if (CastInst *CI = dyn_cast<CastInst>(U)) {
150 // Convert casts directly
151 assert(CI->getOperand(0) == Old);
152 CI->setOperand(0, Concrete);
153 Changed = true;
154 ++NumResolved;
155 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
156 // Can only fix up calls TO the argument, not args passed in.
157 if (CI->getCalledValue() == Old) {
158 ConvertCallTo(CI, Concrete);
159 Changed = true;
160 ++NumResolved;
161 } else {
162 cerr << "Couldn't cleanup this function call, must be an"
163 << " argument or something!" << CI;
164 ++i;
165 }
166 } else {
167 cerr << "Cannot convert use of function: " << U << "\n";
168 ++i;
169 }
170 }
171 }
172 return Changed;
173}
174
175
176static bool ResolveGlobalVariables(Module &M, vector<GlobalValue*> &Globals,
177 GlobalVariable *Concrete) {
178 bool Changed = false;
179 assert(isa<ArrayType>(Concrete->getType()->getElementType()) &&
180 "Concrete version should be an array type!");
181
182 // Get the type of the things that may be resolved to us...
183 const Type *AETy =
184 cast<ArrayType>(Concrete->getType()->getElementType())->getElementType();
185
186 std::vector<Constant*> Args;
187 Args.push_back(Constant::getNullValue(Type::LongTy));
188 Args.push_back(Constant::getNullValue(Type::LongTy));
189 ConstantExpr *Replacement =
190 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(Concrete), Args);
191
192 for (unsigned i = 0; i != Globals.size(); ++i)
193 if (Globals[i] != Concrete) {
194 GlobalVariable *Old = cast<GlobalVariable>(Globals[i]);
195 if (Old->getType()->getElementType() != AETy) {
196 std::cerr << "WARNING: Two global variables exist with the same name "
197 << "that cannot be resolved!\n";
198 return false;
199 }
200
201 // In this case, Old is a pointer to T, Concrete is a pointer to array of
202 // T. Because of this, replace all uses of Old with a constantexpr
203 // getelementptr that returns the address of the first element of the
204 // array.
205 //
206 Old->replaceAllUsesWith(Replacement);
207 // Since there are no uses of Old anymore, remove it from the module.
208 M.getGlobalList().erase(Old);
209
210 ++NumGlobals;
211 Changed = true;
212 }
213 return Changed;
214}
215
216static bool ProcessGlobalsWithSameName(Module &M,
217 vector<GlobalValue*> &Globals) {
218 assert(!Globals.empty() && "Globals list shouldn't be empty here!");
219
220 bool isFunction = isa<Function>(Globals[0]); // Is this group all functions?
221 bool Changed = false;
222 GlobalValue *Concrete = 0; // The most concrete implementation to resolve to
223
224 assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&
225 "Should either be function or gvar!");
226
227 for (unsigned i = 0; i != Globals.size(); ) {
228 if (isa<Function>(Globals[i]) != isFunction) {
229 std::cerr << "WARNING: Found function and global variable with the "
230 << "same name: '" << Globals[i]->getName() << "'.\n";
231 return false; // Don't know how to handle this, bail out!
232 }
233
Chris Lattnera2b8d7b2002-11-10 03:36:55 +0000234 if (isFunction) {
Chris Lattnera45ec542002-10-09 21:10:06 +0000235 // For functions, we look to merge functions definitions of "int (...)"
236 // to 'int (int)' or 'int ()' or whatever else is not completely generic.
237 //
238 Function *F = cast<Function>(Globals[i]);
Chris Lattner6f239632002-11-08 00:38:20 +0000239 if (!F->isExternal()) {
Chris Lattnera2b8d7b2002-11-10 03:36:55 +0000240 if (Concrete && !Concrete->isExternal())
Chris Lattnera45ec542002-10-09 21:10:06 +0000241 return false; // Found two different functions types. Can't choose!
242
243 Concrete = Globals[i];
Chris Lattnera2b8d7b2002-11-10 03:36:55 +0000244 } else if (Concrete) {
245 if (Concrete->isExternal()) // If we have multiple external symbols...x
246 if (F->getFunctionType()->getNumParams() >
247 cast<Function>(Concrete)->getFunctionType()->getNumParams())
248 Concrete = F; // We are more concrete than "Concrete"!
249
250 } else {
251 Concrete = F;
Chris Lattnera45ec542002-10-09 21:10:06 +0000252 }
253 ++i;
254 } else {
255 // For global variables, we have to merge C definitions int A[][4] with
256 // int[6][4]
257 GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
258 if (Concrete == 0) {
259 if (isa<ArrayType>(GV->getType()->getElementType()))
260 Concrete = GV;
261 } else { // Must have different types... one is an array of the other?
262 const ArrayType *AT =
263 dyn_cast<ArrayType>(GV->getType()->getElementType());
264
265 // If GV is an array of Concrete, then GV is the array.
266 if (AT && AT->getElementType() == Concrete->getType()->getElementType())
267 Concrete = GV;
268 else {
269 // Concrete must be an array type, check to see if the element type of
270 // concrete is already GV.
271 AT = cast<ArrayType>(Concrete->getType()->getElementType());
272 if (AT->getElementType() != GV->getType()->getElementType())
273 Concrete = 0; // Don't know how to handle it!
274 }
275 }
276
277 ++i;
278 }
279 }
280
281 if (Globals.size() > 1) { // Found a multiply defined global...
282 // We should find exactly one concrete function definition, which is
283 // probably the implementation. Change all of the function definitions and
284 // uses to use it instead.
285 //
286 if (!Concrete) {
287 cerr << "WARNING: Found function types that are not compatible:\n";
288 for (unsigned i = 0; i < Globals.size(); ++i) {
289 cerr << "\t" << Globals[i]->getType()->getDescription() << " %"
290 << Globals[i]->getName() << "\n";
291 }
292 cerr << " No linkage of globals named '" << Globals[0]->getName()
293 << "' performed!\n";
294 return Changed;
295 }
296
297 if (isFunction)
298 return Changed | ResolveFunctions(M, Globals, cast<Function>(Concrete));
299 else
300 return Changed | ResolveGlobalVariables(M, Globals,
301 cast<GlobalVariable>(Concrete));
302 }
303 return Changed;
304}
305
Chris Lattner7e708292002-06-25 16:13:24 +0000306bool FunctionResolvingPass::run(Module &M) {
307 SymbolTable *ST = M.getSymbolTable();
Chris Lattner22ee3eb2002-05-24 20:42:13 +0000308 if (!ST) return false;
309
Chris Lattnera45ec542002-10-09 21:10:06 +0000310 std::map<string, vector<GlobalValue*> > Globals;
Chris Lattner22ee3eb2002-05-24 20:42:13 +0000311
312 // Loop over the entries in the symbol table. If an entry is a func pointer,
313 // then add it to the Functions map. We do a two pass algorithm here to avoid
314 // problems with iterators getting invalidated if we did a one pass scheme.
315 //
316 for (SymbolTable::iterator I = ST->begin(), E = ST->end(); I != E; ++I)
Chris Lattnera45ec542002-10-09 21:10:06 +0000317 if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {
318 SymbolTable::VarMap &Plane = I->second;
319 for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
320 PI != PE; ++PI) {
321 GlobalValue *GV = cast<GlobalValue>(PI->second);
322 assert(PI->first == GV->getName() &&
323 "Global name and symbol table do not agree!");
324 if (GV->hasExternalLinkage()) // Only resolve decls to external fns
325 Globals[PI->first].push_back(GV);
Chris Lattner22ee3eb2002-05-24 20:42:13 +0000326 }
Chris Lattnera45ec542002-10-09 21:10:06 +0000327 }
Chris Lattner22ee3eb2002-05-24 20:42:13 +0000328
329 bool Changed = false;
330
331 // Now we have a list of all functions with a particular name. If there is
332 // more than one entry in a list, merge the functions together.
333 //
Chris Lattnera45ec542002-10-09 21:10:06 +0000334 for (std::map<string, vector<GlobalValue*> >::iterator I = Globals.begin(),
335 E = Globals.end(); I != E; ++I)
336 Changed |= ProcessGlobalsWithSameName(M, I->second);
Chris Lattner22ee3eb2002-05-24 20:42:13 +0000337
Chris Lattnera2b8d7b2002-11-10 03:36:55 +0000338 // Now loop over all of the globals, checking to see if any are trivially
339 // dead. If so, remove them now.
340
341 for (Module::iterator I = M.begin(), E = M.end(); I != E; )
342 if (I->isExternal() && I->use_empty()) {
343 Function *F = I;
344 ++I;
345 M.getFunctionList().erase(F);
346 ++NumResolved;
347 Changed = true;
348 } else {
349 ++I;
350 }
351
352 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )
353 if (I->isExternal() && I->use_empty()) {
354 GlobalVariable *GV = I;
355 ++I;
356 M.getGlobalList().erase(GV);
357 ++NumGlobals;
358 Changed = true;
359 } else {
360 ++I;
361 }
362
Chris Lattner22ee3eb2002-05-24 20:42:13 +0000363 return Changed;
364}