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