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/LeakDetector.h"
20 #include "llvm/Support/ManagedStatic.h"
21 #include "llvm/Support/StringPool.h"
22 #include "llvm/System/RWMutex.h"
23 #include "llvm/System/Threading.h"
24 #include "SymbolTableListTraitsImpl.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/StringExtras.h"
30 // Explicit instantiations of SymbolTableListTraits since some of the methods
31 // are not in the public header file...
32 template class SymbolTableListTraits<Argument, Function>;
33 template class SymbolTableListTraits<BasicBlock, Function>;
35 //===----------------------------------------------------------------------===//
36 // Argument Implementation
37 //===----------------------------------------------------------------------===//
39 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
40 : Value(Ty, Value::ArgumentVal) {
43 // Make sure that we get added to a function
44 LeakDetector::addGarbageObject(this);
47 Par->getArgumentList().push_back(this);
51 void Argument::setParent(Function *parent) {
53 LeakDetector::addGarbageObject(this);
56 LeakDetector::removeGarbageObject(this);
59 /// getArgNo - Return the index of this formal argument in its containing
60 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
61 unsigned Argument::getArgNo() const {
62 const Function *F = getParent();
63 assert(F && "Argument is not in a function");
65 Function::const_arg_iterator AI = F->arg_begin();
67 for (; &*AI != this; ++AI)
73 /// hasByValAttr - Return true if this argument has the byval attribute on it
74 /// in its containing function.
75 bool Argument::hasByValAttr() const {
76 if (!isa<PointerType>(getType())) return false;
77 return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
80 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
81 /// it in its containing function.
82 bool Argument::hasNoAliasAttr() const {
83 if (!isa<PointerType>(getType())) return false;
84 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
87 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
88 /// on it in its containing function.
89 bool Argument::hasNoCaptureAttr() const {
90 if (!isa<PointerType>(getType())) return false;
91 return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture);
94 /// hasSRetAttr - Return true if this argument has the sret attribute on
95 /// it in its containing function.
96 bool Argument::hasStructRetAttr() const {
97 if (!isa<PointerType>(getType())) return false;
98 if (this != getParent()->arg_begin())
99 return false; // StructRet param must be first param
100 return getParent()->paramHasAttr(1, Attribute::StructRet);
103 /// addAttr - Add a Attribute to an argument
104 void Argument::addAttr(Attributes attr) {
105 getParent()->addAttribute(getArgNo() + 1, attr);
108 /// removeAttr - Remove a Attribute from an argument
109 void Argument::removeAttr(Attributes attr) {
110 getParent()->removeAttribute(getArgNo() + 1, attr);
114 //===----------------------------------------------------------------------===//
115 // Helper Methods in Function
116 //===----------------------------------------------------------------------===//
118 LLVMContext *Function::getContext() const {
119 const Module* M = getParent();
120 if (M) return &M->getContext();
124 const FunctionType *Function::getFunctionType() const {
125 return cast<FunctionType>(getType()->getElementType());
128 bool Function::isVarArg() const {
129 return getFunctionType()->isVarArg();
132 const Type *Function::getReturnType() const {
133 return getFunctionType()->getReturnType();
136 void Function::removeFromParent() {
137 getParent()->getFunctionList().remove(this);
140 void Function::eraseFromParent() {
141 getParent()->getFunctionList().erase(this);
144 //===----------------------------------------------------------------------===//
145 // Function Implementation
146 //===----------------------------------------------------------------------===//
148 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
149 const std::string &name, Module *ParentModule)
150 : GlobalValue(PointerType::getUnqual(Ty),
151 Value::FunctionVal, 0, 0, Linkage, name) {
152 assert(FunctionType::isValidReturnType(getReturnType()) &&
153 !isa<OpaqueType>(getReturnType()) && "invalid return type");
154 SymTab = new ValueSymbolTable();
156 // If the function has arguments, mark them as lazily built.
157 if (Ty->getNumParams())
158 SubclassData = 1; // Set the "has lazy arguments" bit.
160 // Make sure that we get added to a function
161 LeakDetector::addGarbageObject(this);
164 ParentModule->getFunctionList().push_back(this);
166 // Ensure intrinsics have the right parameter attributes.
167 if (unsigned IID = getIntrinsicID())
168 setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
172 Function::~Function() {
173 dropAllReferences(); // After this it is safe to delete instructions.
175 // Delete all of the method arguments and unlink from symbol table...
176 ArgumentList.clear();
179 // Remove the function from the on-the-side GC table.
183 void Function::BuildLazyArguments() const {
184 // Create the arguments vector, all arguments start out unnamed.
185 const FunctionType *FT = getFunctionType();
186 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
187 assert(FT->getParamType(i) != Type::VoidTy &&
188 "Cannot have void typed arguments!");
189 ArgumentList.push_back(new Argument(FT->getParamType(i)));
192 // Clear the lazy arguments bit.
193 const_cast<Function*>(this)->SubclassData &= ~1;
196 size_t Function::arg_size() const {
197 return getFunctionType()->getNumParams();
199 bool Function::arg_empty() const {
200 return getFunctionType()->getNumParams() == 0;
203 void Function::setParent(Module *parent) {
205 LeakDetector::addGarbageObject(this);
208 LeakDetector::removeGarbageObject(this);
211 // dropAllReferences() - This function causes all the subinstructions to "let
212 // go" of all references that they are maintaining. This allows one to
213 // 'delete' a whole class at a time, even though there may be circular
214 // references... first all references are dropped, and all use counts go to
215 // zero. Then everything is deleted for real. Note that no operations are
216 // valid on an object that has "dropped all references", except operator
219 void Function::dropAllReferences() {
220 for (iterator I = begin(), E = end(); I != E; ++I)
221 I->dropAllReferences();
222 BasicBlocks.clear(); // Delete all basic blocks...
225 void Function::addAttribute(unsigned i, Attributes attr) {
226 AttrListPtr PAL = getAttributes();
227 PAL = PAL.addAttr(i, attr);
231 void Function::removeAttribute(unsigned i, Attributes attr) {
232 AttrListPtr PAL = getAttributes();
233 PAL = PAL.removeAttr(i, attr);
237 // Maintain the GC name for each function in an on-the-side table. This saves
238 // allocating an additional word in Function for programs which do not use GC
239 // (i.e., most programs) at the cost of increased overhead for clients which do
241 static DenseMap<const Function*,PooledStringPtr> *GCNames;
242 static StringPool *GCNamePool;
243 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
245 bool Function::hasGC() const {
246 sys::SmartScopedReader<true> Reader(*GCLock);
247 return GCNames && GCNames->count(this);
250 const char *Function::getGC() const {
251 assert(hasGC() && "Function has no collector");
252 sys::SmartScopedReader<true> Reader(*GCLock);
253 return *(*GCNames)[this];
256 void Function::setGC(const char *Str) {
257 sys::SmartScopedWriter<true> Writer(*GCLock);
259 GCNamePool = new StringPool();
261 GCNames = new DenseMap<const Function*,PooledStringPtr>();
262 (*GCNames)[this] = GCNamePool->intern(Str);
265 void Function::clearGC() {
266 sys::SmartScopedWriter<true> Writer(*GCLock);
268 GCNames->erase(this);
269 if (GCNames->empty()) {
272 if (GCNamePool->empty()) {
280 /// copyAttributesFrom - copy all additional attributes (those not needed to
281 /// create a Function) from the Function Src to this one.
282 void Function::copyAttributesFrom(const GlobalValue *Src) {
283 assert(isa<Function>(Src) && "Expected a Function!");
284 GlobalValue::copyAttributesFrom(Src);
285 const Function *SrcF = cast<Function>(Src);
286 setCallingConv(SrcF->getCallingConv());
287 setAttributes(SrcF->getAttributes());
289 setGC(SrcF->getGC());
294 /// getIntrinsicID - This method returns the ID number of the specified
295 /// function, or Intrinsic::not_intrinsic if the function is not an
296 /// intrinsic, or if the pointer is null. This value is always defined to be
297 /// zero to allow easy checking for whether a function is intrinsic or not. The
298 /// particular intrinsic functions which correspond to this value are defined in
299 /// llvm/Intrinsics.h.
301 unsigned Function::getIntrinsicID() const {
302 const ValueName *ValName = this->getValueName();
305 unsigned Len = ValName->getKeyLength();
306 const char *Name = ValName->getKeyData();
308 if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
309 || Name[2] != 'v' || Name[3] != 'm')
310 return 0; // All intrinsics start with 'llvm.'
312 #define GET_FUNCTION_RECOGNIZER
313 #include "llvm/Intrinsics.gen"
314 #undef GET_FUNCTION_RECOGNIZER
318 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
319 assert(id < num_intrinsics && "Invalid intrinsic ID!");
320 const char * const Table[] = {
322 #define GET_INTRINSIC_NAME_TABLE
323 #include "llvm/Intrinsics.gen"
324 #undef GET_INTRINSIC_NAME_TABLE
328 std::string Result(Table[id]);
329 for (unsigned i = 0; i < numTys; ++i) {
330 if (const PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
331 Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
332 MVT::getMVT(PTyp->getElementType()).getMVTString();
335 Result += "." + MVT::getMVT(Tys[i]).getMVTString();
340 const FunctionType *Intrinsic::getType(LLVMContext &Context,
341 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 Context.getFunctionType(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(M->getContext(),
379 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
380 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
381 #include "llvm/Intrinsics.gen"
382 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
384 /// hasAddressTaken - returns true if there are any uses of this function
385 /// other than direct calls or invokes to it.
386 bool Function::hasAddressTaken() const {
387 for (Value::use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
388 if (I.getOperandNo() != 0 ||
389 (!isa<CallInst>(*I) && !isa<InvokeInst>(*I)))