1 //===-- Function.cpp - Implement the Global object classes ----------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Function class for the VMCore library.
12 //===----------------------------------------------------------------------===//
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 "llvm/Support/StringPool.h"
21 #include "SymbolTableListTraitsImpl.h"
22 #include "llvm/ADT/BitVector.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/StringExtras.h"
27 BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
28 BasicBlock *Ret = new BasicBlock();
29 // This should not be garbage monitored.
30 LeakDetector::removeGarbageObject(Ret);
34 iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {
35 return F->getBasicBlockList();
38 Argument *ilist_traits<Argument>::createSentinel() {
39 Argument *Ret = new Argument(Type::Int32Ty);
40 // This should not be garbage monitored.
41 LeakDetector::removeGarbageObject(Ret);
45 iplist<Argument> &ilist_traits<Argument>::getList(Function *F) {
46 return F->getArgumentList();
49 // Explicit instantiations of SymbolTableListTraits since some of the methods
50 // are not in the public header file...
51 template class SymbolTableListTraits<Argument, Function>;
52 template class SymbolTableListTraits<BasicBlock, Function>;
54 //===----------------------------------------------------------------------===//
55 // Argument Implementation
56 //===----------------------------------------------------------------------===//
58 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
59 : Value(Ty, Value::ArgumentVal) {
62 // Make sure that we get added to a function
63 LeakDetector::addGarbageObject(this);
66 Par->getArgumentList().push_back(this);
70 void Argument::setParent(Function *parent) {
72 LeakDetector::addGarbageObject(this);
75 LeakDetector::removeGarbageObject(this);
78 //===----------------------------------------------------------------------===//
79 // ParamAttrsList Implementation
80 //===----------------------------------------------------------------------===//
83 ParamAttrsList::getParamAttrs(uint16_t Index) const {
84 unsigned limit = attrs.size();
85 for (unsigned i = 0; i < limit && attrs[i].index <= Index; ++i)
86 if (attrs[i].index == Index)
87 return attrs[i].attrs;
88 return ParamAttr::None;
92 ParamAttrsList::getParamAttrsText(uint16_t Attrs) {
94 if (Attrs & ParamAttr::ZExt)
96 if (Attrs & ParamAttr::SExt)
98 if (Attrs & ParamAttr::NoReturn)
99 Result += "noreturn ";
100 if (Attrs & ParamAttr::NoUnwind)
101 Result += "nounwind ";
102 if (Attrs & ParamAttr::InReg)
104 if (Attrs & ParamAttr::NoAlias)
105 Result += "noalias ";
106 if (Attrs & ParamAttr::StructRet)
108 if (Attrs & ParamAttr::ByVal)
110 if (Attrs & ParamAttr::Nest)
112 if (Attrs & ParamAttr::ReadNone)
113 Result += "readnone ";
114 if (Attrs & ParamAttr::ReadOnly)
115 Result += "readonly ";
119 /// onlyInformative - Returns whether only informative attributes are set.
120 static inline bool onlyInformative(uint16_t attrs) {
121 return !(attrs & ~ParamAttr::Informative);
125 ParamAttrsList::areCompatible(const ParamAttrsList *A, const ParamAttrsList *B){
128 unsigned ASize = A ? A->size() : 0;
129 unsigned BSize = B ? B->size() : 0;
133 while (AIndex < ASize && BIndex < BSize) {
134 uint16_t AIdx = A->getParamIndex(AIndex);
135 uint16_t BIdx = B->getParamIndex(BIndex);
136 uint16_t AAttrs = A->getParamAttrsAtIndex(AIndex);
137 uint16_t BAttrs = B->getParamAttrsAtIndex(AIndex);
140 if (!onlyInformative(AAttrs))
143 } else if (BIdx < AIdx) {
144 if (!onlyInformative(BAttrs))
148 if (!onlyInformative(AAttrs ^ BAttrs))
154 for (; AIndex < ASize; ++AIndex)
155 if (!onlyInformative(A->getParamAttrsAtIndex(AIndex)))
157 for (; BIndex < BSize; ++BIndex)
158 if (!onlyInformative(B->getParamAttrsAtIndex(AIndex)))
164 ParamAttrsList::Profile(FoldingSetNodeID &ID) const {
165 for (unsigned i = 0; i < attrs.size(); ++i) {
166 uint32_t val = uint32_t(attrs[i].attrs) << 16 | attrs[i].index;
171 static ManagedStatic<FoldingSet<ParamAttrsList> > ParamAttrsLists;
173 const ParamAttrsList *
174 ParamAttrsList::get(const ParamAttrsVector &attrVec) {
175 // If there are no attributes then return a null ParamAttrsList pointer.
180 for (unsigned i = 0, e = attrVec.size(); i < e; ++i) {
181 assert(attrVec[i].attrs != ParamAttr::None
182 && "Pointless parameter attribute!");
183 assert((!i || attrVec[i-1].index < attrVec[i].index)
184 && "Misordered ParamAttrsList!");
188 // Otherwise, build a key to look up the existing attributes.
189 ParamAttrsList key(attrVec);
193 ParamAttrsList* PAL = ParamAttrsLists->FindNodeOrInsertPos(ID, InsertPos);
195 // If we didn't find any existing attributes of the same shape then
196 // create a new one and insert it.
198 PAL = new ParamAttrsList(attrVec);
199 ParamAttrsLists->InsertNode(PAL, InsertPos);
202 // Return the ParamAttrsList that we found or created.
206 const ParamAttrsList *
207 ParamAttrsList::getModified(const ParamAttrsList *PAL,
208 const ParamAttrsVector &modVec) {
213 for (unsigned i = 0, e = modVec.size(); i < e; ++i)
214 assert((!i || modVec[i-1].index < modVec[i].index)
215 && "Misordered ParamAttrsList!");
219 // Strip any instances of ParamAttr::None from modVec before calling 'get'.
220 ParamAttrsVector newVec;
221 for (unsigned i = 0, e = modVec.size(); i < e; ++i)
222 if (modVec[i].attrs != ParamAttr::None)
223 newVec.push_back(modVec[i]);
227 const ParamAttrsVector &oldVec = PAL->attrs;
229 ParamAttrsVector newVec;
232 unsigned oldE = oldVec.size();
233 unsigned modE = modVec.size();
235 while (oldI < oldE && modI < modE) {
236 uint16_t oldIndex = oldVec[oldI].index;
237 uint16_t modIndex = modVec[modI].index;
239 if (oldIndex < modIndex) {
240 newVec.push_back(oldVec[oldI]);
242 } else if (modIndex < oldIndex) {
243 if (modVec[modI].attrs != ParamAttr::None)
244 newVec.push_back(modVec[modI]);
247 // Same index - overwrite or delete existing attributes.
248 if (modVec[modI].attrs != ParamAttr::None)
249 newVec.push_back(modVec[modI]);
255 for (; oldI < oldE; ++oldI)
256 newVec.push_back(oldVec[oldI]);
257 for (; modI < modE; ++modI)
258 if (modVec[modI].attrs != ParamAttr::None)
259 newVec.push_back(modVec[modI]);
264 ParamAttrsList::~ParamAttrsList() {
265 ParamAttrsLists->RemoveNode(this);
268 //===----------------------------------------------------------------------===//
269 // Function Implementation
270 //===----------------------------------------------------------------------===//
272 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
273 const std::string &name, Module *ParentModule)
274 : GlobalValue(PointerType::getUnqual(Ty),
275 Value::FunctionVal, 0, 0, Linkage, name),
277 SymTab = new ValueSymbolTable();
279 assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
280 && "LLVM functions cannot return aggregate values!");
282 // If the function has arguments, mark them as lazily built.
283 if (Ty->getNumParams())
284 SubclassData = 1; // Set the "has lazy arguments" bit.
286 // Make sure that we get added to a function
287 LeakDetector::addGarbageObject(this);
290 ParentModule->getFunctionList().push_back(this);
293 Function::~Function() {
294 dropAllReferences(); // After this it is safe to delete instructions.
296 // Delete all of the method arguments and unlink from symbol table...
297 ArgumentList.clear();
300 // Drop our reference to the parameter attributes, if any.
302 ParamAttrs->dropRef();
304 // Remove the function from the on-the-side collector table.
308 void Function::BuildLazyArguments() const {
309 // Create the arguments vector, all arguments start out unnamed.
310 const FunctionType *FT = getFunctionType();
311 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
312 assert(FT->getParamType(i) != Type::VoidTy &&
313 "Cannot have void typed arguments!");
314 ArgumentList.push_back(new Argument(FT->getParamType(i)));
317 // Clear the lazy arguments bit.
318 const_cast<Function*>(this)->SubclassData &= ~1;
321 size_t Function::arg_size() const {
322 return getFunctionType()->getNumParams();
324 bool Function::arg_empty() const {
325 return getFunctionType()->getNumParams() == 0;
328 void Function::setParent(Module *parent) {
330 LeakDetector::addGarbageObject(this);
333 LeakDetector::removeGarbageObject(this);
336 void Function::setParamAttrs(const ParamAttrsList *attrs) {
337 // Avoid deleting the ParamAttrsList if they are setting the
338 // attributes to the same list.
339 if (ParamAttrs == attrs)
342 // Drop reference on the old ParamAttrsList
344 ParamAttrs->dropRef();
346 // Add reference to the new ParamAttrsList
350 // Set the new ParamAttrsList.
354 const FunctionType *Function::getFunctionType() const {
355 return cast<FunctionType>(getType()->getElementType());
358 bool Function::isVarArg() const {
359 return getFunctionType()->isVarArg();
362 const Type *Function::getReturnType() const {
363 return getFunctionType()->getReturnType();
366 void Function::removeFromParent() {
367 getParent()->getFunctionList().remove(this);
370 void Function::eraseFromParent() {
371 getParent()->getFunctionList().erase(this);
374 // dropAllReferences() - This function causes all the subinstructions to "let
375 // go" of all references that they are maintaining. This allows one to
376 // 'delete' a whole class at a time, even though there may be circular
377 // references... first all references are dropped, and all use counts go to
378 // zero. Then everything is deleted for real. Note that no operations are
379 // valid on an object that has "dropped all references", except operator
382 void Function::dropAllReferences() {
383 for (iterator I = begin(), E = end(); I != E; ++I)
384 I->dropAllReferences();
385 BasicBlocks.clear(); // Delete all basic blocks...
388 // Maintain the collector name for each function in an on-the-side table. This
389 // saves allocating an additional word in Function for programs which do not use
390 // GC (i.e., most programs) at the cost of increased overhead for clients which
392 static DenseMap<const Function*,PooledStringPtr> *CollectorNames;
393 static StringPool *CollectorNamePool;
395 bool Function::hasCollector() const {
396 return CollectorNames && CollectorNames->count(this);
399 const char *Function::getCollector() const {
400 assert(hasCollector() && "Function has no collector");
401 return *(*CollectorNames)[this];
404 void Function::setCollector(const char *Str) {
405 if (!CollectorNamePool)
406 CollectorNamePool = new StringPool();
408 CollectorNames = new DenseMap<const Function*,PooledStringPtr>();
409 (*CollectorNames)[this] = CollectorNamePool->intern(Str);
412 void Function::clearCollector() {
413 if (CollectorNames) {
414 CollectorNames->erase(this);
415 if (CollectorNames->empty()) {
416 delete CollectorNames;
418 if (CollectorNamePool->empty()) {
419 delete CollectorNamePool;
420 CollectorNamePool = 0;
426 /// getIntrinsicID - This method returns the ID number of the specified
427 /// function, or Intrinsic::not_intrinsic if the function is not an
428 /// intrinsic, or if the pointer is null. This value is always defined to be
429 /// zero to allow easy checking for whether a function is intrinsic or not. The
430 /// particular intrinsic functions which correspond to this value are defined in
431 /// llvm/Intrinsics.h.
433 unsigned Function::getIntrinsicID(bool noAssert) const {
434 const ValueName *ValName = this->getValueName();
437 unsigned Len = ValName->getKeyLength();
438 const char *Name = ValName->getKeyData();
440 if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
441 || Name[2] != 'v' || Name[3] != 'm')
442 return 0; // All intrinsics start with 'llvm.'
444 assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
446 #define GET_FUNCTION_RECOGNIZER
447 #include "llvm/Intrinsics.gen"
448 #undef GET_FUNCTION_RECOGNIZER
449 assert(noAssert && "Invalid LLVM intrinsic name");
453 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
454 assert(id < num_intrinsics && "Invalid intrinsic ID!");
455 const char * const Table[] = {
457 #define GET_INTRINSIC_NAME_TABLE
458 #include "llvm/Intrinsics.gen"
459 #undef GET_INTRINSIC_NAME_TABLE
463 std::string Result(Table[id]);
464 for (unsigned i = 0; i < numTys; ++i)
466 Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
470 const FunctionType *Intrinsic::getType(ID id, const Type **Tys,
472 const Type *ResultTy = NULL;
473 std::vector<const Type*> ArgTys;
474 bool IsVarArg = false;
476 #define GET_INTRINSIC_GENERATOR
477 #include "llvm/Intrinsics.gen"
478 #undef GET_INTRINSIC_GENERATOR
480 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
483 const ParamAttrsList *Intrinsic::getParamAttrs(ID id) {
484 static const ParamAttrsList *IntrinsicAttributes[Intrinsic::num_intrinsics];
486 if (IntrinsicAttributes[id])
487 return IntrinsicAttributes[id];
489 ParamAttrsVector Attrs;
490 uint16_t Attr = ParamAttr::None;
492 #define GET_INTRINSIC_ATTRIBUTES
493 #include "llvm/Intrinsics.gen"
494 #undef GET_INTRINSIC_ATTRIBUTES
496 // Intrinsics cannot throw exceptions.
497 Attr |= ParamAttr::NoUnwind;
499 Attrs.push_back(ParamAttrsWithIndex::get(0, Attr));
500 IntrinsicAttributes[id] = ParamAttrsList::get(Attrs);
501 return IntrinsicAttributes[id];
504 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
506 // There can never be multiple globals with the same name of different types,
507 // because intrinsics must be a specific type.
509 cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
510 getType(id, Tys, numTys)));
511 F->setParamAttrs(getParamAttrs(id));
515 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
516 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
517 if (CE->getOpcode() == Instruction::BitCast) {
518 if (isa<PointerType>(CE->getOperand(0)->getType()))
519 return StripPointerCasts(CE->getOperand(0));
520 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
521 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
522 if (!CE->getOperand(i)->isNullValue())
524 return StripPointerCasts(CE->getOperand(0));
529 if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
530 if (isa<PointerType>(CI->getOperand(0)->getType()))
531 return StripPointerCasts(CI->getOperand(0));
532 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
533 if (GEP->hasAllZeroIndices())
534 return StripPointerCasts(GEP->getOperand(0));