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