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 "LLVMContextImpl.h"
16 #include "SymbolTableListTraitsImpl.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/CodeGen/ValueTypes.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/InstIterator.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/LeakDetector.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/RWMutex.h"
30 #include "llvm/Support/StringPool.h"
31 #include "llvm/Support/Threading.h"
34 // Explicit instantiations of SymbolTableListTraits since some of the methods
35 // are not in the public header file...
36 template class llvm::SymbolTableListTraits<Argument, Function>;
37 template class llvm::SymbolTableListTraits<BasicBlock, Function>;
39 //===----------------------------------------------------------------------===//
40 // Argument Implementation
41 //===----------------------------------------------------------------------===//
43 void Argument::anchor() { }
45 Argument::Argument(Type *Ty, const Twine &Name, Function *Par)
46 : Value(Ty, Value::ArgumentVal) {
49 // Make sure that we get added to a function
50 LeakDetector::addGarbageObject(this);
53 Par->getArgumentList().push_back(this);
57 void Argument::setParent(Function *parent) {
59 LeakDetector::addGarbageObject(this);
62 LeakDetector::removeGarbageObject(this);
65 /// getArgNo - Return the index of this formal argument in its containing
66 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
67 unsigned Argument::getArgNo() const {
68 const Function *F = getParent();
69 assert(F && "Argument is not in a function");
71 Function::const_arg_iterator AI = F->arg_begin();
73 for (; &*AI != this; ++AI)
79 /// hasNonNullAttr - Return true if this argument has the nonnull attribute on
80 /// it in its containing function. Also returns true if at least one byte is
81 /// known to be dereferenceable and the pointer is in addrspace(0).
82 bool Argument::hasNonNullAttr() const {
83 if (!getType()->isPointerTy()) return false;
84 if (getParent()->getAttributes().
85 hasAttribute(getArgNo()+1, Attribute::NonNull))
87 else if (getDereferenceableBytes() > 0 &&
88 getType()->getPointerAddressSpace() == 0)
93 /// hasByValAttr - Return true if this argument has the byval attribute on it
94 /// in its containing function.
95 bool Argument::hasByValAttr() const {
96 if (!getType()->isPointerTy()) return false;
97 return getParent()->getAttributes().
98 hasAttribute(getArgNo()+1, Attribute::ByVal);
101 /// \brief Return true if this argument has the inalloca attribute on it in
102 /// its containing function.
103 bool Argument::hasInAllocaAttr() const {
104 if (!getType()->isPointerTy()) return false;
105 return getParent()->getAttributes().
106 hasAttribute(getArgNo()+1, Attribute::InAlloca);
109 bool Argument::hasByValOrInAllocaAttr() const {
110 if (!getType()->isPointerTy()) return false;
111 AttributeSet Attrs = getParent()->getAttributes();
112 return Attrs.hasAttribute(getArgNo() + 1, Attribute::ByVal) ||
113 Attrs.hasAttribute(getArgNo() + 1, Attribute::InAlloca);
116 unsigned Argument::getParamAlignment() const {
117 assert(getType()->isPointerTy() && "Only pointers have alignments");
118 return getParent()->getParamAlignment(getArgNo()+1);
122 uint64_t Argument::getDereferenceableBytes() const {
123 assert(getType()->isPointerTy() &&
124 "Only pointers have dereferenceable bytes");
125 return getParent()->getDereferenceableBytes(getArgNo()+1);
128 /// hasNestAttr - Return true if this argument has the nest attribute on
129 /// it in its containing function.
130 bool Argument::hasNestAttr() const {
131 if (!getType()->isPointerTy()) return false;
132 return getParent()->getAttributes().
133 hasAttribute(getArgNo()+1, Attribute::Nest);
136 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
137 /// it in its containing function.
138 bool Argument::hasNoAliasAttr() const {
139 if (!getType()->isPointerTy()) return false;
140 return getParent()->getAttributes().
141 hasAttribute(getArgNo()+1, Attribute::NoAlias);
144 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
145 /// on it in its containing function.
146 bool Argument::hasNoCaptureAttr() const {
147 if (!getType()->isPointerTy()) return false;
148 return getParent()->getAttributes().
149 hasAttribute(getArgNo()+1, Attribute::NoCapture);
152 /// hasSRetAttr - Return true if this argument has the sret attribute on
153 /// it in its containing function.
154 bool Argument::hasStructRetAttr() const {
155 if (!getType()->isPointerTy()) return false;
156 if (this != getParent()->arg_begin())
157 return false; // StructRet param must be first param
158 return getParent()->getAttributes().
159 hasAttribute(1, Attribute::StructRet);
162 /// hasReturnedAttr - Return true if this argument has the returned attribute on
163 /// it in its containing function.
164 bool Argument::hasReturnedAttr() const {
165 return getParent()->getAttributes().
166 hasAttribute(getArgNo()+1, Attribute::Returned);
169 /// hasZExtAttr - Return true if this argument has the zext attribute on it in
170 /// its containing function.
171 bool Argument::hasZExtAttr() const {
172 return getParent()->getAttributes().
173 hasAttribute(getArgNo()+1, Attribute::ZExt);
176 /// hasSExtAttr Return true if this argument has the sext attribute on it in its
177 /// containing function.
178 bool Argument::hasSExtAttr() const {
179 return getParent()->getAttributes().
180 hasAttribute(getArgNo()+1, Attribute::SExt);
183 /// Return true if this argument has the readonly or readnone attribute on it
184 /// in its containing function.
185 bool Argument::onlyReadsMemory() const {
186 return getParent()->getAttributes().
187 hasAttribute(getArgNo()+1, Attribute::ReadOnly) ||
188 getParent()->getAttributes().
189 hasAttribute(getArgNo()+1, Attribute::ReadNone);
192 /// addAttr - Add attributes to an argument.
193 void Argument::addAttr(AttributeSet AS) {
194 assert(AS.getNumSlots() <= 1 &&
195 "Trying to add more than one attribute set to an argument!");
196 AttrBuilder B(AS, AS.getSlotIndex(0));
197 getParent()->addAttributes(getArgNo() + 1,
198 AttributeSet::get(Parent->getContext(),
202 /// removeAttr - Remove attributes from an argument.
203 void Argument::removeAttr(AttributeSet AS) {
204 assert(AS.getNumSlots() <= 1 &&
205 "Trying to remove more than one attribute set from an argument!");
206 AttrBuilder B(AS, AS.getSlotIndex(0));
207 getParent()->removeAttributes(getArgNo() + 1,
208 AttributeSet::get(Parent->getContext(),
212 //===----------------------------------------------------------------------===//
213 // Helper Methods in Function
214 //===----------------------------------------------------------------------===//
216 bool Function::isMaterializable() const {
217 return getGlobalObjectSubClassData();
220 void Function::setIsMaterializable(bool V) { setGlobalObjectSubClassData(V); }
222 LLVMContext &Function::getContext() const {
223 return getType()->getContext();
226 FunctionType *Function::getFunctionType() const {
227 return cast<FunctionType>(getType()->getElementType());
230 bool Function::isVarArg() const {
231 return getFunctionType()->isVarArg();
234 Type *Function::getReturnType() const {
235 return getFunctionType()->getReturnType();
238 void Function::removeFromParent() {
239 getParent()->getFunctionList().remove(this);
242 void Function::eraseFromParent() {
243 getParent()->getFunctionList().erase(this);
246 //===----------------------------------------------------------------------===//
247 // Function Implementation
248 //===----------------------------------------------------------------------===//
250 Function::Function(FunctionType *Ty, LinkageTypes Linkage, const Twine &name,
251 Module *ParentModule)
252 : GlobalObject(PointerType::getUnqual(Ty), Value::FunctionVal, nullptr, 0,
254 assert(FunctionType::isValidReturnType(getReturnType()) &&
255 "invalid return type");
256 setIsMaterializable(false);
257 SymTab = new ValueSymbolTable();
259 // If the function has arguments, mark them as lazily built.
260 if (Ty->getNumParams())
261 setValueSubclassData(1); // Set the "has lazy arguments" bit.
263 // Make sure that we get added to a function
264 LeakDetector::addGarbageObject(this);
267 ParentModule->getFunctionList().push_back(this);
269 // Ensure intrinsics have the right parameter attributes.
270 if (unsigned IID = getIntrinsicID())
271 setAttributes(Intrinsic::getAttributes(getContext(), Intrinsic::ID(IID)));
275 Function::~Function() {
276 dropAllReferences(); // After this it is safe to delete instructions.
278 // Delete all of the method arguments and unlink from symbol table...
279 ArgumentList.clear();
282 // Remove the function from the on-the-side GC table.
285 // Remove the intrinsicID from the Cache.
286 if (getValueName() && isIntrinsic())
287 getContext().pImpl->IntrinsicIDCache.erase(this);
290 void Function::BuildLazyArguments() const {
291 // Create the arguments vector, all arguments start out unnamed.
292 FunctionType *FT = getFunctionType();
293 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
294 assert(!FT->getParamType(i)->isVoidTy() &&
295 "Cannot have void typed arguments!");
296 ArgumentList.push_back(new Argument(FT->getParamType(i)));
299 // Clear the lazy arguments bit.
300 unsigned SDC = getSubclassDataFromValue();
301 const_cast<Function*>(this)->setValueSubclassData(SDC &= ~(1<<0));
304 size_t Function::arg_size() const {
305 return getFunctionType()->getNumParams();
307 bool Function::arg_empty() const {
308 return getFunctionType()->getNumParams() == 0;
311 void Function::setParent(Module *parent) {
313 LeakDetector::addGarbageObject(this);
316 LeakDetector::removeGarbageObject(this);
319 // dropAllReferences() - This function causes all the subinstructions to "let
320 // go" of all references that they are maintaining. This allows one to
321 // 'delete' a whole class at a time, even though there may be circular
322 // references... first all references are dropped, and all use counts go to
323 // zero. Then everything is deleted for real. Note that no operations are
324 // valid on an object that has "dropped all references", except operator
327 void Function::dropAllReferences() {
328 setIsMaterializable(false);
330 for (iterator I = begin(), E = end(); I != E; ++I)
331 I->dropAllReferences();
333 // Delete all basic blocks. They are now unused, except possibly by
334 // blockaddresses, but BasicBlock's destructor takes care of those.
335 while (!BasicBlocks.empty())
336 BasicBlocks.begin()->eraseFromParent();
338 // Prefix and prologue data are stored in a side table.
339 setPrefixData(nullptr);
340 setPrologueData(nullptr);
343 void Function::addAttribute(unsigned i, Attribute::AttrKind attr) {
344 AttributeSet PAL = getAttributes();
345 PAL = PAL.addAttribute(getContext(), i, attr);
349 void Function::addAttributes(unsigned i, AttributeSet attrs) {
350 AttributeSet PAL = getAttributes();
351 PAL = PAL.addAttributes(getContext(), i, attrs);
355 void Function::removeAttributes(unsigned i, AttributeSet attrs) {
356 AttributeSet PAL = getAttributes();
357 PAL = PAL.removeAttributes(getContext(), i, attrs);
361 // Maintain the GC name for each function in an on-the-side table. This saves
362 // allocating an additional word in Function for programs which do not use GC
363 // (i.e., most programs) at the cost of increased overhead for clients which do
365 static DenseMap<const Function*,PooledStringPtr> *GCNames;
366 static StringPool *GCNamePool;
367 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
369 bool Function::hasGC() const {
370 sys::SmartScopedReader<true> Reader(*GCLock);
371 return GCNames && GCNames->count(this);
374 const char *Function::getGC() const {
375 assert(hasGC() && "Function has no collector");
376 sys::SmartScopedReader<true> Reader(*GCLock);
377 return *(*GCNames)[this];
380 void Function::setGC(const char *Str) {
381 sys::SmartScopedWriter<true> Writer(*GCLock);
383 GCNamePool = new StringPool();
385 GCNames = new DenseMap<const Function*,PooledStringPtr>();
386 (*GCNames)[this] = GCNamePool->intern(Str);
389 void Function::clearGC() {
390 sys::SmartScopedWriter<true> Writer(*GCLock);
392 GCNames->erase(this);
393 if (GCNames->empty()) {
396 if (GCNamePool->empty()) {
398 GCNamePool = nullptr;
404 /// copyAttributesFrom - copy all additional attributes (those not needed to
405 /// create a Function) from the Function Src to this one.
406 void Function::copyAttributesFrom(const GlobalValue *Src) {
407 assert(isa<Function>(Src) && "Expected a Function!");
408 GlobalObject::copyAttributesFrom(Src);
409 const Function *SrcF = cast<Function>(Src);
410 setCallingConv(SrcF->getCallingConv());
411 setAttributes(SrcF->getAttributes());
413 setGC(SrcF->getGC());
416 if (SrcF->hasPrefixData())
417 setPrefixData(SrcF->getPrefixData());
419 setPrefixData(nullptr);
420 if (SrcF->hasPrologueData())
421 setPrologueData(SrcF->getPrologueData());
423 setPrologueData(nullptr);
426 /// getIntrinsicID - This method returns the ID number of the specified
427 /// function, or Intrinsic::not_intrinsic if the function is not an
428 /// intrinsic, or if the pointer is null. This value is always defined to be
429 /// zero to allow easy checking for whether a function is intrinsic or not. The
430 /// particular intrinsic functions which correspond to this value are defined in
431 /// llvm/Intrinsics.h. Results are cached in the LLVM context, subsequent
432 /// requests for the same ID return results much faster from the cache.
434 unsigned Function::getIntrinsicID() const {
435 const ValueName *ValName = this->getValueName();
436 if (!ValName || !isIntrinsic())
439 LLVMContextImpl::IntrinsicIDCacheTy &IntrinsicIDCache =
440 getContext().pImpl->IntrinsicIDCache;
441 if (!IntrinsicIDCache.count(this)) {
442 unsigned Id = lookupIntrinsicID();
443 IntrinsicIDCache[this]=Id;
446 return IntrinsicIDCache[this];
449 /// This private method does the actual lookup of an intrinsic ID when the query
450 /// could not be answered from the cache.
451 unsigned Function::lookupIntrinsicID() const {
452 const ValueName *ValName = this->getValueName();
453 unsigned Len = ValName->getKeyLength();
454 const char *Name = ValName->getKeyData();
456 #define GET_FUNCTION_RECOGNIZER
457 #include "llvm/IR/Intrinsics.gen"
458 #undef GET_FUNCTION_RECOGNIZER
463 /// Returns a stable mangling for the type specified for use in the name
464 /// mangling scheme used by 'any' types in intrinsic signatures. The mangling
465 /// of named types is simply their name. Manglings for unnamed types consist
466 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
467 /// combined with the mangling of their component types. A vararg function
468 /// type will have a suffix of 'vararg'. Since function types can contain
469 /// other function types, we close a function type mangling with suffix 'f'
470 /// which can't be confused with it's prefix. This ensures we don't have
471 /// collisions between two unrelated function types. Otherwise, you might
472 /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.)
473 static std::string getMangledTypeStr(Type* Ty) {
475 if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
476 Result += "p" + llvm::utostr(PTyp->getAddressSpace()) +
477 getMangledTypeStr(PTyp->getElementType());
478 } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
479 Result += "a" + llvm::utostr(ATyp->getNumElements()) +
480 getMangledTypeStr(ATyp->getElementType());
481 } else if (StructType* STyp = dyn_cast<StructType>(Ty)) {
482 if (!STyp->isLiteral())
483 Result += STyp->getName();
485 llvm_unreachable("TODO: implement literal types");
486 } else if (FunctionType* FT = dyn_cast<FunctionType>(Ty)) {
487 Result += "f_" + getMangledTypeStr(FT->getReturnType());
488 for (size_t i = 0; i < FT->getNumParams(); i++)
489 Result += getMangledTypeStr(FT->getParamType(i));
492 // Ensure nested function types are distinguishable.
495 Result += EVT::getEVT(Ty).getEVTString();
499 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
500 assert(id < num_intrinsics && "Invalid intrinsic ID!");
501 static const char * const Table[] = {
503 #define GET_INTRINSIC_NAME_TABLE
504 #include "llvm/IR/Intrinsics.gen"
505 #undef GET_INTRINSIC_NAME_TABLE
509 std::string Result(Table[id]);
510 for (unsigned i = 0; i < Tys.size(); ++i) {
511 Result += "." + getMangledTypeStr(Tys[i]);
517 /// IIT_Info - These are enumerators that describe the entries returned by the
518 /// getIntrinsicInfoTableEntries function.
520 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
522 // Common values should be encoded with 0-15.
540 // Values from 16+ are only encodable with the inefficient encoding.
544 IIT_EMPTYSTRUCT = 19,
554 IIT_HALF_VEC_ARG = 29,
555 IIT_SAME_VEC_WIDTH_ARG = 30
559 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
560 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
561 IIT_Info Info = IIT_Info(Infos[NextElt++]);
562 unsigned StructElts = 2;
563 using namespace Intrinsic;
567 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
570 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
573 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
576 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
579 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
582 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
585 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
588 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
591 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
594 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
597 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
600 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
603 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
604 DecodeIITType(NextElt, Infos, OutputTable);
607 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
608 DecodeIITType(NextElt, Infos, OutputTable);
611 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
612 DecodeIITType(NextElt, Infos, OutputTable);
615 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
616 DecodeIITType(NextElt, Infos, OutputTable);
619 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
620 DecodeIITType(NextElt, Infos, OutputTable);
623 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
624 DecodeIITType(NextElt, Infos, OutputTable);
627 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64));
628 DecodeIITType(NextElt, Infos, OutputTable);
631 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
632 DecodeIITType(NextElt, Infos, OutputTable);
634 case IIT_ANYPTR: { // [ANYPTR addrspace, subtype]
635 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
637 DecodeIITType(NextElt, Infos, OutputTable);
641 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
642 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
645 case IIT_EXTEND_ARG: {
646 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
647 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
651 case IIT_TRUNC_ARG: {
652 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
653 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
657 case IIT_HALF_VEC_ARG: {
658 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
659 OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
663 case IIT_SAME_VEC_WIDTH_ARG: {
664 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
665 OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
669 case IIT_EMPTYSTRUCT:
670 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
672 case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
673 case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
674 case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
676 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
678 for (unsigned i = 0; i != StructElts; ++i)
679 DecodeIITType(NextElt, Infos, OutputTable);
683 llvm_unreachable("unhandled");
687 #define GET_INTRINSIC_GENERATOR_GLOBAL
688 #include "llvm/IR/Intrinsics.gen"
689 #undef GET_INTRINSIC_GENERATOR_GLOBAL
691 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
692 SmallVectorImpl<IITDescriptor> &T){
693 // Check to see if the intrinsic's type was expressible by the table.
694 unsigned TableVal = IIT_Table[id-1];
696 // Decode the TableVal into an array of IITValues.
697 SmallVector<unsigned char, 8> IITValues;
698 ArrayRef<unsigned char> IITEntries;
699 unsigned NextElt = 0;
700 if ((TableVal >> 31) != 0) {
701 // This is an offset into the IIT_LongEncodingTable.
702 IITEntries = IIT_LongEncodingTable;
704 // Strip sentinel bit.
705 NextElt = (TableVal << 1) >> 1;
707 // Decode the TableVal into an array of IITValues. If the entry was encoded
708 // into a single word in the table itself, decode it now.
710 IITValues.push_back(TableVal & 0xF);
714 IITEntries = IITValues;
718 // Okay, decode the table into the output vector of IITDescriptors.
719 DecodeIITType(NextElt, IITEntries, T);
720 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
721 DecodeIITType(NextElt, IITEntries, T);
725 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
726 ArrayRef<Type*> Tys, LLVMContext &Context) {
727 using namespace Intrinsic;
728 IITDescriptor D = Infos.front();
729 Infos = Infos.slice(1);
732 case IITDescriptor::Void: return Type::getVoidTy(Context);
733 case IITDescriptor::VarArg: return Type::getVoidTy(Context);
734 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
735 case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
736 case IITDescriptor::Half: return Type::getHalfTy(Context);
737 case IITDescriptor::Float: return Type::getFloatTy(Context);
738 case IITDescriptor::Double: return Type::getDoubleTy(Context);
740 case IITDescriptor::Integer:
741 return IntegerType::get(Context, D.Integer_Width);
742 case IITDescriptor::Vector:
743 return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
744 case IITDescriptor::Pointer:
745 return PointerType::get(DecodeFixedType(Infos, Tys, Context),
746 D.Pointer_AddressSpace);
747 case IITDescriptor::Struct: {
749 assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
750 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
751 Elts[i] = DecodeFixedType(Infos, Tys, Context);
752 return StructType::get(Context, makeArrayRef(Elts,D.Struct_NumElements));
755 case IITDescriptor::Argument:
756 return Tys[D.getArgumentNumber()];
757 case IITDescriptor::ExtendArgument: {
758 Type *Ty = Tys[D.getArgumentNumber()];
759 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
760 return VectorType::getExtendedElementVectorType(VTy);
762 return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
764 case IITDescriptor::TruncArgument: {
765 Type *Ty = Tys[D.getArgumentNumber()];
766 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
767 return VectorType::getTruncatedElementVectorType(VTy);
769 IntegerType *ITy = cast<IntegerType>(Ty);
770 assert(ITy->getBitWidth() % 2 == 0);
771 return IntegerType::get(Context, ITy->getBitWidth() / 2);
773 case IITDescriptor::HalfVecArgument:
774 return VectorType::getHalfElementsVectorType(cast<VectorType>(
775 Tys[D.getArgumentNumber()]));
776 case IITDescriptor::SameVecWidthArgument:
777 Type *EltTy = DecodeFixedType(Infos, Tys, Context);
778 Type *Ty = Tys[D.getArgumentNumber()];
779 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
780 return VectorType::get(EltTy, VTy->getNumElements());
782 llvm_unreachable("unhandled");
784 llvm_unreachable("unhandled");
789 FunctionType *Intrinsic::getType(LLVMContext &Context,
790 ID id, ArrayRef<Type*> Tys) {
791 SmallVector<IITDescriptor, 8> Table;
792 getIntrinsicInfoTableEntries(id, Table);
794 ArrayRef<IITDescriptor> TableRef = Table;
795 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
797 SmallVector<Type*, 8> ArgTys;
798 while (!TableRef.empty())
799 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
801 // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
802 // If we see void type as the type of the last argument, it is vararg intrinsic
803 if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
805 return FunctionType::get(ResultTy, ArgTys, true);
807 return FunctionType::get(ResultTy, ArgTys, false);
810 bool Intrinsic::isOverloaded(ID id) {
811 #define GET_INTRINSIC_OVERLOAD_TABLE
812 #include "llvm/IR/Intrinsics.gen"
813 #undef GET_INTRINSIC_OVERLOAD_TABLE
816 /// This defines the "Intrinsic::getAttributes(ID id)" method.
817 #define GET_INTRINSIC_ATTRIBUTES
818 #include "llvm/IR/Intrinsics.gen"
819 #undef GET_INTRINSIC_ATTRIBUTES
821 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
822 // There can never be multiple globals with the same name of different types,
823 // because intrinsics must be a specific type.
825 cast<Function>(M->getOrInsertFunction(getName(id, Tys),
826 getType(M->getContext(), id, Tys)));
829 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
830 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
831 #include "llvm/IR/Intrinsics.gen"
832 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
834 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
835 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
836 #include "llvm/IR/Intrinsics.gen"
837 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
839 /// hasAddressTaken - returns true if there are any uses of this function
840 /// other than direct calls or invokes to it.
841 bool Function::hasAddressTaken(const User* *PutOffender) const {
842 for (const Use &U : uses()) {
843 const User *FU = U.getUser();
844 if (isa<BlockAddress>(FU))
846 if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU))
847 return PutOffender ? (*PutOffender = FU, true) : true;
848 ImmutableCallSite CS(cast<Instruction>(FU));
849 if (!CS.isCallee(&U))
850 return PutOffender ? (*PutOffender = FU, true) : true;
855 bool Function::isDefTriviallyDead() const {
857 if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
858 !hasAvailableExternallyLinkage())
861 // Check if the function is used by anything other than a blockaddress.
862 for (const User *U : users())
863 if (!isa<BlockAddress>(U))
869 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
870 /// setjmp or other function that gcc recognizes as "returning twice".
871 bool Function::callsFunctionThatReturnsTwice() const {
872 for (const_inst_iterator
873 I = inst_begin(this), E = inst_end(this); I != E; ++I) {
874 ImmutableCallSite CS(&*I);
875 if (CS && CS.hasFnAttr(Attribute::ReturnsTwice))
882 Constant *Function::getPrefixData() const {
883 assert(hasPrefixData());
884 const LLVMContextImpl::PrefixDataMapTy &PDMap =
885 getContext().pImpl->PrefixDataMap;
886 assert(PDMap.find(this) != PDMap.end());
887 return cast<Constant>(PDMap.find(this)->second->getReturnValue());
890 void Function::setPrefixData(Constant *PrefixData) {
891 if (!PrefixData && !hasPrefixData())
894 unsigned SCData = getSubclassDataFromValue();
895 LLVMContextImpl::PrefixDataMapTy &PDMap = getContext().pImpl->PrefixDataMap;
896 ReturnInst *&PDHolder = PDMap[this];
899 PDHolder->setOperand(0, PrefixData);
901 PDHolder = ReturnInst::Create(getContext(), PrefixData);
908 setValueSubclassData(SCData);
911 Constant *Function::getPrologueData() const {
912 assert(hasPrologueData());
913 const LLVMContextImpl::PrologueDataMapTy &SOMap =
914 getContext().pImpl->PrologueDataMap;
915 assert(SOMap.find(this) != SOMap.end());
916 return cast<Constant>(SOMap.find(this)->second->getReturnValue());
919 void Function::setPrologueData(Constant *PrologueData) {
920 if (!PrologueData && !hasPrologueData())
923 unsigned PDData = getSubclassDataFromValue();
924 LLVMContextImpl::PrologueDataMapTy &PDMap = getContext().pImpl->PrologueDataMap;
925 ReturnInst *&PDHolder = PDMap[this];
928 PDHolder->setOperand(0, PrologueData);
930 PDHolder = ReturnInst::Create(getContext(), PrologueData);
937 setValueSubclassData(PDData);