1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===// 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 Parser for TableGen. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TGParser.h" 14 #include "llvm/ADT/None.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/StringExtras.h" 18 #include "llvm/ADT/Twine.h" 19 #include "llvm/Config/llvm-config.h" 20 #include "llvm/Support/Casting.h" 21 #include "llvm/Support/Compiler.h" 22 #include "llvm/Support/ErrorHandling.h" 23 #include "llvm/Support/raw_ostream.h" 24 #include "llvm/Support/SourceMgr.h" 25 #include <algorithm> 26 #include <cassert> 27 #include <cstdint> 28 29 using namespace llvm; 30 31 //===----------------------------------------------------------------------===// 32 // Support Code for the Semantic Actions. 33 //===----------------------------------------------------------------------===// 34 35 namespace llvm { 36 37 struct SubClassReference { 38 SMRange RefRange; 39 Record *Rec; 40 SmallVector<Init*, 4> TemplateArgs; 41 42 SubClassReference() : Rec(nullptr) {} 43 44 bool isInvalid() const { return Rec == nullptr; } 45 }; 46 47 struct SubMultiClassReference { 48 SMRange RefRange; 49 MultiClass *MC; 50 SmallVector<Init*, 4> TemplateArgs; 51 52 SubMultiClassReference() : MC(nullptr) {} 53 54 bool isInvalid() const { return MC == nullptr; } 55 void dump() const; 56 }; 57 58 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 59 LLVM_DUMP_METHOD void SubMultiClassReference::dump() const { 60 errs() << "Multiclass:\n"; 61 62 MC->dump(); 63 64 errs() << "Template args:\n"; 65 for (Init *TA : TemplateArgs) 66 TA->dump(); 67 } 68 #endif 69 70 } // end namespace llvm 71 72 static bool checkBitsConcrete(Record &R, const RecordVal &RV) { 73 BitsInit *BV = cast<BitsInit>(RV.getValue()); 74 for (unsigned i = 0, e = BV->getNumBits(); i != e; ++i) { 75 Init *Bit = BV->getBit(i); 76 bool IsReference = false; 77 if (auto VBI = dyn_cast<VarBitInit>(Bit)) { 78 if (auto VI = dyn_cast<VarInit>(VBI->getBitVar())) { 79 if (R.getValue(VI->getName())) 80 IsReference = true; 81 } 82 } else if (isa<VarInit>(Bit)) { 83 IsReference = true; 84 } 85 if (!(IsReference || Bit->isConcrete())) 86 return false; 87 } 88 return true; 89 } 90 91 static void checkConcrete(Record &R) { 92 for (const RecordVal &RV : R.getValues()) { 93 // HACK: Disable this check for variables declared with 'field'. This is 94 // done merely because existing targets have legitimate cases of 95 // non-concrete variables in helper defs. Ideally, we'd introduce a 96 // 'maybe' or 'optional' modifier instead of this. 97 if (RV.getPrefix()) 98 continue; 99 100 if (Init *V = RV.getValue()) { 101 bool Ok = isa<BitsInit>(V) ? checkBitsConcrete(R, RV) : V->isConcrete(); 102 if (!Ok) { 103 PrintError(R.getLoc(), 104 Twine("Initializer of '") + RV.getNameInitAsString() + 105 "' in '" + R.getNameInitAsString() + 106 "' could not be fully resolved: " + 107 RV.getValue()->getAsString()); 108 } 109 } 110 } 111 } 112 113 /// Return an Init with a qualifier prefix referring 114 /// to CurRec's name. 115 static Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass, 116 Init *Name, StringRef Scoper) { 117 Init *NewName = 118 BinOpInit::getStrConcat(CurRec.getNameInit(), StringInit::get(Scoper)); 119 NewName = BinOpInit::getStrConcat(NewName, Name); 120 if (CurMultiClass && Scoper != "::") { 121 Init *Prefix = BinOpInit::getStrConcat(CurMultiClass->Rec.getNameInit(), 122 StringInit::get("::")); 123 NewName = BinOpInit::getStrConcat(Prefix, NewName); 124 } 125 126 if (BinOpInit *BinOp = dyn_cast<BinOpInit>(NewName)) 127 NewName = BinOp->Fold(&CurRec); 128 return NewName; 129 } 130 131 /// Return the qualified version of the implicit 'NAME' template argument. 132 static Init *QualifiedNameOfImplicitName(Record &Rec, 133 MultiClass *MC = nullptr) { 134 return QualifyName(Rec, MC, StringInit::get("NAME"), MC ? "::" : ":"); 135 } 136 137 static Init *QualifiedNameOfImplicitName(MultiClass *MC) { 138 return QualifiedNameOfImplicitName(MC->Rec, MC); 139 } 140 141 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) { 142 if (!CurRec) 143 CurRec = &CurMultiClass->Rec; 144 145 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) { 146 // The value already exists in the class, treat this as a set. 147 if (ERV->setValue(RV.getValue())) 148 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" + 149 RV.getType()->getAsString() + "' is incompatible with " + 150 "previous definition of type '" + 151 ERV->getType()->getAsString() + "'"); 152 } else { 153 CurRec->addValue(RV); 154 } 155 return false; 156 } 157 158 /// SetValue - 159 /// Return true on error, false on success. 160 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName, 161 ArrayRef<unsigned> BitList, Init *V, 162 bool AllowSelfAssignment) { 163 if (!V) return false; 164 165 if (!CurRec) CurRec = &CurMultiClass->Rec; 166 167 RecordVal *RV = CurRec->getValue(ValName); 168 if (!RV) 169 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + 170 "' unknown!"); 171 172 // Do not allow assignments like 'X = X'. This will just cause infinite loops 173 // in the resolution machinery. 174 if (BitList.empty()) 175 if (VarInit *VI = dyn_cast<VarInit>(V)) 176 if (VI->getNameInit() == ValName && !AllowSelfAssignment) 177 return Error(Loc, "Recursion / self-assignment forbidden"); 178 179 // If we are assigning to a subset of the bits in the value... then we must be 180 // assigning to a field of BitsRecTy, which must have a BitsInit 181 // initializer. 182 // 183 if (!BitList.empty()) { 184 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue()); 185 if (!CurVal) 186 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + 187 "' is not a bits type"); 188 189 // Convert the incoming value to a bits type of the appropriate size... 190 Init *BI = V->getCastTo(BitsRecTy::get(BitList.size())); 191 if (!BI) 192 return Error(Loc, "Initializer is not compatible with bit range"); 193 194 SmallVector<Init *, 16> NewBits(CurVal->getNumBits()); 195 196 // Loop over bits, assigning values as appropriate. 197 for (unsigned i = 0, e = BitList.size(); i != e; ++i) { 198 unsigned Bit = BitList[i]; 199 if (NewBits[Bit]) 200 return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" + 201 ValName->getAsUnquotedString() + "' more than once"); 202 NewBits[Bit] = BI->getBit(i); 203 } 204 205 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i) 206 if (!NewBits[i]) 207 NewBits[i] = CurVal->getBit(i); 208 209 V = BitsInit::get(NewBits); 210 } 211 212 if (RV->setValue(V)) { 213 std::string InitType; 214 if (BitsInit *BI = dyn_cast<BitsInit>(V)) 215 InitType = (Twine("' of type bit initializer with length ") + 216 Twine(BI->getNumBits())).str(); 217 else if (TypedInit *TI = dyn_cast<TypedInit>(V)) 218 InitType = (Twine("' of type '") + TI->getType()->getAsString()).str(); 219 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + 220 "' of type '" + RV->getType()->getAsString() + 221 "' is incompatible with initializer '" + 222 V->getAsString() + InitType + "'"); 223 } 224 return false; 225 } 226 227 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template 228 /// args as SubClass's template arguments. 229 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) { 230 Record *SC = SubClass.Rec; 231 // Add all of the values in the subclass into the current class. 232 for (const RecordVal &Val : SC->getValues()) 233 if (AddValue(CurRec, SubClass.RefRange.Start, Val)) 234 return true; 235 236 ArrayRef<Init *> TArgs = SC->getTemplateArgs(); 237 238 // Ensure that an appropriate number of template arguments are specified. 239 if (TArgs.size() < SubClass.TemplateArgs.size()) 240 return Error(SubClass.RefRange.Start, 241 "More template args specified than expected"); 242 243 // Loop over all of the template arguments, setting them to the specified 244 // value or leaving them as the default if necessary. 245 MapResolver R(CurRec); 246 247 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) { 248 if (i < SubClass.TemplateArgs.size()) { 249 // If a value is specified for this template arg, set it now. 250 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i], 251 None, SubClass.TemplateArgs[i])) 252 return true; 253 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) { 254 return Error(SubClass.RefRange.Start, 255 "Value not specified for template argument #" + 256 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() + 257 ") of subclass '" + SC->getNameInitAsString() + "'!"); 258 } 259 260 R.set(TArgs[i], CurRec->getValue(TArgs[i])->getValue()); 261 262 CurRec->removeValue(TArgs[i]); 263 } 264 265 Init *Name; 266 if (CurRec->isClass()) 267 Name = 268 VarInit::get(QualifiedNameOfImplicitName(*CurRec), StringRecTy::get()); 269 else 270 Name = CurRec->getNameInit(); 271 R.set(QualifiedNameOfImplicitName(*SC), Name); 272 273 CurRec->resolveReferences(R); 274 275 // Since everything went well, we can now set the "superclass" list for the 276 // current record. 277 ArrayRef<std::pair<Record *, SMRange>> SCs = SC->getSuperClasses(); 278 for (const auto &SCPair : SCs) { 279 if (CurRec->isSubClassOf(SCPair.first)) 280 return Error(SubClass.RefRange.Start, 281 "Already subclass of '" + SCPair.first->getName() + "'!\n"); 282 CurRec->addSuperClass(SCPair.first, SCPair.second); 283 } 284 285 if (CurRec->isSubClassOf(SC)) 286 return Error(SubClass.RefRange.Start, 287 "Already subclass of '" + SC->getName() + "'!\n"); 288 CurRec->addSuperClass(SC, SubClass.RefRange); 289 return false; 290 } 291 292 bool TGParser::AddSubClass(RecordsEntry &Entry, SubClassReference &SubClass) { 293 if (Entry.Rec) 294 return AddSubClass(Entry.Rec.get(), SubClass); 295 296 for (auto &E : Entry.Loop->Entries) { 297 if (AddSubClass(E, SubClass)) 298 return true; 299 } 300 301 return false; 302 } 303 304 /// AddSubMultiClass - Add SubMultiClass as a subclass to 305 /// CurMC, resolving its template args as SubMultiClass's 306 /// template arguments. 307 bool TGParser::AddSubMultiClass(MultiClass *CurMC, 308 SubMultiClassReference &SubMultiClass) { 309 MultiClass *SMC = SubMultiClass.MC; 310 311 ArrayRef<Init *> SMCTArgs = SMC->Rec.getTemplateArgs(); 312 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size()) 313 return Error(SubMultiClass.RefRange.Start, 314 "More template args specified than expected"); 315 316 // Prepare the mapping of template argument name to value, filling in default 317 // values if necessary. 318 SubstStack TemplateArgs; 319 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) { 320 if (i < SubMultiClass.TemplateArgs.size()) { 321 TemplateArgs.emplace_back(SMCTArgs[i], SubMultiClass.TemplateArgs[i]); 322 } else { 323 Init *Default = SMC->Rec.getValue(SMCTArgs[i])->getValue(); 324 if (!Default->isComplete()) { 325 return Error(SubMultiClass.RefRange.Start, 326 "value not specified for template argument #" + Twine(i) + 327 " (" + SMCTArgs[i]->getAsUnquotedString() + 328 ") of multiclass '" + SMC->Rec.getNameInitAsString() + 329 "'"); 330 } 331 TemplateArgs.emplace_back(SMCTArgs[i], Default); 332 } 333 } 334 335 TemplateArgs.emplace_back( 336 QualifiedNameOfImplicitName(SMC), 337 VarInit::get(QualifiedNameOfImplicitName(CurMC), StringRecTy::get())); 338 339 // Add all of the defs in the subclass into the current multiclass. 340 return resolve(SMC->Entries, TemplateArgs, false, &CurMC->Entries); 341 } 342 343 /// Add a record or foreach loop to the current context (global record keeper, 344 /// current inner-most foreach loop, or multiclass). 345 bool TGParser::addEntry(RecordsEntry E) { 346 assert(!E.Rec || !E.Loop); 347 348 if (!Loops.empty()) { 349 Loops.back()->Entries.push_back(std::move(E)); 350 return false; 351 } 352 353 if (E.Loop) { 354 SubstStack Stack; 355 return resolve(*E.Loop, Stack, CurMultiClass == nullptr, 356 CurMultiClass ? &CurMultiClass->Entries : nullptr); 357 } 358 359 if (CurMultiClass) { 360 CurMultiClass->Entries.push_back(std::move(E)); 361 return false; 362 } 363 364 return addDefOne(std::move(E.Rec)); 365 } 366 367 /// Resolve the entries in \p Loop, going over inner loops recursively 368 /// and making the given subsitutions of (name, value) pairs. 369 /// 370 /// The resulting records are stored in \p Dest if non-null. Otherwise, they 371 /// are added to the global record keeper. 372 bool TGParser::resolve(const ForeachLoop &Loop, SubstStack &Substs, 373 bool Final, std::vector<RecordsEntry> *Dest, 374 SMLoc *Loc) { 375 MapResolver R; 376 for (const auto &S : Substs) 377 R.set(S.first, S.second); 378 Init *List = Loop.ListValue->resolveReferences(R); 379 auto LI = dyn_cast<ListInit>(List); 380 if (!LI) { 381 if (!Final) { 382 Dest->emplace_back(std::make_unique<ForeachLoop>(Loop.Loc, Loop.IterVar, 383 List)); 384 return resolve(Loop.Entries, Substs, Final, &Dest->back().Loop->Entries, 385 Loc); 386 } 387 388 PrintError(Loop.Loc, Twine("attempting to loop over '") + 389 List->getAsString() + "', expected a list"); 390 return true; 391 } 392 393 bool Error = false; 394 for (auto Elt : *LI) { 395 if (Loop.IterVar) 396 Substs.emplace_back(Loop.IterVar->getNameInit(), Elt); 397 Error = resolve(Loop.Entries, Substs, Final, Dest); 398 if (Loop.IterVar) 399 Substs.pop_back(); 400 if (Error) 401 break; 402 } 403 return Error; 404 } 405 406 /// Resolve the entries in \p Source, going over loops recursively and 407 /// making the given substitutions of (name, value) pairs. 408 /// 409 /// The resulting records are stored in \p Dest if non-null. Otherwise, they 410 /// are added to the global record keeper. 411 bool TGParser::resolve(const std::vector<RecordsEntry> &Source, 412 SubstStack &Substs, bool Final, 413 std::vector<RecordsEntry> *Dest, SMLoc *Loc) { 414 bool Error = false; 415 for (auto &E : Source) { 416 if (E.Loop) { 417 Error = resolve(*E.Loop, Substs, Final, Dest); 418 } else { 419 auto Rec = std::make_unique<Record>(*E.Rec); 420 if (Loc) 421 Rec->appendLoc(*Loc); 422 423 MapResolver R(Rec.get()); 424 for (const auto &S : Substs) 425 R.set(S.first, S.second); 426 Rec->resolveReferences(R); 427 428 if (Dest) 429 Dest->push_back(std::move(Rec)); 430 else 431 Error = addDefOne(std::move(Rec)); 432 } 433 if (Error) 434 break; 435 } 436 return Error; 437 } 438 439 /// Resolve the record fully and add it to the record keeper. 440 bool TGParser::addDefOne(std::unique_ptr<Record> Rec) { 441 if (Record *Prev = Records.getDef(Rec->getNameInitAsString())) { 442 if (!Rec->isAnonymous()) { 443 PrintError(Rec->getLoc(), 444 "def already exists: " + Rec->getNameInitAsString()); 445 PrintNote(Prev->getLoc(), "location of previous definition"); 446 return true; 447 } 448 Rec->setName(Records.getNewAnonymousName()); 449 } 450 451 Rec->resolveReferences(); 452 checkConcrete(*Rec); 453 454 if (!isa<StringInit>(Rec->getNameInit())) { 455 PrintError(Rec->getLoc(), Twine("record name '") + 456 Rec->getNameInit()->getAsString() + 457 "' could not be fully resolved"); 458 return true; 459 } 460 461 // If ObjectBody has template arguments, it's an error. 462 assert(Rec->getTemplateArgs().empty() && "How'd this get template args?"); 463 464 for (DefsetRecord *Defset : Defsets) { 465 DefInit *I = Rec->getDefInit(); 466 if (!I->getType()->typeIsA(Defset->EltTy)) { 467 PrintError(Rec->getLoc(), Twine("adding record of incompatible type '") + 468 I->getType()->getAsString() + 469 "' to defset"); 470 PrintNote(Defset->Loc, "location of defset declaration"); 471 return true; 472 } 473 Defset->Elements.push_back(I); 474 } 475 476 Records.addDef(std::move(Rec)); 477 return false; 478 } 479 480 //===----------------------------------------------------------------------===// 481 // Parser Code 482 //===----------------------------------------------------------------------===// 483 484 /// isObjectStart - Return true if this is a valid first token for an Object. 485 static bool isObjectStart(tgtok::TokKind K) { 486 return K == tgtok::Class || K == tgtok::Def || K == tgtok::Defm || 487 K == tgtok::Let || K == tgtok::MultiClass || K == tgtok::Foreach || 488 K == tgtok::Defset || K == tgtok::Defvar || K == tgtok::If; 489 } 490 491 bool TGParser::consume(tgtok::TokKind K) { 492 if (Lex.getCode() == K) { 493 Lex.Lex(); 494 return true; 495 } 496 return false; 497 } 498 499 /// ParseObjectName - If a valid object name is specified, return it. If no 500 /// name is specified, return the unset initializer. Return nullptr on parse 501 /// error. 502 /// ObjectName ::= Value [ '#' Value ]* 503 /// ObjectName ::= /*empty*/ 504 /// 505 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) { 506 switch (Lex.getCode()) { 507 case tgtok::colon: 508 case tgtok::semi: 509 case tgtok::l_brace: 510 // These are all of the tokens that can begin an object body. 511 // Some of these can also begin values but we disallow those cases 512 // because they are unlikely to be useful. 513 return UnsetInit::get(); 514 default: 515 break; 516 } 517 518 Record *CurRec = nullptr; 519 if (CurMultiClass) 520 CurRec = &CurMultiClass->Rec; 521 522 Init *Name = ParseValue(CurRec, StringRecTy::get(), ParseNameMode); 523 if (!Name) 524 return nullptr; 525 526 if (CurMultiClass) { 527 Init *NameStr = QualifiedNameOfImplicitName(CurMultiClass); 528 HasReferenceResolver R(NameStr); 529 Name->resolveReferences(R); 530 if (!R.found()) 531 Name = BinOpInit::getStrConcat(VarInit::get(NameStr, StringRecTy::get()), 532 Name); 533 } 534 535 return Name; 536 } 537 538 /// ParseClassID - Parse and resolve a reference to a class name. This returns 539 /// null on error. 540 /// 541 /// ClassID ::= ID 542 /// 543 Record *TGParser::ParseClassID() { 544 if (Lex.getCode() != tgtok::Id) { 545 TokError("expected name for ClassID"); 546 return nullptr; 547 } 548 549 Record *Result = Records.getClass(Lex.getCurStrVal()); 550 if (!Result) { 551 std::string Msg("Couldn't find class '" + Lex.getCurStrVal() + "'"); 552 if (MultiClasses[Lex.getCurStrVal()].get()) 553 TokError(Msg + ". Use 'defm' if you meant to use multiclass '" + 554 Lex.getCurStrVal() + "'"); 555 else 556 TokError(Msg); 557 } 558 559 Lex.Lex(); 560 return Result; 561 } 562 563 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name. 564 /// This returns null on error. 565 /// 566 /// MultiClassID ::= ID 567 /// 568 MultiClass *TGParser::ParseMultiClassID() { 569 if (Lex.getCode() != tgtok::Id) { 570 TokError("expected name for MultiClassID"); 571 return nullptr; 572 } 573 574 MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get(); 575 if (!Result) 576 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'"); 577 578 Lex.Lex(); 579 return Result; 580 } 581 582 /// ParseSubClassReference - Parse a reference to a subclass or to a templated 583 /// subclass. This returns a SubClassRefTy with a null Record* on error. 584 /// 585 /// SubClassRef ::= ClassID 586 /// SubClassRef ::= ClassID '<' ValueList '>' 587 /// 588 SubClassReference TGParser:: 589 ParseSubClassReference(Record *CurRec, bool isDefm) { 590 SubClassReference Result; 591 Result.RefRange.Start = Lex.getLoc(); 592 593 if (isDefm) { 594 if (MultiClass *MC = ParseMultiClassID()) 595 Result.Rec = &MC->Rec; 596 } else { 597 Result.Rec = ParseClassID(); 598 } 599 if (!Result.Rec) return Result; 600 601 // If there is no template arg list, we're done. 602 if (!consume(tgtok::less)) { 603 Result.RefRange.End = Lex.getLoc(); 604 return Result; 605 } 606 607 if (Lex.getCode() == tgtok::greater) { 608 TokError("subclass reference requires a non-empty list of template values"); 609 Result.Rec = nullptr; 610 return Result; 611 } 612 613 ParseValueList(Result.TemplateArgs, CurRec, Result.Rec); 614 if (Result.TemplateArgs.empty()) { 615 Result.Rec = nullptr; // Error parsing value list. 616 return Result; 617 } 618 619 if (!consume(tgtok::greater)) { 620 TokError("expected '>' in template value list"); 621 Result.Rec = nullptr; 622 return Result; 623 } 624 Result.RefRange.End = Lex.getLoc(); 625 626 return Result; 627 } 628 629 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a 630 /// templated submulticlass. This returns a SubMultiClassRefTy with a null 631 /// Record* on error. 632 /// 633 /// SubMultiClassRef ::= MultiClassID 634 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>' 635 /// 636 SubMultiClassReference TGParser:: 637 ParseSubMultiClassReference(MultiClass *CurMC) { 638 SubMultiClassReference Result; 639 Result.RefRange.Start = Lex.getLoc(); 640 641 Result.MC = ParseMultiClassID(); 642 if (!Result.MC) return Result; 643 644 // If there is no template arg list, we're done. 645 if (!consume(tgtok::less)) { 646 Result.RefRange.End = Lex.getLoc(); 647 return Result; 648 } 649 650 if (Lex.getCode() == tgtok::greater) { 651 TokError("subclass reference requires a non-empty list of template values"); 652 Result.MC = nullptr; 653 return Result; 654 } 655 656 ParseValueList(Result.TemplateArgs, &CurMC->Rec, &Result.MC->Rec); 657 if (Result.TemplateArgs.empty()) { 658 Result.MC = nullptr; // Error parsing value list. 659 return Result; 660 } 661 662 if (!consume(tgtok::greater)) { 663 TokError("expected '>' in template value list"); 664 Result.MC = nullptr; 665 return Result; 666 } 667 Result.RefRange.End = Lex.getLoc(); 668 669 return Result; 670 } 671 672 /// ParseRangePiece - Parse a bit/value range. 673 /// RangePiece ::= INTVAL 674 /// RangePiece ::= INTVAL '-' INTVAL 675 /// RangePiece ::= INTVAL INTVAL 676 bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges, 677 TypedInit *FirstItem) { 678 Init *CurVal = FirstItem; 679 if (!CurVal) 680 CurVal = ParseValue(nullptr); 681 682 IntInit *II = dyn_cast_or_null<IntInit>(CurVal); 683 if (!II) 684 return TokError("expected integer or bitrange"); 685 686 int64_t Start = II->getValue(); 687 int64_t End; 688 689 if (Start < 0) 690 return TokError("invalid range, cannot be negative"); 691 692 switch (Lex.getCode()) { 693 default: 694 Ranges.push_back(Start); 695 return false; 696 case tgtok::minus: { 697 Lex.Lex(); // eat 698 699 Init *I_End = ParseValue(nullptr); 700 IntInit *II_End = dyn_cast_or_null<IntInit>(I_End); 701 if (!II_End) { 702 TokError("expected integer value as end of range"); 703 return true; 704 } 705 706 End = II_End->getValue(); 707 break; 708 } 709 case tgtok::IntVal: { 710 End = -Lex.getCurIntVal(); 711 Lex.Lex(); 712 break; 713 } 714 } 715 if (End < 0) 716 return TokError("invalid range, cannot be negative"); 717 718 // Add to the range. 719 if (Start < End) 720 for (; Start <= End; ++Start) 721 Ranges.push_back(Start); 722 else 723 for (; Start >= End; --Start) 724 Ranges.push_back(Start); 725 return false; 726 } 727 728 /// ParseRangeList - Parse a list of scalars and ranges into scalar values. 729 /// 730 /// RangeList ::= RangePiece (',' RangePiece)* 731 /// 732 void TGParser::ParseRangeList(SmallVectorImpl<unsigned> &Result) { 733 // Parse the first piece. 734 if (ParseRangePiece(Result)) { 735 Result.clear(); 736 return; 737 } 738 while (consume(tgtok::comma)) 739 // Parse the next range piece. 740 if (ParseRangePiece(Result)) { 741 Result.clear(); 742 return; 743 } 744 } 745 746 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing. 747 /// OptionalRangeList ::= '<' RangeList '>' 748 /// OptionalRangeList ::= /*empty*/ 749 bool TGParser::ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges) { 750 SMLoc StartLoc = Lex.getLoc(); 751 if (!consume(tgtok::less)) 752 return false; 753 754 // Parse the range list. 755 ParseRangeList(Ranges); 756 if (Ranges.empty()) return true; 757 758 if (!consume(tgtok::greater)) { 759 TokError("expected '>' at end of range list"); 760 return Error(StartLoc, "to match this '<'"); 761 } 762 return false; 763 } 764 765 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing. 766 /// OptionalBitList ::= '{' RangeList '}' 767 /// OptionalBitList ::= /*empty*/ 768 bool TGParser::ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges) { 769 SMLoc StartLoc = Lex.getLoc(); 770 if (!consume(tgtok::l_brace)) 771 return false; 772 773 // Parse the range list. 774 ParseRangeList(Ranges); 775 if (Ranges.empty()) return true; 776 777 if (!consume(tgtok::r_brace)) { 778 TokError("expected '}' at end of bit list"); 779 return Error(StartLoc, "to match this '{'"); 780 } 781 return false; 782 } 783 784 /// ParseType - Parse and return a tblgen type. This returns null on error. 785 /// 786 /// Type ::= STRING // string type 787 /// Type ::= CODE // code type 788 /// Type ::= BIT // bit type 789 /// Type ::= BITS '<' INTVAL '>' // bits<x> type 790 /// Type ::= INT // int type 791 /// Type ::= LIST '<' Type '>' // list<x> type 792 /// Type ::= DAG // dag type 793 /// Type ::= ClassID // Record Type 794 /// 795 RecTy *TGParser::ParseType() { 796 switch (Lex.getCode()) { 797 default: TokError("Unknown token when expecting a type"); return nullptr; 798 case tgtok::String: Lex.Lex(); return StringRecTy::get(); 799 case tgtok::Code: Lex.Lex(); return CodeRecTy::get(); 800 case tgtok::Bit: Lex.Lex(); return BitRecTy::get(); 801 case tgtok::Int: Lex.Lex(); return IntRecTy::get(); 802 case tgtok::Dag: Lex.Lex(); return DagRecTy::get(); 803 case tgtok::Id: 804 if (Record *R = ParseClassID()) return RecordRecTy::get(R); 805 TokError("unknown class name"); 806 return nullptr; 807 case tgtok::Bits: { 808 if (Lex.Lex() != tgtok::less) { // Eat 'bits' 809 TokError("expected '<' after bits type"); 810 return nullptr; 811 } 812 if (Lex.Lex() != tgtok::IntVal) { // Eat '<' 813 TokError("expected integer in bits<n> type"); 814 return nullptr; 815 } 816 uint64_t Val = Lex.getCurIntVal(); 817 if (Lex.Lex() != tgtok::greater) { // Eat count. 818 TokError("expected '>' at end of bits<n> type"); 819 return nullptr; 820 } 821 Lex.Lex(); // Eat '>' 822 return BitsRecTy::get(Val); 823 } 824 case tgtok::List: { 825 if (Lex.Lex() != tgtok::less) { // Eat 'bits' 826 TokError("expected '<' after list type"); 827 return nullptr; 828 } 829 Lex.Lex(); // Eat '<' 830 RecTy *SubType = ParseType(); 831 if (!SubType) return nullptr; 832 833 if (!consume(tgtok::greater)) { 834 TokError("expected '>' at end of list<ty> type"); 835 return nullptr; 836 } 837 return ListRecTy::get(SubType); 838 } 839 } 840 } 841 842 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID 843 /// has already been read. 844 Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMLoc NameLoc, 845 IDParseMode Mode) { 846 if (CurRec) { 847 if (const RecordVal *RV = CurRec->getValue(Name)) 848 return VarInit::get(Name, RV->getType()); 849 } 850 851 if ((CurRec && CurRec->isClass()) || CurMultiClass) { 852 Init *TemplateArgName; 853 if (CurMultiClass) { 854 TemplateArgName = 855 QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::"); 856 } else 857 TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":"); 858 859 Record *TemplateRec = CurMultiClass ? &CurMultiClass->Rec : CurRec; 860 if (TemplateRec->isTemplateArg(TemplateArgName)) { 861 const RecordVal *RV = TemplateRec->getValue(TemplateArgName); 862 assert(RV && "Template arg doesn't exist??"); 863 return VarInit::get(TemplateArgName, RV->getType()); 864 } else if (Name->getValue() == "NAME") { 865 return VarInit::get(TemplateArgName, StringRecTy::get()); 866 } 867 } 868 869 if (CurLocalScope) 870 if (Init *I = CurLocalScope->getVar(Name->getValue())) 871 return I; 872 873 // If this is in a foreach loop, make sure it's not a loop iterator 874 for (const auto &L : Loops) { 875 if (L->IterVar) { 876 VarInit *IterVar = dyn_cast<VarInit>(L->IterVar); 877 if (IterVar && IterVar->getNameInit() == Name) 878 return IterVar; 879 } 880 } 881 882 if (Mode == ParseNameMode) 883 return Name; 884 885 if (Init *I = Records.getGlobal(Name->getValue())) 886 return I; 887 888 // Allow self-references of concrete defs, but delay the lookup so that we 889 // get the correct type. 890 if (CurRec && !CurRec->isClass() && !CurMultiClass && 891 CurRec->getNameInit() == Name) 892 return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType()); 893 894 Error(NameLoc, "Variable not defined: '" + Name->getValue() + "'"); 895 return nullptr; 896 } 897 898 /// ParseOperation - Parse an operator. This returns null on error. 899 /// 900 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')' 901 /// 902 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) { 903 switch (Lex.getCode()) { 904 default: 905 TokError("unknown operation"); 906 return nullptr; 907 case tgtok::XHead: 908 case tgtok::XTail: 909 case tgtok::XSize: 910 case tgtok::XEmpty: 911 case tgtok::XCast: 912 case tgtok::XGetOp: { // Value ::= !unop '(' Value ')' 913 UnOpInit::UnaryOp Code; 914 RecTy *Type = nullptr; 915 916 switch (Lex.getCode()) { 917 default: llvm_unreachable("Unhandled code!"); 918 case tgtok::XCast: 919 Lex.Lex(); // eat the operation 920 Code = UnOpInit::CAST; 921 922 Type = ParseOperatorType(); 923 924 if (!Type) { 925 TokError("did not get type for unary operator"); 926 return nullptr; 927 } 928 929 break; 930 case tgtok::XHead: 931 Lex.Lex(); // eat the operation 932 Code = UnOpInit::HEAD; 933 break; 934 case tgtok::XTail: 935 Lex.Lex(); // eat the operation 936 Code = UnOpInit::TAIL; 937 break; 938 case tgtok::XSize: 939 Lex.Lex(); 940 Code = UnOpInit::SIZE; 941 Type = IntRecTy::get(); 942 break; 943 case tgtok::XEmpty: 944 Lex.Lex(); // eat the operation 945 Code = UnOpInit::EMPTY; 946 Type = IntRecTy::get(); 947 break; 948 case tgtok::XGetOp: 949 Lex.Lex(); // eat the operation 950 if (Lex.getCode() == tgtok::less) { 951 // Parse an optional type suffix, so that you can say 952 // !getop<BaseClass>(someDag) as a shorthand for 953 // !cast<BaseClass>(!getop(someDag)). 954 Type = ParseOperatorType(); 955 956 if (!Type) { 957 TokError("did not get type for unary operator"); 958 return nullptr; 959 } 960 961 if (!isa<RecordRecTy>(Type)) { 962 TokError("type for !getop must be a record type"); 963 // but keep parsing, to consume the operand 964 } 965 } else { 966 Type = RecordRecTy::get({}); 967 } 968 Code = UnOpInit::GETOP; 969 break; 970 } 971 if (!consume(tgtok::l_paren)) { 972 TokError("expected '(' after unary operator"); 973 return nullptr; 974 } 975 976 Init *LHS = ParseValue(CurRec); 977 if (!LHS) return nullptr; 978 979 if (Code == UnOpInit::HEAD || 980 Code == UnOpInit::TAIL || 981 Code == UnOpInit::EMPTY) { 982 ListInit *LHSl = dyn_cast<ListInit>(LHS); 983 StringInit *LHSs = dyn_cast<StringInit>(LHS); 984 TypedInit *LHSt = dyn_cast<TypedInit>(LHS); 985 if (!LHSl && !LHSs && !LHSt) { 986 TokError("expected list or string type argument in unary operator"); 987 return nullptr; 988 } 989 if (LHSt) { 990 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType()); 991 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType()); 992 if (!LType && !SType) { 993 TokError("expected list or string type argument in unary operator"); 994 return nullptr; 995 } 996 } 997 998 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL || 999 Code == UnOpInit::SIZE) { 1000 if (!LHSl && !LHSt) { 1001 TokError("expected list type argument in unary operator"); 1002 return nullptr; 1003 } 1004 } 1005 1006 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) { 1007 if (LHSl && LHSl->empty()) { 1008 TokError("empty list argument in unary operator"); 1009 return nullptr; 1010 } 1011 if (LHSl) { 1012 Init *Item = LHSl->getElement(0); 1013 TypedInit *Itemt = dyn_cast<TypedInit>(Item); 1014 if (!Itemt) { 1015 TokError("untyped list element in unary operator"); 1016 return nullptr; 1017 } 1018 Type = (Code == UnOpInit::HEAD) ? Itemt->getType() 1019 : ListRecTy::get(Itemt->getType()); 1020 } else { 1021 assert(LHSt && "expected list type argument in unary operator"); 1022 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType()); 1023 if (!LType) { 1024 TokError("expected list type argument in unary operator"); 1025 return nullptr; 1026 } 1027 Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType; 1028 } 1029 } 1030 } 1031 1032 if (!consume(tgtok::r_paren)) { 1033 TokError("expected ')' in unary operator"); 1034 return nullptr; 1035 } 1036 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec); 1037 } 1038 1039 case tgtok::XIsA: { 1040 // Value ::= !isa '<' Type '>' '(' Value ')' 1041 Lex.Lex(); // eat the operation 1042 1043 RecTy *Type = ParseOperatorType(); 1044 if (!Type) 1045 return nullptr; 1046 1047 if (!consume(tgtok::l_paren)) { 1048 TokError("expected '(' after type of !isa"); 1049 return nullptr; 1050 } 1051 1052 Init *LHS = ParseValue(CurRec); 1053 if (!LHS) 1054 return nullptr; 1055 1056 if (!consume(tgtok::r_paren)) { 1057 TokError("expected ')' in !isa"); 1058 return nullptr; 1059 } 1060 1061 return (IsAOpInit::get(Type, LHS))->Fold(); 1062 } 1063 1064 case tgtok::XConcat: 1065 case tgtok::XADD: 1066 case tgtok::XMUL: 1067 case tgtok::XAND: 1068 case tgtok::XOR: 1069 case tgtok::XSRA: 1070 case tgtok::XSRL: 1071 case tgtok::XSHL: 1072 case tgtok::XEq: 1073 case tgtok::XNe: 1074 case tgtok::XLe: 1075 case tgtok::XLt: 1076 case tgtok::XGe: 1077 case tgtok::XGt: 1078 case tgtok::XListConcat: 1079 case tgtok::XListSplat: 1080 case tgtok::XStrConcat: 1081 case tgtok::XSetOp: { // Value ::= !binop '(' Value ',' Value ')' 1082 tgtok::TokKind OpTok = Lex.getCode(); 1083 SMLoc OpLoc = Lex.getLoc(); 1084 Lex.Lex(); // eat the operation 1085 1086 BinOpInit::BinaryOp Code; 1087 switch (OpTok) { 1088 default: llvm_unreachable("Unhandled code!"); 1089 case tgtok::XConcat: Code = BinOpInit::CONCAT; break; 1090 case tgtok::XADD: Code = BinOpInit::ADD; break; 1091 case tgtok::XMUL: Code = BinOpInit::MUL; break; 1092 case tgtok::XAND: Code = BinOpInit::AND; break; 1093 case tgtok::XOR: Code = BinOpInit::OR; break; 1094 case tgtok::XSRA: Code = BinOpInit::SRA; break; 1095 case tgtok::XSRL: Code = BinOpInit::SRL; break; 1096 case tgtok::XSHL: Code = BinOpInit::SHL; break; 1097 case tgtok::XEq: Code = BinOpInit::EQ; break; 1098 case tgtok::XNe: Code = BinOpInit::NE; break; 1099 case tgtok::XLe: Code = BinOpInit::LE; break; 1100 case tgtok::XLt: Code = BinOpInit::LT; break; 1101 case tgtok::XGe: Code = BinOpInit::GE; break; 1102 case tgtok::XGt: Code = BinOpInit::GT; break; 1103 case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break; 1104 case tgtok::XListSplat: Code = BinOpInit::LISTSPLAT; break; 1105 case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break; 1106 case tgtok::XSetOp: Code = BinOpInit::SETOP; break; 1107 } 1108 1109 RecTy *Type = nullptr; 1110 RecTy *ArgType = nullptr; 1111 switch (OpTok) { 1112 default: 1113 llvm_unreachable("Unhandled code!"); 1114 case tgtok::XConcat: 1115 case tgtok::XSetOp: 1116 Type = DagRecTy::get(); 1117 ArgType = DagRecTy::get(); 1118 break; 1119 case tgtok::XAND: 1120 case tgtok::XOR: 1121 case tgtok::XSRA: 1122 case tgtok::XSRL: 1123 case tgtok::XSHL: 1124 case tgtok::XADD: 1125 case tgtok::XMUL: 1126 Type = IntRecTy::get(); 1127 ArgType = IntRecTy::get(); 1128 break; 1129 case tgtok::XEq: 1130 case tgtok::XNe: 1131 Type = BitRecTy::get(); 1132 // ArgType for Eq / Ne is not known at this point 1133 break; 1134 case tgtok::XLe: 1135 case tgtok::XLt: 1136 case tgtok::XGe: 1137 case tgtok::XGt: 1138 Type = BitRecTy::get(); 1139 ArgType = IntRecTy::get(); 1140 break; 1141 case tgtok::XListConcat: 1142 // We don't know the list type until we parse the first argument 1143 ArgType = ItemType; 1144 break; 1145 case tgtok::XListSplat: 1146 // Can't do any typechecking until we parse the first argument. 1147 break; 1148 case tgtok::XStrConcat: 1149 Type = StringRecTy::get(); 1150 ArgType = StringRecTy::get(); 1151 break; 1152 } 1153 1154 if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) { 1155 Error(OpLoc, Twine("expected value of type '") + 1156 ItemType->getAsString() + "', got '" + 1157 Type->getAsString() + "'"); 1158 return nullptr; 1159 } 1160 1161 if (!consume(tgtok::l_paren)) { 1162 TokError("expected '(' after binary operator"); 1163 return nullptr; 1164 } 1165 1166 SmallVector<Init*, 2> InitList; 1167 1168 for (;;) { 1169 SMLoc InitLoc = Lex.getLoc(); 1170 InitList.push_back(ParseValue(CurRec, ArgType)); 1171 if (!InitList.back()) return nullptr; 1172 1173 TypedInit *InitListBack = dyn_cast<TypedInit>(InitList.back()); 1174 if (!InitListBack) { 1175 Error(OpLoc, Twine("expected value to be a typed value, got '" + 1176 InitList.back()->getAsString() + "'")); 1177 return nullptr; 1178 } 1179 RecTy *ListType = InitListBack->getType(); 1180 if (!ArgType) { 1181 ArgType = ListType; 1182 1183 switch (Code) { 1184 case BinOpInit::LISTCONCAT: 1185 if (!isa<ListRecTy>(ArgType)) { 1186 Error(InitLoc, Twine("expected a list, got value of type '") + 1187 ArgType->getAsString() + "'"); 1188 return nullptr; 1189 } 1190 break; 1191 case BinOpInit::LISTSPLAT: 1192 if (ItemType && InitList.size() == 1) { 1193 if (!isa<ListRecTy>(ItemType)) { 1194 Error(OpLoc, 1195 Twine("expected output type to be a list, got type '") + 1196 ItemType->getAsString() + "'"); 1197 return nullptr; 1198 } 1199 if (!ArgType->getListTy()->typeIsConvertibleTo(ItemType)) { 1200 Error(OpLoc, Twine("expected first arg type to be '") + 1201 ArgType->getAsString() + 1202 "', got value of type '" + 1203 cast<ListRecTy>(ItemType) 1204 ->getElementType() 1205 ->getAsString() + 1206 "'"); 1207 return nullptr; 1208 } 1209 } 1210 if (InitList.size() == 2 && !isa<IntRecTy>(ArgType)) { 1211 Error(InitLoc, Twine("expected second parameter to be an int, got " 1212 "value of type '") + 1213 ArgType->getAsString() + "'"); 1214 return nullptr; 1215 } 1216 ArgType = nullptr; // Broken invariant: types not identical. 1217 break; 1218 case BinOpInit::EQ: 1219 case BinOpInit::NE: 1220 if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) && 1221 !ArgType->typeIsConvertibleTo(StringRecTy::get())) { 1222 Error(InitLoc, Twine("expected int, bits, or string; got value of " 1223 "type '") + ArgType->getAsString() + "'"); 1224 return nullptr; 1225 } 1226 break; 1227 default: llvm_unreachable("other ops have fixed argument types"); 1228 } 1229 } else { 1230 RecTy *Resolved = resolveTypes(ArgType, ListType); 1231 if (!Resolved) { 1232 Error(InitLoc, Twine("expected value of type '") + 1233 ArgType->getAsString() + "', got '" + 1234 ListType->getAsString() + "'"); 1235 return nullptr; 1236 } 1237 if (Code != BinOpInit::ADD && Code != BinOpInit::AND && 1238 Code != BinOpInit::OR && Code != BinOpInit::SRA && 1239 Code != BinOpInit::SRL && Code != BinOpInit::SHL && 1240 Code != BinOpInit::MUL) 1241 ArgType = Resolved; 1242 } 1243 1244 // Deal with BinOps whose arguments have different types, by 1245 // rewriting ArgType in between them. 1246 switch (Code) { 1247 case BinOpInit::SETOP: 1248 // After parsing the first dag argument, switch to expecting 1249 // a record, with no restriction on its superclasses. 1250 ArgType = RecordRecTy::get({}); 1251 break; 1252 default: 1253 break; 1254 } 1255 1256 if (!consume(tgtok::comma)) 1257 break; 1258 } 1259 1260 if (!consume(tgtok::r_paren)) { 1261 TokError("expected ')' in operator"); 1262 return nullptr; 1263 } 1264 1265 // listconcat returns a list with type of the argument. 1266 if (Code == BinOpInit::LISTCONCAT) 1267 Type = ArgType; 1268 // listsplat returns a list of type of the *first* argument. 1269 if (Code == BinOpInit::LISTSPLAT) 1270 Type = cast<TypedInit>(InitList.front())->getType()->getListTy(); 1271 1272 // We allow multiple operands to associative operators like !strconcat as 1273 // shorthand for nesting them. 1274 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT || 1275 Code == BinOpInit::CONCAT || Code == BinOpInit::ADD || 1276 Code == BinOpInit::AND || Code == BinOpInit::OR || 1277 Code == BinOpInit::MUL) { 1278 while (InitList.size() > 2) { 1279 Init *RHS = InitList.pop_back_val(); 1280 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec); 1281 InitList.back() = RHS; 1282 } 1283 } 1284 1285 if (InitList.size() == 2) 1286 return (BinOpInit::get(Code, InitList[0], InitList[1], Type)) 1287 ->Fold(CurRec); 1288 1289 Error(OpLoc, "expected two operands to operator"); 1290 return nullptr; 1291 } 1292 1293 case tgtok::XForEach: { // Value ::= !foreach '(' Id ',' Value ',' Value ')' 1294 SMLoc OpLoc = Lex.getLoc(); 1295 Lex.Lex(); // eat the operation 1296 if (Lex.getCode() != tgtok::l_paren) { 1297 TokError("expected '(' after !foreach"); 1298 return nullptr; 1299 } 1300 1301 if (Lex.Lex() != tgtok::Id) { // eat the '(' 1302 TokError("first argument of !foreach must be an identifier"); 1303 return nullptr; 1304 } 1305 1306 Init *LHS = StringInit::get(Lex.getCurStrVal()); 1307 Lex.Lex(); 1308 1309 if (CurRec && CurRec->getValue(LHS)) { 1310 TokError((Twine("iteration variable '") + LHS->getAsString() + 1311 "' already defined") 1312 .str()); 1313 return nullptr; 1314 } 1315 1316 if (!consume(tgtok::comma)) { // eat the id 1317 TokError("expected ',' in ternary operator"); 1318 return nullptr; 1319 } 1320 1321 Init *MHS = ParseValue(CurRec); 1322 if (!MHS) 1323 return nullptr; 1324 1325 if (!consume(tgtok::comma)) { 1326 TokError("expected ',' in ternary operator"); 1327 return nullptr; 1328 } 1329 1330 TypedInit *MHSt = dyn_cast<TypedInit>(MHS); 1331 if (!MHSt) { 1332 TokError("could not get type of !foreach input"); 1333 return nullptr; 1334 } 1335 1336 RecTy *InEltType = nullptr; 1337 RecTy *OutEltType = nullptr; 1338 bool IsDAG = false; 1339 1340 if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) { 1341 InEltType = InListTy->getElementType(); 1342 if (ItemType) { 1343 if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) { 1344 OutEltType = OutListTy->getElementType(); 1345 } else { 1346 Error(OpLoc, 1347 "expected value of type '" + Twine(ItemType->getAsString()) + 1348 "', but got !foreach of list type"); 1349 return nullptr; 1350 } 1351 } 1352 } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) { 1353 InEltType = InDagTy; 1354 if (ItemType && !isa<DagRecTy>(ItemType)) { 1355 Error(OpLoc, 1356 "expected value of type '" + Twine(ItemType->getAsString()) + 1357 "', but got !foreach of dag type"); 1358 return nullptr; 1359 } 1360 IsDAG = true; 1361 } else { 1362 TokError("!foreach must have list or dag input"); 1363 return nullptr; 1364 } 1365 1366 // We need to create a temporary record to provide a scope for the iteration 1367 // variable while parsing top-level foreach's. 1368 std::unique_ptr<Record> ParseRecTmp; 1369 Record *ParseRec = CurRec; 1370 if (!ParseRec) { 1371 ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records); 1372 ParseRec = ParseRecTmp.get(); 1373 } 1374 1375 ParseRec->addValue(RecordVal(LHS, InEltType, false)); 1376 Init *RHS = ParseValue(ParseRec, OutEltType); 1377 ParseRec->removeValue(LHS); 1378 if (!RHS) 1379 return nullptr; 1380 1381 if (!consume(tgtok::r_paren)) { 1382 TokError("expected ')' in binary operator"); 1383 return nullptr; 1384 } 1385 1386 RecTy *OutType; 1387 if (IsDAG) { 1388 OutType = InEltType; 1389 } else { 1390 TypedInit *RHSt = dyn_cast<TypedInit>(RHS); 1391 if (!RHSt) { 1392 TokError("could not get type of !foreach result"); 1393 return nullptr; 1394 } 1395 OutType = RHSt->getType()->getListTy(); 1396 } 1397 1398 return (TernOpInit::get(TernOpInit::FOREACH, LHS, MHS, RHS, OutType)) 1399 ->Fold(CurRec); 1400 } 1401 1402 case tgtok::XDag: 1403 case tgtok::XIf: 1404 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')' 1405 TernOpInit::TernaryOp Code; 1406 RecTy *Type = nullptr; 1407 1408 tgtok::TokKind LexCode = Lex.getCode(); 1409 Lex.Lex(); // eat the operation 1410 switch (LexCode) { 1411 default: llvm_unreachable("Unhandled code!"); 1412 case tgtok::XDag: 1413 Code = TernOpInit::DAG; 1414 Type = DagRecTy::get(); 1415 ItemType = nullptr; 1416 break; 1417 case tgtok::XIf: 1418 Code = TernOpInit::IF; 1419 break; 1420 case tgtok::XSubst: 1421 Code = TernOpInit::SUBST; 1422 break; 1423 } 1424 if (!consume(tgtok::l_paren)) { 1425 TokError("expected '(' after ternary operator"); 1426 return nullptr; 1427 } 1428 1429 Init *LHS = ParseValue(CurRec); 1430 if (!LHS) return nullptr; 1431 1432 if (!consume(tgtok::comma)) { 1433 TokError("expected ',' in ternary operator"); 1434 return nullptr; 1435 } 1436 1437 SMLoc MHSLoc = Lex.getLoc(); 1438 Init *MHS = ParseValue(CurRec, ItemType); 1439 if (!MHS) 1440 return nullptr; 1441 1442 if (!consume(tgtok::comma)) { 1443 TokError("expected ',' in ternary operator"); 1444 return nullptr; 1445 } 1446 1447 SMLoc RHSLoc = Lex.getLoc(); 1448 Init *RHS = ParseValue(CurRec, ItemType); 1449 if (!RHS) 1450 return nullptr; 1451 1452 if (!consume(tgtok::r_paren)) { 1453 TokError("expected ')' in binary operator"); 1454 return nullptr; 1455 } 1456 1457 switch (LexCode) { 1458 default: llvm_unreachable("Unhandled code!"); 1459 case tgtok::XDag: { 1460 TypedInit *MHSt = dyn_cast<TypedInit>(MHS); 1461 if (!MHSt && !isa<UnsetInit>(MHS)) { 1462 Error(MHSLoc, "could not determine type of the child list in !dag"); 1463 return nullptr; 1464 } 1465 if (MHSt && !isa<ListRecTy>(MHSt->getType())) { 1466 Error(MHSLoc, Twine("expected list of children, got type '") + 1467 MHSt->getType()->getAsString() + "'"); 1468 return nullptr; 1469 } 1470 1471 TypedInit *RHSt = dyn_cast<TypedInit>(RHS); 1472 if (!RHSt && !isa<UnsetInit>(RHS)) { 1473 Error(RHSLoc, "could not determine type of the name list in !dag"); 1474 return nullptr; 1475 } 1476 if (RHSt && StringRecTy::get()->getListTy() != RHSt->getType()) { 1477 Error(RHSLoc, Twine("expected list<string>, got type '") + 1478 RHSt->getType()->getAsString() + "'"); 1479 return nullptr; 1480 } 1481 1482 if (!MHSt && !RHSt) { 1483 Error(MHSLoc, 1484 "cannot have both unset children and unset names in !dag"); 1485 return nullptr; 1486 } 1487 break; 1488 } 1489 case tgtok::XIf: { 1490 RecTy *MHSTy = nullptr; 1491 RecTy *RHSTy = nullptr; 1492 1493 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS)) 1494 MHSTy = MHSt->getType(); 1495 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS)) 1496 MHSTy = BitsRecTy::get(MHSbits->getNumBits()); 1497 if (isa<BitInit>(MHS)) 1498 MHSTy = BitRecTy::get(); 1499 1500 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS)) 1501 RHSTy = RHSt->getType(); 1502 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS)) 1503 RHSTy = BitsRecTy::get(RHSbits->getNumBits()); 1504 if (isa<BitInit>(RHS)) 1505 RHSTy = BitRecTy::get(); 1506 1507 // For UnsetInit, it's typed from the other hand. 1508 if (isa<UnsetInit>(MHS)) 1509 MHSTy = RHSTy; 1510 if (isa<UnsetInit>(RHS)) 1511 RHSTy = MHSTy; 1512 1513 if (!MHSTy || !RHSTy) { 1514 TokError("could not get type for !if"); 1515 return nullptr; 1516 } 1517 1518 Type = resolveTypes(MHSTy, RHSTy); 1519 if (!Type) { 1520 TokError(Twine("inconsistent types '") + MHSTy->getAsString() + 1521 "' and '" + RHSTy->getAsString() + "' for !if"); 1522 return nullptr; 1523 } 1524 break; 1525 } 1526 case tgtok::XSubst: { 1527 TypedInit *RHSt = dyn_cast<TypedInit>(RHS); 1528 if (!RHSt) { 1529 TokError("could not get type for !subst"); 1530 return nullptr; 1531 } 1532 Type = RHSt->getType(); 1533 break; 1534 } 1535 } 1536 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec); 1537 } 1538 1539 case tgtok::XCond: 1540 return ParseOperationCond(CurRec, ItemType); 1541 1542 case tgtok::XFoldl: { 1543 // Value ::= !foldl '(' Id ',' Id ',' Value ',' Value ',' Value ')' 1544 Lex.Lex(); // eat the operation 1545 if (!consume(tgtok::l_paren)) { 1546 TokError("expected '(' after !foldl"); 1547 return nullptr; 1548 } 1549 1550 Init *StartUntyped = ParseValue(CurRec); 1551 if (!StartUntyped) 1552 return nullptr; 1553 1554 TypedInit *Start = dyn_cast<TypedInit>(StartUntyped); 1555 if (!Start) { 1556 TokError(Twine("could not get type of !foldl start: '") + 1557 StartUntyped->getAsString() + "'"); 1558 return nullptr; 1559 } 1560 1561 if (!consume(tgtok::comma)) { 1562 TokError("expected ',' in !foldl"); 1563 return nullptr; 1564 } 1565 1566 Init *ListUntyped = ParseValue(CurRec); 1567 if (!ListUntyped) 1568 return nullptr; 1569 1570 TypedInit *List = dyn_cast<TypedInit>(ListUntyped); 1571 if (!List) { 1572 TokError(Twine("could not get type of !foldl list: '") + 1573 ListUntyped->getAsString() + "'"); 1574 return nullptr; 1575 } 1576 1577 ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType()); 1578 if (!ListType) { 1579 TokError(Twine("!foldl list must be a list, but is of type '") + 1580 List->getType()->getAsString()); 1581 return nullptr; 1582 } 1583 1584 if (Lex.getCode() != tgtok::comma) { 1585 TokError("expected ',' in !foldl"); 1586 return nullptr; 1587 } 1588 1589 if (Lex.Lex() != tgtok::Id) { // eat the ',' 1590 TokError("third argument of !foldl must be an identifier"); 1591 return nullptr; 1592 } 1593 1594 Init *A = StringInit::get(Lex.getCurStrVal()); 1595 if (CurRec && CurRec->getValue(A)) { 1596 TokError((Twine("left !foldl variable '") + A->getAsString() + 1597 "' already defined") 1598 .str()); 1599 return nullptr; 1600 } 1601 1602 if (Lex.Lex() != tgtok::comma) { // eat the id 1603 TokError("expected ',' in !foldl"); 1604 return nullptr; 1605 } 1606 1607 if (Lex.Lex() != tgtok::Id) { // eat the ',' 1608 TokError("fourth argument of !foldl must be an identifier"); 1609 return nullptr; 1610 } 1611 1612 Init *B = StringInit::get(Lex.getCurStrVal()); 1613 if (CurRec && CurRec->getValue(B)) { 1614 TokError((Twine("right !foldl variable '") + B->getAsString() + 1615 "' already defined") 1616 .str()); 1617 return nullptr; 1618 } 1619 1620 if (Lex.Lex() != tgtok::comma) { // eat the id 1621 TokError("expected ',' in !foldl"); 1622 return nullptr; 1623 } 1624 Lex.Lex(); // eat the ',' 1625 1626 // We need to create a temporary record to provide a scope for the iteration 1627 // variable while parsing top-level foreach's. 1628 std::unique_ptr<Record> ParseRecTmp; 1629 Record *ParseRec = CurRec; 1630 if (!ParseRec) { 1631 ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records); 1632 ParseRec = ParseRecTmp.get(); 1633 } 1634 1635 ParseRec->addValue(RecordVal(A, Start->getType(), false)); 1636 ParseRec->addValue(RecordVal(B, ListType->getElementType(), false)); 1637 Init *ExprUntyped = ParseValue(ParseRec); 1638 ParseRec->removeValue(A); 1639 ParseRec->removeValue(B); 1640 if (!ExprUntyped) 1641 return nullptr; 1642 1643 TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped); 1644 if (!Expr) { 1645 TokError("could not get type of !foldl expression"); 1646 return nullptr; 1647 } 1648 1649 if (Expr->getType() != Start->getType()) { 1650 TokError(Twine("!foldl expression must be of same type as start (") + 1651 Start->getType()->getAsString() + "), but is of type " + 1652 Expr->getType()->getAsString()); 1653 return nullptr; 1654 } 1655 1656 if (!consume(tgtok::r_paren)) { 1657 TokError("expected ')' in fold operator"); 1658 return nullptr; 1659 } 1660 1661 return FoldOpInit::get(Start, List, A, B, Expr, Start->getType()) 1662 ->Fold(CurRec); 1663 } 1664 } 1665 } 1666 1667 /// ParseOperatorType - Parse a type for an operator. This returns 1668 /// null on error. 1669 /// 1670 /// OperatorType ::= '<' Type '>' 1671 /// 1672 RecTy *TGParser::ParseOperatorType() { 1673 RecTy *Type = nullptr; 1674 1675 if (!consume(tgtok::less)) { 1676 TokError("expected type name for operator"); 1677 return nullptr; 1678 } 1679 1680 Type = ParseType(); 1681 1682 if (!Type) { 1683 TokError("expected type name for operator"); 1684 return nullptr; 1685 } 1686 1687 if (!consume(tgtok::greater)) { 1688 TokError("expected type name for operator"); 1689 return nullptr; 1690 } 1691 1692 return Type; 1693 } 1694 1695 Init *TGParser::ParseOperationCond(Record *CurRec, RecTy *ItemType) { 1696 Lex.Lex(); // eat the operation 'cond' 1697 1698 if (!consume(tgtok::l_paren)) { 1699 TokError("expected '(' after !cond operator"); 1700 return nullptr; 1701 } 1702 1703 // Parse through '[Case: Val,]+' 1704 SmallVector<Init *, 4> Case; 1705 SmallVector<Init *, 4> Val; 1706 while (true) { 1707 if (consume(tgtok::r_paren)) 1708 break; 1709 1710 Init *V = ParseValue(CurRec); 1711 if (!V) 1712 return nullptr; 1713 Case.push_back(V); 1714 1715 if (!consume(tgtok::colon)) { 1716 TokError("expected ':' following a condition in !cond operator"); 1717 return nullptr; 1718 } 1719 1720 V = ParseValue(CurRec, ItemType); 1721 if (!V) 1722 return nullptr; 1723 Val.push_back(V); 1724 1725 if (consume(tgtok::r_paren)) 1726 break; 1727 1728 if (!consume(tgtok::comma)) { 1729 TokError("expected ',' or ')' following a value in !cond operator"); 1730 return nullptr; 1731 } 1732 } 1733 1734 if (Case.size() < 1) { 1735 TokError("there should be at least 1 'condition : value' in the !cond operator"); 1736 return nullptr; 1737 } 1738 1739 // resolve type 1740 RecTy *Type = nullptr; 1741 for (Init *V : Val) { 1742 RecTy *VTy = nullptr; 1743 if (TypedInit *Vt = dyn_cast<TypedInit>(V)) 1744 VTy = Vt->getType(); 1745 if (BitsInit *Vbits = dyn_cast<BitsInit>(V)) 1746 VTy = BitsRecTy::get(Vbits->getNumBits()); 1747 if (isa<BitInit>(V)) 1748 VTy = BitRecTy::get(); 1749 1750 if (Type == nullptr) { 1751 if (!isa<UnsetInit>(V)) 1752 Type = VTy; 1753 } else { 1754 if (!isa<UnsetInit>(V)) { 1755 RecTy *RType = resolveTypes(Type, VTy); 1756 if (!RType) { 1757 TokError(Twine("inconsistent types '") + Type->getAsString() + 1758 "' and '" + VTy->getAsString() + "' for !cond"); 1759 return nullptr; 1760 } 1761 Type = RType; 1762 } 1763 } 1764 } 1765 1766 if (!Type) { 1767 TokError("could not determine type for !cond from its arguments"); 1768 return nullptr; 1769 } 1770 return CondOpInit::get(Case, Val, Type)->Fold(CurRec); 1771 } 1772 1773 /// ParseSimpleValue - Parse a tblgen value. This returns null on error. 1774 /// 1775 /// SimpleValue ::= IDValue 1776 /// SimpleValue ::= INTVAL 1777 /// SimpleValue ::= STRVAL+ 1778 /// SimpleValue ::= CODEFRAGMENT 1779 /// SimpleValue ::= '?' 1780 /// SimpleValue ::= '{' ValueList '}' 1781 /// SimpleValue ::= ID '<' ValueListNE '>' 1782 /// SimpleValue ::= '[' ValueList ']' 1783 /// SimpleValue ::= '(' IDValue DagArgList ')' 1784 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')' 1785 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')' 1786 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')' 1787 /// SimpleValue ::= SRATOK '(' Value ',' Value ')' 1788 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')' 1789 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')' 1790 /// SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')' 1791 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')' 1792 /// SimpleValue ::= COND '(' [Value ':' Value,]+ ')' 1793 /// 1794 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType, 1795 IDParseMode Mode) { 1796 Init *R = nullptr; 1797 switch (Lex.getCode()) { 1798 default: TokError("Unknown token when parsing a value"); break; 1799 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break; 1800 case tgtok::BinaryIntVal: { 1801 auto BinaryVal = Lex.getCurBinaryIntVal(); 1802 SmallVector<Init*, 16> Bits(BinaryVal.second); 1803 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i) 1804 Bits[i] = BitInit::get(BinaryVal.first & (1LL << i)); 1805 R = BitsInit::get(Bits); 1806 Lex.Lex(); 1807 break; 1808 } 1809 case tgtok::StrVal: { 1810 std::string Val = Lex.getCurStrVal(); 1811 Lex.Lex(); 1812 1813 // Handle multiple consecutive concatenated strings. 1814 while (Lex.getCode() == tgtok::StrVal) { 1815 Val += Lex.getCurStrVal(); 1816 Lex.Lex(); 1817 } 1818 1819 R = StringInit::get(Val); 1820 break; 1821 } 1822 case tgtok::CodeFragment: 1823 R = CodeInit::get(Lex.getCurStrVal(), Lex.getLoc()); 1824 Lex.Lex(); 1825 break; 1826 case tgtok::question: 1827 R = UnsetInit::get(); 1828 Lex.Lex(); 1829 break; 1830 case tgtok::Id: { 1831 SMLoc NameLoc = Lex.getLoc(); 1832 StringInit *Name = StringInit::get(Lex.getCurStrVal()); 1833 if (Lex.Lex() != tgtok::less) // consume the Id. 1834 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue 1835 1836 // Value ::= ID '<' ValueListNE '>' 1837 if (Lex.Lex() == tgtok::greater) { 1838 TokError("expected non-empty value list"); 1839 return nullptr; 1840 } 1841 1842 // This is a CLASS<initvalslist> expression. This is supposed to synthesize 1843 // a new anonymous definition, deriving from CLASS<initvalslist> with no 1844 // body. 1845 Record *Class = Records.getClass(Name->getValue()); 1846 if (!Class) { 1847 Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'"); 1848 return nullptr; 1849 } 1850 1851 SmallVector<Init *, 8> Args; 1852 ParseValueList(Args, CurRec, Class); 1853 if (Args.empty()) return nullptr; 1854 1855 if (!consume(tgtok::greater)) { 1856 TokError("expected '>' at end of value list"); 1857 return nullptr; 1858 } 1859 1860 // Typecheck the template arguments list 1861 ArrayRef<Init *> ExpectedArgs = Class->getTemplateArgs(); 1862 if (ExpectedArgs.size() < Args.size()) { 1863 Error(NameLoc, 1864 "More template args specified than expected"); 1865 return nullptr; 1866 } 1867 1868 for (unsigned i = 0, e = ExpectedArgs.size(); i != e; ++i) { 1869 RecordVal *ExpectedArg = Class->getValue(ExpectedArgs[i]); 1870 if (i < Args.size()) { 1871 if (TypedInit *TI = dyn_cast<TypedInit>(Args[i])) { 1872 RecTy *ExpectedType = ExpectedArg->getType(); 1873 if (!TI->getType()->typeIsConvertibleTo(ExpectedType)) { 1874 Error(NameLoc, 1875 "Value specified for template argument #" + Twine(i) + " (" + 1876 ExpectedArg->getNameInitAsString() + ") is of type '" + 1877 TI->getType()->getAsString() + "', expected '" + 1878 ExpectedType->getAsString() + "': " + TI->getAsString()); 1879 return nullptr; 1880 } 1881 continue; 1882 } 1883 } else if (ExpectedArg->getValue()->isComplete()) 1884 continue; 1885 1886 Error(NameLoc, 1887 "Value not specified for template argument #" + Twine(i) + " (" + 1888 ExpectedArgs[i]->getAsUnquotedString() + ")"); 1889 return nullptr; 1890 } 1891 1892 return VarDefInit::get(Class, Args)->Fold(); 1893 } 1894 case tgtok::l_brace: { // Value ::= '{' ValueList '}' 1895 SMLoc BraceLoc = Lex.getLoc(); 1896 Lex.Lex(); // eat the '{' 1897 SmallVector<Init*, 16> Vals; 1898 1899 if (Lex.getCode() != tgtok::r_brace) { 1900 ParseValueList(Vals, CurRec); 1901 if (Vals.empty()) return nullptr; 1902 } 1903 if (!consume(tgtok::r_brace)) { 1904 TokError("expected '}' at end of bit list value"); 1905 return nullptr; 1906 } 1907 1908 SmallVector<Init *, 16> NewBits; 1909 1910 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it 1911 // first. We'll first read everything in to a vector, then we can reverse 1912 // it to get the bits in the correct order for the BitsInit value. 1913 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 1914 // FIXME: The following two loops would not be duplicated 1915 // if the API was a little more orthogonal. 1916 1917 // bits<n> values are allowed to initialize n bits. 1918 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) { 1919 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) 1920 NewBits.push_back(BI->getBit((e - i) - 1)); 1921 continue; 1922 } 1923 // bits<n> can also come from variable initializers. 1924 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) { 1925 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) { 1926 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i) 1927 NewBits.push_back(VI->getBit((e - i) - 1)); 1928 continue; 1929 } 1930 // Fallthrough to try convert this to a bit. 1931 } 1932 // All other values must be convertible to just a single bit. 1933 Init *Bit = Vals[i]->getCastTo(BitRecTy::get()); 1934 if (!Bit) { 1935 Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() + 1936 ") is not convertable to a bit"); 1937 return nullptr; 1938 } 1939 NewBits.push_back(Bit); 1940 } 1941 std::reverse(NewBits.begin(), NewBits.end()); 1942 return BitsInit::get(NewBits); 1943 } 1944 case tgtok::l_square: { // Value ::= '[' ValueList ']' 1945 Lex.Lex(); // eat the '[' 1946 SmallVector<Init*, 16> Vals; 1947 1948 RecTy *DeducedEltTy = nullptr; 1949 ListRecTy *GivenListTy = nullptr; 1950 1951 if (ItemType) { 1952 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType); 1953 if (!ListType) { 1954 TokError(Twine("Type mismatch for list, expected list type, got ") + 1955 ItemType->getAsString()); 1956 return nullptr; 1957 } 1958 GivenListTy = ListType; 1959 } 1960 1961 if (Lex.getCode() != tgtok::r_square) { 1962 ParseValueList(Vals, CurRec, nullptr, 1963 GivenListTy ? GivenListTy->getElementType() : nullptr); 1964 if (Vals.empty()) return nullptr; 1965 } 1966 if (!consume(tgtok::r_square)) { 1967 TokError("expected ']' at end of list value"); 1968 return nullptr; 1969 } 1970 1971 RecTy *GivenEltTy = nullptr; 1972 if (consume(tgtok::less)) { 1973 // Optional list element type 1974 GivenEltTy = ParseType(); 1975 if (!GivenEltTy) { 1976 // Couldn't parse element type 1977 return nullptr; 1978 } 1979 1980 if (!consume(tgtok::greater)) { 1981 TokError("expected '>' at end of list element type"); 1982 return nullptr; 1983 } 1984 } 1985 1986 // Check elements 1987 RecTy *EltTy = nullptr; 1988 for (Init *V : Vals) { 1989 TypedInit *TArg = dyn_cast<TypedInit>(V); 1990 if (TArg) { 1991 if (EltTy) { 1992 EltTy = resolveTypes(EltTy, TArg->getType()); 1993 if (!EltTy) { 1994 TokError("Incompatible types in list elements"); 1995 return nullptr; 1996 } 1997 } else { 1998 EltTy = TArg->getType(); 1999 } 2000 } 2001 } 2002 2003 if (GivenEltTy) { 2004 if (EltTy) { 2005 // Verify consistency 2006 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) { 2007 TokError("Incompatible types in list elements"); 2008 return nullptr; 2009 } 2010 } 2011 EltTy = GivenEltTy; 2012 } 2013 2014 if (!EltTy) { 2015 if (!ItemType) { 2016 TokError("No type for list"); 2017 return nullptr; 2018 } 2019 DeducedEltTy = GivenListTy->getElementType(); 2020 } else { 2021 // Make sure the deduced type is compatible with the given type 2022 if (GivenListTy) { 2023 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) { 2024 TokError(Twine("Element type mismatch for list: element type '") + 2025 EltTy->getAsString() + "' not convertible to '" + 2026 GivenListTy->getElementType()->getAsString()); 2027 return nullptr; 2028 } 2029 } 2030 DeducedEltTy = EltTy; 2031 } 2032 2033 return ListInit::get(Vals, DeducedEltTy); 2034 } 2035 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')' 2036 Lex.Lex(); // eat the '(' 2037 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast && 2038 Lex.getCode() != tgtok::question && Lex.getCode() != tgtok::XGetOp) { 2039 TokError("expected identifier in dag init"); 2040 return nullptr; 2041 } 2042 2043 Init *Operator = ParseValue(CurRec); 2044 if (!Operator) return nullptr; 2045 2046 // If the operator name is present, parse it. 2047 StringInit *OperatorName = nullptr; 2048 if (consume(tgtok::colon)) { 2049 if (Lex.getCode() != tgtok::VarName) { // eat the ':' 2050 TokError("expected variable name in dag operator"); 2051 return nullptr; 2052 } 2053 OperatorName = StringInit::get(Lex.getCurStrVal()); 2054 Lex.Lex(); // eat the VarName. 2055 } 2056 2057 SmallVector<std::pair<llvm::Init*, StringInit*>, 8> DagArgs; 2058 if (Lex.getCode() != tgtok::r_paren) { 2059 ParseDagArgList(DagArgs, CurRec); 2060 if (DagArgs.empty()) return nullptr; 2061 } 2062 2063 if (!consume(tgtok::r_paren)) { 2064 TokError("expected ')' in dag init"); 2065 return nullptr; 2066 } 2067 2068 return DagInit::get(Operator, OperatorName, DagArgs); 2069 } 2070 2071 case tgtok::XHead: 2072 case tgtok::XTail: 2073 case tgtok::XSize: 2074 case tgtok::XEmpty: 2075 case tgtok::XCast: 2076 case tgtok::XGetOp: // Value ::= !unop '(' Value ')' 2077 case tgtok::XIsA: 2078 case tgtok::XConcat: 2079 case tgtok::XDag: 2080 case tgtok::XADD: 2081 case tgtok::XMUL: 2082 case tgtok::XAND: 2083 case tgtok::XOR: 2084 case tgtok::XSRA: 2085 case tgtok::XSRL: 2086 case tgtok::XSHL: 2087 case tgtok::XEq: 2088 case tgtok::XNe: 2089 case tgtok::XLe: 2090 case tgtok::XLt: 2091 case tgtok::XGe: 2092 case tgtok::XGt: 2093 case tgtok::XListConcat: 2094 case tgtok::XListSplat: 2095 case tgtok::XStrConcat: 2096 case tgtok::XSetOp: // Value ::= !binop '(' Value ',' Value ')' 2097 case tgtok::XIf: 2098 case tgtok::XCond: 2099 case tgtok::XFoldl: 2100 case tgtok::XForEach: 2101 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')' 2102 return ParseOperation(CurRec, ItemType); 2103 } 2104 } 2105 2106 return R; 2107 } 2108 2109 /// ParseValue - Parse a tblgen value. This returns null on error. 2110 /// 2111 /// Value ::= SimpleValue ValueSuffix* 2112 /// ValueSuffix ::= '{' BitList '}' 2113 /// ValueSuffix ::= '[' BitList ']' 2114 /// ValueSuffix ::= '.' ID 2115 /// 2116 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) { 2117 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode); 2118 if (!Result) return nullptr; 2119 2120 // Parse the suffixes now if present. 2121 while (true) { 2122 switch (Lex.getCode()) { 2123 default: return Result; 2124 case tgtok::l_brace: { 2125 if (Mode == ParseNameMode) 2126 // This is the beginning of the object body. 2127 return Result; 2128 2129 SMLoc CurlyLoc = Lex.getLoc(); 2130 Lex.Lex(); // eat the '{' 2131 SmallVector<unsigned, 16> Ranges; 2132 ParseRangeList(Ranges); 2133 if (Ranges.empty()) return nullptr; 2134 2135 // Reverse the bitlist. 2136 std::reverse(Ranges.begin(), Ranges.end()); 2137 Result = Result->convertInitializerBitRange(Ranges); 2138 if (!Result) { 2139 Error(CurlyLoc, "Invalid bit range for value"); 2140 return nullptr; 2141 } 2142 2143 // Eat the '}'. 2144 if (!consume(tgtok::r_brace)) { 2145 TokError("expected '}' at end of bit range list"); 2146 return nullptr; 2147 } 2148 break; 2149 } 2150 case tgtok::l_square: { 2151 SMLoc SquareLoc = Lex.getLoc(); 2152 Lex.Lex(); // eat the '[' 2153 SmallVector<unsigned, 16> Ranges; 2154 ParseRangeList(Ranges); 2155 if (Ranges.empty()) return nullptr; 2156 2157 Result = Result->convertInitListSlice(Ranges); 2158 if (!Result) { 2159 Error(SquareLoc, "Invalid range for list slice"); 2160 return nullptr; 2161 } 2162 2163 // Eat the ']'. 2164 if (!consume(tgtok::r_square)) { 2165 TokError("expected ']' at end of list slice"); 2166 return nullptr; 2167 } 2168 break; 2169 } 2170 case tgtok::period: { 2171 if (Lex.Lex() != tgtok::Id) { // eat the . 2172 TokError("expected field identifier after '.'"); 2173 return nullptr; 2174 } 2175 StringInit *FieldName = StringInit::get(Lex.getCurStrVal()); 2176 if (!Result->getFieldType(FieldName)) { 2177 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" + 2178 Result->getAsString() + "'"); 2179 return nullptr; 2180 } 2181 Result = FieldInit::get(Result, FieldName)->Fold(CurRec); 2182 Lex.Lex(); // eat field name 2183 break; 2184 } 2185 2186 case tgtok::paste: 2187 SMLoc PasteLoc = Lex.getLoc(); 2188 TypedInit *LHS = dyn_cast<TypedInit>(Result); 2189 if (!LHS) { 2190 Error(PasteLoc, "LHS of paste is not typed!"); 2191 return nullptr; 2192 } 2193 2194 // Check if it's a 'listA # listB' 2195 if (isa<ListRecTy>(LHS->getType())) { 2196 Lex.Lex(); // Eat the '#'. 2197 2198 switch (Lex.getCode()) { 2199 case tgtok::colon: 2200 case tgtok::semi: 2201 case tgtok::l_brace: 2202 Result = LHS; // trailing paste, ignore. 2203 break; 2204 default: 2205 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode); 2206 Result = BinOpInit::getListConcat(LHS, RHSResult); 2207 } 2208 break; 2209 } 2210 2211 // Create a !strconcat() operation, first casting each operand to 2212 // a string if necessary. 2213 if (LHS->getType() != StringRecTy::get()) { 2214 auto CastLHS = dyn_cast<TypedInit>( 2215 UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get()) 2216 ->Fold(CurRec)); 2217 if (!CastLHS) { 2218 Error(PasteLoc, 2219 Twine("can't cast '") + LHS->getAsString() + "' to string"); 2220 return nullptr; 2221 } 2222 LHS = CastLHS; 2223 } 2224 2225 TypedInit *RHS = nullptr; 2226 2227 Lex.Lex(); // Eat the '#'. 2228 switch (Lex.getCode()) { 2229 case tgtok::colon: 2230 case tgtok::semi: 2231 case tgtok::l_brace: 2232 // These are all of the tokens that can begin an object body. 2233 // Some of these can also begin values but we disallow those cases 2234 // because they are unlikely to be useful. 2235 2236 // Trailing paste, concat with an empty string. 2237 RHS = StringInit::get(""); 2238 break; 2239 2240 default: 2241 Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode); 2242 RHS = dyn_cast<TypedInit>(RHSResult); 2243 if (!RHS) { 2244 Error(PasteLoc, "RHS of paste is not typed!"); 2245 return nullptr; 2246 } 2247 2248 if (RHS->getType() != StringRecTy::get()) { 2249 auto CastRHS = dyn_cast<TypedInit>( 2250 UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get()) 2251 ->Fold(CurRec)); 2252 if (!CastRHS) { 2253 Error(PasteLoc, 2254 Twine("can't cast '") + RHS->getAsString() + "' to string"); 2255 return nullptr; 2256 } 2257 RHS = CastRHS; 2258 } 2259 2260 break; 2261 } 2262 2263 Result = BinOpInit::getStrConcat(LHS, RHS); 2264 break; 2265 } 2266 } 2267 } 2268 2269 /// ParseDagArgList - Parse the argument list for a dag literal expression. 2270 /// 2271 /// DagArg ::= Value (':' VARNAME)? 2272 /// DagArg ::= VARNAME 2273 /// DagArgList ::= DagArg 2274 /// DagArgList ::= DagArgList ',' DagArg 2275 void TGParser::ParseDagArgList( 2276 SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result, 2277 Record *CurRec) { 2278 2279 while (true) { 2280 // DagArg ::= VARNAME 2281 if (Lex.getCode() == tgtok::VarName) { 2282 // A missing value is treated like '?'. 2283 StringInit *VarName = StringInit::get(Lex.getCurStrVal()); 2284 Result.emplace_back(UnsetInit::get(), VarName); 2285 Lex.Lex(); 2286 } else { 2287 // DagArg ::= Value (':' VARNAME)? 2288 Init *Val = ParseValue(CurRec); 2289 if (!Val) { 2290 Result.clear(); 2291 return; 2292 } 2293 2294 // If the variable name is present, add it. 2295 StringInit *VarName = nullptr; 2296 if (Lex.getCode() == tgtok::colon) { 2297 if (Lex.Lex() != tgtok::VarName) { // eat the ':' 2298 TokError("expected variable name in dag literal"); 2299 Result.clear(); 2300 return; 2301 } 2302 VarName = StringInit::get(Lex.getCurStrVal()); 2303 Lex.Lex(); // eat the VarName. 2304 } 2305 2306 Result.push_back(std::make_pair(Val, VarName)); 2307 } 2308 if (!consume(tgtok::comma)) 2309 break; 2310 } 2311 } 2312 2313 /// ParseValueList - Parse a comma separated list of values, returning them as a 2314 /// vector. Note that this always expects to be able to parse at least one 2315 /// value. It returns an empty list if this is not possible. 2316 /// 2317 /// ValueList ::= Value (',' Value) 2318 /// 2319 void TGParser::ParseValueList(SmallVectorImpl<Init*> &Result, Record *CurRec, 2320 Record *ArgsRec, RecTy *EltTy) { 2321 RecTy *ItemType = EltTy; 2322 unsigned int ArgN = 0; 2323 if (ArgsRec && !EltTy) { 2324 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs(); 2325 if (TArgs.empty()) { 2326 TokError("template argument provided to non-template class"); 2327 Result.clear(); 2328 return; 2329 } 2330 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]); 2331 if (!RV) { 2332 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN] 2333 << ")\n"; 2334 } 2335 assert(RV && "Template argument record not found??"); 2336 ItemType = RV->getType(); 2337 ++ArgN; 2338 } 2339 Result.push_back(ParseValue(CurRec, ItemType)); 2340 if (!Result.back()) { 2341 Result.clear(); 2342 return; 2343 } 2344 2345 while (consume(tgtok::comma)) { 2346 // ignore trailing comma for lists 2347 if (Lex.getCode() == tgtok::r_square) 2348 return; 2349 2350 if (ArgsRec && !EltTy) { 2351 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs(); 2352 if (ArgN >= TArgs.size()) { 2353 TokError("too many template arguments"); 2354 Result.clear(); 2355 return; 2356 } 2357 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]); 2358 assert(RV && "Template argument record not found??"); 2359 ItemType = RV->getType(); 2360 ++ArgN; 2361 } 2362 Result.push_back(ParseValue(CurRec, ItemType)); 2363 if (!Result.back()) { 2364 Result.clear(); 2365 return; 2366 } 2367 } 2368 } 2369 2370 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an 2371 /// empty string on error. This can happen in a number of different context's, 2372 /// including within a def or in the template args for a def (which which case 2373 /// CurRec will be non-null) and within the template args for a multiclass (in 2374 /// which case CurRec will be null, but CurMultiClass will be set). This can 2375 /// also happen within a def that is within a multiclass, which will set both 2376 /// CurRec and CurMultiClass. 2377 /// 2378 /// Declaration ::= FIELD? Type ID ('=' Value)? 2379 /// 2380 Init *TGParser::ParseDeclaration(Record *CurRec, 2381 bool ParsingTemplateArgs) { 2382 // Read the field prefix if present. 2383 bool HasField = consume(tgtok::Field); 2384 2385 RecTy *Type = ParseType(); 2386 if (!Type) return nullptr; 2387 2388 if (Lex.getCode() != tgtok::Id) { 2389 TokError("Expected identifier in declaration"); 2390 return nullptr; 2391 } 2392 2393 std::string Str = Lex.getCurStrVal(); 2394 if (Str == "NAME") { 2395 TokError("'" + Str + "' is a reserved variable name"); 2396 return nullptr; 2397 } 2398 2399 SMLoc IdLoc = Lex.getLoc(); 2400 Init *DeclName = StringInit::get(Str); 2401 Lex.Lex(); 2402 2403 if (ParsingTemplateArgs) { 2404 if (CurRec) 2405 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":"); 2406 else 2407 assert(CurMultiClass); 2408 if (CurMultiClass) 2409 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName, 2410 "::"); 2411 } 2412 2413 // Add the value. 2414 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField))) 2415 return nullptr; 2416 2417 // If a value is present, parse it. 2418 if (consume(tgtok::equal)) { 2419 SMLoc ValLoc = Lex.getLoc(); 2420 Init *Val = ParseValue(CurRec, Type); 2421 if (!Val || 2422 SetValue(CurRec, ValLoc, DeclName, None, Val)) 2423 // Return the name, even if an error is thrown. This is so that we can 2424 // continue to make some progress, even without the value having been 2425 // initialized. 2426 return DeclName; 2427 } 2428 2429 return DeclName; 2430 } 2431 2432 /// ParseForeachDeclaration - Read a foreach declaration, returning 2433 /// the name of the declared object or a NULL Init on error. Return 2434 /// the name of the parsed initializer list through ForeachListName. 2435 /// 2436 /// ForeachDeclaration ::= ID '=' '{' RangeList '}' 2437 /// ForeachDeclaration ::= ID '=' RangePiece 2438 /// ForeachDeclaration ::= ID '=' Value 2439 /// 2440 VarInit *TGParser::ParseForeachDeclaration(Init *&ForeachListValue) { 2441 if (Lex.getCode() != tgtok::Id) { 2442 TokError("Expected identifier in foreach declaration"); 2443 return nullptr; 2444 } 2445 2446 Init *DeclName = StringInit::get(Lex.getCurStrVal()); 2447 Lex.Lex(); 2448 2449 // If a value is present, parse it. 2450 if (!consume(tgtok::equal)) { 2451 TokError("Expected '=' in foreach declaration"); 2452 return nullptr; 2453 } 2454 2455 RecTy *IterType = nullptr; 2456 SmallVector<unsigned, 16> Ranges; 2457 2458 switch (Lex.getCode()) { 2459 case tgtok::l_brace: { // '{' RangeList '}' 2460 Lex.Lex(); // eat the '{' 2461 ParseRangeList(Ranges); 2462 if (!consume(tgtok::r_brace)) { 2463 TokError("expected '}' at end of bit range list"); 2464 return nullptr; 2465 } 2466 break; 2467 } 2468 2469 default: { 2470 SMLoc ValueLoc = Lex.getLoc(); 2471 Init *I = ParseValue(nullptr); 2472 if (!I) 2473 return nullptr; 2474 2475 TypedInit *TI = dyn_cast<TypedInit>(I); 2476 if (TI && isa<ListRecTy>(TI->getType())) { 2477 ForeachListValue = I; 2478 IterType = cast<ListRecTy>(TI->getType())->getElementType(); 2479 break; 2480 } 2481 2482 if (TI) { 2483 if (ParseRangePiece(Ranges, TI)) 2484 return nullptr; 2485 break; 2486 } 2487 2488 std::string Type; 2489 if (TI) 2490 Type = (Twine("' of type '") + TI->getType()->getAsString()).str(); 2491 Error(ValueLoc, "expected a list, got '" + I->getAsString() + Type + "'"); 2492 if (CurMultiClass) { 2493 PrintNote({}, "references to multiclass template arguments cannot be " 2494 "resolved at this time"); 2495 } 2496 return nullptr; 2497 } 2498 } 2499 2500 2501 if (!Ranges.empty()) { 2502 assert(!IterType && "Type already initialized?"); 2503 IterType = IntRecTy::get(); 2504 std::vector<Init*> Values; 2505 for (unsigned R : Ranges) 2506 Values.push_back(IntInit::get(R)); 2507 ForeachListValue = ListInit::get(Values, IterType); 2508 } 2509 2510 if (!IterType) 2511 return nullptr; 2512 2513 return VarInit::get(DeclName, IterType); 2514 } 2515 2516 /// ParseTemplateArgList - Read a template argument list, which is a non-empty 2517 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are 2518 /// template args for a def, which may or may not be in a multiclass. If null, 2519 /// these are the template args for a multiclass. 2520 /// 2521 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>' 2522 /// 2523 bool TGParser::ParseTemplateArgList(Record *CurRec) { 2524 assert(Lex.getCode() == tgtok::less && "Not a template arg list!"); 2525 Lex.Lex(); // eat the '<' 2526 2527 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec; 2528 2529 // Read the first declaration. 2530 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/); 2531 if (!TemplArg) 2532 return true; 2533 2534 TheRecToAddTo->addTemplateArg(TemplArg); 2535 2536 while (consume(tgtok::comma)) { 2537 // Read the following declarations. 2538 SMLoc Loc = Lex.getLoc(); 2539 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/); 2540 if (!TemplArg) 2541 return true; 2542 2543 if (TheRecToAddTo->isTemplateArg(TemplArg)) 2544 return Error(Loc, "template argument with the same name has already been " 2545 "defined"); 2546 2547 TheRecToAddTo->addTemplateArg(TemplArg); 2548 } 2549 2550 if (!consume(tgtok::greater)) 2551 return TokError("expected '>' at end of template argument list"); 2552 return false; 2553 } 2554 2555 /// ParseBodyItem - Parse a single item at within the body of a def or class. 2556 /// 2557 /// BodyItem ::= Declaration ';' 2558 /// BodyItem ::= LET ID OptionalBitList '=' Value ';' 2559 /// BodyItem ::= Defvar 2560 bool TGParser::ParseBodyItem(Record *CurRec) { 2561 if (Lex.getCode() == tgtok::Defvar) 2562 return ParseDefvar(); 2563 2564 if (Lex.getCode() != tgtok::Let) { 2565 if (!ParseDeclaration(CurRec, false)) 2566 return true; 2567 2568 if (!consume(tgtok::semi)) 2569 return TokError("expected ';' after declaration"); 2570 return false; 2571 } 2572 2573 // LET ID OptionalRangeList '=' Value ';' 2574 if (Lex.Lex() != tgtok::Id) 2575 return TokError("expected field identifier after let"); 2576 2577 SMLoc IdLoc = Lex.getLoc(); 2578 StringInit *FieldName = StringInit::get(Lex.getCurStrVal()); 2579 Lex.Lex(); // eat the field name. 2580 2581 SmallVector<unsigned, 16> BitList; 2582 if (ParseOptionalBitList(BitList)) 2583 return true; 2584 std::reverse(BitList.begin(), BitList.end()); 2585 2586 if (!consume(tgtok::equal)) 2587 return TokError("expected '=' in let expression"); 2588 2589 RecordVal *Field = CurRec->getValue(FieldName); 2590 if (!Field) 2591 return TokError("Value '" + FieldName->getValue() + "' unknown!"); 2592 2593 RecTy *Type = Field->getType(); 2594 if (!BitList.empty() && isa<BitsRecTy>(Type)) { 2595 // When assigning to a subset of a 'bits' object, expect the RHS to have 2596 // the type of that subset instead of the type of the whole object. 2597 Type = BitsRecTy::get(BitList.size()); 2598 } 2599 2600 Init *Val = ParseValue(CurRec, Type); 2601 if (!Val) return true; 2602 2603 if (!consume(tgtok::semi)) 2604 return TokError("expected ';' after let expression"); 2605 2606 return SetValue(CurRec, IdLoc, FieldName, BitList, Val); 2607 } 2608 2609 /// ParseBody - Read the body of a class or def. Return true on error, false on 2610 /// success. 2611 /// 2612 /// Body ::= ';' 2613 /// Body ::= '{' BodyList '}' 2614 /// BodyList BodyItem* 2615 /// 2616 bool TGParser::ParseBody(Record *CurRec) { 2617 // If this is a null definition, just eat the semi and return. 2618 if (consume(tgtok::semi)) 2619 return false; 2620 2621 if (!consume(tgtok::l_brace)) 2622 return TokError("Expected ';' or '{' to start body"); 2623 2624 // An object body introduces a new scope for local variables. 2625 TGLocalVarScope *BodyScope = PushLocalScope(); 2626 2627 while (Lex.getCode() != tgtok::r_brace) 2628 if (ParseBodyItem(CurRec)) 2629 return true; 2630 2631 PopLocalScope(BodyScope); 2632 2633 // Eat the '}'. 2634 Lex.Lex(); 2635 return false; 2636 } 2637 2638 /// Apply the current let bindings to \a CurRec. 2639 /// \returns true on error, false otherwise. 2640 bool TGParser::ApplyLetStack(Record *CurRec) { 2641 for (SmallVectorImpl<LetRecord> &LetInfo : LetStack) 2642 for (LetRecord &LR : LetInfo) 2643 if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value)) 2644 return true; 2645 return false; 2646 } 2647 2648 bool TGParser::ApplyLetStack(RecordsEntry &Entry) { 2649 if (Entry.Rec) 2650 return ApplyLetStack(Entry.Rec.get()); 2651 2652 for (auto &E : Entry.Loop->Entries) { 2653 if (ApplyLetStack(E)) 2654 return true; 2655 } 2656 2657 return false; 2658 } 2659 2660 /// ParseObjectBody - Parse the body of a def or class. This consists of an 2661 /// optional ClassList followed by a Body. CurRec is the current def or class 2662 /// that is being parsed. 2663 /// 2664 /// ObjectBody ::= BaseClassList Body 2665 /// BaseClassList ::= /*empty*/ 2666 /// BaseClassList ::= ':' BaseClassListNE 2667 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)* 2668 /// 2669 bool TGParser::ParseObjectBody(Record *CurRec) { 2670 // If there is a baseclass list, read it. 2671 if (consume(tgtok::colon)) { 2672 2673 // Read all of the subclasses. 2674 SubClassReference SubClass = ParseSubClassReference(CurRec, false); 2675 while (true) { 2676 // Check for error. 2677 if (!SubClass.Rec) return true; 2678 2679 // Add it. 2680 if (AddSubClass(CurRec, SubClass)) 2681 return true; 2682 2683 if (!consume(tgtok::comma)) 2684 break; 2685 SubClass = ParseSubClassReference(CurRec, false); 2686 } 2687 } 2688 2689 if (ApplyLetStack(CurRec)) 2690 return true; 2691 2692 return ParseBody(CurRec); 2693 } 2694 2695 /// ParseDef - Parse and return a top level or multiclass def, return the record 2696 /// corresponding to it. This returns null on error. 2697 /// 2698 /// DefInst ::= DEF ObjectName ObjectBody 2699 /// 2700 bool TGParser::ParseDef(MultiClass *CurMultiClass) { 2701 SMLoc DefLoc = Lex.getLoc(); 2702 assert(Lex.getCode() == tgtok::Def && "Unknown tok"); 2703 Lex.Lex(); // Eat the 'def' token. 2704 2705 // Parse ObjectName and make a record for it. 2706 std::unique_ptr<Record> CurRec; 2707 Init *Name = ParseObjectName(CurMultiClass); 2708 if (!Name) 2709 return true; 2710 2711 if (isa<UnsetInit>(Name)) 2712 CurRec = std::make_unique<Record>(Records.getNewAnonymousName(), DefLoc, Records, 2713 /*Anonymous=*/true); 2714 else 2715 CurRec = std::make_unique<Record>(Name, DefLoc, Records); 2716 2717 if (ParseObjectBody(CurRec.get())) 2718 return true; 2719 2720 return addEntry(std::move(CurRec)); 2721 } 2722 2723 /// ParseDefset - Parse a defset statement. 2724 /// 2725 /// Defset ::= DEFSET Type Id '=' '{' ObjectList '}' 2726 /// 2727 bool TGParser::ParseDefset() { 2728 assert(Lex.getCode() == tgtok::Defset); 2729 Lex.Lex(); // Eat the 'defset' token 2730 2731 DefsetRecord Defset; 2732 Defset.Loc = Lex.getLoc(); 2733 RecTy *Type = ParseType(); 2734 if (!Type) 2735 return true; 2736 if (!isa<ListRecTy>(Type)) 2737 return Error(Defset.Loc, "expected list type"); 2738 Defset.EltTy = cast<ListRecTy>(Type)->getElementType(); 2739 2740 if (Lex.getCode() != tgtok::Id) 2741 return TokError("expected identifier"); 2742 StringInit *DeclName = StringInit::get(Lex.getCurStrVal()); 2743 if (Records.getGlobal(DeclName->getValue())) 2744 return TokError("def or global variable of this name already exists"); 2745 2746 if (Lex.Lex() != tgtok::equal) // Eat the identifier 2747 return TokError("expected '='"); 2748 if (Lex.Lex() != tgtok::l_brace) // Eat the '=' 2749 return TokError("expected '{'"); 2750 SMLoc BraceLoc = Lex.getLoc(); 2751 Lex.Lex(); // Eat the '{' 2752 2753 Defsets.push_back(&Defset); 2754 bool Err = ParseObjectList(nullptr); 2755 Defsets.pop_back(); 2756 if (Err) 2757 return true; 2758 2759 if (!consume(tgtok::r_brace)) { 2760 TokError("expected '}' at end of defset"); 2761 return Error(BraceLoc, "to match this '{'"); 2762 } 2763 2764 Records.addExtraGlobal(DeclName->getValue(), 2765 ListInit::get(Defset.Elements, Defset.EltTy)); 2766 return false; 2767 } 2768 2769 /// ParseDefvar - Parse a defvar statement. 2770 /// 2771 /// Defvar ::= DEFVAR Id '=' Value ';' 2772 /// 2773 bool TGParser::ParseDefvar() { 2774 assert(Lex.getCode() == tgtok::Defvar); 2775 Lex.Lex(); // Eat the 'defvar' token 2776 2777 if (Lex.getCode() != tgtok::Id) 2778 return TokError("expected identifier"); 2779 StringInit *DeclName = StringInit::get(Lex.getCurStrVal()); 2780 if (CurLocalScope) { 2781 if (CurLocalScope->varAlreadyDefined(DeclName->getValue())) 2782 return TokError("local variable of this name already exists"); 2783 } else { 2784 if (Records.getGlobal(DeclName->getValue())) 2785 return TokError("def or global variable of this name already exists"); 2786 } 2787 2788 Lex.Lex(); 2789 if (!consume(tgtok::equal)) 2790 return TokError("expected '='"); 2791 2792 Init *Value = ParseValue(nullptr); 2793 if (!Value) 2794 return true; 2795 2796 if (!consume(tgtok::semi)) 2797 return TokError("expected ';'"); 2798 2799 if (CurLocalScope) 2800 CurLocalScope->addVar(DeclName->getValue(), Value); 2801 else 2802 Records.addExtraGlobal(DeclName->getValue(), Value); 2803 2804 return false; 2805 } 2806 2807 /// ParseForeach - Parse a for statement. Return the record corresponding 2808 /// to it. This returns true on error. 2809 /// 2810 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}' 2811 /// Foreach ::= FOREACH Declaration IN Object 2812 /// 2813 bool TGParser::ParseForeach(MultiClass *CurMultiClass) { 2814 SMLoc Loc = Lex.getLoc(); 2815 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok"); 2816 Lex.Lex(); // Eat the 'for' token. 2817 2818 // Make a temporary object to record items associated with the for 2819 // loop. 2820 Init *ListValue = nullptr; 2821 VarInit *IterName = ParseForeachDeclaration(ListValue); 2822 if (!IterName) 2823 return TokError("expected declaration in for"); 2824 2825 if (!consume(tgtok::In)) 2826 return TokError("Unknown tok"); 2827 2828 // Create a loop object and remember it. 2829 Loops.push_back(std::make_unique<ForeachLoop>(Loc, IterName, ListValue)); 2830 2831 // A foreach loop introduces a new scope for local variables. 2832 TGLocalVarScope *ForeachScope = PushLocalScope(); 2833 2834 if (Lex.getCode() != tgtok::l_brace) { 2835 // FOREACH Declaration IN Object 2836 if (ParseObject(CurMultiClass)) 2837 return true; 2838 } else { 2839 SMLoc BraceLoc = Lex.getLoc(); 2840 // Otherwise, this is a group foreach. 2841 Lex.Lex(); // eat the '{'. 2842 2843 // Parse the object list. 2844 if (ParseObjectList(CurMultiClass)) 2845 return true; 2846 2847 if (!consume(tgtok::r_brace)) { 2848 TokError("expected '}' at end of foreach command"); 2849 return Error(BraceLoc, "to match this '{'"); 2850 } 2851 } 2852 2853 PopLocalScope(ForeachScope); 2854 2855 // Resolve the loop or store it for later resolution. 2856 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back()); 2857 Loops.pop_back(); 2858 2859 return addEntry(std::move(Loop)); 2860 } 2861 2862 /// ParseIf - Parse an if statement. 2863 /// 2864 /// If ::= IF Value THEN IfBody 2865 /// If ::= IF Value THEN IfBody ELSE IfBody 2866 /// 2867 bool TGParser::ParseIf(MultiClass *CurMultiClass) { 2868 SMLoc Loc = Lex.getLoc(); 2869 assert(Lex.getCode() == tgtok::If && "Unknown tok"); 2870 Lex.Lex(); // Eat the 'if' token. 2871 2872 // Make a temporary object to record items associated with the for 2873 // loop. 2874 Init *Condition = ParseValue(nullptr); 2875 if (!Condition) 2876 return true; 2877 2878 if (!consume(tgtok::Then)) 2879 return TokError("Unknown tok"); 2880 2881 // We have to be able to save if statements to execute later, and they have 2882 // to live on the same stack as foreach loops. The simplest implementation 2883 // technique is to convert each 'then' or 'else' clause *into* a foreach 2884 // loop, over a list of length 0 or 1 depending on the condition, and with no 2885 // iteration variable being assigned. 2886 2887 ListInit *EmptyList = ListInit::get({}, BitRecTy::get()); 2888 ListInit *SingletonList = ListInit::get({BitInit::get(1)}, BitRecTy::get()); 2889 RecTy *BitListTy = ListRecTy::get(BitRecTy::get()); 2890 2891 // The foreach containing the then-clause selects SingletonList if 2892 // the condition is true. 2893 Init *ThenClauseList = 2894 TernOpInit::get(TernOpInit::IF, Condition, SingletonList, EmptyList, 2895 BitListTy) 2896 ->Fold(nullptr); 2897 Loops.push_back(std::make_unique<ForeachLoop>(Loc, nullptr, ThenClauseList)); 2898 2899 if (ParseIfBody(CurMultiClass, "then")) 2900 return true; 2901 2902 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back()); 2903 Loops.pop_back(); 2904 2905 if (addEntry(std::move(Loop))) 2906 return true; 2907 2908 // Now look for an optional else clause. The if-else syntax has the usual 2909 // dangling-else ambiguity, and by greedily matching an else here if we can, 2910 // we implement the usual resolution of pairing with the innermost unmatched 2911 // if. 2912 if (consume(tgtok::ElseKW)) { 2913 // The foreach containing the else-clause uses the same pair of lists as 2914 // above, but this time, selects SingletonList if the condition is *false*. 2915 Init *ElseClauseList = 2916 TernOpInit::get(TernOpInit::IF, Condition, EmptyList, SingletonList, 2917 BitListTy) 2918 ->Fold(nullptr); 2919 Loops.push_back( 2920 std::make_unique<ForeachLoop>(Loc, nullptr, ElseClauseList)); 2921 2922 if (ParseIfBody(CurMultiClass, "else")) 2923 return true; 2924 2925 Loop = std::move(Loops.back()); 2926 Loops.pop_back(); 2927 2928 if (addEntry(std::move(Loop))) 2929 return true; 2930 } 2931 2932 return false; 2933 } 2934 2935 /// ParseIfBody - Parse the then-clause or else-clause of an if statement. 2936 /// 2937 /// IfBody ::= Object 2938 /// IfBody ::= '{' ObjectList '}' 2939 /// 2940 bool TGParser::ParseIfBody(MultiClass *CurMultiClass, StringRef Kind) { 2941 TGLocalVarScope *BodyScope = PushLocalScope(); 2942 2943 if (Lex.getCode() != tgtok::l_brace) { 2944 // A single object. 2945 if (ParseObject(CurMultiClass)) 2946 return true; 2947 } else { 2948 SMLoc BraceLoc = Lex.getLoc(); 2949 // A braced block. 2950 Lex.Lex(); // eat the '{'. 2951 2952 // Parse the object list. 2953 if (ParseObjectList(CurMultiClass)) 2954 return true; 2955 2956 if (!consume(tgtok::r_brace)) { 2957 TokError("expected '}' at end of '" + Kind + "' clause"); 2958 return Error(BraceLoc, "to match this '{'"); 2959 } 2960 } 2961 2962 PopLocalScope(BodyScope); 2963 return false; 2964 } 2965 2966 /// ParseClass - Parse a tblgen class definition. 2967 /// 2968 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody 2969 /// 2970 bool TGParser::ParseClass() { 2971 assert(Lex.getCode() == tgtok::Class && "Unexpected token!"); 2972 Lex.Lex(); 2973 2974 if (Lex.getCode() != tgtok::Id) 2975 return TokError("expected class name after 'class' keyword"); 2976 2977 Record *CurRec = Records.getClass(Lex.getCurStrVal()); 2978 if (CurRec) { 2979 // If the body was previously defined, this is an error. 2980 if (!CurRec->getValues().empty() || 2981 !CurRec->getSuperClasses().empty() || 2982 !CurRec->getTemplateArgs().empty()) 2983 return TokError("Class '" + CurRec->getNameInitAsString() + 2984 "' already defined"); 2985 } else { 2986 // If this is the first reference to this class, create and add it. 2987 auto NewRec = 2988 std::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records, 2989 /*Class=*/true); 2990 CurRec = NewRec.get(); 2991 Records.addClass(std::move(NewRec)); 2992 } 2993 Lex.Lex(); // eat the name. 2994 2995 // If there are template args, parse them. 2996 if (Lex.getCode() == tgtok::less) 2997 if (ParseTemplateArgList(CurRec)) 2998 return true; 2999 3000 return ParseObjectBody(CurRec); 3001 } 3002 3003 /// ParseLetList - Parse a non-empty list of assignment expressions into a list 3004 /// of LetRecords. 3005 /// 3006 /// LetList ::= LetItem (',' LetItem)* 3007 /// LetItem ::= ID OptionalRangeList '=' Value 3008 /// 3009 void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) { 3010 do { 3011 if (Lex.getCode() != tgtok::Id) { 3012 TokError("expected identifier in let definition"); 3013 Result.clear(); 3014 return; 3015 } 3016 3017 StringInit *Name = StringInit::get(Lex.getCurStrVal()); 3018 SMLoc NameLoc = Lex.getLoc(); 3019 Lex.Lex(); // Eat the identifier. 3020 3021 // Check for an optional RangeList. 3022 SmallVector<unsigned, 16> Bits; 3023 if (ParseOptionalRangeList(Bits)) { 3024 Result.clear(); 3025 return; 3026 } 3027 std::reverse(Bits.begin(), Bits.end()); 3028 3029 if (!consume(tgtok::equal)) { 3030 TokError("expected '=' in let expression"); 3031 Result.clear(); 3032 return; 3033 } 3034 3035 Init *Val = ParseValue(nullptr); 3036 if (!Val) { 3037 Result.clear(); 3038 return; 3039 } 3040 3041 // Now that we have everything, add the record. 3042 Result.emplace_back(Name, Bits, Val, NameLoc); 3043 } while (consume(tgtok::comma)); 3044 } 3045 3046 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of 3047 /// different related productions. This works inside multiclasses too. 3048 /// 3049 /// Object ::= LET LetList IN '{' ObjectList '}' 3050 /// Object ::= LET LetList IN Object 3051 /// 3052 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) { 3053 assert(Lex.getCode() == tgtok::Let && "Unexpected token"); 3054 Lex.Lex(); 3055 3056 // Add this entry to the let stack. 3057 SmallVector<LetRecord, 8> LetInfo; 3058 ParseLetList(LetInfo); 3059 if (LetInfo.empty()) return true; 3060 LetStack.push_back(std::move(LetInfo)); 3061 3062 if (!consume(tgtok::In)) 3063 return TokError("expected 'in' at end of top-level 'let'"); 3064 3065 TGLocalVarScope *LetScope = PushLocalScope(); 3066 3067 // If this is a scalar let, just handle it now 3068 if (Lex.getCode() != tgtok::l_brace) { 3069 // LET LetList IN Object 3070 if (ParseObject(CurMultiClass)) 3071 return true; 3072 } else { // Object ::= LETCommand '{' ObjectList '}' 3073 SMLoc BraceLoc = Lex.getLoc(); 3074 // Otherwise, this is a group let. 3075 Lex.Lex(); // eat the '{'. 3076 3077 // Parse the object list. 3078 if (ParseObjectList(CurMultiClass)) 3079 return true; 3080 3081 if (!consume(tgtok::r_brace)) { 3082 TokError("expected '}' at end of top level let command"); 3083 return Error(BraceLoc, "to match this '{'"); 3084 } 3085 } 3086 3087 PopLocalScope(LetScope); 3088 3089 // Outside this let scope, this let block is not active. 3090 LetStack.pop_back(); 3091 return false; 3092 } 3093 3094 /// ParseMultiClass - Parse a multiclass definition. 3095 /// 3096 /// MultiClassInst ::= MULTICLASS ID TemplateArgList? 3097 /// ':' BaseMultiClassList '{' MultiClassObject+ '}' 3098 /// MultiClassObject ::= DefInst 3099 /// MultiClassObject ::= MultiClassInst 3100 /// MultiClassObject ::= DefMInst 3101 /// MultiClassObject ::= LETCommand '{' ObjectList '}' 3102 /// MultiClassObject ::= LETCommand Object 3103 /// 3104 bool TGParser::ParseMultiClass() { 3105 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token"); 3106 Lex.Lex(); // Eat the multiclass token. 3107 3108 if (Lex.getCode() != tgtok::Id) 3109 return TokError("expected identifier after multiclass for name"); 3110 std::string Name = Lex.getCurStrVal(); 3111 3112 auto Result = 3113 MultiClasses.insert(std::make_pair(Name, 3114 std::make_unique<MultiClass>(Name, Lex.getLoc(),Records))); 3115 3116 if (!Result.second) 3117 return TokError("multiclass '" + Name + "' already defined"); 3118 3119 CurMultiClass = Result.first->second.get(); 3120 Lex.Lex(); // Eat the identifier. 3121 3122 // If there are template args, parse them. 3123 if (Lex.getCode() == tgtok::less) 3124 if (ParseTemplateArgList(nullptr)) 3125 return true; 3126 3127 bool inherits = false; 3128 3129 // If there are submulticlasses, parse them. 3130 if (consume(tgtok::colon)) { 3131 inherits = true; 3132 3133 // Read all of the submulticlasses. 3134 SubMultiClassReference SubMultiClass = 3135 ParseSubMultiClassReference(CurMultiClass); 3136 while (true) { 3137 // Check for error. 3138 if (!SubMultiClass.MC) return true; 3139 3140 // Add it. 3141 if (AddSubMultiClass(CurMultiClass, SubMultiClass)) 3142 return true; 3143 3144 if (!consume(tgtok::comma)) 3145 break; 3146 SubMultiClass = ParseSubMultiClassReference(CurMultiClass); 3147 } 3148 } 3149 3150 if (Lex.getCode() != tgtok::l_brace) { 3151 if (!inherits) 3152 return TokError("expected '{' in multiclass definition"); 3153 if (!consume(tgtok::semi)) 3154 return TokError("expected ';' in multiclass definition"); 3155 } else { 3156 if (Lex.Lex() == tgtok::r_brace) // eat the '{'. 3157 return TokError("multiclass must contain at least one def"); 3158 3159 // A multiclass body introduces a new scope for local variables. 3160 TGLocalVarScope *MulticlassScope = PushLocalScope(); 3161 3162 while (Lex.getCode() != tgtok::r_brace) { 3163 switch (Lex.getCode()) { 3164 default: 3165 return TokError("expected 'let', 'def', 'defm', 'defvar', 'foreach' " 3166 "or 'if' in multiclass body"); 3167 case tgtok::Let: 3168 case tgtok::Def: 3169 case tgtok::Defm: 3170 case tgtok::Defvar: 3171 case tgtok::Foreach: 3172 case tgtok::If: 3173 if (ParseObject(CurMultiClass)) 3174 return true; 3175 break; 3176 } 3177 } 3178 Lex.Lex(); // eat the '}'. 3179 3180 PopLocalScope(MulticlassScope); 3181 } 3182 3183 CurMultiClass = nullptr; 3184 return false; 3185 } 3186 3187 /// ParseDefm - Parse the instantiation of a multiclass. 3188 /// 3189 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';' 3190 /// 3191 bool TGParser::ParseDefm(MultiClass *CurMultiClass) { 3192 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!"); 3193 Lex.Lex(); // eat the defm 3194 3195 Init *DefmName = ParseObjectName(CurMultiClass); 3196 if (!DefmName) 3197 return true; 3198 if (isa<UnsetInit>(DefmName)) { 3199 DefmName = Records.getNewAnonymousName(); 3200 if (CurMultiClass) 3201 DefmName = BinOpInit::getStrConcat( 3202 VarInit::get(QualifiedNameOfImplicitName(CurMultiClass), 3203 StringRecTy::get()), 3204 DefmName); 3205 } 3206 3207 if (Lex.getCode() != tgtok::colon) 3208 return TokError("expected ':' after defm identifier"); 3209 3210 // Keep track of the new generated record definitions. 3211 std::vector<RecordsEntry> NewEntries; 3212 3213 // This record also inherits from a regular class (non-multiclass)? 3214 bool InheritFromClass = false; 3215 3216 // eat the colon. 3217 Lex.Lex(); 3218 3219 SMLoc SubClassLoc = Lex.getLoc(); 3220 SubClassReference Ref = ParseSubClassReference(nullptr, true); 3221 3222 while (true) { 3223 if (!Ref.Rec) return true; 3224 3225 // To instantiate a multiclass, we need to first get the multiclass, then 3226 // instantiate each def contained in the multiclass with the SubClassRef 3227 // template parameters. 3228 MultiClass *MC = MultiClasses[std::string(Ref.Rec->getName())].get(); 3229 assert(MC && "Didn't lookup multiclass correctly?"); 3230 ArrayRef<Init*> TemplateVals = Ref.TemplateArgs; 3231 3232 // Verify that the correct number of template arguments were specified. 3233 ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs(); 3234 if (TArgs.size() < TemplateVals.size()) 3235 return Error(SubClassLoc, 3236 "more template args specified than multiclass expects"); 3237 3238 SubstStack Substs; 3239 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) { 3240 if (i < TemplateVals.size()) { 3241 Substs.emplace_back(TArgs[i], TemplateVals[i]); 3242 } else { 3243 Init *Default = MC->Rec.getValue(TArgs[i])->getValue(); 3244 if (!Default->isComplete()) { 3245 return Error(SubClassLoc, 3246 "value not specified for template argument #" + 3247 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() + 3248 ") of multiclass '" + MC->Rec.getNameInitAsString() + 3249 "'"); 3250 } 3251 Substs.emplace_back(TArgs[i], Default); 3252 } 3253 } 3254 3255 Substs.emplace_back(QualifiedNameOfImplicitName(MC), DefmName); 3256 3257 if (resolve(MC->Entries, Substs, CurMultiClass == nullptr, &NewEntries, 3258 &SubClassLoc)) 3259 return true; 3260 3261 if (!consume(tgtok::comma)) 3262 break; 3263 3264 if (Lex.getCode() != tgtok::Id) 3265 return TokError("expected identifier"); 3266 3267 SubClassLoc = Lex.getLoc(); 3268 3269 // A defm can inherit from regular classes (non-multiclass) as 3270 // long as they come in the end of the inheritance list. 3271 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr); 3272 3273 if (InheritFromClass) 3274 break; 3275 3276 Ref = ParseSubClassReference(nullptr, true); 3277 } 3278 3279 if (InheritFromClass) { 3280 // Process all the classes to inherit as if they were part of a 3281 // regular 'def' and inherit all record values. 3282 SubClassReference SubClass = ParseSubClassReference(nullptr, false); 3283 while (true) { 3284 // Check for error. 3285 if (!SubClass.Rec) return true; 3286 3287 // Get the expanded definition prototypes and teach them about 3288 // the record values the current class to inherit has 3289 for (auto &E : NewEntries) { 3290 // Add it. 3291 if (AddSubClass(E, SubClass)) 3292 return true; 3293 } 3294 3295 if (!consume(tgtok::comma)) 3296 break; 3297 SubClass = ParseSubClassReference(nullptr, false); 3298 } 3299 } 3300 3301 for (auto &E : NewEntries) { 3302 if (ApplyLetStack(E)) 3303 return true; 3304 3305 addEntry(std::move(E)); 3306 } 3307 3308 if (!consume(tgtok::semi)) 3309 return TokError("expected ';' at end of defm"); 3310 3311 return false; 3312 } 3313 3314 /// ParseObject 3315 /// Object ::= ClassInst 3316 /// Object ::= DefInst 3317 /// Object ::= MultiClassInst 3318 /// Object ::= DefMInst 3319 /// Object ::= LETCommand '{' ObjectList '}' 3320 /// Object ::= LETCommand Object 3321 /// Object ::= Defset 3322 /// Object ::= Defvar 3323 bool TGParser::ParseObject(MultiClass *MC) { 3324 switch (Lex.getCode()) { 3325 default: 3326 return TokError("Expected class, def, defm, defset, multiclass, let, " 3327 "foreach or if"); 3328 case tgtok::Let: return ParseTopLevelLet(MC); 3329 case tgtok::Def: return ParseDef(MC); 3330 case tgtok::Foreach: return ParseForeach(MC); 3331 case tgtok::If: return ParseIf(MC); 3332 case tgtok::Defm: return ParseDefm(MC); 3333 case tgtok::Defset: 3334 if (MC) 3335 return TokError("defset is not allowed inside multiclass"); 3336 return ParseDefset(); 3337 case tgtok::Defvar: 3338 return ParseDefvar(); 3339 case tgtok::Class: 3340 if (MC) 3341 return TokError("class is not allowed inside multiclass"); 3342 if (!Loops.empty()) 3343 return TokError("class is not allowed inside foreach loop"); 3344 return ParseClass(); 3345 case tgtok::MultiClass: 3346 if (!Loops.empty()) 3347 return TokError("multiclass is not allowed inside foreach loop"); 3348 return ParseMultiClass(); 3349 } 3350 } 3351 3352 /// ParseObjectList 3353 /// ObjectList :== Object* 3354 bool TGParser::ParseObjectList(MultiClass *MC) { 3355 while (isObjectStart(Lex.getCode())) { 3356 if (ParseObject(MC)) 3357 return true; 3358 } 3359 return false; 3360 } 3361 3362 bool TGParser::ParseFile() { 3363 Lex.Lex(); // Prime the lexer. 3364 if (ParseObjectList()) return true; 3365 3366 // If we have unread input at the end of the file, report it. 3367 if (Lex.getCode() == tgtok::Eof) 3368 return false; 3369 3370 return TokError("Unexpected input at top level"); 3371 } 3372 3373 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 3374 LLVM_DUMP_METHOD void RecordsEntry::dump() const { 3375 if (Loop) 3376 Loop->dump(); 3377 if (Rec) 3378 Rec->dump(); 3379 } 3380 3381 LLVM_DUMP_METHOD void ForeachLoop::dump() const { 3382 errs() << "foreach " << IterVar->getAsString() << " = " 3383 << ListValue->getAsString() << " in {\n"; 3384 3385 for (const auto &E : Entries) 3386 E.dump(); 3387 3388 errs() << "}\n"; 3389 } 3390 3391 LLVM_DUMP_METHOD void MultiClass::dump() const { 3392 errs() << "Record:\n"; 3393 Rec.dump(); 3394 3395 errs() << "Defs:\n"; 3396 for (const auto &E : Entries) 3397 E.dump(); 3398 } 3399 #endif 3400