e47798e12cd277b0dcb264f046209896ff20babc
[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 "SymbolTableListTraitsImpl.h"
20 #include "llvm/ADT/StringExtras.h"
21 using namespace llvm;
22
23 BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
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>::createSentinel() {
35   Argument *Ret = new Argument(Type::Int32Ty);
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>;
48 template class SymbolTableListTraits<BasicBlock, 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) {
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   setName(Name);
64 }
65
66 void Argument::setParent(Function *parent) {
67   if (getParent())
68     LeakDetector::addGarbageObject(this);
69   Parent = parent;
70   if (getParent())
71     LeakDetector::removeGarbageObject(this);
72 }
73
74 //===----------------------------------------------------------------------===//
75 // ParamAttrsList Implementation
76 //===----------------------------------------------------------------------===//
77
78 uint16_t
79 ParamAttrsList::getParamAttrs(uint16_t Index) const {
80   unsigned limit = attrs.size();
81   for (unsigned i = 0; i < limit; ++i)
82     if (attrs[i].index == Index)
83       return attrs[i].attrs;
84   return ParamAttr::None;
85 }
86
87
88 std::string 
89 ParamAttrsList::getParamAttrsText(uint16_t Attrs) {
90   std::string Result;
91   if (Attrs & ParamAttr::ZExt)
92     Result += "zext ";
93   if (Attrs & ParamAttr::SExt)
94     Result += "sext ";
95   if (Attrs & ParamAttr::NoReturn)
96     Result += "noreturn ";
97   if (Attrs & ParamAttr::NoUnwind)
98     Result += "nounwind ";
99   if (Attrs & ParamAttr::InReg)
100     Result += "inreg ";
101   if (Attrs & ParamAttr::StructRet)
102     Result += "sret ";  
103   return Result;
104 }
105
106 void
107 ParamAttrsList::addAttributes(uint16_t Index, uint16_t Attrs) {
108   // First, try to replace an existing one
109   for (unsigned i = 0; i < attrs.size(); ++i)
110     if (attrs[i].index == Index) {
111       attrs[i].attrs |= Attrs;
112       return;
113     }
114
115   // If not found, add a new one
116   ParamAttrsWithIndex Val;
117   Val.attrs = Attrs;
118   Val.index = Index;
119   attrs.push_back(Val);
120 }
121
122 void
123 ParamAttrsList::removeAttributes(uint16_t Index, uint16_t Attrs) {
124   // Find the index from which to remove the attributes
125   for (unsigned i = 0; i < attrs.size(); ++i)
126     if (attrs[i].index == Index) {
127       attrs[i].attrs &= ~Attrs;
128       if (attrs[i].attrs == ParamAttr::None)
129         attrs.erase(&attrs[i]);
130       return;
131     }
132
133   // The index wasn't found above
134   assert(0 && "Index not found for removeAttributes");
135 }
136
137 //===----------------------------------------------------------------------===//
138 // Function Implementation
139 //===----------------------------------------------------------------------===//
140
141 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
142                    const std::string &name, Module *ParentModule)
143   : GlobalValue(PointerType::get(Ty), Value::FunctionVal, 0, 0, Linkage, name) {
144   ParamAttrs = 0;
145   CallingConvention = 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
173 void Function::setParent(Module *parent) {
174   if (getParent())
175     LeakDetector::addGarbageObject(this);
176   Parent = parent;
177   if (getParent())
178     LeakDetector::removeGarbageObject(this);
179 }
180
181 const FunctionType *Function::getFunctionType() const {
182   return cast<FunctionType>(getType()->getElementType());
183 }
184
185 bool Function::isVarArg() const {
186   return getFunctionType()->isVarArg();
187 }
188
189 const Type *Function::getReturnType() const {
190   return getFunctionType()->getReturnType();
191 }
192
193 void Function::removeFromParent() {
194   getParent()->getFunctionList().remove(this);
195 }
196
197 void Function::eraseFromParent() {
198   getParent()->getFunctionList().erase(this);
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(bool noAssert) const {
223   const ValueName *ValName = this->getValueName();
224   if (!ValName)
225     return 0;
226   unsigned Len = ValName->getKeyLength();
227   const char *Name = ValName->getKeyData();
228   
229   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
230       || Name[2] != 'v' || Name[3] != 'm')
231     return 0;  // All intrinsics start with 'llvm.'
232
233   assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
234
235 #define GET_FUNCTION_RECOGNIZER
236 #include "llvm/Intrinsics.gen"
237 #undef GET_FUNCTION_RECOGNIZER
238   assert(noAssert && "Invalid LLVM intrinsic name");
239   return 0;
240 }
241
242 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { 
243   assert(id < num_intrinsics && "Invalid intrinsic ID!");
244   const char * const Table[] = {
245     "not_intrinsic",
246 #define GET_INTRINSIC_NAME_TABLE
247 #include "llvm/Intrinsics.gen"
248 #undef GET_INTRINSIC_NAME_TABLE
249   };
250   if (numTys == 0)
251     return Table[id];
252   std::string Result(Table[id]);
253   for (unsigned i = 0; i < numTys; ++i) 
254     if (Tys[i])
255       Result += "." + Tys[i]->getDescription();
256   return Result;
257 }
258
259 const FunctionType *Intrinsic::getType(ID id, const Type **Tys, 
260                                        uint32_t numTys) {
261   const Type *ResultTy = NULL;
262   std::vector<const Type*> ArgTys;
263   bool IsVarArg = false;
264   
265 #define GET_INTRINSIC_GENERATOR
266 #include "llvm/Intrinsics.gen"
267 #undef GET_INTRINSIC_GENERATOR
268
269   return FunctionType::get(ResultTy, ArgTys, IsVarArg); 
270 }
271
272 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, 
273                                     unsigned numTys) {
274 // There can never be multiple globals with the same name of different types,
275 // because intrinsics must be a specific type.
276   return cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys), 
277                                                getType(id, Tys, numTys)));
278 }
279
280 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
281   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
282     if (CE->getOpcode() == Instruction::BitCast) {
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 (BitCastInst *CI = dyn_cast<BitCastInst>(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