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/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"
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; ++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;
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 ParamAttrsList::~ParamAttrsList() {
205 ParamAttrsLists->RemoveNode(this);
208 //===----------------------------------------------------------------------===//
209 // Function Implementation
210 //===----------------------------------------------------------------------===//
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),
216 SymTab = new ValueSymbolTable();
218 assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
219 && "LLVM functions cannot return aggregate values!");
221 // If the function has arguments, mark them as lazily built.
222 if (Ty->getNumParams())
223 SubclassData = 1; // Set the "has lazy arguments" bit.
225 // Make sure that we get added to a function
226 LeakDetector::addGarbageObject(this);
229 ParentModule->getFunctionList().push_back(this);
232 Function::~Function() {
233 dropAllReferences(); // After this it is safe to delete instructions.
235 // Delete all of the method arguments and unlink from symbol table...
236 ArgumentList.clear();
239 // Drop our reference to the parameter attributes, if any.
241 ParamAttrs->dropRef();
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)));
253 // Clear the lazy arguments bit.
254 const_cast<Function*>(this)->SubclassData &= ~1;
257 size_t Function::arg_size() const {
258 return getFunctionType()->getNumParams();
260 bool Function::arg_empty() const {
261 return getFunctionType()->getNumParams() == 0;
264 void Function::setParent(Module *parent) {
266 LeakDetector::addGarbageObject(this);
269 LeakDetector::removeGarbageObject(this);
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)
278 // Drop reference on the old ParamAttrsList
280 ParamAttrs->dropRef();
282 // Add reference to the new ParamAttrsList
286 // Set the new ParamAttrsList.
290 bool Function::isStructReturn() const {
292 return ParamAttrs->paramHasAttr(1, ParamAttr::StructRet);
296 const FunctionType *Function::getFunctionType() const {
297 return cast<FunctionType>(getType()->getElementType());
300 bool Function::isVarArg() const {
301 return getFunctionType()->isVarArg();
304 const Type *Function::getReturnType() const {
305 return getFunctionType()->getReturnType();
308 void Function::removeFromParent() {
309 getParent()->getFunctionList().remove(this);
312 void Function::eraseFromParent() {
313 getParent()->getFunctionList().erase(this);
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
324 void Function::dropAllReferences() {
325 for (iterator I = begin(), E = end(); I != E; ++I)
326 I->dropAllReferences();
327 BasicBlocks.clear(); // Delete all basic blocks...
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.
337 unsigned Function::getIntrinsicID(bool noAssert) const {
338 const ValueName *ValName = this->getValueName();
341 unsigned Len = ValName->getKeyLength();
342 const char *Name = ValName->getKeyData();
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.'
348 assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
350 #define GET_FUNCTION_RECOGNIZER
351 #include "llvm/Intrinsics.gen"
352 #undef GET_FUNCTION_RECOGNIZER
353 assert(noAssert && "Invalid LLVM intrinsic name");
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[] = {
361 #define GET_INTRINSIC_NAME_TABLE
362 #include "llvm/Intrinsics.gen"
363 #undef GET_INTRINSIC_NAME_TABLE
367 std::string Result(Table[id]);
368 for (unsigned i = 0; i < numTys; ++i)
370 Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
374 const FunctionType *Intrinsic::getType(ID id, const Type **Tys,
376 const Type *ResultTy = NULL;
377 std::vector<const Type*> ArgTys;
378 bool IsVarArg = false;
380 #define GET_INTRINSIC_GENERATOR
381 #include "llvm/Intrinsics.gen"
382 #undef GET_INTRINSIC_GENERATOR
384 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
387 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
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)));
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())
404 return StripPointerCasts(CE->getOperand(0));
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));