Function.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  1. //===-- Function.cpp - Implement the Global object classes ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Function class for the IR library.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/IR/Function.h"
  14. #include "LLVMContextImpl.h"
  15. #include "SymbolTableListTraitsImpl.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/CodeGen/ValueTypes.h"
  20. #include "llvm/IR/CallSite.h"
  21. #include "llvm/IR/Constants.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/MDBuilder.h"
  27. #include "llvm/IR/Metadata.h"
  28. #include "llvm/IR/Module.h"
  29. #include "llvm/Support/ManagedStatic.h"
  30. #include "llvm/Support/RWMutex.h"
  31. #include "llvm/Support/StringPool.h"
  32. #include "llvm/Support/Threading.h"
  33. using namespace llvm;
  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>;
  38. //===----------------------------------------------------------------------===//
  39. // Argument Implementation
  40. //===----------------------------------------------------------------------===//
  41. void Argument::anchor() { }
  42. Argument::Argument(Type *Ty, const Twine &Name, Function *Par)
  43. : Value(Ty, Value::ArgumentVal) {
  44. Parent = nullptr;
  45. if (Par)
  46. Par->getArgumentList().push_back(this);
  47. setName(Name);
  48. }
  49. void Argument::setParent(Function *parent) {
  50. Parent = parent;
  51. }
  52. /// getArgNo - Return the index of this formal argument in its containing
  53. /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
  54. unsigned Argument::getArgNo() const {
  55. const Function *F = getParent();
  56. assert(F && "Argument is not in a function");
  57. Function::const_arg_iterator AI = F->arg_begin();
  58. unsigned ArgIdx = 0;
  59. for (; &*AI != this; ++AI)
  60. ++ArgIdx;
  61. return ArgIdx;
  62. }
  63. /// hasNonNullAttr - Return true if this argument has the nonnull attribute on
  64. /// it in its containing function. Also returns true if at least one byte is
  65. /// known to be dereferenceable and the pointer is in addrspace(0).
  66. bool Argument::hasNonNullAttr() const {
  67. if (!getType()->isPointerTy()) return false;
  68. if (getParent()->getAttributes().
  69. hasAttribute(getArgNo()+1, Attribute::NonNull))
  70. return true;
  71. else if (getDereferenceableBytes() > 0 &&
  72. getType()->getPointerAddressSpace() == 0)
  73. return true;
  74. return false;
  75. }
  76. /// hasByValAttr - Return true if this argument has the byval attribute on it
  77. /// in its containing function.
  78. bool Argument::hasByValAttr() const {
  79. if (!getType()->isPointerTy()) return false;
  80. return getParent()->getAttributes().
  81. hasAttribute(getArgNo()+1, Attribute::ByVal);
  82. }
  83. /// \brief Return true if this argument has the inalloca attribute on it in
  84. /// its containing function.
  85. bool Argument::hasInAllocaAttr() const {
  86. if (!getType()->isPointerTy()) return false;
  87. return getParent()->getAttributes().
  88. hasAttribute(getArgNo()+1, Attribute::InAlloca);
  89. }
  90. bool Argument::hasByValOrInAllocaAttr() const {
  91. if (!getType()->isPointerTy()) return false;
  92. AttributeSet Attrs = getParent()->getAttributes();
  93. return Attrs.hasAttribute(getArgNo() + 1, Attribute::ByVal) ||
  94. Attrs.hasAttribute(getArgNo() + 1, Attribute::InAlloca);
  95. }
  96. unsigned Argument::getParamAlignment() const {
  97. assert(getType()->isPointerTy() && "Only pointers have alignments");
  98. return getParent()->getParamAlignment(getArgNo()+1);
  99. }
  100. uint64_t Argument::getDereferenceableBytes() const {
  101. assert(getType()->isPointerTy() &&
  102. "Only pointers have dereferenceable bytes");
  103. return getParent()->getDereferenceableBytes(getArgNo()+1);
  104. }
  105. uint64_t Argument::getDereferenceableOrNullBytes() const {
  106. assert(getType()->isPointerTy() &&
  107. "Only pointers have dereferenceable bytes");
  108. return getParent()->getDereferenceableOrNullBytes(getArgNo()+1);
  109. }
  110. /// hasNestAttr - Return true if this argument has the nest attribute on
  111. /// it in its containing function.
  112. bool Argument::hasNestAttr() const {
  113. if (!getType()->isPointerTy()) return false;
  114. return getParent()->getAttributes().
  115. hasAttribute(getArgNo()+1, Attribute::Nest);
  116. }
  117. /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
  118. /// it in its containing function.
  119. bool Argument::hasNoAliasAttr() const {
  120. if (!getType()->isPointerTy()) return false;
  121. return getParent()->getAttributes().
  122. hasAttribute(getArgNo()+1, Attribute::NoAlias);
  123. }
  124. /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
  125. /// on it in its containing function.
  126. bool Argument::hasNoCaptureAttr() const {
  127. if (!getType()->isPointerTy()) return false;
  128. return getParent()->getAttributes().
  129. hasAttribute(getArgNo()+1, Attribute::NoCapture);
  130. }
  131. /// hasSRetAttr - Return true if this argument has the sret attribute on
  132. /// it in its containing function.
  133. bool Argument::hasStructRetAttr() const {
  134. if (!getType()->isPointerTy()) return false;
  135. if (this != getParent()->arg_begin())
  136. return false; // StructRet param must be first param
  137. return getParent()->getAttributes().
  138. hasAttribute(1, Attribute::StructRet);
  139. }
  140. /// hasReturnedAttr - Return true if this argument has the returned attribute on
  141. /// it in its containing function.
  142. bool Argument::hasReturnedAttr() const {
  143. return getParent()->getAttributes().
  144. hasAttribute(getArgNo()+1, Attribute::Returned);
  145. }
  146. /// hasZExtAttr - Return true if this argument has the zext attribute on it in
  147. /// its containing function.
  148. bool Argument::hasZExtAttr() const {
  149. return getParent()->getAttributes().
  150. hasAttribute(getArgNo()+1, Attribute::ZExt);
  151. }
  152. /// hasSExtAttr Return true if this argument has the sext attribute on it in its
  153. /// containing function.
  154. bool Argument::hasSExtAttr() const {
  155. return getParent()->getAttributes().
  156. hasAttribute(getArgNo()+1, Attribute::SExt);
  157. }
  158. /// Return true if this argument has the readonly or readnone attribute on it
  159. /// in its containing function.
  160. bool Argument::onlyReadsMemory() const {
  161. return getParent()->getAttributes().
  162. hasAttribute(getArgNo()+1, Attribute::ReadOnly) ||
  163. getParent()->getAttributes().
  164. hasAttribute(getArgNo()+1, Attribute::ReadNone);
  165. }
  166. /// addAttr - Add attributes to an argument.
  167. void Argument::addAttr(AttributeSet AS) {
  168. assert(AS.getNumSlots() <= 1 &&
  169. "Trying to add more than one attribute set to an argument!");
  170. AttrBuilder B(AS, AS.getSlotIndex(0));
  171. getParent()->addAttributes(getArgNo() + 1,
  172. AttributeSet::get(Parent->getContext(),
  173. getArgNo() + 1, B));
  174. }
  175. /// removeAttr - Remove attributes from an argument.
  176. void Argument::removeAttr(AttributeSet AS) {
  177. assert(AS.getNumSlots() <= 1 &&
  178. "Trying to remove more than one attribute set from an argument!");
  179. AttrBuilder B(AS, AS.getSlotIndex(0));
  180. getParent()->removeAttributes(getArgNo() + 1,
  181. AttributeSet::get(Parent->getContext(),
  182. getArgNo() + 1, B));
  183. }
  184. //===----------------------------------------------------------------------===//
  185. // Helper Methods in Function
  186. //===----------------------------------------------------------------------===//
  187. bool Function::isMaterializable() const {
  188. return getGlobalObjectSubClassData() & IsMaterializableBit;
  189. }
  190. void Function::setIsMaterializable(bool V) {
  191. setGlobalObjectBit(IsMaterializableBit, V);
  192. }
  193. LLVMContext &Function::getContext() const {
  194. return getType()->getContext();
  195. }
  196. FunctionType *Function::getFunctionType() const { return Ty; }
  197. bool Function::isVarArg() const {
  198. return getFunctionType()->isVarArg();
  199. }
  200. Type *Function::getReturnType() const {
  201. return getFunctionType()->getReturnType();
  202. }
  203. void Function::removeFromParent() {
  204. getParent()->getFunctionList().remove(this);
  205. }
  206. void Function::eraseFromParent() {
  207. getParent()->getFunctionList().erase(this);
  208. }
  209. //===----------------------------------------------------------------------===//
  210. // Function Implementation
  211. //===----------------------------------------------------------------------===//
  212. Function::Function(FunctionType *Ty, LinkageTypes Linkage, const Twine &name,
  213. Module *ParentModule)
  214. : GlobalObject(PointerType::getUnqual(Ty), Value::FunctionVal, nullptr, 0,
  215. Linkage, name),
  216. Ty(Ty) {
  217. assert(FunctionType::isValidReturnType(getReturnType()) &&
  218. "invalid return type");
  219. setGlobalObjectSubClassData(0);
  220. SymTab = new ValueSymbolTable();
  221. // If the function has arguments, mark them as lazily built.
  222. if (Ty->getNumParams())
  223. setValueSubclassData(1); // Set the "has lazy arguments" bit.
  224. if (ParentModule)
  225. ParentModule->getFunctionList().push_back(this);
  226. // Ensure intrinsics have the right parameter attributes.
  227. // Note, the IntID field will have been set in Value::setName if this function
  228. // name is a valid intrinsic ID.
  229. if (IntID)
  230. setAttributes(Intrinsic::getAttributes(getContext(), IntID));
  231. }
  232. Function::~Function() {
  233. dropAllReferences(); // After this it is safe to delete instructions.
  234. // Delete all of the method arguments and unlink from symbol table...
  235. ArgumentList.clear();
  236. delete SymTab;
  237. // Remove the function from the on-the-side GC table.
  238. clearGC();
  239. }
  240. void Function::BuildLazyArguments() const {
  241. // Create the arguments vector, all arguments start out unnamed.
  242. FunctionType *FT = getFunctionType();
  243. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  244. assert(!FT->getParamType(i)->isVoidTy() &&
  245. "Cannot have void typed arguments!");
  246. ArgumentList.push_back(new Argument(FT->getParamType(i)));
  247. }
  248. // Clear the lazy arguments bit.
  249. unsigned SDC = getSubclassDataFromValue();
  250. const_cast<Function*>(this)->setValueSubclassData(SDC &= ~(1<<0));
  251. }
  252. size_t Function::arg_size() const {
  253. return getFunctionType()->getNumParams();
  254. }
  255. bool Function::arg_empty() const {
  256. return getFunctionType()->getNumParams() == 0;
  257. }
  258. void Function::setParent(Module *parent) {
  259. Parent = parent;
  260. }
  261. // dropAllReferences() - This function causes all the subinstructions to "let
  262. // go" of all references that they are maintaining. This allows one to
  263. // 'delete' a whole class at a time, even though there may be circular
  264. // references... first all references are dropped, and all use counts go to
  265. // zero. Then everything is deleted for real. Note that no operations are
  266. // valid on an object that has "dropped all references", except operator
  267. // delete.
  268. //
  269. void Function::dropAllReferences() {
  270. setIsMaterializable(false);
  271. for (iterator I = begin(), E = end(); I != E; ++I)
  272. I->dropAllReferences();
  273. // Delete all basic blocks. They are now unused, except possibly by
  274. // blockaddresses, but BasicBlock's destructor takes care of those.
  275. while (!BasicBlocks.empty())
  276. BasicBlocks.begin()->eraseFromParent();
  277. // Prefix and prologue data are stored in a side table.
  278. setPrefixData(nullptr);
  279. setPrologueData(nullptr);
  280. // Metadata is stored in a side-table.
  281. clearMetadata();
  282. }
  283. void Function::addAttribute(unsigned i, Attribute::AttrKind attr) {
  284. AttributeSet PAL = getAttributes();
  285. PAL = PAL.addAttribute(getContext(), i, attr);
  286. setAttributes(PAL);
  287. }
  288. void Function::addAttributes(unsigned i, AttributeSet attrs) {
  289. AttributeSet PAL = getAttributes();
  290. PAL = PAL.addAttributes(getContext(), i, attrs);
  291. setAttributes(PAL);
  292. }
  293. void Function::removeAttributes(unsigned i, AttributeSet attrs) {
  294. AttributeSet PAL = getAttributes();
  295. PAL = PAL.removeAttributes(getContext(), i, attrs);
  296. setAttributes(PAL);
  297. }
  298. void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
  299. AttributeSet PAL = getAttributes();
  300. PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
  301. setAttributes(PAL);
  302. }
  303. void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
  304. AttributeSet PAL = getAttributes();
  305. PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
  306. setAttributes(PAL);
  307. }
  308. // Maintain the GC name for each function in an on-the-side table. This saves
  309. // allocating an additional word in Function for programs which do not use GC
  310. // (i.e., most programs) at the cost of increased overhead for clients which do
  311. // use GC.
  312. static DenseMap<const Function*,PooledStringPtr> *GCNames;
  313. static StringPool *GCNamePool;
  314. static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
  315. bool Function::hasGC() const {
  316. sys::SmartScopedReader<true> Reader(*GCLock);
  317. return GCNames && GCNames->count(this);
  318. }
  319. const char *Function::getGC() const {
  320. assert(hasGC() && "Function has no collector");
  321. sys::SmartScopedReader<true> Reader(*GCLock);
  322. return *(*GCNames)[this];
  323. }
  324. void Function::setGC(const char *Str) {
  325. sys::SmartScopedWriter<true> Writer(*GCLock);
  326. if (!GCNamePool)
  327. GCNamePool = new StringPool();
  328. if (!GCNames)
  329. GCNames = new DenseMap<const Function*,PooledStringPtr>();
  330. (*GCNames)[this] = GCNamePool->intern(Str);
  331. }
  332. void Function::clearGC() {
  333. sys::SmartScopedWriter<true> Writer(*GCLock);
  334. if (GCNames) {
  335. GCNames->erase(this);
  336. if (GCNames->empty()) {
  337. delete GCNames;
  338. GCNames = nullptr;
  339. if (GCNamePool->empty()) {
  340. delete GCNamePool;
  341. GCNamePool = nullptr;
  342. }
  343. }
  344. }
  345. }
  346. /// copyAttributesFrom - copy all additional attributes (those not needed to
  347. /// create a Function) from the Function Src to this one.
  348. void Function::copyAttributesFrom(const GlobalValue *Src) {
  349. assert(isa<Function>(Src) && "Expected a Function!");
  350. GlobalObject::copyAttributesFrom(Src);
  351. const Function *SrcF = cast<Function>(Src);
  352. setCallingConv(SrcF->getCallingConv());
  353. setAttributes(SrcF->getAttributes());
  354. if (SrcF->hasGC())
  355. setGC(SrcF->getGC());
  356. else
  357. clearGC();
  358. if (SrcF->hasPrefixData())
  359. setPrefixData(SrcF->getPrefixData());
  360. else
  361. setPrefixData(nullptr);
  362. if (SrcF->hasPrologueData())
  363. setPrologueData(SrcF->getPrologueData());
  364. else
  365. setPrologueData(nullptr);
  366. }
  367. /// \brief This does the actual lookup of an intrinsic ID which
  368. /// matches the given function name.
  369. static Intrinsic::ID lookupIntrinsicID(const ValueName *ValName) {
  370. unsigned Len = ValName->getKeyLength();
  371. const char *Name = ValName->getKeyData();
  372. #define GET_FUNCTION_RECOGNIZER
  373. #include "llvm/IR/Intrinsics.gen"
  374. #undef GET_FUNCTION_RECOGNIZER
  375. return Intrinsic::not_intrinsic;
  376. }
  377. void Function::recalculateIntrinsicID() {
  378. const ValueName *ValName = this->getValueName();
  379. if (!ValName || !isIntrinsic()) {
  380. IntID = Intrinsic::not_intrinsic;
  381. return;
  382. }
  383. IntID = lookupIntrinsicID(ValName);
  384. }
  385. /// Returns a stable mangling for the type specified for use in the name
  386. /// mangling scheme used by 'any' types in intrinsic signatures. The mangling
  387. /// of named types is simply their name. Manglings for unnamed types consist
  388. /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
  389. /// combined with the mangling of their component types. A vararg function
  390. /// type will have a suffix of 'vararg'. Since function types can contain
  391. /// other function types, we close a function type mangling with suffix 'f'
  392. /// which can't be confused with it's prefix. This ensures we don't have
  393. /// collisions between two unrelated function types. Otherwise, you might
  394. /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.)
  395. /// Manglings of integers, floats, and vectors ('i', 'f', and 'v' prefix in most
  396. /// cases) fall back to the MVT codepath, where they could be mangled to
  397. /// 'x86mmx', for example; matching on derived types is not sufficient to mangle
  398. /// everything.
  399. static std::string getMangledTypeStr(Type* Ty) {
  400. std::string Result;
  401. if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
  402. Result += "p" + llvm::utostr(PTyp->getAddressSpace()) +
  403. getMangledTypeStr(PTyp->getElementType());
  404. } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
  405. Result += "a" + llvm::utostr(ATyp->getNumElements()) +
  406. getMangledTypeStr(ATyp->getElementType());
  407. } else if (StructType* STyp = dyn_cast<StructType>(Ty)) {
  408. assert(!STyp->isLiteral() && "TODO: implement literal types");
  409. Result += STyp->getName();
  410. } else if (FunctionType* FT = dyn_cast<FunctionType>(Ty)) {
  411. Result += "f_" + getMangledTypeStr(FT->getReturnType());
  412. for (size_t i = 0; i < FT->getNumParams(); i++)
  413. Result += getMangledTypeStr(FT->getParamType(i));
  414. if (FT->isVarArg())
  415. Result += "vararg";
  416. // Ensure nested function types are distinguishable.
  417. Result += "f";
  418. } else if (Ty)
  419. Result += EVT::getEVT(Ty).getEVTString();
  420. return Result;
  421. }
  422. std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
  423. assert(id < num_intrinsics && "Invalid intrinsic ID!");
  424. static const char * const Table[] = {
  425. "not_intrinsic",
  426. #define GET_INTRINSIC_NAME_TABLE
  427. #include "llvm/IR/Intrinsics.gen"
  428. #undef GET_INTRINSIC_NAME_TABLE
  429. };
  430. if (Tys.empty())
  431. return Table[id];
  432. std::string Result(Table[id]);
  433. for (unsigned i = 0; i < Tys.size(); ++i) {
  434. Result += "." + getMangledTypeStr(Tys[i]);
  435. }
  436. return Result;
  437. }
  438. /// IIT_Info - These are enumerators that describe the entries returned by the
  439. /// getIntrinsicInfoTableEntries function.
  440. ///
  441. /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
  442. enum IIT_Info {
  443. // Common values should be encoded with 0-15.
  444. IIT_Done = 0,
  445. IIT_I1 = 1,
  446. IIT_I8 = 2,
  447. IIT_I16 = 3,
  448. IIT_I32 = 4,
  449. IIT_I64 = 5,
  450. IIT_F16 = 6,
  451. IIT_F32 = 7,
  452. IIT_F64 = 8,
  453. IIT_V2 = 9,
  454. IIT_V4 = 10,
  455. IIT_V8 = 11,
  456. IIT_V16 = 12,
  457. IIT_V32 = 13,
  458. IIT_PTR = 14,
  459. IIT_ARG = 15,
  460. // Values from 16+ are only encodable with the inefficient encoding.
  461. IIT_V64 = 16,
  462. IIT_MMX = 17,
  463. IIT_METADATA = 18,
  464. IIT_EMPTYSTRUCT = 19,
  465. IIT_STRUCT2 = 20,
  466. IIT_STRUCT3 = 21,
  467. IIT_STRUCT4 = 22,
  468. IIT_STRUCT5 = 23,
  469. IIT_EXTEND_ARG = 24,
  470. IIT_TRUNC_ARG = 25,
  471. IIT_ANYPTR = 26,
  472. IIT_V1 = 27,
  473. IIT_VARARG = 28,
  474. IIT_HALF_VEC_ARG = 29,
  475. IIT_SAME_VEC_WIDTH_ARG = 30,
  476. IIT_PTR_TO_ARG = 31,
  477. IIT_VEC_OF_PTRS_TO_ELT = 32
  478. };
  479. static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
  480. SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
  481. IIT_Info Info = IIT_Info(Infos[NextElt++]);
  482. unsigned StructElts = 2;
  483. using namespace Intrinsic;
  484. switch (Info) {
  485. case IIT_Done:
  486. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
  487. return;
  488. case IIT_VARARG:
  489. OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
  490. return;
  491. case IIT_MMX:
  492. OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
  493. return;
  494. case IIT_METADATA:
  495. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
  496. return;
  497. case IIT_F16:
  498. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
  499. return;
  500. case IIT_F32:
  501. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
  502. return;
  503. case IIT_F64:
  504. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
  505. return;
  506. case IIT_I1:
  507. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
  508. return;
  509. case IIT_I8:
  510. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
  511. return;
  512. case IIT_I16:
  513. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
  514. return;
  515. case IIT_I32:
  516. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
  517. return;
  518. case IIT_I64:
  519. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
  520. return;
  521. case IIT_V1:
  522. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
  523. DecodeIITType(NextElt, Infos, OutputTable);
  524. return;
  525. case IIT_V2:
  526. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
  527. DecodeIITType(NextElt, Infos, OutputTable);
  528. return;
  529. case IIT_V4:
  530. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
  531. DecodeIITType(NextElt, Infos, OutputTable);
  532. return;
  533. case IIT_V8:
  534. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
  535. DecodeIITType(NextElt, Infos, OutputTable);
  536. return;
  537. case IIT_V16:
  538. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
  539. DecodeIITType(NextElt, Infos, OutputTable);
  540. return;
  541. case IIT_V32:
  542. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
  543. DecodeIITType(NextElt, Infos, OutputTable);
  544. return;
  545. case IIT_V64:
  546. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64));
  547. DecodeIITType(NextElt, Infos, OutputTable);
  548. return;
  549. case IIT_PTR:
  550. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
  551. DecodeIITType(NextElt, Infos, OutputTable);
  552. return;
  553. case IIT_ANYPTR: { // [ANYPTR addrspace, subtype]
  554. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
  555. Infos[NextElt++]));
  556. DecodeIITType(NextElt, Infos, OutputTable);
  557. return;
  558. }
  559. case IIT_ARG: {
  560. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  561. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
  562. return;
  563. }
  564. case IIT_EXTEND_ARG: {
  565. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  566. OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
  567. ArgInfo));
  568. return;
  569. }
  570. case IIT_TRUNC_ARG: {
  571. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  572. OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
  573. ArgInfo));
  574. return;
  575. }
  576. case IIT_HALF_VEC_ARG: {
  577. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  578. OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
  579. ArgInfo));
  580. return;
  581. }
  582. case IIT_SAME_VEC_WIDTH_ARG: {
  583. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  584. OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
  585. ArgInfo));
  586. return;
  587. }
  588. case IIT_PTR_TO_ARG: {
  589. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  590. OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
  591. ArgInfo));
  592. return;
  593. }
  594. case IIT_VEC_OF_PTRS_TO_ELT: {
  595. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  596. OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfPtrsToElt,
  597. ArgInfo));
  598. return;
  599. }
  600. case IIT_EMPTYSTRUCT:
  601. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
  602. return;
  603. case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
  604. case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
  605. case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
  606. case IIT_STRUCT2: {
  607. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
  608. for (unsigned i = 0; i != StructElts; ++i)
  609. DecodeIITType(NextElt, Infos, OutputTable);
  610. return;
  611. }
  612. }
  613. llvm_unreachable("unhandled");
  614. }
  615. #define GET_INTRINSIC_GENERATOR_GLOBAL
  616. #include "llvm/IR/Intrinsics.gen"
  617. #undef GET_INTRINSIC_GENERATOR_GLOBAL
  618. void Intrinsic::getIntrinsicInfoTableEntries(ID id,
  619. SmallVectorImpl<IITDescriptor> &T){
  620. // Check to see if the intrinsic's type was expressible by the table.
  621. unsigned TableVal = IIT_Table[id-1];
  622. // Decode the TableVal into an array of IITValues.
  623. SmallVector<unsigned char, 8> IITValues;
  624. ArrayRef<unsigned char> IITEntries;
  625. unsigned NextElt = 0;
  626. if ((TableVal >> 31) != 0) {
  627. // This is an offset into the IIT_LongEncodingTable.
  628. IITEntries = IIT_LongEncodingTable;
  629. // Strip sentinel bit.
  630. NextElt = (TableVal << 1) >> 1;
  631. } else {
  632. // Decode the TableVal into an array of IITValues. If the entry was encoded
  633. // into a single word in the table itself, decode it now.
  634. do {
  635. IITValues.push_back(TableVal & 0xF);
  636. TableVal >>= 4;
  637. } while (TableVal);
  638. IITEntries = IITValues;
  639. NextElt = 0;
  640. }
  641. // Okay, decode the table into the output vector of IITDescriptors.
  642. DecodeIITType(NextElt, IITEntries, T);
  643. while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
  644. DecodeIITType(NextElt, IITEntries, T);
  645. }
  646. static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
  647. ArrayRef<Type*> Tys, LLVMContext &Context) {
  648. using namespace Intrinsic;
  649. IITDescriptor D = Infos.front();
  650. Infos = Infos.slice(1);
  651. switch (D.Kind) {
  652. case IITDescriptor::Void: return Type::getVoidTy(Context);
  653. case IITDescriptor::VarArg: return Type::getVoidTy(Context);
  654. case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
  655. case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
  656. case IITDescriptor::Half: return Type::getHalfTy(Context);
  657. case IITDescriptor::Float: return Type::getFloatTy(Context);
  658. case IITDescriptor::Double: return Type::getDoubleTy(Context);
  659. case IITDescriptor::Integer:
  660. return IntegerType::get(Context, D.Integer_Width);
  661. case IITDescriptor::Vector:
  662. return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
  663. case IITDescriptor::Pointer:
  664. return PointerType::get(DecodeFixedType(Infos, Tys, Context),
  665. D.Pointer_AddressSpace);
  666. case IITDescriptor::Struct: {
  667. Type *Elts[5];
  668. assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
  669. for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
  670. Elts[i] = DecodeFixedType(Infos, Tys, Context);
  671. return StructType::get(Context, makeArrayRef(Elts,D.Struct_NumElements));
  672. }
  673. case IITDescriptor::Argument:
  674. return Tys[D.getArgumentNumber()];
  675. case IITDescriptor::ExtendArgument: {
  676. Type *Ty = Tys[D.getArgumentNumber()];
  677. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  678. return VectorType::getExtendedElementVectorType(VTy);
  679. return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
  680. }
  681. case IITDescriptor::TruncArgument: {
  682. Type *Ty = Tys[D.getArgumentNumber()];
  683. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  684. return VectorType::getTruncatedElementVectorType(VTy);
  685. IntegerType *ITy = cast<IntegerType>(Ty);
  686. assert(ITy->getBitWidth() % 2 == 0);
  687. return IntegerType::get(Context, ITy->getBitWidth() / 2);
  688. }
  689. case IITDescriptor::HalfVecArgument:
  690. return VectorType::getHalfElementsVectorType(cast<VectorType>(
  691. Tys[D.getArgumentNumber()]));
  692. case IITDescriptor::SameVecWidthArgument: {
  693. Type *EltTy = DecodeFixedType(Infos, Tys, Context);
  694. Type *Ty = Tys[D.getArgumentNumber()];
  695. if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
  696. return VectorType::get(EltTy, VTy->getNumElements());
  697. }
  698. llvm_unreachable("unhandled");
  699. }
  700. case IITDescriptor::PtrToArgument: {
  701. Type *Ty = Tys[D.getArgumentNumber()];
  702. return PointerType::getUnqual(Ty);
  703. }
  704. case IITDescriptor::VecOfPtrsToElt: {
  705. Type *Ty = Tys[D.getArgumentNumber()];
  706. VectorType *VTy = dyn_cast<VectorType>(Ty);
  707. if (!VTy)
  708. llvm_unreachable("Expected an argument of Vector Type");
  709. Type *EltTy = VTy->getVectorElementType();
  710. return VectorType::get(PointerType::getUnqual(EltTy),
  711. VTy->getNumElements());
  712. }
  713. }
  714. llvm_unreachable("unhandled");
  715. }
  716. FunctionType *Intrinsic::getType(LLVMContext &Context,
  717. ID id, ArrayRef<Type*> Tys) {
  718. SmallVector<IITDescriptor, 8> Table;
  719. getIntrinsicInfoTableEntries(id, Table);
  720. ArrayRef<IITDescriptor> TableRef = Table;
  721. Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
  722. SmallVector<Type*, 8> ArgTys;
  723. while (!TableRef.empty())
  724. ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
  725. // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
  726. // If we see void type as the type of the last argument, it is vararg intrinsic
  727. if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
  728. ArgTys.pop_back();
  729. return FunctionType::get(ResultTy, ArgTys, true);
  730. }
  731. return FunctionType::get(ResultTy, ArgTys, false);
  732. }
  733. bool Intrinsic::isOverloaded(ID id) {
  734. #define GET_INTRINSIC_OVERLOAD_TABLE
  735. #include "llvm/IR/Intrinsics.gen"
  736. #undef GET_INTRINSIC_OVERLOAD_TABLE
  737. }
  738. /// This defines the "Intrinsic::getAttributes(ID id)" method.
  739. #define GET_INTRINSIC_ATTRIBUTES
  740. #include "llvm/IR/Intrinsics.gen"
  741. #undef GET_INTRINSIC_ATTRIBUTES
  742. Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
  743. // There can never be multiple globals with the same name of different types,
  744. // because intrinsics must be a specific type.
  745. return
  746. cast<Function>(M->getOrInsertFunction(getName(id, Tys),
  747. getType(M->getContext(), id, Tys)));
  748. }
  749. // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
  750. #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
  751. #include "llvm/IR/Intrinsics.gen"
  752. #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
  753. // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
  754. #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
  755. #include "llvm/IR/Intrinsics.gen"
  756. #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
  757. /// hasAddressTaken - returns true if there are any uses of this function
  758. /// other than direct calls or invokes to it.
  759. bool Function::hasAddressTaken(const User* *PutOffender) const {
  760. for (const Use &U : uses()) {
  761. const User *FU = U.getUser();
  762. if (isa<BlockAddress>(FU))
  763. continue;
  764. if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU))
  765. return PutOffender ? (*PutOffender = FU, true) : true;
  766. ImmutableCallSite CS(cast<Instruction>(FU));
  767. if (!CS.isCallee(&U))
  768. return PutOffender ? (*PutOffender = FU, true) : true;
  769. }
  770. return false;
  771. }
  772. bool Function::isDefTriviallyDead() const {
  773. // Check the linkage
  774. if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
  775. !hasAvailableExternallyLinkage())
  776. return false;
  777. // Check if the function is used by anything other than a blockaddress.
  778. for (const User *U : users())
  779. if (!isa<BlockAddress>(U))
  780. return false;
  781. return true;
  782. }
  783. /// callsFunctionThatReturnsTwice - Return true if the function has a call to
  784. /// setjmp or other function that gcc recognizes as "returning twice".
  785. bool Function::callsFunctionThatReturnsTwice() const {
  786. for (const_inst_iterator
  787. I = inst_begin(this), E = inst_end(this); I != E; ++I) {
  788. ImmutableCallSite CS(&*I);
  789. if (CS && CS.hasFnAttr(Attribute::ReturnsTwice))
  790. return true;
  791. }
  792. return false;
  793. }
  794. Constant *Function::getPrefixData() const {
  795. assert(hasPrefixData());
  796. const LLVMContextImpl::PrefixDataMapTy &PDMap =
  797. getContext().pImpl->PrefixDataMap;
  798. assert(PDMap.find(this) != PDMap.end());
  799. return cast<Constant>(PDMap.find(this)->second->getReturnValue());
  800. }
  801. void Function::setPrefixData(Constant *PrefixData) {
  802. if (!PrefixData && !hasPrefixData())
  803. return;
  804. unsigned SCData = getSubclassDataFromValue();
  805. LLVMContextImpl::PrefixDataMapTy &PDMap = getContext().pImpl->PrefixDataMap;
  806. ReturnInst *&PDHolder = PDMap[this];
  807. if (PrefixData) {
  808. if (PDHolder)
  809. PDHolder->setOperand(0, PrefixData);
  810. else
  811. PDHolder = ReturnInst::Create(getContext(), PrefixData);
  812. SCData |= (1<<1);
  813. } else {
  814. delete PDHolder;
  815. PDMap.erase(this);
  816. SCData &= ~(1<<1);
  817. }
  818. setValueSubclassData(SCData);
  819. }
  820. Constant *Function::getPrologueData() const {
  821. assert(hasPrologueData());
  822. const LLVMContextImpl::PrologueDataMapTy &SOMap =
  823. getContext().pImpl->PrologueDataMap;
  824. assert(SOMap.find(this) != SOMap.end());
  825. return cast<Constant>(SOMap.find(this)->second->getReturnValue());
  826. }
  827. void Function::setPrologueData(Constant *PrologueData) {
  828. if (!PrologueData && !hasPrologueData())
  829. return;
  830. unsigned PDData = getSubclassDataFromValue();
  831. LLVMContextImpl::PrologueDataMapTy &PDMap = getContext().pImpl->PrologueDataMap;
  832. ReturnInst *&PDHolder = PDMap[this];
  833. if (PrologueData) {
  834. if (PDHolder)
  835. PDHolder->setOperand(0, PrologueData);
  836. else
  837. PDHolder = ReturnInst::Create(getContext(), PrologueData);
  838. PDData |= (1<<2);
  839. } else {
  840. delete PDHolder;
  841. PDMap.erase(this);
  842. PDData &= ~(1<<2);
  843. }
  844. setValueSubclassData(PDData);
  845. }
  846. void Function::setEntryCount(uint64_t Count) {
  847. MDBuilder MDB(getContext());
  848. setMetadata(LLVMContext::MD_prof, MDB.createFunctionEntryCount(Count));
  849. }
  850. Optional<uint64_t> Function::getEntryCount() const {
  851. MDNode *MD = getMetadata(LLVMContext::MD_prof);
  852. if (MD && MD->getOperand(0))
  853. if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
  854. if (MDS->getString().equals("function_entry_count")) {
  855. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
  856. return CI->getValue().getZExtValue();
  857. }
  858. return None;
  859. }