For PR1136:
[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 class for the VMCore library.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Module.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/ParameterAttributes.h"
17 #include "llvm/IntrinsicInst.h"
18 #include "llvm/Support/LeakDetector.h"
19 #include "llvm/Support/ManagedStatic.h"
20 #include "SymbolTableListTraitsImpl.h"
21 #include "llvm/ADT/StringExtras.h"
22 using namespace llvm;
23
24 BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
25   BasicBlock *Ret = new BasicBlock();
26   // This should not be garbage monitored.
27   LeakDetector::removeGarbageObject(Ret);
28   return Ret;
29 }
30
31 iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {
32   return F->getBasicBlockList();
33 }
34
35 Argument *ilist_traits<Argument>::createSentinel() {
36   Argument *Ret = new Argument(Type::Int32Ty);
37   // This should not be garbage monitored.
38   LeakDetector::removeGarbageObject(Ret);
39   return Ret;
40 }
41
42 iplist<Argument> &ilist_traits<Argument>::getList(Function *F) {
43   return F->getArgumentList();
44 }
45
46 // Explicit instantiations of SymbolTableListTraits since some of the methods
47 // are not in the public header file...
48 template class SymbolTableListTraits<Argument, Function>;
49 template class SymbolTableListTraits<BasicBlock, Function>;
50
51 //===----------------------------------------------------------------------===//
52 // Argument Implementation
53 //===----------------------------------------------------------------------===//
54
55 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
56   : Value(Ty, Value::ArgumentVal) {
57   Parent = 0;
58
59   // Make sure that we get added to a function
60   LeakDetector::addGarbageObject(this);
61
62   if (Par)
63     Par->getArgumentList().push_back(this);
64   setName(Name);
65 }
66
67 void Argument::setParent(Function *parent) {
68   if (getParent())
69     LeakDetector::addGarbageObject(this);
70   Parent = parent;
71   if (getParent())
72     LeakDetector::removeGarbageObject(this);
73 }
74
75 //===----------------------------------------------------------------------===//
76 // ParamAttrsList Implementation
77 //===----------------------------------------------------------------------===//
78
79 uint16_t
80 ParamAttrsList::getParamAttrs(uint16_t Index) const {
81   unsigned limit = attrs.size();
82   for (unsigned i = 0; i < limit; ++i)
83     if (attrs[i].index == Index)
84       return attrs[i].attrs;
85   return ParamAttr::None;
86 }
87
88
89 std::string 
90 ParamAttrsList::getParamAttrsText(uint16_t Attrs) {
91   std::string Result;
92   if (Attrs & ParamAttr::ZExt)
93     Result += "zext ";
94   if (Attrs & ParamAttr::SExt)
95     Result += "sext ";
96   if (Attrs & ParamAttr::NoReturn)
97     Result += "noreturn ";
98   if (Attrs & ParamAttr::NoUnwind)
99     Result += "nounwind ";
100   if (Attrs & ParamAttr::InReg)
101     Result += "inreg ";
102   if (Attrs & ParamAttr::StructRet)
103     Result += "sret ";  
104   return Result;
105 }
106
107 void 
108 ParamAttrsList::Profile(FoldingSetNodeID &ID) const {
109   for (unsigned i = 0; i < attrs.size(); ++i) {
110     unsigned val = attrs[i].attrs << 16 | attrs[i].index;
111     ID.AddInteger(val);
112   }
113 }
114
115 static ManagedStatic<FoldingSet<ParamAttrsList> > ParamAttrsLists;
116
117 ParamAttrsList *
118 ParamAttrsList::get(const ParamAttrsVector &attrVec) {
119   assert(!attrVec.empty() && "Illegal to create empty ParamAttrsList");
120   ParamAttrsList key(attrVec);
121   FoldingSetNodeID ID;
122   key.Profile(ID);
123   void *InsertPos;
124   ParamAttrsList* PAL = ParamAttrsLists->FindNodeOrInsertPos(ID, InsertPos);
125   if (!PAL) {
126     PAL = new ParamAttrsList(attrVec);
127     ParamAttrsLists->InsertNode(PAL, InsertPos);
128   }
129   return PAL;
130 }
131
132 ParamAttrsList::~ParamAttrsList() {
133   ParamAttrsLists->RemoveNode(this);
134 }
135
136 //===----------------------------------------------------------------------===//
137 // Function Implementation
138 //===----------------------------------------------------------------------===//
139
140 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
141                    const std::string &name, Module *ParentModule)
142   : GlobalValue(PointerType::get(Ty), Value::FunctionVal, 0, 0, Linkage, name) {
143   ParamAttrs = 0;
144   SymTab = new ValueSymbolTable();
145
146   assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
147          && "LLVM functions cannot return aggregate values!");
148
149   // Create the arguments vector, all arguments start out unnamed.
150   for (unsigned i = 0, e = Ty->getNumParams(); i != e; ++i) {
151     assert(Ty->getParamType(i) != Type::VoidTy &&
152            "Cannot have void typed arguments!");
153     ArgumentList.push_back(new Argument(Ty->getParamType(i)));
154   }
155
156   // Make sure that we get added to a function
157   LeakDetector::addGarbageObject(this);
158
159   if (ParentModule)
160     ParentModule->getFunctionList().push_back(this);
161 }
162
163 Function::~Function() {
164   dropAllReferences();    // After this it is safe to delete instructions.
165
166   // Delete all of the method arguments and unlink from symbol table...
167   ArgumentList.clear();
168   delete SymTab;
169
170   // Drop our reference to the parameter attributes, if any.
171   if (ParamAttrs)
172     ParamAttrs->dropRef();
173 }
174
175 void Function::setParent(Module *parent) {
176   if (getParent())
177     LeakDetector::addGarbageObject(this);
178   Parent = parent;
179   if (getParent())
180     LeakDetector::removeGarbageObject(this);
181 }
182
183 void Function::setParamAttrs(ParamAttrsList *attrs) { 
184   if (ParamAttrs)
185     ParamAttrs->dropRef();
186
187   if (attrs)
188     attrs->addRef();
189
190   ParamAttrs = attrs; 
191 }
192
193 const FunctionType *Function::getFunctionType() const {
194   return cast<FunctionType>(getType()->getElementType());
195 }
196
197 bool Function::isVarArg() const {
198   return getFunctionType()->isVarArg();
199 }
200
201 const Type *Function::getReturnType() const {
202   return getFunctionType()->getReturnType();
203 }
204
205 void Function::removeFromParent() {
206   getParent()->getFunctionList().remove(this);
207 }
208
209 void Function::eraseFromParent() {
210   getParent()->getFunctionList().erase(this);
211 }
212
213 // dropAllReferences() - This function causes all the subinstructions to "let
214 // go" of all references that they are maintaining.  This allows one to
215 // 'delete' a whole class at a time, even though there may be circular
216 // references... first all references are dropped, and all use counts go to
217 // zero.  Then everything is deleted for real.  Note that no operations are
218 // valid on an object that has "dropped all references", except operator
219 // delete.
220 //
221 void Function::dropAllReferences() {
222   for (iterator I = begin(), E = end(); I != E; ++I)
223     I->dropAllReferences();
224   BasicBlocks.clear();    // Delete all basic blocks...
225 }
226
227 /// getIntrinsicID - This method returns the ID number of the specified
228 /// function, or Intrinsic::not_intrinsic if the function is not an
229 /// intrinsic, or if the pointer is null.  This value is always defined to be
230 /// zero to allow easy checking for whether a function is intrinsic or not.  The
231 /// particular intrinsic functions which correspond to this value are defined in
232 /// llvm/Intrinsics.h.
233 ///
234 unsigned Function::getIntrinsicID(bool noAssert) const {
235   const ValueName *ValName = this->getValueName();
236   if (!ValName)
237     return 0;
238   unsigned Len = ValName->getKeyLength();
239   const char *Name = ValName->getKeyData();
240   
241   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
242       || Name[2] != 'v' || Name[3] != 'm')
243     return 0;  // All intrinsics start with 'llvm.'
244
245   assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
246
247 #define GET_FUNCTION_RECOGNIZER
248 #include "llvm/Intrinsics.gen"
249 #undef GET_FUNCTION_RECOGNIZER
250   assert(noAssert && "Invalid LLVM intrinsic name");
251   return 0;
252 }
253
254 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { 
255   assert(id < num_intrinsics && "Invalid intrinsic ID!");
256   const char * const Table[] = {
257     "not_intrinsic",
258 #define GET_INTRINSIC_NAME_TABLE
259 #include "llvm/Intrinsics.gen"
260 #undef GET_INTRINSIC_NAME_TABLE
261   };
262   if (numTys == 0)
263     return Table[id];
264   std::string Result(Table[id]);
265   for (unsigned i = 0; i < numTys; ++i) 
266     if (Tys[i])
267       Result += "." + Tys[i]->getDescription();
268   return Result;
269 }
270
271 const FunctionType *Intrinsic::getType(ID id, const Type **Tys, 
272                                        uint32_t numTys) {
273   const Type *ResultTy = NULL;
274   std::vector<const Type*> ArgTys;
275   bool IsVarArg = false;
276   
277 #define GET_INTRINSIC_GENERATOR
278 #include "llvm/Intrinsics.gen"
279 #undef GET_INTRINSIC_GENERATOR
280
281   return FunctionType::get(ResultTy, ArgTys, IsVarArg); 
282 }
283
284 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, 
285                                     unsigned numTys) {
286 // There can never be multiple globals with the same name of different types,
287 // because intrinsics must be a specific type.
288   return cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys), 
289                                                getType(id, Tys, numTys)));
290 }
291
292 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
293   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
294     if (CE->getOpcode() == Instruction::BitCast) {
295       if (isa<PointerType>(CE->getOperand(0)->getType()))
296         return StripPointerCasts(CE->getOperand(0));
297     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
298       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
299         if (!CE->getOperand(i)->isNullValue())
300           return Ptr;
301       return StripPointerCasts(CE->getOperand(0));
302     }
303     return Ptr;
304   }
305
306   if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
307     if (isa<PointerType>(CI->getOperand(0)->getType()))
308       return StripPointerCasts(CI->getOperand(0));
309   } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
310     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
311       if (!isa<Constant>(GEP->getOperand(i)) ||
312           !cast<Constant>(GEP->getOperand(i))->isNullValue())
313         return Ptr;
314     return StripPointerCasts(GEP->getOperand(0));
315   }
316   return Ptr;
317 }
318
319 // vim: sw=2 ai