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