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/DenseMap.h"
22 #include "llvm/ADT/StringExtras.h"
25 BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
26 BasicBlock *Ret = BasicBlock::Create();
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 /// getArgNo - Return the index of this formal argument in its containing
77 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
78 unsigned Argument::getArgNo() const {
79 const Function *F = getParent();
80 assert(F && "Argument is not in a function");
82 Function::const_arg_iterator AI = F->arg_begin();
84 for (; &*AI != this; ++AI)
90 /// hasByValAttr - Return true if this argument has the byval attribute on it
91 /// in its containing function.
92 bool Argument::hasByValAttr() const {
93 if (!isa<PointerType>(getType())) return false;
94 return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
97 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
98 /// it in its containing function.
99 bool Argument::hasNoAliasAttr() const {
100 if (!isa<PointerType>(getType())) return false;
101 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
104 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
105 /// on it in its containing function.
106 bool Argument::hasNoCaptureAttr() const {
107 if (!isa<PointerType>(getType())) return false;
108 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture);
111 /// hasSRetAttr - Return true if this argument has the sret attribute on
112 /// it in its containing function.
113 bool Argument::hasStructRetAttr() const {
114 if (!isa<PointerType>(getType())) return false;
115 if (this != getParent()->arg_begin())
116 return false; // StructRet param must be first param
117 return getParent()->paramHasAttr(1, Attribute::StructRet);
120 /// addAttr - Add a Attribute to an argument
121 void Argument::addAttr(Attributes attr) {
122 getParent()->addAttribute(getArgNo() + 1, attr);
125 /// removeAttr - Remove a Attribute from an argument
126 void Argument::removeAttr(Attributes attr) {
127 getParent()->removeAttribute(getArgNo() + 1, attr);
131 //===----------------------------------------------------------------------===//
132 // Helper Methods in Function
133 //===----------------------------------------------------------------------===//
135 const FunctionType *Function::getFunctionType() const {
136 return cast<FunctionType>(getType()->getElementType());
139 bool Function::isVarArg() const {
140 return getFunctionType()->isVarArg();
143 const Type *Function::getReturnType() const {
144 return getFunctionType()->getReturnType();
147 void Function::removeFromParent() {
148 getParent()->getFunctionList().remove(this);
151 void Function::eraseFromParent() {
152 getParent()->getFunctionList().erase(this);
155 //===----------------------------------------------------------------------===//
156 // Function Implementation
157 //===----------------------------------------------------------------------===//
159 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
160 const std::string &name, Module *ParentModule)
161 : GlobalValue(PointerType::getUnqual(Ty),
162 Value::FunctionVal, 0, 0, Linkage, name) {
163 assert(FunctionType::isValidReturnType(getReturnType()) &&
164 !isa<OpaqueType>(getReturnType()) && "invalid return type");
165 SymTab = new ValueSymbolTable();
167 // If the function has arguments, mark them as lazily built.
168 if (Ty->getNumParams())
169 SubclassData = 1; // Set the "has lazy arguments" bit.
171 // Make sure that we get added to a function
172 LeakDetector::addGarbageObject(this);
175 ParentModule->getFunctionList().push_back(this);
177 // Ensure intrinsics have the right parameter attributes.
178 if (unsigned IID = getIntrinsicID())
179 setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
183 Function::~Function() {
184 dropAllReferences(); // After this it is safe to delete instructions.
186 // Delete all of the method arguments and unlink from symbol table...
187 ArgumentList.clear();
190 // Remove the function from the on-the-side GC table.
194 void Function::BuildLazyArguments() const {
195 // Create the arguments vector, all arguments start out unnamed.
196 const FunctionType *FT = getFunctionType();
197 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
198 assert(FT->getParamType(i) != Type::VoidTy &&
199 "Cannot have void typed arguments!");
200 ArgumentList.push_back(new Argument(FT->getParamType(i)));
203 // Clear the lazy arguments bit.
204 const_cast<Function*>(this)->SubclassData &= ~1;
207 size_t Function::arg_size() const {
208 return getFunctionType()->getNumParams();
210 bool Function::arg_empty() const {
211 return getFunctionType()->getNumParams() == 0;
214 void Function::setParent(Module *parent) {
216 LeakDetector::addGarbageObject(this);
219 LeakDetector::removeGarbageObject(this);
222 // dropAllReferences() - This function causes all the subinstructions to "let
223 // go" of all references that they are maintaining. This allows one to
224 // 'delete' a whole class at a time, even though there may be circular
225 // references... first all references are dropped, and all use counts go to
226 // zero. Then everything is deleted for real. Note that no operations are
227 // valid on an object that has "dropped all references", except operator
230 void Function::dropAllReferences() {
231 for (iterator I = begin(), E = end(); I != E; ++I)
232 I->dropAllReferences();
233 BasicBlocks.clear(); // Delete all basic blocks...
236 void Function::addAttribute(unsigned i, Attributes attr) {
237 AttrListPtr PAL = getAttributes();
238 PAL = PAL.addAttr(i, attr);
242 void Function::removeAttribute(unsigned i, Attributes attr) {
243 AttrListPtr PAL = getAttributes();
244 PAL = PAL.removeAttr(i, attr);
248 // Maintain the GC name for each function in an on-the-side table. This saves
249 // allocating an additional word in Function for programs which do not use GC
250 // (i.e., most programs) at the cost of increased overhead for clients which do
252 static DenseMap<const Function*,PooledStringPtr> *GCNames;
253 static StringPool *GCNamePool;
255 bool Function::hasGC() const {
256 return GCNames && GCNames->count(this);
259 const char *Function::getGC() const {
260 assert(hasGC() && "Function has no collector");
261 return *(*GCNames)[this];
264 void Function::setGC(const char *Str) {
266 GCNamePool = new StringPool();
268 GCNames = new DenseMap<const Function*,PooledStringPtr>();
269 (*GCNames)[this] = GCNamePool->intern(Str);
272 void Function::clearGC() {
274 GCNames->erase(this);
275 if (GCNames->empty()) {
278 if (GCNamePool->empty()) {
286 /// copyAttributesFrom - copy all additional attributes (those not needed to
287 /// create a Function) from the Function Src to this one.
288 void Function::copyAttributesFrom(const GlobalValue *Src) {
289 assert(isa<Function>(Src) && "Expected a Function!");
290 GlobalValue::copyAttributesFrom(Src);
291 const Function *SrcF = cast<Function>(Src);
292 setCallingConv(SrcF->getCallingConv());
293 setAttributes(SrcF->getAttributes());
295 setGC(SrcF->getGC());
300 /// getIntrinsicID - This method returns the ID number of the specified
301 /// function, or Intrinsic::not_intrinsic if the function is not an
302 /// intrinsic, or if the pointer is null. This value is always defined to be
303 /// zero to allow easy checking for whether a function is intrinsic or not. The
304 /// particular intrinsic functions which correspond to this value are defined in
305 /// llvm/Intrinsics.h.
307 unsigned Function::getIntrinsicID() const {
308 const ValueName *ValName = this->getValueName();
311 unsigned Len = ValName->getKeyLength();
312 const char *Name = ValName->getKeyData();
314 if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
315 || Name[2] != 'v' || Name[3] != 'm')
316 return 0; // All intrinsics start with 'llvm.'
318 #define GET_FUNCTION_RECOGNIZER
319 #include "llvm/Intrinsics.gen"
320 #undef GET_FUNCTION_RECOGNIZER
324 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
325 assert(id < num_intrinsics && "Invalid intrinsic ID!");
326 const char * const Table[] = {
328 #define GET_INTRINSIC_NAME_TABLE
329 #include "llvm/Intrinsics.gen"
330 #undef GET_INTRINSIC_NAME_TABLE
334 std::string Result(Table[id]);
335 for (unsigned i = 0; i < numTys; ++i) {
336 if (const PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
337 Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
338 MVT::getMVT(PTyp->getElementType()).getMVTString();
341 Result += "." + MVT::getMVT(Tys[i]).getMVTString();
346 const FunctionType *Intrinsic::getType(ID id, const Type **Tys,
348 const Type *ResultTy = NULL;
349 std::vector<const Type*> ArgTys;
350 bool IsVarArg = false;
352 #define GET_INTRINSIC_GENERATOR
353 #include "llvm/Intrinsics.gen"
354 #undef GET_INTRINSIC_GENERATOR
356 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
359 /// This defines the "Intrinsic::getAttributes(ID id)" method.
360 #define GET_INTRINSIC_ATTRIBUTES
361 #include "llvm/Intrinsics.gen"
362 #undef GET_INTRINSIC_ATTRIBUTES
364 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
366 // There can never be multiple globals with the same name of different types,
367 // because intrinsics must be a specific type.
369 cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
370 getType(id, Tys, numTys)));
373 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
374 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
375 #include "llvm/Intrinsics.gen"
376 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN