Adjust to ilist changes.
[oota-llvm.git] / lib / VMCore / Function.cpp
1 //===-- Function.cpp - Implement the Global object classes ----------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Function & GlobalVariable classes for the VMCore
11 // library.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Module.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/IntrinsicInst.h"
18 #include "llvm/Support/LeakDetector.h"
19 #include "SymbolTableListTraitsImpl.h"
20 #include "llvm/ADT/StringExtras.h"
21 using namespace llvm;
22
23 BasicBlock *ilist_traits<BasicBlock>::createSentinal() {
24   BasicBlock *Ret = new BasicBlock();
25   // This should not be garbage monitored.
26   LeakDetector::removeGarbageObject(Ret);
27   return Ret;
28 }
29
30 iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {
31   return F->getBasicBlockList();
32 }
33
34 Argument *ilist_traits<Argument>::createSentinal() {
35   Argument *Ret = new Argument(Type::IntTy);
36   // This should not be garbage monitored.
37   LeakDetector::removeGarbageObject(Ret);
38   return Ret;
39 }
40
41 iplist<Argument> &ilist_traits<Argument>::getList(Function *F) {
42   return F->getArgumentList();
43 }
44
45 // Explicit instantiations of SymbolTableListTraits since some of the methods
46 // are not in the public header file...
47 template class SymbolTableListTraits<Argument, Function, Function>;
48 template class SymbolTableListTraits<BasicBlock, Function, Function>;
49
50 //===----------------------------------------------------------------------===//
51 // Argument Implementation
52 //===----------------------------------------------------------------------===//
53
54 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par) 
55   : Value(Ty, Value::ArgumentVal, Name) {
56   Parent = 0;
57
58   // Make sure that we get added to a function
59   LeakDetector::addGarbageObject(this);
60
61   if (Par)
62     Par->getArgumentList().push_back(this);
63 }
64
65
66 // Specialize setName to take care of symbol table majik
67 void Argument::setName(const std::string &name, SymbolTable *ST) {
68   Function *P;
69   assert((ST == 0 || (!getParent() || ST == &getParent()->getSymbolTable())) &&
70          "Invalid symtab argument!");
71   if ((P = getParent()) && hasName()) P->getSymbolTable().remove(this);
72   Value::setName(name);
73   if (P && hasName()) P->getSymbolTable().insert(this);
74 }
75
76 void Argument::setParent(Function *parent) {
77   if (getParent())
78     LeakDetector::addGarbageObject(this);
79   Parent = parent;
80   if (getParent())
81     LeakDetector::removeGarbageObject(this);
82 }
83
84 //===----------------------------------------------------------------------===//
85 // Function Implementation
86 //===----------------------------------------------------------------------===//
87
88 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
89                    const std::string &name, Module *ParentModule)
90   : GlobalValue(PointerType::get(Ty), Value::FunctionVal, 0, 0, Linkage, name) {
91   BasicBlocks.setItemParent(this);
92   BasicBlocks.setParent(this);
93   ArgumentList.setItemParent(this);
94   ArgumentList.setParent(this);
95   SymTab = new SymbolTable();
96
97   assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
98          && "LLVM functions cannot return aggregate values!");
99
100   // Create the arguments vector, all arguments start out unnamed.
101   for (unsigned i = 0, e = Ty->getNumParams(); i != e; ++i) {
102     assert(Ty->getParamType(i) != Type::VoidTy &&
103            "Cannot have void typed arguments!");
104     ArgumentList.push_back(new Argument(Ty->getParamType(i)));
105   }
106
107   // Make sure that we get added to a function
108   LeakDetector::addGarbageObject(this);
109
110   if (ParentModule)
111     ParentModule->getFunctionList().push_back(this);
112 }
113
114 Function::~Function() {
115   dropAllReferences();    // After this it is safe to delete instructions.
116
117   // Delete all of the method arguments and unlink from symbol table...
118   ArgumentList.clear();
119   ArgumentList.setParent(0);
120   delete SymTab;
121 }
122
123 // Specialize setName to take care of symbol table majik
124 void Function::setName(const std::string &name, SymbolTable *ST) {
125   Module *P;
126   assert((ST == 0 || (!getParent() || ST == &getParent()->getSymbolTable())) &&
127          "Invalid symtab argument!");
128   if ((P = getParent()) && hasName()) P->getSymbolTable().remove(this);
129   Value::setName(name);
130   if (P && hasName()) P->getSymbolTable().insert(this);
131 }
132
133 void Function::setParent(Module *parent) {
134   if (getParent())
135     LeakDetector::addGarbageObject(this);
136   Parent = parent;
137   if (getParent())
138     LeakDetector::removeGarbageObject(this);
139 }
140
141 const FunctionType *Function::getFunctionType() const {
142   return cast<FunctionType>(getType()->getElementType());
143 }
144
145 bool Function::isVarArg() const {
146   return getFunctionType()->isVarArg();
147 }
148
149 const Type *Function::getReturnType() const { 
150   return getFunctionType()->getReturnType();
151 }
152
153 void Function::removeFromParent() {
154   getParent()->getFunctionList().remove(this);
155 }
156
157 void Function::eraseFromParent() {
158   getParent()->getFunctionList().erase(this);
159 }
160
161
162 /// renameLocalSymbols - This method goes through the Function's symbol table
163 /// and renames any symbols that conflict with symbols at global scope.  This is
164 /// required before printing out to a textual form, to ensure that there is no
165 /// ambiguity when parsing.
166 void Function::renameLocalSymbols() {
167   SymbolTable &LST = getSymbolTable();                 // Local Symtab
168   SymbolTable &GST = getParent()->getSymbolTable();    // Global Symtab
169
170   for (SymbolTable::plane_iterator LPI = LST.plane_begin(), E = LST.plane_end();
171        LPI != E; ++LPI)
172     // All global symbols are of pointer type, ignore any non-pointer planes.
173     if (isa<PointerType>(LPI->first)) {
174       // Only check if the global plane has any symbols of this type.
175       SymbolTable::plane_iterator GPI = GST.find(LPI->first);
176       if (GPI != GST.plane_end()) {
177         SymbolTable::ValueMap &LVM       = LPI->second;
178         const SymbolTable::ValueMap &GVM = GPI->second;
179
180         // Loop over all local symbols, renaming those that are in the global
181         // symbol table already.
182         for (SymbolTable::value_iterator VI = LVM.begin(), E = LVM.end();
183              VI != E;) {
184           Value *V                = VI->second;
185           const std::string &Name = VI->first;
186           ++VI;
187           if (GVM.count(Name)) {
188             static unsigned UniqueNum = 0;
189             // Find a name that does not conflict!
190             while (GVM.count(Name + "_" + utostr(++UniqueNum)) ||
191                    LVM.count(Name + "_" + utostr(UniqueNum)))
192               /* scan for UniqueNum that works */;
193             V->setName(Name + "_" + utostr(UniqueNum));
194           }
195         }
196       }
197     }
198 }
199
200
201 // dropAllReferences() - This function causes all the subinstructions to "let
202 // go" of all references that they are maintaining.  This allows one to
203 // 'delete' a whole class at a time, even though there may be circular
204 // references... first all references are dropped, and all use counts go to
205 // zero.  Then everything is deleted for real.  Note that no operations are
206 // valid on an object that has "dropped all references", except operator 
207 // delete.
208 //
209 void Function::dropAllReferences() {
210   for (iterator I = begin(), E = end(); I != E; ++I)
211     I->dropAllReferences();
212   BasicBlocks.clear();    // Delete all basic blocks...
213 }
214
215 /// getIntrinsicID - This method returns the ID number of the specified
216 /// function, or Intrinsic::not_intrinsic if the function is not an
217 /// intrinsic, or if the pointer is null.  This value is always defined to be
218 /// zero to allow easy checking for whether a function is intrinsic or not.  The
219 /// particular intrinsic functions which correspond to this value are defined in
220 /// llvm/Intrinsics.h.
221 ///
222 unsigned Function::getIntrinsicID() const {
223   if (getName().size() < 5 || getName()[4] != '.' || getName()[0] != 'l' ||
224       getName()[1] != 'l' || getName()[2] != 'v' || getName()[3] != 'm')
225     return 0;  // All intrinsics start with 'llvm.'
226
227   assert(getName().size() != 5 && "'llvm.' is an invalid intrinsic name!");
228   
229   switch (getName()[5]) {
230   case 'd':
231     if (getName() == "llvm.dbg.stoppoint")   return Intrinsic::dbg_stoppoint;
232     if (getName() == "llvm.dbg.region.start")return Intrinsic::dbg_region_start;
233     if (getName() == "llvm.dbg.region.end")  return Intrinsic::dbg_region_end;
234     if (getName() == "llvm.dbg.func.start")  return Intrinsic::dbg_func_start;
235     if (getName() == "llvm.dbg.declare")     return Intrinsic::dbg_declare;
236     break;
237   case 'f':
238     if (getName() == "llvm.frameaddress")  return Intrinsic::frameaddress;
239     break;
240   case 'g':
241     if (getName() == "llvm.gcwrite") return Intrinsic::gcwrite;
242     if (getName() == "llvm.gcread")  return Intrinsic::gcread;
243     if (getName() == "llvm.gcroot")  return Intrinsic::gcroot;
244     break;
245   case 'i':
246     if (getName() == "llvm.isunordered") return Intrinsic::isunordered;
247     break;
248   case 'l':
249     if (getName() == "llvm.longjmp")  return Intrinsic::longjmp;
250     break;
251   case 'm':
252     if (getName() == "llvm.memcpy")  return Intrinsic::memcpy;
253     if (getName() == "llvm.memmove")  return Intrinsic::memmove;
254     if (getName() == "llvm.memset")  return Intrinsic::memset;
255     break;
256   case 'r':
257     if (getName() == "llvm.returnaddress")  return Intrinsic::returnaddress;
258     if (getName() == "llvm.readport")       return Intrinsic::readport;
259     if (getName() == "llvm.readio")         return Intrinsic::readio;
260     break;
261   case 's':
262     if (getName() == "llvm.setjmp")     return Intrinsic::setjmp;
263     if (getName() == "llvm.sigsetjmp")  return Intrinsic::sigsetjmp;
264     if (getName() == "llvm.siglongjmp") return Intrinsic::siglongjmp;
265     break;
266   case 'v':
267     if (getName() == "llvm.va_copy")  return Intrinsic::vacopy;
268     if (getName() == "llvm.va_end")   return Intrinsic::vaend;
269     if (getName() == "llvm.va_start") return Intrinsic::vastart;
270   case 'w':
271     if (getName() == "llvm.writeport") return Intrinsic::writeport;
272     if (getName() == "llvm.writeio")   return Intrinsic::writeio;
273     break;
274   }
275   // The "llvm." namespace is reserved!
276   assert(0 && "Unknown LLVM intrinsic function!");
277   return 0;
278 }
279
280 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
281   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
282     if (CE->getOpcode() == Instruction::Cast) {
283       if (isa<PointerType>(CE->getOperand(0)->getType()))
284         return StripPointerCasts(CE->getOperand(0));
285     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
286       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
287         if (!CE->getOperand(i)->isNullValue())
288           return Ptr;
289       return StripPointerCasts(CE->getOperand(0));
290     }
291     return Ptr;
292   }
293
294   if (CastInst *CI = dyn_cast<CastInst>(Ptr)) {
295     if (isa<PointerType>(CI->getOperand(0)->getType()))
296       return StripPointerCasts(CI->getOperand(0));
297   } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
298     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
299       if (!isa<Constant>(GEP->getOperand(i)) ||
300           !cast<Constant>(GEP->getOperand(i))->isNullValue())
301         return Ptr;
302     return StripPointerCasts(GEP->getOperand(0));
303   }
304   return Ptr;
305 }
306
307 // vim: sw=2 ai