Expose parameter attributes via C bindings.
[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 is distributed under the University of Illinois Open Source
6 // 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/IntrinsicInst.h"
17 #include "llvm/CodeGen/ValueTypes.h"
18 #include "llvm/Support/LeakDetector.h"
19 #include "llvm/Support/StringPool.h"
20 #include "SymbolTableListTraitsImpl.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/StringExtras.h"
24 using namespace llvm;
25
26 BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
27   BasicBlock *Ret = BasicBlock::Create();
28   // This should not be garbage monitored.
29   LeakDetector::removeGarbageObject(Ret);
30   return Ret;
31 }
32
33 iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {
34   return F->getBasicBlockList();
35 }
36
37 Argument *ilist_traits<Argument>::createSentinel() {
38   Argument *Ret = new Argument(Type::Int32Ty);
39   // This should not be garbage monitored.
40   LeakDetector::removeGarbageObject(Ret);
41   return Ret;
42 }
43
44 iplist<Argument> &ilist_traits<Argument>::getList(Function *F) {
45   return F->getArgumentList();
46 }
47
48 // Explicit instantiations of SymbolTableListTraits since some of the methods
49 // are not in the public header file...
50 template class SymbolTableListTraits<Argument, Function>;
51 template class SymbolTableListTraits<BasicBlock, Function>;
52
53 //===----------------------------------------------------------------------===//
54 // Argument Implementation
55 //===----------------------------------------------------------------------===//
56
57 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
58   : Value(Ty, Value::ArgumentVal) {
59   Parent = 0;
60
61   // Make sure that we get added to a function
62   LeakDetector::addGarbageObject(this);
63
64   if (Par)
65     Par->getArgumentList().push_back(this);
66   setName(Name);
67 }
68
69 void Argument::setParent(Function *parent) {
70   if (getParent())
71     LeakDetector::addGarbageObject(this);
72   Parent = parent;
73   if (getParent())
74     LeakDetector::removeGarbageObject(this);
75 }
76
77 /// getArgNo - Return the index of this formal argument in its containing
78 /// function.  For example in "void foo(int a, float b)" a is 0 and b is 1. 
79 unsigned Argument::getArgNo() const {
80   const Function *F = getParent();
81   assert(F && "Argument is not in a function");
82   
83   Function::const_arg_iterator AI = F->arg_begin();
84   unsigned ArgIdx = 0;
85   for (; &*AI != this; ++AI)
86     ++ArgIdx;
87
88   return ArgIdx;
89 }
90
91 /// hasByValAttr - Return true if this argument has the byval attribute on it
92 /// in its containing function.
93 bool Argument::hasByValAttr() const {
94   if (!isa<PointerType>(getType())) return false;
95   return getParent()->paramHasAttr(getArgNo()+1, ParamAttr::ByVal);
96 }
97
98 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
99 /// it in its containing function.
100 bool Argument::hasNoAliasAttr() const {
101   if (!isa<PointerType>(getType())) return false;
102   return getParent()->paramHasAttr(getArgNo()+1, ParamAttr::NoAlias);
103 }
104
105 /// hasSRetAttr - Return true if this argument has the sret attribute on
106 /// it in its containing function.
107 bool Argument::hasStructRetAttr() const {
108   if (!isa<PointerType>(getType())) return false;
109   if (this != getParent()->arg_begin()) return false; // StructRet param must be first param
110   return getParent()->paramHasAttr(1, ParamAttr::StructRet);
111 }
112
113 /// addAttr - Add a ParamAttr to an argument
114 void Argument::addAttr(ParameterAttributes attr) {
115   getParent()->setParamAttrs(
116     getParent()->getParamAttrs().addAttr(getArgNo() + 1, attr));
117 }
118   
119 /// removeAttr - Remove a ParamAttr from an argument
120 void Argument::removeAttr(ParameterAttributes attr) {
121   getParent()->setParamAttrs(
122     getParent()->getParamAttrs().removeAttr(getArgNo() + 1, attr));
123 }
124
125
126
127 //===----------------------------------------------------------------------===//
128 // Helper Methods in Function
129 //===----------------------------------------------------------------------===//
130
131 const FunctionType *Function::getFunctionType() const {
132   return cast<FunctionType>(getType()->getElementType());
133 }
134
135 bool Function::isVarArg() const {
136   return getFunctionType()->isVarArg();
137 }
138
139 const Type *Function::getReturnType() const {
140   return getFunctionType()->getReturnType();
141 }
142
143 void Function::removeFromParent() {
144   getParent()->getFunctionList().remove(this);
145 }
146
147 void Function::eraseFromParent() {
148   getParent()->getFunctionList().erase(this);
149 }
150
151 //===----------------------------------------------------------------------===//
152 // Function Implementation
153 //===----------------------------------------------------------------------===//
154
155 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
156                    const std::string &name, Module *ParentModule)
157   : GlobalValue(PointerType::getUnqual(Ty), 
158                 Value::FunctionVal, 0, 0, Linkage, name) {
159   SymTab = new ValueSymbolTable();
160
161   assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy
162           || isa<StructType>(getReturnType()))
163          && "LLVM functions cannot return aggregate values!");
164
165   // If the function has arguments, mark them as lazily built.
166   if (Ty->getNumParams())
167     SubclassData = 1;   // Set the "has lazy arguments" bit.
168   
169   // Make sure that we get added to a function
170   LeakDetector::addGarbageObject(this);
171
172   if (ParentModule)
173     ParentModule->getFunctionList().push_back(this);
174
175   // Ensure intrinsics have the right parameter attributes.
176   if (unsigned IID = getIntrinsicID(true))
177     setParamAttrs(Intrinsic::getParamAttrs(Intrinsic::ID(IID)));
178 }
179
180 Function::~Function() {
181   dropAllReferences();    // After this it is safe to delete instructions.
182
183   // Delete all of the method arguments and unlink from symbol table...
184   ArgumentList.clear();
185   delete SymTab;
186
187   // Remove the function from the on-the-side collector table.
188   clearCollector();
189 }
190
191 void Function::BuildLazyArguments() const {
192   // Create the arguments vector, all arguments start out unnamed.
193   const FunctionType *FT = getFunctionType();
194   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
195     assert(FT->getParamType(i) != Type::VoidTy &&
196            "Cannot have void typed arguments!");
197     ArgumentList.push_back(new Argument(FT->getParamType(i)));
198   }
199   
200   // Clear the lazy arguments bit.
201   const_cast<Function*>(this)->SubclassData &= ~1;
202 }
203
204 size_t Function::arg_size() const {
205   return getFunctionType()->getNumParams();
206 }
207 bool Function::arg_empty() const {
208   return getFunctionType()->getNumParams() == 0;
209 }
210
211 void Function::setParent(Module *parent) {
212   if (getParent())
213     LeakDetector::addGarbageObject(this);
214   Parent = parent;
215   if (getParent())
216     LeakDetector::removeGarbageObject(this);
217 }
218
219 // dropAllReferences() - This function causes all the subinstructions to "let
220 // go" of all references that they are maintaining.  This allows one to
221 // 'delete' a whole class at a time, even though there may be circular
222 // references... first all references are dropped, and all use counts go to
223 // zero.  Then everything is deleted for real.  Note that no operations are
224 // valid on an object that has "dropped all references", except operator
225 // delete.
226 //
227 void Function::dropAllReferences() {
228   for (iterator I = begin(), E = end(); I != E; ++I)
229     I->dropAllReferences();
230   BasicBlocks.clear();    // Delete all basic blocks...
231 }
232
233 void Function::setDoesNotThrow(bool doesNotThrow) {
234   PAListPtr PAL = getParamAttrs();
235   if (doesNotThrow)
236     PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
237   else
238     PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
239   setParamAttrs(PAL);
240 }
241
242 // Maintain the collector name for each function in an on-the-side table. This
243 // saves allocating an additional word in Function for programs which do not use
244 // GC (i.e., most programs) at the cost of increased overhead for clients which
245 // do use GC.
246 static DenseMap<const Function*,PooledStringPtr> *CollectorNames;
247 static StringPool *CollectorNamePool;
248
249 bool Function::hasCollector() const {
250   return CollectorNames && CollectorNames->count(this);
251 }
252
253 const char *Function::getCollector() const {
254   assert(hasCollector() && "Function has no collector");
255   return *(*CollectorNames)[this];
256 }
257
258 void Function::setCollector(const char *Str) {
259   if (!CollectorNamePool)
260     CollectorNamePool = new StringPool();
261   if (!CollectorNames)
262     CollectorNames = new DenseMap<const Function*,PooledStringPtr>();
263   (*CollectorNames)[this] = CollectorNamePool->intern(Str);
264 }
265
266 void Function::clearCollector() {
267   if (CollectorNames) {
268     CollectorNames->erase(this);
269     if (CollectorNames->empty()) {
270       delete CollectorNames;
271       CollectorNames = 0;
272       if (CollectorNamePool->empty()) {
273         delete CollectorNamePool;
274         CollectorNamePool = 0;
275       }
276     }
277   }
278 }
279
280 /// getIntrinsicID - This method returns the ID number of the specified
281 /// function, or Intrinsic::not_intrinsic if the function is not an
282 /// intrinsic, or if the pointer is null.  This value is always defined to be
283 /// zero to allow easy checking for whether a function is intrinsic or not.  The
284 /// particular intrinsic functions which correspond to this value are defined in
285 /// llvm/Intrinsics.h.
286 ///
287 unsigned Function::getIntrinsicID(bool noAssert) const {
288   const ValueName *ValName = this->getValueName();
289   if (!ValName)
290     return 0;
291   unsigned Len = ValName->getKeyLength();
292   const char *Name = ValName->getKeyData();
293   
294   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
295       || Name[2] != 'v' || Name[3] != 'm')
296     return 0;  // All intrinsics start with 'llvm.'
297
298   assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
299
300 #define GET_FUNCTION_RECOGNIZER
301 #include "llvm/Intrinsics.gen"
302 #undef GET_FUNCTION_RECOGNIZER
303   assert(noAssert && "Invalid LLVM intrinsic name");
304   return 0;
305 }
306
307 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { 
308   assert(id < num_intrinsics && "Invalid intrinsic ID!");
309   const char * const Table[] = {
310     "not_intrinsic",
311 #define GET_INTRINSIC_NAME_TABLE
312 #include "llvm/Intrinsics.gen"
313 #undef GET_INTRINSIC_NAME_TABLE
314   };
315   if (numTys == 0)
316     return Table[id];
317   std::string Result(Table[id]);
318   for (unsigned i = 0; i < numTys; ++i) 
319     if (Tys[i])
320       Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
321   return Result;
322 }
323
324 const FunctionType *Intrinsic::getType(ID id, const Type **Tys, 
325                                        unsigned numTys) {
326   const Type *ResultTy = NULL;
327   std::vector<const Type*> ArgTys;
328   bool IsVarArg = false;
329   
330 #define GET_INTRINSIC_GENERATOR
331 #include "llvm/Intrinsics.gen"
332 #undef GET_INTRINSIC_GENERATOR
333
334   return FunctionType::get(ResultTy, ArgTys, IsVarArg); 
335 }
336
337 PAListPtr Intrinsic::getParamAttrs(ID id) {
338   ParameterAttributes Attr = ParamAttr::None;
339
340 #define GET_INTRINSIC_ATTRIBUTES
341 #include "llvm/Intrinsics.gen"
342 #undef GET_INTRINSIC_ATTRIBUTES
343
344   // Intrinsics cannot throw exceptions.
345   Attr |= ParamAttr::NoUnwind;
346
347   ParamAttrsWithIndex PAWI = ParamAttrsWithIndex::get(0, Attr);
348   return PAListPtr::get(&PAWI, 1);
349 }
350
351 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, 
352                                     unsigned numTys) {
353   // There can never be multiple globals with the same name of different types,
354   // because intrinsics must be a specific type.
355   return
356     cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
357                                           getType(id, Tys, numTys)));
358 }
359
360 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
361   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
362     if (CE->getOpcode() == Instruction::BitCast) {
363       if (isa<PointerType>(CE->getOperand(0)->getType()))
364         return StripPointerCasts(CE->getOperand(0));
365     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
366       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
367         if (!CE->getOperand(i)->isNullValue())
368           return Ptr;
369       return StripPointerCasts(CE->getOperand(0));
370     }
371     return Ptr;
372   }
373
374   if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
375     if (isa<PointerType>(CI->getOperand(0)->getType()))
376       return StripPointerCasts(CI->getOperand(0));
377   } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
378     if (GEP->hasAllZeroIndices())
379       return StripPointerCasts(GEP->getOperand(0));
380   }
381   return Ptr;
382 }
383
384 // vim: sw=2 ai