Record.h 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/TableGen/Record.h - Classes for Table Records -------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the main TableGen data structures, including the TableGen
  15. // types, values, and high-level data structures.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_TABLEGEN_RECORD_H
  19. #define LLVM_TABLEGEN_RECORD_H
  20. #include "llvm/ADT/ArrayRef.h"
  21. #include "llvm/ADT/DenseMap.h"
  22. #include "llvm/ADT/DenseSet.h"
  23. #include "llvm/ADT/FoldingSet.h"
  24. #include "llvm/ADT/PointerIntPair.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/StringExtras.h"
  27. #include "llvm/ADT/StringRef.h"
  28. #include "llvm/Support/Casting.h"
  29. #include "llvm/Support/ErrorHandling.h"
  30. #include "llvm/Support/SMLoc.h"
  31. #include "llvm/Support/Timer.h"
  32. #include "llvm/Support/TrailingObjects.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include <algorithm>
  35. #include <cassert>
  36. #include <cstddef>
  37. #include <cstdint>
  38. #include <map>
  39. #include <memory>
  40. #include <string>
  41. #include <utility>
  42. #include <vector>
  43. namespace llvm {
  44. namespace detail {
  45. struct RecordContext;
  46. } // namespace detail
  47. class ListRecTy;
  48. class Record;
  49. class RecordKeeper;
  50. class RecordVal;
  51. class Resolver;
  52. class StringInit;
  53. class TypedInit;
  54. //===----------------------------------------------------------------------===//
  55. // Type Classes
  56. //===----------------------------------------------------------------------===//
  57. class RecTy {
  58. public:
  59. /// Subclass discriminator (for dyn_cast<> et al.)
  60. enum RecTyKind {
  61. BitRecTyKind,
  62. BitsRecTyKind,
  63. IntRecTyKind,
  64. StringRecTyKind,
  65. ListRecTyKind,
  66. DagRecTyKind,
  67. RecordRecTyKind
  68. };
  69. private:
  70. RecTyKind Kind;
  71. /// ListRecTy of the list that has elements of this type.
  72. ListRecTy *ListTy = nullptr;
  73. public:
  74. RecTy(RecTyKind K) : Kind(K) {}
  75. virtual ~RecTy() = default;
  76. RecTyKind getRecTyKind() const { return Kind; }
  77. virtual std::string getAsString() const = 0;
  78. void print(raw_ostream &OS) const { OS << getAsString(); }
  79. void dump() const;
  80. /// Return true if all values of 'this' type can be converted to the specified
  81. /// type.
  82. virtual bool typeIsConvertibleTo(const RecTy *RHS) const;
  83. /// Return true if 'this' type is equal to or a subtype of RHS. For example,
  84. /// a bit set is not an int, but they are convertible.
  85. virtual bool typeIsA(const RecTy *RHS) const;
  86. /// Returns the type representing list<thistype>.
  87. ListRecTy *getListTy();
  88. };
  89. inline raw_ostream &operator<<(raw_ostream &OS, const RecTy &Ty) {
  90. Ty.print(OS);
  91. return OS;
  92. }
  93. /// 'bit' - Represent a single bit
  94. class BitRecTy : public RecTy {
  95. friend detail::RecordContext;
  96. BitRecTy() : RecTy(BitRecTyKind) {}
  97. public:
  98. static bool classof(const RecTy *RT) {
  99. return RT->getRecTyKind() == BitRecTyKind;
  100. }
  101. static BitRecTy *get();
  102. std::string getAsString() const override { return "bit"; }
  103. bool typeIsConvertibleTo(const RecTy *RHS) const override;
  104. };
  105. /// 'bits<n>' - Represent a fixed number of bits
  106. class BitsRecTy : public RecTy {
  107. unsigned Size;
  108. explicit BitsRecTy(unsigned Sz) : RecTy(BitsRecTyKind), Size(Sz) {}
  109. public:
  110. static bool classof(const RecTy *RT) {
  111. return RT->getRecTyKind() == BitsRecTyKind;
  112. }
  113. static BitsRecTy *get(unsigned Sz);
  114. unsigned getNumBits() const { return Size; }
  115. std::string getAsString() const override;
  116. bool typeIsConvertibleTo(const RecTy *RHS) const override;
  117. bool typeIsA(const RecTy *RHS) const override;
  118. };
  119. /// 'int' - Represent an integer value of no particular size
  120. class IntRecTy : public RecTy {
  121. friend detail::RecordContext;
  122. IntRecTy() : RecTy(IntRecTyKind) {}
  123. public:
  124. static bool classof(const RecTy *RT) {
  125. return RT->getRecTyKind() == IntRecTyKind;
  126. }
  127. static IntRecTy *get();
  128. std::string getAsString() const override { return "int"; }
  129. bool typeIsConvertibleTo(const RecTy *RHS) const override;
  130. };
  131. /// 'string' - Represent an string value
  132. class StringRecTy : public RecTy {
  133. friend detail::RecordContext;
  134. StringRecTy() : RecTy(StringRecTyKind) {}
  135. public:
  136. static bool classof(const RecTy *RT) {
  137. return RT->getRecTyKind() == StringRecTyKind;
  138. }
  139. static StringRecTy *get();
  140. std::string getAsString() const override;
  141. bool typeIsConvertibleTo(const RecTy *RHS) const override;
  142. };
  143. /// 'list<Ty>' - Represent a list of element values, all of which must be of
  144. /// the specified type. The type is stored in ElementTy.
  145. class ListRecTy : public RecTy {
  146. friend ListRecTy *RecTy::getListTy();
  147. RecTy *ElementTy;
  148. explicit ListRecTy(RecTy *T) : RecTy(ListRecTyKind), ElementTy(T) {}
  149. public:
  150. static bool classof(const RecTy *RT) {
  151. return RT->getRecTyKind() == ListRecTyKind;
  152. }
  153. static ListRecTy *get(RecTy *T) { return T->getListTy(); }
  154. RecTy *getElementType() const { return ElementTy; }
  155. std::string getAsString() const override;
  156. bool typeIsConvertibleTo(const RecTy *RHS) const override;
  157. bool typeIsA(const RecTy *RHS) const override;
  158. };
  159. /// 'dag' - Represent a dag fragment
  160. class DagRecTy : public RecTy {
  161. friend detail::RecordContext;
  162. DagRecTy() : RecTy(DagRecTyKind) {}
  163. public:
  164. static bool classof(const RecTy *RT) {
  165. return RT->getRecTyKind() == DagRecTyKind;
  166. }
  167. static DagRecTy *get();
  168. std::string getAsString() const override;
  169. };
  170. /// '[classname]' - Type of record values that have zero or more superclasses.
  171. ///
  172. /// The list of superclasses is non-redundant, i.e. only contains classes that
  173. /// are not the superclass of some other listed class.
  174. class RecordRecTy final : public RecTy, public FoldingSetNode,
  175. public TrailingObjects<RecordRecTy, Record *> {
  176. friend class Record;
  177. friend detail::RecordContext;
  178. unsigned NumClasses;
  179. explicit RecordRecTy(unsigned Num)
  180. : RecTy(RecordRecTyKind), NumClasses(Num) {}
  181. public:
  182. RecordRecTy(const RecordRecTy &) = delete;
  183. RecordRecTy &operator=(const RecordRecTy &) = delete;
  184. // Do not use sized deallocation due to trailing objects.
  185. void operator delete(void *p) { ::operator delete(p); }
  186. static bool classof(const RecTy *RT) {
  187. return RT->getRecTyKind() == RecordRecTyKind;
  188. }
  189. /// Get the record type with the given non-redundant list of superclasses.
  190. static RecordRecTy *get(ArrayRef<Record *> Classes);
  191. void Profile(FoldingSetNodeID &ID) const;
  192. ArrayRef<Record *> getClasses() const {
  193. return makeArrayRef(getTrailingObjects<Record *>(), NumClasses);
  194. }
  195. using const_record_iterator = Record * const *;
  196. const_record_iterator classes_begin() const { return getClasses().begin(); }
  197. const_record_iterator classes_end() const { return getClasses().end(); }
  198. std::string getAsString() const override;
  199. bool isSubClassOf(Record *Class) const;
  200. bool typeIsConvertibleTo(const RecTy *RHS) const override;
  201. bool typeIsA(const RecTy *RHS) const override;
  202. };
  203. /// Find a common type that T1 and T2 convert to.
  204. /// Return 0 if no such type exists.
  205. RecTy *resolveTypes(RecTy *T1, RecTy *T2);
  206. //===----------------------------------------------------------------------===//
  207. // Initializer Classes
  208. //===----------------------------------------------------------------------===//
  209. class Init {
  210. protected:
  211. /// Discriminator enum (for isa<>, dyn_cast<>, et al.)
  212. ///
  213. /// This enum is laid out by a preorder traversal of the inheritance
  214. /// hierarchy, and does not contain an entry for abstract classes, as per
  215. /// the recommendation in docs/HowToSetUpLLVMStyleRTTI.rst.
  216. ///
  217. /// We also explicitly include "first" and "last" values for each
  218. /// interior node of the inheritance tree, to make it easier to read the
  219. /// corresponding classof().
  220. ///
  221. /// We could pack these a bit tighter by not having the IK_FirstXXXInit
  222. /// and IK_LastXXXInit be their own values, but that would degrade
  223. /// readability for really no benefit.
  224. enum InitKind : uint8_t {
  225. IK_First, // unused; silence a spurious warning
  226. IK_FirstTypedInit,
  227. IK_BitInit,
  228. IK_BitsInit,
  229. IK_DagInit,
  230. IK_DefInit,
  231. IK_FieldInit,
  232. IK_IntInit,
  233. IK_ListInit,
  234. IK_FirstOpInit,
  235. IK_BinOpInit,
  236. IK_TernOpInit,
  237. IK_UnOpInit,
  238. IK_LastOpInit,
  239. IK_CondOpInit,
  240. IK_FoldOpInit,
  241. IK_IsAOpInit,
  242. IK_AnonymousNameInit,
  243. IK_StringInit,
  244. IK_VarInit,
  245. IK_VarListElementInit,
  246. IK_VarBitInit,
  247. IK_VarDefInit,
  248. IK_LastTypedInit,
  249. IK_UnsetInit
  250. };
  251. private:
  252. const InitKind Kind;
  253. protected:
  254. uint8_t Opc; // Used by UnOpInit, BinOpInit, and TernOpInit
  255. private:
  256. virtual void anchor();
  257. public:
  258. /// Get the kind (type) of the value.
  259. InitKind getKind() const { return Kind; }
  260. protected:
  261. explicit Init(InitKind K, uint8_t Opc = 0) : Kind(K), Opc(Opc) {}
  262. public:
  263. Init(const Init &) = delete;
  264. Init &operator=(const Init &) = delete;
  265. virtual ~Init() = default;
  266. /// Is this a complete value with no unset (uninitialized) subvalues?
  267. virtual bool isComplete() const { return true; }
  268. /// Is this a concrete and fully resolved value without any references or
  269. /// stuck operations? Unset values are concrete.
  270. virtual bool isConcrete() const { return false; }
  271. /// Print this value.
  272. void print(raw_ostream &OS) const { OS << getAsString(); }
  273. /// Convert this value to a literal form.
  274. virtual std::string getAsString() const = 0;
  275. /// Convert this value to a literal form,
  276. /// without adding quotes around a string.
  277. virtual std::string getAsUnquotedString() const { return getAsString(); }
  278. /// Debugging method that may be called through a debugger; just
  279. /// invokes print on stderr.
  280. void dump() const;
  281. /// If this value is convertible to type \p Ty, return a value whose
  282. /// type is \p Ty, generating a !cast operation if required.
  283. /// Otherwise, return null.
  284. virtual Init *getCastTo(RecTy *Ty) const = 0;
  285. /// Convert to a value whose type is \p Ty, or return null if this
  286. /// is not possible. This can happen if the value's type is convertible
  287. /// to \p Ty, but there are unresolved references.
  288. virtual Init *convertInitializerTo(RecTy *Ty) const = 0;
  289. /// This function is used to implement the bit range
  290. /// selection operator. Given a value, it selects the specified bits,
  291. /// returning them as a new \p Init of type \p bits. If it is not legal
  292. /// to use the bit selection operator on this value, null is returned.
  293. virtual Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
  294. return nullptr;
  295. }
  296. /// This function is used to implement the list slice
  297. /// selection operator. Given a value, it selects the specified list
  298. /// elements, returning them as a new \p Init of type \p list. If it
  299. /// is not legal to use the slice operator, null is returned.
  300. virtual Init *convertInitListSlice(ArrayRef<unsigned> Elements) const {
  301. return nullptr;
  302. }
  303. /// This function is used to implement the FieldInit class.
  304. /// Implementors of this method should return the type of the named
  305. /// field if they are of type record.
  306. virtual RecTy *getFieldType(StringInit *FieldName) const {
  307. return nullptr;
  308. }
  309. /// This function is used by classes that refer to other
  310. /// variables which may not be defined at the time the expression is formed.
  311. /// If a value is set for the variable later, this method will be called on
  312. /// users of the value to allow the value to propagate out.
  313. virtual Init *resolveReferences(Resolver &R) const {
  314. return const_cast<Init *>(this);
  315. }
  316. /// Get the \p Init value of the specified bit.
  317. virtual Init *getBit(unsigned Bit) const = 0;
  318. };
  319. inline raw_ostream &operator<<(raw_ostream &OS, const Init &I) {
  320. I.print(OS); return OS;
  321. }
  322. /// This is the common superclass of types that have a specific,
  323. /// explicit type, stored in ValueTy.
  324. class TypedInit : public Init {
  325. RecTy *ValueTy;
  326. protected:
  327. explicit TypedInit(InitKind K, RecTy *T, uint8_t Opc = 0)
  328. : Init(K, Opc), ValueTy(T) {}
  329. public:
  330. TypedInit(const TypedInit &) = delete;
  331. TypedInit &operator=(const TypedInit &) = delete;
  332. static bool classof(const Init *I) {
  333. return I->getKind() >= IK_FirstTypedInit &&
  334. I->getKind() <= IK_LastTypedInit;
  335. }
  336. /// Get the type of the Init as a RecTy.
  337. RecTy *getType() const { return ValueTy; }
  338. Init *getCastTo(RecTy *Ty) const override;
  339. Init *convertInitializerTo(RecTy *Ty) const override;
  340. Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
  341. Init *convertInitListSlice(ArrayRef<unsigned> Elements) const override;
  342. /// This method is used to implement the FieldInit class.
  343. /// Implementors of this method should return the type of the named field if
  344. /// they are of type record.
  345. RecTy *getFieldType(StringInit *FieldName) const override;
  346. };
  347. /// '?' - Represents an uninitialized value.
  348. class UnsetInit : public Init {
  349. friend detail::RecordContext;
  350. UnsetInit() : Init(IK_UnsetInit) {}
  351. public:
  352. UnsetInit(const UnsetInit &) = delete;
  353. UnsetInit &operator=(const UnsetInit &) = delete;
  354. static bool classof(const Init *I) {
  355. return I->getKind() == IK_UnsetInit;
  356. }
  357. /// Get the singleton unset Init.
  358. static UnsetInit *get();
  359. Init *getCastTo(RecTy *Ty) const override;
  360. Init *convertInitializerTo(RecTy *Ty) const override;
  361. Init *getBit(unsigned Bit) const override {
  362. return const_cast<UnsetInit*>(this);
  363. }
  364. /// Is this a complete value with no unset (uninitialized) subvalues?
  365. bool isComplete() const override { return false; }
  366. bool isConcrete() const override { return true; }
  367. /// Get the string representation of the Init.
  368. std::string getAsString() const override { return "?"; }
  369. };
  370. /// 'true'/'false' - Represent a concrete initializer for a bit.
  371. class BitInit final : public TypedInit {
  372. friend detail::RecordContext;
  373. bool Value;
  374. explicit BitInit(bool V, RecTy *T) : TypedInit(IK_BitInit, T), Value(V) {}
  375. public:
  376. BitInit(const BitInit &) = delete;
  377. BitInit &operator=(BitInit &) = delete;
  378. static bool classof(const Init *I) {
  379. return I->getKind() == IK_BitInit;
  380. }
  381. static BitInit *get(bool V);
  382. bool getValue() const { return Value; }
  383. Init *convertInitializerTo(RecTy *Ty) const override;
  384. Init *getBit(unsigned Bit) const override {
  385. assert(Bit < 1 && "Bit index out of range!");
  386. return const_cast<BitInit*>(this);
  387. }
  388. bool isConcrete() const override { return true; }
  389. std::string getAsString() const override { return Value ? "1" : "0"; }
  390. };
  391. /// '{ a, b, c }' - Represents an initializer for a BitsRecTy value.
  392. /// It contains a vector of bits, whose size is determined by the type.
  393. class BitsInit final : public TypedInit, public FoldingSetNode,
  394. public TrailingObjects<BitsInit, Init *> {
  395. unsigned NumBits;
  396. BitsInit(unsigned N)
  397. : TypedInit(IK_BitsInit, BitsRecTy::get(N)), NumBits(N) {}
  398. public:
  399. BitsInit(const BitsInit &) = delete;
  400. BitsInit &operator=(const BitsInit &) = delete;
  401. // Do not use sized deallocation due to trailing objects.
  402. void operator delete(void *p) { ::operator delete(p); }
  403. static bool classof(const Init *I) {
  404. return I->getKind() == IK_BitsInit;
  405. }
  406. static BitsInit *get(ArrayRef<Init *> Range);
  407. void Profile(FoldingSetNodeID &ID) const;
  408. unsigned getNumBits() const { return NumBits; }
  409. Init *convertInitializerTo(RecTy *Ty) const override;
  410. Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
  411. bool isComplete() const override {
  412. for (unsigned i = 0; i != getNumBits(); ++i)
  413. if (!getBit(i)->isComplete()) return false;
  414. return true;
  415. }
  416. bool allInComplete() const {
  417. for (unsigned i = 0; i != getNumBits(); ++i)
  418. if (getBit(i)->isComplete()) return false;
  419. return true;
  420. }
  421. bool isConcrete() const override;
  422. std::string getAsString() const override;
  423. Init *resolveReferences(Resolver &R) const override;
  424. Init *getBit(unsigned Bit) const override {
  425. assert(Bit < NumBits && "Bit index out of range!");
  426. return getTrailingObjects<Init *>()[Bit];
  427. }
  428. };
  429. /// '7' - Represent an initialization by a literal integer value.
  430. class IntInit : public TypedInit {
  431. int64_t Value;
  432. explicit IntInit(int64_t V)
  433. : TypedInit(IK_IntInit, IntRecTy::get()), Value(V) {}
  434. public:
  435. IntInit(const IntInit &) = delete;
  436. IntInit &operator=(const IntInit &) = delete;
  437. static bool classof(const Init *I) {
  438. return I->getKind() == IK_IntInit;
  439. }
  440. static IntInit *get(int64_t V);
  441. int64_t getValue() const { return Value; }
  442. Init *convertInitializerTo(RecTy *Ty) const override;
  443. Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
  444. bool isConcrete() const override { return true; }
  445. std::string getAsString() const override;
  446. Init *getBit(unsigned Bit) const override {
  447. return BitInit::get((Value & (1ULL << Bit)) != 0);
  448. }
  449. };
  450. /// "anonymous_n" - Represent an anonymous record name
  451. class AnonymousNameInit : public TypedInit {
  452. unsigned Value;
  453. explicit AnonymousNameInit(unsigned V)
  454. : TypedInit(IK_AnonymousNameInit, StringRecTy::get()), Value(V) {}
  455. public:
  456. AnonymousNameInit(const AnonymousNameInit &) = delete;
  457. AnonymousNameInit &operator=(const AnonymousNameInit &) = delete;
  458. static bool classof(const Init *I) {
  459. return I->getKind() == IK_AnonymousNameInit;
  460. }
  461. static AnonymousNameInit *get(unsigned);
  462. unsigned getValue() const { return Value; }
  463. StringInit *getNameInit() const;
  464. std::string getAsString() const override;
  465. Init *resolveReferences(Resolver &R) const override;
  466. Init *getBit(unsigned Bit) const override {
  467. llvm_unreachable("Illegal bit reference off string");
  468. }
  469. };
  470. /// "foo" - Represent an initialization by a string value.
  471. class StringInit : public TypedInit {
  472. public:
  473. enum StringFormat {
  474. SF_String, // Format as "text"
  475. SF_Code, // Format as [{text}]
  476. };
  477. private:
  478. StringRef Value;
  479. StringFormat Format;
  480. explicit StringInit(StringRef V, StringFormat Fmt)
  481. : TypedInit(IK_StringInit, StringRecTy::get()), Value(V), Format(Fmt) {}
  482. public:
  483. StringInit(const StringInit &) = delete;
  484. StringInit &operator=(const StringInit &) = delete;
  485. static bool classof(const Init *I) {
  486. return I->getKind() == IK_StringInit;
  487. }
  488. static StringInit *get(StringRef, StringFormat Fmt = SF_String);
  489. static StringFormat determineFormat(StringFormat Fmt1, StringFormat Fmt2) {
  490. return (Fmt1 == SF_Code || Fmt2 == SF_Code) ? SF_Code : SF_String;
  491. }
  492. StringRef getValue() const { return Value; }
  493. StringFormat getFormat() const { return Format; }
  494. bool hasCodeFormat() const { return Format == SF_Code; }
  495. Init *convertInitializerTo(RecTy *Ty) const override;
  496. bool isConcrete() const override { return true; }
  497. std::string getAsString() const override {
  498. if (Format == SF_String)
  499. return "\"" + Value.str() + "\"";
  500. else
  501. return "[{" + Value.str() + "}]";
  502. }
  503. std::string getAsUnquotedString() const override {
  504. return std::string(Value);
  505. }
  506. Init *getBit(unsigned Bit) const override {
  507. llvm_unreachable("Illegal bit reference off string");
  508. }
  509. };
  510. /// [AL, AH, CL] - Represent a list of defs
  511. ///
  512. class ListInit final : public TypedInit, public FoldingSetNode,
  513. public TrailingObjects<ListInit, Init *> {
  514. unsigned NumValues;
  515. public:
  516. using const_iterator = Init *const *;
  517. private:
  518. explicit ListInit(unsigned N, RecTy *EltTy)
  519. : TypedInit(IK_ListInit, ListRecTy::get(EltTy)), NumValues(N) {}
  520. public:
  521. ListInit(const ListInit &) = delete;
  522. ListInit &operator=(const ListInit &) = delete;
  523. // Do not use sized deallocation due to trailing objects.
  524. void operator delete(void *p) { ::operator delete(p); }
  525. static bool classof(const Init *I) {
  526. return I->getKind() == IK_ListInit;
  527. }
  528. static ListInit *get(ArrayRef<Init *> Range, RecTy *EltTy);
  529. void Profile(FoldingSetNodeID &ID) const;
  530. Init *getElement(unsigned i) const {
  531. assert(i < NumValues && "List element index out of range!");
  532. return getTrailingObjects<Init *>()[i];
  533. }
  534. RecTy *getElementType() const {
  535. return cast<ListRecTy>(getType())->getElementType();
  536. }
  537. Record *getElementAsRecord(unsigned i) const;
  538. Init *convertInitListSlice(ArrayRef<unsigned> Elements) const override;
  539. Init *convertInitializerTo(RecTy *Ty) const override;
  540. /// This method is used by classes that refer to other
  541. /// variables which may not be defined at the time they expression is formed.
  542. /// If a value is set for the variable later, this method will be called on
  543. /// users of the value to allow the value to propagate out.
  544. ///
  545. Init *resolveReferences(Resolver &R) const override;
  546. bool isComplete() const override;
  547. bool isConcrete() const override;
  548. std::string getAsString() const override;
  549. ArrayRef<Init*> getValues() const {
  550. return makeArrayRef(getTrailingObjects<Init *>(), NumValues);
  551. }
  552. const_iterator begin() const { return getTrailingObjects<Init *>(); }
  553. const_iterator end () const { return begin() + NumValues; }
  554. size_t size () const { return NumValues; }
  555. bool empty() const { return NumValues == 0; }
  556. Init *getBit(unsigned Bit) const override {
  557. llvm_unreachable("Illegal bit reference off list");
  558. }
  559. };
  560. /// Base class for operators
  561. ///
  562. class OpInit : public TypedInit {
  563. protected:
  564. explicit OpInit(InitKind K, RecTy *Type, uint8_t Opc)
  565. : TypedInit(K, Type, Opc) {}
  566. public:
  567. OpInit(const OpInit &) = delete;
  568. OpInit &operator=(OpInit &) = delete;
  569. static bool classof(const Init *I) {
  570. return I->getKind() >= IK_FirstOpInit &&
  571. I->getKind() <= IK_LastOpInit;
  572. }
  573. // Clone - Clone this operator, replacing arguments with the new list
  574. virtual OpInit *clone(ArrayRef<Init *> Operands) const = 0;
  575. virtual unsigned getNumOperands() const = 0;
  576. virtual Init *getOperand(unsigned i) const = 0;
  577. Init *getBit(unsigned Bit) const override;
  578. };
  579. /// !op (X) - Transform an init.
  580. ///
  581. class UnOpInit : public OpInit, public FoldingSetNode {
  582. public:
  583. enum UnaryOp : uint8_t { CAST, NOT, HEAD, TAIL, SIZE, EMPTY, GETDAGOP };
  584. private:
  585. Init *LHS;
  586. UnOpInit(UnaryOp opc, Init *lhs, RecTy *Type)
  587. : OpInit(IK_UnOpInit, Type, opc), LHS(lhs) {}
  588. public:
  589. UnOpInit(const UnOpInit &) = delete;
  590. UnOpInit &operator=(const UnOpInit &) = delete;
  591. static bool classof(const Init *I) {
  592. return I->getKind() == IK_UnOpInit;
  593. }
  594. static UnOpInit *get(UnaryOp opc, Init *lhs, RecTy *Type);
  595. void Profile(FoldingSetNodeID &ID) const;
  596. // Clone - Clone this operator, replacing arguments with the new list
  597. OpInit *clone(ArrayRef<Init *> Operands) const override {
  598. assert(Operands.size() == 1 &&
  599. "Wrong number of operands for unary operation");
  600. return UnOpInit::get(getOpcode(), *Operands.begin(), getType());
  601. }
  602. unsigned getNumOperands() const override { return 1; }
  603. Init *getOperand(unsigned i) const override {
  604. assert(i == 0 && "Invalid operand id for unary operator");
  605. return getOperand();
  606. }
  607. UnaryOp getOpcode() const { return (UnaryOp)Opc; }
  608. Init *getOperand() const { return LHS; }
  609. // Fold - If possible, fold this to a simpler init. Return this if not
  610. // possible to fold.
  611. Init *Fold(Record *CurRec, bool IsFinal = false) const;
  612. Init *resolveReferences(Resolver &R) const override;
  613. std::string getAsString() const override;
  614. };
  615. /// !op (X, Y) - Combine two inits.
  616. class BinOpInit : public OpInit, public FoldingSetNode {
  617. public:
  618. enum BinaryOp : uint8_t { ADD, SUB, MUL, AND, OR, XOR, SHL, SRA, SRL, LISTCONCAT,
  619. LISTSPLAT, STRCONCAT, INTERLEAVE, CONCAT, EQ,
  620. NE, LE, LT, GE, GT, SETDAGOP };
  621. private:
  622. Init *LHS, *RHS;
  623. BinOpInit(BinaryOp opc, Init *lhs, Init *rhs, RecTy *Type) :
  624. OpInit(IK_BinOpInit, Type, opc), LHS(lhs), RHS(rhs) {}
  625. public:
  626. BinOpInit(const BinOpInit &) = delete;
  627. BinOpInit &operator=(const BinOpInit &) = delete;
  628. static bool classof(const Init *I) {
  629. return I->getKind() == IK_BinOpInit;
  630. }
  631. static BinOpInit *get(BinaryOp opc, Init *lhs, Init *rhs,
  632. RecTy *Type);
  633. static Init *getStrConcat(Init *lhs, Init *rhs);
  634. static Init *getListConcat(TypedInit *lhs, Init *rhs);
  635. void Profile(FoldingSetNodeID &ID) const;
  636. // Clone - Clone this operator, replacing arguments with the new list
  637. OpInit *clone(ArrayRef<Init *> Operands) const override {
  638. assert(Operands.size() == 2 &&
  639. "Wrong number of operands for binary operation");
  640. return BinOpInit::get(getOpcode(), Operands[0], Operands[1], getType());
  641. }
  642. unsigned getNumOperands() const override { return 2; }
  643. Init *getOperand(unsigned i) const override {
  644. switch (i) {
  645. default: llvm_unreachable("Invalid operand id for binary operator");
  646. case 0: return getLHS();
  647. case 1: return getRHS();
  648. }
  649. }
  650. BinaryOp getOpcode() const { return (BinaryOp)Opc; }
  651. Init *getLHS() const { return LHS; }
  652. Init *getRHS() const { return RHS; }
  653. // Fold - If possible, fold this to a simpler init. Return this if not
  654. // possible to fold.
  655. Init *Fold(Record *CurRec) const;
  656. Init *resolveReferences(Resolver &R) const override;
  657. std::string getAsString() const override;
  658. };
  659. /// !op (X, Y, Z) - Combine two inits.
  660. class TernOpInit : public OpInit, public FoldingSetNode {
  661. public:
  662. enum TernaryOp : uint8_t { SUBST, FOREACH, FILTER, IF, DAG, SUBSTR, FIND };
  663. private:
  664. Init *LHS, *MHS, *RHS;
  665. TernOpInit(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs,
  666. RecTy *Type) :
  667. OpInit(IK_TernOpInit, Type, opc), LHS(lhs), MHS(mhs), RHS(rhs) {}
  668. public:
  669. TernOpInit(const TernOpInit &) = delete;
  670. TernOpInit &operator=(const TernOpInit &) = delete;
  671. static bool classof(const Init *I) {
  672. return I->getKind() == IK_TernOpInit;
  673. }
  674. static TernOpInit *get(TernaryOp opc, Init *lhs,
  675. Init *mhs, Init *rhs,
  676. RecTy *Type);
  677. void Profile(FoldingSetNodeID &ID) const;
  678. // Clone - Clone this operator, replacing arguments with the new list
  679. OpInit *clone(ArrayRef<Init *> Operands) const override {
  680. assert(Operands.size() == 3 &&
  681. "Wrong number of operands for ternary operation");
  682. return TernOpInit::get(getOpcode(), Operands[0], Operands[1], Operands[2],
  683. getType());
  684. }
  685. unsigned getNumOperands() const override { return 3; }
  686. Init *getOperand(unsigned i) const override {
  687. switch (i) {
  688. default: llvm_unreachable("Invalid operand id for ternary operator");
  689. case 0: return getLHS();
  690. case 1: return getMHS();
  691. case 2: return getRHS();
  692. }
  693. }
  694. TernaryOp getOpcode() const { return (TernaryOp)Opc; }
  695. Init *getLHS() const { return LHS; }
  696. Init *getMHS() const { return MHS; }
  697. Init *getRHS() const { return RHS; }
  698. // Fold - If possible, fold this to a simpler init. Return this if not
  699. // possible to fold.
  700. Init *Fold(Record *CurRec) const;
  701. bool isComplete() const override {
  702. return LHS->isComplete() && MHS->isComplete() && RHS->isComplete();
  703. }
  704. Init *resolveReferences(Resolver &R) const override;
  705. std::string getAsString() const override;
  706. };
  707. /// !cond(condition_1: value1, ... , condition_n: value)
  708. /// Selects the first value for which condition is true.
  709. /// Otherwise reports an error.
  710. class CondOpInit final : public TypedInit, public FoldingSetNode,
  711. public TrailingObjects<CondOpInit, Init *> {
  712. unsigned NumConds;
  713. RecTy *ValType;
  714. CondOpInit(unsigned NC, RecTy *Type)
  715. : TypedInit(IK_CondOpInit, Type),
  716. NumConds(NC), ValType(Type) {}
  717. size_t numTrailingObjects(OverloadToken<Init *>) const {
  718. return 2*NumConds;
  719. }
  720. public:
  721. CondOpInit(const CondOpInit &) = delete;
  722. CondOpInit &operator=(const CondOpInit &) = delete;
  723. static bool classof(const Init *I) {
  724. return I->getKind() == IK_CondOpInit;
  725. }
  726. static CondOpInit *get(ArrayRef<Init*> C, ArrayRef<Init*> V,
  727. RecTy *Type);
  728. void Profile(FoldingSetNodeID &ID) const;
  729. RecTy *getValType() const { return ValType; }
  730. unsigned getNumConds() const { return NumConds; }
  731. Init *getCond(unsigned Num) const {
  732. assert(Num < NumConds && "Condition number out of range!");
  733. return getTrailingObjects<Init *>()[Num];
  734. }
  735. Init *getVal(unsigned Num) const {
  736. assert(Num < NumConds && "Val number out of range!");
  737. return getTrailingObjects<Init *>()[Num+NumConds];
  738. }
  739. ArrayRef<Init *> getConds() const {
  740. return makeArrayRef(getTrailingObjects<Init *>(), NumConds);
  741. }
  742. ArrayRef<Init *> getVals() const {
  743. return makeArrayRef(getTrailingObjects<Init *>()+NumConds, NumConds);
  744. }
  745. Init *Fold(Record *CurRec) const;
  746. Init *resolveReferences(Resolver &R) const override;
  747. bool isConcrete() const override;
  748. bool isComplete() const override;
  749. std::string getAsString() const override;
  750. using const_case_iterator = SmallVectorImpl<Init*>::const_iterator;
  751. using const_val_iterator = SmallVectorImpl<Init*>::const_iterator;
  752. inline const_case_iterator arg_begin() const { return getConds().begin(); }
  753. inline const_case_iterator arg_end () const { return getConds().end(); }
  754. inline size_t case_size () const { return NumConds; }
  755. inline bool case_empty() const { return NumConds == 0; }
  756. inline const_val_iterator name_begin() const { return getVals().begin();}
  757. inline const_val_iterator name_end () const { return getVals().end(); }
  758. inline size_t val_size () const { return NumConds; }
  759. inline bool val_empty() const { return NumConds == 0; }
  760. Init *getBit(unsigned Bit) const override;
  761. };
  762. /// !foldl (a, b, expr, start, lst) - Fold over a list.
  763. class FoldOpInit : public TypedInit, public FoldingSetNode {
  764. private:
  765. Init *Start;
  766. Init *List;
  767. Init *A;
  768. Init *B;
  769. Init *Expr;
  770. FoldOpInit(Init *Start, Init *List, Init *A, Init *B, Init *Expr, RecTy *Type)
  771. : TypedInit(IK_FoldOpInit, Type), Start(Start), List(List), A(A), B(B),
  772. Expr(Expr) {}
  773. public:
  774. FoldOpInit(const FoldOpInit &) = delete;
  775. FoldOpInit &operator=(const FoldOpInit &) = delete;
  776. static bool classof(const Init *I) { return I->getKind() == IK_FoldOpInit; }
  777. static FoldOpInit *get(Init *Start, Init *List, Init *A, Init *B, Init *Expr,
  778. RecTy *Type);
  779. void Profile(FoldingSetNodeID &ID) const;
  780. // Fold - If possible, fold this to a simpler init. Return this if not
  781. // possible to fold.
  782. Init *Fold(Record *CurRec) const;
  783. bool isComplete() const override { return false; }
  784. Init *resolveReferences(Resolver &R) const override;
  785. Init *getBit(unsigned Bit) const override;
  786. std::string getAsString() const override;
  787. };
  788. /// !isa<type>(expr) - Dynamically determine the type of an expression.
  789. class IsAOpInit : public TypedInit, public FoldingSetNode {
  790. private:
  791. RecTy *CheckType;
  792. Init *Expr;
  793. IsAOpInit(RecTy *CheckType, Init *Expr)
  794. : TypedInit(IK_IsAOpInit, IntRecTy::get()), CheckType(CheckType),
  795. Expr(Expr) {}
  796. public:
  797. IsAOpInit(const IsAOpInit &) = delete;
  798. IsAOpInit &operator=(const IsAOpInit &) = delete;
  799. static bool classof(const Init *I) { return I->getKind() == IK_IsAOpInit; }
  800. static IsAOpInit *get(RecTy *CheckType, Init *Expr);
  801. void Profile(FoldingSetNodeID &ID) const;
  802. // Fold - If possible, fold this to a simpler init. Return this if not
  803. // possible to fold.
  804. Init *Fold() const;
  805. bool isComplete() const override { return false; }
  806. Init *resolveReferences(Resolver &R) const override;
  807. Init *getBit(unsigned Bit) const override;
  808. std::string getAsString() const override;
  809. };
  810. /// 'Opcode' - Represent a reference to an entire variable object.
  811. class VarInit : public TypedInit {
  812. Init *VarName;
  813. explicit VarInit(Init *VN, RecTy *T)
  814. : TypedInit(IK_VarInit, T), VarName(VN) {}
  815. public:
  816. VarInit(const VarInit &) = delete;
  817. VarInit &operator=(const VarInit &) = delete;
  818. static bool classof(const Init *I) {
  819. return I->getKind() == IK_VarInit;
  820. }
  821. static VarInit *get(StringRef VN, RecTy *T);
  822. static VarInit *get(Init *VN, RecTy *T);
  823. StringRef getName() const;
  824. Init *getNameInit() const { return VarName; }
  825. std::string getNameInitAsString() const {
  826. return getNameInit()->getAsUnquotedString();
  827. }
  828. /// This method is used by classes that refer to other
  829. /// variables which may not be defined at the time they expression is formed.
  830. /// If a value is set for the variable later, this method will be called on
  831. /// users of the value to allow the value to propagate out.
  832. ///
  833. Init *resolveReferences(Resolver &R) const override;
  834. Init *getBit(unsigned Bit) const override;
  835. std::string getAsString() const override { return std::string(getName()); }
  836. };
  837. /// Opcode{0} - Represent access to one bit of a variable or field.
  838. class VarBitInit final : public TypedInit {
  839. TypedInit *TI;
  840. unsigned Bit;
  841. VarBitInit(TypedInit *T, unsigned B)
  842. : TypedInit(IK_VarBitInit, BitRecTy::get()), TI(T), Bit(B) {
  843. assert(T->getType() &&
  844. (isa<IntRecTy>(T->getType()) ||
  845. (isa<BitsRecTy>(T->getType()) &&
  846. cast<BitsRecTy>(T->getType())->getNumBits() > B)) &&
  847. "Illegal VarBitInit expression!");
  848. }
  849. public:
  850. VarBitInit(const VarBitInit &) = delete;
  851. VarBitInit &operator=(const VarBitInit &) = delete;
  852. static bool classof(const Init *I) {
  853. return I->getKind() == IK_VarBitInit;
  854. }
  855. static VarBitInit *get(TypedInit *T, unsigned B);
  856. Init *getBitVar() const { return TI; }
  857. unsigned getBitNum() const { return Bit; }
  858. std::string getAsString() const override;
  859. Init *resolveReferences(Resolver &R) const override;
  860. Init *getBit(unsigned B) const override {
  861. assert(B < 1 && "Bit index out of range!");
  862. return const_cast<VarBitInit*>(this);
  863. }
  864. };
  865. /// List[4] - Represent access to one element of a var or
  866. /// field.
  867. class VarListElementInit : public TypedInit {
  868. TypedInit *TI;
  869. unsigned Element;
  870. VarListElementInit(TypedInit *T, unsigned E)
  871. : TypedInit(IK_VarListElementInit,
  872. cast<ListRecTy>(T->getType())->getElementType()),
  873. TI(T), Element(E) {
  874. assert(T->getType() && isa<ListRecTy>(T->getType()) &&
  875. "Illegal VarBitInit expression!");
  876. }
  877. public:
  878. VarListElementInit(const VarListElementInit &) = delete;
  879. VarListElementInit &operator=(const VarListElementInit &) = delete;
  880. static bool classof(const Init *I) {
  881. return I->getKind() == IK_VarListElementInit;
  882. }
  883. static VarListElementInit *get(TypedInit *T, unsigned E);
  884. TypedInit *getVariable() const { return TI; }
  885. unsigned getElementNum() const { return Element; }
  886. std::string getAsString() const override;
  887. Init *resolveReferences(Resolver &R) const override;
  888. Init *getBit(unsigned Bit) const override;
  889. };
  890. /// AL - Represent a reference to a 'def' in the description
  891. class DefInit : public TypedInit {
  892. friend class Record;
  893. Record *Def;
  894. explicit DefInit(Record *D);
  895. public:
  896. DefInit(const DefInit &) = delete;
  897. DefInit &operator=(const DefInit &) = delete;
  898. static bool classof(const Init *I) {
  899. return I->getKind() == IK_DefInit;
  900. }
  901. static DefInit *get(Record*);
  902. Init *convertInitializerTo(RecTy *Ty) const override;
  903. Record *getDef() const { return Def; }
  904. //virtual Init *convertInitializerBitRange(ArrayRef<unsigned> Bits);
  905. RecTy *getFieldType(StringInit *FieldName) const override;
  906. bool isConcrete() const override { return true; }
  907. std::string getAsString() const override;
  908. Init *getBit(unsigned Bit) const override {
  909. llvm_unreachable("Illegal bit reference off def");
  910. }
  911. };
  912. /// classname<targs...> - Represent an uninstantiated anonymous class
  913. /// instantiation.
  914. class VarDefInit final : public TypedInit, public FoldingSetNode,
  915. public TrailingObjects<VarDefInit, Init *> {
  916. Record *Class;
  917. DefInit *Def = nullptr; // after instantiation
  918. unsigned NumArgs;
  919. explicit VarDefInit(Record *Class, unsigned N)
  920. : TypedInit(IK_VarDefInit, RecordRecTy::get(Class)), Class(Class), NumArgs(N) {}
  921. DefInit *instantiate();
  922. public:
  923. VarDefInit(const VarDefInit &) = delete;
  924. VarDefInit &operator=(const VarDefInit &) = delete;
  925. // Do not use sized deallocation due to trailing objects.
  926. void operator delete(void *p) { ::operator delete(p); }
  927. static bool classof(const Init *I) {
  928. return I->getKind() == IK_VarDefInit;
  929. }
  930. static VarDefInit *get(Record *Class, ArrayRef<Init *> Args);
  931. void Profile(FoldingSetNodeID &ID) const;
  932. Init *resolveReferences(Resolver &R) const override;
  933. Init *Fold() const;
  934. std::string getAsString() const override;
  935. Init *getArg(unsigned i) const {
  936. assert(i < NumArgs && "Argument index out of range!");
  937. return getTrailingObjects<Init *>()[i];
  938. }
  939. using const_iterator = Init *const *;
  940. const_iterator args_begin() const { return getTrailingObjects<Init *>(); }
  941. const_iterator args_end () const { return args_begin() + NumArgs; }
  942. size_t args_size () const { return NumArgs; }
  943. bool args_empty() const { return NumArgs == 0; }
  944. ArrayRef<Init *> args() const { return makeArrayRef(args_begin(), NumArgs); }
  945. Init *getBit(unsigned Bit) const override {
  946. llvm_unreachable("Illegal bit reference off anonymous def");
  947. }
  948. };
  949. /// X.Y - Represent a reference to a subfield of a variable
  950. class FieldInit : public TypedInit {
  951. Init *Rec; // Record we are referring to
  952. StringInit *FieldName; // Field we are accessing
  953. FieldInit(Init *R, StringInit *FN)
  954. : TypedInit(IK_FieldInit, R->getFieldType(FN)), Rec(R), FieldName(FN) {
  955. #ifndef NDEBUG
  956. if (!getType()) {
  957. llvm::errs() << "In Record = " << Rec->getAsString()
  958. << ", got FieldName = " << *FieldName
  959. << " with non-record type!\n";
  960. llvm_unreachable("FieldInit with non-record type!");
  961. }
  962. #endif
  963. }
  964. public:
  965. FieldInit(const FieldInit &) = delete;
  966. FieldInit &operator=(const FieldInit &) = delete;
  967. static bool classof(const Init *I) {
  968. return I->getKind() == IK_FieldInit;
  969. }
  970. static FieldInit *get(Init *R, StringInit *FN);
  971. Init *getRecord() const { return Rec; }
  972. StringInit *getFieldName() const { return FieldName; }
  973. Init *getBit(unsigned Bit) const override;
  974. Init *resolveReferences(Resolver &R) const override;
  975. Init *Fold(Record *CurRec) const;
  976. bool isConcrete() const override;
  977. std::string getAsString() const override {
  978. return Rec->getAsString() + "." + FieldName->getValue().str();
  979. }
  980. };
  981. /// (v a, b) - Represent a DAG tree value. DAG inits are required
  982. /// to have at least one value then a (possibly empty) list of arguments. Each
  983. /// argument can have a name associated with it.
  984. class DagInit final : public TypedInit, public FoldingSetNode,
  985. public TrailingObjects<DagInit, Init *, StringInit *> {
  986. friend TrailingObjects;
  987. Init *Val;
  988. StringInit *ValName;
  989. unsigned NumArgs;
  990. unsigned NumArgNames;
  991. DagInit(Init *V, StringInit *VN, unsigned NumArgs, unsigned NumArgNames)
  992. : TypedInit(IK_DagInit, DagRecTy::get()), Val(V), ValName(VN),
  993. NumArgs(NumArgs), NumArgNames(NumArgNames) {}
  994. size_t numTrailingObjects(OverloadToken<Init *>) const { return NumArgs; }
  995. public:
  996. DagInit(const DagInit &) = delete;
  997. DagInit &operator=(const DagInit &) = delete;
  998. static bool classof(const Init *I) {
  999. return I->getKind() == IK_DagInit;
  1000. }
  1001. static DagInit *get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
  1002. ArrayRef<StringInit*> NameRange);
  1003. static DagInit *get(Init *V, StringInit *VN,
  1004. ArrayRef<std::pair<Init*, StringInit*>> Args);
  1005. void Profile(FoldingSetNodeID &ID) const;
  1006. Init *getOperator() const { return Val; }
  1007. Record *getOperatorAsDef(ArrayRef<SMLoc> Loc) const;
  1008. StringInit *getName() const { return ValName; }
  1009. StringRef getNameStr() const {
  1010. return ValName ? ValName->getValue() : StringRef();
  1011. }
  1012. unsigned getNumArgs() const { return NumArgs; }
  1013. Init *getArg(unsigned Num) const {
  1014. assert(Num < NumArgs && "Arg number out of range!");
  1015. return getTrailingObjects<Init *>()[Num];
  1016. }
  1017. StringInit *getArgName(unsigned Num) const {
  1018. assert(Num < NumArgNames && "Arg number out of range!");
  1019. return getTrailingObjects<StringInit *>()[Num];
  1020. }
  1021. StringRef getArgNameStr(unsigned Num) const {
  1022. StringInit *Init = getArgName(Num);
  1023. return Init ? Init->getValue() : StringRef();
  1024. }
  1025. ArrayRef<Init *> getArgs() const {
  1026. return makeArrayRef(getTrailingObjects<Init *>(), NumArgs);
  1027. }
  1028. ArrayRef<StringInit *> getArgNames() const {
  1029. return makeArrayRef(getTrailingObjects<StringInit *>(), NumArgNames);
  1030. }
  1031. Init *resolveReferences(Resolver &R) const override;
  1032. bool isConcrete() const override;
  1033. std::string getAsString() const override;
  1034. using const_arg_iterator = SmallVectorImpl<Init*>::const_iterator;
  1035. using const_name_iterator = SmallVectorImpl<StringInit*>::const_iterator;
  1036. inline const_arg_iterator arg_begin() const { return getArgs().begin(); }
  1037. inline const_arg_iterator arg_end () const { return getArgs().end(); }
  1038. inline size_t arg_size () const { return NumArgs; }
  1039. inline bool arg_empty() const { return NumArgs == 0; }
  1040. inline const_name_iterator name_begin() const { return getArgNames().begin();}
  1041. inline const_name_iterator name_end () const { return getArgNames().end(); }
  1042. inline size_t name_size () const { return NumArgNames; }
  1043. inline bool name_empty() const { return NumArgNames == 0; }
  1044. Init *getBit(unsigned Bit) const override {
  1045. llvm_unreachable("Illegal bit reference off dag");
  1046. }
  1047. };
  1048. //===----------------------------------------------------------------------===//
  1049. // High-Level Classes
  1050. //===----------------------------------------------------------------------===//
  1051. /// This class represents a field in a record, including its name, type,
  1052. /// value, and source location.
  1053. class RecordVal {
  1054. friend class Record;
  1055. public:
  1056. enum FieldKind {
  1057. FK_Normal, // A normal record field.
  1058. FK_NonconcreteOK, // A field that can be nonconcrete ('field' keyword).
  1059. FK_TemplateArg, // A template argument.
  1060. };
  1061. private:
  1062. Init *Name;
  1063. SMLoc Loc; // Source location of definition of name.
  1064. PointerIntPair<RecTy *, 2, FieldKind> TyAndKind;
  1065. Init *Value;
  1066. bool IsUsed = false;
  1067. public:
  1068. RecordVal(Init *N, RecTy *T, FieldKind K);
  1069. RecordVal(Init *N, SMLoc Loc, RecTy *T, FieldKind K);
  1070. /// Get the name of the field as a StringRef.
  1071. StringRef getName() const;
  1072. /// Get the name of the field as an Init.
  1073. Init *getNameInit() const { return Name; }
  1074. /// Get the name of the field as a std::string.
  1075. std::string getNameInitAsString() const {
  1076. return getNameInit()->getAsUnquotedString();
  1077. }
  1078. /// Get the source location of the point where the field was defined.
  1079. const SMLoc &getLoc() const { return Loc; }
  1080. /// Is this a field where nonconcrete values are okay?
  1081. bool isNonconcreteOK() const {
  1082. return TyAndKind.getInt() == FK_NonconcreteOK;
  1083. }
  1084. /// Is this a template argument?
  1085. bool isTemplateArg() const {
  1086. return TyAndKind.getInt() == FK_TemplateArg;
  1087. }
  1088. /// Get the type of the field value as a RecTy.
  1089. RecTy *getType() const { return TyAndKind.getPointer(); }
  1090. /// Get the type of the field for printing purposes.
  1091. std::string getPrintType() const;
  1092. /// Get the value of the field as an Init.
  1093. Init *getValue() const { return Value; }
  1094. /// Set the value of the field from an Init.
  1095. bool setValue(Init *V);
  1096. /// Set the value and source location of the field.
  1097. bool setValue(Init *V, SMLoc NewLoc);
  1098. /// Whether this value is used. Useful for reporting warnings, for example
  1099. /// when a template argument is unused.
  1100. void setUsed(bool Used) { IsUsed = Used; }
  1101. bool isUsed() const { return IsUsed; }
  1102. void dump() const;
  1103. /// Print the value to an output stream, possibly with a semicolon.
  1104. void print(raw_ostream &OS, bool PrintSem = true) const;
  1105. };
  1106. inline raw_ostream &operator<<(raw_ostream &OS, const RecordVal &RV) {
  1107. RV.print(OS << " ");
  1108. return OS;
  1109. }
  1110. class Record {
  1111. public:
  1112. struct AssertionInfo {
  1113. SMLoc Loc;
  1114. Init *Condition;
  1115. Init *Message;
  1116. // User-defined constructor to support std::make_unique(). It can be
  1117. // removed in C++20 when braced initialization is supported.
  1118. AssertionInfo(SMLoc Loc, Init *Condition, Init *Message)
  1119. : Loc(Loc), Condition(Condition), Message(Message) {}
  1120. };
  1121. private:
  1122. Init *Name;
  1123. // Location where record was instantiated, followed by the location of
  1124. // multiclass prototypes used.
  1125. SmallVector<SMLoc, 4> Locs;
  1126. SmallVector<Init *, 0> TemplateArgs;
  1127. SmallVector<RecordVal, 0> Values;
  1128. SmallVector<AssertionInfo, 0> Assertions;
  1129. // All superclasses in the inheritance forest in post-order (yes, it
  1130. // must be a forest; diamond-shaped inheritance is not allowed).
  1131. SmallVector<std::pair<Record *, SMRange>, 0> SuperClasses;
  1132. // Tracks Record instances. Not owned by Record.
  1133. RecordKeeper &TrackedRecords;
  1134. // The DefInit corresponding to this record.
  1135. DefInit *CorrespondingDefInit = nullptr;
  1136. // Unique record ID.
  1137. unsigned ID;
  1138. bool IsAnonymous;
  1139. bool IsClass;
  1140. void checkName();
  1141. public:
  1142. // Constructs a record.
  1143. explicit Record(Init *N, ArrayRef<SMLoc> locs, RecordKeeper &records,
  1144. bool Anonymous = false, bool Class = false)
  1145. : Name(N), Locs(locs.begin(), locs.end()), TrackedRecords(records),
  1146. ID(getNewUID()), IsAnonymous(Anonymous), IsClass(Class) {
  1147. checkName();
  1148. }
  1149. explicit Record(StringRef N, ArrayRef<SMLoc> locs, RecordKeeper &records,
  1150. bool Class = false)
  1151. : Record(StringInit::get(N), locs, records, false, Class) {}
  1152. // When copy-constructing a Record, we must still guarantee a globally unique
  1153. // ID number. Don't copy CorrespondingDefInit either, since it's owned by the
  1154. // original record. All other fields can be copied normally.
  1155. Record(const Record &O)
  1156. : Name(O.Name), Locs(O.Locs), TemplateArgs(O.TemplateArgs),
  1157. Values(O.Values), Assertions(O.Assertions),
  1158. SuperClasses(O.SuperClasses), TrackedRecords(O.TrackedRecords),
  1159. ID(getNewUID()), IsAnonymous(O.IsAnonymous), IsClass(O.IsClass) {}
  1160. static unsigned getNewUID();
  1161. unsigned getID() const { return ID; }
  1162. StringRef getName() const { return cast<StringInit>(Name)->getValue(); }
  1163. Init *getNameInit() const {
  1164. return Name;
  1165. }
  1166. const std::string getNameInitAsString() const {
  1167. return getNameInit()->getAsUnquotedString();
  1168. }
  1169. void setName(Init *Name); // Also updates RecordKeeper.
  1170. ArrayRef<SMLoc> getLoc() const { return Locs; }
  1171. void appendLoc(SMLoc Loc) { Locs.push_back(Loc); }
  1172. // Make the type that this record should have based on its superclasses.
  1173. RecordRecTy *getType();
  1174. /// get the corresponding DefInit.
  1175. DefInit *getDefInit();
  1176. bool isClass() const { return IsClass; }
  1177. ArrayRef<Init *> getTemplateArgs() const {
  1178. return TemplateArgs;
  1179. }
  1180. ArrayRef<RecordVal> getValues() const { return Values; }
  1181. ArrayRef<AssertionInfo> getAssertions() const { return Assertions; }
  1182. ArrayRef<std::pair<Record *, SMRange>> getSuperClasses() const {
  1183. return SuperClasses;
  1184. }
  1185. /// Determine whether this record has the specified direct superclass.
  1186. bool hasDirectSuperClass(const Record *SuperClass) const;
  1187. /// Append the direct superclasses of this record to Classes.
  1188. void getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const;
  1189. bool isTemplateArg(Init *Name) const {
  1190. return llvm::is_contained(TemplateArgs, Name);
  1191. }
  1192. const RecordVal *getValue(const Init *Name) const {
  1193. for (const RecordVal &Val : Values)
  1194. if (Val.Name == Name) return &Val;
  1195. return nullptr;
  1196. }
  1197. const RecordVal *getValue(StringRef Name) const {
  1198. return getValue(StringInit::get(Name));
  1199. }
  1200. RecordVal *getValue(const Init *Name) {
  1201. return const_cast<RecordVal *>(static_cast<const Record *>(this)->getValue(Name));
  1202. }
  1203. RecordVal *getValue(StringRef Name) {
  1204. return const_cast<RecordVal *>(static_cast<const Record *>(this)->getValue(Name));
  1205. }
  1206. void addTemplateArg(Init *Name) {
  1207. assert(!isTemplateArg(Name) && "Template arg already defined!");
  1208. TemplateArgs.push_back(Name);
  1209. }
  1210. void addValue(const RecordVal &RV) {
  1211. assert(getValue(RV.getNameInit()) == nullptr && "Value already added!");
  1212. Values.push_back(RV);
  1213. }
  1214. void removeValue(Init *Name) {
  1215. for (unsigned i = 0, e = Values.size(); i != e; ++i)
  1216. if (Values[i].getNameInit() == Name) {
  1217. Values.erase(Values.begin()+i);
  1218. return;
  1219. }
  1220. llvm_unreachable("Cannot remove an entry that does not exist!");
  1221. }
  1222. void removeValue(StringRef Name) {
  1223. removeValue(StringInit::get(Name));
  1224. }
  1225. void addAssertion(SMLoc Loc, Init *Condition, Init *Message) {
  1226. Assertions.push_back(AssertionInfo(Loc, Condition, Message));
  1227. }
  1228. void appendAssertions(const Record *Rec) {
  1229. Assertions.append(Rec->Assertions);
  1230. }
  1231. void checkRecordAssertions();
  1232. void checkUnusedTemplateArgs();
  1233. bool isSubClassOf(const Record *R) const {
  1234. for (const auto &SCPair : SuperClasses)
  1235. if (SCPair.first == R)
  1236. return true;
  1237. return false;
  1238. }
  1239. bool isSubClassOf(StringRef Name) const {
  1240. for (const auto &SCPair : SuperClasses) {
  1241. if (const auto *SI = dyn_cast<StringInit>(SCPair.first->getNameInit())) {
  1242. if (SI->getValue() == Name)
  1243. return true;
  1244. } else if (SCPair.first->getNameInitAsString() == Name) {
  1245. return true;
  1246. }
  1247. }
  1248. return false;
  1249. }
  1250. void addSuperClass(Record *R, SMRange Range) {
  1251. assert(!CorrespondingDefInit &&
  1252. "changing type of record after it has been referenced");
  1253. assert(!isSubClassOf(R) && "Already subclassing record!");
  1254. SuperClasses.push_back(std::make_pair(R, Range));
  1255. }
  1256. /// If there are any field references that refer to fields
  1257. /// that have been filled in, we can propagate the values now.
  1258. ///
  1259. /// This is a final resolve: any error messages, e.g. due to undefined
  1260. /// !cast references, are generated now.
  1261. void resolveReferences(Init *NewName = nullptr);
  1262. /// Apply the resolver to the name of the record as well as to the
  1263. /// initializers of all fields of the record except SkipVal.
  1264. ///
  1265. /// The resolver should not resolve any of the fields itself, to avoid
  1266. /// recursion / infinite loops.
  1267. void resolveReferences(Resolver &R, const RecordVal *SkipVal = nullptr);
  1268. RecordKeeper &getRecords() const {
  1269. return TrackedRecords;
  1270. }
  1271. bool isAnonymous() const {
  1272. return IsAnonymous;
  1273. }
  1274. void dump() const;
  1275. //===--------------------------------------------------------------------===//
  1276. // High-level methods useful to tablegen back-ends
  1277. //
  1278. ///Return the source location for the named field.
  1279. SMLoc getFieldLoc(StringRef FieldName) const;
  1280. /// Return the initializer for a value with the specified name,
  1281. /// or throw an exception if the field does not exist.
  1282. Init *getValueInit(StringRef FieldName) const;
  1283. /// Return true if the named field is unset.
  1284. bool isValueUnset(StringRef FieldName) const {
  1285. return isa<UnsetInit>(getValueInit(FieldName));
  1286. }
  1287. /// This method looks up the specified field and returns
  1288. /// its value as a string, throwing an exception if the field does not exist
  1289. /// or if the value is not a string.
  1290. StringRef getValueAsString(StringRef FieldName) const;
  1291. /// This method looks up the specified field and returns
  1292. /// its value as a string, throwing an exception if the field if the value is
  1293. /// not a string and llvm::Optional() if the field does not exist.
  1294. llvm::Optional<StringRef> getValueAsOptionalString(StringRef FieldName) const;
  1295. /// This method looks up the specified field and returns
  1296. /// its value as a BitsInit, throwing an exception if the field does not exist
  1297. /// or if the value is not the right type.
  1298. BitsInit *getValueAsBitsInit(StringRef FieldName) const;
  1299. /// This method looks up the specified field and returns
  1300. /// its value as a ListInit, throwing an exception if the field does not exist
  1301. /// or if the value is not the right type.
  1302. ListInit *getValueAsListInit(StringRef FieldName) const;
  1303. /// This method looks up the specified field and
  1304. /// returns its value as a vector of records, throwing an exception if the
  1305. /// field does not exist or if the value is not the right type.
  1306. std::vector<Record*> getValueAsListOfDefs(StringRef FieldName) const;
  1307. /// This method looks up the specified field and
  1308. /// returns its value as a vector of integers, throwing an exception if the
  1309. /// field does not exist or if the value is not the right type.
  1310. std::vector<int64_t> getValueAsListOfInts(StringRef FieldName) const;
  1311. /// This method looks up the specified field and
  1312. /// returns its value as a vector of strings, throwing an exception if the
  1313. /// field does not exist or if the value is not the right type.
  1314. std::vector<StringRef> getValueAsListOfStrings(StringRef FieldName) const;
  1315. /// This method looks up the specified field and returns its
  1316. /// value as a Record, throwing an exception if the field does not exist or if
  1317. /// the value is not the right type.
  1318. Record *getValueAsDef(StringRef FieldName) const;
  1319. /// This method looks up the specified field and returns its value as a
  1320. /// Record, returning null if the field exists but is "uninitialized"
  1321. /// (i.e. set to `?`), and throwing an exception if the field does not
  1322. /// exist or if its value is not the right type.
  1323. Record *getValueAsOptionalDef(StringRef FieldName) const;
  1324. /// This method looks up the specified field and returns its
  1325. /// value as a bit, throwing an exception if the field does not exist or if
  1326. /// the value is not the right type.
  1327. bool getValueAsBit(StringRef FieldName) const;
  1328. /// This method looks up the specified field and
  1329. /// returns its value as a bit. If the field is unset, sets Unset to true and
  1330. /// returns false.
  1331. bool getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const;
  1332. /// This method looks up the specified field and returns its
  1333. /// value as an int64_t, throwing an exception if the field does not exist or
  1334. /// if the value is not the right type.
  1335. int64_t getValueAsInt(StringRef FieldName) const;
  1336. /// This method looks up the specified field and returns its
  1337. /// value as an Dag, throwing an exception if the field does not exist or if
  1338. /// the value is not the right type.
  1339. DagInit *getValueAsDag(StringRef FieldName) const;
  1340. };
  1341. raw_ostream &operator<<(raw_ostream &OS, const Record &R);
  1342. class RecordKeeper {
  1343. friend class RecordRecTy;
  1344. using RecordMap = std::map<std::string, std::unique_ptr<Record>, std::less<>>;
  1345. using GlobalMap = std::map<std::string, Init *, std::less<>>;
  1346. std::string InputFilename;
  1347. RecordMap Classes, Defs;
  1348. mutable StringMap<std::vector<Record *>> ClassRecordsMap;
  1349. FoldingSet<RecordRecTy> RecordTypePool;
  1350. std::map<std::string, Init *, std::less<>> ExtraGlobals;
  1351. unsigned AnonCounter = 0;
  1352. // These members are for the phase timing feature. We need a timer group,
  1353. // the last timer started, and a flag to say whether the last timer
  1354. // is the special "backend overall timer."
  1355. TimerGroup *TimingGroup = nullptr;
  1356. Timer *LastTimer = nullptr;
  1357. bool BackendTimer = false;
  1358. public:
  1359. /// Get the main TableGen input file's name.
  1360. const std::string getInputFilename() const { return InputFilename; }
  1361. /// Get the map of classes.
  1362. const RecordMap &getClasses() const { return Classes; }
  1363. /// Get the map of records (defs).
  1364. const RecordMap &getDefs() const { return Defs; }
  1365. /// Get the map of global variables.
  1366. const GlobalMap &getGlobals() const { return ExtraGlobals; }
  1367. /// Get the class with the specified name.
  1368. Record *getClass(StringRef Name) const {
  1369. auto I = Classes.find(Name);
  1370. return I == Classes.end() ? nullptr : I->second.get();
  1371. }
  1372. /// Get the concrete record with the specified name.
  1373. Record *getDef(StringRef Name) const {
  1374. auto I = Defs.find(Name);
  1375. return I == Defs.end() ? nullptr : I->second.get();
  1376. }
  1377. /// Get the \p Init value of the specified global variable.
  1378. Init *getGlobal(StringRef Name) const {
  1379. if (Record *R = getDef(Name))
  1380. return R->getDefInit();
  1381. auto It = ExtraGlobals.find(Name);
  1382. return It == ExtraGlobals.end() ? nullptr : It->second;
  1383. }
  1384. void saveInputFilename(std::string Filename) {
  1385. InputFilename = Filename;
  1386. }
  1387. void addClass(std::unique_ptr<Record> R) {
  1388. bool Ins = Classes.insert(std::make_pair(std::string(R->getName()),
  1389. std::move(R))).second;
  1390. (void)Ins;
  1391. assert(Ins && "Class already exists");
  1392. }
  1393. void addDef(std::unique_ptr<Record> R) {
  1394. bool Ins = Defs.insert(std::make_pair(std::string(R->getName()),
  1395. std::move(R))).second;
  1396. (void)Ins;
  1397. assert(Ins && "Record already exists");
  1398. }
  1399. void addExtraGlobal(StringRef Name, Init *I) {
  1400. bool Ins = ExtraGlobals.insert(std::make_pair(std::string(Name), I)).second;
  1401. (void)Ins;
  1402. assert(!getDef(Name));
  1403. assert(Ins && "Global already exists");
  1404. }
  1405. Init *getNewAnonymousName();
  1406. /// Start phase timing; called if the --time-phases option is specified.
  1407. void startPhaseTiming() {
  1408. TimingGroup = new TimerGroup("TableGen", "TableGen Phase Timing");
  1409. }
  1410. /// Start timing a phase. Automatically stops any previous phase timer.
  1411. void startTimer(StringRef Name);
  1412. /// Stop timing a phase.
  1413. void stopTimer();
  1414. /// Start timing the overall backend. If the backend itself starts a timer,
  1415. /// then this timer is cleared.
  1416. void startBackendTimer(StringRef Name);
  1417. /// Stop timing the overall backend.
  1418. void stopBackendTimer();
  1419. /// Stop phase timing and print the report.
  1420. void stopPhaseTiming() {
  1421. if (TimingGroup)
  1422. delete TimingGroup;
  1423. }
  1424. //===--------------------------------------------------------------------===//
  1425. // High-level helper methods, useful for tablegen backends.
  1426. /// Get all the concrete records that inherit from the one specified
  1427. /// class. The class must be defined.
  1428. std::vector<Record *> getAllDerivedDefinitions(StringRef ClassName) const;
  1429. /// Get all the concrete records that inherit from all the specified
  1430. /// classes. The classes must be defined.
  1431. std::vector<Record *> getAllDerivedDefinitions(
  1432. ArrayRef<StringRef> ClassNames) const;
  1433. void dump() const;
  1434. };
  1435. /// Sorting predicate to sort record pointers by name.
  1436. struct LessRecord {
  1437. bool operator()(const Record *Rec1, const Record *Rec2) const {
  1438. return StringRef(Rec1->getName()).compare_numeric(Rec2->getName()) < 0;
  1439. }
  1440. };
  1441. /// Sorting predicate to sort record pointers by their
  1442. /// unique ID. If you just need a deterministic order, use this, since it
  1443. /// just compares two `unsigned`; the other sorting predicates require
  1444. /// string manipulation.
  1445. struct LessRecordByID {
  1446. bool operator()(const Record *LHS, const Record *RHS) const {
  1447. return LHS->getID() < RHS->getID();
  1448. }
  1449. };
  1450. /// Sorting predicate to sort record pointers by their
  1451. /// name field.
  1452. struct LessRecordFieldName {
  1453. bool operator()(const Record *Rec1, const Record *Rec2) const {
  1454. return Rec1->getValueAsString("Name") < Rec2->getValueAsString("Name");
  1455. }
  1456. };
  1457. struct LessRecordRegister {
  1458. struct RecordParts {
  1459. SmallVector<std::pair< bool, StringRef>, 4> Parts;
  1460. RecordParts(StringRef Rec) {
  1461. if (Rec.empty())
  1462. return;
  1463. size_t Len = 0;
  1464. const char *Start = Rec.data();
  1465. const char *Curr = Start;
  1466. bool IsDigitPart = isDigit(Curr[0]);
  1467. for (size_t I = 0, E = Rec.size(); I != E; ++I, ++Len) {
  1468. bool IsDigit = isDigit(Curr[I]);
  1469. if (IsDigit != IsDigitPart) {
  1470. Parts.push_back(std::make_pair(IsDigitPart, StringRef(Start, Len)));
  1471. Len = 0;
  1472. Start = &Curr[I];
  1473. IsDigitPart = isDigit(Curr[I]);
  1474. }
  1475. }
  1476. // Push the last part.
  1477. Parts.push_back(std::make_pair(IsDigitPart, StringRef(Start, Len)));
  1478. }
  1479. size_t size() { return Parts.size(); }
  1480. std::pair<bool, StringRef> getPart(size_t i) {
  1481. assert (i < Parts.size() && "Invalid idx!");
  1482. return Parts[i];
  1483. }
  1484. };
  1485. bool operator()(const Record *Rec1, const Record *Rec2) const {
  1486. RecordParts LHSParts(StringRef(Rec1->getName()));
  1487. RecordParts RHSParts(StringRef(Rec2->getName()));
  1488. size_t LHSNumParts = LHSParts.size();
  1489. size_t RHSNumParts = RHSParts.size();
  1490. assert (LHSNumParts && RHSNumParts && "Expected at least one part!");
  1491. if (LHSNumParts != RHSNumParts)
  1492. return LHSNumParts < RHSNumParts;
  1493. // We expect the registers to be of the form [_a-zA-Z]+([0-9]*[_a-zA-Z]*)*.
  1494. for (size_t I = 0, E = LHSNumParts; I < E; I+=2) {
  1495. std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
  1496. std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
  1497. // Expect even part to always be alpha.
  1498. assert (LHSPart.first == false && RHSPart.first == false &&
  1499. "Expected both parts to be alpha.");
  1500. if (int Res = LHSPart.second.compare(RHSPart.second))
  1501. return Res < 0;
  1502. }
  1503. for (size_t I = 1, E = LHSNumParts; I < E; I+=2) {
  1504. std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
  1505. std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
  1506. // Expect odd part to always be numeric.
  1507. assert (LHSPart.first == true && RHSPart.first == true &&
  1508. "Expected both parts to be numeric.");
  1509. if (LHSPart.second.size() != RHSPart.second.size())
  1510. return LHSPart.second.size() < RHSPart.second.size();
  1511. unsigned LHSVal, RHSVal;
  1512. bool LHSFailed = LHSPart.second.getAsInteger(10, LHSVal); (void)LHSFailed;
  1513. assert(!LHSFailed && "Unable to convert LHS to integer.");
  1514. bool RHSFailed = RHSPart.second.getAsInteger(10, RHSVal); (void)RHSFailed;
  1515. assert(!RHSFailed && "Unable to convert RHS to integer.");
  1516. if (LHSVal != RHSVal)
  1517. return LHSVal < RHSVal;
  1518. }
  1519. return LHSNumParts < RHSNumParts;
  1520. }
  1521. };
  1522. raw_ostream &operator<<(raw_ostream &OS, const RecordKeeper &RK);
  1523. //===----------------------------------------------------------------------===//
  1524. // Resolvers
  1525. //===----------------------------------------------------------------------===//
  1526. /// Interface for looking up the initializer for a variable name, used by
  1527. /// Init::resolveReferences.
  1528. class Resolver {
  1529. Record *CurRec;
  1530. bool IsFinal = false;
  1531. public:
  1532. explicit Resolver(Record *CurRec) : CurRec(CurRec) {}
  1533. virtual ~Resolver() = default;
  1534. Record *getCurrentRecord() const { return CurRec; }
  1535. /// Return the initializer for the given variable name (should normally be a
  1536. /// StringInit), or nullptr if the name could not be resolved.
  1537. virtual Init *resolve(Init *VarName) = 0;
  1538. // Whether bits in a BitsInit should stay unresolved if resolving them would
  1539. // result in a ? (UnsetInit). This behavior is used to represent instruction
  1540. // encodings by keeping references to unset variables within a record.
  1541. virtual bool keepUnsetBits() const { return false; }
  1542. // Whether this is the final resolve step before adding a record to the
  1543. // RecordKeeper. Error reporting during resolve and related constant folding
  1544. // should only happen when this is true.
  1545. bool isFinal() const { return IsFinal; }
  1546. void setFinal(bool Final) { IsFinal = Final; }
  1547. };
  1548. /// Resolve arbitrary mappings.
  1549. class MapResolver final : public Resolver {
  1550. struct MappedValue {
  1551. Init *V;
  1552. bool Resolved;
  1553. MappedValue() : V(nullptr), Resolved(false) {}
  1554. MappedValue(Init *V, bool Resolved) : V(V), Resolved(Resolved) {}
  1555. };
  1556. DenseMap<Init *, MappedValue> Map;
  1557. public:
  1558. explicit MapResolver(Record *CurRec = nullptr) : Resolver(CurRec) {}
  1559. void set(Init *Key, Init *Value) { Map[Key] = {Value, false}; }
  1560. bool isComplete(Init *VarName) const {
  1561. auto It = Map.find(VarName);
  1562. assert(It != Map.end() && "key must be present in map");
  1563. return It->second.V->isComplete();
  1564. }
  1565. Init *resolve(Init *VarName) override;
  1566. };
  1567. /// Resolve all variables from a record except for unset variables.
  1568. class RecordResolver final : public Resolver {
  1569. DenseMap<Init *, Init *> Cache;
  1570. SmallVector<Init *, 4> Stack;
  1571. Init *Name = nullptr;
  1572. public:
  1573. explicit RecordResolver(Record &R) : Resolver(&R) {}
  1574. void setName(Init *NewName) { Name = NewName; }
  1575. Init *resolve(Init *VarName) override;
  1576. bool keepUnsetBits() const override { return true; }
  1577. };
  1578. /// Delegate resolving to a sub-resolver, but shadow some variable names.
  1579. class ShadowResolver final : public Resolver {
  1580. Resolver &R;
  1581. DenseSet<Init *> Shadowed;
  1582. public:
  1583. explicit ShadowResolver(Resolver &R)
  1584. : Resolver(R.getCurrentRecord()), R(R) {
  1585. setFinal(R.isFinal());
  1586. }
  1587. void addShadow(Init *Key) { Shadowed.insert(Key); }
  1588. Init *resolve(Init *VarName) override {
  1589. if (Shadowed.count(VarName))
  1590. return nullptr;
  1591. return R.resolve(VarName);
  1592. }
  1593. };
  1594. /// (Optionally) delegate resolving to a sub-resolver, and keep track whether
  1595. /// there were unresolved references.
  1596. class TrackUnresolvedResolver final : public Resolver {
  1597. Resolver *R;
  1598. bool FoundUnresolved = false;
  1599. public:
  1600. explicit TrackUnresolvedResolver(Resolver *R = nullptr)
  1601. : Resolver(R ? R->getCurrentRecord() : nullptr), R(R) {}
  1602. bool foundUnresolved() const { return FoundUnresolved; }
  1603. Init *resolve(Init *VarName) override;
  1604. };
  1605. /// Do not resolve anything, but keep track of whether a given variable was
  1606. /// referenced.
  1607. class HasReferenceResolver final : public Resolver {
  1608. Init *VarNameToTrack;
  1609. bool Found = false;
  1610. public:
  1611. explicit HasReferenceResolver(Init *VarNameToTrack)
  1612. : Resolver(nullptr), VarNameToTrack(VarNameToTrack) {}
  1613. bool found() const { return Found; }
  1614. Init *resolve(Init *VarName) override;
  1615. };
  1616. void EmitDetailedRecords(RecordKeeper &RK, raw_ostream &OS);
  1617. void EmitJSON(RecordKeeper &RK, raw_ostream &OS);
  1618. } // end namespace llvm
  1619. #endif // LLVM_TABLEGEN_RECORD_H
  1620. #ifdef __GNUC__
  1621. #pragma GCC diagnostic pop
  1622. #endif