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/LLVMContext.h"
18 #include "llvm/CodeGen/ValueTypes.h"
19 #include "llvm/Support/CallSite.h"
20 #include "llvm/Support/LeakDetector.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/StringPool.h"
23 #include "llvm/Support/RWMutex.h"
24 #include "llvm/Support/Threading.h"
25 #include "SymbolTableListTraitsImpl.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/StringExtras.h"
32 // Explicit instantiations of SymbolTableListTraits since some of the methods
33 // are not in the public header file...
34 template class llvm::SymbolTableListTraits<Argument, Function>;
35 template class llvm::SymbolTableListTraits<BasicBlock, Function>;
37 //===----------------------------------------------------------------------===//
38 // Argument Implementation
39 //===----------------------------------------------------------------------===//
41 Argument::Argument(const Type *Ty, const Twine &Name, Function *Par)
42 : Value(Ty, Value::ArgumentVal) {
45 // Make sure that we get added to a function
46 LeakDetector::addGarbageObject(this);
49 Par->getArgumentList().push_back(this);
53 void Argument::setParent(Function *parent) {
55 LeakDetector::addGarbageObject(this);
58 LeakDetector::removeGarbageObject(this);
61 /// getArgNo - Return the index of this formal argument in its containing
62 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
63 unsigned Argument::getArgNo() const {
64 const Function *F = getParent();
65 assert(F && "Argument is not in a function");
67 Function::const_arg_iterator AI = F->arg_begin();
69 for (; &*AI != this; ++AI)
75 /// hasByValAttr - Return true if this argument has the byval attribute on it
76 /// in its containing function.
77 bool Argument::hasByValAttr() const {
78 if (!getType()->isPointerTy()) return false;
79 return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
82 /// hasNestAttr - Return true if this argument has the nest attribute on
83 /// it in its containing function.
84 bool Argument::hasNestAttr() const {
85 if (!getType()->isPointerTy()) return false;
86 return getParent()->paramHasAttr(getArgNo()+1, Attribute::Nest);
89 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
90 /// it in its containing function.
91 bool Argument::hasNoAliasAttr() const {
92 if (!getType()->isPointerTy()) return false;
93 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
96 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
97 /// on it in its containing function.
98 bool Argument::hasNoCaptureAttr() const {
99 if (!getType()->isPointerTy()) return false;
100 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture);
103 /// hasSRetAttr - Return true if this argument has the sret attribute on
104 /// it in its containing function.
105 bool Argument::hasStructRetAttr() const {
106 if (!getType()->isPointerTy()) return false;
107 if (this != getParent()->arg_begin())
108 return false; // StructRet param must be first param
109 return getParent()->paramHasAttr(1, Attribute::StructRet);
112 /// addAttr - Add a Attribute to an argument
113 void Argument::addAttr(Attributes attr) {
114 getParent()->addAttribute(getArgNo() + 1, attr);
117 /// removeAttr - Remove a Attribute from an argument
118 void Argument::removeAttr(Attributes attr) {
119 getParent()->removeAttribute(getArgNo() + 1, attr);
123 //===----------------------------------------------------------------------===//
124 // Helper Methods in Function
125 //===----------------------------------------------------------------------===//
127 LLVMContext &Function::getContext() const {
128 return getType()->getContext();
131 const FunctionType *Function::getFunctionType() const {
132 return cast<FunctionType>(getType()->getElementType());
135 bool Function::isVarArg() const {
136 return getFunctionType()->isVarArg();
139 const Type *Function::getReturnType() const {
140 return getFunctionType()->getReturnType();
143 void Function::removeFromParent() {
144 getParent()->getFunctionList().remove(this);
147 void Function::eraseFromParent() {
148 getParent()->getFunctionList().erase(this);
151 //===----------------------------------------------------------------------===//
152 // Function Implementation
153 //===----------------------------------------------------------------------===//
155 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
156 const Twine &name, Module *ParentModule)
157 : GlobalValue(PointerType::getUnqual(Ty),
158 Value::FunctionVal, 0, 0, Linkage, name) {
159 assert(FunctionType::isValidReturnType(getReturnType()) &&
160 !getReturnType()->isOpaqueTy() && "invalid return type");
161 SymTab = new ValueSymbolTable();
163 // If the function has arguments, mark them as lazily built.
164 if (Ty->getNumParams())
165 setValueSubclassData(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())
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)->isVoidTy() &&
195 "Cannot have void typed arguments!");
196 ArgumentList.push_back(new Argument(FT->getParamType(i)));
199 // Clear the lazy arguments bit.
200 unsigned SDC = getSubclassDataFromValue();
201 const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
204 size_t Function::arg_size() const {
205 return getFunctionType()->getNumParams();
207 bool Function::arg_empty() const {
208 return getFunctionType()->getNumParams() == 0;
211 void Function::setParent(Module *parent) {
213 LeakDetector::addGarbageObject(this);
216 LeakDetector::removeGarbageObject(this);
219 // dropAllReferences() - This function causes all the subinstructions to "let
220 // go" of all references that they are maintaining. This allows one to
221 // 'delete' a whole class at a time, even though there may be circular
222 // references... first all references are dropped, and all use counts go to
223 // zero. Then everything is deleted for real. Note that no operations are
224 // valid on an object that has "dropped all references", except operator
227 void Function::dropAllReferences() {
228 for (iterator I = begin(), E = end(); I != E; ++I)
229 I->dropAllReferences();
231 // Delete all basic blocks. They are now unused, except possibly by
232 // blockaddresses, but BasicBlock's destructor takes care of those.
233 while (!BasicBlocks.empty())
234 BasicBlocks.begin()->eraseFromParent();
237 void Function::addAttribute(unsigned i, Attributes attr) {
238 AttrListPtr PAL = getAttributes();
239 PAL = PAL.addAttr(i, attr);
243 void Function::removeAttribute(unsigned i, Attributes attr) {
244 AttrListPtr PAL = getAttributes();
245 PAL = PAL.removeAttr(i, attr);
249 // Maintain the GC name for each function in an on-the-side table. This saves
250 // allocating an additional word in Function for programs which do not use GC
251 // (i.e., most programs) at the cost of increased overhead for clients which do
253 static DenseMap<const Function*,PooledStringPtr> *GCNames;
254 static StringPool *GCNamePool;
255 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
257 bool Function::hasGC() const {
258 sys::SmartScopedReader<true> Reader(*GCLock);
259 return GCNames && GCNames->count(this);
262 const char *Function::getGC() const {
263 assert(hasGC() && "Function has no collector");
264 sys::SmartScopedReader<true> Reader(*GCLock);
265 return *(*GCNames)[this];
268 void Function::setGC(const char *Str) {
269 sys::SmartScopedWriter<true> Writer(*GCLock);
271 GCNamePool = new StringPool();
273 GCNames = new DenseMap<const Function*,PooledStringPtr>();
274 (*GCNames)[this] = GCNamePool->intern(Str);
277 void Function::clearGC() {
278 sys::SmartScopedWriter<true> Writer(*GCLock);
280 GCNames->erase(this);
281 if (GCNames->empty()) {
284 if (GCNamePool->empty()) {
292 /// copyAttributesFrom - copy all additional attributes (those not needed to
293 /// create a Function) from the Function Src to this one.
294 void Function::copyAttributesFrom(const GlobalValue *Src) {
295 assert(isa<Function>(Src) && "Expected a Function!");
296 GlobalValue::copyAttributesFrom(Src);
297 const Function *SrcF = cast<Function>(Src);
298 setCallingConv(SrcF->getCallingConv());
299 setAttributes(SrcF->getAttributes());
301 setGC(SrcF->getGC());
306 /// getIntrinsicID - This method returns the ID number of the specified
307 /// function, or Intrinsic::not_intrinsic if the function is not an
308 /// intrinsic, or if the pointer is null. This value is always defined to be
309 /// zero to allow easy checking for whether a function is intrinsic or not. The
310 /// particular intrinsic functions which correspond to this value are defined in
311 /// llvm/Intrinsics.h.
313 unsigned Function::getIntrinsicID() const {
314 const ValueName *ValName = this->getValueName();
317 unsigned Len = ValName->getKeyLength();
318 const char *Name = ValName->getKeyData();
320 if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
321 || Name[2] != 'v' || Name[3] != 'm')
322 return 0; // All intrinsics start with 'llvm.'
324 #define GET_FUNCTION_RECOGNIZER
325 #include "llvm/Intrinsics.gen"
326 #undef GET_FUNCTION_RECOGNIZER
330 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
331 assert(id < num_intrinsics && "Invalid intrinsic ID!");
332 static const char * const Table[] = {
334 #define GET_INTRINSIC_NAME_TABLE
335 #include "llvm/Intrinsics.gen"
336 #undef GET_INTRINSIC_NAME_TABLE
340 std::string Result(Table[id]);
341 for (unsigned i = 0; i < numTys; ++i) {
342 if (const PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
343 Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
344 EVT::getEVT(PTyp->getElementType()).getEVTString();
347 Result += "." + EVT::getEVT(Tys[i]).getEVTString();
352 const FunctionType *Intrinsic::getType(LLVMContext &Context,
353 ID id, const Type **Tys,
355 const Type *ResultTy = NULL;
356 std::vector<const Type*> ArgTys;
357 bool IsVarArg = false;
359 #define GET_INTRINSIC_GENERATOR
360 #include "llvm/Intrinsics.gen"
361 #undef GET_INTRINSIC_GENERATOR
363 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
366 bool Intrinsic::isOverloaded(ID id) {
367 static const bool OTable[] = {
369 #define GET_INTRINSIC_OVERLOAD_TABLE
370 #include "llvm/Intrinsics.gen"
371 #undef GET_INTRINSIC_OVERLOAD_TABLE
376 /// This defines the "Intrinsic::getAttributes(ID id)" method.
377 #define GET_INTRINSIC_ATTRIBUTES
378 #include "llvm/Intrinsics.gen"
379 #undef GET_INTRINSIC_ATTRIBUTES
381 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
383 // There can never be multiple globals with the same name of different types,
384 // because intrinsics must be a specific type.
386 cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
387 getType(M->getContext(),
391 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
392 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
393 #include "llvm/Intrinsics.gen"
394 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
396 /// hasAddressTaken - returns true if there are any uses of this function
397 /// other than direct calls or invokes to it.
398 bool Function::hasAddressTaken(const User* *PutOffender) const {
399 for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
401 if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
402 return PutOffender ? (*PutOffender = U, true) : true;
403 ImmutableCallSite CS(cast<Instruction>(U));
405 return PutOffender ? (*PutOffender = U, true) : true;
410 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
411 /// setjmp or other function that gcc recognizes as "returning twice".
413 /// FIXME: Remove after <rdar://problem/8031714> is fixed.
414 /// FIXME: Is the obove FIXME valid?
415 bool Function::callsFunctionThatReturnsTwice() const {
416 const Module *M = this->getParent();
417 static const char *ReturnsTwiceFns[] = {
428 for (unsigned I = 0; I < array_lengthof(ReturnsTwiceFns); ++I)
429 if (const Function *Callee = M->getFunction(ReturnsTwiceFns[I])) {
430 if (!Callee->use_empty())
431 for (Value::const_use_iterator
432 I = Callee->use_begin(), E = Callee->use_end();
434 if (const CallInst *CI = dyn_cast<CallInst>(*I))
435 if (CI->getParent()->getParent() == this)