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