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 IR library.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/Function.h"
15 #include "SymbolTableListTraitsImpl.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/CodeGen/ValueTypes.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/IntrinsicInst.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/Support/CallSite.h"
25 #include "llvm/Support/InstIterator.h"
26 #include "llvm/Support/LeakDetector.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/RWMutex.h"
29 #include "llvm/Support/StringPool.h"
30 #include "llvm/Support/Threading.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()->getAttributes().
83 hasAttribute(getArgNo()+1, Attribute::ByVal);
86 unsigned Argument::getParamAlignment() const {
87 assert(getType()->isPointerTy() && "Only pointers have alignments");
88 return getParent()->getParamAlignment(getArgNo()+1);
92 /// hasNestAttr - Return true if this argument has the nest attribute on
93 /// it in its containing function.
94 bool Argument::hasNestAttr() const {
95 if (!getType()->isPointerTy()) return false;
96 return getParent()->getAttributes().
97 hasAttribute(getArgNo()+1, Attribute::Nest);
100 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
101 /// it in its containing function.
102 bool Argument::hasNoAliasAttr() const {
103 if (!getType()->isPointerTy()) return false;
104 return getParent()->getAttributes().
105 hasAttribute(getArgNo()+1, Attribute::NoAlias);
108 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
109 /// on it in its containing function.
110 bool Argument::hasNoCaptureAttr() const {
111 if (!getType()->isPointerTy()) return false;
112 return getParent()->getAttributes().
113 hasAttribute(getArgNo()+1, Attribute::NoCapture);
116 /// hasSRetAttr - Return true if this argument has the sret attribute on
117 /// it in its containing function.
118 bool Argument::hasStructRetAttr() const {
119 if (!getType()->isPointerTy()) return false;
120 if (this != getParent()->arg_begin())
121 return false; // StructRet param must be first param
122 return getParent()->getAttributes().
123 hasAttribute(1, Attribute::StructRet);
126 /// addAttr - Add a Attribute to an argument
127 void Argument::addAttr(Attribute attr) {
128 getParent()->addAttribute(getArgNo() + 1, attr);
131 /// removeAttr - Remove a Attribute from an argument
132 void Argument::removeAttr(Attribute attr) {
133 getParent()->removeAttribute(getArgNo() + 1, attr);
137 //===----------------------------------------------------------------------===//
138 // Helper Methods in Function
139 //===----------------------------------------------------------------------===//
141 LLVMContext &Function::getContext() const {
142 return getType()->getContext();
145 FunctionType *Function::getFunctionType() const {
146 return cast<FunctionType>(getType()->getElementType());
149 bool Function::isVarArg() const {
150 return getFunctionType()->isVarArg();
153 Type *Function::getReturnType() const {
154 return getFunctionType()->getReturnType();
157 void Function::removeFromParent() {
158 getParent()->getFunctionList().remove(this);
161 void Function::eraseFromParent() {
162 getParent()->getFunctionList().erase(this);
165 //===----------------------------------------------------------------------===//
166 // Function Implementation
167 //===----------------------------------------------------------------------===//
169 Function::Function(FunctionType *Ty, LinkageTypes Linkage,
170 const Twine &name, Module *ParentModule)
171 : GlobalValue(PointerType::getUnqual(Ty),
172 Value::FunctionVal, 0, 0, Linkage, name) {
173 assert(FunctionType::isValidReturnType(getReturnType()) &&
174 "invalid return type");
175 SymTab = new ValueSymbolTable();
177 // If the function has arguments, mark them as lazily built.
178 if (Ty->getNumParams())
179 setValueSubclassData(1); // Set the "has lazy arguments" bit.
181 // Make sure that we get added to a function
182 LeakDetector::addGarbageObject(this);
185 ParentModule->getFunctionList().push_back(this);
187 // Ensure intrinsics have the right parameter attributes.
188 if (unsigned IID = getIntrinsicID())
189 setAttributes(Intrinsic::getAttributes(getContext(), Intrinsic::ID(IID)));
193 Function::~Function() {
194 dropAllReferences(); // After this it is safe to delete instructions.
196 // Delete all of the method arguments and unlink from symbol table...
197 ArgumentList.clear();
200 // Remove the function from the on-the-side GC table.
204 void Function::BuildLazyArguments() const {
205 // Create the arguments vector, all arguments start out unnamed.
206 FunctionType *FT = getFunctionType();
207 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
208 assert(!FT->getParamType(i)->isVoidTy() &&
209 "Cannot have void typed arguments!");
210 ArgumentList.push_back(new Argument(FT->getParamType(i)));
213 // Clear the lazy arguments bit.
214 unsigned SDC = getSubclassDataFromValue();
215 const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
218 size_t Function::arg_size() const {
219 return getFunctionType()->getNumParams();
221 bool Function::arg_empty() const {
222 return getFunctionType()->getNumParams() == 0;
225 void Function::setParent(Module *parent) {
227 LeakDetector::addGarbageObject(this);
230 LeakDetector::removeGarbageObject(this);
233 // dropAllReferences() - This function causes all the subinstructions to "let
234 // go" of all references that they are maintaining. This allows one to
235 // 'delete' a whole class at a time, even though there may be circular
236 // references... first all references are dropped, and all use counts go to
237 // zero. Then everything is deleted for real. Note that no operations are
238 // valid on an object that has "dropped all references", except operator
241 void Function::dropAllReferences() {
242 for (iterator I = begin(), E = end(); I != E; ++I)
243 I->dropAllReferences();
245 // Delete all basic blocks. They are now unused, except possibly by
246 // blockaddresses, but BasicBlock's destructor takes care of those.
247 while (!BasicBlocks.empty())
248 BasicBlocks.begin()->eraseFromParent();
251 void Function::addAttribute(unsigned i, Attribute attr) {
252 AttributeSet PAL = getAttributes();
254 PAL = PAL.addAttributes(getContext(), i,
255 AttributeSet::get(getContext(), i, B));
259 void Function::removeAttribute(unsigned i, Attribute attr) {
260 AttributeSet PAL = getAttributes();
261 PAL = PAL.removeAttr(getContext(), i, attr);
265 // Maintain the GC name for each function in an on-the-side table. This saves
266 // allocating an additional word in Function for programs which do not use GC
267 // (i.e., most programs) at the cost of increased overhead for clients which do
269 static DenseMap<const Function*,PooledStringPtr> *GCNames;
270 static StringPool *GCNamePool;
271 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
273 bool Function::hasGC() const {
274 sys::SmartScopedReader<true> Reader(*GCLock);
275 return GCNames && GCNames->count(this);
278 const char *Function::getGC() const {
279 assert(hasGC() && "Function has no collector");
280 sys::SmartScopedReader<true> Reader(*GCLock);
281 return *(*GCNames)[this];
284 void Function::setGC(const char *Str) {
285 sys::SmartScopedWriter<true> Writer(*GCLock);
287 GCNamePool = new StringPool();
289 GCNames = new DenseMap<const Function*,PooledStringPtr>();
290 (*GCNames)[this] = GCNamePool->intern(Str);
293 void Function::clearGC() {
294 sys::SmartScopedWriter<true> Writer(*GCLock);
296 GCNames->erase(this);
297 if (GCNames->empty()) {
300 if (GCNamePool->empty()) {
308 /// copyAttributesFrom - copy all additional attributes (those not needed to
309 /// create a Function) from the Function Src to this one.
310 void Function::copyAttributesFrom(const GlobalValue *Src) {
311 assert(isa<Function>(Src) && "Expected a Function!");
312 GlobalValue::copyAttributesFrom(Src);
313 const Function *SrcF = cast<Function>(Src);
314 setCallingConv(SrcF->getCallingConv());
315 setAttributes(SrcF->getAttributes());
317 setGC(SrcF->getGC());
322 /// getIntrinsicID - This method returns the ID number of the specified
323 /// function, or Intrinsic::not_intrinsic if the function is not an
324 /// intrinsic, or if the pointer is null. This value is always defined to be
325 /// zero to allow easy checking for whether a function is intrinsic or not. The
326 /// particular intrinsic functions which correspond to this value are defined in
327 /// llvm/Intrinsics.h.
329 unsigned Function::getIntrinsicID() const {
330 const ValueName *ValName = this->getValueName();
331 if (!ValName || !isIntrinsic())
333 unsigned Len = ValName->getKeyLength();
334 const char *Name = ValName->getKeyData();
336 #define GET_FUNCTION_RECOGNIZER
337 #include "llvm/IR/Intrinsics.gen"
338 #undef GET_FUNCTION_RECOGNIZER
342 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
343 assert(id < num_intrinsics && "Invalid intrinsic ID!");
344 static const char * const Table[] = {
346 #define GET_INTRINSIC_NAME_TABLE
347 #include "llvm/IR/Intrinsics.gen"
348 #undef GET_INTRINSIC_NAME_TABLE
352 std::string Result(Table[id]);
353 for (unsigned i = 0; i < Tys.size(); ++i) {
354 if (PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
355 Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
356 EVT::getEVT(PTyp->getElementType()).getEVTString();
359 Result += "." + EVT::getEVT(Tys[i]).getEVTString();
365 /// IIT_Info - These are enumerators that describe the entries returned by the
366 /// getIntrinsicInfoTableEntries function.
368 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
370 // Common values should be encoded with 0-15.
388 // Values from 16+ are only encodable with the inefficient encoding.
391 IIT_EMPTYSTRUCT = 18,
396 IIT_EXTEND_VEC_ARG = 23,
397 IIT_TRUNC_VEC_ARG = 24,
402 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
403 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
404 IIT_Info Info = IIT_Info(Infos[NextElt++]);
405 unsigned StructElts = 2;
406 using namespace Intrinsic;
410 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
413 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
416 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
419 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
422 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
425 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
428 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
431 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
434 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
437 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
440 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
443 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
444 DecodeIITType(NextElt, Infos, OutputTable);
447 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
448 DecodeIITType(NextElt, Infos, OutputTable);
451 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
452 DecodeIITType(NextElt, Infos, OutputTable);
455 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
456 DecodeIITType(NextElt, Infos, OutputTable);
459 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
460 DecodeIITType(NextElt, Infos, OutputTable);
463 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
464 DecodeIITType(NextElt, Infos, OutputTable);
466 case IIT_ANYPTR: { // [ANYPTR addrspace, subtype]
467 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
469 DecodeIITType(NextElt, Infos, OutputTable);
473 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
474 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
477 case IIT_EXTEND_VEC_ARG: {
478 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
479 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendVecArgument,
483 case IIT_TRUNC_VEC_ARG: {
484 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
485 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncVecArgument,
489 case IIT_EMPTYSTRUCT:
490 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
492 case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
493 case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
494 case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
496 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
498 for (unsigned i = 0; i != StructElts; ++i)
499 DecodeIITType(NextElt, Infos, OutputTable);
503 llvm_unreachable("unhandled");
507 #define GET_INTRINSIC_GENERATOR_GLOBAL
508 #include "llvm/IR/Intrinsics.gen"
509 #undef GET_INTRINSIC_GENERATOR_GLOBAL
511 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
512 SmallVectorImpl<IITDescriptor> &T){
513 // Check to see if the intrinsic's type was expressible by the table.
514 unsigned TableVal = IIT_Table[id-1];
516 // Decode the TableVal into an array of IITValues.
517 SmallVector<unsigned char, 8> IITValues;
518 ArrayRef<unsigned char> IITEntries;
519 unsigned NextElt = 0;
520 if ((TableVal >> 31) != 0) {
521 // This is an offset into the IIT_LongEncodingTable.
522 IITEntries = IIT_LongEncodingTable;
524 // Strip sentinel bit.
525 NextElt = (TableVal << 1) >> 1;
527 // Decode the TableVal into an array of IITValues. If the entry was encoded
528 // into a single word in the table itself, decode it now.
530 IITValues.push_back(TableVal & 0xF);
534 IITEntries = IITValues;
538 // Okay, decode the table into the output vector of IITDescriptors.
539 DecodeIITType(NextElt, IITEntries, T);
540 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
541 DecodeIITType(NextElt, IITEntries, T);
545 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
546 ArrayRef<Type*> Tys, LLVMContext &Context) {
547 using namespace Intrinsic;
548 IITDescriptor D = Infos.front();
549 Infos = Infos.slice(1);
552 case IITDescriptor::Void: return Type::getVoidTy(Context);
553 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
554 case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
555 case IITDescriptor::Half: return Type::getHalfTy(Context);
556 case IITDescriptor::Float: return Type::getFloatTy(Context);
557 case IITDescriptor::Double: return Type::getDoubleTy(Context);
559 case IITDescriptor::Integer:
560 return IntegerType::get(Context, D.Integer_Width);
561 case IITDescriptor::Vector:
562 return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
563 case IITDescriptor::Pointer:
564 return PointerType::get(DecodeFixedType(Infos, Tys, Context),
565 D.Pointer_AddressSpace);
566 case IITDescriptor::Struct: {
568 assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
569 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
570 Elts[i] = DecodeFixedType(Infos, Tys, Context);
571 return StructType::get(Context, ArrayRef<Type*>(Elts,D.Struct_NumElements));
574 case IITDescriptor::Argument:
575 return Tys[D.getArgumentNumber()];
576 case IITDescriptor::ExtendVecArgument:
577 return VectorType::getExtendedElementVectorType(cast<VectorType>(
578 Tys[D.getArgumentNumber()]));
580 case IITDescriptor::TruncVecArgument:
581 return VectorType::getTruncatedElementVectorType(cast<VectorType>(
582 Tys[D.getArgumentNumber()]));
584 llvm_unreachable("unhandled");
589 FunctionType *Intrinsic::getType(LLVMContext &Context,
590 ID id, ArrayRef<Type*> Tys) {
591 SmallVector<IITDescriptor, 8> Table;
592 getIntrinsicInfoTableEntries(id, Table);
594 ArrayRef<IITDescriptor> TableRef = Table;
595 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
597 SmallVector<Type*, 8> ArgTys;
598 while (!TableRef.empty())
599 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
601 return FunctionType::get(ResultTy, ArgTys, false);
604 bool Intrinsic::isOverloaded(ID id) {
605 #define GET_INTRINSIC_OVERLOAD_TABLE
606 #include "llvm/IR/Intrinsics.gen"
607 #undef GET_INTRINSIC_OVERLOAD_TABLE
610 /// This defines the "Intrinsic::getAttributes(ID id)" method.
611 #define GET_INTRINSIC_ATTRIBUTES
612 #include "llvm/IR/Intrinsics.gen"
613 #undef GET_INTRINSIC_ATTRIBUTES
615 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
616 // There can never be multiple globals with the same name of different types,
617 // because intrinsics must be a specific type.
619 cast<Function>(M->getOrInsertFunction(getName(id, Tys),
620 getType(M->getContext(), id, Tys)));
623 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
624 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
625 #include "llvm/IR/Intrinsics.gen"
626 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
628 /// hasAddressTaken - returns true if there are any uses of this function
629 /// other than direct calls or invokes to it.
630 bool Function::hasAddressTaken(const User* *PutOffender) const {
631 for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
633 if (isa<BlockAddress>(U))
635 if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
636 return PutOffender ? (*PutOffender = U, true) : true;
637 ImmutableCallSite CS(cast<Instruction>(U));
639 return PutOffender ? (*PutOffender = U, true) : true;
644 bool Function::isDefTriviallyDead() const {
646 if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
647 !hasAvailableExternallyLinkage())
650 // Check if the function is used by anything other than a blockaddress.
651 for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I)
652 if (!isa<BlockAddress>(*I))
658 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
659 /// setjmp or other function that gcc recognizes as "returning twice".
660 bool Function::callsFunctionThatReturnsTwice() const {
661 for (const_inst_iterator
662 I = inst_begin(this), E = inst_end(this); I != E; ++I) {
663 const CallInst* callInst = dyn_cast<CallInst>(&*I);
666 if (callInst->canReturnTwice())