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