1 //===- Record.cpp - Record implementation ---------------------------------===// 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 // Implement the tablegen record classes. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/ADT/ArrayRef.h" 14 #include "llvm/ADT/DenseMap.h" 15 #include "llvm/ADT/FoldingSet.h" 16 #include "llvm/ADT/SmallString.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/Statistic.h" 19 #include "llvm/ADT/StringExtras.h" 20 #include "llvm/ADT/StringMap.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/StringSet.h" 23 #include "llvm/Config/llvm-config.h" 24 #include "llvm/Support/Allocator.h" 25 #include "llvm/Support/Casting.h" 26 #include "llvm/Support/Compiler.h" 27 #include "llvm/Support/ErrorHandling.h" 28 #include "llvm/Support/SMLoc.h" 29 #include "llvm/Support/raw_ostream.h" 30 #include "llvm/TableGen/Error.h" 31 #include "llvm/TableGen/Record.h" 32 #include <cassert> 33 #include <cstdint> 34 #include <memory> 35 #include <map> 36 #include <string> 37 #include <utility> 38 #include <vector> 39 40 using namespace llvm; 41 42 #define DEBUG_TYPE "tblgen-records" 43 44 static BumpPtrAllocator Allocator; 45 46 //===----------------------------------------------------------------------===// 47 // Type implementations 48 //===----------------------------------------------------------------------===// 49 50 BitRecTy BitRecTy::Shared; 51 IntRecTy IntRecTy::Shared; 52 StringRecTy StringRecTy::Shared; 53 DagRecTy DagRecTy::Shared; 54 55 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 56 LLVM_DUMP_METHOD void RecTy::dump() const { print(errs()); } 57 #endif 58 59 ListRecTy *RecTy::getListTy() { 60 if (!ListTy) 61 ListTy = new(Allocator) ListRecTy(this); 62 return ListTy; 63 } 64 65 bool RecTy::typeIsConvertibleTo(const RecTy *RHS) const { 66 assert(RHS && "NULL pointer"); 67 return Kind == RHS->getRecTyKind(); 68 } 69 70 bool RecTy::typeIsA(const RecTy *RHS) const { return this == RHS; } 71 72 bool BitRecTy::typeIsConvertibleTo(const RecTy *RHS) const{ 73 if (RecTy::typeIsConvertibleTo(RHS) || RHS->getRecTyKind() == IntRecTyKind) 74 return true; 75 if (const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS)) 76 return BitsTy->getNumBits() == 1; 77 return false; 78 } 79 80 BitsRecTy *BitsRecTy::get(unsigned Sz) { 81 static std::vector<BitsRecTy*> Shared; 82 if (Sz >= Shared.size()) 83 Shared.resize(Sz + 1); 84 BitsRecTy *&Ty = Shared[Sz]; 85 if (!Ty) 86 Ty = new(Allocator) BitsRecTy(Sz); 87 return Ty; 88 } 89 90 std::string BitsRecTy::getAsString() const { 91 return "bits<" + utostr(Size) + ">"; 92 } 93 94 bool BitsRecTy::typeIsConvertibleTo(const RecTy *RHS) const { 95 if (RecTy::typeIsConvertibleTo(RHS)) //argument and the sender are same type 96 return cast<BitsRecTy>(RHS)->Size == Size; 97 RecTyKind kind = RHS->getRecTyKind(); 98 return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind); 99 } 100 101 bool BitsRecTy::typeIsA(const RecTy *RHS) const { 102 if (const BitsRecTy *RHSb = dyn_cast<BitsRecTy>(RHS)) 103 return RHSb->Size == Size; 104 return false; 105 } 106 107 bool IntRecTy::typeIsConvertibleTo(const RecTy *RHS) const { 108 RecTyKind kind = RHS->getRecTyKind(); 109 return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind; 110 } 111 112 std::string StringRecTy::getAsString() const { 113 return "string"; 114 } 115 116 bool StringRecTy::typeIsConvertibleTo(const RecTy *RHS) const { 117 RecTyKind Kind = RHS->getRecTyKind(); 118 return Kind == StringRecTyKind; 119 } 120 121 std::string ListRecTy::getAsString() const { 122 return "list<" + ElementTy->getAsString() + ">"; 123 } 124 125 bool ListRecTy::typeIsConvertibleTo(const RecTy *RHS) const { 126 if (const auto *ListTy = dyn_cast<ListRecTy>(RHS)) 127 return ElementTy->typeIsConvertibleTo(ListTy->getElementType()); 128 return false; 129 } 130 131 bool ListRecTy::typeIsA(const RecTy *RHS) const { 132 if (const ListRecTy *RHSl = dyn_cast<ListRecTy>(RHS)) 133 return getElementType()->typeIsA(RHSl->getElementType()); 134 return false; 135 } 136 137 std::string DagRecTy::getAsString() const { 138 return "dag"; 139 } 140 141 static void ProfileRecordRecTy(FoldingSetNodeID &ID, 142 ArrayRef<Record *> Classes) { 143 ID.AddInteger(Classes.size()); 144 for (Record *R : Classes) 145 ID.AddPointer(R); 146 } 147 148 RecordRecTy *RecordRecTy::get(ArrayRef<Record *> UnsortedClasses) { 149 if (UnsortedClasses.empty()) { 150 static RecordRecTy AnyRecord(0); 151 return &AnyRecord; 152 } 153 154 FoldingSet<RecordRecTy> &ThePool = 155 UnsortedClasses[0]->getRecords().RecordTypePool; 156 157 SmallVector<Record *, 4> Classes(UnsortedClasses.begin(), 158 UnsortedClasses.end()); 159 llvm::sort(Classes, [](Record *LHS, Record *RHS) { 160 return LHS->getNameInitAsString() < RHS->getNameInitAsString(); 161 }); 162 163 FoldingSetNodeID ID; 164 ProfileRecordRecTy(ID, Classes); 165 166 void *IP = nullptr; 167 if (RecordRecTy *Ty = ThePool.FindNodeOrInsertPos(ID, IP)) 168 return Ty; 169 170 #ifndef NDEBUG 171 // Check for redundancy. 172 for (unsigned i = 0; i < Classes.size(); ++i) { 173 for (unsigned j = 0; j < Classes.size(); ++j) { 174 assert(i == j || !Classes[i]->isSubClassOf(Classes[j])); 175 } 176 assert(&Classes[0]->getRecords() == &Classes[i]->getRecords()); 177 } 178 #endif 179 180 void *Mem = Allocator.Allocate(totalSizeToAlloc<Record *>(Classes.size()), 181 alignof(RecordRecTy)); 182 RecordRecTy *Ty = new(Mem) RecordRecTy(Classes.size()); 183 std::uninitialized_copy(Classes.begin(), Classes.end(), 184 Ty->getTrailingObjects<Record *>()); 185 ThePool.InsertNode(Ty, IP); 186 return Ty; 187 } 188 189 void RecordRecTy::Profile(FoldingSetNodeID &ID) const { 190 ProfileRecordRecTy(ID, getClasses()); 191 } 192 193 std::string RecordRecTy::getAsString() const { 194 if (NumClasses == 1) 195 return getClasses()[0]->getNameInitAsString(); 196 197 std::string Str = "{"; 198 bool First = true; 199 for (Record *R : getClasses()) { 200 if (!First) 201 Str += ", "; 202 First = false; 203 Str += R->getNameInitAsString(); 204 } 205 Str += "}"; 206 return Str; 207 } 208 209 bool RecordRecTy::isSubClassOf(Record *Class) const { 210 return llvm::any_of(getClasses(), [Class](Record *MySuperClass) { 211 return MySuperClass == Class || 212 MySuperClass->isSubClassOf(Class); 213 }); 214 } 215 216 bool RecordRecTy::typeIsConvertibleTo(const RecTy *RHS) const { 217 if (this == RHS) 218 return true; 219 220 const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS); 221 if (!RTy) 222 return false; 223 224 return llvm::all_of(RTy->getClasses(), [this](Record *TargetClass) { 225 return isSubClassOf(TargetClass); 226 }); 227 } 228 229 bool RecordRecTy::typeIsA(const RecTy *RHS) const { 230 return typeIsConvertibleTo(RHS); 231 } 232 233 static RecordRecTy *resolveRecordTypes(RecordRecTy *T1, RecordRecTy *T2) { 234 SmallVector<Record *, 4> CommonSuperClasses; 235 SmallVector<Record *, 4> Stack(T1->classes_begin(), T1->classes_end()); 236 237 while (!Stack.empty()) { 238 Record *R = Stack.pop_back_val(); 239 240 if (T2->isSubClassOf(R)) { 241 CommonSuperClasses.push_back(R); 242 } else { 243 R->getDirectSuperClasses(Stack); 244 } 245 } 246 247 return RecordRecTy::get(CommonSuperClasses); 248 } 249 250 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) { 251 if (T1 == T2) 252 return T1; 253 254 if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) { 255 if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2)) 256 return resolveRecordTypes(RecTy1, RecTy2); 257 } 258 259 if (T1->typeIsConvertibleTo(T2)) 260 return T2; 261 if (T2->typeIsConvertibleTo(T1)) 262 return T1; 263 264 if (ListRecTy *ListTy1 = dyn_cast<ListRecTy>(T1)) { 265 if (ListRecTy *ListTy2 = dyn_cast<ListRecTy>(T2)) { 266 RecTy* NewType = resolveTypes(ListTy1->getElementType(), 267 ListTy2->getElementType()); 268 if (NewType) 269 return NewType->getListTy(); 270 } 271 } 272 273 return nullptr; 274 } 275 276 //===----------------------------------------------------------------------===// 277 // Initializer implementations 278 //===----------------------------------------------------------------------===// 279 280 void Init::anchor() {} 281 282 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 283 LLVM_DUMP_METHOD void Init::dump() const { return print(errs()); } 284 #endif 285 286 UnsetInit *UnsetInit::get() { 287 static UnsetInit TheInit; 288 return &TheInit; 289 } 290 291 Init *UnsetInit::getCastTo(RecTy *Ty) const { 292 return const_cast<UnsetInit *>(this); 293 } 294 295 Init *UnsetInit::convertInitializerTo(RecTy *Ty) const { 296 return const_cast<UnsetInit *>(this); 297 } 298 299 BitInit *BitInit::get(bool V) { 300 static BitInit True(true); 301 static BitInit False(false); 302 303 return V ? &True : &False; 304 } 305 306 Init *BitInit::convertInitializerTo(RecTy *Ty) const { 307 if (isa<BitRecTy>(Ty)) 308 return const_cast<BitInit *>(this); 309 310 if (isa<IntRecTy>(Ty)) 311 return IntInit::get(getValue()); 312 313 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) { 314 // Can only convert single bit. 315 if (BRT->getNumBits() == 1) 316 return BitsInit::get(const_cast<BitInit *>(this)); 317 } 318 319 return nullptr; 320 } 321 322 static void 323 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) { 324 ID.AddInteger(Range.size()); 325 326 for (Init *I : Range) 327 ID.AddPointer(I); 328 } 329 330 BitsInit *BitsInit::get(ArrayRef<Init *> Range) { 331 static FoldingSet<BitsInit> ThePool; 332 333 FoldingSetNodeID ID; 334 ProfileBitsInit(ID, Range); 335 336 void *IP = nullptr; 337 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP)) 338 return I; 339 340 void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()), 341 alignof(BitsInit)); 342 BitsInit *I = new(Mem) BitsInit(Range.size()); 343 std::uninitialized_copy(Range.begin(), Range.end(), 344 I->getTrailingObjects<Init *>()); 345 ThePool.InsertNode(I, IP); 346 return I; 347 } 348 349 void BitsInit::Profile(FoldingSetNodeID &ID) const { 350 ProfileBitsInit(ID, makeArrayRef(getTrailingObjects<Init *>(), NumBits)); 351 } 352 353 Init *BitsInit::convertInitializerTo(RecTy *Ty) const { 354 if (isa<BitRecTy>(Ty)) { 355 if (getNumBits() != 1) return nullptr; // Only accept if just one bit! 356 return getBit(0); 357 } 358 359 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) { 360 // If the number of bits is right, return it. Otherwise we need to expand 361 // or truncate. 362 if (getNumBits() != BRT->getNumBits()) return nullptr; 363 return const_cast<BitsInit *>(this); 364 } 365 366 if (isa<IntRecTy>(Ty)) { 367 int64_t Result = 0; 368 for (unsigned i = 0, e = getNumBits(); i != e; ++i) 369 if (auto *Bit = dyn_cast<BitInit>(getBit(i))) 370 Result |= static_cast<int64_t>(Bit->getValue()) << i; 371 else 372 return nullptr; 373 return IntInit::get(Result); 374 } 375 376 return nullptr; 377 } 378 379 Init * 380 BitsInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const { 381 SmallVector<Init *, 16> NewBits(Bits.size()); 382 383 for (unsigned i = 0, e = Bits.size(); i != e; ++i) { 384 if (Bits[i] >= getNumBits()) 385 return nullptr; 386 NewBits[i] = getBit(Bits[i]); 387 } 388 return BitsInit::get(NewBits); 389 } 390 391 bool BitsInit::isConcrete() const { 392 for (unsigned i = 0, e = getNumBits(); i != e; ++i) { 393 if (!getBit(i)->isConcrete()) 394 return false; 395 } 396 return true; 397 } 398 399 std::string BitsInit::getAsString() const { 400 std::string Result = "{ "; 401 for (unsigned i = 0, e = getNumBits(); i != e; ++i) { 402 if (i) Result += ", "; 403 if (Init *Bit = getBit(e-i-1)) 404 Result += Bit->getAsString(); 405 else 406 Result += "*"; 407 } 408 return Result + " }"; 409 } 410 411 // resolveReferences - If there are any field references that refer to fields 412 // that have been filled in, we can propagate the values now. 413 Init *BitsInit::resolveReferences(Resolver &R) const { 414 bool Changed = false; 415 SmallVector<Init *, 16> NewBits(getNumBits()); 416 417 Init *CachedBitVarRef = nullptr; 418 Init *CachedBitVarResolved = nullptr; 419 420 for (unsigned i = 0, e = getNumBits(); i != e; ++i) { 421 Init *CurBit = getBit(i); 422 Init *NewBit = CurBit; 423 424 if (VarBitInit *CurBitVar = dyn_cast<VarBitInit>(CurBit)) { 425 if (CurBitVar->getBitVar() != CachedBitVarRef) { 426 CachedBitVarRef = CurBitVar->getBitVar(); 427 CachedBitVarResolved = CachedBitVarRef->resolveReferences(R); 428 } 429 assert(CachedBitVarResolved && "Unresolved bitvar reference"); 430 NewBit = CachedBitVarResolved->getBit(CurBitVar->getBitNum()); 431 } else { 432 // getBit(0) implicitly converts int and bits<1> values to bit. 433 NewBit = CurBit->resolveReferences(R)->getBit(0); 434 } 435 436 if (isa<UnsetInit>(NewBit) && R.keepUnsetBits()) 437 NewBit = CurBit; 438 NewBits[i] = NewBit; 439 Changed |= CurBit != NewBit; 440 } 441 442 if (Changed) 443 return BitsInit::get(NewBits); 444 445 return const_cast<BitsInit *>(this); 446 } 447 448 IntInit *IntInit::get(int64_t V) { 449 static std::map<int64_t, IntInit*> ThePool; 450 451 IntInit *&I = ThePool[V]; 452 if (!I) I = new(Allocator) IntInit(V); 453 return I; 454 } 455 456 std::string IntInit::getAsString() const { 457 return itostr(Value); 458 } 459 460 static bool canFitInBitfield(int64_t Value, unsigned NumBits) { 461 // For example, with NumBits == 4, we permit Values from [-7 .. 15]. 462 return (NumBits >= sizeof(Value) * 8) || 463 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1); 464 } 465 466 Init *IntInit::convertInitializerTo(RecTy *Ty) const { 467 if (isa<IntRecTy>(Ty)) 468 return const_cast<IntInit *>(this); 469 470 if (isa<BitRecTy>(Ty)) { 471 int64_t Val = getValue(); 472 if (Val != 0 && Val != 1) return nullptr; // Only accept 0 or 1 for a bit! 473 return BitInit::get(Val != 0); 474 } 475 476 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) { 477 int64_t Value = getValue(); 478 // Make sure this bitfield is large enough to hold the integer value. 479 if (!canFitInBitfield(Value, BRT->getNumBits())) 480 return nullptr; 481 482 SmallVector<Init *, 16> NewBits(BRT->getNumBits()); 483 for (unsigned i = 0; i != BRT->getNumBits(); ++i) 484 NewBits[i] = BitInit::get(Value & ((i < 64) ? (1LL << i) : 0)); 485 486 return BitsInit::get(NewBits); 487 } 488 489 return nullptr; 490 } 491 492 Init * 493 IntInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const { 494 SmallVector<Init *, 16> NewBits(Bits.size()); 495 496 for (unsigned i = 0, e = Bits.size(); i != e; ++i) { 497 if (Bits[i] >= 64) 498 return nullptr; 499 500 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i])); 501 } 502 return BitsInit::get(NewBits); 503 } 504 505 AnonymousNameInit *AnonymousNameInit::get(unsigned V) { 506 return new (Allocator) AnonymousNameInit(V); 507 } 508 509 StringInit *AnonymousNameInit::getNameInit() const { 510 return StringInit::get(getAsString()); 511 } 512 513 std::string AnonymousNameInit::getAsString() const { 514 return "anonymous_" + utostr(Value); 515 } 516 517 Init *AnonymousNameInit::resolveReferences(Resolver &R) const { 518 auto *Old = const_cast<Init *>(static_cast<const Init *>(this)); 519 auto *New = R.resolve(Old); 520 New = New ? New : Old; 521 if (R.isFinal()) 522 if (auto *Anonymous = dyn_cast<AnonymousNameInit>(New)) 523 return Anonymous->getNameInit(); 524 return New; 525 } 526 527 StringInit *StringInit::get(StringRef V, StringFormat Fmt) { 528 static StringMap<StringInit*, BumpPtrAllocator &> StringPool(Allocator); 529 static StringMap<StringInit*, BumpPtrAllocator &> CodePool(Allocator); 530 531 if (Fmt == SF_String) { 532 auto &Entry = *StringPool.insert(std::make_pair(V, nullptr)).first; 533 if (!Entry.second) 534 Entry.second = new (Allocator) StringInit(Entry.getKey(), Fmt); 535 return Entry.second; 536 } else { 537 auto &Entry = *CodePool.insert(std::make_pair(V, nullptr)).first; 538 if (!Entry.second) 539 Entry.second = new (Allocator) StringInit(Entry.getKey(), Fmt); 540 return Entry.second; 541 } 542 } 543 544 Init *StringInit::convertInitializerTo(RecTy *Ty) const { 545 if (isa<StringRecTy>(Ty)) 546 return const_cast<StringInit *>(this); 547 548 return nullptr; 549 } 550 551 static void ProfileListInit(FoldingSetNodeID &ID, 552 ArrayRef<Init *> Range, 553 RecTy *EltTy) { 554 ID.AddInteger(Range.size()); 555 ID.AddPointer(EltTy); 556 557 for (Init *I : Range) 558 ID.AddPointer(I); 559 } 560 561 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) { 562 static FoldingSet<ListInit> ThePool; 563 564 FoldingSetNodeID ID; 565 ProfileListInit(ID, Range, EltTy); 566 567 void *IP = nullptr; 568 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP)) 569 return I; 570 571 assert(Range.empty() || !isa<TypedInit>(Range[0]) || 572 cast<TypedInit>(Range[0])->getType()->typeIsConvertibleTo(EltTy)); 573 574 void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()), 575 alignof(ListInit)); 576 ListInit *I = new(Mem) ListInit(Range.size(), EltTy); 577 std::uninitialized_copy(Range.begin(), Range.end(), 578 I->getTrailingObjects<Init *>()); 579 ThePool.InsertNode(I, IP); 580 return I; 581 } 582 583 void ListInit::Profile(FoldingSetNodeID &ID) const { 584 RecTy *EltTy = cast<ListRecTy>(getType())->getElementType(); 585 586 ProfileListInit(ID, getValues(), EltTy); 587 } 588 589 Init *ListInit::convertInitializerTo(RecTy *Ty) const { 590 if (getType() == Ty) 591 return const_cast<ListInit*>(this); 592 593 if (auto *LRT = dyn_cast<ListRecTy>(Ty)) { 594 SmallVector<Init*, 8> Elements; 595 Elements.reserve(getValues().size()); 596 597 // Verify that all of the elements of the list are subclasses of the 598 // appropriate class! 599 bool Changed = false; 600 RecTy *ElementType = LRT->getElementType(); 601 for (Init *I : getValues()) 602 if (Init *CI = I->convertInitializerTo(ElementType)) { 603 Elements.push_back(CI); 604 if (CI != I) 605 Changed = true; 606 } else 607 return nullptr; 608 609 if (!Changed) 610 return const_cast<ListInit*>(this); 611 return ListInit::get(Elements, ElementType); 612 } 613 614 return nullptr; 615 } 616 617 Init *ListInit::convertInitListSlice(ArrayRef<unsigned> Elements) const { 618 SmallVector<Init*, 8> Vals; 619 Vals.reserve(Elements.size()); 620 for (unsigned Element : Elements) { 621 if (Element >= size()) 622 return nullptr; 623 Vals.push_back(getElement(Element)); 624 } 625 return ListInit::get(Vals, getElementType()); 626 } 627 628 Record *ListInit::getElementAsRecord(unsigned i) const { 629 assert(i < NumValues && "List element index out of range!"); 630 DefInit *DI = dyn_cast<DefInit>(getElement(i)); 631 if (!DI) 632 PrintFatalError("Expected record in list!"); 633 return DI->getDef(); 634 } 635 636 Init *ListInit::resolveReferences(Resolver &R) const { 637 SmallVector<Init*, 8> Resolved; 638 Resolved.reserve(size()); 639 bool Changed = false; 640 641 for (Init *CurElt : getValues()) { 642 Init *E = CurElt->resolveReferences(R); 643 Changed |= E != CurElt; 644 Resolved.push_back(E); 645 } 646 647 if (Changed) 648 return ListInit::get(Resolved, getElementType()); 649 return const_cast<ListInit *>(this); 650 } 651 652 bool ListInit::isConcrete() const { 653 for (Init *Element : *this) { 654 if (!Element->isConcrete()) 655 return false; 656 } 657 return true; 658 } 659 660 std::string ListInit::getAsString() const { 661 std::string Result = "["; 662 const char *sep = ""; 663 for (Init *Element : *this) { 664 Result += sep; 665 sep = ", "; 666 Result += Element->getAsString(); 667 } 668 return Result + "]"; 669 } 670 671 Init *OpInit::getBit(unsigned Bit) const { 672 if (getType() == BitRecTy::get()) 673 return const_cast<OpInit*>(this); 674 return VarBitInit::get(const_cast<OpInit*>(this), Bit); 675 } 676 677 static void 678 ProfileUnOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *Op, RecTy *Type) { 679 ID.AddInteger(Opcode); 680 ID.AddPointer(Op); 681 ID.AddPointer(Type); 682 } 683 684 UnOpInit *UnOpInit::get(UnaryOp Opc, Init *LHS, RecTy *Type) { 685 static FoldingSet<UnOpInit> ThePool; 686 687 FoldingSetNodeID ID; 688 ProfileUnOpInit(ID, Opc, LHS, Type); 689 690 void *IP = nullptr; 691 if (UnOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP)) 692 return I; 693 694 UnOpInit *I = new(Allocator) UnOpInit(Opc, LHS, Type); 695 ThePool.InsertNode(I, IP); 696 return I; 697 } 698 699 void UnOpInit::Profile(FoldingSetNodeID &ID) const { 700 ProfileUnOpInit(ID, getOpcode(), getOperand(), getType()); 701 } 702 703 Init *UnOpInit::Fold(Record *CurRec, bool IsFinal) const { 704 switch (getOpcode()) { 705 case CAST: 706 if (isa<StringRecTy>(getType())) { 707 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) 708 return LHSs; 709 710 if (DefInit *LHSd = dyn_cast<DefInit>(LHS)) 711 return StringInit::get(LHSd->getAsString()); 712 713 if (IntInit *LHSi = 714 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()))) 715 return StringInit::get(LHSi->getAsString()); 716 717 } else if (isa<RecordRecTy>(getType())) { 718 if (StringInit *Name = dyn_cast<StringInit>(LHS)) { 719 if (!CurRec && !IsFinal) 720 break; 721 assert(CurRec && "NULL pointer"); 722 Record *D; 723 724 // Self-references are allowed, but their resolution is delayed until 725 // the final resolve to ensure that we get the correct type for them. 726 auto *Anonymous = dyn_cast<AnonymousNameInit>(CurRec->getNameInit()); 727 if (Name == CurRec->getNameInit() || 728 (Anonymous && Name == Anonymous->getNameInit())) { 729 if (!IsFinal) 730 break; 731 D = CurRec; 732 } else { 733 D = CurRec->getRecords().getDef(Name->getValue()); 734 if (!D) { 735 if (IsFinal) 736 PrintFatalError(CurRec->getLoc(), 737 Twine("Undefined reference to record: '") + 738 Name->getValue() + "'\n"); 739 break; 740 } 741 } 742 743 DefInit *DI = DefInit::get(D); 744 if (!DI->getType()->typeIsA(getType())) { 745 PrintFatalError(CurRec->getLoc(), 746 Twine("Expected type '") + 747 getType()->getAsString() + "', got '" + 748 DI->getType()->getAsString() + "' in: " + 749 getAsString() + "\n"); 750 } 751 return DI; 752 } 753 } 754 755 if (Init *NewInit = LHS->convertInitializerTo(getType())) 756 return NewInit; 757 break; 758 759 case NOT: 760 if (IntInit *LHSi = 761 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()))) 762 return IntInit::get(LHSi->getValue() ? 0 : 1); 763 break; 764 765 case HEAD: 766 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) { 767 assert(!LHSl->empty() && "Empty list in head"); 768 return LHSl->getElement(0); 769 } 770 break; 771 772 case TAIL: 773 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) { 774 assert(!LHSl->empty() && "Empty list in tail"); 775 // Note the +1. We can't just pass the result of getValues() 776 // directly. 777 return ListInit::get(LHSl->getValues().slice(1), LHSl->getElementType()); 778 } 779 break; 780 781 case SIZE: 782 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) 783 return IntInit::get(LHSl->size()); 784 if (DagInit *LHSd = dyn_cast<DagInit>(LHS)) 785 return IntInit::get(LHSd->arg_size()); 786 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) 787 return IntInit::get(LHSs->getValue().size()); 788 break; 789 790 case EMPTY: 791 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) 792 return IntInit::get(LHSl->empty()); 793 if (DagInit *LHSd = dyn_cast<DagInit>(LHS)) 794 return IntInit::get(LHSd->arg_empty()); 795 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) 796 return IntInit::get(LHSs->getValue().empty()); 797 break; 798 799 case GETDAGOP: 800 if (DagInit *Dag = dyn_cast<DagInit>(LHS)) { 801 DefInit *DI = DefInit::get(Dag->getOperatorAsDef({})); 802 if (!DI->getType()->typeIsA(getType())) { 803 PrintFatalError(CurRec->getLoc(), 804 Twine("Expected type '") + 805 getType()->getAsString() + "', got '" + 806 DI->getType()->getAsString() + "' in: " + 807 getAsString() + "\n"); 808 } else { 809 return DI; 810 } 811 } 812 break; 813 } 814 return const_cast<UnOpInit *>(this); 815 } 816 817 Init *UnOpInit::resolveReferences(Resolver &R) const { 818 Init *lhs = LHS->resolveReferences(R); 819 820 if (LHS != lhs || (R.isFinal() && getOpcode() == CAST)) 821 return (UnOpInit::get(getOpcode(), lhs, getType())) 822 ->Fold(R.getCurrentRecord(), R.isFinal()); 823 return const_cast<UnOpInit *>(this); 824 } 825 826 std::string UnOpInit::getAsString() const { 827 std::string Result; 828 switch (getOpcode()) { 829 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break; 830 case NOT: Result = "!not"; break; 831 case HEAD: Result = "!head"; break; 832 case TAIL: Result = "!tail"; break; 833 case SIZE: Result = "!size"; break; 834 case EMPTY: Result = "!empty"; break; 835 case GETDAGOP: Result = "!getdagop"; break; 836 } 837 return Result + "(" + LHS->getAsString() + ")"; 838 } 839 840 static void 841 ProfileBinOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *RHS, 842 RecTy *Type) { 843 ID.AddInteger(Opcode); 844 ID.AddPointer(LHS); 845 ID.AddPointer(RHS); 846 ID.AddPointer(Type); 847 } 848 849 BinOpInit *BinOpInit::get(BinaryOp Opc, Init *LHS, 850 Init *RHS, RecTy *Type) { 851 static FoldingSet<BinOpInit> ThePool; 852 853 FoldingSetNodeID ID; 854 ProfileBinOpInit(ID, Opc, LHS, RHS, Type); 855 856 void *IP = nullptr; 857 if (BinOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP)) 858 return I; 859 860 BinOpInit *I = new(Allocator) BinOpInit(Opc, LHS, RHS, Type); 861 ThePool.InsertNode(I, IP); 862 return I; 863 } 864 865 void BinOpInit::Profile(FoldingSetNodeID &ID) const { 866 ProfileBinOpInit(ID, getOpcode(), getLHS(), getRHS(), getType()); 867 } 868 869 static StringInit *ConcatStringInits(const StringInit *I0, 870 const StringInit *I1) { 871 SmallString<80> Concat(I0->getValue()); 872 Concat.append(I1->getValue()); 873 return StringInit::get(Concat, 874 StringInit::determineFormat(I0->getFormat(), 875 I1->getFormat())); 876 } 877 878 static StringInit *interleaveStringList(const ListInit *List, 879 const StringInit *Delim) { 880 if (List->size() == 0) 881 return StringInit::get(""); 882 StringInit *Element = dyn_cast<StringInit>(List->getElement(0)); 883 if (!Element) 884 return nullptr; 885 SmallString<80> Result(Element->getValue()); 886 StringInit::StringFormat Fmt = StringInit::SF_String; 887 888 for (unsigned I = 1, E = List->size(); I < E; ++I) { 889 Result.append(Delim->getValue()); 890 StringInit *Element = dyn_cast<StringInit>(List->getElement(I)); 891 if (!Element) 892 return nullptr; 893 Result.append(Element->getValue()); 894 Fmt = StringInit::determineFormat(Fmt, Element->getFormat()); 895 } 896 return StringInit::get(Result, Fmt); 897 } 898 899 static StringInit *interleaveIntList(const ListInit *List, 900 const StringInit *Delim) { 901 if (List->size() == 0) 902 return StringInit::get(""); 903 IntInit *Element = 904 dyn_cast_or_null<IntInit>(List->getElement(0) 905 ->convertInitializerTo(IntRecTy::get())); 906 if (!Element) 907 return nullptr; 908 SmallString<80> Result(Element->getAsString()); 909 910 for (unsigned I = 1, E = List->size(); I < E; ++I) { 911 Result.append(Delim->getValue()); 912 IntInit *Element = 913 dyn_cast_or_null<IntInit>(List->getElement(I) 914 ->convertInitializerTo(IntRecTy::get())); 915 if (!Element) 916 return nullptr; 917 Result.append(Element->getAsString()); 918 } 919 return StringInit::get(Result); 920 } 921 922 Init *BinOpInit::getStrConcat(Init *I0, Init *I1) { 923 // Shortcut for the common case of concatenating two strings. 924 if (const StringInit *I0s = dyn_cast<StringInit>(I0)) 925 if (const StringInit *I1s = dyn_cast<StringInit>(I1)) 926 return ConcatStringInits(I0s, I1s); 927 return BinOpInit::get(BinOpInit::STRCONCAT, I0, I1, StringRecTy::get()); 928 } 929 930 static ListInit *ConcatListInits(const ListInit *LHS, 931 const ListInit *RHS) { 932 SmallVector<Init *, 8> Args; 933 llvm::append_range(Args, *LHS); 934 llvm::append_range(Args, *RHS); 935 return ListInit::get(Args, LHS->getElementType()); 936 } 937 938 Init *BinOpInit::getListConcat(TypedInit *LHS, Init *RHS) { 939 assert(isa<ListRecTy>(LHS->getType()) && "First arg must be a list"); 940 941 // Shortcut for the common case of concatenating two lists. 942 if (const ListInit *LHSList = dyn_cast<ListInit>(LHS)) 943 if (const ListInit *RHSList = dyn_cast<ListInit>(RHS)) 944 return ConcatListInits(LHSList, RHSList); 945 return BinOpInit::get(BinOpInit::LISTCONCAT, LHS, RHS, LHS->getType()); 946 } 947 948 Init *BinOpInit::Fold(Record *CurRec) const { 949 switch (getOpcode()) { 950 case CONCAT: { 951 DagInit *LHSs = dyn_cast<DagInit>(LHS); 952 DagInit *RHSs = dyn_cast<DagInit>(RHS); 953 if (LHSs && RHSs) { 954 DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator()); 955 DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator()); 956 if ((!LOp && !isa<UnsetInit>(LHSs->getOperator())) || 957 (!ROp && !isa<UnsetInit>(RHSs->getOperator()))) 958 break; 959 if (LOp && ROp && LOp->getDef() != ROp->getDef()) { 960 PrintFatalError(Twine("Concatenated Dag operators do not match: '") + 961 LHSs->getAsString() + "' vs. '" + RHSs->getAsString() + 962 "'"); 963 } 964 Init *Op = LOp ? LOp : ROp; 965 if (!Op) 966 Op = UnsetInit::get(); 967 968 SmallVector<Init*, 8> Args; 969 SmallVector<StringInit*, 8> ArgNames; 970 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) { 971 Args.push_back(LHSs->getArg(i)); 972 ArgNames.push_back(LHSs->getArgName(i)); 973 } 974 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) { 975 Args.push_back(RHSs->getArg(i)); 976 ArgNames.push_back(RHSs->getArgName(i)); 977 } 978 return DagInit::get(Op, nullptr, Args, ArgNames); 979 } 980 break; 981 } 982 case LISTCONCAT: { 983 ListInit *LHSs = dyn_cast<ListInit>(LHS); 984 ListInit *RHSs = dyn_cast<ListInit>(RHS); 985 if (LHSs && RHSs) { 986 SmallVector<Init *, 8> Args; 987 llvm::append_range(Args, *LHSs); 988 llvm::append_range(Args, *RHSs); 989 return ListInit::get(Args, LHSs->getElementType()); 990 } 991 break; 992 } 993 case LISTSPLAT: { 994 TypedInit *Value = dyn_cast<TypedInit>(LHS); 995 IntInit *Size = dyn_cast<IntInit>(RHS); 996 if (Value && Size) { 997 SmallVector<Init *, 8> Args(Size->getValue(), Value); 998 return ListInit::get(Args, Value->getType()); 999 } 1000 break; 1001 } 1002 case STRCONCAT: { 1003 StringInit *LHSs = dyn_cast<StringInit>(LHS); 1004 StringInit *RHSs = dyn_cast<StringInit>(RHS); 1005 if (LHSs && RHSs) 1006 return ConcatStringInits(LHSs, RHSs); 1007 break; 1008 } 1009 case INTERLEAVE: { 1010 ListInit *List = dyn_cast<ListInit>(LHS); 1011 StringInit *Delim = dyn_cast<StringInit>(RHS); 1012 if (List && Delim) { 1013 StringInit *Result; 1014 if (isa<StringRecTy>(List->getElementType())) 1015 Result = interleaveStringList(List, Delim); 1016 else 1017 Result = interleaveIntList(List, Delim); 1018 if (Result) 1019 return Result; 1020 } 1021 break; 1022 } 1023 case EQ: 1024 case NE: 1025 case LE: 1026 case LT: 1027 case GE: 1028 case GT: { 1029 // First see if we have two bit, bits, or int. 1030 IntInit *LHSi = 1031 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get())); 1032 IntInit *RHSi = 1033 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get())); 1034 1035 if (LHSi && RHSi) { 1036 bool Result; 1037 switch (getOpcode()) { 1038 case EQ: Result = LHSi->getValue() == RHSi->getValue(); break; 1039 case NE: Result = LHSi->getValue() != RHSi->getValue(); break; 1040 case LE: Result = LHSi->getValue() <= RHSi->getValue(); break; 1041 case LT: Result = LHSi->getValue() < RHSi->getValue(); break; 1042 case GE: Result = LHSi->getValue() >= RHSi->getValue(); break; 1043 case GT: Result = LHSi->getValue() > RHSi->getValue(); break; 1044 default: llvm_unreachable("unhandled comparison"); 1045 } 1046 return BitInit::get(Result); 1047 } 1048 1049 // Next try strings. 1050 StringInit *LHSs = dyn_cast<StringInit>(LHS); 1051 StringInit *RHSs = dyn_cast<StringInit>(RHS); 1052 1053 if (LHSs && RHSs) { 1054 bool Result; 1055 switch (getOpcode()) { 1056 case EQ: Result = LHSs->getValue() == RHSs->getValue(); break; 1057 case NE: Result = LHSs->getValue() != RHSs->getValue(); break; 1058 case LE: Result = LHSs->getValue() <= RHSs->getValue(); break; 1059 case LT: Result = LHSs->getValue() < RHSs->getValue(); break; 1060 case GE: Result = LHSs->getValue() >= RHSs->getValue(); break; 1061 case GT: Result = LHSs->getValue() > RHSs->getValue(); break; 1062 default: llvm_unreachable("unhandled comparison"); 1063 } 1064 return BitInit::get(Result); 1065 } 1066 1067 // Finally, !eq and !ne can be used with records. 1068 if (getOpcode() == EQ || getOpcode() == NE) { 1069 DefInit *LHSd = dyn_cast<DefInit>(LHS); 1070 DefInit *RHSd = dyn_cast<DefInit>(RHS); 1071 if (LHSd && RHSd) 1072 return BitInit::get((getOpcode() == EQ) ? LHSd == RHSd 1073 : LHSd != RHSd); 1074 } 1075 1076 break; 1077 } 1078 case SETDAGOP: { 1079 DagInit *Dag = dyn_cast<DagInit>(LHS); 1080 DefInit *Op = dyn_cast<DefInit>(RHS); 1081 if (Dag && Op) { 1082 SmallVector<Init*, 8> Args; 1083 SmallVector<StringInit*, 8> ArgNames; 1084 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) { 1085 Args.push_back(Dag->getArg(i)); 1086 ArgNames.push_back(Dag->getArgName(i)); 1087 } 1088 return DagInit::get(Op, nullptr, Args, ArgNames); 1089 } 1090 break; 1091 } 1092 case ADD: 1093 case SUB: 1094 case MUL: 1095 case AND: 1096 case OR: 1097 case XOR: 1098 case SHL: 1099 case SRA: 1100 case SRL: { 1101 IntInit *LHSi = 1102 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get())); 1103 IntInit *RHSi = 1104 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get())); 1105 if (LHSi && RHSi) { 1106 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue(); 1107 int64_t Result; 1108 switch (getOpcode()) { 1109 default: llvm_unreachable("Bad opcode!"); 1110 case ADD: Result = LHSv + RHSv; break; 1111 case SUB: Result = LHSv - RHSv; break; 1112 case MUL: Result = LHSv * RHSv; break; 1113 case AND: Result = LHSv & RHSv; break; 1114 case OR: Result = LHSv | RHSv; break; 1115 case XOR: Result = LHSv ^ RHSv; break; 1116 case SHL: Result = (uint64_t)LHSv << (uint64_t)RHSv; break; 1117 case SRA: Result = LHSv >> RHSv; break; 1118 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break; 1119 } 1120 return IntInit::get(Result); 1121 } 1122 break; 1123 } 1124 } 1125 return const_cast<BinOpInit *>(this); 1126 } 1127 1128 Init *BinOpInit::resolveReferences(Resolver &R) const { 1129 Init *lhs = LHS->resolveReferences(R); 1130 Init *rhs = RHS->resolveReferences(R); 1131 1132 if (LHS != lhs || RHS != rhs) 1133 return (BinOpInit::get(getOpcode(), lhs, rhs, getType())) 1134 ->Fold(R.getCurrentRecord()); 1135 return const_cast<BinOpInit *>(this); 1136 } 1137 1138 std::string BinOpInit::getAsString() const { 1139 std::string Result; 1140 switch (getOpcode()) { 1141 case CONCAT: Result = "!con"; break; 1142 case ADD: Result = "!add"; break; 1143 case SUB: Result = "!sub"; break; 1144 case MUL: Result = "!mul"; break; 1145 case AND: Result = "!and"; break; 1146 case OR: Result = "!or"; break; 1147 case XOR: Result = "!xor"; break; 1148 case SHL: Result = "!shl"; break; 1149 case SRA: Result = "!sra"; break; 1150 case SRL: Result = "!srl"; break; 1151 case EQ: Result = "!eq"; break; 1152 case NE: Result = "!ne"; break; 1153 case LE: Result = "!le"; break; 1154 case LT: Result = "!lt"; break; 1155 case GE: Result = "!ge"; break; 1156 case GT: Result = "!gt"; break; 1157 case LISTCONCAT: Result = "!listconcat"; break; 1158 case LISTSPLAT: Result = "!listsplat"; break; 1159 case STRCONCAT: Result = "!strconcat"; break; 1160 case INTERLEAVE: Result = "!interleave"; break; 1161 case SETDAGOP: Result = "!setdagop"; break; 1162 } 1163 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")"; 1164 } 1165 1166 static void 1167 ProfileTernOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *MHS, 1168 Init *RHS, RecTy *Type) { 1169 ID.AddInteger(Opcode); 1170 ID.AddPointer(LHS); 1171 ID.AddPointer(MHS); 1172 ID.AddPointer(RHS); 1173 ID.AddPointer(Type); 1174 } 1175 1176 TernOpInit *TernOpInit::get(TernaryOp Opc, Init *LHS, Init *MHS, Init *RHS, 1177 RecTy *Type) { 1178 static FoldingSet<TernOpInit> ThePool; 1179 1180 FoldingSetNodeID ID; 1181 ProfileTernOpInit(ID, Opc, LHS, MHS, RHS, Type); 1182 1183 void *IP = nullptr; 1184 if (TernOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP)) 1185 return I; 1186 1187 TernOpInit *I = new(Allocator) TernOpInit(Opc, LHS, MHS, RHS, Type); 1188 ThePool.InsertNode(I, IP); 1189 return I; 1190 } 1191 1192 void TernOpInit::Profile(FoldingSetNodeID &ID) const { 1193 ProfileTernOpInit(ID, getOpcode(), getLHS(), getMHS(), getRHS(), getType()); 1194 } 1195 1196 static Init *ItemApply(Init *LHS, Init *MHSe, Init *RHS, Record *CurRec) { 1197 MapResolver R(CurRec); 1198 R.set(LHS, MHSe); 1199 return RHS->resolveReferences(R); 1200 } 1201 1202 static Init *ForeachDagApply(Init *LHS, DagInit *MHSd, Init *RHS, 1203 Record *CurRec) { 1204 bool Change = false; 1205 Init *Val = ItemApply(LHS, MHSd->getOperator(), RHS, CurRec); 1206 if (Val != MHSd->getOperator()) 1207 Change = true; 1208 1209 SmallVector<std::pair<Init *, StringInit *>, 8> NewArgs; 1210 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) { 1211 Init *Arg = MHSd->getArg(i); 1212 Init *NewArg; 1213 StringInit *ArgName = MHSd->getArgName(i); 1214 1215 if (DagInit *Argd = dyn_cast<DagInit>(Arg)) 1216 NewArg = ForeachDagApply(LHS, Argd, RHS, CurRec); 1217 else 1218 NewArg = ItemApply(LHS, Arg, RHS, CurRec); 1219 1220 NewArgs.push_back(std::make_pair(NewArg, ArgName)); 1221 if (Arg != NewArg) 1222 Change = true; 1223 } 1224 1225 if (Change) 1226 return DagInit::get(Val, nullptr, NewArgs); 1227 return MHSd; 1228 } 1229 1230 // Applies RHS to all elements of MHS, using LHS as a temp variable. 1231 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type, 1232 Record *CurRec) { 1233 if (DagInit *MHSd = dyn_cast<DagInit>(MHS)) 1234 return ForeachDagApply(LHS, MHSd, RHS, CurRec); 1235 1236 if (ListInit *MHSl = dyn_cast<ListInit>(MHS)) { 1237 SmallVector<Init *, 8> NewList(MHSl->begin(), MHSl->end()); 1238 1239 for (Init *&Item : NewList) { 1240 Init *NewItem = ItemApply(LHS, Item, RHS, CurRec); 1241 if (NewItem != Item) 1242 Item = NewItem; 1243 } 1244 return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType()); 1245 } 1246 1247 return nullptr; 1248 } 1249 1250 // Evaluates RHS for all elements of MHS, using LHS as a temp variable. 1251 // Creates a new list with the elements that evaluated to true. 1252 static Init *FilterHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type, 1253 Record *CurRec) { 1254 if (ListInit *MHSl = dyn_cast<ListInit>(MHS)) { 1255 SmallVector<Init *, 8> NewList; 1256 1257 for (Init *Item : MHSl->getValues()) { 1258 Init *Include = ItemApply(LHS, Item, RHS, CurRec); 1259 if (!Include) 1260 return nullptr; 1261 if (IntInit *IncludeInt = dyn_cast_or_null<IntInit>( 1262 Include->convertInitializerTo(IntRecTy::get()))) { 1263 if (IncludeInt->getValue()) 1264 NewList.push_back(Item); 1265 } else { 1266 return nullptr; 1267 } 1268 } 1269 return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType()); 1270 } 1271 1272 return nullptr; 1273 } 1274 1275 Init *TernOpInit::Fold(Record *CurRec) const { 1276 switch (getOpcode()) { 1277 case SUBST: { 1278 DefInit *LHSd = dyn_cast<DefInit>(LHS); 1279 VarInit *LHSv = dyn_cast<VarInit>(LHS); 1280 StringInit *LHSs = dyn_cast<StringInit>(LHS); 1281 1282 DefInit *MHSd = dyn_cast<DefInit>(MHS); 1283 VarInit *MHSv = dyn_cast<VarInit>(MHS); 1284 StringInit *MHSs = dyn_cast<StringInit>(MHS); 1285 1286 DefInit *RHSd = dyn_cast<DefInit>(RHS); 1287 VarInit *RHSv = dyn_cast<VarInit>(RHS); 1288 StringInit *RHSs = dyn_cast<StringInit>(RHS); 1289 1290 if (LHSd && MHSd && RHSd) { 1291 Record *Val = RHSd->getDef(); 1292 if (LHSd->getAsString() == RHSd->getAsString()) 1293 Val = MHSd->getDef(); 1294 return DefInit::get(Val); 1295 } 1296 if (LHSv && MHSv && RHSv) { 1297 std::string Val = std::string(RHSv->getName()); 1298 if (LHSv->getAsString() == RHSv->getAsString()) 1299 Val = std::string(MHSv->getName()); 1300 return VarInit::get(Val, getType()); 1301 } 1302 if (LHSs && MHSs && RHSs) { 1303 std::string Val = std::string(RHSs->getValue()); 1304 1305 std::string::size_type found; 1306 std::string::size_type idx = 0; 1307 while (true) { 1308 found = Val.find(std::string(LHSs->getValue()), idx); 1309 if (found == std::string::npos) 1310 break; 1311 Val.replace(found, LHSs->getValue().size(), 1312 std::string(MHSs->getValue())); 1313 idx = found + MHSs->getValue().size(); 1314 } 1315 1316 return StringInit::get(Val); 1317 } 1318 break; 1319 } 1320 1321 case FOREACH: { 1322 if (Init *Result = ForeachHelper(LHS, MHS, RHS, getType(), CurRec)) 1323 return Result; 1324 break; 1325 } 1326 1327 case FILTER: { 1328 if (Init *Result = FilterHelper(LHS, MHS, RHS, getType(), CurRec)) 1329 return Result; 1330 break; 1331 } 1332 1333 case IF: { 1334 if (IntInit *LHSi = dyn_cast_or_null<IntInit>( 1335 LHS->convertInitializerTo(IntRecTy::get()))) { 1336 if (LHSi->getValue()) 1337 return MHS; 1338 return RHS; 1339 } 1340 break; 1341 } 1342 1343 case DAG: { 1344 ListInit *MHSl = dyn_cast<ListInit>(MHS); 1345 ListInit *RHSl = dyn_cast<ListInit>(RHS); 1346 bool MHSok = MHSl || isa<UnsetInit>(MHS); 1347 bool RHSok = RHSl || isa<UnsetInit>(RHS); 1348 1349 if (isa<UnsetInit>(MHS) && isa<UnsetInit>(RHS)) 1350 break; // Typically prevented by the parser, but might happen with template args 1351 1352 if (MHSok && RHSok && (!MHSl || !RHSl || MHSl->size() == RHSl->size())) { 1353 SmallVector<std::pair<Init *, StringInit *>, 8> Children; 1354 unsigned Size = MHSl ? MHSl->size() : RHSl->size(); 1355 for (unsigned i = 0; i != Size; ++i) { 1356 Init *Node = MHSl ? MHSl->getElement(i) : UnsetInit::get(); 1357 Init *Name = RHSl ? RHSl->getElement(i) : UnsetInit::get(); 1358 if (!isa<StringInit>(Name) && !isa<UnsetInit>(Name)) 1359 return const_cast<TernOpInit *>(this); 1360 Children.emplace_back(Node, dyn_cast<StringInit>(Name)); 1361 } 1362 return DagInit::get(LHS, nullptr, Children); 1363 } 1364 break; 1365 } 1366 1367 case SUBSTR: { 1368 StringInit *LHSs = dyn_cast<StringInit>(LHS); 1369 IntInit *MHSi = dyn_cast<IntInit>(MHS); 1370 IntInit *RHSi = dyn_cast<IntInit>(RHS); 1371 if (LHSs && MHSi && RHSi) { 1372 int64_t StringSize = LHSs->getValue().size(); 1373 int64_t Start = MHSi->getValue(); 1374 int64_t Length = RHSi->getValue(); 1375 if (Start < 0 || Start > StringSize) 1376 PrintError(CurRec->getLoc(), 1377 Twine("!substr start position is out of range 0...") + 1378 std::to_string(StringSize) + ": " + 1379 std::to_string(Start)); 1380 if (Length < 0) 1381 PrintError(CurRec->getLoc(), "!substr length must be nonnegative"); 1382 return StringInit::get(LHSs->getValue().substr(Start, Length), 1383 LHSs->getFormat()); 1384 } 1385 break; 1386 } 1387 } 1388 1389 return const_cast<TernOpInit *>(this); 1390 } 1391 1392 Init *TernOpInit::resolveReferences(Resolver &R) const { 1393 Init *lhs = LHS->resolveReferences(R); 1394 1395 if (getOpcode() == IF && lhs != LHS) { 1396 if (IntInit *Value = dyn_cast_or_null<IntInit>( 1397 lhs->convertInitializerTo(IntRecTy::get()))) { 1398 // Short-circuit 1399 if (Value->getValue()) 1400 return MHS->resolveReferences(R); 1401 return RHS->resolveReferences(R); 1402 } 1403 } 1404 1405 Init *mhs = MHS->resolveReferences(R); 1406 Init *rhs; 1407 1408 if (getOpcode() == FOREACH || getOpcode() == FILTER) { 1409 ShadowResolver SR(R); 1410 SR.addShadow(lhs); 1411 rhs = RHS->resolveReferences(SR); 1412 } else { 1413 rhs = RHS->resolveReferences(R); 1414 } 1415 1416 if (LHS != lhs || MHS != mhs || RHS != rhs) 1417 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs, getType())) 1418 ->Fold(R.getCurrentRecord()); 1419 return const_cast<TernOpInit *>(this); 1420 } 1421 1422 std::string TernOpInit::getAsString() const { 1423 std::string Result; 1424 bool UnquotedLHS = false; 1425 switch (getOpcode()) { 1426 case DAG: Result = "!dag"; break; 1427 case FILTER: Result = "!filter"; UnquotedLHS = true; break; 1428 case FOREACH: Result = "!foreach"; UnquotedLHS = true; break; 1429 case IF: Result = "!if"; break; 1430 case SUBST: Result = "!subst"; break; 1431 case SUBSTR: Result = "!substr"; break; 1432 } 1433 return (Result + "(" + 1434 (UnquotedLHS ? LHS->getAsUnquotedString() : LHS->getAsString()) + 1435 ", " + MHS->getAsString() + ", " + RHS->getAsString() + ")"); 1436 } 1437 1438 static void ProfileFoldOpInit(FoldingSetNodeID &ID, Init *A, Init *B, 1439 Init *Start, Init *List, Init *Expr, 1440 RecTy *Type) { 1441 ID.AddPointer(Start); 1442 ID.AddPointer(List); 1443 ID.AddPointer(A); 1444 ID.AddPointer(B); 1445 ID.AddPointer(Expr); 1446 ID.AddPointer(Type); 1447 } 1448 1449 FoldOpInit *FoldOpInit::get(Init *Start, Init *List, Init *A, Init *B, 1450 Init *Expr, RecTy *Type) { 1451 static FoldingSet<FoldOpInit> ThePool; 1452 1453 FoldingSetNodeID ID; 1454 ProfileFoldOpInit(ID, Start, List, A, B, Expr, Type); 1455 1456 void *IP = nullptr; 1457 if (FoldOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP)) 1458 return I; 1459 1460 FoldOpInit *I = new (Allocator) FoldOpInit(Start, List, A, B, Expr, Type); 1461 ThePool.InsertNode(I, IP); 1462 return I; 1463 } 1464 1465 void FoldOpInit::Profile(FoldingSetNodeID &ID) const { 1466 ProfileFoldOpInit(ID, Start, List, A, B, Expr, getType()); 1467 } 1468 1469 Init *FoldOpInit::Fold(Record *CurRec) const { 1470 if (ListInit *LI = dyn_cast<ListInit>(List)) { 1471 Init *Accum = Start; 1472 for (Init *Elt : *LI) { 1473 MapResolver R(CurRec); 1474 R.set(A, Accum); 1475 R.set(B, Elt); 1476 Accum = Expr->resolveReferences(R); 1477 } 1478 return Accum; 1479 } 1480 return const_cast<FoldOpInit *>(this); 1481 } 1482 1483 Init *FoldOpInit::resolveReferences(Resolver &R) const { 1484 Init *NewStart = Start->resolveReferences(R); 1485 Init *NewList = List->resolveReferences(R); 1486 ShadowResolver SR(R); 1487 SR.addShadow(A); 1488 SR.addShadow(B); 1489 Init *NewExpr = Expr->resolveReferences(SR); 1490 1491 if (Start == NewStart && List == NewList && Expr == NewExpr) 1492 return const_cast<FoldOpInit *>(this); 1493 1494 return get(NewStart, NewList, A, B, NewExpr, getType()) 1495 ->Fold(R.getCurrentRecord()); 1496 } 1497 1498 Init *FoldOpInit::getBit(unsigned Bit) const { 1499 return VarBitInit::get(const_cast<FoldOpInit *>(this), Bit); 1500 } 1501 1502 std::string FoldOpInit::getAsString() const { 1503 return (Twine("!foldl(") + Start->getAsString() + ", " + List->getAsString() + 1504 ", " + A->getAsUnquotedString() + ", " + B->getAsUnquotedString() + 1505 ", " + Expr->getAsString() + ")") 1506 .str(); 1507 } 1508 1509 static void ProfileIsAOpInit(FoldingSetNodeID &ID, RecTy *CheckType, 1510 Init *Expr) { 1511 ID.AddPointer(CheckType); 1512 ID.AddPointer(Expr); 1513 } 1514 1515 IsAOpInit *IsAOpInit::get(RecTy *CheckType, Init *Expr) { 1516 static FoldingSet<IsAOpInit> ThePool; 1517 1518 FoldingSetNodeID ID; 1519 ProfileIsAOpInit(ID, CheckType, Expr); 1520 1521 void *IP = nullptr; 1522 if (IsAOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP)) 1523 return I; 1524 1525 IsAOpInit *I = new (Allocator) IsAOpInit(CheckType, Expr); 1526 ThePool.InsertNode(I, IP); 1527 return I; 1528 } 1529 1530 void IsAOpInit::Profile(FoldingSetNodeID &ID) const { 1531 ProfileIsAOpInit(ID, CheckType, Expr); 1532 } 1533 1534 Init *IsAOpInit::Fold() const { 1535 if (TypedInit *TI = dyn_cast<TypedInit>(Expr)) { 1536 // Is the expression type known to be (a subclass of) the desired type? 1537 if (TI->getType()->typeIsConvertibleTo(CheckType)) 1538 return IntInit::get(1); 1539 1540 if (isa<RecordRecTy>(CheckType)) { 1541 // If the target type is not a subclass of the expression type, or if 1542 // the expression has fully resolved to a record, we know that it can't 1543 // be of the required type. 1544 if (!CheckType->typeIsConvertibleTo(TI->getType()) || isa<DefInit>(Expr)) 1545 return IntInit::get(0); 1546 } else { 1547 // We treat non-record types as not castable. 1548 return IntInit::get(0); 1549 } 1550 } 1551 return const_cast<IsAOpInit *>(this); 1552 } 1553 1554 Init *IsAOpInit::resolveReferences(Resolver &R) const { 1555 Init *NewExpr = Expr->resolveReferences(R); 1556 if (Expr != NewExpr) 1557 return get(CheckType, NewExpr)->Fold(); 1558 return const_cast<IsAOpInit *>(this); 1559 } 1560 1561 Init *IsAOpInit::getBit(unsigned Bit) const { 1562 return VarBitInit::get(const_cast<IsAOpInit *>(this), Bit); 1563 } 1564 1565 std::string IsAOpInit::getAsString() const { 1566 return (Twine("!isa<") + CheckType->getAsString() + ">(" + 1567 Expr->getAsString() + ")") 1568 .str(); 1569 } 1570 1571 RecTy *TypedInit::getFieldType(StringInit *FieldName) const { 1572 if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType())) { 1573 for (Record *Rec : RecordType->getClasses()) { 1574 if (RecordVal *Field = Rec->getValue(FieldName)) 1575 return Field->getType(); 1576 } 1577 } 1578 return nullptr; 1579 } 1580 1581 Init * 1582 TypedInit::convertInitializerTo(RecTy *Ty) const { 1583 if (getType() == Ty || getType()->typeIsA(Ty)) 1584 return const_cast<TypedInit *>(this); 1585 1586 if (isa<BitRecTy>(getType()) && isa<BitsRecTy>(Ty) && 1587 cast<BitsRecTy>(Ty)->getNumBits() == 1) 1588 return BitsInit::get({const_cast<TypedInit *>(this)}); 1589 1590 return nullptr; 1591 } 1592 1593 Init *TypedInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const { 1594 BitsRecTy *T = dyn_cast<BitsRecTy>(getType()); 1595 if (!T) return nullptr; // Cannot subscript a non-bits variable. 1596 unsigned NumBits = T->getNumBits(); 1597 1598 SmallVector<Init *, 16> NewBits; 1599 NewBits.reserve(Bits.size()); 1600 for (unsigned Bit : Bits) { 1601 if (Bit >= NumBits) 1602 return nullptr; 1603 1604 NewBits.push_back(VarBitInit::get(const_cast<TypedInit *>(this), Bit)); 1605 } 1606 return BitsInit::get(NewBits); 1607 } 1608 1609 Init *TypedInit::getCastTo(RecTy *Ty) const { 1610 // Handle the common case quickly 1611 if (getType() == Ty || getType()->typeIsA(Ty)) 1612 return const_cast<TypedInit *>(this); 1613 1614 if (Init *Converted = convertInitializerTo(Ty)) { 1615 assert(!isa<TypedInit>(Converted) || 1616 cast<TypedInit>(Converted)->getType()->typeIsA(Ty)); 1617 return Converted; 1618 } 1619 1620 if (!getType()->typeIsConvertibleTo(Ty)) 1621 return nullptr; 1622 1623 return UnOpInit::get(UnOpInit::CAST, const_cast<TypedInit *>(this), Ty) 1624 ->Fold(nullptr); 1625 } 1626 1627 Init *TypedInit::convertInitListSlice(ArrayRef<unsigned> Elements) const { 1628 ListRecTy *T = dyn_cast<ListRecTy>(getType()); 1629 if (!T) return nullptr; // Cannot subscript a non-list variable. 1630 1631 if (Elements.size() == 1) 1632 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]); 1633 1634 SmallVector<Init*, 8> ListInits; 1635 ListInits.reserve(Elements.size()); 1636 for (unsigned Element : Elements) 1637 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this), 1638 Element)); 1639 return ListInit::get(ListInits, T->getElementType()); 1640 } 1641 1642 1643 VarInit *VarInit::get(StringRef VN, RecTy *T) { 1644 Init *Value = StringInit::get(VN); 1645 return VarInit::get(Value, T); 1646 } 1647 1648 VarInit *VarInit::get(Init *VN, RecTy *T) { 1649 using Key = std::pair<RecTy *, Init *>; 1650 static DenseMap<Key, VarInit*> ThePool; 1651 1652 Key TheKey(std::make_pair(T, VN)); 1653 1654 VarInit *&I = ThePool[TheKey]; 1655 if (!I) 1656 I = new(Allocator) VarInit(VN, T); 1657 return I; 1658 } 1659 1660 StringRef VarInit::getName() const { 1661 StringInit *NameString = cast<StringInit>(getNameInit()); 1662 return NameString->getValue(); 1663 } 1664 1665 Init *VarInit::getBit(unsigned Bit) const { 1666 if (getType() == BitRecTy::get()) 1667 return const_cast<VarInit*>(this); 1668 return VarBitInit::get(const_cast<VarInit*>(this), Bit); 1669 } 1670 1671 Init *VarInit::resolveReferences(Resolver &R) const { 1672 if (Init *Val = R.resolve(VarName)) 1673 return Val; 1674 return const_cast<VarInit *>(this); 1675 } 1676 1677 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) { 1678 using Key = std::pair<TypedInit *, unsigned>; 1679 static DenseMap<Key, VarBitInit*> ThePool; 1680 1681 Key TheKey(std::make_pair(T, B)); 1682 1683 VarBitInit *&I = ThePool[TheKey]; 1684 if (!I) 1685 I = new(Allocator) VarBitInit(T, B); 1686 return I; 1687 } 1688 1689 std::string VarBitInit::getAsString() const { 1690 return TI->getAsString() + "{" + utostr(Bit) + "}"; 1691 } 1692 1693 Init *VarBitInit::resolveReferences(Resolver &R) const { 1694 Init *I = TI->resolveReferences(R); 1695 if (TI != I) 1696 return I->getBit(getBitNum()); 1697 1698 return const_cast<VarBitInit*>(this); 1699 } 1700 1701 VarListElementInit *VarListElementInit::get(TypedInit *T, 1702 unsigned E) { 1703 using Key = std::pair<TypedInit *, unsigned>; 1704 static DenseMap<Key, VarListElementInit*> ThePool; 1705 1706 Key TheKey(std::make_pair(T, E)); 1707 1708 VarListElementInit *&I = ThePool[TheKey]; 1709 if (!I) I = new(Allocator) VarListElementInit(T, E); 1710 return I; 1711 } 1712 1713 std::string VarListElementInit::getAsString() const { 1714 return TI->getAsString() + "[" + utostr(Element) + "]"; 1715 } 1716 1717 Init *VarListElementInit::resolveReferences(Resolver &R) const { 1718 Init *NewTI = TI->resolveReferences(R); 1719 if (ListInit *List = dyn_cast<ListInit>(NewTI)) { 1720 // Leave out-of-bounds array references as-is. This can happen without 1721 // being an error, e.g. in the untaken "branch" of an !if expression. 1722 if (getElementNum() < List->size()) 1723 return List->getElement(getElementNum()); 1724 } 1725 if (NewTI != TI && isa<TypedInit>(NewTI)) 1726 return VarListElementInit::get(cast<TypedInit>(NewTI), getElementNum()); 1727 return const_cast<VarListElementInit *>(this); 1728 } 1729 1730 Init *VarListElementInit::getBit(unsigned Bit) const { 1731 if (getType() == BitRecTy::get()) 1732 return const_cast<VarListElementInit*>(this); 1733 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit); 1734 } 1735 1736 DefInit::DefInit(Record *D) 1737 : TypedInit(IK_DefInit, D->getType()), Def(D) {} 1738 1739 DefInit *DefInit::get(Record *R) { 1740 return R->getDefInit(); 1741 } 1742 1743 Init *DefInit::convertInitializerTo(RecTy *Ty) const { 1744 if (auto *RRT = dyn_cast<RecordRecTy>(Ty)) 1745 if (getType()->typeIsConvertibleTo(RRT)) 1746 return const_cast<DefInit *>(this); 1747 return nullptr; 1748 } 1749 1750 RecTy *DefInit::getFieldType(StringInit *FieldName) const { 1751 if (const RecordVal *RV = Def->getValue(FieldName)) 1752 return RV->getType(); 1753 return nullptr; 1754 } 1755 1756 std::string DefInit::getAsString() const { return std::string(Def->getName()); } 1757 1758 static void ProfileVarDefInit(FoldingSetNodeID &ID, 1759 Record *Class, 1760 ArrayRef<Init *> Args) { 1761 ID.AddInteger(Args.size()); 1762 ID.AddPointer(Class); 1763 1764 for (Init *I : Args) 1765 ID.AddPointer(I); 1766 } 1767 1768 VarDefInit *VarDefInit::get(Record *Class, ArrayRef<Init *> Args) { 1769 static FoldingSet<VarDefInit> ThePool; 1770 1771 FoldingSetNodeID ID; 1772 ProfileVarDefInit(ID, Class, Args); 1773 1774 void *IP = nullptr; 1775 if (VarDefInit *I = ThePool.FindNodeOrInsertPos(ID, IP)) 1776 return I; 1777 1778 void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Args.size()), 1779 alignof(VarDefInit)); 1780 VarDefInit *I = new(Mem) VarDefInit(Class, Args.size()); 1781 std::uninitialized_copy(Args.begin(), Args.end(), 1782 I->getTrailingObjects<Init *>()); 1783 ThePool.InsertNode(I, IP); 1784 return I; 1785 } 1786 1787 void VarDefInit::Profile(FoldingSetNodeID &ID) const { 1788 ProfileVarDefInit(ID, Class, args()); 1789 } 1790 1791 DefInit *VarDefInit::instantiate() { 1792 if (!Def) { 1793 RecordKeeper &Records = Class->getRecords(); 1794 auto NewRecOwner = std::make_unique<Record>(Records.getNewAnonymousName(), 1795 Class->getLoc(), Records, 1796 /*IsAnonymous=*/true); 1797 Record *NewRec = NewRecOwner.get(); 1798 1799 // Copy values from class to instance 1800 for (const RecordVal &Val : Class->getValues()) 1801 NewRec->addValue(Val); 1802 1803 // Copy assertions from class to instance. 1804 NewRec->appendAssertions(Class); 1805 1806 // Substitute and resolve template arguments 1807 ArrayRef<Init *> TArgs = Class->getTemplateArgs(); 1808 MapResolver R(NewRec); 1809 1810 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) { 1811 if (i < args_size()) 1812 R.set(TArgs[i], getArg(i)); 1813 else 1814 R.set(TArgs[i], NewRec->getValue(TArgs[i])->getValue()); 1815 1816 NewRec->removeValue(TArgs[i]); 1817 } 1818 1819 NewRec->resolveReferences(R); 1820 1821 // Add superclasses. 1822 ArrayRef<std::pair<Record *, SMRange>> SCs = Class->getSuperClasses(); 1823 for (const auto &SCPair : SCs) 1824 NewRec->addSuperClass(SCPair.first, SCPair.second); 1825 1826 NewRec->addSuperClass(Class, 1827 SMRange(Class->getLoc().back(), 1828 Class->getLoc().back())); 1829 1830 // Resolve internal references and store in record keeper 1831 NewRec->resolveReferences(); 1832 Records.addDef(std::move(NewRecOwner)); 1833 1834 // Check the assertions. 1835 NewRec->checkAssertions(); 1836 1837 Def = DefInit::get(NewRec); 1838 } 1839 1840 return Def; 1841 } 1842 1843 Init *VarDefInit::resolveReferences(Resolver &R) const { 1844 TrackUnresolvedResolver UR(&R); 1845 bool Changed = false; 1846 SmallVector<Init *, 8> NewArgs; 1847 NewArgs.reserve(args_size()); 1848 1849 for (Init *Arg : args()) { 1850 Init *NewArg = Arg->resolveReferences(UR); 1851 NewArgs.push_back(NewArg); 1852 Changed |= NewArg != Arg; 1853 } 1854 1855 if (Changed) { 1856 auto New = VarDefInit::get(Class, NewArgs); 1857 if (!UR.foundUnresolved()) 1858 return New->instantiate(); 1859 return New; 1860 } 1861 return const_cast<VarDefInit *>(this); 1862 } 1863 1864 Init *VarDefInit::Fold() const { 1865 if (Def) 1866 return Def; 1867 1868 TrackUnresolvedResolver R; 1869 for (Init *Arg : args()) 1870 Arg->resolveReferences(R); 1871 1872 if (!R.foundUnresolved()) 1873 return const_cast<VarDefInit *>(this)->instantiate(); 1874 return const_cast<VarDefInit *>(this); 1875 } 1876 1877 std::string VarDefInit::getAsString() const { 1878 std::string Result = Class->getNameInitAsString() + "<"; 1879 const char *sep = ""; 1880 for (Init *Arg : args()) { 1881 Result += sep; 1882 sep = ", "; 1883 Result += Arg->getAsString(); 1884 } 1885 return Result + ">"; 1886 } 1887 1888 FieldInit *FieldInit::get(Init *R, StringInit *FN) { 1889 using Key = std::pair<Init *, StringInit *>; 1890 static DenseMap<Key, FieldInit*> ThePool; 1891 1892 Key TheKey(std::make_pair(R, FN)); 1893 1894 FieldInit *&I = ThePool[TheKey]; 1895 if (!I) I = new(Allocator) FieldInit(R, FN); 1896 return I; 1897 } 1898 1899 Init *FieldInit::getBit(unsigned Bit) const { 1900 if (getType() == BitRecTy::get()) 1901 return const_cast<FieldInit*>(this); 1902 return VarBitInit::get(const_cast<FieldInit*>(this), Bit); 1903 } 1904 1905 Init *FieldInit::resolveReferences(Resolver &R) const { 1906 Init *NewRec = Rec->resolveReferences(R); 1907 if (NewRec != Rec) 1908 return FieldInit::get(NewRec, FieldName)->Fold(R.getCurrentRecord()); 1909 return const_cast<FieldInit *>(this); 1910 } 1911 1912 Init *FieldInit::Fold(Record *CurRec) const { 1913 if (DefInit *DI = dyn_cast<DefInit>(Rec)) { 1914 Record *Def = DI->getDef(); 1915 if (Def == CurRec) 1916 PrintFatalError(CurRec->getLoc(), 1917 Twine("Attempting to access field '") + 1918 FieldName->getAsUnquotedString() + "' of '" + 1919 Rec->getAsString() + "' is a forbidden self-reference"); 1920 Init *FieldVal = Def->getValue(FieldName)->getValue(); 1921 if (FieldVal->isComplete()) 1922 return FieldVal; 1923 } 1924 return const_cast<FieldInit *>(this); 1925 } 1926 1927 bool FieldInit::isConcrete() const { 1928 if (DefInit *DI = dyn_cast<DefInit>(Rec)) { 1929 Init *FieldVal = DI->getDef()->getValue(FieldName)->getValue(); 1930 return FieldVal->isConcrete(); 1931 } 1932 return false; 1933 } 1934 1935 static void ProfileCondOpInit(FoldingSetNodeID &ID, 1936 ArrayRef<Init *> CondRange, 1937 ArrayRef<Init *> ValRange, 1938 const RecTy *ValType) { 1939 assert(CondRange.size() == ValRange.size() && 1940 "Number of conditions and values must match!"); 1941 ID.AddPointer(ValType); 1942 ArrayRef<Init *>::iterator Case = CondRange.begin(); 1943 ArrayRef<Init *>::iterator Val = ValRange.begin(); 1944 1945 while (Case != CondRange.end()) { 1946 ID.AddPointer(*Case++); 1947 ID.AddPointer(*Val++); 1948 } 1949 } 1950 1951 void CondOpInit::Profile(FoldingSetNodeID &ID) const { 1952 ProfileCondOpInit(ID, 1953 makeArrayRef(getTrailingObjects<Init *>(), NumConds), 1954 makeArrayRef(getTrailingObjects<Init *>() + NumConds, NumConds), 1955 ValType); 1956 } 1957 1958 CondOpInit * 1959 CondOpInit::get(ArrayRef<Init *> CondRange, 1960 ArrayRef<Init *> ValRange, RecTy *Ty) { 1961 assert(CondRange.size() == ValRange.size() && 1962 "Number of conditions and values must match!"); 1963 1964 static FoldingSet<CondOpInit> ThePool; 1965 FoldingSetNodeID ID; 1966 ProfileCondOpInit(ID, CondRange, ValRange, Ty); 1967 1968 void *IP = nullptr; 1969 if (CondOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP)) 1970 return I; 1971 1972 void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(2*CondRange.size()), 1973 alignof(BitsInit)); 1974 CondOpInit *I = new(Mem) CondOpInit(CondRange.size(), Ty); 1975 1976 std::uninitialized_copy(CondRange.begin(), CondRange.end(), 1977 I->getTrailingObjects<Init *>()); 1978 std::uninitialized_copy(ValRange.begin(), ValRange.end(), 1979 I->getTrailingObjects<Init *>()+CondRange.size()); 1980 ThePool.InsertNode(I, IP); 1981 return I; 1982 } 1983 1984 Init *CondOpInit::resolveReferences(Resolver &R) const { 1985 SmallVector<Init*, 4> NewConds; 1986 bool Changed = false; 1987 for (const Init *Case : getConds()) { 1988 Init *NewCase = Case->resolveReferences(R); 1989 NewConds.push_back(NewCase); 1990 Changed |= NewCase != Case; 1991 } 1992 1993 SmallVector<Init*, 4> NewVals; 1994 for (const Init *Val : getVals()) { 1995 Init *NewVal = Val->resolveReferences(R); 1996 NewVals.push_back(NewVal); 1997 Changed |= NewVal != Val; 1998 } 1999 2000 if (Changed) 2001 return (CondOpInit::get(NewConds, NewVals, 2002 getValType()))->Fold(R.getCurrentRecord()); 2003 2004 return const_cast<CondOpInit *>(this); 2005 } 2006 2007 Init *CondOpInit::Fold(Record *CurRec) const { 2008 for ( unsigned i = 0; i < NumConds; ++i) { 2009 Init *Cond = getCond(i); 2010 Init *Val = getVal(i); 2011 2012 if (IntInit *CondI = dyn_cast_or_null<IntInit>( 2013 Cond->convertInitializerTo(IntRecTy::get()))) { 2014 if (CondI->getValue()) 2015 return Val->convertInitializerTo(getValType()); 2016 } else 2017 return const_cast<CondOpInit *>(this); 2018 } 2019 2020 PrintFatalError(CurRec->getLoc(), 2021 CurRec->getName() + 2022 " does not have any true condition in:" + 2023 this->getAsString()); 2024 return nullptr; 2025 } 2026 2027 bool CondOpInit::isConcrete() const { 2028 for (const Init *Case : getConds()) 2029 if (!Case->isConcrete()) 2030 return false; 2031 2032 for (const Init *Val : getVals()) 2033 if (!Val->isConcrete()) 2034 return false; 2035 2036 return true; 2037 } 2038 2039 bool CondOpInit::isComplete() const { 2040 for (const Init *Case : getConds()) 2041 if (!Case->isComplete()) 2042 return false; 2043 2044 for (const Init *Val : getVals()) 2045 if (!Val->isConcrete()) 2046 return false; 2047 2048 return true; 2049 } 2050 2051 std::string CondOpInit::getAsString() const { 2052 std::string Result = "!cond("; 2053 for (unsigned i = 0; i < getNumConds(); i++) { 2054 Result += getCond(i)->getAsString() + ": "; 2055 Result += getVal(i)->getAsString(); 2056 if (i != getNumConds()-1) 2057 Result += ", "; 2058 } 2059 return Result + ")"; 2060 } 2061 2062 Init *CondOpInit::getBit(unsigned Bit) const { 2063 return VarBitInit::get(const_cast<CondOpInit *>(this), Bit); 2064 } 2065 2066 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, StringInit *VN, 2067 ArrayRef<Init *> ArgRange, 2068 ArrayRef<StringInit *> NameRange) { 2069 ID.AddPointer(V); 2070 ID.AddPointer(VN); 2071 2072 ArrayRef<Init *>::iterator Arg = ArgRange.begin(); 2073 ArrayRef<StringInit *>::iterator Name = NameRange.begin(); 2074 while (Arg != ArgRange.end()) { 2075 assert(Name != NameRange.end() && "Arg name underflow!"); 2076 ID.AddPointer(*Arg++); 2077 ID.AddPointer(*Name++); 2078 } 2079 assert(Name == NameRange.end() && "Arg name overflow!"); 2080 } 2081 2082 DagInit * 2083 DagInit::get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange, 2084 ArrayRef<StringInit *> NameRange) { 2085 static FoldingSet<DagInit> ThePool; 2086 2087 FoldingSetNodeID ID; 2088 ProfileDagInit(ID, V, VN, ArgRange, NameRange); 2089 2090 void *IP = nullptr; 2091 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP)) 2092 return I; 2093 2094 void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *, StringInit *>(ArgRange.size(), NameRange.size()), alignof(BitsInit)); 2095 DagInit *I = new(Mem) DagInit(V, VN, ArgRange.size(), NameRange.size()); 2096 std::uninitialized_copy(ArgRange.begin(), ArgRange.end(), 2097 I->getTrailingObjects<Init *>()); 2098 std::uninitialized_copy(NameRange.begin(), NameRange.end(), 2099 I->getTrailingObjects<StringInit *>()); 2100 ThePool.InsertNode(I, IP); 2101 return I; 2102 } 2103 2104 DagInit * 2105 DagInit::get(Init *V, StringInit *VN, 2106 ArrayRef<std::pair<Init*, StringInit*>> args) { 2107 SmallVector<Init *, 8> Args; 2108 SmallVector<StringInit *, 8> Names; 2109 2110 for (const auto &Arg : args) { 2111 Args.push_back(Arg.first); 2112 Names.push_back(Arg.second); 2113 } 2114 2115 return DagInit::get(V, VN, Args, Names); 2116 } 2117 2118 void DagInit::Profile(FoldingSetNodeID &ID) const { 2119 ProfileDagInit(ID, Val, ValName, makeArrayRef(getTrailingObjects<Init *>(), NumArgs), makeArrayRef(getTrailingObjects<StringInit *>(), NumArgNames)); 2120 } 2121 2122 Record *DagInit::getOperatorAsDef(ArrayRef<SMLoc> Loc) const { 2123 if (DefInit *DefI = dyn_cast<DefInit>(Val)) 2124 return DefI->getDef(); 2125 PrintFatalError(Loc, "Expected record as operator"); 2126 return nullptr; 2127 } 2128 2129 Init *DagInit::resolveReferences(Resolver &R) const { 2130 SmallVector<Init*, 8> NewArgs; 2131 NewArgs.reserve(arg_size()); 2132 bool ArgsChanged = false; 2133 for (const Init *Arg : getArgs()) { 2134 Init *NewArg = Arg->resolveReferences(R); 2135 NewArgs.push_back(NewArg); 2136 ArgsChanged |= NewArg != Arg; 2137 } 2138 2139 Init *Op = Val->resolveReferences(R); 2140 if (Op != Val || ArgsChanged) 2141 return DagInit::get(Op, ValName, NewArgs, getArgNames()); 2142 2143 return const_cast<DagInit *>(this); 2144 } 2145 2146 bool DagInit::isConcrete() const { 2147 if (!Val->isConcrete()) 2148 return false; 2149 for (const Init *Elt : getArgs()) { 2150 if (!Elt->isConcrete()) 2151 return false; 2152 } 2153 return true; 2154 } 2155 2156 std::string DagInit::getAsString() const { 2157 std::string Result = "(" + Val->getAsString(); 2158 if (ValName) 2159 Result += ":" + ValName->getAsUnquotedString(); 2160 if (!arg_empty()) { 2161 Result += " " + getArg(0)->getAsString(); 2162 if (getArgName(0)) Result += ":$" + getArgName(0)->getAsUnquotedString(); 2163 for (unsigned i = 1, e = getNumArgs(); i != e; ++i) { 2164 Result += ", " + getArg(i)->getAsString(); 2165 if (getArgName(i)) Result += ":$" + getArgName(i)->getAsUnquotedString(); 2166 } 2167 } 2168 return Result + ")"; 2169 } 2170 2171 //===----------------------------------------------------------------------===// 2172 // Other implementations 2173 //===----------------------------------------------------------------------===// 2174 2175 RecordVal::RecordVal(Init *N, RecTy *T, FieldKind K) 2176 : Name(N), TyAndKind(T, K) { 2177 setValue(UnsetInit::get()); 2178 assert(Value && "Cannot create unset value for current type!"); 2179 } 2180 2181 // This constructor accepts the same arguments as the above, but also 2182 // a source location. 2183 RecordVal::RecordVal(Init *N, SMLoc Loc, RecTy *T, FieldKind K) 2184 : Name(N), Loc(Loc), TyAndKind(T, K) { 2185 setValue(UnsetInit::get()); 2186 assert(Value && "Cannot create unset value for current type!"); 2187 } 2188 2189 StringRef RecordVal::getName() const { 2190 return cast<StringInit>(getNameInit())->getValue(); 2191 } 2192 2193 std::string RecordVal::getPrintType() const { 2194 if (getType() == StringRecTy::get()) { 2195 if (auto *StrInit = dyn_cast<StringInit>(Value)) { 2196 if (StrInit->hasCodeFormat()) 2197 return "code"; 2198 else 2199 return "string"; 2200 } else { 2201 return "string"; 2202 } 2203 } else { 2204 return TyAndKind.getPointer()->getAsString(); 2205 } 2206 } 2207 2208 bool RecordVal::setValue(Init *V) { 2209 if (V) { 2210 Value = V->getCastTo(getType()); 2211 if (Value) { 2212 assert(!isa<TypedInit>(Value) || 2213 cast<TypedInit>(Value)->getType()->typeIsA(getType())); 2214 if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) { 2215 if (!isa<BitsInit>(Value)) { 2216 SmallVector<Init *, 64> Bits; 2217 Bits.reserve(BTy->getNumBits()); 2218 for (unsigned I = 0, E = BTy->getNumBits(); I < E; ++I) 2219 Bits.push_back(Value->getBit(I)); 2220 Value = BitsInit::get(Bits); 2221 } 2222 } 2223 } 2224 return Value == nullptr; 2225 } 2226 Value = nullptr; 2227 return false; 2228 } 2229 2230 // This version of setValue takes a source location and resets the 2231 // location in the RecordVal. 2232 bool RecordVal::setValue(Init *V, SMLoc NewLoc) { 2233 Loc = NewLoc; 2234 if (V) { 2235 Value = V->getCastTo(getType()); 2236 if (Value) { 2237 assert(!isa<TypedInit>(Value) || 2238 cast<TypedInit>(Value)->getType()->typeIsA(getType())); 2239 if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) { 2240 if (!isa<BitsInit>(Value)) { 2241 SmallVector<Init *, 64> Bits; 2242 Bits.reserve(BTy->getNumBits()); 2243 for (unsigned I = 0, E = BTy->getNumBits(); I < E; ++I) 2244 Bits.push_back(Value->getBit(I)); 2245 Value = BitsInit::get(Bits); 2246 } 2247 } 2248 } 2249 return Value == nullptr; 2250 } 2251 Value = nullptr; 2252 return false; 2253 } 2254 2255 #include "llvm/TableGen/Record.h" 2256 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2257 LLVM_DUMP_METHOD void RecordVal::dump() const { errs() << *this; } 2258 #endif 2259 2260 void RecordVal::print(raw_ostream &OS, bool PrintSem) const { 2261 if (isNonconcreteOK()) OS << "field "; 2262 OS << getPrintType() << " " << getNameInitAsString(); 2263 2264 if (getValue()) 2265 OS << " = " << *getValue(); 2266 2267 if (PrintSem) OS << ";\n"; 2268 } 2269 2270 unsigned Record::LastID = 0; 2271 2272 void Record::checkName() { 2273 // Ensure the record name has string type. 2274 const TypedInit *TypedName = cast<const TypedInit>(Name); 2275 if (!isa<StringRecTy>(TypedName->getType())) 2276 PrintFatalError(getLoc(), Twine("Record name '") + Name->getAsString() + 2277 "' is not a string!"); 2278 } 2279 2280 RecordRecTy *Record::getType() { 2281 SmallVector<Record *, 4> DirectSCs; 2282 getDirectSuperClasses(DirectSCs); 2283 return RecordRecTy::get(DirectSCs); 2284 } 2285 2286 DefInit *Record::getDefInit() { 2287 if (!CorrespondingDefInit) 2288 CorrespondingDefInit = new (Allocator) DefInit(this); 2289 return CorrespondingDefInit; 2290 } 2291 2292 void Record::setName(Init *NewName) { 2293 Name = NewName; 2294 checkName(); 2295 // DO NOT resolve record values to the name at this point because 2296 // there might be default values for arguments of this def. Those 2297 // arguments might not have been resolved yet so we don't want to 2298 // prematurely assume values for those arguments were not passed to 2299 // this def. 2300 // 2301 // Nonetheless, it may be that some of this Record's values 2302 // reference the record name. Indeed, the reason for having the 2303 // record name be an Init is to provide this flexibility. The extra 2304 // resolve steps after completely instantiating defs takes care of 2305 // this. See TGParser::ParseDef and TGParser::ParseDefm. 2306 } 2307 2308 // NOTE for the next two functions: 2309 // Superclasses are in post-order, so the final one is a direct 2310 // superclass. All of its transitive superclases immediately precede it, 2311 // so we can step through the direct superclasses in reverse order. 2312 2313 bool Record::hasDirectSuperClass(const Record *Superclass) const { 2314 ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses(); 2315 2316 for (int I = SCs.size() - 1; I >= 0; --I) { 2317 const Record *SC = SCs[I].first; 2318 if (SC == Superclass) 2319 return true; 2320 I -= SC->getSuperClasses().size(); 2321 } 2322 2323 return false; 2324 } 2325 2326 void Record::getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const { 2327 ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses(); 2328 2329 while (!SCs.empty()) { 2330 Record *SC = SCs.back().first; 2331 SCs = SCs.drop_back(1 + SC->getSuperClasses().size()); 2332 Classes.push_back(SC); 2333 } 2334 } 2335 2336 void Record::resolveReferences(Resolver &R, const RecordVal *SkipVal) { 2337 Init *OldName = getNameInit(); 2338 Init *NewName = Name->resolveReferences(R); 2339 if (NewName != OldName) { 2340 // Re-register with RecordKeeper. 2341 setName(NewName); 2342 } 2343 2344 // Resolve the field values. 2345 for (RecordVal &Value : Values) { 2346 if (SkipVal == &Value) // Skip resolve the same field as the given one 2347 continue; 2348 if (Init *V = Value.getValue()) { 2349 Init *VR = V->resolveReferences(R); 2350 if (Value.setValue(VR)) { 2351 std::string Type; 2352 if (TypedInit *VRT = dyn_cast<TypedInit>(VR)) 2353 Type = 2354 (Twine("of type '") + VRT->getType()->getAsString() + "' ").str(); 2355 PrintFatalError( 2356 getLoc(), 2357 Twine("Invalid value ") + Type + "found when setting field '" + 2358 Value.getNameInitAsString() + "' of type '" + 2359 Value.getType()->getAsString() + 2360 "' after resolving references: " + VR->getAsUnquotedString() + 2361 "\n"); 2362 } 2363 } 2364 } 2365 2366 // Resolve the assertion expressions. 2367 for (auto &Assertion : Assertions) { 2368 Init *Value = std::get<1>(Assertion)->resolveReferences(R); 2369 std::get<1>(Assertion) = Value; 2370 Value = std::get<2>(Assertion)->resolveReferences(R); 2371 std::get<2>(Assertion) = Value; 2372 } 2373 } 2374 2375 void Record::resolveReferences(Init *NewName) { 2376 RecordResolver R(*this); 2377 R.setName(NewName); 2378 R.setFinal(true); 2379 resolveReferences(R); 2380 } 2381 2382 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2383 LLVM_DUMP_METHOD void Record::dump() const { errs() << *this; } 2384 #endif 2385 2386 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) { 2387 OS << R.getNameInitAsString(); 2388 2389 ArrayRef<Init *> TArgs = R.getTemplateArgs(); 2390 if (!TArgs.empty()) { 2391 OS << "<"; 2392 bool NeedComma = false; 2393 for (const Init *TA : TArgs) { 2394 if (NeedComma) OS << ", "; 2395 NeedComma = true; 2396 const RecordVal *RV = R.getValue(TA); 2397 assert(RV && "Template argument record not found??"); 2398 RV->print(OS, false); 2399 } 2400 OS << ">"; 2401 } 2402 2403 OS << " {"; 2404 ArrayRef<std::pair<Record *, SMRange>> SC = R.getSuperClasses(); 2405 if (!SC.empty()) { 2406 OS << "\t//"; 2407 for (const auto &SuperPair : SC) 2408 OS << " " << SuperPair.first->getNameInitAsString(); 2409 } 2410 OS << "\n"; 2411 2412 for (const RecordVal &Val : R.getValues()) 2413 if (Val.isNonconcreteOK() && !R.isTemplateArg(Val.getNameInit())) 2414 OS << Val; 2415 for (const RecordVal &Val : R.getValues()) 2416 if (!Val.isNonconcreteOK() && !R.isTemplateArg(Val.getNameInit())) 2417 OS << Val; 2418 2419 return OS << "}\n"; 2420 } 2421 2422 SMLoc Record::getFieldLoc(StringRef FieldName) const { 2423 const RecordVal *R = getValue(FieldName); 2424 if (!R) 2425 PrintFatalError(getLoc(), "Record `" + getName() + 2426 "' does not have a field named `" + FieldName + "'!\n"); 2427 return R->getLoc(); 2428 } 2429 2430 Init *Record::getValueInit(StringRef FieldName) const { 2431 const RecordVal *R = getValue(FieldName); 2432 if (!R || !R->getValue()) 2433 PrintFatalError(getLoc(), "Record `" + getName() + 2434 "' does not have a field named `" + FieldName + "'!\n"); 2435 return R->getValue(); 2436 } 2437 2438 StringRef Record::getValueAsString(StringRef FieldName) const { 2439 llvm::Optional<StringRef> S = getValueAsOptionalString(FieldName); 2440 if (!S.hasValue()) 2441 PrintFatalError(getLoc(), "Record `" + getName() + 2442 "' does not have a field named `" + FieldName + "'!\n"); 2443 return S.getValue(); 2444 } 2445 2446 llvm::Optional<StringRef> 2447 Record::getValueAsOptionalString(StringRef FieldName) const { 2448 const RecordVal *R = getValue(FieldName); 2449 if (!R || !R->getValue()) 2450 return llvm::Optional<StringRef>(); 2451 if (isa<UnsetInit>(R->getValue())) 2452 return llvm::Optional<StringRef>(); 2453 2454 if (StringInit *SI = dyn_cast<StringInit>(R->getValue())) 2455 return SI->getValue(); 2456 2457 PrintFatalError(getLoc(), 2458 "Record `" + getName() + "', ` field `" + FieldName + 2459 "' exists but does not have a string initializer!"); 2460 } 2461 2462 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const { 2463 const RecordVal *R = getValue(FieldName); 2464 if (!R || !R->getValue()) 2465 PrintFatalError(getLoc(), "Record `" + getName() + 2466 "' does not have a field named `" + FieldName + "'!\n"); 2467 2468 if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue())) 2469 return BI; 2470 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName + 2471 "' exists but does not have a bits value"); 2472 } 2473 2474 ListInit *Record::getValueAsListInit(StringRef FieldName) const { 2475 const RecordVal *R = getValue(FieldName); 2476 if (!R || !R->getValue()) 2477 PrintFatalError(getLoc(), "Record `" + getName() + 2478 "' does not have a field named `" + FieldName + "'!\n"); 2479 2480 if (ListInit *LI = dyn_cast<ListInit>(R->getValue())) 2481 return LI; 2482 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName + 2483 "' exists but does not have a list value"); 2484 } 2485 2486 std::vector<Record*> 2487 Record::getValueAsListOfDefs(StringRef FieldName) const { 2488 ListInit *List = getValueAsListInit(FieldName); 2489 std::vector<Record*> Defs; 2490 for (Init *I : List->getValues()) { 2491 if (DefInit *DI = dyn_cast<DefInit>(I)) 2492 Defs.push_back(DI->getDef()); 2493 else 2494 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + 2495 FieldName + "' list is not entirely DefInit!"); 2496 } 2497 return Defs; 2498 } 2499 2500 int64_t Record::getValueAsInt(StringRef FieldName) const { 2501 const RecordVal *R = getValue(FieldName); 2502 if (!R || !R->getValue()) 2503 PrintFatalError(getLoc(), "Record `" + getName() + 2504 "' does not have a field named `" + FieldName + "'!\n"); 2505 2506 if (IntInit *II = dyn_cast<IntInit>(R->getValue())) 2507 return II->getValue(); 2508 PrintFatalError(getLoc(), Twine("Record `") + getName() + "', field `" + 2509 FieldName + 2510 "' exists but does not have an int value: " + 2511 R->getValue()->getAsString()); 2512 } 2513 2514 std::vector<int64_t> 2515 Record::getValueAsListOfInts(StringRef FieldName) const { 2516 ListInit *List = getValueAsListInit(FieldName); 2517 std::vector<int64_t> Ints; 2518 for (Init *I : List->getValues()) { 2519 if (IntInit *II = dyn_cast<IntInit>(I)) 2520 Ints.push_back(II->getValue()); 2521 else 2522 PrintFatalError(getLoc(), 2523 Twine("Record `") + getName() + "', field `" + FieldName + 2524 "' exists but does not have a list of ints value: " + 2525 I->getAsString()); 2526 } 2527 return Ints; 2528 } 2529 2530 std::vector<StringRef> 2531 Record::getValueAsListOfStrings(StringRef FieldName) const { 2532 ListInit *List = getValueAsListInit(FieldName); 2533 std::vector<StringRef> Strings; 2534 for (Init *I : List->getValues()) { 2535 if (StringInit *SI = dyn_cast<StringInit>(I)) 2536 Strings.push_back(SI->getValue()); 2537 else 2538 PrintFatalError(getLoc(), 2539 Twine("Record `") + getName() + "', field `" + FieldName + 2540 "' exists but does not have a list of strings value: " + 2541 I->getAsString()); 2542 } 2543 return Strings; 2544 } 2545 2546 Record *Record::getValueAsDef(StringRef FieldName) const { 2547 const RecordVal *R = getValue(FieldName); 2548 if (!R || !R->getValue()) 2549 PrintFatalError(getLoc(), "Record `" + getName() + 2550 "' does not have a field named `" + FieldName + "'!\n"); 2551 2552 if (DefInit *DI = dyn_cast<DefInit>(R->getValue())) 2553 return DI->getDef(); 2554 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + 2555 FieldName + "' does not have a def initializer!"); 2556 } 2557 2558 Record *Record::getValueAsOptionalDef(StringRef FieldName) const { 2559 const RecordVal *R = getValue(FieldName); 2560 if (!R || !R->getValue()) 2561 PrintFatalError(getLoc(), "Record `" + getName() + 2562 "' does not have a field named `" + FieldName + "'!\n"); 2563 2564 if (DefInit *DI = dyn_cast<DefInit>(R->getValue())) 2565 return DI->getDef(); 2566 if (isa<UnsetInit>(R->getValue())) 2567 return nullptr; 2568 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + 2569 FieldName + "' does not have either a def initializer or '?'!"); 2570 } 2571 2572 2573 bool Record::getValueAsBit(StringRef FieldName) const { 2574 const RecordVal *R = getValue(FieldName); 2575 if (!R || !R->getValue()) 2576 PrintFatalError(getLoc(), "Record `" + getName() + 2577 "' does not have a field named `" + FieldName + "'!\n"); 2578 2579 if (BitInit *BI = dyn_cast<BitInit>(R->getValue())) 2580 return BI->getValue(); 2581 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + 2582 FieldName + "' does not have a bit initializer!"); 2583 } 2584 2585 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const { 2586 const RecordVal *R = getValue(FieldName); 2587 if (!R || !R->getValue()) 2588 PrintFatalError(getLoc(), "Record `" + getName() + 2589 "' does not have a field named `" + FieldName.str() + "'!\n"); 2590 2591 if (isa<UnsetInit>(R->getValue())) { 2592 Unset = true; 2593 return false; 2594 } 2595 Unset = false; 2596 if (BitInit *BI = dyn_cast<BitInit>(R->getValue())) 2597 return BI->getValue(); 2598 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + 2599 FieldName + "' does not have a bit initializer!"); 2600 } 2601 2602 DagInit *Record::getValueAsDag(StringRef FieldName) const { 2603 const RecordVal *R = getValue(FieldName); 2604 if (!R || !R->getValue()) 2605 PrintFatalError(getLoc(), "Record `" + getName() + 2606 "' does not have a field named `" + FieldName + "'!\n"); 2607 2608 if (DagInit *DI = dyn_cast<DagInit>(R->getValue())) 2609 return DI; 2610 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + 2611 FieldName + "' does not have a dag initializer!"); 2612 } 2613 2614 // Check all record assertions: For each one, resolve the condition 2615 // and message, then call CheckAssert(). 2616 // Note: The condition and message are probably already resolved, 2617 // but resolving again allows calls before records are resolved. 2618 void Record::checkAssertions() { 2619 RecordResolver R(*this); 2620 R.setFinal(true); 2621 2622 for (auto Assertion : getAssertions()) { 2623 Init *Condition = std::get<1>(Assertion)->resolveReferences(R); 2624 Init *Message = std::get<2>(Assertion)->resolveReferences(R); 2625 CheckAssert(std::get<0>(Assertion), Condition, Message); 2626 } 2627 } 2628 2629 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2630 LLVM_DUMP_METHOD void RecordKeeper::dump() const { errs() << *this; } 2631 #endif 2632 2633 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) { 2634 OS << "------------- Classes -----------------\n"; 2635 for (const auto &C : RK.getClasses()) 2636 OS << "class " << *C.second; 2637 2638 OS << "------------- Defs -----------------\n"; 2639 for (const auto &D : RK.getDefs()) 2640 OS << "def " << *D.second; 2641 return OS; 2642 } 2643 2644 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as 2645 /// an identifier. 2646 Init *RecordKeeper::getNewAnonymousName() { 2647 return AnonymousNameInit::get(AnonCounter++); 2648 } 2649 2650 // These functions implement the phase timing facility. Starting a timer 2651 // when one is already running stops the running one. 2652 2653 void RecordKeeper::startTimer(StringRef Name) { 2654 if (TimingGroup) { 2655 if (LastTimer && LastTimer->isRunning()) { 2656 LastTimer->stopTimer(); 2657 if (BackendTimer) { 2658 LastTimer->clear(); 2659 BackendTimer = false; 2660 } 2661 } 2662 2663 LastTimer = new Timer("", Name, *TimingGroup); 2664 LastTimer->startTimer(); 2665 } 2666 } 2667 2668 void RecordKeeper::stopTimer() { 2669 if (TimingGroup) { 2670 assert(LastTimer && "No phase timer was started"); 2671 LastTimer->stopTimer(); 2672 } 2673 } 2674 2675 void RecordKeeper::startBackendTimer(StringRef Name) { 2676 if (TimingGroup) { 2677 startTimer(Name); 2678 BackendTimer = true; 2679 } 2680 } 2681 2682 void RecordKeeper::stopBackendTimer() { 2683 if (TimingGroup) { 2684 if (BackendTimer) { 2685 stopTimer(); 2686 BackendTimer = false; 2687 } 2688 } 2689 } 2690 2691 // We cache the record vectors for single classes. Many backends request 2692 // the same vectors multiple times. 2693 std::vector<Record *> RecordKeeper::getAllDerivedDefinitions( 2694 StringRef ClassName) const { 2695 2696 auto Pair = ClassRecordsMap.try_emplace(ClassName); 2697 if (Pair.second) 2698 Pair.first->second = getAllDerivedDefinitions(makeArrayRef(ClassName)); 2699 2700 return Pair.first->second; 2701 } 2702 2703 std::vector<Record *> RecordKeeper::getAllDerivedDefinitions( 2704 ArrayRef<StringRef> ClassNames) const { 2705 SmallVector<Record *, 2> ClassRecs; 2706 std::vector<Record *> Defs; 2707 2708 assert(ClassNames.size() > 0 && "At least one class must be passed."); 2709 for (const auto &ClassName : ClassNames) { 2710 Record *Class = getClass(ClassName); 2711 if (!Class) 2712 PrintFatalError("The class '" + ClassName + "' is not defined\n"); 2713 ClassRecs.push_back(Class); 2714 } 2715 2716 for (const auto &OneDef : getDefs()) { 2717 if (all_of(ClassRecs, [&OneDef](const Record *Class) { 2718 return OneDef.second->isSubClassOf(Class); 2719 })) 2720 Defs.push_back(OneDef.second.get()); 2721 } 2722 2723 return Defs; 2724 } 2725 2726 Init *MapResolver::resolve(Init *VarName) { 2727 auto It = Map.find(VarName); 2728 if (It == Map.end()) 2729 return nullptr; 2730 2731 Init *I = It->second.V; 2732 2733 if (!It->second.Resolved && Map.size() > 1) { 2734 // Resolve mutual references among the mapped variables, but prevent 2735 // infinite recursion. 2736 Map.erase(It); 2737 I = I->resolveReferences(*this); 2738 Map[VarName] = {I, true}; 2739 } 2740 2741 return I; 2742 } 2743 2744 Init *RecordResolver::resolve(Init *VarName) { 2745 Init *Val = Cache.lookup(VarName); 2746 if (Val) 2747 return Val; 2748 2749 if (llvm::is_contained(Stack, VarName)) 2750 return nullptr; // prevent infinite recursion 2751 2752 if (RecordVal *RV = getCurrentRecord()->getValue(VarName)) { 2753 if (!isa<UnsetInit>(RV->getValue())) { 2754 Val = RV->getValue(); 2755 Stack.push_back(VarName); 2756 Val = Val->resolveReferences(*this); 2757 Stack.pop_back(); 2758 } 2759 } else if (Name && VarName == getCurrentRecord()->getNameInit()) { 2760 Stack.push_back(VarName); 2761 Val = Name->resolveReferences(*this); 2762 Stack.pop_back(); 2763 } 2764 2765 Cache[VarName] = Val; 2766 return Val; 2767 } 2768 2769 Init *TrackUnresolvedResolver::resolve(Init *VarName) { 2770 Init *I = nullptr; 2771 2772 if (R) { 2773 I = R->resolve(VarName); 2774 if (I && !FoundUnresolved) { 2775 // Do not recurse into the resolved initializer, as that would change 2776 // the behavior of the resolver we're delegating, but do check to see 2777 // if there are unresolved variables remaining. 2778 TrackUnresolvedResolver Sub; 2779 I->resolveReferences(Sub); 2780 FoundUnresolved |= Sub.FoundUnresolved; 2781 } 2782 } 2783 2784 if (!I) 2785 FoundUnresolved = true; 2786 return I; 2787 } 2788 2789 Init *HasReferenceResolver::resolve(Init *VarName) 2790 { 2791 if (VarName == VarNameToTrack) 2792 Found = true; 2793 return nullptr; 2794 } 2795