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