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 static bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,
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();
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);
60 // Check to make sure that if there are specified types, that they
63 unsigned NumArguments = std::min(OldMT->getParamTypes().size(),
64 ConcreteMT->getParamTypes().size());
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";
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.
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> (...)
83 Value *Replacement = Concrete;
84 if (Concrete->getType() != Old->getType())
85 Replacement = ConstantExpr::getCast(ConstantPointerRef::get(Concrete),
87 NumResolved += Old->use_size();
88 Old->replaceAllUsesWith(Replacement);
90 // Since there are no uses of Old anymore, remove it from the module.
91 M.getFunctionList().erase(Old);
97 static bool ResolveGlobalVariables(Module &M,
98 std::vector<GlobalValue*> &Globals,
99 GlobalVariable *Concrete) {
100 bool Changed = false;
101 assert(isa<ArrayType>(Concrete->getType()->getElementType()) &&
102 "Concrete version should be an array type!");
104 // Get the type of the things that may be resolved to us...
105 const ArrayType *CATy =cast<ArrayType>(Concrete->getType()->getElementType());
106 const Type *AETy = CATy->getElementType();
108 Constant *CCPR = ConstantPointerRef::get(Concrete);
110 for (unsigned i = 0; i != Globals.size(); ++i)
111 if (Globals[i] != Concrete) {
112 GlobalVariable *Old = cast<GlobalVariable>(Globals[i]);
113 const ArrayType *OATy = cast<ArrayType>(Old->getType()->getElementType());
114 if (OATy->getElementType() != AETy || OATy->getNumElements() != 0) {
115 std::cerr << "WARNING: Two global variables exist with the same name "
116 << "that cannot be resolved!\n";
120 Old->replaceAllUsesWith(ConstantExpr::getCast(CCPR, Old->getType()));
122 // Since there are no uses of Old anymore, remove it from the module.
123 M.getGlobalList().erase(Old);
131 static bool ProcessGlobalsWithSameName(Module &M,
132 std::vector<GlobalValue*> &Globals) {
133 assert(!Globals.empty() && "Globals list shouldn't be empty here!");
135 bool isFunction = isa<Function>(Globals[0]); // Is this group all functions?
136 GlobalValue *Concrete = 0; // The most concrete implementation to resolve to
138 assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&
139 "Should either be function or gvar!");
141 for (unsigned i = 0; i != Globals.size(); ) {
142 if (isa<Function>(Globals[i]) != isFunction) {
143 std::cerr << "WARNING: Found function and global variable with the "
144 << "same name: '" << Globals[i]->getName() << "'.\n";
145 return false; // Don't know how to handle this, bail out!
149 // For functions, we look to merge functions definitions of "int (...)"
150 // to 'int (int)' or 'int ()' or whatever else is not completely generic.
152 Function *F = cast<Function>(Globals[i]);
153 if (!F->isExternal()) {
154 if (Concrete && !Concrete->isExternal())
155 return false; // Found two different functions types. Can't choose!
157 Concrete = Globals[i];
158 } else if (Concrete) {
159 if (Concrete->isExternal()) // If we have multiple external symbols...x
160 if (F->getFunctionType()->getNumParams() >
161 cast<Function>(Concrete)->getFunctionType()->getNumParams())
162 Concrete = F; // We are more concrete than "Concrete"!
168 // For global variables, we have to merge C definitions int A[][4] with
169 // int[6][4]. A[][4] is represented as A[0][4] by the CFE.
170 GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
171 if (!isa<ArrayType>(GV->getType()->getElementType())) {
173 break; // Non array's cannot be compatible with other types.
174 } else if (Concrete == 0) {
177 // Must have different types... allow merging A[0][4] w/ A[6][4] if
178 // A[0][4] is external.
179 const ArrayType *NAT = cast<ArrayType>(GV->getType()->getElementType());
180 const ArrayType *CAT =
181 cast<ArrayType>(Concrete->getType()->getElementType());
183 if (NAT->getElementType() != CAT->getElementType()) {
184 Concrete = 0; // Non-compatible types
186 } else if (NAT->getNumElements() == 0 && GV->isExternal()) {
187 // Concrete remains the same
188 } else if (CAT->getNumElements() == 0 && Concrete->isExternal()) {
189 Concrete = GV; // Concrete becomes GV
191 Concrete = 0; // Cannot merge these types...
199 if (Globals.size() > 1) { // Found a multiply defined global...
200 // If there are no external declarations, and there is at most one
201 // externally visible instance of the global, then there is nothing to do.
203 bool HasExternal = false;
204 unsigned NumInstancesWithExternalLinkage = 0;
206 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
207 if (Globals[i]->isExternal())
209 else if (!Globals[i]->hasInternalLinkage())
210 NumInstancesWithExternalLinkage++;
213 if (!HasExternal && NumInstancesWithExternalLinkage <= 1)
214 return false; // Nothing to do? Must have multiple internal definitions.
217 // We should find exactly one concrete function definition, which is
218 // probably the implementation. Change all of the function definitions and
219 // uses to use it instead.
222 std::cerr << "WARNING: Found global types that are not compatible:\n";
223 for (unsigned i = 0; i < Globals.size(); ++i) {
224 std::cerr << "\t" << Globals[i]->getType()->getDescription() << " %"
225 << Globals[i]->getName() << "\n";
227 std::cerr << " No linkage of globals named '" << Globals[0]->getName()
233 return ResolveFunctions(M, Globals, cast<Function>(Concrete));
235 return ResolveGlobalVariables(M, Globals,
236 cast<GlobalVariable>(Concrete));
241 bool FunctionResolvingPass::run(Module &M) {
242 SymbolTable &ST = M.getSymbolTable();
244 std::map<std::string, std::vector<GlobalValue*> > Globals;
246 // Loop over the entries in the symbol table. If an entry is a func pointer,
247 // then add it to the Functions map. We do a two pass algorithm here to avoid
248 // problems with iterators getting invalidated if we did a one pass scheme.
250 for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)
251 if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {
252 SymbolTable::VarMap &Plane = I->second;
253 for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
255 GlobalValue *GV = cast<GlobalValue>(PI->second);
256 assert(PI->first == GV->getName() &&
257 "Global name and symbol table do not agree!");
258 Globals[PI->first].push_back(GV);
262 bool Changed = false;
264 // Now we have a list of all functions with a particular name. If there is
265 // more than one entry in a list, merge the functions together.
267 for (std::map<std::string, std::vector<GlobalValue*> >::iterator
268 I = Globals.begin(), E = Globals.end(); I != E; ++I)
269 Changed |= ProcessGlobalsWithSameName(M, I->second);
271 // Now loop over all of the globals, checking to see if any are trivially
272 // dead. If so, remove them now.
274 for (Module::iterator I = M.begin(), E = M.end(); I != E; )
275 if (I->isExternal() && I->use_empty()) {
278 M.getFunctionList().erase(F);
285 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )
286 if (I->isExternal() && I->use_empty()) {
287 GlobalVariable *GV = I;
289 M.getGlobalList().erase(GV);