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 "llvm/Assembly/Writer.h" // FIXME: remove when varargs implemented
22 #include "Support/Statistic.h"
26 Statistic<>NumResolved("funcresolve", "Number of varargs functions resolved");
27 Statistic<> NumGlobals("funcresolve", "Number of global variables resolved");
29 struct FunctionResolvingPass : public Pass {
32 RegisterOpt<FunctionResolvingPass> X("funcresolve", "Resolve Functions");
35 Pass *createFunctionResolvingPass() {
36 return new FunctionResolvingPass();
39 // ConvertCallTo - Convert a call to a varargs function with no arg types
40 // specified to a concrete nonvarargs function.
42 static void ConvertCallTo(CallInst *CI, Function *Dest) {
43 const FunctionType::ParamTypes &ParamTys =
44 Dest->getFunctionType()->getParamTypes();
45 BasicBlock *BB = CI->getParent();
47 // Keep an iterator to where we want to insert cast instructions if the
48 // argument types don't agree.
50 unsigned NumArgsToCopy = CI->getNumOperands()-1;
51 if (NumArgsToCopy != ParamTys.size() &&
52 !(NumArgsToCopy > ParamTys.size() &&
53 Dest->getFunctionType()->isVarArg())) {
54 std::cerr << "WARNING: Call arguments do not match expected number of"
56 std::cerr << "WARNING: In function '"
57 << CI->getParent()->getParent()->getName() << "': call: " << *CI;
58 std::cerr << "Function resolved to: ";
59 WriteAsOperand(std::cerr, Dest);
61 if (NumArgsToCopy > ParamTys.size())
62 NumArgsToCopy = ParamTys.size();
65 std::vector<Value*> Params;
67 // Convert all of the call arguments over... inserting cast instructions if
68 // the types are not compatible.
69 for (unsigned i = 1; i <= NumArgsToCopy; ++i) {
70 Value *V = CI->getOperand(i);
72 if (i-1 < ParamTys.size() && V->getType() != ParamTys[i-1]) {
73 // Must insert a cast...
74 V = new CastInst(V, ParamTys[i-1], "argcast", CI);
80 // Replace the old call instruction with a new call instruction that calls
83 Instruction *NewCall = new CallInst(Dest, Params, "", CI);
84 std::string Name = CI->getName(); CI->setName("");
86 // Transfer the name over...
87 if (NewCall->getType() != Type::VoidTy)
88 NewCall->setName(Name);
90 // Replace uses of the old instruction with the appropriate values...
92 if (NewCall->getType() == CI->getType()) {
93 CI->replaceAllUsesWith(NewCall);
94 NewCall->setName(Name);
96 } else if (NewCall->getType() == Type::VoidTy) {
97 // Resolved function does not return a value but the prototype does. This
98 // often occurs because undefined functions default to returning integers.
99 // Just replace uses of the call (which are broken anyway) with dummy
101 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
102 } else if (CI->getType() == Type::VoidTy) {
103 // If we are gaining a new return value, we don't have to do anything
104 // special here, because it will automatically be ignored.
106 // Insert a cast instruction to convert the return value of the function
107 // into it's new type. Of course we only need to do this if the return
108 // value of the function is actually USED.
110 if (!CI->use_empty()) {
111 // Insert the new cast instruction...
112 CastInst *NewCast = new CastInst(NewCall, CI->getType(), Name, CI);
113 CI->replaceAllUsesWith(NewCast);
117 // The old instruction is no longer needed, destroy it!
118 BB->getInstList().erase(CI);
122 static bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,
123 Function *Concrete) {
124 bool Changed = false;
125 for (unsigned i = 0; i != Globals.size(); ++i)
126 if (Globals[i] != Concrete) {
127 Function *Old = cast<Function>(Globals[i]);
128 const FunctionType *OldMT = Old->getFunctionType();
129 const FunctionType *ConcreteMT = Concrete->getFunctionType();
131 if (OldMT->getParamTypes().size() < ConcreteMT->getParamTypes().size() &&
132 !ConcreteMT->isVarArg())
133 if (!Old->use_empty()) {
134 std::cerr << "WARNING: Linking function '" << Old->getName()
135 << "' is causing arguments to be dropped.\n";
136 std::cerr << "WARNING: Prototype: ";
137 WriteAsOperand(std::cerr, Old);
138 std::cerr << " resolved to ";
139 WriteAsOperand(std::cerr, Concrete);
143 // Check to make sure that if there are specified types, that they
146 unsigned NumArguments = std::min(OldMT->getParamTypes().size(),
147 ConcreteMT->getParamTypes().size());
149 if (!Old->use_empty() && !Concrete->use_empty())
150 for (unsigned i = 0; i < NumArguments; ++i)
151 if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i]) {
152 std::cerr << "WARNING: Function [" << Old->getName()
153 << "]: Parameter types conflict for: '" << OldMT
154 << "' and '" << ConcreteMT << "'\n";
158 // Attempt to convert all of the uses of the old function to the
159 // concrete form of the function. If there is a use of the fn that
160 // we don't understand here we punt to avoid making a bad
163 // At this point, we know that the return values are the same for
164 // our two functions and that the Old function has no varargs fns
165 // specified. In otherwords it's just <retty> (...)
167 for (unsigned i = 0; i < Old->use_size(); ) {
168 User *U = *(Old->use_begin()+i);
169 if (CastInst *CI = dyn_cast<CastInst>(U)) {
170 // Convert casts directly
171 assert(CI->getOperand(0) == Old);
172 CI->setOperand(0, Concrete);
175 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
176 // Can only fix up calls TO the argument, not args passed in.
177 if (CI->getCalledValue() == Old) {
178 ConvertCallTo(CI, Concrete);
182 std::cerr << "Couldn't cleanup this function call, must be an"
183 << " argument or something!" << CI;
187 std::cerr << "Cannot convert use of function: " << U << "\n";
196 static bool ResolveGlobalVariables(Module &M,
197 std::vector<GlobalValue*> &Globals,
198 GlobalVariable *Concrete) {
199 bool Changed = false;
200 assert(isa<ArrayType>(Concrete->getType()->getElementType()) &&
201 "Concrete version should be an array type!");
203 // Get the type of the things that may be resolved to us...
205 cast<ArrayType>(Concrete->getType()->getElementType())->getElementType();
207 std::vector<Constant*> Args;
208 Args.push_back(Constant::getNullValue(Type::LongTy));
209 Args.push_back(Constant::getNullValue(Type::LongTy));
210 ConstantExpr *Replacement =
211 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(Concrete), Args);
213 for (unsigned i = 0; i != Globals.size(); ++i)
214 if (Globals[i] != Concrete) {
215 GlobalVariable *Old = cast<GlobalVariable>(Globals[i]);
216 if (Old->getType()->getElementType() != AETy) {
217 std::cerr << "WARNING: Two global variables exist with the same name "
218 << "that cannot be resolved!\n";
222 // In this case, Old is a pointer to T, Concrete is a pointer to array of
223 // T. Because of this, replace all uses of Old with a constantexpr
224 // getelementptr that returns the address of the first element of the
227 Old->replaceAllUsesWith(Replacement);
228 // Since there are no uses of Old anymore, remove it from the module.
229 M.getGlobalList().erase(Old);
237 static bool ProcessGlobalsWithSameName(Module &M,
238 std::vector<GlobalValue*> &Globals) {
239 assert(!Globals.empty() && "Globals list shouldn't be empty here!");
241 bool isFunction = isa<Function>(Globals[0]); // Is this group all functions?
242 bool Changed = false;
243 GlobalValue *Concrete = 0; // The most concrete implementation to resolve to
245 assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&
246 "Should either be function or gvar!");
248 for (unsigned i = 0; i != Globals.size(); ) {
249 if (isa<Function>(Globals[i]) != isFunction) {
250 std::cerr << "WARNING: Found function and global variable with the "
251 << "same name: '" << Globals[i]->getName() << "'.\n";
252 return false; // Don't know how to handle this, bail out!
256 // For functions, we look to merge functions definitions of "int (...)"
257 // to 'int (int)' or 'int ()' or whatever else is not completely generic.
259 Function *F = cast<Function>(Globals[i]);
260 if (!F->isExternal()) {
261 if (Concrete && !Concrete->isExternal())
262 return false; // Found two different functions types. Can't choose!
264 Concrete = Globals[i];
265 } else if (Concrete) {
266 if (Concrete->isExternal()) // If we have multiple external symbols...x
267 if (F->getFunctionType()->getNumParams() >
268 cast<Function>(Concrete)->getFunctionType()->getNumParams())
269 Concrete = F; // We are more concrete than "Concrete"!
276 // For global variables, we have to merge C definitions int A[][4] with
278 GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
280 if (isa<ArrayType>(GV->getType()->getElementType()))
282 } else { // Must have different types... one is an array of the other?
283 const ArrayType *AT =
284 dyn_cast<ArrayType>(GV->getType()->getElementType());
286 // If GV is an array of Concrete, then GV is the array.
287 if (AT && AT->getElementType() == Concrete->getType()->getElementType())
290 // Concrete must be an array type, check to see if the element type of
291 // concrete is already GV.
292 AT = cast<ArrayType>(Concrete->getType()->getElementType());
293 if (AT->getElementType() != GV->getType()->getElementType())
294 Concrete = 0; // Don't know how to handle it!
302 if (Globals.size() > 1) { // Found a multiply defined global...
303 // We should find exactly one concrete function definition, which is
304 // probably the implementation. Change all of the function definitions and
305 // uses to use it instead.
308 std::cerr << "WARNING: Found function types that are not compatible:\n";
309 for (unsigned i = 0; i < Globals.size(); ++i) {
310 std::cerr << "\t" << Globals[i]->getType()->getDescription() << " %"
311 << Globals[i]->getName() << "\n";
313 std::cerr << " No linkage of globals named '" << Globals[0]->getName()
319 return Changed | ResolveFunctions(M, Globals, cast<Function>(Concrete));
321 return Changed | ResolveGlobalVariables(M, Globals,
322 cast<GlobalVariable>(Concrete));
327 bool FunctionResolvingPass::run(Module &M) {
328 SymbolTable &ST = M.getSymbolTable();
330 std::map<std::string, std::vector<GlobalValue*> > Globals;
332 // Loop over the entries in the symbol table. If an entry is a func pointer,
333 // then add it to the Functions map. We do a two pass algorithm here to avoid
334 // problems with iterators getting invalidated if we did a one pass scheme.
336 for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)
337 if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {
338 SymbolTable::VarMap &Plane = I->second;
339 for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
341 GlobalValue *GV = cast<GlobalValue>(PI->second);
342 assert(PI->first == GV->getName() &&
343 "Global name and symbol table do not agree!");
344 if (GV->hasExternalLinkage()) // Only resolve decls to external fns
345 Globals[PI->first].push_back(GV);
349 bool Changed = false;
351 // Now we have a list of all functions with a particular name. If there is
352 // more than one entry in a list, merge the functions together.
354 for (std::map<std::string, std::vector<GlobalValue*> >::iterator
355 I = Globals.begin(), E = Globals.end(); I != E; ++I)
356 Changed |= ProcessGlobalsWithSameName(M, I->second);
358 // Now loop over all of the globals, checking to see if any are trivially
359 // dead. If so, remove them now.
361 for (Module::iterator I = M.begin(), E = M.end(); I != E; )
362 if (I->isExternal() && I->use_empty()) {
365 M.getFunctionList().erase(F);
372 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )
373 if (I->isExternal() && I->use_empty()) {
374 GlobalVariable *GV = I;
376 M.getGlobalList().erase(GV);