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