Recommit [NFC] Better encapsulation of llvm::Optional Storage
[llvm-complete.git] / include / llvm / TableGen / Record.h
blobe4a07bbb71be20a8dd52c1a45d7fbbaa6d1bf792
1 //===- llvm/TableGen/Record.h - Classes for Table Records -------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the main TableGen data structures, including the TableGen
10 // types, values, and high-level data structures.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_TABLEGEN_RECORD_H
15 #define LLVM_TABLEGEN_RECORD_H
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/PointerIntPair.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/Support/Casting.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/SMLoc.h"
27 #include "llvm/Support/TrailingObjects.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <algorithm>
30 #include <cassert>
31 #include <cstddef>
32 #include <cstdint>
33 #include <map>
34 #include <memory>
35 #include <string>
36 #include <utility>
37 #include <vector>
39 namespace llvm {
41 class ListRecTy;
42 struct MultiClass;
43 class Record;
44 class RecordKeeper;
45 class RecordVal;
46 class Resolver;
47 class StringInit;
48 class TypedInit;
50 //===----------------------------------------------------------------------===//
51 // Type Classes
52 //===----------------------------------------------------------------------===//
54 class RecTy {
55 public:
56 /// Subclass discriminator (for dyn_cast<> et al.)
57 enum RecTyKind {
58 BitRecTyKind,
59 BitsRecTyKind,
60 CodeRecTyKind,
61 IntRecTyKind,
62 StringRecTyKind,
63 ListRecTyKind,
64 DagRecTyKind,
65 RecordRecTyKind
68 private:
69 RecTyKind Kind;
70 ListRecTy *ListTy = nullptr;
72 public:
73 RecTy(RecTyKind K) : Kind(K) {}
74 virtual ~RecTy() = default;
76 RecTyKind getRecTyKind() const { return Kind; }
78 virtual std::string getAsString() const = 0;
79 void print(raw_ostream &OS) const { OS << getAsString(); }
80 void dump() const;
82 /// Return true if all values of 'this' type can be converted to the specified
83 /// type.
84 virtual bool typeIsConvertibleTo(const RecTy *RHS) const;
86 /// Return true if 'this' type is equal to or a subtype of RHS. For example,
87 /// a bit set is not an int, but they are convertible.
88 virtual bool typeIsA(const RecTy *RHS) const;
90 /// Returns the type representing list<this>.
91 ListRecTy *getListTy();
94 inline raw_ostream &operator<<(raw_ostream &OS, const RecTy &Ty) {
95 Ty.print(OS);
96 return OS;
99 /// 'bit' - Represent a single bit
100 class BitRecTy : public RecTy {
101 static BitRecTy Shared;
103 BitRecTy() : RecTy(BitRecTyKind) {}
105 public:
106 static bool classof(const RecTy *RT) {
107 return RT->getRecTyKind() == BitRecTyKind;
110 static BitRecTy *get() { return &Shared; }
112 std::string getAsString() const override { return "bit"; }
114 bool typeIsConvertibleTo(const RecTy *RHS) const override;
117 /// 'bits<n>' - Represent a fixed number of bits
118 class BitsRecTy : public RecTy {
119 unsigned Size;
121 explicit BitsRecTy(unsigned Sz) : RecTy(BitsRecTyKind), Size(Sz) {}
123 public:
124 static bool classof(const RecTy *RT) {
125 return RT->getRecTyKind() == BitsRecTyKind;
128 static BitsRecTy *get(unsigned Sz);
130 unsigned getNumBits() const { return Size; }
132 std::string getAsString() const override;
134 bool typeIsConvertibleTo(const RecTy *RHS) const override;
136 bool typeIsA(const RecTy *RHS) const override;
139 /// 'code' - Represent a code fragment
140 class CodeRecTy : public RecTy {
141 static CodeRecTy Shared;
143 CodeRecTy() : RecTy(CodeRecTyKind) {}
145 public:
146 static bool classof(const RecTy *RT) {
147 return RT->getRecTyKind() == CodeRecTyKind;
150 static CodeRecTy *get() { return &Shared; }
152 std::string getAsString() const override { return "code"; }
154 bool typeIsConvertibleTo(const RecTy *RHS) const override;
157 /// 'int' - Represent an integer value of no particular size
158 class IntRecTy : public RecTy {
159 static IntRecTy Shared;
161 IntRecTy() : RecTy(IntRecTyKind) {}
163 public:
164 static bool classof(const RecTy *RT) {
165 return RT->getRecTyKind() == IntRecTyKind;
168 static IntRecTy *get() { return &Shared; }
170 std::string getAsString() const override { return "int"; }
172 bool typeIsConvertibleTo(const RecTy *RHS) const override;
175 /// 'string' - Represent an string value
176 class StringRecTy : public RecTy {
177 static StringRecTy Shared;
179 StringRecTy() : RecTy(StringRecTyKind) {}
181 public:
182 static bool classof(const RecTy *RT) {
183 return RT->getRecTyKind() == StringRecTyKind;
186 static StringRecTy *get() { return &Shared; }
188 std::string getAsString() const override;
190 bool typeIsConvertibleTo(const RecTy *RHS) const override;
193 /// 'list<Ty>' - Represent a list of values, all of which must be of
194 /// the specified type.
195 class ListRecTy : public RecTy {
196 friend ListRecTy *RecTy::getListTy();
198 RecTy *Ty;
200 explicit ListRecTy(RecTy *T) : RecTy(ListRecTyKind), Ty(T) {}
202 public:
203 static bool classof(const RecTy *RT) {
204 return RT->getRecTyKind() == ListRecTyKind;
207 static ListRecTy *get(RecTy *T) { return T->getListTy(); }
208 RecTy *getElementType() const { return Ty; }
210 std::string getAsString() const override;
212 bool typeIsConvertibleTo(const RecTy *RHS) const override;
214 bool typeIsA(const RecTy *RHS) const override;
217 /// 'dag' - Represent a dag fragment
218 class DagRecTy : public RecTy {
219 static DagRecTy Shared;
221 DagRecTy() : RecTy(DagRecTyKind) {}
223 public:
224 static bool classof(const RecTy *RT) {
225 return RT->getRecTyKind() == DagRecTyKind;
228 static DagRecTy *get() { return &Shared; }
230 std::string getAsString() const override;
233 /// '[classname]' - Type of record values that have zero or more superclasses.
235 /// The list of superclasses is non-redundant, i.e. only contains classes that
236 /// are not the superclass of some other listed class.
237 class RecordRecTy final : public RecTy, public FoldingSetNode,
238 public TrailingObjects<RecordRecTy, Record *> {
239 friend class Record;
241 unsigned NumClasses;
243 explicit RecordRecTy(unsigned Num)
244 : RecTy(RecordRecTyKind), NumClasses(Num) {}
246 public:
247 RecordRecTy(const RecordRecTy &) = delete;
248 RecordRecTy &operator=(const RecordRecTy &) = delete;
250 // Do not use sized deallocation due to trailing objects.
251 void operator delete(void *p) { ::operator delete(p); }
253 static bool classof(const RecTy *RT) {
254 return RT->getRecTyKind() == RecordRecTyKind;
257 /// Get the record type with the given non-redundant list of superclasses.
258 static RecordRecTy *get(ArrayRef<Record *> Classes);
260 void Profile(FoldingSetNodeID &ID) const;
262 ArrayRef<Record *> getClasses() const {
263 return makeArrayRef(getTrailingObjects<Record *>(), NumClasses);
266 using const_record_iterator = Record * const *;
268 const_record_iterator classes_begin() const { return getClasses().begin(); }
269 const_record_iterator classes_end() const { return getClasses().end(); }
271 std::string getAsString() const override;
273 bool isSubClassOf(Record *Class) const;
274 bool typeIsConvertibleTo(const RecTy *RHS) const override;
276 bool typeIsA(const RecTy *RHS) const override;
279 /// Find a common type that T1 and T2 convert to.
280 /// Return 0 if no such type exists.
281 RecTy *resolveTypes(RecTy *T1, RecTy *T2);
283 //===----------------------------------------------------------------------===//
284 // Initializer Classes
285 //===----------------------------------------------------------------------===//
287 class Init {
288 protected:
289 /// Discriminator enum (for isa<>, dyn_cast<>, et al.)
291 /// This enum is laid out by a preorder traversal of the inheritance
292 /// hierarchy, and does not contain an entry for abstract classes, as per
293 /// the recommendation in docs/HowToSetUpLLVMStyleRTTI.rst.
295 /// We also explicitly include "first" and "last" values for each
296 /// interior node of the inheritance tree, to make it easier to read the
297 /// corresponding classof().
299 /// We could pack these a bit tighter by not having the IK_FirstXXXInit
300 /// and IK_LastXXXInit be their own values, but that would degrade
301 /// readability for really no benefit.
302 enum InitKind : uint8_t {
303 IK_First, // unused; silence a spurious warning
304 IK_FirstTypedInit,
305 IK_BitInit,
306 IK_BitsInit,
307 IK_CodeInit,
308 IK_DagInit,
309 IK_DefInit,
310 IK_FieldInit,
311 IK_IntInit,
312 IK_ListInit,
313 IK_FirstOpInit,
314 IK_BinOpInit,
315 IK_TernOpInit,
316 IK_UnOpInit,
317 IK_LastOpInit,
318 IK_CondOpInit,
319 IK_FoldOpInit,
320 IK_IsAOpInit,
321 IK_StringInit,
322 IK_VarInit,
323 IK_VarListElementInit,
324 IK_VarBitInit,
325 IK_VarDefInit,
326 IK_LastTypedInit,
327 IK_UnsetInit
330 private:
331 const InitKind Kind;
333 protected:
334 uint8_t Opc; // Used by UnOpInit, BinOpInit, and TernOpInit
336 private:
337 virtual void anchor();
339 public:
340 InitKind getKind() const { return Kind; }
342 protected:
343 explicit Init(InitKind K, uint8_t Opc = 0) : Kind(K), Opc(Opc) {}
345 public:
346 Init(const Init &) = delete;
347 Init &operator=(const Init &) = delete;
348 virtual ~Init() = default;
350 /// This virtual method should be overridden by values that may
351 /// not be completely specified yet.
352 virtual bool isComplete() const { return true; }
354 /// Is this a concrete and fully resolved value without any references or
355 /// stuck operations? Unset values are concrete.
356 virtual bool isConcrete() const { return false; }
358 /// Print out this value.
359 void print(raw_ostream &OS) const { OS << getAsString(); }
361 /// Convert this value to a string form.
362 virtual std::string getAsString() const = 0;
363 /// Convert this value to a string form,
364 /// without adding quote markers. This primaruly affects
365 /// StringInits where we will not surround the string value with
366 /// quotes.
367 virtual std::string getAsUnquotedString() const { return getAsString(); }
369 /// Debugging method that may be called through a debugger, just
370 /// invokes print on stderr.
371 void dump() const;
373 /// If this initializer is convertible to Ty, return an initializer whose
374 /// type is-a Ty, generating a !cast operation if required. Otherwise, return
375 /// nullptr.
376 virtual Init *getCastTo(RecTy *Ty) const = 0;
378 /// Convert to an initializer whose type is-a Ty, or return nullptr if this
379 /// is not possible (this can happen if the initializer's type is convertible
380 /// to Ty, but there are unresolved references).
381 virtual Init *convertInitializerTo(RecTy *Ty) const = 0;
383 /// This method is used to implement the bitrange
384 /// selection operator. Given an initializer, it selects the specified bits
385 /// out, returning them as a new init of bits type. If it is not legal to use
386 /// the bit subscript operator on this initializer, return null.
387 virtual Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
388 return nullptr;
391 /// This method is used to implement the list slice
392 /// selection operator. Given an initializer, it selects the specified list
393 /// elements, returning them as a new init of list type. If it is not legal
394 /// to take a slice of this, return null.
395 virtual Init *convertInitListSlice(ArrayRef<unsigned> Elements) const {
396 return nullptr;
399 /// This method is used to implement the FieldInit class.
400 /// Implementors of this method should return the type of the named field if
401 /// they are of record type.
402 virtual RecTy *getFieldType(StringInit *FieldName) const {
403 return nullptr;
406 /// This method is used by classes that refer to other
407 /// variables which may not be defined at the time the expression is formed.
408 /// If a value is set for the variable later, this method will be called on
409 /// users of the value to allow the value to propagate out.
410 virtual Init *resolveReferences(Resolver &R) const {
411 return const_cast<Init *>(this);
414 /// This method is used to return the initializer for the specified
415 /// bit.
416 virtual Init *getBit(unsigned Bit) const = 0;
419 inline raw_ostream &operator<<(raw_ostream &OS, const Init &I) {
420 I.print(OS); return OS;
423 /// This is the common super-class of types that have a specific,
424 /// explicit, type.
425 class TypedInit : public Init {
426 RecTy *Ty;
428 protected:
429 explicit TypedInit(InitKind K, RecTy *T, uint8_t Opc = 0)
430 : Init(K, Opc), Ty(T) {}
432 public:
433 TypedInit(const TypedInit &) = delete;
434 TypedInit &operator=(const TypedInit &) = delete;
436 static bool classof(const Init *I) {
437 return I->getKind() >= IK_FirstTypedInit &&
438 I->getKind() <= IK_LastTypedInit;
441 RecTy *getType() const { return Ty; }
443 Init *getCastTo(RecTy *Ty) const override;
444 Init *convertInitializerTo(RecTy *Ty) const override;
446 Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
447 Init *convertInitListSlice(ArrayRef<unsigned> Elements) const override;
449 /// This method is used to implement the FieldInit class.
450 /// Implementors of this method should return the type of the named field if
451 /// they are of record type.
453 RecTy *getFieldType(StringInit *FieldName) const override;
456 /// '?' - Represents an uninitialized value
457 class UnsetInit : public Init {
458 UnsetInit() : Init(IK_UnsetInit) {}
460 public:
461 UnsetInit(const UnsetInit &) = delete;
462 UnsetInit &operator=(const UnsetInit &) = delete;
464 static bool classof(const Init *I) {
465 return I->getKind() == IK_UnsetInit;
468 static UnsetInit *get();
470 Init *getCastTo(RecTy *Ty) const override;
471 Init *convertInitializerTo(RecTy *Ty) const override;
473 Init *getBit(unsigned Bit) const override {
474 return const_cast<UnsetInit*>(this);
477 bool isComplete() const override { return false; }
478 bool isConcrete() const override { return true; }
479 std::string getAsString() const override { return "?"; }
482 /// 'true'/'false' - Represent a concrete initializer for a bit.
483 class BitInit final : public TypedInit {
484 bool Value;
486 explicit BitInit(bool V) : TypedInit(IK_BitInit, BitRecTy::get()), Value(V) {}
488 public:
489 BitInit(const BitInit &) = delete;
490 BitInit &operator=(BitInit &) = delete;
492 static bool classof(const Init *I) {
493 return I->getKind() == IK_BitInit;
496 static BitInit *get(bool V);
498 bool getValue() const { return Value; }
500 Init *convertInitializerTo(RecTy *Ty) const override;
502 Init *getBit(unsigned Bit) const override {
503 assert(Bit < 1 && "Bit index out of range!");
504 return const_cast<BitInit*>(this);
507 bool isConcrete() const override { return true; }
508 std::string getAsString() const override { return Value ? "1" : "0"; }
511 /// '{ a, b, c }' - Represents an initializer for a BitsRecTy value.
512 /// It contains a vector of bits, whose size is determined by the type.
513 class BitsInit final : public TypedInit, public FoldingSetNode,
514 public TrailingObjects<BitsInit, Init *> {
515 unsigned NumBits;
517 BitsInit(unsigned N)
518 : TypedInit(IK_BitsInit, BitsRecTy::get(N)), NumBits(N) {}
520 public:
521 BitsInit(const BitsInit &) = delete;
522 BitsInit &operator=(const BitsInit &) = delete;
524 // Do not use sized deallocation due to trailing objects.
525 void operator delete(void *p) { ::operator delete(p); }
527 static bool classof(const Init *I) {
528 return I->getKind() == IK_BitsInit;
531 static BitsInit *get(ArrayRef<Init *> Range);
533 void Profile(FoldingSetNodeID &ID) const;
535 unsigned getNumBits() const { return NumBits; }
537 Init *convertInitializerTo(RecTy *Ty) const override;
538 Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
540 bool isComplete() const override {
541 for (unsigned i = 0; i != getNumBits(); ++i)
542 if (!getBit(i)->isComplete()) return false;
543 return true;
546 bool allInComplete() const {
547 for (unsigned i = 0; i != getNumBits(); ++i)
548 if (getBit(i)->isComplete()) return false;
549 return true;
552 bool isConcrete() const override;
553 std::string getAsString() const override;
555 Init *resolveReferences(Resolver &R) const override;
557 Init *getBit(unsigned Bit) const override {
558 assert(Bit < NumBits && "Bit index out of range!");
559 return getTrailingObjects<Init *>()[Bit];
563 /// '7' - Represent an initialization by a literal integer value.
564 class IntInit : public TypedInit {
565 int64_t Value;
567 explicit IntInit(int64_t V)
568 : TypedInit(IK_IntInit, IntRecTy::get()), Value(V) {}
570 public:
571 IntInit(const IntInit &) = delete;
572 IntInit &operator=(const IntInit &) = delete;
574 static bool classof(const Init *I) {
575 return I->getKind() == IK_IntInit;
578 static IntInit *get(int64_t V);
580 int64_t getValue() const { return Value; }
582 Init *convertInitializerTo(RecTy *Ty) const override;
583 Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
585 bool isConcrete() const override { return true; }
586 std::string getAsString() const override;
588 Init *getBit(unsigned Bit) const override {
589 return BitInit::get((Value & (1ULL << Bit)) != 0);
593 /// "foo" - Represent an initialization by a string value.
594 class StringInit : public TypedInit {
595 StringRef Value;
597 explicit StringInit(StringRef V)
598 : TypedInit(IK_StringInit, StringRecTy::get()), Value(V) {}
600 public:
601 StringInit(const StringInit &) = delete;
602 StringInit &operator=(const StringInit &) = delete;
604 static bool classof(const Init *I) {
605 return I->getKind() == IK_StringInit;
608 static StringInit *get(StringRef);
610 StringRef getValue() const { return Value; }
612 Init *convertInitializerTo(RecTy *Ty) const override;
614 bool isConcrete() const override { return true; }
615 std::string getAsString() const override { return "\"" + Value.str() + "\""; }
617 std::string getAsUnquotedString() const override { return Value; }
619 Init *getBit(unsigned Bit) const override {
620 llvm_unreachable("Illegal bit reference off string");
624 class CodeInit : public TypedInit {
625 StringRef Value;
627 explicit CodeInit(StringRef V)
628 : TypedInit(IK_CodeInit, static_cast<RecTy *>(CodeRecTy::get())),
629 Value(V) {}
631 public:
632 CodeInit(const StringInit &) = delete;
633 CodeInit &operator=(const StringInit &) = delete;
635 static bool classof(const Init *I) {
636 return I->getKind() == IK_CodeInit;
639 static CodeInit *get(StringRef);
641 StringRef getValue() const { return Value; }
643 Init *convertInitializerTo(RecTy *Ty) const override;
645 bool isConcrete() const override { return true; }
646 std::string getAsString() const override {
647 return "[{" + Value.str() + "}]";
650 std::string getAsUnquotedString() const override { return Value; }
652 Init *getBit(unsigned Bit) const override {
653 llvm_unreachable("Illegal bit reference off string");
657 /// [AL, AH, CL] - Represent a list of defs
659 class ListInit final : public TypedInit, public FoldingSetNode,
660 public TrailingObjects<ListInit, Init *> {
661 unsigned NumValues;
663 public:
664 using const_iterator = Init *const *;
666 private:
667 explicit ListInit(unsigned N, RecTy *EltTy)
668 : TypedInit(IK_ListInit, ListRecTy::get(EltTy)), NumValues(N) {}
670 public:
671 ListInit(const ListInit &) = delete;
672 ListInit &operator=(const ListInit &) = delete;
674 // Do not use sized deallocation due to trailing objects.
675 void operator delete(void *p) { ::operator delete(p); }
677 static bool classof(const Init *I) {
678 return I->getKind() == IK_ListInit;
680 static ListInit *get(ArrayRef<Init *> Range, RecTy *EltTy);
682 void Profile(FoldingSetNodeID &ID) const;
684 Init *getElement(unsigned i) const {
685 assert(i < NumValues && "List element index out of range!");
686 return getTrailingObjects<Init *>()[i];
688 RecTy *getElementType() const {
689 return cast<ListRecTy>(getType())->getElementType();
692 Record *getElementAsRecord(unsigned i) const;
694 Init *convertInitListSlice(ArrayRef<unsigned> Elements) const override;
696 Init *convertInitializerTo(RecTy *Ty) const override;
698 /// This method is used by classes that refer to other
699 /// variables which may not be defined at the time they expression is formed.
700 /// If a value is set for the variable later, this method will be called on
701 /// users of the value to allow the value to propagate out.
703 Init *resolveReferences(Resolver &R) const override;
705 bool isConcrete() const override;
706 std::string getAsString() const override;
708 ArrayRef<Init*> getValues() const {
709 return makeArrayRef(getTrailingObjects<Init *>(), NumValues);
712 const_iterator begin() const { return getTrailingObjects<Init *>(); }
713 const_iterator end () const { return begin() + NumValues; }
715 size_t size () const { return NumValues; }
716 bool empty() const { return NumValues == 0; }
718 Init *getBit(unsigned Bit) const override {
719 llvm_unreachable("Illegal bit reference off list");
723 /// Base class for operators
725 class OpInit : public TypedInit {
726 protected:
727 explicit OpInit(InitKind K, RecTy *Type, uint8_t Opc)
728 : TypedInit(K, Type, Opc) {}
730 public:
731 OpInit(const OpInit &) = delete;
732 OpInit &operator=(OpInit &) = delete;
734 static bool classof(const Init *I) {
735 return I->getKind() >= IK_FirstOpInit &&
736 I->getKind() <= IK_LastOpInit;
739 // Clone - Clone this operator, replacing arguments with the new list
740 virtual OpInit *clone(ArrayRef<Init *> Operands) const = 0;
742 virtual unsigned getNumOperands() const = 0;
743 virtual Init *getOperand(unsigned i) const = 0;
745 Init *getBit(unsigned Bit) const override;
748 /// !op (X) - Transform an init.
750 class UnOpInit : public OpInit, public FoldingSetNode {
751 public:
752 enum UnaryOp : uint8_t { CAST, HEAD, TAIL, SIZE, EMPTY };
754 private:
755 Init *LHS;
757 UnOpInit(UnaryOp opc, Init *lhs, RecTy *Type)
758 : OpInit(IK_UnOpInit, Type, opc), LHS(lhs) {}
760 public:
761 UnOpInit(const UnOpInit &) = delete;
762 UnOpInit &operator=(const UnOpInit &) = delete;
764 static bool classof(const Init *I) {
765 return I->getKind() == IK_UnOpInit;
768 static UnOpInit *get(UnaryOp opc, Init *lhs, RecTy *Type);
770 void Profile(FoldingSetNodeID &ID) const;
772 // Clone - Clone this operator, replacing arguments with the new list
773 OpInit *clone(ArrayRef<Init *> Operands) const override {
774 assert(Operands.size() == 1 &&
775 "Wrong number of operands for unary operation");
776 return UnOpInit::get(getOpcode(), *Operands.begin(), getType());
779 unsigned getNumOperands() const override { return 1; }
781 Init *getOperand(unsigned i) const override {
782 assert(i == 0 && "Invalid operand id for unary operator");
783 return getOperand();
786 UnaryOp getOpcode() const { return (UnaryOp)Opc; }
787 Init *getOperand() const { return LHS; }
789 // Fold - If possible, fold this to a simpler init. Return this if not
790 // possible to fold.
791 Init *Fold(Record *CurRec, bool IsFinal = false) const;
793 Init *resolveReferences(Resolver &R) const override;
795 std::string getAsString() const override;
798 /// !op (X, Y) - Combine two inits.
799 class BinOpInit : public OpInit, public FoldingSetNode {
800 public:
801 enum BinaryOp : uint8_t { ADD, AND, OR, SHL, SRA, SRL, LISTCONCAT,
802 STRCONCAT, CONCAT, EQ, NE, LE, LT, GE, GT };
804 private:
805 Init *LHS, *RHS;
807 BinOpInit(BinaryOp opc, Init *lhs, Init *rhs, RecTy *Type) :
808 OpInit(IK_BinOpInit, Type, opc), LHS(lhs), RHS(rhs) {}
810 public:
811 BinOpInit(const BinOpInit &) = delete;
812 BinOpInit &operator=(const BinOpInit &) = delete;
814 static bool classof(const Init *I) {
815 return I->getKind() == IK_BinOpInit;
818 static BinOpInit *get(BinaryOp opc, Init *lhs, Init *rhs,
819 RecTy *Type);
820 static Init *getStrConcat(Init *lhs, Init *rhs);
822 void Profile(FoldingSetNodeID &ID) const;
824 // Clone - Clone this operator, replacing arguments with the new list
825 OpInit *clone(ArrayRef<Init *> Operands) const override {
826 assert(Operands.size() == 2 &&
827 "Wrong number of operands for binary operation");
828 return BinOpInit::get(getOpcode(), Operands[0], Operands[1], getType());
831 unsigned getNumOperands() const override { return 2; }
832 Init *getOperand(unsigned i) const override {
833 switch (i) {
834 default: llvm_unreachable("Invalid operand id for binary operator");
835 case 0: return getLHS();
836 case 1: return getRHS();
840 BinaryOp getOpcode() const { return (BinaryOp)Opc; }
841 Init *getLHS() const { return LHS; }
842 Init *getRHS() const { return RHS; }
844 // Fold - If possible, fold this to a simpler init. Return this if not
845 // possible to fold.
846 Init *Fold(Record *CurRec) const;
848 Init *resolveReferences(Resolver &R) const override;
850 std::string getAsString() const override;
853 /// !op (X, Y, Z) - Combine two inits.
854 class TernOpInit : public OpInit, public FoldingSetNode {
855 public:
856 enum TernaryOp : uint8_t { SUBST, FOREACH, IF, DAG };
858 private:
859 Init *LHS, *MHS, *RHS;
861 TernOpInit(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs,
862 RecTy *Type) :
863 OpInit(IK_TernOpInit, Type, opc), LHS(lhs), MHS(mhs), RHS(rhs) {}
865 public:
866 TernOpInit(const TernOpInit &) = delete;
867 TernOpInit &operator=(const TernOpInit &) = delete;
869 static bool classof(const Init *I) {
870 return I->getKind() == IK_TernOpInit;
873 static TernOpInit *get(TernaryOp opc, Init *lhs,
874 Init *mhs, Init *rhs,
875 RecTy *Type);
877 void Profile(FoldingSetNodeID &ID) const;
879 // Clone - Clone this operator, replacing arguments with the new list
880 OpInit *clone(ArrayRef<Init *> Operands) const override {
881 assert(Operands.size() == 3 &&
882 "Wrong number of operands for ternary operation");
883 return TernOpInit::get(getOpcode(), Operands[0], Operands[1], Operands[2],
884 getType());
887 unsigned getNumOperands() const override { return 3; }
888 Init *getOperand(unsigned i) const override {
889 switch (i) {
890 default: llvm_unreachable("Invalid operand id for ternary operator");
891 case 0: return getLHS();
892 case 1: return getMHS();
893 case 2: return getRHS();
897 TernaryOp getOpcode() const { return (TernaryOp)Opc; }
898 Init *getLHS() const { return LHS; }
899 Init *getMHS() const { return MHS; }
900 Init *getRHS() const { return RHS; }
902 // Fold - If possible, fold this to a simpler init. Return this if not
903 // possible to fold.
904 Init *Fold(Record *CurRec) const;
906 bool isComplete() const override {
907 return LHS->isComplete() && MHS->isComplete() && RHS->isComplete();
910 Init *resolveReferences(Resolver &R) const override;
912 std::string getAsString() const override;
915 /// !cond(condition_1: value1, ... , condition_n: value)
916 /// Selects the first value for which condition is true.
917 /// Otherwise reports an error.
918 class CondOpInit final : public TypedInit, public FoldingSetNode,
919 public TrailingObjects<CondOpInit, Init *> {
920 unsigned NumConds;
921 RecTy *ValType;
923 CondOpInit(unsigned NC, RecTy *Type)
924 : TypedInit(IK_CondOpInit, Type),
925 NumConds(NC), ValType(Type) {}
927 size_t numTrailingObjects(OverloadToken<Init *>) const {
928 return 2*NumConds;
931 public:
932 CondOpInit(const CondOpInit &) = delete;
933 CondOpInit &operator=(const CondOpInit &) = delete;
935 static bool classof(const Init *I) {
936 return I->getKind() == IK_CondOpInit;
939 static CondOpInit *get(ArrayRef<Init*> C, ArrayRef<Init*> V,
940 RecTy *Type);
942 void Profile(FoldingSetNodeID &ID) const;
944 RecTy *getValType() const { return ValType; }
946 unsigned getNumConds() const { return NumConds; }
948 Init *getCond(unsigned Num) const {
949 assert(Num < NumConds && "Condition number out of range!");
950 return getTrailingObjects<Init *>()[Num];
953 Init *getVal(unsigned Num) const {
954 assert(Num < NumConds && "Val number out of range!");
955 return getTrailingObjects<Init *>()[Num+NumConds];
958 ArrayRef<Init *> getConds() const {
959 return makeArrayRef(getTrailingObjects<Init *>(), NumConds);
962 ArrayRef<Init *> getVals() const {
963 return makeArrayRef(getTrailingObjects<Init *>()+NumConds, NumConds);
966 Init *Fold(Record *CurRec) const;
968 Init *resolveReferences(Resolver &R) const override;
970 bool isConcrete() const override;
971 bool isComplete() const override;
972 std::string getAsString() const override;
974 using const_case_iterator = SmallVectorImpl<Init*>::const_iterator;
975 using const_val_iterator = SmallVectorImpl<Init*>::const_iterator;
977 inline const_case_iterator arg_begin() const { return getConds().begin(); }
978 inline const_case_iterator arg_end () const { return getConds().end(); }
980 inline size_t case_size () const { return NumConds; }
981 inline bool case_empty() const { return NumConds == 0; }
983 inline const_val_iterator name_begin() const { return getVals().begin();}
984 inline const_val_iterator name_end () const { return getVals().end(); }
986 inline size_t val_size () const { return NumConds; }
987 inline bool val_empty() const { return NumConds == 0; }
989 Init *getBit(unsigned Bit) const override;
992 /// !foldl (a, b, expr, start, lst) - Fold over a list.
993 class FoldOpInit : public TypedInit, public FoldingSetNode {
994 private:
995 Init *Start;
996 Init *List;
997 Init *A;
998 Init *B;
999 Init *Expr;
1001 FoldOpInit(Init *Start, Init *List, Init *A, Init *B, Init *Expr, RecTy *Type)
1002 : TypedInit(IK_FoldOpInit, Type), Start(Start), List(List), A(A), B(B),
1003 Expr(Expr) {}
1005 public:
1006 FoldOpInit(const FoldOpInit &) = delete;
1007 FoldOpInit &operator=(const FoldOpInit &) = delete;
1009 static bool classof(const Init *I) { return I->getKind() == IK_FoldOpInit; }
1011 static FoldOpInit *get(Init *Start, Init *List, Init *A, Init *B, Init *Expr,
1012 RecTy *Type);
1014 void Profile(FoldingSetNodeID &ID) const;
1016 // Fold - If possible, fold this to a simpler init. Return this if not
1017 // possible to fold.
1018 Init *Fold(Record *CurRec) const;
1020 bool isComplete() const override { return false; }
1022 Init *resolveReferences(Resolver &R) const override;
1024 Init *getBit(unsigned Bit) const override;
1026 std::string getAsString() const override;
1029 /// !isa<type>(expr) - Dynamically determine the type of an expression.
1030 class IsAOpInit : public TypedInit, public FoldingSetNode {
1031 private:
1032 RecTy *CheckType;
1033 Init *Expr;
1035 IsAOpInit(RecTy *CheckType, Init *Expr)
1036 : TypedInit(IK_IsAOpInit, IntRecTy::get()), CheckType(CheckType),
1037 Expr(Expr) {}
1039 public:
1040 IsAOpInit(const IsAOpInit &) = delete;
1041 IsAOpInit &operator=(const IsAOpInit &) = delete;
1043 static bool classof(const Init *I) { return I->getKind() == IK_IsAOpInit; }
1045 static IsAOpInit *get(RecTy *CheckType, Init *Expr);
1047 void Profile(FoldingSetNodeID &ID) const;
1049 // Fold - If possible, fold this to a simpler init. Return this if not
1050 // possible to fold.
1051 Init *Fold() const;
1053 bool isComplete() const override { return false; }
1055 Init *resolveReferences(Resolver &R) const override;
1057 Init *getBit(unsigned Bit) const override;
1059 std::string getAsString() const override;
1062 /// 'Opcode' - Represent a reference to an entire variable object.
1063 class VarInit : public TypedInit {
1064 Init *VarName;
1066 explicit VarInit(Init *VN, RecTy *T)
1067 : TypedInit(IK_VarInit, T), VarName(VN) {}
1069 public:
1070 VarInit(const VarInit &) = delete;
1071 VarInit &operator=(const VarInit &) = delete;
1073 static bool classof(const Init *I) {
1074 return I->getKind() == IK_VarInit;
1077 static VarInit *get(StringRef VN, RecTy *T);
1078 static VarInit *get(Init *VN, RecTy *T);
1080 StringRef getName() const;
1081 Init *getNameInit() const { return VarName; }
1083 std::string getNameInitAsString() const {
1084 return getNameInit()->getAsUnquotedString();
1087 /// This method is used by classes that refer to other
1088 /// variables which may not be defined at the time they expression is formed.
1089 /// If a value is set for the variable later, this method will be called on
1090 /// users of the value to allow the value to propagate out.
1092 Init *resolveReferences(Resolver &R) const override;
1094 Init *getBit(unsigned Bit) const override;
1096 std::string getAsString() const override { return getName(); }
1099 /// Opcode{0} - Represent access to one bit of a variable or field.
1100 class VarBitInit final : public TypedInit {
1101 TypedInit *TI;
1102 unsigned Bit;
1104 VarBitInit(TypedInit *T, unsigned B)
1105 : TypedInit(IK_VarBitInit, BitRecTy::get()), TI(T), Bit(B) {
1106 assert(T->getType() &&
1107 (isa<IntRecTy>(T->getType()) ||
1108 (isa<BitsRecTy>(T->getType()) &&
1109 cast<BitsRecTy>(T->getType())->getNumBits() > B)) &&
1110 "Illegal VarBitInit expression!");
1113 public:
1114 VarBitInit(const VarBitInit &) = delete;
1115 VarBitInit &operator=(const VarBitInit &) = delete;
1117 static bool classof(const Init *I) {
1118 return I->getKind() == IK_VarBitInit;
1121 static VarBitInit *get(TypedInit *T, unsigned B);
1123 Init *getBitVar() const { return TI; }
1124 unsigned getBitNum() const { return Bit; }
1126 std::string getAsString() const override;
1127 Init *resolveReferences(Resolver &R) const override;
1129 Init *getBit(unsigned B) const override {
1130 assert(B < 1 && "Bit index out of range!");
1131 return const_cast<VarBitInit*>(this);
1135 /// List[4] - Represent access to one element of a var or
1136 /// field.
1137 class VarListElementInit : public TypedInit {
1138 TypedInit *TI;
1139 unsigned Element;
1141 VarListElementInit(TypedInit *T, unsigned E)
1142 : TypedInit(IK_VarListElementInit,
1143 cast<ListRecTy>(T->getType())->getElementType()),
1144 TI(T), Element(E) {
1145 assert(T->getType() && isa<ListRecTy>(T->getType()) &&
1146 "Illegal VarBitInit expression!");
1149 public:
1150 VarListElementInit(const VarListElementInit &) = delete;
1151 VarListElementInit &operator=(const VarListElementInit &) = delete;
1153 static bool classof(const Init *I) {
1154 return I->getKind() == IK_VarListElementInit;
1157 static VarListElementInit *get(TypedInit *T, unsigned E);
1159 TypedInit *getVariable() const { return TI; }
1160 unsigned getElementNum() const { return Element; }
1162 std::string getAsString() const override;
1163 Init *resolveReferences(Resolver &R) const override;
1165 Init *getBit(unsigned Bit) const override;
1168 /// AL - Represent a reference to a 'def' in the description
1169 class DefInit : public TypedInit {
1170 friend class Record;
1172 Record *Def;
1174 explicit DefInit(Record *D);
1176 public:
1177 DefInit(const DefInit &) = delete;
1178 DefInit &operator=(const DefInit &) = delete;
1180 static bool classof(const Init *I) {
1181 return I->getKind() == IK_DefInit;
1184 static DefInit *get(Record*);
1186 Init *convertInitializerTo(RecTy *Ty) const override;
1188 Record *getDef() const { return Def; }
1190 //virtual Init *convertInitializerBitRange(ArrayRef<unsigned> Bits);
1192 RecTy *getFieldType(StringInit *FieldName) const override;
1194 bool isConcrete() const override { return true; }
1195 std::string getAsString() const override;
1197 Init *getBit(unsigned Bit) const override {
1198 llvm_unreachable("Illegal bit reference off def");
1202 /// classname<targs...> - Represent an uninstantiated anonymous class
1203 /// instantiation.
1204 class VarDefInit final : public TypedInit, public FoldingSetNode,
1205 public TrailingObjects<VarDefInit, Init *> {
1206 Record *Class;
1207 DefInit *Def = nullptr; // after instantiation
1208 unsigned NumArgs;
1210 explicit VarDefInit(Record *Class, unsigned N)
1211 : TypedInit(IK_VarDefInit, RecordRecTy::get(Class)), Class(Class), NumArgs(N) {}
1213 DefInit *instantiate();
1215 public:
1216 VarDefInit(const VarDefInit &) = delete;
1217 VarDefInit &operator=(const VarDefInit &) = delete;
1219 // Do not use sized deallocation due to trailing objects.
1220 void operator delete(void *p) { ::operator delete(p); }
1222 static bool classof(const Init *I) {
1223 return I->getKind() == IK_VarDefInit;
1225 static VarDefInit *get(Record *Class, ArrayRef<Init *> Args);
1227 void Profile(FoldingSetNodeID &ID) const;
1229 Init *resolveReferences(Resolver &R) const override;
1230 Init *Fold() const;
1232 std::string getAsString() const override;
1234 Init *getArg(unsigned i) const {
1235 assert(i < NumArgs && "Argument index out of range!");
1236 return getTrailingObjects<Init *>()[i];
1239 using const_iterator = Init *const *;
1241 const_iterator args_begin() const { return getTrailingObjects<Init *>(); }
1242 const_iterator args_end () const { return args_begin() + NumArgs; }
1244 size_t args_size () const { return NumArgs; }
1245 bool args_empty() const { return NumArgs == 0; }
1247 ArrayRef<Init *> args() const { return makeArrayRef(args_begin(), NumArgs); }
1249 Init *getBit(unsigned Bit) const override {
1250 llvm_unreachable("Illegal bit reference off anonymous def");
1254 /// X.Y - Represent a reference to a subfield of a variable
1255 class FieldInit : public TypedInit {
1256 Init *Rec; // Record we are referring to
1257 StringInit *FieldName; // Field we are accessing
1259 FieldInit(Init *R, StringInit *FN)
1260 : TypedInit(IK_FieldInit, R->getFieldType(FN)), Rec(R), FieldName(FN) {
1261 assert(getType() && "FieldInit with non-record type!");
1264 public:
1265 FieldInit(const FieldInit &) = delete;
1266 FieldInit &operator=(const FieldInit &) = delete;
1268 static bool classof(const Init *I) {
1269 return I->getKind() == IK_FieldInit;
1272 static FieldInit *get(Init *R, StringInit *FN);
1274 Init *getRecord() const { return Rec; }
1275 StringInit *getFieldName() const { return FieldName; }
1277 Init *getBit(unsigned Bit) const override;
1279 Init *resolveReferences(Resolver &R) const override;
1280 Init *Fold(Record *CurRec) const;
1282 std::string getAsString() const override {
1283 return Rec->getAsString() + "." + FieldName->getValue().str();
1287 /// (v a, b) - Represent a DAG tree value. DAG inits are required
1288 /// to have at least one value then a (possibly empty) list of arguments. Each
1289 /// argument can have a name associated with it.
1290 class DagInit final : public TypedInit, public FoldingSetNode,
1291 public TrailingObjects<DagInit, Init *, StringInit *> {
1292 friend TrailingObjects;
1294 Init *Val;
1295 StringInit *ValName;
1296 unsigned NumArgs;
1297 unsigned NumArgNames;
1299 DagInit(Init *V, StringInit *VN, unsigned NumArgs, unsigned NumArgNames)
1300 : TypedInit(IK_DagInit, DagRecTy::get()), Val(V), ValName(VN),
1301 NumArgs(NumArgs), NumArgNames(NumArgNames) {}
1303 size_t numTrailingObjects(OverloadToken<Init *>) const { return NumArgs; }
1305 public:
1306 DagInit(const DagInit &) = delete;
1307 DagInit &operator=(const DagInit &) = delete;
1309 static bool classof(const Init *I) {
1310 return I->getKind() == IK_DagInit;
1313 static DagInit *get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
1314 ArrayRef<StringInit*> NameRange);
1315 static DagInit *get(Init *V, StringInit *VN,
1316 ArrayRef<std::pair<Init*, StringInit*>> Args);
1318 void Profile(FoldingSetNodeID &ID) const;
1320 Init *getOperator() const { return Val; }
1322 StringInit *getName() const { return ValName; }
1324 StringRef getNameStr() const {
1325 return ValName ? ValName->getValue() : StringRef();
1328 unsigned getNumArgs() const { return NumArgs; }
1330 Init *getArg(unsigned Num) const {
1331 assert(Num < NumArgs && "Arg number out of range!");
1332 return getTrailingObjects<Init *>()[Num];
1335 StringInit *getArgName(unsigned Num) const {
1336 assert(Num < NumArgNames && "Arg number out of range!");
1337 return getTrailingObjects<StringInit *>()[Num];
1340 StringRef getArgNameStr(unsigned Num) const {
1341 StringInit *Init = getArgName(Num);
1342 return Init ? Init->getValue() : StringRef();
1345 ArrayRef<Init *> getArgs() const {
1346 return makeArrayRef(getTrailingObjects<Init *>(), NumArgs);
1349 ArrayRef<StringInit *> getArgNames() const {
1350 return makeArrayRef(getTrailingObjects<StringInit *>(), NumArgNames);
1353 Init *resolveReferences(Resolver &R) const override;
1355 bool isConcrete() const override;
1356 std::string getAsString() const override;
1358 using const_arg_iterator = SmallVectorImpl<Init*>::const_iterator;
1359 using const_name_iterator = SmallVectorImpl<StringInit*>::const_iterator;
1361 inline const_arg_iterator arg_begin() const { return getArgs().begin(); }
1362 inline const_arg_iterator arg_end () const { return getArgs().end(); }
1364 inline size_t arg_size () const { return NumArgs; }
1365 inline bool arg_empty() const { return NumArgs == 0; }
1367 inline const_name_iterator name_begin() const { return getArgNames().begin();}
1368 inline const_name_iterator name_end () const { return getArgNames().end(); }
1370 inline size_t name_size () const { return NumArgNames; }
1371 inline bool name_empty() const { return NumArgNames == 0; }
1373 Init *getBit(unsigned Bit) const override {
1374 llvm_unreachable("Illegal bit reference off dag");
1378 //===----------------------------------------------------------------------===//
1379 // High-Level Classes
1380 //===----------------------------------------------------------------------===//
1382 class RecordVal {
1383 friend class Record;
1385 Init *Name;
1386 PointerIntPair<RecTy *, 1, bool> TyAndPrefix;
1387 Init *Value;
1389 public:
1390 RecordVal(Init *N, RecTy *T, bool P);
1392 StringRef getName() const;
1393 Init *getNameInit() const { return Name; }
1395 std::string getNameInitAsString() const {
1396 return getNameInit()->getAsUnquotedString();
1399 bool getPrefix() const { return TyAndPrefix.getInt(); }
1400 RecTy *getType() const { return TyAndPrefix.getPointer(); }
1401 Init *getValue() const { return Value; }
1403 bool setValue(Init *V);
1405 void dump() const;
1406 void print(raw_ostream &OS, bool PrintSem = true) const;
1409 inline raw_ostream &operator<<(raw_ostream &OS, const RecordVal &RV) {
1410 RV.print(OS << " ");
1411 return OS;
1414 class Record {
1415 static unsigned LastID;
1417 Init *Name;
1418 // Location where record was instantiated, followed by the location of
1419 // multiclass prototypes used.
1420 SmallVector<SMLoc, 4> Locs;
1421 SmallVector<Init *, 0> TemplateArgs;
1422 SmallVector<RecordVal, 0> Values;
1424 // All superclasses in the inheritance forest in reverse preorder (yes, it
1425 // must be a forest; diamond-shaped inheritance is not allowed).
1426 SmallVector<std::pair<Record *, SMRange>, 0> SuperClasses;
1428 // Tracks Record instances. Not owned by Record.
1429 RecordKeeper &TrackedRecords;
1431 DefInit *TheInit = nullptr;
1433 // Unique record ID.
1434 unsigned ID;
1436 bool IsAnonymous;
1437 bool IsClass;
1439 void checkName();
1441 public:
1442 // Constructs a record.
1443 explicit Record(Init *N, ArrayRef<SMLoc> locs, RecordKeeper &records,
1444 bool Anonymous = false, bool Class = false)
1445 : Name(N), Locs(locs.begin(), locs.end()), TrackedRecords(records),
1446 ID(LastID++), IsAnonymous(Anonymous), IsClass(Class) {
1447 checkName();
1450 explicit Record(StringRef N, ArrayRef<SMLoc> locs, RecordKeeper &records,
1451 bool Class = false)
1452 : Record(StringInit::get(N), locs, records, false, Class) {}
1454 // When copy-constructing a Record, we must still guarantee a globally unique
1455 // ID number. Don't copy TheInit either since it's owned by the original
1456 // record. All other fields can be copied normally.
1457 Record(const Record &O)
1458 : Name(O.Name), Locs(O.Locs), TemplateArgs(O.TemplateArgs),
1459 Values(O.Values), SuperClasses(O.SuperClasses),
1460 TrackedRecords(O.TrackedRecords), ID(LastID++),
1461 IsAnonymous(O.IsAnonymous), IsClass(O.IsClass) { }
1463 static unsigned getNewUID() { return LastID++; }
1465 unsigned getID() const { return ID; }
1467 StringRef getName() const { return cast<StringInit>(Name)->getValue(); }
1469 Init *getNameInit() const {
1470 return Name;
1473 const std::string getNameInitAsString() const {
1474 return getNameInit()->getAsUnquotedString();
1477 void setName(Init *Name); // Also updates RecordKeeper.
1479 ArrayRef<SMLoc> getLoc() const { return Locs; }
1480 void appendLoc(SMLoc Loc) { Locs.push_back(Loc); }
1482 // Make the type that this record should have based on its superclasses.
1483 RecordRecTy *getType();
1485 /// get the corresponding DefInit.
1486 DefInit *getDefInit();
1488 bool isClass() const { return IsClass; }
1490 ArrayRef<Init *> getTemplateArgs() const {
1491 return TemplateArgs;
1494 ArrayRef<RecordVal> getValues() const { return Values; }
1496 ArrayRef<std::pair<Record *, SMRange>> getSuperClasses() const {
1497 return SuperClasses;
1500 /// Append the direct super classes of this record to Classes.
1501 void getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const;
1503 bool isTemplateArg(Init *Name) const {
1504 for (Init *TA : TemplateArgs)
1505 if (TA == Name) return true;
1506 return false;
1509 const RecordVal *getValue(const Init *Name) const {
1510 for (const RecordVal &Val : Values)
1511 if (Val.Name == Name) return &Val;
1512 return nullptr;
1515 const RecordVal *getValue(StringRef Name) const {
1516 return getValue(StringInit::get(Name));
1519 RecordVal *getValue(const Init *Name) {
1520 return const_cast<RecordVal *>(static_cast<const Record *>(this)->getValue(Name));
1523 RecordVal *getValue(StringRef Name) {
1524 return const_cast<RecordVal *>(static_cast<const Record *>(this)->getValue(Name));
1527 void addTemplateArg(Init *Name) {
1528 assert(!isTemplateArg(Name) && "Template arg already defined!");
1529 TemplateArgs.push_back(Name);
1532 void addValue(const RecordVal &RV) {
1533 assert(getValue(RV.getNameInit()) == nullptr && "Value already added!");
1534 Values.push_back(RV);
1537 void removeValue(Init *Name) {
1538 for (unsigned i = 0, e = Values.size(); i != e; ++i)
1539 if (Values[i].getNameInit() == Name) {
1540 Values.erase(Values.begin()+i);
1541 return;
1543 llvm_unreachable("Cannot remove an entry that does not exist!");
1546 void removeValue(StringRef Name) {
1547 removeValue(StringInit::get(Name));
1550 bool isSubClassOf(const Record *R) const {
1551 for (const auto &SCPair : SuperClasses)
1552 if (SCPair.first == R)
1553 return true;
1554 return false;
1557 bool isSubClassOf(StringRef Name) const {
1558 for (const auto &SCPair : SuperClasses) {
1559 if (const auto *SI = dyn_cast<StringInit>(SCPair.first->getNameInit())) {
1560 if (SI->getValue() == Name)
1561 return true;
1562 } else if (SCPair.first->getNameInitAsString() == Name) {
1563 return true;
1566 return false;
1569 void addSuperClass(Record *R, SMRange Range) {
1570 assert(!TheInit && "changing type of record after it has been referenced");
1571 assert(!isSubClassOf(R) && "Already subclassing record!");
1572 SuperClasses.push_back(std::make_pair(R, Range));
1575 /// If there are any field references that refer to fields
1576 /// that have been filled in, we can propagate the values now.
1578 /// This is a final resolve: any error messages, e.g. due to undefined
1579 /// !cast references, are generated now.
1580 void resolveReferences();
1582 /// Apply the resolver to the name of the record as well as to the
1583 /// initializers of all fields of the record except SkipVal.
1585 /// The resolver should not resolve any of the fields itself, to avoid
1586 /// recursion / infinite loops.
1587 void resolveReferences(Resolver &R, const RecordVal *SkipVal = nullptr);
1589 /// If anything in this record refers to RV, replace the
1590 /// reference to RV with the RHS of RV. If RV is null, we resolve all
1591 /// possible references.
1592 void resolveReferencesTo(const RecordVal *RV);
1594 RecordKeeper &getRecords() const {
1595 return TrackedRecords;
1598 bool isAnonymous() const {
1599 return IsAnonymous;
1602 void print(raw_ostream &OS) const;
1603 void dump() const;
1605 //===--------------------------------------------------------------------===//
1606 // High-level methods useful to tablegen back-ends
1609 /// Return the initializer for a value with the specified name,
1610 /// or throw an exception if the field does not exist.
1611 Init *getValueInit(StringRef FieldName) const;
1613 /// Return true if the named field is unset.
1614 bool isValueUnset(StringRef FieldName) const {
1615 return isa<UnsetInit>(getValueInit(FieldName));
1618 /// This method looks up the specified field and returns
1619 /// its value as a string, throwing an exception if the field does not exist
1620 /// or if the value is not a string.
1621 StringRef getValueAsString(StringRef FieldName) const;
1623 /// This method looks up the specified field and returns
1624 /// its value as a BitsInit, throwing an exception if the field does not exist
1625 /// or if the value is not the right type.
1626 BitsInit *getValueAsBitsInit(StringRef FieldName) const;
1628 /// This method looks up the specified field and returns
1629 /// its value as a ListInit, throwing an exception if the field does not exist
1630 /// or if the value is not the right type.
1631 ListInit *getValueAsListInit(StringRef FieldName) const;
1633 /// This method looks up the specified field and
1634 /// returns its value as a vector of records, throwing an exception if the
1635 /// field does not exist or if the value is not the right type.
1636 std::vector<Record*> getValueAsListOfDefs(StringRef FieldName) const;
1638 /// This method looks up the specified field and
1639 /// returns its value as a vector of integers, throwing an exception if the
1640 /// field does not exist or if the value is not the right type.
1641 std::vector<int64_t> getValueAsListOfInts(StringRef FieldName) const;
1643 /// This method looks up the specified field and
1644 /// returns its value as a vector of strings, throwing an exception if the
1645 /// field does not exist or if the value is not the right type.
1646 std::vector<StringRef> getValueAsListOfStrings(StringRef FieldName) const;
1648 /// This method looks up the specified field and returns its
1649 /// value as a Record, throwing an exception if the field does not exist or if
1650 /// the value is not the right type.
1651 Record *getValueAsDef(StringRef FieldName) const;
1653 /// This method looks up the specified field and returns its
1654 /// value as a bit, throwing an exception if the field does not exist or if
1655 /// the value is not the right type.
1656 bool getValueAsBit(StringRef FieldName) const;
1658 /// This method looks up the specified field and
1659 /// returns its value as a bit. If the field is unset, sets Unset to true and
1660 /// returns false.
1661 bool getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const;
1663 /// This method looks up the specified field and returns its
1664 /// value as an int64_t, throwing an exception if the field does not exist or
1665 /// if the value is not the right type.
1666 int64_t getValueAsInt(StringRef FieldName) const;
1668 /// This method looks up the specified field and returns its
1669 /// value as an Dag, throwing an exception if the field does not exist or if
1670 /// the value is not the right type.
1671 DagInit *getValueAsDag(StringRef FieldName) const;
1674 raw_ostream &operator<<(raw_ostream &OS, const Record &R);
1676 class RecordKeeper {
1677 friend class RecordRecTy;
1678 using RecordMap = std::map<std::string, std::unique_ptr<Record>>;
1679 RecordMap Classes, Defs;
1680 FoldingSet<RecordRecTy> RecordTypePool;
1681 std::map<std::string, Init *> ExtraGlobals;
1682 unsigned AnonCounter = 0;
1684 public:
1685 const RecordMap &getClasses() const { return Classes; }
1686 const RecordMap &getDefs() const { return Defs; }
1688 Record *getClass(StringRef Name) const {
1689 auto I = Classes.find(Name);
1690 return I == Classes.end() ? nullptr : I->second.get();
1693 Record *getDef(StringRef Name) const {
1694 auto I = Defs.find(Name);
1695 return I == Defs.end() ? nullptr : I->second.get();
1698 Init *getGlobal(StringRef Name) const {
1699 if (Record *R = getDef(Name))
1700 return R->getDefInit();
1701 auto It = ExtraGlobals.find(Name);
1702 return It == ExtraGlobals.end() ? nullptr : It->second;
1705 void addClass(std::unique_ptr<Record> R) {
1706 bool Ins = Classes.insert(std::make_pair(R->getName(),
1707 std::move(R))).second;
1708 (void)Ins;
1709 assert(Ins && "Class already exists");
1712 void addDef(std::unique_ptr<Record> R) {
1713 bool Ins = Defs.insert(std::make_pair(R->getName(),
1714 std::move(R))).second;
1715 (void)Ins;
1716 assert(Ins && "Record already exists");
1719 void addExtraGlobal(StringRef Name, Init *I) {
1720 bool Ins = ExtraGlobals.insert(std::make_pair(Name, I)).second;
1721 (void)Ins;
1722 assert(!getDef(Name));
1723 assert(Ins && "Global already exists");
1726 Init *getNewAnonymousName();
1728 //===--------------------------------------------------------------------===//
1729 // High-level helper methods, useful for tablegen backends...
1731 /// This method returns all concrete definitions
1732 /// that derive from the specified class name. A class with the specified
1733 /// name must exist.
1734 std::vector<Record *> getAllDerivedDefinitions(StringRef ClassName) const;
1736 void dump() const;
1739 /// Sorting predicate to sort record pointers by name.
1740 struct LessRecord {
1741 bool operator()(const Record *Rec1, const Record *Rec2) const {
1742 return StringRef(Rec1->getName()).compare_numeric(Rec2->getName()) < 0;
1746 /// Sorting predicate to sort record pointers by their
1747 /// unique ID. If you just need a deterministic order, use this, since it
1748 /// just compares two `unsigned`; the other sorting predicates require
1749 /// string manipulation.
1750 struct LessRecordByID {
1751 bool operator()(const Record *LHS, const Record *RHS) const {
1752 return LHS->getID() < RHS->getID();
1756 /// Sorting predicate to sort record pointers by their
1757 /// name field.
1758 struct LessRecordFieldName {
1759 bool operator()(const Record *Rec1, const Record *Rec2) const {
1760 return Rec1->getValueAsString("Name") < Rec2->getValueAsString("Name");
1764 struct LessRecordRegister {
1765 static bool ascii_isdigit(char x) { return x >= '0' && x <= '9'; }
1767 struct RecordParts {
1768 SmallVector<std::pair< bool, StringRef>, 4> Parts;
1770 RecordParts(StringRef Rec) {
1771 if (Rec.empty())
1772 return;
1774 size_t Len = 0;
1775 const char *Start = Rec.data();
1776 const char *Curr = Start;
1777 bool isDigitPart = ascii_isdigit(Curr[0]);
1778 for (size_t I = 0, E = Rec.size(); I != E; ++I, ++Len) {
1779 bool isDigit = ascii_isdigit(Curr[I]);
1780 if (isDigit != isDigitPart) {
1781 Parts.push_back(std::make_pair(isDigitPart, StringRef(Start, Len)));
1782 Len = 0;
1783 Start = &Curr[I];
1784 isDigitPart = ascii_isdigit(Curr[I]);
1787 // Push the last part.
1788 Parts.push_back(std::make_pair(isDigitPart, StringRef(Start, Len)));
1791 size_t size() { return Parts.size(); }
1793 std::pair<bool, StringRef> getPart(size_t i) {
1794 assert (i < Parts.size() && "Invalid idx!");
1795 return Parts[i];
1799 bool operator()(const Record *Rec1, const Record *Rec2) const {
1800 RecordParts LHSParts(StringRef(Rec1->getName()));
1801 RecordParts RHSParts(StringRef(Rec2->getName()));
1803 size_t LHSNumParts = LHSParts.size();
1804 size_t RHSNumParts = RHSParts.size();
1805 assert (LHSNumParts && RHSNumParts && "Expected at least one part!");
1807 if (LHSNumParts != RHSNumParts)
1808 return LHSNumParts < RHSNumParts;
1810 // We expect the registers to be of the form [_a-zA-Z]+([0-9]*[_a-zA-Z]*)*.
1811 for (size_t I = 0, E = LHSNumParts; I < E; I+=2) {
1812 std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
1813 std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
1814 // Expect even part to always be alpha.
1815 assert (LHSPart.first == false && RHSPart.first == false &&
1816 "Expected both parts to be alpha.");
1817 if (int Res = LHSPart.second.compare(RHSPart.second))
1818 return Res < 0;
1820 for (size_t I = 1, E = LHSNumParts; I < E; I+=2) {
1821 std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
1822 std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
1823 // Expect odd part to always be numeric.
1824 assert (LHSPart.first == true && RHSPart.first == true &&
1825 "Expected both parts to be numeric.");
1826 if (LHSPart.second.size() != RHSPart.second.size())
1827 return LHSPart.second.size() < RHSPart.second.size();
1829 unsigned LHSVal, RHSVal;
1831 bool LHSFailed = LHSPart.second.getAsInteger(10, LHSVal); (void)LHSFailed;
1832 assert(!LHSFailed && "Unable to convert LHS to integer.");
1833 bool RHSFailed = RHSPart.second.getAsInteger(10, RHSVal); (void)RHSFailed;
1834 assert(!RHSFailed && "Unable to convert RHS to integer.");
1836 if (LHSVal != RHSVal)
1837 return LHSVal < RHSVal;
1839 return LHSNumParts < RHSNumParts;
1843 raw_ostream &operator<<(raw_ostream &OS, const RecordKeeper &RK);
1845 //===----------------------------------------------------------------------===//
1846 // Resolvers
1847 //===----------------------------------------------------------------------===//
1849 /// Interface for looking up the initializer for a variable name, used by
1850 /// Init::resolveReferences.
1851 class Resolver {
1852 Record *CurRec;
1853 bool IsFinal = false;
1855 public:
1856 explicit Resolver(Record *CurRec) : CurRec(CurRec) {}
1857 virtual ~Resolver() {}
1859 Record *getCurrentRecord() const { return CurRec; }
1861 /// Return the initializer for the given variable name (should normally be a
1862 /// StringInit), or nullptr if the name could not be resolved.
1863 virtual Init *resolve(Init *VarName) = 0;
1865 // Whether bits in a BitsInit should stay unresolved if resolving them would
1866 // result in a ? (UnsetInit). This behavior is used to represent instruction
1867 // encodings by keeping references to unset variables within a record.
1868 virtual bool keepUnsetBits() const { return false; }
1870 // Whether this is the final resolve step before adding a record to the
1871 // RecordKeeper. Error reporting during resolve and related constant folding
1872 // should only happen when this is true.
1873 bool isFinal() const { return IsFinal; }
1875 void setFinal(bool Final) { IsFinal = Final; }
1878 /// Resolve arbitrary mappings.
1879 class MapResolver final : public Resolver {
1880 struct MappedValue {
1881 Init *V;
1882 bool Resolved;
1884 MappedValue() : V(nullptr), Resolved(false) {}
1885 MappedValue(Init *V, bool Resolved) : V(V), Resolved(Resolved) {}
1888 DenseMap<Init *, MappedValue> Map;
1890 public:
1891 explicit MapResolver(Record *CurRec = nullptr) : Resolver(CurRec) {}
1893 void set(Init *Key, Init *Value) { Map[Key] = {Value, false}; }
1895 Init *resolve(Init *VarName) override;
1898 /// Resolve all variables from a record except for unset variables.
1899 class RecordResolver final : public Resolver {
1900 DenseMap<Init *, Init *> Cache;
1901 SmallVector<Init *, 4> Stack;
1903 public:
1904 explicit RecordResolver(Record &R) : Resolver(&R) {}
1906 Init *resolve(Init *VarName) override;
1908 bool keepUnsetBits() const override { return true; }
1911 /// Resolve all references to a specific RecordVal.
1913 // TODO: This is used for resolving references to template arguments, in a
1914 // rather inefficient way. Change those uses to resolve all template
1915 // arguments simultaneously and get rid of this class.
1916 class RecordValResolver final : public Resolver {
1917 const RecordVal *RV;
1919 public:
1920 explicit RecordValResolver(Record &R, const RecordVal *RV)
1921 : Resolver(&R), RV(RV) {}
1923 Init *resolve(Init *VarName) override {
1924 if (VarName == RV->getNameInit())
1925 return RV->getValue();
1926 return nullptr;
1930 /// Delegate resolving to a sub-resolver, but shadow some variable names.
1931 class ShadowResolver final : public Resolver {
1932 Resolver &R;
1933 DenseSet<Init *> Shadowed;
1935 public:
1936 explicit ShadowResolver(Resolver &R)
1937 : Resolver(R.getCurrentRecord()), R(R) {
1938 setFinal(R.isFinal());
1941 void addShadow(Init *Key) { Shadowed.insert(Key); }
1943 Init *resolve(Init *VarName) override {
1944 if (Shadowed.count(VarName))
1945 return nullptr;
1946 return R.resolve(VarName);
1950 /// (Optionally) delegate resolving to a sub-resolver, and keep track whether
1951 /// there were unresolved references.
1952 class TrackUnresolvedResolver final : public Resolver {
1953 Resolver *R;
1954 bool FoundUnresolved = false;
1956 public:
1957 explicit TrackUnresolvedResolver(Resolver *R = nullptr)
1958 : Resolver(R ? R->getCurrentRecord() : nullptr), R(R) {}
1960 bool foundUnresolved() const { return FoundUnresolved; }
1962 Init *resolve(Init *VarName) override;
1965 /// Do not resolve anything, but keep track of whether a given variable was
1966 /// referenced.
1967 class HasReferenceResolver final : public Resolver {
1968 Init *VarNameToTrack;
1969 bool Found = false;
1971 public:
1972 explicit HasReferenceResolver(Init *VarNameToTrack)
1973 : Resolver(nullptr), VarNameToTrack(VarNameToTrack) {}
1975 bool found() const { return Found; }
1977 Init *resolve(Init *VarName) override;
1980 void EmitJSON(RecordKeeper &RK, raw_ostream &OS);
1982 } // end namespace llvm
1984 #endif // LLVM_TABLEGEN_RECORD_H