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/System/RWMutex.h"
24
#include "llvm/System/Threading.h"
25
#include "SymbolTableListTraitsImpl.h"
26
#include "llvm/ADT/DenseMap.h"
27
#include "llvm/ADT/StringExtras.h"
31
// Explicit instantiations of SymbolTableListTraits since some of the methods
32
// are not in the public header file...
33
template class llvm::SymbolTableListTraits<Argument, Function>;
34
template class llvm::SymbolTableListTraits<BasicBlock, Function>;
36
//===----------------------------------------------------------------------===//
37
// Argument Implementation
38
//===----------------------------------------------------------------------===//
40
Argument::Argument(const Type *Ty, const Twine &Name, Function *Par)
41
: Value(Ty, Value::ArgumentVal) {
44
// Make sure that we get added to a function
45
LeakDetector::addGarbageObject(this);
48
Par->getArgumentList().push_back(this);
52
void Argument::setParent(Function *parent) {
54
LeakDetector::addGarbageObject(this);
57
LeakDetector::removeGarbageObject(this);
60
/// getArgNo - Return the index of this formal argument in its containing
61
/// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
62
unsigned Argument::getArgNo() const {
63
const Function *F = getParent();
64
assert(F && "Argument is not in a function");
66
Function::const_arg_iterator AI = F->arg_begin();
68
for (; &*AI != this; ++AI)
74
/// hasByValAttr - Return true if this argument has the byval attribute on it
75
/// in its containing function.
76
bool Argument::hasByValAttr() const {
77
if (!getType()->isPointerTy()) return false;
78
return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
81
/// hasNestAttr - Return true if this argument has the nest attribute on
82
/// it in its containing function.
83
bool Argument::hasNestAttr() const {
84
if (!getType()->isPointerTy()) return false;
85
return getParent()->paramHasAttr(getArgNo()+1, Attribute::Nest);
88
/// hasNoAliasAttr - Return true if this argument has the noalias attribute on
89
/// it in its containing function.
90
bool Argument::hasNoAliasAttr() const {
91
if (!getType()->isPointerTy()) return false;
92
return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
95
/// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
96
/// on it in its containing function.
97
bool Argument::hasNoCaptureAttr() const {
98
if (!getType()->isPointerTy()) return false;
99
return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture);
102
/// hasSRetAttr - Return true if this argument has the sret attribute on
103
/// it in its containing function.
104
bool Argument::hasStructRetAttr() const {
105
if (!getType()->isPointerTy()) return false;
106
if (this != getParent()->arg_begin())
107
return false; // StructRet param must be first param
108
return getParent()->paramHasAttr(1, Attribute::StructRet);
111
/// addAttr - Add a Attribute to an argument
112
void Argument::addAttr(Attributes attr) {
113
getParent()->addAttribute(getArgNo() + 1, attr);
116
/// removeAttr - Remove a Attribute from an argument
117
void Argument::removeAttr(Attributes attr) {
118
getParent()->removeAttribute(getArgNo() + 1, attr);
122
//===----------------------------------------------------------------------===//
123
// Helper Methods in Function
124
//===----------------------------------------------------------------------===//
126
LLVMContext &Function::getContext() const {
127
return getType()->getContext();
130
const FunctionType *Function::getFunctionType() const {
131
return cast<FunctionType>(getType()->getElementType());
134
bool Function::isVarArg() const {
135
return getFunctionType()->isVarArg();
138
const Type *Function::getReturnType() const {
139
return getFunctionType()->getReturnType();
142
void Function::removeFromParent() {
143
getParent()->getFunctionList().remove(this);
146
void Function::eraseFromParent() {
147
getParent()->getFunctionList().erase(this);
150
//===----------------------------------------------------------------------===//
151
// Function Implementation
152
//===----------------------------------------------------------------------===//
154
Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
155
const Twine &name, Module *ParentModule)
156
: GlobalValue(PointerType::getUnqual(Ty),
157
Value::FunctionVal, 0, 0, Linkage, name) {
158
assert(FunctionType::isValidReturnType(getReturnType()) &&
159
!getReturnType()->isOpaqueTy() && "invalid return type");
160
SymTab = new ValueSymbolTable();
162
// If the function has arguments, mark them as lazily built.
163
if (Ty->getNumParams())
164
setValueSubclassData(1); // Set the "has lazy arguments" bit.
166
// Make sure that we get added to a function
167
LeakDetector::addGarbageObject(this);
170
ParentModule->getFunctionList().push_back(this);
172
// Ensure intrinsics have the right parameter attributes.
173
if (unsigned IID = getIntrinsicID())
174
setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
178
Function::~Function() {
179
dropAllReferences(); // After this it is safe to delete instructions.
181
// Delete all of the method arguments and unlink from symbol table...
182
ArgumentList.clear();
185
// Remove the function from the on-the-side GC table.
189
void Function::BuildLazyArguments() const {
190
// Create the arguments vector, all arguments start out unnamed.
191
const FunctionType *FT = getFunctionType();
192
for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
193
assert(!FT->getParamType(i)->isVoidTy() &&
194
"Cannot have void typed arguments!");
195
ArgumentList.push_back(new Argument(FT->getParamType(i)));
198
// Clear the lazy arguments bit.
199
unsigned SDC = getSubclassDataFromValue();
200
const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
203
size_t Function::arg_size() const {
204
return getFunctionType()->getNumParams();
206
bool Function::arg_empty() const {
207
return getFunctionType()->getNumParams() == 0;
210
void Function::setParent(Module *parent) {
212
LeakDetector::addGarbageObject(this);
215
LeakDetector::removeGarbageObject(this);
218
// dropAllReferences() - This function causes all the subinstructions to "let
219
// go" of all references that they are maintaining. This allows one to
220
// 'delete' a whole class at a time, even though there may be circular
221
// references... first all references are dropped, and all use counts go to
222
// zero. Then everything is deleted for real. Note that no operations are
223
// valid on an object that has "dropped all references", except operator
226
void Function::dropAllReferences() {
227
for (iterator I = begin(), E = end(); I != E; ++I)
228
I->dropAllReferences();
230
// Delete all basic blocks.
231
while (!BasicBlocks.empty()) {
232
// If there is still a reference to the block, it must be a 'blockaddress'
233
// constant pointing to it. Just replace the BlockAddress with undef.
234
BasicBlock *BB = BasicBlocks.begin();
235
if (!BB->use_empty()) {
236
BlockAddress *BA = cast<BlockAddress>(BB->use_back());
237
BA->replaceAllUsesWith(UndefValue::get(BA->getType()));
238
BA->destroyConstant();
241
BB->eraseFromParent();
245
void Function::addAttribute(unsigned i, Attributes attr) {
246
AttrListPtr PAL = getAttributes();
247
PAL = PAL.addAttr(i, attr);
251
void Function::removeAttribute(unsigned i, Attributes attr) {
252
AttrListPtr PAL = getAttributes();
253
PAL = PAL.removeAttr(i, attr);
257
// Maintain the GC name for each function in an on-the-side table. This saves
258
// allocating an additional word in Function for programs which do not use GC
259
// (i.e., most programs) at the cost of increased overhead for clients which do
261
static DenseMap<const Function*,PooledStringPtr> *GCNames;
262
static StringPool *GCNamePool;
263
static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
265
bool Function::hasGC() const {
266
sys::SmartScopedReader<true> Reader(*GCLock);
267
return GCNames && GCNames->count(this);
270
const char *Function::getGC() const {
271
assert(hasGC() && "Function has no collector");
272
sys::SmartScopedReader<true> Reader(*GCLock);
273
return *(*GCNames)[this];
276
void Function::setGC(const char *Str) {
277
sys::SmartScopedWriter<true> Writer(*GCLock);
279
GCNamePool = new StringPool();
281
GCNames = new DenseMap<const Function*,PooledStringPtr>();
282
(*GCNames)[this] = GCNamePool->intern(Str);
285
void Function::clearGC() {
286
sys::SmartScopedWriter<true> Writer(*GCLock);
288
GCNames->erase(this);
289
if (GCNames->empty()) {
292
if (GCNamePool->empty()) {
300
/// copyAttributesFrom - copy all additional attributes (those not needed to
301
/// create a Function) from the Function Src to this one.
302
void Function::copyAttributesFrom(const GlobalValue *Src) {
303
assert(isa<Function>(Src) && "Expected a Function!");
304
GlobalValue::copyAttributesFrom(Src);
305
const Function *SrcF = cast<Function>(Src);
306
setCallingConv(SrcF->getCallingConv());
307
setAttributes(SrcF->getAttributes());
309
setGC(SrcF->getGC());
314
/// getIntrinsicID - This method returns the ID number of the specified
315
/// function, or Intrinsic::not_intrinsic if the function is not an
316
/// intrinsic, or if the pointer is null. This value is always defined to be
317
/// zero to allow easy checking for whether a function is intrinsic or not. The
318
/// particular intrinsic functions which correspond to this value are defined in
319
/// llvm/Intrinsics.h.
321
unsigned Function::getIntrinsicID() const {
322
const ValueName *ValName = this->getValueName();
325
unsigned Len = ValName->getKeyLength();
326
const char *Name = ValName->getKeyData();
328
if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
329
|| Name[2] != 'v' || Name[3] != 'm')
330
return 0; // All intrinsics start with 'llvm.'
332
#define GET_FUNCTION_RECOGNIZER
333
#include "llvm/Intrinsics.gen"
334
#undef GET_FUNCTION_RECOGNIZER
338
std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) {
339
assert(id < num_intrinsics && "Invalid intrinsic ID!");
340
const char * const Table[] = {
342
#define GET_INTRINSIC_NAME_TABLE
343
#include "llvm/Intrinsics.gen"
344
#undef GET_INTRINSIC_NAME_TABLE
348
std::string Result(Table[id]);
349
for (unsigned i = 0; i < numTys; ++i) {
350
if (const PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
351
Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
352
EVT::getEVT(PTyp->getElementType()).getEVTString();
355
Result += "." + EVT::getEVT(Tys[i]).getEVTString();
360
const FunctionType *Intrinsic::getType(LLVMContext &Context,
361
ID id, const Type **Tys,
363
const Type *ResultTy = NULL;
364
std::vector<const Type*> 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
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, const Type **Tys,
391
// There can never be multiple globals with the same name of different types,
392
// because intrinsics must be a specific type.
394
cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
395
getType(M->getContext(),
399
// This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
400
#define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
401
#include "llvm/Intrinsics.gen"
402
#undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
404
/// hasAddressTaken - returns true if there are any uses of this function
405
/// other than direct calls or invokes to it.
406
bool Function::hasAddressTaken(const User* *PutOffender) const {
407
for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
409
if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
410
return PutOffender ? (*PutOffender = U, true) : true;
411
ImmutableCallSite CS(cast<Instruction>(U));
413
return PutOffender ? (*PutOffender = U, true) : true;