Attributes.cpp 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978
  1. //===- Attributes.cpp - Implement AttributesList --------------------------===//
  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. // \file
  10. // This file implements the Attribute, AttributeImpl, AttrBuilder,
  11. // AttributeListImpl, and AttributeList classes.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/IR/Attributes.h"
  15. #include "AttributeImpl.h"
  16. #include "LLVMContextImpl.h"
  17. #include "llvm/ADT/ArrayRef.h"
  18. #include "llvm/ADT/FoldingSet.h"
  19. #include "llvm/ADT/Optional.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/StringExtras.h"
  23. #include "llvm/ADT/StringRef.h"
  24. #include "llvm/ADT/StringSwitch.h"
  25. #include "llvm/Config/llvm-config.h"
  26. #include "llvm/IR/Function.h"
  27. #include "llvm/IR/LLVMContext.h"
  28. #include "llvm/IR/Type.h"
  29. #include "llvm/Support/Compiler.h"
  30. #include "llvm/Support/Debug.h"
  31. #include "llvm/Support/ErrorHandling.h"
  32. #include "llvm/Support/raw_ostream.h"
  33. #include <algorithm>
  34. #include <cassert>
  35. #include <cstddef>
  36. #include <cstdint>
  37. #include <limits>
  38. #include <string>
  39. #include <tuple>
  40. #include <utility>
  41. using namespace llvm;
  42. //===----------------------------------------------------------------------===//
  43. // Attribute Construction Methods
  44. //===----------------------------------------------------------------------===//
  45. // allocsize has two integer arguments, but because they're both 32 bits, we can
  46. // pack them into one 64-bit value, at the cost of making said value
  47. // nonsensical.
  48. //
  49. // In order to do this, we need to reserve one value of the second (optional)
  50. // allocsize argument to signify "not present."
  51. static const unsigned AllocSizeNumElemsNotPresent = -1;
  52. static uint64_t packAllocSizeArgs(unsigned ElemSizeArg,
  53. const Optional<unsigned> &NumElemsArg) {
  54. assert((!NumElemsArg.hasValue() ||
  55. *NumElemsArg != AllocSizeNumElemsNotPresent) &&
  56. "Attempting to pack a reserved value");
  57. return uint64_t(ElemSizeArg) << 32 |
  58. NumElemsArg.getValueOr(AllocSizeNumElemsNotPresent);
  59. }
  60. static std::pair<unsigned, Optional<unsigned>>
  61. unpackAllocSizeArgs(uint64_t Num) {
  62. unsigned NumElems = Num & std::numeric_limits<unsigned>::max();
  63. unsigned ElemSizeArg = Num >> 32;
  64. Optional<unsigned> NumElemsArg;
  65. if (NumElems != AllocSizeNumElemsNotPresent)
  66. NumElemsArg = NumElems;
  67. return std::make_pair(ElemSizeArg, NumElemsArg);
  68. }
  69. static uint64_t packVScaleRangeArgs(unsigned MinValue,
  70. Optional<unsigned> MaxValue) {
  71. return uint64_t(MinValue) << 32 | MaxValue.getValueOr(0);
  72. }
  73. static std::pair<unsigned, Optional<unsigned>>
  74. unpackVScaleRangeArgs(uint64_t Value) {
  75. unsigned MaxValue = Value & std::numeric_limits<unsigned>::max();
  76. unsigned MinValue = Value >> 32;
  77. return std::make_pair(MinValue,
  78. MaxValue > 0 ? MaxValue : Optional<unsigned>());
  79. }
  80. Attribute Attribute::get(LLVMContext &Context, Attribute::AttrKind Kind,
  81. uint64_t Val) {
  82. if (Val)
  83. assert(Attribute::isIntAttrKind(Kind) && "Not an int attribute");
  84. else
  85. assert(Attribute::isEnumAttrKind(Kind) && "Not an enum attribute");
  86. LLVMContextImpl *pImpl = Context.pImpl;
  87. FoldingSetNodeID ID;
  88. ID.AddInteger(Kind);
  89. if (Val) ID.AddInteger(Val);
  90. void *InsertPoint;
  91. AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
  92. if (!PA) {
  93. // If we didn't find any existing attributes of the same shape then create a
  94. // new one and insert it.
  95. if (!Val)
  96. PA = new (pImpl->Alloc) EnumAttributeImpl(Kind);
  97. else
  98. PA = new (pImpl->Alloc) IntAttributeImpl(Kind, Val);
  99. pImpl->AttrsSet.InsertNode(PA, InsertPoint);
  100. }
  101. // Return the Attribute that we found or created.
  102. return Attribute(PA);
  103. }
  104. Attribute Attribute::get(LLVMContext &Context, StringRef Kind, StringRef Val) {
  105. LLVMContextImpl *pImpl = Context.pImpl;
  106. FoldingSetNodeID ID;
  107. ID.AddString(Kind);
  108. if (!Val.empty()) ID.AddString(Val);
  109. void *InsertPoint;
  110. AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
  111. if (!PA) {
  112. // If we didn't find any existing attributes of the same shape then create a
  113. // new one and insert it.
  114. void *Mem =
  115. pImpl->Alloc.Allocate(StringAttributeImpl::totalSizeToAlloc(Kind, Val),
  116. alignof(StringAttributeImpl));
  117. PA = new (Mem) StringAttributeImpl(Kind, Val);
  118. pImpl->AttrsSet.InsertNode(PA, InsertPoint);
  119. }
  120. // Return the Attribute that we found or created.
  121. return Attribute(PA);
  122. }
  123. Attribute Attribute::get(LLVMContext &Context, Attribute::AttrKind Kind,
  124. Type *Ty) {
  125. assert(Attribute::isTypeAttrKind(Kind) && "Not a type attribute");
  126. LLVMContextImpl *pImpl = Context.pImpl;
  127. FoldingSetNodeID ID;
  128. ID.AddInteger(Kind);
  129. ID.AddPointer(Ty);
  130. void *InsertPoint;
  131. AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
  132. if (!PA) {
  133. // If we didn't find any existing attributes of the same shape then create a
  134. // new one and insert it.
  135. PA = new (pImpl->Alloc) TypeAttributeImpl(Kind, Ty);
  136. pImpl->AttrsSet.InsertNode(PA, InsertPoint);
  137. }
  138. // Return the Attribute that we found or created.
  139. return Attribute(PA);
  140. }
  141. Attribute Attribute::getWithAlignment(LLVMContext &Context, Align A) {
  142. assert(A <= llvm::Value::MaximumAlignment && "Alignment too large.");
  143. return get(Context, Alignment, A.value());
  144. }
  145. Attribute Attribute::getWithStackAlignment(LLVMContext &Context, Align A) {
  146. assert(A <= 0x100 && "Alignment too large.");
  147. return get(Context, StackAlignment, A.value());
  148. }
  149. Attribute Attribute::getWithDereferenceableBytes(LLVMContext &Context,
  150. uint64_t Bytes) {
  151. assert(Bytes && "Bytes must be non-zero.");
  152. return get(Context, Dereferenceable, Bytes);
  153. }
  154. Attribute Attribute::getWithDereferenceableOrNullBytes(LLVMContext &Context,
  155. uint64_t Bytes) {
  156. assert(Bytes && "Bytes must be non-zero.");
  157. return get(Context, DereferenceableOrNull, Bytes);
  158. }
  159. Attribute Attribute::getWithByValType(LLVMContext &Context, Type *Ty) {
  160. return get(Context, ByVal, Ty);
  161. }
  162. Attribute Attribute::getWithStructRetType(LLVMContext &Context, Type *Ty) {
  163. return get(Context, StructRet, Ty);
  164. }
  165. Attribute Attribute::getWithByRefType(LLVMContext &Context, Type *Ty) {
  166. return get(Context, ByRef, Ty);
  167. }
  168. Attribute Attribute::getWithPreallocatedType(LLVMContext &Context, Type *Ty) {
  169. return get(Context, Preallocated, Ty);
  170. }
  171. Attribute Attribute::getWithInAllocaType(LLVMContext &Context, Type *Ty) {
  172. return get(Context, InAlloca, Ty);
  173. }
  174. Attribute
  175. Attribute::getWithAllocSizeArgs(LLVMContext &Context, unsigned ElemSizeArg,
  176. const Optional<unsigned> &NumElemsArg) {
  177. assert(!(ElemSizeArg == 0 && NumElemsArg && *NumElemsArg == 0) &&
  178. "Invalid allocsize arguments -- given allocsize(0, 0)");
  179. return get(Context, AllocSize, packAllocSizeArgs(ElemSizeArg, NumElemsArg));
  180. }
  181. Attribute Attribute::getWithVScaleRangeArgs(LLVMContext &Context,
  182. unsigned MinValue,
  183. unsigned MaxValue) {
  184. return get(Context, VScaleRange, packVScaleRangeArgs(MinValue, MaxValue));
  185. }
  186. Attribute::AttrKind Attribute::getAttrKindFromName(StringRef AttrName) {
  187. return StringSwitch<Attribute::AttrKind>(AttrName)
  188. #define GET_ATTR_NAMES
  189. #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
  190. .Case(#DISPLAY_NAME, Attribute::ENUM_NAME)
  191. #include "llvm/IR/Attributes.inc"
  192. .Default(Attribute::None);
  193. }
  194. StringRef Attribute::getNameFromAttrKind(Attribute::AttrKind AttrKind) {
  195. switch (AttrKind) {
  196. #define GET_ATTR_NAMES
  197. #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
  198. case Attribute::ENUM_NAME: \
  199. return #DISPLAY_NAME;
  200. #include "llvm/IR/Attributes.inc"
  201. case Attribute::None:
  202. return "none";
  203. default:
  204. llvm_unreachable("invalid Kind");
  205. }
  206. }
  207. bool Attribute::isExistingAttribute(StringRef Name) {
  208. return StringSwitch<bool>(Name)
  209. #define GET_ATTR_NAMES
  210. #define ATTRIBUTE_ALL(ENUM_NAME, DISPLAY_NAME) .Case(#DISPLAY_NAME, true)
  211. #include "llvm/IR/Attributes.inc"
  212. .Default(false);
  213. }
  214. //===----------------------------------------------------------------------===//
  215. // Attribute Accessor Methods
  216. //===----------------------------------------------------------------------===//
  217. bool Attribute::isEnumAttribute() const {
  218. return pImpl && pImpl->isEnumAttribute();
  219. }
  220. bool Attribute::isIntAttribute() const {
  221. return pImpl && pImpl->isIntAttribute();
  222. }
  223. bool Attribute::isStringAttribute() const {
  224. return pImpl && pImpl->isStringAttribute();
  225. }
  226. bool Attribute::isTypeAttribute() const {
  227. return pImpl && pImpl->isTypeAttribute();
  228. }
  229. Attribute::AttrKind Attribute::getKindAsEnum() const {
  230. if (!pImpl) return None;
  231. assert((isEnumAttribute() || isIntAttribute() || isTypeAttribute()) &&
  232. "Invalid attribute type to get the kind as an enum!");
  233. return pImpl->getKindAsEnum();
  234. }
  235. uint64_t Attribute::getValueAsInt() const {
  236. if (!pImpl) return 0;
  237. assert(isIntAttribute() &&
  238. "Expected the attribute to be an integer attribute!");
  239. return pImpl->getValueAsInt();
  240. }
  241. bool Attribute::getValueAsBool() const {
  242. if (!pImpl) return false;
  243. assert(isStringAttribute() &&
  244. "Expected the attribute to be a string attribute!");
  245. return pImpl->getValueAsBool();
  246. }
  247. StringRef Attribute::getKindAsString() const {
  248. if (!pImpl) return {};
  249. assert(isStringAttribute() &&
  250. "Invalid attribute type to get the kind as a string!");
  251. return pImpl->getKindAsString();
  252. }
  253. StringRef Attribute::getValueAsString() const {
  254. if (!pImpl) return {};
  255. assert(isStringAttribute() &&
  256. "Invalid attribute type to get the value as a string!");
  257. return pImpl->getValueAsString();
  258. }
  259. Type *Attribute::getValueAsType() const {
  260. if (!pImpl) return {};
  261. assert(isTypeAttribute() &&
  262. "Invalid attribute type to get the value as a type!");
  263. return pImpl->getValueAsType();
  264. }
  265. bool Attribute::hasAttribute(AttrKind Kind) const {
  266. return (pImpl && pImpl->hasAttribute(Kind)) || (!pImpl && Kind == None);
  267. }
  268. bool Attribute::hasAttribute(StringRef Kind) const {
  269. if (!isStringAttribute()) return false;
  270. return pImpl && pImpl->hasAttribute(Kind);
  271. }
  272. MaybeAlign Attribute::getAlignment() const {
  273. assert(hasAttribute(Attribute::Alignment) &&
  274. "Trying to get alignment from non-alignment attribute!");
  275. return MaybeAlign(pImpl->getValueAsInt());
  276. }
  277. MaybeAlign Attribute::getStackAlignment() const {
  278. assert(hasAttribute(Attribute::StackAlignment) &&
  279. "Trying to get alignment from non-alignment attribute!");
  280. return MaybeAlign(pImpl->getValueAsInt());
  281. }
  282. uint64_t Attribute::getDereferenceableBytes() const {
  283. assert(hasAttribute(Attribute::Dereferenceable) &&
  284. "Trying to get dereferenceable bytes from "
  285. "non-dereferenceable attribute!");
  286. return pImpl->getValueAsInt();
  287. }
  288. uint64_t Attribute::getDereferenceableOrNullBytes() const {
  289. assert(hasAttribute(Attribute::DereferenceableOrNull) &&
  290. "Trying to get dereferenceable bytes from "
  291. "non-dereferenceable attribute!");
  292. return pImpl->getValueAsInt();
  293. }
  294. std::pair<unsigned, Optional<unsigned>> Attribute::getAllocSizeArgs() const {
  295. assert(hasAttribute(Attribute::AllocSize) &&
  296. "Trying to get allocsize args from non-allocsize attribute");
  297. return unpackAllocSizeArgs(pImpl->getValueAsInt());
  298. }
  299. unsigned Attribute::getVScaleRangeMin() const {
  300. assert(hasAttribute(Attribute::VScaleRange) &&
  301. "Trying to get vscale args from non-vscale attribute");
  302. return unpackVScaleRangeArgs(pImpl->getValueAsInt()).first;
  303. }
  304. Optional<unsigned> Attribute::getVScaleRangeMax() const {
  305. assert(hasAttribute(Attribute::VScaleRange) &&
  306. "Trying to get vscale args from non-vscale attribute");
  307. return unpackVScaleRangeArgs(pImpl->getValueAsInt()).second;
  308. }
  309. std::string Attribute::getAsString(bool InAttrGrp) const {
  310. if (!pImpl) return {};
  311. if (isEnumAttribute())
  312. return getNameFromAttrKind(getKindAsEnum()).str();
  313. if (isTypeAttribute()) {
  314. std::string Result = getNameFromAttrKind(getKindAsEnum()).str();
  315. Result += '(';
  316. raw_string_ostream OS(Result);
  317. getValueAsType()->print(OS, false, true);
  318. OS.flush();
  319. Result += ')';
  320. return Result;
  321. }
  322. // FIXME: These should be output like this:
  323. //
  324. // align=4
  325. // alignstack=8
  326. //
  327. if (hasAttribute(Attribute::Alignment))
  328. return (InAttrGrp ? "align=" + Twine(getValueAsInt())
  329. : "align " + Twine(getValueAsInt()))
  330. .str();
  331. auto AttrWithBytesToString = [&](const char *Name) {
  332. return (InAttrGrp ? Name + ("=" + Twine(getValueAsInt()))
  333. : Name + ("(" + Twine(getValueAsInt())) + ")")
  334. .str();
  335. };
  336. if (hasAttribute(Attribute::StackAlignment))
  337. return AttrWithBytesToString("alignstack");
  338. if (hasAttribute(Attribute::Dereferenceable))
  339. return AttrWithBytesToString("dereferenceable");
  340. if (hasAttribute(Attribute::DereferenceableOrNull))
  341. return AttrWithBytesToString("dereferenceable_or_null");
  342. if (hasAttribute(Attribute::AllocSize)) {
  343. unsigned ElemSize;
  344. Optional<unsigned> NumElems;
  345. std::tie(ElemSize, NumElems) = getAllocSizeArgs();
  346. return (NumElems
  347. ? "allocsize(" + Twine(ElemSize) + "," + Twine(*NumElems) + ")"
  348. : "allocsize(" + Twine(ElemSize) + ")")
  349. .str();
  350. }
  351. if (hasAttribute(Attribute::VScaleRange)) {
  352. unsigned MinValue = getVScaleRangeMin();
  353. Optional<unsigned> MaxValue = getVScaleRangeMax();
  354. return ("vscale_range(" + Twine(MinValue) + "," +
  355. Twine(MaxValue.getValueOr(0)) + ")")
  356. .str();
  357. }
  358. // Convert target-dependent attributes to strings of the form:
  359. //
  360. // "kind"
  361. // "kind" = "value"
  362. //
  363. if (isStringAttribute()) {
  364. std::string Result;
  365. {
  366. raw_string_ostream OS(Result);
  367. OS << '"' << getKindAsString() << '"';
  368. // Since some attribute strings contain special characters that cannot be
  369. // printable, those have to be escaped to make the attribute value
  370. // printable as is. e.g. "\01__gnu_mcount_nc"
  371. const auto &AttrVal = pImpl->getValueAsString();
  372. if (!AttrVal.empty()) {
  373. OS << "=\"";
  374. printEscapedString(AttrVal, OS);
  375. OS << "\"";
  376. }
  377. }
  378. return Result;
  379. }
  380. llvm_unreachable("Unknown attribute");
  381. }
  382. bool Attribute::hasParentContext(LLVMContext &C) const {
  383. assert(isValid() && "invalid Attribute doesn't refer to any context");
  384. FoldingSetNodeID ID;
  385. pImpl->Profile(ID);
  386. void *Unused;
  387. return C.pImpl->AttrsSet.FindNodeOrInsertPos(ID, Unused) == pImpl;
  388. }
  389. bool Attribute::operator<(Attribute A) const {
  390. if (!pImpl && !A.pImpl) return false;
  391. if (!pImpl) return true;
  392. if (!A.pImpl) return false;
  393. return *pImpl < *A.pImpl;
  394. }
  395. void Attribute::Profile(FoldingSetNodeID &ID) const {
  396. ID.AddPointer(pImpl);
  397. }
  398. enum AttributeProperty {
  399. FnAttr = (1 << 0),
  400. ParamAttr = (1 << 1),
  401. RetAttr = (1 << 2),
  402. };
  403. #define GET_ATTR_PROP_TABLE
  404. #include "llvm/IR/Attributes.inc"
  405. static bool hasAttributeProperty(Attribute::AttrKind Kind,
  406. AttributeProperty Prop) {
  407. unsigned Index = Kind - 1;
  408. assert(Index < sizeof(AttrPropTable) / sizeof(AttrPropTable[0]) &&
  409. "Invalid attribute kind");
  410. return AttrPropTable[Index] & Prop;
  411. }
  412. bool Attribute::canUseAsFnAttr(AttrKind Kind) {
  413. return hasAttributeProperty(Kind, AttributeProperty::FnAttr);
  414. }
  415. bool Attribute::canUseAsParamAttr(AttrKind Kind) {
  416. return hasAttributeProperty(Kind, AttributeProperty::ParamAttr);
  417. }
  418. bool Attribute::canUseAsRetAttr(AttrKind Kind) {
  419. return hasAttributeProperty(Kind, AttributeProperty::RetAttr);
  420. }
  421. //===----------------------------------------------------------------------===//
  422. // AttributeImpl Definition
  423. //===----------------------------------------------------------------------===//
  424. bool AttributeImpl::hasAttribute(Attribute::AttrKind A) const {
  425. if (isStringAttribute()) return false;
  426. return getKindAsEnum() == A;
  427. }
  428. bool AttributeImpl::hasAttribute(StringRef Kind) const {
  429. if (!isStringAttribute()) return false;
  430. return getKindAsString() == Kind;
  431. }
  432. Attribute::AttrKind AttributeImpl::getKindAsEnum() const {
  433. assert(isEnumAttribute() || isIntAttribute() || isTypeAttribute());
  434. return static_cast<const EnumAttributeImpl *>(this)->getEnumKind();
  435. }
  436. uint64_t AttributeImpl::getValueAsInt() const {
  437. assert(isIntAttribute());
  438. return static_cast<const IntAttributeImpl *>(this)->getValue();
  439. }
  440. bool AttributeImpl::getValueAsBool() const {
  441. assert(getValueAsString().empty() || getValueAsString() == "false" || getValueAsString() == "true");
  442. return getValueAsString() == "true";
  443. }
  444. StringRef AttributeImpl::getKindAsString() const {
  445. assert(isStringAttribute());
  446. return static_cast<const StringAttributeImpl *>(this)->getStringKind();
  447. }
  448. StringRef AttributeImpl::getValueAsString() const {
  449. assert(isStringAttribute());
  450. return static_cast<const StringAttributeImpl *>(this)->getStringValue();
  451. }
  452. Type *AttributeImpl::getValueAsType() const {
  453. assert(isTypeAttribute());
  454. return static_cast<const TypeAttributeImpl *>(this)->getTypeValue();
  455. }
  456. bool AttributeImpl::operator<(const AttributeImpl &AI) const {
  457. if (this == &AI)
  458. return false;
  459. // This sorts the attributes with Attribute::AttrKinds coming first (sorted
  460. // relative to their enum value) and then strings.
  461. if (!isStringAttribute()) {
  462. if (AI.isStringAttribute())
  463. return true;
  464. if (getKindAsEnum() != AI.getKindAsEnum())
  465. return getKindAsEnum() < AI.getKindAsEnum();
  466. assert(!AI.isEnumAttribute() && "Non-unique attribute");
  467. assert(!AI.isTypeAttribute() && "Comparison of types would be unstable");
  468. // TODO: Is this actually needed?
  469. assert(AI.isIntAttribute() && "Only possibility left");
  470. return getValueAsInt() < AI.getValueAsInt();
  471. }
  472. if (!AI.isStringAttribute())
  473. return false;
  474. if (getKindAsString() == AI.getKindAsString())
  475. return getValueAsString() < AI.getValueAsString();
  476. return getKindAsString() < AI.getKindAsString();
  477. }
  478. //===----------------------------------------------------------------------===//
  479. // AttributeSet Definition
  480. //===----------------------------------------------------------------------===//
  481. AttributeSet AttributeSet::get(LLVMContext &C, const AttrBuilder &B) {
  482. return AttributeSet(AttributeSetNode::get(C, B));
  483. }
  484. AttributeSet AttributeSet::get(LLVMContext &C, ArrayRef<Attribute> Attrs) {
  485. return AttributeSet(AttributeSetNode::get(C, Attrs));
  486. }
  487. AttributeSet AttributeSet::addAttribute(LLVMContext &C,
  488. Attribute::AttrKind Kind) const {
  489. if (hasAttribute(Kind)) return *this;
  490. AttrBuilder B(C);
  491. B.addAttribute(Kind);
  492. return addAttributes(C, AttributeSet::get(C, B));
  493. }
  494. AttributeSet AttributeSet::addAttribute(LLVMContext &C, StringRef Kind,
  495. StringRef Value) const {
  496. AttrBuilder B(C);
  497. B.addAttribute(Kind, Value);
  498. return addAttributes(C, AttributeSet::get(C, B));
  499. }
  500. AttributeSet AttributeSet::addAttributes(LLVMContext &C,
  501. const AttributeSet AS) const {
  502. if (!hasAttributes())
  503. return AS;
  504. if (!AS.hasAttributes())
  505. return *this;
  506. AttrBuilder B(C, *this);
  507. B.merge(AttrBuilder(C, AS));
  508. return get(C, B);
  509. }
  510. AttributeSet AttributeSet::removeAttribute(LLVMContext &C,
  511. Attribute::AttrKind Kind) const {
  512. if (!hasAttribute(Kind)) return *this;
  513. AttrBuilder B(C, *this);
  514. B.removeAttribute(Kind);
  515. return get(C, B);
  516. }
  517. AttributeSet AttributeSet::removeAttribute(LLVMContext &C,
  518. StringRef Kind) const {
  519. if (!hasAttribute(Kind)) return *this;
  520. AttrBuilder B(C, *this);
  521. B.removeAttribute(Kind);
  522. return get(C, B);
  523. }
  524. AttributeSet AttributeSet::removeAttributes(LLVMContext &C,
  525. const AttributeMask &Attrs) const {
  526. AttrBuilder B(C, *this);
  527. // If there is nothing to remove, directly return the original set.
  528. if (!B.overlaps(Attrs))
  529. return *this;
  530. B.remove(Attrs);
  531. return get(C, B);
  532. }
  533. unsigned AttributeSet::getNumAttributes() const {
  534. return SetNode ? SetNode->getNumAttributes() : 0;
  535. }
  536. bool AttributeSet::hasAttribute(Attribute::AttrKind Kind) const {
  537. return SetNode ? SetNode->hasAttribute(Kind) : false;
  538. }
  539. bool AttributeSet::hasAttribute(StringRef Kind) const {
  540. return SetNode ? SetNode->hasAttribute(Kind) : false;
  541. }
  542. Attribute AttributeSet::getAttribute(Attribute::AttrKind Kind) const {
  543. return SetNode ? SetNode->getAttribute(Kind) : Attribute();
  544. }
  545. Attribute AttributeSet::getAttribute(StringRef Kind) const {
  546. return SetNode ? SetNode->getAttribute(Kind) : Attribute();
  547. }
  548. MaybeAlign AttributeSet::getAlignment() const {
  549. return SetNode ? SetNode->getAlignment() : None;
  550. }
  551. MaybeAlign AttributeSet::getStackAlignment() const {
  552. return SetNode ? SetNode->getStackAlignment() : None;
  553. }
  554. uint64_t AttributeSet::getDereferenceableBytes() const {
  555. return SetNode ? SetNode->getDereferenceableBytes() : 0;
  556. }
  557. uint64_t AttributeSet::getDereferenceableOrNullBytes() const {
  558. return SetNode ? SetNode->getDereferenceableOrNullBytes() : 0;
  559. }
  560. Type *AttributeSet::getByRefType() const {
  561. return SetNode ? SetNode->getAttributeType(Attribute::ByRef) : nullptr;
  562. }
  563. Type *AttributeSet::getByValType() const {
  564. return SetNode ? SetNode->getAttributeType(Attribute::ByVal) : nullptr;
  565. }
  566. Type *AttributeSet::getStructRetType() const {
  567. return SetNode ? SetNode->getAttributeType(Attribute::StructRet) : nullptr;
  568. }
  569. Type *AttributeSet::getPreallocatedType() const {
  570. return SetNode ? SetNode->getAttributeType(Attribute::Preallocated) : nullptr;
  571. }
  572. Type *AttributeSet::getInAllocaType() const {
  573. return SetNode ? SetNode->getAttributeType(Attribute::InAlloca) : nullptr;
  574. }
  575. Type *AttributeSet::getElementType() const {
  576. return SetNode ? SetNode->getAttributeType(Attribute::ElementType) : nullptr;
  577. }
  578. std::pair<unsigned, Optional<unsigned>> AttributeSet::getAllocSizeArgs() const {
  579. return SetNode ? SetNode->getAllocSizeArgs()
  580. : std::pair<unsigned, Optional<unsigned>>(0, 0);
  581. }
  582. unsigned AttributeSet::getVScaleRangeMin() const {
  583. return SetNode ? SetNode->getVScaleRangeMin() : 1;
  584. }
  585. Optional<unsigned> AttributeSet::getVScaleRangeMax() const {
  586. return SetNode ? SetNode->getVScaleRangeMax() : None;
  587. }
  588. std::string AttributeSet::getAsString(bool InAttrGrp) const {
  589. return SetNode ? SetNode->getAsString(InAttrGrp) : "";
  590. }
  591. bool AttributeSet::hasParentContext(LLVMContext &C) const {
  592. assert(hasAttributes() && "empty AttributeSet doesn't refer to any context");
  593. FoldingSetNodeID ID;
  594. SetNode->Profile(ID);
  595. void *Unused;
  596. return C.pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, Unused) == SetNode;
  597. }
  598. AttributeSet::iterator AttributeSet::begin() const {
  599. return SetNode ? SetNode->begin() : nullptr;
  600. }
  601. AttributeSet::iterator AttributeSet::end() const {
  602. return SetNode ? SetNode->end() : nullptr;
  603. }
  604. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  605. LLVM_DUMP_METHOD void AttributeSet::dump() const {
  606. dbgs() << "AS =\n";
  607. dbgs() << " { ";
  608. dbgs() << getAsString(true) << " }\n";
  609. }
  610. #endif
  611. //===----------------------------------------------------------------------===//
  612. // AttributeSetNode Definition
  613. //===----------------------------------------------------------------------===//
  614. AttributeSetNode::AttributeSetNode(ArrayRef<Attribute> Attrs)
  615. : NumAttrs(Attrs.size()) {
  616. // There's memory after the node where we can store the entries in.
  617. llvm::copy(Attrs, getTrailingObjects<Attribute>());
  618. for (const auto &I : *this) {
  619. if (I.isStringAttribute())
  620. StringAttrs.insert({ I.getKindAsString(), I });
  621. else
  622. AvailableAttrs.addAttribute(I.getKindAsEnum());
  623. }
  624. }
  625. AttributeSetNode *AttributeSetNode::get(LLVMContext &C,
  626. ArrayRef<Attribute> Attrs) {
  627. SmallVector<Attribute, 8> SortedAttrs(Attrs.begin(), Attrs.end());
  628. llvm::sort(SortedAttrs);
  629. return getSorted(C, SortedAttrs);
  630. }
  631. AttributeSetNode *AttributeSetNode::getSorted(LLVMContext &C,
  632. ArrayRef<Attribute> SortedAttrs) {
  633. if (SortedAttrs.empty())
  634. return nullptr;
  635. // Build a key to look up the existing attributes.
  636. LLVMContextImpl *pImpl = C.pImpl;
  637. FoldingSetNodeID ID;
  638. assert(llvm::is_sorted(SortedAttrs) && "Expected sorted attributes!");
  639. for (const auto &Attr : SortedAttrs)
  640. Attr.Profile(ID);
  641. void *InsertPoint;
  642. AttributeSetNode *PA =
  643. pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, InsertPoint);
  644. // If we didn't find any existing attributes of the same shape then create a
  645. // new one and insert it.
  646. if (!PA) {
  647. // Coallocate entries after the AttributeSetNode itself.
  648. void *Mem = ::operator new(totalSizeToAlloc<Attribute>(SortedAttrs.size()));
  649. PA = new (Mem) AttributeSetNode(SortedAttrs);
  650. pImpl->AttrsSetNodes.InsertNode(PA, InsertPoint);
  651. }
  652. // Return the AttributeSetNode that we found or created.
  653. return PA;
  654. }
  655. AttributeSetNode *AttributeSetNode::get(LLVMContext &C, const AttrBuilder &B) {
  656. return getSorted(C, B.attrs());
  657. }
  658. bool AttributeSetNode::hasAttribute(StringRef Kind) const {
  659. return StringAttrs.count(Kind);
  660. }
  661. Optional<Attribute>
  662. AttributeSetNode::findEnumAttribute(Attribute::AttrKind Kind) const {
  663. // Do a quick presence check.
  664. if (!hasAttribute(Kind))
  665. return None;
  666. // Attributes in a set are sorted by enum value, followed by string
  667. // attributes. Binary search the one we want.
  668. const Attribute *I =
  669. std::lower_bound(begin(), end() - StringAttrs.size(), Kind,
  670. [](Attribute A, Attribute::AttrKind Kind) {
  671. return A.getKindAsEnum() < Kind;
  672. });
  673. assert(I != end() && I->hasAttribute(Kind) && "Presence check failed?");
  674. return *I;
  675. }
  676. Attribute AttributeSetNode::getAttribute(Attribute::AttrKind Kind) const {
  677. if (auto A = findEnumAttribute(Kind))
  678. return *A;
  679. return {};
  680. }
  681. Attribute AttributeSetNode::getAttribute(StringRef Kind) const {
  682. return StringAttrs.lookup(Kind);
  683. }
  684. MaybeAlign AttributeSetNode::getAlignment() const {
  685. if (auto A = findEnumAttribute(Attribute::Alignment))
  686. return A->getAlignment();
  687. return None;
  688. }
  689. MaybeAlign AttributeSetNode::getStackAlignment() const {
  690. if (auto A = findEnumAttribute(Attribute::StackAlignment))
  691. return A->getStackAlignment();
  692. return None;
  693. }
  694. Type *AttributeSetNode::getAttributeType(Attribute::AttrKind Kind) const {
  695. if (auto A = findEnumAttribute(Kind))
  696. return A->getValueAsType();
  697. return nullptr;
  698. }
  699. uint64_t AttributeSetNode::getDereferenceableBytes() const {
  700. if (auto A = findEnumAttribute(Attribute::Dereferenceable))
  701. return A->getDereferenceableBytes();
  702. return 0;
  703. }
  704. uint64_t AttributeSetNode::getDereferenceableOrNullBytes() const {
  705. if (auto A = findEnumAttribute(Attribute::DereferenceableOrNull))
  706. return A->getDereferenceableOrNullBytes();
  707. return 0;
  708. }
  709. std::pair<unsigned, Optional<unsigned>>
  710. AttributeSetNode::getAllocSizeArgs() const {
  711. if (auto A = findEnumAttribute(Attribute::AllocSize))
  712. return A->getAllocSizeArgs();
  713. return std::make_pair(0, 0);
  714. }
  715. unsigned AttributeSetNode::getVScaleRangeMin() const {
  716. if (auto A = findEnumAttribute(Attribute::VScaleRange))
  717. return A->getVScaleRangeMin();
  718. return 1;
  719. }
  720. Optional<unsigned> AttributeSetNode::getVScaleRangeMax() const {
  721. if (auto A = findEnumAttribute(Attribute::VScaleRange))
  722. return A->getVScaleRangeMax();
  723. return None;
  724. }
  725. std::string AttributeSetNode::getAsString(bool InAttrGrp) const {
  726. std::string Str;
  727. for (iterator I = begin(), E = end(); I != E; ++I) {
  728. if (I != begin())
  729. Str += ' ';
  730. Str += I->getAsString(InAttrGrp);
  731. }
  732. return Str;
  733. }
  734. //===----------------------------------------------------------------------===//
  735. // AttributeListImpl Definition
  736. //===----------------------------------------------------------------------===//
  737. /// Map from AttributeList index to the internal array index. Adding one happens
  738. /// to work, because -1 wraps around to 0.
  739. static unsigned attrIdxToArrayIdx(unsigned Index) {
  740. return Index + 1;
  741. }
  742. AttributeListImpl::AttributeListImpl(ArrayRef<AttributeSet> Sets)
  743. : NumAttrSets(Sets.size()) {
  744. assert(!Sets.empty() && "pointless AttributeListImpl");
  745. // There's memory after the node where we can store the entries in.
  746. llvm::copy(Sets, getTrailingObjects<AttributeSet>());
  747. // Initialize AvailableFunctionAttrs and AvailableSomewhereAttrs
  748. // summary bitsets.
  749. for (const auto &I : Sets[attrIdxToArrayIdx(AttributeList::FunctionIndex)])
  750. if (!I.isStringAttribute())
  751. AvailableFunctionAttrs.addAttribute(I.getKindAsEnum());
  752. for (const auto &Set : Sets)
  753. for (const auto &I : Set)
  754. if (!I.isStringAttribute())
  755. AvailableSomewhereAttrs.addAttribute(I.getKindAsEnum());
  756. }
  757. void AttributeListImpl::Profile(FoldingSetNodeID &ID) const {
  758. Profile(ID, makeArrayRef(begin(), end()));
  759. }
  760. void AttributeListImpl::Profile(FoldingSetNodeID &ID,
  761. ArrayRef<AttributeSet> Sets) {
  762. for (const auto &Set : Sets)
  763. ID.AddPointer(Set.SetNode);
  764. }
  765. bool AttributeListImpl::hasAttrSomewhere(Attribute::AttrKind Kind,
  766. unsigned *Index) const {
  767. if (!AvailableSomewhereAttrs.hasAttribute(Kind))
  768. return false;
  769. if (Index) {
  770. for (unsigned I = 0, E = NumAttrSets; I != E; ++I) {
  771. if (begin()[I].hasAttribute(Kind)) {
  772. *Index = I - 1;
  773. break;
  774. }
  775. }
  776. }
  777. return true;
  778. }
  779. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  780. LLVM_DUMP_METHOD void AttributeListImpl::dump() const {
  781. AttributeList(const_cast<AttributeListImpl *>(this)).dump();
  782. }
  783. #endif
  784. //===----------------------------------------------------------------------===//
  785. // AttributeList Construction and Mutation Methods
  786. //===----------------------------------------------------------------------===//
  787. AttributeList AttributeList::getImpl(LLVMContext &C,
  788. ArrayRef<AttributeSet> AttrSets) {
  789. assert(!AttrSets.empty() && "pointless AttributeListImpl");
  790. LLVMContextImpl *pImpl = C.pImpl;
  791. FoldingSetNodeID ID;
  792. AttributeListImpl::Profile(ID, AttrSets);
  793. void *InsertPoint;
  794. AttributeListImpl *PA =
  795. pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint);
  796. // If we didn't find any existing attributes of the same shape then
  797. // create a new one and insert it.
  798. if (!PA) {
  799. // Coallocate entries after the AttributeListImpl itself.
  800. void *Mem = pImpl->Alloc.Allocate(
  801. AttributeListImpl::totalSizeToAlloc<AttributeSet>(AttrSets.size()),
  802. alignof(AttributeListImpl));
  803. PA = new (Mem) AttributeListImpl(AttrSets);
  804. pImpl->AttrsLists.InsertNode(PA, InsertPoint);
  805. }
  806. // Return the AttributesList that we found or created.
  807. return AttributeList(PA);
  808. }
  809. AttributeList
  810. AttributeList::get(LLVMContext &C,
  811. ArrayRef<std::pair<unsigned, Attribute>> Attrs) {
  812. // If there are no attributes then return a null AttributesList pointer.
  813. if (Attrs.empty())
  814. return {};
  815. assert(llvm::is_sorted(Attrs,
  816. [](const std::pair<unsigned, Attribute> &LHS,
  817. const std::pair<unsigned, Attribute> &RHS) {
  818. return LHS.first < RHS.first;
  819. }) &&
  820. "Misordered Attributes list!");
  821. assert(llvm::all_of(Attrs,
  822. [](const std::pair<unsigned, Attribute> &Pair) {
  823. return Pair.second.isValid();
  824. }) &&
  825. "Pointless attribute!");
  826. // Create a vector if (unsigned, AttributeSetNode*) pairs from the attributes
  827. // list.
  828. SmallVector<std::pair<unsigned, AttributeSet>, 8> AttrPairVec;
  829. for (ArrayRef<std::pair<unsigned, Attribute>>::iterator I = Attrs.begin(),
  830. E = Attrs.end(); I != E; ) {
  831. unsigned Index = I->first;
  832. SmallVector<Attribute, 4> AttrVec;
  833. while (I != E && I->first == Index) {
  834. AttrVec.push_back(I->second);
  835. ++I;
  836. }
  837. AttrPairVec.emplace_back(Index, AttributeSet::get(C, AttrVec));
  838. }
  839. return get(C, AttrPairVec);
  840. }
  841. AttributeList
  842. AttributeList::get(LLVMContext &C,
  843. ArrayRef<std::pair<unsigned, AttributeSet>> Attrs) {
  844. // If there are no attributes then return a null AttributesList pointer.
  845. if (Attrs.empty())
  846. return {};
  847. assert(llvm::is_sorted(Attrs,
  848. [](const std::pair<unsigned, AttributeSet> &LHS,
  849. const std::pair<unsigned, AttributeSet> &RHS) {
  850. return LHS.first < RHS.first;
  851. }) &&
  852. "Misordered Attributes list!");
  853. assert(llvm::none_of(Attrs,
  854. [](const std::pair<unsigned, AttributeSet> &Pair) {
  855. return !Pair.second.hasAttributes();
  856. }) &&
  857. "Pointless attribute!");
  858. unsigned MaxIndex = Attrs.back().first;
  859. // If the MaxIndex is FunctionIndex and there are other indices in front
  860. // of it, we need to use the largest of those to get the right size.
  861. if (MaxIndex == FunctionIndex && Attrs.size() > 1)
  862. MaxIndex = Attrs[Attrs.size() - 2].first;
  863. SmallVector<AttributeSet, 4> AttrVec(attrIdxToArrayIdx(MaxIndex) + 1);
  864. for (const auto &Pair : Attrs)
  865. AttrVec[attrIdxToArrayIdx(Pair.first)] = Pair.second;
  866. return getImpl(C, AttrVec);
  867. }
  868. AttributeList AttributeList::get(LLVMContext &C, AttributeSet FnAttrs,
  869. AttributeSet RetAttrs,
  870. ArrayRef<AttributeSet> ArgAttrs) {
  871. // Scan from the end to find the last argument with attributes. Most
  872. // arguments don't have attributes, so it's nice if we can have fewer unique
  873. // AttributeListImpls by dropping empty attribute sets at the end of the list.
  874. unsigned NumSets = 0;
  875. for (size_t I = ArgAttrs.size(); I != 0; --I) {
  876. if (ArgAttrs[I - 1].hasAttributes()) {
  877. NumSets = I + 2;
  878. break;
  879. }
  880. }
  881. if (NumSets == 0) {
  882. // Check function and return attributes if we didn't have argument
  883. // attributes.
  884. if (RetAttrs.hasAttributes())
  885. NumSets = 2;
  886. else if (FnAttrs.hasAttributes())
  887. NumSets = 1;
  888. }
  889. // If all attribute sets were empty, we can use the empty attribute list.
  890. if (NumSets == 0)
  891. return {};
  892. SmallVector<AttributeSet, 8> AttrSets;
  893. AttrSets.reserve(NumSets);
  894. // If we have any attributes, we always have function attributes.
  895. AttrSets.push_back(FnAttrs);
  896. if (NumSets > 1)
  897. AttrSets.push_back(RetAttrs);
  898. if (NumSets > 2) {
  899. // Drop the empty argument attribute sets at the end.
  900. ArgAttrs = ArgAttrs.take_front(NumSets - 2);
  901. llvm::append_range(AttrSets, ArgAttrs);
  902. }
  903. return getImpl(C, AttrSets);
  904. }
  905. AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
  906. AttributeSet Attrs) {
  907. if (!Attrs.hasAttributes())
  908. return {};
  909. Index = attrIdxToArrayIdx(Index);
  910. SmallVector<AttributeSet, 8> AttrSets(Index + 1);
  911. AttrSets[Index] = Attrs;
  912. return getImpl(C, AttrSets);
  913. }
  914. AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
  915. const AttrBuilder &B) {
  916. return get(C, Index, AttributeSet::get(C, B));
  917. }
  918. AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
  919. ArrayRef<Attribute::AttrKind> Kinds) {
  920. SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
  921. for (const auto K : Kinds)
  922. Attrs.emplace_back(Index, Attribute::get(C, K));
  923. return get(C, Attrs);
  924. }
  925. AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
  926. ArrayRef<Attribute::AttrKind> Kinds,
  927. ArrayRef<uint64_t> Values) {
  928. assert(Kinds.size() == Values.size() && "Mismatched attribute values.");
  929. SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
  930. auto VI = Values.begin();
  931. for (const auto K : Kinds)
  932. Attrs.emplace_back(Index, Attribute::get(C, K, *VI++));
  933. return get(C, Attrs);
  934. }
  935. AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
  936. ArrayRef<StringRef> Kinds) {
  937. SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
  938. for (const auto &K : Kinds)
  939. Attrs.emplace_back(Index, Attribute::get(C, K));
  940. return get(C, Attrs);
  941. }
  942. AttributeList AttributeList::get(LLVMContext &C,
  943. ArrayRef<AttributeList> Attrs) {
  944. if (Attrs.empty())
  945. return {};
  946. if (Attrs.size() == 1)
  947. return Attrs[0];
  948. unsigned MaxSize = 0;
  949. for (const auto &List : Attrs)
  950. MaxSize = std::max(MaxSize, List.getNumAttrSets());
  951. // If every list was empty, there is no point in merging the lists.
  952. if (MaxSize == 0)
  953. return {};
  954. SmallVector<AttributeSet, 8> NewAttrSets(MaxSize);
  955. for (unsigned I = 0; I < MaxSize; ++I) {
  956. AttrBuilder CurBuilder(C);
  957. for (const auto &List : Attrs)
  958. CurBuilder.merge(AttrBuilder(C, List.getAttributes(I - 1)));
  959. NewAttrSets[I] = AttributeSet::get(C, CurBuilder);
  960. }
  961. return getImpl(C, NewAttrSets);
  962. }
  963. AttributeList
  964. AttributeList::addAttributeAtIndex(LLVMContext &C, unsigned Index,
  965. Attribute::AttrKind Kind) const {
  966. if (hasAttributeAtIndex(Index, Kind))
  967. return *this;
  968. AttributeSet Attrs = getAttributes(Index);
  969. // TODO: Insert at correct position and avoid sort.
  970. SmallVector<Attribute, 8> NewAttrs(Attrs.begin(), Attrs.end());
  971. NewAttrs.push_back(Attribute::get(C, Kind));
  972. return setAttributesAtIndex(C, Index, AttributeSet::get(C, NewAttrs));
  973. }
  974. AttributeList AttributeList::addAttributeAtIndex(LLVMContext &C, unsigned Index,
  975. StringRef Kind,
  976. StringRef Value) const {
  977. AttrBuilder B(C);
  978. B.addAttribute(Kind, Value);
  979. return addAttributesAtIndex(C, Index, B);
  980. }
  981. AttributeList AttributeList::addAttributeAtIndex(LLVMContext &C, unsigned Index,
  982. Attribute A) const {
  983. AttrBuilder B(C);
  984. B.addAttribute(A);
  985. return addAttributesAtIndex(C, Index, B);
  986. }
  987. AttributeList AttributeList::setAttributesAtIndex(LLVMContext &C,
  988. unsigned Index,
  989. AttributeSet Attrs) const {
  990. Index = attrIdxToArrayIdx(Index);
  991. SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
  992. if (Index >= AttrSets.size())
  993. AttrSets.resize(Index + 1);
  994. AttrSets[Index] = Attrs;
  995. return AttributeList::getImpl(C, AttrSets);
  996. }
  997. AttributeList AttributeList::addAttributesAtIndex(LLVMContext &C,
  998. unsigned Index,
  999. const AttrBuilder &B) const {
  1000. if (!B.hasAttributes())
  1001. return *this;
  1002. if (!pImpl)
  1003. return AttributeList::get(C, {{Index, AttributeSet::get(C, B)}});
  1004. AttrBuilder Merged(C, getAttributes(Index));
  1005. Merged.merge(B);
  1006. return setAttributesAtIndex(C, Index, AttributeSet::get(C, Merged));
  1007. }
  1008. AttributeList AttributeList::addParamAttribute(LLVMContext &C,
  1009. ArrayRef<unsigned> ArgNos,
  1010. Attribute A) const {
  1011. assert(llvm::is_sorted(ArgNos));
  1012. SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
  1013. unsigned MaxIndex = attrIdxToArrayIdx(ArgNos.back() + FirstArgIndex);
  1014. if (MaxIndex >= AttrSets.size())
  1015. AttrSets.resize(MaxIndex + 1);
  1016. for (unsigned ArgNo : ArgNos) {
  1017. unsigned Index = attrIdxToArrayIdx(ArgNo + FirstArgIndex);
  1018. AttrBuilder B(C, AttrSets[Index]);
  1019. B.addAttribute(A);
  1020. AttrSets[Index] = AttributeSet::get(C, B);
  1021. }
  1022. return getImpl(C, AttrSets);
  1023. }
  1024. AttributeList
  1025. AttributeList::removeAttributeAtIndex(LLVMContext &C, unsigned Index,
  1026. Attribute::AttrKind Kind) const {
  1027. if (!hasAttributeAtIndex(Index, Kind))
  1028. return *this;
  1029. Index = attrIdxToArrayIdx(Index);
  1030. SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
  1031. assert(Index < AttrSets.size());
  1032. AttrSets[Index] = AttrSets[Index].removeAttribute(C, Kind);
  1033. return getImpl(C, AttrSets);
  1034. }
  1035. AttributeList AttributeList::removeAttributeAtIndex(LLVMContext &C,
  1036. unsigned Index,
  1037. StringRef Kind) const {
  1038. if (!hasAttributeAtIndex(Index, Kind))
  1039. return *this;
  1040. Index = attrIdxToArrayIdx(Index);
  1041. SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
  1042. assert(Index < AttrSets.size());
  1043. AttrSets[Index] = AttrSets[Index].removeAttribute(C, Kind);
  1044. return getImpl(C, AttrSets);
  1045. }
  1046. AttributeList AttributeList::removeAttributesAtIndex(
  1047. LLVMContext &C, unsigned Index, const AttributeMask &AttrsToRemove) const {
  1048. AttributeSet Attrs = getAttributes(Index);
  1049. AttributeSet NewAttrs = Attrs.removeAttributes(C, AttrsToRemove);
  1050. // If nothing was removed, return the original list.
  1051. if (Attrs == NewAttrs)
  1052. return *this;
  1053. return setAttributesAtIndex(C, Index, NewAttrs);
  1054. }
  1055. AttributeList
  1056. AttributeList::removeAttributesAtIndex(LLVMContext &C,
  1057. unsigned WithoutIndex) const {
  1058. if (!pImpl)
  1059. return {};
  1060. WithoutIndex = attrIdxToArrayIdx(WithoutIndex);
  1061. if (WithoutIndex >= getNumAttrSets())
  1062. return *this;
  1063. SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
  1064. AttrSets[WithoutIndex] = AttributeSet();
  1065. return getImpl(C, AttrSets);
  1066. }
  1067. AttributeList AttributeList::addDereferenceableRetAttr(LLVMContext &C,
  1068. uint64_t Bytes) const {
  1069. AttrBuilder B(C);
  1070. B.addDereferenceableAttr(Bytes);
  1071. return addRetAttributes(C, B);
  1072. }
  1073. AttributeList AttributeList::addDereferenceableParamAttr(LLVMContext &C,
  1074. unsigned Index,
  1075. uint64_t Bytes) const {
  1076. AttrBuilder B(C);
  1077. B.addDereferenceableAttr(Bytes);
  1078. return addParamAttributes(C, Index, B);
  1079. }
  1080. AttributeList
  1081. AttributeList::addDereferenceableOrNullParamAttr(LLVMContext &C, unsigned Index,
  1082. uint64_t Bytes) const {
  1083. AttrBuilder B(C);
  1084. B.addDereferenceableOrNullAttr(Bytes);
  1085. return addParamAttributes(C, Index, B);
  1086. }
  1087. AttributeList
  1088. AttributeList::addAllocSizeParamAttr(LLVMContext &C, unsigned Index,
  1089. unsigned ElemSizeArg,
  1090. const Optional<unsigned> &NumElemsArg) {
  1091. AttrBuilder B(C);
  1092. B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
  1093. return addParamAttributes(C, Index, B);
  1094. }
  1095. //===----------------------------------------------------------------------===//
  1096. // AttributeList Accessor Methods
  1097. //===----------------------------------------------------------------------===//
  1098. AttributeSet AttributeList::getParamAttrs(unsigned ArgNo) const {
  1099. return getAttributes(ArgNo + FirstArgIndex);
  1100. }
  1101. AttributeSet AttributeList::getRetAttrs() const {
  1102. return getAttributes(ReturnIndex);
  1103. }
  1104. AttributeSet AttributeList::getFnAttrs() const {
  1105. return getAttributes(FunctionIndex);
  1106. }
  1107. bool AttributeList::hasAttributeAtIndex(unsigned Index,
  1108. Attribute::AttrKind Kind) const {
  1109. return getAttributes(Index).hasAttribute(Kind);
  1110. }
  1111. bool AttributeList::hasAttributeAtIndex(unsigned Index, StringRef Kind) const {
  1112. return getAttributes(Index).hasAttribute(Kind);
  1113. }
  1114. bool AttributeList::hasAttributesAtIndex(unsigned Index) const {
  1115. return getAttributes(Index).hasAttributes();
  1116. }
  1117. bool AttributeList::hasFnAttr(Attribute::AttrKind Kind) const {
  1118. return pImpl && pImpl->hasFnAttribute(Kind);
  1119. }
  1120. bool AttributeList::hasFnAttr(StringRef Kind) const {
  1121. return hasAttributeAtIndex(AttributeList::FunctionIndex, Kind);
  1122. }
  1123. bool AttributeList::hasAttrSomewhere(Attribute::AttrKind Attr,
  1124. unsigned *Index) const {
  1125. return pImpl && pImpl->hasAttrSomewhere(Attr, Index);
  1126. }
  1127. Attribute AttributeList::getAttributeAtIndex(unsigned Index,
  1128. Attribute::AttrKind Kind) const {
  1129. return getAttributes(Index).getAttribute(Kind);
  1130. }
  1131. Attribute AttributeList::getAttributeAtIndex(unsigned Index,
  1132. StringRef Kind) const {
  1133. return getAttributes(Index).getAttribute(Kind);
  1134. }
  1135. MaybeAlign AttributeList::getRetAlignment() const {
  1136. return getAttributes(ReturnIndex).getAlignment();
  1137. }
  1138. MaybeAlign AttributeList::getParamAlignment(unsigned ArgNo) const {
  1139. return getAttributes(ArgNo + FirstArgIndex).getAlignment();
  1140. }
  1141. MaybeAlign AttributeList::getParamStackAlignment(unsigned ArgNo) const {
  1142. return getAttributes(ArgNo + FirstArgIndex).getStackAlignment();
  1143. }
  1144. Type *AttributeList::getParamByValType(unsigned Index) const {
  1145. return getAttributes(Index+FirstArgIndex).getByValType();
  1146. }
  1147. Type *AttributeList::getParamStructRetType(unsigned Index) const {
  1148. return getAttributes(Index + FirstArgIndex).getStructRetType();
  1149. }
  1150. Type *AttributeList::getParamByRefType(unsigned Index) const {
  1151. return getAttributes(Index + FirstArgIndex).getByRefType();
  1152. }
  1153. Type *AttributeList::getParamPreallocatedType(unsigned Index) const {
  1154. return getAttributes(Index + FirstArgIndex).getPreallocatedType();
  1155. }
  1156. Type *AttributeList::getParamInAllocaType(unsigned Index) const {
  1157. return getAttributes(Index + FirstArgIndex).getInAllocaType();
  1158. }
  1159. Type *AttributeList::getParamElementType(unsigned Index) const {
  1160. return getAttributes(Index + FirstArgIndex).getElementType();
  1161. }
  1162. MaybeAlign AttributeList::getFnStackAlignment() const {
  1163. return getFnAttrs().getStackAlignment();
  1164. }
  1165. MaybeAlign AttributeList::getRetStackAlignment() const {
  1166. return getRetAttrs().getStackAlignment();
  1167. }
  1168. uint64_t AttributeList::getRetDereferenceableBytes() const {
  1169. return getRetAttrs().getDereferenceableBytes();
  1170. }
  1171. uint64_t AttributeList::getParamDereferenceableBytes(unsigned Index) const {
  1172. return getParamAttrs(Index).getDereferenceableBytes();
  1173. }
  1174. uint64_t AttributeList::getRetDereferenceableOrNullBytes() const {
  1175. return getRetAttrs().getDereferenceableOrNullBytes();
  1176. }
  1177. uint64_t
  1178. AttributeList::getParamDereferenceableOrNullBytes(unsigned Index) const {
  1179. return getParamAttrs(Index).getDereferenceableOrNullBytes();
  1180. }
  1181. std::string AttributeList::getAsString(unsigned Index, bool InAttrGrp) const {
  1182. return getAttributes(Index).getAsString(InAttrGrp);
  1183. }
  1184. AttributeSet AttributeList::getAttributes(unsigned Index) const {
  1185. Index = attrIdxToArrayIdx(Index);
  1186. if (!pImpl || Index >= getNumAttrSets())
  1187. return {};
  1188. return pImpl->begin()[Index];
  1189. }
  1190. bool AttributeList::hasParentContext(LLVMContext &C) const {
  1191. assert(!isEmpty() && "an empty attribute list has no parent context");
  1192. FoldingSetNodeID ID;
  1193. pImpl->Profile(ID);
  1194. void *Unused;
  1195. return C.pImpl->AttrsLists.FindNodeOrInsertPos(ID, Unused) == pImpl;
  1196. }
  1197. AttributeList::iterator AttributeList::begin() const {
  1198. return pImpl ? pImpl->begin() : nullptr;
  1199. }
  1200. AttributeList::iterator AttributeList::end() const {
  1201. return pImpl ? pImpl->end() : nullptr;
  1202. }
  1203. //===----------------------------------------------------------------------===//
  1204. // AttributeList Introspection Methods
  1205. //===----------------------------------------------------------------------===//
  1206. unsigned AttributeList::getNumAttrSets() const {
  1207. return pImpl ? pImpl->NumAttrSets : 0;
  1208. }
  1209. void AttributeList::print(raw_ostream &O) const {
  1210. O << "AttributeList[\n";
  1211. for (unsigned i : indexes()) {
  1212. if (!getAttributes(i).hasAttributes())
  1213. continue;
  1214. O << " { ";
  1215. switch (i) {
  1216. case AttrIndex::ReturnIndex:
  1217. O << "return";
  1218. break;
  1219. case AttrIndex::FunctionIndex:
  1220. O << "function";
  1221. break;
  1222. default:
  1223. O << "arg(" << i - AttrIndex::FirstArgIndex << ")";
  1224. }
  1225. O << " => " << getAsString(i) << " }\n";
  1226. }
  1227. O << "]\n";
  1228. }
  1229. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1230. LLVM_DUMP_METHOD void AttributeList::dump() const { print(dbgs()); }
  1231. #endif
  1232. //===----------------------------------------------------------------------===//
  1233. // AttrBuilder Method Implementations
  1234. //===----------------------------------------------------------------------===//
  1235. AttrBuilder::AttrBuilder(LLVMContext &Ctx, AttributeSet AS) : Ctx(Ctx) {
  1236. append_range(Attrs, AS);
  1237. assert(is_sorted(Attrs) && "AttributeSet should be sorted");
  1238. }
  1239. void AttrBuilder::clear() { Attrs.clear(); }
  1240. /// Attribute comparator that only compares attribute keys. Enum attributes are
  1241. /// sorted before string attributes.
  1242. struct AttributeComparator {
  1243. bool operator()(Attribute A0, Attribute A1) const {
  1244. bool A0IsString = A0.isStringAttribute();
  1245. bool A1IsString = A1.isStringAttribute();
  1246. if (A0IsString) {
  1247. if (A1IsString)
  1248. return A0.getKindAsString() < A1.getKindAsString();
  1249. else
  1250. return false;
  1251. }
  1252. if (A1IsString)
  1253. return true;
  1254. return A0.getKindAsEnum() < A1.getKindAsEnum();
  1255. }
  1256. bool operator()(Attribute A0, Attribute::AttrKind Kind) const {
  1257. if (A0.isStringAttribute())
  1258. return false;
  1259. return A0.getKindAsEnum() < Kind;
  1260. }
  1261. bool operator()(Attribute A0, StringRef Kind) const {
  1262. if (A0.isStringAttribute())
  1263. return A0.getKindAsString() < Kind;
  1264. return true;
  1265. }
  1266. };
  1267. template <typename K>
  1268. static void addAttributeImpl(SmallVectorImpl<Attribute> &Attrs, K Kind,
  1269. Attribute Attr) {
  1270. auto It = lower_bound(Attrs, Kind, AttributeComparator());
  1271. if (It != Attrs.end() && It->hasAttribute(Kind))
  1272. std::swap(*It, Attr);
  1273. else
  1274. Attrs.insert(It, Attr);
  1275. }
  1276. AttrBuilder &AttrBuilder::addAttribute(Attribute Attr) {
  1277. if (Attr.isStringAttribute())
  1278. addAttributeImpl(Attrs, Attr.getKindAsString(), Attr);
  1279. else
  1280. addAttributeImpl(Attrs, Attr.getKindAsEnum(), Attr);
  1281. return *this;
  1282. }
  1283. AttrBuilder &AttrBuilder::addAttribute(Attribute::AttrKind Kind) {
  1284. addAttributeImpl(Attrs, Kind, Attribute::get(Ctx, Kind));
  1285. return *this;
  1286. }
  1287. AttrBuilder &AttrBuilder::addAttribute(StringRef A, StringRef V) {
  1288. addAttributeImpl(Attrs, A, Attribute::get(Ctx, A, V));
  1289. return *this;
  1290. }
  1291. AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) {
  1292. assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!");
  1293. auto It = lower_bound(Attrs, Val, AttributeComparator());
  1294. if (It != Attrs.end() && It->hasAttribute(Val))
  1295. Attrs.erase(It);
  1296. return *this;
  1297. }
  1298. AttrBuilder &AttrBuilder::removeAttribute(StringRef A) {
  1299. auto It = lower_bound(Attrs, A, AttributeComparator());
  1300. if (It != Attrs.end() && It->hasAttribute(A))
  1301. Attrs.erase(It);
  1302. return *this;
  1303. }
  1304. uint64_t AttrBuilder::getRawIntAttr(Attribute::AttrKind Kind) const {
  1305. assert(Attribute::isIntAttrKind(Kind) && "Not an int attribute");
  1306. Attribute A = getAttribute(Kind);
  1307. return A.isValid() ? A.getValueAsInt() : 0;
  1308. }
  1309. AttrBuilder &AttrBuilder::addRawIntAttr(Attribute::AttrKind Kind,
  1310. uint64_t Value) {
  1311. return addAttribute(Attribute::get(Ctx, Kind, Value));
  1312. }
  1313. std::pair<unsigned, Optional<unsigned>> AttrBuilder::getAllocSizeArgs() const {
  1314. return unpackAllocSizeArgs(getRawIntAttr(Attribute::AllocSize));
  1315. }
  1316. unsigned AttrBuilder::getVScaleRangeMin() const {
  1317. return unpackVScaleRangeArgs(getRawIntAttr(Attribute::VScaleRange)).first;
  1318. }
  1319. Optional<unsigned> AttrBuilder::getVScaleRangeMax() const {
  1320. return unpackVScaleRangeArgs(getRawIntAttr(Attribute::VScaleRange)).second;
  1321. }
  1322. AttrBuilder &AttrBuilder::addAlignmentAttr(MaybeAlign Align) {
  1323. if (!Align)
  1324. return *this;
  1325. assert(*Align <= llvm::Value::MaximumAlignment && "Alignment too large.");
  1326. return addRawIntAttr(Attribute::Alignment, Align->value());
  1327. }
  1328. AttrBuilder &AttrBuilder::addStackAlignmentAttr(MaybeAlign Align) {
  1329. // Default alignment, allow the target to define how to align it.
  1330. if (!Align)
  1331. return *this;
  1332. assert(*Align <= 0x100 && "Alignment too large.");
  1333. return addRawIntAttr(Attribute::StackAlignment, Align->value());
  1334. }
  1335. AttrBuilder &AttrBuilder::addDereferenceableAttr(uint64_t Bytes) {
  1336. if (Bytes == 0) return *this;
  1337. return addRawIntAttr(Attribute::Dereferenceable, Bytes);
  1338. }
  1339. AttrBuilder &AttrBuilder::addDereferenceableOrNullAttr(uint64_t Bytes) {
  1340. if (Bytes == 0)
  1341. return *this;
  1342. return addRawIntAttr(Attribute::DereferenceableOrNull, Bytes);
  1343. }
  1344. AttrBuilder &AttrBuilder::addAllocSizeAttr(unsigned ElemSize,
  1345. const Optional<unsigned> &NumElems) {
  1346. return addAllocSizeAttrFromRawRepr(packAllocSizeArgs(ElemSize, NumElems));
  1347. }
  1348. AttrBuilder &AttrBuilder::addAllocSizeAttrFromRawRepr(uint64_t RawArgs) {
  1349. // (0, 0) is our "not present" value, so we need to check for it here.
  1350. assert(RawArgs && "Invalid allocsize arguments -- given allocsize(0, 0)");
  1351. return addRawIntAttr(Attribute::AllocSize, RawArgs);
  1352. }
  1353. AttrBuilder &AttrBuilder::addVScaleRangeAttr(unsigned MinValue,
  1354. Optional<unsigned> MaxValue) {
  1355. return addVScaleRangeAttrFromRawRepr(packVScaleRangeArgs(MinValue, MaxValue));
  1356. }
  1357. AttrBuilder &AttrBuilder::addVScaleRangeAttrFromRawRepr(uint64_t RawArgs) {
  1358. // (0, 0) is not present hence ignore this case
  1359. if (RawArgs == 0)
  1360. return *this;
  1361. return addRawIntAttr(Attribute::VScaleRange, RawArgs);
  1362. }
  1363. Type *AttrBuilder::getTypeAttr(Attribute::AttrKind Kind) const {
  1364. assert(Attribute::isTypeAttrKind(Kind) && "Not a type attribute");
  1365. Attribute A = getAttribute(Kind);
  1366. return A.isValid() ? A.getValueAsType() : nullptr;
  1367. }
  1368. AttrBuilder &AttrBuilder::addTypeAttr(Attribute::AttrKind Kind, Type *Ty) {
  1369. return addAttribute(Attribute::get(Ctx, Kind, Ty));
  1370. }
  1371. AttrBuilder &AttrBuilder::addByValAttr(Type *Ty) {
  1372. return addTypeAttr(Attribute::ByVal, Ty);
  1373. }
  1374. AttrBuilder &AttrBuilder::addStructRetAttr(Type *Ty) {
  1375. return addTypeAttr(Attribute::StructRet, Ty);
  1376. }
  1377. AttrBuilder &AttrBuilder::addByRefAttr(Type *Ty) {
  1378. return addTypeAttr(Attribute::ByRef, Ty);
  1379. }
  1380. AttrBuilder &AttrBuilder::addPreallocatedAttr(Type *Ty) {
  1381. return addTypeAttr(Attribute::Preallocated, Ty);
  1382. }
  1383. AttrBuilder &AttrBuilder::addInAllocaAttr(Type *Ty) {
  1384. return addTypeAttr(Attribute::InAlloca, Ty);
  1385. }
  1386. AttrBuilder &AttrBuilder::merge(const AttrBuilder &B) {
  1387. // TODO: Could make this O(n) as we're merging two sorted lists.
  1388. for (const auto &I : B.attrs())
  1389. addAttribute(I);
  1390. return *this;
  1391. }
  1392. AttrBuilder &AttrBuilder::remove(const AttributeMask &AM) {
  1393. erase_if(Attrs, [&](Attribute A) { return AM.contains(A); });
  1394. return *this;
  1395. }
  1396. bool AttrBuilder::overlaps(const AttributeMask &AM) const {
  1397. return any_of(Attrs, [&](Attribute A) { return AM.contains(A); });
  1398. }
  1399. Attribute AttrBuilder::getAttribute(Attribute::AttrKind A) const {
  1400. assert((unsigned)A < Attribute::EndAttrKinds && "Attribute out of range!");
  1401. auto It = lower_bound(Attrs, A, AttributeComparator());
  1402. if (It != Attrs.end() && It->hasAttribute(A))
  1403. return *It;
  1404. return {};
  1405. }
  1406. Attribute AttrBuilder::getAttribute(StringRef A) const {
  1407. auto It = lower_bound(Attrs, A, AttributeComparator());
  1408. if (It != Attrs.end() && It->hasAttribute(A))
  1409. return *It;
  1410. return {};
  1411. }
  1412. bool AttrBuilder::contains(Attribute::AttrKind A) const {
  1413. return getAttribute(A).isValid();
  1414. }
  1415. bool AttrBuilder::contains(StringRef A) const {
  1416. return getAttribute(A).isValid();
  1417. }
  1418. bool AttrBuilder::hasAlignmentAttr() const {
  1419. return getRawIntAttr(Attribute::Alignment) != 0;
  1420. }
  1421. bool AttrBuilder::operator==(const AttrBuilder &B) const {
  1422. return Attrs == B.Attrs;
  1423. }
  1424. //===----------------------------------------------------------------------===//
  1425. // AttributeFuncs Function Defintions
  1426. //===----------------------------------------------------------------------===//
  1427. /// Which attributes cannot be applied to a type.
  1428. AttributeMask AttributeFuncs::typeIncompatible(Type *Ty) {
  1429. AttributeMask Incompatible;
  1430. if (!Ty->isIntegerTy())
  1431. // Attributes that only apply to integers.
  1432. Incompatible.addAttribute(Attribute::SExt)
  1433. .addAttribute(Attribute::ZExt);
  1434. if (!Ty->isPointerTy())
  1435. // Attributes that only apply to pointers.
  1436. Incompatible.addAttribute(Attribute::Nest)
  1437. .addAttribute(Attribute::NoAlias)
  1438. .addAttribute(Attribute::NoCapture)
  1439. .addAttribute(Attribute::NonNull)
  1440. .addAttribute(Attribute::ReadNone)
  1441. .addAttribute(Attribute::ReadOnly)
  1442. .addAttribute(Attribute::SwiftError)
  1443. .addAttribute(Attribute::Dereferenceable)
  1444. .addAttribute(Attribute::DereferenceableOrNull)
  1445. .addAttribute(Attribute::Preallocated)
  1446. .addAttribute(Attribute::InAlloca)
  1447. .addAttribute(Attribute::ByVal)
  1448. .addAttribute(Attribute::StructRet)
  1449. .addAttribute(Attribute::ByRef)
  1450. .addAttribute(Attribute::ElementType);
  1451. if (!Ty->isPtrOrPtrVectorTy())
  1452. // Attributes that only apply to pointers or vectors of pointers.
  1453. Incompatible.addAttribute(Attribute::Alignment);
  1454. // Some attributes can apply to all "values" but there are no `void` values.
  1455. if (Ty->isVoidTy())
  1456. Incompatible.addAttribute(Attribute::NoUndef);
  1457. return Incompatible;
  1458. }
  1459. AttributeMask AttributeFuncs::getUBImplyingAttributes() {
  1460. AttributeMask AM;
  1461. AM.addAttribute(Attribute::NoUndef);
  1462. AM.addAttribute(Attribute::Dereferenceable);
  1463. AM.addAttribute(Attribute::DereferenceableOrNull);
  1464. return AM;
  1465. }
  1466. template<typename AttrClass>
  1467. static bool isEqual(const Function &Caller, const Function &Callee) {
  1468. return Caller.getFnAttribute(AttrClass::getKind()) ==
  1469. Callee.getFnAttribute(AttrClass::getKind());
  1470. }
  1471. /// Compute the logical AND of the attributes of the caller and the
  1472. /// callee.
  1473. ///
  1474. /// This function sets the caller's attribute to false if the callee's attribute
  1475. /// is false.
  1476. template<typename AttrClass>
  1477. static void setAND(Function &Caller, const Function &Callee) {
  1478. if (AttrClass::isSet(Caller, AttrClass::getKind()) &&
  1479. !AttrClass::isSet(Callee, AttrClass::getKind()))
  1480. AttrClass::set(Caller, AttrClass::getKind(), false);
  1481. }
  1482. /// Compute the logical OR of the attributes of the caller and the
  1483. /// callee.
  1484. ///
  1485. /// This function sets the caller's attribute to true if the callee's attribute
  1486. /// is true.
  1487. template<typename AttrClass>
  1488. static void setOR(Function &Caller, const Function &Callee) {
  1489. if (!AttrClass::isSet(Caller, AttrClass::getKind()) &&
  1490. AttrClass::isSet(Callee, AttrClass::getKind()))
  1491. AttrClass::set(Caller, AttrClass::getKind(), true);
  1492. }
  1493. /// If the inlined function had a higher stack protection level than the
  1494. /// calling function, then bump up the caller's stack protection level.
  1495. static void adjustCallerSSPLevel(Function &Caller, const Function &Callee) {
  1496. // If the calling function has *no* stack protection level (e.g. it was built
  1497. // with Clang's -fno-stack-protector or no_stack_protector attribute), don't
  1498. // change it as that could change the program's semantics.
  1499. if (!Caller.hasStackProtectorFnAttr())
  1500. return;
  1501. // If upgrading the SSP attribute, clear out the old SSP Attributes first.
  1502. // Having multiple SSP attributes doesn't actually hurt, but it adds useless
  1503. // clutter to the IR.
  1504. AttributeMask OldSSPAttr;
  1505. OldSSPAttr.addAttribute(Attribute::StackProtect)
  1506. .addAttribute(Attribute::StackProtectStrong)
  1507. .addAttribute(Attribute::StackProtectReq);
  1508. if (Callee.hasFnAttribute(Attribute::StackProtectReq)) {
  1509. Caller.removeFnAttrs(OldSSPAttr);
  1510. Caller.addFnAttr(Attribute::StackProtectReq);
  1511. } else if (Callee.hasFnAttribute(Attribute::StackProtectStrong) &&
  1512. !Caller.hasFnAttribute(Attribute::StackProtectReq)) {
  1513. Caller.removeFnAttrs(OldSSPAttr);
  1514. Caller.addFnAttr(Attribute::StackProtectStrong);
  1515. } else if (Callee.hasFnAttribute(Attribute::StackProtect) &&
  1516. !Caller.hasFnAttribute(Attribute::StackProtectReq) &&
  1517. !Caller.hasFnAttribute(Attribute::StackProtectStrong))
  1518. Caller.addFnAttr(Attribute::StackProtect);
  1519. }
  1520. /// If the inlined function required stack probes, then ensure that
  1521. /// the calling function has those too.
  1522. static void adjustCallerStackProbes(Function &Caller, const Function &Callee) {
  1523. if (!Caller.hasFnAttribute("probe-stack") &&
  1524. Callee.hasFnAttribute("probe-stack")) {
  1525. Caller.addFnAttr(Callee.getFnAttribute("probe-stack"));
  1526. }
  1527. }
  1528. /// If the inlined function defines the size of guard region
  1529. /// on the stack, then ensure that the calling function defines a guard region
  1530. /// that is no larger.
  1531. static void
  1532. adjustCallerStackProbeSize(Function &Caller, const Function &Callee) {
  1533. Attribute CalleeAttr = Callee.getFnAttribute("stack-probe-size");
  1534. if (CalleeAttr.isValid()) {
  1535. Attribute CallerAttr = Caller.getFnAttribute("stack-probe-size");
  1536. if (CallerAttr.isValid()) {
  1537. uint64_t CallerStackProbeSize, CalleeStackProbeSize;
  1538. CallerAttr.getValueAsString().getAsInteger(0, CallerStackProbeSize);
  1539. CalleeAttr.getValueAsString().getAsInteger(0, CalleeStackProbeSize);
  1540. if (CallerStackProbeSize > CalleeStackProbeSize) {
  1541. Caller.addFnAttr(CalleeAttr);
  1542. }
  1543. } else {
  1544. Caller.addFnAttr(CalleeAttr);
  1545. }
  1546. }
  1547. }
  1548. /// If the inlined function defines a min legal vector width, then ensure
  1549. /// the calling function has the same or larger min legal vector width. If the
  1550. /// caller has the attribute, but the callee doesn't, we need to remove the
  1551. /// attribute from the caller since we can't make any guarantees about the
  1552. /// caller's requirements.
  1553. /// This function is called after the inlining decision has been made so we have
  1554. /// to merge the attribute this way. Heuristics that would use
  1555. /// min-legal-vector-width to determine inline compatibility would need to be
  1556. /// handled as part of inline cost analysis.
  1557. static void
  1558. adjustMinLegalVectorWidth(Function &Caller, const Function &Callee) {
  1559. Attribute CallerAttr = Caller.getFnAttribute("min-legal-vector-width");
  1560. if (CallerAttr.isValid()) {
  1561. Attribute CalleeAttr = Callee.getFnAttribute("min-legal-vector-width");
  1562. if (CalleeAttr.isValid()) {
  1563. uint64_t CallerVectorWidth, CalleeVectorWidth;
  1564. CallerAttr.getValueAsString().getAsInteger(0, CallerVectorWidth);
  1565. CalleeAttr.getValueAsString().getAsInteger(0, CalleeVectorWidth);
  1566. if (CallerVectorWidth < CalleeVectorWidth)
  1567. Caller.addFnAttr(CalleeAttr);
  1568. } else {
  1569. // If the callee doesn't have the attribute then we don't know anything
  1570. // and must drop the attribute from the caller.
  1571. Caller.removeFnAttr("min-legal-vector-width");
  1572. }
  1573. }
  1574. }
  1575. /// If the inlined function has null_pointer_is_valid attribute,
  1576. /// set this attribute in the caller post inlining.
  1577. static void
  1578. adjustNullPointerValidAttr(Function &Caller, const Function &Callee) {
  1579. if (Callee.nullPointerIsDefined() && !Caller.nullPointerIsDefined()) {
  1580. Caller.addFnAttr(Attribute::NullPointerIsValid);
  1581. }
  1582. }
  1583. struct EnumAttr {
  1584. static bool isSet(const Function &Fn,
  1585. Attribute::AttrKind Kind) {
  1586. return Fn.hasFnAttribute(Kind);
  1587. }
  1588. static void set(Function &Fn,
  1589. Attribute::AttrKind Kind, bool Val) {
  1590. if (Val)
  1591. Fn.addFnAttr(Kind);
  1592. else
  1593. Fn.removeFnAttr(Kind);
  1594. }
  1595. };
  1596. struct StrBoolAttr {
  1597. static bool isSet(const Function &Fn,
  1598. StringRef Kind) {
  1599. auto A = Fn.getFnAttribute(Kind);
  1600. return A.getValueAsString().equals("true");
  1601. }
  1602. static void set(Function &Fn,
  1603. StringRef Kind, bool Val) {
  1604. Fn.addFnAttr(Kind, Val ? "true" : "false");
  1605. }
  1606. };
  1607. #define GET_ATTR_NAMES
  1608. #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
  1609. struct ENUM_NAME##Attr : EnumAttr { \
  1610. static enum Attribute::AttrKind getKind() { \
  1611. return llvm::Attribute::ENUM_NAME; \
  1612. } \
  1613. };
  1614. #define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
  1615. struct ENUM_NAME##Attr : StrBoolAttr { \
  1616. static StringRef getKind() { return #DISPLAY_NAME; } \
  1617. };
  1618. #include "llvm/IR/Attributes.inc"
  1619. #define GET_ATTR_COMPAT_FUNC
  1620. #include "llvm/IR/Attributes.inc"
  1621. bool AttributeFuncs::areInlineCompatible(const Function &Caller,
  1622. const Function &Callee) {
  1623. return hasCompatibleFnAttrs(Caller, Callee);
  1624. }
  1625. bool AttributeFuncs::areOutlineCompatible(const Function &A,
  1626. const Function &B) {
  1627. return hasCompatibleFnAttrs(A, B);
  1628. }
  1629. void AttributeFuncs::mergeAttributesForInlining(Function &Caller,
  1630. const Function &Callee) {
  1631. mergeFnAttrs(Caller, Callee);
  1632. }
  1633. void AttributeFuncs::mergeAttributesForOutlining(Function &Base,
  1634. const Function &ToMerge) {
  1635. // We merge functions so that they meet the most general case.
  1636. // For example, if the NoNansFPMathAttr is set in one function, but not in
  1637. // the other, in the merged function we can say that the NoNansFPMathAttr
  1638. // is not set.
  1639. // However if we have the SpeculativeLoadHardeningAttr set true in one
  1640. // function, but not the other, we make sure that the function retains
  1641. // that aspect in the merged function.
  1642. mergeFnAttrs(Base, ToMerge);
  1643. }