e4bfcb91141f6e71537fff398b69facdaf4b3985
[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"
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 static bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,
40                              Function *Concrete) {
41   bool Changed = false;
42   for (unsigned i = 0; i != Globals.size(); ++i)
43     if (Globals[i] != Concrete) {
44       Function *Old = cast<Function>(Globals[i]);
45       const FunctionType *OldMT = Old->getFunctionType();
46       const FunctionType *ConcreteMT = Concrete->getFunctionType();
47       
48       if (OldMT->getParamTypes().size() > ConcreteMT->getParamTypes().size() &&
49           !ConcreteMT->isVarArg())
50         if (!Old->use_empty()) {
51           std::cerr << "WARNING: Linking function '" << Old->getName()
52                     << "' is causing arguments to be dropped.\n";
53           std::cerr << "WARNING: Prototype: ";
54           WriteAsOperand(std::cerr, Old);
55           std::cerr << " resolved to ";
56           WriteAsOperand(std::cerr, Concrete);
57           std::cerr << "\n";
58         }
59       
60       // Check to make sure that if there are specified types, that they
61       // match...
62       //
63       unsigned NumArguments = std::min(OldMT->getParamTypes().size(),
64                                        ConcreteMT->getParamTypes().size());
65
66       if (!Old->use_empty() && !Concrete->use_empty())
67         for (unsigned i = 0; i < NumArguments; ++i)
68           if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i]) {
69             std::cerr << "WARNING: Function [" << Old->getName()
70                       << "]: Parameter types conflict for: '" << OldMT
71                       << "' and '" << ConcreteMT << "'\n";
72             return Changed;
73           }
74       
75       // Attempt to convert all of the uses of the old function to the concrete
76       // form of the function.  If there is a use of the fn that we don't
77       // understand here we punt to avoid making a bad transformation.
78       //
79       // At this point, we know that the return values are the same for our two
80       // functions and that the Old function has no varargs fns specified.  In
81       // otherwords it's just <retty> (...)
82       //
83       if (!Old->use_empty()) {  // Avoid making the CPR unless we really need it
84         Value *Replacement = Concrete;
85         if (Concrete->getType() != Old->getType())
86           Replacement = ConstantExpr::getCast(ConstantPointerRef::get(Concrete),
87                                               Old->getType());
88         NumResolved += Old->use_size();
89         Old->replaceAllUsesWith(Replacement);
90       }
91
92       // Since there are no uses of Old anymore, remove it from the module.
93       M.getFunctionList().erase(Old);
94     }
95   return Changed;
96 }
97
98
99 static bool ResolveGlobalVariables(Module &M,
100                                    std::vector<GlobalValue*> &Globals,
101                                    GlobalVariable *Concrete) {
102   bool Changed = false;
103   assert(isa<ArrayType>(Concrete->getType()->getElementType()) &&
104          "Concrete version should be an array type!");
105
106   // Get the type of the things that may be resolved to us...
107   const ArrayType *CATy =cast<ArrayType>(Concrete->getType()->getElementType());
108   const Type *AETy = CATy->getElementType();
109
110   Constant *CCPR = ConstantPointerRef::get(Concrete);
111
112   for (unsigned i = 0; i != Globals.size(); ++i)
113     if (Globals[i] != Concrete) {
114       GlobalVariable *Old = cast<GlobalVariable>(Globals[i]);
115       const ArrayType *OATy = cast<ArrayType>(Old->getType()->getElementType());
116       if (OATy->getElementType() != AETy || OATy->getNumElements() != 0) {
117         std::cerr << "WARNING: Two global variables exist with the same name "
118                   << "that cannot be resolved!\n";
119         return false;
120       }
121
122       Old->replaceAllUsesWith(ConstantExpr::getCast(CCPR, Old->getType()));
123
124       // Since there are no uses of Old anymore, remove it from the module.
125       M.getGlobalList().erase(Old);
126
127       ++NumGlobals;
128       Changed = true;
129     }
130   return Changed;
131 }
132
133 static bool ProcessGlobalsWithSameName(Module &M,
134                                        std::vector<GlobalValue*> &Globals) {
135   assert(!Globals.empty() && "Globals list shouldn't be empty here!");
136
137   bool isFunction = isa<Function>(Globals[0]);   // Is this group all functions?
138   GlobalValue *Concrete = 0;  // The most concrete implementation to resolve to
139
140   assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&
141          "Should either be function or gvar!");
142
143   for (unsigned i = 0; i != Globals.size(); ) {
144     if (isa<Function>(Globals[i]) != isFunction) {
145       std::cerr << "WARNING: Found function and global variable with the "
146                 << "same name: '" << Globals[i]->getName() << "'.\n";
147       return false;                 // Don't know how to handle this, bail out!
148     }
149
150     if (isFunction) {
151       // For functions, we look to merge functions definitions of "int (...)"
152       // to 'int (int)' or 'int ()' or whatever else is not completely generic.
153       //
154       Function *F = cast<Function>(Globals[i]);
155       if (!F->isExternal()) {
156         if (Concrete && !Concrete->isExternal())
157           return false;   // Found two different functions types.  Can't choose!
158         
159         Concrete = Globals[i];
160       } else if (Concrete) {
161         if (Concrete->isExternal()) // If we have multiple external symbols...x
162           if (F->getFunctionType()->getNumParams() > 
163               cast<Function>(Concrete)->getFunctionType()->getNumParams())
164             Concrete = F;  // We are more concrete than "Concrete"!
165
166       } else {
167         Concrete = F;
168       }
169     } else {
170       // For global variables, we have to merge C definitions int A[][4] with
171       // int[6][4].  A[][4] is represented as A[0][4] by the CFE.
172       GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
173       if (!isa<ArrayType>(GV->getType()->getElementType())) {
174         Concrete = 0;
175         break;  // Non array's cannot be compatible with other types.
176       } else if (Concrete == 0) {
177         Concrete = GV;
178       } else {
179         // Must have different types... allow merging A[0][4] w/ A[6][4] if
180         // A[0][4] is external.
181         const ArrayType *NAT = cast<ArrayType>(GV->getType()->getElementType());
182         const ArrayType *CAT =
183           cast<ArrayType>(Concrete->getType()->getElementType());
184
185         if (NAT->getElementType() != CAT->getElementType()) {
186           Concrete = 0;  // Non-compatible types
187           break;
188         } else if (NAT->getNumElements() == 0 && GV->isExternal()) {
189           // Concrete remains the same
190         } else if (CAT->getNumElements() == 0 && Concrete->isExternal()) {
191           Concrete = GV;   // Concrete becomes GV
192         } else {
193           Concrete = 0;    // Cannot merge these types...
194           break;
195         }
196       }
197     }
198     ++i;
199   }
200
201   if (Globals.size() > 1) {         // Found a multiply defined global...
202     // If there are no external declarations, and there is at most one
203     // externally visible instance of the global, then there is nothing to do.
204     //
205     bool HasExternal = false;
206     unsigned NumInstancesWithExternalLinkage = 0;
207
208     for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
209       if (Globals[i]->isExternal())
210         HasExternal = true;
211       else if (!Globals[i]->hasInternalLinkage())
212         NumInstancesWithExternalLinkage++;
213     }
214     
215     if (!HasExternal && NumInstancesWithExternalLinkage <= 1)
216       return false;  // Nothing to do?  Must have multiple internal definitions.
217
218
219     // We should find exactly one concrete function definition, which is
220     // probably the implementation.  Change all of the function definitions and
221     // uses to use it instead.
222     //
223     if (!Concrete) {
224       std::cerr << "WARNING: Found global types that are not compatible:\n";
225       for (unsigned i = 0; i < Globals.size(); ++i) {
226         std::cerr << "\t" << Globals[i]->getType()->getDescription() << " %"
227                   << Globals[i]->getName() << "\n";
228       }
229       std::cerr << "  No linkage of globals named '" << Globals[0]->getName()
230                 << "' performed!\n";
231       return false;
232     }
233
234     if (isFunction)
235       return ResolveFunctions(M, Globals, cast<Function>(Concrete));
236     else
237       return ResolveGlobalVariables(M, Globals,
238                                     cast<GlobalVariable>(Concrete));
239   }
240   return false;
241 }
242
243 bool FunctionResolvingPass::run(Module &M) {
244   SymbolTable &ST = M.getSymbolTable();
245
246   std::map<std::string, std::vector<GlobalValue*> > Globals;
247
248   // Loop over the entries in the symbol table. If an entry is a func pointer,
249   // then add it to the Functions map.  We do a two pass algorithm here to avoid
250   // problems with iterators getting invalidated if we did a one pass scheme.
251   //
252   for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)
253     if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {
254       SymbolTable::VarMap &Plane = I->second;
255       for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
256            PI != PE; ++PI) {
257         GlobalValue *GV = cast<GlobalValue>(PI->second);
258         assert(PI->first == GV->getName() &&
259                "Global name and symbol table do not agree!");
260         Globals[PI->first].push_back(GV);
261       }
262     }
263
264   bool Changed = false;
265
266   // Now we have a list of all functions with a particular name.  If there is
267   // more than one entry in a list, merge the functions together.
268   //
269   for (std::map<std::string, std::vector<GlobalValue*> >::iterator
270          I = Globals.begin(), E = Globals.end(); I != E; ++I)
271     Changed |= ProcessGlobalsWithSameName(M, I->second);
272
273   // Now loop over all of the globals, checking to see if any are trivially
274   // dead.  If so, remove them now.
275
276   for (Module::iterator I = M.begin(), E = M.end(); I != E; )
277     if (I->isExternal() && I->use_empty()) {
278       Function *F = I;
279       ++I;
280       M.getFunctionList().erase(F);
281       ++NumResolved;
282       Changed = true;
283     } else {
284       ++I;
285     }
286
287   for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )
288     if (I->isExternal() && I->use_empty()) {
289       GlobalVariable *GV = I;
290       ++I;
291       M.getGlobalList().erase(GV);
292       ++NumGlobals;
293       Changed = true;
294     } else {
295       ++I;
296     }
297
298   return Changed;
299 }