1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // Implement the Parser for TableGen.
11 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/None.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/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 "llvm/TableGen/Record.h"
30 //===----------------------------------------------------------------------===//
31 // Support Code for the Semantic Actions.
32 //===----------------------------------------------------------------------===//
36 struct SubClassReference {
39 SmallVector<Init*, 4> TemplateArgs;
41 SubClassReference() : Rec(nullptr) {}
43 bool isInvalid() const { return Rec == nullptr; }
46 struct SubMultiClassReference {
49 SmallVector<Init*, 4> TemplateArgs;
51 SubMultiClassReference() : MC(nullptr) {}
53 bool isInvalid() const { return MC == nullptr; }
57 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
58 LLVM_DUMP_METHOD void SubMultiClassReference::dump() const {
59 errs() << "Multiclass:\n";
63 errs() << "Template args:\n";
64 for (Init *TA : TemplateArgs)
69 } // end namespace llvm
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()))
81 } else if (isa<VarInit>(Bit)) {
84 if (!(IsReference || Bit->isConcrete()))
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.
99 if (Init *V = RV.getValue()) {
100 bool Ok = isa<BitsInit>(V) ? checkBitsConcrete(R, RV) : V->isConcrete();
102 PrintError(R.getLoc(),
103 Twine("Initializer of '") + RV.getNameInitAsString() +
104 "' in '" + R.getNameInitAsString() +
105 "' could not be fully resolved: " +
106 RV.getValue()->getAsString());
112 /// Return an Init with a qualifier prefix referring
113 /// to CurRec's name.
114 static Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass,
115 Init *Name, StringRef Scoper) {
117 BinOpInit::getStrConcat(CurRec.getNameInit(), StringInit::get(Scoper));
118 NewName = BinOpInit::getStrConcat(NewName, Name);
119 if (CurMultiClass && Scoper != "::") {
120 Init *Prefix = BinOpInit::getStrConcat(CurMultiClass->Rec.getNameInit(),
121 StringInit::get("::"));
122 NewName = BinOpInit::getStrConcat(Prefix, NewName);
125 if (BinOpInit *BinOp = dyn_cast<BinOpInit>(NewName))
126 NewName = BinOp->Fold(&CurRec);
130 /// Return the qualified version of the implicit 'NAME' template argument.
131 static Init *QualifiedNameOfImplicitName(Record &Rec,
132 MultiClass *MC = nullptr) {
133 return QualifyName(Rec, MC, StringInit::get("NAME"), MC ? "::" : ":");
136 static Init *QualifiedNameOfImplicitName(MultiClass *MC) {
137 return QualifiedNameOfImplicitName(MC->Rec, MC);
140 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
142 CurRec = &CurMultiClass->Rec;
144 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
145 // The value already exists in the class, treat this as a set.
146 if (ERV->setValue(RV.getValue()))
147 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
148 RV.getType()->getAsString() + "' is incompatible with " +
149 "previous definition of type '" +
150 ERV->getType()->getAsString() + "'");
152 CurRec->addValue(RV);
158 /// Return true on error, false on success.
159 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
160 ArrayRef<unsigned> BitList, Init *V,
161 bool AllowSelfAssignment) {
162 if (!V) return false;
164 if (!CurRec) CurRec = &CurMultiClass->Rec;
166 RecordVal *RV = CurRec->getValue(ValName);
168 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
171 // Do not allow assignments like 'X = X'. This will just cause infinite loops
172 // in the resolution machinery.
174 if (VarInit *VI = dyn_cast<VarInit>(V))
175 if (VI->getNameInit() == ValName && !AllowSelfAssignment)
176 return Error(Loc, "Recursion / self-assignment forbidden");
178 // If we are assigning to a subset of the bits in the value... then we must be
179 // assigning to a field of BitsRecTy, which must have a BitsInit
182 if (!BitList.empty()) {
183 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
185 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
186 "' is not a bits type");
188 // Convert the incoming value to a bits type of the appropriate size...
189 Init *BI = V->getCastTo(BitsRecTy::get(BitList.size()));
191 return Error(Loc, "Initializer is not compatible with bit range");
193 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
195 // Loop over bits, assigning values as appropriate.
196 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
197 unsigned Bit = BitList[i];
199 return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" +
200 ValName->getAsUnquotedString() + "' more than once");
201 NewBits[Bit] = BI->getBit(i);
204 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
206 NewBits[i] = CurVal->getBit(i);
208 V = BitsInit::get(NewBits);
211 if (RV->setValue(V)) {
212 std::string InitType;
213 if (BitsInit *BI = dyn_cast<BitsInit>(V))
214 InitType = (Twine("' of type bit initializer with length ") +
215 Twine(BI->getNumBits())).str();
216 else if (TypedInit *TI = dyn_cast<TypedInit>(V))
217 InitType = (Twine("' of type '") + TI->getType()->getAsString()).str();
218 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
219 "' of type '" + RV->getType()->getAsString() +
220 "' is incompatible with initializer '" +
221 V->getAsString() + InitType + "'");
226 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
227 /// args as SubClass's template arguments.
228 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
229 Record *SC = SubClass.Rec;
230 // Add all of the values in the subclass into the current class.
231 for (const RecordVal &Val : SC->getValues())
232 if (AddValue(CurRec, SubClass.RefRange.Start, Val))
235 ArrayRef<Init *> TArgs = SC->getTemplateArgs();
237 // Ensure that an appropriate number of template arguments are specified.
238 if (TArgs.size() < SubClass.TemplateArgs.size())
239 return Error(SubClass.RefRange.Start,
240 "More template args specified than expected");
242 // Loop over all of the template arguments, setting them to the specified
243 // value or leaving them as the default if necessary.
244 MapResolver R(CurRec);
246 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
247 if (i < SubClass.TemplateArgs.size()) {
248 // If a value is specified for this template arg, set it now.
249 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
250 None, SubClass.TemplateArgs[i]))
252 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
253 return Error(SubClass.RefRange.Start,
254 "Value not specified for template argument #" +
255 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
256 ") of subclass '" + SC->getNameInitAsString() + "'!");
259 R.set(TArgs[i], CurRec->getValue(TArgs[i])->getValue());
261 CurRec->removeValue(TArgs[i]);
265 if (CurRec->isClass())
267 VarInit::get(QualifiedNameOfImplicitName(*CurRec), StringRecTy::get());
269 Name = CurRec->getNameInit();
270 R.set(QualifiedNameOfImplicitName(*SC), Name);
272 CurRec->resolveReferences(R);
274 // Since everything went well, we can now set the "superclass" list for the
276 ArrayRef<std::pair<Record *, SMRange>> SCs = SC->getSuperClasses();
277 for (const auto &SCPair : SCs) {
278 if (CurRec->isSubClassOf(SCPair.first))
279 return Error(SubClass.RefRange.Start,
280 "Already subclass of '" + SCPair.first->getName() + "'!\n");
281 CurRec->addSuperClass(SCPair.first, SCPair.second);
284 if (CurRec->isSubClassOf(SC))
285 return Error(SubClass.RefRange.Start,
286 "Already subclass of '" + SC->getName() + "'!\n");
287 CurRec->addSuperClass(SC, SubClass.RefRange);
291 bool TGParser::AddSubClass(RecordsEntry &Entry, SubClassReference &SubClass) {
293 return AddSubClass(Entry.Rec.get(), SubClass);
295 for (auto &E : Entry.Loop->Entries) {
296 if (AddSubClass(E, SubClass))
303 /// AddSubMultiClass - Add SubMultiClass as a subclass to
304 /// CurMC, resolving its template args as SubMultiClass's
305 /// template arguments.
306 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
307 SubMultiClassReference &SubMultiClass) {
308 MultiClass *SMC = SubMultiClass.MC;
310 ArrayRef<Init *> SMCTArgs = SMC->Rec.getTemplateArgs();
311 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
312 return Error(SubMultiClass.RefRange.Start,
313 "More template args specified than expected");
315 // Prepare the mapping of template argument name to value, filling in default
316 // values if necessary.
317 SubstStack TemplateArgs;
318 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
319 if (i < SubMultiClass.TemplateArgs.size()) {
320 TemplateArgs.emplace_back(SMCTArgs[i], SubMultiClass.TemplateArgs[i]);
322 Init *Default = SMC->Rec.getValue(SMCTArgs[i])->getValue();
323 if (!Default->isComplete()) {
324 return Error(SubMultiClass.RefRange.Start,
325 "value not specified for template argument #" + Twine(i) +
326 " (" + SMCTArgs[i]->getAsUnquotedString() +
327 ") of multiclass '" + SMC->Rec.getNameInitAsString() +
330 TemplateArgs.emplace_back(SMCTArgs[i], Default);
334 TemplateArgs.emplace_back(
335 QualifiedNameOfImplicitName(SMC),
336 VarInit::get(QualifiedNameOfImplicitName(CurMC), StringRecTy::get()));
338 // Add all of the defs in the subclass into the current multiclass.
339 return resolve(SMC->Entries, TemplateArgs, false, &CurMC->Entries);
342 /// Add a record or foreach loop to the current context (global record keeper,
343 /// current inner-most foreach loop, or multiclass).
344 bool TGParser::addEntry(RecordsEntry E) {
345 assert(!E.Rec || !E.Loop);
347 if (!Loops.empty()) {
348 Loops.back()->Entries.push_back(std::move(E));
354 return resolve(*E.Loop, Stack, CurMultiClass == nullptr,
355 CurMultiClass ? &CurMultiClass->Entries : nullptr);
359 CurMultiClass->Entries.push_back(std::move(E));
363 return addDefOne(std::move(E.Rec));
366 /// Resolve the entries in \p Loop, going over inner loops recursively
367 /// and making the given subsitutions of (name, value) pairs.
369 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
370 /// are added to the global record keeper.
371 bool TGParser::resolve(const ForeachLoop &Loop, SubstStack &Substs,
372 bool Final, std::vector<RecordsEntry> *Dest,
375 for (const auto &S : Substs)
376 R.set(S.first, S.second);
377 Init *List = Loop.ListValue->resolveReferences(R);
378 auto LI = dyn_cast<ListInit>(List);
381 Dest->emplace_back(std::make_unique<ForeachLoop>(Loop.Loc, Loop.IterVar,
383 return resolve(Loop.Entries, Substs, Final, &Dest->back().Loop->Entries,
387 PrintError(Loop.Loc, Twine("attempting to loop over '") +
388 List->getAsString() + "', expected a list");
393 for (auto Elt : *LI) {
395 Substs.emplace_back(Loop.IterVar->getNameInit(), Elt);
396 Error = resolve(Loop.Entries, Substs, Final, Dest);
405 /// Resolve the entries in \p Source, going over loops recursively and
406 /// making the given substitutions of (name, value) pairs.
408 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
409 /// are added to the global record keeper.
410 bool TGParser::resolve(const std::vector<RecordsEntry> &Source,
411 SubstStack &Substs, bool Final,
412 std::vector<RecordsEntry> *Dest, SMLoc *Loc) {
414 for (auto &E : Source) {
416 Error = resolve(*E.Loop, Substs, Final, Dest);
418 auto Rec = std::make_unique<Record>(*E.Rec);
420 Rec->appendLoc(*Loc);
422 MapResolver R(Rec.get());
423 for (const auto &S : Substs)
424 R.set(S.first, S.second);
425 Rec->resolveReferences(R);
428 Dest->push_back(std::move(Rec));
430 Error = addDefOne(std::move(Rec));
438 /// Resolve the record fully and add it to the record keeper.
439 bool TGParser::addDefOne(std::unique_ptr<Record> Rec) {
440 if (Record *Prev = Records.getDef(Rec->getNameInitAsString())) {
441 if (!Rec->isAnonymous()) {
442 PrintError(Rec->getLoc(),
443 "def already exists: " + Rec->getNameInitAsString());
444 PrintNote(Prev->getLoc(), "location of previous definition");
447 Rec->setName(Records.getNewAnonymousName());
450 Rec->resolveReferences();
453 if (!isa<StringInit>(Rec->getNameInit())) {
454 PrintError(Rec->getLoc(), Twine("record name '") +
455 Rec->getNameInit()->getAsString() +
456 "' could not be fully resolved");
460 // If ObjectBody has template arguments, it's an error.
461 assert(Rec->getTemplateArgs().empty() && "How'd this get template args?");
463 for (DefsetRecord *Defset : Defsets) {
464 DefInit *I = Rec->getDefInit();
465 if (!I->getType()->typeIsA(Defset->EltTy)) {
466 PrintError(Rec->getLoc(), Twine("adding record of incompatible type '") +
467 I->getType()->getAsString() +
469 PrintNote(Defset->Loc, "location of defset declaration");
472 Defset->Elements.push_back(I);
475 Records.addDef(std::move(Rec));
479 //===----------------------------------------------------------------------===//
481 //===----------------------------------------------------------------------===//
483 /// isObjectStart - Return true if this is a valid first token for an Object.
484 static bool isObjectStart(tgtok::TokKind K) {
485 return K == tgtok::Class || K == tgtok::Def || K == tgtok::Defm ||
486 K == tgtok::Let || K == tgtok::MultiClass || K == tgtok::Foreach ||
487 K == tgtok::Defset || K == tgtok::Defvar || K == tgtok::If;
490 /// ParseObjectName - If a valid object name is specified, return it. If no
491 /// name is specified, return the unset initializer. Return nullptr on parse
493 /// ObjectName ::= Value [ '#' Value ]*
494 /// ObjectName ::= /*empty*/
496 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
497 switch (Lex.getCode()) {
501 // These are all of the tokens that can begin an object body.
502 // Some of these can also begin values but we disallow those cases
503 // because they are unlikely to be useful.
504 return UnsetInit::get();
509 Record *CurRec = nullptr;
511 CurRec = &CurMultiClass->Rec;
513 Init *Name = ParseValue(CurRec, StringRecTy::get(), ParseNameMode);
518 Init *NameStr = QualifiedNameOfImplicitName(CurMultiClass);
519 HasReferenceResolver R(NameStr);
520 Name->resolveReferences(R);
522 Name = BinOpInit::getStrConcat(VarInit::get(NameStr, StringRecTy::get()),
529 /// ParseClassID - Parse and resolve a reference to a class name. This returns
534 Record *TGParser::ParseClassID() {
535 if (Lex.getCode() != tgtok::Id) {
536 TokError("expected name for ClassID");
540 Record *Result = Records.getClass(Lex.getCurStrVal());
542 std::string Msg("Couldn't find class '" + Lex.getCurStrVal() + "'");
543 if (MultiClasses[Lex.getCurStrVal()].get())
544 TokError(Msg + ". Use 'defm' if you meant to use multiclass '" +
545 Lex.getCurStrVal() + "'");
554 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
555 /// This returns null on error.
557 /// MultiClassID ::= ID
559 MultiClass *TGParser::ParseMultiClassID() {
560 if (Lex.getCode() != tgtok::Id) {
561 TokError("expected name for MultiClassID");
565 MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
567 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
573 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
574 /// subclass. This returns a SubClassRefTy with a null Record* on error.
576 /// SubClassRef ::= ClassID
577 /// SubClassRef ::= ClassID '<' ValueList '>'
579 SubClassReference TGParser::
580 ParseSubClassReference(Record *CurRec, bool isDefm) {
581 SubClassReference Result;
582 Result.RefRange.Start = Lex.getLoc();
585 if (MultiClass *MC = ParseMultiClassID())
586 Result.Rec = &MC->Rec;
588 Result.Rec = ParseClassID();
590 if (!Result.Rec) return Result;
592 // If there is no template arg list, we're done.
593 if (Lex.getCode() != tgtok::less) {
594 Result.RefRange.End = Lex.getLoc();
597 Lex.Lex(); // Eat the '<'
599 if (Lex.getCode() == tgtok::greater) {
600 TokError("subclass reference requires a non-empty list of template values");
601 Result.Rec = nullptr;
605 ParseValueList(Result.TemplateArgs, CurRec, Result.Rec);
606 if (Result.TemplateArgs.empty()) {
607 Result.Rec = nullptr; // Error parsing value list.
611 if (Lex.getCode() != tgtok::greater) {
612 TokError("expected '>' in template value list");
613 Result.Rec = nullptr;
617 Result.RefRange.End = Lex.getLoc();
622 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
623 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
624 /// Record* on error.
626 /// SubMultiClassRef ::= MultiClassID
627 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
629 SubMultiClassReference TGParser::
630 ParseSubMultiClassReference(MultiClass *CurMC) {
631 SubMultiClassReference Result;
632 Result.RefRange.Start = Lex.getLoc();
634 Result.MC = ParseMultiClassID();
635 if (!Result.MC) return Result;
637 // If there is no template arg list, we're done.
638 if (Lex.getCode() != tgtok::less) {
639 Result.RefRange.End = Lex.getLoc();
642 Lex.Lex(); // Eat the '<'
644 if (Lex.getCode() == tgtok::greater) {
645 TokError("subclass reference requires a non-empty list of template values");
650 ParseValueList(Result.TemplateArgs, &CurMC->Rec, &Result.MC->Rec);
651 if (Result.TemplateArgs.empty()) {
652 Result.MC = nullptr; // Error parsing value list.
656 if (Lex.getCode() != tgtok::greater) {
657 TokError("expected '>' in template value list");
662 Result.RefRange.End = Lex.getLoc();
667 /// ParseRangePiece - Parse a bit/value range.
668 /// RangePiece ::= INTVAL
669 /// RangePiece ::= INTVAL '-' INTVAL
670 /// RangePiece ::= INTVAL INTVAL
671 bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
672 TypedInit *FirstItem) {
673 Init *CurVal = FirstItem;
675 CurVal = ParseValue(nullptr);
677 IntInit *II = dyn_cast_or_null<IntInit>(CurVal);
679 return TokError("expected integer or bitrange");
681 int64_t Start = II->getValue();
685 return TokError("invalid range, cannot be negative");
687 switch (Lex.getCode()) {
689 Ranges.push_back(Start);
694 Init *I_End = ParseValue(nullptr);
695 IntInit *II_End = dyn_cast_or_null<IntInit>(I_End);
697 TokError("expected integer value as end of range");
701 End = II_End->getValue();
704 case tgtok::IntVal: {
705 End = -Lex.getCurIntVal();
711 return TokError("invalid range, cannot be negative");
715 for (; Start <= End; ++Start)
716 Ranges.push_back(Start);
718 for (; Start >= End; --Start)
719 Ranges.push_back(Start);
723 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
725 /// RangeList ::= RangePiece (',' RangePiece)*
727 void TGParser::ParseRangeList(SmallVectorImpl<unsigned> &Result) {
728 // Parse the first piece.
729 if (ParseRangePiece(Result)) {
733 while (Lex.getCode() == tgtok::comma) {
734 Lex.Lex(); // Eat the comma.
736 // Parse the next range piece.
737 if (ParseRangePiece(Result)) {
744 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
745 /// OptionalRangeList ::= '<' RangeList '>'
746 /// OptionalRangeList ::= /*empty*/
747 bool TGParser::ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges) {
748 if (Lex.getCode() != tgtok::less)
751 SMLoc StartLoc = Lex.getLoc();
752 Lex.Lex(); // eat the '<'
754 // Parse the range list.
755 ParseRangeList(Ranges);
756 if (Ranges.empty()) return true;
758 if (Lex.getCode() != tgtok::greater) {
759 TokError("expected '>' at end of range list");
760 return Error(StartLoc, "to match this '<'");
762 Lex.Lex(); // eat the '>'.
766 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
767 /// OptionalBitList ::= '{' RangeList '}'
768 /// OptionalBitList ::= /*empty*/
769 bool TGParser::ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges) {
770 if (Lex.getCode() != tgtok::l_brace)
773 SMLoc StartLoc = Lex.getLoc();
774 Lex.Lex(); // eat the '{'
776 // Parse the range list.
777 ParseRangeList(Ranges);
778 if (Ranges.empty()) return true;
780 if (Lex.getCode() != tgtok::r_brace) {
781 TokError("expected '}' at end of bit list");
782 return Error(StartLoc, "to match this '{'");
784 Lex.Lex(); // eat the '}'.
788 /// ParseType - Parse and return a tblgen type. This returns null on error.
790 /// Type ::= STRING // string type
791 /// Type ::= CODE // code type
792 /// Type ::= BIT // bit type
793 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
794 /// Type ::= INT // int type
795 /// Type ::= LIST '<' Type '>' // list<x> type
796 /// Type ::= DAG // dag type
797 /// Type ::= ClassID // Record Type
799 RecTy *TGParser::ParseType() {
800 switch (Lex.getCode()) {
801 default: TokError("Unknown token when expecting a type"); return nullptr;
802 case tgtok::String: Lex.Lex(); return StringRecTy::get();
803 case tgtok::Code: Lex.Lex(); return CodeRecTy::get();
804 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
805 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
806 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
808 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
809 TokError("unknown class name");
812 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
813 TokError("expected '<' after bits type");
816 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
817 TokError("expected integer in bits<n> type");
820 uint64_t Val = Lex.getCurIntVal();
821 if (Lex.Lex() != tgtok::greater) { // Eat count.
822 TokError("expected '>' at end of bits<n> type");
825 Lex.Lex(); // Eat '>'
826 return BitsRecTy::get(Val);
829 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
830 TokError("expected '<' after list type");
833 Lex.Lex(); // Eat '<'
834 RecTy *SubType = ParseType();
835 if (!SubType) return nullptr;
837 if (Lex.getCode() != tgtok::greater) {
838 TokError("expected '>' at end of list<ty> type");
841 Lex.Lex(); // Eat '>'
842 return ListRecTy::get(SubType);
847 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
848 /// has already been read.
849 Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMLoc NameLoc,
852 if (const RecordVal *RV = CurRec->getValue(Name))
853 return VarInit::get(Name, RV->getType());
856 if ((CurRec && CurRec->isClass()) || CurMultiClass) {
857 Init *TemplateArgName;
860 QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
862 TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
864 Record *TemplateRec = CurMultiClass ? &CurMultiClass->Rec : CurRec;
865 if (TemplateRec->isTemplateArg(TemplateArgName)) {
866 const RecordVal *RV = TemplateRec->getValue(TemplateArgName);
867 assert(RV && "Template arg doesn't exist??");
868 return VarInit::get(TemplateArgName, RV->getType());
869 } else if (Name->getValue() == "NAME") {
870 return VarInit::get(TemplateArgName, StringRecTy::get());
875 if (Init *I = CurLocalScope->getVar(Name->getValue()))
878 // If this is in a foreach loop, make sure it's not a loop iterator
879 for (const auto &L : Loops) {
881 VarInit *IterVar = dyn_cast<VarInit>(L->IterVar);
882 if (IterVar && IterVar->getNameInit() == Name)
887 if (Mode == ParseNameMode)
890 if (Init *I = Records.getGlobal(Name->getValue()))
893 // Allow self-references of concrete defs, but delay the lookup so that we
894 // get the correct type.
895 if (CurRec && !CurRec->isClass() && !CurMultiClass &&
896 CurRec->getNameInit() == Name)
897 return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType());
899 Error(NameLoc, "Variable not defined: '" + Name->getValue() + "'");
903 /// ParseOperation - Parse an operator. This returns null on error.
905 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
907 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
908 switch (Lex.getCode()) {
910 TokError("unknown operation");
917 case tgtok::XGetOp: { // Value ::= !unop '(' Value ')'
918 UnOpInit::UnaryOp Code;
919 RecTy *Type = nullptr;
921 switch (Lex.getCode()) {
922 default: llvm_unreachable("Unhandled code!");
924 Lex.Lex(); // eat the operation
925 Code = UnOpInit::CAST;
927 Type = ParseOperatorType();
930 TokError("did not get type for unary operator");
936 Lex.Lex(); // eat the operation
937 Code = UnOpInit::HEAD;
940 Lex.Lex(); // eat the operation
941 Code = UnOpInit::TAIL;
945 Code = UnOpInit::SIZE;
946 Type = IntRecTy::get();
949 Lex.Lex(); // eat the operation
950 Code = UnOpInit::EMPTY;
951 Type = IntRecTy::get();
954 Lex.Lex(); // eat the operation
955 if (Lex.getCode() == tgtok::less) {
956 // Parse an optional type suffix, so that you can say
957 // !getop<BaseClass>(someDag) as a shorthand for
958 // !cast<BaseClass>(!getop(someDag)).
959 Type = ParseOperatorType();
962 TokError("did not get type for unary operator");
966 if (!isa<RecordRecTy>(Type)) {
967 TokError("type for !getop must be a record type");
968 // but keep parsing, to consume the operand
971 Type = RecordRecTy::get({});
973 Code = UnOpInit::GETOP;
976 if (Lex.getCode() != tgtok::l_paren) {
977 TokError("expected '(' after unary operator");
980 Lex.Lex(); // eat the '('
982 Init *LHS = ParseValue(CurRec);
983 if (!LHS) return nullptr;
985 if (Code == UnOpInit::HEAD ||
986 Code == UnOpInit::TAIL ||
987 Code == UnOpInit::EMPTY) {
988 ListInit *LHSl = dyn_cast<ListInit>(LHS);
989 StringInit *LHSs = dyn_cast<StringInit>(LHS);
990 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
991 if (!LHSl && !LHSs && !LHSt) {
992 TokError("expected list or string type argument in unary operator");
996 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
997 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
998 if (!LType && !SType) {
999 TokError("expected list or string type argument in unary operator");
1004 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL ||
1005 Code == UnOpInit::SIZE) {
1006 if (!LHSl && !LHSt) {
1007 TokError("expected list type argument in unary operator");
1012 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
1013 if (LHSl && LHSl->empty()) {
1014 TokError("empty list argument in unary operator");
1018 Init *Item = LHSl->getElement(0);
1019 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
1021 TokError("untyped list element in unary operator");
1024 Type = (Code == UnOpInit::HEAD) ? Itemt->getType()
1025 : ListRecTy::get(Itemt->getType());
1027 assert(LHSt && "expected list type argument in unary operator");
1028 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1030 TokError("expected list type argument in unary operator");
1033 Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType;
1038 if (Lex.getCode() != tgtok::r_paren) {
1039 TokError("expected ')' in unary operator");
1042 Lex.Lex(); // eat the ')'
1043 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec);
1047 // Value ::= !isa '<' Type '>' '(' Value ')'
1048 Lex.Lex(); // eat the operation
1050 RecTy *Type = ParseOperatorType();
1054 if (Lex.getCode() != tgtok::l_paren) {
1055 TokError("expected '(' after type of !isa");
1058 Lex.Lex(); // eat the '('
1060 Init *LHS = ParseValue(CurRec);
1064 if (Lex.getCode() != tgtok::r_paren) {
1065 TokError("expected ')' in !isa");
1068 Lex.Lex(); // eat the ')'
1070 return (IsAOpInit::get(Type, LHS))->Fold();
1073 case tgtok::XConcat:
1087 case tgtok::XListConcat:
1088 case tgtok::XListSplat:
1089 case tgtok::XStrConcat:
1090 case tgtok::XSetOp: { // Value ::= !binop '(' Value ',' Value ')'
1091 tgtok::TokKind OpTok = Lex.getCode();
1092 SMLoc OpLoc = Lex.getLoc();
1093 Lex.Lex(); // eat the operation
1095 BinOpInit::BinaryOp Code;
1097 default: llvm_unreachable("Unhandled code!");
1098 case tgtok::XConcat: Code = BinOpInit::CONCAT; break;
1099 case tgtok::XADD: Code = BinOpInit::ADD; break;
1100 case tgtok::XMUL: Code = BinOpInit::MUL; break;
1101 case tgtok::XAND: Code = BinOpInit::AND; break;
1102 case tgtok::XOR: Code = BinOpInit::OR; break;
1103 case tgtok::XSRA: Code = BinOpInit::SRA; break;
1104 case tgtok::XSRL: Code = BinOpInit::SRL; break;
1105 case tgtok::XSHL: Code = BinOpInit::SHL; break;
1106 case tgtok::XEq: Code = BinOpInit::EQ; break;
1107 case tgtok::XNe: Code = BinOpInit::NE; break;
1108 case tgtok::XLe: Code = BinOpInit::LE; break;
1109 case tgtok::XLt: Code = BinOpInit::LT; break;
1110 case tgtok::XGe: Code = BinOpInit::GE; break;
1111 case tgtok::XGt: Code = BinOpInit::GT; break;
1112 case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break;
1113 case tgtok::XListSplat: Code = BinOpInit::LISTSPLAT; break;
1114 case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break;
1115 case tgtok::XSetOp: Code = BinOpInit::SETOP; break;
1118 RecTy *Type = nullptr;
1119 RecTy *ArgType = nullptr;
1122 llvm_unreachable("Unhandled code!");
1123 case tgtok::XConcat:
1125 Type = DagRecTy::get();
1126 ArgType = DagRecTy::get();
1135 Type = IntRecTy::get();
1136 ArgType = IntRecTy::get();
1140 Type = BitRecTy::get();
1141 // ArgType for Eq / Ne is not known at this point
1147 Type = BitRecTy::get();
1148 ArgType = IntRecTy::get();
1150 case tgtok::XListConcat:
1151 // We don't know the list type until we parse the first argument
1154 case tgtok::XListSplat:
1155 // Can't do any typechecking until we parse the first argument.
1157 case tgtok::XStrConcat:
1158 Type = StringRecTy::get();
1159 ArgType = StringRecTy::get();
1163 if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) {
1164 Error(OpLoc, Twine("expected value of type '") +
1165 ItemType->getAsString() + "', got '" +
1166 Type->getAsString() + "'");
1170 if (Lex.getCode() != tgtok::l_paren) {
1171 TokError("expected '(' after binary operator");
1174 Lex.Lex(); // eat the '('
1176 SmallVector<Init*, 2> InitList;
1179 SMLoc InitLoc = Lex.getLoc();
1180 InitList.push_back(ParseValue(CurRec, ArgType));
1181 if (!InitList.back()) return nullptr;
1183 RecTy *ListType = cast<TypedInit>(InitList.back())->getType();
1188 case BinOpInit::LISTCONCAT:
1189 if (!isa<ListRecTy>(ArgType)) {
1190 Error(InitLoc, Twine("expected a list, got value of type '") +
1191 ArgType->getAsString() + "'");
1195 case BinOpInit::LISTSPLAT:
1196 if (ItemType && InitList.size() == 1) {
1197 if (!isa<ListRecTy>(ItemType)) {
1199 Twine("expected output type to be a list, got type '") +
1200 ItemType->getAsString() + "'");
1203 if (!ArgType->getListTy()->typeIsConvertibleTo(ItemType)) {
1204 Error(OpLoc, Twine("expected first arg type to be '") +
1205 ArgType->getAsString() +
1206 "', got value of type '" +
1207 cast<ListRecTy>(ItemType)
1214 if (InitList.size() == 2 && !isa<IntRecTy>(ArgType)) {
1215 Error(InitLoc, Twine("expected second parameter to be an int, got "
1216 "value of type '") +
1217 ArgType->getAsString() + "'");
1220 ArgType = nullptr; // Broken invariant: types not identical.
1224 if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) &&
1225 !ArgType->typeIsConvertibleTo(StringRecTy::get())) {
1226 Error(InitLoc, Twine("expected int, bits, or string; got value of "
1227 "type '") + ArgType->getAsString() + "'");
1231 default: llvm_unreachable("other ops have fixed argument types");
1234 RecTy *Resolved = resolveTypes(ArgType, ListType);
1236 Error(InitLoc, Twine("expected value of type '") +
1237 ArgType->getAsString() + "', got '" +
1238 ListType->getAsString() + "'");
1241 if (Code != BinOpInit::ADD && Code != BinOpInit::AND &&
1242 Code != BinOpInit::OR && Code != BinOpInit::SRA &&
1243 Code != BinOpInit::SRL && Code != BinOpInit::SHL &&
1244 Code != BinOpInit::MUL)
1248 // Deal with BinOps whose arguments have different types, by
1249 // rewriting ArgType in between them.
1251 case BinOpInit::SETOP:
1252 // After parsing the first dag argument, switch to expecting
1253 // a record, with no restriction on its superclasses.
1254 ArgType = RecordRecTy::get({});
1260 if (Lex.getCode() != tgtok::comma)
1262 Lex.Lex(); // eat the ','
1265 if (Lex.getCode() != tgtok::r_paren) {
1266 TokError("expected ')' in operator");
1269 Lex.Lex(); // eat the ')'
1271 // listconcat returns a list with type of the argument.
1272 if (Code == BinOpInit::LISTCONCAT)
1274 // listsplat returns a list of type of the *first* argument.
1275 if (Code == BinOpInit::LISTSPLAT)
1276 Type = cast<TypedInit>(InitList.front())->getType()->getListTy();
1278 // We allow multiple operands to associative operators like !strconcat as
1279 // shorthand for nesting them.
1280 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT ||
1281 Code == BinOpInit::CONCAT || Code == BinOpInit::ADD ||
1282 Code == BinOpInit::AND || Code == BinOpInit::OR ||
1283 Code == BinOpInit::MUL) {
1284 while (InitList.size() > 2) {
1285 Init *RHS = InitList.pop_back_val();
1286 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec);
1287 InitList.back() = RHS;
1291 if (InitList.size() == 2)
1292 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
1295 Error(OpLoc, "expected two operands to operator");
1299 case tgtok::XForEach: { // Value ::= !foreach '(' Id ',' Value ',' Value ')'
1300 SMLoc OpLoc = Lex.getLoc();
1301 Lex.Lex(); // eat the operation
1302 if (Lex.getCode() != tgtok::l_paren) {
1303 TokError("expected '(' after !foreach");
1307 if (Lex.Lex() != tgtok::Id) { // eat the '('
1308 TokError("first argument of !foreach must be an identifier");
1312 Init *LHS = StringInit::get(Lex.getCurStrVal());
1314 if (CurRec && CurRec->getValue(LHS)) {
1315 TokError((Twine("iteration variable '") + LHS->getAsString() +
1316 "' already defined")
1321 if (Lex.Lex() != tgtok::comma) { // eat the id
1322 TokError("expected ',' in ternary operator");
1325 Lex.Lex(); // eat the ','
1327 Init *MHS = ParseValue(CurRec);
1331 if (Lex.getCode() != tgtok::comma) {
1332 TokError("expected ',' in ternary operator");
1335 Lex.Lex(); // eat the ','
1337 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1339 TokError("could not get type of !foreach input");
1343 RecTy *InEltType = nullptr;
1344 RecTy *OutEltType = nullptr;
1347 if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) {
1348 InEltType = InListTy->getElementType();
1350 if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) {
1351 OutEltType = OutListTy->getElementType();
1354 "expected value of type '" + Twine(ItemType->getAsString()) +
1355 "', but got !foreach of list type");
1359 } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) {
1360 InEltType = InDagTy;
1361 if (ItemType && !isa<DagRecTy>(ItemType)) {
1363 "expected value of type '" + Twine(ItemType->getAsString()) +
1364 "', but got !foreach of dag type");
1369 TokError("!foreach must have list or dag input");
1373 // We need to create a temporary record to provide a scope for the iteration
1374 // variable while parsing top-level foreach's.
1375 std::unique_ptr<Record> ParseRecTmp;
1376 Record *ParseRec = CurRec;
1378 ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1379 ParseRec = ParseRecTmp.get();
1382 ParseRec->addValue(RecordVal(LHS, InEltType, false));
1383 Init *RHS = ParseValue(ParseRec, OutEltType);
1384 ParseRec->removeValue(LHS);
1388 if (Lex.getCode() != tgtok::r_paren) {
1389 TokError("expected ')' in binary operator");
1392 Lex.Lex(); // eat the ')'
1396 OutType = InEltType;
1398 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1400 TokError("could not get type of !foreach result");
1403 OutType = RHSt->getType()->getListTy();
1406 return (TernOpInit::get(TernOpInit::FOREACH, LHS, MHS, RHS, OutType))
1412 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1413 TernOpInit::TernaryOp Code;
1414 RecTy *Type = nullptr;
1416 tgtok::TokKind LexCode = Lex.getCode();
1417 Lex.Lex(); // eat the operation
1419 default: llvm_unreachable("Unhandled code!");
1421 Code = TernOpInit::DAG;
1422 Type = DagRecTy::get();
1426 Code = TernOpInit::IF;
1429 Code = TernOpInit::SUBST;
1432 if (Lex.getCode() != tgtok::l_paren) {
1433 TokError("expected '(' after ternary operator");
1436 Lex.Lex(); // eat the '('
1438 Init *LHS = ParseValue(CurRec);
1439 if (!LHS) return nullptr;
1441 if (Lex.getCode() != tgtok::comma) {
1442 TokError("expected ',' in ternary operator");
1445 Lex.Lex(); // eat the ','
1447 SMLoc MHSLoc = Lex.getLoc();
1448 Init *MHS = ParseValue(CurRec, ItemType);
1452 if (Lex.getCode() != tgtok::comma) {
1453 TokError("expected ',' in ternary operator");
1456 Lex.Lex(); // eat the ','
1458 SMLoc RHSLoc = Lex.getLoc();
1459 Init *RHS = ParseValue(CurRec, ItemType);
1463 if (Lex.getCode() != tgtok::r_paren) {
1464 TokError("expected ')' in binary operator");
1467 Lex.Lex(); // eat the ')'
1470 default: llvm_unreachable("Unhandled code!");
1472 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1473 if (!MHSt && !isa<UnsetInit>(MHS)) {
1474 Error(MHSLoc, "could not determine type of the child list in !dag");
1477 if (MHSt && !isa<ListRecTy>(MHSt->getType())) {
1478 Error(MHSLoc, Twine("expected list of children, got type '") +
1479 MHSt->getType()->getAsString() + "'");
1483 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1484 if (!RHSt && !isa<UnsetInit>(RHS)) {
1485 Error(RHSLoc, "could not determine type of the name list in !dag");
1488 if (RHSt && StringRecTy::get()->getListTy() != RHSt->getType()) {
1489 Error(RHSLoc, Twine("expected list<string>, got type '") +
1490 RHSt->getType()->getAsString() + "'");
1494 if (!MHSt && !RHSt) {
1496 "cannot have both unset children and unset names in !dag");
1502 RecTy *MHSTy = nullptr;
1503 RecTy *RHSTy = nullptr;
1505 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1506 MHSTy = MHSt->getType();
1507 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1508 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1509 if (isa<BitInit>(MHS))
1510 MHSTy = BitRecTy::get();
1512 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1513 RHSTy = RHSt->getType();
1514 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1515 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1516 if (isa<BitInit>(RHS))
1517 RHSTy = BitRecTy::get();
1519 // For UnsetInit, it's typed from the other hand.
1520 if (isa<UnsetInit>(MHS))
1522 if (isa<UnsetInit>(RHS))
1525 if (!MHSTy || !RHSTy) {
1526 TokError("could not get type for !if");
1530 Type = resolveTypes(MHSTy, RHSTy);
1532 TokError(Twine("inconsistent types '") + MHSTy->getAsString() +
1533 "' and '" + RHSTy->getAsString() + "' for !if");
1538 case tgtok::XSubst: {
1539 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1541 TokError("could not get type for !subst");
1544 Type = RHSt->getType();
1548 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
1552 return ParseOperationCond(CurRec, ItemType);
1554 case tgtok::XFoldl: {
1555 // Value ::= !foldl '(' Id ',' Id ',' Value ',' Value ',' Value ')'
1556 Lex.Lex(); // eat the operation
1557 if (Lex.getCode() != tgtok::l_paren) {
1558 TokError("expected '(' after !foldl");
1561 Lex.Lex(); // eat the '('
1563 Init *StartUntyped = ParseValue(CurRec);
1567 TypedInit *Start = dyn_cast<TypedInit>(StartUntyped);
1569 TokError(Twine("could not get type of !foldl start: '") +
1570 StartUntyped->getAsString() + "'");
1574 if (Lex.getCode() != tgtok::comma) {
1575 TokError("expected ',' in !foldl");
1578 Lex.Lex(); // eat the ','
1580 Init *ListUntyped = ParseValue(CurRec);
1584 TypedInit *List = dyn_cast<TypedInit>(ListUntyped);
1586 TokError(Twine("could not get type of !foldl list: '") +
1587 ListUntyped->getAsString() + "'");
1591 ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType());
1593 TokError(Twine("!foldl list must be a list, but is of type '") +
1594 List->getType()->getAsString());
1598 if (Lex.getCode() != tgtok::comma) {
1599 TokError("expected ',' in !foldl");
1603 if (Lex.Lex() != tgtok::Id) { // eat the ','
1604 TokError("third argument of !foldl must be an identifier");
1608 Init *A = StringInit::get(Lex.getCurStrVal());
1609 if (CurRec && CurRec->getValue(A)) {
1610 TokError((Twine("left !foldl variable '") + A->getAsString() +
1611 "' already defined")
1616 if (Lex.Lex() != tgtok::comma) { // eat the id
1617 TokError("expected ',' in !foldl");
1621 if (Lex.Lex() != tgtok::Id) { // eat the ','
1622 TokError("fourth argument of !foldl must be an identifier");
1626 Init *B = StringInit::get(Lex.getCurStrVal());
1627 if (CurRec && CurRec->getValue(B)) {
1628 TokError((Twine("right !foldl variable '") + B->getAsString() +
1629 "' already defined")
1634 if (Lex.Lex() != tgtok::comma) { // eat the id
1635 TokError("expected ',' in !foldl");
1638 Lex.Lex(); // eat the ','
1640 // We need to create a temporary record to provide a scope for the iteration
1641 // variable while parsing top-level foreach's.
1642 std::unique_ptr<Record> ParseRecTmp;
1643 Record *ParseRec = CurRec;
1645 ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1646 ParseRec = ParseRecTmp.get();
1649 ParseRec->addValue(RecordVal(A, Start->getType(), false));
1650 ParseRec->addValue(RecordVal(B, ListType->getElementType(), false));
1651 Init *ExprUntyped = ParseValue(ParseRec);
1652 ParseRec->removeValue(A);
1653 ParseRec->removeValue(B);
1657 TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped);
1659 TokError("could not get type of !foldl expression");
1663 if (Expr->getType() != Start->getType()) {
1664 TokError(Twine("!foldl expression must be of same type as start (") +
1665 Start->getType()->getAsString() + "), but is of type " +
1666 Expr->getType()->getAsString());
1670 if (Lex.getCode() != tgtok::r_paren) {
1671 TokError("expected ')' in fold operator");
1674 Lex.Lex(); // eat the ')'
1676 return FoldOpInit::get(Start, List, A, B, Expr, Start->getType())
1682 /// ParseOperatorType - Parse a type for an operator. This returns
1685 /// OperatorType ::= '<' Type '>'
1687 RecTy *TGParser::ParseOperatorType() {
1688 RecTy *Type = nullptr;
1690 if (Lex.getCode() != tgtok::less) {
1691 TokError("expected type name for operator");
1694 Lex.Lex(); // eat the <
1699 TokError("expected type name for operator");
1703 if (Lex.getCode() != tgtok::greater) {
1704 TokError("expected type name for operator");
1707 Lex.Lex(); // eat the >
1712 Init *TGParser::ParseOperationCond(Record *CurRec, RecTy *ItemType) {
1713 Lex.Lex(); // eat the operation 'cond'
1715 if (Lex.getCode() != tgtok::l_paren) {
1716 TokError("expected '(' after !cond operator");
1719 Lex.Lex(); // eat the '('
1721 // Parse through '[Case: Val,]+'
1722 SmallVector<Init *, 4> Case;
1723 SmallVector<Init *, 4> Val;
1725 if (Lex.getCode() == tgtok::r_paren) {
1726 Lex.Lex(); // eat the ')'
1730 Init *V = ParseValue(CurRec);
1735 if (Lex.getCode() != tgtok::colon) {
1736 TokError("expected ':' following a condition in !cond operator");
1739 Lex.Lex(); // eat the ':'
1741 V = ParseValue(CurRec, ItemType);
1746 if (Lex.getCode() == tgtok::r_paren) {
1747 Lex.Lex(); // eat the ')'
1751 if (Lex.getCode() != tgtok::comma) {
1752 TokError("expected ',' or ')' following a value in !cond operator");
1755 Lex.Lex(); // eat the ','
1758 if (Case.size() < 1) {
1759 TokError("there should be at least 1 'condition : value' in the !cond operator");
1764 RecTy *Type = nullptr;
1765 for (Init *V : Val) {
1766 RecTy *VTy = nullptr;
1767 if (TypedInit *Vt = dyn_cast<TypedInit>(V))
1768 VTy = Vt->getType();
1769 if (BitsInit *Vbits = dyn_cast<BitsInit>(V))
1770 VTy = BitsRecTy::get(Vbits->getNumBits());
1771 if (isa<BitInit>(V))
1772 VTy = BitRecTy::get();
1774 if (Type == nullptr) {
1775 if (!isa<UnsetInit>(V))
1778 if (!isa<UnsetInit>(V)) {
1779 RecTy *RType = resolveTypes(Type, VTy);
1781 TokError(Twine("inconsistent types '") + Type->getAsString() +
1782 "' and '" + VTy->getAsString() + "' for !cond");
1791 TokError("could not determine type for !cond from its arguments");
1794 return CondOpInit::get(Case, Val, Type)->Fold(CurRec);
1797 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1799 /// SimpleValue ::= IDValue
1800 /// SimpleValue ::= INTVAL
1801 /// SimpleValue ::= STRVAL+
1802 /// SimpleValue ::= CODEFRAGMENT
1803 /// SimpleValue ::= '?'
1804 /// SimpleValue ::= '{' ValueList '}'
1805 /// SimpleValue ::= ID '<' ValueListNE '>'
1806 /// SimpleValue ::= '[' ValueList ']'
1807 /// SimpleValue ::= '(' IDValue DagArgList ')'
1808 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1809 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1810 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1811 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1812 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1813 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1814 /// SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')'
1815 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1816 /// SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
1818 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1821 switch (Lex.getCode()) {
1822 default: TokError("Unknown token when parsing a value"); break;
1824 // This is a leading paste operation. This is deprecated but
1825 // still exists in some .td files. Ignore it.
1826 Lex.Lex(); // Skip '#'.
1827 return ParseSimpleValue(CurRec, ItemType, Mode);
1828 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1829 case tgtok::BinaryIntVal: {
1830 auto BinaryVal = Lex.getCurBinaryIntVal();
1831 SmallVector<Init*, 16> Bits(BinaryVal.second);
1832 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
1833 Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
1834 R = BitsInit::get(Bits);
1838 case tgtok::StrVal: {
1839 std::string Val = Lex.getCurStrVal();
1842 // Handle multiple consecutive concatenated strings.
1843 while (Lex.getCode() == tgtok::StrVal) {
1844 Val += Lex.getCurStrVal();
1848 R = StringInit::get(Val);
1851 case tgtok::CodeFragment:
1852 R = CodeInit::get(Lex.getCurStrVal(), Lex.getLoc());
1855 case tgtok::question:
1856 R = UnsetInit::get();
1860 SMLoc NameLoc = Lex.getLoc();
1861 StringInit *Name = StringInit::get(Lex.getCurStrVal());
1862 if (Lex.Lex() != tgtok::less) // consume the Id.
1863 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1865 // Value ::= ID '<' ValueListNE '>'
1866 if (Lex.Lex() == tgtok::greater) {
1867 TokError("expected non-empty value list");
1871 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1872 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1874 Record *Class = Records.getClass(Name->getValue());
1876 Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'");
1880 SmallVector<Init *, 8> Args;
1881 ParseValueList(Args, CurRec, Class);
1882 if (Args.empty()) return nullptr;
1884 if (Lex.getCode() != tgtok::greater) {
1885 TokError("expected '>' at end of value list");
1888 Lex.Lex(); // eat the '>'
1890 // Typecheck the template arguments list
1891 ArrayRef<Init *> ExpectedArgs = Class->getTemplateArgs();
1892 if (ExpectedArgs.size() < Args.size()) {
1894 "More template args specified than expected");
1898 for (unsigned i = 0, e = ExpectedArgs.size(); i != e; ++i) {
1899 RecordVal *ExpectedArg = Class->getValue(ExpectedArgs[i]);
1900 if (i < Args.size()) {
1901 if (TypedInit *TI = dyn_cast<TypedInit>(Args[i])) {
1902 RecTy *ExpectedType = ExpectedArg->getType();
1903 if (!TI->getType()->typeIsConvertibleTo(ExpectedType)) {
1905 "Value specified for template argument #" + Twine(i) + " (" +
1906 ExpectedArg->getNameInitAsString() + ") is of type '" +
1907 TI->getType()->getAsString() + "', expected '" +
1908 ExpectedType->getAsString() + "': " + TI->getAsString());
1913 } else if (ExpectedArg->getValue()->isComplete())
1917 "Value not specified for template argument #" + Twine(i) + " (" +
1918 ExpectedArgs[i]->getAsUnquotedString() + ")");
1922 return VarDefInit::get(Class, Args)->Fold();
1924 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1925 SMLoc BraceLoc = Lex.getLoc();
1926 Lex.Lex(); // eat the '{'
1927 SmallVector<Init*, 16> Vals;
1929 if (Lex.getCode() != tgtok::r_brace) {
1930 ParseValueList(Vals, CurRec);
1931 if (Vals.empty()) return nullptr;
1933 if (Lex.getCode() != tgtok::r_brace) {
1934 TokError("expected '}' at end of bit list value");
1937 Lex.Lex(); // eat the '}'
1939 SmallVector<Init *, 16> NewBits;
1941 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1942 // first. We'll first read everything in to a vector, then we can reverse
1943 // it to get the bits in the correct order for the BitsInit value.
1944 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1945 // FIXME: The following two loops would not be duplicated
1946 // if the API was a little more orthogonal.
1948 // bits<n> values are allowed to initialize n bits.
1949 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
1950 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
1951 NewBits.push_back(BI->getBit((e - i) - 1));
1954 // bits<n> can also come from variable initializers.
1955 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
1956 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
1957 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
1958 NewBits.push_back(VI->getBit((e - i) - 1));
1961 // Fallthrough to try convert this to a bit.
1963 // All other values must be convertible to just a single bit.
1964 Init *Bit = Vals[i]->getCastTo(BitRecTy::get());
1966 Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
1967 ") is not convertable to a bit");
1970 NewBits.push_back(Bit);
1972 std::reverse(NewBits.begin(), NewBits.end());
1973 return BitsInit::get(NewBits);
1975 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1976 Lex.Lex(); // eat the '['
1977 SmallVector<Init*, 16> Vals;
1979 RecTy *DeducedEltTy = nullptr;
1980 ListRecTy *GivenListTy = nullptr;
1983 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1985 TokError(Twine("Type mismatch for list, expected list type, got ") +
1986 ItemType->getAsString());
1989 GivenListTy = ListType;
1992 if (Lex.getCode() != tgtok::r_square) {
1993 ParseValueList(Vals, CurRec, nullptr,
1994 GivenListTy ? GivenListTy->getElementType() : nullptr);
1995 if (Vals.empty()) return nullptr;
1997 if (Lex.getCode() != tgtok::r_square) {
1998 TokError("expected ']' at end of list value");
2001 Lex.Lex(); // eat the ']'
2003 RecTy *GivenEltTy = nullptr;
2004 if (Lex.getCode() == tgtok::less) {
2005 // Optional list element type
2006 Lex.Lex(); // eat the '<'
2008 GivenEltTy = ParseType();
2010 // Couldn't parse element type
2014 if (Lex.getCode() != tgtok::greater) {
2015 TokError("expected '>' at end of list element type");
2018 Lex.Lex(); // eat the '>'
2022 RecTy *EltTy = nullptr;
2023 for (Init *V : Vals) {
2024 TypedInit *TArg = dyn_cast<TypedInit>(V);
2027 EltTy = resolveTypes(EltTy, TArg->getType());
2029 TokError("Incompatible types in list elements");
2033 EltTy = TArg->getType();
2040 // Verify consistency
2041 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
2042 TokError("Incompatible types in list elements");
2051 TokError("No type for list");
2054 DeducedEltTy = GivenListTy->getElementType();
2056 // Make sure the deduced type is compatible with the given type
2058 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
2059 TokError(Twine("Element type mismatch for list: element type '") +
2060 EltTy->getAsString() + "' not convertible to '" +
2061 GivenListTy->getElementType()->getAsString());
2065 DeducedEltTy = EltTy;
2068 return ListInit::get(Vals, DeducedEltTy);
2070 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
2071 Lex.Lex(); // eat the '('
2072 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast &&
2073 Lex.getCode() != tgtok::question && Lex.getCode() != tgtok::XGetOp) {
2074 TokError("expected identifier in dag init");
2078 Init *Operator = ParseValue(CurRec);
2079 if (!Operator) return nullptr;
2081 // If the operator name is present, parse it.
2082 StringInit *OperatorName = nullptr;
2083 if (Lex.getCode() == tgtok::colon) {
2084 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
2085 TokError("expected variable name in dag operator");
2088 OperatorName = StringInit::get(Lex.getCurStrVal());
2089 Lex.Lex(); // eat the VarName.
2092 SmallVector<std::pair<llvm::Init*, StringInit*>, 8> DagArgs;
2093 if (Lex.getCode() != tgtok::r_paren) {
2094 ParseDagArgList(DagArgs, CurRec);
2095 if (DagArgs.empty()) return nullptr;
2098 if (Lex.getCode() != tgtok::r_paren) {
2099 TokError("expected ')' in dag init");
2102 Lex.Lex(); // eat the ')'
2104 return DagInit::get(Operator, OperatorName, DagArgs);
2112 case tgtok::XGetOp: // Value ::= !unop '(' Value ')'
2114 case tgtok::XConcat:
2129 case tgtok::XListConcat:
2130 case tgtok::XListSplat:
2131 case tgtok::XStrConcat:
2132 case tgtok::XSetOp: // Value ::= !binop '(' Value ',' Value ')'
2136 case tgtok::XForEach:
2137 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
2138 return ParseOperation(CurRec, ItemType);
2145 /// ParseValue - Parse a tblgen value. This returns null on error.
2147 /// Value ::= SimpleValue ValueSuffix*
2148 /// ValueSuffix ::= '{' BitList '}'
2149 /// ValueSuffix ::= '[' BitList ']'
2150 /// ValueSuffix ::= '.' ID
2152 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
2153 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
2154 if (!Result) return nullptr;
2156 // Parse the suffixes now if present.
2158 switch (Lex.getCode()) {
2159 default: return Result;
2160 case tgtok::l_brace: {
2161 if (Mode == ParseNameMode)
2162 // This is the beginning of the object body.
2165 SMLoc CurlyLoc = Lex.getLoc();
2166 Lex.Lex(); // eat the '{'
2167 SmallVector<unsigned, 16> Ranges;
2168 ParseRangeList(Ranges);
2169 if (Ranges.empty()) return nullptr;
2171 // Reverse the bitlist.
2172 std::reverse(Ranges.begin(), Ranges.end());
2173 Result = Result->convertInitializerBitRange(Ranges);
2175 Error(CurlyLoc, "Invalid bit range for value");
2180 if (Lex.getCode() != tgtok::r_brace) {
2181 TokError("expected '}' at end of bit range list");
2187 case tgtok::l_square: {
2188 SMLoc SquareLoc = Lex.getLoc();
2189 Lex.Lex(); // eat the '['
2190 SmallVector<unsigned, 16> Ranges;
2191 ParseRangeList(Ranges);
2192 if (Ranges.empty()) return nullptr;
2194 Result = Result->convertInitListSlice(Ranges);
2196 Error(SquareLoc, "Invalid range for list slice");
2201 if (Lex.getCode() != tgtok::r_square) {
2202 TokError("expected ']' at end of list slice");
2208 case tgtok::period: {
2209 if (Lex.Lex() != tgtok::Id) { // eat the .
2210 TokError("expected field identifier after '.'");
2213 StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2214 if (!Result->getFieldType(FieldName)) {
2215 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
2216 Result->getAsString() + "'");
2219 Result = FieldInit::get(Result, FieldName)->Fold(CurRec);
2220 Lex.Lex(); // eat field name
2225 SMLoc PasteLoc = Lex.getLoc();
2226 TypedInit *LHS = dyn_cast<TypedInit>(Result);
2228 Error(PasteLoc, "LHS of paste is not typed!");
2232 // Check if it's a 'listA # listB'
2233 if (isa<ListRecTy>(LHS->getType())) {
2234 Lex.Lex(); // Eat the '#'.
2236 switch (Lex.getCode()) {
2239 case tgtok::l_brace:
2240 Result = LHS; // trailing paste, ignore.
2243 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
2244 Result = BinOpInit::getListConcat(LHS, RHSResult);
2249 // Create a !strconcat() operation, first casting each operand to
2250 // a string if necessary.
2251 if (LHS->getType() != StringRecTy::get()) {
2252 auto CastLHS = dyn_cast<TypedInit>(
2253 UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get())
2257 Twine("can't cast '") + LHS->getAsString() + "' to string");
2263 TypedInit *RHS = nullptr;
2265 Lex.Lex(); // Eat the '#'.
2266 switch (Lex.getCode()) {
2269 case tgtok::l_brace:
2270 // These are all of the tokens that can begin an object body.
2271 // Some of these can also begin values but we disallow those cases
2272 // because they are unlikely to be useful.
2274 // Trailing paste, concat with an empty string.
2275 RHS = StringInit::get("");
2279 Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode);
2280 RHS = dyn_cast<TypedInit>(RHSResult);
2282 Error(PasteLoc, "RHS of paste is not typed!");
2286 if (RHS->getType() != StringRecTy::get()) {
2287 auto CastRHS = dyn_cast<TypedInit>(
2288 UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get())
2292 Twine("can't cast '") + RHS->getAsString() + "' to string");
2301 Result = BinOpInit::getStrConcat(LHS, RHS);
2307 /// ParseDagArgList - Parse the argument list for a dag literal expression.
2309 /// DagArg ::= Value (':' VARNAME)?
2310 /// DagArg ::= VARNAME
2311 /// DagArgList ::= DagArg
2312 /// DagArgList ::= DagArgList ',' DagArg
2313 void TGParser::ParseDagArgList(
2314 SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result,
2318 // DagArg ::= VARNAME
2319 if (Lex.getCode() == tgtok::VarName) {
2320 // A missing value is treated like '?'.
2321 StringInit *VarName = StringInit::get(Lex.getCurStrVal());
2322 Result.emplace_back(UnsetInit::get(), VarName);
2325 // DagArg ::= Value (':' VARNAME)?
2326 Init *Val = ParseValue(CurRec);
2332 // If the variable name is present, add it.
2333 StringInit *VarName = nullptr;
2334 if (Lex.getCode() == tgtok::colon) {
2335 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
2336 TokError("expected variable name in dag literal");
2340 VarName = StringInit::get(Lex.getCurStrVal());
2341 Lex.Lex(); // eat the VarName.
2344 Result.push_back(std::make_pair(Val, VarName));
2346 if (Lex.getCode() != tgtok::comma) break;
2347 Lex.Lex(); // eat the ','
2351 /// ParseValueList - Parse a comma separated list of values, returning them as a
2352 /// vector. Note that this always expects to be able to parse at least one
2353 /// value. It returns an empty list if this is not possible.
2355 /// ValueList ::= Value (',' Value)
2357 void TGParser::ParseValueList(SmallVectorImpl<Init*> &Result, Record *CurRec,
2358 Record *ArgsRec, RecTy *EltTy) {
2359 RecTy *ItemType = EltTy;
2360 unsigned int ArgN = 0;
2361 if (ArgsRec && !EltTy) {
2362 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2363 if (TArgs.empty()) {
2364 TokError("template argument provided to non-template class");
2368 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2370 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
2373 assert(RV && "Template argument record not found??");
2374 ItemType = RV->getType();
2377 Result.push_back(ParseValue(CurRec, ItemType));
2378 if (!Result.back()) {
2383 while (Lex.getCode() == tgtok::comma) {
2384 Lex.Lex(); // Eat the comma
2386 // ignore trailing comma for lists
2387 if (Lex.getCode() == tgtok::r_square)
2390 if (ArgsRec && !EltTy) {
2391 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2392 if (ArgN >= TArgs.size()) {
2393 TokError("too many template arguments");
2397 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2398 assert(RV && "Template argument record not found??");
2399 ItemType = RV->getType();
2402 Result.push_back(ParseValue(CurRec, ItemType));
2403 if (!Result.back()) {
2410 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
2411 /// empty string on error. This can happen in a number of different context's,
2412 /// including within a def or in the template args for a def (which which case
2413 /// CurRec will be non-null) and within the template args for a multiclass (in
2414 /// which case CurRec will be null, but CurMultiClass will be set). This can
2415 /// also happen within a def that is within a multiclass, which will set both
2416 /// CurRec and CurMultiClass.
2418 /// Declaration ::= FIELD? Type ID ('=' Value)?
2420 Init *TGParser::ParseDeclaration(Record *CurRec,
2421 bool ParsingTemplateArgs) {
2422 // Read the field prefix if present.
2423 bool HasField = Lex.getCode() == tgtok::Field;
2424 if (HasField) Lex.Lex();
2426 RecTy *Type = ParseType();
2427 if (!Type) return nullptr;
2429 if (Lex.getCode() != tgtok::Id) {
2430 TokError("Expected identifier in declaration");
2434 std::string Str = Lex.getCurStrVal();
2435 if (Str == "NAME") {
2436 TokError("'" + Str + "' is a reserved variable name");
2440 SMLoc IdLoc = Lex.getLoc();
2441 Init *DeclName = StringInit::get(Str);
2444 if (ParsingTemplateArgs) {
2446 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
2448 assert(CurMultiClass);
2450 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
2455 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
2458 // If a value is present, parse it.
2459 if (Lex.getCode() == tgtok::equal) {
2461 SMLoc ValLoc = Lex.getLoc();
2462 Init *Val = ParseValue(CurRec, Type);
2464 SetValue(CurRec, ValLoc, DeclName, None, Val))
2465 // Return the name, even if an error is thrown. This is so that we can
2466 // continue to make some progress, even without the value having been
2474 /// ParseForeachDeclaration - Read a foreach declaration, returning
2475 /// the name of the declared object or a NULL Init on error. Return
2476 /// the name of the parsed initializer list through ForeachListName.
2478 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
2479 /// ForeachDeclaration ::= ID '=' RangePiece
2480 /// ForeachDeclaration ::= ID '=' Value
2482 VarInit *TGParser::ParseForeachDeclaration(Init *&ForeachListValue) {
2483 if (Lex.getCode() != tgtok::Id) {
2484 TokError("Expected identifier in foreach declaration");
2488 Init *DeclName = StringInit::get(Lex.getCurStrVal());
2491 // If a value is present, parse it.
2492 if (Lex.getCode() != tgtok::equal) {
2493 TokError("Expected '=' in foreach declaration");
2496 Lex.Lex(); // Eat the '='
2498 RecTy *IterType = nullptr;
2499 SmallVector<unsigned, 16> Ranges;
2501 switch (Lex.getCode()) {
2502 case tgtok::l_brace: { // '{' RangeList '}'
2503 Lex.Lex(); // eat the '{'
2504 ParseRangeList(Ranges);
2505 if (Lex.getCode() != tgtok::r_brace) {
2506 TokError("expected '}' at end of bit range list");
2514 SMLoc ValueLoc = Lex.getLoc();
2515 Init *I = ParseValue(nullptr);
2519 TypedInit *TI = dyn_cast<TypedInit>(I);
2520 if (TI && isa<ListRecTy>(TI->getType())) {
2521 ForeachListValue = I;
2522 IterType = cast<ListRecTy>(TI->getType())->getElementType();
2527 if (ParseRangePiece(Ranges, TI))
2534 Type = (Twine("' of type '") + TI->getType()->getAsString()).str();
2535 Error(ValueLoc, "expected a list, got '" + I->getAsString() + Type + "'");
2536 if (CurMultiClass) {
2537 PrintNote({}, "references to multiclass template arguments cannot be "
2538 "resolved at this time");
2545 if (!Ranges.empty()) {
2546 assert(!IterType && "Type already initialized?");
2547 IterType = IntRecTy::get();
2548 std::vector<Init*> Values;
2549 for (unsigned R : Ranges)
2550 Values.push_back(IntInit::get(R));
2551 ForeachListValue = ListInit::get(Values, IterType);
2557 return VarInit::get(DeclName, IterType);
2560 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
2561 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
2562 /// template args for a def, which may or may not be in a multiclass. If null,
2563 /// these are the template args for a multiclass.
2565 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
2567 bool TGParser::ParseTemplateArgList(Record *CurRec) {
2568 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
2569 Lex.Lex(); // eat the '<'
2571 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
2573 // Read the first declaration.
2574 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2578 TheRecToAddTo->addTemplateArg(TemplArg);
2580 while (Lex.getCode() == tgtok::comma) {
2581 Lex.Lex(); // eat the ','
2583 // Read the following declarations.
2584 SMLoc Loc = Lex.getLoc();
2585 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2589 if (TheRecToAddTo->isTemplateArg(TemplArg))
2590 return Error(Loc, "template argument with the same name has already been "
2593 TheRecToAddTo->addTemplateArg(TemplArg);
2596 if (Lex.getCode() != tgtok::greater)
2597 return TokError("expected '>' at end of template argument list");
2598 Lex.Lex(); // eat the '>'.
2602 /// ParseBodyItem - Parse a single item at within the body of a def or class.
2604 /// BodyItem ::= Declaration ';'
2605 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
2606 /// BodyItem ::= Defvar
2607 bool TGParser::ParseBodyItem(Record *CurRec) {
2608 if (Lex.getCode() == tgtok::Defvar)
2609 return ParseDefvar();
2611 if (Lex.getCode() != tgtok::Let) {
2612 if (!ParseDeclaration(CurRec, false))
2615 if (Lex.getCode() != tgtok::semi)
2616 return TokError("expected ';' after declaration");
2621 // LET ID OptionalRangeList '=' Value ';'
2622 if (Lex.Lex() != tgtok::Id)
2623 return TokError("expected field identifier after let");
2625 SMLoc IdLoc = Lex.getLoc();
2626 StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2627 Lex.Lex(); // eat the field name.
2629 SmallVector<unsigned, 16> BitList;
2630 if (ParseOptionalBitList(BitList))
2632 std::reverse(BitList.begin(), BitList.end());
2634 if (Lex.getCode() != tgtok::equal)
2635 return TokError("expected '=' in let expression");
2636 Lex.Lex(); // eat the '='.
2638 RecordVal *Field = CurRec->getValue(FieldName);
2640 return TokError("Value '" + FieldName->getValue() + "' unknown!");
2642 RecTy *Type = Field->getType();
2644 Init *Val = ParseValue(CurRec, Type);
2645 if (!Val) return true;
2647 if (Lex.getCode() != tgtok::semi)
2648 return TokError("expected ';' after let expression");
2651 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
2654 /// ParseBody - Read the body of a class or def. Return true on error, false on
2658 /// Body ::= '{' BodyList '}'
2659 /// BodyList BodyItem*
2661 bool TGParser::ParseBody(Record *CurRec) {
2662 // If this is a null definition, just eat the semi and return.
2663 if (Lex.getCode() == tgtok::semi) {
2668 if (Lex.getCode() != tgtok::l_brace)
2669 return TokError("Expected ';' or '{' to start body");
2673 // An object body introduces a new scope for local variables.
2674 TGLocalVarScope *BodyScope = PushLocalScope();
2676 while (Lex.getCode() != tgtok::r_brace)
2677 if (ParseBodyItem(CurRec))
2680 PopLocalScope(BodyScope);
2687 /// Apply the current let bindings to \a CurRec.
2688 /// \returns true on error, false otherwise.
2689 bool TGParser::ApplyLetStack(Record *CurRec) {
2690 for (SmallVectorImpl<LetRecord> &LetInfo : LetStack)
2691 for (LetRecord &LR : LetInfo)
2692 if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
2697 bool TGParser::ApplyLetStack(RecordsEntry &Entry) {
2699 return ApplyLetStack(Entry.Rec.get());
2701 for (auto &E : Entry.Loop->Entries) {
2702 if (ApplyLetStack(E))
2709 /// ParseObjectBody - Parse the body of a def or class. This consists of an
2710 /// optional ClassList followed by a Body. CurRec is the current def or class
2711 /// that is being parsed.
2713 /// ObjectBody ::= BaseClassList Body
2714 /// BaseClassList ::= /*empty*/
2715 /// BaseClassList ::= ':' BaseClassListNE
2716 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
2718 bool TGParser::ParseObjectBody(Record *CurRec) {
2719 // If there is a baseclass list, read it.
2720 if (Lex.getCode() == tgtok::colon) {
2723 // Read all of the subclasses.
2724 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
2727 if (!SubClass.Rec) return true;
2730 if (AddSubClass(CurRec, SubClass))
2733 if (Lex.getCode() != tgtok::comma) break;
2734 Lex.Lex(); // eat ','.
2735 SubClass = ParseSubClassReference(CurRec, false);
2739 if (ApplyLetStack(CurRec))
2742 return ParseBody(CurRec);
2745 /// ParseDef - Parse and return a top level or multiclass def, return the record
2746 /// corresponding to it. This returns null on error.
2748 /// DefInst ::= DEF ObjectName ObjectBody
2750 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
2751 SMLoc DefLoc = Lex.getLoc();
2752 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
2753 Lex.Lex(); // Eat the 'def' token.
2755 // Parse ObjectName and make a record for it.
2756 std::unique_ptr<Record> CurRec;
2757 Init *Name = ParseObjectName(CurMultiClass);
2761 if (isa<UnsetInit>(Name))
2762 CurRec = std::make_unique<Record>(Records.getNewAnonymousName(), DefLoc, Records,
2763 /*Anonymous=*/true);
2765 CurRec = std::make_unique<Record>(Name, DefLoc, Records);
2767 if (ParseObjectBody(CurRec.get()))
2770 return addEntry(std::move(CurRec));
2773 /// ParseDefset - Parse a defset statement.
2775 /// Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
2777 bool TGParser::ParseDefset() {
2778 assert(Lex.getCode() == tgtok::Defset);
2779 Lex.Lex(); // Eat the 'defset' token
2781 DefsetRecord Defset;
2782 Defset.Loc = Lex.getLoc();
2783 RecTy *Type = ParseType();
2786 if (!isa<ListRecTy>(Type))
2787 return Error(Defset.Loc, "expected list type");
2788 Defset.EltTy = cast<ListRecTy>(Type)->getElementType();
2790 if (Lex.getCode() != tgtok::Id)
2791 return TokError("expected identifier");
2792 StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
2793 if (Records.getGlobal(DeclName->getValue()))
2794 return TokError("def or global variable of this name already exists");
2796 if (Lex.Lex() != tgtok::equal) // Eat the identifier
2797 return TokError("expected '='");
2798 if (Lex.Lex() != tgtok::l_brace) // Eat the '='
2799 return TokError("expected '{'");
2800 SMLoc BraceLoc = Lex.getLoc();
2801 Lex.Lex(); // Eat the '{'
2803 Defsets.push_back(&Defset);
2804 bool Err = ParseObjectList(nullptr);
2809 if (Lex.getCode() != tgtok::r_brace) {
2810 TokError("expected '}' at end of defset");
2811 return Error(BraceLoc, "to match this '{'");
2813 Lex.Lex(); // Eat the '}'
2815 Records.addExtraGlobal(DeclName->getValue(),
2816 ListInit::get(Defset.Elements, Defset.EltTy));
2820 /// ParseDefvar - Parse a defvar statement.
2822 /// Defvar ::= DEFVAR Id '=' Value ';'
2824 bool TGParser::ParseDefvar() {
2825 assert(Lex.getCode() == tgtok::Defvar);
2826 Lex.Lex(); // Eat the 'defvar' token
2828 if (Lex.getCode() != tgtok::Id)
2829 return TokError("expected identifier");
2830 StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
2831 if (CurLocalScope) {
2832 if (CurLocalScope->varAlreadyDefined(DeclName->getValue()))
2833 return TokError("local variable of this name already exists");
2835 if (Records.getGlobal(DeclName->getValue()))
2836 return TokError("def or global variable of this name already exists");
2839 if (Lex.Lex() != tgtok::equal) // Eat the identifier
2840 return TokError("expected '='");
2841 Lex.Lex(); // Eat the '='
2843 Init *Value = ParseValue(nullptr);
2847 if (Lex.getCode() != tgtok::semi)
2848 return TokError("expected ';'");
2849 Lex.Lex(); // Eat the ';'
2852 CurLocalScope->addVar(DeclName->getValue(), Value);
2854 Records.addExtraGlobal(DeclName->getValue(), Value);
2859 /// ParseForeach - Parse a for statement. Return the record corresponding
2860 /// to it. This returns true on error.
2862 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2863 /// Foreach ::= FOREACH Declaration IN Object
2865 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2866 SMLoc Loc = Lex.getLoc();
2867 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2868 Lex.Lex(); // Eat the 'for' token.
2870 // Make a temporary object to record items associated with the for
2872 Init *ListValue = nullptr;
2873 VarInit *IterName = ParseForeachDeclaration(ListValue);
2875 return TokError("expected declaration in for");
2877 if (Lex.getCode() != tgtok::In)
2878 return TokError("Unknown tok");
2879 Lex.Lex(); // Eat the in
2881 // Create a loop object and remember it.
2882 Loops.push_back(std::make_unique<ForeachLoop>(Loc, IterName, ListValue));
2884 // A foreach loop introduces a new scope for local variables.
2885 TGLocalVarScope *ForeachScope = PushLocalScope();
2887 if (Lex.getCode() != tgtok::l_brace) {
2888 // FOREACH Declaration IN Object
2889 if (ParseObject(CurMultiClass))
2892 SMLoc BraceLoc = Lex.getLoc();
2893 // Otherwise, this is a group foreach.
2894 Lex.Lex(); // eat the '{'.
2896 // Parse the object list.
2897 if (ParseObjectList(CurMultiClass))
2900 if (Lex.getCode() != tgtok::r_brace) {
2901 TokError("expected '}' at end of foreach command");
2902 return Error(BraceLoc, "to match this '{'");
2904 Lex.Lex(); // Eat the }
2907 PopLocalScope(ForeachScope);
2909 // Resolve the loop or store it for later resolution.
2910 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
2913 return addEntry(std::move(Loop));
2916 /// ParseIf - Parse an if statement.
2918 /// If ::= IF Value THEN IfBody
2919 /// If ::= IF Value THEN IfBody ELSE IfBody
2921 bool TGParser::ParseIf(MultiClass *CurMultiClass) {
2922 SMLoc Loc = Lex.getLoc();
2923 assert(Lex.getCode() == tgtok::If && "Unknown tok");
2924 Lex.Lex(); // Eat the 'if' token.
2926 // Make a temporary object to record items associated with the for
2928 Init *Condition = ParseValue(nullptr);
2932 if (Lex.getCode() != tgtok::Then)
2933 return TokError("Unknown tok");
2934 Lex.Lex(); // Eat the 'then'
2936 // We have to be able to save if statements to execute later, and they have
2937 // to live on the same stack as foreach loops. The simplest implementation
2938 // technique is to convert each 'then' or 'else' clause *into* a foreach
2939 // loop, over a list of length 0 or 1 depending on the condition, and with no
2940 // iteration variable being assigned.
2942 ListInit *EmptyList = ListInit::get({}, BitRecTy::get());
2943 ListInit *SingletonList = ListInit::get({BitInit::get(1)}, BitRecTy::get());
2944 RecTy *BitListTy = ListRecTy::get(BitRecTy::get());
2946 // The foreach containing the then-clause selects SingletonList if
2947 // the condition is true.
2948 Init *ThenClauseList =
2949 TernOpInit::get(TernOpInit::IF, Condition, SingletonList, EmptyList,
2952 Loops.push_back(std::make_unique<ForeachLoop>(Loc, nullptr, ThenClauseList));
2954 if (ParseIfBody(CurMultiClass, "then"))
2957 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
2960 if (addEntry(std::move(Loop)))
2963 // Now look for an optional else clause. The if-else syntax has the usual
2964 // dangling-else ambiguity, and by greedily matching an else here if we can,
2965 // we implement the usual resolution of pairing with the innermost unmatched
2967 if (Lex.getCode() == tgtok::ElseKW) {
2968 Lex.Lex(); // Eat the 'else'
2970 // The foreach containing the else-clause uses the same pair of lists as
2971 // above, but this time, selects SingletonList if the condition is *false*.
2972 Init *ElseClauseList =
2973 TernOpInit::get(TernOpInit::IF, Condition, EmptyList, SingletonList,
2977 std::make_unique<ForeachLoop>(Loc, nullptr, ElseClauseList));
2979 if (ParseIfBody(CurMultiClass, "else"))
2982 Loop = std::move(Loops.back());
2985 if (addEntry(std::move(Loop)))
2992 /// ParseIfBody - Parse the then-clause or else-clause of an if statement.
2994 /// IfBody ::= Object
2995 /// IfBody ::= '{' ObjectList '}'
2997 bool TGParser::ParseIfBody(MultiClass *CurMultiClass, StringRef Kind) {
2998 TGLocalVarScope *BodyScope = PushLocalScope();
3000 if (Lex.getCode() != tgtok::l_brace) {
3002 if (ParseObject(CurMultiClass))
3005 SMLoc BraceLoc = Lex.getLoc();
3007 Lex.Lex(); // eat the '{'.
3009 // Parse the object list.
3010 if (ParseObjectList(CurMultiClass))
3013 if (Lex.getCode() != tgtok::r_brace) {
3014 TokError("expected '}' at end of '" + Kind + "' clause");
3015 return Error(BraceLoc, "to match this '{'");
3018 Lex.Lex(); // Eat the }
3021 PopLocalScope(BodyScope);
3025 /// ParseClass - Parse a tblgen class definition.
3027 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
3029 bool TGParser::ParseClass() {
3030 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
3033 if (Lex.getCode() != tgtok::Id)
3034 return TokError("expected class name after 'class' keyword");
3036 Record *CurRec = Records.getClass(Lex.getCurStrVal());
3038 // If the body was previously defined, this is an error.
3039 if (!CurRec->getValues().empty() ||
3040 !CurRec->getSuperClasses().empty() ||
3041 !CurRec->getTemplateArgs().empty())
3042 return TokError("Class '" + CurRec->getNameInitAsString() +
3043 "' already defined");
3045 // If this is the first reference to this class, create and add it.
3047 std::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records,
3049 CurRec = NewRec.get();
3050 Records.addClass(std::move(NewRec));
3052 Lex.Lex(); // eat the name.
3054 // If there are template args, parse them.
3055 if (Lex.getCode() == tgtok::less)
3056 if (ParseTemplateArgList(CurRec))
3059 return ParseObjectBody(CurRec);
3062 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
3065 /// LetList ::= LetItem (',' LetItem)*
3066 /// LetItem ::= ID OptionalRangeList '=' Value
3068 void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) {
3070 if (Lex.getCode() != tgtok::Id) {
3071 TokError("expected identifier in let definition");
3076 StringInit *Name = StringInit::get(Lex.getCurStrVal());
3077 SMLoc NameLoc = Lex.getLoc();
3078 Lex.Lex(); // Eat the identifier.
3080 // Check for an optional RangeList.
3081 SmallVector<unsigned, 16> Bits;
3082 if (ParseOptionalRangeList(Bits)) {
3086 std::reverse(Bits.begin(), Bits.end());
3088 if (Lex.getCode() != tgtok::equal) {
3089 TokError("expected '=' in let expression");
3093 Lex.Lex(); // eat the '='.
3095 Init *Val = ParseValue(nullptr);
3101 // Now that we have everything, add the record.
3102 Result.emplace_back(Name, Bits, Val, NameLoc);
3104 if (Lex.getCode() != tgtok::comma)
3106 Lex.Lex(); // eat the comma.
3110 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
3111 /// different related productions. This works inside multiclasses too.
3113 /// Object ::= LET LetList IN '{' ObjectList '}'
3114 /// Object ::= LET LetList IN Object
3116 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
3117 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
3120 // Add this entry to the let stack.
3121 SmallVector<LetRecord, 8> LetInfo;
3122 ParseLetList(LetInfo);
3123 if (LetInfo.empty()) return true;
3124 LetStack.push_back(std::move(LetInfo));
3126 if (Lex.getCode() != tgtok::In)
3127 return TokError("expected 'in' at end of top-level 'let'");
3130 TGLocalVarScope *LetScope = PushLocalScope();
3132 // If this is a scalar let, just handle it now
3133 if (Lex.getCode() != tgtok::l_brace) {
3134 // LET LetList IN Object
3135 if (ParseObject(CurMultiClass))
3137 } else { // Object ::= LETCommand '{' ObjectList '}'
3138 SMLoc BraceLoc = Lex.getLoc();
3139 // Otherwise, this is a group let.
3140 Lex.Lex(); // eat the '{'.
3142 // Parse the object list.
3143 if (ParseObjectList(CurMultiClass))
3146 if (Lex.getCode() != tgtok::r_brace) {
3147 TokError("expected '}' at end of top level let command");
3148 return Error(BraceLoc, "to match this '{'");
3153 PopLocalScope(LetScope);
3155 // Outside this let scope, this let block is not active.
3156 LetStack.pop_back();
3160 /// ParseMultiClass - Parse a multiclass definition.
3162 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
3163 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
3164 /// MultiClassObject ::= DefInst
3165 /// MultiClassObject ::= MultiClassInst
3166 /// MultiClassObject ::= DefMInst
3167 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
3168 /// MultiClassObject ::= LETCommand Object
3170 bool TGParser::ParseMultiClass() {
3171 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
3172 Lex.Lex(); // Eat the multiclass token.
3174 if (Lex.getCode() != tgtok::Id)
3175 return TokError("expected identifier after multiclass for name");
3176 std::string Name = Lex.getCurStrVal();
3179 MultiClasses.insert(std::make_pair(Name,
3180 std::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
3183 return TokError("multiclass '" + Name + "' already defined");
3185 CurMultiClass = Result.first->second.get();
3186 Lex.Lex(); // Eat the identifier.
3188 // If there are template args, parse them.
3189 if (Lex.getCode() == tgtok::less)
3190 if (ParseTemplateArgList(nullptr))
3193 bool inherits = false;
3195 // If there are submulticlasses, parse them.
3196 if (Lex.getCode() == tgtok::colon) {
3201 // Read all of the submulticlasses.
3202 SubMultiClassReference SubMultiClass =
3203 ParseSubMultiClassReference(CurMultiClass);
3206 if (!SubMultiClass.MC) return true;
3209 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
3212 if (Lex.getCode() != tgtok::comma) break;
3213 Lex.Lex(); // eat ','.
3214 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
3218 if (Lex.getCode() != tgtok::l_brace) {
3220 return TokError("expected '{' in multiclass definition");
3221 if (Lex.getCode() != tgtok::semi)
3222 return TokError("expected ';' in multiclass definition");
3223 Lex.Lex(); // eat the ';'.
3225 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
3226 return TokError("multiclass must contain at least one def");
3228 // A multiclass body introduces a new scope for local variables.
3229 TGLocalVarScope *MulticlassScope = PushLocalScope();
3231 while (Lex.getCode() != tgtok::r_brace) {
3232 switch (Lex.getCode()) {
3234 return TokError("expected 'let', 'def', 'defm', 'defvar', 'foreach' "
3235 "or 'if' in multiclass body");
3240 case tgtok::Foreach:
3242 if (ParseObject(CurMultiClass))
3247 Lex.Lex(); // eat the '}'.
3249 PopLocalScope(MulticlassScope);
3252 CurMultiClass = nullptr;
3256 /// ParseDefm - Parse the instantiation of a multiclass.
3258 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
3260 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
3261 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
3262 Lex.Lex(); // eat the defm
3264 Init *DefmName = ParseObjectName(CurMultiClass);
3267 if (isa<UnsetInit>(DefmName)) {
3268 DefmName = Records.getNewAnonymousName();
3270 DefmName = BinOpInit::getStrConcat(
3271 VarInit::get(QualifiedNameOfImplicitName(CurMultiClass),
3272 StringRecTy::get()),
3276 if (Lex.getCode() != tgtok::colon)
3277 return TokError("expected ':' after defm identifier");
3279 // Keep track of the new generated record definitions.
3280 std::vector<RecordsEntry> NewEntries;
3282 // This record also inherits from a regular class (non-multiclass)?
3283 bool InheritFromClass = false;
3288 SMLoc SubClassLoc = Lex.getLoc();
3289 SubClassReference Ref = ParseSubClassReference(nullptr, true);
3292 if (!Ref.Rec) return true;
3294 // To instantiate a multiclass, we need to first get the multiclass, then
3295 // instantiate each def contained in the multiclass with the SubClassRef
3296 // template parameters.
3297 MultiClass *MC = MultiClasses[Ref.Rec->getName()].get();
3298 assert(MC && "Didn't lookup multiclass correctly?");
3299 ArrayRef<Init*> TemplateVals = Ref.TemplateArgs;
3301 // Verify that the correct number of template arguments were specified.
3302 ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs();
3303 if (TArgs.size() < TemplateVals.size())
3304 return Error(SubClassLoc,
3305 "more template args specified than multiclass expects");
3308 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
3309 if (i < TemplateVals.size()) {
3310 Substs.emplace_back(TArgs[i], TemplateVals[i]);
3312 Init *Default = MC->Rec.getValue(TArgs[i])->getValue();
3313 if (!Default->isComplete()) {
3314 return Error(SubClassLoc,
3315 "value not specified for template argument #" +
3316 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
3317 ") of multiclass '" + MC->Rec.getNameInitAsString() +
3320 Substs.emplace_back(TArgs[i], Default);
3324 Substs.emplace_back(QualifiedNameOfImplicitName(MC), DefmName);
3326 if (resolve(MC->Entries, Substs, CurMultiClass == nullptr, &NewEntries,
3330 if (Lex.getCode() != tgtok::comma) break;
3331 Lex.Lex(); // eat ','.
3333 if (Lex.getCode() != tgtok::Id)
3334 return TokError("expected identifier");
3336 SubClassLoc = Lex.getLoc();
3338 // A defm can inherit from regular classes (non-multiclass) as
3339 // long as they come in the end of the inheritance list.
3340 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
3342 if (InheritFromClass)
3345 Ref = ParseSubClassReference(nullptr, true);
3348 if (InheritFromClass) {
3349 // Process all the classes to inherit as if they were part of a
3350 // regular 'def' and inherit all record values.
3351 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
3354 if (!SubClass.Rec) return true;
3356 // Get the expanded definition prototypes and teach them about
3357 // the record values the current class to inherit has
3358 for (auto &E : NewEntries) {
3360 if (AddSubClass(E, SubClass))
3364 if (Lex.getCode() != tgtok::comma) break;
3365 Lex.Lex(); // eat ','.
3366 SubClass = ParseSubClassReference(nullptr, false);
3370 for (auto &E : NewEntries) {
3371 if (ApplyLetStack(E))
3374 addEntry(std::move(E));
3377 if (Lex.getCode() != tgtok::semi)
3378 return TokError("expected ';' at end of defm");
3385 /// Object ::= ClassInst
3386 /// Object ::= DefInst
3387 /// Object ::= MultiClassInst
3388 /// Object ::= DefMInst
3389 /// Object ::= LETCommand '{' ObjectList '}'
3390 /// Object ::= LETCommand Object
3391 /// Object ::= Defset
3392 /// Object ::= Defvar
3393 bool TGParser::ParseObject(MultiClass *MC) {
3394 switch (Lex.getCode()) {
3396 return TokError("Expected class, def, defm, defset, multiclass, let, "
3398 case tgtok::Let: return ParseTopLevelLet(MC);
3399 case tgtok::Def: return ParseDef(MC);
3400 case tgtok::Foreach: return ParseForeach(MC);
3401 case tgtok::If: return ParseIf(MC);
3402 case tgtok::Defm: return ParseDefm(MC);
3405 return TokError("defset is not allowed inside multiclass");
3406 return ParseDefset();
3408 return ParseDefvar();
3411 return TokError("class is not allowed inside multiclass");
3413 return TokError("class is not allowed inside foreach loop");
3414 return ParseClass();
3415 case tgtok::MultiClass:
3417 return TokError("multiclass is not allowed inside foreach loop");
3418 return ParseMultiClass();
3423 /// ObjectList :== Object*
3424 bool TGParser::ParseObjectList(MultiClass *MC) {
3425 while (isObjectStart(Lex.getCode())) {
3426 if (ParseObject(MC))
3432 bool TGParser::ParseFile() {
3433 Lex.Lex(); // Prime the lexer.
3434 if (ParseObjectList()) return true;
3436 // If we have unread input at the end of the file, report it.
3437 if (Lex.getCode() == tgtok::Eof)
3440 return TokError("Unexpected input at top level");
3443 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3444 LLVM_DUMP_METHOD void RecordsEntry::dump() const {
3451 LLVM_DUMP_METHOD void ForeachLoop::dump() const {
3452 errs() << "foreach " << IterVar->getAsString() << " = "
3453 << ListValue->getAsString() << " in {\n";
3455 for (const auto &E : Entries)
3461 LLVM_DUMP_METHOD void MultiClass::dump() const {
3462 errs() << "Record:\n";
3465 errs() << "Defs:\n";
3466 for (const auto &E : Entries)