1 //===- FunctionResolution.cpp - Resolve declarations to implementations ---===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Loop over the functions that are in the module and look for functions that
11 // have the same name. More often than not, there will be things like:
13 // declare void %foo(...)
14 // void %foo(int, int) { ... }
16 // because of the way things are declared in C. If this is the case, patch
19 //===----------------------------------------------------------------------===//
21 #include "llvm/Transforms/IPO.h"
22 #include "llvm/Module.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Constants.h"
27 #include "llvm/Support/CallSite.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Assembly/Writer.h"
30 #include "llvm/ADT/Statistic.h"
36 Statistic<>NumResolved("funcresolve", "Number of varargs functions resolved");
37 Statistic<> NumGlobals("funcresolve", "Number of global variables resolved");
39 struct FunctionResolvingPass : public ModulePass {
40 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
41 AU.addRequired<TargetData>();
44 bool runOnModule(Module &M);
46 RegisterPass<FunctionResolvingPass> X("funcresolve", "Resolve Functions");
49 ModulePass *llvm::createFunctionResolvingPass() {
50 return new FunctionResolvingPass();
53 static bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,
56 for (unsigned i = 0; i != Globals.size(); ++i)
57 if (Globals[i] != Concrete) {
58 Function *Old = cast<Function>(Globals[i]);
59 const FunctionType *OldFT = Old->getFunctionType();
60 const FunctionType *ConcreteFT = Concrete->getFunctionType();
62 if (OldFT->getNumParams() > ConcreteFT->getNumParams() &&
63 !ConcreteFT->isVarArg())
64 if (!Old->use_empty()) {
65 std::cerr << "WARNING: Linking function '" << Old->getName()
66 << "' is causing arguments to be dropped.\n";
67 std::cerr << "WARNING: Prototype: ";
68 WriteAsOperand(std::cerr, Old);
69 std::cerr << " resolved to ";
70 WriteAsOperand(std::cerr, Concrete);
74 // Check to make sure that if there are specified types, that they
77 unsigned NumArguments = std::min(OldFT->getNumParams(),
78 ConcreteFT->getNumParams());
80 if (!Old->use_empty() && !Concrete->use_empty())
81 for (unsigned i = 0; i < NumArguments; ++i)
82 if (OldFT->getParamType(i) != ConcreteFT->getParamType(i))
83 if (OldFT->getParamType(i)->getTypeID() !=
84 ConcreteFT->getParamType(i)->getTypeID()) {
85 std::cerr << "WARNING: Function [" << Old->getName()
86 << "]: Parameter types conflict for: '";
87 WriteTypeSymbolic(std::cerr, OldFT, &M);
89 << Old->getParent()->getModuleIdentifier() << ") and '";
90 WriteTypeSymbolic(std::cerr, ConcreteFT, &M);
92 << Concrete->getParent()->getModuleIdentifier() << ")\n";
96 // Attempt to convert all of the uses of the old function to the concrete
97 // form of the function. If there is a use of the fn that we don't
98 // understand here we punt to avoid making a bad transformation.
100 // At this point, we know that the return values are the same for our two
101 // functions and that the Old function has no varargs fns specified. In
102 // otherwords it's just <retty> (...)
104 if (!Old->use_empty()) {
105 Value *Replacement = Concrete;
106 if (Concrete->getType() != Old->getType())
107 Replacement = ConstantExpr::getCast(Concrete, Old->getType());
108 NumResolved += Old->getNumUses();
109 Old->replaceAllUsesWith(Replacement);
112 // Since there are no uses of Old anymore, remove it from the module.
113 M.getFunctionList().erase(Old);
119 static bool ResolveGlobalVariables(Module &M,
120 std::vector<GlobalValue*> &Globals,
121 GlobalVariable *Concrete) {
122 bool Changed = false;
124 for (unsigned i = 0; i != Globals.size(); ++i)
125 if (Globals[i] != Concrete) {
126 Constant *Cast = ConstantExpr::getCast(Concrete, Globals[i]->getType());
127 Globals[i]->replaceAllUsesWith(Cast);
129 // Since there are no uses of Old anymore, remove it from the module.
130 M.getGlobalList().erase(cast<GlobalVariable>(Globals[i]));
138 // Check to see if all of the callers of F ignore the return value.
139 static bool CallersAllIgnoreReturnValue(Function &F) {
140 if (F.getReturnType() == Type::VoidTy) return true;
141 for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
142 if (GlobalValue *GV = dyn_cast<GlobalValue>(*I)) {
143 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end();
145 CallSite CS = CallSite::get(*I);
146 if (!CS.getInstruction() || !CS.getInstruction()->use_empty())
150 CallSite CS = CallSite::get(*I);
151 if (!CS.getInstruction() || !CS.getInstruction()->use_empty())
158 static bool ProcessGlobalsWithSameName(Module &M, TargetData &TD,
159 std::vector<GlobalValue*> &Globals) {
160 assert(!Globals.empty() && "Globals list shouldn't be empty here!");
162 bool isFunction = isa<Function>(Globals[0]); // Is this group all functions?
163 GlobalValue *Concrete = 0; // The most concrete implementation to resolve to
165 for (unsigned i = 0; i != Globals.size(); ) {
166 if (isa<Function>(Globals[i]) != isFunction) {
167 std::cerr << "WARNING: Found function and global variable with the "
168 << "same name: '" << Globals[i]->getName() << "'.\n";
169 return false; // Don't know how to handle this, bail out!
173 // For functions, we look to merge functions definitions of "int (...)"
174 // to 'int (int)' or 'int ()' or whatever else is not completely generic.
176 Function *F = cast<Function>(Globals[i]);
177 if (!F->isExternal()) {
178 if (Concrete && !Concrete->isExternal())
179 return false; // Found two different functions types. Can't choose!
181 Concrete = Globals[i];
182 } else if (Concrete) {
183 if (Concrete->isExternal()) // If we have multiple external symbols...
184 if (F->getFunctionType()->getNumParams() >
185 cast<Function>(Concrete)->getFunctionType()->getNumParams())
186 Concrete = F; // We are more concrete than "Concrete"!
192 GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
193 if (!GV->isExternal()) {
195 std::cerr << "WARNING: Two global variables with external linkage"
196 << " exist with the same name: '" << GV->getName()
206 if (Globals.size() > 1) { // Found a multiply defined global...
207 // If there are no external declarations, and there is at most one
208 // externally visible instance of the global, then there is nothing to do.
210 bool HasExternal = false;
211 unsigned NumInstancesWithExternalLinkage = 0;
213 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
214 if (Globals[i]->isExternal())
216 else if (!Globals[i]->hasInternalLinkage())
217 NumInstancesWithExternalLinkage++;
220 if (!HasExternal && NumInstancesWithExternalLinkage <= 1)
221 return false; // Nothing to do? Must have multiple internal definitions.
223 // There are a couple of special cases we don't want to print the warning
224 // for, check them now.
225 bool DontPrintWarning = false;
226 if (Concrete && Globals.size() == 2) {
227 GlobalValue *Other = Globals[Globals[0] == Concrete];
228 // If the non-concrete global is a function which takes (...) arguments,
229 // and the return values match (or was never used), do not warn.
230 if (Function *ConcreteF = dyn_cast<Function>(Concrete))
231 if (Function *OtherF = dyn_cast<Function>(Other))
232 if ((ConcreteF->getReturnType() == OtherF->getReturnType() ||
233 CallersAllIgnoreReturnValue(*OtherF)) &&
234 OtherF->getFunctionType()->isVarArg() &&
235 OtherF->getFunctionType()->getNumParams() == 0)
236 DontPrintWarning = true;
238 // Otherwise, if the non-concrete global is a global array variable with a
239 // size of 0, and the concrete global is an array with a real size, don't
240 // warn. This occurs due to declaring 'extern int A[];'.
241 if (GlobalVariable *ConcreteGV = dyn_cast<GlobalVariable>(Concrete))
242 if (GlobalVariable *OtherGV = dyn_cast<GlobalVariable>(Other)) {
243 const Type *CTy = ConcreteGV->getType();
244 const Type *OTy = OtherGV->getType();
247 if (!OTy->isSized() || !TD.getTypeSize(OTy) ||
248 TD.getTypeSize(OTy) == TD.getTypeSize(CTy))
249 DontPrintWarning = true;
253 if (0 && !DontPrintWarning) {
254 std::cerr << "WARNING: Found global types that are not compatible:\n";
255 for (unsigned i = 0; i < Globals.size(); ++i) {
257 WriteTypeSymbolic(std::cerr, Globals[i]->getType(), &M);
258 std::cerr << " %" << Globals[i]->getName() << "\n";
263 Concrete = Globals[0];
264 else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Concrete)) {
265 // Handle special case hack to change globals if it will make their types
266 // happier in the long run. The situation we do this is intentionally
267 // extremely limited.
268 if (GV->use_empty() && GV->hasInitializer() &&
269 GV->getInitializer()->isNullValue()) {
270 // Check to see if there is another (external) global with the same size
271 // and a non-empty use-list. If so, we will make IT be the real
273 unsigned TS = TD.getTypeSize(Concrete->getType()->getElementType());
274 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
275 if (Globals[i] != Concrete && !Globals[i]->use_empty() &&
276 isa<GlobalVariable>(Globals[i]) &&
277 TD.getTypeSize(Globals[i]->getType()->getElementType()) == TS) {
278 // At this point we want to replace Concrete with Globals[i]. Make
279 // concrete external, and Globals[i] have an initializer.
280 GlobalVariable *NGV = cast<GlobalVariable>(Globals[i]);
281 const Type *ElTy = NGV->getType()->getElementType();
282 NGV->setInitializer(Constant::getNullValue(ElTy));
283 cast<GlobalVariable>(Concrete)->setInitializer(0);
291 return ResolveFunctions(M, Globals, cast<Function>(Concrete));
293 return ResolveGlobalVariables(M, Globals,
294 cast<GlobalVariable>(Concrete));
299 bool FunctionResolvingPass::runOnModule(Module &M) {
300 std::map<std::string, std::vector<GlobalValue*> > Globals;
302 // Loop over the globals, adding them to the Globals map. We use a two pass
303 // algorithm here to avoid problems with iterators getting invalidated if we
304 // did a one pass scheme.
306 bool Changed = false;
307 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
309 if (F->use_empty() && F->isExternal()) {
310 M.getFunctionList().erase(F);
312 } else if (!F->hasInternalLinkage() && !F->getName().empty() &&
313 !F->getIntrinsicID())
314 Globals[F->getName()].push_back(F);
317 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
319 GlobalVariable *GV = I++;
320 if (GV->use_empty() && GV->isExternal()) {
321 M.getGlobalList().erase(GV);
323 } else if (!GV->hasInternalLinkage() && !GV->getName().empty())
324 Globals[GV->getName()].push_back(GV);
327 TargetData &TD = getAnalysis<TargetData>();
329 // Now we have a list of all functions with a particular name. If there is
330 // more than one entry in a list, merge the functions together.
332 for (std::map<std::string, std::vector<GlobalValue*> >::iterator
333 I = Globals.begin(), E = Globals.end(); I != E; ++I)
334 Changed |= ProcessGlobalsWithSameName(M, TD, I->second);
336 // Now loop over all of the globals, checking to see if any are trivially
337 // dead. If so, remove them now.
339 for (Module::iterator I = M.begin(), E = M.end(); I != E; )
340 if (I->isExternal() && I->use_empty()) {
343 M.getFunctionList().erase(F);
350 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
352 if (I->isExternal() && I->use_empty()) {
353 GlobalVariable *GV = I;
355 M.getGlobalList().erase(GV);