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