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. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_TABLEGEN_RECORD_H 15 #define LLVM_TABLEGEN_RECORD_H 16 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/StringExtras.h" 24 #include "llvm/ADT/StringRef.h" 25 #include "llvm/Support/Casting.h" 26 #include "llvm/Support/ErrorHandling.h" 27 #include "llvm/Support/SMLoc.h" 28 #include "llvm/Support/Timer.h" 29 #include "llvm/Support/TrailingObjects.h" 30 #include "llvm/Support/raw_ostream.h" 31 #include <cassert> 32 #include <cstddef> 33 #include <cstdint> 34 #include <map> 35 #include <memory> 36 #include <optional> 37 #include <string> 38 #include <utility> 39 #include <variant> 40 #include <vector> 41 42 namespace llvm { 43 namespace detail { 44 struct RecordKeeperImpl; 45 } // namespace detail 46 47 class ListRecTy; 48 class Record; 49 class RecordKeeper; 50 class RecordVal; 51 class Resolver; 52 class StringInit; 53 class TypedInit; 54 class TGTimer; 55 56 //===----------------------------------------------------------------------===// 57 // Type Classes 58 //===----------------------------------------------------------------------===// 59 60 class RecTy { 61 public: 62 /// Subclass discriminator (for dyn_cast<> et al.) 63 enum RecTyKind { 64 BitRecTyKind, 65 BitsRecTyKind, 66 IntRecTyKind, 67 StringRecTyKind, 68 ListRecTyKind, 69 DagRecTyKind, 70 RecordRecTyKind 71 }; 72 73 private: 74 RecTyKind Kind; 75 /// The RecordKeeper that uniqued this Type. 76 RecordKeeper &RK; 77 /// ListRecTy of the list that has elements of this type. Its a cache that 78 /// is populated on demand. 79 mutable const ListRecTy *ListTy = nullptr; 80 81 public: 82 RecTy(RecTyKind K, RecordKeeper &RK) : Kind(K), RK(RK) {} 83 virtual ~RecTy() = default; 84 85 RecTyKind getRecTyKind() const { return Kind; } 86 87 /// Return the RecordKeeper that uniqued this Type. 88 RecordKeeper &getRecordKeeper() const { return RK; } 89 90 virtual std::string getAsString() const = 0; 91 void print(raw_ostream &OS) const { OS << getAsString(); } 92 void dump() const; 93 94 /// Return true if all values of 'this' type can be converted to the specified 95 /// type. 96 virtual bool typeIsConvertibleTo(const RecTy *RHS) const; 97 98 /// Return true if 'this' type is equal to or a subtype of RHS. For example, 99 /// a bit set is not an int, but they are convertible. 100 virtual bool typeIsA(const RecTy *RHS) const; 101 102 /// Returns the type representing list<thistype>. 103 const ListRecTy *getListTy() const; 104 }; 105 106 inline raw_ostream &operator<<(raw_ostream &OS, const RecTy &Ty) { 107 Ty.print(OS); 108 return OS; 109 } 110 111 /// 'bit' - Represent a single bit 112 class BitRecTy : public RecTy { 113 friend detail::RecordKeeperImpl; 114 115 BitRecTy(RecordKeeper &RK) : RecTy(BitRecTyKind, RK) {} 116 117 public: 118 static bool classof(const RecTy *RT) { 119 return RT->getRecTyKind() == BitRecTyKind; 120 } 121 122 static const BitRecTy *get(RecordKeeper &RK); 123 124 std::string getAsString() const override { return "bit"; } 125 126 bool typeIsConvertibleTo(const RecTy *RHS) const override; 127 }; 128 129 /// 'bits<n>' - Represent a fixed number of bits 130 class BitsRecTy : public RecTy { 131 unsigned Size; 132 133 explicit BitsRecTy(RecordKeeper &RK, unsigned Sz) 134 : RecTy(BitsRecTyKind, RK), Size(Sz) {} 135 136 public: 137 static bool classof(const RecTy *RT) { 138 return RT->getRecTyKind() == BitsRecTyKind; 139 } 140 141 static const BitsRecTy *get(RecordKeeper &RK, unsigned Sz); 142 143 unsigned getNumBits() const { return Size; } 144 145 std::string getAsString() const override; 146 147 bool typeIsConvertibleTo(const RecTy *RHS) const override; 148 }; 149 150 /// 'int' - Represent an integer value of no particular size 151 class IntRecTy : public RecTy { 152 friend detail::RecordKeeperImpl; 153 154 IntRecTy(RecordKeeper &RK) : RecTy(IntRecTyKind, RK) {} 155 156 public: 157 static bool classof(const RecTy *RT) { 158 return RT->getRecTyKind() == IntRecTyKind; 159 } 160 161 static const IntRecTy *get(RecordKeeper &RK); 162 163 std::string getAsString() const override { return "int"; } 164 165 bool typeIsConvertibleTo(const RecTy *RHS) const override; 166 }; 167 168 /// 'string' - Represent an string value 169 class StringRecTy : public RecTy { 170 friend detail::RecordKeeperImpl; 171 172 StringRecTy(RecordKeeper &RK) : RecTy(StringRecTyKind, RK) {} 173 174 public: 175 static bool classof(const RecTy *RT) { 176 return RT->getRecTyKind() == StringRecTyKind; 177 } 178 179 static const StringRecTy *get(RecordKeeper &RK); 180 181 std::string getAsString() const override; 182 183 bool typeIsConvertibleTo(const RecTy *RHS) const override; 184 }; 185 186 /// 'list<Ty>' - Represent a list of element values, all of which must be of 187 /// the specified type. The type is stored in ElementTy. 188 class ListRecTy : public RecTy { 189 friend const ListRecTy *RecTy::getListTy() const; 190 191 const RecTy *ElementTy; 192 193 explicit ListRecTy(const RecTy *T) 194 : RecTy(ListRecTyKind, T->getRecordKeeper()), ElementTy(T) {} 195 196 public: 197 static bool classof(const RecTy *RT) { 198 return RT->getRecTyKind() == ListRecTyKind; 199 } 200 201 static const ListRecTy *get(const RecTy *T) { return T->getListTy(); } 202 const RecTy *getElementType() const { return ElementTy; } 203 204 std::string getAsString() const override; 205 206 bool typeIsConvertibleTo(const RecTy *RHS) const override; 207 208 bool typeIsA(const RecTy *RHS) const override; 209 }; 210 211 /// 'dag' - Represent a dag fragment 212 class DagRecTy : public RecTy { 213 friend detail::RecordKeeperImpl; 214 215 DagRecTy(RecordKeeper &RK) : RecTy(DagRecTyKind, RK) {} 216 217 public: 218 static bool classof(const RecTy *RT) { 219 return RT->getRecTyKind() == DagRecTyKind; 220 } 221 222 static const DagRecTy *get(RecordKeeper &RK); 223 224 std::string getAsString() const override; 225 }; 226 227 /// '[classname]' - Type of record values that have zero or more superclasses. 228 /// 229 /// The list of superclasses is non-redundant, i.e. only contains classes that 230 /// are not the superclass of some other listed class. 231 class RecordRecTy final : public RecTy, 232 public FoldingSetNode, 233 public TrailingObjects<RecordRecTy, const Record *> { 234 friend class Record; 235 friend detail::RecordKeeperImpl; 236 237 unsigned NumClasses; 238 239 explicit RecordRecTy(RecordKeeper &RK, unsigned Num) 240 : RecTy(RecordRecTyKind, RK), NumClasses(Num) {} 241 242 public: 243 RecordRecTy(const RecordRecTy &) = delete; 244 RecordRecTy &operator=(const RecordRecTy &) = delete; 245 246 // Do not use sized deallocation due to trailing objects. 247 void operator delete(void *p) { ::operator delete(p); } 248 249 static bool classof(const RecTy *RT) { 250 return RT->getRecTyKind() == RecordRecTyKind; 251 } 252 253 /// Get the record type with the given non-redundant list of superclasses. 254 static const RecordRecTy *get(RecordKeeper &RK, 255 ArrayRef<const Record *> Classes); 256 static const RecordRecTy *get(const Record *Class); 257 258 void Profile(FoldingSetNodeID &ID) const; 259 260 ArrayRef<const Record *> getClasses() const { 261 return ArrayRef(getTrailingObjects<const Record *>(), NumClasses); 262 } 263 264 using const_record_iterator = const Record *const *; 265 266 const_record_iterator classes_begin() const { return getClasses().begin(); } 267 const_record_iterator classes_end() const { return getClasses().end(); } 268 269 std::string getAsString() const override; 270 271 bool isSubClassOf(const Record *Class) const; 272 bool typeIsConvertibleTo(const RecTy *RHS) const override; 273 274 bool typeIsA(const RecTy *RHS) const override; 275 }; 276 277 /// Find a common type that T1 and T2 convert to. 278 /// Return 0 if no such type exists. 279 const RecTy *resolveTypes(const RecTy *T1, const RecTy *T2); 280 281 //===----------------------------------------------------------------------===// 282 // Initializer Classes 283 //===----------------------------------------------------------------------===// 284 285 class Init { 286 protected: 287 /// Discriminator enum (for isa<>, dyn_cast<>, et al.) 288 /// 289 /// This enum is laid out by a preorder traversal of the inheritance 290 /// hierarchy, and does not contain an entry for abstract classes, as per 291 /// the recommendation in docs/HowToSetUpLLVMStyleRTTI.rst. 292 /// 293 /// We also explicitly include "first" and "last" values for each 294 /// interior node of the inheritance tree, to make it easier to read the 295 /// corresponding classof(). 296 /// 297 /// We could pack these a bit tighter by not having the IK_FirstXXXInit 298 /// and IK_LastXXXInit be their own values, but that would degrade 299 /// readability for really no benefit. 300 enum InitKind : uint8_t { 301 IK_First, // unused; silence a spurious warning 302 IK_FirstTypedInit, 303 IK_BitInit, 304 IK_BitsInit, 305 IK_DagInit, 306 IK_DefInit, 307 IK_FieldInit, 308 IK_IntInit, 309 IK_ListInit, 310 IK_FirstOpInit, 311 IK_BinOpInit, 312 IK_TernOpInit, 313 IK_UnOpInit, 314 IK_LastOpInit, 315 IK_CondOpInit, 316 IK_FoldOpInit, 317 IK_IsAOpInit, 318 IK_ExistsOpInit, 319 IK_AnonymousNameInit, 320 IK_StringInit, 321 IK_VarInit, 322 IK_VarBitInit, 323 IK_VarDefInit, 324 IK_LastTypedInit, 325 IK_UnsetInit, 326 IK_ArgumentInit, 327 }; 328 329 private: 330 const InitKind Kind; 331 332 protected: 333 uint8_t Opc; // Used by UnOpInit, BinOpInit, and TernOpInit 334 335 private: 336 virtual void anchor(); 337 338 public: 339 /// Get the kind (type) of the value. 340 InitKind getKind() const { return Kind; } 341 342 /// Get the record keeper that initialized this Init. 343 RecordKeeper &getRecordKeeper() const; 344 345 protected: 346 explicit Init(InitKind K, uint8_t Opc = 0) : Kind(K), Opc(Opc) {} 347 348 public: 349 Init(const Init &) = delete; 350 Init &operator=(const Init &) = delete; 351 virtual ~Init() = default; 352 353 /// Is this a complete value with no unset (uninitialized) subvalues? 354 virtual bool isComplete() const { return true; } 355 356 /// Is this a concrete and fully resolved value without any references or 357 /// stuck operations? Unset values are concrete. 358 virtual bool isConcrete() const { return false; } 359 360 /// Print this value. 361 void print(raw_ostream &OS) const { OS << getAsString(); } 362 363 /// Convert this value to a literal form. 364 virtual std::string getAsString() const = 0; 365 366 /// Convert this value to a literal form, 367 /// without adding quotes around a string. 368 virtual std::string getAsUnquotedString() const { return getAsString(); } 369 370 /// Debugging method that may be called through a debugger; just 371 /// invokes print on stderr. 372 void dump() const; 373 374 /// If this value is convertible to type \p Ty, return a value whose 375 /// type is \p Ty, generating a !cast operation if required. 376 /// Otherwise, return null. 377 virtual const Init *getCastTo(const RecTy *Ty) const = 0; 378 379 /// Convert to a value whose type is \p Ty, or return null if this 380 /// is not possible. This can happen if the value's type is convertible 381 /// to \p Ty, but there are unresolved references. 382 virtual const Init *convertInitializerTo(const RecTy *Ty) const = 0; 383 384 /// This function is used to implement the bit range 385 /// selection operator. Given a value, it selects the specified bits, 386 /// returning them as a new \p Init of type \p bits. If it is not legal 387 /// to use the bit selection operator on this value, null is returned. 388 virtual const Init * 389 convertInitializerBitRange(ArrayRef<unsigned> Bits) const { 390 return nullptr; 391 } 392 393 /// This function is used to implement the FieldInit class. 394 /// Implementors of this method should return the type of the named 395 /// field if they are of type record. 396 virtual const RecTy *getFieldType(const StringInit *FieldName) const { 397 return nullptr; 398 } 399 400 /// This function is used by classes that refer to other 401 /// variables which may not be defined at the time the expression is formed. 402 /// If a value is set for the variable later, this method will be called on 403 /// users of the value to allow the value to propagate out. 404 virtual const Init *resolveReferences(Resolver &R) const { return this; } 405 406 /// Get the \p Init value of the specified bit. 407 virtual const Init *getBit(unsigned Bit) const = 0; 408 }; 409 410 inline raw_ostream &operator<<(raw_ostream &OS, const Init &I) { 411 I.print(OS); return OS; 412 } 413 414 /// This is the common superclass of types that have a specific, 415 /// explicit type, stored in ValueTy. 416 class TypedInit : public Init { 417 const RecTy *ValueTy; 418 419 protected: 420 explicit TypedInit(InitKind K, const RecTy *T, uint8_t Opc = 0) 421 : Init(K, Opc), ValueTy(T) {} 422 423 public: 424 TypedInit(const TypedInit &) = delete; 425 TypedInit &operator=(const TypedInit &) = delete; 426 427 static bool classof(const Init *I) { 428 return I->getKind() >= IK_FirstTypedInit && 429 I->getKind() <= IK_LastTypedInit; 430 } 431 432 /// Get the type of the Init as a RecTy. 433 const RecTy *getType() const { return ValueTy; } 434 435 /// Get the record keeper that initialized this Init. 436 RecordKeeper &getRecordKeeper() const { return ValueTy->getRecordKeeper(); } 437 438 const Init *getCastTo(const RecTy *Ty) const override; 439 const Init *convertInitializerTo(const RecTy *Ty) const override; 440 441 const Init * 442 convertInitializerBitRange(ArrayRef<unsigned> Bits) const override; 443 444 /// This method is used to implement the FieldInit class. 445 /// Implementors of this method should return the type of the named field if 446 /// they are of type record. 447 const RecTy *getFieldType(const StringInit *FieldName) const override; 448 }; 449 450 /// '?' - Represents an uninitialized value. 451 class UnsetInit final : public Init { 452 friend detail::RecordKeeperImpl; 453 454 /// The record keeper that initialized this Init. 455 RecordKeeper &RK; 456 457 UnsetInit(RecordKeeper &RK) : Init(IK_UnsetInit), RK(RK) {} 458 459 public: 460 UnsetInit(const UnsetInit &) = delete; 461 UnsetInit &operator=(const UnsetInit &) = delete; 462 463 static bool classof(const Init *I) { 464 return I->getKind() == IK_UnsetInit; 465 } 466 467 /// Get the singleton unset Init. 468 static UnsetInit *get(RecordKeeper &RK); 469 470 /// Get the record keeper that initialized this Init. 471 RecordKeeper &getRecordKeeper() const { return RK; } 472 473 const Init *getCastTo(const RecTy *Ty) const override; 474 const Init *convertInitializerTo(const RecTy *Ty) const override; 475 476 const Init *getBit(unsigned Bit) const override { return this; } 477 478 /// Is this a complete value with no unset (uninitialized) subvalues? 479 bool isComplete() const override { return false; } 480 481 bool isConcrete() const override { return true; } 482 483 /// Get the string representation of the Init. 484 std::string getAsString() const override { return "?"; } 485 }; 486 487 // Represent an argument. 488 using ArgAuxType = std::variant<unsigned, const Init *>; 489 class ArgumentInit final : public Init, public FoldingSetNode { 490 public: 491 enum Kind { 492 Positional, 493 Named, 494 }; 495 496 private: 497 const Init *Value; 498 ArgAuxType Aux; 499 500 protected: 501 explicit ArgumentInit(const Init *Value, ArgAuxType Aux) 502 : Init(IK_ArgumentInit), Value(Value), Aux(Aux) {} 503 504 public: 505 ArgumentInit(const ArgumentInit &) = delete; 506 ArgumentInit &operator=(const ArgumentInit &) = delete; 507 508 static bool classof(const Init *I) { return I->getKind() == IK_ArgumentInit; } 509 510 RecordKeeper &getRecordKeeper() const { return Value->getRecordKeeper(); } 511 512 static const ArgumentInit *get(const Init *Value, ArgAuxType Aux); 513 514 bool isPositional() const { return Aux.index() == Positional; } 515 bool isNamed() const { return Aux.index() == Named; } 516 517 const Init *getValue() const { return Value; } 518 unsigned getIndex() const { 519 assert(isPositional() && "Should be positional!"); 520 return std::get<Positional>(Aux); 521 } 522 const Init *getName() const { 523 assert(isNamed() && "Should be named!"); 524 return std::get<Named>(Aux); 525 } 526 const ArgumentInit *cloneWithValue(const Init *Value) const { 527 return get(Value, Aux); 528 } 529 530 void Profile(FoldingSetNodeID &ID) const; 531 532 const Init *resolveReferences(Resolver &R) const override; 533 std::string getAsString() const override { 534 if (isPositional()) 535 return utostr(getIndex()) + ": " + Value->getAsString(); 536 if (isNamed()) 537 return getName()->getAsString() + ": " + Value->getAsString(); 538 llvm_unreachable("Unsupported argument type!"); 539 return ""; 540 } 541 542 bool isComplete() const override { return false; } 543 bool isConcrete() const override { return false; } 544 const Init *getBit(unsigned Bit) const override { return Value->getBit(Bit); } 545 const Init *getCastTo(const RecTy *Ty) const override { 546 return Value->getCastTo(Ty); 547 } 548 const Init *convertInitializerTo(const RecTy *Ty) const override { 549 return Value->convertInitializerTo(Ty); 550 } 551 }; 552 553 /// 'true'/'false' - Represent a concrete initializer for a bit. 554 class BitInit final : public TypedInit { 555 friend detail::RecordKeeperImpl; 556 557 bool Value; 558 559 explicit BitInit(bool V, const RecTy *T) 560 : TypedInit(IK_BitInit, T), Value(V) {} 561 562 public: 563 BitInit(const BitInit &) = delete; 564 BitInit &operator=(BitInit &) = delete; 565 566 static bool classof(const Init *I) { 567 return I->getKind() == IK_BitInit; 568 } 569 570 static BitInit *get(RecordKeeper &RK, bool V); 571 572 bool getValue() const { return Value; } 573 574 const Init *convertInitializerTo(const RecTy *Ty) const override; 575 576 const Init *getBit(unsigned Bit) const override { 577 assert(Bit < 1 && "Bit index out of range!"); 578 return this; 579 } 580 581 bool isConcrete() const override { return true; } 582 std::string getAsString() const override { return Value ? "1" : "0"; } 583 }; 584 585 /// '{ a, b, c }' - Represents an initializer for a BitsRecTy value. 586 /// It contains a vector of bits, whose size is determined by the type. 587 class BitsInit final : public TypedInit, 588 public FoldingSetNode, 589 public TrailingObjects<BitsInit, const Init *> { 590 unsigned NumBits; 591 592 BitsInit(RecordKeeper &RK, unsigned N) 593 : TypedInit(IK_BitsInit, BitsRecTy::get(RK, N)), NumBits(N) {} 594 595 public: 596 BitsInit(const BitsInit &) = delete; 597 BitsInit &operator=(const BitsInit &) = delete; 598 599 // Do not use sized deallocation due to trailing objects. 600 void operator delete(void *p) { ::operator delete(p); } 601 602 static bool classof(const Init *I) { 603 return I->getKind() == IK_BitsInit; 604 } 605 606 static BitsInit *get(RecordKeeper &RK, ArrayRef<const Init *> Range); 607 608 void Profile(FoldingSetNodeID &ID) const; 609 610 unsigned getNumBits() const { return NumBits; } 611 612 const Init *convertInitializerTo(const RecTy *Ty) const override; 613 const Init * 614 convertInitializerBitRange(ArrayRef<unsigned> Bits) const override; 615 std::optional<int64_t> convertInitializerToInt() const; 616 617 bool isComplete() const override { 618 for (unsigned i = 0; i != getNumBits(); ++i) 619 if (!getBit(i)->isComplete()) return false; 620 return true; 621 } 622 623 bool allInComplete() const { 624 for (unsigned i = 0; i != getNumBits(); ++i) 625 if (getBit(i)->isComplete()) return false; 626 return true; 627 } 628 629 bool isConcrete() const override; 630 std::string getAsString() const override; 631 632 const Init *resolveReferences(Resolver &R) const override; 633 634 const Init *getBit(unsigned Bit) const override { 635 assert(Bit < NumBits && "Bit index out of range!"); 636 return getTrailingObjects<const Init *>()[Bit]; 637 } 638 }; 639 640 /// '7' - Represent an initialization by a literal integer value. 641 class IntInit final : public TypedInit { 642 int64_t Value; 643 644 explicit IntInit(RecordKeeper &RK, int64_t V) 645 : TypedInit(IK_IntInit, IntRecTy::get(RK)), Value(V) {} 646 647 public: 648 IntInit(const IntInit &) = delete; 649 IntInit &operator=(const IntInit &) = delete; 650 651 static bool classof(const Init *I) { 652 return I->getKind() == IK_IntInit; 653 } 654 655 static IntInit *get(RecordKeeper &RK, int64_t V); 656 657 int64_t getValue() const { return Value; } 658 659 const Init *convertInitializerTo(const RecTy *Ty) const override; 660 const Init * 661 convertInitializerBitRange(ArrayRef<unsigned> Bits) const override; 662 663 bool isConcrete() const override { return true; } 664 std::string getAsString() const override; 665 666 const Init *getBit(unsigned Bit) const override { 667 return BitInit::get(getRecordKeeper(), (Value & (1ULL << Bit)) != 0); 668 } 669 }; 670 671 /// "anonymous_n" - Represent an anonymous record name 672 class AnonymousNameInit final : public TypedInit { 673 unsigned Value; 674 675 explicit AnonymousNameInit(RecordKeeper &RK, unsigned V) 676 : TypedInit(IK_AnonymousNameInit, StringRecTy::get(RK)), Value(V) {} 677 678 public: 679 AnonymousNameInit(const AnonymousNameInit &) = delete; 680 AnonymousNameInit &operator=(const AnonymousNameInit &) = delete; 681 682 static bool classof(const Init *I) { 683 return I->getKind() == IK_AnonymousNameInit; 684 } 685 686 static AnonymousNameInit *get(RecordKeeper &RK, unsigned); 687 688 unsigned getValue() const { return Value; } 689 690 const StringInit *getNameInit() const; 691 692 std::string getAsString() const override; 693 694 const Init *resolveReferences(Resolver &R) const override; 695 696 const Init *getBit(unsigned Bit) const override { 697 llvm_unreachable("Illegal bit reference off string"); 698 } 699 }; 700 701 /// "foo" - Represent an initialization by a string value. 702 class StringInit final : public TypedInit { 703 public: 704 enum StringFormat { 705 SF_String, // Format as "text" 706 SF_Code, // Format as [{text}] 707 }; 708 709 private: 710 StringRef Value; 711 StringFormat Format; 712 713 explicit StringInit(RecordKeeper &RK, StringRef V, StringFormat Fmt) 714 : TypedInit(IK_StringInit, StringRecTy::get(RK)), Value(V), Format(Fmt) {} 715 716 public: 717 StringInit(const StringInit &) = delete; 718 StringInit &operator=(const StringInit &) = delete; 719 720 static bool classof(const Init *I) { 721 return I->getKind() == IK_StringInit; 722 } 723 724 static const StringInit *get(RecordKeeper &RK, StringRef, 725 StringFormat Fmt = SF_String); 726 727 static StringFormat determineFormat(StringFormat Fmt1, StringFormat Fmt2) { 728 return (Fmt1 == SF_Code || Fmt2 == SF_Code) ? SF_Code : SF_String; 729 } 730 731 StringRef getValue() const { return Value; } 732 StringFormat getFormat() const { return Format; } 733 bool hasCodeFormat() const { return Format == SF_Code; } 734 735 const Init *convertInitializerTo(const RecTy *Ty) const override; 736 737 bool isConcrete() const override { return true; } 738 739 std::string getAsString() const override { 740 if (Format == SF_String) 741 return "\"" + Value.str() + "\""; 742 else 743 return "[{" + Value.str() + "}]"; 744 } 745 746 std::string getAsUnquotedString() const override { 747 return std::string(Value); 748 } 749 750 const Init *getBit(unsigned Bit) const override { 751 llvm_unreachable("Illegal bit reference off string"); 752 } 753 }; 754 755 /// [AL, AH, CL] - Represent a list of defs 756 /// 757 class ListInit final : public TypedInit, 758 public FoldingSetNode, 759 public TrailingObjects<ListInit, const Init *> { 760 unsigned NumValues; 761 762 public: 763 using const_iterator = const Init *const *; 764 765 private: 766 explicit ListInit(unsigned N, const RecTy *EltTy) 767 : TypedInit(IK_ListInit, ListRecTy::get(EltTy)), NumValues(N) {} 768 769 public: 770 ListInit(const ListInit &) = delete; 771 ListInit &operator=(const ListInit &) = delete; 772 773 // Do not use sized deallocation due to trailing objects. 774 void operator delete(void *p) { ::operator delete(p); } 775 776 static bool classof(const Init *I) { 777 return I->getKind() == IK_ListInit; 778 } 779 static const ListInit *get(ArrayRef<const Init *> Range, const RecTy *EltTy); 780 781 void Profile(FoldingSetNodeID &ID) const; 782 783 const Init *getElement(unsigned i) const { 784 assert(i < NumValues && "List element index out of range!"); 785 return getTrailingObjects<const Init *>()[i]; 786 } 787 const RecTy *getElementType() const { 788 return cast<ListRecTy>(getType())->getElementType(); 789 } 790 791 const Record *getElementAsRecord(unsigned i) const; 792 793 const Init *convertInitializerTo(const RecTy *Ty) const override; 794 795 /// This method is used by classes that refer to other 796 /// variables which may not be defined at the time they expression is formed. 797 /// If a value is set for the variable later, this method will be called on 798 /// users of the value to allow the value to propagate out. 799 /// 800 const Init *resolveReferences(Resolver &R) const override; 801 802 bool isComplete() const override; 803 bool isConcrete() const override; 804 std::string getAsString() const override; 805 806 ArrayRef<const Init *> getValues() const { 807 return ArrayRef(getTrailingObjects<const Init *>(), NumValues); 808 } 809 810 const_iterator begin() const { return getTrailingObjects<const Init *>(); } 811 const_iterator end () const { return begin() + NumValues; } 812 813 size_t size () const { return NumValues; } 814 bool empty() const { return NumValues == 0; } 815 816 const Init *getBit(unsigned Bit) const override { 817 llvm_unreachable("Illegal bit reference off list"); 818 } 819 }; 820 821 /// Base class for operators 822 /// 823 class OpInit : public TypedInit { 824 protected: 825 explicit OpInit(InitKind K, const RecTy *Type, uint8_t Opc) 826 : TypedInit(K, Type, Opc) {} 827 828 public: 829 OpInit(const OpInit &) = delete; 830 OpInit &operator=(OpInit &) = delete; 831 832 static bool classof(const Init *I) { 833 return I->getKind() >= IK_FirstOpInit && 834 I->getKind() <= IK_LastOpInit; 835 } 836 837 const Init *getBit(unsigned Bit) const final; 838 }; 839 840 /// !op (X) - Transform an init. 841 /// 842 class UnOpInit final : public OpInit, public FoldingSetNode { 843 public: 844 enum UnaryOp : uint8_t { 845 TOLOWER, 846 TOUPPER, 847 CAST, 848 NOT, 849 HEAD, 850 TAIL, 851 SIZE, 852 EMPTY, 853 GETDAGOP, 854 LOG2, 855 REPR, 856 LISTFLATTEN, 857 INITIALIZED, 858 }; 859 860 private: 861 const Init *LHS; 862 863 UnOpInit(UnaryOp opc, const Init *lhs, const RecTy *Type) 864 : OpInit(IK_UnOpInit, Type, opc), LHS(lhs) {} 865 866 public: 867 UnOpInit(const UnOpInit &) = delete; 868 UnOpInit &operator=(const UnOpInit &) = delete; 869 870 static bool classof(const Init *I) { 871 return I->getKind() == IK_UnOpInit; 872 } 873 874 static const UnOpInit *get(UnaryOp opc, const Init *lhs, const RecTy *Type); 875 876 void Profile(FoldingSetNodeID &ID) const; 877 878 UnaryOp getOpcode() const { return (UnaryOp)Opc; } 879 const Init *getOperand() const { return LHS; } 880 881 // Fold - If possible, fold this to a simpler init. Return this if not 882 // possible to fold. 883 const Init *Fold(const Record *CurRec, bool IsFinal = false) const; 884 885 const Init *resolveReferences(Resolver &R) const override; 886 887 std::string getAsString() const override; 888 }; 889 890 /// !op (X, Y) - Combine two inits. 891 class BinOpInit final : public OpInit, public FoldingSetNode { 892 public: 893 enum BinaryOp : uint8_t { 894 ADD, 895 SUB, 896 MUL, 897 DIV, 898 AND, 899 OR, 900 XOR, 901 SHL, 902 SRA, 903 SRL, 904 LISTCONCAT, 905 LISTSPLAT, 906 LISTREMOVE, 907 LISTELEM, 908 LISTSLICE, 909 RANGEC, 910 STRCONCAT, 911 INTERLEAVE, 912 CONCAT, 913 EQ, 914 NE, 915 LE, 916 LT, 917 GE, 918 GT, 919 GETDAGARG, 920 GETDAGNAME, 921 SETDAGOP, 922 }; 923 924 private: 925 const Init *LHS, *RHS; 926 927 BinOpInit(BinaryOp opc, const Init *lhs, const Init *rhs, const RecTy *Type) 928 : OpInit(IK_BinOpInit, Type, opc), LHS(lhs), RHS(rhs) {} 929 930 public: 931 BinOpInit(const BinOpInit &) = delete; 932 BinOpInit &operator=(const BinOpInit &) = delete; 933 934 static bool classof(const Init *I) { 935 return I->getKind() == IK_BinOpInit; 936 } 937 938 static const BinOpInit *get(BinaryOp opc, const Init *lhs, const Init *rhs, 939 const RecTy *Type); 940 static const Init *getStrConcat(const Init *lhs, const Init *rhs); 941 static const Init *getListConcat(const TypedInit *lhs, const Init *rhs); 942 943 void Profile(FoldingSetNodeID &ID) const; 944 945 BinaryOp getOpcode() const { return (BinaryOp)Opc; } 946 const Init *getLHS() const { return LHS; } 947 const Init *getRHS() const { return RHS; } 948 949 std::optional<bool> CompareInit(unsigned Opc, const Init *LHS, 950 const Init *RHS) const; 951 952 // Fold - If possible, fold this to a simpler init. Return this if not 953 // possible to fold. 954 const Init *Fold(const Record *CurRec) const; 955 956 const Init *resolveReferences(Resolver &R) const override; 957 958 std::string getAsString() const override; 959 }; 960 961 /// !op (X, Y, Z) - Combine two inits. 962 class TernOpInit final : public OpInit, public FoldingSetNode { 963 public: 964 enum TernaryOp : uint8_t { 965 SUBST, 966 FOREACH, 967 FILTER, 968 IF, 969 DAG, 970 RANGE, 971 SUBSTR, 972 FIND, 973 SETDAGARG, 974 SETDAGNAME, 975 }; 976 977 private: 978 const Init *LHS, *MHS, *RHS; 979 980 TernOpInit(TernaryOp opc, const Init *lhs, const Init *mhs, const Init *rhs, 981 const RecTy *Type) 982 : OpInit(IK_TernOpInit, Type, opc), LHS(lhs), MHS(mhs), RHS(rhs) {} 983 984 public: 985 TernOpInit(const TernOpInit &) = delete; 986 TernOpInit &operator=(const TernOpInit &) = delete; 987 988 static bool classof(const Init *I) { 989 return I->getKind() == IK_TernOpInit; 990 } 991 992 static const TernOpInit *get(TernaryOp opc, const Init *lhs, const Init *mhs, 993 const Init *rhs, const RecTy *Type); 994 995 void Profile(FoldingSetNodeID &ID) const; 996 997 TernaryOp getOpcode() const { return (TernaryOp)Opc; } 998 const Init *getLHS() const { return LHS; } 999 const Init *getMHS() const { return MHS; } 1000 const Init *getRHS() const { return RHS; } 1001 1002 // Fold - If possible, fold this to a simpler init. Return this if not 1003 // possible to fold. 1004 const Init *Fold(const Record *CurRec) const; 1005 1006 bool isComplete() const override { 1007 return LHS->isComplete() && MHS->isComplete() && RHS->isComplete(); 1008 } 1009 1010 const Init *resolveReferences(Resolver &R) const override; 1011 1012 std::string getAsString() const override; 1013 }; 1014 1015 /// !cond(condition_1: value1, ... , condition_n: value) 1016 /// Selects the first value for which condition is true. 1017 /// Otherwise reports an error. 1018 class CondOpInit final : public TypedInit, 1019 public FoldingSetNode, 1020 public TrailingObjects<CondOpInit, const Init *> { 1021 unsigned NumConds; 1022 const RecTy *ValType; 1023 1024 CondOpInit(unsigned NC, const RecTy *Type) 1025 : TypedInit(IK_CondOpInit, Type), NumConds(NC), ValType(Type) {} 1026 1027 size_t numTrailingObjects(OverloadToken<Init *>) const { 1028 return 2*NumConds; 1029 } 1030 1031 public: 1032 CondOpInit(const CondOpInit &) = delete; 1033 CondOpInit &operator=(const CondOpInit &) = delete; 1034 1035 static bool classof(const Init *I) { 1036 return I->getKind() == IK_CondOpInit; 1037 } 1038 1039 static const CondOpInit *get(ArrayRef<const Init *> C, 1040 ArrayRef<const Init *> V, const RecTy *Type); 1041 1042 void Profile(FoldingSetNodeID &ID) const; 1043 1044 const RecTy *getValType() const { return ValType; } 1045 1046 unsigned getNumConds() const { return NumConds; } 1047 1048 const Init *getCond(unsigned Num) const { 1049 assert(Num < NumConds && "Condition number out of range!"); 1050 return getTrailingObjects<const Init *>()[Num]; 1051 } 1052 1053 const Init *getVal(unsigned Num) const { 1054 assert(Num < NumConds && "Val number out of range!"); 1055 return getTrailingObjects<const Init *>()[Num + NumConds]; 1056 } 1057 1058 ArrayRef<const Init *> getConds() const { 1059 return ArrayRef(getTrailingObjects<const Init *>(), NumConds); 1060 } 1061 1062 ArrayRef<const Init *> getVals() const { 1063 return ArrayRef(getTrailingObjects<const Init *>() + NumConds, NumConds); 1064 } 1065 1066 const Init *Fold(const Record *CurRec) const; 1067 1068 const Init *resolveReferences(Resolver &R) const override; 1069 1070 bool isConcrete() const override; 1071 bool isComplete() const override; 1072 std::string getAsString() const override; 1073 1074 using const_case_iterator = SmallVectorImpl<const Init *>::const_iterator; 1075 using const_val_iterator = SmallVectorImpl<const Init *>::const_iterator; 1076 1077 inline const_case_iterator arg_begin() const { return getConds().begin(); } 1078 inline const_case_iterator arg_end () const { return getConds().end(); } 1079 1080 inline size_t case_size () const { return NumConds; } 1081 inline bool case_empty() const { return NumConds == 0; } 1082 1083 inline const_val_iterator name_begin() const { return getVals().begin();} 1084 inline const_val_iterator name_end () const { return getVals().end(); } 1085 1086 inline size_t val_size () const { return NumConds; } 1087 inline bool val_empty() const { return NumConds == 0; } 1088 1089 const Init *getBit(unsigned Bit) const override; 1090 }; 1091 1092 /// !foldl (a, b, expr, start, lst) - Fold over a list. 1093 class FoldOpInit final : public TypedInit, public FoldingSetNode { 1094 private: 1095 const Init *Start, *List, *A, *B, *Expr; 1096 1097 FoldOpInit(const Init *Start, const Init *List, const Init *A, const Init *B, 1098 const Init *Expr, const RecTy *Type) 1099 : TypedInit(IK_FoldOpInit, Type), Start(Start), List(List), A(A), B(B), 1100 Expr(Expr) {} 1101 1102 public: 1103 FoldOpInit(const FoldOpInit &) = delete; 1104 FoldOpInit &operator=(const FoldOpInit &) = delete; 1105 1106 static bool classof(const Init *I) { return I->getKind() == IK_FoldOpInit; } 1107 1108 static const FoldOpInit *get(const Init *Start, const Init *List, 1109 const Init *A, const Init *B, const Init *Expr, 1110 const RecTy *Type); 1111 1112 void Profile(FoldingSetNodeID &ID) const; 1113 1114 // Fold - If possible, fold this to a simpler init. Return this if not 1115 // possible to fold. 1116 const Init *Fold(const Record *CurRec) const; 1117 1118 bool isComplete() const override { return false; } 1119 1120 const Init *resolveReferences(Resolver &R) const override; 1121 1122 const Init *getBit(unsigned Bit) const override; 1123 1124 std::string getAsString() const override; 1125 }; 1126 1127 /// !isa<type>(expr) - Dynamically determine the type of an expression. 1128 class IsAOpInit final : public TypedInit, public FoldingSetNode { 1129 private: 1130 const RecTy *CheckType; 1131 const Init *Expr; 1132 1133 IsAOpInit(const RecTy *CheckType, const Init *Expr) 1134 : TypedInit(IK_IsAOpInit, IntRecTy::get(CheckType->getRecordKeeper())), 1135 CheckType(CheckType), Expr(Expr) {} 1136 1137 public: 1138 IsAOpInit(const IsAOpInit &) = delete; 1139 IsAOpInit &operator=(const IsAOpInit &) = delete; 1140 1141 static bool classof(const Init *I) { return I->getKind() == IK_IsAOpInit; } 1142 1143 static const IsAOpInit *get(const RecTy *CheckType, const Init *Expr); 1144 1145 void Profile(FoldingSetNodeID &ID) const; 1146 1147 // Fold - If possible, fold this to a simpler init. Return this if not 1148 // possible to fold. 1149 const Init *Fold() const; 1150 1151 bool isComplete() const override { return false; } 1152 1153 const Init *resolveReferences(Resolver &R) const override; 1154 1155 const Init *getBit(unsigned Bit) const override; 1156 1157 std::string getAsString() const override; 1158 }; 1159 1160 /// !exists<type>(expr) - Dynamically determine if a record of `type` named 1161 /// `expr` exists. 1162 class ExistsOpInit final : public TypedInit, public FoldingSetNode { 1163 private: 1164 const RecTy *CheckType; 1165 const Init *Expr; 1166 1167 ExistsOpInit(const RecTy *CheckType, const Init *Expr) 1168 : TypedInit(IK_ExistsOpInit, IntRecTy::get(CheckType->getRecordKeeper())), 1169 CheckType(CheckType), Expr(Expr) {} 1170 1171 public: 1172 ExistsOpInit(const ExistsOpInit &) = delete; 1173 ExistsOpInit &operator=(const ExistsOpInit &) = delete; 1174 1175 static bool classof(const Init *I) { return I->getKind() == IK_ExistsOpInit; } 1176 1177 static const ExistsOpInit *get(const RecTy *CheckType, const Init *Expr); 1178 1179 void Profile(FoldingSetNodeID &ID) const; 1180 1181 // Fold - If possible, fold this to a simpler init. Return this if not 1182 // possible to fold. 1183 const Init *Fold(const Record *CurRec, bool IsFinal = false) const; 1184 1185 bool isComplete() const override { return false; } 1186 1187 const Init *resolveReferences(Resolver &R) const override; 1188 1189 const Init *getBit(unsigned Bit) const override; 1190 1191 std::string getAsString() const override; 1192 }; 1193 1194 /// 'Opcode' - Represent a reference to an entire variable object. 1195 class VarInit final : public TypedInit { 1196 const Init *VarName; 1197 1198 explicit VarInit(const Init *VN, const RecTy *T) 1199 : TypedInit(IK_VarInit, T), VarName(VN) {} 1200 1201 public: 1202 VarInit(const VarInit &) = delete; 1203 VarInit &operator=(const VarInit &) = delete; 1204 1205 static bool classof(const Init *I) { 1206 return I->getKind() == IK_VarInit; 1207 } 1208 1209 static const VarInit *get(StringRef VN, const RecTy *T); 1210 static const VarInit *get(const Init *VN, const RecTy *T); 1211 1212 StringRef getName() const; 1213 const Init *getNameInit() const { return VarName; } 1214 1215 std::string getNameInitAsString() const { 1216 return getNameInit()->getAsUnquotedString(); 1217 } 1218 1219 /// This method is used by classes that refer to other 1220 /// variables which may not be defined at the time they expression is formed. 1221 /// If a value is set for the variable later, this method will be called on 1222 /// users of the value to allow the value to propagate out. 1223 /// 1224 const Init *resolveReferences(Resolver &R) const override; 1225 1226 const Init *getBit(unsigned Bit) const override; 1227 1228 std::string getAsString() const override { return std::string(getName()); } 1229 }; 1230 1231 /// Opcode{0} - Represent access to one bit of a variable or field. 1232 class VarBitInit final : public TypedInit { 1233 const TypedInit *TI; 1234 unsigned Bit; 1235 1236 VarBitInit(const TypedInit *T, unsigned B) 1237 : TypedInit(IK_VarBitInit, BitRecTy::get(T->getRecordKeeper())), TI(T), 1238 Bit(B) { 1239 assert(T->getType() && 1240 (isa<IntRecTy>(T->getType()) || 1241 (isa<BitsRecTy>(T->getType()) && 1242 cast<BitsRecTy>(T->getType())->getNumBits() > B)) && 1243 "Illegal VarBitInit expression!"); 1244 } 1245 1246 public: 1247 VarBitInit(const VarBitInit &) = delete; 1248 VarBitInit &operator=(const VarBitInit &) = delete; 1249 1250 static bool classof(const Init *I) { 1251 return I->getKind() == IK_VarBitInit; 1252 } 1253 1254 static const VarBitInit *get(const TypedInit *T, unsigned B); 1255 1256 const Init *getBitVar() const { return TI; } 1257 unsigned getBitNum() const { return Bit; } 1258 1259 std::string getAsString() const override; 1260 const Init *resolveReferences(Resolver &R) const override; 1261 1262 const Init *getBit(unsigned B) const override { 1263 assert(B < 1 && "Bit index out of range!"); 1264 return this; 1265 } 1266 }; 1267 1268 /// AL - Represent a reference to a 'def' in the description 1269 class DefInit final : public TypedInit { 1270 friend class Record; 1271 1272 const Record *Def; 1273 1274 explicit DefInit(const Record *D); 1275 1276 public: 1277 DefInit(const DefInit &) = delete; 1278 DefInit &operator=(const DefInit &) = delete; 1279 1280 static bool classof(const Init *I) { 1281 return I->getKind() == IK_DefInit; 1282 } 1283 1284 const Init *convertInitializerTo(const RecTy *Ty) const override; 1285 1286 const Record *getDef() const { return Def; } 1287 1288 const RecTy *getFieldType(const StringInit *FieldName) const override; 1289 1290 bool isConcrete() const override { return true; } 1291 std::string getAsString() const override; 1292 1293 const Init *getBit(unsigned Bit) const override { 1294 llvm_unreachable("Illegal bit reference off def"); 1295 } 1296 }; 1297 1298 /// classname<targs...> - Represent an uninstantiated anonymous class 1299 /// instantiation. 1300 class VarDefInit final 1301 : public TypedInit, 1302 public FoldingSetNode, 1303 public TrailingObjects<VarDefInit, const ArgumentInit *> { 1304 SMLoc Loc; 1305 const Record *Class; 1306 const DefInit *Def = nullptr; // after instantiation 1307 unsigned NumArgs; 1308 1309 explicit VarDefInit(SMLoc Loc, const Record *Class, unsigned N); 1310 1311 const DefInit *instantiate(); 1312 1313 public: 1314 VarDefInit(const VarDefInit &) = delete; 1315 VarDefInit &operator=(const VarDefInit &) = delete; 1316 1317 // Do not use sized deallocation due to trailing objects. 1318 void operator delete(void *p) { ::operator delete(p); } 1319 1320 static bool classof(const Init *I) { 1321 return I->getKind() == IK_VarDefInit; 1322 } 1323 static const VarDefInit *get(SMLoc Loc, const Record *Class, 1324 ArrayRef<const ArgumentInit *> Args); 1325 1326 void Profile(FoldingSetNodeID &ID) const; 1327 1328 const Init *resolveReferences(Resolver &R) const override; 1329 const Init *Fold() const; 1330 1331 std::string getAsString() const override; 1332 1333 const ArgumentInit *getArg(unsigned i) const { 1334 assert(i < NumArgs && "Argument index out of range!"); 1335 return getTrailingObjects<const ArgumentInit *>()[i]; 1336 } 1337 1338 using const_iterator = const ArgumentInit *const *; 1339 1340 const_iterator args_begin() const { 1341 return getTrailingObjects<const ArgumentInit *>(); 1342 } 1343 const_iterator args_end () const { return args_begin() + NumArgs; } 1344 1345 size_t args_size () const { return NumArgs; } 1346 bool args_empty() const { return NumArgs == 0; } 1347 1348 ArrayRef<const ArgumentInit *> args() const { 1349 return ArrayRef(args_begin(), NumArgs); 1350 } 1351 1352 const Init *getBit(unsigned Bit) const override { 1353 llvm_unreachable("Illegal bit reference off anonymous def"); 1354 } 1355 }; 1356 1357 /// X.Y - Represent a reference to a subfield of a variable 1358 class FieldInit final : public TypedInit { 1359 const Init *Rec; // Record we are referring to 1360 const StringInit *FieldName; // Field we are accessing 1361 1362 FieldInit(const Init *R, const StringInit *FN) 1363 : TypedInit(IK_FieldInit, R->getFieldType(FN)), Rec(R), FieldName(FN) { 1364 #ifndef NDEBUG 1365 if (!getType()) { 1366 llvm::errs() << "In Record = " << Rec->getAsString() 1367 << ", got FieldName = " << *FieldName 1368 << " with non-record type!\n"; 1369 llvm_unreachable("FieldInit with non-record type!"); 1370 } 1371 #endif 1372 } 1373 1374 public: 1375 FieldInit(const FieldInit &) = delete; 1376 FieldInit &operator=(const FieldInit &) = delete; 1377 1378 static bool classof(const Init *I) { 1379 return I->getKind() == IK_FieldInit; 1380 } 1381 1382 static const FieldInit *get(const Init *R, const StringInit *FN); 1383 1384 const Init *getRecord() const { return Rec; } 1385 const StringInit *getFieldName() const { return FieldName; } 1386 1387 const Init *getBit(unsigned Bit) const override; 1388 1389 const Init *resolveReferences(Resolver &R) const override; 1390 const Init *Fold(const Record *CurRec) const; 1391 1392 bool isConcrete() const override; 1393 std::string getAsString() const override { 1394 return Rec->getAsString() + "." + FieldName->getValue().str(); 1395 } 1396 }; 1397 1398 /// (v a, b) - Represent a DAG tree value. DAG inits are required 1399 /// to have at least one value then a (possibly empty) list of arguments. Each 1400 /// argument can have a name associated with it. 1401 class DagInit final 1402 : public TypedInit, 1403 public FoldingSetNode, 1404 public TrailingObjects<DagInit, const Init *, const StringInit *> { 1405 friend TrailingObjects; 1406 1407 const Init *Val; 1408 const StringInit *ValName; 1409 unsigned NumArgs; 1410 unsigned NumArgNames; 1411 1412 DagInit(const Init *V, const StringInit *VN, unsigned NumArgs, 1413 unsigned NumArgNames) 1414 : TypedInit(IK_DagInit, DagRecTy::get(V->getRecordKeeper())), Val(V), 1415 ValName(VN), NumArgs(NumArgs), NumArgNames(NumArgNames) {} 1416 1417 size_t numTrailingObjects(OverloadToken<const Init *>) const { 1418 return NumArgs; 1419 } 1420 1421 public: 1422 DagInit(const DagInit &) = delete; 1423 DagInit &operator=(const DagInit &) = delete; 1424 1425 static bool classof(const Init *I) { 1426 return I->getKind() == IK_DagInit; 1427 } 1428 1429 static const DagInit *get(const Init *V, const StringInit *VN, 1430 ArrayRef<const Init *> ArgRange, 1431 ArrayRef<const StringInit *> NameRange); 1432 static const DagInit * 1433 get(const Init *V, const StringInit *VN, 1434 ArrayRef<std::pair<const Init *, const StringInit *>> Args); 1435 1436 void Profile(FoldingSetNodeID &ID) const; 1437 1438 const Init *getOperator() const { return Val; } 1439 const Record *getOperatorAsDef(ArrayRef<SMLoc> Loc) const; 1440 1441 const StringInit *getName() const { return ValName; } 1442 1443 StringRef getNameStr() const { 1444 return ValName ? ValName->getValue() : StringRef(); 1445 } 1446 1447 unsigned getNumArgs() const { return NumArgs; } 1448 1449 const Init *getArg(unsigned Num) const { 1450 assert(Num < NumArgs && "Arg number out of range!"); 1451 return getTrailingObjects<const Init *>()[Num]; 1452 } 1453 1454 /// This method looks up the specified argument name and returns its argument 1455 /// number or std::nullopt if that argument name does not exist. 1456 std::optional<unsigned> getArgNo(StringRef Name) const; 1457 1458 const StringInit *getArgName(unsigned Num) const { 1459 assert(Num < NumArgNames && "Arg number out of range!"); 1460 return getTrailingObjects<const StringInit *>()[Num]; 1461 } 1462 1463 StringRef getArgNameStr(unsigned Num) const { 1464 const StringInit *Init = getArgName(Num); 1465 return Init ? Init->getValue() : StringRef(); 1466 } 1467 1468 ArrayRef<const Init *> getArgs() const { 1469 return ArrayRef(getTrailingObjects<const Init *>(), NumArgs); 1470 } 1471 1472 ArrayRef<const StringInit *> getArgNames() const { 1473 return ArrayRef(getTrailingObjects<const StringInit *>(), NumArgNames); 1474 } 1475 1476 const Init *resolveReferences(Resolver &R) const override; 1477 1478 bool isConcrete() const override; 1479 std::string getAsString() const override; 1480 1481 using const_arg_iterator = SmallVectorImpl<const Init *>::const_iterator; 1482 using const_name_iterator = 1483 SmallVectorImpl<const StringInit *>::const_iterator; 1484 1485 inline const_arg_iterator arg_begin() const { return getArgs().begin(); } 1486 inline const_arg_iterator arg_end () const { return getArgs().end(); } 1487 1488 inline size_t arg_size () const { return NumArgs; } 1489 inline bool arg_empty() const { return NumArgs == 0; } 1490 1491 inline const_name_iterator name_begin() const { return getArgNames().begin();} 1492 inline const_name_iterator name_end () const { return getArgNames().end(); } 1493 1494 inline size_t name_size () const { return NumArgNames; } 1495 inline bool name_empty() const { return NumArgNames == 0; } 1496 1497 const Init *getBit(unsigned Bit) const override { 1498 llvm_unreachable("Illegal bit reference off dag"); 1499 } 1500 }; 1501 1502 //===----------------------------------------------------------------------===// 1503 // High-Level Classes 1504 //===----------------------------------------------------------------------===// 1505 1506 /// This class represents a field in a record, including its name, type, 1507 /// value, and source location. 1508 class RecordVal { 1509 friend class Record; 1510 1511 public: 1512 enum FieldKind { 1513 FK_Normal, // A normal record field. 1514 FK_NonconcreteOK, // A field that can be nonconcrete ('field' keyword). 1515 FK_TemplateArg, // A template argument. 1516 }; 1517 1518 private: 1519 const Init *Name; 1520 SMLoc Loc; // Source location of definition of name. 1521 PointerIntPair<const RecTy *, 2, FieldKind> TyAndKind; 1522 const Init *Value; 1523 bool IsUsed = false; 1524 1525 /// Reference locations to this record value. 1526 SmallVector<SMRange> ReferenceLocs; 1527 1528 public: 1529 RecordVal(const Init *N, const RecTy *T, FieldKind K); 1530 RecordVal(const Init *N, SMLoc Loc, const RecTy *T, FieldKind K); 1531 1532 /// Get the record keeper used to unique this value. 1533 RecordKeeper &getRecordKeeper() const { return Name->getRecordKeeper(); } 1534 1535 /// Get the name of the field as a StringRef. 1536 StringRef getName() const; 1537 1538 /// Get the name of the field as an Init. 1539 const Init *getNameInit() const { return Name; } 1540 1541 /// Get the name of the field as a std::string. 1542 std::string getNameInitAsString() const { 1543 return getNameInit()->getAsUnquotedString(); 1544 } 1545 1546 /// Get the source location of the point where the field was defined. 1547 const SMLoc &getLoc() const { return Loc; } 1548 1549 /// Is this a field where nonconcrete values are okay? 1550 bool isNonconcreteOK() const { 1551 return TyAndKind.getInt() == FK_NonconcreteOK; 1552 } 1553 1554 /// Is this a template argument? 1555 bool isTemplateArg() const { 1556 return TyAndKind.getInt() == FK_TemplateArg; 1557 } 1558 1559 /// Get the type of the field value as a RecTy. 1560 const RecTy *getType() const { return TyAndKind.getPointer(); } 1561 1562 /// Get the type of the field for printing purposes. 1563 std::string getPrintType() const; 1564 1565 /// Get the value of the field as an Init. 1566 const Init *getValue() const { return Value; } 1567 1568 /// Set the value of the field from an Init. 1569 bool setValue(const Init *V); 1570 1571 /// Set the value and source location of the field. 1572 bool setValue(const Init *V, SMLoc NewLoc); 1573 1574 /// Add a reference to this record value. 1575 void addReferenceLoc(SMRange Loc) { ReferenceLocs.push_back(Loc); } 1576 1577 /// Return the references of this record value. 1578 ArrayRef<SMRange> getReferenceLocs() const { return ReferenceLocs; } 1579 1580 /// Whether this value is used. Useful for reporting warnings, for example 1581 /// when a template argument is unused. 1582 void setUsed(bool Used) { IsUsed = Used; } 1583 bool isUsed() const { return IsUsed; } 1584 1585 void dump() const; 1586 1587 /// Print the value to an output stream, possibly with a semicolon. 1588 void print(raw_ostream &OS, bool PrintSem = true) const; 1589 }; 1590 1591 inline raw_ostream &operator<<(raw_ostream &OS, const RecordVal &RV) { 1592 RV.print(OS << " "); 1593 return OS; 1594 } 1595 1596 class Record { 1597 public: 1598 struct AssertionInfo { 1599 SMLoc Loc; 1600 const Init *Condition; 1601 const Init *Message; 1602 1603 // User-defined constructor to support std::make_unique(). It can be 1604 // removed in C++20 when braced initialization is supported. 1605 AssertionInfo(SMLoc Loc, const Init *Condition, const Init *Message) 1606 : Loc(Loc), Condition(Condition), Message(Message) {} 1607 }; 1608 1609 struct DumpInfo { 1610 SMLoc Loc; 1611 const Init *Message; 1612 1613 // User-defined constructor to support std::make_unique(). It can be 1614 // removed in C++20 when braced initialization is supported. 1615 DumpInfo(SMLoc Loc, const Init *Message) : Loc(Loc), Message(Message) {} 1616 }; 1617 1618 enum RecordKind { RK_Def, RK_AnonymousDef, RK_Class, RK_MultiClass }; 1619 1620 private: 1621 const Init *Name; 1622 // Location where record was instantiated, followed by the location of 1623 // multiclass prototypes used, and finally by the locations of references to 1624 // this record. 1625 SmallVector<SMLoc, 4> Locs; 1626 SmallVector<SMLoc, 0> ForwardDeclarationLocs; 1627 mutable SmallVector<SMRange, 0> ReferenceLocs; 1628 SmallVector<const Init *, 0> TemplateArgs; 1629 SmallVector<RecordVal, 0> Values; 1630 SmallVector<AssertionInfo, 0> Assertions; 1631 SmallVector<DumpInfo, 0> Dumps; 1632 1633 // All superclasses in the inheritance forest in post-order (yes, it 1634 // must be a forest; diamond-shaped inheritance is not allowed). 1635 SmallVector<std::pair<const Record *, SMRange>, 0> SuperClasses; 1636 1637 // Tracks Record instances. Not owned by Record. 1638 RecordKeeper &TrackedRecords; 1639 1640 // The DefInit corresponding to this record. 1641 mutable DefInit *CorrespondingDefInit = nullptr; 1642 1643 // Unique record ID. 1644 unsigned ID; 1645 1646 RecordKind Kind; 1647 1648 void checkName(); 1649 1650 public: 1651 // Constructs a record. 1652 explicit Record(const Init *N, ArrayRef<SMLoc> locs, RecordKeeper &records, 1653 RecordKind Kind = RK_Def) 1654 : Name(N), Locs(locs), TrackedRecords(records), 1655 ID(getNewUID(N->getRecordKeeper())), Kind(Kind) { 1656 checkName(); 1657 } 1658 1659 explicit Record(StringRef N, ArrayRef<SMLoc> locs, RecordKeeper &records, 1660 RecordKind Kind = RK_Def) 1661 : Record(StringInit::get(records, N), locs, records, Kind) {} 1662 1663 // When copy-constructing a Record, we must still guarantee a globally unique 1664 // ID number. Don't copy CorrespondingDefInit either, since it's owned by the 1665 // original record. All other fields can be copied normally. 1666 Record(const Record &O) 1667 : Name(O.Name), Locs(O.Locs), TemplateArgs(O.TemplateArgs), 1668 Values(O.Values), Assertions(O.Assertions), 1669 SuperClasses(O.SuperClasses), TrackedRecords(O.TrackedRecords), 1670 ID(getNewUID(O.getRecords())), Kind(O.Kind) {} 1671 1672 static unsigned getNewUID(RecordKeeper &RK); 1673 1674 unsigned getID() const { return ID; } 1675 1676 StringRef getName() const { return cast<StringInit>(Name)->getValue(); } 1677 1678 const Init *getNameInit() const { return Name; } 1679 1680 std::string getNameInitAsString() const { 1681 return getNameInit()->getAsUnquotedString(); 1682 } 1683 1684 void setName(const Init *Name); // Also updates RecordKeeper. 1685 1686 ArrayRef<SMLoc> getLoc() const { return Locs; } 1687 void appendLoc(SMLoc Loc) { Locs.push_back(Loc); } 1688 1689 ArrayRef<SMLoc> getForwardDeclarationLocs() const { 1690 return ForwardDeclarationLocs; 1691 } 1692 1693 /// Add a reference to this record value. 1694 void appendReferenceLoc(SMRange Loc) const { ReferenceLocs.push_back(Loc); } 1695 1696 /// Return the references of this record value. 1697 ArrayRef<SMRange> getReferenceLocs() const { return ReferenceLocs; } 1698 1699 // Update a class location when encountering a (re-)definition. 1700 void updateClassLoc(SMLoc Loc); 1701 1702 // Make the type that this record should have based on its superclasses. 1703 const RecordRecTy *getType() const; 1704 1705 /// get the corresponding DefInit. 1706 DefInit *getDefInit() const; 1707 1708 bool isClass() const { return Kind == RK_Class; } 1709 1710 bool isMultiClass() const { return Kind == RK_MultiClass; } 1711 1712 bool isAnonymous() const { return Kind == RK_AnonymousDef; } 1713 1714 ArrayRef<const Init *> getTemplateArgs() const { return TemplateArgs; } 1715 1716 ArrayRef<RecordVal> getValues() const { return Values; } 1717 1718 ArrayRef<AssertionInfo> getAssertions() const { return Assertions; } 1719 ArrayRef<DumpInfo> getDumps() const { return Dumps; } 1720 1721 ArrayRef<std::pair<const Record *, SMRange>> getSuperClasses() const { 1722 return SuperClasses; 1723 } 1724 1725 /// Determine whether this record has the specified direct superclass. 1726 bool hasDirectSuperClass(const Record *SuperClass) const; 1727 1728 /// Append the direct superclasses of this record to Classes. 1729 void getDirectSuperClasses(SmallVectorImpl<const Record *> &Classes) const; 1730 1731 bool isTemplateArg(const Init *Name) const { 1732 return llvm::is_contained(TemplateArgs, Name); 1733 } 1734 1735 const RecordVal *getValue(const Init *Name) const { 1736 for (const RecordVal &Val : Values) 1737 if (Val.Name == Name) return &Val; 1738 return nullptr; 1739 } 1740 1741 const RecordVal *getValue(StringRef Name) const { 1742 return getValue(StringInit::get(getRecords(), Name)); 1743 } 1744 1745 RecordVal *getValue(const Init *Name) { 1746 return const_cast<RecordVal *>( 1747 static_cast<const Record *>(this)->getValue(Name)); 1748 } 1749 1750 RecordVal *getValue(StringRef Name) { 1751 return const_cast<RecordVal *>( 1752 static_cast<const Record *>(this)->getValue(Name)); 1753 } 1754 1755 void addTemplateArg(const Init *Name) { 1756 assert(!isTemplateArg(Name) && "Template arg already defined!"); 1757 TemplateArgs.push_back(Name); 1758 } 1759 1760 void addValue(const RecordVal &RV) { 1761 assert(getValue(RV.getNameInit()) == nullptr && "Value already added!"); 1762 Values.push_back(RV); 1763 } 1764 1765 void removeValue(const Init *Name) { 1766 for (unsigned i = 0, e = Values.size(); i != e; ++i) 1767 if (Values[i].getNameInit() == Name) { 1768 Values.erase(Values.begin()+i); 1769 return; 1770 } 1771 llvm_unreachable("Cannot remove an entry that does not exist!"); 1772 } 1773 1774 void removeValue(StringRef Name) { 1775 removeValue(StringInit::get(getRecords(), Name)); 1776 } 1777 1778 void addAssertion(SMLoc Loc, const Init *Condition, const Init *Message) { 1779 Assertions.push_back(AssertionInfo(Loc, Condition, Message)); 1780 } 1781 1782 void addDump(SMLoc Loc, const Init *Message) { 1783 Dumps.push_back(DumpInfo(Loc, Message)); 1784 } 1785 1786 void appendAssertions(const Record *Rec) { 1787 Assertions.append(Rec->Assertions); 1788 } 1789 1790 void appendDumps(const Record *Rec) { Dumps.append(Rec->Dumps); } 1791 1792 void checkRecordAssertions(); 1793 void emitRecordDumps(); 1794 void checkUnusedTemplateArgs(); 1795 1796 bool isSubClassOf(const Record *R) const { 1797 for (const auto &[SC, _] : SuperClasses) 1798 if (SC == R) 1799 return true; 1800 return false; 1801 } 1802 1803 bool isSubClassOf(StringRef Name) const { 1804 for (const auto &[SC, _] : SuperClasses) { 1805 if (const auto *SI = dyn_cast<StringInit>(SC->getNameInit())) { 1806 if (SI->getValue() == Name) 1807 return true; 1808 } else if (SC->getNameInitAsString() == Name) { 1809 return true; 1810 } 1811 } 1812 return false; 1813 } 1814 1815 void addSuperClass(const Record *R, SMRange Range) { 1816 assert(!CorrespondingDefInit && 1817 "changing type of record after it has been referenced"); 1818 assert(!isSubClassOf(R) && "Already subclassing record!"); 1819 SuperClasses.emplace_back(R, Range); 1820 } 1821 1822 /// If there are any field references that refer to fields that have been 1823 /// filled in, we can propagate the values now. 1824 /// 1825 /// This is a final resolve: any error messages, e.g. due to undefined !cast 1826 /// references, are generated now. 1827 void resolveReferences(const Init *NewName = nullptr); 1828 1829 /// Apply the resolver to the name of the record as well as to the 1830 /// initializers of all fields of the record except SkipVal. 1831 /// 1832 /// The resolver should not resolve any of the fields itself, to avoid 1833 /// recursion / infinite loops. 1834 void resolveReferences(Resolver &R, const RecordVal *SkipVal = nullptr); 1835 1836 RecordKeeper &getRecords() const { 1837 return TrackedRecords; 1838 } 1839 1840 void dump() const; 1841 1842 //===--------------------------------------------------------------------===// 1843 // High-level methods useful to tablegen back-ends 1844 // 1845 1846 /// Return the source location for the named field. 1847 SMLoc getFieldLoc(StringRef FieldName) const; 1848 1849 /// Return the initializer for a value with the specified name, or throw an 1850 /// exception if the field does not exist. 1851 const Init *getValueInit(StringRef FieldName) const; 1852 1853 /// Return true if the named field is unset. 1854 bool isValueUnset(StringRef FieldName) const { 1855 return isa<UnsetInit>(getValueInit(FieldName)); 1856 } 1857 1858 /// This method looks up the specified field and returns its value as a 1859 /// string, throwing an exception if the field does not exist or if the value 1860 /// is not a string. 1861 StringRef getValueAsString(StringRef FieldName) const; 1862 1863 /// This method looks up the specified field and returns its value as a 1864 /// string, throwing an exception if the value is not a string and 1865 /// std::nullopt if the field does not exist. 1866 std::optional<StringRef> getValueAsOptionalString(StringRef FieldName) const; 1867 1868 /// This method looks up the specified field and returns its value as a 1869 /// BitsInit, throwing an exception if the field does not exist or if the 1870 /// value is not the right type. 1871 const BitsInit *getValueAsBitsInit(StringRef FieldName) const; 1872 1873 /// This method looks up the specified field and returns its value as a 1874 /// ListInit, throwing an exception if the field does not exist or if the 1875 /// value is not the right type. 1876 const ListInit *getValueAsListInit(StringRef FieldName) const; 1877 1878 /// This method looks up the specified field and returns its value as a 1879 /// vector of records, throwing an exception if the field does not exist or 1880 /// if the value is not the right type. 1881 std::vector<const Record *> getValueAsListOfDefs(StringRef FieldName) const; 1882 1883 /// This method looks up the specified field and returns its value as a 1884 /// vector of integers, throwing an exception if the field does not exist or 1885 /// if the value is not the right type. 1886 std::vector<int64_t> getValueAsListOfInts(StringRef FieldName) const; 1887 1888 /// This method looks up the specified field and returns its value as a 1889 /// vector of strings, throwing an exception if the field does not exist or 1890 /// if the value is not the right type. 1891 std::vector<StringRef> getValueAsListOfStrings(StringRef FieldName) const; 1892 1893 /// This method looks up the specified field and returns its value as a 1894 /// Record, throwing an exception if the field does not exist or if the value 1895 /// is not the right type. 1896 const Record *getValueAsDef(StringRef FieldName) const; 1897 1898 /// This method looks up the specified field and returns its value as a 1899 /// Record, returning null if the field exists but is "uninitialized" (i.e. 1900 /// set to `?`), and throwing an exception if the field does not exist or if 1901 /// its value is not the right type. 1902 const Record *getValueAsOptionalDef(StringRef FieldName) const; 1903 1904 /// This method looks up the specified field and returns its value as a bit, 1905 /// throwing an exception if the field does not exist or if the value is not 1906 /// the right type. 1907 bool getValueAsBit(StringRef FieldName) const; 1908 1909 /// This method looks up the specified field and returns its value as a bit. 1910 /// If the field is unset, sets Unset to true and returns false. 1911 bool getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const; 1912 1913 /// This method looks up the specified field and returns its value as an 1914 /// int64_t, throwing an exception if the field does not exist or if the 1915 /// value is not the right type. 1916 int64_t getValueAsInt(StringRef FieldName) const; 1917 1918 /// This method looks up the specified field and returns its value as an Dag, 1919 /// throwing an exception if the field does not exist or if the value is not 1920 /// the right type. 1921 const DagInit *getValueAsDag(StringRef FieldName) const; 1922 }; 1923 1924 raw_ostream &operator<<(raw_ostream &OS, const Record &R); 1925 1926 class RecordKeeper { 1927 using RecordMap = std::map<std::string, std::unique_ptr<Record>, std::less<>>; 1928 using GlobalMap = std::map<std::string, const Init *, std::less<>>; 1929 1930 public: 1931 RecordKeeper(); 1932 ~RecordKeeper(); 1933 1934 /// Return the internal implementation of the RecordKeeper. 1935 detail::RecordKeeperImpl &getImpl() { return *Impl; } 1936 1937 /// Get the main TableGen input file's name. 1938 const std::string getInputFilename() const { return InputFilename; } 1939 1940 /// Get the map of classes. 1941 const RecordMap &getClasses() const { return Classes; } 1942 1943 /// Get the map of records (defs). 1944 const RecordMap &getDefs() const { return Defs; } 1945 1946 /// Get the map of global variables. 1947 const GlobalMap &getGlobals() const { return ExtraGlobals; } 1948 1949 /// Get the class with the specified name. 1950 const Record *getClass(StringRef Name) const { 1951 auto I = Classes.find(Name); 1952 return I == Classes.end() ? nullptr : I->second.get(); 1953 } 1954 1955 /// Get the concrete record with the specified name. 1956 const Record *getDef(StringRef Name) const { 1957 auto I = Defs.find(Name); 1958 return I == Defs.end() ? nullptr : I->second.get(); 1959 } 1960 1961 /// Get the \p Init value of the specified global variable. 1962 const Init *getGlobal(StringRef Name) const { 1963 if (const Record *R = getDef(Name)) 1964 return R->getDefInit(); 1965 auto It = ExtraGlobals.find(Name); 1966 return It == ExtraGlobals.end() ? nullptr : It->second; 1967 } 1968 1969 void saveInputFilename(std::string Filename) { 1970 InputFilename = Filename; 1971 } 1972 1973 void addClass(std::unique_ptr<Record> R) { 1974 bool Ins = 1975 Classes.try_emplace(std::string(R->getName()), std::move(R)).second; 1976 (void)Ins; 1977 assert(Ins && "Class already exists"); 1978 } 1979 1980 void addDef(std::unique_ptr<Record> R) { 1981 bool Ins = Defs.try_emplace(std::string(R->getName()), std::move(R)).second; 1982 (void)Ins; 1983 assert(Ins && "Record already exists"); 1984 } 1985 1986 void addExtraGlobal(StringRef Name, const Init *I) { 1987 bool Ins = ExtraGlobals.try_emplace(std::string(Name), I).second; 1988 (void)Ins; 1989 assert(!getDef(Name)); 1990 assert(Ins && "Global already exists"); 1991 } 1992 1993 const Init *getNewAnonymousName(); 1994 1995 TGTimer &getTimer() const { return *Timer; } 1996 1997 //===--------------------------------------------------------------------===// 1998 // High-level helper methods, useful for tablegen backends. 1999 2000 /// Get all the concrete records that inherit from the one specified 2001 /// class. The class must be defined. 2002 ArrayRef<const Record *> getAllDerivedDefinitions(StringRef ClassName) const; 2003 2004 /// Get all the concrete records that inherit from all the specified 2005 /// classes. The classes must be defined. 2006 std::vector<const Record *> 2007 getAllDerivedDefinitions(ArrayRef<StringRef> ClassNames) const; 2008 2009 /// Get all the concrete records that inherit from specified class, if the 2010 /// class is defined. Returns an empty vector if the class is not defined. 2011 ArrayRef<const Record *> 2012 getAllDerivedDefinitionsIfDefined(StringRef ClassName) const; 2013 2014 void dump() const; 2015 2016 void dumpAllocationStats(raw_ostream &OS) const; 2017 2018 private: 2019 RecordKeeper(RecordKeeper &&) = delete; 2020 RecordKeeper(const RecordKeeper &) = delete; 2021 RecordKeeper &operator=(RecordKeeper &&) = delete; 2022 RecordKeeper &operator=(const RecordKeeper &) = delete; 2023 2024 std::string InputFilename; 2025 RecordMap Classes, Defs; 2026 mutable std::map<std::string, std::vector<const Record *>> Cache; 2027 GlobalMap ExtraGlobals; 2028 2029 /// The internal uniquer implementation of the RecordKeeper. 2030 std::unique_ptr<detail::RecordKeeperImpl> Impl; 2031 std::unique_ptr<TGTimer> Timer; 2032 }; 2033 2034 /// Sorting predicate to sort record pointers by name. 2035 struct LessRecord { 2036 bool operator()(const Record *Rec1, const Record *Rec2) const { 2037 return Rec1->getName().compare_numeric(Rec2->getName()) < 0; 2038 } 2039 }; 2040 2041 /// Sorting predicate to sort record pointers by their 2042 /// unique ID. If you just need a deterministic order, use this, since it 2043 /// just compares two `unsigned`; the other sorting predicates require 2044 /// string manipulation. 2045 struct LessRecordByID { 2046 bool operator()(const Record *LHS, const Record *RHS) const { 2047 return LHS->getID() < RHS->getID(); 2048 } 2049 }; 2050 2051 /// Sorting predicate to sort record pointers by their Name field. 2052 struct LessRecordFieldName { 2053 bool operator()(const Record *Rec1, const Record *Rec2) const { 2054 return Rec1->getValueAsString("Name") < Rec2->getValueAsString("Name"); 2055 } 2056 }; 2057 2058 struct LessRecordRegister { 2059 struct RecordParts { 2060 SmallVector<std::pair< bool, StringRef>, 4> Parts; 2061 2062 RecordParts(StringRef Rec) { 2063 if (Rec.empty()) 2064 return; 2065 2066 size_t Len = 0; 2067 const char *Start = Rec.data(); 2068 const char *Curr = Start; 2069 bool IsDigitPart = isDigit(Curr[0]); 2070 for (size_t I = 0, E = Rec.size(); I != E; ++I, ++Len) { 2071 bool IsDigit = isDigit(Curr[I]); 2072 if (IsDigit != IsDigitPart) { 2073 Parts.emplace_back(IsDigitPart, StringRef(Start, Len)); 2074 Len = 0; 2075 Start = &Curr[I]; 2076 IsDigitPart = isDigit(Curr[I]); 2077 } 2078 } 2079 // Push the last part. 2080 Parts.emplace_back(IsDigitPart, StringRef(Start, Len)); 2081 } 2082 2083 size_t size() { return Parts.size(); } 2084 2085 std::pair<bool, StringRef> getPart(size_t i) { 2086 assert (i < Parts.size() && "Invalid idx!"); 2087 return Parts[i]; 2088 } 2089 }; 2090 2091 bool operator()(const Record *Rec1, const Record *Rec2) const { 2092 int64_t LHSPositionOrder = Rec1->getValueAsInt("PositionOrder"); 2093 int64_t RHSPositionOrder = Rec2->getValueAsInt("PositionOrder"); 2094 if (LHSPositionOrder != RHSPositionOrder) 2095 return LHSPositionOrder < RHSPositionOrder; 2096 2097 RecordParts LHSParts(StringRef(Rec1->getName())); 2098 RecordParts RHSParts(StringRef(Rec2->getName())); 2099 2100 size_t LHSNumParts = LHSParts.size(); 2101 size_t RHSNumParts = RHSParts.size(); 2102 assert (LHSNumParts && RHSNumParts && "Expected at least one part!"); 2103 2104 if (LHSNumParts != RHSNumParts) 2105 return LHSNumParts < RHSNumParts; 2106 2107 // We expect the registers to be of the form [_a-zA-Z]+([0-9]*[_a-zA-Z]*)*. 2108 for (size_t I = 0, E = LHSNumParts; I < E; I+=2) { 2109 std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I); 2110 std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I); 2111 // Expect even part to always be alpha. 2112 assert (LHSPart.first == false && RHSPart.first == false && 2113 "Expected both parts to be alpha."); 2114 if (int Res = LHSPart.second.compare(RHSPart.second)) 2115 return Res < 0; 2116 } 2117 for (size_t I = 1, E = LHSNumParts; I < E; I+=2) { 2118 std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I); 2119 std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I); 2120 // Expect odd part to always be numeric. 2121 assert (LHSPart.first == true && RHSPart.first == true && 2122 "Expected both parts to be numeric."); 2123 if (LHSPart.second.size() != RHSPart.second.size()) 2124 return LHSPart.second.size() < RHSPart.second.size(); 2125 2126 unsigned LHSVal, RHSVal; 2127 2128 bool LHSFailed = LHSPart.second.getAsInteger(10, LHSVal); (void)LHSFailed; 2129 assert(!LHSFailed && "Unable to convert LHS to integer."); 2130 bool RHSFailed = RHSPart.second.getAsInteger(10, RHSVal); (void)RHSFailed; 2131 assert(!RHSFailed && "Unable to convert RHS to integer."); 2132 2133 if (LHSVal != RHSVal) 2134 return LHSVal < RHSVal; 2135 } 2136 return LHSNumParts < RHSNumParts; 2137 } 2138 }; 2139 2140 raw_ostream &operator<<(raw_ostream &OS, const RecordKeeper &RK); 2141 2142 //===----------------------------------------------------------------------===// 2143 // Resolvers 2144 //===----------------------------------------------------------------------===// 2145 2146 /// Interface for looking up the initializer for a variable name, used by 2147 /// Init::resolveReferences. 2148 class Resolver { 2149 const Record *CurRec; 2150 bool IsFinal = false; 2151 2152 public: 2153 explicit Resolver(const Record *CurRec) : CurRec(CurRec) {} 2154 virtual ~Resolver() = default; 2155 2156 const Record *getCurrentRecord() const { return CurRec; } 2157 2158 /// Return the initializer for the given variable name (should normally be a 2159 /// StringInit), or nullptr if the name could not be resolved. 2160 virtual const Init *resolve(const Init *VarName) = 0; 2161 2162 // Whether bits in a BitsInit should stay unresolved if resolving them would 2163 // result in a ? (UnsetInit). This behavior is used to represent instruction 2164 // encodings by keeping references to unset variables within a record. 2165 virtual bool keepUnsetBits() const { return false; } 2166 2167 // Whether this is the final resolve step before adding a record to the 2168 // RecordKeeper. Error reporting during resolve and related constant folding 2169 // should only happen when this is true. 2170 bool isFinal() const { return IsFinal; } 2171 2172 void setFinal(bool Final) { IsFinal = Final; } 2173 }; 2174 2175 /// Resolve arbitrary mappings. 2176 class MapResolver final : public Resolver { 2177 struct MappedValue { 2178 const Init *V; 2179 bool Resolved; 2180 2181 MappedValue() : V(nullptr), Resolved(false) {} 2182 MappedValue(const Init *V, bool Resolved) : V(V), Resolved(Resolved) {} 2183 }; 2184 2185 DenseMap<const Init *, MappedValue> Map; 2186 2187 public: 2188 explicit MapResolver(const Record *CurRec = nullptr) : Resolver(CurRec) {} 2189 2190 void set(const Init *Key, const Init *Value) { Map[Key] = {Value, false}; } 2191 2192 bool isComplete(Init *VarName) const { 2193 auto It = Map.find(VarName); 2194 assert(It != Map.end() && "key must be present in map"); 2195 return It->second.V->isComplete(); 2196 } 2197 2198 const Init *resolve(const Init *VarName) override; 2199 }; 2200 2201 /// Resolve all variables from a record except for unset variables. 2202 class RecordResolver final : public Resolver { 2203 DenseMap<const Init *, const Init *> Cache; 2204 SmallVector<const Init *, 4> Stack; 2205 const Init *Name = nullptr; 2206 2207 public: 2208 explicit RecordResolver(const Record &R) : Resolver(&R) {} 2209 2210 void setName(const Init *NewName) { Name = NewName; } 2211 2212 const Init *resolve(const Init *VarName) override; 2213 2214 bool keepUnsetBits() const override { return true; } 2215 }; 2216 2217 /// Delegate resolving to a sub-resolver, but shadow some variable names. 2218 class ShadowResolver final : public Resolver { 2219 Resolver &R; 2220 DenseSet<const Init *> Shadowed; 2221 2222 public: 2223 explicit ShadowResolver(Resolver &R) 2224 : Resolver(R.getCurrentRecord()), R(R) { 2225 setFinal(R.isFinal()); 2226 } 2227 2228 void addShadow(const Init *Key) { Shadowed.insert(Key); } 2229 2230 const Init *resolve(const Init *VarName) override { 2231 if (Shadowed.count(VarName)) 2232 return nullptr; 2233 return R.resolve(VarName); 2234 } 2235 }; 2236 2237 /// (Optionally) delegate resolving to a sub-resolver, and keep track whether 2238 /// there were unresolved references. 2239 class TrackUnresolvedResolver final : public Resolver { 2240 Resolver *R; 2241 bool FoundUnresolved = false; 2242 2243 public: 2244 explicit TrackUnresolvedResolver(Resolver *R = nullptr) 2245 : Resolver(R ? R->getCurrentRecord() : nullptr), R(R) {} 2246 2247 bool foundUnresolved() const { return FoundUnresolved; } 2248 2249 const Init *resolve(const Init *VarName) override; 2250 }; 2251 2252 /// Do not resolve anything, but keep track of whether a given variable was 2253 /// referenced. 2254 class HasReferenceResolver final : public Resolver { 2255 const Init *VarNameToTrack; 2256 bool Found = false; 2257 2258 public: 2259 explicit HasReferenceResolver(const Init *VarNameToTrack) 2260 : Resolver(nullptr), VarNameToTrack(VarNameToTrack) {} 2261 2262 bool found() const { return Found; } 2263 2264 const Init *resolve(const Init *VarName) override; 2265 }; 2266 2267 void EmitDetailedRecords(const RecordKeeper &RK, raw_ostream &OS); 2268 void EmitJSON(const RecordKeeper &RK, raw_ostream &OS); 2269 2270 } // end namespace llvm 2271 2272 #endif // LLVM_TABLEGEN_RECORD_H 2273