Merge System into Support.
[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.
231   while (!BasicBlocks.empty()) {
232     // If there is still a reference to the block, it must be a 'blockaddress'
233     // constant pointing to it.  Just replace the BlockAddress with undef.
234     BasicBlock *BB = BasicBlocks.begin();
235     if (!BB->use_empty()) {
236       BlockAddress *BA = cast<BlockAddress>(BB->use_back());
237       BA->replaceAllUsesWith(UndefValue::get(BA->getType()));
238       BA->destroyConstant();
239     }
240     
241     BB->eraseFromParent();
242   }
243 }
244
245 void Function::addAttribute(unsigned i, Attributes attr) {
246   AttrListPtr PAL = getAttributes();
247   PAL = PAL.addAttr(i, attr);
248   setAttributes(PAL);
249 }
250
251 void Function::removeAttribute(unsigned i, Attributes attr) {
252   AttrListPtr PAL = getAttributes();
253   PAL = PAL.removeAttr(i, attr);
254   setAttributes(PAL);
255 }
256
257 // Maintain the GC name for each function in an on-the-side table. This saves
258 // allocating an additional word in Function for programs which do not use GC
259 // (i.e., most programs) at the cost of increased overhead for clients which do
260 // use GC.
261 static DenseMap<const Function*,PooledStringPtr> *GCNames;
262 static StringPool *GCNamePool;
263 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
264
265 bool Function::hasGC() const {
266   sys::SmartScopedReader<true> Reader(*GCLock);
267   return GCNames && GCNames->count(this);
268 }
269
270 const char *Function::getGC() const {
271   assert(hasGC() && "Function has no collector");
272   sys::SmartScopedReader<true> Reader(*GCLock);
273   return *(*GCNames)[this];
274 }
275
276 void Function::setGC(const char *Str) {
277   sys::SmartScopedWriter<true> Writer(*GCLock);
278   if (!GCNamePool)
279     GCNamePool = new StringPool();
280   if (!GCNames)
281     GCNames = new DenseMap<const Function*,PooledStringPtr>();
282   (*GCNames)[this] = GCNamePool->intern(Str);
283 }
284
285 void Function::clearGC() {
286   sys::SmartScopedWriter<true> Writer(*GCLock);
287   if (GCNames) {
288     GCNames->erase(this);
289     if (GCNames->empty()) {
290       delete GCNames;
291       GCNames = 0;
292       if (GCNamePool->empty()) {
293         delete GCNamePool;
294         GCNamePool = 0;
295       }
296     }
297   }
298 }
299
300 /// copyAttributesFrom - copy all additional attributes (those not needed to
301 /// create a Function) from the Function Src to this one.
302 void Function::copyAttributesFrom(const GlobalValue *Src) {
303   assert(isa<Function>(Src) && "Expected a Function!");
304   GlobalValue::copyAttributesFrom(Src);
305   const Function *SrcF = cast<Function>(Src);
306   setCallingConv(SrcF->getCallingConv());
307   setAttributes(SrcF->getAttributes());
308   if (SrcF->hasGC())
309     setGC(SrcF->getGC());
310   else
311     clearGC();
312 }
313
314 /// getIntrinsicID - This method returns the ID number of the specified
315 /// function, or Intrinsic::not_intrinsic if the function is not an
316 /// intrinsic, or if the pointer is null.  This value is always defined to be
317 /// zero to allow easy checking for whether a function is intrinsic or not.  The
318 /// particular intrinsic functions which correspond to this value are defined in
319 /// llvm/Intrinsics.h.
320 ///
321 unsigned Function::getIntrinsicID() const {
322   const ValueName *ValName = this->getValueName();
323   if (!ValName)
324     return 0;
325   unsigned Len = ValName->getKeyLength();
326   const char *Name = ValName->getKeyData();
327   
328   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
329       || Name[2] != 'v' || Name[3] != 'm')
330     return 0;  // All intrinsics start with 'llvm.'
331
332 #define GET_FUNCTION_RECOGNIZER
333 #include "llvm/Intrinsics.gen"
334 #undef GET_FUNCTION_RECOGNIZER
335   return 0;
336 }
337
338 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { 
339   assert(id < num_intrinsics && "Invalid intrinsic ID!");
340   const char * const Table[] = {
341     "not_intrinsic",
342 #define GET_INTRINSIC_NAME_TABLE
343 #include "llvm/Intrinsics.gen"
344 #undef GET_INTRINSIC_NAME_TABLE
345   };
346   if (numTys == 0)
347     return Table[id];
348   std::string Result(Table[id]);
349   for (unsigned i = 0; i < numTys; ++i) {
350     if (const PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
351       Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) + 
352                 EVT::getEVT(PTyp->getElementType()).getEVTString();
353     }
354     else if (Tys[i])
355       Result += "." + EVT::getEVT(Tys[i]).getEVTString();
356   }
357   return Result;
358 }
359
360 const FunctionType *Intrinsic::getType(LLVMContext &Context,
361                                        ID id, const Type **Tys, 
362                                        unsigned numTys) {
363   const Type *ResultTy = NULL;
364   std::vector<const Type*> ArgTys;
365   bool IsVarArg = false;
366   
367 #define GET_INTRINSIC_GENERATOR
368 #include "llvm/Intrinsics.gen"
369 #undef GET_INTRINSIC_GENERATOR
370
371   return FunctionType::get(ResultTy, ArgTys, IsVarArg); 
372 }
373
374 bool Intrinsic::isOverloaded(ID id) {
375   const bool OTable[] = {
376     false,
377 #define GET_INTRINSIC_OVERLOAD_TABLE
378 #include "llvm/Intrinsics.gen"
379 #undef GET_INTRINSIC_OVERLOAD_TABLE
380   };
381   return OTable[id];
382 }
383
384 /// This defines the "Intrinsic::getAttributes(ID id)" method.
385 #define GET_INTRINSIC_ATTRIBUTES
386 #include "llvm/Intrinsics.gen"
387 #undef GET_INTRINSIC_ATTRIBUTES
388
389 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, 
390                                     unsigned numTys) {
391   // There can never be multiple globals with the same name of different types,
392   // because intrinsics must be a specific type.
393   return
394     cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
395                                           getType(M->getContext(),
396                                                   id, Tys, numTys)));
397 }
398
399 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
400 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
401 #include "llvm/Intrinsics.gen"
402 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
403
404 /// hasAddressTaken - returns true if there are any uses of this function
405 /// other than direct calls or invokes to it.
406 bool Function::hasAddressTaken(const User* *PutOffender) const {
407   for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
408     const User *U = *I;
409     if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
410       return PutOffender ? (*PutOffender = U, true) : true;
411     ImmutableCallSite CS(cast<Instruction>(U));
412     if (!CS.isCallee(I))
413       return PutOffender ? (*PutOffender = U, true) : true;
414   }
415   return false;
416 }
417
418 // vim: sw=2 ai