Function.cpp 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  1. //===- Function.cpp - Implement the Global object classes -----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Function class for the IR library.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/IR/Function.h"
  13. #include "SymbolTableListTraitsImpl.h"
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/DenseSet.h"
  16. #include "llvm/ADT/None.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SmallString.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/IR/Argument.h"
  23. #include "llvm/IR/Attributes.h"
  24. #include "llvm/IR/BasicBlock.h"
  25. #include "llvm/IR/Constant.h"
  26. #include "llvm/IR/Constants.h"
  27. #include "llvm/IR/DerivedTypes.h"
  28. #include "llvm/IR/GlobalValue.h"
  29. #include "llvm/IR/InstIterator.h"
  30. #include "llvm/IR/Instruction.h"
  31. #include "llvm/IR/Instructions.h"
  32. #include "llvm/IR/IntrinsicInst.h"
  33. #include "llvm/IR/Intrinsics.h"
  34. #include "llvm/IR/LLVMContext.h"
  35. #include "llvm/IR/MDBuilder.h"
  36. #include "llvm/IR/Metadata.h"
  37. #include "llvm/IR/Module.h"
  38. #include "llvm/IR/SymbolTableListTraits.h"
  39. #include "llvm/IR/Type.h"
  40. #include "llvm/IR/Use.h"
  41. #include "llvm/IR/User.h"
  42. #include "llvm/IR/Value.h"
  43. #include "llvm/IR/ValueSymbolTable.h"
  44. #include "llvm/Support/Casting.h"
  45. #include "llvm/Support/Compiler.h"
  46. #include "llvm/Support/ErrorHandling.h"
  47. #include <algorithm>
  48. #include <cassert>
  49. #include <cstddef>
  50. #include <cstdint>
  51. #include <cstring>
  52. #include <string>
  53. using namespace llvm;
  54. using ProfileCount = Function::ProfileCount;
  55. // Explicit instantiations of SymbolTableListTraits since some of the methods
  56. // are not in the public header file...
  57. template class llvm::SymbolTableListTraits<BasicBlock>;
  58. //===----------------------------------------------------------------------===//
  59. // Argument Implementation
  60. //===----------------------------------------------------------------------===//
  61. Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo)
  62. : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) {
  63. setName(Name);
  64. }
  65. void Argument::setParent(Function *parent) {
  66. Parent = parent;
  67. }
  68. bool Argument::hasNonNullAttr() const {
  69. if (!getType()->isPointerTy()) return false;
  70. if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull))
  71. return true;
  72. else if (getDereferenceableBytes() > 0 &&
  73. !NullPointerIsDefined(getParent(),
  74. getType()->getPointerAddressSpace()))
  75. return true;
  76. return false;
  77. }
  78. bool Argument::hasByValAttr() const {
  79. if (!getType()->isPointerTy()) return false;
  80. return hasAttribute(Attribute::ByVal);
  81. }
  82. bool Argument::hasSwiftSelfAttr() const {
  83. return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf);
  84. }
  85. bool Argument::hasSwiftErrorAttr() const {
  86. return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError);
  87. }
  88. bool Argument::hasInAllocaAttr() const {
  89. if (!getType()->isPointerTy()) return false;
  90. return hasAttribute(Attribute::InAlloca);
  91. }
  92. bool Argument::hasByValOrInAllocaAttr() const {
  93. if (!getType()->isPointerTy()) return false;
  94. AttributeList Attrs = getParent()->getAttributes();
  95. return Attrs.hasParamAttribute(getArgNo(), Attribute::ByVal) ||
  96. Attrs.hasParamAttribute(getArgNo(), Attribute::InAlloca);
  97. }
  98. unsigned Argument::getParamAlignment() const {
  99. assert(getType()->isPointerTy() && "Only pointers have alignments");
  100. return getParent()->getParamAlignment(getArgNo());
  101. }
  102. Type *Argument::getParamByValType() const {
  103. assert(getType()->isPointerTy() && "Only pointers have byval types");
  104. return getParent()->getParamByValType(getArgNo());
  105. }
  106. uint64_t Argument::getDereferenceableBytes() const {
  107. assert(getType()->isPointerTy() &&
  108. "Only pointers have dereferenceable bytes");
  109. return getParent()->getParamDereferenceableBytes(getArgNo());
  110. }
  111. uint64_t Argument::getDereferenceableOrNullBytes() const {
  112. assert(getType()->isPointerTy() &&
  113. "Only pointers have dereferenceable bytes");
  114. return getParent()->getParamDereferenceableOrNullBytes(getArgNo());
  115. }
  116. bool Argument::hasNestAttr() const {
  117. if (!getType()->isPointerTy()) return false;
  118. return hasAttribute(Attribute::Nest);
  119. }
  120. bool Argument::hasNoAliasAttr() const {
  121. if (!getType()->isPointerTy()) return false;
  122. return hasAttribute(Attribute::NoAlias);
  123. }
  124. bool Argument::hasNoCaptureAttr() const {
  125. if (!getType()->isPointerTy()) return false;
  126. return hasAttribute(Attribute::NoCapture);
  127. }
  128. bool Argument::hasStructRetAttr() const {
  129. if (!getType()->isPointerTy()) return false;
  130. return hasAttribute(Attribute::StructRet);
  131. }
  132. bool Argument::hasInRegAttr() const {
  133. return hasAttribute(Attribute::InReg);
  134. }
  135. bool Argument::hasReturnedAttr() const {
  136. return hasAttribute(Attribute::Returned);
  137. }
  138. bool Argument::hasZExtAttr() const {
  139. return hasAttribute(Attribute::ZExt);
  140. }
  141. bool Argument::hasSExtAttr() const {
  142. return hasAttribute(Attribute::SExt);
  143. }
  144. bool Argument::onlyReadsMemory() const {
  145. AttributeList Attrs = getParent()->getAttributes();
  146. return Attrs.hasParamAttribute(getArgNo(), Attribute::ReadOnly) ||
  147. Attrs.hasParamAttribute(getArgNo(), Attribute::ReadNone);
  148. }
  149. void Argument::addAttrs(AttrBuilder &B) {
  150. AttributeList AL = getParent()->getAttributes();
  151. AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B);
  152. getParent()->setAttributes(AL);
  153. }
  154. void Argument::addAttr(Attribute::AttrKind Kind) {
  155. getParent()->addParamAttr(getArgNo(), Kind);
  156. }
  157. void Argument::addAttr(Attribute Attr) {
  158. getParent()->addParamAttr(getArgNo(), Attr);
  159. }
  160. void Argument::removeAttr(Attribute::AttrKind Kind) {
  161. getParent()->removeParamAttr(getArgNo(), Kind);
  162. }
  163. bool Argument::hasAttribute(Attribute::AttrKind Kind) const {
  164. return getParent()->hasParamAttribute(getArgNo(), Kind);
  165. }
  166. Attribute Argument::getAttribute(Attribute::AttrKind Kind) const {
  167. return getParent()->getParamAttribute(getArgNo(), Kind);
  168. }
  169. //===----------------------------------------------------------------------===//
  170. // Helper Methods in Function
  171. //===----------------------------------------------------------------------===//
  172. LLVMContext &Function::getContext() const {
  173. return getType()->getContext();
  174. }
  175. unsigned Function::getInstructionCount() const {
  176. unsigned NumInstrs = 0;
  177. for (const BasicBlock &BB : BasicBlocks)
  178. NumInstrs += std::distance(BB.instructionsWithoutDebug().begin(),
  179. BB.instructionsWithoutDebug().end());
  180. return NumInstrs;
  181. }
  182. Function *Function::Create(FunctionType *Ty, LinkageTypes Linkage,
  183. const Twine &N, Module &M) {
  184. return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M);
  185. }
  186. void Function::removeFromParent() {
  187. getParent()->getFunctionList().remove(getIterator());
  188. }
  189. void Function::eraseFromParent() {
  190. getParent()->getFunctionList().erase(getIterator());
  191. }
  192. //===----------------------------------------------------------------------===//
  193. // Function Implementation
  194. //===----------------------------------------------------------------------===//
  195. static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) {
  196. // If AS == -1 and we are passed a valid module pointer we place the function
  197. // in the program address space. Otherwise we default to AS0.
  198. if (AddrSpace == static_cast<unsigned>(-1))
  199. return M ? M->getDataLayout().getProgramAddressSpace() : 0;
  200. return AddrSpace;
  201. }
  202. Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,
  203. const Twine &name, Module *ParentModule)
  204. : GlobalObject(Ty, Value::FunctionVal,
  205. OperandTraits<Function>::op_begin(this), 0, Linkage, name,
  206. computeAddrSpace(AddrSpace, ParentModule)),
  207. NumArgs(Ty->getNumParams()) {
  208. assert(FunctionType::isValidReturnType(getReturnType()) &&
  209. "invalid return type");
  210. setGlobalObjectSubClassData(0);
  211. // We only need a symbol table for a function if the context keeps value names
  212. if (!getContext().shouldDiscardValueNames())
  213. SymTab = make_unique<ValueSymbolTable>();
  214. // If the function has arguments, mark them as lazily built.
  215. if (Ty->getNumParams())
  216. setValueSubclassData(1); // Set the "has lazy arguments" bit.
  217. if (ParentModule)
  218. ParentModule->getFunctionList().push_back(this);
  219. HasLLVMReservedName = getName().startswith("llvm.");
  220. // Ensure intrinsics have the right parameter attributes.
  221. // Note, the IntID field will have been set in Value::setName if this function
  222. // name is a valid intrinsic ID.
  223. if (IntID)
  224. setAttributes(Intrinsic::getAttributes(getContext(), IntID));
  225. }
  226. Function::~Function() {
  227. dropAllReferences(); // After this it is safe to delete instructions.
  228. // Delete all of the method arguments and unlink from symbol table...
  229. if (Arguments)
  230. clearArguments();
  231. // Remove the function from the on-the-side GC table.
  232. clearGC();
  233. }
  234. void Function::BuildLazyArguments() const {
  235. // Create the arguments vector, all arguments start out unnamed.
  236. auto *FT = getFunctionType();
  237. if (NumArgs > 0) {
  238. Arguments = std::allocator<Argument>().allocate(NumArgs);
  239. for (unsigned i = 0, e = NumArgs; i != e; ++i) {
  240. Type *ArgTy = FT->getParamType(i);
  241. assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!");
  242. new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i);
  243. }
  244. }
  245. // Clear the lazy arguments bit.
  246. unsigned SDC = getSubclassDataFromValue();
  247. const_cast<Function*>(this)->setValueSubclassData(SDC &= ~(1<<0));
  248. assert(!hasLazyArguments());
  249. }
  250. static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) {
  251. return MutableArrayRef<Argument>(Args, Count);
  252. }
  253. void Function::clearArguments() {
  254. for (Argument &A : makeArgArray(Arguments, NumArgs)) {
  255. A.setName("");
  256. A.~Argument();
  257. }
  258. std::allocator<Argument>().deallocate(Arguments, NumArgs);
  259. Arguments = nullptr;
  260. }
  261. void Function::stealArgumentListFrom(Function &Src) {
  262. assert(isDeclaration() && "Expected no references to current arguments");
  263. // Drop the current arguments, if any, and set the lazy argument bit.
  264. if (!hasLazyArguments()) {
  265. assert(llvm::all_of(makeArgArray(Arguments, NumArgs),
  266. [](const Argument &A) { return A.use_empty(); }) &&
  267. "Expected arguments to be unused in declaration");
  268. clearArguments();
  269. setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
  270. }
  271. // Nothing to steal if Src has lazy arguments.
  272. if (Src.hasLazyArguments())
  273. return;
  274. // Steal arguments from Src, and fix the lazy argument bits.
  275. assert(arg_size() == Src.arg_size());
  276. Arguments = Src.Arguments;
  277. Src.Arguments = nullptr;
  278. for (Argument &A : makeArgArray(Arguments, NumArgs)) {
  279. // FIXME: This does the work of transferNodesFromList inefficiently.
  280. SmallString<128> Name;
  281. if (A.hasName())
  282. Name = A.getName();
  283. if (!Name.empty())
  284. A.setName("");
  285. A.setParent(this);
  286. if (!Name.empty())
  287. A.setName(Name);
  288. }
  289. setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
  290. assert(!hasLazyArguments());
  291. Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));
  292. }
  293. // dropAllReferences() - This function causes all the subinstructions to "let
  294. // go" of all references that they are maintaining. This allows one to
  295. // 'delete' a whole class at a time, even though there may be circular
  296. // references... first all references are dropped, and all use counts go to
  297. // zero. Then everything is deleted for real. Note that no operations are
  298. // valid on an object that has "dropped all references", except operator
  299. // delete.
  300. //
  301. void Function::dropAllReferences() {
  302. setIsMaterializable(false);
  303. for (BasicBlock &BB : *this)
  304. BB.dropAllReferences();
  305. // Delete all basic blocks. They are now unused, except possibly by
  306. // blockaddresses, but BasicBlock's destructor takes care of those.
  307. while (!BasicBlocks.empty())
  308. BasicBlocks.begin()->eraseFromParent();
  309. // Drop uses of any optional data (real or placeholder).
  310. if (getNumOperands()) {
  311. User::dropAllReferences();
  312. setNumHungOffUseOperands(0);
  313. setValueSubclassData(getSubclassDataFromValue() & ~0xe);
  314. }
  315. // Metadata is stored in a side-table.
  316. clearMetadata();
  317. }
  318. void Function::addAttribute(unsigned i, Attribute::AttrKind Kind) {
  319. AttributeList PAL = getAttributes();
  320. PAL = PAL.addAttribute(getContext(), i, Kind);
  321. setAttributes(PAL);
  322. }
  323. void Function::addAttribute(unsigned i, Attribute Attr) {
  324. AttributeList PAL = getAttributes();
  325. PAL = PAL.addAttribute(getContext(), i, Attr);
  326. setAttributes(PAL);
  327. }
  328. void Function::addAttributes(unsigned i, const AttrBuilder &Attrs) {
  329. AttributeList PAL = getAttributes();
  330. PAL = PAL.addAttributes(getContext(), i, Attrs);
  331. setAttributes(PAL);
  332. }
  333. void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
  334. AttributeList PAL = getAttributes();
  335. PAL = PAL.addParamAttribute(getContext(), ArgNo, Kind);
  336. setAttributes(PAL);
  337. }
  338. void Function::addParamAttr(unsigned ArgNo, Attribute Attr) {
  339. AttributeList PAL = getAttributes();
  340. PAL = PAL.addParamAttribute(getContext(), ArgNo, Attr);
  341. setAttributes(PAL);
  342. }
  343. void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
  344. AttributeList PAL = getAttributes();
  345. PAL = PAL.addParamAttributes(getContext(), ArgNo, Attrs);
  346. setAttributes(PAL);
  347. }
  348. void Function::removeAttribute(unsigned i, Attribute::AttrKind Kind) {
  349. AttributeList PAL = getAttributes();
  350. PAL = PAL.removeAttribute(getContext(), i, Kind);
  351. setAttributes(PAL);
  352. }
  353. void Function::removeAttribute(unsigned i, StringRef Kind) {
  354. AttributeList PAL = getAttributes();
  355. PAL = PAL.removeAttribute(getContext(), i, Kind);
  356. setAttributes(PAL);
  357. }
  358. void Function::removeAttributes(unsigned i, const AttrBuilder &Attrs) {
  359. AttributeList PAL = getAttributes();
  360. PAL = PAL.removeAttributes(getContext(), i, Attrs);
  361. setAttributes(PAL);
  362. }
  363. void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
  364. AttributeList PAL = getAttributes();
  365. PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
  366. setAttributes(PAL);
  367. }
  368. void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) {
  369. AttributeList PAL = getAttributes();
  370. PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
  371. setAttributes(PAL);
  372. }
  373. void Function::removeParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
  374. AttributeList PAL = getAttributes();
  375. PAL = PAL.removeParamAttributes(getContext(), ArgNo, Attrs);
  376. setAttributes(PAL);
  377. }
  378. void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
  379. AttributeList PAL = getAttributes();
  380. PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
  381. setAttributes(PAL);
  382. }
  383. void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) {
  384. AttributeList PAL = getAttributes();
  385. PAL = PAL.addDereferenceableParamAttr(getContext(), ArgNo, Bytes);
  386. setAttributes(PAL);
  387. }
  388. void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
  389. AttributeList PAL = getAttributes();
  390. PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
  391. setAttributes(PAL);
  392. }
  393. void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo,
  394. uint64_t Bytes) {
  395. AttributeList PAL = getAttributes();
  396. PAL = PAL.addDereferenceableOrNullParamAttr(getContext(), ArgNo, Bytes);
  397. setAttributes(PAL);
  398. }
  399. const std::string &Function::getGC() const {
  400. assert(hasGC() && "Function has no collector");
  401. return getContext().getGC(*this);
  402. }
  403. void Function::setGC(std::string Str) {
  404. setValueSubclassDataBit(14, !Str.empty());
  405. getContext().setGC(*this, std::move(Str));
  406. }
  407. void Function::clearGC() {
  408. if (!hasGC())
  409. return;
  410. getContext().deleteGC(*this);
  411. setValueSubclassDataBit(14, false);
  412. }
  413. /// Copy all additional attributes (those not needed to create a Function) from
  414. /// the Function Src to this one.
  415. void Function::copyAttributesFrom(const Function *Src) {
  416. GlobalObject::copyAttributesFrom(Src);
  417. setCallingConv(Src->getCallingConv());
  418. setAttributes(Src->getAttributes());
  419. if (Src->hasGC())
  420. setGC(Src->getGC());
  421. else
  422. clearGC();
  423. if (Src->hasPersonalityFn())
  424. setPersonalityFn(Src->getPersonalityFn());
  425. if (Src->hasPrefixData())
  426. setPrefixData(Src->getPrefixData());
  427. if (Src->hasPrologueData())
  428. setPrologueData(Src->getPrologueData());
  429. }
  430. /// Table of string intrinsic names indexed by enum value.
  431. static const char * const IntrinsicNameTable[] = {
  432. "not_intrinsic",
  433. #define GET_INTRINSIC_NAME_TABLE
  434. #include "llvm/IR/IntrinsicImpl.inc"
  435. #undef GET_INTRINSIC_NAME_TABLE
  436. };
  437. /// Table of per-target intrinsic name tables.
  438. #define GET_INTRINSIC_TARGET_DATA
  439. #include "llvm/IR/IntrinsicImpl.inc"
  440. #undef GET_INTRINSIC_TARGET_DATA
  441. /// Find the segment of \c IntrinsicNameTable for intrinsics with the same
  442. /// target as \c Name, or the generic table if \c Name is not target specific.
  443. ///
  444. /// Returns the relevant slice of \c IntrinsicNameTable
  445. static ArrayRef<const char *> findTargetSubtable(StringRef Name) {
  446. assert(Name.startswith("llvm."));
  447. ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos);
  448. // Drop "llvm." and take the first dotted component. That will be the target
  449. // if this is target specific.
  450. StringRef Target = Name.drop_front(5).split('.').first;
  451. auto It = std::lower_bound(Targets.begin(), Targets.end(), Target,
  452. [](const IntrinsicTargetInfo &TI,
  453. StringRef Target) { return TI.Name < Target; });
  454. // We've either found the target or just fall back to the generic set, which
  455. // is always first.
  456. const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0];
  457. return makeArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count);
  458. }
  459. /// This does the actual lookup of an intrinsic ID which
  460. /// matches the given function name.
  461. Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) {
  462. ArrayRef<const char *> NameTable = findTargetSubtable(Name);
  463. int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name);
  464. if (Idx == -1)
  465. return Intrinsic::not_intrinsic;
  466. // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have
  467. // an index into a sub-table.
  468. int Adjust = NameTable.data() - IntrinsicNameTable;
  469. Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust);
  470. // If the intrinsic is not overloaded, require an exact match. If it is
  471. // overloaded, require either exact or prefix match.
  472. const auto MatchSize = strlen(NameTable[Idx]);
  473. assert(Name.size() >= MatchSize && "Expected either exact or prefix match");
  474. bool IsExactMatch = Name.size() == MatchSize;
  475. return IsExactMatch || isOverloaded(ID) ? ID : Intrinsic::not_intrinsic;
  476. }
  477. void Function::recalculateIntrinsicID() {
  478. StringRef Name = getName();
  479. if (!Name.startswith("llvm.")) {
  480. HasLLVMReservedName = false;
  481. IntID = Intrinsic::not_intrinsic;
  482. return;
  483. }
  484. HasLLVMReservedName = true;
  485. IntID = lookupIntrinsicID(Name);
  486. }
  487. /// Returns a stable mangling for the type specified for use in the name
  488. /// mangling scheme used by 'any' types in intrinsic signatures. The mangling
  489. /// of named types is simply their name. Manglings for unnamed types consist
  490. /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
  491. /// combined with the mangling of their component types. A vararg function
  492. /// type will have a suffix of 'vararg'. Since function types can contain
  493. /// other function types, we close a function type mangling with suffix 'f'
  494. /// which can't be confused with it's prefix. This ensures we don't have
  495. /// collisions between two unrelated function types. Otherwise, you might
  496. /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.)
  497. ///
  498. static std::string getMangledTypeStr(Type* Ty) {
  499. std::string Result;
  500. if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
  501. Result += "p" + utostr(PTyp->getAddressSpace()) +
  502. getMangledTypeStr(PTyp->getElementType());
  503. } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
  504. Result += "a" + utostr(ATyp->getNumElements()) +
  505. getMangledTypeStr(ATyp->getElementType());
  506. } else if (StructType *STyp = dyn_cast<StructType>(Ty)) {
  507. if (!STyp->isLiteral()) {
  508. Result += "s_";
  509. Result += STyp->getName();
  510. } else {
  511. Result += "sl_";
  512. for (auto Elem : STyp->elements())
  513. Result += getMangledTypeStr(Elem);
  514. }
  515. // Ensure nested structs are distinguishable.
  516. Result += "s";
  517. } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) {
  518. Result += "f_" + getMangledTypeStr(FT->getReturnType());
  519. for (size_t i = 0; i < FT->getNumParams(); i++)
  520. Result += getMangledTypeStr(FT->getParamType(i));
  521. if (FT->isVarArg())
  522. Result += "vararg";
  523. // Ensure nested function types are distinguishable.
  524. Result += "f";
  525. } else if (isa<VectorType>(Ty)) {
  526. Result += "v" + utostr(Ty->getVectorNumElements()) +
  527. getMangledTypeStr(Ty->getVectorElementType());
  528. } else if (Ty) {
  529. switch (Ty->getTypeID()) {
  530. default: llvm_unreachable("Unhandled type");
  531. case Type::VoidTyID: Result += "isVoid"; break;
  532. case Type::MetadataTyID: Result += "Metadata"; break;
  533. case Type::HalfTyID: Result += "f16"; break;
  534. case Type::FloatTyID: Result += "f32"; break;
  535. case Type::DoubleTyID: Result += "f64"; break;
  536. case Type::X86_FP80TyID: Result += "f80"; break;
  537. case Type::FP128TyID: Result += "f128"; break;
  538. case Type::PPC_FP128TyID: Result += "ppcf128"; break;
  539. case Type::X86_MMXTyID: Result += "x86mmx"; break;
  540. case Type::IntegerTyID:
  541. Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth());
  542. break;
  543. }
  544. }
  545. return Result;
  546. }
  547. StringRef Intrinsic::getName(ID id) {
  548. assert(id < num_intrinsics && "Invalid intrinsic ID!");
  549. assert(!isOverloaded(id) &&
  550. "This version of getName does not support overloading");
  551. return IntrinsicNameTable[id];
  552. }
  553. std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
  554. assert(id < num_intrinsics && "Invalid intrinsic ID!");
  555. std::string Result(IntrinsicNameTable[id]);
  556. for (Type *Ty : Tys) {
  557. Result += "." + getMangledTypeStr(Ty);
  558. }
  559. return Result;
  560. }
  561. /// IIT_Info - These are enumerators that describe the entries returned by the
  562. /// getIntrinsicInfoTableEntries function.
  563. ///
  564. /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
  565. enum IIT_Info {
  566. // Common values should be encoded with 0-15.
  567. IIT_Done = 0,
  568. IIT_I1 = 1,
  569. IIT_I8 = 2,
  570. IIT_I16 = 3,
  571. IIT_I32 = 4,
  572. IIT_I64 = 5,
  573. IIT_F16 = 6,
  574. IIT_F32 = 7,
  575. IIT_F64 = 8,
  576. IIT_V2 = 9,
  577. IIT_V4 = 10,
  578. IIT_V8 = 11,
  579. IIT_V16 = 12,
  580. IIT_V32 = 13,
  581. IIT_PTR = 14,
  582. IIT_ARG = 15,
  583. // Values from 16+ are only encodable with the inefficient encoding.
  584. IIT_V64 = 16,
  585. IIT_MMX = 17,
  586. IIT_TOKEN = 18,
  587. IIT_METADATA = 19,
  588. IIT_EMPTYSTRUCT = 20,
  589. IIT_STRUCT2 = 21,
  590. IIT_STRUCT3 = 22,
  591. IIT_STRUCT4 = 23,
  592. IIT_STRUCT5 = 24,
  593. IIT_EXTEND_ARG = 25,
  594. IIT_TRUNC_ARG = 26,
  595. IIT_ANYPTR = 27,
  596. IIT_V1 = 28,
  597. IIT_VARARG = 29,
  598. IIT_HALF_VEC_ARG = 30,
  599. IIT_SAME_VEC_WIDTH_ARG = 31,
  600. IIT_PTR_TO_ARG = 32,
  601. IIT_PTR_TO_ELT = 33,
  602. IIT_VEC_OF_ANYPTRS_TO_ELT = 34,
  603. IIT_I128 = 35,
  604. IIT_V512 = 36,
  605. IIT_V1024 = 37,
  606. IIT_STRUCT6 = 38,
  607. IIT_STRUCT7 = 39,
  608. IIT_STRUCT8 = 40,
  609. IIT_F128 = 41,
  610. IIT_VEC_ELEMENT = 42
  611. };
  612. static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
  613. SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
  614. using namespace Intrinsic;
  615. IIT_Info Info = IIT_Info(Infos[NextElt++]);
  616. unsigned StructElts = 2;
  617. switch (Info) {
  618. case IIT_Done:
  619. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
  620. return;
  621. case IIT_VARARG:
  622. OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
  623. return;
  624. case IIT_MMX:
  625. OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
  626. return;
  627. case IIT_TOKEN:
  628. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
  629. return;
  630. case IIT_METADATA:
  631. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
  632. return;
  633. case IIT_F16:
  634. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
  635. return;
  636. case IIT_F32:
  637. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
  638. return;
  639. case IIT_F64:
  640. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
  641. return;
  642. case IIT_F128:
  643. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0));
  644. return;
  645. case IIT_I1:
  646. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
  647. return;
  648. case IIT_I8:
  649. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
  650. return;
  651. case IIT_I16:
  652. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
  653. return;
  654. case IIT_I32:
  655. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
  656. return;
  657. case IIT_I64:
  658. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
  659. return;
  660. case IIT_I128:
  661. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
  662. return;
  663. case IIT_V1:
  664. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
  665. DecodeIITType(NextElt, Infos, OutputTable);
  666. return;
  667. case IIT_V2:
  668. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
  669. DecodeIITType(NextElt, Infos, OutputTable);
  670. return;
  671. case IIT_V4:
  672. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
  673. DecodeIITType(NextElt, Infos, OutputTable);
  674. return;
  675. case IIT_V8:
  676. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
  677. DecodeIITType(NextElt, Infos, OutputTable);
  678. return;
  679. case IIT_V16:
  680. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
  681. DecodeIITType(NextElt, Infos, OutputTable);
  682. return;
  683. case IIT_V32:
  684. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
  685. DecodeIITType(NextElt, Infos, OutputTable);
  686. return;
  687. case IIT_V64:
  688. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64));
  689. DecodeIITType(NextElt, Infos, OutputTable);
  690. return;
  691. case IIT_V512:
  692. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 512));
  693. DecodeIITType(NextElt, Infos, OutputTable);
  694. return;
  695. case IIT_V1024:
  696. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1024));
  697. DecodeIITType(NextElt, Infos, OutputTable);
  698. return;
  699. case IIT_PTR:
  700. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
  701. DecodeIITType(NextElt, Infos, OutputTable);
  702. return;
  703. case IIT_ANYPTR: { // [ANYPTR addrspace, subtype]
  704. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
  705. Infos[NextElt++]));
  706. DecodeIITType(NextElt, Infos, OutputTable);
  707. return;
  708. }
  709. case IIT_ARG: {
  710. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  711. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
  712. return;
  713. }
  714. case IIT_EXTEND_ARG: {
  715. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  716. OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
  717. ArgInfo));
  718. return;
  719. }
  720. case IIT_TRUNC_ARG: {
  721. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  722. OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
  723. ArgInfo));
  724. return;
  725. }
  726. case IIT_HALF_VEC_ARG: {
  727. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  728. OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
  729. ArgInfo));
  730. return;
  731. }
  732. case IIT_SAME_VEC_WIDTH_ARG: {
  733. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  734. OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
  735. ArgInfo));
  736. return;
  737. }
  738. case IIT_PTR_TO_ARG: {
  739. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  740. OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
  741. ArgInfo));
  742. return;
  743. }
  744. case IIT_PTR_TO_ELT: {
  745. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  746. OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo));
  747. return;
  748. }
  749. case IIT_VEC_OF_ANYPTRS_TO_ELT: {
  750. unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  751. unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  752. OutputTable.push_back(
  753. IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo));
  754. return;
  755. }
  756. case IIT_EMPTYSTRUCT:
  757. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
  758. return;
  759. case IIT_STRUCT8: ++StructElts; LLVM_FALLTHROUGH;
  760. case IIT_STRUCT7: ++StructElts; LLVM_FALLTHROUGH;
  761. case IIT_STRUCT6: ++StructElts; LLVM_FALLTHROUGH;
  762. case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH;
  763. case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH;
  764. case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH;
  765. case IIT_STRUCT2: {
  766. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
  767. for (unsigned i = 0; i != StructElts; ++i)
  768. DecodeIITType(NextElt, Infos, OutputTable);
  769. return;
  770. }
  771. case IIT_VEC_ELEMENT: {
  772. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  773. OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument,
  774. ArgInfo));
  775. return;
  776. }
  777. }
  778. llvm_unreachable("unhandled");
  779. }
  780. #define GET_INTRINSIC_GENERATOR_GLOBAL
  781. #include "llvm/IR/IntrinsicImpl.inc"
  782. #undef GET_INTRINSIC_GENERATOR_GLOBAL
  783. void Intrinsic::getIntrinsicInfoTableEntries(ID id,
  784. SmallVectorImpl<IITDescriptor> &T){
  785. // Check to see if the intrinsic's type was expressible by the table.
  786. unsigned TableVal = IIT_Table[id-1];
  787. // Decode the TableVal into an array of IITValues.
  788. SmallVector<unsigned char, 8> IITValues;
  789. ArrayRef<unsigned char> IITEntries;
  790. unsigned NextElt = 0;
  791. if ((TableVal >> 31) != 0) {
  792. // This is an offset into the IIT_LongEncodingTable.
  793. IITEntries = IIT_LongEncodingTable;
  794. // Strip sentinel bit.
  795. NextElt = (TableVal << 1) >> 1;
  796. } else {
  797. // Decode the TableVal into an array of IITValues. If the entry was encoded
  798. // into a single word in the table itself, decode it now.
  799. do {
  800. IITValues.push_back(TableVal & 0xF);
  801. TableVal >>= 4;
  802. } while (TableVal);
  803. IITEntries = IITValues;
  804. NextElt = 0;
  805. }
  806. // Okay, decode the table into the output vector of IITDescriptors.
  807. DecodeIITType(NextElt, IITEntries, T);
  808. while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
  809. DecodeIITType(NextElt, IITEntries, T);
  810. }
  811. static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
  812. ArrayRef<Type*> Tys, LLVMContext &Context) {
  813. using namespace Intrinsic;
  814. IITDescriptor D = Infos.front();
  815. Infos = Infos.slice(1);
  816. switch (D.Kind) {
  817. case IITDescriptor::Void: return Type::getVoidTy(Context);
  818. case IITDescriptor::VarArg: return Type::getVoidTy(Context);
  819. case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
  820. case IITDescriptor::Token: return Type::getTokenTy(Context);
  821. case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
  822. case IITDescriptor::Half: return Type::getHalfTy(Context);
  823. case IITDescriptor::Float: return Type::getFloatTy(Context);
  824. case IITDescriptor::Double: return Type::getDoubleTy(Context);
  825. case IITDescriptor::Quad: return Type::getFP128Ty(Context);
  826. case IITDescriptor::Integer:
  827. return IntegerType::get(Context, D.Integer_Width);
  828. case IITDescriptor::Vector:
  829. return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
  830. case IITDescriptor::Pointer:
  831. return PointerType::get(DecodeFixedType(Infos, Tys, Context),
  832. D.Pointer_AddressSpace);
  833. case IITDescriptor::Struct: {
  834. SmallVector<Type *, 8> Elts;
  835. for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
  836. Elts.push_back(DecodeFixedType(Infos, Tys, Context));
  837. return StructType::get(Context, Elts);
  838. }
  839. case IITDescriptor::Argument:
  840. return Tys[D.getArgumentNumber()];
  841. case IITDescriptor::ExtendArgument: {
  842. Type *Ty = Tys[D.getArgumentNumber()];
  843. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  844. return VectorType::getExtendedElementVectorType(VTy);
  845. return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
  846. }
  847. case IITDescriptor::TruncArgument: {
  848. Type *Ty = Tys[D.getArgumentNumber()];
  849. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  850. return VectorType::getTruncatedElementVectorType(VTy);
  851. IntegerType *ITy = cast<IntegerType>(Ty);
  852. assert(ITy->getBitWidth() % 2 == 0);
  853. return IntegerType::get(Context, ITy->getBitWidth() / 2);
  854. }
  855. case IITDescriptor::HalfVecArgument:
  856. return VectorType::getHalfElementsVectorType(cast<VectorType>(
  857. Tys[D.getArgumentNumber()]));
  858. case IITDescriptor::SameVecWidthArgument: {
  859. Type *EltTy = DecodeFixedType(Infos, Tys, Context);
  860. Type *Ty = Tys[D.getArgumentNumber()];
  861. if (auto *VTy = dyn_cast<VectorType>(Ty))
  862. return VectorType::get(EltTy, VTy->getNumElements());
  863. return EltTy;
  864. }
  865. case IITDescriptor::PtrToArgument: {
  866. Type *Ty = Tys[D.getArgumentNumber()];
  867. return PointerType::getUnqual(Ty);
  868. }
  869. case IITDescriptor::PtrToElt: {
  870. Type *Ty = Tys[D.getArgumentNumber()];
  871. VectorType *VTy = dyn_cast<VectorType>(Ty);
  872. if (!VTy)
  873. llvm_unreachable("Expected an argument of Vector Type");
  874. Type *EltTy = VTy->getVectorElementType();
  875. return PointerType::getUnqual(EltTy);
  876. }
  877. case IITDescriptor::VecElementArgument: {
  878. Type *Ty = Tys[D.getArgumentNumber()];
  879. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  880. return VTy->getElementType();
  881. llvm_unreachable("Expected an argument of Vector Type");
  882. }
  883. case IITDescriptor::VecOfAnyPtrsToElt:
  884. // Return the overloaded type (which determines the pointers address space)
  885. return Tys[D.getOverloadArgNumber()];
  886. }
  887. llvm_unreachable("unhandled");
  888. }
  889. FunctionType *Intrinsic::getType(LLVMContext &Context,
  890. ID id, ArrayRef<Type*> Tys) {
  891. SmallVector<IITDescriptor, 8> Table;
  892. getIntrinsicInfoTableEntries(id, Table);
  893. ArrayRef<IITDescriptor> TableRef = Table;
  894. Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
  895. SmallVector<Type*, 8> ArgTys;
  896. while (!TableRef.empty())
  897. ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
  898. // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
  899. // If we see void type as the type of the last argument, it is vararg intrinsic
  900. if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
  901. ArgTys.pop_back();
  902. return FunctionType::get(ResultTy, ArgTys, true);
  903. }
  904. return FunctionType::get(ResultTy, ArgTys, false);
  905. }
  906. bool Intrinsic::isOverloaded(ID id) {
  907. #define GET_INTRINSIC_OVERLOAD_TABLE
  908. #include "llvm/IR/IntrinsicImpl.inc"
  909. #undef GET_INTRINSIC_OVERLOAD_TABLE
  910. }
  911. bool Intrinsic::isLeaf(ID id) {
  912. switch (id) {
  913. default:
  914. return true;
  915. case Intrinsic::experimental_gc_statepoint:
  916. case Intrinsic::experimental_patchpoint_void:
  917. case Intrinsic::experimental_patchpoint_i64:
  918. return false;
  919. }
  920. }
  921. /// This defines the "Intrinsic::getAttributes(ID id)" method.
  922. #define GET_INTRINSIC_ATTRIBUTES
  923. #include "llvm/IR/IntrinsicImpl.inc"
  924. #undef GET_INTRINSIC_ATTRIBUTES
  925. Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
  926. // There can never be multiple globals with the same name of different types,
  927. // because intrinsics must be a specific type.
  928. return cast<Function>(
  929. M->getOrInsertFunction(getName(id, Tys),
  930. getType(M->getContext(), id, Tys))
  931. .getCallee());
  932. }
  933. // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
  934. #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
  935. #include "llvm/IR/IntrinsicImpl.inc"
  936. #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
  937. // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
  938. #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
  939. #include "llvm/IR/IntrinsicImpl.inc"
  940. #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
  941. using DeferredIntrinsicMatchPair =
  942. std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>;
  943. static bool matchIntrinsicType(
  944. Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
  945. SmallVectorImpl<Type *> &ArgTys,
  946. SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks,
  947. bool IsDeferredCheck) {
  948. using namespace Intrinsic;
  949. // If we ran out of descriptors, there are too many arguments.
  950. if (Infos.empty()) return true;
  951. // Do this before slicing off the 'front' part
  952. auto InfosRef = Infos;
  953. auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) {
  954. DeferredChecks.emplace_back(T, InfosRef);
  955. return false;
  956. };
  957. IITDescriptor D = Infos.front();
  958. Infos = Infos.slice(1);
  959. switch (D.Kind) {
  960. case IITDescriptor::Void: return !Ty->isVoidTy();
  961. case IITDescriptor::VarArg: return true;
  962. case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
  963. case IITDescriptor::Token: return !Ty->isTokenTy();
  964. case IITDescriptor::Metadata: return !Ty->isMetadataTy();
  965. case IITDescriptor::Half: return !Ty->isHalfTy();
  966. case IITDescriptor::Float: return !Ty->isFloatTy();
  967. case IITDescriptor::Double: return !Ty->isDoubleTy();
  968. case IITDescriptor::Quad: return !Ty->isFP128Ty();
  969. case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
  970. case IITDescriptor::Vector: {
  971. VectorType *VT = dyn_cast<VectorType>(Ty);
  972. return !VT || VT->getNumElements() != D.Vector_Width ||
  973. matchIntrinsicType(VT->getElementType(), Infos, ArgTys,
  974. DeferredChecks, IsDeferredCheck);
  975. }
  976. case IITDescriptor::Pointer: {
  977. PointerType *PT = dyn_cast<PointerType>(Ty);
  978. return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
  979. matchIntrinsicType(PT->getElementType(), Infos, ArgTys,
  980. DeferredChecks, IsDeferredCheck);
  981. }
  982. case IITDescriptor::Struct: {
  983. StructType *ST = dyn_cast<StructType>(Ty);
  984. if (!ST || ST->getNumElements() != D.Struct_NumElements)
  985. return true;
  986. for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
  987. if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys,
  988. DeferredChecks, IsDeferredCheck))
  989. return true;
  990. return false;
  991. }
  992. case IITDescriptor::Argument:
  993. // If this is the second occurrence of an argument,
  994. // verify that the later instance matches the previous instance.
  995. if (D.getArgumentNumber() < ArgTys.size())
  996. return Ty != ArgTys[D.getArgumentNumber()];
  997. if (D.getArgumentNumber() > ArgTys.size() ||
  998. D.getArgumentKind() == IITDescriptor::AK_MatchType)
  999. return IsDeferredCheck || DeferCheck(Ty);
  1000. assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck &&
  1001. "Table consistency error");
  1002. ArgTys.push_back(Ty);
  1003. switch (D.getArgumentKind()) {
  1004. case IITDescriptor::AK_Any: return false; // Success
  1005. case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
  1006. case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
  1007. case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
  1008. case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
  1009. default: break;
  1010. }
  1011. llvm_unreachable("all argument kinds not covered");
  1012. case IITDescriptor::ExtendArgument: {
  1013. // If this is a forward reference, defer the check for later.
  1014. if (D.getArgumentNumber() >= ArgTys.size())
  1015. return IsDeferredCheck || DeferCheck(Ty);
  1016. Type *NewTy = ArgTys[D.getArgumentNumber()];
  1017. if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
  1018. NewTy = VectorType::getExtendedElementVectorType(VTy);
  1019. else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
  1020. NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
  1021. else
  1022. return true;
  1023. return Ty != NewTy;
  1024. }
  1025. case IITDescriptor::TruncArgument: {
  1026. // If this is a forward reference, defer the check for later.
  1027. if (D.getArgumentNumber() >= ArgTys.size())
  1028. return IsDeferredCheck || DeferCheck(Ty);
  1029. Type *NewTy = ArgTys[D.getArgumentNumber()];
  1030. if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
  1031. NewTy = VectorType::getTruncatedElementVectorType(VTy);
  1032. else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
  1033. NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
  1034. else
  1035. return true;
  1036. return Ty != NewTy;
  1037. }
  1038. case IITDescriptor::HalfVecArgument:
  1039. // If this is a forward reference, defer the check for later.
  1040. return D.getArgumentNumber() >= ArgTys.size() ||
  1041. !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
  1042. VectorType::getHalfElementsVectorType(
  1043. cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
  1044. case IITDescriptor::SameVecWidthArgument: {
  1045. if (D.getArgumentNumber() >= ArgTys.size()) {
  1046. // Defer check and subsequent check for the vector element type.
  1047. Infos = Infos.slice(1);
  1048. return IsDeferredCheck || DeferCheck(Ty);
  1049. }
  1050. auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
  1051. auto *ThisArgType = dyn_cast<VectorType>(Ty);
  1052. // Both must be vectors of the same number of elements or neither.
  1053. if ((ReferenceType != nullptr) != (ThisArgType != nullptr))
  1054. return true;
  1055. Type *EltTy = Ty;
  1056. if (ThisArgType) {
  1057. if (ReferenceType->getVectorNumElements() !=
  1058. ThisArgType->getVectorNumElements())
  1059. return true;
  1060. EltTy = ThisArgType->getVectorElementType();
  1061. }
  1062. return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks,
  1063. IsDeferredCheck);
  1064. }
  1065. case IITDescriptor::PtrToArgument: {
  1066. if (D.getArgumentNumber() >= ArgTys.size())
  1067. return IsDeferredCheck || DeferCheck(Ty);
  1068. Type * ReferenceType = ArgTys[D.getArgumentNumber()];
  1069. PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
  1070. return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
  1071. }
  1072. case IITDescriptor::PtrToElt: {
  1073. if (D.getArgumentNumber() >= ArgTys.size())
  1074. return IsDeferredCheck || DeferCheck(Ty);
  1075. VectorType * ReferenceType =
  1076. dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
  1077. PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
  1078. return (!ThisArgType || !ReferenceType ||
  1079. ThisArgType->getElementType() != ReferenceType->getElementType());
  1080. }
  1081. case IITDescriptor::VecOfAnyPtrsToElt: {
  1082. unsigned RefArgNumber = D.getRefArgNumber();
  1083. if (RefArgNumber >= ArgTys.size()) {
  1084. if (IsDeferredCheck)
  1085. return true;
  1086. // If forward referencing, already add the pointer-vector type and
  1087. // defer the checks for later.
  1088. ArgTys.push_back(Ty);
  1089. return DeferCheck(Ty);
  1090. }
  1091. if (!IsDeferredCheck){
  1092. assert(D.getOverloadArgNumber() == ArgTys.size() &&
  1093. "Table consistency error");
  1094. ArgTys.push_back(Ty);
  1095. }
  1096. // Verify the overloaded type "matches" the Ref type.
  1097. // i.e. Ty is a vector with the same width as Ref.
  1098. // Composed of pointers to the same element type as Ref.
  1099. VectorType *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]);
  1100. VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
  1101. if (!ThisArgVecTy || !ReferenceType ||
  1102. (ReferenceType->getVectorNumElements() !=
  1103. ThisArgVecTy->getVectorNumElements()))
  1104. return true;
  1105. PointerType *ThisArgEltTy =
  1106. dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
  1107. if (!ThisArgEltTy)
  1108. return true;
  1109. return ThisArgEltTy->getElementType() !=
  1110. ReferenceType->getVectorElementType();
  1111. }
  1112. case IITDescriptor::VecElementArgument: {
  1113. if (D.getArgumentNumber() >= ArgTys.size())
  1114. return IsDeferredCheck ? true : DeferCheck(Ty);
  1115. auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
  1116. return !ReferenceType || Ty != ReferenceType->getElementType();
  1117. }
  1118. }
  1119. llvm_unreachable("unhandled");
  1120. }
  1121. Intrinsic::MatchIntrinsicTypesResult
  1122. Intrinsic::matchIntrinsicSignature(FunctionType *FTy,
  1123. ArrayRef<Intrinsic::IITDescriptor> &Infos,
  1124. SmallVectorImpl<Type *> &ArgTys) {
  1125. SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks;
  1126. if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks,
  1127. false))
  1128. return MatchIntrinsicTypes_NoMatchRet;
  1129. unsigned NumDeferredReturnChecks = DeferredChecks.size();
  1130. for (auto Ty : FTy->params())
  1131. if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false))
  1132. return MatchIntrinsicTypes_NoMatchArg;
  1133. for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) {
  1134. DeferredIntrinsicMatchPair &Check = DeferredChecks[I];
  1135. if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks,
  1136. true))
  1137. return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet
  1138. : MatchIntrinsicTypes_NoMatchArg;
  1139. }
  1140. return MatchIntrinsicTypes_Match;
  1141. }
  1142. bool
  1143. Intrinsic::matchIntrinsicVarArg(bool isVarArg,
  1144. ArrayRef<Intrinsic::IITDescriptor> &Infos) {
  1145. // If there are no descriptors left, then it can't be a vararg.
  1146. if (Infos.empty())
  1147. return isVarArg;
  1148. // There should be only one descriptor remaining at this point.
  1149. if (Infos.size() != 1)
  1150. return true;
  1151. // Check and verify the descriptor.
  1152. IITDescriptor D = Infos.front();
  1153. Infos = Infos.slice(1);
  1154. if (D.Kind == IITDescriptor::VarArg)
  1155. return !isVarArg;
  1156. return true;
  1157. }
  1158. Optional<Function*> Intrinsic::remangleIntrinsicFunction(Function *F) {
  1159. Intrinsic::ID ID = F->getIntrinsicID();
  1160. if (!ID)
  1161. return None;
  1162. FunctionType *FTy = F->getFunctionType();
  1163. // Accumulate an array of overloaded types for the given intrinsic
  1164. SmallVector<Type *, 4> ArgTys;
  1165. {
  1166. SmallVector<Intrinsic::IITDescriptor, 8> Table;
  1167. getIntrinsicInfoTableEntries(ID, Table);
  1168. ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
  1169. if (Intrinsic::matchIntrinsicSignature(FTy, TableRef, ArgTys))
  1170. return None;
  1171. if (Intrinsic::matchIntrinsicVarArg(FTy->isVarArg(), TableRef))
  1172. return None;
  1173. }
  1174. StringRef Name = F->getName();
  1175. if (Name == Intrinsic::getName(ID, ArgTys))
  1176. return None;
  1177. auto NewDecl = Intrinsic::getDeclaration(F->getParent(), ID, ArgTys);
  1178. NewDecl->setCallingConv(F->getCallingConv());
  1179. assert(NewDecl->getFunctionType() == FTy && "Shouldn't change the signature");
  1180. return NewDecl;
  1181. }
  1182. /// hasAddressTaken - returns true if there are any uses of this function
  1183. /// other than direct calls or invokes to it.
  1184. bool Function::hasAddressTaken(const User* *PutOffender) const {
  1185. for (const Use &U : uses()) {
  1186. const User *FU = U.getUser();
  1187. if (isa<BlockAddress>(FU))
  1188. continue;
  1189. const auto *Call = dyn_cast<CallBase>(FU);
  1190. if (!Call) {
  1191. if (PutOffender)
  1192. *PutOffender = FU;
  1193. return true;
  1194. }
  1195. if (!Call->isCallee(&U)) {
  1196. if (PutOffender)
  1197. *PutOffender = FU;
  1198. return true;
  1199. }
  1200. }
  1201. return false;
  1202. }
  1203. bool Function::isDefTriviallyDead() const {
  1204. // Check the linkage
  1205. if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
  1206. !hasAvailableExternallyLinkage())
  1207. return false;
  1208. // Check if the function is used by anything other than a blockaddress.
  1209. for (const User *U : users())
  1210. if (!isa<BlockAddress>(U))
  1211. return false;
  1212. return true;
  1213. }
  1214. /// callsFunctionThatReturnsTwice - Return true if the function has a call to
  1215. /// setjmp or other function that gcc recognizes as "returning twice".
  1216. bool Function::callsFunctionThatReturnsTwice() const {
  1217. for (const Instruction &I : instructions(this))
  1218. if (const auto *Call = dyn_cast<CallBase>(&I))
  1219. if (Call->hasFnAttr(Attribute::ReturnsTwice))
  1220. return true;
  1221. return false;
  1222. }
  1223. Constant *Function::getPersonalityFn() const {
  1224. assert(hasPersonalityFn() && getNumOperands());
  1225. return cast<Constant>(Op<0>());
  1226. }
  1227. void Function::setPersonalityFn(Constant *Fn) {
  1228. setHungoffOperand<0>(Fn);
  1229. setValueSubclassDataBit(3, Fn != nullptr);
  1230. }
  1231. Constant *Function::getPrefixData() const {
  1232. assert(hasPrefixData() && getNumOperands());
  1233. return cast<Constant>(Op<1>());
  1234. }
  1235. void Function::setPrefixData(Constant *PrefixData) {
  1236. setHungoffOperand<1>(PrefixData);
  1237. setValueSubclassDataBit(1, PrefixData != nullptr);
  1238. }
  1239. Constant *Function::getPrologueData() const {
  1240. assert(hasPrologueData() && getNumOperands());
  1241. return cast<Constant>(Op<2>());
  1242. }
  1243. void Function::setPrologueData(Constant *PrologueData) {
  1244. setHungoffOperand<2>(PrologueData);
  1245. setValueSubclassDataBit(2, PrologueData != nullptr);
  1246. }
  1247. void Function::allocHungoffUselist() {
  1248. // If we've already allocated a uselist, stop here.
  1249. if (getNumOperands())
  1250. return;
  1251. allocHungoffUses(3, /*IsPhi=*/ false);
  1252. setNumHungOffUseOperands(3);
  1253. // Initialize the uselist with placeholder operands to allow traversal.
  1254. auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
  1255. Op<0>().set(CPN);
  1256. Op<1>().set(CPN);
  1257. Op<2>().set(CPN);
  1258. }
  1259. template <int Idx>
  1260. void Function::setHungoffOperand(Constant *C) {
  1261. if (C) {
  1262. allocHungoffUselist();
  1263. Op<Idx>().set(C);
  1264. } else if (getNumOperands()) {
  1265. Op<Idx>().set(
  1266. ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
  1267. }
  1268. }
  1269. void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
  1270. assert(Bit < 16 && "SubclassData contains only 16 bits");
  1271. if (On)
  1272. setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
  1273. else
  1274. setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
  1275. }
  1276. void Function::setEntryCount(ProfileCount Count,
  1277. const DenseSet<GlobalValue::GUID> *S) {
  1278. assert(Count.hasValue());
  1279. #if !defined(NDEBUG)
  1280. auto PrevCount = getEntryCount();
  1281. assert(!PrevCount.hasValue() || PrevCount.getType() == Count.getType());
  1282. #endif
  1283. MDBuilder MDB(getContext());
  1284. setMetadata(
  1285. LLVMContext::MD_prof,
  1286. MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S));
  1287. }
  1288. void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type,
  1289. const DenseSet<GlobalValue::GUID> *Imports) {
  1290. setEntryCount(ProfileCount(Count, Type), Imports);
  1291. }
  1292. ProfileCount Function::getEntryCount(bool AllowSynthetic) const {
  1293. MDNode *MD = getMetadata(LLVMContext::MD_prof);
  1294. if (MD && MD->getOperand(0))
  1295. if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) {
  1296. if (MDS->getString().equals("function_entry_count")) {
  1297. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
  1298. uint64_t Count = CI->getValue().getZExtValue();
  1299. // A value of -1 is used for SamplePGO when there were no samples.
  1300. // Treat this the same as unknown.
  1301. if (Count == (uint64_t)-1)
  1302. return ProfileCount::getInvalid();
  1303. return ProfileCount(Count, PCT_Real);
  1304. } else if (AllowSynthetic &&
  1305. MDS->getString().equals("synthetic_function_entry_count")) {
  1306. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
  1307. uint64_t Count = CI->getValue().getZExtValue();
  1308. return ProfileCount(Count, PCT_Synthetic);
  1309. }
  1310. }
  1311. return ProfileCount::getInvalid();
  1312. }
  1313. DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const {
  1314. DenseSet<GlobalValue::GUID> R;
  1315. if (MDNode *MD = getMetadata(LLVMContext::MD_prof))
  1316. if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
  1317. if (MDS->getString().equals("function_entry_count"))
  1318. for (unsigned i = 2; i < MD->getNumOperands(); i++)
  1319. R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i))
  1320. ->getValue()
  1321. .getZExtValue());
  1322. return R;
  1323. }
  1324. void Function::setSectionPrefix(StringRef Prefix) {
  1325. MDBuilder MDB(getContext());
  1326. setMetadata(LLVMContext::MD_section_prefix,
  1327. MDB.createFunctionSectionPrefix(Prefix));
  1328. }
  1329. Optional<StringRef> Function::getSectionPrefix() const {
  1330. if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) {
  1331. assert(cast<MDString>(MD->getOperand(0))
  1332. ->getString()
  1333. .equals("function_section_prefix") &&
  1334. "Metadata not match");
  1335. return cast<MDString>(MD->getOperand(1))->getString();
  1336. }
  1337. return None;
  1338. }
  1339. bool Function::nullPointerIsDefined() const {
  1340. return getFnAttribute("null-pointer-is-valid")
  1341. .getValueAsString()
  1342. .equals("true");
  1343. }
  1344. bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) {
  1345. if (F && F->nullPointerIsDefined())
  1346. return true;
  1347. if (AS != 0)
  1348. return true;
  1349. return false;
  1350. }