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 "SymbolTableListTraitsImpl.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/StringExtras.h"
25 BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
26 BasicBlock *Ret = new BasicBlock();
27 // This should not be garbage monitored.
28 LeakDetector::removeGarbageObject(Ret);
32 iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {
33 return F->getBasicBlockList();
36 Argument *ilist_traits<Argument>::createSentinel() {
37 Argument *Ret = new Argument(Type::Int32Ty);
38 // This should not be garbage monitored.
39 LeakDetector::removeGarbageObject(Ret);
43 iplist<Argument> &ilist_traits<Argument>::getList(Function *F) {
44 return F->getArgumentList();
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>;
52 //===----------------------------------------------------------------------===//
53 // Argument Implementation
54 //===----------------------------------------------------------------------===//
56 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
57 : Value(Ty, Value::ArgumentVal) {
60 // Make sure that we get added to a function
61 LeakDetector::addGarbageObject(this);
64 Par->getArgumentList().push_back(this);
68 void Argument::setParent(Function *parent) {
70 LeakDetector::addGarbageObject(this);
73 LeakDetector::removeGarbageObject(this);
76 //===----------------------------------------------------------------------===//
77 // ParamAttrsList Implementation
78 //===----------------------------------------------------------------------===//
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;
90 ParamAttrsList::getParamAttrsText(uint16_t Attrs) {
92 if (Attrs & ParamAttr::ZExt)
94 if (Attrs & ParamAttr::SExt)
96 if (Attrs & ParamAttr::NoReturn)
97 Result += "noreturn ";
98 if (Attrs & ParamAttr::NoUnwind)
99 Result += "nounwind ";
100 if (Attrs & ParamAttr::InReg)
102 if (Attrs & ParamAttr::NoAlias)
103 Result += "noalias ";
104 if (Attrs & ParamAttr::StructRet)
106 if (Attrs & ParamAttr::ByVal)
108 if (Attrs & ParamAttr::Nest)
110 if (Attrs & ParamAttr::ReadNone)
111 Result += "readnone ";
112 if (Attrs & ParamAttr::ReadOnly)
113 Result += "readonly ";
117 /// onlyInformative - Returns whether only informative attributes are set.
118 static inline bool onlyInformative(uint16_t attrs) {
119 return !(attrs & ~ParamAttr::Informative);
123 ParamAttrsList::areCompatible(const ParamAttrsList *A, const ParamAttrsList *B){
126 unsigned ASize = A ? A->size() : 0;
127 unsigned BSize = B ? B->size() : 0;
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);
138 if (!onlyInformative(AAttrs))
141 } else if (BIdx < AIdx) {
142 if (!onlyInformative(BAttrs))
146 if (!onlyInformative(AAttrs ^ BAttrs))
152 for (; AIndex < ASize; ++AIndex)
153 if (!onlyInformative(A->getParamAttrsAtIndex(AIndex)))
155 for (; BIndex < BSize; ++BIndex)
156 if (!onlyInformative(B->getParamAttrsAtIndex(AIndex)))
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;
169 static ManagedStatic<FoldingSet<ParamAttrsList> > ParamAttrsLists;
171 const ParamAttrsList *
172 ParamAttrsList::get(const ParamAttrsVector &attrVec) {
173 // If there are no attributes then return a null ParamAttrsList pointer.
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!");
186 // Otherwise, build a key to look up the existing attributes.
187 ParamAttrsList key(attrVec);
191 ParamAttrsList* PAL = ParamAttrsLists->FindNodeOrInsertPos(ID, InsertPos);
193 // If we didn't find any existing attributes of the same shape then
194 // create a new one and insert it.
196 PAL = new ParamAttrsList(attrVec);
197 ParamAttrsLists->InsertNode(PAL, InsertPos);
200 // Return the ParamAttrsList that we found or created.
204 const ParamAttrsList *
205 ParamAttrsList::getModified(const ParamAttrsList *PAL,
206 const ParamAttrsVector &modVec) {
211 for (unsigned i = 0, e = modVec.size(); i < e; ++i)
212 assert((!i || modVec[i-1].index < modVec[i].index)
213 && "Misordered ParamAttrsList!");
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]);
225 const ParamAttrsVector &oldVec = PAL->attrs;
227 ParamAttrsVector newVec;
230 unsigned oldE = oldVec.size();
231 unsigned modE = modVec.size();
233 while (oldI < oldE && modI < modE) {
234 uint16_t oldIndex = oldVec[oldI].index;
235 uint16_t modIndex = modVec[modI].index;
237 if (oldIndex < modIndex) {
238 newVec.push_back(oldVec[oldI]);
240 } else if (modIndex < oldIndex) {
241 if (modVec[modI].attrs != ParamAttr::None)
242 newVec.push_back(modVec[modI]);
245 // Same index - overwrite or delete existing attributes.
246 if (modVec[modI].attrs != ParamAttr::None)
247 newVec.push_back(modVec[modI]);
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]);
262 ParamAttrsList::~ParamAttrsList() {
263 ParamAttrsLists->RemoveNode(this);
266 //===----------------------------------------------------------------------===//
267 // Function Implementation
268 //===----------------------------------------------------------------------===//
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),
274 SymTab = new ValueSymbolTable();
276 assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
277 && "LLVM functions cannot return aggregate values!");
279 // If the function has arguments, mark them as lazily built.
280 if (Ty->getNumParams())
281 SubclassData = 1; // Set the "has lazy arguments" bit.
283 // Make sure that we get added to a function
284 LeakDetector::addGarbageObject(this);
287 ParentModule->getFunctionList().push_back(this);
290 Function::~Function() {
291 dropAllReferences(); // After this it is safe to delete instructions.
293 // Delete all of the method arguments and unlink from symbol table...
294 ArgumentList.clear();
297 // Drop our reference to the parameter attributes, if any.
299 ParamAttrs->dropRef();
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)));
311 // Clear the lazy arguments bit.
312 const_cast<Function*>(this)->SubclassData &= ~1;
315 size_t Function::arg_size() const {
316 return getFunctionType()->getNumParams();
318 bool Function::arg_empty() const {
319 return getFunctionType()->getNumParams() == 0;
322 void Function::setParent(Module *parent) {
324 LeakDetector::addGarbageObject(this);
327 LeakDetector::removeGarbageObject(this);
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)
336 // Drop reference on the old ParamAttrsList
338 ParamAttrs->dropRef();
340 // Add reference to the new ParamAttrsList
344 // Set the new ParamAttrsList.
348 const FunctionType *Function::getFunctionType() const {
349 return cast<FunctionType>(getType()->getElementType());
352 bool Function::isVarArg() const {
353 return getFunctionType()->isVarArg();
356 const Type *Function::getReturnType() const {
357 return getFunctionType()->getReturnType();
360 void Function::removeFromParent() {
361 getParent()->getFunctionList().remove(this);
364 void Function::eraseFromParent() {
365 getParent()->getFunctionList().erase(this);
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
376 void Function::dropAllReferences() {
377 for (iterator I = begin(), E = end(); I != E; ++I)
378 I->dropAllReferences();
379 BasicBlocks.clear(); // Delete all basic blocks...
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.
389 unsigned Function::getIntrinsicID(bool noAssert) const {
390 const ValueName *ValName = this->getValueName();
393 unsigned Len = ValName->getKeyLength();
394 const char *Name = ValName->getKeyData();
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.'
400 assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
402 #define GET_FUNCTION_RECOGNIZER
403 #include "llvm/Intrinsics.gen"
404 #undef GET_FUNCTION_RECOGNIZER
405 assert(noAssert && "Invalid LLVM intrinsic name");
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[] = {
413 #define GET_INTRINSIC_NAME_TABLE
414 #include "llvm/Intrinsics.gen"
415 #undef GET_INTRINSIC_NAME_TABLE
419 std::string Result(Table[id]);
420 for (unsigned i = 0; i < numTys; ++i)
422 Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
426 const FunctionType *Intrinsic::getType(ID id, const Type **Tys,
428 const Type *ResultTy = NULL;
429 std::vector<const Type*> ArgTys;
430 bool IsVarArg = false;
432 #define GET_INTRINSIC_GENERATOR
433 #include "llvm/Intrinsics.gen"
434 #undef GET_INTRINSIC_GENERATOR
436 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
439 const ParamAttrsList *Intrinsic::getParamAttrs(ID id) {
440 static const ParamAttrsList *IntrinsicAttributes[Intrinsic::num_intrinsics];
442 if (IntrinsicAttributes[id])
443 return IntrinsicAttributes[id];
445 ParamAttrsVector Attrs;
446 uint16_t Attr = ParamAttr::None;
448 #define GET_INTRINSIC_ATTRIBUTES
449 #include "llvm/Intrinsics.gen"
450 #undef GET_INTRINSIC_ATTRIBUTES
452 // Intrinsics cannot throw exceptions.
453 Attr |= ParamAttr::NoUnwind;
455 Attrs.push_back(ParamAttrsWithIndex::get(0, Attr));
456 IntrinsicAttributes[id] = ParamAttrsList::get(Attrs);
457 return IntrinsicAttributes[id];
460 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
462 // There can never be multiple globals with the same name of different types,
463 // because intrinsics must be a specific type.
465 cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
466 getType(id, Tys, numTys)));
467 F->setParamAttrs(getParamAttrs(id));
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())
480 return StripPointerCasts(CE->getOperand(0));
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));