Implement: FunctionResolve/2003-04-18-ForwardDeclGlobal.ll
[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   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"
55               << " parameters.\n";
56     std::cerr << "WARNING: In function '"
57               << CI->getParent()->getParent()->getName() << "': call: " << *CI;
58     std::cerr << "Function resolved to: ";
59     WriteAsOperand(std::cerr, Dest);
60     std::cerr << "\n";
61     if (NumArgsToCopy > ParamTys.size())
62       NumArgsToCopy = ParamTys.size();
63   }
64
65   std::vector<Value*> Params;
66
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);
71
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);
75     }
76
77     Params.push_back(V);
78   }
79
80   // Replace the old call instruction with a new call instruction that calls
81   // the real function.
82   //
83   Instruction *NewCall = new CallInst(Dest, Params, "", CI);
84   std::string Name = CI->getName(); CI->setName("");
85
86   // Transfer the name over...
87   if (NewCall->getType() != Type::VoidTy)
88     NewCall->setName(Name);
89
90   // Replace uses of the old instruction with the appropriate values...
91   //
92   if (NewCall->getType() == CI->getType()) {
93     CI->replaceAllUsesWith(NewCall);
94     NewCall->setName(Name);
95
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
100     // values.
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.
105   } else {
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.
109     //
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);
114     }
115   }
116
117   // The old instruction is no longer needed, destroy it!
118   BB->getInstList().erase(CI);
119 }
120
121
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();
130       
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);
140           std::cerr << "\n";
141         }
142       
143       // Check to make sure that if there are specified types, that they
144       // match...
145       //
146       unsigned NumArguments = std::min(OldMT->getParamTypes().size(),
147                                        ConcreteMT->getParamTypes().size());
148
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";
155             return Changed;
156           }
157       
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
161       // transformation.
162       //
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> (...)
166       //
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);
173           Changed = true;
174           ++NumResolved;
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);
179             Changed = true;
180             ++NumResolved;
181           } else {
182             std::cerr << "Couldn't cleanup this function call, must be an"
183                       << " argument or something!" << CI;
184             ++i;
185           }
186         } else {
187           std::cerr << "Cannot convert use of function: " << U << "\n";
188           ++i;
189         }
190       }
191     }
192   return Changed;
193 }
194
195
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!");
202
203   // Get the type of the things that may be resolved to us...
204   const ArrayType *CATy =cast<ArrayType>(Concrete->getType()->getElementType());
205   const Type *AETy = CATy->getElementType();
206
207   Constant *CCPR = ConstantPointerRef::get(Concrete);
208
209   for (unsigned i = 0; i != Globals.size(); ++i)
210     if (Globals[i] != Concrete) {
211       GlobalVariable *Old = cast<GlobalVariable>(Globals[i]);
212       const ArrayType *OATy = cast<ArrayType>(Old->getType()->getElementType());
213       if (OATy->getElementType() != AETy || OATy->getNumElements() != 0) {
214         std::cerr << "WARNING: Two global variables exist with the same name "
215                   << "that cannot be resolved!\n";
216         return false;
217       }
218
219       Old->replaceAllUsesWith(ConstantExpr::getCast(CCPR, Old->getType()));
220
221       // Since there are no uses of Old anymore, remove it from the module.
222       M.getGlobalList().erase(Old);
223
224       ++NumGlobals;
225       Changed = true;
226     }
227   return Changed;
228 }
229
230 static bool ProcessGlobalsWithSameName(Module &M,
231                                        std::vector<GlobalValue*> &Globals) {
232   assert(!Globals.empty() && "Globals list shouldn't be empty here!");
233
234   bool isFunction = isa<Function>(Globals[0]);   // Is this group all functions?
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
247     if (isFunction) {
248       // 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]);
252       if (!F->isExternal()) {
253         if (Concrete && !Concrete->isExternal())
254           return false;   // Found two different functions types.  Can't choose!
255         
256         Concrete = Globals[i];
257       } 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;
265       }
266     } else {
267       // For global variables, we have to merge C definitions int A[][4] with
268       // int[6][4].  A[][4] is represented as A[0][4] by the CFE.
269       GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
270       if (!isa<ArrayType>(GV->getType()->getElementType())) {
271         Concrete = 0;
272         break;  // Non array's cannot be compatible with other types.
273       } else if (Concrete == 0) {
274         Concrete = GV;
275       } else {
276         // Must have different types... allow merging A[0][4] w/ A[6][4] if
277         // A[0][4] is external.
278         const ArrayType *NAT = cast<ArrayType>(GV->getType()->getElementType());
279         const ArrayType *CAT =
280           cast<ArrayType>(Concrete->getType()->getElementType());
281
282         if (NAT->getElementType() != CAT->getElementType()) {
283           Concrete = 0;  // Non-compatible types
284           break;
285         } else if (NAT->getNumElements() == 0 && GV->isExternal()) {
286           // Concrete remains the same
287         } else if (CAT->getNumElements() == 0 && Concrete->isExternal()) {
288           Concrete = GV;   // Concrete becomes GV
289         } else {
290           Concrete = 0;    // Cannot merge these types...
291           break;
292         }
293       }
294     }
295     ++i;
296   }
297
298   if (Globals.size() > 1) {         // Found a multiply defined global...
299     // We should find exactly one concrete function definition, which is
300     // probably the implementation.  Change all of the function definitions and
301     // uses to use it instead.
302     //
303     if (!Concrete) {
304       std::cerr << "WARNING: Found global types that are not compatible:\n";
305       for (unsigned i = 0; i < Globals.size(); ++i) {
306         std::cerr << "\t" << Globals[i]->getType()->getDescription() << " %"
307                   << Globals[i]->getName() << "\n";
308       }
309       std::cerr << "  No linkage of globals named '" << Globals[0]->getName()
310                 << "' performed!\n";
311       return false;
312     }
313
314     if (isFunction)
315       return ResolveFunctions(M, Globals, cast<Function>(Concrete));
316     else
317       return ResolveGlobalVariables(M, Globals,
318                                     cast<GlobalVariable>(Concrete));
319   }
320   return false;
321 }
322
323 bool FunctionResolvingPass::run(Module &M) {
324   SymbolTable &ST = M.getSymbolTable();
325
326   std::map<std::string, std::vector<GlobalValue*> > Globals;
327
328   // Loop over the entries in the symbol table. If an entry is a func pointer,
329   // then add it to the Functions map.  We do a two pass algorithm here to avoid
330   // problems with iterators getting invalidated if we did a one pass scheme.
331   //
332   for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)
333     if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {
334       SymbolTable::VarMap &Plane = I->second;
335       for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
336            PI != PE; ++PI) {
337         GlobalValue *GV = cast<GlobalValue>(PI->second);
338         assert(PI->first == GV->getName() &&
339                "Global name and symbol table do not agree!");
340         if (GV->hasExternalLinkage())  // Only resolve decls to external fns
341           Globals[PI->first].push_back(GV);
342       }
343     }
344
345   bool Changed = false;
346
347   // Now we have a list of all functions with a particular name.  If there is
348   // more than one entry in a list, merge the functions together.
349   //
350   for (std::map<std::string, std::vector<GlobalValue*> >::iterator
351          I = Globals.begin(), E = Globals.end(); I != E; ++I)
352     Changed |= ProcessGlobalsWithSameName(M, I->second);
353
354   // Now loop over all of the globals, checking to see if any are trivially
355   // dead.  If so, remove them now.
356
357   for (Module::iterator I = M.begin(), E = M.end(); I != E; )
358     if (I->isExternal() && I->use_empty()) {
359       Function *F = I;
360       ++I;
361       M.getFunctionList().erase(F);
362       ++NumResolved;
363       Changed = true;
364     } else {
365       ++I;
366     }
367
368   for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )
369     if (I->isExternal() && I->use_empty()) {
370       GlobalVariable *GV = I;
371       ++I;
372       M.getGlobalList().erase(GV);
373       ++NumGlobals;
374       Changed = true;
375     } else {
376       ++I;
377     }
378
379   return Changed;
380 }