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