Actually print the function _name_ if there is a problem
[oota-llvm.git] / lib / Transforms / IPO / FunctionResolution.cpp
1 //===- 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
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"
23 #include <algorithm>
24
25 namespace {
26   Statistic<>NumResolved("funcresolve", "Number of varargs functions resolved");
27   Statistic<> NumGlobals("funcresolve", "Number of global variables resolved");
28
29   struct FunctionResolvingPass : public Pass {
30     bool run(Module &M);
31   };
32   RegisterOpt<FunctionResolvingPass> X("funcresolve", "Resolve Functions");
33 }
34
35 Pass *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 //
42 static void ConvertCallTo(CallInst *CI, Function *Dest) {
43   const FunctionType::ParamTypes &ParamTys =
44     Dest->getFunctionType()->getParamTypes();
45   BasicBlock *BB = CI->getParent();
46
47   // Keep an iterator to where we want to insert cast instructions if the
48   // argument types don't agree.
49   //
50   BasicBlock::iterator BBI = CI;
51   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   }
60
61   std::vector<Value*> Params;
62
63   // Convert all of the call arguments over... inserting cast instructions if
64   // the types are not compatible.
65   for (unsigned i = 1; i <= ParamTys.size(); ++i) {
66     Value *V = CI->getOperand(i);
67
68     if (V->getType() != ParamTys[i-1])  // Must insert a cast...
69       V = new CastInst(V, ParamTys[i-1], "argcast", BBI);
70
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   //
77   Instruction *NewCall = new CallInst(Dest, Params, "", BBI);
78
79   // Remove the old call instruction from the program...
80   BB->getInstList().remove(BBI);
81
82   // Transfer the name over...
83   if (NewCall->getType() != Type::VoidTy)
84     NewCall->setName(CI->getName());
85
86   // 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
100     // special here, because it will automatically be ignored.
101   } else {
102     // 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()) {
107       // Insert the new cast instruction...
108       CastInst *NewCast = new CastInst(NewCall, CI->getType(),
109                                        NewCall->getName(), BBI);
110       CI->replaceAllUsesWith(NewCast);
111     }
112   }
113
114   // The old instruction is no longer needed, destroy it!
115   delete CI;
116 }
117
118
119 static bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,
120                              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]) {
137           std::cerr << "funcresolve: Function [" << Old->getName()
138                     << "]: Parameter types conflict for: '" << OldMT
139                     << "' and '" << ConcreteMT << "'\n";
140           return Changed;
141         }
142       
143       // Attempt to convert all of the uses of the old function to the
144       // concrete form of the function.  If there is a use of the fn that
145       // we don't understand here we punt to avoid making a bad
146       // transformation.
147       //
148       // At this point, we know that the return values are the same for
149       // our two functions and that the Old function has no varargs fns
150       // specified.  In otherwords it's just <retty> (...)
151       //
152       for (unsigned i = 0; i < Old->use_size(); ) {
153         User *U = *(Old->use_begin()+i);
154         if (CastInst *CI = dyn_cast<CastInst>(U)) {
155           // Convert casts directly
156           assert(CI->getOperand(0) == Old);
157           CI->setOperand(0, Concrete);
158           Changed = true;
159           ++NumResolved;
160         } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
161           // Can only fix up calls TO the argument, not args passed in.
162           if (CI->getCalledValue() == Old) {
163             ConvertCallTo(CI, Concrete);
164             Changed = true;
165             ++NumResolved;
166           } else {
167             std::cerr << "Couldn't cleanup this function call, must be an"
168                       << " argument or something!" << CI;
169             ++i;
170           }
171         } else {
172           std::cerr << "Cannot convert use of function: " << U << "\n";
173           ++i;
174         }
175       }
176     }
177   return Changed;
178 }
179
180
181 static bool ResolveGlobalVariables(Module &M,
182                                    std::vector<GlobalValue*> &Globals,
183                                    GlobalVariable *Concrete) {
184   bool Changed = false;
185   assert(isa<ArrayType>(Concrete->getType()->getElementType()) &&
186          "Concrete version should be an array type!");
187
188   // Get the type of the things that may be resolved to us...
189   const Type *AETy =
190     cast<ArrayType>(Concrete->getType()->getElementType())->getElementType();
191
192   std::vector<Constant*> Args;
193   Args.push_back(Constant::getNullValue(Type::LongTy));
194   Args.push_back(Constant::getNullValue(Type::LongTy));
195   ConstantExpr *Replacement =
196     ConstantExpr::getGetElementPtr(ConstantPointerRef::get(Concrete), Args);
197   
198   for (unsigned i = 0; i != Globals.size(); ++i)
199     if (Globals[i] != Concrete) {
200       GlobalVariable *Old = cast<GlobalVariable>(Globals[i]);
201       if (Old->getType()->getElementType() != AETy) {
202         std::cerr << "WARNING: Two global variables exist with the same name "
203                   << "that cannot be resolved!\n";
204         return false;
205       }
206
207       // In this case, Old is a pointer to T, Concrete is a pointer to array of
208       // T.  Because of this, replace all uses of Old with a constantexpr
209       // getelementptr that returns the address of the first element of the
210       // array.
211       //
212       Old->replaceAllUsesWith(Replacement);
213       // Since there are no uses of Old anymore, remove it from the module.
214       M.getGlobalList().erase(Old);
215
216       ++NumGlobals;
217       Changed = true;
218     }
219   return Changed;
220 }
221
222 static bool ProcessGlobalsWithSameName(Module &M,
223                                        std::vector<GlobalValue*> &Globals) {
224   assert(!Globals.empty() && "Globals list shouldn't be empty here!");
225
226   bool isFunction = isa<Function>(Globals[0]);   // Is this group all functions?
227   bool Changed = false;
228   GlobalValue *Concrete = 0;  // The most concrete implementation to resolve to
229
230   assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&
231          "Should either be function or gvar!");
232
233   for (unsigned i = 0; i != Globals.size(); ) {
234     if (isa<Function>(Globals[i]) != isFunction) {
235       std::cerr << "WARNING: Found function and global variable with the "
236                 << "same name: '" << Globals[i]->getName() << "'.\n";
237       return false;                 // Don't know how to handle this, bail out!
238     }
239
240     if (isFunction) {
241       // For functions, we look to merge functions definitions of "int (...)"
242       // to 'int (int)' or 'int ()' or whatever else is not completely generic.
243       //
244       Function *F = cast<Function>(Globals[i]);
245       if (!F->isExternal()) {
246         if (Concrete && !Concrete->isExternal())
247           return false;   // Found two different functions types.  Can't choose!
248         
249         Concrete = Globals[i];
250       } else if (Concrete) {
251         if (Concrete->isExternal()) // If we have multiple external symbols...x
252           if (F->getFunctionType()->getNumParams() > 
253               cast<Function>(Concrete)->getFunctionType()->getNumParams())
254             Concrete = F;  // We are more concrete than "Concrete"!
255
256       } else {
257         Concrete = F;
258       }
259       ++i;
260     } else {
261       // For global variables, we have to merge C definitions int A[][4] with
262       // int[6][4]
263       GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
264       if (Concrete == 0) {
265         if (isa<ArrayType>(GV->getType()->getElementType()))
266           Concrete = GV;
267       } else {    // Must have different types... one is an array of the other?
268         const ArrayType *AT =
269           dyn_cast<ArrayType>(GV->getType()->getElementType());
270
271         // If GV is an array of Concrete, then GV is the array.
272         if (AT && AT->getElementType() == Concrete->getType()->getElementType())
273           Concrete = GV;
274         else {
275           // Concrete must be an array type, check to see if the element type of
276           // concrete is already GV.
277           AT = cast<ArrayType>(Concrete->getType()->getElementType());
278           if (AT->getElementType() != GV->getType()->getElementType())
279             Concrete = 0;           // Don't know how to handle it!
280         }
281       }
282       
283       ++i;
284     }
285   }
286
287   if (Globals.size() > 1) {         // Found a multiply defined global...
288     // We should find exactly one concrete function definition, which is
289     // probably the implementation.  Change all of the function definitions and
290     // uses to use it instead.
291     //
292     if (!Concrete) {
293       std::cerr << "WARNING: Found function types that are not compatible:\n";
294       for (unsigned i = 0; i < Globals.size(); ++i) {
295         std::cerr << "\t" << Globals[i]->getType()->getDescription() << " %"
296                   << Globals[i]->getName() << "\n";
297       }
298       std::cerr << "  No linkage of globals named '" << Globals[0]->getName()
299                 << "' performed!\n";
300       return Changed;
301     }
302
303     if (isFunction)
304       return Changed | ResolveFunctions(M, Globals, cast<Function>(Concrete));
305     else
306       return Changed | ResolveGlobalVariables(M, Globals,
307                                               cast<GlobalVariable>(Concrete));
308   }
309   return Changed;
310 }
311
312 bool FunctionResolvingPass::run(Module &M) {
313   SymbolTable &ST = M.getSymbolTable();
314
315   std::map<std::string, std::vector<GlobalValue*> > Globals;
316
317   // Loop over the entries in the symbol table. If an entry is a func pointer,
318   // then add it to the Functions map.  We do a two pass algorithm here to avoid
319   // problems with iterators getting invalidated if we did a one pass scheme.
320   //
321   for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)
322     if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {
323       SymbolTable::VarMap &Plane = I->second;
324       for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
325            PI != PE; ++PI) {
326         GlobalValue *GV = cast<GlobalValue>(PI->second);
327         assert(PI->first == GV->getName() &&
328                "Global name and symbol table do not agree!");
329         if (GV->hasExternalLinkage())  // Only resolve decls to external fns
330           Globals[PI->first].push_back(GV);
331       }
332     }
333
334   bool Changed = false;
335
336   // Now we have a list of all functions with a particular name.  If there is
337   // more than one entry in a list, merge the functions together.
338   //
339   for (std::map<std::string, std::vector<GlobalValue*> >::iterator
340          I = Globals.begin(), E = Globals.end(); I != E; ++I)
341     Changed |= ProcessGlobalsWithSameName(M, I->second);
342
343   // Now loop over all of the globals, checking to see if any are trivially
344   // dead.  If so, remove them now.
345
346   for (Module::iterator I = M.begin(), E = M.end(); I != E; )
347     if (I->isExternal() && I->use_empty()) {
348       Function *F = I;
349       ++I;
350       M.getFunctionList().erase(F);
351       ++NumResolved;
352       Changed = true;
353     } else {
354       ++I;
355     }
356
357   for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )
358     if (I->isExternal() && I->use_empty()) {
359       GlobalVariable *GV = I;
360       ++I;
361       M.getGlobalList().erase(GV);
362       ++NumGlobals;
363       Changed = true;
364     } else {
365       ++I;
366     }
367
368   return Changed;
369 }