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/CodeGen/ValueTypes.h"
18 #include "llvm/Support/LeakDetector.h"
19 #include "llvm/Support/StringPool.h"
20 #include "SymbolTableListTraitsImpl.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/StringExtras.h"
26 BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
27 BasicBlock *Ret = BasicBlock::Create();
28 // This should not be garbage monitored.
29 LeakDetector::removeGarbageObject(Ret);
33 iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {
34 return F->getBasicBlockList();
37 Argument *ilist_traits<Argument>::createSentinel() {
38 Argument *Ret = new Argument(Type::Int32Ty);
39 // This should not be garbage monitored.
40 LeakDetector::removeGarbageObject(Ret);
44 iplist<Argument> &ilist_traits<Argument>::getList(Function *F) {
45 return F->getArgumentList();
48 // Explicit instantiations of SymbolTableListTraits since some of the methods
49 // are not in the public header file...
50 template class SymbolTableListTraits<Argument, Function>;
51 template class SymbolTableListTraits<BasicBlock, Function>;
53 //===----------------------------------------------------------------------===//
54 // Argument Implementation
55 //===----------------------------------------------------------------------===//
57 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
58 : Value(Ty, Value::ArgumentVal) {
61 // Make sure that we get added to a function
62 LeakDetector::addGarbageObject(this);
65 Par->getArgumentList().push_back(this);
69 void Argument::setParent(Function *parent) {
71 LeakDetector::addGarbageObject(this);
74 LeakDetector::removeGarbageObject(this);
77 /// getArgNo - Return the index of this formal argument in its containing
78 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
79 unsigned Argument::getArgNo() const {
80 const Function *F = getParent();
81 assert(F && "Argument is not in a function");
83 Function::const_arg_iterator AI = F->arg_begin();
85 for (; &*AI != this; ++AI)
91 /// hasByValAttr - Return true if this argument has the byval attribute on it
92 /// in its containing function.
93 bool Argument::hasByValAttr() const {
94 if (!isa<PointerType>(getType())) return false;
95 return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
98 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
99 /// it in its containing function.
100 bool Argument::hasNoAliasAttr() const {
101 if (!isa<PointerType>(getType())) return false;
102 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
105 /// hasSRetAttr - Return true if this argument has the sret attribute on
106 /// it in its containing function.
107 bool Argument::hasStructRetAttr() const {
108 if (!isa<PointerType>(getType())) return false;
109 if (this != getParent()->arg_begin())
110 return false; // StructRet param must be first param
111 return getParent()->paramHasAttr(1, Attribute::StructRet);
114 /// addAttr - Add a Attribute to an argument
115 void Argument::addAttr(Attributes attr) {
116 getParent()->addAttribute(getArgNo() + 1, attr);
119 /// removeAttr - Remove a Attribute from an argument
120 void Argument::removeAttr(Attributes attr) {
121 getParent()->removeAttribute(getArgNo() + 1, attr);
125 //===----------------------------------------------------------------------===//
126 // Helper Methods in Function
127 //===----------------------------------------------------------------------===//
129 const FunctionType *Function::getFunctionType() const {
130 return cast<FunctionType>(getType()->getElementType());
133 bool Function::isVarArg() const {
134 return getFunctionType()->isVarArg();
137 const Type *Function::getReturnType() const {
138 return getFunctionType()->getReturnType();
141 void Function::removeFromParent() {
142 getParent()->getFunctionList().remove(this);
145 void Function::eraseFromParent() {
146 getParent()->getFunctionList().erase(this);
149 //===----------------------------------------------------------------------===//
150 // Function Implementation
151 //===----------------------------------------------------------------------===//
153 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
154 const std::string &name, Module *ParentModule)
155 : GlobalValue(PointerType::getUnqual(Ty),
156 Value::FunctionVal, 0, 0, Linkage, name) {
157 SymTab = new ValueSymbolTable();
159 assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy
160 || isa<StructType>(getReturnType()))
161 && "LLVM functions cannot return aggregate values!");
163 // If the function has arguments, mark them as lazily built.
164 if (Ty->getNumParams())
165 SubclassData = 1; // Set the "has lazy arguments" bit.
167 // Make sure that we get added to a function
168 LeakDetector::addGarbageObject(this);
171 ParentModule->getFunctionList().push_back(this);
173 // Ensure intrinsics have the right parameter attributes.
174 if (unsigned IID = getIntrinsicID(true))
175 setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
179 Function::~Function() {
180 dropAllReferences(); // After this it is safe to delete instructions.
182 // Delete all of the method arguments and unlink from symbol table...
183 ArgumentList.clear();
186 // Remove the function from the on-the-side GC table.
190 void Function::BuildLazyArguments() const {
191 // Create the arguments vector, all arguments start out unnamed.
192 const FunctionType *FT = getFunctionType();
193 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
194 assert(FT->getParamType(i) != Type::VoidTy &&
195 "Cannot have void typed arguments!");
196 ArgumentList.push_back(new Argument(FT->getParamType(i)));
199 // Clear the lazy arguments bit.
200 const_cast<Function*>(this)->SubclassData &= ~1;
203 size_t Function::arg_size() const {
204 return getFunctionType()->getNumParams();
206 bool Function::arg_empty() const {
207 return getFunctionType()->getNumParams() == 0;
210 void Function::setParent(Module *parent) {
212 LeakDetector::addGarbageObject(this);
215 LeakDetector::removeGarbageObject(this);
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 void Function::addAttribute(unsigned i, Attributes attr) {
233 AttrListPtr PAL = getAttributes();
234 PAL = PAL.addAttr(i, attr);
238 void Function::removeAttribute(unsigned i, Attributes attr) {
239 AttrListPtr PAL = getAttributes();
240 PAL = PAL.removeAttr(i, attr);
244 // Maintain the GC name for each function in an on-the-side table. This saves
245 // allocating an additional word in Function for programs which do not use GC
246 // (i.e., most programs) at the cost of increased overhead for clients which do
248 static DenseMap<const Function*,PooledStringPtr> *GCNames;
249 static StringPool *GCNamePool;
251 bool Function::hasGC() const {
252 return GCNames && GCNames->count(this);
255 const char *Function::getGC() const {
256 assert(hasGC() && "Function has no collector");
257 return *(*GCNames)[this];
260 void Function::setGC(const char *Str) {
262 GCNamePool = new StringPool();
264 GCNames = new DenseMap<const Function*,PooledStringPtr>();
265 (*GCNames)[this] = GCNamePool->intern(Str);
268 void Function::clearGC() {
270 GCNames->erase(this);
271 if (GCNames->empty()) {
274 if (GCNamePool->empty()) {
282 /// copyAttributesFrom - copy all additional attributes (those not needed to
283 /// create a Function) from the Function Src to this one.
284 void Function::copyAttributesFrom(const GlobalValue *Src) {
285 assert(isa<Function>(Src) && "Expected a Function!");
286 GlobalValue::copyAttributesFrom(Src);
287 const Function *SrcF = cast<Function>(Src);
288 setCallingConv(SrcF->getCallingConv());
289 setAttributes(SrcF->getAttributes());
291 setGC(SrcF->getGC());
296 /// getIntrinsicID - This method returns the ID number of the specified
297 /// function, or Intrinsic::not_intrinsic if the function is not an
298 /// intrinsic, or if the pointer is null. This value is always defined to be
299 /// zero to allow easy checking for whether a function is intrinsic or not. The
300 /// particular intrinsic functions which correspond to this value are defined in
301 /// llvm/Intrinsics.h.
303 unsigned Function::getIntrinsicID(bool noAssert) const {
304 const ValueName *ValName = this->getValueName();
307 unsigned Len = ValName->getKeyLength();
308 const char *Name = ValName->getKeyData();
310 if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
311 || Name[2] != 'v' || Name[3] != 'm')
312 return 0; // All intrinsics start with 'llvm.'
314 assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
316 #define GET_FUNCTION_RECOGNIZER
317 #include "llvm/Intrinsics.gen"
318 #undef GET_FUNCTION_RECOGNIZER
319 assert(noAssert && "Invalid LLVM intrinsic name");
323 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
324 assert(id < num_intrinsics && "Invalid intrinsic ID!");
325 const char * const Table[] = {
327 #define GET_INTRINSIC_NAME_TABLE
328 #include "llvm/Intrinsics.gen"
329 #undef GET_INTRINSIC_NAME_TABLE
333 std::string Result(Table[id]);
334 for (unsigned i = 0; i < numTys; ++i) {
335 if (const PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
336 Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
337 MVT::getMVT(PTyp->getElementType()).getMVTString();
340 Result += "." + MVT::getMVT(Tys[i]).getMVTString();
345 const FunctionType *Intrinsic::getType(ID id, const Type **Tys,
347 const Type *ResultTy = NULL;
348 std::vector<const Type*> ArgTys;
349 bool IsVarArg = false;
351 #define GET_INTRINSIC_GENERATOR
352 #include "llvm/Intrinsics.gen"
353 #undef GET_INTRINSIC_GENERATOR
355 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
358 AttrListPtr Intrinsic::getAttributes(ID id) {
359 Attributes Attr = Attribute::None;
361 #define GET_INTRINSIC_ATTRIBUTES
362 #include "llvm/Intrinsics.gen"
363 #undef GET_INTRINSIC_ATTRIBUTES
365 // Intrinsics cannot throw exceptions.
366 Attr |= Attribute::NoUnwind;
368 AttributeWithIndex PAWI = AttributeWithIndex::get(~0, Attr);
369 return AttrListPtr::get(&PAWI, 1);
372 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
374 // There can never be multiple globals with the same name of different types,
375 // because intrinsics must be a specific type.
377 cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
378 getType(id, Tys, numTys)));