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