1 //===- FunctionResolution.cpp - Resolve declarations to implementations ---===//
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:
6 // declare void %foo(...)
7 // void %foo(int, int) { ... }
9 // because of the way things are declared in C. If this is the case, patch
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/IPO.h"
15 #include "llvm/Module.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Pass.h"
19 #include "llvm/iOther.h"
20 #include "llvm/Constants.h"
21 #include "Support/Statistic.h"
29 Statistic<>NumResolved("funcresolve", "Number of varargs functions resolved");
30 Statistic<> NumGlobals("funcresolve", "Number of global variables resolved");
32 struct FunctionResolvingPass : public Pass {
35 RegisterOpt<FunctionResolvingPass> X("funcresolve", "Resolve Functions");
38 Pass *createFunctionResolvingPass() {
39 return new FunctionResolvingPass();
42 // ConvertCallTo - Convert a call to a varargs function with no arg types
43 // specified to a concrete nonvarargs function.
45 static void ConvertCallTo(CallInst *CI, Function *Dest) {
46 const FunctionType::ParamTypes &ParamTys =
47 Dest->getFunctionType()->getParamTypes();
48 BasicBlock *BB = CI->getParent();
50 // Keep an iterator to where we want to insert cast instructions if the
51 // argument types don't agree.
53 BasicBlock::iterator BBI = CI;
54 assert(CI->getNumOperands()-1 == ParamTys.size() &&
55 "Function calls resolved funny somehow, incompatible number of args");
57 vector<Value*> Params;
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);
64 if (V->getType() != ParamTys[i-1]) // Must insert a cast...
65 V = new CastInst(V, ParamTys[i-1], "argcast", BBI);
70 // Replace the old call instruction with a new call instruction that calls
73 Instruction *NewCall = new CallInst(Dest, Params, "", BBI);
75 // Remove the old call instruction from the program...
76 BB->getInstList().remove(BBI);
78 // Transfer the name over...
79 if (NewCall->getType() != Type::VoidTy)
80 NewCall->setName(CI->getName());
82 // Replace uses of the old instruction with the appropriate values...
84 if (NewCall->getType() == CI->getType()) {
85 CI->replaceAllUsesWith(NewCall);
86 NewCall->setName(CI->getName());
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
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
96 // special here, because it will automatically be ignored.
98 // 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.
102 if (!CI->use_empty()) {
103 // Insert the new cast instruction...
104 CastInst *NewCast = new CastInst(NewCall, CI->getType(),
105 NewCall->getName(), BBI);
106 CI->replaceAllUsesWith(NewCast);
110 // The old instruction is no longer needed, destroy it!
115 static 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();
124 assert(OldMT->getParamTypes().size() <=
125 ConcreteMT->getParamTypes().size() &&
126 "Concrete type must have more specified parameters!");
128 // Check to make sure that if there are specified types, that they
131 for (unsigned i = 0; i < OldMT->getParamTypes().size(); ++i)
132 if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i]) {
133 cerr << "Parameter types conflict for: '" << OldMT
134 << "' and '" << ConcreteMT << "'\n";
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
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> (...)
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);
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);
162 cerr << "Couldn't cleanup this function call, must be an"
163 << " argument or something!" << CI;
167 cerr << "Cannot convert use of function: " << U << "\n";
176 static 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!");
182 // Get the type of the things that may be resolved to us...
184 cast<ArrayType>(Concrete->getType()->getElementType())->getElementType();
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);
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";
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
206 Old->replaceAllUsesWith(Replacement);
207 // Since there are no uses of Old anymore, remove it from the module.
208 M.getGlobalList().erase(Old);
216 static bool ProcessGlobalsWithSameName(Module &M,
217 vector<GlobalValue*> &Globals) {
218 assert(!Globals.empty() && "Globals list shouldn't be empty here!");
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
224 assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&
225 "Should either be function or gvar!");
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!
235 // For functions, we look to merge functions definitions of "int (...)"
236 // to 'int (int)' or 'int ()' or whatever else is not completely generic.
238 Function *F = cast<Function>(Globals[i]);
239 if (!F->isExternal()) {
240 if (Concrete && !Concrete->isExternal())
241 return false; // Found two different functions types. Can't choose!
243 Concrete = Globals[i];
244 } 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"!
255 // For global variables, we have to merge C definitions int A[][4] with
257 GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
259 if (isa<ArrayType>(GV->getType()->getElementType()))
261 } else { // Must have different types... one is an array of the other?
262 const ArrayType *AT =
263 dyn_cast<ArrayType>(GV->getType()->getElementType());
265 // If GV is an array of Concrete, then GV is the array.
266 if (AT && AT->getElementType() == Concrete->getType()->getElementType())
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!
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.
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";
292 cerr << " No linkage of globals named '" << Globals[0]->getName()
298 return Changed | ResolveFunctions(M, Globals, cast<Function>(Concrete));
300 return Changed | ResolveGlobalVariables(M, Globals,
301 cast<GlobalVariable>(Concrete));
306 bool FunctionResolvingPass::run(Module &M) {
307 SymbolTable &ST = M.getSymbolTable();
309 std::map<string, vector<GlobalValue*> > Globals;
311 // Loop over the entries in the symbol table. If an entry is a func pointer,
312 // then add it to the Functions map. We do a two pass algorithm here to avoid
313 // problems with iterators getting invalidated if we did a one pass scheme.
315 for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)
316 if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {
317 SymbolTable::VarMap &Plane = I->second;
318 for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
320 GlobalValue *GV = cast<GlobalValue>(PI->second);
321 assert(PI->first == GV->getName() &&
322 "Global name and symbol table do not agree!");
323 if (GV->hasExternalLinkage()) // Only resolve decls to external fns
324 Globals[PI->first].push_back(GV);
328 bool Changed = false;
330 // Now we have a list of all functions with a particular name. If there is
331 // more than one entry in a list, merge the functions together.
333 for (std::map<string, vector<GlobalValue*> >::iterator I = Globals.begin(),
334 E = Globals.end(); I != E; ++I)
335 Changed |= ProcessGlobalsWithSameName(M, I->second);
337 // Now loop over all of the globals, checking to see if any are trivially
338 // dead. If so, remove them now.
340 for (Module::iterator I = M.begin(), E = M.end(); I != E; )
341 if (I->isExternal() && I->use_empty()) {
344 M.getFunctionList().erase(F);
351 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )
352 if (I->isExternal() && I->use_empty()) {
353 GlobalVariable *GV = I;
355 M.getGlobalList().erase(GV);