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