Reverting dtor devirtualization patch.
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 "SymbolTableListTraitsImpl.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/StringExtras.h"
23 using namespace llvm;
24
25 BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
26   BasicBlock *Ret = new BasicBlock();
27   // This should not be garbage monitored.
28   LeakDetector::removeGarbageObject(Ret);
29   return Ret;
30 }
31
32 iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {
33   return F->getBasicBlockList();
34 }
35
36 Argument *ilist_traits<Argument>::createSentinel() {
37   Argument *Ret = new Argument(Type::Int32Ty);
38   // This should not be garbage monitored.
39   LeakDetector::removeGarbageObject(Ret);
40   return Ret;
41 }
42
43 iplist<Argument> &ilist_traits<Argument>::getList(Function *F) {
44   return F->getArgumentList();
45 }
46
47 // Explicit instantiations of SymbolTableListTraits since some of the methods
48 // are not in the public header file...
49 template class SymbolTableListTraits<Argument, Function>;
50 template class SymbolTableListTraits<BasicBlock, Function>;
51
52 //===----------------------------------------------------------------------===//
53 // Argument Implementation
54 //===----------------------------------------------------------------------===//
55
56 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
57   : Value(Ty, Value::ArgumentVal) {
58   Parent = 0;
59
60   // Make sure that we get added to a function
61   LeakDetector::addGarbageObject(this);
62
63   if (Par)
64     Par->getArgumentList().push_back(this);
65   setName(Name);
66 }
67
68 void Argument::setParent(Function *parent) {
69   if (getParent())
70     LeakDetector::addGarbageObject(this);
71   Parent = parent;
72   if (getParent())
73     LeakDetector::removeGarbageObject(this);
74 }
75
76 //===----------------------------------------------------------------------===//
77 // ParamAttrsList Implementation
78 //===----------------------------------------------------------------------===//
79
80 uint16_t
81 ParamAttrsList::getParamAttrs(uint16_t Index) const {
82   unsigned limit = attrs.size();
83   for (unsigned i = 0; i < limit && attrs[i].index <= Index; ++i)
84     if (attrs[i].index == Index)
85       return attrs[i].attrs;
86   return ParamAttr::None;
87 }
88
89 std::string 
90 ParamAttrsList::getParamAttrsText(uint16_t Attrs) {
91   std::string Result;
92   if (Attrs & ParamAttr::ZExt)
93     Result += "zeroext ";
94   if (Attrs & ParamAttr::SExt)
95     Result += "signext ";
96   if (Attrs & ParamAttr::NoReturn)
97     Result += "noreturn ";
98   if (Attrs & ParamAttr::NoUnwind)
99     Result += "nounwind ";
100   if (Attrs & ParamAttr::InReg)
101     Result += "inreg ";
102   if (Attrs & ParamAttr::NoAlias)
103     Result += "noalias ";
104   if (Attrs & ParamAttr::StructRet)
105     Result += "sret ";  
106   if (Attrs & ParamAttr::ByVal)
107     Result += "byval ";
108   if (Attrs & ParamAttr::Nest)
109     Result += "nest ";
110   if (Attrs & ParamAttr::ReadNone)
111     Result += "readnone ";
112   if (Attrs & ParamAttr::ReadOnly)
113     Result += "readonly ";
114   return Result;
115 }
116
117 /// onlyInformative - Returns whether only informative attributes are set.
118 static inline bool onlyInformative(uint16_t attrs) {
119   return !(attrs & ~ParamAttr::Informative);
120 }
121
122 bool
123 ParamAttrsList::areCompatible(const ParamAttrsList *A, const ParamAttrsList *B){
124   if (A == B)
125     return true;
126   unsigned ASize = A ? A->size() : 0;
127   unsigned BSize = B ? B->size() : 0;
128   unsigned AIndex = 0;
129   unsigned BIndex = 0;
130
131   while (AIndex < ASize && BIndex < BSize) {
132     uint16_t AIdx = A->getParamIndex(AIndex);
133     uint16_t BIdx = B->getParamIndex(BIndex);
134     uint16_t AAttrs = A->getParamAttrsAtIndex(AIndex);
135     uint16_t BAttrs = B->getParamAttrsAtIndex(AIndex);
136
137     if (AIdx < BIdx) {
138       if (!onlyInformative(AAttrs))
139         return false;
140       ++AIndex;
141     } else if (BIdx < AIdx) {
142       if (!onlyInformative(BAttrs))
143         return false;
144       ++BIndex;
145     } else {
146       if (!onlyInformative(AAttrs ^ BAttrs))
147         return false;
148       ++AIndex;
149       ++BIndex;
150     }
151   }
152   for (; AIndex < ASize; ++AIndex)
153     if (!onlyInformative(A->getParamAttrsAtIndex(AIndex)))
154       return false;
155   for (; BIndex < BSize; ++BIndex)
156     if (!onlyInformative(B->getParamAttrsAtIndex(AIndex)))
157       return false;
158   return true;
159 }
160
161 void 
162 ParamAttrsList::Profile(FoldingSetNodeID &ID) const {
163   for (unsigned i = 0; i < attrs.size(); ++i) {
164     uint32_t val = uint32_t(attrs[i].attrs) << 16 | attrs[i].index;
165     ID.AddInteger(val);
166   }
167 }
168
169 static ManagedStatic<FoldingSet<ParamAttrsList> > ParamAttrsLists;
170
171 const ParamAttrsList *
172 ParamAttrsList::get(const ParamAttrsVector &attrVec) {
173   // If there are no attributes then return a null ParamAttrsList pointer.
174   if (attrVec.empty())
175     return 0;
176
177 #ifndef NDEBUG
178   for (unsigned i = 0, e = attrVec.size(); i < e; ++i) {
179     assert(attrVec[i].attrs != ParamAttr::None
180            && "Pointless parameter attribute!");
181     assert((!i || attrVec[i-1].index < attrVec[i].index)
182            && "Misordered ParamAttrsList!");
183   }
184 #endif
185
186   // Otherwise, build a key to look up the existing attributes.
187   ParamAttrsList key(attrVec);
188   FoldingSetNodeID ID;
189   key.Profile(ID);
190   void *InsertPos;
191   ParamAttrsList* PAL = ParamAttrsLists->FindNodeOrInsertPos(ID, InsertPos);
192
193   // If we didn't find any existing attributes of the same shape then
194   // create a new one and insert it.
195   if (!PAL) {
196     PAL = new ParamAttrsList(attrVec);
197     ParamAttrsLists->InsertNode(PAL, InsertPos);
198   }
199
200   // Return the ParamAttrsList that we found or created.
201   return PAL;
202 }
203
204 const ParamAttrsList *
205 ParamAttrsList::getModified(const ParamAttrsList *PAL,
206                             const ParamAttrsVector &modVec) {
207   if (modVec.empty())
208     return PAL;
209
210 #ifndef NDEBUG
211   for (unsigned i = 0, e = modVec.size(); i < e; ++i)
212     assert((!i || modVec[i-1].index < modVec[i].index)
213            && "Misordered ParamAttrsList!");
214 #endif
215
216   if (!PAL) {
217     // Strip any instances of ParamAttr::None from modVec before calling 'get'.
218     ParamAttrsVector newVec;
219     for (unsigned i = 0, e = modVec.size(); i < e; ++i)
220       if (modVec[i].attrs != ParamAttr::None)
221         newVec.push_back(modVec[i]);
222     return get(newVec);
223   }
224
225   const ParamAttrsVector &oldVec = PAL->attrs;
226
227   ParamAttrsVector newVec;
228   unsigned oldI = 0;
229   unsigned modI = 0;
230   unsigned oldE = oldVec.size();
231   unsigned modE = modVec.size();
232
233   while (oldI < oldE && modI < modE) {
234     uint16_t oldIndex = oldVec[oldI].index;
235     uint16_t modIndex = modVec[modI].index;
236
237     if (oldIndex < modIndex) {
238       newVec.push_back(oldVec[oldI]);
239       ++oldI;
240     } else if (modIndex < oldIndex) {
241       if (modVec[modI].attrs != ParamAttr::None)
242         newVec.push_back(modVec[modI]);
243       ++modI;
244     } else {
245       // Same index - overwrite or delete existing attributes.
246       if (modVec[modI].attrs != ParamAttr::None)
247         newVec.push_back(modVec[modI]);
248       ++oldI;
249       ++modI;
250     }
251   }
252
253   for (; oldI < oldE; ++oldI)
254     newVec.push_back(oldVec[oldI]);
255   for (; modI < modE; ++modI)
256     if (modVec[modI].attrs != ParamAttr::None)
257       newVec.push_back(modVec[modI]);
258
259   return get(newVec);
260 }
261
262 ParamAttrsList::~ParamAttrsList() {
263   ParamAttrsLists->RemoveNode(this);
264 }
265
266 //===----------------------------------------------------------------------===//
267 // Function Implementation
268 //===----------------------------------------------------------------------===//
269
270 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
271                    const std::string &name, Module *ParentModule)
272   : GlobalValue(PointerType::get(Ty), Value::FunctionVal, 0, 0, Linkage, name),
273     ParamAttrs(0) {
274   SymTab = new ValueSymbolTable();
275
276   assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
277          && "LLVM functions cannot return aggregate values!");
278
279   // If the function has arguments, mark them as lazily built.
280   if (Ty->getNumParams())
281     SubclassData = 1;   // Set the "has lazy arguments" bit.
282   
283   // Make sure that we get added to a function
284   LeakDetector::addGarbageObject(this);
285
286   if (ParentModule)
287     ParentModule->getFunctionList().push_back(this);
288 }
289
290 Function::~Function() {
291   dropAllReferences();    // After this it is safe to delete instructions.
292
293   // Delete all of the method arguments and unlink from symbol table...
294   ArgumentList.clear();
295   delete SymTab;
296
297   // Drop our reference to the parameter attributes, if any.
298   if (ParamAttrs)
299     ParamAttrs->dropRef();
300 }
301
302 void Function::BuildLazyArguments() const {
303   // Create the arguments vector, all arguments start out unnamed.
304   const FunctionType *FT = getFunctionType();
305   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
306     assert(FT->getParamType(i) != Type::VoidTy &&
307            "Cannot have void typed arguments!");
308     ArgumentList.push_back(new Argument(FT->getParamType(i)));
309   }
310   
311   // Clear the lazy arguments bit.
312   const_cast<Function*>(this)->SubclassData &= ~1;
313 }
314
315 size_t Function::arg_size() const {
316   return getFunctionType()->getNumParams();
317 }
318 bool Function::arg_empty() const {
319   return getFunctionType()->getNumParams() == 0;
320 }
321
322 void Function::setParent(Module *parent) {
323   if (getParent())
324     LeakDetector::addGarbageObject(this);
325   Parent = parent;
326   if (getParent())
327     LeakDetector::removeGarbageObject(this);
328 }
329
330 void Function::setParamAttrs(const ParamAttrsList *attrs) {
331   // Avoid deleting the ParamAttrsList if they are setting the
332   // attributes to the same list.
333   if (ParamAttrs == attrs)
334     return;
335
336   // Drop reference on the old ParamAttrsList
337   if (ParamAttrs)
338     ParamAttrs->dropRef();
339
340   // Add reference to the new ParamAttrsList
341   if (attrs)
342     attrs->addRef();
343
344   // Set the new ParamAttrsList.
345   ParamAttrs = attrs; 
346 }
347
348 const FunctionType *Function::getFunctionType() const {
349   return cast<FunctionType>(getType()->getElementType());
350 }
351
352 bool Function::isVarArg() const {
353   return getFunctionType()->isVarArg();
354 }
355
356 const Type *Function::getReturnType() const {
357   return getFunctionType()->getReturnType();
358 }
359
360 void Function::removeFromParent() {
361   getParent()->getFunctionList().remove(this);
362 }
363
364 void Function::eraseFromParent() {
365   getParent()->getFunctionList().erase(this);
366 }
367
368 // dropAllReferences() - This function causes all the subinstructions to "let
369 // go" of all references that they are maintaining.  This allows one to
370 // 'delete' a whole class at a time, even though there may be circular
371 // references... first all references are dropped, and all use counts go to
372 // zero.  Then everything is deleted for real.  Note that no operations are
373 // valid on an object that has "dropped all references", except operator
374 // delete.
375 //
376 void Function::dropAllReferences() {
377   for (iterator I = begin(), E = end(); I != E; ++I)
378     I->dropAllReferences();
379   BasicBlocks.clear();    // Delete all basic blocks...
380 }
381
382 /// getIntrinsicID - This method returns the ID number of the specified
383 /// function, or Intrinsic::not_intrinsic if the function is not an
384 /// intrinsic, or if the pointer is null.  This value is always defined to be
385 /// zero to allow easy checking for whether a function is intrinsic or not.  The
386 /// particular intrinsic functions which correspond to this value are defined in
387 /// llvm/Intrinsics.h.
388 ///
389 unsigned Function::getIntrinsicID(bool noAssert) const {
390   const ValueName *ValName = this->getValueName();
391   if (!ValName)
392     return 0;
393   unsigned Len = ValName->getKeyLength();
394   const char *Name = ValName->getKeyData();
395   
396   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
397       || Name[2] != 'v' || Name[3] != 'm')
398     return 0;  // All intrinsics start with 'llvm.'
399
400   assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
401
402 #define GET_FUNCTION_RECOGNIZER
403 #include "llvm/Intrinsics.gen"
404 #undef GET_FUNCTION_RECOGNIZER
405   assert(noAssert && "Invalid LLVM intrinsic name");
406   return 0;
407 }
408
409 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { 
410   assert(id < num_intrinsics && "Invalid intrinsic ID!");
411   const char * const Table[] = {
412     "not_intrinsic",
413 #define GET_INTRINSIC_NAME_TABLE
414 #include "llvm/Intrinsics.gen"
415 #undef GET_INTRINSIC_NAME_TABLE
416   };
417   if (numTys == 0)
418     return Table[id];
419   std::string Result(Table[id]);
420   for (unsigned i = 0; i < numTys; ++i) 
421     if (Tys[i])
422       Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
423   return Result;
424 }
425
426 const FunctionType *Intrinsic::getType(ID id, const Type **Tys, 
427                                        unsigned numTys) {
428   const Type *ResultTy = NULL;
429   std::vector<const Type*> ArgTys;
430   bool IsVarArg = false;
431   
432 #define GET_INTRINSIC_GENERATOR
433 #include "llvm/Intrinsics.gen"
434 #undef GET_INTRINSIC_GENERATOR
435
436   return FunctionType::get(ResultTy, ArgTys, IsVarArg); 
437 }
438
439 const ParamAttrsList *Intrinsic::getParamAttrs(ID id) {
440   static const ParamAttrsList *IntrinsicAttributes[Intrinsic::num_intrinsics];
441
442   if (IntrinsicAttributes[id])
443     return IntrinsicAttributes[id];
444
445   ParamAttrsVector Attrs;
446   uint16_t Attr = ParamAttr::None;
447
448 #define GET_INTRINSIC_ATTRIBUTES
449 #include "llvm/Intrinsics.gen"
450 #undef GET_INTRINSIC_ATTRIBUTES
451
452   // Intrinsics cannot throw exceptions.
453   Attr |= ParamAttr::NoUnwind;
454
455   Attrs.push_back(ParamAttrsWithIndex::get(0, Attr));
456   IntrinsicAttributes[id] = ParamAttrsList::get(Attrs);
457   return IntrinsicAttributes[id];
458 }
459
460 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, 
461                                     unsigned numTys) {
462   // There can never be multiple globals with the same name of different types,
463   // because intrinsics must be a specific type.
464   Function *F =
465     cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
466                                           getType(id, Tys, numTys)));
467   F->setParamAttrs(getParamAttrs(id));
468   return F;
469 }
470
471 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
472   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
473     if (CE->getOpcode() == Instruction::BitCast) {
474       if (isa<PointerType>(CE->getOperand(0)->getType()))
475         return StripPointerCasts(CE->getOperand(0));
476     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
477       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
478         if (!CE->getOperand(i)->isNullValue())
479           return Ptr;
480       return StripPointerCasts(CE->getOperand(0));
481     }
482     return Ptr;
483   }
484
485   if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
486     if (isa<PointerType>(CI->getOperand(0)->getType()))
487       return StripPointerCasts(CI->getOperand(0));
488   } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
489     if (GEP->hasAllZeroIndices())
490       return StripPointerCasts(GEP->getOperand(0));
491   }
492   return Ptr;
493 }
494
495 // vim: sw=2 ai