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