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 attributes to an argument.
127 void Argument::addAttr(AttributeSet AS) {
128 assert(AS.getNumSlots() == 1 &&
129 "Trying to add more than one attribute set to an argument!");
130 AttrBuilder B(AS, AS.getSlotIndex(0));
131 getParent()->addAttributes(getArgNo() + 1,
132 AttributeSet::get(Parent->getContext(),
136 /// removeAttr - Remove attributes from an argument.
137 void Argument::removeAttr(AttributeSet AS) {
138 assert(AS.getNumSlots() == 1 &&
139 "Trying to remove more than one attribute set from an argument!");
140 AttrBuilder B(AS, AS.getSlotIndex(0));
141 getParent()->removeAttributes(getArgNo() + 1,
142 AttributeSet::get(Parent->getContext(),
146 //===----------------------------------------------------------------------===//
147 // Helper Methods in Function
148 //===----------------------------------------------------------------------===//
150 LLVMContext &Function::getContext() const {
151 return getType()->getContext();
154 FunctionType *Function::getFunctionType() const {
155 return cast<FunctionType>(getType()->getElementType());
158 bool Function::isVarArg() const {
159 return getFunctionType()->isVarArg();
162 Type *Function::getReturnType() const {
163 return getFunctionType()->getReturnType();
166 void Function::removeFromParent() {
167 getParent()->getFunctionList().remove(this);
170 void Function::eraseFromParent() {
171 getParent()->getFunctionList().erase(this);
174 //===----------------------------------------------------------------------===//
175 // Function Implementation
176 //===----------------------------------------------------------------------===//
178 Function::Function(FunctionType *Ty, LinkageTypes Linkage,
179 const Twine &name, Module *ParentModule)
180 : GlobalValue(PointerType::getUnqual(Ty),
181 Value::FunctionVal, 0, 0, Linkage, name) {
182 assert(FunctionType::isValidReturnType(getReturnType()) &&
183 "invalid return type");
184 SymTab = new ValueSymbolTable();
186 // If the function has arguments, mark them as lazily built.
187 if (Ty->getNumParams())
188 setValueSubclassData(1); // Set the "has lazy arguments" bit.
190 // Make sure that we get added to a function
191 LeakDetector::addGarbageObject(this);
194 ParentModule->getFunctionList().push_back(this);
196 // Ensure intrinsics have the right parameter attributes.
197 if (unsigned IID = getIntrinsicID())
198 setAttributes(Intrinsic::getAttributes(getContext(), Intrinsic::ID(IID)));
202 Function::~Function() {
203 dropAllReferences(); // After this it is safe to delete instructions.
205 // Delete all of the method arguments and unlink from symbol table...
206 ArgumentList.clear();
209 // Remove the function from the on-the-side GC table.
213 void Function::BuildLazyArguments() const {
214 // Create the arguments vector, all arguments start out unnamed.
215 FunctionType *FT = getFunctionType();
216 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
217 assert(!FT->getParamType(i)->isVoidTy() &&
218 "Cannot have void typed arguments!");
219 ArgumentList.push_back(new Argument(FT->getParamType(i)));
222 // Clear the lazy arguments bit.
223 unsigned SDC = getSubclassDataFromValue();
224 const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
227 size_t Function::arg_size() const {
228 return getFunctionType()->getNumParams();
230 bool Function::arg_empty() const {
231 return getFunctionType()->getNumParams() == 0;
234 void Function::setParent(Module *parent) {
236 LeakDetector::addGarbageObject(this);
239 LeakDetector::removeGarbageObject(this);
242 // dropAllReferences() - This function causes all the subinstructions to "let
243 // go" of all references that they are maintaining. This allows one to
244 // 'delete' a whole class at a time, even though there may be circular
245 // references... first all references are dropped, and all use counts go to
246 // zero. Then everything is deleted for real. Note that no operations are
247 // valid on an object that has "dropped all references", except operator
250 void Function::dropAllReferences() {
251 for (iterator I = begin(), E = end(); I != E; ++I)
252 I->dropAllReferences();
254 // Delete all basic blocks. They are now unused, except possibly by
255 // blockaddresses, but BasicBlock's destructor takes care of those.
256 while (!BasicBlocks.empty())
257 BasicBlocks.begin()->eraseFromParent();
260 void Function::addAttribute(unsigned i, Attribute::AttrKind attr) {
261 AttributeSet PAL = getAttributes();
262 PAL = PAL.addAttribute(getContext(), i, attr);
266 void Function::addAttributes(unsigned i, AttributeSet attrs) {
267 AttributeSet PAL = getAttributes();
268 PAL = PAL.addAttributes(getContext(), i, attrs);
272 void Function::removeAttributes(unsigned i, AttributeSet attrs) {
273 AttributeSet PAL = getAttributes();
274 PAL = PAL.removeAttributes(getContext(), i, attrs);
278 // Maintain the GC name for each function in an on-the-side table. This saves
279 // allocating an additional word in Function for programs which do not use GC
280 // (i.e., most programs) at the cost of increased overhead for clients which do
282 static DenseMap<const Function*,PooledStringPtr> *GCNames;
283 static StringPool *GCNamePool;
284 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
286 bool Function::hasGC() const {
287 sys::SmartScopedReader<true> Reader(*GCLock);
288 return GCNames && GCNames->count(this);
291 const char *Function::getGC() const {
292 assert(hasGC() && "Function has no collector");
293 sys::SmartScopedReader<true> Reader(*GCLock);
294 return *(*GCNames)[this];
297 void Function::setGC(const char *Str) {
298 sys::SmartScopedWriter<true> Writer(*GCLock);
300 GCNamePool = new StringPool();
302 GCNames = new DenseMap<const Function*,PooledStringPtr>();
303 (*GCNames)[this] = GCNamePool->intern(Str);
306 void Function::clearGC() {
307 sys::SmartScopedWriter<true> Writer(*GCLock);
309 GCNames->erase(this);
310 if (GCNames->empty()) {
313 if (GCNamePool->empty()) {
321 /// copyAttributesFrom - copy all additional attributes (those not needed to
322 /// create a Function) from the Function Src to this one.
323 void Function::copyAttributesFrom(const GlobalValue *Src) {
324 assert(isa<Function>(Src) && "Expected a Function!");
325 GlobalValue::copyAttributesFrom(Src);
326 const Function *SrcF = cast<Function>(Src);
327 setCallingConv(SrcF->getCallingConv());
328 setAttributes(SrcF->getAttributes());
330 setGC(SrcF->getGC());
335 /// getIntrinsicID - This method returns the ID number of the specified
336 /// function, or Intrinsic::not_intrinsic if the function is not an
337 /// intrinsic, or if the pointer is null. This value is always defined to be
338 /// zero to allow easy checking for whether a function is intrinsic or not. The
339 /// particular intrinsic functions which correspond to this value are defined in
340 /// llvm/Intrinsics.h.
342 unsigned Function::getIntrinsicID() const {
343 const ValueName *ValName = this->getValueName();
344 if (!ValName || !isIntrinsic())
346 unsigned Len = ValName->getKeyLength();
347 const char *Name = ValName->getKeyData();
349 #define GET_FUNCTION_RECOGNIZER
350 #include "llvm/IR/Intrinsics.gen"
351 #undef GET_FUNCTION_RECOGNIZER
355 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
356 assert(id < num_intrinsics && "Invalid intrinsic ID!");
357 static const char * const Table[] = {
359 #define GET_INTRINSIC_NAME_TABLE
360 #include "llvm/IR/Intrinsics.gen"
361 #undef GET_INTRINSIC_NAME_TABLE
365 std::string Result(Table[id]);
366 for (unsigned i = 0; i < Tys.size(); ++i) {
367 if (PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
368 Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
369 EVT::getEVT(PTyp->getElementType()).getEVTString();
372 Result += "." + EVT::getEVT(Tys[i]).getEVTString();
378 /// IIT_Info - These are enumerators that describe the entries returned by the
379 /// getIntrinsicInfoTableEntries function.
381 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
383 // Common values should be encoded with 0-15.
401 // Values from 16+ are only encodable with the inefficient encoding.
404 IIT_EMPTYSTRUCT = 18,
409 IIT_EXTEND_VEC_ARG = 23,
410 IIT_TRUNC_VEC_ARG = 24,
415 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
416 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
417 IIT_Info Info = IIT_Info(Infos[NextElt++]);
418 unsigned StructElts = 2;
419 using namespace Intrinsic;
423 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
426 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
429 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
432 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
435 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
438 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
441 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
444 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
447 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
450 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
453 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
456 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
457 DecodeIITType(NextElt, Infos, OutputTable);
460 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
461 DecodeIITType(NextElt, Infos, OutputTable);
464 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
465 DecodeIITType(NextElt, Infos, OutputTable);
468 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
469 DecodeIITType(NextElt, Infos, OutputTable);
472 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
473 DecodeIITType(NextElt, Infos, OutputTable);
476 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
477 DecodeIITType(NextElt, Infos, OutputTable);
479 case IIT_ANYPTR: { // [ANYPTR addrspace, subtype]
480 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
482 DecodeIITType(NextElt, Infos, OutputTable);
486 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
487 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
490 case IIT_EXTEND_VEC_ARG: {
491 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
492 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendVecArgument,
496 case IIT_TRUNC_VEC_ARG: {
497 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
498 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncVecArgument,
502 case IIT_EMPTYSTRUCT:
503 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
505 case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
506 case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
507 case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
509 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
511 for (unsigned i = 0; i != StructElts; ++i)
512 DecodeIITType(NextElt, Infos, OutputTable);
516 llvm_unreachable("unhandled");
520 #define GET_INTRINSIC_GENERATOR_GLOBAL
521 #include "llvm/IR/Intrinsics.gen"
522 #undef GET_INTRINSIC_GENERATOR_GLOBAL
524 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
525 SmallVectorImpl<IITDescriptor> &T){
526 // Check to see if the intrinsic's type was expressible by the table.
527 unsigned TableVal = IIT_Table[id-1];
529 // Decode the TableVal into an array of IITValues.
530 SmallVector<unsigned char, 8> IITValues;
531 ArrayRef<unsigned char> IITEntries;
532 unsigned NextElt = 0;
533 if ((TableVal >> 31) != 0) {
534 // This is an offset into the IIT_LongEncodingTable.
535 IITEntries = IIT_LongEncodingTable;
537 // Strip sentinel bit.
538 NextElt = (TableVal << 1) >> 1;
540 // Decode the TableVal into an array of IITValues. If the entry was encoded
541 // into a single word in the table itself, decode it now.
543 IITValues.push_back(TableVal & 0xF);
547 IITEntries = IITValues;
551 // Okay, decode the table into the output vector of IITDescriptors.
552 DecodeIITType(NextElt, IITEntries, T);
553 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
554 DecodeIITType(NextElt, IITEntries, T);
558 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
559 ArrayRef<Type*> Tys, LLVMContext &Context) {
560 using namespace Intrinsic;
561 IITDescriptor D = Infos.front();
562 Infos = Infos.slice(1);
565 case IITDescriptor::Void: return Type::getVoidTy(Context);
566 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
567 case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
568 case IITDescriptor::Half: return Type::getHalfTy(Context);
569 case IITDescriptor::Float: return Type::getFloatTy(Context);
570 case IITDescriptor::Double: return Type::getDoubleTy(Context);
572 case IITDescriptor::Integer:
573 return IntegerType::get(Context, D.Integer_Width);
574 case IITDescriptor::Vector:
575 return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
576 case IITDescriptor::Pointer:
577 return PointerType::get(DecodeFixedType(Infos, Tys, Context),
578 D.Pointer_AddressSpace);
579 case IITDescriptor::Struct: {
581 assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
582 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
583 Elts[i] = DecodeFixedType(Infos, Tys, Context);
584 return StructType::get(Context, ArrayRef<Type*>(Elts,D.Struct_NumElements));
587 case IITDescriptor::Argument:
588 return Tys[D.getArgumentNumber()];
589 case IITDescriptor::ExtendVecArgument:
590 return VectorType::getExtendedElementVectorType(cast<VectorType>(
591 Tys[D.getArgumentNumber()]));
593 case IITDescriptor::TruncVecArgument:
594 return VectorType::getTruncatedElementVectorType(cast<VectorType>(
595 Tys[D.getArgumentNumber()]));
597 llvm_unreachable("unhandled");
602 FunctionType *Intrinsic::getType(LLVMContext &Context,
603 ID id, ArrayRef<Type*> Tys) {
604 SmallVector<IITDescriptor, 8> Table;
605 getIntrinsicInfoTableEntries(id, Table);
607 ArrayRef<IITDescriptor> TableRef = Table;
608 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
610 SmallVector<Type*, 8> ArgTys;
611 while (!TableRef.empty())
612 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
614 return FunctionType::get(ResultTy, ArgTys, false);
617 bool Intrinsic::isOverloaded(ID id) {
618 #define GET_INTRINSIC_OVERLOAD_TABLE
619 #include "llvm/IR/Intrinsics.gen"
620 #undef GET_INTRINSIC_OVERLOAD_TABLE
623 /// This defines the "Intrinsic::getAttributes(ID id)" method.
624 #define GET_INTRINSIC_ATTRIBUTES
625 #include "llvm/IR/Intrinsics.gen"
626 #undef GET_INTRINSIC_ATTRIBUTES
628 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
629 // There can never be multiple globals with the same name of different types,
630 // because intrinsics must be a specific type.
632 cast<Function>(M->getOrInsertFunction(getName(id, Tys),
633 getType(M->getContext(), id, Tys)));
636 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
637 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
638 #include "llvm/IR/Intrinsics.gen"
639 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
641 /// hasAddressTaken - returns true if there are any uses of this function
642 /// other than direct calls or invokes to it.
643 bool Function::hasAddressTaken(const User* *PutOffender) const {
644 for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
646 if (isa<BlockAddress>(U))
648 if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
649 return PutOffender ? (*PutOffender = U, true) : true;
650 ImmutableCallSite CS(cast<Instruction>(U));
652 return PutOffender ? (*PutOffender = U, true) : true;
657 bool Function::isDefTriviallyDead() const {
659 if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
660 !hasAvailableExternallyLinkage())
663 // Check if the function is used by anything other than a blockaddress.
664 for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I)
665 if (!isa<BlockAddress>(*I))
671 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
672 /// setjmp or other function that gcc recognizes as "returning twice".
673 bool Function::callsFunctionThatReturnsTwice() const {
674 for (const_inst_iterator
675 I = inst_begin(this), E = inst_end(this); I != E; ++I) {
676 const CallInst* callInst = dyn_cast<CallInst>(&*I);
679 if (callInst->canReturnTwice())