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