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
) {
394 Substs
.emplace_back(Loop
.IterVar
->getNameInit(), Elt
);
395 Error
= resolve(Loop
.Entries
, Substs
, Final
, Dest
);
403 /// Resolve the entries in \p Source, going over loops recursively and
404 /// making the given substitutions of (name, value) pairs.
406 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
407 /// are added to the global record keeper.
408 bool TGParser::resolve(const std::vector
<RecordsEntry
> &Source
,
409 SubstStack
&Substs
, bool Final
,
410 std::vector
<RecordsEntry
> *Dest
, SMLoc
*Loc
) {
412 for (auto &E
: Source
) {
414 Error
= resolve(*E
.Loop
, Substs
, Final
, Dest
);
416 auto Rec
= std::make_unique
<Record
>(*E
.Rec
);
418 Rec
->appendLoc(*Loc
);
420 MapResolver
R(Rec
.get());
421 for (const auto &S
: Substs
)
422 R
.set(S
.first
, S
.second
);
423 Rec
->resolveReferences(R
);
426 Dest
->push_back(std::move(Rec
));
428 Error
= addDefOne(std::move(Rec
));
436 /// Resolve the record fully and add it to the record keeper.
437 bool TGParser::addDefOne(std::unique_ptr
<Record
> Rec
) {
438 if (Record
*Prev
= Records
.getDef(Rec
->getNameInitAsString())) {
439 if (!Rec
->isAnonymous()) {
440 PrintError(Rec
->getLoc(),
441 "def already exists: " + Rec
->getNameInitAsString());
442 PrintNote(Prev
->getLoc(), "location of previous definition");
445 Rec
->setName(Records
.getNewAnonymousName());
448 Rec
->resolveReferences();
451 if (!isa
<StringInit
>(Rec
->getNameInit())) {
452 PrintError(Rec
->getLoc(), Twine("record name '") +
453 Rec
->getNameInit()->getAsString() +
454 "' could not be fully resolved");
458 // If ObjectBody has template arguments, it's an error.
459 assert(Rec
->getTemplateArgs().empty() && "How'd this get template args?");
461 for (DefsetRecord
*Defset
: Defsets
) {
462 DefInit
*I
= Rec
->getDefInit();
463 if (!I
->getType()->typeIsA(Defset
->EltTy
)) {
464 PrintError(Rec
->getLoc(), Twine("adding record of incompatible type '") +
465 I
->getType()->getAsString() +
467 PrintNote(Defset
->Loc
, "location of defset declaration");
470 Defset
->Elements
.push_back(I
);
473 Records
.addDef(std::move(Rec
));
477 //===----------------------------------------------------------------------===//
479 //===----------------------------------------------------------------------===//
481 /// isObjectStart - Return true if this is a valid first token for an Object.
482 static bool isObjectStart(tgtok::TokKind K
) {
483 return K
== tgtok::Class
|| K
== tgtok::Def
|| K
== tgtok::Defm
||
484 K
== tgtok::Let
|| K
== tgtok::MultiClass
|| K
== tgtok::Foreach
||
488 /// ParseObjectName - If a valid object name is specified, return it. If no
489 /// name is specified, return the unset initializer. Return nullptr on parse
491 /// ObjectName ::= Value [ '#' Value ]*
492 /// ObjectName ::= /*empty*/
494 Init
*TGParser::ParseObjectName(MultiClass
*CurMultiClass
) {
495 switch (Lex
.getCode()) {
499 // These are all of the tokens that can begin an object body.
500 // Some of these can also begin values but we disallow those cases
501 // because they are unlikely to be useful.
502 return UnsetInit::get();
507 Record
*CurRec
= nullptr;
509 CurRec
= &CurMultiClass
->Rec
;
511 Init
*Name
= ParseValue(CurRec
, StringRecTy::get(), ParseNameMode
);
516 Init
*NameStr
= QualifiedNameOfImplicitName(CurMultiClass
);
517 HasReferenceResolver
R(NameStr
);
518 Name
->resolveReferences(R
);
520 Name
= BinOpInit::getStrConcat(VarInit::get(NameStr
, StringRecTy::get()),
527 /// ParseClassID - Parse and resolve a reference to a class name. This returns
532 Record
*TGParser::ParseClassID() {
533 if (Lex
.getCode() != tgtok::Id
) {
534 TokError("expected name for ClassID");
538 Record
*Result
= Records
.getClass(Lex
.getCurStrVal());
540 std::string
Msg("Couldn't find class '" + Lex
.getCurStrVal() + "'");
541 if (MultiClasses
[Lex
.getCurStrVal()].get())
542 TokError(Msg
+ ". Use 'defm' if you meant to use multiclass '" +
543 Lex
.getCurStrVal() + "'");
552 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
553 /// This returns null on error.
555 /// MultiClassID ::= ID
557 MultiClass
*TGParser::ParseMultiClassID() {
558 if (Lex
.getCode() != tgtok::Id
) {
559 TokError("expected name for MultiClassID");
563 MultiClass
*Result
= MultiClasses
[Lex
.getCurStrVal()].get();
565 TokError("Couldn't find multiclass '" + Lex
.getCurStrVal() + "'");
571 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
572 /// subclass. This returns a SubClassRefTy with a null Record* on error.
574 /// SubClassRef ::= ClassID
575 /// SubClassRef ::= ClassID '<' ValueList '>'
577 SubClassReference
TGParser::
578 ParseSubClassReference(Record
*CurRec
, bool isDefm
) {
579 SubClassReference Result
;
580 Result
.RefRange
.Start
= Lex
.getLoc();
583 if (MultiClass
*MC
= ParseMultiClassID())
584 Result
.Rec
= &MC
->Rec
;
586 Result
.Rec
= ParseClassID();
588 if (!Result
.Rec
) return Result
;
590 // If there is no template arg list, we're done.
591 if (Lex
.getCode() != tgtok::less
) {
592 Result
.RefRange
.End
= Lex
.getLoc();
595 Lex
.Lex(); // Eat the '<'
597 if (Lex
.getCode() == tgtok::greater
) {
598 TokError("subclass reference requires a non-empty list of template values");
599 Result
.Rec
= nullptr;
603 ParseValueList(Result
.TemplateArgs
, CurRec
, Result
.Rec
);
604 if (Result
.TemplateArgs
.empty()) {
605 Result
.Rec
= nullptr; // Error parsing value list.
609 if (Lex
.getCode() != tgtok::greater
) {
610 TokError("expected '>' in template value list");
611 Result
.Rec
= nullptr;
615 Result
.RefRange
.End
= Lex
.getLoc();
620 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
621 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
622 /// Record* on error.
624 /// SubMultiClassRef ::= MultiClassID
625 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
627 SubMultiClassReference
TGParser::
628 ParseSubMultiClassReference(MultiClass
*CurMC
) {
629 SubMultiClassReference Result
;
630 Result
.RefRange
.Start
= Lex
.getLoc();
632 Result
.MC
= ParseMultiClassID();
633 if (!Result
.MC
) return Result
;
635 // If there is no template arg list, we're done.
636 if (Lex
.getCode() != tgtok::less
) {
637 Result
.RefRange
.End
= Lex
.getLoc();
640 Lex
.Lex(); // Eat the '<'
642 if (Lex
.getCode() == tgtok::greater
) {
643 TokError("subclass reference requires a non-empty list of template values");
648 ParseValueList(Result
.TemplateArgs
, &CurMC
->Rec
, &Result
.MC
->Rec
);
649 if (Result
.TemplateArgs
.empty()) {
650 Result
.MC
= nullptr; // Error parsing value list.
654 if (Lex
.getCode() != tgtok::greater
) {
655 TokError("expected '>' in template value list");
660 Result
.RefRange
.End
= Lex
.getLoc();
665 /// ParseRangePiece - Parse a bit/value range.
666 /// RangePiece ::= INTVAL
667 /// RangePiece ::= INTVAL '-' INTVAL
668 /// RangePiece ::= INTVAL INTVAL
669 bool TGParser::ParseRangePiece(SmallVectorImpl
<unsigned> &Ranges
,
670 TypedInit
*FirstItem
) {
671 Init
*CurVal
= FirstItem
;
673 CurVal
= ParseValue(nullptr);
675 IntInit
*II
= dyn_cast_or_null
<IntInit
>(CurVal
);
677 return TokError("expected integer or bitrange");
679 int64_t Start
= II
->getValue();
683 return TokError("invalid range, cannot be negative");
685 switch (Lex
.getCode()) {
687 Ranges
.push_back(Start
);
692 Init
*I_End
= ParseValue(nullptr);
693 IntInit
*II_End
= dyn_cast_or_null
<IntInit
>(I_End
);
695 TokError("expected integer value as end of range");
699 End
= II_End
->getValue();
702 case tgtok::IntVal
: {
703 End
= -Lex
.getCurIntVal();
709 return TokError("invalid range, cannot be negative");
713 for (; Start
<= End
; ++Start
)
714 Ranges
.push_back(Start
);
716 for (; Start
>= End
; --Start
)
717 Ranges
.push_back(Start
);
721 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
723 /// RangeList ::= RangePiece (',' RangePiece)*
725 void TGParser::ParseRangeList(SmallVectorImpl
<unsigned> &Result
) {
726 // Parse the first piece.
727 if (ParseRangePiece(Result
)) {
731 while (Lex
.getCode() == tgtok::comma
) {
732 Lex
.Lex(); // Eat the comma.
734 // Parse the next range piece.
735 if (ParseRangePiece(Result
)) {
742 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
743 /// OptionalRangeList ::= '<' RangeList '>'
744 /// OptionalRangeList ::= /*empty*/
745 bool TGParser::ParseOptionalRangeList(SmallVectorImpl
<unsigned> &Ranges
) {
746 if (Lex
.getCode() != tgtok::less
)
749 SMLoc StartLoc
= Lex
.getLoc();
750 Lex
.Lex(); // eat the '<'
752 // Parse the range list.
753 ParseRangeList(Ranges
);
754 if (Ranges
.empty()) return true;
756 if (Lex
.getCode() != tgtok::greater
) {
757 TokError("expected '>' at end of range list");
758 return Error(StartLoc
, "to match this '<'");
760 Lex
.Lex(); // eat the '>'.
764 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
765 /// OptionalBitList ::= '{' RangeList '}'
766 /// OptionalBitList ::= /*empty*/
767 bool TGParser::ParseOptionalBitList(SmallVectorImpl
<unsigned> &Ranges
) {
768 if (Lex
.getCode() != tgtok::l_brace
)
771 SMLoc StartLoc
= Lex
.getLoc();
772 Lex
.Lex(); // eat the '{'
774 // Parse the range list.
775 ParseRangeList(Ranges
);
776 if (Ranges
.empty()) return true;
778 if (Lex
.getCode() != tgtok::r_brace
) {
779 TokError("expected '}' at end of bit list");
780 return Error(StartLoc
, "to match this '{'");
782 Lex
.Lex(); // eat the '}'.
786 /// ParseType - Parse and return a tblgen type. This returns null on error.
788 /// Type ::= STRING // string type
789 /// Type ::= CODE // code type
790 /// Type ::= BIT // bit type
791 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
792 /// Type ::= INT // int type
793 /// Type ::= LIST '<' Type '>' // list<x> type
794 /// Type ::= DAG // dag type
795 /// Type ::= ClassID // Record Type
797 RecTy
*TGParser::ParseType() {
798 switch (Lex
.getCode()) {
799 default: TokError("Unknown token when expecting a type"); return nullptr;
800 case tgtok::String
: Lex
.Lex(); return StringRecTy::get();
801 case tgtok::Code
: Lex
.Lex(); return CodeRecTy::get();
802 case tgtok::Bit
: Lex
.Lex(); return BitRecTy::get();
803 case tgtok::Int
: Lex
.Lex(); return IntRecTy::get();
804 case tgtok::Dag
: Lex
.Lex(); return DagRecTy::get();
806 if (Record
*R
= ParseClassID()) return RecordRecTy::get(R
);
807 TokError("unknown class name");
810 if (Lex
.Lex() != tgtok::less
) { // Eat 'bits'
811 TokError("expected '<' after bits type");
814 if (Lex
.Lex() != tgtok::IntVal
) { // Eat '<'
815 TokError("expected integer in bits<n> type");
818 uint64_t Val
= Lex
.getCurIntVal();
819 if (Lex
.Lex() != tgtok::greater
) { // Eat count.
820 TokError("expected '>' at end of bits<n> type");
823 Lex
.Lex(); // Eat '>'
824 return BitsRecTy::get(Val
);
827 if (Lex
.Lex() != tgtok::less
) { // Eat 'bits'
828 TokError("expected '<' after list type");
831 Lex
.Lex(); // Eat '<'
832 RecTy
*SubType
= ParseType();
833 if (!SubType
) return nullptr;
835 if (Lex
.getCode() != tgtok::greater
) {
836 TokError("expected '>' at end of list<ty> type");
839 Lex
.Lex(); // Eat '>'
840 return ListRecTy::get(SubType
);
845 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
846 /// has already been read.
847 Init
*TGParser::ParseIDValue(Record
*CurRec
, StringInit
*Name
, SMLoc NameLoc
,
850 if (const RecordVal
*RV
= CurRec
->getValue(Name
))
851 return VarInit::get(Name
, RV
->getType());
854 if ((CurRec
&& CurRec
->isClass()) || CurMultiClass
) {
855 Init
*TemplateArgName
;
858 QualifyName(CurMultiClass
->Rec
, CurMultiClass
, Name
, "::");
860 TemplateArgName
= QualifyName(*CurRec
, CurMultiClass
, Name
, ":");
862 Record
*TemplateRec
= CurMultiClass
? &CurMultiClass
->Rec
: CurRec
;
863 if (TemplateRec
->isTemplateArg(TemplateArgName
)) {
864 const RecordVal
*RV
= TemplateRec
->getValue(TemplateArgName
);
865 assert(RV
&& "Template arg doesn't exist??");
866 return VarInit::get(TemplateArgName
, RV
->getType());
867 } else if (Name
->getValue() == "NAME") {
868 return VarInit::get(TemplateArgName
, StringRecTy::get());
872 // If this is in a foreach loop, make sure it's not a loop iterator
873 for (const auto &L
: Loops
) {
874 VarInit
*IterVar
= dyn_cast
<VarInit
>(L
->IterVar
);
875 if (IterVar
&& IterVar
->getNameInit() == Name
)
879 if (Mode
== ParseNameMode
)
882 if (Init
*I
= Records
.getGlobal(Name
->getValue()))
885 // Allow self-references of concrete defs, but delay the lookup so that we
886 // get the correct type.
887 if (CurRec
&& !CurRec
->isClass() && !CurMultiClass
&&
888 CurRec
->getNameInit() == Name
)
889 return UnOpInit::get(UnOpInit::CAST
, Name
, CurRec
->getType());
891 Error(NameLoc
, "Variable not defined: '" + Name
->getValue() + "'");
895 /// ParseOperation - Parse an operator. This returns null on error.
897 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
899 Init
*TGParser::ParseOperation(Record
*CurRec
, RecTy
*ItemType
) {
900 switch (Lex
.getCode()) {
902 TokError("unknown operation");
908 case tgtok::XCast
: { // Value ::= !unop '(' Value ')'
909 UnOpInit::UnaryOp Code
;
910 RecTy
*Type
= nullptr;
912 switch (Lex
.getCode()) {
913 default: llvm_unreachable("Unhandled code!");
915 Lex
.Lex(); // eat the operation
916 Code
= UnOpInit::CAST
;
918 Type
= ParseOperatorType();
921 TokError("did not get type for unary operator");
927 Lex
.Lex(); // eat the operation
928 Code
= UnOpInit::HEAD
;
931 Lex
.Lex(); // eat the operation
932 Code
= UnOpInit::TAIL
;
936 Code
= UnOpInit::SIZE
;
937 Type
= IntRecTy::get();
940 Lex
.Lex(); // eat the operation
941 Code
= UnOpInit::EMPTY
;
942 Type
= IntRecTy::get();
945 if (Lex
.getCode() != tgtok::l_paren
) {
946 TokError("expected '(' after unary operator");
949 Lex
.Lex(); // eat the '('
951 Init
*LHS
= ParseValue(CurRec
);
952 if (!LHS
) return nullptr;
954 if (Code
== UnOpInit::HEAD
||
955 Code
== UnOpInit::TAIL
||
956 Code
== UnOpInit::EMPTY
) {
957 ListInit
*LHSl
= dyn_cast
<ListInit
>(LHS
);
958 StringInit
*LHSs
= dyn_cast
<StringInit
>(LHS
);
959 TypedInit
*LHSt
= dyn_cast
<TypedInit
>(LHS
);
960 if (!LHSl
&& !LHSs
&& !LHSt
) {
961 TokError("expected list or string type argument in unary operator");
965 ListRecTy
*LType
= dyn_cast
<ListRecTy
>(LHSt
->getType());
966 StringRecTy
*SType
= dyn_cast
<StringRecTy
>(LHSt
->getType());
967 if (!LType
&& !SType
) {
968 TokError("expected list or string type argument in unary operator");
973 if (Code
== UnOpInit::HEAD
|| Code
== UnOpInit::TAIL
||
974 Code
== UnOpInit::SIZE
) {
975 if (!LHSl
&& !LHSt
) {
976 TokError("expected list type argument in unary operator");
981 if (Code
== UnOpInit::HEAD
|| Code
== UnOpInit::TAIL
) {
982 if (LHSl
&& LHSl
->empty()) {
983 TokError("empty list argument in unary operator");
987 Init
*Item
= LHSl
->getElement(0);
988 TypedInit
*Itemt
= dyn_cast
<TypedInit
>(Item
);
990 TokError("untyped list element in unary operator");
993 Type
= (Code
== UnOpInit::HEAD
) ? Itemt
->getType()
994 : ListRecTy::get(Itemt
->getType());
996 assert(LHSt
&& "expected list type argument in unary operator");
997 ListRecTy
*LType
= dyn_cast
<ListRecTy
>(LHSt
->getType());
999 TokError("expected list type argument in unary operator");
1002 Type
= (Code
== UnOpInit::HEAD
) ? LType
->getElementType() : LType
;
1007 if (Lex
.getCode() != tgtok::r_paren
) {
1008 TokError("expected ')' in unary operator");
1011 Lex
.Lex(); // eat the ')'
1012 return (UnOpInit::get(Code
, LHS
, Type
))->Fold(CurRec
);
1016 // Value ::= !isa '<' Type '>' '(' Value ')'
1017 Lex
.Lex(); // eat the operation
1019 RecTy
*Type
= ParseOperatorType();
1023 if (Lex
.getCode() != tgtok::l_paren
) {
1024 TokError("expected '(' after type of !isa");
1027 Lex
.Lex(); // eat the '('
1029 Init
*LHS
= ParseValue(CurRec
);
1033 if (Lex
.getCode() != tgtok::r_paren
) {
1034 TokError("expected ')' in !isa");
1037 Lex
.Lex(); // eat the ')'
1039 return (IsAOpInit::get(Type
, LHS
))->Fold();
1042 case tgtok::XConcat
:
1056 case tgtok::XListConcat
:
1057 case tgtok::XListSplat
:
1058 case tgtok::XStrConcat
: { // Value ::= !binop '(' Value ',' Value ')'
1059 tgtok::TokKind OpTok
= Lex
.getCode();
1060 SMLoc OpLoc
= Lex
.getLoc();
1061 Lex
.Lex(); // eat the operation
1063 BinOpInit::BinaryOp Code
;
1065 default: llvm_unreachable("Unhandled code!");
1066 case tgtok::XConcat
: Code
= BinOpInit::CONCAT
; break;
1067 case tgtok::XADD
: Code
= BinOpInit::ADD
; break;
1068 case tgtok::XMUL
: Code
= BinOpInit::MUL
; break;
1069 case tgtok::XAND
: Code
= BinOpInit::AND
; break;
1070 case tgtok::XOR
: Code
= BinOpInit::OR
; break;
1071 case tgtok::XSRA
: Code
= BinOpInit::SRA
; break;
1072 case tgtok::XSRL
: Code
= BinOpInit::SRL
; break;
1073 case tgtok::XSHL
: Code
= BinOpInit::SHL
; break;
1074 case tgtok::XEq
: Code
= BinOpInit::EQ
; break;
1075 case tgtok::XNe
: Code
= BinOpInit::NE
; break;
1076 case tgtok::XLe
: Code
= BinOpInit::LE
; break;
1077 case tgtok::XLt
: Code
= BinOpInit::LT
; break;
1078 case tgtok::XGe
: Code
= BinOpInit::GE
; break;
1079 case tgtok::XGt
: Code
= BinOpInit::GT
; break;
1080 case tgtok::XListConcat
: Code
= BinOpInit::LISTCONCAT
; break;
1081 case tgtok::XListSplat
: Code
= BinOpInit::LISTSPLAT
; break;
1082 case tgtok::XStrConcat
: Code
= BinOpInit::STRCONCAT
; break;
1085 RecTy
*Type
= nullptr;
1086 RecTy
*ArgType
= nullptr;
1089 llvm_unreachable("Unhandled code!");
1090 case tgtok::XConcat
:
1091 Type
= DagRecTy::get();
1092 ArgType
= DagRecTy::get();
1101 Type
= IntRecTy::get();
1102 ArgType
= IntRecTy::get();
1106 Type
= BitRecTy::get();
1107 // ArgType for Eq / Ne is not known at this point
1113 Type
= BitRecTy::get();
1114 ArgType
= IntRecTy::get();
1116 case tgtok::XListConcat
:
1117 // We don't know the list type until we parse the first argument
1120 case tgtok::XListSplat
:
1121 // Can't do any typechecking until we parse the first argument.
1123 case tgtok::XStrConcat
:
1124 Type
= StringRecTy::get();
1125 ArgType
= StringRecTy::get();
1129 if (Type
&& ItemType
&& !Type
->typeIsConvertibleTo(ItemType
)) {
1130 Error(OpLoc
, Twine("expected value of type '") +
1131 ItemType
->getAsString() + "', got '" +
1132 Type
->getAsString() + "'");
1136 if (Lex
.getCode() != tgtok::l_paren
) {
1137 TokError("expected '(' after binary operator");
1140 Lex
.Lex(); // eat the '('
1142 SmallVector
<Init
*, 2> InitList
;
1145 SMLoc InitLoc
= Lex
.getLoc();
1146 InitList
.push_back(ParseValue(CurRec
, ArgType
));
1147 if (!InitList
.back()) return nullptr;
1149 // All BinOps require their arguments to be of compatible types.
1150 RecTy
*ListType
= cast
<TypedInit
>(InitList
.back())->getType();
1155 case BinOpInit::LISTCONCAT
:
1156 if (!isa
<ListRecTy
>(ArgType
)) {
1157 Error(InitLoc
, Twine("expected a list, got value of type '") +
1158 ArgType
->getAsString() + "'");
1162 case BinOpInit::LISTSPLAT
:
1163 if (ItemType
&& InitList
.size() == 1) {
1164 if (!isa
<ListRecTy
>(ItemType
)) {
1166 Twine("expected output type to be a list, got type '") +
1167 ItemType
->getAsString() + "'");
1170 if (!ArgType
->getListTy()->typeIsConvertibleTo(ItemType
)) {
1171 Error(OpLoc
, Twine("expected first arg type to be '") +
1172 ArgType
->getAsString() +
1173 "', got value of type '" +
1174 cast
<ListRecTy
>(ItemType
)
1181 if (InitList
.size() == 2 && !isa
<IntRecTy
>(ArgType
)) {
1182 Error(InitLoc
, Twine("expected second parameter to be an int, got "
1183 "value of type '") +
1184 ArgType
->getAsString() + "'");
1187 ArgType
= nullptr; // Broken invariant: types not identical.
1191 if (!ArgType
->typeIsConvertibleTo(IntRecTy::get()) &&
1192 !ArgType
->typeIsConvertibleTo(StringRecTy::get())) {
1193 Error(InitLoc
, Twine("expected int, bits, or string; got value of "
1194 "type '") + ArgType
->getAsString() + "'");
1198 default: llvm_unreachable("other ops have fixed argument types");
1201 RecTy
*Resolved
= resolveTypes(ArgType
, ListType
);
1203 Error(InitLoc
, Twine("expected value of type '") +
1204 ArgType
->getAsString() + "', got '" +
1205 ListType
->getAsString() + "'");
1208 if (Code
!= BinOpInit::ADD
&& Code
!= BinOpInit::AND
&&
1209 Code
!= BinOpInit::OR
&& Code
!= BinOpInit::SRA
&&
1210 Code
!= BinOpInit::SRL
&& Code
!= BinOpInit::SHL
&&
1211 Code
!= BinOpInit::MUL
)
1215 if (Lex
.getCode() != tgtok::comma
)
1217 Lex
.Lex(); // eat the ','
1220 if (Lex
.getCode() != tgtok::r_paren
) {
1221 TokError("expected ')' in operator");
1224 Lex
.Lex(); // eat the ')'
1226 // listconcat returns a list with type of the argument.
1227 if (Code
== BinOpInit::LISTCONCAT
)
1229 // listsplat returns a list of type of the *first* argument.
1230 if (Code
== BinOpInit::LISTSPLAT
)
1231 Type
= cast
<TypedInit
>(InitList
.front())->getType()->getListTy();
1233 // We allow multiple operands to associative operators like !strconcat as
1234 // shorthand for nesting them.
1235 if (Code
== BinOpInit::STRCONCAT
|| Code
== BinOpInit::LISTCONCAT
||
1236 Code
== BinOpInit::CONCAT
|| Code
== BinOpInit::ADD
||
1237 Code
== BinOpInit::AND
|| Code
== BinOpInit::OR
||
1238 Code
== BinOpInit::MUL
) {
1239 while (InitList
.size() > 2) {
1240 Init
*RHS
= InitList
.pop_back_val();
1241 RHS
= (BinOpInit::get(Code
, InitList
.back(), RHS
, Type
))->Fold(CurRec
);
1242 InitList
.back() = RHS
;
1246 if (InitList
.size() == 2)
1247 return (BinOpInit::get(Code
, InitList
[0], InitList
[1], Type
))
1250 Error(OpLoc
, "expected two operands to operator");
1254 case tgtok::XForEach
: { // Value ::= !foreach '(' Id ',' Value ',' Value ')'
1255 SMLoc OpLoc
= Lex
.getLoc();
1256 Lex
.Lex(); // eat the operation
1257 if (Lex
.getCode() != tgtok::l_paren
) {
1258 TokError("expected '(' after !foreach");
1262 if (Lex
.Lex() != tgtok::Id
) { // eat the '('
1263 TokError("first argument of !foreach must be an identifier");
1267 Init
*LHS
= StringInit::get(Lex
.getCurStrVal());
1269 if (CurRec
&& CurRec
->getValue(LHS
)) {
1270 TokError((Twine("iteration variable '") + LHS
->getAsString() +
1271 "' already defined")
1276 if (Lex
.Lex() != tgtok::comma
) { // eat the id
1277 TokError("expected ',' in ternary operator");
1280 Lex
.Lex(); // eat the ','
1282 Init
*MHS
= ParseValue(CurRec
);
1286 if (Lex
.getCode() != tgtok::comma
) {
1287 TokError("expected ',' in ternary operator");
1290 Lex
.Lex(); // eat the ','
1292 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
1294 TokError("could not get type of !foreach input");
1298 RecTy
*InEltType
= nullptr;
1299 RecTy
*OutEltType
= nullptr;
1302 if (ListRecTy
*InListTy
= dyn_cast
<ListRecTy
>(MHSt
->getType())) {
1303 InEltType
= InListTy
->getElementType();
1305 if (ListRecTy
*OutListTy
= dyn_cast
<ListRecTy
>(ItemType
)) {
1306 OutEltType
= OutListTy
->getElementType();
1309 "expected value of type '" + Twine(ItemType
->getAsString()) +
1310 "', but got !foreach of list type");
1314 } else if (DagRecTy
*InDagTy
= dyn_cast
<DagRecTy
>(MHSt
->getType())) {
1315 InEltType
= InDagTy
;
1316 if (ItemType
&& !isa
<DagRecTy
>(ItemType
)) {
1318 "expected value of type '" + Twine(ItemType
->getAsString()) +
1319 "', but got !foreach of dag type");
1324 TokError("!foreach must have list or dag input");
1328 // We need to create a temporary record to provide a scope for the iteration
1329 // variable while parsing top-level foreach's.
1330 std::unique_ptr
<Record
> ParseRecTmp
;
1331 Record
*ParseRec
= CurRec
;
1333 ParseRecTmp
= std::make_unique
<Record
>(".parse", ArrayRef
<SMLoc
>{}, Records
);
1334 ParseRec
= ParseRecTmp
.get();
1337 ParseRec
->addValue(RecordVal(LHS
, InEltType
, false));
1338 Init
*RHS
= ParseValue(ParseRec
, OutEltType
);
1339 ParseRec
->removeValue(LHS
);
1343 if (Lex
.getCode() != tgtok::r_paren
) {
1344 TokError("expected ')' in binary operator");
1347 Lex
.Lex(); // eat the ')'
1351 OutType
= InEltType
;
1353 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
1355 TokError("could not get type of !foreach result");
1358 OutType
= RHSt
->getType()->getListTy();
1361 return (TernOpInit::get(TernOpInit::FOREACH
, LHS
, MHS
, RHS
, OutType
))
1367 case tgtok::XSubst
: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1368 TernOpInit::TernaryOp Code
;
1369 RecTy
*Type
= nullptr;
1371 tgtok::TokKind LexCode
= Lex
.getCode();
1372 Lex
.Lex(); // eat the operation
1374 default: llvm_unreachable("Unhandled code!");
1376 Code
= TernOpInit::DAG
;
1377 Type
= DagRecTy::get();
1381 Code
= TernOpInit::IF
;
1384 Code
= TernOpInit::SUBST
;
1387 if (Lex
.getCode() != tgtok::l_paren
) {
1388 TokError("expected '(' after ternary operator");
1391 Lex
.Lex(); // eat the '('
1393 Init
*LHS
= ParseValue(CurRec
);
1394 if (!LHS
) return nullptr;
1396 if (Lex
.getCode() != tgtok::comma
) {
1397 TokError("expected ',' in ternary operator");
1400 Lex
.Lex(); // eat the ','
1402 SMLoc MHSLoc
= Lex
.getLoc();
1403 Init
*MHS
= ParseValue(CurRec
, ItemType
);
1407 if (Lex
.getCode() != tgtok::comma
) {
1408 TokError("expected ',' in ternary operator");
1411 Lex
.Lex(); // eat the ','
1413 SMLoc RHSLoc
= Lex
.getLoc();
1414 Init
*RHS
= ParseValue(CurRec
, ItemType
);
1418 if (Lex
.getCode() != tgtok::r_paren
) {
1419 TokError("expected ')' in binary operator");
1422 Lex
.Lex(); // eat the ')'
1425 default: llvm_unreachable("Unhandled code!");
1427 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
1428 if (!MHSt
&& !isa
<UnsetInit
>(MHS
)) {
1429 Error(MHSLoc
, "could not determine type of the child list in !dag");
1432 if (MHSt
&& !isa
<ListRecTy
>(MHSt
->getType())) {
1433 Error(MHSLoc
, Twine("expected list of children, got type '") +
1434 MHSt
->getType()->getAsString() + "'");
1438 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
1439 if (!RHSt
&& !isa
<UnsetInit
>(RHS
)) {
1440 Error(RHSLoc
, "could not determine type of the name list in !dag");
1443 if (RHSt
&& StringRecTy::get()->getListTy() != RHSt
->getType()) {
1444 Error(RHSLoc
, Twine("expected list<string>, got type '") +
1445 RHSt
->getType()->getAsString() + "'");
1449 if (!MHSt
&& !RHSt
) {
1451 "cannot have both unset children and unset names in !dag");
1457 RecTy
*MHSTy
= nullptr;
1458 RecTy
*RHSTy
= nullptr;
1460 if (TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
))
1461 MHSTy
= MHSt
->getType();
1462 if (BitsInit
*MHSbits
= dyn_cast
<BitsInit
>(MHS
))
1463 MHSTy
= BitsRecTy::get(MHSbits
->getNumBits());
1464 if (isa
<BitInit
>(MHS
))
1465 MHSTy
= BitRecTy::get();
1467 if (TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
))
1468 RHSTy
= RHSt
->getType();
1469 if (BitsInit
*RHSbits
= dyn_cast
<BitsInit
>(RHS
))
1470 RHSTy
= BitsRecTy::get(RHSbits
->getNumBits());
1471 if (isa
<BitInit
>(RHS
))
1472 RHSTy
= BitRecTy::get();
1474 // For UnsetInit, it's typed from the other hand.
1475 if (isa
<UnsetInit
>(MHS
))
1477 if (isa
<UnsetInit
>(RHS
))
1480 if (!MHSTy
|| !RHSTy
) {
1481 TokError("could not get type for !if");
1485 Type
= resolveTypes(MHSTy
, RHSTy
);
1487 TokError(Twine("inconsistent types '") + MHSTy
->getAsString() +
1488 "' and '" + RHSTy
->getAsString() + "' for !if");
1493 case tgtok::XSubst
: {
1494 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
1496 TokError("could not get type for !subst");
1499 Type
= RHSt
->getType();
1503 return (TernOpInit::get(Code
, LHS
, MHS
, RHS
, Type
))->Fold(CurRec
);
1507 return ParseOperationCond(CurRec
, ItemType
);
1509 case tgtok::XFoldl
: {
1510 // Value ::= !foldl '(' Id ',' Id ',' Value ',' Value ',' Value ')'
1511 Lex
.Lex(); // eat the operation
1512 if (Lex
.getCode() != tgtok::l_paren
) {
1513 TokError("expected '(' after !foldl");
1516 Lex
.Lex(); // eat the '('
1518 Init
*StartUntyped
= ParseValue(CurRec
);
1522 TypedInit
*Start
= dyn_cast
<TypedInit
>(StartUntyped
);
1524 TokError(Twine("could not get type of !foldl start: '") +
1525 StartUntyped
->getAsString() + "'");
1529 if (Lex
.getCode() != tgtok::comma
) {
1530 TokError("expected ',' in !foldl");
1533 Lex
.Lex(); // eat the ','
1535 Init
*ListUntyped
= ParseValue(CurRec
);
1539 TypedInit
*List
= dyn_cast
<TypedInit
>(ListUntyped
);
1541 TokError(Twine("could not get type of !foldl list: '") +
1542 ListUntyped
->getAsString() + "'");
1546 ListRecTy
*ListType
= dyn_cast
<ListRecTy
>(List
->getType());
1548 TokError(Twine("!foldl list must be a list, but is of type '") +
1549 List
->getType()->getAsString());
1553 if (Lex
.getCode() != tgtok::comma
) {
1554 TokError("expected ',' in !foldl");
1558 if (Lex
.Lex() != tgtok::Id
) { // eat the ','
1559 TokError("third argument of !foldl must be an identifier");
1563 Init
*A
= StringInit::get(Lex
.getCurStrVal());
1564 if (CurRec
&& CurRec
->getValue(A
)) {
1565 TokError((Twine("left !foldl variable '") + A
->getAsString() +
1566 "' already defined")
1571 if (Lex
.Lex() != tgtok::comma
) { // eat the id
1572 TokError("expected ',' in !foldl");
1576 if (Lex
.Lex() != tgtok::Id
) { // eat the ','
1577 TokError("fourth argument of !foldl must be an identifier");
1581 Init
*B
= StringInit::get(Lex
.getCurStrVal());
1582 if (CurRec
&& CurRec
->getValue(B
)) {
1583 TokError((Twine("right !foldl variable '") + B
->getAsString() +
1584 "' already defined")
1589 if (Lex
.Lex() != tgtok::comma
) { // eat the id
1590 TokError("expected ',' in !foldl");
1593 Lex
.Lex(); // eat the ','
1595 // We need to create a temporary record to provide a scope for the iteration
1596 // variable while parsing top-level foreach's.
1597 std::unique_ptr
<Record
> ParseRecTmp
;
1598 Record
*ParseRec
= CurRec
;
1600 ParseRecTmp
= std::make_unique
<Record
>(".parse", ArrayRef
<SMLoc
>{}, Records
);
1601 ParseRec
= ParseRecTmp
.get();
1604 ParseRec
->addValue(RecordVal(A
, Start
->getType(), false));
1605 ParseRec
->addValue(RecordVal(B
, ListType
->getElementType(), false));
1606 Init
*ExprUntyped
= ParseValue(ParseRec
);
1607 ParseRec
->removeValue(A
);
1608 ParseRec
->removeValue(B
);
1612 TypedInit
*Expr
= dyn_cast
<TypedInit
>(ExprUntyped
);
1614 TokError("could not get type of !foldl expression");
1618 if (Expr
->getType() != Start
->getType()) {
1619 TokError(Twine("!foldl expression must be of same type as start (") +
1620 Start
->getType()->getAsString() + "), but is of type " +
1621 Expr
->getType()->getAsString());
1625 if (Lex
.getCode() != tgtok::r_paren
) {
1626 TokError("expected ')' in fold operator");
1629 Lex
.Lex(); // eat the ')'
1631 return FoldOpInit::get(Start
, List
, A
, B
, Expr
, Start
->getType())
1637 /// ParseOperatorType - Parse a type for an operator. This returns
1640 /// OperatorType ::= '<' Type '>'
1642 RecTy
*TGParser::ParseOperatorType() {
1643 RecTy
*Type
= nullptr;
1645 if (Lex
.getCode() != tgtok::less
) {
1646 TokError("expected type name for operator");
1649 Lex
.Lex(); // eat the <
1654 TokError("expected type name for operator");
1658 if (Lex
.getCode() != tgtok::greater
) {
1659 TokError("expected type name for operator");
1662 Lex
.Lex(); // eat the >
1667 Init
*TGParser::ParseOperationCond(Record
*CurRec
, RecTy
*ItemType
) {
1668 Lex
.Lex(); // eat the operation 'cond'
1670 if (Lex
.getCode() != tgtok::l_paren
) {
1671 TokError("expected '(' after !cond operator");
1674 Lex
.Lex(); // eat the '('
1676 // Parse through '[Case: Val,]+'
1677 SmallVector
<Init
*, 4> Case
;
1678 SmallVector
<Init
*, 4> Val
;
1680 if (Lex
.getCode() == tgtok::r_paren
) {
1681 Lex
.Lex(); // eat the ')'
1685 Init
*V
= ParseValue(CurRec
);
1690 if (Lex
.getCode() != tgtok::colon
) {
1691 TokError("expected ':' following a condition in !cond operator");
1694 Lex
.Lex(); // eat the ':'
1696 V
= ParseValue(CurRec
, ItemType
);
1701 if (Lex
.getCode() == tgtok::r_paren
) {
1702 Lex
.Lex(); // eat the ')'
1706 if (Lex
.getCode() != tgtok::comma
) {
1707 TokError("expected ',' or ')' following a value in !cond operator");
1710 Lex
.Lex(); // eat the ','
1713 if (Case
.size() < 1) {
1714 TokError("there should be at least 1 'condition : value' in the !cond operator");
1719 RecTy
*Type
= nullptr;
1720 for (Init
*V
: Val
) {
1721 RecTy
*VTy
= nullptr;
1722 if (TypedInit
*Vt
= dyn_cast
<TypedInit
>(V
))
1723 VTy
= Vt
->getType();
1724 if (BitsInit
*Vbits
= dyn_cast
<BitsInit
>(V
))
1725 VTy
= BitsRecTy::get(Vbits
->getNumBits());
1726 if (isa
<BitInit
>(V
))
1727 VTy
= BitRecTy::get();
1729 if (Type
== nullptr) {
1730 if (!isa
<UnsetInit
>(V
))
1733 if (!isa
<UnsetInit
>(V
)) {
1734 RecTy
*RType
= resolveTypes(Type
, VTy
);
1736 TokError(Twine("inconsistent types '") + Type
->getAsString() +
1737 "' and '" + VTy
->getAsString() + "' for !cond");
1746 TokError("could not determine type for !cond from its arguments");
1749 return CondOpInit::get(Case
, Val
, Type
)->Fold(CurRec
);
1752 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1754 /// SimpleValue ::= IDValue
1755 /// SimpleValue ::= INTVAL
1756 /// SimpleValue ::= STRVAL+
1757 /// SimpleValue ::= CODEFRAGMENT
1758 /// SimpleValue ::= '?'
1759 /// SimpleValue ::= '{' ValueList '}'
1760 /// SimpleValue ::= ID '<' ValueListNE '>'
1761 /// SimpleValue ::= '[' ValueList ']'
1762 /// SimpleValue ::= '(' IDValue DagArgList ')'
1763 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1764 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1765 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1766 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1767 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1768 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1769 /// SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')'
1770 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1771 /// SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
1773 Init
*TGParser::ParseSimpleValue(Record
*CurRec
, RecTy
*ItemType
,
1776 switch (Lex
.getCode()) {
1777 default: TokError("Unknown token when parsing a value"); break;
1779 // This is a leading paste operation. This is deprecated but
1780 // still exists in some .td files. Ignore it.
1781 Lex
.Lex(); // Skip '#'.
1782 return ParseSimpleValue(CurRec
, ItemType
, Mode
);
1783 case tgtok::IntVal
: R
= IntInit::get(Lex
.getCurIntVal()); Lex
.Lex(); break;
1784 case tgtok::BinaryIntVal
: {
1785 auto BinaryVal
= Lex
.getCurBinaryIntVal();
1786 SmallVector
<Init
*, 16> Bits(BinaryVal
.second
);
1787 for (unsigned i
= 0, e
= BinaryVal
.second
; i
!= e
; ++i
)
1788 Bits
[i
] = BitInit::get(BinaryVal
.first
& (1LL << i
));
1789 R
= BitsInit::get(Bits
);
1793 case tgtok::StrVal
: {
1794 std::string Val
= Lex
.getCurStrVal();
1797 // Handle multiple consecutive concatenated strings.
1798 while (Lex
.getCode() == tgtok::StrVal
) {
1799 Val
+= Lex
.getCurStrVal();
1803 R
= StringInit::get(Val
);
1806 case tgtok::CodeFragment
:
1807 R
= CodeInit::get(Lex
.getCurStrVal(), Lex
.getLoc());
1810 case tgtok::question
:
1811 R
= UnsetInit::get();
1815 SMLoc NameLoc
= Lex
.getLoc();
1816 StringInit
*Name
= StringInit::get(Lex
.getCurStrVal());
1817 if (Lex
.Lex() != tgtok::less
) // consume the Id.
1818 return ParseIDValue(CurRec
, Name
, NameLoc
, Mode
); // Value ::= IDValue
1820 // Value ::= ID '<' ValueListNE '>'
1821 if (Lex
.Lex() == tgtok::greater
) {
1822 TokError("expected non-empty value list");
1826 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1827 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1829 Record
*Class
= Records
.getClass(Name
->getValue());
1831 Error(NameLoc
, "Expected a class name, got '" + Name
->getValue() + "'");
1835 SmallVector
<Init
*, 8> Args
;
1836 ParseValueList(Args
, CurRec
, Class
);
1837 if (Args
.empty()) return nullptr;
1839 if (Lex
.getCode() != tgtok::greater
) {
1840 TokError("expected '>' at end of value list");
1843 Lex
.Lex(); // eat the '>'
1845 // Typecheck the template arguments list
1846 ArrayRef
<Init
*> ExpectedArgs
= Class
->getTemplateArgs();
1847 if (ExpectedArgs
.size() < Args
.size()) {
1849 "More template args specified than expected");
1853 for (unsigned i
= 0, e
= ExpectedArgs
.size(); i
!= e
; ++i
) {
1854 RecordVal
*ExpectedArg
= Class
->getValue(ExpectedArgs
[i
]);
1855 if (i
< Args
.size()) {
1856 if (TypedInit
*TI
= dyn_cast
<TypedInit
>(Args
[i
])) {
1857 RecTy
*ExpectedType
= ExpectedArg
->getType();
1858 if (!TI
->getType()->typeIsConvertibleTo(ExpectedType
)) {
1860 "Value specified for template argument #" + Twine(i
) + " (" +
1861 ExpectedArg
->getNameInitAsString() + ") is of type '" +
1862 TI
->getType()->getAsString() + "', expected '" +
1863 ExpectedType
->getAsString() + "': " + TI
->getAsString());
1868 } else if (ExpectedArg
->getValue()->isComplete())
1872 "Value not specified for template argument #" + Twine(i
) + " (" +
1873 ExpectedArgs
[i
]->getAsUnquotedString() + ")");
1877 return VarDefInit::get(Class
, Args
)->Fold();
1879 case tgtok::l_brace
: { // Value ::= '{' ValueList '}'
1880 SMLoc BraceLoc
= Lex
.getLoc();
1881 Lex
.Lex(); // eat the '{'
1882 SmallVector
<Init
*, 16> Vals
;
1884 if (Lex
.getCode() != tgtok::r_brace
) {
1885 ParseValueList(Vals
, CurRec
);
1886 if (Vals
.empty()) return nullptr;
1888 if (Lex
.getCode() != tgtok::r_brace
) {
1889 TokError("expected '}' at end of bit list value");
1892 Lex
.Lex(); // eat the '}'
1894 SmallVector
<Init
*, 16> NewBits
;
1896 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1897 // first. We'll first read everything in to a vector, then we can reverse
1898 // it to get the bits in the correct order for the BitsInit value.
1899 for (unsigned i
= 0, e
= Vals
.size(); i
!= e
; ++i
) {
1900 // FIXME: The following two loops would not be duplicated
1901 // if the API was a little more orthogonal.
1903 // bits<n> values are allowed to initialize n bits.
1904 if (BitsInit
*BI
= dyn_cast
<BitsInit
>(Vals
[i
])) {
1905 for (unsigned i
= 0, e
= BI
->getNumBits(); i
!= e
; ++i
)
1906 NewBits
.push_back(BI
->getBit((e
- i
) - 1));
1909 // bits<n> can also come from variable initializers.
1910 if (VarInit
*VI
= dyn_cast
<VarInit
>(Vals
[i
])) {
1911 if (BitsRecTy
*BitsRec
= dyn_cast
<BitsRecTy
>(VI
->getType())) {
1912 for (unsigned i
= 0, e
= BitsRec
->getNumBits(); i
!= e
; ++i
)
1913 NewBits
.push_back(VI
->getBit((e
- i
) - 1));
1916 // Fallthrough to try convert this to a bit.
1918 // All other values must be convertible to just a single bit.
1919 Init
*Bit
= Vals
[i
]->getCastTo(BitRecTy::get());
1921 Error(BraceLoc
, "Element #" + Twine(i
) + " (" + Vals
[i
]->getAsString() +
1922 ") is not convertable to a bit");
1925 NewBits
.push_back(Bit
);
1927 std::reverse(NewBits
.begin(), NewBits
.end());
1928 return BitsInit::get(NewBits
);
1930 case tgtok::l_square
: { // Value ::= '[' ValueList ']'
1931 Lex
.Lex(); // eat the '['
1932 SmallVector
<Init
*, 16> Vals
;
1934 RecTy
*DeducedEltTy
= nullptr;
1935 ListRecTy
*GivenListTy
= nullptr;
1938 ListRecTy
*ListType
= dyn_cast
<ListRecTy
>(ItemType
);
1940 TokError(Twine("Type mismatch for list, expected list type, got ") +
1941 ItemType
->getAsString());
1944 GivenListTy
= ListType
;
1947 if (Lex
.getCode() != tgtok::r_square
) {
1948 ParseValueList(Vals
, CurRec
, nullptr,
1949 GivenListTy
? GivenListTy
->getElementType() : nullptr);
1950 if (Vals
.empty()) return nullptr;
1952 if (Lex
.getCode() != tgtok::r_square
) {
1953 TokError("expected ']' at end of list value");
1956 Lex
.Lex(); // eat the ']'
1958 RecTy
*GivenEltTy
= nullptr;
1959 if (Lex
.getCode() == tgtok::less
) {
1960 // Optional list element type
1961 Lex
.Lex(); // eat the '<'
1963 GivenEltTy
= ParseType();
1965 // Couldn't parse element type
1969 if (Lex
.getCode() != tgtok::greater
) {
1970 TokError("expected '>' at end of list element type");
1973 Lex
.Lex(); // eat the '>'
1977 RecTy
*EltTy
= nullptr;
1978 for (Init
*V
: Vals
) {
1979 TypedInit
*TArg
= dyn_cast
<TypedInit
>(V
);
1982 EltTy
= resolveTypes(EltTy
, TArg
->getType());
1984 TokError("Incompatible types in list elements");
1988 EltTy
= TArg
->getType();
1995 // Verify consistency
1996 if (!EltTy
->typeIsConvertibleTo(GivenEltTy
)) {
1997 TokError("Incompatible types in list elements");
2006 TokError("No type for list");
2009 DeducedEltTy
= GivenListTy
->getElementType();
2011 // Make sure the deduced type is compatible with the given type
2013 if (!EltTy
->typeIsConvertibleTo(GivenListTy
->getElementType())) {
2014 TokError(Twine("Element type mismatch for list: element type '") +
2015 EltTy
->getAsString() + "' not convertible to '" +
2016 GivenListTy
->getElementType()->getAsString());
2020 DeducedEltTy
= EltTy
;
2023 return ListInit::get(Vals
, DeducedEltTy
);
2025 case tgtok::l_paren
: { // Value ::= '(' IDValue DagArgList ')'
2026 Lex
.Lex(); // eat the '('
2027 if (Lex
.getCode() != tgtok::Id
&& Lex
.getCode() != tgtok::XCast
) {
2028 TokError("expected identifier in dag init");
2032 Init
*Operator
= ParseValue(CurRec
);
2033 if (!Operator
) return nullptr;
2035 // If the operator name is present, parse it.
2036 StringInit
*OperatorName
= nullptr;
2037 if (Lex
.getCode() == tgtok::colon
) {
2038 if (Lex
.Lex() != tgtok::VarName
) { // eat the ':'
2039 TokError("expected variable name in dag operator");
2042 OperatorName
= StringInit::get(Lex
.getCurStrVal());
2043 Lex
.Lex(); // eat the VarName.
2046 SmallVector
<std::pair
<llvm::Init
*, StringInit
*>, 8> DagArgs
;
2047 if (Lex
.getCode() != tgtok::r_paren
) {
2048 ParseDagArgList(DagArgs
, CurRec
);
2049 if (DagArgs
.empty()) return nullptr;
2052 if (Lex
.getCode() != tgtok::r_paren
) {
2053 TokError("expected ')' in dag init");
2056 Lex
.Lex(); // eat the ')'
2058 return DagInit::get(Operator
, OperatorName
, DagArgs
);
2065 case tgtok::XCast
: // Value ::= !unop '(' Value ')'
2067 case tgtok::XConcat
:
2082 case tgtok::XListConcat
:
2083 case tgtok::XListSplat
:
2084 case tgtok::XStrConcat
: // Value ::= !binop '(' Value ',' Value ')'
2088 case tgtok::XForEach
:
2089 case tgtok::XSubst
: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
2090 return ParseOperation(CurRec
, ItemType
);
2097 /// ParseValue - Parse a tblgen value. This returns null on error.
2099 /// Value ::= SimpleValue ValueSuffix*
2100 /// ValueSuffix ::= '{' BitList '}'
2101 /// ValueSuffix ::= '[' BitList ']'
2102 /// ValueSuffix ::= '.' ID
2104 Init
*TGParser::ParseValue(Record
*CurRec
, RecTy
*ItemType
, IDParseMode Mode
) {
2105 Init
*Result
= ParseSimpleValue(CurRec
, ItemType
, Mode
);
2106 if (!Result
) return nullptr;
2108 // Parse the suffixes now if present.
2110 switch (Lex
.getCode()) {
2111 default: return Result
;
2112 case tgtok::l_brace
: {
2113 if (Mode
== ParseNameMode
)
2114 // This is the beginning of the object body.
2117 SMLoc CurlyLoc
= Lex
.getLoc();
2118 Lex
.Lex(); // eat the '{'
2119 SmallVector
<unsigned, 16> Ranges
;
2120 ParseRangeList(Ranges
);
2121 if (Ranges
.empty()) return nullptr;
2123 // Reverse the bitlist.
2124 std::reverse(Ranges
.begin(), Ranges
.end());
2125 Result
= Result
->convertInitializerBitRange(Ranges
);
2127 Error(CurlyLoc
, "Invalid bit range for value");
2132 if (Lex
.getCode() != tgtok::r_brace
) {
2133 TokError("expected '}' at end of bit range list");
2139 case tgtok::l_square
: {
2140 SMLoc SquareLoc
= Lex
.getLoc();
2141 Lex
.Lex(); // eat the '['
2142 SmallVector
<unsigned, 16> Ranges
;
2143 ParseRangeList(Ranges
);
2144 if (Ranges
.empty()) return nullptr;
2146 Result
= Result
->convertInitListSlice(Ranges
);
2148 Error(SquareLoc
, "Invalid range for list slice");
2153 if (Lex
.getCode() != tgtok::r_square
) {
2154 TokError("expected ']' at end of list slice");
2160 case tgtok::period
: {
2161 if (Lex
.Lex() != tgtok::Id
) { // eat the .
2162 TokError("expected field identifier after '.'");
2165 StringInit
*FieldName
= StringInit::get(Lex
.getCurStrVal());
2166 if (!Result
->getFieldType(FieldName
)) {
2167 TokError("Cannot access field '" + Lex
.getCurStrVal() + "' of value '" +
2168 Result
->getAsString() + "'");
2171 Result
= FieldInit::get(Result
, FieldName
)->Fold(CurRec
);
2172 Lex
.Lex(); // eat field name
2177 SMLoc PasteLoc
= Lex
.getLoc();
2178 TypedInit
*LHS
= dyn_cast
<TypedInit
>(Result
);
2180 Error(PasteLoc
, "LHS of paste is not typed!");
2184 // Check if it's a 'listA # listB'
2185 if (isa
<ListRecTy
>(LHS
->getType())) {
2186 Lex
.Lex(); // Eat the '#'.
2188 switch (Lex
.getCode()) {
2191 case tgtok::l_brace
:
2192 Result
= LHS
; // trailing paste, ignore.
2195 Init
*RHSResult
= ParseValue(CurRec
, ItemType
, ParseNameMode
);
2196 Result
= BinOpInit::getListConcat(LHS
, RHSResult
);
2201 // Create a !strconcat() operation, first casting each operand to
2202 // a string if necessary.
2203 if (LHS
->getType() != StringRecTy::get()) {
2204 auto CastLHS
= dyn_cast
<TypedInit
>(
2205 UnOpInit::get(UnOpInit::CAST
, LHS
, StringRecTy::get())
2209 Twine("can't cast '") + LHS
->getAsString() + "' to string");
2215 TypedInit
*RHS
= nullptr;
2217 Lex
.Lex(); // Eat the '#'.
2218 switch (Lex
.getCode()) {
2221 case tgtok::l_brace
:
2222 // These are all of the tokens that can begin an object body.
2223 // Some of these can also begin values but we disallow those cases
2224 // because they are unlikely to be useful.
2226 // Trailing paste, concat with an empty string.
2227 RHS
= StringInit::get("");
2231 Init
*RHSResult
= ParseValue(CurRec
, nullptr, ParseNameMode
);
2232 RHS
= dyn_cast
<TypedInit
>(RHSResult
);
2234 Error(PasteLoc
, "RHS of paste is not typed!");
2238 if (RHS
->getType() != StringRecTy::get()) {
2239 auto CastRHS
= dyn_cast
<TypedInit
>(
2240 UnOpInit::get(UnOpInit::CAST
, RHS
, StringRecTy::get())
2244 Twine("can't cast '") + RHS
->getAsString() + "' to string");
2253 Result
= BinOpInit::getStrConcat(LHS
, RHS
);
2259 /// ParseDagArgList - Parse the argument list for a dag literal expression.
2261 /// DagArg ::= Value (':' VARNAME)?
2262 /// DagArg ::= VARNAME
2263 /// DagArgList ::= DagArg
2264 /// DagArgList ::= DagArgList ',' DagArg
2265 void TGParser::ParseDagArgList(
2266 SmallVectorImpl
<std::pair
<llvm::Init
*, StringInit
*>> &Result
,
2270 // DagArg ::= VARNAME
2271 if (Lex
.getCode() == tgtok::VarName
) {
2272 // A missing value is treated like '?'.
2273 StringInit
*VarName
= StringInit::get(Lex
.getCurStrVal());
2274 Result
.emplace_back(UnsetInit::get(), VarName
);
2277 // DagArg ::= Value (':' VARNAME)?
2278 Init
*Val
= ParseValue(CurRec
);
2284 // If the variable name is present, add it.
2285 StringInit
*VarName
= nullptr;
2286 if (Lex
.getCode() == tgtok::colon
) {
2287 if (Lex
.Lex() != tgtok::VarName
) { // eat the ':'
2288 TokError("expected variable name in dag literal");
2292 VarName
= StringInit::get(Lex
.getCurStrVal());
2293 Lex
.Lex(); // eat the VarName.
2296 Result
.push_back(std::make_pair(Val
, VarName
));
2298 if (Lex
.getCode() != tgtok::comma
) break;
2299 Lex
.Lex(); // eat the ','
2303 /// ParseValueList - Parse a comma separated list of values, returning them as a
2304 /// vector. Note that this always expects to be able to parse at least one
2305 /// value. It returns an empty list if this is not possible.
2307 /// ValueList ::= Value (',' Value)
2309 void TGParser::ParseValueList(SmallVectorImpl
<Init
*> &Result
, Record
*CurRec
,
2310 Record
*ArgsRec
, RecTy
*EltTy
) {
2311 RecTy
*ItemType
= EltTy
;
2312 unsigned int ArgN
= 0;
2313 if (ArgsRec
&& !EltTy
) {
2314 ArrayRef
<Init
*> TArgs
= ArgsRec
->getTemplateArgs();
2315 if (TArgs
.empty()) {
2316 TokError("template argument provided to non-template class");
2320 const RecordVal
*RV
= ArgsRec
->getValue(TArgs
[ArgN
]);
2322 errs() << "Cannot find template arg " << ArgN
<< " (" << TArgs
[ArgN
]
2325 assert(RV
&& "Template argument record not found??");
2326 ItemType
= RV
->getType();
2329 Result
.push_back(ParseValue(CurRec
, ItemType
));
2330 if (!Result
.back()) {
2335 while (Lex
.getCode() == tgtok::comma
) {
2336 Lex
.Lex(); // Eat the comma
2338 // ignore trailing comma for lists
2339 if (Lex
.getCode() == tgtok::r_square
)
2342 if (ArgsRec
&& !EltTy
) {
2343 ArrayRef
<Init
*> TArgs
= ArgsRec
->getTemplateArgs();
2344 if (ArgN
>= TArgs
.size()) {
2345 TokError("too many template arguments");
2349 const RecordVal
*RV
= ArgsRec
->getValue(TArgs
[ArgN
]);
2350 assert(RV
&& "Template argument record not found??");
2351 ItemType
= RV
->getType();
2354 Result
.push_back(ParseValue(CurRec
, ItemType
));
2355 if (!Result
.back()) {
2362 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
2363 /// empty string on error. This can happen in a number of different context's,
2364 /// including within a def or in the template args for a def (which which case
2365 /// CurRec will be non-null) and within the template args for a multiclass (in
2366 /// which case CurRec will be null, but CurMultiClass will be set). This can
2367 /// also happen within a def that is within a multiclass, which will set both
2368 /// CurRec and CurMultiClass.
2370 /// Declaration ::= FIELD? Type ID ('=' Value)?
2372 Init
*TGParser::ParseDeclaration(Record
*CurRec
,
2373 bool ParsingTemplateArgs
) {
2374 // Read the field prefix if present.
2375 bool HasField
= Lex
.getCode() == tgtok::Field
;
2376 if (HasField
) Lex
.Lex();
2378 RecTy
*Type
= ParseType();
2379 if (!Type
) return nullptr;
2381 if (Lex
.getCode() != tgtok::Id
) {
2382 TokError("Expected identifier in declaration");
2386 std::string Str
= Lex
.getCurStrVal();
2387 if (Str
== "NAME") {
2388 TokError("'" + Str
+ "' is a reserved variable name");
2392 SMLoc IdLoc
= Lex
.getLoc();
2393 Init
*DeclName
= StringInit::get(Str
);
2396 if (ParsingTemplateArgs
) {
2398 DeclName
= QualifyName(*CurRec
, CurMultiClass
, DeclName
, ":");
2400 assert(CurMultiClass
);
2402 DeclName
= QualifyName(CurMultiClass
->Rec
, CurMultiClass
, DeclName
,
2407 if (AddValue(CurRec
, IdLoc
, RecordVal(DeclName
, Type
, HasField
)))
2410 // If a value is present, parse it.
2411 if (Lex
.getCode() == tgtok::equal
) {
2413 SMLoc ValLoc
= Lex
.getLoc();
2414 Init
*Val
= ParseValue(CurRec
, Type
);
2416 SetValue(CurRec
, ValLoc
, DeclName
, None
, Val
))
2417 // Return the name, even if an error is thrown. This is so that we can
2418 // continue to make some progress, even without the value having been
2426 /// ParseForeachDeclaration - Read a foreach declaration, returning
2427 /// the name of the declared object or a NULL Init on error. Return
2428 /// the name of the parsed initializer list through ForeachListName.
2430 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
2431 /// ForeachDeclaration ::= ID '=' RangePiece
2432 /// ForeachDeclaration ::= ID '=' Value
2434 VarInit
*TGParser::ParseForeachDeclaration(Init
*&ForeachListValue
) {
2435 if (Lex
.getCode() != tgtok::Id
) {
2436 TokError("Expected identifier in foreach declaration");
2440 Init
*DeclName
= StringInit::get(Lex
.getCurStrVal());
2443 // If a value is present, parse it.
2444 if (Lex
.getCode() != tgtok::equal
) {
2445 TokError("Expected '=' in foreach declaration");
2448 Lex
.Lex(); // Eat the '='
2450 RecTy
*IterType
= nullptr;
2451 SmallVector
<unsigned, 16> Ranges
;
2453 switch (Lex
.getCode()) {
2454 case tgtok::l_brace
: { // '{' RangeList '}'
2455 Lex
.Lex(); // eat the '{'
2456 ParseRangeList(Ranges
);
2457 if (Lex
.getCode() != tgtok::r_brace
) {
2458 TokError("expected '}' at end of bit range list");
2466 SMLoc ValueLoc
= Lex
.getLoc();
2467 Init
*I
= ParseValue(nullptr);
2471 TypedInit
*TI
= dyn_cast
<TypedInit
>(I
);
2472 if (TI
&& isa
<ListRecTy
>(TI
->getType())) {
2473 ForeachListValue
= I
;
2474 IterType
= cast
<ListRecTy
>(TI
->getType())->getElementType();
2479 if (ParseRangePiece(Ranges
, TI
))
2486 Type
= (Twine("' of type '") + TI
->getType()->getAsString()).str();
2487 Error(ValueLoc
, "expected a list, got '" + I
->getAsString() + Type
+ "'");
2488 if (CurMultiClass
) {
2489 PrintNote({}, "references to multiclass template arguments cannot be "
2490 "resolved at this time");
2497 if (!Ranges
.empty()) {
2498 assert(!IterType
&& "Type already initialized?");
2499 IterType
= IntRecTy::get();
2500 std::vector
<Init
*> Values
;
2501 for (unsigned R
: Ranges
)
2502 Values
.push_back(IntInit::get(R
));
2503 ForeachListValue
= ListInit::get(Values
, IterType
);
2509 return VarInit::get(DeclName
, IterType
);
2512 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
2513 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
2514 /// template args for a def, which may or may not be in a multiclass. If null,
2515 /// these are the template args for a multiclass.
2517 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
2519 bool TGParser::ParseTemplateArgList(Record
*CurRec
) {
2520 assert(Lex
.getCode() == tgtok::less
&& "Not a template arg list!");
2521 Lex
.Lex(); // eat the '<'
2523 Record
*TheRecToAddTo
= CurRec
? CurRec
: &CurMultiClass
->Rec
;
2525 // Read the first declaration.
2526 Init
*TemplArg
= ParseDeclaration(CurRec
, true/*templateargs*/);
2530 TheRecToAddTo
->addTemplateArg(TemplArg
);
2532 while (Lex
.getCode() == tgtok::comma
) {
2533 Lex
.Lex(); // eat the ','
2535 // Read the following declarations.
2536 SMLoc Loc
= Lex
.getLoc();
2537 TemplArg
= ParseDeclaration(CurRec
, true/*templateargs*/);
2541 if (TheRecToAddTo
->isTemplateArg(TemplArg
))
2542 return Error(Loc
, "template argument with the same name has already been "
2545 TheRecToAddTo
->addTemplateArg(TemplArg
);
2548 if (Lex
.getCode() != tgtok::greater
)
2549 return TokError("expected '>' at end of template argument list");
2550 Lex
.Lex(); // eat the '>'.
2554 /// ParseBodyItem - Parse a single item at within the body of a def or class.
2556 /// BodyItem ::= Declaration ';'
2557 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
2558 bool TGParser::ParseBodyItem(Record
*CurRec
) {
2559 if (Lex
.getCode() != tgtok::Let
) {
2560 if (!ParseDeclaration(CurRec
, false))
2563 if (Lex
.getCode() != tgtok::semi
)
2564 return TokError("expected ';' after declaration");
2569 // LET ID OptionalRangeList '=' Value ';'
2570 if (Lex
.Lex() != tgtok::Id
)
2571 return TokError("expected field identifier after let");
2573 SMLoc IdLoc
= Lex
.getLoc();
2574 StringInit
*FieldName
= StringInit::get(Lex
.getCurStrVal());
2575 Lex
.Lex(); // eat the field name.
2577 SmallVector
<unsigned, 16> BitList
;
2578 if (ParseOptionalBitList(BitList
))
2580 std::reverse(BitList
.begin(), BitList
.end());
2582 if (Lex
.getCode() != tgtok::equal
)
2583 return TokError("expected '=' in let expression");
2584 Lex
.Lex(); // eat the '='.
2586 RecordVal
*Field
= CurRec
->getValue(FieldName
);
2588 return TokError("Value '" + FieldName
->getValue() + "' unknown!");
2590 RecTy
*Type
= Field
->getType();
2592 Init
*Val
= ParseValue(CurRec
, Type
);
2593 if (!Val
) return true;
2595 if (Lex
.getCode() != tgtok::semi
)
2596 return TokError("expected ';' after let expression");
2599 return SetValue(CurRec
, IdLoc
, FieldName
, BitList
, Val
);
2602 /// ParseBody - Read the body of a class or def. Return true on error, false on
2606 /// Body ::= '{' BodyList '}'
2607 /// BodyList BodyItem*
2609 bool TGParser::ParseBody(Record
*CurRec
) {
2610 // If this is a null definition, just eat the semi and return.
2611 if (Lex
.getCode() == tgtok::semi
) {
2616 if (Lex
.getCode() != tgtok::l_brace
)
2617 return TokError("Expected ';' or '{' to start body");
2621 while (Lex
.getCode() != tgtok::r_brace
)
2622 if (ParseBodyItem(CurRec
))
2630 /// Apply the current let bindings to \a CurRec.
2631 /// \returns true on error, false otherwise.
2632 bool TGParser::ApplyLetStack(Record
*CurRec
) {
2633 for (SmallVectorImpl
<LetRecord
> &LetInfo
: LetStack
)
2634 for (LetRecord
&LR
: LetInfo
)
2635 if (SetValue(CurRec
, LR
.Loc
, LR
.Name
, LR
.Bits
, LR
.Value
))
2640 bool TGParser::ApplyLetStack(RecordsEntry
&Entry
) {
2642 return ApplyLetStack(Entry
.Rec
.get());
2644 for (auto &E
: Entry
.Loop
->Entries
) {
2645 if (ApplyLetStack(E
))
2652 /// ParseObjectBody - Parse the body of a def or class. This consists of an
2653 /// optional ClassList followed by a Body. CurRec is the current def or class
2654 /// that is being parsed.
2656 /// ObjectBody ::= BaseClassList Body
2657 /// BaseClassList ::= /*empty*/
2658 /// BaseClassList ::= ':' BaseClassListNE
2659 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
2661 bool TGParser::ParseObjectBody(Record
*CurRec
) {
2662 // If there is a baseclass list, read it.
2663 if (Lex
.getCode() == tgtok::colon
) {
2666 // Read all of the subclasses.
2667 SubClassReference SubClass
= ParseSubClassReference(CurRec
, false);
2670 if (!SubClass
.Rec
) return true;
2673 if (AddSubClass(CurRec
, SubClass
))
2676 if (Lex
.getCode() != tgtok::comma
) break;
2677 Lex
.Lex(); // eat ','.
2678 SubClass
= ParseSubClassReference(CurRec
, false);
2682 if (ApplyLetStack(CurRec
))
2685 return ParseBody(CurRec
);
2688 /// ParseDef - Parse and return a top level or multiclass def, return the record
2689 /// corresponding to it. This returns null on error.
2691 /// DefInst ::= DEF ObjectName ObjectBody
2693 bool TGParser::ParseDef(MultiClass
*CurMultiClass
) {
2694 SMLoc DefLoc
= Lex
.getLoc();
2695 assert(Lex
.getCode() == tgtok::Def
&& "Unknown tok");
2696 Lex
.Lex(); // Eat the 'def' token.
2698 // Parse ObjectName and make a record for it.
2699 std::unique_ptr
<Record
> CurRec
;
2700 Init
*Name
= ParseObjectName(CurMultiClass
);
2704 if (isa
<UnsetInit
>(Name
))
2705 CurRec
= std::make_unique
<Record
>(Records
.getNewAnonymousName(), DefLoc
, Records
,
2706 /*Anonymous=*/true);
2708 CurRec
= std::make_unique
<Record
>(Name
, DefLoc
, Records
);
2710 if (ParseObjectBody(CurRec
.get()))
2713 return addEntry(std::move(CurRec
));
2716 /// ParseDefset - Parse a defset statement.
2718 /// Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
2720 bool TGParser::ParseDefset() {
2721 assert(Lex
.getCode() == tgtok::Defset
);
2722 Lex
.Lex(); // Eat the 'defset' token
2724 DefsetRecord Defset
;
2725 Defset
.Loc
= Lex
.getLoc();
2726 RecTy
*Type
= ParseType();
2729 if (!isa
<ListRecTy
>(Type
))
2730 return Error(Defset
.Loc
, "expected list type");
2731 Defset
.EltTy
= cast
<ListRecTy
>(Type
)->getElementType();
2733 if (Lex
.getCode() != tgtok::Id
)
2734 return TokError("expected identifier");
2735 StringInit
*DeclName
= StringInit::get(Lex
.getCurStrVal());
2736 if (Records
.getGlobal(DeclName
->getValue()))
2737 return TokError("def or global variable of this name already exists");
2739 if (Lex
.Lex() != tgtok::equal
) // Eat the identifier
2740 return TokError("expected '='");
2741 if (Lex
.Lex() != tgtok::l_brace
) // Eat the '='
2742 return TokError("expected '{'");
2743 SMLoc BraceLoc
= Lex
.getLoc();
2744 Lex
.Lex(); // Eat the '{'
2746 Defsets
.push_back(&Defset
);
2747 bool Err
= ParseObjectList(nullptr);
2752 if (Lex
.getCode() != tgtok::r_brace
) {
2753 TokError("expected '}' at end of defset");
2754 return Error(BraceLoc
, "to match this '{'");
2756 Lex
.Lex(); // Eat the '}'
2758 Records
.addExtraGlobal(DeclName
->getValue(),
2759 ListInit::get(Defset
.Elements
, Defset
.EltTy
));
2763 /// ParseForeach - Parse a for statement. Return the record corresponding
2764 /// to it. This returns true on error.
2766 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2767 /// Foreach ::= FOREACH Declaration IN Object
2769 bool TGParser::ParseForeach(MultiClass
*CurMultiClass
) {
2770 SMLoc Loc
= Lex
.getLoc();
2771 assert(Lex
.getCode() == tgtok::Foreach
&& "Unknown tok");
2772 Lex
.Lex(); // Eat the 'for' token.
2774 // Make a temporary object to record items associated with the for
2776 Init
*ListValue
= nullptr;
2777 VarInit
*IterName
= ParseForeachDeclaration(ListValue
);
2779 return TokError("expected declaration in for");
2781 if (Lex
.getCode() != tgtok::In
)
2782 return TokError("Unknown tok");
2783 Lex
.Lex(); // Eat the in
2785 // Create a loop object and remember it.
2786 Loops
.push_back(std::make_unique
<ForeachLoop
>(Loc
, IterName
, ListValue
));
2788 if (Lex
.getCode() != tgtok::l_brace
) {
2789 // FOREACH Declaration IN Object
2790 if (ParseObject(CurMultiClass
))
2793 SMLoc BraceLoc
= Lex
.getLoc();
2794 // Otherwise, this is a group foreach.
2795 Lex
.Lex(); // eat the '{'.
2797 // Parse the object list.
2798 if (ParseObjectList(CurMultiClass
))
2801 if (Lex
.getCode() != tgtok::r_brace
) {
2802 TokError("expected '}' at end of foreach command");
2803 return Error(BraceLoc
, "to match this '{'");
2805 Lex
.Lex(); // Eat the }
2808 // Resolve the loop or store it for later resolution.
2809 std::unique_ptr
<ForeachLoop
> Loop
= std::move(Loops
.back());
2812 return addEntry(std::move(Loop
));
2815 /// ParseClass - Parse a tblgen class definition.
2817 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2819 bool TGParser::ParseClass() {
2820 assert(Lex
.getCode() == tgtok::Class
&& "Unexpected token!");
2823 if (Lex
.getCode() != tgtok::Id
)
2824 return TokError("expected class name after 'class' keyword");
2826 Record
*CurRec
= Records
.getClass(Lex
.getCurStrVal());
2828 // If the body was previously defined, this is an error.
2829 if (!CurRec
->getValues().empty() ||
2830 !CurRec
->getSuperClasses().empty() ||
2831 !CurRec
->getTemplateArgs().empty())
2832 return TokError("Class '" + CurRec
->getNameInitAsString() +
2833 "' already defined");
2835 // If this is the first reference to this class, create and add it.
2837 std::make_unique
<Record
>(Lex
.getCurStrVal(), Lex
.getLoc(), Records
,
2839 CurRec
= NewRec
.get();
2840 Records
.addClass(std::move(NewRec
));
2842 Lex
.Lex(); // eat the name.
2844 // If there are template args, parse them.
2845 if (Lex
.getCode() == tgtok::less
)
2846 if (ParseTemplateArgList(CurRec
))
2849 return ParseObjectBody(CurRec
);
2852 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2855 /// LetList ::= LetItem (',' LetItem)*
2856 /// LetItem ::= ID OptionalRangeList '=' Value
2858 void TGParser::ParseLetList(SmallVectorImpl
<LetRecord
> &Result
) {
2860 if (Lex
.getCode() != tgtok::Id
) {
2861 TokError("expected identifier in let definition");
2866 StringInit
*Name
= StringInit::get(Lex
.getCurStrVal());
2867 SMLoc NameLoc
= Lex
.getLoc();
2868 Lex
.Lex(); // Eat the identifier.
2870 // Check for an optional RangeList.
2871 SmallVector
<unsigned, 16> Bits
;
2872 if (ParseOptionalRangeList(Bits
)) {
2876 std::reverse(Bits
.begin(), Bits
.end());
2878 if (Lex
.getCode() != tgtok::equal
) {
2879 TokError("expected '=' in let expression");
2883 Lex
.Lex(); // eat the '='.
2885 Init
*Val
= ParseValue(nullptr);
2891 // Now that we have everything, add the record.
2892 Result
.emplace_back(Name
, Bits
, Val
, NameLoc
);
2894 if (Lex
.getCode() != tgtok::comma
)
2896 Lex
.Lex(); // eat the comma.
2900 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2901 /// different related productions. This works inside multiclasses too.
2903 /// Object ::= LET LetList IN '{' ObjectList '}'
2904 /// Object ::= LET LetList IN Object
2906 bool TGParser::ParseTopLevelLet(MultiClass
*CurMultiClass
) {
2907 assert(Lex
.getCode() == tgtok::Let
&& "Unexpected token");
2910 // Add this entry to the let stack.
2911 SmallVector
<LetRecord
, 8> LetInfo
;
2912 ParseLetList(LetInfo
);
2913 if (LetInfo
.empty()) return true;
2914 LetStack
.push_back(std::move(LetInfo
));
2916 if (Lex
.getCode() != tgtok::In
)
2917 return TokError("expected 'in' at end of top-level 'let'");
2920 // If this is a scalar let, just handle it now
2921 if (Lex
.getCode() != tgtok::l_brace
) {
2922 // LET LetList IN Object
2923 if (ParseObject(CurMultiClass
))
2925 } else { // Object ::= LETCommand '{' ObjectList '}'
2926 SMLoc BraceLoc
= Lex
.getLoc();
2927 // Otherwise, this is a group let.
2928 Lex
.Lex(); // eat the '{'.
2930 // Parse the object list.
2931 if (ParseObjectList(CurMultiClass
))
2934 if (Lex
.getCode() != tgtok::r_brace
) {
2935 TokError("expected '}' at end of top level let command");
2936 return Error(BraceLoc
, "to match this '{'");
2941 // Outside this let scope, this let block is not active.
2942 LetStack
.pop_back();
2946 /// ParseMultiClass - Parse a multiclass definition.
2948 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2949 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2950 /// MultiClassObject ::= DefInst
2951 /// MultiClassObject ::= MultiClassInst
2952 /// MultiClassObject ::= DefMInst
2953 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
2954 /// MultiClassObject ::= LETCommand Object
2956 bool TGParser::ParseMultiClass() {
2957 assert(Lex
.getCode() == tgtok::MultiClass
&& "Unexpected token");
2958 Lex
.Lex(); // Eat the multiclass token.
2960 if (Lex
.getCode() != tgtok::Id
)
2961 return TokError("expected identifier after multiclass for name");
2962 std::string Name
= Lex
.getCurStrVal();
2965 MultiClasses
.insert(std::make_pair(Name
,
2966 std::make_unique
<MultiClass
>(Name
, Lex
.getLoc(),Records
)));
2969 return TokError("multiclass '" + Name
+ "' already defined");
2971 CurMultiClass
= Result
.first
->second
.get();
2972 Lex
.Lex(); // Eat the identifier.
2974 // If there are template args, parse them.
2975 if (Lex
.getCode() == tgtok::less
)
2976 if (ParseTemplateArgList(nullptr))
2979 bool inherits
= false;
2981 // If there are submulticlasses, parse them.
2982 if (Lex
.getCode() == tgtok::colon
) {
2987 // Read all of the submulticlasses.
2988 SubMultiClassReference SubMultiClass
=
2989 ParseSubMultiClassReference(CurMultiClass
);
2992 if (!SubMultiClass
.MC
) return true;
2995 if (AddSubMultiClass(CurMultiClass
, SubMultiClass
))
2998 if (Lex
.getCode() != tgtok::comma
) break;
2999 Lex
.Lex(); // eat ','.
3000 SubMultiClass
= ParseSubMultiClassReference(CurMultiClass
);
3004 if (Lex
.getCode() != tgtok::l_brace
) {
3006 return TokError("expected '{' in multiclass definition");
3007 if (Lex
.getCode() != tgtok::semi
)
3008 return TokError("expected ';' in multiclass definition");
3009 Lex
.Lex(); // eat the ';'.
3011 if (Lex
.Lex() == tgtok::r_brace
) // eat the '{'.
3012 return TokError("multiclass must contain at least one def");
3014 while (Lex
.getCode() != tgtok::r_brace
) {
3015 switch (Lex
.getCode()) {
3017 return TokError("expected 'let', 'def', 'defm' or 'foreach' in "
3022 case tgtok::Foreach
:
3023 if (ParseObject(CurMultiClass
))
3028 Lex
.Lex(); // eat the '}'.
3031 CurMultiClass
= nullptr;
3035 /// ParseDefm - Parse the instantiation of a multiclass.
3037 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
3039 bool TGParser::ParseDefm(MultiClass
*CurMultiClass
) {
3040 assert(Lex
.getCode() == tgtok::Defm
&& "Unexpected token!");
3041 Lex
.Lex(); // eat the defm
3043 Init
*DefmName
= ParseObjectName(CurMultiClass
);
3046 if (isa
<UnsetInit
>(DefmName
)) {
3047 DefmName
= Records
.getNewAnonymousName();
3049 DefmName
= BinOpInit::getStrConcat(
3050 VarInit::get(QualifiedNameOfImplicitName(CurMultiClass
),
3051 StringRecTy::get()),
3055 if (Lex
.getCode() != tgtok::colon
)
3056 return TokError("expected ':' after defm identifier");
3058 // Keep track of the new generated record definitions.
3059 std::vector
<RecordsEntry
> NewEntries
;
3061 // This record also inherits from a regular class (non-multiclass)?
3062 bool InheritFromClass
= false;
3067 SMLoc SubClassLoc
= Lex
.getLoc();
3068 SubClassReference Ref
= ParseSubClassReference(nullptr, true);
3071 if (!Ref
.Rec
) return true;
3073 // To instantiate a multiclass, we need to first get the multiclass, then
3074 // instantiate each def contained in the multiclass with the SubClassRef
3075 // template parameters.
3076 MultiClass
*MC
= MultiClasses
[Ref
.Rec
->getName()].get();
3077 assert(MC
&& "Didn't lookup multiclass correctly?");
3078 ArrayRef
<Init
*> TemplateVals
= Ref
.TemplateArgs
;
3080 // Verify that the correct number of template arguments were specified.
3081 ArrayRef
<Init
*> TArgs
= MC
->Rec
.getTemplateArgs();
3082 if (TArgs
.size() < TemplateVals
.size())
3083 return Error(SubClassLoc
,
3084 "more template args specified than multiclass expects");
3087 for (unsigned i
= 0, e
= TArgs
.size(); i
!= e
; ++i
) {
3088 if (i
< TemplateVals
.size()) {
3089 Substs
.emplace_back(TArgs
[i
], TemplateVals
[i
]);
3091 Init
*Default
= MC
->Rec
.getValue(TArgs
[i
])->getValue();
3092 if (!Default
->isComplete()) {
3093 return Error(SubClassLoc
,
3094 "value not specified for template argument #" +
3095 Twine(i
) + " (" + TArgs
[i
]->getAsUnquotedString() +
3096 ") of multiclass '" + MC
->Rec
.getNameInitAsString() +
3099 Substs
.emplace_back(TArgs
[i
], Default
);
3103 Substs
.emplace_back(QualifiedNameOfImplicitName(MC
), DefmName
);
3105 if (resolve(MC
->Entries
, Substs
, CurMultiClass
== nullptr, &NewEntries
,
3109 if (Lex
.getCode() != tgtok::comma
) break;
3110 Lex
.Lex(); // eat ','.
3112 if (Lex
.getCode() != tgtok::Id
)
3113 return TokError("expected identifier");
3115 SubClassLoc
= Lex
.getLoc();
3117 // A defm can inherit from regular classes (non-multiclass) as
3118 // long as they come in the end of the inheritance list.
3119 InheritFromClass
= (Records
.getClass(Lex
.getCurStrVal()) != nullptr);
3121 if (InheritFromClass
)
3124 Ref
= ParseSubClassReference(nullptr, true);
3127 if (InheritFromClass
) {
3128 // Process all the classes to inherit as if they were part of a
3129 // regular 'def' and inherit all record values.
3130 SubClassReference SubClass
= ParseSubClassReference(nullptr, false);
3133 if (!SubClass
.Rec
) return true;
3135 // Get the expanded definition prototypes and teach them about
3136 // the record values the current class to inherit has
3137 for (auto &E
: NewEntries
) {
3139 if (AddSubClass(E
, SubClass
))
3143 if (Lex
.getCode() != tgtok::comma
) break;
3144 Lex
.Lex(); // eat ','.
3145 SubClass
= ParseSubClassReference(nullptr, false);
3149 for (auto &E
: NewEntries
) {
3150 if (ApplyLetStack(E
))
3153 addEntry(std::move(E
));
3156 if (Lex
.getCode() != tgtok::semi
)
3157 return TokError("expected ';' at end of defm");
3164 /// Object ::= ClassInst
3165 /// Object ::= DefInst
3166 /// Object ::= MultiClassInst
3167 /// Object ::= DefMInst
3168 /// Object ::= LETCommand '{' ObjectList '}'
3169 /// Object ::= LETCommand Object
3170 bool TGParser::ParseObject(MultiClass
*MC
) {
3171 switch (Lex
.getCode()) {
3173 return TokError("Expected class, def, defm, defset, multiclass, let or "
3175 case tgtok::Let
: return ParseTopLevelLet(MC
);
3176 case tgtok::Def
: return ParseDef(MC
);
3177 case tgtok::Foreach
: return ParseForeach(MC
);
3178 case tgtok::Defm
: return ParseDefm(MC
);
3181 return TokError("defset is not allowed inside multiclass");
3182 return ParseDefset();
3185 return TokError("class is not allowed inside multiclass");
3187 return TokError("class is not allowed inside foreach loop");
3188 return ParseClass();
3189 case tgtok::MultiClass
:
3191 return TokError("multiclass is not allowed inside foreach loop");
3192 return ParseMultiClass();
3197 /// ObjectList :== Object*
3198 bool TGParser::ParseObjectList(MultiClass
*MC
) {
3199 while (isObjectStart(Lex
.getCode())) {
3200 if (ParseObject(MC
))
3206 bool TGParser::ParseFile() {
3207 Lex
.Lex(); // Prime the lexer.
3208 if (ParseObjectList()) return true;
3210 // If we have unread input at the end of the file, report it.
3211 if (Lex
.getCode() == tgtok::Eof
)
3214 return TokError("Unexpected input at top level");
3217 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3218 LLVM_DUMP_METHOD
void RecordsEntry::dump() const {
3225 LLVM_DUMP_METHOD
void ForeachLoop::dump() const {
3226 errs() << "foreach " << IterVar
->getAsString() << " = "
3227 << ListValue
->getAsString() << " in {\n";
3229 for (const auto &E
: Entries
)
3235 LLVM_DUMP_METHOD
void MultiClass::dump() const {
3236 errs() << "Record:\n";
3239 errs() << "Defs:\n";
3240 for (const auto &E
: Entries
)