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