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/System/RWMutex.h"
22 #include "SymbolTableListTraitsImpl.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/StringExtras.h"
28 // Explicit instantiations of SymbolTableListTraits since some of the methods
29 // are not in the public header file...
30 template class SymbolTableListTraits<Argument, Function>;
31 template class SymbolTableListTraits<BasicBlock, Function>;
33 //===----------------------------------------------------------------------===//
34 // Argument Implementation
35 //===----------------------------------------------------------------------===//
37 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
38 : Value(Ty, Value::ArgumentVal) {
41 // Make sure that we get added to a function
42 LeakDetector::addGarbageObject(this);
45 Par->getArgumentList().push_back(this);
49 void Argument::setParent(Function *parent) {
51 LeakDetector::addGarbageObject(this);
54 LeakDetector::removeGarbageObject(this);
57 /// getArgNo - Return the index of this formal argument in its containing
58 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
59 unsigned Argument::getArgNo() const {
60 const Function *F = getParent();
61 assert(F && "Argument is not in a function");
63 Function::const_arg_iterator AI = F->arg_begin();
65 for (; &*AI != this; ++AI)
71 /// hasByValAttr - Return true if this argument has the byval attribute on it
72 /// in its containing function.
73 bool Argument::hasByValAttr() const {
74 if (!isa<PointerType>(getType())) return false;
75 return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
78 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
79 /// it in its containing function.
80 bool Argument::hasNoAliasAttr() const {
81 if (!isa<PointerType>(getType())) return false;
82 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
85 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
86 /// on it in its containing function.
87 bool Argument::hasNoCaptureAttr() const {
88 if (!isa<PointerType>(getType())) return false;
89 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture);
92 /// hasSRetAttr - Return true if this argument has the sret attribute on
93 /// it in its containing function.
94 bool Argument::hasStructRetAttr() const {
95 if (!isa<PointerType>(getType())) return false;
96 if (this != getParent()->arg_begin())
97 return false; // StructRet param must be first param
98 return getParent()->paramHasAttr(1, Attribute::StructRet);
101 /// addAttr - Add a Attribute to an argument
102 void Argument::addAttr(Attributes attr) {
103 getParent()->addAttribute(getArgNo() + 1, attr);
106 /// removeAttr - Remove a Attribute from an argument
107 void Argument::removeAttr(Attributes attr) {
108 getParent()->removeAttribute(getArgNo() + 1, attr);
112 //===----------------------------------------------------------------------===//
113 // Helper Methods in Function
114 //===----------------------------------------------------------------------===//
116 const FunctionType *Function::getFunctionType() const {
117 return cast<FunctionType>(getType()->getElementType());
120 bool Function::isVarArg() const {
121 return getFunctionType()->isVarArg();
124 const Type *Function::getReturnType() const {
125 return getFunctionType()->getReturnType();
128 void Function::removeFromParent() {
129 getParent()->getFunctionList().remove(this);
132 void Function::eraseFromParent() {
133 getParent()->getFunctionList().erase(this);
136 //===----------------------------------------------------------------------===//
137 // Function Implementation
138 //===----------------------------------------------------------------------===//
140 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
141 const std::string &name, Module *ParentModule)
142 : GlobalValue(PointerType::getUnqual(Ty),
143 Value::FunctionVal, 0, 0, Linkage, name) {
144 assert(FunctionType::isValidReturnType(getReturnType()) &&
145 !isa<OpaqueType>(getReturnType()) && "invalid return type");
146 SymTab = new ValueSymbolTable();
148 // If the function has arguments, mark them as lazily built.
149 if (Ty->getNumParams())
150 SubclassData = 1; // Set the "has lazy arguments" bit.
152 // Make sure that we get added to a function
153 LeakDetector::addGarbageObject(this);
156 ParentModule->getFunctionList().push_back(this);
158 // Ensure intrinsics have the right parameter attributes.
159 if (unsigned IID = getIntrinsicID())
160 setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
164 Function::~Function() {
165 dropAllReferences(); // After this it is safe to delete instructions.
167 // Delete all of the method arguments and unlink from symbol table...
168 ArgumentList.clear();
171 // Remove the function from the on-the-side GC table.
175 void Function::BuildLazyArguments() const {
176 // Create the arguments vector, all arguments start out unnamed.
177 const FunctionType *FT = getFunctionType();
178 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
179 assert(FT->getParamType(i) != Type::VoidTy &&
180 "Cannot have void typed arguments!");
181 ArgumentList.push_back(new Argument(FT->getParamType(i)));
184 // Clear the lazy arguments bit.
185 const_cast<Function*>(this)->SubclassData &= ~1;
188 size_t Function::arg_size() const {
189 return getFunctionType()->getNumParams();
191 bool Function::arg_empty() const {
192 return getFunctionType()->getNumParams() == 0;
195 void Function::setParent(Module *parent) {
197 LeakDetector::addGarbageObject(this);
200 LeakDetector::removeGarbageObject(this);
203 // dropAllReferences() - This function causes all the subinstructions to "let
204 // go" of all references that they are maintaining. This allows one to
205 // 'delete' a whole class at a time, even though there may be circular
206 // references... first all references are dropped, and all use counts go to
207 // zero. Then everything is deleted for real. Note that no operations are
208 // valid on an object that has "dropped all references", except operator
211 void Function::dropAllReferences() {
212 for (iterator I = begin(), E = end(); I != E; ++I)
213 I->dropAllReferences();
214 BasicBlocks.clear(); // Delete all basic blocks...
217 void Function::addAttribute(unsigned i, Attributes attr) {
218 AttrListPtr PAL = getAttributes();
219 PAL = PAL.addAttr(i, attr);
223 void Function::removeAttribute(unsigned i, Attributes attr) {
224 AttrListPtr PAL = getAttributes();
225 PAL = PAL.removeAttr(i, attr);
229 // Maintain the GC name for each function in an on-the-side table. This saves
230 // allocating an additional word in Function for programs which do not use GC
231 // (i.e., most programs) at the cost of increased overhead for clients which do
233 static ManagedStatic<DenseMap<const Function*,PooledStringPtr> > GCNames;
234 static ManagedStatic<StringPool> GCNamePool;
235 static ManagedStatic<sys::RWMutex> GCLock;
237 bool Function::hasGC() const {
238 if (llvm_is_multithreaded()) {
239 sys::ScopedReader Reader(&*GCLock);
240 return GCNames->count(this);
242 return GCNames->count(this);
245 const char *Function::getGC() const {
246 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()) {
257 sys::ScopedWriter Writer(&*GCLock);
258 (*GCNames)[this] = GCNamePool->intern(Str);
260 (*GCNames)[this] = GCNamePool->intern(Str);
263 void Function::clearGC() {
264 if (llvm_is_multithreaded()) {
265 sys::ScopedWriter Writer(&*GCLock);
266 GCNames->erase(this);
268 GCNames->erase(this);
271 /// copyAttributesFrom - copy all additional attributes (those not needed to
272 /// create a Function) from the Function Src to this one.
273 void Function::copyAttributesFrom(const GlobalValue *Src) {
274 assert(isa<Function>(Src) && "Expected a Function!");
275 GlobalValue::copyAttributesFrom(Src);
276 const Function *SrcF = cast<Function>(Src);
277 setCallingConv(SrcF->getCallingConv());
278 setAttributes(SrcF->getAttributes());
280 setGC(SrcF->getGC());
285 /// getIntrinsicID - This method returns the ID number of the specified
286 /// function, or Intrinsic::not_intrinsic if the function is not an
287 /// intrinsic, or if the pointer is null. This value is always defined to be
288 /// zero to allow easy checking for whether a function is intrinsic or not. The
289 /// particular intrinsic functions which correspond to this value are defined in
290 /// llvm/Intrinsics.h.
292 unsigned Function::getIntrinsicID() const {
293 const ValueName *ValName = this->getValueName();
296 unsigned Len = ValName->getKeyLength();
297 const char *Name = ValName->getKeyData();
299 if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
300 || Name[2] != 'v' || Name[3] != 'm')
301 return 0; // All intrinsics start with 'llvm.'
303 #define GET_FUNCTION_RECOGNIZER
304 #include "llvm/Intrinsics.gen"
305 #undef GET_FUNCTION_RECOGNIZER
309 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
310 assert(id < num_intrinsics && "Invalid intrinsic ID!");
311 const char * const Table[] = {
313 #define GET_INTRINSIC_NAME_TABLE
314 #include "llvm/Intrinsics.gen"
315 #undef GET_INTRINSIC_NAME_TABLE
319 std::string Result(Table[id]);
320 for (unsigned i = 0; i < numTys; ++i) {
321 if (const PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
322 Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
323 MVT::getMVT(PTyp->getElementType()).getMVTString();
326 Result += "." + MVT::getMVT(Tys[i]).getMVTString();
331 const FunctionType *Intrinsic::getType(ID id, const Type **Tys,
333 const Type *ResultTy = NULL;
334 std::vector<const Type*> ArgTys;
335 bool IsVarArg = false;
337 #define GET_INTRINSIC_GENERATOR
338 #include "llvm/Intrinsics.gen"
339 #undef GET_INTRINSIC_GENERATOR
341 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
344 bool Intrinsic::isOverloaded(ID id) {
345 const bool OTable[] = {
347 #define GET_INTRINSIC_OVERLOAD_TABLE
348 #include "llvm/Intrinsics.gen"
349 #undef GET_INTRINSIC_OVERLOAD_TABLE
354 /// This defines the "Intrinsic::getAttributes(ID id)" method.
355 #define GET_INTRINSIC_ATTRIBUTES
356 #include "llvm/Intrinsics.gen"
357 #undef GET_INTRINSIC_ATTRIBUTES
359 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys,
361 // There can never be multiple globals with the same name of different types,
362 // because intrinsics must be a specific type.
364 cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
365 getType(id, Tys, numTys)));
368 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
369 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
370 #include "llvm/Intrinsics.gen"
371 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
373 /// hasAddressTaken - returns true if there are any uses of this function
374 /// other than direct calls or invokes to it.
375 bool Function::hasAddressTaken() const {
376 for (Value::use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
377 if (I.getOperandNo() != 0 ||
378 (!isa<CallInst>(*I) && !isa<InvokeInst>(*I)))