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