Function.cpp 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993
  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/AbstractCallSite.h"
  23. #include "llvm/IR/Argument.h"
  24. #include "llvm/IR/Attributes.h"
  25. #include "llvm/IR/BasicBlock.h"
  26. #include "llvm/IR/Constant.h"
  27. #include "llvm/IR/Constants.h"
  28. #include "llvm/IR/DerivedTypes.h"
  29. #include "llvm/IR/GlobalValue.h"
  30. #include "llvm/IR/InstIterator.h"
  31. #include "llvm/IR/Instruction.h"
  32. #include "llvm/IR/IntrinsicInst.h"
  33. #include "llvm/IR/Intrinsics.h"
  34. #include "llvm/IR/IntrinsicsAArch64.h"
  35. #include "llvm/IR/IntrinsicsAMDGPU.h"
  36. #include "llvm/IR/IntrinsicsARM.h"
  37. #include "llvm/IR/IntrinsicsBPF.h"
  38. #include "llvm/IR/IntrinsicsHexagon.h"
  39. #include "llvm/IR/IntrinsicsMips.h"
  40. #include "llvm/IR/IntrinsicsNVPTX.h"
  41. #include "llvm/IR/IntrinsicsPowerPC.h"
  42. #include "llvm/IR/IntrinsicsR600.h"
  43. #include "llvm/IR/IntrinsicsRISCV.h"
  44. #include "llvm/IR/IntrinsicsS390.h"
  45. #include "llvm/IR/IntrinsicsVE.h"
  46. #include "llvm/IR/IntrinsicsWebAssembly.h"
  47. #include "llvm/IR/IntrinsicsX86.h"
  48. #include "llvm/IR/IntrinsicsXCore.h"
  49. #include "llvm/IR/LLVMContext.h"
  50. #include "llvm/IR/MDBuilder.h"
  51. #include "llvm/IR/Metadata.h"
  52. #include "llvm/IR/Module.h"
  53. #include "llvm/IR/Operator.h"
  54. #include "llvm/IR/SymbolTableListTraits.h"
  55. #include "llvm/IR/Type.h"
  56. #include "llvm/IR/Use.h"
  57. #include "llvm/IR/User.h"
  58. #include "llvm/IR/Value.h"
  59. #include "llvm/IR/ValueSymbolTable.h"
  60. #include "llvm/Support/Casting.h"
  61. #include "llvm/Support/CommandLine.h"
  62. #include "llvm/Support/Compiler.h"
  63. #include "llvm/Support/ErrorHandling.h"
  64. #include <cassert>
  65. #include <cstddef>
  66. #include <cstdint>
  67. #include <cstring>
  68. #include <string>
  69. using namespace llvm;
  70. using ProfileCount = Function::ProfileCount;
  71. // Explicit instantiations of SymbolTableListTraits since some of the methods
  72. // are not in the public header file...
  73. template class llvm::SymbolTableListTraits<BasicBlock>;
  74. static cl::opt<unsigned> NonGlobalValueMaxNameSize(
  75. "non-global-value-max-name-size", cl::Hidden, cl::init(1024),
  76. cl::desc("Maximum size for the name of non-global values."));
  77. //===----------------------------------------------------------------------===//
  78. // Argument Implementation
  79. //===----------------------------------------------------------------------===//
  80. Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo)
  81. : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) {
  82. setName(Name);
  83. }
  84. void Argument::setParent(Function *parent) {
  85. Parent = parent;
  86. }
  87. bool Argument::hasNonNullAttr(bool AllowUndefOrPoison) const {
  88. if (!getType()->isPointerTy()) return false;
  89. if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull) &&
  90. (AllowUndefOrPoison ||
  91. getParent()->hasParamAttribute(getArgNo(), Attribute::NoUndef)))
  92. return true;
  93. else if (getDereferenceableBytes() > 0 &&
  94. !NullPointerIsDefined(getParent(),
  95. getType()->getPointerAddressSpace()))
  96. return true;
  97. return false;
  98. }
  99. bool Argument::hasByValAttr() const {
  100. if (!getType()->isPointerTy()) return false;
  101. return hasAttribute(Attribute::ByVal);
  102. }
  103. bool Argument::hasByRefAttr() const {
  104. if (!getType()->isPointerTy())
  105. return false;
  106. return hasAttribute(Attribute::ByRef);
  107. }
  108. bool Argument::hasSwiftSelfAttr() const {
  109. return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf);
  110. }
  111. bool Argument::hasSwiftErrorAttr() const {
  112. return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError);
  113. }
  114. bool Argument::hasInAllocaAttr() const {
  115. if (!getType()->isPointerTy()) return false;
  116. return hasAttribute(Attribute::InAlloca);
  117. }
  118. bool Argument::hasPreallocatedAttr() const {
  119. if (!getType()->isPointerTy())
  120. return false;
  121. return hasAttribute(Attribute::Preallocated);
  122. }
  123. bool Argument::hasPassPointeeByValueCopyAttr() const {
  124. if (!getType()->isPointerTy()) return false;
  125. AttributeList Attrs = getParent()->getAttributes();
  126. return Attrs.hasParamAttr(getArgNo(), Attribute::ByVal) ||
  127. Attrs.hasParamAttr(getArgNo(), Attribute::InAlloca) ||
  128. Attrs.hasParamAttr(getArgNo(), Attribute::Preallocated);
  129. }
  130. bool Argument::hasPointeeInMemoryValueAttr() const {
  131. if (!getType()->isPointerTy())
  132. return false;
  133. AttributeList Attrs = getParent()->getAttributes();
  134. return Attrs.hasParamAttr(getArgNo(), Attribute::ByVal) ||
  135. Attrs.hasParamAttr(getArgNo(), Attribute::StructRet) ||
  136. Attrs.hasParamAttr(getArgNo(), Attribute::InAlloca) ||
  137. Attrs.hasParamAttr(getArgNo(), Attribute::Preallocated) ||
  138. Attrs.hasParamAttr(getArgNo(), Attribute::ByRef);
  139. }
  140. /// For a byval, sret, inalloca, or preallocated parameter, get the in-memory
  141. /// parameter type.
  142. static Type *getMemoryParamAllocType(AttributeSet ParamAttrs) {
  143. // FIXME: All the type carrying attributes are mutually exclusive, so there
  144. // should be a single query to get the stored type that handles any of them.
  145. if (Type *ByValTy = ParamAttrs.getByValType())
  146. return ByValTy;
  147. if (Type *ByRefTy = ParamAttrs.getByRefType())
  148. return ByRefTy;
  149. if (Type *PreAllocTy = ParamAttrs.getPreallocatedType())
  150. return PreAllocTy;
  151. if (Type *InAllocaTy = ParamAttrs.getInAllocaType())
  152. return InAllocaTy;
  153. if (Type *SRetTy = ParamAttrs.getStructRetType())
  154. return SRetTy;
  155. return nullptr;
  156. }
  157. uint64_t Argument::getPassPointeeByValueCopySize(const DataLayout &DL) const {
  158. AttributeSet ParamAttrs =
  159. getParent()->getAttributes().getParamAttrs(getArgNo());
  160. if (Type *MemTy = getMemoryParamAllocType(ParamAttrs))
  161. return DL.getTypeAllocSize(MemTy);
  162. return 0;
  163. }
  164. Type *Argument::getPointeeInMemoryValueType() const {
  165. AttributeSet ParamAttrs =
  166. getParent()->getAttributes().getParamAttrs(getArgNo());
  167. return getMemoryParamAllocType(ParamAttrs);
  168. }
  169. uint64_t Argument::getParamAlignment() const {
  170. assert(getType()->isPointerTy() && "Only pointers have alignments");
  171. return getParent()->getParamAlignment(getArgNo());
  172. }
  173. MaybeAlign Argument::getParamAlign() const {
  174. assert(getType()->isPointerTy() && "Only pointers have alignments");
  175. return getParent()->getParamAlign(getArgNo());
  176. }
  177. MaybeAlign Argument::getParamStackAlign() const {
  178. return getParent()->getParamStackAlign(getArgNo());
  179. }
  180. Type *Argument::getParamByValType() const {
  181. assert(getType()->isPointerTy() && "Only pointers have byval types");
  182. return getParent()->getParamByValType(getArgNo());
  183. }
  184. Type *Argument::getParamStructRetType() const {
  185. assert(getType()->isPointerTy() && "Only pointers have sret types");
  186. return getParent()->getParamStructRetType(getArgNo());
  187. }
  188. Type *Argument::getParamByRefType() const {
  189. assert(getType()->isPointerTy() && "Only pointers have byref types");
  190. return getParent()->getParamByRefType(getArgNo());
  191. }
  192. Type *Argument::getParamInAllocaType() const {
  193. assert(getType()->isPointerTy() && "Only pointers have inalloca types");
  194. return getParent()->getParamInAllocaType(getArgNo());
  195. }
  196. uint64_t Argument::getDereferenceableBytes() const {
  197. assert(getType()->isPointerTy() &&
  198. "Only pointers have dereferenceable bytes");
  199. return getParent()->getParamDereferenceableBytes(getArgNo());
  200. }
  201. uint64_t Argument::getDereferenceableOrNullBytes() const {
  202. assert(getType()->isPointerTy() &&
  203. "Only pointers have dereferenceable bytes");
  204. return getParent()->getParamDereferenceableOrNullBytes(getArgNo());
  205. }
  206. bool Argument::hasNestAttr() const {
  207. if (!getType()->isPointerTy()) return false;
  208. return hasAttribute(Attribute::Nest);
  209. }
  210. bool Argument::hasNoAliasAttr() const {
  211. if (!getType()->isPointerTy()) return false;
  212. return hasAttribute(Attribute::NoAlias);
  213. }
  214. bool Argument::hasNoCaptureAttr() const {
  215. if (!getType()->isPointerTy()) return false;
  216. return hasAttribute(Attribute::NoCapture);
  217. }
  218. bool Argument::hasNoFreeAttr() const {
  219. if (!getType()->isPointerTy()) return false;
  220. return hasAttribute(Attribute::NoFree);
  221. }
  222. bool Argument::hasStructRetAttr() const {
  223. if (!getType()->isPointerTy()) return false;
  224. return hasAttribute(Attribute::StructRet);
  225. }
  226. bool Argument::hasInRegAttr() const {
  227. return hasAttribute(Attribute::InReg);
  228. }
  229. bool Argument::hasReturnedAttr() const {
  230. return hasAttribute(Attribute::Returned);
  231. }
  232. bool Argument::hasZExtAttr() const {
  233. return hasAttribute(Attribute::ZExt);
  234. }
  235. bool Argument::hasSExtAttr() const {
  236. return hasAttribute(Attribute::SExt);
  237. }
  238. bool Argument::onlyReadsMemory() const {
  239. AttributeList Attrs = getParent()->getAttributes();
  240. return Attrs.hasParamAttr(getArgNo(), Attribute::ReadOnly) ||
  241. Attrs.hasParamAttr(getArgNo(), Attribute::ReadNone);
  242. }
  243. void Argument::addAttrs(AttrBuilder &B) {
  244. AttributeList AL = getParent()->getAttributes();
  245. AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B);
  246. getParent()->setAttributes(AL);
  247. }
  248. void Argument::addAttr(Attribute::AttrKind Kind) {
  249. getParent()->addParamAttr(getArgNo(), Kind);
  250. }
  251. void Argument::addAttr(Attribute Attr) {
  252. getParent()->addParamAttr(getArgNo(), Attr);
  253. }
  254. void Argument::removeAttr(Attribute::AttrKind Kind) {
  255. getParent()->removeParamAttr(getArgNo(), Kind);
  256. }
  257. void Argument::removeAttrs(const AttributeMask &AM) {
  258. AttributeList AL = getParent()->getAttributes();
  259. AL = AL.removeParamAttributes(Parent->getContext(), getArgNo(), AM);
  260. getParent()->setAttributes(AL);
  261. }
  262. bool Argument::hasAttribute(Attribute::AttrKind Kind) const {
  263. return getParent()->hasParamAttribute(getArgNo(), Kind);
  264. }
  265. Attribute Argument::getAttribute(Attribute::AttrKind Kind) const {
  266. return getParent()->getParamAttribute(getArgNo(), Kind);
  267. }
  268. //===----------------------------------------------------------------------===//
  269. // Helper Methods in Function
  270. //===----------------------------------------------------------------------===//
  271. LLVMContext &Function::getContext() const {
  272. return getType()->getContext();
  273. }
  274. unsigned Function::getInstructionCount() const {
  275. unsigned NumInstrs = 0;
  276. for (const BasicBlock &BB : BasicBlocks)
  277. NumInstrs += std::distance(BB.instructionsWithoutDebug().begin(),
  278. BB.instructionsWithoutDebug().end());
  279. return NumInstrs;
  280. }
  281. Function *Function::Create(FunctionType *Ty, LinkageTypes Linkage,
  282. const Twine &N, Module &M) {
  283. return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M);
  284. }
  285. Function *Function::createWithDefaultAttr(FunctionType *Ty,
  286. LinkageTypes Linkage,
  287. unsigned AddrSpace, const Twine &N,
  288. Module *M) {
  289. auto *F = new Function(Ty, Linkage, AddrSpace, N, M);
  290. AttrBuilder B(F->getContext());
  291. if (M->getUwtable())
  292. B.addAttribute(Attribute::UWTable);
  293. switch (M->getFramePointer()) {
  294. case FramePointerKind::None:
  295. // 0 ("none") is the default.
  296. break;
  297. case FramePointerKind::NonLeaf:
  298. B.addAttribute("frame-pointer", "non-leaf");
  299. break;
  300. case FramePointerKind::All:
  301. B.addAttribute("frame-pointer", "all");
  302. break;
  303. }
  304. F->addFnAttrs(B);
  305. return F;
  306. }
  307. void Function::removeFromParent() {
  308. getParent()->getFunctionList().remove(getIterator());
  309. }
  310. void Function::eraseFromParent() {
  311. getParent()->getFunctionList().erase(getIterator());
  312. }
  313. //===----------------------------------------------------------------------===//
  314. // Function Implementation
  315. //===----------------------------------------------------------------------===//
  316. static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) {
  317. // If AS == -1 and we are passed a valid module pointer we place the function
  318. // in the program address space. Otherwise we default to AS0.
  319. if (AddrSpace == static_cast<unsigned>(-1))
  320. return M ? M->getDataLayout().getProgramAddressSpace() : 0;
  321. return AddrSpace;
  322. }
  323. Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,
  324. const Twine &name, Module *ParentModule)
  325. : GlobalObject(Ty, Value::FunctionVal,
  326. OperandTraits<Function>::op_begin(this), 0, Linkage, name,
  327. computeAddrSpace(AddrSpace, ParentModule)),
  328. NumArgs(Ty->getNumParams()) {
  329. assert(FunctionType::isValidReturnType(getReturnType()) &&
  330. "invalid return type");
  331. setGlobalObjectSubClassData(0);
  332. // We only need a symbol table for a function if the context keeps value names
  333. if (!getContext().shouldDiscardValueNames())
  334. SymTab = std::make_unique<ValueSymbolTable>(NonGlobalValueMaxNameSize);
  335. // If the function has arguments, mark them as lazily built.
  336. if (Ty->getNumParams())
  337. setValueSubclassData(1); // Set the "has lazy arguments" bit.
  338. if (ParentModule)
  339. ParentModule->getFunctionList().push_back(this);
  340. HasLLVMReservedName = getName().startswith("llvm.");
  341. // Ensure intrinsics have the right parameter attributes.
  342. // Note, the IntID field will have been set in Value::setName if this function
  343. // name is a valid intrinsic ID.
  344. if (IntID)
  345. setAttributes(Intrinsic::getAttributes(getContext(), IntID));
  346. }
  347. Function::~Function() {
  348. dropAllReferences(); // After this it is safe to delete instructions.
  349. // Delete all of the method arguments and unlink from symbol table...
  350. if (Arguments)
  351. clearArguments();
  352. // Remove the function from the on-the-side GC table.
  353. clearGC();
  354. }
  355. void Function::BuildLazyArguments() const {
  356. // Create the arguments vector, all arguments start out unnamed.
  357. auto *FT = getFunctionType();
  358. if (NumArgs > 0) {
  359. Arguments = std::allocator<Argument>().allocate(NumArgs);
  360. for (unsigned i = 0, e = NumArgs; i != e; ++i) {
  361. Type *ArgTy = FT->getParamType(i);
  362. assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!");
  363. new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i);
  364. }
  365. }
  366. // Clear the lazy arguments bit.
  367. unsigned SDC = getSubclassDataFromValue();
  368. SDC &= ~(1 << 0);
  369. const_cast<Function*>(this)->setValueSubclassData(SDC);
  370. assert(!hasLazyArguments());
  371. }
  372. static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) {
  373. return MutableArrayRef<Argument>(Args, Count);
  374. }
  375. bool Function::isConstrainedFPIntrinsic() const {
  376. switch (getIntrinsicID()) {
  377. #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
  378. case Intrinsic::INTRINSIC:
  379. #include "llvm/IR/ConstrainedOps.def"
  380. return true;
  381. #undef INSTRUCTION
  382. default:
  383. return false;
  384. }
  385. }
  386. void Function::clearArguments() {
  387. for (Argument &A : makeArgArray(Arguments, NumArgs)) {
  388. A.setName("");
  389. A.~Argument();
  390. }
  391. std::allocator<Argument>().deallocate(Arguments, NumArgs);
  392. Arguments = nullptr;
  393. }
  394. void Function::stealArgumentListFrom(Function &Src) {
  395. assert(isDeclaration() && "Expected no references to current arguments");
  396. // Drop the current arguments, if any, and set the lazy argument bit.
  397. if (!hasLazyArguments()) {
  398. assert(llvm::all_of(makeArgArray(Arguments, NumArgs),
  399. [](const Argument &A) { return A.use_empty(); }) &&
  400. "Expected arguments to be unused in declaration");
  401. clearArguments();
  402. setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
  403. }
  404. // Nothing to steal if Src has lazy arguments.
  405. if (Src.hasLazyArguments())
  406. return;
  407. // Steal arguments from Src, and fix the lazy argument bits.
  408. assert(arg_size() == Src.arg_size());
  409. Arguments = Src.Arguments;
  410. Src.Arguments = nullptr;
  411. for (Argument &A : makeArgArray(Arguments, NumArgs)) {
  412. // FIXME: This does the work of transferNodesFromList inefficiently.
  413. SmallString<128> Name;
  414. if (A.hasName())
  415. Name = A.getName();
  416. if (!Name.empty())
  417. A.setName("");
  418. A.setParent(this);
  419. if (!Name.empty())
  420. A.setName(Name);
  421. }
  422. setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
  423. assert(!hasLazyArguments());
  424. Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));
  425. }
  426. // dropAllReferences() - This function causes all the subinstructions to "let
  427. // go" of all references that they are maintaining. This allows one to
  428. // 'delete' a whole class at a time, even though there may be circular
  429. // references... first all references are dropped, and all use counts go to
  430. // zero. Then everything is deleted for real. Note that no operations are
  431. // valid on an object that has "dropped all references", except operator
  432. // delete.
  433. //
  434. void Function::dropAllReferences() {
  435. setIsMaterializable(false);
  436. for (BasicBlock &BB : *this)
  437. BB.dropAllReferences();
  438. // Delete all basic blocks. They are now unused, except possibly by
  439. // blockaddresses, but BasicBlock's destructor takes care of those.
  440. while (!BasicBlocks.empty())
  441. BasicBlocks.begin()->eraseFromParent();
  442. // Drop uses of any optional data (real or placeholder).
  443. if (getNumOperands()) {
  444. User::dropAllReferences();
  445. setNumHungOffUseOperands(0);
  446. setValueSubclassData(getSubclassDataFromValue() & ~0xe);
  447. }
  448. // Metadata is stored in a side-table.
  449. clearMetadata();
  450. }
  451. void Function::addAttributeAtIndex(unsigned i, Attribute Attr) {
  452. AttributeSets = AttributeSets.addAttributeAtIndex(getContext(), i, Attr);
  453. }
  454. void Function::addFnAttr(Attribute::AttrKind Kind) {
  455. AttributeSets = AttributeSets.addFnAttribute(getContext(), Kind);
  456. }
  457. void Function::addFnAttr(StringRef Kind, StringRef Val) {
  458. AttributeSets = AttributeSets.addFnAttribute(getContext(), Kind, Val);
  459. }
  460. void Function::addFnAttr(Attribute Attr) {
  461. AttributeSets = AttributeSets.addFnAttribute(getContext(), Attr);
  462. }
  463. void Function::addFnAttrs(const AttrBuilder &Attrs) {
  464. AttributeSets = AttributeSets.addFnAttributes(getContext(), Attrs);
  465. }
  466. void Function::addRetAttr(Attribute::AttrKind Kind) {
  467. AttributeSets = AttributeSets.addRetAttribute(getContext(), Kind);
  468. }
  469. void Function::addRetAttr(Attribute Attr) {
  470. AttributeSets = AttributeSets.addRetAttribute(getContext(), Attr);
  471. }
  472. void Function::addRetAttrs(const AttrBuilder &Attrs) {
  473. AttributeSets = AttributeSets.addRetAttributes(getContext(), Attrs);
  474. }
  475. void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
  476. AttributeSets = AttributeSets.addParamAttribute(getContext(), ArgNo, Kind);
  477. }
  478. void Function::addParamAttr(unsigned ArgNo, Attribute Attr) {
  479. AttributeSets = AttributeSets.addParamAttribute(getContext(), ArgNo, Attr);
  480. }
  481. void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
  482. AttributeSets = AttributeSets.addParamAttributes(getContext(), ArgNo, Attrs);
  483. }
  484. void Function::removeAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) {
  485. AttributeSets = AttributeSets.removeAttributeAtIndex(getContext(), i, Kind);
  486. }
  487. void Function::removeAttributeAtIndex(unsigned i, StringRef Kind) {
  488. AttributeSets = AttributeSets.removeAttributeAtIndex(getContext(), i, Kind);
  489. }
  490. void Function::removeFnAttr(Attribute::AttrKind Kind) {
  491. AttributeSets = AttributeSets.removeFnAttribute(getContext(), Kind);
  492. }
  493. void Function::removeFnAttr(StringRef Kind) {
  494. AttributeSets = AttributeSets.removeFnAttribute(getContext(), Kind);
  495. }
  496. void Function::removeFnAttrs(const AttributeMask &AM) {
  497. AttributeSets = AttributeSets.removeFnAttributes(getContext(), AM);
  498. }
  499. void Function::removeRetAttr(Attribute::AttrKind Kind) {
  500. AttributeSets = AttributeSets.removeRetAttribute(getContext(), Kind);
  501. }
  502. void Function::removeRetAttr(StringRef Kind) {
  503. AttributeSets = AttributeSets.removeRetAttribute(getContext(), Kind);
  504. }
  505. void Function::removeRetAttrs(const AttributeMask &Attrs) {
  506. AttributeSets = AttributeSets.removeRetAttributes(getContext(), Attrs);
  507. }
  508. void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
  509. AttributeSets = AttributeSets.removeParamAttribute(getContext(), ArgNo, Kind);
  510. }
  511. void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) {
  512. AttributeSets = AttributeSets.removeParamAttribute(getContext(), ArgNo, Kind);
  513. }
  514. void Function::removeParamAttrs(unsigned ArgNo, const AttributeMask &Attrs) {
  515. AttributeSets =
  516. AttributeSets.removeParamAttributes(getContext(), ArgNo, Attrs);
  517. }
  518. void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) {
  519. AttributeSets =
  520. AttributeSets.addDereferenceableParamAttr(getContext(), ArgNo, Bytes);
  521. }
  522. bool Function::hasFnAttribute(Attribute::AttrKind Kind) const {
  523. return AttributeSets.hasFnAttr(Kind);
  524. }
  525. bool Function::hasFnAttribute(StringRef Kind) const {
  526. return AttributeSets.hasFnAttr(Kind);
  527. }
  528. bool Function::hasRetAttribute(Attribute::AttrKind Kind) const {
  529. return AttributeSets.hasRetAttr(Kind);
  530. }
  531. bool Function::hasParamAttribute(unsigned ArgNo,
  532. Attribute::AttrKind Kind) const {
  533. return AttributeSets.hasParamAttr(ArgNo, Kind);
  534. }
  535. Attribute Function::getAttributeAtIndex(unsigned i,
  536. Attribute::AttrKind Kind) const {
  537. return AttributeSets.getAttributeAtIndex(i, Kind);
  538. }
  539. Attribute Function::getAttributeAtIndex(unsigned i, StringRef Kind) const {
  540. return AttributeSets.getAttributeAtIndex(i, Kind);
  541. }
  542. Attribute Function::getFnAttribute(Attribute::AttrKind Kind) const {
  543. return AttributeSets.getFnAttr(Kind);
  544. }
  545. Attribute Function::getFnAttribute(StringRef Kind) const {
  546. return AttributeSets.getFnAttr(Kind);
  547. }
  548. /// gets the specified attribute from the list of attributes.
  549. Attribute Function::getParamAttribute(unsigned ArgNo,
  550. Attribute::AttrKind Kind) const {
  551. return AttributeSets.getParamAttr(ArgNo, Kind);
  552. }
  553. void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo,
  554. uint64_t Bytes) {
  555. AttributeSets = AttributeSets.addDereferenceableOrNullParamAttr(getContext(),
  556. ArgNo, Bytes);
  557. }
  558. DenormalMode Function::getDenormalMode(const fltSemantics &FPType) const {
  559. if (&FPType == &APFloat::IEEEsingle()) {
  560. Attribute Attr = getFnAttribute("denormal-fp-math-f32");
  561. StringRef Val = Attr.getValueAsString();
  562. if (!Val.empty())
  563. return parseDenormalFPAttribute(Val);
  564. // If the f32 variant of the attribute isn't specified, try to use the
  565. // generic one.
  566. }
  567. Attribute Attr = getFnAttribute("denormal-fp-math");
  568. return parseDenormalFPAttribute(Attr.getValueAsString());
  569. }
  570. const std::string &Function::getGC() const {
  571. assert(hasGC() && "Function has no collector");
  572. return getContext().getGC(*this);
  573. }
  574. void Function::setGC(std::string Str) {
  575. setValueSubclassDataBit(14, !Str.empty());
  576. getContext().setGC(*this, std::move(Str));
  577. }
  578. void Function::clearGC() {
  579. if (!hasGC())
  580. return;
  581. getContext().deleteGC(*this);
  582. setValueSubclassDataBit(14, false);
  583. }
  584. bool Function::hasStackProtectorFnAttr() const {
  585. return hasFnAttribute(Attribute::StackProtect) ||
  586. hasFnAttribute(Attribute::StackProtectStrong) ||
  587. hasFnAttribute(Attribute::StackProtectReq);
  588. }
  589. /// Copy all additional attributes (those not needed to create a Function) from
  590. /// the Function Src to this one.
  591. void Function::copyAttributesFrom(const Function *Src) {
  592. GlobalObject::copyAttributesFrom(Src);
  593. setCallingConv(Src->getCallingConv());
  594. setAttributes(Src->getAttributes());
  595. if (Src->hasGC())
  596. setGC(Src->getGC());
  597. else
  598. clearGC();
  599. if (Src->hasPersonalityFn())
  600. setPersonalityFn(Src->getPersonalityFn());
  601. if (Src->hasPrefixData())
  602. setPrefixData(Src->getPrefixData());
  603. if (Src->hasPrologueData())
  604. setPrologueData(Src->getPrologueData());
  605. }
  606. /// Table of string intrinsic names indexed by enum value.
  607. static const char * const IntrinsicNameTable[] = {
  608. "not_intrinsic",
  609. #define GET_INTRINSIC_NAME_TABLE
  610. #include "llvm/IR/IntrinsicImpl.inc"
  611. #undef GET_INTRINSIC_NAME_TABLE
  612. };
  613. /// Table of per-target intrinsic name tables.
  614. #define GET_INTRINSIC_TARGET_DATA
  615. #include "llvm/IR/IntrinsicImpl.inc"
  616. #undef GET_INTRINSIC_TARGET_DATA
  617. bool Function::isTargetIntrinsic(Intrinsic::ID IID) {
  618. return IID > TargetInfos[0].Count;
  619. }
  620. bool Function::isTargetIntrinsic() const {
  621. return isTargetIntrinsic(IntID);
  622. }
  623. /// Find the segment of \c IntrinsicNameTable for intrinsics with the same
  624. /// target as \c Name, or the generic table if \c Name is not target specific.
  625. ///
  626. /// Returns the relevant slice of \c IntrinsicNameTable
  627. static ArrayRef<const char *> findTargetSubtable(StringRef Name) {
  628. assert(Name.startswith("llvm."));
  629. ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos);
  630. // Drop "llvm." and take the first dotted component. That will be the target
  631. // if this is target specific.
  632. StringRef Target = Name.drop_front(5).split('.').first;
  633. auto It = partition_point(
  634. Targets, [=](const IntrinsicTargetInfo &TI) { return TI.Name < Target; });
  635. // We've either found the target or just fall back to the generic set, which
  636. // is always first.
  637. const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0];
  638. return makeArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count);
  639. }
  640. /// This does the actual lookup of an intrinsic ID which
  641. /// matches the given function name.
  642. Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) {
  643. ArrayRef<const char *> NameTable = findTargetSubtable(Name);
  644. int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name);
  645. if (Idx == -1)
  646. return Intrinsic::not_intrinsic;
  647. // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have
  648. // an index into a sub-table.
  649. int Adjust = NameTable.data() - IntrinsicNameTable;
  650. Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust);
  651. // If the intrinsic is not overloaded, require an exact match. If it is
  652. // overloaded, require either exact or prefix match.
  653. const auto MatchSize = strlen(NameTable[Idx]);
  654. assert(Name.size() >= MatchSize && "Expected either exact or prefix match");
  655. bool IsExactMatch = Name.size() == MatchSize;
  656. return IsExactMatch || Intrinsic::isOverloaded(ID) ? ID
  657. : Intrinsic::not_intrinsic;
  658. }
  659. void Function::recalculateIntrinsicID() {
  660. StringRef Name = getName();
  661. if (!Name.startswith("llvm.")) {
  662. HasLLVMReservedName = false;
  663. IntID = Intrinsic::not_intrinsic;
  664. return;
  665. }
  666. HasLLVMReservedName = true;
  667. IntID = lookupIntrinsicID(Name);
  668. }
  669. /// Returns a stable mangling for the type specified for use in the name
  670. /// mangling scheme used by 'any' types in intrinsic signatures. The mangling
  671. /// of named types is simply their name. Manglings for unnamed types consist
  672. /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
  673. /// combined with the mangling of their component types. A vararg function
  674. /// type will have a suffix of 'vararg'. Since function types can contain
  675. /// other function types, we close a function type mangling with suffix 'f'
  676. /// which can't be confused with it's prefix. This ensures we don't have
  677. /// collisions between two unrelated function types. Otherwise, you might
  678. /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.)
  679. /// The HasUnnamedType boolean is set if an unnamed type was encountered,
  680. /// indicating that extra care must be taken to ensure a unique name.
  681. static std::string getMangledTypeStr(Type *Ty, bool &HasUnnamedType) {
  682. std::string Result;
  683. if (PointerType *PTyp = dyn_cast<PointerType>(Ty)) {
  684. Result += "p" + utostr(PTyp->getAddressSpace());
  685. // Opaque pointer doesn't have pointee type information, so we just mangle
  686. // address space for opaque pointer.
  687. if (!PTyp->isOpaque())
  688. Result += getMangledTypeStr(PTyp->getNonOpaquePointerElementType(),
  689. HasUnnamedType);
  690. } else if (ArrayType *ATyp = dyn_cast<ArrayType>(Ty)) {
  691. Result += "a" + utostr(ATyp->getNumElements()) +
  692. getMangledTypeStr(ATyp->getElementType(), HasUnnamedType);
  693. } else if (StructType *STyp = dyn_cast<StructType>(Ty)) {
  694. if (!STyp->isLiteral()) {
  695. Result += "s_";
  696. if (STyp->hasName())
  697. Result += STyp->getName();
  698. else
  699. HasUnnamedType = true;
  700. } else {
  701. Result += "sl_";
  702. for (auto Elem : STyp->elements())
  703. Result += getMangledTypeStr(Elem, HasUnnamedType);
  704. }
  705. // Ensure nested structs are distinguishable.
  706. Result += "s";
  707. } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) {
  708. Result += "f_" + getMangledTypeStr(FT->getReturnType(), HasUnnamedType);
  709. for (size_t i = 0; i < FT->getNumParams(); i++)
  710. Result += getMangledTypeStr(FT->getParamType(i), HasUnnamedType);
  711. if (FT->isVarArg())
  712. Result += "vararg";
  713. // Ensure nested function types are distinguishable.
  714. Result += "f";
  715. } else if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
  716. ElementCount EC = VTy->getElementCount();
  717. if (EC.isScalable())
  718. Result += "nx";
  719. Result += "v" + utostr(EC.getKnownMinValue()) +
  720. getMangledTypeStr(VTy->getElementType(), HasUnnamedType);
  721. } else if (Ty) {
  722. switch (Ty->getTypeID()) {
  723. default: llvm_unreachable("Unhandled type");
  724. case Type::VoidTyID: Result += "isVoid"; break;
  725. case Type::MetadataTyID: Result += "Metadata"; break;
  726. case Type::HalfTyID: Result += "f16"; break;
  727. case Type::BFloatTyID: Result += "bf16"; break;
  728. case Type::FloatTyID: Result += "f32"; break;
  729. case Type::DoubleTyID: Result += "f64"; break;
  730. case Type::X86_FP80TyID: Result += "f80"; break;
  731. case Type::FP128TyID: Result += "f128"; break;
  732. case Type::PPC_FP128TyID: Result += "ppcf128"; break;
  733. case Type::X86_MMXTyID: Result += "x86mmx"; break;
  734. case Type::X86_AMXTyID: Result += "x86amx"; break;
  735. case Type::IntegerTyID:
  736. Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth());
  737. break;
  738. }
  739. }
  740. return Result;
  741. }
  742. StringRef Intrinsic::getBaseName(ID id) {
  743. assert(id < num_intrinsics && "Invalid intrinsic ID!");
  744. return IntrinsicNameTable[id];
  745. }
  746. StringRef Intrinsic::getName(ID id) {
  747. assert(id < num_intrinsics && "Invalid intrinsic ID!");
  748. assert(!Intrinsic::isOverloaded(id) &&
  749. "This version of getName does not support overloading");
  750. return getBaseName(id);
  751. }
  752. static std::string getIntrinsicNameImpl(Intrinsic::ID Id, ArrayRef<Type *> Tys,
  753. Module *M, FunctionType *FT,
  754. bool EarlyModuleCheck) {
  755. assert(Id < Intrinsic::num_intrinsics && "Invalid intrinsic ID!");
  756. assert((Tys.empty() || Intrinsic::isOverloaded(Id)) &&
  757. "This version of getName is for overloaded intrinsics only");
  758. (void)EarlyModuleCheck;
  759. assert((!EarlyModuleCheck || M ||
  760. !any_of(Tys, [](Type *T) { return isa<PointerType>(T); })) &&
  761. "Intrinsic overloading on pointer types need to provide a Module");
  762. bool HasUnnamedType = false;
  763. std::string Result(Intrinsic::getBaseName(Id));
  764. for (Type *Ty : Tys)
  765. Result += "." + getMangledTypeStr(Ty, HasUnnamedType);
  766. if (HasUnnamedType) {
  767. assert(M && "unnamed types need a module");
  768. if (!FT)
  769. FT = Intrinsic::getType(M->getContext(), Id, Tys);
  770. else
  771. assert((FT == Intrinsic::getType(M->getContext(), Id, Tys)) &&
  772. "Provided FunctionType must match arguments");
  773. return M->getUniqueIntrinsicName(Result, Id, FT);
  774. }
  775. return Result;
  776. }
  777. std::string Intrinsic::getName(ID Id, ArrayRef<Type *> Tys, Module *M,
  778. FunctionType *FT) {
  779. assert(M && "We need to have a Module");
  780. return getIntrinsicNameImpl(Id, Tys, M, FT, true);
  781. }
  782. std::string Intrinsic::getNameNoUnnamedTypes(ID Id, ArrayRef<Type *> Tys) {
  783. return getIntrinsicNameImpl(Id, Tys, nullptr, nullptr, false);
  784. }
  785. /// IIT_Info - These are enumerators that describe the entries returned by the
  786. /// getIntrinsicInfoTableEntries function.
  787. ///
  788. /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
  789. enum IIT_Info {
  790. // Common values should be encoded with 0-15.
  791. IIT_Done = 0,
  792. IIT_I1 = 1,
  793. IIT_I8 = 2,
  794. IIT_I16 = 3,
  795. IIT_I32 = 4,
  796. IIT_I64 = 5,
  797. IIT_F16 = 6,
  798. IIT_F32 = 7,
  799. IIT_F64 = 8,
  800. IIT_V2 = 9,
  801. IIT_V4 = 10,
  802. IIT_V8 = 11,
  803. IIT_V16 = 12,
  804. IIT_V32 = 13,
  805. IIT_PTR = 14,
  806. IIT_ARG = 15,
  807. // Values from 16+ are only encodable with the inefficient encoding.
  808. IIT_V64 = 16,
  809. IIT_MMX = 17,
  810. IIT_TOKEN = 18,
  811. IIT_METADATA = 19,
  812. IIT_EMPTYSTRUCT = 20,
  813. IIT_STRUCT2 = 21,
  814. IIT_STRUCT3 = 22,
  815. IIT_STRUCT4 = 23,
  816. IIT_STRUCT5 = 24,
  817. IIT_EXTEND_ARG = 25,
  818. IIT_TRUNC_ARG = 26,
  819. IIT_ANYPTR = 27,
  820. IIT_V1 = 28,
  821. IIT_VARARG = 29,
  822. IIT_HALF_VEC_ARG = 30,
  823. IIT_SAME_VEC_WIDTH_ARG = 31,
  824. IIT_PTR_TO_ARG = 32,
  825. IIT_PTR_TO_ELT = 33,
  826. IIT_VEC_OF_ANYPTRS_TO_ELT = 34,
  827. IIT_I128 = 35,
  828. IIT_V512 = 36,
  829. IIT_V1024 = 37,
  830. IIT_STRUCT6 = 38,
  831. IIT_STRUCT7 = 39,
  832. IIT_STRUCT8 = 40,
  833. IIT_F128 = 41,
  834. IIT_VEC_ELEMENT = 42,
  835. IIT_SCALABLE_VEC = 43,
  836. IIT_SUBDIVIDE2_ARG = 44,
  837. IIT_SUBDIVIDE4_ARG = 45,
  838. IIT_VEC_OF_BITCASTS_TO_INT = 46,
  839. IIT_V128 = 47,
  840. IIT_BF16 = 48,
  841. IIT_STRUCT9 = 49,
  842. IIT_V256 = 50,
  843. IIT_AMX = 51,
  844. IIT_PPCF128 = 52,
  845. IIT_V3 = 53,
  846. IIT_EXTERNREF = 54,
  847. IIT_FUNCREF = 55
  848. };
  849. static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
  850. IIT_Info LastInfo,
  851. SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
  852. using namespace Intrinsic;
  853. bool IsScalableVector = (LastInfo == IIT_SCALABLE_VEC);
  854. IIT_Info Info = IIT_Info(Infos[NextElt++]);
  855. unsigned StructElts = 2;
  856. switch (Info) {
  857. case IIT_Done:
  858. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
  859. return;
  860. case IIT_VARARG:
  861. OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
  862. return;
  863. case IIT_MMX:
  864. OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
  865. return;
  866. case IIT_AMX:
  867. OutputTable.push_back(IITDescriptor::get(IITDescriptor::AMX, 0));
  868. return;
  869. case IIT_TOKEN:
  870. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
  871. return;
  872. case IIT_METADATA:
  873. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
  874. return;
  875. case IIT_F16:
  876. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
  877. return;
  878. case IIT_BF16:
  879. OutputTable.push_back(IITDescriptor::get(IITDescriptor::BFloat, 0));
  880. return;
  881. case IIT_F32:
  882. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
  883. return;
  884. case IIT_F64:
  885. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
  886. return;
  887. case IIT_F128:
  888. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0));
  889. return;
  890. case IIT_PPCF128:
  891. OutputTable.push_back(IITDescriptor::get(IITDescriptor::PPCQuad, 0));
  892. return;
  893. case IIT_I1:
  894. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
  895. return;
  896. case IIT_I8:
  897. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
  898. return;
  899. case IIT_I16:
  900. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
  901. return;
  902. case IIT_I32:
  903. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
  904. return;
  905. case IIT_I64:
  906. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
  907. return;
  908. case IIT_I128:
  909. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
  910. return;
  911. case IIT_V1:
  912. OutputTable.push_back(IITDescriptor::getVector(1, IsScalableVector));
  913. DecodeIITType(NextElt, Infos, Info, OutputTable);
  914. return;
  915. case IIT_V2:
  916. OutputTable.push_back(IITDescriptor::getVector(2, IsScalableVector));
  917. DecodeIITType(NextElt, Infos, Info, OutputTable);
  918. return;
  919. case IIT_V3:
  920. OutputTable.push_back(IITDescriptor::getVector(3, IsScalableVector));
  921. DecodeIITType(NextElt, Infos, Info, OutputTable);
  922. return;
  923. case IIT_V4:
  924. OutputTable.push_back(IITDescriptor::getVector(4, IsScalableVector));
  925. DecodeIITType(NextElt, Infos, Info, OutputTable);
  926. return;
  927. case IIT_V8:
  928. OutputTable.push_back(IITDescriptor::getVector(8, IsScalableVector));
  929. DecodeIITType(NextElt, Infos, Info, OutputTable);
  930. return;
  931. case IIT_V16:
  932. OutputTable.push_back(IITDescriptor::getVector(16, IsScalableVector));
  933. DecodeIITType(NextElt, Infos, Info, OutputTable);
  934. return;
  935. case IIT_V32:
  936. OutputTable.push_back(IITDescriptor::getVector(32, IsScalableVector));
  937. DecodeIITType(NextElt, Infos, Info, OutputTable);
  938. return;
  939. case IIT_V64:
  940. OutputTable.push_back(IITDescriptor::getVector(64, IsScalableVector));
  941. DecodeIITType(NextElt, Infos, Info, OutputTable);
  942. return;
  943. case IIT_V128:
  944. OutputTable.push_back(IITDescriptor::getVector(128, IsScalableVector));
  945. DecodeIITType(NextElt, Infos, Info, OutputTable);
  946. return;
  947. case IIT_V256:
  948. OutputTable.push_back(IITDescriptor::getVector(256, IsScalableVector));
  949. DecodeIITType(NextElt, Infos, Info, OutputTable);
  950. return;
  951. case IIT_V512:
  952. OutputTable.push_back(IITDescriptor::getVector(512, IsScalableVector));
  953. DecodeIITType(NextElt, Infos, Info, OutputTable);
  954. return;
  955. case IIT_V1024:
  956. OutputTable.push_back(IITDescriptor::getVector(1024, IsScalableVector));
  957. DecodeIITType(NextElt, Infos, Info, OutputTable);
  958. return;
  959. case IIT_EXTERNREF:
  960. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 10));
  961. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
  962. return;
  963. case IIT_FUNCREF:
  964. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 20));
  965. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
  966. return;
  967. case IIT_PTR:
  968. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
  969. DecodeIITType(NextElt, Infos, Info, OutputTable);
  970. return;
  971. case IIT_ANYPTR: { // [ANYPTR addrspace, subtype]
  972. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
  973. Infos[NextElt++]));
  974. DecodeIITType(NextElt, Infos, Info, OutputTable);
  975. return;
  976. }
  977. case IIT_ARG: {
  978. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  979. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
  980. return;
  981. }
  982. case IIT_EXTEND_ARG: {
  983. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  984. OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
  985. ArgInfo));
  986. return;
  987. }
  988. case IIT_TRUNC_ARG: {
  989. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  990. OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
  991. ArgInfo));
  992. return;
  993. }
  994. case IIT_HALF_VEC_ARG: {
  995. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  996. OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
  997. ArgInfo));
  998. return;
  999. }
  1000. case IIT_SAME_VEC_WIDTH_ARG: {
  1001. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1002. OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
  1003. ArgInfo));
  1004. return;
  1005. }
  1006. case IIT_PTR_TO_ARG: {
  1007. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1008. OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
  1009. ArgInfo));
  1010. return;
  1011. }
  1012. case IIT_PTR_TO_ELT: {
  1013. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1014. OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo));
  1015. return;
  1016. }
  1017. case IIT_VEC_OF_ANYPTRS_TO_ELT: {
  1018. unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1019. unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1020. OutputTable.push_back(
  1021. IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo));
  1022. return;
  1023. }
  1024. case IIT_EMPTYSTRUCT:
  1025. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
  1026. return;
  1027. case IIT_STRUCT9: ++StructElts; LLVM_FALLTHROUGH;
  1028. case IIT_STRUCT8: ++StructElts; LLVM_FALLTHROUGH;
  1029. case IIT_STRUCT7: ++StructElts; LLVM_FALLTHROUGH;
  1030. case IIT_STRUCT6: ++StructElts; LLVM_FALLTHROUGH;
  1031. case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH;
  1032. case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH;
  1033. case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH;
  1034. case IIT_STRUCT2: {
  1035. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
  1036. for (unsigned i = 0; i != StructElts; ++i)
  1037. DecodeIITType(NextElt, Infos, Info, OutputTable);
  1038. return;
  1039. }
  1040. case IIT_SUBDIVIDE2_ARG: {
  1041. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1042. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide2Argument,
  1043. ArgInfo));
  1044. return;
  1045. }
  1046. case IIT_SUBDIVIDE4_ARG: {
  1047. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1048. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide4Argument,
  1049. ArgInfo));
  1050. return;
  1051. }
  1052. case IIT_VEC_ELEMENT: {
  1053. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1054. OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument,
  1055. ArgInfo));
  1056. return;
  1057. }
  1058. case IIT_SCALABLE_VEC: {
  1059. DecodeIITType(NextElt, Infos, Info, OutputTable);
  1060. return;
  1061. }
  1062. case IIT_VEC_OF_BITCASTS_TO_INT: {
  1063. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1064. OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfBitcastsToInt,
  1065. ArgInfo));
  1066. return;
  1067. }
  1068. }
  1069. llvm_unreachable("unhandled");
  1070. }
  1071. #define GET_INTRINSIC_GENERATOR_GLOBAL
  1072. #include "llvm/IR/IntrinsicImpl.inc"
  1073. #undef GET_INTRINSIC_GENERATOR_GLOBAL
  1074. void Intrinsic::getIntrinsicInfoTableEntries(ID id,
  1075. SmallVectorImpl<IITDescriptor> &T){
  1076. // Check to see if the intrinsic's type was expressible by the table.
  1077. unsigned TableVal = IIT_Table[id-1];
  1078. // Decode the TableVal into an array of IITValues.
  1079. SmallVector<unsigned char, 8> IITValues;
  1080. ArrayRef<unsigned char> IITEntries;
  1081. unsigned NextElt = 0;
  1082. if ((TableVal >> 31) != 0) {
  1083. // This is an offset into the IIT_LongEncodingTable.
  1084. IITEntries = IIT_LongEncodingTable;
  1085. // Strip sentinel bit.
  1086. NextElt = (TableVal << 1) >> 1;
  1087. } else {
  1088. // Decode the TableVal into an array of IITValues. If the entry was encoded
  1089. // into a single word in the table itself, decode it now.
  1090. do {
  1091. IITValues.push_back(TableVal & 0xF);
  1092. TableVal >>= 4;
  1093. } while (TableVal);
  1094. IITEntries = IITValues;
  1095. NextElt = 0;
  1096. }
  1097. // Okay, decode the table into the output vector of IITDescriptors.
  1098. DecodeIITType(NextElt, IITEntries, IIT_Done, T);
  1099. while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
  1100. DecodeIITType(NextElt, IITEntries, IIT_Done, T);
  1101. }
  1102. static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
  1103. ArrayRef<Type*> Tys, LLVMContext &Context) {
  1104. using namespace Intrinsic;
  1105. IITDescriptor D = Infos.front();
  1106. Infos = Infos.slice(1);
  1107. switch (D.Kind) {
  1108. case IITDescriptor::Void: return Type::getVoidTy(Context);
  1109. case IITDescriptor::VarArg: return Type::getVoidTy(Context);
  1110. case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
  1111. case IITDescriptor::AMX: return Type::getX86_AMXTy(Context);
  1112. case IITDescriptor::Token: return Type::getTokenTy(Context);
  1113. case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
  1114. case IITDescriptor::Half: return Type::getHalfTy(Context);
  1115. case IITDescriptor::BFloat: return Type::getBFloatTy(Context);
  1116. case IITDescriptor::Float: return Type::getFloatTy(Context);
  1117. case IITDescriptor::Double: return Type::getDoubleTy(Context);
  1118. case IITDescriptor::Quad: return Type::getFP128Ty(Context);
  1119. case IITDescriptor::PPCQuad: return Type::getPPC_FP128Ty(Context);
  1120. case IITDescriptor::Integer:
  1121. return IntegerType::get(Context, D.Integer_Width);
  1122. case IITDescriptor::Vector:
  1123. return VectorType::get(DecodeFixedType(Infos, Tys, Context),
  1124. D.Vector_Width);
  1125. case IITDescriptor::Pointer:
  1126. return PointerType::get(DecodeFixedType(Infos, Tys, Context),
  1127. D.Pointer_AddressSpace);
  1128. case IITDescriptor::Struct: {
  1129. SmallVector<Type *, 8> Elts;
  1130. for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
  1131. Elts.push_back(DecodeFixedType(Infos, Tys, Context));
  1132. return StructType::get(Context, Elts);
  1133. }
  1134. case IITDescriptor::Argument:
  1135. return Tys[D.getArgumentNumber()];
  1136. case IITDescriptor::ExtendArgument: {
  1137. Type *Ty = Tys[D.getArgumentNumber()];
  1138. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  1139. return VectorType::getExtendedElementVectorType(VTy);
  1140. return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
  1141. }
  1142. case IITDescriptor::TruncArgument: {
  1143. Type *Ty = Tys[D.getArgumentNumber()];
  1144. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  1145. return VectorType::getTruncatedElementVectorType(VTy);
  1146. IntegerType *ITy = cast<IntegerType>(Ty);
  1147. assert(ITy->getBitWidth() % 2 == 0);
  1148. return IntegerType::get(Context, ITy->getBitWidth() / 2);
  1149. }
  1150. case IITDescriptor::Subdivide2Argument:
  1151. case IITDescriptor::Subdivide4Argument: {
  1152. Type *Ty = Tys[D.getArgumentNumber()];
  1153. VectorType *VTy = dyn_cast<VectorType>(Ty);
  1154. assert(VTy && "Expected an argument of Vector Type");
  1155. int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
  1156. return VectorType::getSubdividedVectorType(VTy, SubDivs);
  1157. }
  1158. case IITDescriptor::HalfVecArgument:
  1159. return VectorType::getHalfElementsVectorType(cast<VectorType>(
  1160. Tys[D.getArgumentNumber()]));
  1161. case IITDescriptor::SameVecWidthArgument: {
  1162. Type *EltTy = DecodeFixedType(Infos, Tys, Context);
  1163. Type *Ty = Tys[D.getArgumentNumber()];
  1164. if (auto *VTy = dyn_cast<VectorType>(Ty))
  1165. return VectorType::get(EltTy, VTy->getElementCount());
  1166. return EltTy;
  1167. }
  1168. case IITDescriptor::PtrToArgument: {
  1169. Type *Ty = Tys[D.getArgumentNumber()];
  1170. return PointerType::getUnqual(Ty);
  1171. }
  1172. case IITDescriptor::PtrToElt: {
  1173. Type *Ty = Tys[D.getArgumentNumber()];
  1174. VectorType *VTy = dyn_cast<VectorType>(Ty);
  1175. if (!VTy)
  1176. llvm_unreachable("Expected an argument of Vector Type");
  1177. Type *EltTy = VTy->getElementType();
  1178. return PointerType::getUnqual(EltTy);
  1179. }
  1180. case IITDescriptor::VecElementArgument: {
  1181. Type *Ty = Tys[D.getArgumentNumber()];
  1182. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  1183. return VTy->getElementType();
  1184. llvm_unreachable("Expected an argument of Vector Type");
  1185. }
  1186. case IITDescriptor::VecOfBitcastsToInt: {
  1187. Type *Ty = Tys[D.getArgumentNumber()];
  1188. VectorType *VTy = dyn_cast<VectorType>(Ty);
  1189. assert(VTy && "Expected an argument of Vector Type");
  1190. return VectorType::getInteger(VTy);
  1191. }
  1192. case IITDescriptor::VecOfAnyPtrsToElt:
  1193. // Return the overloaded type (which determines the pointers address space)
  1194. return Tys[D.getOverloadArgNumber()];
  1195. }
  1196. llvm_unreachable("unhandled");
  1197. }
  1198. FunctionType *Intrinsic::getType(LLVMContext &Context,
  1199. ID id, ArrayRef<Type*> Tys) {
  1200. SmallVector<IITDescriptor, 8> Table;
  1201. getIntrinsicInfoTableEntries(id, Table);
  1202. ArrayRef<IITDescriptor> TableRef = Table;
  1203. Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
  1204. SmallVector<Type*, 8> ArgTys;
  1205. while (!TableRef.empty())
  1206. ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
  1207. // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
  1208. // If we see void type as the type of the last argument, it is vararg intrinsic
  1209. if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
  1210. ArgTys.pop_back();
  1211. return FunctionType::get(ResultTy, ArgTys, true);
  1212. }
  1213. return FunctionType::get(ResultTy, ArgTys, false);
  1214. }
  1215. bool Intrinsic::isOverloaded(ID id) {
  1216. #define GET_INTRINSIC_OVERLOAD_TABLE
  1217. #include "llvm/IR/IntrinsicImpl.inc"
  1218. #undef GET_INTRINSIC_OVERLOAD_TABLE
  1219. }
  1220. bool Intrinsic::isLeaf(ID id) {
  1221. switch (id) {
  1222. default:
  1223. return true;
  1224. case Intrinsic::experimental_gc_statepoint:
  1225. case Intrinsic::experimental_patchpoint_void:
  1226. case Intrinsic::experimental_patchpoint_i64:
  1227. return false;
  1228. }
  1229. }
  1230. /// This defines the "Intrinsic::getAttributes(ID id)" method.
  1231. #define GET_INTRINSIC_ATTRIBUTES
  1232. #include "llvm/IR/IntrinsicImpl.inc"
  1233. #undef GET_INTRINSIC_ATTRIBUTES
  1234. Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
  1235. // There can never be multiple globals with the same name of different types,
  1236. // because intrinsics must be a specific type.
  1237. auto *FT = getType(M->getContext(), id, Tys);
  1238. return cast<Function>(
  1239. M->getOrInsertFunction(Tys.empty() ? getName(id)
  1240. : getName(id, Tys, M, FT),
  1241. getType(M->getContext(), id, Tys))
  1242. .getCallee());
  1243. }
  1244. // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
  1245. #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
  1246. #include "llvm/IR/IntrinsicImpl.inc"
  1247. #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
  1248. // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
  1249. #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
  1250. #include "llvm/IR/IntrinsicImpl.inc"
  1251. #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
  1252. using DeferredIntrinsicMatchPair =
  1253. std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>;
  1254. static bool matchIntrinsicType(
  1255. Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
  1256. SmallVectorImpl<Type *> &ArgTys,
  1257. SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks,
  1258. bool IsDeferredCheck) {
  1259. using namespace Intrinsic;
  1260. // If we ran out of descriptors, there are too many arguments.
  1261. if (Infos.empty()) return true;
  1262. // Do this before slicing off the 'front' part
  1263. auto InfosRef = Infos;
  1264. auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) {
  1265. DeferredChecks.emplace_back(T, InfosRef);
  1266. return false;
  1267. };
  1268. IITDescriptor D = Infos.front();
  1269. Infos = Infos.slice(1);
  1270. switch (D.Kind) {
  1271. case IITDescriptor::Void: return !Ty->isVoidTy();
  1272. case IITDescriptor::VarArg: return true;
  1273. case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
  1274. case IITDescriptor::AMX: return !Ty->isX86_AMXTy();
  1275. case IITDescriptor::Token: return !Ty->isTokenTy();
  1276. case IITDescriptor::Metadata: return !Ty->isMetadataTy();
  1277. case IITDescriptor::Half: return !Ty->isHalfTy();
  1278. case IITDescriptor::BFloat: return !Ty->isBFloatTy();
  1279. case IITDescriptor::Float: return !Ty->isFloatTy();
  1280. case IITDescriptor::Double: return !Ty->isDoubleTy();
  1281. case IITDescriptor::Quad: return !Ty->isFP128Ty();
  1282. case IITDescriptor::PPCQuad: return !Ty->isPPC_FP128Ty();
  1283. case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
  1284. case IITDescriptor::Vector: {
  1285. VectorType *VT = dyn_cast<VectorType>(Ty);
  1286. return !VT || VT->getElementCount() != D.Vector_Width ||
  1287. matchIntrinsicType(VT->getElementType(), Infos, ArgTys,
  1288. DeferredChecks, IsDeferredCheck);
  1289. }
  1290. case IITDescriptor::Pointer: {
  1291. PointerType *PT = dyn_cast<PointerType>(Ty);
  1292. if (!PT || PT->getAddressSpace() != D.Pointer_AddressSpace)
  1293. return true;
  1294. if (!PT->isOpaque())
  1295. return matchIntrinsicType(PT->getNonOpaquePointerElementType(), Infos,
  1296. ArgTys, DeferredChecks, IsDeferredCheck);
  1297. // Consume IIT descriptors relating to the pointer element type.
  1298. while (Infos.front().Kind == IITDescriptor::Pointer)
  1299. Infos = Infos.slice(1);
  1300. Infos = Infos.slice(1);
  1301. return false;
  1302. }
  1303. case IITDescriptor::Struct: {
  1304. StructType *ST = dyn_cast<StructType>(Ty);
  1305. if (!ST || ST->getNumElements() != D.Struct_NumElements)
  1306. return true;
  1307. for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
  1308. if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys,
  1309. DeferredChecks, IsDeferredCheck))
  1310. return true;
  1311. return false;
  1312. }
  1313. case IITDescriptor::Argument:
  1314. // If this is the second occurrence of an argument,
  1315. // verify that the later instance matches the previous instance.
  1316. if (D.getArgumentNumber() < ArgTys.size())
  1317. return Ty != ArgTys[D.getArgumentNumber()];
  1318. if (D.getArgumentNumber() > ArgTys.size() ||
  1319. D.getArgumentKind() == IITDescriptor::AK_MatchType)
  1320. return IsDeferredCheck || DeferCheck(Ty);
  1321. assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck &&
  1322. "Table consistency error");
  1323. ArgTys.push_back(Ty);
  1324. switch (D.getArgumentKind()) {
  1325. case IITDescriptor::AK_Any: return false; // Success
  1326. case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
  1327. case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
  1328. case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
  1329. case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
  1330. default: break;
  1331. }
  1332. llvm_unreachable("all argument kinds not covered");
  1333. case IITDescriptor::ExtendArgument: {
  1334. // If this is a forward reference, defer the check for later.
  1335. if (D.getArgumentNumber() >= ArgTys.size())
  1336. return IsDeferredCheck || DeferCheck(Ty);
  1337. Type *NewTy = ArgTys[D.getArgumentNumber()];
  1338. if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
  1339. NewTy = VectorType::getExtendedElementVectorType(VTy);
  1340. else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
  1341. NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
  1342. else
  1343. return true;
  1344. return Ty != NewTy;
  1345. }
  1346. case IITDescriptor::TruncArgument: {
  1347. // If this is a forward reference, defer the check for later.
  1348. if (D.getArgumentNumber() >= ArgTys.size())
  1349. return IsDeferredCheck || DeferCheck(Ty);
  1350. Type *NewTy = ArgTys[D.getArgumentNumber()];
  1351. if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
  1352. NewTy = VectorType::getTruncatedElementVectorType(VTy);
  1353. else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
  1354. NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
  1355. else
  1356. return true;
  1357. return Ty != NewTy;
  1358. }
  1359. case IITDescriptor::HalfVecArgument:
  1360. // If this is a forward reference, defer the check for later.
  1361. if (D.getArgumentNumber() >= ArgTys.size())
  1362. return IsDeferredCheck || DeferCheck(Ty);
  1363. return !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
  1364. VectorType::getHalfElementsVectorType(
  1365. cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
  1366. case IITDescriptor::SameVecWidthArgument: {
  1367. if (D.getArgumentNumber() >= ArgTys.size()) {
  1368. // Defer check and subsequent check for the vector element type.
  1369. Infos = Infos.slice(1);
  1370. return IsDeferredCheck || DeferCheck(Ty);
  1371. }
  1372. auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
  1373. auto *ThisArgType = dyn_cast<VectorType>(Ty);
  1374. // Both must be vectors of the same number of elements or neither.
  1375. if ((ReferenceType != nullptr) != (ThisArgType != nullptr))
  1376. return true;
  1377. Type *EltTy = Ty;
  1378. if (ThisArgType) {
  1379. if (ReferenceType->getElementCount() !=
  1380. ThisArgType->getElementCount())
  1381. return true;
  1382. EltTy = ThisArgType->getElementType();
  1383. }
  1384. return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks,
  1385. IsDeferredCheck);
  1386. }
  1387. case IITDescriptor::PtrToArgument: {
  1388. if (D.getArgumentNumber() >= ArgTys.size())
  1389. return IsDeferredCheck || DeferCheck(Ty);
  1390. Type * ReferenceType = ArgTys[D.getArgumentNumber()];
  1391. PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
  1392. return (!ThisArgType ||
  1393. !ThisArgType->isOpaqueOrPointeeTypeMatches(ReferenceType));
  1394. }
  1395. case IITDescriptor::PtrToElt: {
  1396. if (D.getArgumentNumber() >= ArgTys.size())
  1397. return IsDeferredCheck || DeferCheck(Ty);
  1398. VectorType * ReferenceType =
  1399. dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
  1400. PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
  1401. if (!ThisArgType || !ReferenceType)
  1402. return true;
  1403. return !ThisArgType->isOpaqueOrPointeeTypeMatches(
  1404. ReferenceType->getElementType());
  1405. }
  1406. case IITDescriptor::VecOfAnyPtrsToElt: {
  1407. unsigned RefArgNumber = D.getRefArgNumber();
  1408. if (RefArgNumber >= ArgTys.size()) {
  1409. if (IsDeferredCheck)
  1410. return true;
  1411. // If forward referencing, already add the pointer-vector type and
  1412. // defer the checks for later.
  1413. ArgTys.push_back(Ty);
  1414. return DeferCheck(Ty);
  1415. }
  1416. if (!IsDeferredCheck){
  1417. assert(D.getOverloadArgNumber() == ArgTys.size() &&
  1418. "Table consistency error");
  1419. ArgTys.push_back(Ty);
  1420. }
  1421. // Verify the overloaded type "matches" the Ref type.
  1422. // i.e. Ty is a vector with the same width as Ref.
  1423. // Composed of pointers to the same element type as Ref.
  1424. auto *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]);
  1425. auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
  1426. if (!ThisArgVecTy || !ReferenceType ||
  1427. (ReferenceType->getElementCount() != ThisArgVecTy->getElementCount()))
  1428. return true;
  1429. PointerType *ThisArgEltTy =
  1430. dyn_cast<PointerType>(ThisArgVecTy->getElementType());
  1431. if (!ThisArgEltTy)
  1432. return true;
  1433. return !ThisArgEltTy->isOpaqueOrPointeeTypeMatches(
  1434. ReferenceType->getElementType());
  1435. }
  1436. case IITDescriptor::VecElementArgument: {
  1437. if (D.getArgumentNumber() >= ArgTys.size())
  1438. return IsDeferredCheck ? true : DeferCheck(Ty);
  1439. auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
  1440. return !ReferenceType || Ty != ReferenceType->getElementType();
  1441. }
  1442. case IITDescriptor::Subdivide2Argument:
  1443. case IITDescriptor::Subdivide4Argument: {
  1444. // If this is a forward reference, defer the check for later.
  1445. if (D.getArgumentNumber() >= ArgTys.size())
  1446. return IsDeferredCheck || DeferCheck(Ty);
  1447. Type *NewTy = ArgTys[D.getArgumentNumber()];
  1448. if (auto *VTy = dyn_cast<VectorType>(NewTy)) {
  1449. int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
  1450. NewTy = VectorType::getSubdividedVectorType(VTy, SubDivs);
  1451. return Ty != NewTy;
  1452. }
  1453. return true;
  1454. }
  1455. case IITDescriptor::VecOfBitcastsToInt: {
  1456. if (D.getArgumentNumber() >= ArgTys.size())
  1457. return IsDeferredCheck || DeferCheck(Ty);
  1458. auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
  1459. auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
  1460. if (!ThisArgVecTy || !ReferenceType)
  1461. return true;
  1462. return ThisArgVecTy != VectorType::getInteger(ReferenceType);
  1463. }
  1464. }
  1465. llvm_unreachable("unhandled");
  1466. }
  1467. Intrinsic::MatchIntrinsicTypesResult
  1468. Intrinsic::matchIntrinsicSignature(FunctionType *FTy,
  1469. ArrayRef<Intrinsic::IITDescriptor> &Infos,
  1470. SmallVectorImpl<Type *> &ArgTys) {
  1471. SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks;
  1472. if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks,
  1473. false))
  1474. return MatchIntrinsicTypes_NoMatchRet;
  1475. unsigned NumDeferredReturnChecks = DeferredChecks.size();
  1476. for (auto Ty : FTy->params())
  1477. if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false))
  1478. return MatchIntrinsicTypes_NoMatchArg;
  1479. for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) {
  1480. DeferredIntrinsicMatchPair &Check = DeferredChecks[I];
  1481. if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks,
  1482. true))
  1483. return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet
  1484. : MatchIntrinsicTypes_NoMatchArg;
  1485. }
  1486. return MatchIntrinsicTypes_Match;
  1487. }
  1488. bool
  1489. Intrinsic::matchIntrinsicVarArg(bool isVarArg,
  1490. ArrayRef<Intrinsic::IITDescriptor> &Infos) {
  1491. // If there are no descriptors left, then it can't be a vararg.
  1492. if (Infos.empty())
  1493. return isVarArg;
  1494. // There should be only one descriptor remaining at this point.
  1495. if (Infos.size() != 1)
  1496. return true;
  1497. // Check and verify the descriptor.
  1498. IITDescriptor D = Infos.front();
  1499. Infos = Infos.slice(1);
  1500. if (D.Kind == IITDescriptor::VarArg)
  1501. return !isVarArg;
  1502. return true;
  1503. }
  1504. bool Intrinsic::getIntrinsicSignature(Function *F,
  1505. SmallVectorImpl<Type *> &ArgTys) {
  1506. Intrinsic::ID ID = F->getIntrinsicID();
  1507. if (!ID)
  1508. return false;
  1509. SmallVector<Intrinsic::IITDescriptor, 8> Table;
  1510. getIntrinsicInfoTableEntries(ID, Table);
  1511. ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
  1512. if (Intrinsic::matchIntrinsicSignature(F->getFunctionType(), TableRef,
  1513. ArgTys) !=
  1514. Intrinsic::MatchIntrinsicTypesResult::MatchIntrinsicTypes_Match) {
  1515. return false;
  1516. }
  1517. if (Intrinsic::matchIntrinsicVarArg(F->getFunctionType()->isVarArg(),
  1518. TableRef))
  1519. return false;
  1520. return true;
  1521. }
  1522. Optional<Function *> Intrinsic::remangleIntrinsicFunction(Function *F) {
  1523. SmallVector<Type *, 4> ArgTys;
  1524. if (!getIntrinsicSignature(F, ArgTys))
  1525. return None;
  1526. Intrinsic::ID ID = F->getIntrinsicID();
  1527. StringRef Name = F->getName();
  1528. std::string WantedName =
  1529. Intrinsic::getName(ID, ArgTys, F->getParent(), F->getFunctionType());
  1530. if (Name == WantedName)
  1531. return None;
  1532. Function *NewDecl = [&] {
  1533. if (auto *ExistingGV = F->getParent()->getNamedValue(WantedName)) {
  1534. if (auto *ExistingF = dyn_cast<Function>(ExistingGV))
  1535. if (ExistingF->getFunctionType() == F->getFunctionType())
  1536. return ExistingF;
  1537. // The name already exists, but is not a function or has the wrong
  1538. // prototype. Make place for the new one by renaming the old version.
  1539. // Either this old version will be removed later on or the module is
  1540. // invalid and we'll get an error.
  1541. ExistingGV->setName(WantedName + ".renamed");
  1542. }
  1543. return Intrinsic::getDeclaration(F->getParent(), ID, ArgTys);
  1544. }();
  1545. NewDecl->setCallingConv(F->getCallingConv());
  1546. assert(NewDecl->getFunctionType() == F->getFunctionType() &&
  1547. "Shouldn't change the signature");
  1548. return NewDecl;
  1549. }
  1550. /// hasAddressTaken - returns true if there are any uses of this function
  1551. /// other than direct calls or invokes to it. Optionally ignores callback
  1552. /// uses, assume like pointer annotation calls, and references in llvm.used
  1553. /// and llvm.compiler.used variables.
  1554. bool Function::hasAddressTaken(const User **PutOffender,
  1555. bool IgnoreCallbackUses,
  1556. bool IgnoreAssumeLikeCalls, bool IgnoreLLVMUsed,
  1557. bool IgnoreARCAttachedCall) const {
  1558. for (const Use &U : uses()) {
  1559. const User *FU = U.getUser();
  1560. if (isa<BlockAddress>(FU))
  1561. continue;
  1562. if (IgnoreCallbackUses) {
  1563. AbstractCallSite ACS(&U);
  1564. if (ACS && ACS.isCallbackCall())
  1565. continue;
  1566. }
  1567. const auto *Call = dyn_cast<CallBase>(FU);
  1568. if (!Call) {
  1569. if (IgnoreAssumeLikeCalls) {
  1570. if (const auto *FI = dyn_cast<Instruction>(FU)) {
  1571. if (FI->isCast() && !FI->user_empty() &&
  1572. llvm::all_of(FU->users(), [](const User *U) {
  1573. if (const auto *I = dyn_cast<IntrinsicInst>(U))
  1574. return I->isAssumeLikeIntrinsic();
  1575. return false;
  1576. }))
  1577. continue;
  1578. }
  1579. }
  1580. if (IgnoreLLVMUsed && !FU->user_empty()) {
  1581. const User *FUU = FU;
  1582. if (isa<BitCastOperator>(FU) && FU->hasOneUse() &&
  1583. !FU->user_begin()->user_empty())
  1584. FUU = *FU->user_begin();
  1585. if (llvm::all_of(FUU->users(), [](const User *U) {
  1586. if (const auto *GV = dyn_cast<GlobalVariable>(U))
  1587. return GV->hasName() &&
  1588. (GV->getName().equals("llvm.compiler.used") ||
  1589. GV->getName().equals("llvm.used"));
  1590. return false;
  1591. }))
  1592. continue;
  1593. }
  1594. if (PutOffender)
  1595. *PutOffender = FU;
  1596. return true;
  1597. }
  1598. if (!Call->isCallee(&U)) {
  1599. if (IgnoreARCAttachedCall &&
  1600. Call->isOperandBundleOfType(LLVMContext::OB_clang_arc_attachedcall,
  1601. U.getOperandNo()))
  1602. continue;
  1603. if (PutOffender)
  1604. *PutOffender = FU;
  1605. return true;
  1606. }
  1607. }
  1608. return false;
  1609. }
  1610. bool Function::isDefTriviallyDead() const {
  1611. // Check the linkage
  1612. if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
  1613. !hasAvailableExternallyLinkage())
  1614. return false;
  1615. // Check if the function is used by anything other than a blockaddress.
  1616. for (const User *U : users())
  1617. if (!isa<BlockAddress>(U))
  1618. return false;
  1619. return true;
  1620. }
  1621. /// callsFunctionThatReturnsTwice - Return true if the function has a call to
  1622. /// setjmp or other function that gcc recognizes as "returning twice".
  1623. bool Function::callsFunctionThatReturnsTwice() const {
  1624. for (const Instruction &I : instructions(this))
  1625. if (const auto *Call = dyn_cast<CallBase>(&I))
  1626. if (Call->hasFnAttr(Attribute::ReturnsTwice))
  1627. return true;
  1628. return false;
  1629. }
  1630. Constant *Function::getPersonalityFn() const {
  1631. assert(hasPersonalityFn() && getNumOperands());
  1632. return cast<Constant>(Op<0>());
  1633. }
  1634. void Function::setPersonalityFn(Constant *Fn) {
  1635. setHungoffOperand<0>(Fn);
  1636. setValueSubclassDataBit(3, Fn != nullptr);
  1637. }
  1638. Constant *Function::getPrefixData() const {
  1639. assert(hasPrefixData() && getNumOperands());
  1640. return cast<Constant>(Op<1>());
  1641. }
  1642. void Function::setPrefixData(Constant *PrefixData) {
  1643. setHungoffOperand<1>(PrefixData);
  1644. setValueSubclassDataBit(1, PrefixData != nullptr);
  1645. }
  1646. Constant *Function::getPrologueData() const {
  1647. assert(hasPrologueData() && getNumOperands());
  1648. return cast<Constant>(Op<2>());
  1649. }
  1650. void Function::setPrologueData(Constant *PrologueData) {
  1651. setHungoffOperand<2>(PrologueData);
  1652. setValueSubclassDataBit(2, PrologueData != nullptr);
  1653. }
  1654. void Function::allocHungoffUselist() {
  1655. // If we've already allocated a uselist, stop here.
  1656. if (getNumOperands())
  1657. return;
  1658. allocHungoffUses(3, /*IsPhi=*/ false);
  1659. setNumHungOffUseOperands(3);
  1660. // Initialize the uselist with placeholder operands to allow traversal.
  1661. auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
  1662. Op<0>().set(CPN);
  1663. Op<1>().set(CPN);
  1664. Op<2>().set(CPN);
  1665. }
  1666. template <int Idx>
  1667. void Function::setHungoffOperand(Constant *C) {
  1668. if (C) {
  1669. allocHungoffUselist();
  1670. Op<Idx>().set(C);
  1671. } else if (getNumOperands()) {
  1672. Op<Idx>().set(
  1673. ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
  1674. }
  1675. }
  1676. void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
  1677. assert(Bit < 16 && "SubclassData contains only 16 bits");
  1678. if (On)
  1679. setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
  1680. else
  1681. setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
  1682. }
  1683. void Function::setEntryCount(ProfileCount Count,
  1684. const DenseSet<GlobalValue::GUID> *S) {
  1685. #if !defined(NDEBUG)
  1686. auto PrevCount = getEntryCount();
  1687. assert(!PrevCount.hasValue() || PrevCount->getType() == Count.getType());
  1688. #endif
  1689. auto ImportGUIDs = getImportGUIDs();
  1690. if (S == nullptr && ImportGUIDs.size())
  1691. S = &ImportGUIDs;
  1692. MDBuilder MDB(getContext());
  1693. setMetadata(
  1694. LLVMContext::MD_prof,
  1695. MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S));
  1696. }
  1697. void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type,
  1698. const DenseSet<GlobalValue::GUID> *Imports) {
  1699. setEntryCount(ProfileCount(Count, Type), Imports);
  1700. }
  1701. Optional<ProfileCount> Function::getEntryCount(bool AllowSynthetic) const {
  1702. MDNode *MD = getMetadata(LLVMContext::MD_prof);
  1703. if (MD && MD->getOperand(0))
  1704. if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) {
  1705. if (MDS->getString().equals("function_entry_count")) {
  1706. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
  1707. uint64_t Count = CI->getValue().getZExtValue();
  1708. // A value of -1 is used for SamplePGO when there were no samples.
  1709. // Treat this the same as unknown.
  1710. if (Count == (uint64_t)-1)
  1711. return None;
  1712. return ProfileCount(Count, PCT_Real);
  1713. } else if (AllowSynthetic &&
  1714. MDS->getString().equals("synthetic_function_entry_count")) {
  1715. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
  1716. uint64_t Count = CI->getValue().getZExtValue();
  1717. return ProfileCount(Count, PCT_Synthetic);
  1718. }
  1719. }
  1720. return None;
  1721. }
  1722. DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const {
  1723. DenseSet<GlobalValue::GUID> R;
  1724. if (MDNode *MD = getMetadata(LLVMContext::MD_prof))
  1725. if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
  1726. if (MDS->getString().equals("function_entry_count"))
  1727. for (unsigned i = 2; i < MD->getNumOperands(); i++)
  1728. R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i))
  1729. ->getValue()
  1730. .getZExtValue());
  1731. return R;
  1732. }
  1733. void Function::setSectionPrefix(StringRef Prefix) {
  1734. MDBuilder MDB(getContext());
  1735. setMetadata(LLVMContext::MD_section_prefix,
  1736. MDB.createFunctionSectionPrefix(Prefix));
  1737. }
  1738. Optional<StringRef> Function::getSectionPrefix() const {
  1739. if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) {
  1740. assert(cast<MDString>(MD->getOperand(0))
  1741. ->getString()
  1742. .equals("function_section_prefix") &&
  1743. "Metadata not match");
  1744. return cast<MDString>(MD->getOperand(1))->getString();
  1745. }
  1746. return None;
  1747. }
  1748. bool Function::nullPointerIsDefined() const {
  1749. return hasFnAttribute(Attribute::NullPointerIsValid);
  1750. }
  1751. bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) {
  1752. if (F && F->nullPointerIsDefined())
  1753. return true;
  1754. if (AS != 0)
  1755. return true;
  1756. return false;
  1757. }