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