Rename some GC classes so that their roll will hopefully be clearer.
[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())
110     return false; // StructRet param must be first param
111   return getParent()->paramHasAttr(1, ParamAttr::StructRet);
112 }
113
114 /// addAttr - Add a ParamAttr to an argument
115 void Argument::addAttr(ParameterAttributes attr) {
116   getParent()->addParamAttr(getArgNo() + 1, attr);
117 }
118
119 /// removeAttr - Remove a ParamAttr from an argument
120 void Argument::removeAttr(ParameterAttributes attr) {
121   getParent()->removeParamAttr(getArgNo() + 1, attr);
122 }
123
124
125 //===----------------------------------------------------------------------===//
126 // Helper Methods in Function
127 //===----------------------------------------------------------------------===//
128
129 const FunctionType *Function::getFunctionType() const {
130   return cast<FunctionType>(getType()->getElementType());
131 }
132
133 bool Function::isVarArg() const {
134   return getFunctionType()->isVarArg();
135 }
136
137 const Type *Function::getReturnType() const {
138   return getFunctionType()->getReturnType();
139 }
140
141 void Function::removeFromParent() {
142   getParent()->getFunctionList().remove(this);
143 }
144
145 void Function::eraseFromParent() {
146   getParent()->getFunctionList().erase(this);
147 }
148
149 //===----------------------------------------------------------------------===//
150 // Function Implementation
151 //===----------------------------------------------------------------------===//
152
153 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
154                    const std::string &name, Module *ParentModule)
155   : GlobalValue(PointerType::getUnqual(Ty), 
156                 Value::FunctionVal, 0, 0, Linkage, name) {
157   SymTab = new ValueSymbolTable();
158
159   assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy
160           || isa<StructType>(getReturnType()))
161          && "LLVM functions cannot return aggregate values!");
162
163   // If the function has arguments, mark them as lazily built.
164   if (Ty->getNumParams())
165     SubclassData = 1;   // Set the "has lazy arguments" bit.
166   
167   // Make sure that we get added to a function
168   LeakDetector::addGarbageObject(this);
169
170   if (ParentModule)
171     ParentModule->getFunctionList().push_back(this);
172
173   // Ensure intrinsics have the right parameter attributes.
174   if (unsigned IID = getIntrinsicID(true))
175     setParamAttrs(Intrinsic::getParamAttrs(Intrinsic::ID(IID)));
176 }
177
178 Function::~Function() {
179   dropAllReferences();    // After this it is safe to delete instructions.
180
181   // Delete all of the method arguments and unlink from symbol table...
182   ArgumentList.clear();
183   delete SymTab;
184
185   // Remove the function from the on-the-side GC table.
186   clearGC();
187 }
188
189 void Function::BuildLazyArguments() const {
190   // Create the arguments vector, all arguments start out unnamed.
191   const FunctionType *FT = getFunctionType();
192   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
193     assert(FT->getParamType(i) != Type::VoidTy &&
194            "Cannot have void typed arguments!");
195     ArgumentList.push_back(new Argument(FT->getParamType(i)));
196   }
197   
198   // Clear the lazy arguments bit.
199   const_cast<Function*>(this)->SubclassData &= ~1;
200 }
201
202 size_t Function::arg_size() const {
203   return getFunctionType()->getNumParams();
204 }
205 bool Function::arg_empty() const {
206   return getFunctionType()->getNumParams() == 0;
207 }
208
209 void Function::setParent(Module *parent) {
210   if (getParent())
211     LeakDetector::addGarbageObject(this);
212   Parent = parent;
213   if (getParent())
214     LeakDetector::removeGarbageObject(this);
215 }
216
217 // dropAllReferences() - This function causes all the subinstructions to "let
218 // go" of all references that they are maintaining.  This allows one to
219 // 'delete' a whole class at a time, even though there may be circular
220 // references... first all references are dropped, and all use counts go to
221 // zero.  Then everything is deleted for real.  Note that no operations are
222 // valid on an object that has "dropped all references", except operator
223 // delete.
224 //
225 void Function::dropAllReferences() {
226   for (iterator I = begin(), E = end(); I != E; ++I)
227     I->dropAllReferences();
228   BasicBlocks.clear();    // Delete all basic blocks...
229 }
230
231 void Function::addParamAttr(unsigned i, ParameterAttributes attr) {
232   PAListPtr PAL = getParamAttrs();
233   PAL = PAL.addAttr(i, attr);
234   setParamAttrs(PAL);
235 }
236
237 void Function::removeParamAttr(unsigned i, ParameterAttributes attr) {
238   PAListPtr PAL = getParamAttrs();
239   PAL = PAL.removeAttr(i, attr);
240   setParamAttrs(PAL);
241 }
242
243 // Maintain the GC name for each function in an on-the-side table. This saves
244 // allocating an additional word in Function for programs which do not use GC
245 // (i.e., most programs) at the cost of increased overhead for clients which do
246 // use GC.
247 static DenseMap<const Function*,PooledStringPtr> *GCNames;
248 static StringPool *GCNamePool;
249
250 bool Function::hasGC() const {
251   return GCNames && GCNames->count(this);
252 }
253
254 const char *Function::getGC() const {
255   assert(hasGC() && "Function has no collector");
256   return *(*GCNames)[this];
257 }
258
259 void Function::setGC(const char *Str) {
260   if (!GCNamePool)
261     GCNamePool = new StringPool();
262   if (!GCNames)
263     GCNames = new DenseMap<const Function*,PooledStringPtr>();
264   (*GCNames)[this] = GCNamePool->intern(Str);
265 }
266
267 void Function::clearGC() {
268   if (GCNames) {
269     GCNames->erase(this);
270     if (GCNames->empty()) {
271       delete GCNames;
272       GCNames = 0;
273       if (GCNamePool->empty()) {
274         delete GCNamePool;
275         GCNamePool = 0;
276       }
277     }
278   }
279 }
280
281 /// copyAttributesFrom - copy all additional attributes (those not needed to
282 /// create a Function) from the Function Src to this one.
283 void Function::copyAttributesFrom(const GlobalValue *Src) {
284   assert(isa<Function>(Src) && "Expected a Function!");
285   GlobalValue::copyAttributesFrom(Src);
286   const Function *SrcF = cast<Function>(Src);
287   setCallingConv(SrcF->getCallingConv());
288   setParamAttrs(SrcF->getParamAttrs());
289   if (SrcF->hasGC())
290     setGC(SrcF->getGC());
291   else
292     clearGC();
293 }
294
295 /// getIntrinsicID - This method returns the ID number of the specified
296 /// function, or Intrinsic::not_intrinsic if the function is not an
297 /// intrinsic, or if the pointer is null.  This value is always defined to be
298 /// zero to allow easy checking for whether a function is intrinsic or not.  The
299 /// particular intrinsic functions which correspond to this value are defined in
300 /// llvm/Intrinsics.h.
301 ///
302 unsigned Function::getIntrinsicID(bool noAssert) const {
303   const ValueName *ValName = this->getValueName();
304   if (!ValName)
305     return 0;
306   unsigned Len = ValName->getKeyLength();
307   const char *Name = ValName->getKeyData();
308   
309   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
310       || Name[2] != 'v' || Name[3] != 'm')
311     return 0;  // All intrinsics start with 'llvm.'
312
313   assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
314
315 #define GET_FUNCTION_RECOGNIZER
316 #include "llvm/Intrinsics.gen"
317 #undef GET_FUNCTION_RECOGNIZER
318   assert(noAssert && "Invalid LLVM intrinsic name");
319   return 0;
320 }
321
322 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { 
323   assert(id < num_intrinsics && "Invalid intrinsic ID!");
324   const char * const Table[] = {
325     "not_intrinsic",
326 #define GET_INTRINSIC_NAME_TABLE
327 #include "llvm/Intrinsics.gen"
328 #undef GET_INTRINSIC_NAME_TABLE
329   };
330   if (numTys == 0)
331     return Table[id];
332   std::string Result(Table[id]);
333   for (unsigned i = 0; i < numTys; ++i) {
334     if (const PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
335       Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) + 
336                 MVT::getMVT(PTyp->getElementType()).getMVTString();
337     }
338     else if (Tys[i])
339       Result += "." + MVT::getMVT(Tys[i]).getMVTString();
340   }
341   return Result;
342 }
343
344 const FunctionType *Intrinsic::getType(ID id, const Type **Tys, 
345                                        unsigned numTys) {
346   const Type *ResultTy = NULL;
347   std::vector<const Type*> ArgTys;
348   bool IsVarArg = false;
349   
350 #define GET_INTRINSIC_GENERATOR
351 #include "llvm/Intrinsics.gen"
352 #undef GET_INTRINSIC_GENERATOR
353
354   return FunctionType::get(ResultTy, ArgTys, IsVarArg); 
355 }
356
357 PAListPtr Intrinsic::getParamAttrs(ID id) {
358   ParameterAttributes Attr = ParamAttr::None;
359
360 #define GET_INTRINSIC_ATTRIBUTES
361 #include "llvm/Intrinsics.gen"
362 #undef GET_INTRINSIC_ATTRIBUTES
363
364   // Intrinsics cannot throw exceptions.
365   Attr |= ParamAttr::NoUnwind;
366
367   ParamAttrsWithIndex PAWI = ParamAttrsWithIndex::get(0, Attr);
368   return PAListPtr::get(&PAWI, 1);
369 }
370
371 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, 
372                                     unsigned numTys) {
373   // There can never be multiple globals with the same name of different types,
374   // because intrinsics must be a specific type.
375   return
376     cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
377                                           getType(id, Tys, numTys)));
378 }
379
380 // vim: sw=2 ai