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/ManagedStatic.h"
20 #include "llvm/Support/StringPool.h"
21 #include "llvm/Support/Threading.h"
22 #include "llvm/System/RWMutex.h"
23 #include "SymbolTableListTraitsImpl.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/StringExtras.h"
29 // Explicit instantiations of SymbolTableListTraits since some of the methods
30 // are not in the public header file...
31 template class SymbolTableListTraits<Argument, Function>;
32 template class SymbolTableListTraits<BasicBlock, Function>;
34 //===----------------------------------------------------------------------===//
35 // Argument Implementation
36 //===----------------------------------------------------------------------===//
38 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
39 : Value(Ty, Value::ArgumentVal) {
42 // Make sure that we get added to a function
43 LeakDetector::addGarbageObject(this);
46 Par->getArgumentList().push_back(this);
50 void Argument::setParent(Function *parent) {
52 LeakDetector::addGarbageObject(this);
55 LeakDetector::removeGarbageObject(this);
58 /// getArgNo - Return the index of this formal argument in its containing
59 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
60 unsigned Argument::getArgNo() const {
61 const Function *F = getParent();
62 assert(F && "Argument is not in a function");
64 Function::const_arg_iterator AI = F->arg_begin();
66 for (; &*AI != this; ++AI)
72 /// hasByValAttr - Return true if this argument has the byval attribute on it
73 /// in its containing function.
74 bool Argument::hasByValAttr() const {
75 if (!isa<PointerType>(getType())) return false;
76 return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
79 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
80 /// it in its containing function.
81 bool Argument::hasNoAliasAttr() const {
82 if (!isa<PointerType>(getType())) return false;
83 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
86 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
87 /// on it in its containing function.
88 bool Argument::hasNoCaptureAttr() const {
89 if (!isa<PointerType>(getType())) return false;
90 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture);
93 /// hasSRetAttr - Return true if this argument has the sret attribute on
94 /// it in its containing function.
95 bool Argument::hasStructRetAttr() const {
96 if (!isa<PointerType>(getType())) return false;
97 if (this != getParent()->arg_begin())
98 return false; // StructRet param must be first param
99 return getParent()->paramHasAttr(1, Attribute::StructRet);
102 /// addAttr - Add a Attribute to an argument
103 void Argument::addAttr(Attributes attr) {
104 getParent()->addAttribute(getArgNo() + 1, attr);
107 /// removeAttr - Remove a Attribute from an argument
108 void Argument::removeAttr(Attributes attr) {
109 getParent()->removeAttribute(getArgNo() + 1, attr);
113 //===----------------------------------------------------------------------===//
114 // Helper Methods in Function
115 //===----------------------------------------------------------------------===//
117 const FunctionType *Function::getFunctionType() const {
118 return cast<FunctionType>(getType()->getElementType());
121 bool Function::isVarArg() const {
122 return getFunctionType()->isVarArg();
125 const Type *Function::getReturnType() const {
126 return getFunctionType()->getReturnType();
129 void Function::removeFromParent() {
130 getParent()->getFunctionList().remove(this);
133 void Function::eraseFromParent() {
134 getParent()->getFunctionList().erase(this);
137 //===----------------------------------------------------------------------===//
138 // Function Implementation
139 //===----------------------------------------------------------------------===//
141 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
142 const std::string &name, Module *ParentModule)
143 : GlobalValue(PointerType::getUnqual(Ty),
144 Value::FunctionVal, 0, 0, Linkage, name) {
145 assert(FunctionType::isValidReturnType(getReturnType()) &&
146 !isa<OpaqueType>(getReturnType()) && "invalid return type");
147 SymTab = new ValueSymbolTable();
149 // If the function has arguments, mark them as lazily built.
150 if (Ty->getNumParams())
151 SubclassData = 1; // Set the "has lazy arguments" bit.
153 // Make sure that we get added to a function
154 LeakDetector::addGarbageObject(this);
157 ParentModule->getFunctionList().push_back(this);
159 // Ensure intrinsics have the right parameter attributes.
160 if (unsigned IID = getIntrinsicID())
161 setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
165 Function::~Function() {
166 dropAllReferences(); // After this it is safe to delete instructions.
168 // Delete all of the method arguments and unlink from symbol table...
169 ArgumentList.clear();
172 // Remove the function from the on-the-side GC table.
176 void Function::BuildLazyArguments() const {
177 // Create the arguments vector, all arguments start out unnamed.
178 const FunctionType *FT = getFunctionType();
179 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
180 assert(FT->getParamType(i) != Type::VoidTy &&
181 "Cannot have void typed arguments!");
182 ArgumentList.push_back(new Argument(FT->getParamType(i)));
185 // Clear the lazy arguments bit.
186 const_cast<Function*>(this)->SubclassData &= ~1;
189 size_t Function::arg_size() const {
190 return getFunctionType()->getNumParams();
192 bool Function::arg_empty() const {
193 return getFunctionType()->getNumParams() == 0;
196 void Function::setParent(Module *parent) {
198 LeakDetector::addGarbageObject(this);
201 LeakDetector::removeGarbageObject(this);
204 // dropAllReferences() - This function causes all the subinstructions to "let
205 // go" of all references that they are maintaining. This allows one to
206 // 'delete' a whole class at a time, even though there may be circular
207 // references... first all references are dropped, and all use counts go to
208 // zero. Then everything is deleted for real. Note that no operations are
209 // valid on an object that has "dropped all references", except operator
212 void Function::dropAllReferences() {
213 for (iterator I = begin(), E = end(); I != E; ++I)
214 I->dropAllReferences();
215 BasicBlocks.clear(); // Delete all basic blocks...
218 void Function::addAttribute(unsigned i, Attributes attr) {
219 AttrListPtr PAL = getAttributes();
220 PAL = PAL.addAttr(i, attr);
224 void Function::removeAttribute(unsigned i, Attributes attr) {
225 AttrListPtr PAL = getAttributes();
226 PAL = PAL.removeAttr(i, attr);
230 // Maintain the GC name for each function in an on-the-side table. This saves
231 // allocating an additional word in Function for programs which do not use GC
232 // (i.e., most programs) at the cost of increased overhead for clients which do
234 static DenseMap<const Function*,PooledStringPtr> *GCNames;
235 static StringPool *GCNamePool;
236 static ManagedStatic<sys::RWMutex> GCLock;
238 bool Function::hasGC() const {
239 if (llvm_is_multithreaded()) {
240 sys::ScopedReader Reader(&*GCLock);
241 return GCNames && GCNames->count(this);
243 return GCNames && GCNames->count(this);
246 const char *Function::getGC() const {
247 assert(hasGC() && "Function has no collector");
248 if (llvm_is_multithreaded()) {
249 sys::ScopedReader Reader(&*GCLock);
250 return *(*GCNames)[this];
252 return *(*GCNames)[this];
255 void Function::setGC(const char *Str) {
256 if (llvm_is_multithreaded()) GCLock->writer_acquire();
258 GCNamePool = new StringPool();
260 GCNames = new DenseMap<const Function*,PooledStringPtr>();
261 (*GCNames)[this] = GCNamePool->intern(Str);
262 if (llvm_is_multithreaded()) GCLock->writer_release();
265 void Function::clearGC() {
266 if (llvm_is_multithreaded()) GCLock->writer_acquire();
268 GCNames->erase(this);
269 if (GCNames->empty()) {
272 if (GCNamePool->empty()) {
278 if (llvm_is_multithreaded()) GCLock->writer_release();
281 /// copyAttributesFrom - copy all additional attributes (those not needed to
282 /// create a Function) from the Function Src to this one.
283 void Function::copyAttributesFrom(const GlobalValue *Src) {
284 assert(isa<Function>(Src) && "Expected a Function!");
285 GlobalValue::copyAttributesFrom(Src);
286 const Function *SrcF = cast<Function>(Src);
287 setCallingConv(SrcF->getCallingConv());
288 setAttributes(SrcF->getAttributes());
290 setGC(SrcF->getGC());
295 /// getIntrinsicID - This method returns the ID number of the specified
296 /// function, or Intrinsic::not_intrinsic if the function is not an
297 /// intrinsic, or if the pointer is null. This value is always defined to be
298 /// zero to allow easy checking for whether a function is intrinsic or not. The
299 /// particular intrinsic functions which correspond to this value are defined in
300 /// llvm/Intrinsics.h.
302 unsigned Function::getIntrinsicID() const {
303 const ValueName *ValName = this->getValueName();
306 unsigned Len = ValName->getKeyLength();
307 const char *Name = ValName->getKeyData();
309 if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
310 || Name[2] != 'v' || Name[3] != 'm')
311 return 0; // All intrinsics start with 'llvm.'
313 #define GET_FUNCTION_RECOGNIZER
314 #include "llvm/Intrinsics.gen"
315 #undef GET_FUNCTION_RECOGNIZER
319 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
320 assert(id < num_intrinsics && "Invalid intrinsic ID!");
321 const char * const Table[] = {
323 #define GET_INTRINSIC_NAME_TABLE
324 #include "llvm/Intrinsics.gen"
325 #undef GET_INTRINSIC_NAME_TABLE
329 std::string Result(Table[id]);
330 for (unsigned i = 0; i < numTys; ++i) {
331 if (const PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
332 Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
333 MVT::getMVT(PTyp->getElementType()).getMVTString();
336 Result += "." + MVT::getMVT(Tys[i]).getMVTString();
341 const FunctionType *Intrinsic::getType(ID id, const Type **Tys,
343 const Type *ResultTy = NULL;
344 std::vector<const Type*> ArgTys;
345 bool IsVarArg = false;
347 #define GET_INTRINSIC_GENERATOR
348 #include "llvm/Intrinsics.gen"
349 #undef GET_INTRINSIC_GENERATOR
351 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
354 bool Intrinsic::isOverloaded(ID id) {
355 const bool OTable[] = {
357 #define GET_INTRINSIC_OVERLOAD_TABLE
358 #include "llvm/Intrinsics.gen"
359 #undef GET_INTRINSIC_OVERLOAD_TABLE
364 /// This defines the "Intrinsic::getAttributes(ID id)" method.
365 #define GET_INTRINSIC_ATTRIBUTES
366 #include "llvm/Intrinsics.gen"
367 #undef GET_INTRINSIC_ATTRIBUTES
369 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
371 // There can never be multiple globals with the same name of different types,
372 // because intrinsics must be a specific type.
374 cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
375 getType(id, Tys, numTys)));
378 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
379 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
380 #include "llvm/Intrinsics.gen"
381 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
383 /// hasAddressTaken - returns true if there are any uses of this function
384 /// other than direct calls or invokes to it.
385 bool Function::hasAddressTaken() const {
386 for (Value::use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
387 if (I.getOperandNo() != 0 ||
388 (!isa<CallInst>(*I) && !isa<InvokeInst>(*I)))