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