1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Implement the Parser for TableGen. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TGParser.h" 15 #include "llvm/ADT/None.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/StringExtras.h" 19 #include "llvm/Config/llvm-config.h" 20 #include "llvm/Support/Casting.h" 21 #include "llvm/Support/Compiler.h" 22 #include "llvm/Support/ErrorHandling.h" 23 #include "llvm/Support/raw_ostream.h" 24 #include "llvm/TableGen/Record.h" 25 #include <algorithm> 26 #include <cassert> 27 #include <cstdint> 28 29 using namespace llvm; 30 31 //===----------------------------------------------------------------------===// 32 // Support Code for the Semantic Actions. 33 //===----------------------------------------------------------------------===// 34 35 namespace llvm { 36 37 struct SubClassReference { 38 SMRange RefRange; 39 Record *Rec; 40 SmallVector<Init*, 4> TemplateArgs; 41 42 SubClassReference() : Rec(nullptr) {} 43 44 bool isInvalid() const { return Rec == nullptr; } 45 }; 46 47 struct SubMultiClassReference { 48 SMRange RefRange; 49 MultiClass *MC; 50 SmallVector<Init*, 4> TemplateArgs; 51 52 SubMultiClassReference() : MC(nullptr) {} 53 54 bool isInvalid() const { return MC == nullptr; } 55 void dump() const; 56 }; 57 58 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 59 LLVM_DUMP_METHOD void SubMultiClassReference::dump() const { 60 errs() << "Multiclass:\n"; 61 62 MC->dump(); 63 64 errs() << "Template args:\n"; 65 for (Init *TA : TemplateArgs) 66 TA->dump(); 67 } 68 #endif 69 70 } // end namespace llvm 71 72 static bool checkBitsConcrete(Record &R, const RecordVal &RV) { 73 BitsInit *BV = cast<BitsInit>(RV.getValue()); 74 for (unsigned i = 0, e = BV->getNumBits(); i != e; ++i) { 75 Init *Bit = BV->getBit(i); 76 bool IsReference = false; 77 if (auto VBI = dyn_cast<VarBitInit>(Bit)) { 78 if (auto VI = dyn_cast<VarInit>(VBI->getBitVar())) { 79 if (R.getValue(VI->getName())) 80 IsReference = true; 81 } 82 } else if (isa<VarInit>(Bit)) { 83 IsReference = true; 84 } 85 if (!(IsReference || Bit->isConcrete())) 86 return false; 87 } 88 return true; 89 } 90 91 static void checkConcrete(Record &R) { 92 for (const RecordVal &RV : R.getValues()) { 93 // HACK: Disable this check for variables declared with 'field'. This is 94 // done merely because existing targets have legitimate cases of 95 // non-concrete variables in helper defs. Ideally, we'd introduce a 96 // 'maybe' or 'optional' modifier instead of this. 97 if (RV.getPrefix()) 98 continue; 99 100 if (Init *V = RV.getValue()) { 101 bool Ok = isa<BitsInit>(V) ? checkBitsConcrete(R, RV) : V->isConcrete(); 102 if (!Ok) { 103 PrintError(R.getLoc(), 104 Twine("Initializer of '") + RV.getNameInitAsString() + 105 "' in '" + R.getNameInitAsString() + 106 "' could not be fully resolved: " + 107 RV.getValue()->getAsString()); 108 } 109 } 110 } 111 } 112 113 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) { 114 if (!CurRec) 115 CurRec = &CurMultiClass->Rec; 116 117 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) { 118 // The value already exists in the class, treat this as a set. 119 if (ERV->setValue(RV.getValue())) 120 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" + 121 RV.getType()->getAsString() + "' is incompatible with " + 122 "previous definition of type '" + 123 ERV->getType()->getAsString() + "'"); 124 } else { 125 CurRec->addValue(RV); 126 } 127 return false; 128 } 129 130 /// SetValue - 131 /// Return true on error, false on success. 132 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName, 133 ArrayRef<unsigned> BitList, Init *V, 134 bool AllowSelfAssignment) { 135 if (!V) return false; 136 137 if (!CurRec) CurRec = &CurMultiClass->Rec; 138 139 RecordVal *RV = CurRec->getValue(ValName); 140 if (!RV) 141 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + 142 "' unknown!"); 143 144 // Do not allow assignments like 'X = X'. This will just cause infinite loops 145 // in the resolution machinery. 146 if (BitList.empty()) 147 if (VarInit *VI = dyn_cast<VarInit>(V)) 148 if (VI->getNameInit() == ValName && !AllowSelfAssignment) 149 return Error(Loc, "Recursion / self-assignment forbidden"); 150 151 // If we are assigning to a subset of the bits in the value... then we must be 152 // assigning to a field of BitsRecTy, which must have a BitsInit 153 // initializer. 154 // 155 if (!BitList.empty()) { 156 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue()); 157 if (!CurVal) 158 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + 159 "' is not a bits type"); 160 161 // Convert the incoming value to a bits type of the appropriate size... 162 Init *BI = V->getCastTo(BitsRecTy::get(BitList.size())); 163 if (!BI) 164 return Error(Loc, "Initializer is not compatible with bit range"); 165 166 SmallVector<Init *, 16> NewBits(CurVal->getNumBits()); 167 168 // Loop over bits, assigning values as appropriate. 169 for (unsigned i = 0, e = BitList.size(); i != e; ++i) { 170 unsigned Bit = BitList[i]; 171 if (NewBits[Bit]) 172 return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" + 173 ValName->getAsUnquotedString() + "' more than once"); 174 NewBits[Bit] = BI->getBit(i); 175 } 176 177 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i) 178 if (!NewBits[i]) 179 NewBits[i] = CurVal->getBit(i); 180 181 V = BitsInit::get(NewBits); 182 } 183 184 if (RV->setValue(V)) { 185 std::string InitType; 186 if (BitsInit *BI = dyn_cast<BitsInit>(V)) 187 InitType = (Twine("' of type bit initializer with length ") + 188 Twine(BI->getNumBits())).str(); 189 else if (TypedInit *TI = dyn_cast<TypedInit>(V)) 190 InitType = (Twine("' of type '") + TI->getType()->getAsString()).str(); 191 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + 192 "' of type '" + RV->getType()->getAsString() + 193 "' is incompatible with initializer '" + 194 V->getAsString() + InitType + "'"); 195 } 196 return false; 197 } 198 199 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template 200 /// args as SubClass's template arguments. 201 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) { 202 Record *SC = SubClass.Rec; 203 // Add all of the values in the subclass into the current class. 204 for (const RecordVal &Val : SC->getValues()) 205 if (AddValue(CurRec, SubClass.RefRange.Start, Val)) 206 return true; 207 208 ArrayRef<Init *> TArgs = SC->getTemplateArgs(); 209 210 // Ensure that an appropriate number of template arguments are specified. 211 if (TArgs.size() < SubClass.TemplateArgs.size()) 212 return Error(SubClass.RefRange.Start, 213 "More template args specified than expected"); 214 215 // Loop over all of the template arguments, setting them to the specified 216 // value or leaving them as the default if necessary. 217 MapResolver R(CurRec); 218 219 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) { 220 if (i < SubClass.TemplateArgs.size()) { 221 // If a value is specified for this template arg, set it now. 222 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i], 223 None, SubClass.TemplateArgs[i])) 224 return true; 225 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) { 226 return Error(SubClass.RefRange.Start, 227 "Value not specified for template argument #" + 228 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() + 229 ") of subclass '" + SC->getNameInitAsString() + "'!"); 230 } 231 232 R.set(TArgs[i], CurRec->getValue(TArgs[i])->getValue()); 233 234 CurRec->removeValue(TArgs[i]); 235 } 236 237 CurRec->resolveReferences(R); 238 239 // Since everything went well, we can now set the "superclass" list for the 240 // current record. 241 ArrayRef<std::pair<Record *, SMRange>> SCs = SC->getSuperClasses(); 242 for (const auto &SCPair : SCs) { 243 if (CurRec->isSubClassOf(SCPair.first)) 244 return Error(SubClass.RefRange.Start, 245 "Already subclass of '" + SCPair.first->getName() + "'!\n"); 246 CurRec->addSuperClass(SCPair.first, SCPair.second); 247 } 248 249 if (CurRec->isSubClassOf(SC)) 250 return Error(SubClass.RefRange.Start, 251 "Already subclass of '" + SC->getName() + "'!\n"); 252 CurRec->addSuperClass(SC, SubClass.RefRange); 253 return false; 254 } 255 256 /// AddSubMultiClass - Add SubMultiClass as a subclass to 257 /// CurMC, resolving its template args as SubMultiClass's 258 /// template arguments. 259 bool TGParser::AddSubMultiClass(MultiClass *CurMC, 260 SubMultiClassReference &SubMultiClass) { 261 MultiClass *SMC = SubMultiClass.MC; 262 Record *CurRec = &CurMC->Rec; 263 264 // Add all of the values in the subclass into the current class. 265 for (const auto &SMCVal : SMC->Rec.getValues()) 266 if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVal)) 267 return true; 268 269 unsigned newDefStart = CurMC->DefPrototypes.size(); 270 271 // Add all of the defs in the subclass into the current multiclass. 272 for (const std::unique_ptr<Record> &R : SMC->DefPrototypes) { 273 // Clone the def and add it to the current multiclass 274 auto NewDef = make_unique<Record>(*R); 275 276 // Add all of the values in the superclass into the current def. 277 for (const auto &MCVal : CurRec->getValues()) 278 if (AddValue(NewDef.get(), SubMultiClass.RefRange.Start, MCVal)) 279 return true; 280 281 CurMC->DefPrototypes.push_back(std::move(NewDef)); 282 } 283 284 ArrayRef<Init *> SMCTArgs = SMC->Rec.getTemplateArgs(); 285 286 // Ensure that an appropriate number of template arguments are 287 // specified. 288 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size()) 289 return Error(SubMultiClass.RefRange.Start, 290 "More template args specified than expected"); 291 292 // Loop over all of the template arguments, setting them to the specified 293 // value or leaving them as the default if necessary. 294 MapResolver CurRecResolver(CurRec); 295 296 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) { 297 if (i < SubMultiClass.TemplateArgs.size()) { 298 // If a value is specified for this template arg, set it in the 299 // superclass now. 300 if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i], 301 None, SubMultiClass.TemplateArgs[i])) 302 return true; 303 304 // If a value is specified for this template arg, set it in the 305 // new defs now. 306 for (const auto &Def : 307 makeArrayRef(CurMC->DefPrototypes).slice(newDefStart)) { 308 if (SetValue(Def.get(), SubMultiClass.RefRange.Start, SMCTArgs[i], 309 None, SubMultiClass.TemplateArgs[i])) 310 return true; 311 } 312 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) { 313 return Error(SubMultiClass.RefRange.Start, 314 "Value not specified for template argument #" + 315 Twine(i) + " (" + SMCTArgs[i]->getAsUnquotedString() + 316 ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!"); 317 } 318 319 CurRecResolver.set(SMCTArgs[i], CurRec->getValue(SMCTArgs[i])->getValue()); 320 321 CurRec->removeValue(SMCTArgs[i]); 322 } 323 324 CurRec->resolveReferences(CurRecResolver); 325 326 for (const auto &Def : 327 makeArrayRef(CurMC->DefPrototypes).slice(newDefStart)) { 328 MapResolver R(Def.get()); 329 330 for (Init *SMCTArg : SMCTArgs) { 331 R.set(SMCTArg, Def->getValue(SMCTArg)->getValue()); 332 Def->removeValue(SMCTArg); 333 } 334 335 Def->resolveReferences(R); 336 } 337 338 return false; 339 } 340 341 /// Add a record that results from 'def' or 'defm', after template arguments 342 /// and the external let stack have been resolved. 343 /// 344 /// Apply foreach loops, resolve internal variable references, and add to the 345 /// current multi class or the global record keeper as appropriate. 346 bool TGParser::addDef(std::unique_ptr<Record> Rec, Init *DefmName) { 347 IterSet IterVals; 348 349 if (Loops.empty()) 350 return addDefOne(std::move(Rec), DefmName, IterVals); 351 352 return addDefForeach(Rec.get(), DefmName, IterVals); 353 } 354 355 /// Recursive helper function for addDef/addDefOne to resolve references to 356 /// foreach variables. 357 bool TGParser::addDefForeach(Record *Rec, Init *DefmName, IterSet &IterVals) { 358 if (IterVals.size() != Loops.size()) { 359 assert(IterVals.size() < Loops.size()); 360 ForeachLoop &CurLoop = Loops[IterVals.size()]; 361 ListInit *List = CurLoop.ListValue; 362 363 // Process each value. 364 for (unsigned i = 0; i < List->size(); ++i) { 365 IterVals.push_back(IterRecord(CurLoop.IterVar, List->getElement(i))); 366 if (addDefForeach(Rec, DefmName, IterVals)) 367 return true; 368 IterVals.pop_back(); 369 } 370 return false; 371 } 372 373 // This is the bottom of the recursion. We have all of the iterator values 374 // for this point in the iteration space. Instantiate a new record to 375 // reflect this combination of values. 376 auto IterRec = make_unique<Record>(*Rec); 377 return addDefOne(std::move(IterRec), DefmName, IterVals); 378 } 379 380 /// After resolving foreach loops, add the record as a prototype to the 381 /// current multiclass, or resolve fully and add to the record keeper. 382 bool TGParser::addDefOne(std::unique_ptr<Record> Rec, Init *DefmName, 383 IterSet &IterVals) { 384 MapResolver R(Rec.get()); 385 386 for (IterRecord &IR : IterVals) 387 R.set(IR.IterVar->getNameInit(), IR.IterValue); 388 389 Rec->resolveReferences(R); 390 391 if (CurMultiClass) { 392 for (const auto &Proto : CurMultiClass->DefPrototypes) { 393 if (Proto->getNameInit() == Rec->getNameInit()) { 394 if (!Rec->isAnonymous()) { 395 PrintError(Rec->getLoc(), 396 Twine("def '") + Rec->getNameInitAsString() + 397 "' already defined in this multiclass!"); 398 PrintNote(Proto->getLoc(), "location of previous definition"); 399 return true; 400 } 401 Rec->setName(Records.getNewAnonymousName()); 402 break; 403 } 404 } 405 CurMultiClass->DefPrototypes.emplace_back(std::move(Rec)); 406 return false; 407 } 408 409 // Name construction is an incoherent mess. Unfortunately, existing .td 410 // files rely on pretty much all the quirks and implementation details of 411 // this. 412 if (DefmName) { 413 MapResolver R(Rec.get()); 414 R.set(StringInit::get("NAME"), DefmName); 415 Rec->resolveReferences(R); 416 } 417 418 if (Record *Prev = Records.getDef(Rec->getNameInitAsString())) { 419 if (!Rec->isAnonymous()) { 420 PrintError(Rec->getLoc(), 421 "def already exists: " + Rec->getNameInitAsString()); 422 PrintNote(Prev->getLoc(), "location of previous definition"); 423 return true; 424 } 425 Rec->setName(Records.getNewAnonymousName()); 426 } 427 428 Rec->resolveReferences(); 429 checkConcrete(*Rec); 430 431 // If ObjectBody has template arguments, it's an error. 432 assert(Rec->getTemplateArgs().empty() && "How'd this get template args?"); 433 434 for (DefsetRecord *Defset : Defsets) { 435 DefInit *I = Rec->getDefInit(); 436 if (!I->getType()->typeIsA(Defset->EltTy)) { 437 PrintError(Rec->getLoc(), Twine("adding record of incompatible type '") + 438 I->getType()->getAsString() + 439 "' to defset"); 440 PrintNote(Defset->Loc, "location of defset declaration"); 441 return true; 442 } 443 Defset->Elements.push_back(I); 444 } 445 446 Records.addDef(std::move(Rec)); 447 return false; 448 } 449 450 //===----------------------------------------------------------------------===// 451 // Parser Code 452 //===----------------------------------------------------------------------===// 453 454 /// isObjectStart - Return true if this is a valid first token for an Object. 455 static bool isObjectStart(tgtok::TokKind K) { 456 return K == tgtok::Class || K == tgtok::Def || K == tgtok::Defm || 457 K == tgtok::Let || K == tgtok::MultiClass || K == tgtok::Foreach || 458 K == tgtok::Defset; 459 } 460 461 /// ParseObjectName - If a valid object name is specified, return it. If no 462 /// name is specified, return the unset initializer. Return nullptr on parse 463 /// error. 464 /// ObjectName ::= Value [ '#' Value ]* 465 /// ObjectName ::= /*empty*/ 466 /// 467 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) { 468 switch (Lex.getCode()) { 469 case tgtok::colon: 470 case tgtok::semi: 471 case tgtok::l_brace: 472 // These are all of the tokens that can begin an object body. 473 // Some of these can also begin values but we disallow those cases 474 // because they are unlikely to be useful. 475 return UnsetInit::get(); 476 default: 477 break; 478 } 479 480 Record *CurRec = nullptr; 481 if (CurMultiClass) 482 CurRec = &CurMultiClass->Rec; 483 484 return ParseValue(CurRec, StringRecTy::get(), ParseNameMode); 485 } 486 487 /// ParseClassID - Parse and resolve a reference to a class name. This returns 488 /// null on error. 489 /// 490 /// ClassID ::= ID 491 /// 492 Record *TGParser::ParseClassID() { 493 if (Lex.getCode() != tgtok::Id) { 494 TokError("expected name for ClassID"); 495 return nullptr; 496 } 497 498 Record *Result = Records.getClass(Lex.getCurStrVal()); 499 if (!Result) 500 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'"); 501 502 Lex.Lex(); 503 return Result; 504 } 505 506 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name. 507 /// This returns null on error. 508 /// 509 /// MultiClassID ::= ID 510 /// 511 MultiClass *TGParser::ParseMultiClassID() { 512 if (Lex.getCode() != tgtok::Id) { 513 TokError("expected name for MultiClassID"); 514 return nullptr; 515 } 516 517 MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get(); 518 if (!Result) 519 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'"); 520 521 Lex.Lex(); 522 return Result; 523 } 524 525 /// ParseSubClassReference - Parse a reference to a subclass or to a templated 526 /// subclass. This returns a SubClassRefTy with a null Record* on error. 527 /// 528 /// SubClassRef ::= ClassID 529 /// SubClassRef ::= ClassID '<' ValueList '>' 530 /// 531 SubClassReference TGParser:: 532 ParseSubClassReference(Record *CurRec, bool isDefm) { 533 SubClassReference Result; 534 Result.RefRange.Start = Lex.getLoc(); 535 536 if (isDefm) { 537 if (MultiClass *MC = ParseMultiClassID()) 538 Result.Rec = &MC->Rec; 539 } else { 540 Result.Rec = ParseClassID(); 541 } 542 if (!Result.Rec) return Result; 543 544 // If there is no template arg list, we're done. 545 if (Lex.getCode() != tgtok::less) { 546 Result.RefRange.End = Lex.getLoc(); 547 return Result; 548 } 549 Lex.Lex(); // Eat the '<' 550 551 if (Lex.getCode() == tgtok::greater) { 552 TokError("subclass reference requires a non-empty list of template values"); 553 Result.Rec = nullptr; 554 return Result; 555 } 556 557 ParseValueList(Result.TemplateArgs, CurRec, Result.Rec); 558 if (Result.TemplateArgs.empty()) { 559 Result.Rec = nullptr; // Error parsing value list. 560 return Result; 561 } 562 563 if (Lex.getCode() != tgtok::greater) { 564 TokError("expected '>' in template value list"); 565 Result.Rec = nullptr; 566 return Result; 567 } 568 Lex.Lex(); 569 Result.RefRange.End = Lex.getLoc(); 570 571 return Result; 572 } 573 574 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a 575 /// templated submulticlass. This returns a SubMultiClassRefTy with a null 576 /// Record* on error. 577 /// 578 /// SubMultiClassRef ::= MultiClassID 579 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>' 580 /// 581 SubMultiClassReference TGParser:: 582 ParseSubMultiClassReference(MultiClass *CurMC) { 583 SubMultiClassReference Result; 584 Result.RefRange.Start = Lex.getLoc(); 585 586 Result.MC = ParseMultiClassID(); 587 if (!Result.MC) return Result; 588 589 // If there is no template arg list, we're done. 590 if (Lex.getCode() != tgtok::less) { 591 Result.RefRange.End = Lex.getLoc(); 592 return Result; 593 } 594 Lex.Lex(); // Eat the '<' 595 596 if (Lex.getCode() == tgtok::greater) { 597 TokError("subclass reference requires a non-empty list of template values"); 598 Result.MC = nullptr; 599 return Result; 600 } 601 602 ParseValueList(Result.TemplateArgs, &CurMC->Rec, &Result.MC->Rec); 603 if (Result.TemplateArgs.empty()) { 604 Result.MC = nullptr; // Error parsing value list. 605 return Result; 606 } 607 608 if (Lex.getCode() != tgtok::greater) { 609 TokError("expected '>' in template value list"); 610 Result.MC = nullptr; 611 return Result; 612 } 613 Lex.Lex(); 614 Result.RefRange.End = Lex.getLoc(); 615 616 return Result; 617 } 618 619 /// ParseRangePiece - Parse a bit/value range. 620 /// RangePiece ::= INTVAL 621 /// RangePiece ::= INTVAL '-' INTVAL 622 /// RangePiece ::= INTVAL INTVAL 623 bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges) { 624 if (Lex.getCode() != tgtok::IntVal) { 625 TokError("expected integer or bitrange"); 626 return true; 627 } 628 int64_t Start = Lex.getCurIntVal(); 629 int64_t End; 630 631 if (Start < 0) 632 return TokError("invalid range, cannot be negative"); 633 634 switch (Lex.Lex()) { // eat first character. 635 default: 636 Ranges.push_back(Start); 637 return false; 638 case tgtok::minus: 639 if (Lex.Lex() != tgtok::IntVal) { 640 TokError("expected integer value as end of range"); 641 return true; 642 } 643 End = Lex.getCurIntVal(); 644 break; 645 case tgtok::IntVal: 646 End = -Lex.getCurIntVal(); 647 break; 648 } 649 if (End < 0) 650 return TokError("invalid range, cannot be negative"); 651 Lex.Lex(); 652 653 // Add to the range. 654 if (Start < End) 655 for (; Start <= End; ++Start) 656 Ranges.push_back(Start); 657 else 658 for (; Start >= End; --Start) 659 Ranges.push_back(Start); 660 return false; 661 } 662 663 /// ParseRangeList - Parse a list of scalars and ranges into scalar values. 664 /// 665 /// RangeList ::= RangePiece (',' RangePiece)* 666 /// 667 void TGParser::ParseRangeList(SmallVectorImpl<unsigned> &Result) { 668 // Parse the first piece. 669 if (ParseRangePiece(Result)) { 670 Result.clear(); 671 return; 672 } 673 while (Lex.getCode() == tgtok::comma) { 674 Lex.Lex(); // Eat the comma. 675 676 // Parse the next range piece. 677 if (ParseRangePiece(Result)) { 678 Result.clear(); 679 return; 680 } 681 } 682 } 683 684 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing. 685 /// OptionalRangeList ::= '<' RangeList '>' 686 /// OptionalRangeList ::= /*empty*/ 687 bool TGParser::ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges) { 688 if (Lex.getCode() != tgtok::less) 689 return false; 690 691 SMLoc StartLoc = Lex.getLoc(); 692 Lex.Lex(); // eat the '<' 693 694 // Parse the range list. 695 ParseRangeList(Ranges); 696 if (Ranges.empty()) return true; 697 698 if (Lex.getCode() != tgtok::greater) { 699 TokError("expected '>' at end of range list"); 700 return Error(StartLoc, "to match this '<'"); 701 } 702 Lex.Lex(); // eat the '>'. 703 return false; 704 } 705 706 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing. 707 /// OptionalBitList ::= '{' RangeList '}' 708 /// OptionalBitList ::= /*empty*/ 709 bool TGParser::ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges) { 710 if (Lex.getCode() != tgtok::l_brace) 711 return false; 712 713 SMLoc StartLoc = Lex.getLoc(); 714 Lex.Lex(); // eat the '{' 715 716 // Parse the range list. 717 ParseRangeList(Ranges); 718 if (Ranges.empty()) return true; 719 720 if (Lex.getCode() != tgtok::r_brace) { 721 TokError("expected '}' at end of bit list"); 722 return Error(StartLoc, "to match this '{'"); 723 } 724 Lex.Lex(); // eat the '}'. 725 return false; 726 } 727 728 /// ParseType - Parse and return a tblgen type. This returns null on error. 729 /// 730 /// Type ::= STRING // string type 731 /// Type ::= CODE // code type 732 /// Type ::= BIT // bit type 733 /// Type ::= BITS '<' INTVAL '>' // bits<x> type 734 /// Type ::= INT // int type 735 /// Type ::= LIST '<' Type '>' // list<x> type 736 /// Type ::= DAG // dag type 737 /// Type ::= ClassID // Record Type 738 /// 739 RecTy *TGParser::ParseType() { 740 switch (Lex.getCode()) { 741 default: TokError("Unknown token when expecting a type"); return nullptr; 742 case tgtok::String: Lex.Lex(); return StringRecTy::get(); 743 case tgtok::Code: Lex.Lex(); return CodeRecTy::get(); 744 case tgtok::Bit: Lex.Lex(); return BitRecTy::get(); 745 case tgtok::Int: Lex.Lex(); return IntRecTy::get(); 746 case tgtok::Dag: Lex.Lex(); return DagRecTy::get(); 747 case tgtok::Id: 748 if (Record *R = ParseClassID()) return RecordRecTy::get(R); 749 TokError("unknown class name"); 750 return nullptr; 751 case tgtok::Bits: { 752 if (Lex.Lex() != tgtok::less) { // Eat 'bits' 753 TokError("expected '<' after bits type"); 754 return nullptr; 755 } 756 if (Lex.Lex() != tgtok::IntVal) { // Eat '<' 757 TokError("expected integer in bits<n> type"); 758 return nullptr; 759 } 760 uint64_t Val = Lex.getCurIntVal(); 761 if (Lex.Lex() != tgtok::greater) { // Eat count. 762 TokError("expected '>' at end of bits<n> type"); 763 return nullptr; 764 } 765 Lex.Lex(); // Eat '>' 766 return BitsRecTy::get(Val); 767 } 768 case tgtok::List: { 769 if (Lex.Lex() != tgtok::less) { // Eat 'bits' 770 TokError("expected '<' after list type"); 771 return nullptr; 772 } 773 Lex.Lex(); // Eat '<' 774 RecTy *SubType = ParseType(); 775 if (!SubType) return nullptr; 776 777 if (Lex.getCode() != tgtok::greater) { 778 TokError("expected '>' at end of list<ty> type"); 779 return nullptr; 780 } 781 Lex.Lex(); // Eat '>' 782 return ListRecTy::get(SubType); 783 } 784 } 785 } 786 787 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID 788 /// has already been read. 789 Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMLoc NameLoc, 790 IDParseMode Mode) { 791 if (CurRec) { 792 if (const RecordVal *RV = CurRec->getValue(Name)) 793 return VarInit::get(Name, RV->getType()); 794 795 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":"); 796 797 if (CurMultiClass) 798 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, 799 "::"); 800 801 if (CurRec->isTemplateArg(TemplateArgName)) { 802 const RecordVal *RV = CurRec->getValue(TemplateArgName); 803 assert(RV && "Template arg doesn't exist??"); 804 return VarInit::get(TemplateArgName, RV->getType()); 805 } 806 } 807 808 if (CurMultiClass) { 809 if (Name->getValue() == "NAME") 810 return VarInit::get(Name, StringRecTy::get()); 811 812 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::"); 813 814 if (CurMultiClass->Rec.isTemplateArg(MCName)) { 815 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName); 816 assert(RV && "Template arg doesn't exist??"); 817 return VarInit::get(MCName, RV->getType()); 818 } 819 } 820 821 // If this is in a foreach loop, make sure it's not a loop iterator 822 for (const auto &L : Loops) { 823 VarInit *IterVar = dyn_cast<VarInit>(L.IterVar); 824 if (IterVar && IterVar->getNameInit() == Name) 825 return IterVar; 826 } 827 828 if (Mode == ParseNameMode) 829 return Name; 830 831 if (Init *I = Records.getGlobal(Name->getValue())) 832 return I; 833 834 // Allow self-references of concrete defs, but delay the lookup so that we 835 // get the correct type. 836 if (CurRec && !CurMultiClass && CurRec->getNameInit() == Name) 837 return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType()); 838 839 if (Mode == ParseValueMode) { 840 Error(NameLoc, "Variable not defined: '" + Name->getValue() + "'"); 841 return nullptr; 842 } 843 844 return Name; 845 } 846 847 /// ParseOperation - Parse an operator. This returns null on error. 848 /// 849 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')' 850 /// 851 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) { 852 switch (Lex.getCode()) { 853 default: 854 TokError("unknown operation"); 855 return nullptr; 856 case tgtok::XHead: 857 case tgtok::XTail: 858 case tgtok::XSize: 859 case tgtok::XEmpty: 860 case tgtok::XCast: { // Value ::= !unop '(' Value ')' 861 UnOpInit::UnaryOp Code; 862 RecTy *Type = nullptr; 863 864 switch (Lex.getCode()) { 865 default: llvm_unreachable("Unhandled code!"); 866 case tgtok::XCast: 867 Lex.Lex(); // eat the operation 868 Code = UnOpInit::CAST; 869 870 Type = ParseOperatorType(); 871 872 if (!Type) { 873 TokError("did not get type for unary operator"); 874 return nullptr; 875 } 876 877 break; 878 case tgtok::XHead: 879 Lex.Lex(); // eat the operation 880 Code = UnOpInit::HEAD; 881 break; 882 case tgtok::XTail: 883 Lex.Lex(); // eat the operation 884 Code = UnOpInit::TAIL; 885 break; 886 case tgtok::XSize: 887 Lex.Lex(); 888 Code = UnOpInit::SIZE; 889 Type = IntRecTy::get(); 890 break; 891 case tgtok::XEmpty: 892 Lex.Lex(); // eat the operation 893 Code = UnOpInit::EMPTY; 894 Type = IntRecTy::get(); 895 break; 896 } 897 if (Lex.getCode() != tgtok::l_paren) { 898 TokError("expected '(' after unary operator"); 899 return nullptr; 900 } 901 Lex.Lex(); // eat the '(' 902 903 Init *LHS = ParseValue(CurRec); 904 if (!LHS) return nullptr; 905 906 if (Code == UnOpInit::HEAD || 907 Code == UnOpInit::TAIL || 908 Code == UnOpInit::EMPTY) { 909 ListInit *LHSl = dyn_cast<ListInit>(LHS); 910 StringInit *LHSs = dyn_cast<StringInit>(LHS); 911 TypedInit *LHSt = dyn_cast<TypedInit>(LHS); 912 if (!LHSl && !LHSs && !LHSt) { 913 TokError("expected list or string type argument in unary operator"); 914 return nullptr; 915 } 916 if (LHSt) { 917 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType()); 918 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType()); 919 if (!LType && !SType) { 920 TokError("expected list or string type argument in unary operator"); 921 return nullptr; 922 } 923 } 924 925 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL || 926 Code == UnOpInit::SIZE) { 927 if (!LHSl && !LHSt) { 928 TokError("expected list type argument in unary operator"); 929 return nullptr; 930 } 931 } 932 933 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) { 934 if (LHSl && LHSl->empty()) { 935 TokError("empty list argument in unary operator"); 936 return nullptr; 937 } 938 if (LHSl) { 939 Init *Item = LHSl->getElement(0); 940 TypedInit *Itemt = dyn_cast<TypedInit>(Item); 941 if (!Itemt) { 942 TokError("untyped list element in unary operator"); 943 return nullptr; 944 } 945 Type = (Code == UnOpInit::HEAD) ? Itemt->getType() 946 : ListRecTy::get(Itemt->getType()); 947 } else { 948 assert(LHSt && "expected list type argument in unary operator"); 949 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType()); 950 if (!LType) { 951 TokError("expected list type argument in unary operator"); 952 return nullptr; 953 } 954 Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType; 955 } 956 } 957 } 958 959 if (Lex.getCode() != tgtok::r_paren) { 960 TokError("expected ')' in unary operator"); 961 return nullptr; 962 } 963 Lex.Lex(); // eat the ')' 964 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec); 965 } 966 967 case tgtok::XIsA: { 968 // Value ::= !isa '<' Type '>' '(' Value ')' 969 Lex.Lex(); // eat the operation 970 971 RecTy *Type = ParseOperatorType(); 972 if (!Type) 973 return nullptr; 974 975 if (Lex.getCode() != tgtok::l_paren) { 976 TokError("expected '(' after type of !isa"); 977 return nullptr; 978 } 979 Lex.Lex(); // eat the '(' 980 981 Init *LHS = ParseValue(CurRec); 982 if (!LHS) 983 return nullptr; 984 985 if (Lex.getCode() != tgtok::r_paren) { 986 TokError("expected ')' in !isa"); 987 return nullptr; 988 } 989 Lex.Lex(); // eat the ')' 990 991 return (IsAOpInit::get(Type, LHS))->Fold(); 992 } 993 994 case tgtok::XConcat: 995 case tgtok::XADD: 996 case tgtok::XAND: 997 case tgtok::XOR: 998 case tgtok::XSRA: 999 case tgtok::XSRL: 1000 case tgtok::XSHL: 1001 case tgtok::XEq: 1002 case tgtok::XNe: 1003 case tgtok::XLe: 1004 case tgtok::XLt: 1005 case tgtok::XGe: 1006 case tgtok::XGt: 1007 case tgtok::XListConcat: 1008 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')' 1009 tgtok::TokKind OpTok = Lex.getCode(); 1010 SMLoc OpLoc = Lex.getLoc(); 1011 Lex.Lex(); // eat the operation 1012 1013 BinOpInit::BinaryOp Code; 1014 switch (OpTok) { 1015 default: llvm_unreachable("Unhandled code!"); 1016 case tgtok::XConcat: Code = BinOpInit::CONCAT; break; 1017 case tgtok::XADD: Code = BinOpInit::ADD; break; 1018 case tgtok::XAND: Code = BinOpInit::AND; break; 1019 case tgtok::XOR: Code = BinOpInit::OR; break; 1020 case tgtok::XSRA: Code = BinOpInit::SRA; break; 1021 case tgtok::XSRL: Code = BinOpInit::SRL; break; 1022 case tgtok::XSHL: Code = BinOpInit::SHL; break; 1023 case tgtok::XEq: Code = BinOpInit::EQ; break; 1024 case tgtok::XNe: Code = BinOpInit::NE; break; 1025 case tgtok::XLe: Code = BinOpInit::LE; break; 1026 case tgtok::XLt: Code = BinOpInit::LT; break; 1027 case tgtok::XGe: Code = BinOpInit::GE; break; 1028 case tgtok::XGt: Code = BinOpInit::GT; break; 1029 case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break; 1030 case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break; 1031 } 1032 1033 RecTy *Type = nullptr; 1034 RecTy *ArgType = nullptr; 1035 switch (OpTok) { 1036 default: 1037 llvm_unreachable("Unhandled code!"); 1038 case tgtok::XConcat: 1039 Type = DagRecTy::get(); 1040 ArgType = DagRecTy::get(); 1041 break; 1042 case tgtok::XAND: 1043 case tgtok::XOR: 1044 case tgtok::XSRA: 1045 case tgtok::XSRL: 1046 case tgtok::XSHL: 1047 case tgtok::XADD: 1048 Type = IntRecTy::get(); 1049 ArgType = IntRecTy::get(); 1050 break; 1051 case tgtok::XEq: 1052 case tgtok::XNe: 1053 Type = BitRecTy::get(); 1054 // ArgType for Eq / Ne is not known at this point 1055 break; 1056 case tgtok::XLe: 1057 case tgtok::XLt: 1058 case tgtok::XGe: 1059 case tgtok::XGt: 1060 Type = BitRecTy::get(); 1061 ArgType = IntRecTy::get(); 1062 break; 1063 case tgtok::XListConcat: 1064 // We don't know the list type until we parse the first argument 1065 ArgType = ItemType; 1066 break; 1067 case tgtok::XStrConcat: 1068 Type = StringRecTy::get(); 1069 ArgType = StringRecTy::get(); 1070 break; 1071 } 1072 1073 if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) { 1074 Error(OpLoc, Twine("expected value of type '") + 1075 ItemType->getAsString() + "', got '" + 1076 Type->getAsString() + "'"); 1077 return nullptr; 1078 } 1079 1080 if (Lex.getCode() != tgtok::l_paren) { 1081 TokError("expected '(' after binary operator"); 1082 return nullptr; 1083 } 1084 Lex.Lex(); // eat the '(' 1085 1086 SmallVector<Init*, 2> InitList; 1087 1088 for (;;) { 1089 SMLoc InitLoc = Lex.getLoc(); 1090 InitList.push_back(ParseValue(CurRec, ArgType)); 1091 if (!InitList.back()) return nullptr; 1092 1093 // All BinOps require their arguments to be of compatible types. 1094 TypedInit *TI = dyn_cast<TypedInit>(InitList.back()); 1095 if (!ArgType) { 1096 ArgType = TI->getType(); 1097 1098 switch (Code) { 1099 case BinOpInit::LISTCONCAT: 1100 if (!isa<ListRecTy>(ArgType)) { 1101 Error(InitLoc, Twine("expected a list, got value of type '") + 1102 ArgType->getAsString() + "'"); 1103 return nullptr; 1104 } 1105 break; 1106 case BinOpInit::EQ: 1107 case BinOpInit::NE: 1108 if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) && 1109 !ArgType->typeIsConvertibleTo(StringRecTy::get())) { 1110 Error(InitLoc, Twine("expected int, bits, or string; got value of " 1111 "type '") + ArgType->getAsString() + "'"); 1112 return nullptr; 1113 } 1114 break; 1115 default: llvm_unreachable("other ops have fixed argument types"); 1116 } 1117 } else { 1118 RecTy *Resolved = resolveTypes(ArgType, TI->getType()); 1119 if (!Resolved) { 1120 Error(InitLoc, Twine("expected value of type '") + 1121 ArgType->getAsString() + "', got '" + 1122 TI->getType()->getAsString() + "'"); 1123 return nullptr; 1124 } 1125 if (Code != BinOpInit::ADD && Code != BinOpInit::AND && 1126 Code != BinOpInit::OR && Code != BinOpInit::SRA && 1127 Code != BinOpInit::SRL && Code != BinOpInit::SHL) 1128 ArgType = Resolved; 1129 } 1130 1131 if (Lex.getCode() != tgtok::comma) 1132 break; 1133 Lex.Lex(); // eat the ',' 1134 } 1135 1136 if (Lex.getCode() != tgtok::r_paren) { 1137 TokError("expected ')' in operator"); 1138 return nullptr; 1139 } 1140 Lex.Lex(); // eat the ')' 1141 1142 if (Code == BinOpInit::LISTCONCAT) 1143 Type = ArgType; 1144 1145 // We allow multiple operands to associative operators like !strconcat as 1146 // shorthand for nesting them. 1147 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT || 1148 Code == BinOpInit::CONCAT || Code == BinOpInit::ADD || 1149 Code == BinOpInit::AND || Code == BinOpInit::OR) { 1150 while (InitList.size() > 2) { 1151 Init *RHS = InitList.pop_back_val(); 1152 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec); 1153 InitList.back() = RHS; 1154 } 1155 } 1156 1157 if (InitList.size() == 2) 1158 return (BinOpInit::get(Code, InitList[0], InitList[1], Type)) 1159 ->Fold(CurRec); 1160 1161 Error(OpLoc, "expected two operands to operator"); 1162 return nullptr; 1163 } 1164 1165 case tgtok::XForEach: { // Value ::= !foreach '(' Id ',' Value ',' Value ')' 1166 SMLoc OpLoc = Lex.getLoc(); 1167 Lex.Lex(); // eat the operation 1168 if (Lex.getCode() != tgtok::l_paren) { 1169 TokError("expected '(' after !foreach"); 1170 return nullptr; 1171 } 1172 1173 if (Lex.Lex() != tgtok::Id) { // eat the '(' 1174 TokError("first argument of !foreach must be an identifier"); 1175 return nullptr; 1176 } 1177 1178 Init *LHS = StringInit::get(Lex.getCurStrVal()); 1179 1180 if (CurRec->getValue(LHS)) { 1181 TokError((Twine("iteration variable '") + LHS->getAsString() + 1182 "' already defined") 1183 .str()); 1184 return nullptr; 1185 } 1186 1187 if (Lex.Lex() != tgtok::comma) { // eat the id 1188 TokError("expected ',' in ternary operator"); 1189 return nullptr; 1190 } 1191 Lex.Lex(); // eat the ',' 1192 1193 Init *MHS = ParseValue(CurRec); 1194 if (!MHS) 1195 return nullptr; 1196 1197 if (Lex.getCode() != tgtok::comma) { 1198 TokError("expected ',' in ternary operator"); 1199 return nullptr; 1200 } 1201 Lex.Lex(); // eat the ',' 1202 1203 TypedInit *MHSt = dyn_cast<TypedInit>(MHS); 1204 if (!MHSt) { 1205 TokError("could not get type of !foreach input"); 1206 return nullptr; 1207 } 1208 1209 RecTy *InEltType = nullptr; 1210 RecTy *OutEltType = nullptr; 1211 bool IsDAG = false; 1212 1213 if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) { 1214 InEltType = InListTy->getElementType(); 1215 if (ItemType) { 1216 if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) { 1217 OutEltType = OutListTy->getElementType(); 1218 } else { 1219 Error(OpLoc, 1220 "expected value of type '" + Twine(ItemType->getAsString()) + 1221 "', but got !foreach of list type"); 1222 return nullptr; 1223 } 1224 } 1225 } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) { 1226 InEltType = InDagTy; 1227 if (ItemType && !isa<DagRecTy>(ItemType)) { 1228 Error(OpLoc, 1229 "expected value of type '" + Twine(ItemType->getAsString()) + 1230 "', but got !foreach of dag type"); 1231 return nullptr; 1232 } 1233 IsDAG = true; 1234 } else { 1235 TokError("!foreach must have list or dag input"); 1236 return nullptr; 1237 } 1238 1239 CurRec->addValue(RecordVal(LHS, InEltType, false)); 1240 Init *RHS = ParseValue(CurRec, OutEltType); 1241 CurRec->removeValue(LHS); 1242 if (!RHS) 1243 return nullptr; 1244 1245 if (Lex.getCode() != tgtok::r_paren) { 1246 TokError("expected ')' in binary operator"); 1247 return nullptr; 1248 } 1249 Lex.Lex(); // eat the ')' 1250 1251 RecTy *OutType; 1252 if (IsDAG) { 1253 OutType = InEltType; 1254 } else { 1255 TypedInit *RHSt = dyn_cast<TypedInit>(RHS); 1256 if (!RHSt) { 1257 TokError("could not get type of !foreach result"); 1258 return nullptr; 1259 } 1260 OutType = RHSt->getType()->getListTy(); 1261 } 1262 1263 return (TernOpInit::get(TernOpInit::FOREACH, LHS, MHS, RHS, OutType)) 1264 ->Fold(CurRec); 1265 } 1266 1267 case tgtok::XDag: 1268 case tgtok::XIf: 1269 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')' 1270 TernOpInit::TernaryOp Code; 1271 RecTy *Type = nullptr; 1272 1273 tgtok::TokKind LexCode = Lex.getCode(); 1274 Lex.Lex(); // eat the operation 1275 switch (LexCode) { 1276 default: llvm_unreachable("Unhandled code!"); 1277 case tgtok::XDag: 1278 Code = TernOpInit::DAG; 1279 Type = DagRecTy::get(); 1280 ItemType = nullptr; 1281 break; 1282 case tgtok::XIf: 1283 Code = TernOpInit::IF; 1284 break; 1285 case tgtok::XSubst: 1286 Code = TernOpInit::SUBST; 1287 break; 1288 } 1289 if (Lex.getCode() != tgtok::l_paren) { 1290 TokError("expected '(' after ternary operator"); 1291 return nullptr; 1292 } 1293 Lex.Lex(); // eat the '(' 1294 1295 Init *LHS = ParseValue(CurRec); 1296 if (!LHS) return nullptr; 1297 1298 if (Lex.getCode() != tgtok::comma) { 1299 TokError("expected ',' in ternary operator"); 1300 return nullptr; 1301 } 1302 Lex.Lex(); // eat the ',' 1303 1304 SMLoc MHSLoc = Lex.getLoc(); 1305 Init *MHS = ParseValue(CurRec, ItemType); 1306 if (!MHS) 1307 return nullptr; 1308 1309 if (Lex.getCode() != tgtok::comma) { 1310 TokError("expected ',' in ternary operator"); 1311 return nullptr; 1312 } 1313 Lex.Lex(); // eat the ',' 1314 1315 SMLoc RHSLoc = Lex.getLoc(); 1316 Init *RHS = ParseValue(CurRec, ItemType); 1317 if (!RHS) 1318 return nullptr; 1319 1320 if (Lex.getCode() != tgtok::r_paren) { 1321 TokError("expected ')' in binary operator"); 1322 return nullptr; 1323 } 1324 Lex.Lex(); // eat the ')' 1325 1326 switch (LexCode) { 1327 default: llvm_unreachable("Unhandled code!"); 1328 case tgtok::XDag: { 1329 TypedInit *MHSt = dyn_cast<TypedInit>(MHS); 1330 if (!MHSt && !isa<UnsetInit>(MHS)) { 1331 Error(MHSLoc, "could not determine type of the child list in !dag"); 1332 return nullptr; 1333 } 1334 if (MHSt && !isa<ListRecTy>(MHSt->getType())) { 1335 Error(MHSLoc, Twine("expected list of children, got type '") + 1336 MHSt->getType()->getAsString() + "'"); 1337 return nullptr; 1338 } 1339 1340 TypedInit *RHSt = dyn_cast<TypedInit>(RHS); 1341 if (!RHSt && !isa<UnsetInit>(RHS)) { 1342 Error(RHSLoc, "could not determine type of the name list in !dag"); 1343 return nullptr; 1344 } 1345 if (RHSt && StringRecTy::get()->getListTy() != RHSt->getType()) { 1346 Error(RHSLoc, Twine("expected list<string>, got type '") + 1347 RHSt->getType()->getAsString() + "'"); 1348 return nullptr; 1349 } 1350 1351 if (!MHSt && !RHSt) { 1352 Error(MHSLoc, 1353 "cannot have both unset children and unset names in !dag"); 1354 return nullptr; 1355 } 1356 break; 1357 } 1358 case tgtok::XIf: { 1359 RecTy *MHSTy = nullptr; 1360 RecTy *RHSTy = nullptr; 1361 1362 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS)) 1363 MHSTy = MHSt->getType(); 1364 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS)) 1365 MHSTy = BitsRecTy::get(MHSbits->getNumBits()); 1366 if (isa<BitInit>(MHS)) 1367 MHSTy = BitRecTy::get(); 1368 1369 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS)) 1370 RHSTy = RHSt->getType(); 1371 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS)) 1372 RHSTy = BitsRecTy::get(RHSbits->getNumBits()); 1373 if (isa<BitInit>(RHS)) 1374 RHSTy = BitRecTy::get(); 1375 1376 // For UnsetInit, it's typed from the other hand. 1377 if (isa<UnsetInit>(MHS)) 1378 MHSTy = RHSTy; 1379 if (isa<UnsetInit>(RHS)) 1380 RHSTy = MHSTy; 1381 1382 if (!MHSTy || !RHSTy) { 1383 TokError("could not get type for !if"); 1384 return nullptr; 1385 } 1386 1387 Type = resolveTypes(MHSTy, RHSTy); 1388 if (!Type) { 1389 TokError(Twine("inconsistent types '") + MHSTy->getAsString() + 1390 "' and '" + RHSTy->getAsString() + "' for !if"); 1391 return nullptr; 1392 } 1393 break; 1394 } 1395 case tgtok::XSubst: { 1396 TypedInit *RHSt = dyn_cast<TypedInit>(RHS); 1397 if (!RHSt) { 1398 TokError("could not get type for !subst"); 1399 return nullptr; 1400 } 1401 Type = RHSt->getType(); 1402 break; 1403 } 1404 } 1405 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec); 1406 } 1407 1408 case tgtok::XFoldl: { 1409 // Value ::= !foldl '(' Id ',' Id ',' Value ',' Value ',' Value ')' 1410 Lex.Lex(); // eat the operation 1411 if (Lex.getCode() != tgtok::l_paren) { 1412 TokError("expected '(' after !foldl"); 1413 return nullptr; 1414 } 1415 Lex.Lex(); // eat the '(' 1416 1417 Init *StartUntyped = ParseValue(CurRec); 1418 if (!StartUntyped) 1419 return nullptr; 1420 1421 TypedInit *Start = dyn_cast<TypedInit>(StartUntyped); 1422 if (!Start) { 1423 TokError(Twine("could not get type of !foldl start: '") + 1424 StartUntyped->getAsString() + "'"); 1425 return nullptr; 1426 } 1427 1428 if (Lex.getCode() != tgtok::comma) { 1429 TokError("expected ',' in !foldl"); 1430 return nullptr; 1431 } 1432 Lex.Lex(); // eat the ',' 1433 1434 Init *ListUntyped = ParseValue(CurRec); 1435 if (!ListUntyped) 1436 return nullptr; 1437 1438 TypedInit *List = dyn_cast<TypedInit>(ListUntyped); 1439 if (!List) { 1440 TokError(Twine("could not get type of !foldl list: '") + 1441 ListUntyped->getAsString() + "'"); 1442 return nullptr; 1443 } 1444 1445 ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType()); 1446 if (!ListType) { 1447 TokError(Twine("!foldl list must be a list, but is of type '") + 1448 List->getType()->getAsString()); 1449 return nullptr; 1450 } 1451 1452 if (Lex.getCode() != tgtok::comma) { 1453 TokError("expected ',' in !foldl"); 1454 return nullptr; 1455 } 1456 1457 if (Lex.Lex() != tgtok::Id) { // eat the ',' 1458 TokError("third argument of !foldl must be an identifier"); 1459 return nullptr; 1460 } 1461 1462 Init *A = StringInit::get(Lex.getCurStrVal()); 1463 if (CurRec->getValue(A)) { 1464 TokError((Twine("left !foldl variable '") + A->getAsString() + 1465 "' already defined") 1466 .str()); 1467 return nullptr; 1468 } 1469 1470 if (Lex.Lex() != tgtok::comma) { // eat the id 1471 TokError("expected ',' in !foldl"); 1472 return nullptr; 1473 } 1474 1475 if (Lex.Lex() != tgtok::Id) { // eat the ',' 1476 TokError("fourth argument of !foldl must be an identifier"); 1477 return nullptr; 1478 } 1479 1480 Init *B = StringInit::get(Lex.getCurStrVal()); 1481 if (CurRec->getValue(B)) { 1482 TokError((Twine("right !foldl variable '") + B->getAsString() + 1483 "' already defined") 1484 .str()); 1485 return nullptr; 1486 } 1487 1488 if (Lex.Lex() != tgtok::comma) { // eat the id 1489 TokError("expected ',' in !foldl"); 1490 return nullptr; 1491 } 1492 Lex.Lex(); // eat the ',' 1493 1494 CurRec->addValue(RecordVal(A, Start->getType(), false)); 1495 CurRec->addValue(RecordVal(B, ListType->getElementType(), false)); 1496 Init *ExprUntyped = ParseValue(CurRec); 1497 CurRec->removeValue(A); 1498 CurRec->removeValue(B); 1499 if (!ExprUntyped) 1500 return nullptr; 1501 1502 TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped); 1503 if (!Expr) { 1504 TokError("could not get type of !foldl expression"); 1505 return nullptr; 1506 } 1507 1508 if (Expr->getType() != Start->getType()) { 1509 TokError(Twine("!foldl expression must be of same type as start (") + 1510 Start->getType()->getAsString() + "), but is of type " + 1511 Expr->getType()->getAsString()); 1512 return nullptr; 1513 } 1514 1515 if (Lex.getCode() != tgtok::r_paren) { 1516 TokError("expected ')' in fold operator"); 1517 return nullptr; 1518 } 1519 Lex.Lex(); // eat the ')' 1520 1521 return FoldOpInit::get(Start, List, A, B, Expr, Start->getType()) 1522 ->Fold(CurRec); 1523 } 1524 } 1525 } 1526 1527 /// ParseOperatorType - Parse a type for an operator. This returns 1528 /// null on error. 1529 /// 1530 /// OperatorType ::= '<' Type '>' 1531 /// 1532 RecTy *TGParser::ParseOperatorType() { 1533 RecTy *Type = nullptr; 1534 1535 if (Lex.getCode() != tgtok::less) { 1536 TokError("expected type name for operator"); 1537 return nullptr; 1538 } 1539 Lex.Lex(); // eat the < 1540 1541 Type = ParseType(); 1542 1543 if (!Type) { 1544 TokError("expected type name for operator"); 1545 return nullptr; 1546 } 1547 1548 if (Lex.getCode() != tgtok::greater) { 1549 TokError("expected type name for operator"); 1550 return nullptr; 1551 } 1552 Lex.Lex(); // eat the > 1553 1554 return Type; 1555 } 1556 1557 /// ParseSimpleValue - Parse a tblgen value. This returns null on error. 1558 /// 1559 /// SimpleValue ::= IDValue 1560 /// SimpleValue ::= INTVAL 1561 /// SimpleValue ::= STRVAL+ 1562 /// SimpleValue ::= CODEFRAGMENT 1563 /// SimpleValue ::= '?' 1564 /// SimpleValue ::= '{' ValueList '}' 1565 /// SimpleValue ::= ID '<' ValueListNE '>' 1566 /// SimpleValue ::= '[' ValueList ']' 1567 /// SimpleValue ::= '(' IDValue DagArgList ')' 1568 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')' 1569 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')' 1570 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')' 1571 /// SimpleValue ::= SRATOK '(' Value ',' Value ')' 1572 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')' 1573 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')' 1574 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')' 1575 /// 1576 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType, 1577 IDParseMode Mode) { 1578 Init *R = nullptr; 1579 switch (Lex.getCode()) { 1580 default: TokError("Unknown token when parsing a value"); break; 1581 case tgtok::paste: 1582 // This is a leading paste operation. This is deprecated but 1583 // still exists in some .td files. Ignore it. 1584 Lex.Lex(); // Skip '#'. 1585 return ParseSimpleValue(CurRec, ItemType, Mode); 1586 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break; 1587 case tgtok::BinaryIntVal: { 1588 auto BinaryVal = Lex.getCurBinaryIntVal(); 1589 SmallVector<Init*, 16> Bits(BinaryVal.second); 1590 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i) 1591 Bits[i] = BitInit::get(BinaryVal.first & (1LL << i)); 1592 R = BitsInit::get(Bits); 1593 Lex.Lex(); 1594 break; 1595 } 1596 case tgtok::StrVal: { 1597 std::string Val = Lex.getCurStrVal(); 1598 Lex.Lex(); 1599 1600 // Handle multiple consecutive concatenated strings. 1601 while (Lex.getCode() == tgtok::StrVal) { 1602 Val += Lex.getCurStrVal(); 1603 Lex.Lex(); 1604 } 1605 1606 R = StringInit::get(Val); 1607 break; 1608 } 1609 case tgtok::CodeFragment: 1610 R = CodeInit::get(Lex.getCurStrVal()); 1611 Lex.Lex(); 1612 break; 1613 case tgtok::question: 1614 R = UnsetInit::get(); 1615 Lex.Lex(); 1616 break; 1617 case tgtok::Id: { 1618 SMLoc NameLoc = Lex.getLoc(); 1619 StringInit *Name = StringInit::get(Lex.getCurStrVal()); 1620 if (Lex.Lex() != tgtok::less) // consume the Id. 1621 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue 1622 1623 // Value ::= ID '<' ValueListNE '>' 1624 if (Lex.Lex() == tgtok::greater) { 1625 TokError("expected non-empty value list"); 1626 return nullptr; 1627 } 1628 1629 // This is a CLASS<initvalslist> expression. This is supposed to synthesize 1630 // a new anonymous definition, deriving from CLASS<initvalslist> with no 1631 // body. 1632 Record *Class = Records.getClass(Name->getValue()); 1633 if (!Class) { 1634 Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'"); 1635 return nullptr; 1636 } 1637 1638 SmallVector<Init *, 8> Args; 1639 ParseValueList(Args, CurRec, Class); 1640 if (Args.empty()) return nullptr; 1641 1642 if (Lex.getCode() != tgtok::greater) { 1643 TokError("expected '>' at end of value list"); 1644 return nullptr; 1645 } 1646 Lex.Lex(); // eat the '>' 1647 1648 // Typecheck the template arguments list 1649 ArrayRef<Init *> ExpectedArgs = Class->getTemplateArgs(); 1650 if (ExpectedArgs.size() < Args.size()) { 1651 Error(NameLoc, 1652 "More template args specified than expected"); 1653 return nullptr; 1654 } 1655 1656 for (unsigned i = 0, e = ExpectedArgs.size(); i != e; ++i) { 1657 RecordVal *ExpectedArg = Class->getValue(ExpectedArgs[i]); 1658 if (i < Args.size()) { 1659 if (TypedInit *TI = dyn_cast<TypedInit>(Args[i])) { 1660 RecTy *ExpectedType = ExpectedArg->getType(); 1661 if (!TI->getType()->typeIsConvertibleTo(ExpectedType)) { 1662 Error(NameLoc, 1663 "Value specified for template argument #" + Twine(i) + " (" + 1664 ExpectedArg->getNameInitAsString() + ") is of type '" + 1665 TI->getType()->getAsString() + "', expected '" + 1666 ExpectedType->getAsString() + "': " + TI->getAsString()); 1667 return nullptr; 1668 } 1669 continue; 1670 } 1671 } else if (ExpectedArg->getValue()->isComplete()) 1672 continue; 1673 1674 Error(NameLoc, 1675 "Value not specified for template argument #" + Twine(i) + " (" + 1676 ExpectedArgs[i]->getAsUnquotedString() + ")"); 1677 return nullptr; 1678 } 1679 1680 return VarDefInit::get(Class, Args)->Fold(); 1681 } 1682 case tgtok::l_brace: { // Value ::= '{' ValueList '}' 1683 SMLoc BraceLoc = Lex.getLoc(); 1684 Lex.Lex(); // eat the '{' 1685 SmallVector<Init*, 16> Vals; 1686 1687 if (Lex.getCode() != tgtok::r_brace) { 1688 ParseValueList(Vals, CurRec); 1689 if (Vals.empty()) return nullptr; 1690 } 1691 if (Lex.getCode() != tgtok::r_brace) { 1692 TokError("expected '}' at end of bit list value"); 1693 return nullptr; 1694 } 1695 Lex.Lex(); // eat the '}' 1696 1697 SmallVector<Init *, 16> NewBits; 1698 1699 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it 1700 // first. We'll first read everything in to a vector, then we can reverse 1701 // it to get the bits in the correct order for the BitsInit value. 1702 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 1703 // FIXME: The following two loops would not be duplicated 1704 // if the API was a little more orthogonal. 1705 1706 // bits<n> values are allowed to initialize n bits. 1707 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) { 1708 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) 1709 NewBits.push_back(BI->getBit((e - i) - 1)); 1710 continue; 1711 } 1712 // bits<n> can also come from variable initializers. 1713 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) { 1714 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) { 1715 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i) 1716 NewBits.push_back(VI->getBit((e - i) - 1)); 1717 continue; 1718 } 1719 // Fallthrough to try convert this to a bit. 1720 } 1721 // All other values must be convertible to just a single bit. 1722 Init *Bit = Vals[i]->getCastTo(BitRecTy::get()); 1723 if (!Bit) { 1724 Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() + 1725 ") is not convertable to a bit"); 1726 return nullptr; 1727 } 1728 NewBits.push_back(Bit); 1729 } 1730 std::reverse(NewBits.begin(), NewBits.end()); 1731 return BitsInit::get(NewBits); 1732 } 1733 case tgtok::l_square: { // Value ::= '[' ValueList ']' 1734 Lex.Lex(); // eat the '[' 1735 SmallVector<Init*, 16> Vals; 1736 1737 RecTy *DeducedEltTy = nullptr; 1738 ListRecTy *GivenListTy = nullptr; 1739 1740 if (ItemType) { 1741 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType); 1742 if (!ListType) { 1743 TokError(Twine("Type mismatch for list, expected list type, got ") + 1744 ItemType->getAsString()); 1745 return nullptr; 1746 } 1747 GivenListTy = ListType; 1748 } 1749 1750 if (Lex.getCode() != tgtok::r_square) { 1751 ParseValueList(Vals, CurRec, nullptr, 1752 GivenListTy ? GivenListTy->getElementType() : nullptr); 1753 if (Vals.empty()) return nullptr; 1754 } 1755 if (Lex.getCode() != tgtok::r_square) { 1756 TokError("expected ']' at end of list value"); 1757 return nullptr; 1758 } 1759 Lex.Lex(); // eat the ']' 1760 1761 RecTy *GivenEltTy = nullptr; 1762 if (Lex.getCode() == tgtok::less) { 1763 // Optional list element type 1764 Lex.Lex(); // eat the '<' 1765 1766 GivenEltTy = ParseType(); 1767 if (!GivenEltTy) { 1768 // Couldn't parse element type 1769 return nullptr; 1770 } 1771 1772 if (Lex.getCode() != tgtok::greater) { 1773 TokError("expected '>' at end of list element type"); 1774 return nullptr; 1775 } 1776 Lex.Lex(); // eat the '>' 1777 } 1778 1779 // Check elements 1780 RecTy *EltTy = nullptr; 1781 for (Init *V : Vals) { 1782 TypedInit *TArg = dyn_cast<TypedInit>(V); 1783 if (TArg) { 1784 if (EltTy) { 1785 EltTy = resolveTypes(EltTy, TArg->getType()); 1786 if (!EltTy) { 1787 TokError("Incompatible types in list elements"); 1788 return nullptr; 1789 } 1790 } else { 1791 EltTy = TArg->getType(); 1792 } 1793 } 1794 } 1795 1796 if (GivenEltTy) { 1797 if (EltTy) { 1798 // Verify consistency 1799 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) { 1800 TokError("Incompatible types in list elements"); 1801 return nullptr; 1802 } 1803 } 1804 EltTy = GivenEltTy; 1805 } 1806 1807 if (!EltTy) { 1808 if (!ItemType) { 1809 TokError("No type for list"); 1810 return nullptr; 1811 } 1812 DeducedEltTy = GivenListTy->getElementType(); 1813 } else { 1814 // Make sure the deduced type is compatible with the given type 1815 if (GivenListTy) { 1816 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) { 1817 TokError(Twine("Element type mismatch for list: element type '") + 1818 EltTy->getAsString() + "' not convertible to '" + 1819 GivenListTy->getElementType()->getAsString()); 1820 return nullptr; 1821 } 1822 } 1823 DeducedEltTy = EltTy; 1824 } 1825 1826 return ListInit::get(Vals, DeducedEltTy); 1827 } 1828 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')' 1829 Lex.Lex(); // eat the '(' 1830 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) { 1831 TokError("expected identifier in dag init"); 1832 return nullptr; 1833 } 1834 1835 Init *Operator = ParseValue(CurRec); 1836 if (!Operator) return nullptr; 1837 1838 // If the operator name is present, parse it. 1839 StringInit *OperatorName = nullptr; 1840 if (Lex.getCode() == tgtok::colon) { 1841 if (Lex.Lex() != tgtok::VarName) { // eat the ':' 1842 TokError("expected variable name in dag operator"); 1843 return nullptr; 1844 } 1845 OperatorName = StringInit::get(Lex.getCurStrVal()); 1846 Lex.Lex(); // eat the VarName. 1847 } 1848 1849 SmallVector<std::pair<llvm::Init*, StringInit*>, 8> DagArgs; 1850 if (Lex.getCode() != tgtok::r_paren) { 1851 ParseDagArgList(DagArgs, CurRec); 1852 if (DagArgs.empty()) return nullptr; 1853 } 1854 1855 if (Lex.getCode() != tgtok::r_paren) { 1856 TokError("expected ')' in dag init"); 1857 return nullptr; 1858 } 1859 Lex.Lex(); // eat the ')' 1860 1861 return DagInit::get(Operator, OperatorName, DagArgs); 1862 } 1863 1864 case tgtok::XHead: 1865 case tgtok::XTail: 1866 case tgtok::XSize: 1867 case tgtok::XEmpty: 1868 case tgtok::XCast: // Value ::= !unop '(' Value ')' 1869 case tgtok::XIsA: 1870 case tgtok::XConcat: 1871 case tgtok::XDag: 1872 case tgtok::XADD: 1873 case tgtok::XAND: 1874 case tgtok::XOR: 1875 case tgtok::XSRA: 1876 case tgtok::XSRL: 1877 case tgtok::XSHL: 1878 case tgtok::XEq: 1879 case tgtok::XNe: 1880 case tgtok::XLe: 1881 case tgtok::XLt: 1882 case tgtok::XGe: 1883 case tgtok::XGt: 1884 case tgtok::XListConcat: 1885 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')' 1886 case tgtok::XIf: 1887 case tgtok::XFoldl: 1888 case tgtok::XForEach: 1889 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')' 1890 return ParseOperation(CurRec, ItemType); 1891 } 1892 } 1893 1894 return R; 1895 } 1896 1897 /// ParseValue - Parse a tblgen value. This returns null on error. 1898 /// 1899 /// Value ::= SimpleValue ValueSuffix* 1900 /// ValueSuffix ::= '{' BitList '}' 1901 /// ValueSuffix ::= '[' BitList ']' 1902 /// ValueSuffix ::= '.' ID 1903 /// 1904 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) { 1905 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode); 1906 if (!Result) return nullptr; 1907 1908 // Parse the suffixes now if present. 1909 while (true) { 1910 switch (Lex.getCode()) { 1911 default: return Result; 1912 case tgtok::l_brace: { 1913 if (Mode == ParseNameMode) 1914 // This is the beginning of the object body. 1915 return Result; 1916 1917 SMLoc CurlyLoc = Lex.getLoc(); 1918 Lex.Lex(); // eat the '{' 1919 SmallVector<unsigned, 16> Ranges; 1920 ParseRangeList(Ranges); 1921 if (Ranges.empty()) return nullptr; 1922 1923 // Reverse the bitlist. 1924 std::reverse(Ranges.begin(), Ranges.end()); 1925 Result = Result->convertInitializerBitRange(Ranges); 1926 if (!Result) { 1927 Error(CurlyLoc, "Invalid bit range for value"); 1928 return nullptr; 1929 } 1930 1931 // Eat the '}'. 1932 if (Lex.getCode() != tgtok::r_brace) { 1933 TokError("expected '}' at end of bit range list"); 1934 return nullptr; 1935 } 1936 Lex.Lex(); 1937 break; 1938 } 1939 case tgtok::l_square: { 1940 SMLoc SquareLoc = Lex.getLoc(); 1941 Lex.Lex(); // eat the '[' 1942 SmallVector<unsigned, 16> Ranges; 1943 ParseRangeList(Ranges); 1944 if (Ranges.empty()) return nullptr; 1945 1946 Result = Result->convertInitListSlice(Ranges); 1947 if (!Result) { 1948 Error(SquareLoc, "Invalid range for list slice"); 1949 return nullptr; 1950 } 1951 1952 // Eat the ']'. 1953 if (Lex.getCode() != tgtok::r_square) { 1954 TokError("expected ']' at end of list slice"); 1955 return nullptr; 1956 } 1957 Lex.Lex(); 1958 break; 1959 } 1960 case tgtok::period: { 1961 if (Lex.Lex() != tgtok::Id) { // eat the . 1962 TokError("expected field identifier after '.'"); 1963 return nullptr; 1964 } 1965 StringInit *FieldName = StringInit::get(Lex.getCurStrVal()); 1966 if (!Result->getFieldType(FieldName)) { 1967 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" + 1968 Result->getAsString() + "'"); 1969 return nullptr; 1970 } 1971 Result = FieldInit::get(Result, FieldName)->Fold(CurRec); 1972 Lex.Lex(); // eat field name 1973 break; 1974 } 1975 1976 case tgtok::paste: 1977 SMLoc PasteLoc = Lex.getLoc(); 1978 1979 // Create a !strconcat() operation, first casting each operand to 1980 // a string if necessary. 1981 1982 TypedInit *LHS = dyn_cast<TypedInit>(Result); 1983 if (!LHS) { 1984 Error(PasteLoc, "LHS of paste is not typed!"); 1985 return nullptr; 1986 } 1987 1988 if (LHS->getType() != StringRecTy::get()) { 1989 LHS = dyn_cast<TypedInit>( 1990 UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get()) 1991 ->Fold(CurRec)); 1992 if (!LHS) { 1993 Error(PasteLoc, Twine("can't cast '") + LHS->getAsString() + 1994 "' to string"); 1995 return nullptr; 1996 } 1997 } 1998 1999 TypedInit *RHS = nullptr; 2000 2001 Lex.Lex(); // Eat the '#'. 2002 switch (Lex.getCode()) { 2003 case tgtok::colon: 2004 case tgtok::semi: 2005 case tgtok::l_brace: 2006 // These are all of the tokens that can begin an object body. 2007 // Some of these can also begin values but we disallow those cases 2008 // because they are unlikely to be useful. 2009 2010 // Trailing paste, concat with an empty string. 2011 RHS = StringInit::get(""); 2012 break; 2013 2014 default: 2015 Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode); 2016 RHS = dyn_cast<TypedInit>(RHSResult); 2017 if (!RHS) { 2018 Error(PasteLoc, "RHS of paste is not typed!"); 2019 return nullptr; 2020 } 2021 2022 if (RHS->getType() != StringRecTy::get()) { 2023 RHS = dyn_cast<TypedInit>( 2024 UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get()) 2025 ->Fold(CurRec)); 2026 if (!RHS) { 2027 Error(PasteLoc, Twine("can't cast '") + RHS->getAsString() + 2028 "' to string"); 2029 return nullptr; 2030 } 2031 } 2032 2033 break; 2034 } 2035 2036 Result = BinOpInit::getStrConcat(LHS, RHS); 2037 break; 2038 } 2039 } 2040 } 2041 2042 /// ParseDagArgList - Parse the argument list for a dag literal expression. 2043 /// 2044 /// DagArg ::= Value (':' VARNAME)? 2045 /// DagArg ::= VARNAME 2046 /// DagArgList ::= DagArg 2047 /// DagArgList ::= DagArgList ',' DagArg 2048 void TGParser::ParseDagArgList( 2049 SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result, 2050 Record *CurRec) { 2051 2052 while (true) { 2053 // DagArg ::= VARNAME 2054 if (Lex.getCode() == tgtok::VarName) { 2055 // A missing value is treated like '?'. 2056 StringInit *VarName = StringInit::get(Lex.getCurStrVal()); 2057 Result.emplace_back(UnsetInit::get(), VarName); 2058 Lex.Lex(); 2059 } else { 2060 // DagArg ::= Value (':' VARNAME)? 2061 Init *Val = ParseValue(CurRec); 2062 if (!Val) { 2063 Result.clear(); 2064 return; 2065 } 2066 2067 // If the variable name is present, add it. 2068 StringInit *VarName = nullptr; 2069 if (Lex.getCode() == tgtok::colon) { 2070 if (Lex.Lex() != tgtok::VarName) { // eat the ':' 2071 TokError("expected variable name in dag literal"); 2072 Result.clear(); 2073 return; 2074 } 2075 VarName = StringInit::get(Lex.getCurStrVal()); 2076 Lex.Lex(); // eat the VarName. 2077 } 2078 2079 Result.push_back(std::make_pair(Val, VarName)); 2080 } 2081 if (Lex.getCode() != tgtok::comma) break; 2082 Lex.Lex(); // eat the ',' 2083 } 2084 } 2085 2086 /// ParseValueList - Parse a comma separated list of values, returning them as a 2087 /// vector. Note that this always expects to be able to parse at least one 2088 /// value. It returns an empty list if this is not possible. 2089 /// 2090 /// ValueList ::= Value (',' Value) 2091 /// 2092 void TGParser::ParseValueList(SmallVectorImpl<Init*> &Result, Record *CurRec, 2093 Record *ArgsRec, RecTy *EltTy) { 2094 RecTy *ItemType = EltTy; 2095 unsigned int ArgN = 0; 2096 if (ArgsRec && !EltTy) { 2097 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs(); 2098 if (TArgs.empty()) { 2099 TokError("template argument provided to non-template class"); 2100 Result.clear(); 2101 return; 2102 } 2103 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]); 2104 if (!RV) { 2105 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN] 2106 << ")\n"; 2107 } 2108 assert(RV && "Template argument record not found??"); 2109 ItemType = RV->getType(); 2110 ++ArgN; 2111 } 2112 Result.push_back(ParseValue(CurRec, ItemType)); 2113 if (!Result.back()) { 2114 Result.clear(); 2115 return; 2116 } 2117 2118 while (Lex.getCode() == tgtok::comma) { 2119 Lex.Lex(); // Eat the comma 2120 2121 if (ArgsRec && !EltTy) { 2122 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs(); 2123 if (ArgN >= TArgs.size()) { 2124 TokError("too many template arguments"); 2125 Result.clear(); 2126 return; 2127 } 2128 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]); 2129 assert(RV && "Template argument record not found??"); 2130 ItemType = RV->getType(); 2131 ++ArgN; 2132 } 2133 Result.push_back(ParseValue(CurRec, ItemType)); 2134 if (!Result.back()) { 2135 Result.clear(); 2136 return; 2137 } 2138 } 2139 } 2140 2141 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an 2142 /// empty string on error. This can happen in a number of different context's, 2143 /// including within a def or in the template args for a def (which which case 2144 /// CurRec will be non-null) and within the template args for a multiclass (in 2145 /// which case CurRec will be null, but CurMultiClass will be set). This can 2146 /// also happen within a def that is within a multiclass, which will set both 2147 /// CurRec and CurMultiClass. 2148 /// 2149 /// Declaration ::= FIELD? Type ID ('=' Value)? 2150 /// 2151 Init *TGParser::ParseDeclaration(Record *CurRec, 2152 bool ParsingTemplateArgs) { 2153 // Read the field prefix if present. 2154 bool HasField = Lex.getCode() == tgtok::Field; 2155 if (HasField) Lex.Lex(); 2156 2157 RecTy *Type = ParseType(); 2158 if (!Type) return nullptr; 2159 2160 if (Lex.getCode() != tgtok::Id) { 2161 TokError("Expected identifier in declaration"); 2162 return nullptr; 2163 } 2164 2165 SMLoc IdLoc = Lex.getLoc(); 2166 Init *DeclName = StringInit::get(Lex.getCurStrVal()); 2167 Lex.Lex(); 2168 2169 if (ParsingTemplateArgs) { 2170 if (CurRec) 2171 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":"); 2172 else 2173 assert(CurMultiClass); 2174 if (CurMultiClass) 2175 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName, 2176 "::"); 2177 } 2178 2179 // Add the value. 2180 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField))) 2181 return nullptr; 2182 2183 // If a value is present, parse it. 2184 if (Lex.getCode() == tgtok::equal) { 2185 Lex.Lex(); 2186 SMLoc ValLoc = Lex.getLoc(); 2187 Init *Val = ParseValue(CurRec, Type); 2188 if (!Val || 2189 SetValue(CurRec, ValLoc, DeclName, None, Val)) 2190 // Return the name, even if an error is thrown. This is so that we can 2191 // continue to make some progress, even without the value having been 2192 // initialized. 2193 return DeclName; 2194 } 2195 2196 return DeclName; 2197 } 2198 2199 /// ParseForeachDeclaration - Read a foreach declaration, returning 2200 /// the name of the declared object or a NULL Init on error. Return 2201 /// the name of the parsed initializer list through ForeachListName. 2202 /// 2203 /// ForeachDeclaration ::= ID '=' '{' RangeList '}' 2204 /// ForeachDeclaration ::= ID '=' RangePiece 2205 /// ForeachDeclaration ::= ID '=' Value 2206 /// 2207 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) { 2208 if (Lex.getCode() != tgtok::Id) { 2209 TokError("Expected identifier in foreach declaration"); 2210 return nullptr; 2211 } 2212 2213 Init *DeclName = StringInit::get(Lex.getCurStrVal()); 2214 Lex.Lex(); 2215 2216 // If a value is present, parse it. 2217 if (Lex.getCode() != tgtok::equal) { 2218 TokError("Expected '=' in foreach declaration"); 2219 return nullptr; 2220 } 2221 Lex.Lex(); // Eat the '=' 2222 2223 RecTy *IterType = nullptr; 2224 SmallVector<unsigned, 16> Ranges; 2225 2226 switch (Lex.getCode()) { 2227 case tgtok::IntVal: { // RangePiece. 2228 if (ParseRangePiece(Ranges)) 2229 return nullptr; 2230 break; 2231 } 2232 2233 case tgtok::l_brace: { // '{' RangeList '}' 2234 Lex.Lex(); // eat the '{' 2235 ParseRangeList(Ranges); 2236 if (Lex.getCode() != tgtok::r_brace) { 2237 TokError("expected '}' at end of bit range list"); 2238 return nullptr; 2239 } 2240 Lex.Lex(); 2241 break; 2242 } 2243 2244 default: { 2245 SMLoc ValueLoc = Lex.getLoc(); 2246 Init *I = ParseValue(nullptr); 2247 if (!isa<ListInit>(I)) { 2248 std::string Type; 2249 if (TypedInit *TI = dyn_cast<TypedInit>(I)) 2250 Type = (Twine("' of type '") + TI->getType()->getAsString()).str(); 2251 Error(ValueLoc, "expected a list, got '" + I->getAsString() + Type + "'"); 2252 if (CurMultiClass) 2253 PrintNote({}, "references to multiclass template arguments cannot be " 2254 "resolved at this time"); 2255 return nullptr; 2256 } 2257 ForeachListValue = dyn_cast<ListInit>(I); 2258 IterType = ForeachListValue->getElementType(); 2259 break; 2260 } 2261 } 2262 2263 if (!Ranges.empty()) { 2264 assert(!IterType && "Type already initialized?"); 2265 IterType = IntRecTy::get(); 2266 std::vector<Init*> Values; 2267 for (unsigned R : Ranges) 2268 Values.push_back(IntInit::get(R)); 2269 ForeachListValue = ListInit::get(Values, IterType); 2270 } 2271 2272 if (!IterType) 2273 return nullptr; 2274 2275 return VarInit::get(DeclName, IterType); 2276 } 2277 2278 /// ParseTemplateArgList - Read a template argument list, which is a non-empty 2279 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are 2280 /// template args for a def, which may or may not be in a multiclass. If null, 2281 /// these are the template args for a multiclass. 2282 /// 2283 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>' 2284 /// 2285 bool TGParser::ParseTemplateArgList(Record *CurRec) { 2286 assert(Lex.getCode() == tgtok::less && "Not a template arg list!"); 2287 Lex.Lex(); // eat the '<' 2288 2289 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec; 2290 2291 // Read the first declaration. 2292 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/); 2293 if (!TemplArg) 2294 return true; 2295 2296 TheRecToAddTo->addTemplateArg(TemplArg); 2297 2298 while (Lex.getCode() == tgtok::comma) { 2299 Lex.Lex(); // eat the ',' 2300 2301 // Read the following declarations. 2302 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/); 2303 if (!TemplArg) 2304 return true; 2305 TheRecToAddTo->addTemplateArg(TemplArg); 2306 } 2307 2308 if (Lex.getCode() != tgtok::greater) 2309 return TokError("expected '>' at end of template argument list"); 2310 Lex.Lex(); // eat the '>'. 2311 return false; 2312 } 2313 2314 /// ParseBodyItem - Parse a single item at within the body of a def or class. 2315 /// 2316 /// BodyItem ::= Declaration ';' 2317 /// BodyItem ::= LET ID OptionalBitList '=' Value ';' 2318 bool TGParser::ParseBodyItem(Record *CurRec) { 2319 if (Lex.getCode() != tgtok::Let) { 2320 if (!ParseDeclaration(CurRec, false)) 2321 return true; 2322 2323 if (Lex.getCode() != tgtok::semi) 2324 return TokError("expected ';' after declaration"); 2325 Lex.Lex(); 2326 return false; 2327 } 2328 2329 // LET ID OptionalRangeList '=' Value ';' 2330 if (Lex.Lex() != tgtok::Id) 2331 return TokError("expected field identifier after let"); 2332 2333 SMLoc IdLoc = Lex.getLoc(); 2334 StringInit *FieldName = StringInit::get(Lex.getCurStrVal()); 2335 Lex.Lex(); // eat the field name. 2336 2337 SmallVector<unsigned, 16> BitList; 2338 if (ParseOptionalBitList(BitList)) 2339 return true; 2340 std::reverse(BitList.begin(), BitList.end()); 2341 2342 if (Lex.getCode() != tgtok::equal) 2343 return TokError("expected '=' in let expression"); 2344 Lex.Lex(); // eat the '='. 2345 2346 RecordVal *Field = CurRec->getValue(FieldName); 2347 if (!Field) 2348 return TokError("Value '" + FieldName->getValue() + "' unknown!"); 2349 2350 RecTy *Type = Field->getType(); 2351 2352 Init *Val = ParseValue(CurRec, Type); 2353 if (!Val) return true; 2354 2355 if (Lex.getCode() != tgtok::semi) 2356 return TokError("expected ';' after let expression"); 2357 Lex.Lex(); 2358 2359 return SetValue(CurRec, IdLoc, FieldName, BitList, Val); 2360 } 2361 2362 /// ParseBody - Read the body of a class or def. Return true on error, false on 2363 /// success. 2364 /// 2365 /// Body ::= ';' 2366 /// Body ::= '{' BodyList '}' 2367 /// BodyList BodyItem* 2368 /// 2369 bool TGParser::ParseBody(Record *CurRec) { 2370 // If this is a null definition, just eat the semi and return. 2371 if (Lex.getCode() == tgtok::semi) { 2372 Lex.Lex(); 2373 return false; 2374 } 2375 2376 if (Lex.getCode() != tgtok::l_brace) 2377 return TokError("Expected ';' or '{' to start body"); 2378 // Eat the '{'. 2379 Lex.Lex(); 2380 2381 while (Lex.getCode() != tgtok::r_brace) 2382 if (ParseBodyItem(CurRec)) 2383 return true; 2384 2385 // Eat the '}'. 2386 Lex.Lex(); 2387 return false; 2388 } 2389 2390 /// Apply the current let bindings to \a CurRec. 2391 /// \returns true on error, false otherwise. 2392 bool TGParser::ApplyLetStack(Record *CurRec) { 2393 for (SmallVectorImpl<LetRecord> &LetInfo : LetStack) 2394 for (LetRecord &LR : LetInfo) 2395 if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value)) 2396 return true; 2397 return false; 2398 } 2399 2400 /// ParseObjectBody - Parse the body of a def or class. This consists of an 2401 /// optional ClassList followed by a Body. CurRec is the current def or class 2402 /// that is being parsed. 2403 /// 2404 /// ObjectBody ::= BaseClassList Body 2405 /// BaseClassList ::= /*empty*/ 2406 /// BaseClassList ::= ':' BaseClassListNE 2407 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)* 2408 /// 2409 bool TGParser::ParseObjectBody(Record *CurRec) { 2410 // If there is a baseclass list, read it. 2411 if (Lex.getCode() == tgtok::colon) { 2412 Lex.Lex(); 2413 2414 // Read all of the subclasses. 2415 SubClassReference SubClass = ParseSubClassReference(CurRec, false); 2416 while (true) { 2417 // Check for error. 2418 if (!SubClass.Rec) return true; 2419 2420 // Add it. 2421 if (AddSubClass(CurRec, SubClass)) 2422 return true; 2423 2424 if (Lex.getCode() != tgtok::comma) break; 2425 Lex.Lex(); // eat ','. 2426 SubClass = ParseSubClassReference(CurRec, false); 2427 } 2428 } 2429 2430 if (ApplyLetStack(CurRec)) 2431 return true; 2432 2433 return ParseBody(CurRec); 2434 } 2435 2436 /// ParseDef - Parse and return a top level or multiclass def, return the record 2437 /// corresponding to it. This returns null on error. 2438 /// 2439 /// DefInst ::= DEF ObjectName ObjectBody 2440 /// 2441 bool TGParser::ParseDef(MultiClass *CurMultiClass) { 2442 SMLoc DefLoc = Lex.getLoc(); 2443 assert(Lex.getCode() == tgtok::Def && "Unknown tok"); 2444 Lex.Lex(); // Eat the 'def' token. 2445 2446 // Parse ObjectName and make a record for it. 2447 std::unique_ptr<Record> CurRec; 2448 Init *Name = ParseObjectName(CurMultiClass); 2449 if (!Name) 2450 return true; 2451 2452 if (isa<UnsetInit>(Name)) 2453 CurRec = make_unique<Record>(Records.getNewAnonymousName(), DefLoc, Records, 2454 /*Anonymous=*/true); 2455 else 2456 CurRec = make_unique<Record>(Name, DefLoc, Records); 2457 2458 if (ParseObjectBody(CurRec.get())) 2459 return true; 2460 2461 return addDef(std::move(CurRec), nullptr); 2462 } 2463 2464 /// ParseDefset - Parse a defset statement. 2465 /// 2466 /// Defset ::= DEFSET Type Id '=' '{' ObjectList '}' 2467 /// 2468 bool TGParser::ParseDefset() { 2469 assert(Lex.getCode() == tgtok::Defset); 2470 Lex.Lex(); // Eat the 'defset' token 2471 2472 DefsetRecord Defset; 2473 Defset.Loc = Lex.getLoc(); 2474 RecTy *Type = ParseType(); 2475 if (!Type) 2476 return true; 2477 if (!isa<ListRecTy>(Type)) 2478 return Error(Defset.Loc, "expected list type"); 2479 Defset.EltTy = cast<ListRecTy>(Type)->getElementType(); 2480 2481 if (Lex.getCode() != tgtok::Id) 2482 return TokError("expected identifier"); 2483 StringInit *DeclName = StringInit::get(Lex.getCurStrVal()); 2484 if (Records.getGlobal(DeclName->getValue())) 2485 return TokError("def or global variable of this name already exists"); 2486 2487 if (Lex.Lex() != tgtok::equal) // Eat the identifier 2488 return TokError("expected '='"); 2489 if (Lex.Lex() != tgtok::l_brace) // Eat the '=' 2490 return TokError("expected '{'"); 2491 SMLoc BraceLoc = Lex.getLoc(); 2492 Lex.Lex(); // Eat the '{' 2493 2494 Defsets.push_back(&Defset); 2495 bool Err = ParseObjectList(nullptr); 2496 Defsets.pop_back(); 2497 if (Err) 2498 return true; 2499 2500 if (Lex.getCode() != tgtok::r_brace) { 2501 TokError("expected '}' at end of defset"); 2502 return Error(BraceLoc, "to match this '{'"); 2503 } 2504 Lex.Lex(); // Eat the '}' 2505 2506 Records.addExtraGlobal(DeclName->getValue(), 2507 ListInit::get(Defset.Elements, Defset.EltTy)); 2508 return false; 2509 } 2510 2511 /// ParseForeach - Parse a for statement. Return the record corresponding 2512 /// to it. This returns true on error. 2513 /// 2514 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}' 2515 /// Foreach ::= FOREACH Declaration IN Object 2516 /// 2517 bool TGParser::ParseForeach(MultiClass *CurMultiClass) { 2518 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok"); 2519 Lex.Lex(); // Eat the 'for' token. 2520 2521 // Make a temporary object to record items associated with the for 2522 // loop. 2523 ListInit *ListValue = nullptr; 2524 VarInit *IterName = ParseForeachDeclaration(ListValue); 2525 if (!IterName) 2526 return TokError("expected declaration in for"); 2527 2528 if (Lex.getCode() != tgtok::In) 2529 return TokError("Unknown tok"); 2530 Lex.Lex(); // Eat the in 2531 2532 // Create a loop object and remember it. 2533 Loops.push_back(ForeachLoop(IterName, ListValue)); 2534 2535 if (Lex.getCode() != tgtok::l_brace) { 2536 // FOREACH Declaration IN Object 2537 if (ParseObject(CurMultiClass)) 2538 return true; 2539 } else { 2540 SMLoc BraceLoc = Lex.getLoc(); 2541 // Otherwise, this is a group foreach. 2542 Lex.Lex(); // eat the '{'. 2543 2544 // Parse the object list. 2545 if (ParseObjectList(CurMultiClass)) 2546 return true; 2547 2548 if (Lex.getCode() != tgtok::r_brace) { 2549 TokError("expected '}' at end of foreach command"); 2550 return Error(BraceLoc, "to match this '{'"); 2551 } 2552 Lex.Lex(); // Eat the } 2553 } 2554 2555 // We've processed everything in this loop. 2556 Loops.pop_back(); 2557 2558 return false; 2559 } 2560 2561 /// ParseClass - Parse a tblgen class definition. 2562 /// 2563 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody 2564 /// 2565 bool TGParser::ParseClass() { 2566 assert(Lex.getCode() == tgtok::Class && "Unexpected token!"); 2567 Lex.Lex(); 2568 2569 if (Lex.getCode() != tgtok::Id) 2570 return TokError("expected class name after 'class' keyword"); 2571 2572 Record *CurRec = Records.getClass(Lex.getCurStrVal()); 2573 if (CurRec) { 2574 // If the body was previously defined, this is an error. 2575 if (CurRec->getValues().size() > 1 || // Account for NAME. 2576 !CurRec->getSuperClasses().empty() || 2577 !CurRec->getTemplateArgs().empty()) 2578 return TokError("Class '" + CurRec->getNameInitAsString() + 2579 "' already defined"); 2580 } else { 2581 // If this is the first reference to this class, create and add it. 2582 auto NewRec = 2583 llvm::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records); 2584 CurRec = NewRec.get(); 2585 Records.addClass(std::move(NewRec)); 2586 } 2587 Lex.Lex(); // eat the name. 2588 2589 // If there are template args, parse them. 2590 if (Lex.getCode() == tgtok::less) 2591 if (ParseTemplateArgList(CurRec)) 2592 return true; 2593 2594 // Finally, parse the object body. 2595 return ParseObjectBody(CurRec); 2596 } 2597 2598 /// ParseLetList - Parse a non-empty list of assignment expressions into a list 2599 /// of LetRecords. 2600 /// 2601 /// LetList ::= LetItem (',' LetItem)* 2602 /// LetItem ::= ID OptionalRangeList '=' Value 2603 /// 2604 void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) { 2605 while (true) { 2606 if (Lex.getCode() != tgtok::Id) { 2607 TokError("expected identifier in let definition"); 2608 Result.clear(); 2609 return; 2610 } 2611 2612 StringInit *Name = StringInit::get(Lex.getCurStrVal()); 2613 SMLoc NameLoc = Lex.getLoc(); 2614 Lex.Lex(); // Eat the identifier. 2615 2616 // Check for an optional RangeList. 2617 SmallVector<unsigned, 16> Bits; 2618 if (ParseOptionalRangeList(Bits)) { 2619 Result.clear(); 2620 return; 2621 } 2622 std::reverse(Bits.begin(), Bits.end()); 2623 2624 if (Lex.getCode() != tgtok::equal) { 2625 TokError("expected '=' in let expression"); 2626 Result.clear(); 2627 return; 2628 } 2629 Lex.Lex(); // eat the '='. 2630 2631 Init *Val = ParseValue(nullptr); 2632 if (!Val) { 2633 Result.clear(); 2634 return; 2635 } 2636 2637 // Now that we have everything, add the record. 2638 Result.emplace_back(Name, Bits, Val, NameLoc); 2639 2640 if (Lex.getCode() != tgtok::comma) 2641 return; 2642 Lex.Lex(); // eat the comma. 2643 } 2644 } 2645 2646 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of 2647 /// different related productions. This works inside multiclasses too. 2648 /// 2649 /// Object ::= LET LetList IN '{' ObjectList '}' 2650 /// Object ::= LET LetList IN Object 2651 /// 2652 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) { 2653 assert(Lex.getCode() == tgtok::Let && "Unexpected token"); 2654 Lex.Lex(); 2655 2656 // Add this entry to the let stack. 2657 SmallVector<LetRecord, 8> LetInfo; 2658 ParseLetList(LetInfo); 2659 if (LetInfo.empty()) return true; 2660 LetStack.push_back(std::move(LetInfo)); 2661 2662 if (Lex.getCode() != tgtok::In) 2663 return TokError("expected 'in' at end of top-level 'let'"); 2664 Lex.Lex(); 2665 2666 // If this is a scalar let, just handle it now 2667 if (Lex.getCode() != tgtok::l_brace) { 2668 // LET LetList IN Object 2669 if (ParseObject(CurMultiClass)) 2670 return true; 2671 } else { // Object ::= LETCommand '{' ObjectList '}' 2672 SMLoc BraceLoc = Lex.getLoc(); 2673 // Otherwise, this is a group let. 2674 Lex.Lex(); // eat the '{'. 2675 2676 // Parse the object list. 2677 if (ParseObjectList(CurMultiClass)) 2678 return true; 2679 2680 if (Lex.getCode() != tgtok::r_brace) { 2681 TokError("expected '}' at end of top level let command"); 2682 return Error(BraceLoc, "to match this '{'"); 2683 } 2684 Lex.Lex(); 2685 } 2686 2687 // Outside this let scope, this let block is not active. 2688 LetStack.pop_back(); 2689 return false; 2690 } 2691 2692 /// ParseMultiClass - Parse a multiclass definition. 2693 /// 2694 /// MultiClassInst ::= MULTICLASS ID TemplateArgList? 2695 /// ':' BaseMultiClassList '{' MultiClassObject+ '}' 2696 /// MultiClassObject ::= DefInst 2697 /// MultiClassObject ::= MultiClassInst 2698 /// MultiClassObject ::= DefMInst 2699 /// MultiClassObject ::= LETCommand '{' ObjectList '}' 2700 /// MultiClassObject ::= LETCommand Object 2701 /// 2702 bool TGParser::ParseMultiClass() { 2703 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token"); 2704 Lex.Lex(); // Eat the multiclass token. 2705 2706 if (Lex.getCode() != tgtok::Id) 2707 return TokError("expected identifier after multiclass for name"); 2708 std::string Name = Lex.getCurStrVal(); 2709 2710 auto Result = 2711 MultiClasses.insert(std::make_pair(Name, 2712 llvm::make_unique<MultiClass>(Name, Lex.getLoc(),Records))); 2713 2714 if (!Result.second) 2715 return TokError("multiclass '" + Name + "' already defined"); 2716 2717 CurMultiClass = Result.first->second.get(); 2718 Lex.Lex(); // Eat the identifier. 2719 2720 // If there are template args, parse them. 2721 if (Lex.getCode() == tgtok::less) 2722 if (ParseTemplateArgList(nullptr)) 2723 return true; 2724 2725 bool inherits = false; 2726 2727 // If there are submulticlasses, parse them. 2728 if (Lex.getCode() == tgtok::colon) { 2729 inherits = true; 2730 2731 Lex.Lex(); 2732 2733 // Read all of the submulticlasses. 2734 SubMultiClassReference SubMultiClass = 2735 ParseSubMultiClassReference(CurMultiClass); 2736 while (true) { 2737 // Check for error. 2738 if (!SubMultiClass.MC) return true; 2739 2740 // Add it. 2741 if (AddSubMultiClass(CurMultiClass, SubMultiClass)) 2742 return true; 2743 2744 if (Lex.getCode() != tgtok::comma) break; 2745 Lex.Lex(); // eat ','. 2746 SubMultiClass = ParseSubMultiClassReference(CurMultiClass); 2747 } 2748 } 2749 2750 if (Lex.getCode() != tgtok::l_brace) { 2751 if (!inherits) 2752 return TokError("expected '{' in multiclass definition"); 2753 if (Lex.getCode() != tgtok::semi) 2754 return TokError("expected ';' in multiclass definition"); 2755 Lex.Lex(); // eat the ';'. 2756 } else { 2757 if (Lex.Lex() == tgtok::r_brace) // eat the '{'. 2758 return TokError("multiclass must contain at least one def"); 2759 2760 while (Lex.getCode() != tgtok::r_brace) { 2761 switch (Lex.getCode()) { 2762 default: 2763 return TokError("expected 'let', 'def', 'defm' or 'foreach' in " 2764 "multiclass body"); 2765 case tgtok::Let: 2766 case tgtok::Def: 2767 case tgtok::Defm: 2768 case tgtok::Foreach: 2769 if (ParseObject(CurMultiClass)) 2770 return true; 2771 break; 2772 } 2773 } 2774 Lex.Lex(); // eat the '}'. 2775 } 2776 2777 CurMultiClass = nullptr; 2778 return false; 2779 } 2780 2781 /// ParseDefm - Parse the instantiation of a multiclass. 2782 /// 2783 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';' 2784 /// 2785 bool TGParser::ParseDefm(MultiClass *CurMultiClass) { 2786 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!"); 2787 Lex.Lex(); // eat the defm 2788 2789 Init *DefmName = ParseObjectName(CurMultiClass); 2790 if (!DefmName) 2791 return true; 2792 if (isa<UnsetInit>(DefmName)) 2793 DefmName = Records.getNewAnonymousName(); 2794 2795 if (Lex.getCode() != tgtok::colon) 2796 return TokError("expected ':' after defm identifier"); 2797 2798 // Keep track of the new generated record definitions. 2799 SmallVector<std::unique_ptr<Record>, 8> NewRecDefs; 2800 2801 // This record also inherits from a regular class (non-multiclass)? 2802 bool InheritFromClass = false; 2803 2804 // eat the colon. 2805 Lex.Lex(); 2806 2807 SMLoc SubClassLoc = Lex.getLoc(); 2808 SubClassReference Ref = ParseSubClassReference(nullptr, true); 2809 2810 while (true) { 2811 if (!Ref.Rec) return true; 2812 2813 // To instantiate a multiclass, we need to first get the multiclass, then 2814 // instantiate each def contained in the multiclass with the SubClassRef 2815 // template parameters. 2816 MultiClass *MC = MultiClasses[Ref.Rec->getName()].get(); 2817 assert(MC && "Didn't lookup multiclass correctly?"); 2818 ArrayRef<Init*> TemplateVals = Ref.TemplateArgs; 2819 2820 // Verify that the correct number of template arguments were specified. 2821 ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs(); 2822 if (TArgs.size() < TemplateVals.size()) 2823 return Error(SubClassLoc, 2824 "more template args specified than multiclass expects"); 2825 2826 DenseMap<Init *, Init *> TemplateArgs; 2827 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) { 2828 if (i < TemplateVals.size()) { 2829 TemplateArgs.insert({TArgs[i], TemplateVals[i]}); 2830 } else { 2831 Init *Default = MC->Rec.getValue(TArgs[i])->getValue(); 2832 if (!Default->isComplete()) { 2833 return Error(SubClassLoc, 2834 "value not specified for template argument #" + 2835 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() + 2836 ") of multiclass '" + MC->Rec.getNameInitAsString() + 2837 "'"); 2838 } 2839 TemplateArgs.insert({TArgs[i], Default}); 2840 } 2841 } 2842 2843 // Loop over all the def's in the multiclass, instantiating each one. 2844 for (const std::unique_ptr<Record> &DefProto : MC->DefPrototypes) { 2845 bool ResolveName = true; 2846 auto CurRec = make_unique<Record>(*DefProto); 2847 CurRec->appendLoc(SubClassLoc); 2848 2849 if (StringInit *NameString = 2850 dyn_cast<StringInit>(CurRec->getNameInit())) { 2851 // We have a fully expanded string so there are no operators to 2852 // resolve. We should concatenate the given prefix and name. 2853 // 2854 // TODO: This MUST happen before template argument resolution. This 2855 // does not make sense and should be changed, but at the time of 2856 // writing, there are existing .td files which rely on this 2857 // implementation detail. It's a bad idea and should be fixed. 2858 // See test/TableGen/name-resolution-consistency.td for some 2859 // examples. 2860 CurRec->setName(BinOpInit::getStrConcat(DefmName, NameString)); 2861 ResolveName = false; 2862 } 2863 2864 MapResolver R(CurRec.get()); 2865 2866 if (ResolveName) { 2867 // If the proto's name wasn't resolved, we probably have a reference to 2868 // NAME and need to replace it. 2869 // 2870 // TODO: Whether the name is resolved is basically determined by magic. 2871 // Unfortunately, existing .td files depend on it. 2872 R.set(StringInit::get("NAME"), DefmName); 2873 } 2874 2875 for (const auto &TArg : TemplateArgs) 2876 R.set(TArg.first, TArg.second); 2877 2878 CurRec->resolveReferences(R); 2879 2880 NewRecDefs.emplace_back(std::move(CurRec)); 2881 } 2882 2883 if (Lex.getCode() != tgtok::comma) break; 2884 Lex.Lex(); // eat ','. 2885 2886 if (Lex.getCode() != tgtok::Id) 2887 return TokError("expected identifier"); 2888 2889 SubClassLoc = Lex.getLoc(); 2890 2891 // A defm can inherit from regular classes (non-multiclass) as 2892 // long as they come in the end of the inheritance list. 2893 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr); 2894 2895 if (InheritFromClass) 2896 break; 2897 2898 Ref = ParseSubClassReference(nullptr, true); 2899 } 2900 2901 if (InheritFromClass) { 2902 // Process all the classes to inherit as if they were part of a 2903 // regular 'def' and inherit all record values. 2904 SubClassReference SubClass = ParseSubClassReference(nullptr, false); 2905 while (true) { 2906 // Check for error. 2907 if (!SubClass.Rec) return true; 2908 2909 // Get the expanded definition prototypes and teach them about 2910 // the record values the current class to inherit has 2911 for (const auto &CurRec : NewRecDefs) { 2912 // Add it. 2913 if (AddSubClass(CurRec.get(), SubClass)) 2914 return true; 2915 } 2916 2917 if (Lex.getCode() != tgtok::comma) break; 2918 Lex.Lex(); // eat ','. 2919 SubClass = ParseSubClassReference(nullptr, false); 2920 } 2921 } 2922 2923 for (auto &CurRec : NewRecDefs) { 2924 if (ApplyLetStack(CurRec.get())) 2925 return true; 2926 2927 addDef(std::move(CurRec), DefmName); 2928 } 2929 2930 if (Lex.getCode() != tgtok::semi) 2931 return TokError("expected ';' at end of defm"); 2932 Lex.Lex(); 2933 2934 return false; 2935 } 2936 2937 /// ParseObject 2938 /// Object ::= ClassInst 2939 /// Object ::= DefInst 2940 /// Object ::= MultiClassInst 2941 /// Object ::= DefMInst 2942 /// Object ::= LETCommand '{' ObjectList '}' 2943 /// Object ::= LETCommand Object 2944 bool TGParser::ParseObject(MultiClass *MC) { 2945 switch (Lex.getCode()) { 2946 default: 2947 return TokError("Expected class, def, defm, defset, multiclass, let or " 2948 "foreach"); 2949 case tgtok::Let: return ParseTopLevelLet(MC); 2950 case tgtok::Def: return ParseDef(MC); 2951 case tgtok::Foreach: return ParseForeach(MC); 2952 case tgtok::Defm: return ParseDefm(MC); 2953 case tgtok::Defset: 2954 if (MC) 2955 return TokError("defset is not allowed inside multiclass"); 2956 return ParseDefset(); 2957 case tgtok::Class: 2958 if (MC) 2959 return TokError("class is not allowed inside multiclass"); 2960 if (!Loops.empty()) 2961 return TokError("class is not allowed inside foreach loop"); 2962 return ParseClass(); 2963 case tgtok::MultiClass: 2964 if (!Loops.empty()) 2965 return TokError("multiclass is not allowed inside foreach loop"); 2966 return ParseMultiClass(); 2967 } 2968 } 2969 2970 /// ParseObjectList 2971 /// ObjectList :== Object* 2972 bool TGParser::ParseObjectList(MultiClass *MC) { 2973 while (isObjectStart(Lex.getCode())) { 2974 if (ParseObject(MC)) 2975 return true; 2976 } 2977 return false; 2978 } 2979 2980 bool TGParser::ParseFile() { 2981 Lex.Lex(); // Prime the lexer. 2982 if (ParseObjectList()) return true; 2983 2984 // If we have unread input at the end of the file, report it. 2985 if (Lex.getCode() == tgtok::Eof) 2986 return false; 2987 2988 return TokError("Unexpected input at top level"); 2989 } 2990