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