For PR1146:
[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, Function>;
48 template class SymbolTableListTraits<BasicBlock, Function, 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   BasicBlocks.setItemParent(this);
147   BasicBlocks.setParent(this);
148   ArgumentList.setItemParent(this);
149   ArgumentList.setParent(this);
150   SymTab = new ValueSymbolTable();
151
152   assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
153          && "LLVM functions cannot return aggregate values!");
154
155   // Create the arguments vector, all arguments start out unnamed.
156   for (unsigned i = 0, e = Ty->getNumParams(); i != e; ++i) {
157     assert(Ty->getParamType(i) != Type::VoidTy &&
158            "Cannot have void typed arguments!");
159     ArgumentList.push_back(new Argument(Ty->getParamType(i)));
160   }
161
162   // Make sure that we get added to a function
163   LeakDetector::addGarbageObject(this);
164
165   if (ParentModule)
166     ParentModule->getFunctionList().push_back(this);
167 }
168
169 Function::~Function() {
170   dropAllReferences();    // After this it is safe to delete instructions.
171
172   // Delete all of the method arguments and unlink from symbol table...
173   ArgumentList.clear();
174   ArgumentList.setParent(0);
175   delete SymTab;
176 }
177
178 void Function::setParent(Module *parent) {
179   if (getParent())
180     LeakDetector::addGarbageObject(this);
181   Parent = parent;
182   if (getParent())
183     LeakDetector::removeGarbageObject(this);
184 }
185
186 const FunctionType *Function::getFunctionType() const {
187   return cast<FunctionType>(getType()->getElementType());
188 }
189
190 bool Function::isVarArg() const {
191   return getFunctionType()->isVarArg();
192 }
193
194 const Type *Function::getReturnType() const {
195   return getFunctionType()->getReturnType();
196 }
197
198 void Function::removeFromParent() {
199   getParent()->getFunctionList().remove(this);
200 }
201
202 void Function::eraseFromParent() {
203   getParent()->getFunctionList().erase(this);
204 }
205
206 // dropAllReferences() - This function causes all the subinstructions to "let
207 // go" of all references that they are maintaining.  This allows one to
208 // 'delete' a whole class at a time, even though there may be circular
209 // references... first all references are dropped, and all use counts go to
210 // zero.  Then everything is deleted for real.  Note that no operations are
211 // valid on an object that has "dropped all references", except operator
212 // delete.
213 //
214 void Function::dropAllReferences() {
215   for (iterator I = begin(), E = end(); I != E; ++I)
216     I->dropAllReferences();
217   BasicBlocks.clear();    // Delete all basic blocks...
218 }
219
220 /// getIntrinsicID - This method returns the ID number of the specified
221 /// function, or Intrinsic::not_intrinsic if the function is not an
222 /// intrinsic, or if the pointer is null.  This value is always defined to be
223 /// zero to allow easy checking for whether a function is intrinsic or not.  The
224 /// particular intrinsic functions which correspond to this value are defined in
225 /// llvm/Intrinsics.h.
226 ///
227 unsigned Function::getIntrinsicID() const {
228   const ValueName *ValName = this->getValueName();
229   unsigned Len = ValName->getKeyLength();
230   const char *Name = ValName->getKeyData();
231   
232   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
233       || Name[2] != 'v' || Name[3] != 'm')
234     return 0;  // All intrinsics start with 'llvm.'
235
236   assert(Len != 5 && "'llvm.' is an invalid intrinsic name!");
237
238 #define GET_FUNCTION_RECOGNIZER
239 #include "llvm/Intrinsics.gen"
240 #undef GET_FUNCTION_RECOGNIZER
241   return 0;
242 }
243
244 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { 
245   assert(id < num_intrinsics && "Invalid intrinsic ID!");
246   const char * const Table[] = {
247     "not_intrinsic",
248 #define GET_INTRINSIC_NAME_TABLE
249 #include "llvm/Intrinsics.gen"
250 #undef GET_INTRINSIC_NAME_TABLE
251   };
252   if (numTys == 0)
253     return Table[id];
254   std::string Result(Table[id]);
255   for (unsigned i = 0; i < numTys; ++i) 
256     if (Tys[i])
257       Result += "." + Tys[i]->getDescription();
258   return Result;
259 }
260
261 const FunctionType *Intrinsic::getType(ID id, const Type **Tys, 
262                                        uint32_t numTys) {
263   const Type *ResultTy = NULL;
264   std::vector<const Type*> ArgTys;
265   bool IsVarArg = false;
266   
267 #define GET_INTRINSIC_GENERATOR
268 #include "llvm/Intrinsics.gen"
269 #undef GET_INTRINSIC_GENERATOR
270
271   return FunctionType::get(ResultTy, ArgTys, IsVarArg); 
272 }
273
274 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, 
275                                     unsigned numTys) {
276 // There can never be multiple globals with the same name of different types,
277 // because intrinsics must be a specific type.
278   return cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys), 
279                                                getType(id, Tys, numTys)));
280 }
281
282 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
283   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
284     if (CE->getOpcode() == Instruction::BitCast) {
285       if (isa<PointerType>(CE->getOperand(0)->getType()))
286         return StripPointerCasts(CE->getOperand(0));
287     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
288       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
289         if (!CE->getOperand(i)->isNullValue())
290           return Ptr;
291       return StripPointerCasts(CE->getOperand(0));
292     }
293     return Ptr;
294   }
295
296   if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
297     if (isa<PointerType>(CI->getOperand(0)->getType()))
298       return StripPointerCasts(CI->getOperand(0));
299   } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
300     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
301       if (!isa<Constant>(GEP->getOperand(i)) ||
302           !cast<Constant>(GEP->getOperand(i))->isNullValue())
303         return Ptr;
304     return StripPointerCasts(GEP->getOperand(0));
305   }
306   return Ptr;
307 }
308
309 // vim: sw=2 ai