LLVM API Documentation

Function.cpp
Go to the documentation of this file.
00001 //===-- Function.cpp - Implement the Global object classes ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Function class for the IR library.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/IR/Function.h"
00015 #include "LLVMContextImpl.h"
00016 #include "SymbolTableListTraitsImpl.h"
00017 #include "llvm/ADT/DenseMap.h"
00018 #include "llvm/ADT/STLExtras.h"
00019 #include "llvm/ADT/StringExtras.h"
00020 #include "llvm/CodeGen/ValueTypes.h"
00021 #include "llvm/IR/CallSite.h"
00022 #include "llvm/IR/DerivedTypes.h"
00023 #include "llvm/IR/InstIterator.h"
00024 #include "llvm/IR/IntrinsicInst.h"
00025 #include "llvm/IR/LLVMContext.h"
00026 #include "llvm/IR/LeakDetector.h"
00027 #include "llvm/IR/Module.h"
00028 #include "llvm/Support/ManagedStatic.h"
00029 #include "llvm/Support/RWMutex.h"
00030 #include "llvm/Support/StringPool.h"
00031 #include "llvm/Support/Threading.h"
00032 using namespace llvm;
00033 
00034 // Explicit instantiations of SymbolTableListTraits since some of the methods
00035 // are not in the public header file...
00036 template class llvm::SymbolTableListTraits<Argument, Function>;
00037 template class llvm::SymbolTableListTraits<BasicBlock, Function>;
00038 
00039 //===----------------------------------------------------------------------===//
00040 // Argument Implementation
00041 //===----------------------------------------------------------------------===//
00042 
00043 void Argument::anchor() { }
00044 
00045 Argument::Argument(Type *Ty, const Twine &Name, Function *Par)
00046   : Value(Ty, Value::ArgumentVal) {
00047   Parent = nullptr;
00048 
00049   // Make sure that we get added to a function
00050   LeakDetector::addGarbageObject(this);
00051 
00052   if (Par)
00053     Par->getArgumentList().push_back(this);
00054   setName(Name);
00055 }
00056 
00057 void Argument::setParent(Function *parent) {
00058   if (getParent())
00059     LeakDetector::addGarbageObject(this);
00060   Parent = parent;
00061   if (getParent())
00062     LeakDetector::removeGarbageObject(this);
00063 }
00064 
00065 /// getArgNo - Return the index of this formal argument in its containing
00066 /// function.  For example in "void foo(int a, float b)" a is 0 and b is 1.
00067 unsigned Argument::getArgNo() const {
00068   const Function *F = getParent();
00069   assert(F && "Argument is not in a function");
00070 
00071   Function::const_arg_iterator AI = F->arg_begin();
00072   unsigned ArgIdx = 0;
00073   for (; &*AI != this; ++AI)
00074     ++ArgIdx;
00075 
00076   return ArgIdx;
00077 }
00078 
00079 /// hasNonNullAttr - Return true if this argument has the nonnull attribute on
00080 /// it in its containing function. Also returns true if at least one byte is
00081 /// known to be dereferenceable and the pointer is in addrspace(0).
00082 bool Argument::hasNonNullAttr() const {
00083   if (!getType()->isPointerTy()) return false;
00084   if (getParent()->getAttributes().
00085         hasAttribute(getArgNo()+1, Attribute::NonNull))
00086     return true;
00087   else if (getDereferenceableBytes() > 0 &&
00088            getType()->getPointerAddressSpace() == 0)
00089     return true;
00090   return false;
00091 }
00092 
00093 /// hasByValAttr - Return true if this argument has the byval attribute on it
00094 /// in its containing function.
00095 bool Argument::hasByValAttr() const {
00096   if (!getType()->isPointerTy()) return false;
00097   return getParent()->getAttributes().
00098     hasAttribute(getArgNo()+1, Attribute::ByVal);
00099 }
00100 
00101 /// \brief Return true if this argument has the inalloca attribute on it in
00102 /// its containing function.
00103 bool Argument::hasInAllocaAttr() const {
00104   if (!getType()->isPointerTy()) return false;
00105   return getParent()->getAttributes().
00106     hasAttribute(getArgNo()+1, Attribute::InAlloca);
00107 }
00108 
00109 bool Argument::hasByValOrInAllocaAttr() const {
00110   if (!getType()->isPointerTy()) return false;
00111   AttributeSet Attrs = getParent()->getAttributes();
00112   return Attrs.hasAttribute(getArgNo() + 1, Attribute::ByVal) ||
00113          Attrs.hasAttribute(getArgNo() + 1, Attribute::InAlloca);
00114 }
00115 
00116 unsigned Argument::getParamAlignment() const {
00117   assert(getType()->isPointerTy() && "Only pointers have alignments");
00118   return getParent()->getParamAlignment(getArgNo()+1);
00119 
00120 }
00121 
00122 uint64_t Argument::getDereferenceableBytes() const {
00123   assert(getType()->isPointerTy() &&
00124          "Only pointers have dereferenceable bytes");
00125   return getParent()->getDereferenceableBytes(getArgNo()+1);
00126 }
00127 
00128 /// hasNestAttr - Return true if this argument has the nest attribute on
00129 /// it in its containing function.
00130 bool Argument::hasNestAttr() const {
00131   if (!getType()->isPointerTy()) return false;
00132   return getParent()->getAttributes().
00133     hasAttribute(getArgNo()+1, Attribute::Nest);
00134 }
00135 
00136 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
00137 /// it in its containing function.
00138 bool Argument::hasNoAliasAttr() const {
00139   if (!getType()->isPointerTy()) return false;
00140   return getParent()->getAttributes().
00141     hasAttribute(getArgNo()+1, Attribute::NoAlias);
00142 }
00143 
00144 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
00145 /// on it in its containing function.
00146 bool Argument::hasNoCaptureAttr() const {
00147   if (!getType()->isPointerTy()) return false;
00148   return getParent()->getAttributes().
00149     hasAttribute(getArgNo()+1, Attribute::NoCapture);
00150 }
00151 
00152 /// hasSRetAttr - Return true if this argument has the sret attribute on
00153 /// it in its containing function.
00154 bool Argument::hasStructRetAttr() const {
00155   if (!getType()->isPointerTy()) return false;
00156   if (this != getParent()->arg_begin())
00157     return false; // StructRet param must be first param
00158   return getParent()->getAttributes().
00159     hasAttribute(1, Attribute::StructRet);
00160 }
00161 
00162 /// hasReturnedAttr - Return true if this argument has the returned attribute on
00163 /// it in its containing function.
00164 bool Argument::hasReturnedAttr() const {
00165   return getParent()->getAttributes().
00166     hasAttribute(getArgNo()+1, Attribute::Returned);
00167 }
00168 
00169 /// hasZExtAttr - Return true if this argument has the zext attribute on it in
00170 /// its containing function.
00171 bool Argument::hasZExtAttr() const {
00172   return getParent()->getAttributes().
00173     hasAttribute(getArgNo()+1, Attribute::ZExt);
00174 }
00175 
00176 /// hasSExtAttr Return true if this argument has the sext attribute on it in its
00177 /// containing function.
00178 bool Argument::hasSExtAttr() const {
00179   return getParent()->getAttributes().
00180     hasAttribute(getArgNo()+1, Attribute::SExt);
00181 }
00182 
00183 /// Return true if this argument has the readonly or readnone attribute on it
00184 /// in its containing function.
00185 bool Argument::onlyReadsMemory() const {
00186   return getParent()->getAttributes().
00187       hasAttribute(getArgNo()+1, Attribute::ReadOnly) ||
00188       getParent()->getAttributes().
00189       hasAttribute(getArgNo()+1, Attribute::ReadNone);
00190 }
00191 
00192 /// addAttr - Add attributes to an argument.
00193 void Argument::addAttr(AttributeSet AS) {
00194   assert(AS.getNumSlots() <= 1 &&
00195          "Trying to add more than one attribute set to an argument!");
00196   AttrBuilder B(AS, AS.getSlotIndex(0));
00197   getParent()->addAttributes(getArgNo() + 1,
00198                              AttributeSet::get(Parent->getContext(),
00199                                                getArgNo() + 1, B));
00200 }
00201 
00202 /// removeAttr - Remove attributes from an argument.
00203 void Argument::removeAttr(AttributeSet AS) {
00204   assert(AS.getNumSlots() <= 1 &&
00205          "Trying to remove more than one attribute set from an argument!");
00206   AttrBuilder B(AS, AS.getSlotIndex(0));
00207   getParent()->removeAttributes(getArgNo() + 1,
00208                                 AttributeSet::get(Parent->getContext(),
00209                                                   getArgNo() + 1, B));
00210 }
00211 
00212 //===----------------------------------------------------------------------===//
00213 // Helper Methods in Function
00214 //===----------------------------------------------------------------------===//
00215 
00216 bool Function::isMaterializable() const {
00217   return getGlobalObjectSubClassData();
00218 }
00219 
00220 void Function::setIsMaterializable(bool V) { setGlobalObjectSubClassData(V); }
00221 
00222 LLVMContext &Function::getContext() const {
00223   return getType()->getContext();
00224 }
00225 
00226 FunctionType *Function::getFunctionType() const {
00227   return cast<FunctionType>(getType()->getElementType());
00228 }
00229 
00230 bool Function::isVarArg() const {
00231   return getFunctionType()->isVarArg();
00232 }
00233 
00234 Type *Function::getReturnType() const {
00235   return getFunctionType()->getReturnType();
00236 }
00237 
00238 void Function::removeFromParent() {
00239   getParent()->getFunctionList().remove(this);
00240 }
00241 
00242 void Function::eraseFromParent() {
00243   getParent()->getFunctionList().erase(this);
00244 }
00245 
00246 //===----------------------------------------------------------------------===//
00247 // Function Implementation
00248 //===----------------------------------------------------------------------===//
00249 
00250 Function::Function(FunctionType *Ty, LinkageTypes Linkage, const Twine &name,
00251                    Module *ParentModule)
00252     : GlobalObject(PointerType::getUnqual(Ty), Value::FunctionVal, nullptr, 0,
00253                    Linkage, name) {
00254   assert(FunctionType::isValidReturnType(getReturnType()) &&
00255          "invalid return type");
00256   setIsMaterializable(false);
00257   SymTab = new ValueSymbolTable();
00258 
00259   // If the function has arguments, mark them as lazily built.
00260   if (Ty->getNumParams())
00261     setValueSubclassData(1);   // Set the "has lazy arguments" bit.
00262 
00263   // Make sure that we get added to a function
00264   LeakDetector::addGarbageObject(this);
00265 
00266   if (ParentModule)
00267     ParentModule->getFunctionList().push_back(this);
00268 
00269   // Ensure intrinsics have the right parameter attributes.
00270   if (unsigned IID = getIntrinsicID())
00271     setAttributes(Intrinsic::getAttributes(getContext(), Intrinsic::ID(IID)));
00272 
00273 }
00274 
00275 Function::~Function() {
00276   dropAllReferences();    // After this it is safe to delete instructions.
00277 
00278   // Delete all of the method arguments and unlink from symbol table...
00279   ArgumentList.clear();
00280   delete SymTab;
00281 
00282   // Remove the function from the on-the-side GC table.
00283   clearGC();
00284 
00285   // Remove the intrinsicID from the Cache.
00286   if (getValueName() && isIntrinsic())
00287     getContext().pImpl->IntrinsicIDCache.erase(this);
00288 }
00289 
00290 void Function::BuildLazyArguments() const {
00291   // Create the arguments vector, all arguments start out unnamed.
00292   FunctionType *FT = getFunctionType();
00293   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
00294     assert(!FT->getParamType(i)->isVoidTy() &&
00295            "Cannot have void typed arguments!");
00296     ArgumentList.push_back(new Argument(FT->getParamType(i)));
00297   }
00298 
00299   // Clear the lazy arguments bit.
00300   unsigned SDC = getSubclassDataFromValue();
00301   const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
00302 }
00303 
00304 size_t Function::arg_size() const {
00305   return getFunctionType()->getNumParams();
00306 }
00307 bool Function::arg_empty() const {
00308   return getFunctionType()->getNumParams() == 0;
00309 }
00310 
00311 void Function::setParent(Module *parent) {
00312   if (getParent())
00313     LeakDetector::addGarbageObject(this);
00314   Parent = parent;
00315   if (getParent())
00316     LeakDetector::removeGarbageObject(this);
00317 }
00318 
00319 // dropAllReferences() - This function causes all the subinstructions to "let
00320 // go" of all references that they are maintaining.  This allows one to
00321 // 'delete' a whole class at a time, even though there may be circular
00322 // references... first all references are dropped, and all use counts go to
00323 // zero.  Then everything is deleted for real.  Note that no operations are
00324 // valid on an object that has "dropped all references", except operator
00325 // delete.
00326 //
00327 void Function::dropAllReferences() {
00328   setIsMaterializable(false);
00329 
00330   for (iterator I = begin(), E = end(); I != E; ++I)
00331     I->dropAllReferences();
00332 
00333   // Delete all basic blocks. They are now unused, except possibly by
00334   // blockaddresses, but BasicBlock's destructor takes care of those.
00335   while (!BasicBlocks.empty())
00336     BasicBlocks.begin()->eraseFromParent();
00337 
00338   // Prefix data is stored in a side table.
00339   setPrefixData(nullptr);
00340 }
00341 
00342 void Function::addAttribute(unsigned i, Attribute::AttrKind attr) {
00343   AttributeSet PAL = getAttributes();
00344   PAL = PAL.addAttribute(getContext(), i, attr);
00345   setAttributes(PAL);
00346 }
00347 
00348 void Function::addAttributes(unsigned i, AttributeSet attrs) {
00349   AttributeSet PAL = getAttributes();
00350   PAL = PAL.addAttributes(getContext(), i, attrs);
00351   setAttributes(PAL);
00352 }
00353 
00354 void Function::removeAttributes(unsigned i, AttributeSet attrs) {
00355   AttributeSet PAL = getAttributes();
00356   PAL = PAL.removeAttributes(getContext(), i, attrs);
00357   setAttributes(PAL);
00358 }
00359 
00360 // Maintain the GC name for each function in an on-the-side table. This saves
00361 // allocating an additional word in Function for programs which do not use GC
00362 // (i.e., most programs) at the cost of increased overhead for clients which do
00363 // use GC.
00364 static DenseMap<const Function*,PooledStringPtr> *GCNames;
00365 static StringPool *GCNamePool;
00366 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
00367 
00368 bool Function::hasGC() const {
00369   sys::SmartScopedReader<true> Reader(*GCLock);
00370   return GCNames && GCNames->count(this);
00371 }
00372 
00373 const char *Function::getGC() const {
00374   assert(hasGC() && "Function has no collector");
00375   sys::SmartScopedReader<true> Reader(*GCLock);
00376   return *(*GCNames)[this];
00377 }
00378 
00379 void Function::setGC(const char *Str) {
00380   sys::SmartScopedWriter<true> Writer(*GCLock);
00381   if (!GCNamePool)
00382     GCNamePool = new StringPool();
00383   if (!GCNames)
00384     GCNames = new DenseMap<const Function*,PooledStringPtr>();
00385   (*GCNames)[this] = GCNamePool->intern(Str);
00386 }
00387 
00388 void Function::clearGC() {
00389   sys::SmartScopedWriter<true> Writer(*GCLock);
00390   if (GCNames) {
00391     GCNames->erase(this);
00392     if (GCNames->empty()) {
00393       delete GCNames;
00394       GCNames = nullptr;
00395       if (GCNamePool->empty()) {
00396         delete GCNamePool;
00397         GCNamePool = nullptr;
00398       }
00399     }
00400   }
00401 }
00402 
00403 /// copyAttributesFrom - copy all additional attributes (those not needed to
00404 /// create a Function) from the Function Src to this one.
00405 void Function::copyAttributesFrom(const GlobalValue *Src) {
00406   assert(isa<Function>(Src) && "Expected a Function!");
00407   GlobalObject::copyAttributesFrom(Src);
00408   const Function *SrcF = cast<Function>(Src);
00409   setCallingConv(SrcF->getCallingConv());
00410   setAttributes(SrcF->getAttributes());
00411   if (SrcF->hasGC())
00412     setGC(SrcF->getGC());
00413   else
00414     clearGC();
00415   if (SrcF->hasPrefixData())
00416     setPrefixData(SrcF->getPrefixData());
00417   else
00418     setPrefixData(nullptr);
00419 }
00420 
00421 /// getIntrinsicID - This method returns the ID number of the specified
00422 /// function, or Intrinsic::not_intrinsic if the function is not an
00423 /// intrinsic, or if the pointer is null.  This value is always defined to be
00424 /// zero to allow easy checking for whether a function is intrinsic or not.  The
00425 /// particular intrinsic functions which correspond to this value are defined in
00426 /// llvm/Intrinsics.h.  Results are cached in the LLVM context, subsequent
00427 /// requests for the same ID return results much faster from the cache.
00428 ///
00429 unsigned Function::getIntrinsicID() const {
00430   const ValueName *ValName = this->getValueName();
00431   if (!ValName || !isIntrinsic())
00432     return 0;
00433 
00434   LLVMContextImpl::IntrinsicIDCacheTy &IntrinsicIDCache =
00435     getContext().pImpl->IntrinsicIDCache;
00436   if (!IntrinsicIDCache.count(this)) {
00437     unsigned Id = lookupIntrinsicID();
00438     IntrinsicIDCache[this]=Id;
00439     return Id;
00440   }
00441   return IntrinsicIDCache[this];
00442 }
00443 
00444 /// This private method does the actual lookup of an intrinsic ID when the query
00445 /// could not be answered from the cache.
00446 unsigned Function::lookupIntrinsicID() const {
00447   const ValueName *ValName = this->getValueName();
00448   unsigned Len = ValName->getKeyLength();
00449   const char *Name = ValName->getKeyData();
00450 
00451 #define GET_FUNCTION_RECOGNIZER
00452 #include "llvm/IR/Intrinsics.gen"
00453 #undef GET_FUNCTION_RECOGNIZER
00454 
00455   return 0;
00456 }
00457 
00458 /// Returns a stable mangling for the type specified for use in the name
00459 /// mangling scheme used by 'any' types in intrinsic signatures.
00460 static std::string getMangledTypeStr(Type* Ty) {
00461   std::string Result;
00462   if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
00463     Result += "p" + llvm::utostr(PTyp->getAddressSpace()) +
00464       getMangledTypeStr(PTyp->getElementType());
00465   } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
00466     Result += "a" + llvm::utostr(ATyp->getNumElements()) +
00467       getMangledTypeStr(ATyp->getElementType());
00468   } else if (StructType* STyp = dyn_cast<StructType>(Ty)) {
00469     if (!STyp->isLiteral())
00470       Result += STyp->getName();
00471     else
00472       llvm_unreachable("TODO: implement literal types");
00473   } else if (FunctionType* FT = dyn_cast<FunctionType>(Ty)) {
00474     Result += "f_" + getMangledTypeStr(FT->getReturnType());
00475     for (size_t i = 0; i < FT->getNumParams(); i++)
00476       Result += getMangledTypeStr(FT->getParamType(i));
00477     if (FT->isVarArg())
00478       Result += "vararg";
00479     Result += "f"; //ensure distinguishable
00480   } else if (Ty)
00481     Result += EVT::getEVT(Ty).getEVTString();
00482   return Result;
00483 }
00484 
00485 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
00486   assert(id < num_intrinsics && "Invalid intrinsic ID!");
00487   static const char * const Table[] = {
00488     "not_intrinsic",
00489 #define GET_INTRINSIC_NAME_TABLE
00490 #include "llvm/IR/Intrinsics.gen"
00491 #undef GET_INTRINSIC_NAME_TABLE
00492   };
00493   if (Tys.empty())
00494     return Table[id];
00495   std::string Result(Table[id]);
00496   for (unsigned i = 0; i < Tys.size(); ++i) {
00497     Result += "." + getMangledTypeStr(Tys[i]);
00498   }
00499   return Result;
00500 }
00501 
00502 
00503 /// IIT_Info - These are enumerators that describe the entries returned by the
00504 /// getIntrinsicInfoTableEntries function.
00505 ///
00506 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
00507 enum IIT_Info {
00508   // Common values should be encoded with 0-15.
00509   IIT_Done = 0,
00510   IIT_I1   = 1,
00511   IIT_I8   = 2,
00512   IIT_I16  = 3,
00513   IIT_I32  = 4,
00514   IIT_I64  = 5,
00515   IIT_F16  = 6,
00516   IIT_F32  = 7,
00517   IIT_F64  = 8,
00518   IIT_V2   = 9,
00519   IIT_V4   = 10,
00520   IIT_V8   = 11,
00521   IIT_V16  = 12,
00522   IIT_V32  = 13,
00523   IIT_PTR  = 14,
00524   IIT_ARG  = 15,
00525 
00526   // Values from 16+ are only encodable with the inefficient encoding.
00527   IIT_V64  = 16,
00528   IIT_MMX  = 17,
00529   IIT_METADATA = 18,
00530   IIT_EMPTYSTRUCT = 19,
00531   IIT_STRUCT2 = 20,
00532   IIT_STRUCT3 = 21,
00533   IIT_STRUCT4 = 22,
00534   IIT_STRUCT5 = 23,
00535   IIT_EXTEND_ARG = 24,
00536   IIT_TRUNC_ARG = 25,
00537   IIT_ANYPTR = 26,
00538   IIT_V1   = 27,
00539   IIT_VARARG = 28,
00540   IIT_HALF_VEC_ARG = 29,
00541   IIT_SAME_VEC_WIDTH_ARG = 30
00542 };
00543 
00544 
00545 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
00546                       SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
00547   IIT_Info Info = IIT_Info(Infos[NextElt++]);
00548   unsigned StructElts = 2;
00549   using namespace Intrinsic;
00550 
00551   switch (Info) {
00552   case IIT_Done:
00553     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
00554     return;
00555   case IIT_VARARG:
00556     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
00557     return;
00558   case IIT_MMX:
00559     OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
00560     return;
00561   case IIT_METADATA:
00562     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
00563     return;
00564   case IIT_F16:
00565     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
00566     return;
00567   case IIT_F32:
00568     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
00569     return;
00570   case IIT_F64:
00571     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
00572     return;
00573   case IIT_I1:
00574     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
00575     return;
00576   case IIT_I8:
00577     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
00578     return;
00579   case IIT_I16:
00580     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
00581     return;
00582   case IIT_I32:
00583     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
00584     return;
00585   case IIT_I64:
00586     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
00587     return;
00588   case IIT_V1:
00589     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
00590     DecodeIITType(NextElt, Infos, OutputTable);
00591     return;
00592   case IIT_V2:
00593     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
00594     DecodeIITType(NextElt, Infos, OutputTable);
00595     return;
00596   case IIT_V4:
00597     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
00598     DecodeIITType(NextElt, Infos, OutputTable);
00599     return;
00600   case IIT_V8:
00601     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
00602     DecodeIITType(NextElt, Infos, OutputTable);
00603     return;
00604   case IIT_V16:
00605     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
00606     DecodeIITType(NextElt, Infos, OutputTable);
00607     return;
00608   case IIT_V32:
00609     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
00610     DecodeIITType(NextElt, Infos, OutputTable);
00611     return;
00612   case IIT_V64:
00613     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64));
00614     DecodeIITType(NextElt, Infos, OutputTable);
00615     return;
00616   case IIT_PTR:
00617     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
00618     DecodeIITType(NextElt, Infos, OutputTable);
00619     return;
00620   case IIT_ANYPTR: {  // [ANYPTR addrspace, subtype]
00621     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
00622                                              Infos[NextElt++]));
00623     DecodeIITType(NextElt, Infos, OutputTable);
00624     return;
00625   }
00626   case IIT_ARG: {
00627     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00628     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
00629     return;
00630   }
00631   case IIT_EXTEND_ARG: {
00632     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00633     OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
00634                                              ArgInfo));
00635     return;
00636   }
00637   case IIT_TRUNC_ARG: {
00638     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00639     OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
00640                                              ArgInfo));
00641     return;
00642   }
00643   case IIT_HALF_VEC_ARG: {
00644     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00645     OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
00646                                              ArgInfo));
00647     return;
00648   }
00649   case IIT_SAME_VEC_WIDTH_ARG: {
00650     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00651     OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
00652                                              ArgInfo));
00653     return;
00654   }
00655   case IIT_EMPTYSTRUCT:
00656     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
00657     return;
00658   case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
00659   case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
00660   case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
00661   case IIT_STRUCT2: {
00662     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
00663 
00664     for (unsigned i = 0; i != StructElts; ++i)
00665       DecodeIITType(NextElt, Infos, OutputTable);
00666     return;
00667   }
00668   }
00669   llvm_unreachable("unhandled");
00670 }
00671 
00672 
00673 #define GET_INTRINSIC_GENERATOR_GLOBAL
00674 #include "llvm/IR/Intrinsics.gen"
00675 #undef GET_INTRINSIC_GENERATOR_GLOBAL
00676 
00677 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
00678                                              SmallVectorImpl<IITDescriptor> &T){
00679   // Check to see if the intrinsic's type was expressible by the table.
00680   unsigned TableVal = IIT_Table[id-1];
00681 
00682   // Decode the TableVal into an array of IITValues.
00683   SmallVector<unsigned char, 8> IITValues;
00684   ArrayRef<unsigned char> IITEntries;
00685   unsigned NextElt = 0;
00686   if ((TableVal >> 31) != 0) {
00687     // This is an offset into the IIT_LongEncodingTable.
00688     IITEntries = IIT_LongEncodingTable;
00689 
00690     // Strip sentinel bit.
00691     NextElt = (TableVal << 1) >> 1;
00692   } else {
00693     // Decode the TableVal into an array of IITValues.  If the entry was encoded
00694     // into a single word in the table itself, decode it now.
00695     do {
00696       IITValues.push_back(TableVal & 0xF);
00697       TableVal >>= 4;
00698     } while (TableVal);
00699 
00700     IITEntries = IITValues;
00701     NextElt = 0;
00702   }
00703 
00704   // Okay, decode the table into the output vector of IITDescriptors.
00705   DecodeIITType(NextElt, IITEntries, T);
00706   while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
00707     DecodeIITType(NextElt, IITEntries, T);
00708 }
00709 
00710 
00711 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
00712                              ArrayRef<Type*> Tys, LLVMContext &Context) {
00713   using namespace Intrinsic;
00714   IITDescriptor D = Infos.front();
00715   Infos = Infos.slice(1);
00716 
00717   switch (D.Kind) {
00718   case IITDescriptor::Void: return Type::getVoidTy(Context);
00719   case IITDescriptor::VarArg: return Type::getVoidTy(Context);
00720   case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
00721   case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
00722   case IITDescriptor::Half: return Type::getHalfTy(Context);
00723   case IITDescriptor::Float: return Type::getFloatTy(Context);
00724   case IITDescriptor::Double: return Type::getDoubleTy(Context);
00725 
00726   case IITDescriptor::Integer:
00727     return IntegerType::get(Context, D.Integer_Width);
00728   case IITDescriptor::Vector:
00729     return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
00730   case IITDescriptor::Pointer:
00731     return PointerType::get(DecodeFixedType(Infos, Tys, Context),
00732                             D.Pointer_AddressSpace);
00733   case IITDescriptor::Struct: {
00734     Type *Elts[5];
00735     assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
00736     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
00737       Elts[i] = DecodeFixedType(Infos, Tys, Context);
00738     return StructType::get(Context, makeArrayRef(Elts,D.Struct_NumElements));
00739   }
00740 
00741   case IITDescriptor::Argument:
00742     return Tys[D.getArgumentNumber()];
00743   case IITDescriptor::ExtendArgument: {
00744     Type *Ty = Tys[D.getArgumentNumber()];
00745     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00746       return VectorType::getExtendedElementVectorType(VTy);
00747 
00748     return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
00749   }
00750   case IITDescriptor::TruncArgument: {
00751     Type *Ty = Tys[D.getArgumentNumber()];
00752     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00753       return VectorType::getTruncatedElementVectorType(VTy);
00754 
00755     IntegerType *ITy = cast<IntegerType>(Ty);
00756     assert(ITy->getBitWidth() % 2 == 0);
00757     return IntegerType::get(Context, ITy->getBitWidth() / 2);
00758   }
00759   case IITDescriptor::HalfVecArgument:
00760     return VectorType::getHalfElementsVectorType(cast<VectorType>(
00761                                                   Tys[D.getArgumentNumber()]));
00762   case IITDescriptor::SameVecWidthArgument:
00763     Type *EltTy = DecodeFixedType(Infos, Tys, Context);
00764     Type *Ty = Tys[D.getArgumentNumber()];
00765     if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
00766       return VectorType::get(EltTy, VTy->getNumElements());
00767     }
00768     llvm_unreachable("unhandled");
00769  }
00770   llvm_unreachable("unhandled");
00771 }
00772 
00773 
00774 
00775 FunctionType *Intrinsic::getType(LLVMContext &Context,
00776                                  ID id, ArrayRef<Type*> Tys) {
00777   SmallVector<IITDescriptor, 8> Table;
00778   getIntrinsicInfoTableEntries(id, Table);
00779 
00780   ArrayRef<IITDescriptor> TableRef = Table;
00781   Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
00782 
00783   SmallVector<Type*, 8> ArgTys;
00784   while (!TableRef.empty())
00785     ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
00786 
00787   // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
00788   // If we see void type as the type of the last argument, it is vararg intrinsic
00789   if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
00790     ArgTys.pop_back();
00791     return FunctionType::get(ResultTy, ArgTys, true);
00792   }
00793   return FunctionType::get(ResultTy, ArgTys, false);
00794 }
00795 
00796 bool Intrinsic::isOverloaded(ID id) {
00797 #define GET_INTRINSIC_OVERLOAD_TABLE
00798 #include "llvm/IR/Intrinsics.gen"
00799 #undef GET_INTRINSIC_OVERLOAD_TABLE
00800 }
00801 
00802 /// This defines the "Intrinsic::getAttributes(ID id)" method.
00803 #define GET_INTRINSIC_ATTRIBUTES
00804 #include "llvm/IR/Intrinsics.gen"
00805 #undef GET_INTRINSIC_ATTRIBUTES
00806 
00807 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
00808   // There can never be multiple globals with the same name of different types,
00809   // because intrinsics must be a specific type.
00810   return
00811     cast<Function>(M->getOrInsertFunction(getName(id, Tys),
00812                                           getType(M->getContext(), id, Tys)));
00813 }
00814 
00815 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
00816 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
00817 #include "llvm/IR/Intrinsics.gen"
00818 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
00819 
00820 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
00821 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
00822 #include "llvm/IR/Intrinsics.gen"
00823 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
00824 
00825 /// hasAddressTaken - returns true if there are any uses of this function
00826 /// other than direct calls or invokes to it.
00827 bool Function::hasAddressTaken(const User* *PutOffender) const {
00828   for (const Use &U : uses()) {
00829     const User *FU = U.getUser();
00830     if (isa<BlockAddress>(FU))
00831       continue;
00832     if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU))
00833       return PutOffender ? (*PutOffender = FU, true) : true;
00834     ImmutableCallSite CS(cast<Instruction>(FU));
00835     if (!CS.isCallee(&U))
00836       return PutOffender ? (*PutOffender = FU, true) : true;
00837   }
00838   return false;
00839 }
00840 
00841 bool Function::isDefTriviallyDead() const {
00842   // Check the linkage
00843   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
00844       !hasAvailableExternallyLinkage())
00845     return false;
00846 
00847   // Check if the function is used by anything other than a blockaddress.
00848   for (const User *U : users())
00849     if (!isa<BlockAddress>(U))
00850       return false;
00851 
00852   return true;
00853 }
00854 
00855 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
00856 /// setjmp or other function that gcc recognizes as "returning twice".
00857 bool Function::callsFunctionThatReturnsTwice() const {
00858   for (const_inst_iterator
00859          I = inst_begin(this), E = inst_end(this); I != E; ++I) {
00860     ImmutableCallSite CS(&*I);
00861     if (CS && CS.hasFnAttr(Attribute::ReturnsTwice))
00862       return true;
00863   }
00864 
00865   return false;
00866 }
00867 
00868 Constant *Function::getPrefixData() const {
00869   assert(hasPrefixData());
00870   const LLVMContextImpl::PrefixDataMapTy &PDMap =
00871       getContext().pImpl->PrefixDataMap;
00872   assert(PDMap.find(this) != PDMap.end());
00873   return cast<Constant>(PDMap.find(this)->second->getReturnValue());
00874 }
00875 
00876 void Function::setPrefixData(Constant *PrefixData) {
00877   if (!PrefixData && !hasPrefixData())
00878     return;
00879 
00880   unsigned SCData = getSubclassDataFromValue();
00881   LLVMContextImpl::PrefixDataMapTy &PDMap = getContext().pImpl->PrefixDataMap;
00882   ReturnInst *&PDHolder = PDMap[this];
00883   if (PrefixData) {
00884     if (PDHolder)
00885       PDHolder->setOperand(0, PrefixData);
00886     else
00887       PDHolder = ReturnInst::Create(getContext(), PrefixData);
00888     SCData |= 2;
00889   } else {
00890     delete PDHolder;
00891     PDMap.erase(this);
00892     SCData &= ~2;
00893   }
00894   setValueSubclassData(SCData);
00895 }