b1405e592622607fc4b8dc5f9ee260b25714b5ff
[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 void Function::destroyThis(Function*v) {
291   v->dropAllReferences();    // After this it is safe to delete instructions.
292
293   // Delete all of the method arguments and unlink from symbol table...
294   v->ArgumentList.clear();
295   delete v->SymTab;
296
297   // Drop our reference to the parameter attributes, if any.
298   if (v->ParamAttrs)
299     v->ParamAttrs->dropRef();
300   GlobalValue::destroyThis(v);
301 }
302
303 void Function::BuildLazyArguments() const {
304   // Create the arguments vector, all arguments start out unnamed.
305   const FunctionType *FT = getFunctionType();
306   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
307     assert(FT->getParamType(i) != Type::VoidTy &&
308            "Cannot have void typed arguments!");
309     ArgumentList.push_back(new Argument(FT->getParamType(i)));
310   }
311   
312   // Clear the lazy arguments bit.
313   const_cast<Function*>(this)->SubclassData &= ~1;
314 }
315
316 size_t Function::arg_size() const {
317   return getFunctionType()->getNumParams();
318 }
319 bool Function::arg_empty() const {
320   return getFunctionType()->getNumParams() == 0;
321 }
322
323 void Function::setParent(Module *parent) {
324   if (getParent())
325     LeakDetector::addGarbageObject(this);
326   Parent = parent;
327   if (getParent())
328     LeakDetector::removeGarbageObject(this);
329 }
330
331 void Function::setParamAttrs(const ParamAttrsList *attrs) {
332   // Avoid deleting the ParamAttrsList if they are setting the
333   // attributes to the same list.
334   if (ParamAttrs == attrs)
335     return;
336
337   // Drop reference on the old ParamAttrsList
338   if (ParamAttrs)
339     ParamAttrs->dropRef();
340
341   // Add reference to the new ParamAttrsList
342   if (attrs)
343     attrs->addRef();
344
345   // Set the new ParamAttrsList.
346   ParamAttrs = attrs; 
347 }
348
349 const FunctionType *Function::getFunctionType() const {
350   return cast<FunctionType>(getType()->getElementType());
351 }
352
353 bool Function::isVarArg() const {
354   return getFunctionType()->isVarArg();
355 }
356
357 const Type *Function::getReturnType() const {
358   return getFunctionType()->getReturnType();
359 }
360
361 void Function::removeFromParent() {
362   getParent()->getFunctionList().remove(this);
363 }
364
365 void Function::eraseFromParent() {
366   getParent()->getFunctionList().erase(this);
367 }
368
369 // dropAllReferences() - This function causes all the subinstructions to "let
370 // go" of all references that they are maintaining.  This allows one to
371 // 'delete' a whole class at a time, even though there may be circular
372 // references... first all references are dropped, and all use counts go to
373 // zero.  Then everything is deleted for real.  Note that no operations are
374 // valid on an object that has "dropped all references", except operator
375 // delete.
376 //
377 void Function::dropAllReferences() {
378   for (iterator I = begin(), E = end(); I != E; ++I)
379     I->dropAllReferences();
380   BasicBlocks.clear();    // Delete all basic blocks...
381 }
382
383 /// getIntrinsicID - This method returns the ID number of the specified
384 /// function, or Intrinsic::not_intrinsic if the function is not an
385 /// intrinsic, or if the pointer is null.  This value is always defined to be
386 /// zero to allow easy checking for whether a function is intrinsic or not.  The
387 /// particular intrinsic functions which correspond to this value are defined in
388 /// llvm/Intrinsics.h.
389 ///
390 unsigned Function::getIntrinsicID(bool noAssert) const {
391   const ValueName *ValName = this->getValueName();
392   if (!ValName)
393     return 0;
394   unsigned Len = ValName->getKeyLength();
395   const char *Name = ValName->getKeyData();
396   
397   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
398       || Name[2] != 'v' || Name[3] != 'm')
399     return 0;  // All intrinsics start with 'llvm.'
400
401   assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
402
403 #define GET_FUNCTION_RECOGNIZER
404 #include "llvm/Intrinsics.gen"
405 #undef GET_FUNCTION_RECOGNIZER
406   assert(noAssert && "Invalid LLVM intrinsic name");
407   return 0;
408 }
409
410 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { 
411   assert(id < num_intrinsics && "Invalid intrinsic ID!");
412   const char * const Table[] = {
413     "not_intrinsic",
414 #define GET_INTRINSIC_NAME_TABLE
415 #include "llvm/Intrinsics.gen"
416 #undef GET_INTRINSIC_NAME_TABLE
417   };
418   if (numTys == 0)
419     return Table[id];
420   std::string Result(Table[id]);
421   for (unsigned i = 0; i < numTys; ++i) 
422     if (Tys[i])
423       Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
424   return Result;
425 }
426
427 const FunctionType *Intrinsic::getType(ID id, const Type **Tys, 
428                                        unsigned numTys) {
429   const Type *ResultTy = NULL;
430   std::vector<const Type*> ArgTys;
431   bool IsVarArg = false;
432   
433 #define GET_INTRINSIC_GENERATOR
434 #include "llvm/Intrinsics.gen"
435 #undef GET_INTRINSIC_GENERATOR
436
437   return FunctionType::get(ResultTy, ArgTys, IsVarArg); 
438 }
439
440 const ParamAttrsList *Intrinsic::getParamAttrs(ID id) {
441   static const ParamAttrsList *IntrinsicAttributes[Intrinsic::num_intrinsics];
442
443   if (IntrinsicAttributes[id])
444     return IntrinsicAttributes[id];
445
446   ParamAttrsVector Attrs;
447   uint16_t Attr = ParamAttr::None;
448
449 #define GET_INTRINSIC_ATTRIBUTES
450 #include "llvm/Intrinsics.gen"
451 #undef GET_INTRINSIC_ATTRIBUTES
452
453   // Intrinsics cannot throw exceptions.
454   Attr |= ParamAttr::NoUnwind;
455
456   Attrs.push_back(ParamAttrsWithIndex::get(0, Attr));
457   IntrinsicAttributes[id] = ParamAttrsList::get(Attrs);
458   return IntrinsicAttributes[id];
459 }
460
461 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, 
462                                     unsigned numTys) {
463   // There can never be multiple globals with the same name of different types,
464   // because intrinsics must be a specific type.
465   Function *F =
466     cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
467                                           getType(id, Tys, numTys)));
468   F->setParamAttrs(getParamAttrs(id));
469   return F;
470 }
471
472 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
473   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
474     if (CE->getOpcode() == Instruction::BitCast) {
475       if (isa<PointerType>(CE->getOperand(0)->getType()))
476         return StripPointerCasts(CE->getOperand(0));
477     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
478       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
479         if (!CE->getOperand(i)->isNullValue())
480           return Ptr;
481       return StripPointerCasts(CE->getOperand(0));
482     }
483     return Ptr;
484   }
485
486   if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
487     if (isa<PointerType>(CI->getOperand(0)->getType()))
488       return StripPointerCasts(CI->getOperand(0));
489   } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
490     if (GEP->hasAllZeroIndices())
491       return StripPointerCasts(GEP->getOperand(0));
492   }
493   return Ptr;
494 }
495
496 // vim: sw=2 ai