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/InstIterator.h"
21 #include "llvm/Support/LeakDetector.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/StringPool.h"
24 #include "llvm/Support/RWMutex.h"
25 #include "llvm/Support/Threading.h"
26 #include "SymbolTableListTraitsImpl.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/StringExtras.h"
32 // Explicit instantiations of SymbolTableListTraits since some of the methods
33 // are not in the public header file...
34 template class llvm::SymbolTableListTraits<Argument, Function>;
35 template class llvm::SymbolTableListTraits<BasicBlock, Function>;
37 //===----------------------------------------------------------------------===//
38 // Argument Implementation
39 //===----------------------------------------------------------------------===//
41 void Argument::anchor() { }
43 Argument::Argument(Type *Ty, const Twine &Name, Function *Par)
44 : Value(Ty, Value::ArgumentVal) {
47 // Make sure that we get added to a function
48 LeakDetector::addGarbageObject(this);
51 Par->getArgumentList().push_back(this);
55 void Argument::setParent(Function *parent) {
57 LeakDetector::addGarbageObject(this);
60 LeakDetector::removeGarbageObject(this);
63 /// getArgNo - Return the index of this formal argument in its containing
64 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
65 unsigned Argument::getArgNo() const {
66 const Function *F = getParent();
67 assert(F && "Argument is not in a function");
69 Function::const_arg_iterator AI = F->arg_begin();
71 for (; &*AI != this; ++AI)
77 /// hasByValAttr - Return true if this argument has the byval attribute on it
78 /// in its containing function.
79 bool Argument::hasByValAttr() const {
80 if (!getType()->isPointerTy()) return false;
81 return getParent()->getParamAttributes(getArgNo()+1).
82 hasAttribute(Attributes::ByVal);
85 unsigned Argument::getParamAlignment() const {
86 assert(getType()->isPointerTy() && "Only pointers have alignments");
87 return getParent()->getParamAlignment(getArgNo()+1);
91 /// hasNestAttr - Return true if this argument has the nest attribute on
92 /// it in its containing function.
93 bool Argument::hasNestAttr() const {
94 if (!getType()->isPointerTy()) return false;
95 return getParent()->getParamAttributes(getArgNo()+1).
96 hasAttribute(Attributes::Nest);
99 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
100 /// it in its containing function.
101 bool Argument::hasNoAliasAttr() const {
102 if (!getType()->isPointerTy()) return false;
103 return getParent()->getParamAttributes(getArgNo()+1).
104 hasAttribute(Attributes::NoAlias);
107 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
108 /// on it in its containing function.
109 bool Argument::hasNoCaptureAttr() const {
110 if (!getType()->isPointerTy()) return false;
111 return getParent()->getParamAttributes(getArgNo()+1).
112 hasAttribute(Attributes::NoCapture);
115 /// hasSRetAttr - Return true if this argument has the sret attribute on
116 /// it in its containing function.
117 bool Argument::hasStructRetAttr() const {
118 if (!getType()->isPointerTy()) return false;
119 if (this != getParent()->arg_begin())
120 return false; // StructRet param must be first param
121 return getParent()->getParamAttributes(1).
122 hasAttribute(Attributes::StructRet);
125 /// addAttr - Add a Attribute to an argument
126 void Argument::addAttr(Attributes attr) {
127 getParent()->addAttribute(getArgNo() + 1, attr);
130 /// removeAttr - Remove a Attribute from an argument
131 void Argument::removeAttr(Attributes attr) {
132 getParent()->removeAttribute(getArgNo() + 1, attr);
136 //===----------------------------------------------------------------------===//
137 // Helper Methods in Function
138 //===----------------------------------------------------------------------===//
140 LLVMContext &Function::getContext() const {
141 return getType()->getContext();
144 FunctionType *Function::getFunctionType() const {
145 return cast<FunctionType>(getType()->getElementType());
148 bool Function::isVarArg() const {
149 return getFunctionType()->isVarArg();
152 Type *Function::getReturnType() const {
153 return getFunctionType()->getReturnType();
156 void Function::removeFromParent() {
157 getParent()->getFunctionList().remove(this);
160 void Function::eraseFromParent() {
161 getParent()->getFunctionList().erase(this);
164 //===----------------------------------------------------------------------===//
165 // Function Implementation
166 //===----------------------------------------------------------------------===//
168 Function::Function(FunctionType *Ty, LinkageTypes Linkage,
169 const Twine &name, Module *ParentModule)
170 : GlobalValue(PointerType::getUnqual(Ty),
171 Value::FunctionVal, 0, 0, Linkage, name) {
172 assert(FunctionType::isValidReturnType(getReturnType()) &&
173 "invalid return type");
174 SymTab = new ValueSymbolTable();
176 // If the function has arguments, mark them as lazily built.
177 if (Ty->getNumParams())
178 setValueSubclassData(1); // Set the "has lazy arguments" bit.
180 // Make sure that we get added to a function
181 LeakDetector::addGarbageObject(this);
184 ParentModule->getFunctionList().push_back(this);
186 // Ensure intrinsics have the right parameter attributes.
187 if (unsigned IID = getIntrinsicID())
188 setAttributes(Intrinsic::getAttributes(getContext(), Intrinsic::ID(IID)));
192 Function::~Function() {
193 dropAllReferences(); // After this it is safe to delete instructions.
195 // Delete all of the method arguments and unlink from symbol table...
196 ArgumentList.clear();
199 // Remove the function from the on-the-side GC table.
203 void Function::BuildLazyArguments() const {
204 // Create the arguments vector, all arguments start out unnamed.
205 FunctionType *FT = getFunctionType();
206 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
207 assert(!FT->getParamType(i)->isVoidTy() &&
208 "Cannot have void typed arguments!");
209 ArgumentList.push_back(new Argument(FT->getParamType(i)));
212 // Clear the lazy arguments bit.
213 unsigned SDC = getSubclassDataFromValue();
214 const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
217 size_t Function::arg_size() const {
218 return getFunctionType()->getNumParams();
220 bool Function::arg_empty() const {
221 return getFunctionType()->getNumParams() == 0;
224 void Function::setParent(Module *parent) {
226 LeakDetector::addGarbageObject(this);
229 LeakDetector::removeGarbageObject(this);
232 // dropAllReferences() - This function causes all the subinstructions to "let
233 // go" of all references that they are maintaining. This allows one to
234 // 'delete' a whole class at a time, even though there may be circular
235 // references... first all references are dropped, and all use counts go to
236 // zero. Then everything is deleted for real. Note that no operations are
237 // valid on an object that has "dropped all references", except operator
240 void Function::dropAllReferences() {
241 for (iterator I = begin(), E = end(); I != E; ++I)
242 I->dropAllReferences();
244 // Delete all basic blocks. They are now unused, except possibly by
245 // blockaddresses, but BasicBlock's destructor takes care of those.
246 while (!BasicBlocks.empty())
247 BasicBlocks.begin()->eraseFromParent();
250 void Function::addAttribute(unsigned i, Attributes attr) {
251 AttrListPtr PAL = getAttributes();
252 PAL = PAL.addAttr(getContext(), i, attr);
256 void Function::removeAttribute(unsigned i, Attributes attr) {
257 AttrListPtr PAL = getAttributes();
258 PAL = PAL.removeAttr(getContext(), i, attr);
262 // Maintain the GC name for each function in an on-the-side table. This saves
263 // allocating an additional word in Function for programs which do not use GC
264 // (i.e., most programs) at the cost of increased overhead for clients which do
266 static DenseMap<const Function*,PooledStringPtr> *GCNames;
267 static StringPool *GCNamePool;
268 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
270 bool Function::hasGC() const {
271 sys::SmartScopedReader<true> Reader(*GCLock);
272 return GCNames && GCNames->count(this);
275 const char *Function::getGC() const {
276 assert(hasGC() && "Function has no collector");
277 sys::SmartScopedReader<true> Reader(*GCLock);
278 return *(*GCNames)[this];
281 void Function::setGC(const char *Str) {
282 sys::SmartScopedWriter<true> Writer(*GCLock);
284 GCNamePool = new StringPool();
286 GCNames = new DenseMap<const Function*,PooledStringPtr>();
287 (*GCNames)[this] = GCNamePool->intern(Str);
290 void Function::clearGC() {
291 sys::SmartScopedWriter<true> Writer(*GCLock);
293 GCNames->erase(this);
294 if (GCNames->empty()) {
297 if (GCNamePool->empty()) {
305 /// copyAttributesFrom - copy all additional attributes (those not needed to
306 /// create a Function) from the Function Src to this one.
307 void Function::copyAttributesFrom(const GlobalValue *Src) {
308 assert(isa<Function>(Src) && "Expected a Function!");
309 GlobalValue::copyAttributesFrom(Src);
310 const Function *SrcF = cast<Function>(Src);
311 setCallingConv(SrcF->getCallingConv());
312 setAttributes(SrcF->getAttributes());
314 setGC(SrcF->getGC());
319 /// getIntrinsicID - This method returns the ID number of the specified
320 /// function, or Intrinsic::not_intrinsic if the function is not an
321 /// intrinsic, or if the pointer is null. This value is always defined to be
322 /// zero to allow easy checking for whether a function is intrinsic or not. The
323 /// particular intrinsic functions which correspond to this value are defined in
324 /// llvm/Intrinsics.h.
326 unsigned Function::getIntrinsicID() const {
327 const ValueName *ValName = this->getValueName();
330 unsigned Len = ValName->getKeyLength();
331 const char *Name = ValName->getKeyData();
333 if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
334 || Name[2] != 'v' || Name[3] != 'm')
335 return 0; // All intrinsics start with 'llvm.'
337 #define GET_FUNCTION_RECOGNIZER
338 #include "llvm/Intrinsics.gen"
339 #undef GET_FUNCTION_RECOGNIZER
343 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
344 assert(id < num_intrinsics && "Invalid intrinsic ID!");
345 static const char * const Table[] = {
347 #define GET_INTRINSIC_NAME_TABLE
348 #include "llvm/Intrinsics.gen"
349 #undef GET_INTRINSIC_NAME_TABLE
353 std::string Result(Table[id]);
354 for (unsigned i = 0; i < Tys.size(); ++i) {
355 if (PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
356 Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
357 EVT::getEVT(PTyp->getElementType()).getEVTString();
360 Result += "." + EVT::getEVT(Tys[i]).getEVTString();
366 /// IIT_Info - These are enumerators that describe the entries returned by the
367 /// getIntrinsicInfoTableEntries function.
369 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
371 // Common values should be encoded with 0-15.
389 // Values from 16+ are only encodable with the inefficient encoding.
391 IIT_EMPTYSTRUCT = 17,
396 IIT_EXTEND_VEC_ARG = 22,
397 IIT_TRUNC_VEC_ARG = 23,
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::Float, 0));
422 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
425 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
428 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
431 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
434 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
437 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
440 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
441 DecodeIITType(NextElt, Infos, OutputTable);
444 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
445 DecodeIITType(NextElt, Infos, OutputTable);
448 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
449 DecodeIITType(NextElt, Infos, OutputTable);
452 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
453 DecodeIITType(NextElt, Infos, OutputTable);
456 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
457 DecodeIITType(NextElt, Infos, OutputTable);
460 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
461 DecodeIITType(NextElt, Infos, OutputTable);
463 case IIT_ANYPTR: { // [ANYPTR addrspace, subtype]
464 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
466 DecodeIITType(NextElt, Infos, OutputTable);
470 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
471 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
474 case IIT_EXTEND_VEC_ARG: {
475 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
476 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendVecArgument,
480 case IIT_TRUNC_VEC_ARG: {
481 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
482 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncVecArgument,
486 case IIT_EMPTYSTRUCT:
487 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
489 case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
490 case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
491 case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
493 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
495 for (unsigned i = 0; i != StructElts; ++i)
496 DecodeIITType(NextElt, Infos, OutputTable);
500 llvm_unreachable("unhandled");
504 #define GET_INTRINSIC_GENERATOR_GLOBAL
505 #include "llvm/Intrinsics.gen"
506 #undef GET_INTRINSIC_GENERATOR_GLOBAL
508 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
509 SmallVectorImpl<IITDescriptor> &T){
510 // Check to see if the intrinsic's type was expressible by the table.
511 unsigned TableVal = IIT_Table[id-1];
513 // Decode the TableVal into an array of IITValues.
514 SmallVector<unsigned char, 8> IITValues;
515 ArrayRef<unsigned char> IITEntries;
516 unsigned NextElt = 0;
517 if ((TableVal >> 31) != 0) {
518 // This is an offset into the IIT_LongEncodingTable.
519 IITEntries = IIT_LongEncodingTable;
521 // Strip sentinel bit.
522 NextElt = (TableVal << 1) >> 1;
524 // Decode the TableVal into an array of IITValues. If the entry was encoded
525 // into a single word in the table itself, decode it now.
527 IITValues.push_back(TableVal & 0xF);
531 IITEntries = IITValues;
535 // Okay, decode the table into the output vector of IITDescriptors.
536 DecodeIITType(NextElt, IITEntries, T);
537 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
538 DecodeIITType(NextElt, IITEntries, T);
542 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
543 ArrayRef<Type*> Tys, LLVMContext &Context) {
544 using namespace Intrinsic;
545 IITDescriptor D = Infos.front();
546 Infos = Infos.slice(1);
549 case IITDescriptor::Void: return Type::getVoidTy(Context);
550 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
551 case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
552 case IITDescriptor::Float: return Type::getFloatTy(Context);
553 case IITDescriptor::Double: return Type::getDoubleTy(Context);
555 case IITDescriptor::Integer:
556 return IntegerType::get(Context, D.Integer_Width);
557 case IITDescriptor::Vector:
558 return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
559 case IITDescriptor::Pointer:
560 return PointerType::get(DecodeFixedType(Infos, Tys, Context),
561 D.Pointer_AddressSpace);
562 case IITDescriptor::Struct: {
564 assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
565 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
566 Elts[i] = DecodeFixedType(Infos, Tys, Context);
567 return StructType::get(Context, ArrayRef<Type*>(Elts,D.Struct_NumElements));
570 case IITDescriptor::Argument:
571 return Tys[D.getArgumentNumber()];
572 case IITDescriptor::ExtendVecArgument:
573 return VectorType::getExtendedElementVectorType(cast<VectorType>(
574 Tys[D.getArgumentNumber()]));
576 case IITDescriptor::TruncVecArgument:
577 return VectorType::getTruncatedElementVectorType(cast<VectorType>(
578 Tys[D.getArgumentNumber()]));
580 llvm_unreachable("unhandled");
585 FunctionType *Intrinsic::getType(LLVMContext &Context,
586 ID id, ArrayRef<Type*> Tys) {
587 SmallVector<IITDescriptor, 8> Table;
588 getIntrinsicInfoTableEntries(id, Table);
590 ArrayRef<IITDescriptor> TableRef = Table;
591 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
593 SmallVector<Type*, 8> ArgTys;
594 while (!TableRef.empty())
595 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
597 return FunctionType::get(ResultTy, ArgTys, false);
600 bool Intrinsic::isOverloaded(ID id) {
601 #define GET_INTRINSIC_OVERLOAD_TABLE
602 #include "llvm/Intrinsics.gen"
603 #undef GET_INTRINSIC_OVERLOAD_TABLE
606 /// This defines the "Intrinsic::getAttributes(ID id)" method.
607 #define GET_INTRINSIC_ATTRIBUTES
608 #include "llvm/Intrinsics.gen"
609 #undef GET_INTRINSIC_ATTRIBUTES
611 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
612 // There can never be multiple globals with the same name of different types,
613 // because intrinsics must be a specific type.
615 cast<Function>(M->getOrInsertFunction(getName(id, Tys),
616 getType(M->getContext(), id, Tys)));
619 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
620 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
621 #include "llvm/Intrinsics.gen"
622 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
624 /// hasAddressTaken - returns true if there are any uses of this function
625 /// other than direct calls or invokes to it.
626 bool Function::hasAddressTaken(const User* *PutOffender) const {
627 for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
629 if (isa<BlockAddress>(U))
631 if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
632 return PutOffender ? (*PutOffender = U, true) : true;
633 ImmutableCallSite CS(cast<Instruction>(U));
635 return PutOffender ? (*PutOffender = U, true) : true;
640 bool Function::isDefTriviallyDead() const {
642 if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
643 !hasAvailableExternallyLinkage())
646 // Check if the function is used by anything other than a blockaddress.
647 for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I)
648 if (!isa<BlockAddress>(*I))
654 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
655 /// setjmp or other function that gcc recognizes as "returning twice".
656 bool Function::callsFunctionThatReturnsTwice() const {
657 for (const_inst_iterator
658 I = inst_begin(this), E = inst_end(this); I != E; ++I) {
659 const CallInst* callInst = dyn_cast<CallInst>(&*I);
662 if (callInst->canReturnTwice())