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) {
129 getParent()->addAttributes(getArgNo() + 1,
130 AttributeSet::get(getParent()->getContext(),
134 /// removeAttr - Remove a Attribute from an argument
135 void Argument::removeAttr(Attribute attr) {
137 getParent()->removeAttributes(getArgNo() + 1,
138 AttributeSet::get(getParent()->getContext(),
143 //===----------------------------------------------------------------------===//
144 // Helper Methods in Function
145 //===----------------------------------------------------------------------===//
147 LLVMContext &Function::getContext() const {
148 return getType()->getContext();
151 FunctionType *Function::getFunctionType() const {
152 return cast<FunctionType>(getType()->getElementType());
155 bool Function::isVarArg() const {
156 return getFunctionType()->isVarArg();
159 Type *Function::getReturnType() const {
160 return getFunctionType()->getReturnType();
163 void Function::removeFromParent() {
164 getParent()->getFunctionList().remove(this);
167 void Function::eraseFromParent() {
168 getParent()->getFunctionList().erase(this);
171 //===----------------------------------------------------------------------===//
172 // Function Implementation
173 //===----------------------------------------------------------------------===//
175 Function::Function(FunctionType *Ty, LinkageTypes Linkage,
176 const Twine &name, Module *ParentModule)
177 : GlobalValue(PointerType::getUnqual(Ty),
178 Value::FunctionVal, 0, 0, Linkage, name) {
179 assert(FunctionType::isValidReturnType(getReturnType()) &&
180 "invalid return type");
181 SymTab = new ValueSymbolTable();
183 // If the function has arguments, mark them as lazily built.
184 if (Ty->getNumParams())
185 setValueSubclassData(1); // Set the "has lazy arguments" bit.
187 // Make sure that we get added to a function
188 LeakDetector::addGarbageObject(this);
191 ParentModule->getFunctionList().push_back(this);
193 // Ensure intrinsics have the right parameter attributes.
194 if (unsigned IID = getIntrinsicID())
195 setAttributes(Intrinsic::getAttributes(getContext(), Intrinsic::ID(IID)));
199 Function::~Function() {
200 dropAllReferences(); // After this it is safe to delete instructions.
202 // Delete all of the method arguments and unlink from symbol table...
203 ArgumentList.clear();
206 // Remove the function from the on-the-side GC table.
210 void Function::BuildLazyArguments() const {
211 // Create the arguments vector, all arguments start out unnamed.
212 FunctionType *FT = getFunctionType();
213 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
214 assert(!FT->getParamType(i)->isVoidTy() &&
215 "Cannot have void typed arguments!");
216 ArgumentList.push_back(new Argument(FT->getParamType(i)));
219 // Clear the lazy arguments bit.
220 unsigned SDC = getSubclassDataFromValue();
221 const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
224 size_t Function::arg_size() const {
225 return getFunctionType()->getNumParams();
227 bool Function::arg_empty() const {
228 return getFunctionType()->getNumParams() == 0;
231 void Function::setParent(Module *parent) {
233 LeakDetector::addGarbageObject(this);
236 LeakDetector::removeGarbageObject(this);
239 // dropAllReferences() - This function causes all the subinstructions to "let
240 // go" of all references that they are maintaining. This allows one to
241 // 'delete' a whole class at a time, even though there may be circular
242 // references... first all references are dropped, and all use counts go to
243 // zero. Then everything is deleted for real. Note that no operations are
244 // valid on an object that has "dropped all references", except operator
247 void Function::dropAllReferences() {
248 for (iterator I = begin(), E = end(); I != E; ++I)
249 I->dropAllReferences();
251 // Delete all basic blocks. They are now unused, except possibly by
252 // blockaddresses, but BasicBlock's destructor takes care of those.
253 while (!BasicBlocks.empty())
254 BasicBlocks.begin()->eraseFromParent();
257 void Function::addAttribute(unsigned i, Attribute::AttrKind attr) {
258 AttributeSet PAL = getAttributes();
259 PAL = PAL.addAttribute(getContext(), i, attr);
263 void Function::addAttributes(unsigned i, AttributeSet attrs) {
264 AttributeSet PAL = getAttributes();
265 PAL = PAL.addAttributes(getContext(), i, attrs);
269 void Function::removeAttributes(unsigned i, AttributeSet attrs) {
270 AttributeSet PAL = getAttributes();
271 PAL = PAL.removeAttributes(getContext(), i, attrs);
275 // Maintain the GC name for each function in an on-the-side table. This saves
276 // allocating an additional word in Function for programs which do not use GC
277 // (i.e., most programs) at the cost of increased overhead for clients which do
279 static DenseMap<const Function*,PooledStringPtr> *GCNames;
280 static StringPool *GCNamePool;
281 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
283 bool Function::hasGC() const {
284 sys::SmartScopedReader<true> Reader(*GCLock);
285 return GCNames && GCNames->count(this);
288 const char *Function::getGC() const {
289 assert(hasGC() && "Function has no collector");
290 sys::SmartScopedReader<true> Reader(*GCLock);
291 return *(*GCNames)[this];
294 void Function::setGC(const char *Str) {
295 sys::SmartScopedWriter<true> Writer(*GCLock);
297 GCNamePool = new StringPool();
299 GCNames = new DenseMap<const Function*,PooledStringPtr>();
300 (*GCNames)[this] = GCNamePool->intern(Str);
303 void Function::clearGC() {
304 sys::SmartScopedWriter<true> Writer(*GCLock);
306 GCNames->erase(this);
307 if (GCNames->empty()) {
310 if (GCNamePool->empty()) {
318 /// copyAttributesFrom - copy all additional attributes (those not needed to
319 /// create a Function) from the Function Src to this one.
320 void Function::copyAttributesFrom(const GlobalValue *Src) {
321 assert(isa<Function>(Src) && "Expected a Function!");
322 GlobalValue::copyAttributesFrom(Src);
323 const Function *SrcF = cast<Function>(Src);
324 setCallingConv(SrcF->getCallingConv());
325 setAttributes(SrcF->getAttributes());
327 setGC(SrcF->getGC());
332 /// getIntrinsicID - This method returns the ID number of the specified
333 /// function, or Intrinsic::not_intrinsic if the function is not an
334 /// intrinsic, or if the pointer is null. This value is always defined to be
335 /// zero to allow easy checking for whether a function is intrinsic or not. The
336 /// particular intrinsic functions which correspond to this value are defined in
337 /// llvm/Intrinsics.h.
339 unsigned Function::getIntrinsicID() const {
340 const ValueName *ValName = this->getValueName();
341 if (!ValName || !isIntrinsic())
343 unsigned Len = ValName->getKeyLength();
344 const char *Name = ValName->getKeyData();
346 #define GET_FUNCTION_RECOGNIZER
347 #include "llvm/IR/Intrinsics.gen"
348 #undef GET_FUNCTION_RECOGNIZER
352 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
353 assert(id < num_intrinsics && "Invalid intrinsic ID!");
354 static const char * const Table[] = {
356 #define GET_INTRINSIC_NAME_TABLE
357 #include "llvm/IR/Intrinsics.gen"
358 #undef GET_INTRINSIC_NAME_TABLE
362 std::string Result(Table[id]);
363 for (unsigned i = 0; i < Tys.size(); ++i) {
364 if (PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
365 Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
366 EVT::getEVT(PTyp->getElementType()).getEVTString();
369 Result += "." + EVT::getEVT(Tys[i]).getEVTString();
375 /// IIT_Info - These are enumerators that describe the entries returned by the
376 /// getIntrinsicInfoTableEntries function.
378 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
380 // Common values should be encoded with 0-15.
398 // Values from 16+ are only encodable with the inefficient encoding.
401 IIT_EMPTYSTRUCT = 18,
406 IIT_EXTEND_VEC_ARG = 23,
407 IIT_TRUNC_VEC_ARG = 24,
412 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
413 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
414 IIT_Info Info = IIT_Info(Infos[NextElt++]);
415 unsigned StructElts = 2;
416 using namespace Intrinsic;
420 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
423 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
426 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
429 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
432 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
435 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
438 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
441 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
444 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
447 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
450 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
453 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
454 DecodeIITType(NextElt, Infos, OutputTable);
457 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
458 DecodeIITType(NextElt, Infos, OutputTable);
461 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
462 DecodeIITType(NextElt, Infos, OutputTable);
465 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
466 DecodeIITType(NextElt, Infos, OutputTable);
469 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
470 DecodeIITType(NextElt, Infos, OutputTable);
473 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
474 DecodeIITType(NextElt, Infos, OutputTable);
476 case IIT_ANYPTR: { // [ANYPTR addrspace, subtype]
477 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
479 DecodeIITType(NextElt, Infos, OutputTable);
483 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
484 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
487 case IIT_EXTEND_VEC_ARG: {
488 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
489 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendVecArgument,
493 case IIT_TRUNC_VEC_ARG: {
494 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
495 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncVecArgument,
499 case IIT_EMPTYSTRUCT:
500 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
502 case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
503 case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
504 case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
506 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
508 for (unsigned i = 0; i != StructElts; ++i)
509 DecodeIITType(NextElt, Infos, OutputTable);
513 llvm_unreachable("unhandled");
517 #define GET_INTRINSIC_GENERATOR_GLOBAL
518 #include "llvm/IR/Intrinsics.gen"
519 #undef GET_INTRINSIC_GENERATOR_GLOBAL
521 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
522 SmallVectorImpl<IITDescriptor> &T){
523 // Check to see if the intrinsic's type was expressible by the table.
524 unsigned TableVal = IIT_Table[id-1];
526 // Decode the TableVal into an array of IITValues.
527 SmallVector<unsigned char, 8> IITValues;
528 ArrayRef<unsigned char> IITEntries;
529 unsigned NextElt = 0;
530 if ((TableVal >> 31) != 0) {
531 // This is an offset into the IIT_LongEncodingTable.
532 IITEntries = IIT_LongEncodingTable;
534 // Strip sentinel bit.
535 NextElt = (TableVal << 1) >> 1;
537 // Decode the TableVal into an array of IITValues. If the entry was encoded
538 // into a single word in the table itself, decode it now.
540 IITValues.push_back(TableVal & 0xF);
544 IITEntries = IITValues;
548 // Okay, decode the table into the output vector of IITDescriptors.
549 DecodeIITType(NextElt, IITEntries, T);
550 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
551 DecodeIITType(NextElt, IITEntries, T);
555 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
556 ArrayRef<Type*> Tys, LLVMContext &Context) {
557 using namespace Intrinsic;
558 IITDescriptor D = Infos.front();
559 Infos = Infos.slice(1);
562 case IITDescriptor::Void: return Type::getVoidTy(Context);
563 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
564 case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
565 case IITDescriptor::Half: return Type::getHalfTy(Context);
566 case IITDescriptor::Float: return Type::getFloatTy(Context);
567 case IITDescriptor::Double: return Type::getDoubleTy(Context);
569 case IITDescriptor::Integer:
570 return IntegerType::get(Context, D.Integer_Width);
571 case IITDescriptor::Vector:
572 return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
573 case IITDescriptor::Pointer:
574 return PointerType::get(DecodeFixedType(Infos, Tys, Context),
575 D.Pointer_AddressSpace);
576 case IITDescriptor::Struct: {
578 assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
579 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
580 Elts[i] = DecodeFixedType(Infos, Tys, Context);
581 return StructType::get(Context, ArrayRef<Type*>(Elts,D.Struct_NumElements));
584 case IITDescriptor::Argument:
585 return Tys[D.getArgumentNumber()];
586 case IITDescriptor::ExtendVecArgument:
587 return VectorType::getExtendedElementVectorType(cast<VectorType>(
588 Tys[D.getArgumentNumber()]));
590 case IITDescriptor::TruncVecArgument:
591 return VectorType::getTruncatedElementVectorType(cast<VectorType>(
592 Tys[D.getArgumentNumber()]));
594 llvm_unreachable("unhandled");
599 FunctionType *Intrinsic::getType(LLVMContext &Context,
600 ID id, ArrayRef<Type*> Tys) {
601 SmallVector<IITDescriptor, 8> Table;
602 getIntrinsicInfoTableEntries(id, Table);
604 ArrayRef<IITDescriptor> TableRef = Table;
605 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
607 SmallVector<Type*, 8> ArgTys;
608 while (!TableRef.empty())
609 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
611 return FunctionType::get(ResultTy, ArgTys, false);
614 bool Intrinsic::isOverloaded(ID id) {
615 #define GET_INTRINSIC_OVERLOAD_TABLE
616 #include "llvm/IR/Intrinsics.gen"
617 #undef GET_INTRINSIC_OVERLOAD_TABLE
620 /// This defines the "Intrinsic::getAttributes(ID id)" method.
621 #define GET_INTRINSIC_ATTRIBUTES
622 #include "llvm/IR/Intrinsics.gen"
623 #undef GET_INTRINSIC_ATTRIBUTES
625 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
626 // There can never be multiple globals with the same name of different types,
627 // because intrinsics must be a specific type.
629 cast<Function>(M->getOrInsertFunction(getName(id, Tys),
630 getType(M->getContext(), id, Tys)));
633 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
634 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
635 #include "llvm/IR/Intrinsics.gen"
636 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
638 /// hasAddressTaken - returns true if there are any uses of this function
639 /// other than direct calls or invokes to it.
640 bool Function::hasAddressTaken(const User* *PutOffender) const {
641 for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
643 if (isa<BlockAddress>(U))
645 if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
646 return PutOffender ? (*PutOffender = U, true) : true;
647 ImmutableCallSite CS(cast<Instruction>(U));
649 return PutOffender ? (*PutOffender = U, true) : true;
654 bool Function::isDefTriviallyDead() const {
656 if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
657 !hasAvailableExternallyLinkage())
660 // Check if the function is used by anything other than a blockaddress.
661 for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I)
662 if (!isa<BlockAddress>(*I))
668 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
669 /// setjmp or other function that gcc recognizes as "returning twice".
670 bool Function::callsFunctionThatReturnsTwice() const {
671 for (const_inst_iterator
672 I = inst_begin(this), E = inst_end(this); I != E; ++I) {
673 const CallInst* callInst = dyn_cast<CallInst>(&*I);
676 if (callInst->canReturnTwice())