1 //===-- Function.cpp - Implement the Global object classes ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/ParameterAttributes.h"
18 #include "llvm/CodeGen/ValueTypes.h"
19 #include "llvm/Support/LeakDetector.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 // Helper Methods in Function
80 //===----------------------------------------------------------------------===//
82 const FunctionType *Function::getFunctionType() const {
83 return cast<FunctionType>(getType()->getElementType());
86 bool Function::isVarArg() const {
87 return getFunctionType()->isVarArg();
90 const Type *Function::getReturnType() const {
91 return getFunctionType()->getReturnType();
94 void Function::removeFromParent() {
95 getParent()->getFunctionList().remove(this);
98 void Function::eraseFromParent() {
99 getParent()->getFunctionList().erase(this);
102 /// @brief Determine whether the function has the given attribute.
103 bool Function::paramHasAttr(uint16_t i, unsigned attr) const {
104 return ParamAttrs && ParamAttrs->paramHasAttr(i, (ParameterAttributes)attr);
107 /// @brief Determine if the function cannot return.
108 bool Function::doesNotReturn() const {
109 return paramHasAttr(0, ParamAttr::NoReturn);
112 /// @brief Determine if the function cannot unwind.
113 bool Function::doesNotThrow() const {
114 return paramHasAttr(0, ParamAttr::NoUnwind);
117 /// @brief Determine if the function does not access memory.
118 bool Function::doesNotAccessMemory() const {
119 return paramHasAttr(0, ParamAttr::ReadNone);
122 /// @brief Determine if the function does not access or only reads memory.
123 bool Function::onlyReadsMemory() const {
124 return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
127 /// @brief Determine if the function returns a structure.
128 bool Function::isStructReturn() const {
129 return paramHasAttr(1, ParamAttr::StructRet);
132 //===----------------------------------------------------------------------===//
133 // Function Implementation
134 //===----------------------------------------------------------------------===//
136 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
137 const std::string &name, Module *ParentModule)
138 : GlobalValue(PointerType::getUnqual(Ty),
139 Value::FunctionVal, 0, 0, Linkage, name),
141 SymTab = new ValueSymbolTable();
143 assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)
144 && "LLVM functions cannot return aggregate values!");
146 // If the function has arguments, mark them as lazily built.
147 if (Ty->getNumParams())
148 SubclassData = 1; // Set the "has lazy arguments" bit.
150 // Make sure that we get added to a function
151 LeakDetector::addGarbageObject(this);
154 ParentModule->getFunctionList().push_back(this);
157 Function::~Function() {
158 dropAllReferences(); // After this it is safe to delete instructions.
160 // Delete all of the method arguments and unlink from symbol table...
161 ArgumentList.clear();
164 // Drop our reference to the parameter attributes, if any.
166 ParamAttrs->dropRef();
168 // Remove the function from the on-the-side collector table.
172 void Function::BuildLazyArguments() const {
173 // Create the arguments vector, all arguments start out unnamed.
174 const FunctionType *FT = getFunctionType();
175 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
176 assert(FT->getParamType(i) != Type::VoidTy &&
177 "Cannot have void typed arguments!");
178 ArgumentList.push_back(new Argument(FT->getParamType(i)));
181 // Clear the lazy arguments bit.
182 const_cast<Function*>(this)->SubclassData &= ~1;
185 size_t Function::arg_size() const {
186 return getFunctionType()->getNumParams();
188 bool Function::arg_empty() const {
189 return getFunctionType()->getNumParams() == 0;
192 void Function::setParent(Module *parent) {
194 LeakDetector::addGarbageObject(this);
197 LeakDetector::removeGarbageObject(this);
200 void Function::setParamAttrs(const ParamAttrsList *attrs) {
201 // Avoid deleting the ParamAttrsList if they are setting the
202 // attributes to the same list.
203 if (ParamAttrs == attrs)
206 // Drop reference on the old ParamAttrsList
208 ParamAttrs->dropRef();
210 // Add reference to the new ParamAttrsList
214 // Set the new ParamAttrsList.
218 // dropAllReferences() - This function causes all the subinstructions to "let
219 // go" of all references that they are maintaining. This allows one to
220 // 'delete' a whole class at a time, even though there may be circular
221 // references... first all references are dropped, and all use counts go to
222 // zero. Then everything is deleted for real. Note that no operations are
223 // valid on an object that has "dropped all references", except operator
226 void Function::dropAllReferences() {
227 for (iterator I = begin(), E = end(); I != E; ++I)
228 I->dropAllReferences();
229 BasicBlocks.clear(); // Delete all basic blocks...
232 // Maintain the collector name for each function in an on-the-side table. This
233 // saves allocating an additional word in Function for programs which do not use
234 // GC (i.e., most programs) at the cost of increased overhead for clients which
236 static DenseMap<const Function*,PooledStringPtr> *CollectorNames;
237 static StringPool *CollectorNamePool;
239 bool Function::hasCollector() const {
240 return CollectorNames && CollectorNames->count(this);
243 const char *Function::getCollector() const {
244 assert(hasCollector() && "Function has no collector");
245 return *(*CollectorNames)[this];
248 void Function::setCollector(const char *Str) {
249 if (!CollectorNamePool)
250 CollectorNamePool = new StringPool();
252 CollectorNames = new DenseMap<const Function*,PooledStringPtr>();
253 (*CollectorNames)[this] = CollectorNamePool->intern(Str);
256 void Function::clearCollector() {
257 if (CollectorNames) {
258 CollectorNames->erase(this);
259 if (CollectorNames->empty()) {
260 delete CollectorNames;
262 if (CollectorNamePool->empty()) {
263 delete CollectorNamePool;
264 CollectorNamePool = 0;
270 /// getIntrinsicID - This method returns the ID number of the specified
271 /// function, or Intrinsic::not_intrinsic if the function is not an
272 /// intrinsic, or if the pointer is null. This value is always defined to be
273 /// zero to allow easy checking for whether a function is intrinsic or not. The
274 /// particular intrinsic functions which correspond to this value are defined in
275 /// llvm/Intrinsics.h.
277 unsigned Function::getIntrinsicID(bool noAssert) const {
278 const ValueName *ValName = this->getValueName();
281 unsigned Len = ValName->getKeyLength();
282 const char *Name = ValName->getKeyData();
284 if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
285 || Name[2] != 'v' || Name[3] != 'm')
286 return 0; // All intrinsics start with 'llvm.'
288 assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
290 #define GET_FUNCTION_RECOGNIZER
291 #include "llvm/Intrinsics.gen"
292 #undef GET_FUNCTION_RECOGNIZER
293 assert(noAssert && "Invalid LLVM intrinsic name");
297 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
298 assert(id < num_intrinsics && "Invalid intrinsic ID!");
299 const char * const Table[] = {
301 #define GET_INTRINSIC_NAME_TABLE
302 #include "llvm/Intrinsics.gen"
303 #undef GET_INTRINSIC_NAME_TABLE
307 std::string Result(Table[id]);
308 for (unsigned i = 0; i < numTys; ++i)
310 Result += "." + MVT::getValueTypeString(MVT::getValueType(Tys[i]));
314 const FunctionType *Intrinsic::getType(ID id, const Type **Tys,
316 const Type *ResultTy = NULL;
317 std::vector<const Type*> ArgTys;
318 bool IsVarArg = false;
320 #define GET_INTRINSIC_GENERATOR
321 #include "llvm/Intrinsics.gen"
322 #undef GET_INTRINSIC_GENERATOR
324 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
327 const ParamAttrsList *Intrinsic::getParamAttrs(ID id) {
328 ParamAttrsVector Attrs;
329 uint16_t Attr = ParamAttr::None;
331 #define GET_INTRINSIC_ATTRIBUTES
332 #include "llvm/Intrinsics.gen"
333 #undef GET_INTRINSIC_ATTRIBUTES
335 // Intrinsics cannot throw exceptions.
336 Attr |= ParamAttr::NoUnwind;
338 Attrs.push_back(ParamAttrsWithIndex::get(0, Attr));
339 return ParamAttrsList::get(Attrs);
342 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
344 // There can never be multiple globals with the same name of different types,
345 // because intrinsics must be a specific type.
347 cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
348 getType(id, Tys, numTys)));
349 F->setParamAttrs(getParamAttrs(id));
353 Value *IntrinsicInst::StripPointerCasts(Value *Ptr) {
354 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
355 if (CE->getOpcode() == Instruction::BitCast) {
356 if (isa<PointerType>(CE->getOperand(0)->getType()))
357 return StripPointerCasts(CE->getOperand(0));
358 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
359 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
360 if (!CE->getOperand(i)->isNullValue())
362 return StripPointerCasts(CE->getOperand(0));
367 if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {
368 if (isa<PointerType>(CI->getOperand(0)->getType()))
369 return StripPointerCasts(CI->getOperand(0));
370 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
371 if (GEP->hasAllZeroIndices())
372 return StripPointerCasts(GEP->getOperand(0));