54ed25c7b7f21c9a830298c26a5ad8649161191e
[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::NoAlias)
103     Result += "noalias ";
104   if (Attrs & ParamAttr::StructRet)
105     Result += "sret ";  
106   return Result;
107 }
108
109 void 
110 ParamAttrsList::Profile(FoldingSetNodeID &ID) const {
111   for (unsigned i = 0; i < attrs.size(); ++i) {
112     unsigned val = attrs[i].attrs << 16 | attrs[i].index;
113     ID.AddInteger(val);
114   }
115 }
116
117 static ManagedStatic<FoldingSet<ParamAttrsList> > ParamAttrsLists;
118
119 ParamAttrsList *
120 ParamAttrsList::get(const ParamAttrsVector &attrVec) {
121   assert(!attrVec.empty() && "Illegal to create empty ParamAttrsList");
122   ParamAttrsList key(attrVec);
123   FoldingSetNodeID ID;
124   key.Profile(ID);
125   void *InsertPos;
126   ParamAttrsList* PAL = ParamAttrsLists->FindNodeOrInsertPos(ID, InsertPos);
127   if (!PAL) {
128     PAL = new ParamAttrsList(attrVec);
129     ParamAttrsLists->InsertNode(PAL, InsertPos);
130   }
131   return PAL;
132 }
133
134 ParamAttrsList::~ParamAttrsList() {
135   ParamAttrsLists->RemoveNode(this);
136 }
137
138 //===----------------------------------------------------------------------===//
139 // Function Implementation
140 //===----------------------------------------------------------------------===//
141
142 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
143                    const std::string &name, Module *ParentModule)
144   : GlobalValue(PointerType::get(Ty), Value::FunctionVal, 0, 0, Linkage, name) {
145   ParamAttrs = 0;
146   SymTab = new ValueSymbolTable();
147
148   assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
149          && "LLVM functions cannot return aggregate values!");
150
151   // Create the arguments vector, all arguments start out unnamed.
152   for (unsigned i = 0, e = Ty->getNumParams(); i != e; ++i) {
153     assert(Ty->getParamType(i) != Type::VoidTy &&
154            "Cannot have void typed arguments!");
155     ArgumentList.push_back(new Argument(Ty->getParamType(i)));
156   }
157
158   // Make sure that we get added to a function
159   LeakDetector::addGarbageObject(this);
160
161   if (ParentModule)
162     ParentModule->getFunctionList().push_back(this);
163 }
164
165 Function::~Function() {
166   dropAllReferences();    // After this it is safe to delete instructions.
167
168   // Delete all of the method arguments and unlink from symbol table...
169   ArgumentList.clear();
170   delete SymTab;
171
172   // Drop our reference to the parameter attributes, if any.
173   if (ParamAttrs)
174     ParamAttrs->dropRef();
175 }
176
177 void Function::setParent(Module *parent) {
178   if (getParent())
179     LeakDetector::addGarbageObject(this);
180   Parent = parent;
181   if (getParent())
182     LeakDetector::removeGarbageObject(this);
183 }
184
185 void Function::setParamAttrs(ParamAttrsList *attrs) { 
186   if (ParamAttrs)
187     ParamAttrs->dropRef();
188
189   if (attrs)
190     attrs->addRef();
191
192   ParamAttrs = attrs; 
193 }
194
195 const FunctionType *Function::getFunctionType() const {
196   return cast<FunctionType>(getType()->getElementType());
197 }
198
199 bool Function::isVarArg() const {
200   return getFunctionType()->isVarArg();
201 }
202
203 const Type *Function::getReturnType() const {
204   return getFunctionType()->getReturnType();
205 }
206
207 void Function::removeFromParent() {
208   getParent()->getFunctionList().remove(this);
209 }
210
211 void Function::eraseFromParent() {
212   getParent()->getFunctionList().erase(this);
213 }
214
215 // dropAllReferences() - This function causes all the subinstructions to "let
216 // go" of all references that they are maintaining.  This allows one to
217 // 'delete' a whole class at a time, even though there may be circular
218 // references... first all references are dropped, and all use counts go to
219 // zero.  Then everything is deleted for real.  Note that no operations are
220 // valid on an object that has "dropped all references", except operator
221 // delete.
222 //
223 void Function::dropAllReferences() {
224   for (iterator I = begin(), E = end(); I != E; ++I)
225     I->dropAllReferences();
226   BasicBlocks.clear();    // Delete all basic blocks...
227 }
228
229 /// getIntrinsicID - This method returns the ID number of the specified
230 /// function, or Intrinsic::not_intrinsic if the function is not an
231 /// intrinsic, or if the pointer is null.  This value is always defined to be
232 /// zero to allow easy checking for whether a function is intrinsic or not.  The
233 /// particular intrinsic functions which correspond to this value are defined in
234 /// llvm/Intrinsics.h.
235 ///
236 unsigned Function::getIntrinsicID(bool noAssert) const {
237   const ValueName *ValName = this->getValueName();
238   if (!ValName)
239     return 0;
240   unsigned Len = ValName->getKeyLength();
241   const char *Name = ValName->getKeyData();
242   
243   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
244       || Name[2] != 'v' || Name[3] != 'm')
245     return 0;  // All intrinsics start with 'llvm.'
246
247   assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
248
249 #define GET_FUNCTION_RECOGNIZER
250 #include "llvm/Intrinsics.gen"
251 #undef GET_FUNCTION_RECOGNIZER
252   assert(noAssert && "Invalid LLVM intrinsic name");
253   return 0;
254 }
255
256 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { 
257   assert(id < num_intrinsics && "Invalid intrinsic ID!");
258   const char * const Table[] = {
259     "not_intrinsic",
260 #define GET_INTRINSIC_NAME_TABLE
261 #include "llvm/Intrinsics.gen"
262 #undef GET_INTRINSIC_NAME_TABLE
263   };
264   if (numTys == 0)
265     return Table[id];
266   std::string Result(Table[id]);
267   for (unsigned i = 0; i < numTys; ++i) 
268     if (Tys[i])
269       Result += "." + Tys[i]->getDescription();
270   return Result;
271 }
272
273 const FunctionType *Intrinsic::getType(ID id, const Type **Tys, 
274                                        uint32_t numTys) {
275   const Type *ResultTy = NULL;
276   std::vector<const Type*> ArgTys;
277   bool IsVarArg = false;
278   
279 #define GET_INTRINSIC_GENERATOR
280 #include "llvm/Intrinsics.gen"
281 #undef GET_INTRINSIC_GENERATOR
282
283   return FunctionType::get(ResultTy, ArgTys, IsVarArg); 
284 }
285
286 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, 
287                                     unsigned numTys) {
288 // There can never be multiple globals with the same name of different types,
289 // because intrinsics must be a specific type.
290   return cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys), 
291                                                getType(id, Tys, numTys)));
292 }
293
294 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
295   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
296     if (CE->getOpcode() == Instruction::BitCast) {
297       if (isa<PointerType>(CE->getOperand(0)->getType()))
298         return StripPointerCasts(CE->getOperand(0));
299     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
300       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
301         if (!CE->getOperand(i)->isNullValue())
302           return Ptr;
303       return StripPointerCasts(CE->getOperand(0));
304     }
305     return Ptr;
306   }
307
308   if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
309     if (isa<PointerType>(CI->getOperand(0)->getType()))
310       return StripPointerCasts(CI->getOperand(0));
311   } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
312     if (GEP->hasAllZeroIndices())
313       return StripPointerCasts(GEP->getOperand(0));
314   }
315   return Ptr;
316 }
317
318 // vim: sw=2 ai