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