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 /// Return true if this argument has the readonly or readnone attribute on it
00170 /// in its containing function.
00171 bool Argument::onlyReadsMemory() const {
00172   return getParent()->getAttributes().
00173       hasAttribute(getArgNo()+1, Attribute::ReadOnly) ||
00174       getParent()->getAttributes().
00175       hasAttribute(getArgNo()+1, Attribute::ReadNone);
00176 }
00177 
00178 /// addAttr - Add attributes to an argument.
00179 void Argument::addAttr(AttributeSet AS) {
00180   assert(AS.getNumSlots() <= 1 &&
00181          "Trying to add more than one attribute set to an argument!");
00182   AttrBuilder B(AS, AS.getSlotIndex(0));
00183   getParent()->addAttributes(getArgNo() + 1,
00184                              AttributeSet::get(Parent->getContext(),
00185                                                getArgNo() + 1, B));
00186 }
00187 
00188 /// removeAttr - Remove attributes from an argument.
00189 void Argument::removeAttr(AttributeSet AS) {
00190   assert(AS.getNumSlots() <= 1 &&
00191          "Trying to remove more than one attribute set from an argument!");
00192   AttrBuilder B(AS, AS.getSlotIndex(0));
00193   getParent()->removeAttributes(getArgNo() + 1,
00194                                 AttributeSet::get(Parent->getContext(),
00195                                                   getArgNo() + 1, B));
00196 }
00197 
00198 //===----------------------------------------------------------------------===//
00199 // Helper Methods in Function
00200 //===----------------------------------------------------------------------===//
00201 
00202 LLVMContext &Function::getContext() const {
00203   return getType()->getContext();
00204 }
00205 
00206 FunctionType *Function::getFunctionType() const {
00207   return cast<FunctionType>(getType()->getElementType());
00208 }
00209 
00210 bool Function::isVarArg() const {
00211   return getFunctionType()->isVarArg();
00212 }
00213 
00214 Type *Function::getReturnType() const {
00215   return getFunctionType()->getReturnType();
00216 }
00217 
00218 void Function::removeFromParent() {
00219   getParent()->getFunctionList().remove(this);
00220 }
00221 
00222 void Function::eraseFromParent() {
00223   getParent()->getFunctionList().erase(this);
00224 }
00225 
00226 //===----------------------------------------------------------------------===//
00227 // Function Implementation
00228 //===----------------------------------------------------------------------===//
00229 
00230 Function::Function(FunctionType *Ty, LinkageTypes Linkage,
00231                    const Twine &name, Module *ParentModule)
00232   : GlobalObject(PointerType::getUnqual(Ty),
00233                 Value::FunctionVal, nullptr, 0, Linkage, name) {
00234   assert(FunctionType::isValidReturnType(getReturnType()) &&
00235          "invalid return type");
00236   SymTab = new ValueSymbolTable();
00237 
00238   // If the function has arguments, mark them as lazily built.
00239   if (Ty->getNumParams())
00240     setValueSubclassData(1);   // Set the "has lazy arguments" bit.
00241 
00242   // Make sure that we get added to a function
00243   LeakDetector::addGarbageObject(this);
00244 
00245   if (ParentModule)
00246     ParentModule->getFunctionList().push_back(this);
00247 
00248   // Ensure intrinsics have the right parameter attributes.
00249   if (unsigned IID = getIntrinsicID())
00250     setAttributes(Intrinsic::getAttributes(getContext(), Intrinsic::ID(IID)));
00251 
00252 }
00253 
00254 Function::~Function() {
00255   dropAllReferences();    // After this it is safe to delete instructions.
00256 
00257   // Delete all of the method arguments and unlink from symbol table...
00258   ArgumentList.clear();
00259   delete SymTab;
00260 
00261   // Remove the function from the on-the-side GC table.
00262   clearGC();
00263 
00264   // Remove the intrinsicID from the Cache.
00265   if (getValueName() && isIntrinsic())
00266     getContext().pImpl->IntrinsicIDCache.erase(this);
00267 }
00268 
00269 void Function::BuildLazyArguments() const {
00270   // Create the arguments vector, all arguments start out unnamed.
00271   FunctionType *FT = getFunctionType();
00272   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
00273     assert(!FT->getParamType(i)->isVoidTy() &&
00274            "Cannot have void typed arguments!");
00275     ArgumentList.push_back(new Argument(FT->getParamType(i)));
00276   }
00277 
00278   // Clear the lazy arguments bit.
00279   unsigned SDC = getSubclassDataFromValue();
00280   const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
00281 }
00282 
00283 size_t Function::arg_size() const {
00284   return getFunctionType()->getNumParams();
00285 }
00286 bool Function::arg_empty() const {
00287   return getFunctionType()->getNumParams() == 0;
00288 }
00289 
00290 void Function::setParent(Module *parent) {
00291   if (getParent())
00292     LeakDetector::addGarbageObject(this);
00293   Parent = parent;
00294   if (getParent())
00295     LeakDetector::removeGarbageObject(this);
00296 }
00297 
00298 // dropAllReferences() - This function causes all the subinstructions to "let
00299 // go" of all references that they are maintaining.  This allows one to
00300 // 'delete' a whole class at a time, even though there may be circular
00301 // references... first all references are dropped, and all use counts go to
00302 // zero.  Then everything is deleted for real.  Note that no operations are
00303 // valid on an object that has "dropped all references", except operator
00304 // delete.
00305 //
00306 void Function::dropAllReferences() {
00307   for (iterator I = begin(), E = end(); I != E; ++I)
00308     I->dropAllReferences();
00309 
00310   // Delete all basic blocks. They are now unused, except possibly by
00311   // blockaddresses, but BasicBlock's destructor takes care of those.
00312   while (!BasicBlocks.empty())
00313     BasicBlocks.begin()->eraseFromParent();
00314 
00315   // Prefix data is stored in a side table.
00316   setPrefixData(nullptr);
00317 }
00318 
00319 void Function::addAttribute(unsigned i, Attribute::AttrKind attr) {
00320   AttributeSet PAL = getAttributes();
00321   PAL = PAL.addAttribute(getContext(), i, attr);
00322   setAttributes(PAL);
00323 }
00324 
00325 void Function::addAttributes(unsigned i, AttributeSet attrs) {
00326   AttributeSet PAL = getAttributes();
00327   PAL = PAL.addAttributes(getContext(), i, attrs);
00328   setAttributes(PAL);
00329 }
00330 
00331 void Function::removeAttributes(unsigned i, AttributeSet attrs) {
00332   AttributeSet PAL = getAttributes();
00333   PAL = PAL.removeAttributes(getContext(), i, attrs);
00334   setAttributes(PAL);
00335 }
00336 
00337 // Maintain the GC name for each function in an on-the-side table. This saves
00338 // allocating an additional word in Function for programs which do not use GC
00339 // (i.e., most programs) at the cost of increased overhead for clients which do
00340 // use GC.
00341 static DenseMap<const Function*,PooledStringPtr> *GCNames;
00342 static StringPool *GCNamePool;
00343 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
00344 
00345 bool Function::hasGC() const {
00346   sys::SmartScopedReader<true> Reader(*GCLock);
00347   return GCNames && GCNames->count(this);
00348 }
00349 
00350 const char *Function::getGC() const {
00351   assert(hasGC() && "Function has no collector");
00352   sys::SmartScopedReader<true> Reader(*GCLock);
00353   return *(*GCNames)[this];
00354 }
00355 
00356 void Function::setGC(const char *Str) {
00357   sys::SmartScopedWriter<true> Writer(*GCLock);
00358   if (!GCNamePool)
00359     GCNamePool = new StringPool();
00360   if (!GCNames)
00361     GCNames = new DenseMap<const Function*,PooledStringPtr>();
00362   (*GCNames)[this] = GCNamePool->intern(Str);
00363 }
00364 
00365 void Function::clearGC() {
00366   sys::SmartScopedWriter<true> Writer(*GCLock);
00367   if (GCNames) {
00368     GCNames->erase(this);
00369     if (GCNames->empty()) {
00370       delete GCNames;
00371       GCNames = nullptr;
00372       if (GCNamePool->empty()) {
00373         delete GCNamePool;
00374         GCNamePool = nullptr;
00375       }
00376     }
00377   }
00378 }
00379 
00380 /// copyAttributesFrom - copy all additional attributes (those not needed to
00381 /// create a Function) from the Function Src to this one.
00382 void Function::copyAttributesFrom(const GlobalValue *Src) {
00383   assert(isa<Function>(Src) && "Expected a Function!");
00384   GlobalObject::copyAttributesFrom(Src);
00385   const Function *SrcF = cast<Function>(Src);
00386   setCallingConv(SrcF->getCallingConv());
00387   setAttributes(SrcF->getAttributes());
00388   if (SrcF->hasGC())
00389     setGC(SrcF->getGC());
00390   else
00391     clearGC();
00392   if (SrcF->hasPrefixData())
00393     setPrefixData(SrcF->getPrefixData());
00394   else
00395     setPrefixData(nullptr);
00396 }
00397 
00398 /// getIntrinsicID - This method returns the ID number of the specified
00399 /// function, or Intrinsic::not_intrinsic if the function is not an
00400 /// intrinsic, or if the pointer is null.  This value is always defined to be
00401 /// zero to allow easy checking for whether a function is intrinsic or not.  The
00402 /// particular intrinsic functions which correspond to this value are defined in
00403 /// llvm/Intrinsics.h.  Results are cached in the LLVM context, subsequent
00404 /// requests for the same ID return results much faster from the cache.
00405 ///
00406 unsigned Function::getIntrinsicID() const {
00407   const ValueName *ValName = this->getValueName();
00408   if (!ValName || !isIntrinsic())
00409     return 0;
00410 
00411   LLVMContextImpl::IntrinsicIDCacheTy &IntrinsicIDCache =
00412     getContext().pImpl->IntrinsicIDCache;
00413   if (!IntrinsicIDCache.count(this)) {
00414     unsigned Id = lookupIntrinsicID();
00415     IntrinsicIDCache[this]=Id;
00416     return Id;
00417   }
00418   return IntrinsicIDCache[this];
00419 }
00420 
00421 /// This private method does the actual lookup of an intrinsic ID when the query
00422 /// could not be answered from the cache.
00423 unsigned Function::lookupIntrinsicID() const {
00424   const ValueName *ValName = this->getValueName();
00425   unsigned Len = ValName->getKeyLength();
00426   const char *Name = ValName->getKeyData();
00427 
00428 #define GET_FUNCTION_RECOGNIZER
00429 #include "llvm/IR/Intrinsics.gen"
00430 #undef GET_FUNCTION_RECOGNIZER
00431 
00432   return 0;
00433 }
00434 
00435 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
00436   assert(id < num_intrinsics && "Invalid intrinsic ID!");
00437   static const char * const Table[] = {
00438     "not_intrinsic",
00439 #define GET_INTRINSIC_NAME_TABLE
00440 #include "llvm/IR/Intrinsics.gen"
00441 #undef GET_INTRINSIC_NAME_TABLE
00442   };
00443   if (Tys.empty())
00444     return Table[id];
00445   std::string Result(Table[id]);
00446   for (unsigned i = 0; i < Tys.size(); ++i) {
00447     if (PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
00448       Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
00449                 EVT::getEVT(PTyp->getElementType()).getEVTString();
00450     }
00451     else if (Tys[i])
00452       Result += "." + EVT::getEVT(Tys[i]).getEVTString();
00453   }
00454   return Result;
00455 }
00456 
00457 
00458 /// IIT_Info - These are enumerators that describe the entries returned by the
00459 /// getIntrinsicInfoTableEntries function.
00460 ///
00461 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
00462 enum IIT_Info {
00463   // Common values should be encoded with 0-15.
00464   IIT_Done = 0,
00465   IIT_I1   = 1,
00466   IIT_I8   = 2,
00467   IIT_I16  = 3,
00468   IIT_I32  = 4,
00469   IIT_I64  = 5,
00470   IIT_F16  = 6,
00471   IIT_F32  = 7,
00472   IIT_F64  = 8,
00473   IIT_V2   = 9,
00474   IIT_V4   = 10,
00475   IIT_V8   = 11,
00476   IIT_V16  = 12,
00477   IIT_V32  = 13,
00478   IIT_PTR  = 14,
00479   IIT_ARG  = 15,
00480 
00481   // Values from 16+ are only encodable with the inefficient encoding.
00482   IIT_MMX  = 16,
00483   IIT_METADATA = 17,
00484   IIT_EMPTYSTRUCT = 18,
00485   IIT_STRUCT2 = 19,
00486   IIT_STRUCT3 = 20,
00487   IIT_STRUCT4 = 21,
00488   IIT_STRUCT5 = 22,
00489   IIT_EXTEND_ARG = 23,
00490   IIT_TRUNC_ARG = 24,
00491   IIT_ANYPTR = 25,
00492   IIT_V1   = 26,
00493   IIT_VARARG = 27,
00494   IIT_HALF_VEC_ARG = 28
00495 };
00496 
00497 
00498 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
00499                       SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
00500   IIT_Info Info = IIT_Info(Infos[NextElt++]);
00501   unsigned StructElts = 2;
00502   using namespace Intrinsic;
00503 
00504   switch (Info) {
00505   case IIT_Done:
00506     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
00507     return;
00508   case IIT_VARARG:
00509     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
00510     return;
00511   case IIT_MMX:
00512     OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
00513     return;
00514   case IIT_METADATA:
00515     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
00516     return;
00517   case IIT_F16:
00518     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
00519     return;
00520   case IIT_F32:
00521     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
00522     return;
00523   case IIT_F64:
00524     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
00525     return;
00526   case IIT_I1:
00527     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
00528     return;
00529   case IIT_I8:
00530     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
00531     return;
00532   case IIT_I16:
00533     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
00534     return;
00535   case IIT_I32:
00536     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
00537     return;
00538   case IIT_I64:
00539     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
00540     return;
00541   case IIT_V1:
00542     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
00543     DecodeIITType(NextElt, Infos, OutputTable);
00544     return;
00545   case IIT_V2:
00546     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
00547     DecodeIITType(NextElt, Infos, OutputTable);
00548     return;
00549   case IIT_V4:
00550     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
00551     DecodeIITType(NextElt, Infos, OutputTable);
00552     return;
00553   case IIT_V8:
00554     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
00555     DecodeIITType(NextElt, Infos, OutputTable);
00556     return;
00557   case IIT_V16:
00558     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
00559     DecodeIITType(NextElt, Infos, OutputTable);
00560     return;
00561   case IIT_V32:
00562     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
00563     DecodeIITType(NextElt, Infos, OutputTable);
00564     return;
00565   case IIT_PTR:
00566     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
00567     DecodeIITType(NextElt, Infos, OutputTable);
00568     return;
00569   case IIT_ANYPTR: {  // [ANYPTR addrspace, subtype]
00570     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
00571                                              Infos[NextElt++]));
00572     DecodeIITType(NextElt, Infos, OutputTable);
00573     return;
00574   }
00575   case IIT_ARG: {
00576     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00577     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
00578     return;
00579   }
00580   case IIT_EXTEND_ARG: {
00581     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00582     OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
00583                                              ArgInfo));
00584     return;
00585   }
00586   case IIT_TRUNC_ARG: {
00587     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00588     OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
00589                                              ArgInfo));
00590     return;
00591   }
00592   case IIT_HALF_VEC_ARG: {
00593     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00594     OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
00595                                              ArgInfo));
00596     return;
00597   }
00598   case IIT_EMPTYSTRUCT:
00599     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
00600     return;
00601   case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
00602   case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
00603   case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
00604   case IIT_STRUCT2: {
00605     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
00606 
00607     for (unsigned i = 0; i != StructElts; ++i)
00608       DecodeIITType(NextElt, Infos, OutputTable);
00609     return;
00610   }
00611   }
00612   llvm_unreachable("unhandled");
00613 }
00614 
00615 
00616 #define GET_INTRINSIC_GENERATOR_GLOBAL
00617 #include "llvm/IR/Intrinsics.gen"
00618 #undef GET_INTRINSIC_GENERATOR_GLOBAL
00619 
00620 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
00621                                              SmallVectorImpl<IITDescriptor> &T){
00622   // Check to see if the intrinsic's type was expressible by the table.
00623   unsigned TableVal = IIT_Table[id-1];
00624 
00625   // Decode the TableVal into an array of IITValues.
00626   SmallVector<unsigned char, 8> IITValues;
00627   ArrayRef<unsigned char> IITEntries;
00628   unsigned NextElt = 0;
00629   if ((TableVal >> 31) != 0) {
00630     // This is an offset into the IIT_LongEncodingTable.
00631     IITEntries = IIT_LongEncodingTable;
00632 
00633     // Strip sentinel bit.
00634     NextElt = (TableVal << 1) >> 1;
00635   } else {
00636     // Decode the TableVal into an array of IITValues.  If the entry was encoded
00637     // into a single word in the table itself, decode it now.
00638     do {
00639       IITValues.push_back(TableVal & 0xF);
00640       TableVal >>= 4;
00641     } while (TableVal);
00642 
00643     IITEntries = IITValues;
00644     NextElt = 0;
00645   }
00646 
00647   // Okay, decode the table into the output vector of IITDescriptors.
00648   DecodeIITType(NextElt, IITEntries, T);
00649   while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
00650     DecodeIITType(NextElt, IITEntries, T);
00651 }
00652 
00653 
00654 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
00655                              ArrayRef<Type*> Tys, LLVMContext &Context) {
00656   using namespace Intrinsic;
00657   IITDescriptor D = Infos.front();
00658   Infos = Infos.slice(1);
00659 
00660   switch (D.Kind) {
00661   case IITDescriptor::Void: return Type::getVoidTy(Context);
00662   case IITDescriptor::VarArg: return Type::getVoidTy(Context);
00663   case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
00664   case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
00665   case IITDescriptor::Half: return Type::getHalfTy(Context);
00666   case IITDescriptor::Float: return Type::getFloatTy(Context);
00667   case IITDescriptor::Double: return Type::getDoubleTy(Context);
00668 
00669   case IITDescriptor::Integer:
00670     return IntegerType::get(Context, D.Integer_Width);
00671   case IITDescriptor::Vector:
00672     return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
00673   case IITDescriptor::Pointer:
00674     return PointerType::get(DecodeFixedType(Infos, Tys, Context),
00675                             D.Pointer_AddressSpace);
00676   case IITDescriptor::Struct: {
00677     Type *Elts[5];
00678     assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
00679     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
00680       Elts[i] = DecodeFixedType(Infos, Tys, Context);
00681     return StructType::get(Context, ArrayRef<Type*>(Elts,D.Struct_NumElements));
00682   }
00683 
00684   case IITDescriptor::Argument:
00685     return Tys[D.getArgumentNumber()];
00686   case IITDescriptor::ExtendArgument: {
00687     Type *Ty = Tys[D.getArgumentNumber()];
00688     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00689       return VectorType::getExtendedElementVectorType(VTy);
00690 
00691     return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
00692   }
00693   case IITDescriptor::TruncArgument: {
00694     Type *Ty = Tys[D.getArgumentNumber()];
00695     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00696       return VectorType::getTruncatedElementVectorType(VTy);
00697 
00698     IntegerType *ITy = cast<IntegerType>(Ty);
00699     assert(ITy->getBitWidth() % 2 == 0);
00700     return IntegerType::get(Context, ITy->getBitWidth() / 2);
00701   }
00702   case IITDescriptor::HalfVecArgument:
00703     return VectorType::getHalfElementsVectorType(cast<VectorType>(
00704                                                   Tys[D.getArgumentNumber()]));
00705   }
00706   llvm_unreachable("unhandled");
00707 }
00708 
00709 
00710 
00711 FunctionType *Intrinsic::getType(LLVMContext &Context,
00712                                  ID id, ArrayRef<Type*> Tys) {
00713   SmallVector<IITDescriptor, 8> Table;
00714   getIntrinsicInfoTableEntries(id, Table);
00715 
00716   ArrayRef<IITDescriptor> TableRef = Table;
00717   Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
00718 
00719   SmallVector<Type*, 8> ArgTys;
00720   while (!TableRef.empty())
00721     ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
00722 
00723   return FunctionType::get(ResultTy, ArgTys, false);
00724 }
00725 
00726 bool Intrinsic::isOverloaded(ID id) {
00727 #define GET_INTRINSIC_OVERLOAD_TABLE
00728 #include "llvm/IR/Intrinsics.gen"
00729 #undef GET_INTRINSIC_OVERLOAD_TABLE
00730 }
00731 
00732 /// This defines the "Intrinsic::getAttributes(ID id)" method.
00733 #define GET_INTRINSIC_ATTRIBUTES
00734 #include "llvm/IR/Intrinsics.gen"
00735 #undef GET_INTRINSIC_ATTRIBUTES
00736 
00737 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
00738   // There can never be multiple globals with the same name of different types,
00739   // because intrinsics must be a specific type.
00740   return
00741     cast<Function>(M->getOrInsertFunction(getName(id, Tys),
00742                                           getType(M->getContext(), id, Tys)));
00743 }
00744 
00745 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
00746 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
00747 #include "llvm/IR/Intrinsics.gen"
00748 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
00749 
00750 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
00751 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
00752 #include "llvm/IR/Intrinsics.gen"
00753 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
00754 
00755 /// hasAddressTaken - returns true if there are any uses of this function
00756 /// other than direct calls or invokes to it.
00757 bool Function::hasAddressTaken(const User* *PutOffender) const {
00758   for (const Use &U : uses()) {
00759     const User *FU = U.getUser();
00760     if (isa<BlockAddress>(FU))
00761       continue;
00762     if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU))
00763       return PutOffender ? (*PutOffender = FU, true) : true;
00764     ImmutableCallSite CS(cast<Instruction>(FU));
00765     if (!CS.isCallee(&U))
00766       return PutOffender ? (*PutOffender = FU, true) : true;
00767   }
00768   return false;
00769 }
00770 
00771 bool Function::isDefTriviallyDead() const {
00772   // Check the linkage
00773   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
00774       !hasAvailableExternallyLinkage())
00775     return false;
00776 
00777   // Check if the function is used by anything other than a blockaddress.
00778   for (const User *U : users())
00779     if (!isa<BlockAddress>(U))
00780       return false;
00781 
00782   return true;
00783 }
00784 
00785 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
00786 /// setjmp or other function that gcc recognizes as "returning twice".
00787 bool Function::callsFunctionThatReturnsTwice() const {
00788   for (const_inst_iterator
00789          I = inst_begin(this), E = inst_end(this); I != E; ++I) {
00790     ImmutableCallSite CS(&*I);
00791     if (CS && CS.hasFnAttr(Attribute::ReturnsTwice))
00792       return true;
00793   }
00794 
00795   return false;
00796 }
00797 
00798 Constant *Function::getPrefixData() const {
00799   assert(hasPrefixData());
00800   const LLVMContextImpl::PrefixDataMapTy &PDMap =
00801       getContext().pImpl->PrefixDataMap;
00802   assert(PDMap.find(this) != PDMap.end());
00803   return cast<Constant>(PDMap.find(this)->second->getReturnValue());
00804 }
00805 
00806 void Function::setPrefixData(Constant *PrefixData) {
00807   if (!PrefixData && !hasPrefixData())
00808     return;
00809 
00810   unsigned SCData = getSubclassDataFromValue();
00811   LLVMContextImpl::PrefixDataMapTy &PDMap = getContext().pImpl->PrefixDataMap;
00812   ReturnInst *&PDHolder = PDMap[this];
00813   if (PrefixData) {
00814     if (PDHolder)
00815       PDHolder->setOperand(0, PrefixData);
00816     else
00817       PDHolder = ReturnInst::Create(getContext(), PrefixData);
00818     SCData |= 2;
00819   } else {
00820     delete PDHolder;
00821     PDMap.erase(this);
00822     SCData &= ~2;
00823   }
00824   setValueSubclassData(SCData);
00825 }