Fix PR1146: parameter attributes are longer part of
[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/ParameterAttributes.h"
17 #include "llvm/IntrinsicInst.h"
18 #include "llvm/CodeGen/ValueTypes.h"
19 #include "llvm/Support/LeakDetector.h"
20 #include "llvm/Support/ManagedStatic.h"
21 #include "SymbolTableListTraitsImpl.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; ++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 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 ParamAttrsList::~ParamAttrsList() {
205   ParamAttrsLists->RemoveNode(this);
206 }
207
208 //===----------------------------------------------------------------------===//
209 // Function Implementation
210 //===----------------------------------------------------------------------===//
211
212 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
213                    const std::string &name, Module *ParentModule)
214   : GlobalValue(PointerType::get(Ty), Value::FunctionVal, 0, 0, Linkage, name),
215     ParamAttrs(0) {
216   SymTab = new ValueSymbolTable();
217
218   assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
219          && "LLVM functions cannot return aggregate values!");
220
221   // If the function has arguments, mark them as lazily built.
222   if (Ty->getNumParams())
223     SubclassData = 1;   // Set the "has lazy arguments" bit.
224   
225   // Make sure that we get added to a function
226   LeakDetector::addGarbageObject(this);
227
228   if (ParentModule)
229     ParentModule->getFunctionList().push_back(this);
230 }
231
232 Function::~Function() {
233   dropAllReferences();    // After this it is safe to delete instructions.
234
235   // Delete all of the method arguments and unlink from symbol table...
236   ArgumentList.clear();
237   delete SymTab;
238
239   // Drop our reference to the parameter attributes, if any.
240   if (ParamAttrs)
241     ParamAttrs->dropRef();
242 }
243
244 void Function::BuildLazyArguments() const {
245   // Create the arguments vector, all arguments start out unnamed.
246   const FunctionType *FT = getFunctionType();
247   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
248     assert(FT->getParamType(i) != Type::VoidTy &&
249            "Cannot have void typed arguments!");
250     ArgumentList.push_back(new Argument(FT->getParamType(i)));
251   }
252   
253   // Clear the lazy arguments bit.
254   const_cast<Function*>(this)->SubclassData &= ~1;
255 }
256
257 size_t Function::arg_size() const {
258   return getFunctionType()->getNumParams();
259 }
260 bool Function::arg_empty() const {
261   return getFunctionType()->getNumParams() == 0;
262 }
263
264 void Function::setParent(Module *parent) {
265   if (getParent())
266     LeakDetector::addGarbageObject(this);
267   Parent = parent;
268   if (getParent())
269     LeakDetector::removeGarbageObject(this);
270 }
271
272 void Function::setParamAttrs(const ParamAttrsList *attrs) {
273   // Avoid deleting the ParamAttrsList if they are setting the
274   // attributes to the same list.
275   if (ParamAttrs == attrs)
276     return;
277
278   // Drop reference on the old ParamAttrsList
279   if (ParamAttrs)
280     ParamAttrs->dropRef();
281
282   // Add reference to the new ParamAttrsList
283   if (attrs)
284     attrs->addRef();
285
286   // Set the new ParamAttrsList.
287   ParamAttrs = attrs; 
288 }
289
290 bool Function::isStructReturn() const {
291   if (ParamAttrs)
292     return ParamAttrs->paramHasAttr(1, ParamAttr::StructRet);
293   return false;
294 }
295
296 const FunctionType *Function::getFunctionType() const {
297   return cast<FunctionType>(getType()->getElementType());
298 }
299
300 bool Function::isVarArg() const {
301   return getFunctionType()->isVarArg();
302 }
303
304 const Type *Function::getReturnType() const {
305   return getFunctionType()->getReturnType();
306 }
307
308 void Function::removeFromParent() {
309   getParent()->getFunctionList().remove(this);
310 }
311
312 void Function::eraseFromParent() {
313   getParent()->getFunctionList().erase(this);
314 }
315
316 // dropAllReferences() - This function causes all the subinstructions to "let
317 // go" of all references that they are maintaining.  This allows one to
318 // 'delete' a whole class at a time, even though there may be circular
319 // references... first all references are dropped, and all use counts go to
320 // zero.  Then everything is deleted for real.  Note that no operations are
321 // valid on an object that has "dropped all references", except operator
322 // delete.
323 //
324 void Function::dropAllReferences() {
325   for (iterator I = begin(), E = end(); I != E; ++I)
326     I->dropAllReferences();
327   BasicBlocks.clear();    // Delete all basic blocks...
328 }
329
330 /// getIntrinsicID - This method returns the ID number of the specified
331 /// function, or Intrinsic::not_intrinsic if the function is not an
332 /// intrinsic, or if the pointer is null.  This value is always defined to be
333 /// zero to allow easy checking for whether a function is intrinsic or not.  The
334 /// particular intrinsic functions which correspond to this value are defined in
335 /// llvm/Intrinsics.h.
336 ///
337 unsigned Function::getIntrinsicID(bool noAssert) const {
338   const ValueName *ValName = this->getValueName();
339   if (!ValName)
340     return 0;
341   unsigned Len = ValName->getKeyLength();
342   const char *Name = ValName->getKeyData();
343   
344   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
345       || Name[2] != 'v' || Name[3] != 'm')
346     return 0;  // All intrinsics start with 'llvm.'
347
348   assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
349
350 #define GET_FUNCTION_RECOGNIZER
351 #include "llvm/Intrinsics.gen"
352 #undef GET_FUNCTION_RECOGNIZER
353   assert(noAssert && "Invalid LLVM intrinsic name");
354   return 0;
355 }
356
357 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { 
358   assert(id < num_intrinsics && "Invalid intrinsic ID!");
359   const char * const Table[] = {
360     "not_intrinsic",
361 #define GET_INTRINSIC_NAME_TABLE
362 #include "llvm/Intrinsics.gen"
363 #undef GET_INTRINSIC_NAME_TABLE
364   };
365   if (numTys == 0)
366     return Table[id];
367   std::string Result(Table[id]);
368   for (unsigned i = 0; i < numTys; ++i) 
369     if (Tys[i])
370       Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
371   return Result;
372 }
373
374 const FunctionType *Intrinsic::getType(ID id, const Type **Tys, 
375                                        unsigned numTys) {
376   const Type *ResultTy = NULL;
377   std::vector<const Type*> ArgTys;
378   bool IsVarArg = false;
379   
380 #define GET_INTRINSIC_GENERATOR
381 #include "llvm/Intrinsics.gen"
382 #undef GET_INTRINSIC_GENERATOR
383
384   return FunctionType::get(ResultTy, ArgTys, IsVarArg); 
385 }
386
387 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, 
388                                     unsigned numTys) {
389 // There can never be multiple globals with the same name of different types,
390 // because intrinsics must be a specific type.
391   return cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys), 
392                                                getType(id, Tys, numTys)));
393 }
394
395 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
396   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
397     if (CE->getOpcode() == Instruction::BitCast) {
398       if (isa<PointerType>(CE->getOperand(0)->getType()))
399         return StripPointerCasts(CE->getOperand(0));
400     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
401       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
402         if (!CE->getOperand(i)->isNullValue())
403           return Ptr;
404       return StripPointerCasts(CE->getOperand(0));
405     }
406     return Ptr;
407   }
408
409   if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
410     if (isa<PointerType>(CI->getOperand(0)->getType()))
411       return StripPointerCasts(CI->getOperand(0));
412   } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
413     if (GEP->hasAllZeroIndices())
414       return StripPointerCasts(GEP->getOperand(0));
415   }
416   return Ptr;
417 }
418
419 // vim: sw=2 ai