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