Add an accessor to Function so that Passes can easily get access to the context.
[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/ManagedStatic.h"
20 #include "llvm/Support/StringPool.h"
21 #include "llvm/System/RWMutex.h"
22 #include "llvm/System/Threading.h"
23 #include "SymbolTableListTraitsImpl.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/StringExtras.h"
26 using namespace llvm;
27
28
29 // Explicit instantiations of SymbolTableListTraits since some of the methods
30 // are not in the public header file...
31 template class SymbolTableListTraits<Argument, Function>;
32 template class SymbolTableListTraits<BasicBlock, Function>;
33
34 //===----------------------------------------------------------------------===//
35 // Argument Implementation
36 //===----------------------------------------------------------------------===//
37
38 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
39   : Value(Ty, Value::ArgumentVal) {
40   Parent = 0;
41
42   // Make sure that we get added to a function
43   LeakDetector::addGarbageObject(this);
44
45   if (Par)
46     Par->getArgumentList().push_back(this);
47   setName(Name);
48 }
49
50 void Argument::setParent(Function *parent) {
51   if (getParent())
52     LeakDetector::addGarbageObject(this);
53   Parent = parent;
54   if (getParent())
55     LeakDetector::removeGarbageObject(this);
56 }
57
58 /// getArgNo - Return the index of this formal argument in its containing
59 /// function.  For example in "void foo(int a, float b)" a is 0 and b is 1. 
60 unsigned Argument::getArgNo() const {
61   const Function *F = getParent();
62   assert(F && "Argument is not in a function");
63   
64   Function::const_arg_iterator AI = F->arg_begin();
65   unsigned ArgIdx = 0;
66   for (; &*AI != this; ++AI)
67     ++ArgIdx;
68
69   return ArgIdx;
70 }
71
72 /// hasByValAttr - Return true if this argument has the byval attribute on it
73 /// in its containing function.
74 bool Argument::hasByValAttr() const {
75   if (!isa<PointerType>(getType())) return false;
76   return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
77 }
78
79 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
80 /// it in its containing function.
81 bool Argument::hasNoAliasAttr() const {
82   if (!isa<PointerType>(getType())) return false;
83   return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
84 }
85
86 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
87 /// on it in its containing function.
88 bool Argument::hasNoCaptureAttr() const {
89   if (!isa<PointerType>(getType())) return false;
90   return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture);
91 }
92
93 /// hasSRetAttr - Return true if this argument has the sret attribute on
94 /// it in its containing function.
95 bool Argument::hasStructRetAttr() const {
96   if (!isa<PointerType>(getType())) return false;
97   if (this != getParent()->arg_begin())
98     return false; // StructRet param must be first param
99   return getParent()->paramHasAttr(1, Attribute::StructRet);
100 }
101
102 /// addAttr - Add a Attribute to an argument
103 void Argument::addAttr(Attributes attr) {
104   getParent()->addAttribute(getArgNo() + 1, attr);
105 }
106
107 /// removeAttr - Remove a Attribute from an argument
108 void Argument::removeAttr(Attributes attr) {
109   getParent()->removeAttribute(getArgNo() + 1, attr);
110 }
111
112
113 //===----------------------------------------------------------------------===//
114 // Helper Methods in Function
115 //===----------------------------------------------------------------------===//
116
117 LLVMContext* Function::getContext() {
118   Module* M = getParent();
119   if (M) return &M->getContext();
120   return 0;
121 }
122
123 const FunctionType *Function::getFunctionType() const {
124   return cast<FunctionType>(getType()->getElementType());
125 }
126
127 bool Function::isVarArg() const {
128   return getFunctionType()->isVarArg();
129 }
130
131 const Type *Function::getReturnType() const {
132   return getFunctionType()->getReturnType();
133 }
134
135 void Function::removeFromParent() {
136   getParent()->getFunctionList().remove(this);
137 }
138
139 void Function::eraseFromParent() {
140   getParent()->getFunctionList().erase(this);
141 }
142
143 //===----------------------------------------------------------------------===//
144 // Function Implementation
145 //===----------------------------------------------------------------------===//
146
147 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
148                    const std::string &name, Module *ParentModule)
149   : GlobalValue(PointerType::getUnqual(Ty), 
150                 Value::FunctionVal, 0, 0, Linkage, name) {
151   assert(FunctionType::isValidReturnType(getReturnType()) &&
152          !isa<OpaqueType>(getReturnType()) && "invalid return type");
153   SymTab = new ValueSymbolTable();
154
155   // If the function has arguments, mark them as lazily built.
156   if (Ty->getNumParams())
157     SubclassData = 1;   // Set the "has lazy arguments" bit.
158   
159   // Make sure that we get added to a function
160   LeakDetector::addGarbageObject(this);
161
162   if (ParentModule)
163     ParentModule->getFunctionList().push_back(this);
164
165   // Ensure intrinsics have the right parameter attributes.
166   if (unsigned IID = getIntrinsicID())
167     setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
168
169 }
170
171 Function::~Function() {
172   dropAllReferences();    // After this it is safe to delete instructions.
173
174   // Delete all of the method arguments and unlink from symbol table...
175   ArgumentList.clear();
176   delete SymTab;
177
178   // Remove the function from the on-the-side GC table.
179   clearGC();
180 }
181
182 void Function::BuildLazyArguments() const {
183   // Create the arguments vector, all arguments start out unnamed.
184   const FunctionType *FT = getFunctionType();
185   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
186     assert(FT->getParamType(i) != Type::VoidTy &&
187            "Cannot have void typed arguments!");
188     ArgumentList.push_back(new Argument(FT->getParamType(i)));
189   }
190   
191   // Clear the lazy arguments bit.
192   const_cast<Function*>(this)->SubclassData &= ~1;
193 }
194
195 size_t Function::arg_size() const {
196   return getFunctionType()->getNumParams();
197 }
198 bool Function::arg_empty() const {
199   return getFunctionType()->getNumParams() == 0;
200 }
201
202 void Function::setParent(Module *parent) {
203   if (getParent())
204     LeakDetector::addGarbageObject(this);
205   Parent = parent;
206   if (getParent())
207     LeakDetector::removeGarbageObject(this);
208 }
209
210 // dropAllReferences() - This function causes all the subinstructions to "let
211 // go" of all references that they are maintaining.  This allows one to
212 // 'delete' a whole class at a time, even though there may be circular
213 // references... first all references are dropped, and all use counts go to
214 // zero.  Then everything is deleted for real.  Note that no operations are
215 // valid on an object that has "dropped all references", except operator
216 // delete.
217 //
218 void Function::dropAllReferences() {
219   for (iterator I = begin(), E = end(); I != E; ++I)
220     I->dropAllReferences();
221   BasicBlocks.clear();    // Delete all basic blocks...
222 }
223
224 void Function::addAttribute(unsigned i, Attributes attr) {
225   AttrListPtr PAL = getAttributes();
226   PAL = PAL.addAttr(i, attr);
227   setAttributes(PAL);
228 }
229
230 void Function::removeAttribute(unsigned i, Attributes attr) {
231   AttrListPtr PAL = getAttributes();
232   PAL = PAL.removeAttr(i, attr);
233   setAttributes(PAL);
234 }
235
236 // Maintain the GC name for each function in an on-the-side table. This saves
237 // allocating an additional word in Function for programs which do not use GC
238 // (i.e., most programs) at the cost of increased overhead for clients which do
239 // use GC.
240 static DenseMap<const Function*,PooledStringPtr> *GCNames;
241 static StringPool *GCNamePool;
242 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
243
244 bool Function::hasGC() const {
245   sys::SmartScopedReader<true> Reader(&*GCLock);
246   return GCNames && GCNames->count(this);
247 }
248
249 const char *Function::getGC() const {
250   assert(hasGC() && "Function has no collector");
251   sys::SmartScopedReader<true> Reader(&*GCLock);
252   return *(*GCNames)[this];
253 }
254
255 void Function::setGC(const char *Str) {
256   sys::SmartScopedWriter<true> Writer(&*GCLock);
257   if (!GCNamePool)
258     GCNamePool = new StringPool();
259   if (!GCNames)
260     GCNames = new DenseMap<const Function*,PooledStringPtr>();
261   (*GCNames)[this] = GCNamePool->intern(Str);
262 }
263
264 void Function::clearGC() {
265   sys::SmartScopedWriter<true> Writer(&*GCLock);
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   /// hasAddressTaken - returns true if there are any uses of this function
382   /// other than direct calls or invokes to it.
383 bool Function::hasAddressTaken() const {
384   for (Value::use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
385     if (I.getOperandNo() != 0 ||
386         (!isa<CallInst>(*I) && !isa<InvokeInst>(*I)))
387       return true;
388   }
389   return false;
390 }
391
392 // vim: sw=2 ai