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/InstIterator.h"
21 #include "llvm/Support/LeakDetector.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/StringPool.h"
24 #include "llvm/Support/RWMutex.h"
25 #include "llvm/Support/Threading.h"
26 #include "SymbolTableListTraitsImpl.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/StringExtras.h"
33 // Explicit instantiations of SymbolTableListTraits since some of the methods
34 // are not in the public header file...
35 template class llvm::SymbolTableListTraits<Argument, Function>;
36 template class llvm::SymbolTableListTraits<BasicBlock, Function>;
38 //===----------------------------------------------------------------------===//
39 // Argument Implementation
40 //===----------------------------------------------------------------------===//
42 void Argument::anchor() { }
44 Argument::Argument(Type *Ty, const Twine &Name, Function *Par)
45 : Value(Ty, Value::ArgumentVal) {
48 // Make sure that we get added to a function
49 LeakDetector::addGarbageObject(this);
52 Par->getArgumentList().push_back(this);
56 void Argument::setParent(Function *parent) {
58 LeakDetector::addGarbageObject(this);
61 LeakDetector::removeGarbageObject(this);
64 /// getArgNo - Return the index of this formal argument in its containing
65 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
66 unsigned Argument::getArgNo() const {
67 const Function *F = getParent();
68 assert(F && "Argument is not in a function");
70 Function::const_arg_iterator AI = F->arg_begin();
72 for (; &*AI != this; ++AI)
78 /// hasByValAttr - Return true if this argument has the byval attribute on it
79 /// in its containing function.
80 bool Argument::hasByValAttr() const {
81 if (!getType()->isPointerTy()) return false;
82 return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
85 unsigned Argument::getParamAlignment() const {
86 assert(getType()->isPointerTy() && "Only pointers have alignments");
87 return getParent()->getParamAlignment(getArgNo()+1);
91 /// hasNestAttr - Return true if this argument has the nest attribute on
92 /// it in its containing function.
93 bool Argument::hasNestAttr() const {
94 if (!getType()->isPointerTy()) return false;
95 return getParent()->paramHasAttr(getArgNo()+1, Attribute::Nest);
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 (!getType()->isPointerTy()) return false;
102 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
105 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
106 /// on it in its containing function.
107 bool Argument::hasNoCaptureAttr() const {
108 if (!getType()->isPointerTy()) return false;
109 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture);
112 /// hasSRetAttr - Return true if this argument has the sret attribute on
113 /// it in its containing function.
114 bool Argument::hasStructRetAttr() const {
115 if (!getType()->isPointerTy()) return false;
116 if (this != getParent()->arg_begin())
117 return false; // StructRet param must be first param
118 return getParent()->paramHasAttr(1, Attribute::StructRet);
121 /// addAttr - Add a Attribute to an argument
122 void Argument::addAttr(Attributes attr) {
123 getParent()->addAttribute(getArgNo() + 1, attr);
126 /// removeAttr - Remove a Attribute from an argument
127 void Argument::removeAttr(Attributes attr) {
128 getParent()->removeAttribute(getArgNo() + 1, attr);
132 //===----------------------------------------------------------------------===//
133 // Helper Methods in Function
134 //===----------------------------------------------------------------------===//
136 LLVMContext &Function::getContext() const {
137 return getType()->getContext();
140 FunctionType *Function::getFunctionType() const {
141 return cast<FunctionType>(getType()->getElementType());
144 bool Function::isVarArg() const {
145 return getFunctionType()->isVarArg();
148 Type *Function::getReturnType() const {
149 return getFunctionType()->getReturnType();
152 void Function::removeFromParent() {
153 getParent()->getFunctionList().remove(this);
156 void Function::eraseFromParent() {
157 getParent()->getFunctionList().erase(this);
160 //===----------------------------------------------------------------------===//
161 // Function Implementation
162 //===----------------------------------------------------------------------===//
164 Function::Function(FunctionType *Ty, LinkageTypes Linkage,
165 const Twine &name, Module *ParentModule)
166 : GlobalValue(PointerType::getUnqual(Ty),
167 Value::FunctionVal, 0, 0, Linkage, name) {
168 assert(FunctionType::isValidReturnType(getReturnType()) &&
169 "invalid return type");
170 SymTab = new ValueSymbolTable();
172 // If the function has arguments, mark them as lazily built.
173 if (Ty->getNumParams())
174 setValueSubclassData(1); // Set the "has lazy arguments" bit.
176 // Make sure that we get added to a function
177 LeakDetector::addGarbageObject(this);
180 ParentModule->getFunctionList().push_back(this);
182 // Ensure intrinsics have the right parameter attributes.
183 if (unsigned IID = getIntrinsicID())
184 setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
188 Function::~Function() {
189 dropAllReferences(); // After this it is safe to delete instructions.
191 // Delete all of the method arguments and unlink from symbol table...
192 ArgumentList.clear();
195 // Remove the function from the on-the-side GC table.
199 void Function::BuildLazyArguments() const {
200 // Create the arguments vector, all arguments start out unnamed.
201 FunctionType *FT = getFunctionType();
202 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
203 assert(!FT->getParamType(i)->isVoidTy() &&
204 "Cannot have void typed arguments!");
205 ArgumentList.push_back(new Argument(FT->getParamType(i)));
208 // Clear the lazy arguments bit.
209 unsigned SDC = getSubclassDataFromValue();
210 const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
213 size_t Function::arg_size() const {
214 return getFunctionType()->getNumParams();
216 bool Function::arg_empty() const {
217 return getFunctionType()->getNumParams() == 0;
220 void Function::setParent(Module *parent) {
222 LeakDetector::addGarbageObject(this);
225 LeakDetector::removeGarbageObject(this);
228 // dropAllReferences() - This function causes all the subinstructions to "let
229 // go" of all references that they are maintaining. This allows one to
230 // 'delete' a whole class at a time, even though there may be circular
231 // references... first all references are dropped, and all use counts go to
232 // zero. Then everything is deleted for real. Note that no operations are
233 // valid on an object that has "dropped all references", except operator
236 void Function::dropAllReferences() {
237 for (iterator I = begin(), E = end(); I != E; ++I)
238 I->dropAllReferences();
240 // Delete all basic blocks. They are now unused, except possibly by
241 // blockaddresses, but BasicBlock's destructor takes care of those.
242 while (!BasicBlocks.empty())
243 BasicBlocks.begin()->eraseFromParent();
246 void Function::addAttribute(unsigned i, Attributes attr) {
247 AttrListPtr PAL = getAttributes();
248 PAL = PAL.addAttr(i, attr);
252 void Function::removeAttribute(unsigned i, Attributes attr) {
253 AttrListPtr PAL = getAttributes();
254 PAL = PAL.removeAttr(i, attr);
258 // Maintain the GC name for each function in an on-the-side table. This saves
259 // allocating an additional word in Function for programs which do not use GC
260 // (i.e., most programs) at the cost of increased overhead for clients which do
262 static DenseMap<const Function*,PooledStringPtr> *GCNames;
263 static StringPool *GCNamePool;
264 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
266 bool Function::hasGC() const {
267 sys::SmartScopedReader<true> Reader(*GCLock);
268 return GCNames && GCNames->count(this);
271 const char *Function::getGC() const {
272 assert(hasGC() && "Function has no collector");
273 sys::SmartScopedReader<true> Reader(*GCLock);
274 return *(*GCNames)[this];
277 void Function::setGC(const char *Str) {
278 sys::SmartScopedWriter<true> Writer(*GCLock);
280 GCNamePool = new StringPool();
282 GCNames = new DenseMap<const Function*,PooledStringPtr>();
283 (*GCNames)[this] = GCNamePool->intern(Str);
286 void Function::clearGC() {
287 sys::SmartScopedWriter<true> Writer(*GCLock);
289 GCNames->erase(this);
290 if (GCNames->empty()) {
293 if (GCNamePool->empty()) {
301 /// copyAttributesFrom - copy all additional attributes (those not needed to
302 /// create a Function) from the Function Src to this one.
303 void Function::copyAttributesFrom(const GlobalValue *Src) {
304 assert(isa<Function>(Src) && "Expected a Function!");
305 GlobalValue::copyAttributesFrom(Src);
306 const Function *SrcF = cast<Function>(Src);
307 setCallingConv(SrcF->getCallingConv());
308 setAttributes(SrcF->getAttributes());
310 setGC(SrcF->getGC());
315 /// getIntrinsicID - This method returns the ID number of the specified
316 /// function, or Intrinsic::not_intrinsic if the function is not an
317 /// intrinsic, or if the pointer is null. This value is always defined to be
318 /// zero to allow easy checking for whether a function is intrinsic or not. The
319 /// particular intrinsic functions which correspond to this value are defined in
320 /// llvm/Intrinsics.h.
322 unsigned Function::getIntrinsicID() const {
323 const ValueName *ValName = this->getValueName();
326 unsigned Len = ValName->getKeyLength();
327 const char *Name = ValName->getKeyData();
329 if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
330 || Name[2] != 'v' || Name[3] != 'm')
331 return 0; // All intrinsics start with 'llvm.'
333 #define GET_FUNCTION_RECOGNIZER
334 #include "llvm/Intrinsics.gen"
335 #undef GET_FUNCTION_RECOGNIZER
339 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
340 assert(id < num_intrinsics && "Invalid intrinsic ID!");
341 static const char * const Table[] = {
343 #define GET_INTRINSIC_NAME_TABLE
344 #include "llvm/Intrinsics.gen"
345 #undef GET_INTRINSIC_NAME_TABLE
349 std::string Result(Table[id]);
350 for (unsigned i = 0; i < Tys.size(); ++i) {
351 if (PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
352 Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
353 EVT::getEVT(PTyp->getElementType()).getEVTString();
356 Result += "." + EVT::getEVT(Tys[i]).getEVTString();
361 FunctionType *Intrinsic::getType(LLVMContext &Context,
362 ID id, ArrayRef<Type*> Tys) {
363 Type *ResultTy = NULL;
364 SmallVector<Type*, 8> ArgTys;
365 bool IsVarArg = false;
367 #define GET_INTRINSIC_GENERATOR
368 #include "llvm/Intrinsics.gen"
369 #undef GET_INTRINSIC_GENERATOR
371 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
374 bool Intrinsic::isOverloaded(ID id) {
375 static const bool OTable[] = {
377 #define GET_INTRINSIC_OVERLOAD_TABLE
378 #include "llvm/Intrinsics.gen"
379 #undef GET_INTRINSIC_OVERLOAD_TABLE
384 /// This defines the "Intrinsic::getAttributes(ID id)" method.
385 #define GET_INTRINSIC_ATTRIBUTES
386 #include "llvm/Intrinsics.gen"
387 #undef GET_INTRINSIC_ATTRIBUTES
389 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
390 // There can never be multiple globals with the same name of different types,
391 // because intrinsics must be a specific type.
393 cast<Function>(M->getOrInsertFunction(getName(id, Tys),
394 getType(M->getContext(), id, Tys)));
397 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
398 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
399 #include "llvm/Intrinsics.gen"
400 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
402 /// hasAddressTaken - returns true if there are any uses of this function
403 /// other than direct calls or invokes to it.
404 bool Function::hasAddressTaken(const User* *PutOffender) const {
405 for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
407 // FIXME: Check for blockaddress, which does not take the address.
408 if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
409 return PutOffender ? (*PutOffender = U, true) : true;
410 ImmutableCallSite CS(cast<Instruction>(U));
412 return PutOffender ? (*PutOffender = U, true) : true;
417 bool Function::isDefTriviallyDead() const {
419 if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
420 !hasAvailableExternallyLinkage())
423 // Check if the function is used by anything other than a blockaddress.
424 for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I)
425 if (!isa<BlockAddress>(*I))
431 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
432 /// setjmp or other function that gcc recognizes as "returning twice".
433 bool Function::callsFunctionThatReturnsTwice() const {
434 for (const_inst_iterator
435 I = inst_begin(this), E = inst_end(this); I != E; ++I) {
436 const CallInst* callInst = dyn_cast<CallInst>(&*I);
439 if (callInst->canReturnTwice())