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