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"
35 Statistic<>NumResolved("funcresolve", "Number of varargs functions resolved");
36 Statistic<> NumGlobals("funcresolve", "Number of global variables resolved");
38 struct FunctionResolvingPass : public ModulePass {
39 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
40 AU.addRequired<TargetData>();
43 bool runOnModule(Module &M);
45 RegisterOpt<FunctionResolvingPass> X("funcresolve", "Resolve Functions");
48 ModulePass *llvm::createFunctionResolvingPass() {
49 return new FunctionResolvingPass();
52 static bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,
55 for (unsigned i = 0; i != Globals.size(); ++i)
56 if (Globals[i] != Concrete) {
57 Function *Old = cast<Function>(Globals[i]);
58 const FunctionType *OldMT = Old->getFunctionType();
59 const FunctionType *ConcreteMT = Concrete->getFunctionType();
61 if (OldMT->getNumParams() > ConcreteMT->getNumParams() &&
62 !ConcreteMT->isVarArg())
63 if (!Old->use_empty()) {
64 std::cerr << "WARNING: Linking function '" << Old->getName()
65 << "' is causing arguments to be dropped.\n";
66 std::cerr << "WARNING: Prototype: ";
67 WriteAsOperand(std::cerr, Old);
68 std::cerr << " resolved to ";
69 WriteAsOperand(std::cerr, Concrete);
73 // Check to make sure that if there are specified types, that they
76 unsigned NumArguments = std::min(OldMT->getNumParams(),
77 ConcreteMT->getNumParams());
79 if (!Old->use_empty() && !Concrete->use_empty())
80 for (unsigned i = 0; i < NumArguments; ++i)
81 if (OldMT->getParamType(i) != ConcreteMT->getParamType(i))
82 if (OldMT->getParamType(i)->getTypeID() !=
83 ConcreteMT->getParamType(i)->getTypeID()) {
84 std::cerr << "WARNING: Function [" << Old->getName()
85 << "]: Parameter types conflict for: '";
86 WriteTypeSymbolic(std::cerr, OldMT, &M);
87 std::cerr << "' and '";
88 WriteTypeSymbolic(std::cerr, ConcreteMT, &M);
93 // Attempt to convert all of the uses of the old function to the concrete
94 // form of the function. If there is a use of the fn that we don't
95 // understand here we punt to avoid making a bad transformation.
97 // At this point, we know that the return values are the same for our two
98 // functions and that the Old function has no varargs fns specified. In
99 // otherwords it's just <retty> (...)
101 if (!Old->use_empty()) { // Avoid making the CPR unless we really need it
102 Value *Replacement = Concrete;
103 if (Concrete->getType() != Old->getType())
104 Replacement = ConstantExpr::getCast(Concrete,Old->getType());
105 NumResolved += Old->use_size();
106 Old->replaceAllUsesWith(Replacement);
109 // Since there are no uses of Old anymore, remove it from the module.
110 M.getFunctionList().erase(Old);
116 static bool ResolveGlobalVariables(Module &M,
117 std::vector<GlobalValue*> &Globals,
118 GlobalVariable *Concrete) {
119 bool Changed = false;
121 for (unsigned i = 0; i != Globals.size(); ++i)
122 if (Globals[i] != Concrete) {
123 Constant *Cast = ConstantExpr::getCast(Concrete, Globals[i]->getType());
124 Globals[i]->replaceAllUsesWith(Cast);
126 // Since there are no uses of Old anymore, remove it from the module.
127 M.getGlobalList().erase(cast<GlobalVariable>(Globals[i]));
135 // Check to see if all of the callers of F ignore the return value.
136 static bool CallersAllIgnoreReturnValue(Function &F) {
137 if (F.getReturnType() == Type::VoidTy) return true;
138 for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
139 if (GlobalValue *GV = dyn_cast<GlobalValue>(*I)) {
140 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end();
142 CallSite CS = CallSite::get(*I);
143 if (!CS.getInstruction() || !CS.getInstruction()->use_empty())
147 CallSite CS = CallSite::get(*I);
148 if (!CS.getInstruction() || !CS.getInstruction()->use_empty())
155 static bool ProcessGlobalsWithSameName(Module &M, TargetData &TD,
156 std::vector<GlobalValue*> &Globals) {
157 assert(!Globals.empty() && "Globals list shouldn't be empty here!");
159 bool isFunction = isa<Function>(Globals[0]); // Is this group all functions?
160 GlobalValue *Concrete = 0; // The most concrete implementation to resolve to
162 for (unsigned i = 0; i != Globals.size(); ) {
163 if (isa<Function>(Globals[i]) != isFunction) {
164 std::cerr << "WARNING: Found function and global variable with the "
165 << "same name: '" << Globals[i]->getName() << "'.\n";
166 return false; // Don't know how to handle this, bail out!
170 // For functions, we look to merge functions definitions of "int (...)"
171 // to 'int (int)' or 'int ()' or whatever else is not completely generic.
173 Function *F = cast<Function>(Globals[i]);
174 if (!F->isExternal()) {
175 if (Concrete && !Concrete->isExternal())
176 return false; // Found two different functions types. Can't choose!
178 Concrete = Globals[i];
179 } else if (Concrete) {
180 if (Concrete->isExternal()) // If we have multiple external symbols...
181 if (F->getFunctionType()->getNumParams() >
182 cast<Function>(Concrete)->getFunctionType()->getNumParams())
183 Concrete = F; // We are more concrete than "Concrete"!
189 GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
190 if (!GV->isExternal()) {
192 std::cerr << "WARNING: Two global variables with external linkage"
193 << " exist with the same name: '" << GV->getName()
203 if (Globals.size() > 1) { // Found a multiply defined global...
204 // If there are no external declarations, and there is at most one
205 // externally visible instance of the global, then there is nothing to do.
207 bool HasExternal = false;
208 unsigned NumInstancesWithExternalLinkage = 0;
210 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
211 if (Globals[i]->isExternal())
213 else if (!Globals[i]->hasInternalLinkage())
214 NumInstancesWithExternalLinkage++;
217 if (!HasExternal && NumInstancesWithExternalLinkage <= 1)
218 return false; // Nothing to do? Must have multiple internal definitions.
220 // There are a couple of special cases we don't want to print the warning
221 // for, check them now.
222 bool DontPrintWarning = false;
223 if (Concrete && Globals.size() == 2) {
224 GlobalValue *Other = Globals[Globals[0] == Concrete];
225 // If the non-concrete global is a function which takes (...) arguments,
226 // and the return values match (or was never used), do not warn.
227 if (Function *ConcreteF = dyn_cast<Function>(Concrete))
228 if (Function *OtherF = dyn_cast<Function>(Other))
229 if ((ConcreteF->getReturnType() == OtherF->getReturnType() ||
230 CallersAllIgnoreReturnValue(*OtherF)) &&
231 OtherF->getFunctionType()->isVarArg() &&
232 OtherF->getFunctionType()->getNumParams() == 0)
233 DontPrintWarning = true;
235 // Otherwise, if the non-concrete global is a global array variable with a
236 // size of 0, and the concrete global is an array with a real size, don't
237 // warn. This occurs due to declaring 'extern int A[];'.
238 if (GlobalVariable *ConcreteGV = dyn_cast<GlobalVariable>(Concrete))
239 if (GlobalVariable *OtherGV = dyn_cast<GlobalVariable>(Other)) {
240 const Type *CTy = ConcreteGV->getType();
241 const Type *OTy = OtherGV->getType();
244 if (!OTy->isSized() || !TD.getTypeSize(OTy) ||
245 TD.getTypeSize(OTy) == TD.getTypeSize(CTy))
246 DontPrintWarning = true;
250 if (0 && !DontPrintWarning) {
251 std::cerr << "WARNING: Found global types that are not compatible:\n";
252 for (unsigned i = 0; i < Globals.size(); ++i) {
254 WriteTypeSymbolic(std::cerr, Globals[i]->getType(), &M);
255 std::cerr << " %" << Globals[i]->getName() << "\n";
260 Concrete = Globals[0];
261 else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Concrete)) {
262 // Handle special case hack to change globals if it will make their types
263 // happier in the long run. The situation we do this is intentionally
264 // extremely limited.
265 if (GV->use_empty() && GV->hasInitializer() &&
266 GV->getInitializer()->isNullValue()) {
267 // Check to see if there is another (external) global with the same size
268 // and a non-empty use-list. If so, we will make IT be the real
270 unsigned TS = TD.getTypeSize(Concrete->getType()->getElementType());
271 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
272 if (Globals[i] != Concrete && !Globals[i]->use_empty() &&
273 isa<GlobalVariable>(Globals[i]) &&
274 TD.getTypeSize(Globals[i]->getType()->getElementType()) == TS) {
275 // At this point we want to replace Concrete with Globals[i]. Make
276 // concrete external, and Globals[i] have an initializer.
277 GlobalVariable *NGV = cast<GlobalVariable>(Globals[i]);
278 const Type *ElTy = NGV->getType()->getElementType();
279 NGV->setInitializer(Constant::getNullValue(ElTy));
280 cast<GlobalVariable>(Concrete)->setInitializer(0);
288 return ResolveFunctions(M, Globals, cast<Function>(Concrete));
290 return ResolveGlobalVariables(M, Globals,
291 cast<GlobalVariable>(Concrete));
296 bool FunctionResolvingPass::runOnModule(Module &M) {
297 std::map<std::string, std::vector<GlobalValue*> > Globals;
299 // Loop over the globals, adding them to the Globals map. We use a two pass
300 // algorithm here to avoid problems with iterators getting invalidated if we
301 // did a one pass scheme.
303 bool Changed = false;
304 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
306 if (F->use_empty() && F->isExternal()) {
307 M.getFunctionList().erase(F);
309 } else if (!F->hasInternalLinkage() && !F->getName().empty() &&
310 !F->getIntrinsicID())
311 Globals[F->getName()].push_back(F);
314 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ) {
315 GlobalVariable *GV = I++;
316 if (GV->use_empty() && GV->isExternal()) {
317 M.getGlobalList().erase(GV);
319 } else if (!GV->hasInternalLinkage() && !GV->getName().empty())
320 Globals[GV->getName()].push_back(GV);
323 TargetData &TD = getAnalysis<TargetData>();
325 // Now we have a list of all functions with a particular name. If there is
326 // more than one entry in a list, merge the functions together.
328 for (std::map<std::string, std::vector<GlobalValue*> >::iterator
329 I = Globals.begin(), E = Globals.end(); I != E; ++I)
330 Changed |= ProcessGlobalsWithSameName(M, TD, I->second);
332 // Now loop over all of the globals, checking to see if any are trivially
333 // dead. If so, remove them now.
335 for (Module::iterator I = M.begin(), E = M.end(); I != E; )
336 if (I->isExternal() && I->use_empty()) {
339 M.getFunctionList().erase(F);
346 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )
347 if (I->isExternal() && I->use_empty()) {
348 GlobalVariable *GV = I;
350 M.getGlobalList().erase(GV);