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/DenseMapInfo.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/Config/llvm-config.h"
19 #include "llvm/Support/Casting.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/raw_ostream.h"
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.
96 if (RV
.isNonconcreteOK())
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
, Init
*Name
,
116 RecordKeeper
&RK
= CurRec
.getRecords();
117 Init
*NewName
= BinOpInit::getStrConcat(CurRec
.getNameInit(),
118 StringInit::get(RK
, Scoper
));
119 NewName
= BinOpInit::getStrConcat(NewName
, Name
);
120 if (CurMultiClass
&& Scoper
!= "::") {
121 Init
*Prefix
= BinOpInit::getStrConcat(CurMultiClass
->Rec
.getNameInit(),
122 StringInit::get(RK
, "::"));
123 NewName
= BinOpInit::getStrConcat(Prefix
, NewName
);
126 if (BinOpInit
*BinOp
= dyn_cast
<BinOpInit
>(NewName
))
127 NewName
= BinOp
->Fold(&CurRec
);
131 /// Return the qualified version of the implicit 'NAME' template argument.
132 static Init
*QualifiedNameOfImplicitName(Record
&Rec
,
133 MultiClass
*MC
= nullptr) {
134 return QualifyName(Rec
, MC
, StringInit::get(Rec
.getRecords(), "NAME"),
138 static Init
*QualifiedNameOfImplicitName(MultiClass
*MC
) {
139 return QualifiedNameOfImplicitName(MC
->Rec
, MC
);
142 bool TGParser::AddValue(Record
*CurRec
, SMLoc Loc
, const RecordVal
&RV
) {
144 CurRec
= &CurMultiClass
->Rec
;
146 if (RecordVal
*ERV
= CurRec
->getValue(RV
.getNameInit())) {
147 // The value already exists in the class, treat this as a set.
148 if (ERV
->setValue(RV
.getValue()))
149 return Error(Loc
, "New definition of '" + RV
.getName() + "' of type '" +
150 RV
.getType()->getAsString() + "' is incompatible with " +
151 "previous definition of type '" +
152 ERV
->getType()->getAsString() + "'");
154 CurRec
->addValue(RV
);
160 /// Return true on error, false on success.
161 bool TGParser::SetValue(Record
*CurRec
, SMLoc Loc
, Init
*ValName
,
162 ArrayRef
<unsigned> BitList
, Init
*V
,
163 bool AllowSelfAssignment
, bool OverrideDefLoc
) {
164 if (!V
) return false;
166 if (!CurRec
) CurRec
= &CurMultiClass
->Rec
;
168 RecordVal
*RV
= CurRec
->getValue(ValName
);
170 return Error(Loc
, "Value '" + ValName
->getAsUnquotedString() +
173 // Do not allow assignments like 'X = X'. This will just cause infinite loops
174 // in the resolution machinery.
176 if (VarInit
*VI
= dyn_cast
<VarInit
>(V
))
177 if (VI
->getNameInit() == ValName
&& !AllowSelfAssignment
)
178 return Error(Loc
, "Recursion / self-assignment forbidden");
180 // If we are assigning to a subset of the bits in the value... then we must be
181 // assigning to a field of BitsRecTy, which must have a BitsInit
184 if (!BitList
.empty()) {
185 BitsInit
*CurVal
= dyn_cast
<BitsInit
>(RV
->getValue());
187 return Error(Loc
, "Value '" + ValName
->getAsUnquotedString() +
188 "' is not a bits type");
190 // Convert the incoming value to a bits type of the appropriate size...
191 Init
*BI
= V
->getCastTo(BitsRecTy::get(Records
, BitList
.size()));
193 return Error(Loc
, "Initializer is not compatible with bit range");
195 SmallVector
<Init
*, 16> NewBits(CurVal
->getNumBits());
197 // Loop over bits, assigning values as appropriate.
198 for (unsigned i
= 0, e
= BitList
.size(); i
!= e
; ++i
) {
199 unsigned Bit
= BitList
[i
];
201 return Error(Loc
, "Cannot set bit #" + Twine(Bit
) + " of value '" +
202 ValName
->getAsUnquotedString() + "' more than once");
203 NewBits
[Bit
] = BI
->getBit(i
);
206 for (unsigned i
= 0, e
= CurVal
->getNumBits(); i
!= e
; ++i
)
208 NewBits
[i
] = CurVal
->getBit(i
);
210 V
= BitsInit::get(Records
, NewBits
);
213 if (OverrideDefLoc
? RV
->setValue(V
, Loc
) : RV
->setValue(V
)) {
214 std::string InitType
;
215 if (BitsInit
*BI
= dyn_cast
<BitsInit
>(V
))
216 InitType
= (Twine("' of type bit initializer with length ") +
217 Twine(BI
->getNumBits())).str();
218 else if (TypedInit
*TI
= dyn_cast
<TypedInit
>(V
))
219 InitType
= (Twine("' of type '") + TI
->getType()->getAsString()).str();
220 return Error(Loc
, "Field '" + ValName
->getAsUnquotedString() +
221 "' of type '" + RV
->getType()->getAsString() +
222 "' is incompatible with value '" +
223 V
->getAsString() + InitType
+ "'");
228 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
229 /// args as SubClass's template arguments.
230 bool TGParser::AddSubClass(Record
*CurRec
, SubClassReference
&SubClass
) {
231 Record
*SC
= SubClass
.Rec
;
232 MapResolver
R(CurRec
);
234 // Loop over all the subclass record's fields. Add template arguments
235 // to the resolver map. Add regular fields to the new record.
236 for (const RecordVal
&Field
: SC
->getValues()) {
237 if (Field
.isTemplateArg()) {
238 R
.set(Field
.getNameInit(), Field
.getValue());
240 if (AddValue(CurRec
, SubClass
.RefRange
.Start
, Field
))
245 ArrayRef
<Init
*> TArgs
= SC
->getTemplateArgs();
246 assert(SubClass
.TemplateArgs
.size() <= TArgs
.size() &&
247 "Too many template arguments allowed");
249 // Loop over the template argument names. If a value was specified,
250 // reset the map value. If not and there was no default, complain.
251 for (unsigned I
= 0, E
= TArgs
.size(); I
!= E
; ++I
) {
252 if (I
< SubClass
.TemplateArgs
.size())
253 R
.set(TArgs
[I
], SubClass
.TemplateArgs
[I
]);
254 else if (!R
.isComplete(TArgs
[I
]))
255 return Error(SubClass
.RefRange
.Start
,
256 "Value not specified for template argument '" +
257 TArgs
[I
]->getAsUnquotedString() + "' (#" + Twine(I
) +
258 ") of parent class '" + SC
->getNameInitAsString() + "'");
261 // Copy the subclass record's assertions to the new record.
262 CurRec
->appendAssertions(SC
);
265 if (CurRec
->isClass())
266 Name
= VarInit::get(QualifiedNameOfImplicitName(*CurRec
),
267 StringRecTy::get(Records
));
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
);
298 for (auto &E
: Entry
.Loop
->Entries
) {
299 if (AddSubClass(E
, SubClass
))
306 /// AddSubMultiClass - Add SubMultiClass as a subclass to
307 /// CurMC, resolving its template args as SubMultiClass's
308 /// template arguments.
309 bool TGParser::AddSubMultiClass(MultiClass
*CurMC
,
310 SubMultiClassReference
&SubMultiClass
) {
311 MultiClass
*SMC
= SubMultiClass
.MC
;
313 ArrayRef
<Init
*> SMCTArgs
= SMC
->Rec
.getTemplateArgs();
314 if (SMCTArgs
.size() < SubMultiClass
.TemplateArgs
.size())
315 return Error(SubMultiClass
.RefRange
.Start
,
316 "More template args specified than expected");
318 // Prepare the mapping of template argument name to value, filling in default
319 // values if necessary.
320 SubstStack TemplateArgs
;
321 for (unsigned i
= 0, e
= SMCTArgs
.size(); i
!= e
; ++i
) {
322 if (i
< SubMultiClass
.TemplateArgs
.size()) {
323 TemplateArgs
.emplace_back(SMCTArgs
[i
], SubMultiClass
.TemplateArgs
[i
]);
325 Init
*Default
= SMC
->Rec
.getValue(SMCTArgs
[i
])->getValue();
326 if (!Default
->isComplete()) {
327 return Error(SubMultiClass
.RefRange
.Start
,
328 "value not specified for template argument #" + Twine(i
) +
329 " (" + SMCTArgs
[i
]->getAsUnquotedString() +
330 ") of multiclass '" + SMC
->Rec
.getNameInitAsString() +
333 TemplateArgs
.emplace_back(SMCTArgs
[i
], Default
);
337 TemplateArgs
.emplace_back(QualifiedNameOfImplicitName(SMC
),
338 VarInit::get(QualifiedNameOfImplicitName(CurMC
),
339 StringRecTy::get(Records
)));
341 // Add all of the defs in the subclass into the current multiclass.
342 return resolve(SMC
->Entries
, TemplateArgs
, false, &CurMC
->Entries
);
345 /// Add a record, foreach loop, or assertion to the current context.
346 bool TGParser::addEntry(RecordsEntry E
) {
347 assert((!!E
.Rec
+ !!E
.Loop
+ !!E
.Assertion
) == 1 &&
348 "RecordsEntry has invalid number of items");
350 // If we are parsing a loop, add it to the loop's entries.
351 if (!Loops
.empty()) {
352 Loops
.back()->Entries
.push_back(std::move(E
));
356 // If it is a loop, then resolve and perform the loop.
359 return resolve(*E
.Loop
, Stack
, CurMultiClass
== nullptr,
360 CurMultiClass
? &CurMultiClass
->Entries
: nullptr);
363 // If we are parsing a multiclass, add it to the multiclass's entries.
365 CurMultiClass
->Entries
.push_back(std::move(E
));
369 // If it is an assertion, then it's a top-level one, so check it.
371 CheckAssert(E
.Assertion
->Loc
, E
.Assertion
->Condition
, E
.Assertion
->Message
);
375 // It must be a record, so finish it off.
376 return addDefOne(std::move(E
.Rec
));
379 /// Resolve the entries in \p Loop, going over inner loops recursively
380 /// and making the given subsitutions of (name, value) pairs.
382 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
383 /// are added to the global record keeper.
384 bool TGParser::resolve(const ForeachLoop
&Loop
, SubstStack
&Substs
,
385 bool Final
, std::vector
<RecordsEntry
> *Dest
,
389 for (const auto &S
: Substs
)
390 R
.set(S
.first
, S
.second
);
391 Init
*List
= Loop
.ListValue
->resolveReferences(R
);
393 // For if-then-else blocks, we lower to a foreach loop whose list is a
394 // ternary selection between lists of different length. Since we don't
395 // have a means to track variable length record lists, we *must* resolve
396 // the condition here. We want to defer final resolution of the arms
397 // until the resulting records are finalized.
398 // e.g. !if(!exists<SchedWrite>("__does_not_exist__"), [1], [])
399 if (auto *TI
= dyn_cast
<TernOpInit
>(List
);
400 TI
&& TI
->getOpcode() == TernOpInit::IF
&& Final
) {
401 Init
*OldLHS
= TI
->getLHS();
403 Init
*LHS
= OldLHS
->resolveReferences(R
);
406 Twine("unable to resolve if condition '") +
407 LHS
->getAsString() + "' at end of containing scope");
410 Init
*MHS
= TI
->getMHS();
411 Init
*RHS
= TI
->getRHS();
412 List
= TernOpInit::get(TernOpInit::IF
, LHS
, MHS
, RHS
, TI
->getType())
416 auto LI
= dyn_cast
<ListInit
>(List
);
419 Dest
->emplace_back(std::make_unique
<ForeachLoop
>(Loop
.Loc
, Loop
.IterVar
,
421 return resolve(Loop
.Entries
, Substs
, Final
, &Dest
->back().Loop
->Entries
,
425 PrintError(Loop
.Loc
, Twine("attempting to loop over '") +
426 List
->getAsString() + "', expected a list");
431 for (auto *Elt
: *LI
) {
433 Substs
.emplace_back(Loop
.IterVar
->getNameInit(), Elt
);
434 Error
= resolve(Loop
.Entries
, Substs
, Final
, Dest
);
443 /// Resolve the entries in \p Source, going over loops recursively and
444 /// making the given substitutions of (name, value) pairs.
446 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
447 /// are added to the global record keeper.
448 bool TGParser::resolve(const std::vector
<RecordsEntry
> &Source
,
449 SubstStack
&Substs
, bool Final
,
450 std::vector
<RecordsEntry
> *Dest
, SMLoc
*Loc
) {
452 for (auto &E
: Source
) {
454 Error
= resolve(*E
.Loop
, Substs
, Final
, Dest
);
456 } else if (E
.Assertion
) {
458 for (const auto &S
: Substs
)
459 R
.set(S
.first
, S
.second
);
460 Init
*Condition
= E
.Assertion
->Condition
->resolveReferences(R
);
461 Init
*Message
= E
.Assertion
->Message
->resolveReferences(R
);
464 Dest
->push_back(std::make_unique
<Record::AssertionInfo
>(
465 E
.Assertion
->Loc
, Condition
, Message
));
467 CheckAssert(E
.Assertion
->Loc
, Condition
, Message
);
470 auto Rec
= std::make_unique
<Record
>(*E
.Rec
);
472 Rec
->appendLoc(*Loc
);
474 MapResolver
R(Rec
.get());
475 for (const auto &S
: Substs
)
476 R
.set(S
.first
, S
.second
);
477 Rec
->resolveReferences(R
);
480 Dest
->push_back(std::move(Rec
));
482 Error
= addDefOne(std::move(Rec
));
490 /// Resolve the record fully and add it to the record keeper.
491 bool TGParser::addDefOne(std::unique_ptr
<Record
> Rec
) {
492 Init
*NewName
= nullptr;
493 if (Record
*Prev
= Records
.getDef(Rec
->getNameInitAsString())) {
494 if (!Rec
->isAnonymous()) {
495 PrintError(Rec
->getLoc(),
496 "def already exists: " + Rec
->getNameInitAsString());
497 PrintNote(Prev
->getLoc(), "location of previous definition");
500 NewName
= Records
.getNewAnonymousName();
503 Rec
->resolveReferences(NewName
);
506 if (!isa
<StringInit
>(Rec
->getNameInit())) {
507 PrintError(Rec
->getLoc(), Twine("record name '") +
508 Rec
->getNameInit()->getAsString() +
509 "' could not be fully resolved");
513 // Check the assertions.
514 Rec
->checkRecordAssertions();
516 // If ObjectBody has template arguments, it's an error.
517 assert(Rec
->getTemplateArgs().empty() && "How'd this get template args?");
519 for (DefsetRecord
*Defset
: Defsets
) {
520 DefInit
*I
= Rec
->getDefInit();
521 if (!I
->getType()->typeIsA(Defset
->EltTy
)) {
522 PrintError(Rec
->getLoc(), Twine("adding record of incompatible type '") +
523 I
->getType()->getAsString() +
525 PrintNote(Defset
->Loc
, "location of defset declaration");
528 Defset
->Elements
.push_back(I
);
531 Records
.addDef(std::move(Rec
));
535 //===----------------------------------------------------------------------===//
537 //===----------------------------------------------------------------------===//
539 /// isObjectStart - Return true if this is a valid first token for a statement.
540 static bool isObjectStart(tgtok::TokKind K
) {
541 return K
== tgtok::Assert
|| K
== tgtok::Class
|| K
== tgtok::Def
||
542 K
== tgtok::Defm
|| K
== tgtok::Defset
|| K
== tgtok::Defvar
||
543 K
== tgtok::Foreach
|| K
== tgtok::If
|| K
== tgtok::Let
||
544 K
== tgtok::MultiClass
;
547 bool TGParser::consume(tgtok::TokKind K
) {
548 if (Lex
.getCode() == K
) {
555 /// ParseObjectName - If a valid object name is specified, return it. If no
556 /// name is specified, return the unset initializer. Return nullptr on parse
558 /// ObjectName ::= Value [ '#' Value ]*
559 /// ObjectName ::= /*empty*/
561 Init
*TGParser::ParseObjectName(MultiClass
*CurMultiClass
) {
562 switch (Lex
.getCode()) {
566 // These are all of the tokens that can begin an object body.
567 // Some of these can also begin values but we disallow those cases
568 // because they are unlikely to be useful.
569 return UnsetInit::get(Records
);
574 Record
*CurRec
= nullptr;
576 CurRec
= &CurMultiClass
->Rec
;
578 Init
*Name
= ParseValue(CurRec
, StringRecTy::get(Records
), ParseNameMode
);
583 Init
*NameStr
= QualifiedNameOfImplicitName(CurMultiClass
);
584 HasReferenceResolver
R(NameStr
);
585 Name
->resolveReferences(R
);
587 Name
= BinOpInit::getStrConcat(
588 VarInit::get(NameStr
, StringRecTy::get(Records
)), Name
);
594 /// ParseClassID - Parse and resolve a reference to a class name. This returns
599 Record
*TGParser::ParseClassID() {
600 if (Lex
.getCode() != tgtok::Id
) {
601 TokError("expected name for ClassID");
605 Record
*Result
= Records
.getClass(Lex
.getCurStrVal());
607 std::string
Msg("Couldn't find class '" + Lex
.getCurStrVal() + "'");
608 if (MultiClasses
[Lex
.getCurStrVal()].get())
609 TokError(Msg
+ ". Use 'defm' if you meant to use multiclass '" +
610 Lex
.getCurStrVal() + "'");
613 } else if (TrackReferenceLocs
) {
614 Result
->appendReferenceLoc(Lex
.getLocRange());
621 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
622 /// This returns null on error.
624 /// MultiClassID ::= ID
626 MultiClass
*TGParser::ParseMultiClassID() {
627 if (Lex
.getCode() != tgtok::Id
) {
628 TokError("expected name for MultiClassID");
632 MultiClass
*Result
= MultiClasses
[Lex
.getCurStrVal()].get();
634 TokError("Couldn't find multiclass '" + Lex
.getCurStrVal() + "'");
640 /// ParseSubClassReference - Parse a reference to a subclass or a
641 /// multiclass. This returns a SubClassRefTy with a null Record* on error.
643 /// SubClassRef ::= ClassID
644 /// SubClassRef ::= ClassID '<' ValueList '>'
646 SubClassReference
TGParser::
647 ParseSubClassReference(Record
*CurRec
, bool isDefm
) {
648 SubClassReference Result
;
649 Result
.RefRange
.Start
= Lex
.getLoc();
652 if (MultiClass
*MC
= ParseMultiClassID())
653 Result
.Rec
= &MC
->Rec
;
655 Result
.Rec
= ParseClassID();
657 if (!Result
.Rec
) return Result
;
659 // If there is no template arg list, we're done.
660 if (!consume(tgtok::less
)) {
661 Result
.RefRange
.End
= Lex
.getLoc();
665 if (ParseTemplateArgValueList(Result
.TemplateArgs
, CurRec
, Result
.Rec
)) {
666 Result
.Rec
= nullptr; // Error parsing value list.
670 if (CheckTemplateArgValues(Result
.TemplateArgs
, Result
.RefRange
.Start
,
672 Result
.Rec
= nullptr; // Error checking value list.
676 Result
.RefRange
.End
= Lex
.getLoc();
680 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
681 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
682 /// Record* on error.
684 /// SubMultiClassRef ::= MultiClassID
685 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
687 SubMultiClassReference
TGParser::
688 ParseSubMultiClassReference(MultiClass
*CurMC
) {
689 SubMultiClassReference Result
;
690 Result
.RefRange
.Start
= Lex
.getLoc();
692 Result
.MC
= ParseMultiClassID();
693 if (!Result
.MC
) return Result
;
695 // If there is no template arg list, we're done.
696 if (!consume(tgtok::less
)) {
697 Result
.RefRange
.End
= Lex
.getLoc();
701 if (ParseTemplateArgValueList(Result
.TemplateArgs
, &CurMC
->Rec
,
703 Result
.MC
= nullptr; // Error parsing value list.
707 Result
.RefRange
.End
= Lex
.getLoc();
712 /// ParseSliceElement - Parse subscript or range
714 /// SliceElement ::= Value<list<int>>
715 /// SliceElement ::= Value<int>
716 /// SliceElement ::= Value<int> '...' Value<int>
717 /// SliceElement ::= Value<int> '-' Value<int> (deprecated)
718 /// SliceElement ::= Value<int> INTVAL(Negative; deprecated)
720 /// SliceElement is either IntRecTy, ListRecTy, or nullptr
722 TypedInit
*TGParser::ParseSliceElement(Record
*CurRec
) {
723 auto LHSLoc
= Lex
.getLoc();
724 auto *CurVal
= ParseValue(CurRec
);
727 auto *LHS
= cast
<TypedInit
>(CurVal
);
729 TypedInit
*RHS
= nullptr;
730 switch (Lex
.getCode()) {
731 case tgtok::dotdotdot
:
732 case tgtok::minus
: { // Deprecated
734 auto RHSLoc
= Lex
.getLoc();
735 CurVal
= ParseValue(CurRec
);
738 RHS
= cast
<TypedInit
>(CurVal
);
739 if (!isa
<IntRecTy
>(RHS
->getType())) {
741 "expected int...int, got " + Twine(RHS
->getType()->getAsString()));
746 case tgtok::IntVal
: { // Deprecated "-num"
747 auto i
= -Lex
.getCurIntVal();
749 TokError("invalid range, cannot be negative");
752 RHS
= IntInit::get(Records
, i
);
753 Lex
.Lex(); // eat IntVal
756 default: // Single value (IntRecTy or ListRecTy)
761 assert(isa
<IntRecTy
>(RHS
->getType()));
763 // Closed-interval range <LHS:IntRecTy>...<RHS:IntRecTy>
764 if (!isa
<IntRecTy
>(LHS
->getType())) {
766 "expected int...int, got " + Twine(LHS
->getType()->getAsString()));
770 return cast
<TypedInit
>(BinOpInit::get(BinOpInit::RANGEC
, LHS
, RHS
,
771 IntRecTy::get(Records
)->getListTy())
775 /// ParseSliceElements - Parse subscripts in square brackets.
777 /// SliceElements ::= ( SliceElement ',' )* SliceElement ','?
779 /// SliceElement is either IntRecTy, ListRecTy, or nullptr
781 /// Returns ListRecTy by defaut.
782 /// Returns IntRecTy if;
784 /// - SliceElements is Value<int> w/o trailing comma
786 TypedInit
*TGParser::ParseSliceElements(Record
*CurRec
, bool Single
) {
788 SmallVector
<Init
*, 2> Elems
; // int
789 SmallVector
<TypedInit
*, 2> Slices
; // list<int>
791 auto FlushElems
= [&] {
792 if (!Elems
.empty()) {
793 Slices
.push_back(ListInit::get(Elems
, IntRecTy::get(Records
)));
799 auto LHSLoc
= Lex
.getLoc();
800 CurVal
= ParseSliceElement(CurRec
);
803 auto *CurValTy
= CurVal
->getType();
805 if (auto *ListValTy
= dyn_cast
<ListRecTy
>(CurValTy
)) {
806 if (!isa
<IntRecTy
>(ListValTy
->getElementType())) {
808 "expected list<int>, got " + Twine(ListValTy
->getAsString()));
813 Slices
.push_back(CurVal
);
816 } else if (!isa
<IntRecTy
>(CurValTy
)) {
818 "unhandled type " + Twine(CurValTy
->getAsString()) + " in range");
822 if (Lex
.getCode() != tgtok::comma
)
825 Lex
.Lex(); // eat comma
827 // `[i,]` is not LISTELEM but LISTSLICE
830 Elems
.push_back(CurVal
);
832 } while (Lex
.getCode() != tgtok::r_square
);
839 Elems
.push_back(CurVal
);
844 // Concatenate lists in Slices
845 TypedInit
*Result
= nullptr;
846 for (auto *Slice
: Slices
) {
847 Result
= (Result
? cast
<TypedInit
>(BinOpInit::getListConcat(Result
, Slice
))
854 /// ParseRangePiece - Parse a bit/value range.
855 /// RangePiece ::= INTVAL
856 /// RangePiece ::= INTVAL '...' INTVAL
857 /// RangePiece ::= INTVAL '-' INTVAL
858 /// RangePiece ::= INTVAL INTVAL
859 // The last two forms are deprecated.
860 bool TGParser::ParseRangePiece(SmallVectorImpl
<unsigned> &Ranges
,
861 TypedInit
*FirstItem
) {
862 Init
*CurVal
= FirstItem
;
864 CurVal
= ParseValue(nullptr);
866 IntInit
*II
= dyn_cast_or_null
<IntInit
>(CurVal
);
868 return TokError("expected integer or bitrange");
870 int64_t Start
= II
->getValue();
874 return TokError("invalid range, cannot be negative");
876 switch (Lex
.getCode()) {
878 Ranges
.push_back(Start
);
881 case tgtok::dotdotdot
:
885 Init
*I_End
= ParseValue(nullptr);
886 IntInit
*II_End
= dyn_cast_or_null
<IntInit
>(I_End
);
888 TokError("expected integer value as end of range");
892 End
= II_End
->getValue();
895 case tgtok::IntVal
: {
896 End
= -Lex
.getCurIntVal();
902 return TokError("invalid range, cannot be negative");
906 for (; Start
<= End
; ++Start
)
907 Ranges
.push_back(Start
);
909 for (; Start
>= End
; --Start
)
910 Ranges
.push_back(Start
);
914 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
916 /// RangeList ::= RangePiece (',' RangePiece)*
918 void TGParser::ParseRangeList(SmallVectorImpl
<unsigned> &Result
) {
919 // Parse the first piece.
920 if (ParseRangePiece(Result
)) {
924 while (consume(tgtok::comma
))
925 // Parse the next range piece.
926 if (ParseRangePiece(Result
)) {
932 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
933 /// OptionalRangeList ::= '<' RangeList '>'
934 /// OptionalRangeList ::= /*empty*/
935 bool TGParser::ParseOptionalRangeList(SmallVectorImpl
<unsigned> &Ranges
) {
936 SMLoc StartLoc
= Lex
.getLoc();
937 if (!consume(tgtok::less
))
940 // Parse the range list.
941 ParseRangeList(Ranges
);
942 if (Ranges
.empty()) return true;
944 if (!consume(tgtok::greater
)) {
945 TokError("expected '>' at end of range list");
946 return Error(StartLoc
, "to match this '<'");
951 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
952 /// OptionalBitList ::= '{' RangeList '}'
953 /// OptionalBitList ::= /*empty*/
954 bool TGParser::ParseOptionalBitList(SmallVectorImpl
<unsigned> &Ranges
) {
955 SMLoc StartLoc
= Lex
.getLoc();
956 if (!consume(tgtok::l_brace
))
959 // Parse the range list.
960 ParseRangeList(Ranges
);
961 if (Ranges
.empty()) return true;
963 if (!consume(tgtok::r_brace
)) {
964 TokError("expected '}' at end of bit list");
965 return Error(StartLoc
, "to match this '{'");
970 /// ParseType - Parse and return a tblgen type. This returns null on error.
972 /// Type ::= STRING // string type
973 /// Type ::= CODE // code type
974 /// Type ::= BIT // bit type
975 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
976 /// Type ::= INT // int type
977 /// Type ::= LIST '<' Type '>' // list<x> type
978 /// Type ::= DAG // dag type
979 /// Type ::= ClassID // Record Type
981 RecTy
*TGParser::ParseType() {
982 switch (Lex
.getCode()) {
983 default: TokError("Unknown token when expecting a type"); return nullptr;
987 return StringRecTy::get(Records
);
990 return BitRecTy::get(Records
);
993 return IntRecTy::get(Records
);
996 return DagRecTy::get(Records
);
998 if (Record
*R
= ParseClassID())
999 return RecordRecTy::get(R
);
1000 TokError("unknown class name");
1003 if (Lex
.Lex() != tgtok::less
) { // Eat 'bits'
1004 TokError("expected '<' after bits type");
1007 if (Lex
.Lex() != tgtok::IntVal
) { // Eat '<'
1008 TokError("expected integer in bits<n> type");
1011 uint64_t Val
= Lex
.getCurIntVal();
1012 if (Lex
.Lex() != tgtok::greater
) { // Eat count.
1013 TokError("expected '>' at end of bits<n> type");
1016 Lex
.Lex(); // Eat '>'
1017 return BitsRecTy::get(Records
, Val
);
1020 if (Lex
.Lex() != tgtok::less
) { // Eat 'bits'
1021 TokError("expected '<' after list type");
1024 Lex
.Lex(); // Eat '<'
1025 RecTy
*SubType
= ParseType();
1026 if (!SubType
) return nullptr;
1028 if (!consume(tgtok::greater
)) {
1029 TokError("expected '>' at end of list<ty> type");
1032 return ListRecTy::get(SubType
);
1038 Init
*TGParser::ParseIDValue(Record
*CurRec
, StringInit
*Name
, SMRange NameLoc
,
1041 if (RecordVal
*RV
= CurRec
->getValue(Name
)) {
1042 if (TrackReferenceLocs
)
1043 RV
->addReferenceLoc(NameLoc
);
1044 return VarInit::get(Name
, RV
->getType());
1048 if ((CurRec
&& CurRec
->isClass()) || CurMultiClass
) {
1049 Init
*TemplateArgName
;
1050 if (CurMultiClass
) {
1052 QualifyName(CurMultiClass
->Rec
, CurMultiClass
, Name
, "::");
1054 TemplateArgName
= QualifyName(*CurRec
, CurMultiClass
, Name
, ":");
1056 Record
*TemplateRec
= CurMultiClass
? &CurMultiClass
->Rec
: CurRec
;
1057 if (TemplateRec
->isTemplateArg(TemplateArgName
)) {
1058 RecordVal
*RV
= TemplateRec
->getValue(TemplateArgName
);
1059 assert(RV
&& "Template arg doesn't exist??");
1061 if (TrackReferenceLocs
)
1062 RV
->addReferenceLoc(NameLoc
);
1063 return VarInit::get(TemplateArgName
, RV
->getType());
1064 } else if (Name
->getValue() == "NAME") {
1065 return VarInit::get(TemplateArgName
, StringRecTy::get(Records
));
1070 if (Init
*I
= CurLocalScope
->getVar(Name
->getValue()))
1073 // If this is in a foreach loop, make sure it's not a loop iterator
1074 for (const auto &L
: Loops
) {
1076 VarInit
*IterVar
= dyn_cast
<VarInit
>(L
->IterVar
);
1077 if (IterVar
&& IterVar
->getNameInit() == Name
)
1082 if (Mode
== ParseNameMode
)
1085 if (Init
*I
= Records
.getGlobal(Name
->getValue())) {
1086 // Add a reference to the global if it's a record.
1087 if (TrackReferenceLocs
) {
1088 if (auto *Def
= dyn_cast
<DefInit
>(I
))
1089 Def
->getDef()->appendReferenceLoc(NameLoc
);
1094 // Allow self-references of concrete defs, but delay the lookup so that we
1095 // get the correct type.
1096 if (CurRec
&& !CurRec
->isClass() && !CurMultiClass
&&
1097 CurRec
->getNameInit() == Name
)
1098 return UnOpInit::get(UnOpInit::CAST
, Name
, CurRec
->getType());
1100 Error(NameLoc
.Start
, "Variable not defined: '" + Name
->getValue() + "'");
1104 /// ParseOperation - Parse an operator. This returns null on error.
1106 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
1108 Init
*TGParser::ParseOperation(Record
*CurRec
, RecTy
*ItemType
) {
1109 switch (Lex
.getCode()) {
1111 TokError("unknown bang operator");
1114 case tgtok::XToLower
:
1115 case tgtok::XToUpper
:
1122 case tgtok::XGetDagOp
: { // Value ::= !unop '(' Value ')'
1123 UnOpInit::UnaryOp Code
;
1124 RecTy
*Type
= nullptr;
1126 switch (Lex
.getCode()) {
1127 default: llvm_unreachable("Unhandled code!");
1129 Lex
.Lex(); // eat the operation
1130 Code
= UnOpInit::CAST
;
1132 Type
= ParseOperatorType();
1135 TokError("did not get type for unary operator");
1140 case tgtok::XToLower
:
1141 Lex
.Lex(); // eat the operation
1142 Code
= UnOpInit::TOLOWER
;
1143 Type
= StringRecTy::get(Records
);
1145 case tgtok::XToUpper
:
1146 Lex
.Lex(); // eat the operation
1147 Code
= UnOpInit::TOUPPER
;
1148 Type
= StringRecTy::get(Records
);
1151 Lex
.Lex(); // eat the operation
1152 Code
= UnOpInit::NOT
;
1153 Type
= IntRecTy::get(Records
);
1156 Lex
.Lex(); // eat the operation
1157 Code
= UnOpInit::LOG2
;
1158 Type
= IntRecTy::get(Records
);
1161 Lex
.Lex(); // eat the operation
1162 Code
= UnOpInit::HEAD
;
1165 Lex
.Lex(); // eat the operation
1166 Code
= UnOpInit::TAIL
;
1170 Code
= UnOpInit::SIZE
;
1171 Type
= IntRecTy::get(Records
);
1174 Lex
.Lex(); // eat the operation
1175 Code
= UnOpInit::EMPTY
;
1176 Type
= IntRecTy::get(Records
);
1178 case tgtok::XGetDagOp
:
1179 Lex
.Lex(); // eat the operation
1180 if (Lex
.getCode() == tgtok::less
) {
1181 // Parse an optional type suffix, so that you can say
1182 // !getdagop<BaseClass>(someDag) as a shorthand for
1183 // !cast<BaseClass>(!getdagop(someDag)).
1184 Type
= ParseOperatorType();
1187 TokError("did not get type for unary operator");
1191 if (!isa
<RecordRecTy
>(Type
)) {
1192 TokError("type for !getdagop must be a record type");
1193 // but keep parsing, to consume the operand
1196 Type
= RecordRecTy::get(Records
, {});
1198 Code
= UnOpInit::GETDAGOP
;
1201 if (!consume(tgtok::l_paren
)) {
1202 TokError("expected '(' after unary operator");
1206 Init
*LHS
= ParseValue(CurRec
);
1207 if (!LHS
) return nullptr;
1209 if (Code
== UnOpInit::EMPTY
|| Code
== UnOpInit::SIZE
) {
1210 ListInit
*LHSl
= dyn_cast
<ListInit
>(LHS
);
1211 StringInit
*LHSs
= dyn_cast
<StringInit
>(LHS
);
1212 DagInit
*LHSd
= dyn_cast
<DagInit
>(LHS
);
1213 TypedInit
*LHSt
= dyn_cast
<TypedInit
>(LHS
);
1214 if (!LHSl
&& !LHSs
&& !LHSd
&& !LHSt
) {
1215 TokError("expected string, list, or dag type argument in unary operator");
1219 ListRecTy
*LType
= dyn_cast
<ListRecTy
>(LHSt
->getType());
1220 StringRecTy
*SType
= dyn_cast
<StringRecTy
>(LHSt
->getType());
1221 DagRecTy
*DType
= dyn_cast
<DagRecTy
>(LHSt
->getType());
1222 if (!LType
&& !SType
&& !DType
) {
1223 TokError("expected string, list, or dag type argument in unary operator");
1229 if (Code
== UnOpInit::HEAD
|| Code
== UnOpInit::TAIL
) {
1230 ListInit
*LHSl
= dyn_cast
<ListInit
>(LHS
);
1231 TypedInit
*LHSt
= dyn_cast
<TypedInit
>(LHS
);
1232 if (!LHSl
&& !LHSt
) {
1233 TokError("expected list type argument in unary operator");
1237 ListRecTy
*LType
= dyn_cast
<ListRecTy
>(LHSt
->getType());
1239 TokError("expected list type argument in unary operator");
1244 if (LHSl
&& LHSl
->empty()) {
1245 TokError("empty list argument in unary operator");
1249 Init
*Item
= LHSl
->getElement(0);
1250 TypedInit
*Itemt
= dyn_cast
<TypedInit
>(Item
);
1252 TokError("untyped list element in unary operator");
1255 Type
= (Code
== UnOpInit::HEAD
) ? Itemt
->getType()
1256 : ListRecTy::get(Itemt
->getType());
1258 assert(LHSt
&& "expected list type argument in unary operator");
1259 ListRecTy
*LType
= dyn_cast
<ListRecTy
>(LHSt
->getType());
1260 Type
= (Code
== UnOpInit::HEAD
) ? LType
->getElementType() : LType
;
1264 if (!consume(tgtok::r_paren
)) {
1265 TokError("expected ')' in unary operator");
1268 return (UnOpInit::get(Code
, LHS
, Type
))->Fold(CurRec
);
1272 // Value ::= !isa '<' Type '>' '(' Value ')'
1273 Lex
.Lex(); // eat the operation
1275 RecTy
*Type
= ParseOperatorType();
1279 if (!consume(tgtok::l_paren
)) {
1280 TokError("expected '(' after type of !isa");
1284 Init
*LHS
= ParseValue(CurRec
);
1288 if (!consume(tgtok::r_paren
)) {
1289 TokError("expected ')' in !isa");
1293 return (IsAOpInit::get(Type
, LHS
))->Fold();
1296 case tgtok::XExists
: {
1297 // Value ::= !exists '<' Type '>' '(' Value ')'
1298 Lex
.Lex(); // eat the operation
1300 RecTy
*Type
= ParseOperatorType();
1304 if (!consume(tgtok::l_paren
)) {
1305 TokError("expected '(' after type of !exists");
1309 SMLoc ExprLoc
= Lex
.getLoc();
1310 Init
*Expr
= ParseValue(CurRec
);
1314 TypedInit
*ExprType
= dyn_cast
<TypedInit
>(Expr
);
1316 Error(ExprLoc
, "expected string type argument in !exists operator");
1320 RecordRecTy
*RecType
= dyn_cast
<RecordRecTy
>(ExprType
->getType());
1323 "expected string type argument in !exists operator, please "
1324 "use !isa instead");
1328 StringRecTy
*SType
= dyn_cast
<StringRecTy
>(ExprType
->getType());
1330 Error(ExprLoc
, "expected string type argument in !exists operator");
1334 if (!consume(tgtok::r_paren
)) {
1335 TokError("expected ')' in !exists");
1339 return (ExistsOpInit::get(Type
, Expr
))->Fold(CurRec
);
1342 case tgtok::XConcat
:
1359 case tgtok::XListConcat
:
1360 case tgtok::XListSplat
:
1361 case tgtok::XListRemove
:
1363 case tgtok::XStrConcat
:
1364 case tgtok::XInterleave
:
1365 case tgtok::XSetDagOp
: { // Value ::= !binop '(' Value ',' Value ')'
1366 tgtok::TokKind OpTok
= Lex
.getCode();
1367 SMLoc OpLoc
= Lex
.getLoc();
1368 Lex
.Lex(); // eat the operation
1370 BinOpInit::BinaryOp Code
;
1372 default: llvm_unreachable("Unhandled code!");
1373 case tgtok::XConcat
: Code
= BinOpInit::CONCAT
; break;
1374 case tgtok::XADD
: Code
= BinOpInit::ADD
; break;
1375 case tgtok::XSUB
: Code
= BinOpInit::SUB
; break;
1376 case tgtok::XMUL
: Code
= BinOpInit::MUL
; break;
1377 case tgtok::XDIV
: Code
= BinOpInit::DIV
; break;
1378 case tgtok::XAND
: Code
= BinOpInit::AND
; break;
1379 case tgtok::XOR
: Code
= BinOpInit::OR
; break;
1380 case tgtok::XXOR
: Code
= BinOpInit::XOR
; break;
1381 case tgtok::XSRA
: Code
= BinOpInit::SRA
; break;
1382 case tgtok::XSRL
: Code
= BinOpInit::SRL
; break;
1383 case tgtok::XSHL
: Code
= BinOpInit::SHL
; break;
1384 case tgtok::XEq
: Code
= BinOpInit::EQ
; break;
1385 case tgtok::XNe
: Code
= BinOpInit::NE
; break;
1386 case tgtok::XLe
: Code
= BinOpInit::LE
; break;
1387 case tgtok::XLt
: Code
= BinOpInit::LT
; break;
1388 case tgtok::XGe
: Code
= BinOpInit::GE
; break;
1389 case tgtok::XGt
: Code
= BinOpInit::GT
; break;
1390 case tgtok::XListConcat
: Code
= BinOpInit::LISTCONCAT
; break;
1391 case tgtok::XListSplat
: Code
= BinOpInit::LISTSPLAT
; break;
1392 case tgtok::XListRemove
: Code
= BinOpInit::LISTREMOVE
; break;
1393 case tgtok::XRange
: Code
= BinOpInit::RANGE
; break;
1394 case tgtok::XStrConcat
: Code
= BinOpInit::STRCONCAT
; break;
1395 case tgtok::XInterleave
: Code
= BinOpInit::INTERLEAVE
; break;
1396 case tgtok::XSetDagOp
: Code
= BinOpInit::SETDAGOP
; break;
1399 RecTy
*Type
= nullptr;
1400 RecTy
*ArgType
= nullptr;
1403 llvm_unreachable("Unhandled code!");
1404 case tgtok::XConcat
:
1405 case tgtok::XSetDagOp
:
1406 Type
= DagRecTy::get(Records
);
1407 ArgType
= DagRecTy::get(Records
);
1419 Type
= IntRecTy::get(Records
);
1420 ArgType
= IntRecTy::get(Records
);
1428 Type
= BitRecTy::get(Records
);
1429 // ArgType for the comparison operators is not yet known.
1431 case tgtok::XListConcat
:
1432 // We don't know the list type until we parse the first argument.
1435 case tgtok::XListSplat
:
1436 // Can't do any typechecking until we parse the first argument.
1438 case tgtok::XListRemove
:
1439 // We don't know the list type until we parse the first argument.
1443 Type
= IntRecTy::get(Records
)->getListTy();
1444 // ArgType may be either Int or List.
1446 case tgtok::XStrConcat
:
1447 Type
= StringRecTy::get(Records
);
1448 ArgType
= StringRecTy::get(Records
);
1450 case tgtok::XInterleave
:
1451 Type
= StringRecTy::get(Records
);
1452 // The first argument type is not yet known.
1455 if (Type
&& ItemType
&& !Type
->typeIsConvertibleTo(ItemType
)) {
1456 Error(OpLoc
, Twine("expected value of type '") +
1457 ItemType
->getAsString() + "', got '" +
1458 Type
->getAsString() + "'");
1462 if (!consume(tgtok::l_paren
)) {
1463 TokError("expected '(' after binary operator");
1467 SmallVector
<Init
*, 2> InitList
;
1469 // Note that this loop consumes an arbitrary number of arguments.
1470 // The actual count is checked later.
1472 SMLoc InitLoc
= Lex
.getLoc();
1473 InitList
.push_back(ParseValue(CurRec
, ArgType
));
1474 if (!InitList
.back()) return nullptr;
1476 TypedInit
*InitListBack
= dyn_cast
<TypedInit
>(InitList
.back());
1477 if (!InitListBack
) {
1478 Error(OpLoc
, Twine("expected value to be a typed value, got '" +
1479 InitList
.back()->getAsString() + "'"));
1482 RecTy
*ListType
= InitListBack
->getType();
1485 // Argument type must be determined from the argument itself.
1489 case BinOpInit::LISTCONCAT
:
1490 if (!isa
<ListRecTy
>(ArgType
)) {
1491 Error(InitLoc
, Twine("expected a list, got value of type '") +
1492 ArgType
->getAsString() + "'");
1496 case BinOpInit::LISTSPLAT
:
1497 if (ItemType
&& InitList
.size() == 1) {
1498 if (!isa
<ListRecTy
>(ItemType
)) {
1500 Twine("expected output type to be a list, got type '") +
1501 ItemType
->getAsString() + "'");
1504 if (!ArgType
->getListTy()->typeIsConvertibleTo(ItemType
)) {
1505 Error(OpLoc
, Twine("expected first arg type to be '") +
1506 ArgType
->getAsString() +
1507 "', got value of type '" +
1508 cast
<ListRecTy
>(ItemType
)
1515 if (InitList
.size() == 2 && !isa
<IntRecTy
>(ArgType
)) {
1516 Error(InitLoc
, Twine("expected second parameter to be an int, got "
1517 "value of type '") +
1518 ArgType
->getAsString() + "'");
1521 ArgType
= nullptr; // Broken invariant: types not identical.
1523 case BinOpInit::LISTREMOVE
:
1524 if (!isa
<ListRecTy
>(ArgType
)) {
1525 Error(InitLoc
, Twine("expected a list, got value of type '") +
1526 ArgType
->getAsString() + "'");
1530 case BinOpInit::RANGE
:
1531 if (InitList
.size() == 1) {
1532 if (isa
<ListRecTy
>(ArgType
)) {
1533 ArgType
= nullptr; // Detect error if 2nd arg were present.
1534 } else if (isa
<IntRecTy
>(ArgType
)) {
1535 // Assume 2nd arg should be IntRecTy
1538 Twine("expected list or int, got value of type '") +
1539 ArgType
->getAsString() + "'");
1543 // Don't come here unless 1st arg is ListRecTy.
1544 assert(isa
<ListRecTy
>(cast
<TypedInit
>(InitList
[0])->getType()));
1546 Twine("expected one list, got extra value of type '") +
1547 ArgType
->getAsString() + "'");
1553 if (!ArgType
->typeIsConvertibleTo(IntRecTy::get(Records
)) &&
1554 !ArgType
->typeIsConvertibleTo(StringRecTy::get(Records
)) &&
1555 !ArgType
->typeIsConvertibleTo(RecordRecTy::get(Records
, {}))) {
1556 Error(InitLoc
, Twine("expected bit, bits, int, string, or record; "
1557 "got value of type '") + ArgType
->getAsString() +
1566 if (!ArgType
->typeIsConvertibleTo(IntRecTy::get(Records
)) &&
1567 !ArgType
->typeIsConvertibleTo(StringRecTy::get(Records
))) {
1568 Error(InitLoc
, Twine("expected bit, bits, int, or string; "
1569 "got value of type '") + ArgType
->getAsString() +
1574 case BinOpInit::INTERLEAVE
:
1575 switch (InitList
.size()) {
1576 case 1: // First argument must be a list of strings or integers.
1577 if (ArgType
!= StringRecTy::get(Records
)->getListTy() &&
1578 !ArgType
->typeIsConvertibleTo(
1579 IntRecTy::get(Records
)->getListTy())) {
1580 Error(InitLoc
, Twine("expected list of string, int, bits, or bit; "
1581 "got value of type '") +
1582 ArgType
->getAsString() + "'");
1586 case 2: // Second argument must be a string.
1587 if (!isa
<StringRecTy
>(ArgType
)) {
1588 Error(InitLoc
, Twine("expected second argument to be a string, "
1589 "got value of type '") +
1590 ArgType
->getAsString() + "'");
1596 ArgType
= nullptr; // Broken invariant: types not identical.
1598 default: llvm_unreachable("other ops have fixed argument types");
1602 // Desired argument type is a known and in ArgType.
1603 RecTy
*Resolved
= resolveTypes(ArgType
, ListType
);
1605 Error(InitLoc
, Twine("expected value of type '") +
1606 ArgType
->getAsString() + "', got '" +
1607 ListType
->getAsString() + "'");
1610 if (Code
!= BinOpInit::ADD
&& Code
!= BinOpInit::SUB
&&
1611 Code
!= BinOpInit::AND
&& Code
!= BinOpInit::OR
&&
1612 Code
!= BinOpInit::XOR
&& Code
!= BinOpInit::SRA
&&
1613 Code
!= BinOpInit::SRL
&& Code
!= BinOpInit::SHL
&&
1614 Code
!= BinOpInit::MUL
&& Code
!= BinOpInit::DIV
)
1618 // Deal with BinOps whose arguments have different types, by
1619 // rewriting ArgType in between them.
1621 case BinOpInit::SETDAGOP
:
1622 // After parsing the first dag argument, switch to expecting
1623 // a record, with no restriction on its superclasses.
1624 ArgType
= RecordRecTy::get(Records
, {});
1630 if (!consume(tgtok::comma
))
1634 if (!consume(tgtok::r_paren
)) {
1635 TokError("expected ')' in operator");
1639 // listconcat returns a list with type of the argument.
1640 if (Code
== BinOpInit::LISTCONCAT
)
1642 // listsplat returns a list of type of the *first* argument.
1643 if (Code
== BinOpInit::LISTSPLAT
)
1644 Type
= cast
<TypedInit
>(InitList
.front())->getType()->getListTy();
1645 // listremove returns a list with type of the argument.
1646 if (Code
== BinOpInit::LISTREMOVE
)
1649 if (Code
== BinOpInit::RANGE
) {
1651 auto ArgCount
= InitList
.size();
1652 assert(ArgCount
>= 1);
1653 auto *Arg0
= cast
<TypedInit
>(InitList
[0]);
1654 auto *Arg0Ty
= Arg0
->getType();
1655 if (ArgCount
== 1) {
1656 if (isa
<ListRecTy
>(Arg0Ty
)) {
1658 LHS
= IntInit::get(Records
, 0);
1659 RHS
= UnOpInit::get(UnOpInit::SIZE
, Arg0
, IntRecTy::get(Records
))
1662 assert(isa
<IntRecTy
>(Arg0Ty
));
1664 LHS
= IntInit::get(Records
, 0);
1667 } else if (ArgCount
== 2) {
1668 assert(isa
<IntRecTy
>(Arg0Ty
));
1669 auto *Arg1
= cast
<TypedInit
>(InitList
[1]);
1670 assert(isa
<IntRecTy
>(Arg1
->getType()));
1674 Error(OpLoc
, "expected at most two values of integer");
1677 return BinOpInit::get(Code
, LHS
, RHS
, Type
)->Fold(CurRec
);
1680 // We allow multiple operands to associative operators like !strconcat as
1681 // shorthand for nesting them.
1682 if (Code
== BinOpInit::STRCONCAT
|| Code
== BinOpInit::LISTCONCAT
||
1683 Code
== BinOpInit::CONCAT
|| Code
== BinOpInit::ADD
||
1684 Code
== BinOpInit::AND
|| Code
== BinOpInit::OR
||
1685 Code
== BinOpInit::XOR
|| Code
== BinOpInit::MUL
) {
1686 while (InitList
.size() > 2) {
1687 Init
*RHS
= InitList
.pop_back_val();
1688 RHS
= (BinOpInit::get(Code
, InitList
.back(), RHS
, Type
))->Fold(CurRec
);
1689 InitList
.back() = RHS
;
1693 if (InitList
.size() == 2)
1694 return (BinOpInit::get(Code
, InitList
[0], InitList
[1], Type
))
1697 Error(OpLoc
, "expected two operands to operator");
1701 case tgtok::XForEach
:
1702 case tgtok::XFilter
: {
1703 return ParseOperationForEachFilter(CurRec
, ItemType
);
1708 case tgtok::XSubst
: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1709 TernOpInit::TernaryOp Code
;
1710 RecTy
*Type
= nullptr;
1712 tgtok::TokKind LexCode
= Lex
.getCode();
1713 Lex
.Lex(); // eat the operation
1715 default: llvm_unreachable("Unhandled code!");
1717 Code
= TernOpInit::DAG
;
1718 Type
= DagRecTy::get(Records
);
1722 Code
= TernOpInit::IF
;
1725 Code
= TernOpInit::SUBST
;
1728 if (!consume(tgtok::l_paren
)) {
1729 TokError("expected '(' after ternary operator");
1733 Init
*LHS
= ParseValue(CurRec
);
1734 if (!LHS
) return nullptr;
1736 if (!consume(tgtok::comma
)) {
1737 TokError("expected ',' in ternary operator");
1741 SMLoc MHSLoc
= Lex
.getLoc();
1742 Init
*MHS
= ParseValue(CurRec
, ItemType
);
1746 if (!consume(tgtok::comma
)) {
1747 TokError("expected ',' in ternary operator");
1751 SMLoc RHSLoc
= Lex
.getLoc();
1752 Init
*RHS
= ParseValue(CurRec
, ItemType
);
1756 if (!consume(tgtok::r_paren
)) {
1757 TokError("expected ')' in binary operator");
1762 default: llvm_unreachable("Unhandled code!");
1764 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
1765 if (!MHSt
&& !isa
<UnsetInit
>(MHS
)) {
1766 Error(MHSLoc
, "could not determine type of the child list in !dag");
1769 if (MHSt
&& !isa
<ListRecTy
>(MHSt
->getType())) {
1770 Error(MHSLoc
, Twine("expected list of children, got type '") +
1771 MHSt
->getType()->getAsString() + "'");
1775 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
1776 if (!RHSt
&& !isa
<UnsetInit
>(RHS
)) {
1777 Error(RHSLoc
, "could not determine type of the name list in !dag");
1780 if (RHSt
&& StringRecTy::get(Records
)->getListTy() != RHSt
->getType()) {
1781 Error(RHSLoc
, Twine("expected list<string>, got type '") +
1782 RHSt
->getType()->getAsString() + "'");
1786 if (!MHSt
&& !RHSt
) {
1788 "cannot have both unset children and unset names in !dag");
1794 RecTy
*MHSTy
= nullptr;
1795 RecTy
*RHSTy
= nullptr;
1797 if (TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
))
1798 MHSTy
= MHSt
->getType();
1799 if (BitsInit
*MHSbits
= dyn_cast
<BitsInit
>(MHS
))
1800 MHSTy
= BitsRecTy::get(Records
, MHSbits
->getNumBits());
1801 if (isa
<BitInit
>(MHS
))
1802 MHSTy
= BitRecTy::get(Records
);
1804 if (TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
))
1805 RHSTy
= RHSt
->getType();
1806 if (BitsInit
*RHSbits
= dyn_cast
<BitsInit
>(RHS
))
1807 RHSTy
= BitsRecTy::get(Records
, RHSbits
->getNumBits());
1808 if (isa
<BitInit
>(RHS
))
1809 RHSTy
= BitRecTy::get(Records
);
1811 // For UnsetInit, it's typed from the other hand.
1812 if (isa
<UnsetInit
>(MHS
))
1814 if (isa
<UnsetInit
>(RHS
))
1817 if (!MHSTy
|| !RHSTy
) {
1818 TokError("could not get type for !if");
1822 Type
= resolveTypes(MHSTy
, RHSTy
);
1824 TokError(Twine("inconsistent types '") + MHSTy
->getAsString() +
1825 "' and '" + RHSTy
->getAsString() + "' for !if");
1830 case tgtok::XSubst
: {
1831 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
1833 TokError("could not get type for !subst");
1836 Type
= RHSt
->getType();
1840 return (TernOpInit::get(Code
, LHS
, MHS
, RHS
, Type
))->Fold(CurRec
);
1843 case tgtok::XSubstr
:
1844 return ParseOperationSubstr(CurRec
, ItemType
);
1847 return ParseOperationFind(CurRec
, ItemType
);
1850 return ParseOperationCond(CurRec
, ItemType
);
1852 case tgtok::XFoldl
: {
1853 // Value ::= !foldl '(' Value ',' Value ',' Id ',' Id ',' Expr ')'
1854 Lex
.Lex(); // eat the operation
1855 if (!consume(tgtok::l_paren
)) {
1856 TokError("expected '(' after !foldl");
1860 Init
*StartUntyped
= ParseValue(CurRec
);
1864 TypedInit
*Start
= dyn_cast
<TypedInit
>(StartUntyped
);
1866 TokError(Twine("could not get type of !foldl start: '") +
1867 StartUntyped
->getAsString() + "'");
1871 if (!consume(tgtok::comma
)) {
1872 TokError("expected ',' in !foldl");
1876 Init
*ListUntyped
= ParseValue(CurRec
);
1880 TypedInit
*List
= dyn_cast
<TypedInit
>(ListUntyped
);
1882 TokError(Twine("could not get type of !foldl list: '") +
1883 ListUntyped
->getAsString() + "'");
1887 ListRecTy
*ListType
= dyn_cast
<ListRecTy
>(List
->getType());
1889 TokError(Twine("!foldl list must be a list, but is of type '") +
1890 List
->getType()->getAsString());
1894 if (Lex
.getCode() != tgtok::comma
) {
1895 TokError("expected ',' in !foldl");
1899 if (Lex
.Lex() != tgtok::Id
) { // eat the ','
1900 TokError("third argument of !foldl must be an identifier");
1904 Init
*A
= StringInit::get(Records
, Lex
.getCurStrVal());
1905 if (CurRec
&& CurRec
->getValue(A
)) {
1906 TokError((Twine("left !foldl variable '") + A
->getAsString() +
1907 "' already defined")
1912 if (Lex
.Lex() != tgtok::comma
) { // eat the id
1913 TokError("expected ',' in !foldl");
1917 if (Lex
.Lex() != tgtok::Id
) { // eat the ','
1918 TokError("fourth argument of !foldl must be an identifier");
1922 Init
*B
= StringInit::get(Records
, Lex
.getCurStrVal());
1923 if (CurRec
&& CurRec
->getValue(B
)) {
1924 TokError((Twine("right !foldl variable '") + B
->getAsString() +
1925 "' already defined")
1930 if (Lex
.Lex() != tgtok::comma
) { // eat the id
1931 TokError("expected ',' in !foldl");
1934 Lex
.Lex(); // eat the ','
1936 // We need to create a temporary record to provide a scope for the
1938 std::unique_ptr
<Record
> ParseRecTmp
;
1939 Record
*ParseRec
= CurRec
;
1941 ParseRecTmp
= std::make_unique
<Record
>(".parse", ArrayRef
<SMLoc
>{}, Records
);
1942 ParseRec
= ParseRecTmp
.get();
1945 ParseRec
->addValue(RecordVal(A
, Start
->getType(), RecordVal::FK_Normal
));
1946 ParseRec
->addValue(RecordVal(B
, ListType
->getElementType(),
1947 RecordVal::FK_Normal
));
1948 Init
*ExprUntyped
= ParseValue(ParseRec
);
1949 ParseRec
->removeValue(A
);
1950 ParseRec
->removeValue(B
);
1954 TypedInit
*Expr
= dyn_cast
<TypedInit
>(ExprUntyped
);
1956 TokError("could not get type of !foldl expression");
1960 if (Expr
->getType() != Start
->getType()) {
1961 TokError(Twine("!foldl expression must be of same type as start (") +
1962 Start
->getType()->getAsString() + "), but is of type " +
1963 Expr
->getType()->getAsString());
1967 if (!consume(tgtok::r_paren
)) {
1968 TokError("expected ')' in fold operator");
1972 return FoldOpInit::get(Start
, List
, A
, B
, Expr
, Start
->getType())
1978 /// ParseOperatorType - Parse a type for an operator. This returns
1981 /// OperatorType ::= '<' Type '>'
1983 RecTy
*TGParser::ParseOperatorType() {
1984 RecTy
*Type
= nullptr;
1986 if (!consume(tgtok::less
)) {
1987 TokError("expected type name for operator");
1991 if (Lex
.getCode() == tgtok::Code
)
1992 TokError("the 'code' type is not allowed in bang operators; use 'string'");
1997 TokError("expected type name for operator");
2001 if (!consume(tgtok::greater
)) {
2002 TokError("expected type name for operator");
2009 /// Parse the !substr operation. Return null on error.
2011 /// Substr ::= !substr(string, start-int [, length-int]) => string
2012 Init
*TGParser::ParseOperationSubstr(Record
*CurRec
, RecTy
*ItemType
) {
2013 TernOpInit::TernaryOp Code
= TernOpInit::SUBSTR
;
2014 RecTy
*Type
= StringRecTy::get(Records
);
2016 Lex
.Lex(); // eat the operation
2018 if (!consume(tgtok::l_paren
)) {
2019 TokError("expected '(' after !substr operator");
2023 Init
*LHS
= ParseValue(CurRec
);
2027 if (!consume(tgtok::comma
)) {
2028 TokError("expected ',' in !substr operator");
2032 SMLoc MHSLoc
= Lex
.getLoc();
2033 Init
*MHS
= ParseValue(CurRec
);
2037 SMLoc RHSLoc
= Lex
.getLoc();
2039 if (consume(tgtok::comma
)) {
2040 RHSLoc
= Lex
.getLoc();
2041 RHS
= ParseValue(CurRec
);
2045 RHS
= IntInit::get(Records
, std::numeric_limits
<int64_t>::max());
2048 if (!consume(tgtok::r_paren
)) {
2049 TokError("expected ')' in !substr operator");
2053 if (ItemType
&& !Type
->typeIsConvertibleTo(ItemType
)) {
2054 Error(RHSLoc
, Twine("expected value of type '") +
2055 ItemType
->getAsString() + "', got '" +
2056 Type
->getAsString() + "'");
2059 TypedInit
*LHSt
= dyn_cast
<TypedInit
>(LHS
);
2060 if (!LHSt
&& !isa
<UnsetInit
>(LHS
)) {
2061 TokError("could not determine type of the string in !substr");
2064 if (LHSt
&& !isa
<StringRecTy
>(LHSt
->getType())) {
2065 TokError(Twine("expected string, got type '") +
2066 LHSt
->getType()->getAsString() + "'");
2070 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
2071 if (!MHSt
&& !isa
<UnsetInit
>(MHS
)) {
2072 TokError("could not determine type of the start position in !substr");
2075 if (MHSt
&& !isa
<IntRecTy
>(MHSt
->getType())) {
2076 Error(MHSLoc
, Twine("expected int, got type '") +
2077 MHSt
->getType()->getAsString() + "'");
2082 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
2083 if (!RHSt
&& !isa
<UnsetInit
>(RHS
)) {
2084 TokError("could not determine type of the length in !substr");
2087 if (RHSt
&& !isa
<IntRecTy
>(RHSt
->getType())) {
2088 TokError(Twine("expected int, got type '") +
2089 RHSt
->getType()->getAsString() + "'");
2094 return (TernOpInit::get(Code
, LHS
, MHS
, RHS
, Type
))->Fold(CurRec
);
2097 /// Parse the !find operation. Return null on error.
2099 /// Substr ::= !find(string, string [, start-int]) => int
2100 Init
*TGParser::ParseOperationFind(Record
*CurRec
, RecTy
*ItemType
) {
2101 TernOpInit::TernaryOp Code
= TernOpInit::FIND
;
2102 RecTy
*Type
= IntRecTy::get(Records
);
2104 Lex
.Lex(); // eat the operation
2106 if (!consume(tgtok::l_paren
)) {
2107 TokError("expected '(' after !find operator");
2111 Init
*LHS
= ParseValue(CurRec
);
2115 if (!consume(tgtok::comma
)) {
2116 TokError("expected ',' in !find operator");
2120 SMLoc MHSLoc
= Lex
.getLoc();
2121 Init
*MHS
= ParseValue(CurRec
);
2125 SMLoc RHSLoc
= Lex
.getLoc();
2127 if (consume(tgtok::comma
)) {
2128 RHSLoc
= Lex
.getLoc();
2129 RHS
= ParseValue(CurRec
);
2133 RHS
= IntInit::get(Records
, 0);
2136 if (!consume(tgtok::r_paren
)) {
2137 TokError("expected ')' in !find operator");
2141 if (ItemType
&& !Type
->typeIsConvertibleTo(ItemType
)) {
2142 Error(RHSLoc
, Twine("expected value of type '") +
2143 ItemType
->getAsString() + "', got '" +
2144 Type
->getAsString() + "'");
2147 TypedInit
*LHSt
= dyn_cast
<TypedInit
>(LHS
);
2148 if (!LHSt
&& !isa
<UnsetInit
>(LHS
)) {
2149 TokError("could not determine type of the source string in !find");
2152 if (LHSt
&& !isa
<StringRecTy
>(LHSt
->getType())) {
2153 TokError(Twine("expected string, got type '") +
2154 LHSt
->getType()->getAsString() + "'");
2158 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
2159 if (!MHSt
&& !isa
<UnsetInit
>(MHS
)) {
2160 TokError("could not determine type of the target string in !find");
2163 if (MHSt
&& !isa
<StringRecTy
>(MHSt
->getType())) {
2164 Error(MHSLoc
, Twine("expected string, got type '") +
2165 MHSt
->getType()->getAsString() + "'");
2170 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
2171 if (!RHSt
&& !isa
<UnsetInit
>(RHS
)) {
2172 TokError("could not determine type of the start position in !find");
2175 if (RHSt
&& !isa
<IntRecTy
>(RHSt
->getType())) {
2176 TokError(Twine("expected int, got type '") +
2177 RHSt
->getType()->getAsString() + "'");
2182 return (TernOpInit::get(Code
, LHS
, MHS
, RHS
, Type
))->Fold(CurRec
);
2185 /// Parse the !foreach and !filter operations. Return null on error.
2187 /// ForEach ::= !foreach(ID, list-or-dag, expr) => list<expr type>
2188 /// Filter ::= !foreach(ID, list, predicate) ==> list<list type>
2189 Init
*TGParser::ParseOperationForEachFilter(Record
*CurRec
, RecTy
*ItemType
) {
2190 SMLoc OpLoc
= Lex
.getLoc();
2191 tgtok::TokKind Operation
= Lex
.getCode();
2192 Lex
.Lex(); // eat the operation
2193 if (Lex
.getCode() != tgtok::l_paren
) {
2194 TokError("expected '(' after !foreach/!filter");
2198 if (Lex
.Lex() != tgtok::Id
) { // eat the '('
2199 TokError("first argument of !foreach/!filter must be an identifier");
2203 Init
*LHS
= StringInit::get(Records
, Lex
.getCurStrVal());
2204 Lex
.Lex(); // eat the ID.
2206 if (CurRec
&& CurRec
->getValue(LHS
)) {
2207 TokError((Twine("iteration variable '") + LHS
->getAsString() +
2208 "' is already defined")
2213 if (!consume(tgtok::comma
)) {
2214 TokError("expected ',' in !foreach/!filter");
2218 Init
*MHS
= ParseValue(CurRec
);
2222 if (!consume(tgtok::comma
)) {
2223 TokError("expected ',' in !foreach/!filter");
2227 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
2229 TokError("could not get type of !foreach/!filter list or dag");
2233 RecTy
*InEltType
= nullptr;
2234 RecTy
*ExprEltType
= nullptr;
2237 if (ListRecTy
*InListTy
= dyn_cast
<ListRecTy
>(MHSt
->getType())) {
2238 InEltType
= InListTy
->getElementType();
2240 if (ListRecTy
*OutListTy
= dyn_cast
<ListRecTy
>(ItemType
)) {
2241 ExprEltType
= (Operation
== tgtok::XForEach
)
2242 ? OutListTy
->getElementType()
2243 : IntRecTy::get(Records
);
2246 "expected value of type '" +
2247 Twine(ItemType
->getAsString()) +
2248 "', but got list type");
2252 } else if (DagRecTy
*InDagTy
= dyn_cast
<DagRecTy
>(MHSt
->getType())) {
2253 if (Operation
== tgtok::XFilter
) {
2254 TokError("!filter must have a list argument");
2257 InEltType
= InDagTy
;
2258 if (ItemType
&& !isa
<DagRecTy
>(ItemType
)) {
2260 "expected value of type '" + Twine(ItemType
->getAsString()) +
2261 "', but got dag type");
2266 if (Operation
== tgtok::XForEach
)
2267 TokError("!foreach must have a list or dag argument");
2269 TokError("!filter must have a list argument");
2273 // We need to create a temporary record to provide a scope for the
2274 // iteration variable.
2275 std::unique_ptr
<Record
> ParseRecTmp
;
2276 Record
*ParseRec
= CurRec
;
2279 std::make_unique
<Record
>(".parse", ArrayRef
<SMLoc
>{}, Records
);
2280 ParseRec
= ParseRecTmp
.get();
2283 ParseRec
->addValue(RecordVal(LHS
, InEltType
, RecordVal::FK_Normal
));
2284 Init
*RHS
= ParseValue(ParseRec
, ExprEltType
);
2285 ParseRec
->removeValue(LHS
);
2289 if (!consume(tgtok::r_paren
)) {
2290 TokError("expected ')' in !foreach/!filter");
2294 RecTy
*OutType
= InEltType
;
2295 if (Operation
== tgtok::XForEach
&& !IsDAG
) {
2296 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
2298 TokError("could not get type of !foreach result expression");
2301 OutType
= RHSt
->getType()->getListTy();
2302 } else if (Operation
== tgtok::XFilter
) {
2303 OutType
= InEltType
->getListTy();
2306 return (TernOpInit::get((Operation
== tgtok::XForEach
) ? TernOpInit::FOREACH
2307 : TernOpInit::FILTER
,
2308 LHS
, MHS
, RHS
, OutType
))
2312 Init
*TGParser::ParseOperationCond(Record
*CurRec
, RecTy
*ItemType
) {
2313 Lex
.Lex(); // eat the operation 'cond'
2315 if (!consume(tgtok::l_paren
)) {
2316 TokError("expected '(' after !cond operator");
2320 // Parse through '[Case: Val,]+'
2321 SmallVector
<Init
*, 4> Case
;
2322 SmallVector
<Init
*, 4> Val
;
2324 if (consume(tgtok::r_paren
))
2327 Init
*V
= ParseValue(CurRec
);
2332 if (!consume(tgtok::colon
)) {
2333 TokError("expected ':' following a condition in !cond operator");
2337 V
= ParseValue(CurRec
, ItemType
);
2342 if (consume(tgtok::r_paren
))
2345 if (!consume(tgtok::comma
)) {
2346 TokError("expected ',' or ')' following a value in !cond operator");
2351 if (Case
.size() < 1) {
2352 TokError("there should be at least 1 'condition : value' in the !cond operator");
2357 RecTy
*Type
= nullptr;
2358 for (Init
*V
: Val
) {
2359 RecTy
*VTy
= nullptr;
2360 if (TypedInit
*Vt
= dyn_cast
<TypedInit
>(V
))
2361 VTy
= Vt
->getType();
2362 if (BitsInit
*Vbits
= dyn_cast
<BitsInit
>(V
))
2363 VTy
= BitsRecTy::get(Records
, Vbits
->getNumBits());
2364 if (isa
<BitInit
>(V
))
2365 VTy
= BitRecTy::get(Records
);
2367 if (Type
== nullptr) {
2368 if (!isa
<UnsetInit
>(V
))
2371 if (!isa
<UnsetInit
>(V
)) {
2372 RecTy
*RType
= resolveTypes(Type
, VTy
);
2374 TokError(Twine("inconsistent types '") + Type
->getAsString() +
2375 "' and '" + VTy
->getAsString() + "' for !cond");
2384 TokError("could not determine type for !cond from its arguments");
2387 return CondOpInit::get(Case
, Val
, Type
)->Fold(CurRec
);
2390 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
2392 /// SimpleValue ::= IDValue
2393 /// SimpleValue ::= INTVAL
2394 /// SimpleValue ::= STRVAL+
2395 /// SimpleValue ::= CODEFRAGMENT
2396 /// SimpleValue ::= '?'
2397 /// SimpleValue ::= '{' ValueList '}'
2398 /// SimpleValue ::= ID '<' ValueListNE '>'
2399 /// SimpleValue ::= '[' ValueList ']'
2400 /// SimpleValue ::= '(' IDValue DagArgList ')'
2401 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
2402 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
2403 /// SimpleValue ::= DIVTOK '(' Value ',' Value ')'
2404 /// SimpleValue ::= SUBTOK '(' Value ',' Value ')'
2405 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
2406 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
2407 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
2408 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
2409 /// SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')'
2410 /// SimpleValue ::= LISTREMOVETOK '(' Value ',' Value ')'
2411 /// SimpleValue ::= RANGE '(' Value ')'
2412 /// SimpleValue ::= RANGE '(' Value ',' Value ')'
2413 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
2414 /// SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
2416 Init
*TGParser::ParseSimpleValue(Record
*CurRec
, RecTy
*ItemType
,
2419 switch (Lex
.getCode()) {
2420 default: TokError("Unknown or reserved token when parsing a value"); break;
2422 case tgtok::TrueVal
:
2423 R
= IntInit::get(Records
, 1);
2426 case tgtok::FalseVal
:
2427 R
= IntInit::get(Records
, 0);
2431 R
= IntInit::get(Records
, Lex
.getCurIntVal());
2434 case tgtok::BinaryIntVal
: {
2435 auto BinaryVal
= Lex
.getCurBinaryIntVal();
2436 SmallVector
<Init
*, 16> Bits(BinaryVal
.second
);
2437 for (unsigned i
= 0, e
= BinaryVal
.second
; i
!= e
; ++i
)
2438 Bits
[i
] = BitInit::get(Records
, BinaryVal
.first
& (1LL << i
));
2439 R
= BitsInit::get(Records
, Bits
);
2443 case tgtok::StrVal
: {
2444 std::string Val
= Lex
.getCurStrVal();
2447 // Handle multiple consecutive concatenated strings.
2448 while (Lex
.getCode() == tgtok::StrVal
) {
2449 Val
+= Lex
.getCurStrVal();
2453 R
= StringInit::get(Records
, Val
);
2456 case tgtok::CodeFragment
:
2457 R
= StringInit::get(Records
, Lex
.getCurStrVal(), StringInit::SF_Code
);
2460 case tgtok::question
:
2461 R
= UnsetInit::get(Records
);
2465 SMRange NameLoc
= Lex
.getLocRange();
2466 StringInit
*Name
= StringInit::get(Records
, Lex
.getCurStrVal());
2467 if (Lex
.Lex() != tgtok::less
) // consume the Id.
2468 return ParseIDValue(CurRec
, Name
, NameLoc
, Mode
); // Value ::= IDValue
2470 // Value ::= CLASSID '<' ValueListNE '>' (CLASSID has been consumed)
2471 // This is supposed to synthesize a new anonymous definition, deriving
2472 // from the class with the template arguments, but no body.
2473 Record
*Class
= Records
.getClass(Name
->getValue());
2475 Error(NameLoc
.Start
,
2476 "Expected a class name, got '" + Name
->getValue() + "'");
2480 SmallVector
<Init
*, 8> Args
;
2481 Lex
.Lex(); // consume the <
2482 if (ParseTemplateArgValueList(Args
, CurRec
, Class
))
2483 return nullptr; // Error parsing value list.
2485 if (CheckTemplateArgValues(Args
, NameLoc
.Start
, Class
))
2486 return nullptr; // Error checking template argument values.
2488 // Loop through the arguments that were not specified and make sure
2489 // they have a complete value.
2490 ArrayRef
<Init
*> TArgs
= Class
->getTemplateArgs();
2491 for (unsigned I
= Args
.size(), E
= TArgs
.size(); I
< E
; ++I
) {
2492 RecordVal
*Arg
= Class
->getValue(TArgs
[I
]);
2493 if (!Arg
->getValue()->isComplete()) {
2494 Error(NameLoc
.Start
, "Value not specified for template argument '" +
2495 TArgs
[I
]->getAsUnquotedString() + "' (#" +
2496 Twine(I
) + ") of parent class '" +
2497 Class
->getNameInitAsString() + "'");
2501 if (TrackReferenceLocs
)
2502 Class
->appendReferenceLoc(NameLoc
);
2503 return VarDefInit::get(Class
, Args
)->Fold();
2505 case tgtok::l_brace
: { // Value ::= '{' ValueList '}'
2506 SMLoc BraceLoc
= Lex
.getLoc();
2507 Lex
.Lex(); // eat the '{'
2508 SmallVector
<Init
*, 16> Vals
;
2510 if (Lex
.getCode() != tgtok::r_brace
) {
2511 ParseValueList(Vals
, CurRec
);
2512 if (Vals
.empty()) return nullptr;
2514 if (!consume(tgtok::r_brace
)) {
2515 TokError("expected '}' at end of bit list value");
2519 SmallVector
<Init
*, 16> NewBits
;
2521 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
2522 // first. We'll first read everything in to a vector, then we can reverse
2523 // it to get the bits in the correct order for the BitsInit value.
2524 for (unsigned i
= 0, e
= Vals
.size(); i
!= e
; ++i
) {
2525 // FIXME: The following two loops would not be duplicated
2526 // if the API was a little more orthogonal.
2528 // bits<n> values are allowed to initialize n bits.
2529 if (BitsInit
*BI
= dyn_cast
<BitsInit
>(Vals
[i
])) {
2530 for (unsigned i
= 0, e
= BI
->getNumBits(); i
!= e
; ++i
)
2531 NewBits
.push_back(BI
->getBit((e
- i
) - 1));
2534 // bits<n> can also come from variable initializers.
2535 if (VarInit
*VI
= dyn_cast
<VarInit
>(Vals
[i
])) {
2536 if (BitsRecTy
*BitsRec
= dyn_cast
<BitsRecTy
>(VI
->getType())) {
2537 for (unsigned i
= 0, e
= BitsRec
->getNumBits(); i
!= e
; ++i
)
2538 NewBits
.push_back(VI
->getBit((e
- i
) - 1));
2541 // Fallthrough to try convert this to a bit.
2543 // All other values must be convertible to just a single bit.
2544 Init
*Bit
= Vals
[i
]->getCastTo(BitRecTy::get(Records
));
2546 Error(BraceLoc
, "Element #" + Twine(i
) + " (" + Vals
[i
]->getAsString() +
2547 ") is not convertable to a bit");
2550 NewBits
.push_back(Bit
);
2552 std::reverse(NewBits
.begin(), NewBits
.end());
2553 return BitsInit::get(Records
, NewBits
);
2555 case tgtok::l_square
: { // Value ::= '[' ValueList ']'
2556 Lex
.Lex(); // eat the '['
2557 SmallVector
<Init
*, 16> Vals
;
2559 RecTy
*DeducedEltTy
= nullptr;
2560 ListRecTy
*GivenListTy
= nullptr;
2563 ListRecTy
*ListType
= dyn_cast
<ListRecTy
>(ItemType
);
2565 TokError(Twine("Encountered a list when expecting a ") +
2566 ItemType
->getAsString());
2569 GivenListTy
= ListType
;
2572 if (Lex
.getCode() != tgtok::r_square
) {
2573 ParseValueList(Vals
, CurRec
,
2574 GivenListTy
? GivenListTy
->getElementType() : nullptr);
2575 if (Vals
.empty()) return nullptr;
2577 if (!consume(tgtok::r_square
)) {
2578 TokError("expected ']' at end of list value");
2582 RecTy
*GivenEltTy
= nullptr;
2583 if (consume(tgtok::less
)) {
2584 // Optional list element type
2585 GivenEltTy
= ParseType();
2587 // Couldn't parse element type
2591 if (!consume(tgtok::greater
)) {
2592 TokError("expected '>' at end of list element type");
2598 RecTy
*EltTy
= nullptr;
2599 for (Init
*V
: Vals
) {
2600 TypedInit
*TArg
= dyn_cast
<TypedInit
>(V
);
2603 EltTy
= resolveTypes(EltTy
, TArg
->getType());
2605 TokError("Incompatible types in list elements");
2609 EltTy
= TArg
->getType();
2616 // Verify consistency
2617 if (!EltTy
->typeIsConvertibleTo(GivenEltTy
)) {
2618 TokError("Incompatible types in list elements");
2627 TokError("No type for list");
2630 DeducedEltTy
= GivenListTy
->getElementType();
2632 // Make sure the deduced type is compatible with the given type
2634 if (!EltTy
->typeIsConvertibleTo(GivenListTy
->getElementType())) {
2635 TokError(Twine("Element type mismatch for list: element type '") +
2636 EltTy
->getAsString() + "' not convertible to '" +
2637 GivenListTy
->getElementType()->getAsString());
2641 DeducedEltTy
= EltTy
;
2644 return ListInit::get(Vals
, DeducedEltTy
);
2646 case tgtok::l_paren
: { // Value ::= '(' IDValue DagArgList ')'
2647 Lex
.Lex(); // eat the '('
2648 if (Lex
.getCode() != tgtok::Id
&& Lex
.getCode() != tgtok::XCast
&&
2649 Lex
.getCode() != tgtok::question
&& Lex
.getCode() != tgtok::XGetDagOp
) {
2650 TokError("expected identifier in dag init");
2654 Init
*Operator
= ParseValue(CurRec
);
2655 if (!Operator
) return nullptr;
2657 // If the operator name is present, parse it.
2658 StringInit
*OperatorName
= nullptr;
2659 if (consume(tgtok::colon
)) {
2660 if (Lex
.getCode() != tgtok::VarName
) { // eat the ':'
2661 TokError("expected variable name in dag operator");
2664 OperatorName
= StringInit::get(Records
, Lex
.getCurStrVal());
2665 Lex
.Lex(); // eat the VarName.
2668 SmallVector
<std::pair
<llvm::Init
*, StringInit
*>, 8> DagArgs
;
2669 if (Lex
.getCode() != tgtok::r_paren
) {
2670 ParseDagArgList(DagArgs
, CurRec
);
2671 if (DagArgs
.empty()) return nullptr;
2674 if (!consume(tgtok::r_paren
)) {
2675 TokError("expected ')' in dag init");
2679 return DagInit::get(Operator
, OperatorName
, DagArgs
);
2687 case tgtok::XToLower
:
2688 case tgtok::XToUpper
:
2689 case tgtok::XGetDagOp
: // Value ::= !unop '(' Value ')'
2690 case tgtok::XExists
:
2692 case tgtok::XConcat
:
2712 case tgtok::XListConcat
:
2713 case tgtok::XListSplat
:
2714 case tgtok::XListRemove
:
2716 case tgtok::XStrConcat
:
2717 case tgtok::XInterleave
:
2718 case tgtok::XSetDagOp
: // Value ::= !binop '(' Value ',' Value ')'
2722 case tgtok::XForEach
:
2723 case tgtok::XFilter
:
2725 case tgtok::XSubstr
:
2726 case tgtok::XFind
: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
2727 return ParseOperation(CurRec
, ItemType
);
2734 /// ParseValue - Parse a TableGen value. This returns null on error.
2736 /// Value ::= SimpleValue ValueSuffix*
2737 /// ValueSuffix ::= '{' BitList '}'
2738 /// ValueSuffix ::= '[' SliceElements ']'
2739 /// ValueSuffix ::= '.' ID
2741 Init
*TGParser::ParseValue(Record
*CurRec
, RecTy
*ItemType
, IDParseMode Mode
) {
2742 SMLoc LHSLoc
= Lex
.getLoc();
2743 Init
*Result
= ParseSimpleValue(CurRec
, ItemType
, Mode
);
2744 if (!Result
) return nullptr;
2746 // Parse the suffixes now if present.
2748 switch (Lex
.getCode()) {
2749 default: return Result
;
2750 case tgtok::l_brace
: {
2751 if (Mode
== ParseNameMode
)
2752 // This is the beginning of the object body.
2755 SMLoc CurlyLoc
= Lex
.getLoc();
2756 Lex
.Lex(); // eat the '{'
2757 SmallVector
<unsigned, 16> Ranges
;
2758 ParseRangeList(Ranges
);
2759 if (Ranges
.empty()) return nullptr;
2761 // Reverse the bitlist.
2762 std::reverse(Ranges
.begin(), Ranges
.end());
2763 Result
= Result
->convertInitializerBitRange(Ranges
);
2765 Error(CurlyLoc
, "Invalid bit range for value");
2770 if (!consume(tgtok::r_brace
)) {
2771 TokError("expected '}' at end of bit range list");
2776 case tgtok::l_square
: {
2777 auto *LHS
= dyn_cast
<TypedInit
>(Result
);
2779 Error(LHSLoc
, "Invalid value, list expected");
2783 auto *LHSTy
= dyn_cast
<ListRecTy
>(LHS
->getType());
2785 Error(LHSLoc
, "Type '" + Twine(LHS
->getType()->getAsString()) +
2786 "' is invalid, list expected");
2790 Lex
.Lex(); // eat the '['
2791 TypedInit
*RHS
= ParseSliceElements(CurRec
, /*Single=*/true);
2795 if (isa
<ListRecTy
>(RHS
->getType())) {
2797 BinOpInit::get(BinOpInit::LISTSLICE
, LHS
, RHS
, LHSTy
)->Fold(CurRec
);
2799 Result
= BinOpInit::get(BinOpInit::LISTELEM
, LHS
, RHS
,
2800 LHSTy
->getElementType())
2807 if (!consume(tgtok::r_square
)) {
2808 TokError("expected ']' at end of list slice");
2814 if (Lex
.Lex() != tgtok::Id
) { // eat the .
2815 TokError("expected field identifier after '.'");
2818 SMRange FieldNameLoc
= Lex
.getLocRange();
2819 StringInit
*FieldName
= StringInit::get(Records
, Lex
.getCurStrVal());
2820 if (!Result
->getFieldType(FieldName
)) {
2821 TokError("Cannot access field '" + Lex
.getCurStrVal() + "' of value '" +
2822 Result
->getAsString() + "'");
2826 // Add a reference to this field if we know the record class.
2827 if (TrackReferenceLocs
) {
2828 if (auto *DI
= dyn_cast
<DefInit
>(Result
)) {
2829 DI
->getDef()->getValue(FieldName
)->addReferenceLoc(FieldNameLoc
);
2830 } else if (auto *TI
= dyn_cast
<TypedInit
>(Result
)) {
2831 if (auto *RecTy
= dyn_cast
<RecordRecTy
>(TI
->getType())) {
2832 for (Record
*R
: RecTy
->getClasses())
2833 if (auto *RV
= R
->getValue(FieldName
))
2834 RV
->addReferenceLoc(FieldNameLoc
);
2839 Result
= FieldInit::get(Result
, FieldName
)->Fold(CurRec
);
2840 Lex
.Lex(); // eat field name
2845 SMLoc PasteLoc
= Lex
.getLoc();
2846 TypedInit
*LHS
= dyn_cast
<TypedInit
>(Result
);
2848 Error(PasteLoc
, "LHS of paste is not typed!");
2852 // Check if it's a 'listA # listB'
2853 if (isa
<ListRecTy
>(LHS
->getType())) {
2854 Lex
.Lex(); // Eat the '#'.
2856 assert(Mode
== ParseValueMode
&& "encountered paste of lists in name");
2858 switch (Lex
.getCode()) {
2861 case tgtok::l_brace
:
2862 Result
= LHS
; // trailing paste, ignore.
2865 Init
*RHSResult
= ParseValue(CurRec
, ItemType
, ParseValueMode
);
2868 Result
= BinOpInit::getListConcat(LHS
, RHSResult
);
2874 // Create a !strconcat() operation, first casting each operand to
2875 // a string if necessary.
2876 if (LHS
->getType() != StringRecTy::get(Records
)) {
2877 auto CastLHS
= dyn_cast
<TypedInit
>(
2878 UnOpInit::get(UnOpInit::CAST
, LHS
, StringRecTy::get(Records
))
2882 Twine("can't cast '") + LHS
->getAsString() + "' to string");
2888 TypedInit
*RHS
= nullptr;
2890 Lex
.Lex(); // Eat the '#'.
2891 switch (Lex
.getCode()) {
2894 case tgtok::l_brace
:
2895 // These are all of the tokens that can begin an object body.
2896 // Some of these can also begin values but we disallow those cases
2897 // because they are unlikely to be useful.
2899 // Trailing paste, concat with an empty string.
2900 RHS
= StringInit::get(Records
, "");
2904 Init
*RHSResult
= ParseValue(CurRec
, nullptr, ParseNameMode
);
2907 RHS
= dyn_cast
<TypedInit
>(RHSResult
);
2909 Error(PasteLoc
, "RHS of paste is not typed!");
2913 if (RHS
->getType() != StringRecTy::get(Records
)) {
2914 auto CastRHS
= dyn_cast
<TypedInit
>(
2915 UnOpInit::get(UnOpInit::CAST
, RHS
, StringRecTy::get(Records
))
2919 Twine("can't cast '") + RHS
->getAsString() + "' to string");
2928 Result
= BinOpInit::getStrConcat(LHS
, RHS
);
2934 /// ParseDagArgList - Parse the argument list for a dag literal expression.
2936 /// DagArg ::= Value (':' VARNAME)?
2937 /// DagArg ::= VARNAME
2938 /// DagArgList ::= DagArg
2939 /// DagArgList ::= DagArgList ',' DagArg
2940 void TGParser::ParseDagArgList(
2941 SmallVectorImpl
<std::pair
<llvm::Init
*, StringInit
*>> &Result
,
2945 // DagArg ::= VARNAME
2946 if (Lex
.getCode() == tgtok::VarName
) {
2947 // A missing value is treated like '?'.
2948 StringInit
*VarName
= StringInit::get(Records
, Lex
.getCurStrVal());
2949 Result
.emplace_back(UnsetInit::get(Records
), VarName
);
2952 // DagArg ::= Value (':' VARNAME)?
2953 Init
*Val
= ParseValue(CurRec
);
2959 // If the variable name is present, add it.
2960 StringInit
*VarName
= nullptr;
2961 if (Lex
.getCode() == tgtok::colon
) {
2962 if (Lex
.Lex() != tgtok::VarName
) { // eat the ':'
2963 TokError("expected variable name in dag literal");
2967 VarName
= StringInit::get(Records
, Lex
.getCurStrVal());
2968 Lex
.Lex(); // eat the VarName.
2971 Result
.push_back(std::make_pair(Val
, VarName
));
2973 if (!consume(tgtok::comma
))
2978 /// ParseValueList - Parse a comma separated list of values, returning them
2979 /// in a vector. Note that this always expects to be able to parse at least one
2980 /// value. It returns an empty list if this is not possible.
2982 /// ValueList ::= Value (',' Value)
2984 void TGParser::ParseValueList(SmallVectorImpl
<Init
*> &Result
, Record
*CurRec
,
2987 Result
.push_back(ParseValue(CurRec
, ItemType
));
2988 if (!Result
.back()) {
2993 while (consume(tgtok::comma
)) {
2994 // ignore trailing comma for lists
2995 if (Lex
.getCode() == tgtok::r_square
)
2997 Result
.push_back(ParseValue(CurRec
, ItemType
));
2998 if (!Result
.back()) {
3005 // ParseTemplateArgValueList - Parse a template argument list with the syntax
3006 // shown, filling in the Result vector. The open angle has been consumed.
3007 // An empty argument list is allowed. Return false if okay, true if an
3008 // error was detected.
3010 // TemplateArgList ::= '<' [Value {',' Value}*] '>'
3011 bool TGParser::ParseTemplateArgValueList(SmallVectorImpl
<Init
*> &Result
,
3012 Record
*CurRec
, Record
*ArgsRec
) {
3014 assert(Result
.empty() && "Result vector is not empty");
3015 ArrayRef
<Init
*> TArgs
= ArgsRec
->getTemplateArgs();
3016 unsigned ArgIndex
= 0;
3019 if (consume(tgtok::greater
)) // empty value list
3023 if (ArgIndex
>= TArgs
.size()) {
3024 TokError("Too many template arguments: " + utostr(ArgIndex
+ 1));
3027 const RecordVal
*Arg
= ArgsRec
->getValue(TArgs
[ArgIndex
]);
3028 assert(Arg
&& "Template argument record not found");
3030 ItemType
= Arg
->getType();
3031 Init
*Value
= ParseValue(CurRec
, ItemType
);
3034 Result
.push_back(Value
);
3036 if (consume(tgtok::greater
)) // end of argument list?
3038 if (!consume(tgtok::comma
))
3039 return TokError("Expected comma before next argument");
3044 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
3045 /// empty string on error. This can happen in a number of different contexts,
3046 /// including within a def or in the template args for a class (in which case
3047 /// CurRec will be non-null) and within the template args for a multiclass (in
3048 /// which case CurRec will be null, but CurMultiClass will be set). This can
3049 /// also happen within a def that is within a multiclass, which will set both
3050 /// CurRec and CurMultiClass.
3052 /// Declaration ::= FIELD? Type ID ('=' Value)?
3054 Init
*TGParser::ParseDeclaration(Record
*CurRec
,
3055 bool ParsingTemplateArgs
) {
3056 // Read the field prefix if present.
3057 bool HasField
= consume(tgtok::Field
);
3059 RecTy
*Type
= ParseType();
3060 if (!Type
) return nullptr;
3062 if (Lex
.getCode() != tgtok::Id
) {
3063 TokError("Expected identifier in declaration");
3067 std::string Str
= Lex
.getCurStrVal();
3068 if (Str
== "NAME") {
3069 TokError("'" + Str
+ "' is a reserved variable name");
3073 SMLoc IdLoc
= Lex
.getLoc();
3074 Init
*DeclName
= StringInit::get(Records
, Str
);
3078 if (!ParsingTemplateArgs
) { // def, possibly in a multiclass
3079 BadField
= AddValue(CurRec
, IdLoc
,
3080 RecordVal(DeclName
, IdLoc
, Type
,
3081 HasField
? RecordVal::FK_NonconcreteOK
3082 : RecordVal::FK_Normal
));
3084 } else if (CurRec
) { // class template argument
3085 DeclName
= QualifyName(*CurRec
, CurMultiClass
, DeclName
, ":");
3086 BadField
= AddValue(CurRec
, IdLoc
, RecordVal(DeclName
, IdLoc
, Type
,
3087 RecordVal::FK_TemplateArg
));
3089 } else { // multiclass template argument
3090 assert(CurMultiClass
&& "invalid context for template argument");
3091 DeclName
= QualifyName(CurMultiClass
->Rec
, CurMultiClass
, DeclName
, "::");
3092 BadField
= AddValue(CurRec
, IdLoc
, RecordVal(DeclName
, IdLoc
, Type
,
3093 RecordVal::FK_TemplateArg
));
3098 // If a value is present, parse it and set new field's value.
3099 if (consume(tgtok::equal
)) {
3100 SMLoc ValLoc
= Lex
.getLoc();
3101 Init
*Val
= ParseValue(CurRec
, Type
);
3103 SetValue(CurRec
, ValLoc
, DeclName
, std::nullopt
, Val
,
3104 /*AllowSelfAssignment=*/false, /*OverrideDefLoc=*/false)) {
3105 // Return the name, even if an error is thrown. This is so that we can
3106 // continue to make some progress, even without the value having been
3115 /// ParseForeachDeclaration - Read a foreach declaration, returning
3116 /// the name of the declared object or a NULL Init on error. Return
3117 /// the name of the parsed initializer list through ForeachListName.
3119 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
3120 /// ForeachDeclaration ::= ID '=' RangePiece
3121 /// ForeachDeclaration ::= ID '=' Value
3123 VarInit
*TGParser::ParseForeachDeclaration(Init
*&ForeachListValue
) {
3124 if (Lex
.getCode() != tgtok::Id
) {
3125 TokError("Expected identifier in foreach declaration");
3129 Init
*DeclName
= StringInit::get(Records
, Lex
.getCurStrVal());
3132 // If a value is present, parse it.
3133 if (!consume(tgtok::equal
)) {
3134 TokError("Expected '=' in foreach declaration");
3138 RecTy
*IterType
= nullptr;
3139 SmallVector
<unsigned, 16> Ranges
;
3141 switch (Lex
.getCode()) {
3142 case tgtok::l_brace
: { // '{' RangeList '}'
3143 Lex
.Lex(); // eat the '{'
3144 ParseRangeList(Ranges
);
3145 if (!consume(tgtok::r_brace
)) {
3146 TokError("expected '}' at end of bit range list");
3153 SMLoc ValueLoc
= Lex
.getLoc();
3154 Init
*I
= ParseValue(nullptr);
3158 TypedInit
*TI
= dyn_cast
<TypedInit
>(I
);
3159 if (TI
&& isa
<ListRecTy
>(TI
->getType())) {
3160 ForeachListValue
= I
;
3161 IterType
= cast
<ListRecTy
>(TI
->getType())->getElementType();
3166 if (ParseRangePiece(Ranges
, TI
))
3171 Error(ValueLoc
, "expected a list, got '" + I
->getAsString() + "'");
3172 if (CurMultiClass
) {
3173 PrintNote({}, "references to multiclass template arguments cannot be "
3174 "resolved at this time");
3181 if (!Ranges
.empty()) {
3182 assert(!IterType
&& "Type already initialized?");
3183 IterType
= IntRecTy::get(Records
);
3184 std::vector
<Init
*> Values
;
3185 for (unsigned R
: Ranges
)
3186 Values
.push_back(IntInit::get(Records
, R
));
3187 ForeachListValue
= ListInit::get(Values
, IterType
);
3193 return VarInit::get(DeclName
, IterType
);
3196 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
3197 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
3198 /// template args for a class. If null, these are the template args for a
3201 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
3203 bool TGParser::ParseTemplateArgList(Record
*CurRec
) {
3204 assert(Lex
.getCode() == tgtok::less
&& "Not a template arg list!");
3205 Lex
.Lex(); // eat the '<'
3207 Record
*TheRecToAddTo
= CurRec
? CurRec
: &CurMultiClass
->Rec
;
3209 // Read the first declaration.
3210 Init
*TemplArg
= ParseDeclaration(CurRec
, true/*templateargs*/);
3214 TheRecToAddTo
->addTemplateArg(TemplArg
);
3216 while (consume(tgtok::comma
)) {
3217 // Read the following declarations.
3218 SMLoc Loc
= Lex
.getLoc();
3219 TemplArg
= ParseDeclaration(CurRec
, true/*templateargs*/);
3223 if (TheRecToAddTo
->isTemplateArg(TemplArg
))
3224 return Error(Loc
, "template argument with the same name has already been "
3227 TheRecToAddTo
->addTemplateArg(TemplArg
);
3230 if (!consume(tgtok::greater
))
3231 return TokError("expected '>' at end of template argument list");
3235 /// ParseBodyItem - Parse a single item within the body of a def or class.
3237 /// BodyItem ::= Declaration ';'
3238 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
3239 /// BodyItem ::= Defvar
3240 /// BodyItem ::= Assert
3242 bool TGParser::ParseBodyItem(Record
*CurRec
) {
3243 if (Lex
.getCode() == tgtok::Assert
)
3244 return ParseAssert(nullptr, CurRec
);
3246 if (Lex
.getCode() == tgtok::Defvar
)
3247 return ParseDefvar(CurRec
);
3249 if (Lex
.getCode() != tgtok::Let
) {
3250 if (!ParseDeclaration(CurRec
, false))
3253 if (!consume(tgtok::semi
))
3254 return TokError("expected ';' after declaration");
3258 // LET ID OptionalRangeList '=' Value ';'
3259 if (Lex
.Lex() != tgtok::Id
)
3260 return TokError("expected field identifier after let");
3262 SMLoc IdLoc
= Lex
.getLoc();
3263 StringInit
*FieldName
= StringInit::get(Records
, Lex
.getCurStrVal());
3264 Lex
.Lex(); // eat the field name.
3266 SmallVector
<unsigned, 16> BitList
;
3267 if (ParseOptionalBitList(BitList
))
3269 std::reverse(BitList
.begin(), BitList
.end());
3271 if (!consume(tgtok::equal
))
3272 return TokError("expected '=' in let expression");
3274 RecordVal
*Field
= CurRec
->getValue(FieldName
);
3276 return TokError("Value '" + FieldName
->getValue() + "' unknown!");
3278 RecTy
*Type
= Field
->getType();
3279 if (!BitList
.empty() && isa
<BitsRecTy
>(Type
)) {
3280 // When assigning to a subset of a 'bits' object, expect the RHS to have
3281 // the type of that subset instead of the type of the whole object.
3282 Type
= BitsRecTy::get(Records
, BitList
.size());
3285 Init
*Val
= ParseValue(CurRec
, Type
);
3286 if (!Val
) return true;
3288 if (!consume(tgtok::semi
))
3289 return TokError("expected ';' after let expression");
3291 return SetValue(CurRec
, IdLoc
, FieldName
, BitList
, Val
);
3294 /// ParseBody - Read the body of a class or def. Return true on error, false on
3298 /// Body ::= '{' BodyList '}'
3299 /// BodyList BodyItem*
3301 bool TGParser::ParseBody(Record
*CurRec
) {
3302 // If this is a null definition, just eat the semi and return.
3303 if (consume(tgtok::semi
))
3306 if (!consume(tgtok::l_brace
))
3307 return TokError("Expected '{' to start body or ';' for declaration only");
3309 // An object body introduces a new scope for local variables.
3310 TGLocalVarScope
*BodyScope
= PushLocalScope();
3312 while (Lex
.getCode() != tgtok::r_brace
)
3313 if (ParseBodyItem(CurRec
))
3316 PopLocalScope(BodyScope
);
3321 // If we have a semicolon, print a gentle error.
3322 SMLoc SemiLoc
= Lex
.getLoc();
3323 if (consume(tgtok::semi
)) {
3324 PrintError(SemiLoc
, "A class or def body should not end with a semicolon");
3325 PrintNote("Semicolon ignored; remove to eliminate this error");
3331 /// Apply the current let bindings to \a CurRec.
3332 /// \returns true on error, false otherwise.
3333 bool TGParser::ApplyLetStack(Record
*CurRec
) {
3334 for (SmallVectorImpl
<LetRecord
> &LetInfo
: LetStack
)
3335 for (LetRecord
&LR
: LetInfo
)
3336 if (SetValue(CurRec
, LR
.Loc
, LR
.Name
, LR
.Bits
, LR
.Value
))
3341 /// Apply the current let bindings to the RecordsEntry.
3342 bool TGParser::ApplyLetStack(RecordsEntry
&Entry
) {
3344 return ApplyLetStack(Entry
.Rec
.get());
3346 // Let bindings are not applied to assertions.
3347 if (Entry
.Assertion
)
3350 for (auto &E
: Entry
.Loop
->Entries
) {
3351 if (ApplyLetStack(E
))
3358 /// ParseObjectBody - Parse the body of a def or class. This consists of an
3359 /// optional ClassList followed by a Body. CurRec is the current def or class
3360 /// that is being parsed.
3362 /// ObjectBody ::= BaseClassList Body
3363 /// BaseClassList ::= /*empty*/
3364 /// BaseClassList ::= ':' BaseClassListNE
3365 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
3367 bool TGParser::ParseObjectBody(Record
*CurRec
) {
3368 // If there is a baseclass list, read it.
3369 if (consume(tgtok::colon
)) {
3371 // Read all of the subclasses.
3372 SubClassReference SubClass
= ParseSubClassReference(CurRec
, false);
3375 if (!SubClass
.Rec
) return true;
3378 if (AddSubClass(CurRec
, SubClass
))
3381 if (!consume(tgtok::comma
))
3383 SubClass
= ParseSubClassReference(CurRec
, false);
3387 if (ApplyLetStack(CurRec
))
3390 return ParseBody(CurRec
);
3393 /// ParseDef - Parse and return a top level or multiclass record definition.
3394 /// Return false if okay, true if error.
3396 /// DefInst ::= DEF ObjectName ObjectBody
3398 bool TGParser::ParseDef(MultiClass
*CurMultiClass
) {
3399 SMLoc DefLoc
= Lex
.getLoc();
3400 assert(Lex
.getCode() == tgtok::Def
&& "Unknown tok");
3401 Lex
.Lex(); // Eat the 'def' token.
3403 // If the name of the def is an Id token, use that for the location.
3404 // Otherwise, the name is more complex and we use the location of the 'def'
3406 SMLoc NameLoc
= Lex
.getCode() == tgtok::Id
? Lex
.getLoc() : DefLoc
;
3408 // Parse ObjectName and make a record for it.
3409 std::unique_ptr
<Record
> CurRec
;
3410 Init
*Name
= ParseObjectName(CurMultiClass
);
3414 if (isa
<UnsetInit
>(Name
)) {
3416 std::make_unique
<Record
>(Records
.getNewAnonymousName(), DefLoc
, Records
,
3417 /*Anonymous=*/true);
3419 CurRec
= std::make_unique
<Record
>(Name
, NameLoc
, Records
);
3422 if (ParseObjectBody(CurRec
.get()))
3425 return addEntry(std::move(CurRec
));
3428 /// ParseDefset - Parse a defset statement.
3430 /// Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
3432 bool TGParser::ParseDefset() {
3433 assert(Lex
.getCode() == tgtok::Defset
);
3434 Lex
.Lex(); // Eat the 'defset' token
3436 DefsetRecord Defset
;
3437 Defset
.Loc
= Lex
.getLoc();
3438 RecTy
*Type
= ParseType();
3441 if (!isa
<ListRecTy
>(Type
))
3442 return Error(Defset
.Loc
, "expected list type");
3443 Defset
.EltTy
= cast
<ListRecTy
>(Type
)->getElementType();
3445 if (Lex
.getCode() != tgtok::Id
)
3446 return TokError("expected identifier");
3447 StringInit
*DeclName
= StringInit::get(Records
, Lex
.getCurStrVal());
3448 if (Records
.getGlobal(DeclName
->getValue()))
3449 return TokError("def or global variable of this name already exists");
3451 if (Lex
.Lex() != tgtok::equal
) // Eat the identifier
3452 return TokError("expected '='");
3453 if (Lex
.Lex() != tgtok::l_brace
) // Eat the '='
3454 return TokError("expected '{'");
3455 SMLoc BraceLoc
= Lex
.getLoc();
3456 Lex
.Lex(); // Eat the '{'
3458 Defsets
.push_back(&Defset
);
3459 bool Err
= ParseObjectList(nullptr);
3464 if (!consume(tgtok::r_brace
)) {
3465 TokError("expected '}' at end of defset");
3466 return Error(BraceLoc
, "to match this '{'");
3469 Records
.addExtraGlobal(DeclName
->getValue(),
3470 ListInit::get(Defset
.Elements
, Defset
.EltTy
));
3474 /// ParseDefvar - Parse a defvar statement.
3476 /// Defvar ::= DEFVAR Id '=' Value ';'
3478 bool TGParser::ParseDefvar(Record
*CurRec
) {
3479 assert(Lex
.getCode() == tgtok::Defvar
);
3480 Lex
.Lex(); // Eat the 'defvar' token
3482 if (Lex
.getCode() != tgtok::Id
)
3483 return TokError("expected identifier");
3484 StringInit
*DeclName
= StringInit::get(Records
, Lex
.getCurStrVal());
3485 if (CurLocalScope
) {
3486 if (CurLocalScope
->varAlreadyDefined(DeclName
->getValue()))
3487 return TokError("local variable of this name already exists");
3489 if (Records
.getGlobal(DeclName
->getValue()))
3490 return TokError("def or global variable of this name already exists");
3494 if (!consume(tgtok::equal
))
3495 return TokError("expected '='");
3497 Init
*Value
= ParseValue(CurRec
);
3501 if (!consume(tgtok::semi
))
3502 return TokError("expected ';'");
3505 CurLocalScope
->addVar(DeclName
->getValue(), Value
);
3507 Records
.addExtraGlobal(DeclName
->getValue(), Value
);
3512 /// ParseForeach - Parse a for statement. Return the record corresponding
3513 /// to it. This returns true on error.
3515 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
3516 /// Foreach ::= FOREACH Declaration IN Object
3518 bool TGParser::ParseForeach(MultiClass
*CurMultiClass
) {
3519 SMLoc Loc
= Lex
.getLoc();
3520 assert(Lex
.getCode() == tgtok::Foreach
&& "Unknown tok");
3521 Lex
.Lex(); // Eat the 'for' token.
3523 // Make a temporary object to record items associated with the for
3525 Init
*ListValue
= nullptr;
3526 VarInit
*IterName
= ParseForeachDeclaration(ListValue
);
3528 return TokError("expected declaration in for");
3530 if (!consume(tgtok::In
))
3531 return TokError("Unknown tok");
3533 // Create a loop object and remember it.
3534 Loops
.push_back(std::make_unique
<ForeachLoop
>(Loc
, IterName
, ListValue
));
3536 // A foreach loop introduces a new scope for local variables.
3537 TGLocalVarScope
*ForeachScope
= PushLocalScope();
3539 if (Lex
.getCode() != tgtok::l_brace
) {
3540 // FOREACH Declaration IN Object
3541 if (ParseObject(CurMultiClass
))
3544 SMLoc BraceLoc
= Lex
.getLoc();
3545 // Otherwise, this is a group foreach.
3546 Lex
.Lex(); // eat the '{'.
3548 // Parse the object list.
3549 if (ParseObjectList(CurMultiClass
))
3552 if (!consume(tgtok::r_brace
)) {
3553 TokError("expected '}' at end of foreach command");
3554 return Error(BraceLoc
, "to match this '{'");
3558 PopLocalScope(ForeachScope
);
3560 // Resolve the loop or store it for later resolution.
3561 std::unique_ptr
<ForeachLoop
> Loop
= std::move(Loops
.back());
3564 return addEntry(std::move(Loop
));
3567 /// ParseIf - Parse an if statement.
3569 /// If ::= IF Value THEN IfBody
3570 /// If ::= IF Value THEN IfBody ELSE IfBody
3572 bool TGParser::ParseIf(MultiClass
*CurMultiClass
) {
3573 SMLoc Loc
= Lex
.getLoc();
3574 assert(Lex
.getCode() == tgtok::If
&& "Unknown tok");
3575 Lex
.Lex(); // Eat the 'if' token.
3577 // Make a temporary object to record items associated with the for
3579 Init
*Condition
= ParseValue(nullptr);
3583 if (!consume(tgtok::Then
))
3584 return TokError("Unknown tok");
3586 // We have to be able to save if statements to execute later, and they have
3587 // to live on the same stack as foreach loops. The simplest implementation
3588 // technique is to convert each 'then' or 'else' clause *into* a foreach
3589 // loop, over a list of length 0 or 1 depending on the condition, and with no
3590 // iteration variable being assigned.
3592 ListInit
*EmptyList
= ListInit::get({}, BitRecTy::get(Records
));
3593 ListInit
*SingletonList
=
3594 ListInit::get({BitInit::get(Records
, true)}, BitRecTy::get(Records
));
3595 RecTy
*BitListTy
= ListRecTy::get(BitRecTy::get(Records
));
3597 // The foreach containing the then-clause selects SingletonList if
3598 // the condition is true.
3599 Init
*ThenClauseList
=
3600 TernOpInit::get(TernOpInit::IF
, Condition
, SingletonList
, EmptyList
,
3603 Loops
.push_back(std::make_unique
<ForeachLoop
>(Loc
, nullptr, ThenClauseList
));
3605 if (ParseIfBody(CurMultiClass
, "then"))
3608 std::unique_ptr
<ForeachLoop
> Loop
= std::move(Loops
.back());
3611 if (addEntry(std::move(Loop
)))
3614 // Now look for an optional else clause. The if-else syntax has the usual
3615 // dangling-else ambiguity, and by greedily matching an else here if we can,
3616 // we implement the usual resolution of pairing with the innermost unmatched
3618 if (consume(tgtok::ElseKW
)) {
3619 // The foreach containing the else-clause uses the same pair of lists as
3620 // above, but this time, selects SingletonList if the condition is *false*.
3621 Init
*ElseClauseList
=
3622 TernOpInit::get(TernOpInit::IF
, Condition
, EmptyList
, SingletonList
,
3626 std::make_unique
<ForeachLoop
>(Loc
, nullptr, ElseClauseList
));
3628 if (ParseIfBody(CurMultiClass
, "else"))
3631 Loop
= std::move(Loops
.back());
3634 if (addEntry(std::move(Loop
)))
3641 /// ParseIfBody - Parse the then-clause or else-clause of an if statement.
3643 /// IfBody ::= Object
3644 /// IfBody ::= '{' ObjectList '}'
3646 bool TGParser::ParseIfBody(MultiClass
*CurMultiClass
, StringRef Kind
) {
3647 TGLocalVarScope
*BodyScope
= PushLocalScope();
3649 if (Lex
.getCode() != tgtok::l_brace
) {
3651 if (ParseObject(CurMultiClass
))
3654 SMLoc BraceLoc
= Lex
.getLoc();
3656 Lex
.Lex(); // eat the '{'.
3658 // Parse the object list.
3659 if (ParseObjectList(CurMultiClass
))
3662 if (!consume(tgtok::r_brace
)) {
3663 TokError("expected '}' at end of '" + Kind
+ "' clause");
3664 return Error(BraceLoc
, "to match this '{'");
3668 PopLocalScope(BodyScope
);
3672 /// ParseAssert - Parse an assert statement.
3674 /// Assert ::= ASSERT condition , message ;
3675 bool TGParser::ParseAssert(MultiClass
*CurMultiClass
, Record
*CurRec
) {
3676 assert(Lex
.getCode() == tgtok::Assert
&& "Unknown tok");
3677 Lex
.Lex(); // Eat the 'assert' token.
3679 SMLoc ConditionLoc
= Lex
.getLoc();
3680 Init
*Condition
= ParseValue(CurRec
);
3684 if (!consume(tgtok::comma
)) {
3685 TokError("expected ',' in assert statement");
3689 Init
*Message
= ParseValue(CurRec
);
3693 if (!consume(tgtok::semi
))
3694 return TokError("expected ';'");
3697 CurRec
->addAssertion(ConditionLoc
, Condition
, Message
);
3699 addEntry(std::make_unique
<Record::AssertionInfo
>(ConditionLoc
, Condition
,
3704 /// ParseClass - Parse a tblgen class definition.
3706 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
3708 bool TGParser::ParseClass() {
3709 assert(Lex
.getCode() == tgtok::Class
&& "Unexpected token!");
3712 if (Lex
.getCode() != tgtok::Id
)
3713 return TokError("expected class name after 'class' keyword");
3715 Record
*CurRec
= Records
.getClass(Lex
.getCurStrVal());
3717 // If the body was previously defined, this is an error.
3718 if (!CurRec
->getValues().empty() ||
3719 !CurRec
->getSuperClasses().empty() ||
3720 !CurRec
->getTemplateArgs().empty())
3721 return TokError("Class '" + CurRec
->getNameInitAsString() +
3722 "' already defined");
3724 CurRec
->updateClassLoc(Lex
.getLoc());
3726 // If this is the first reference to this class, create and add it.
3728 std::make_unique
<Record
>(Lex
.getCurStrVal(), Lex
.getLoc(), Records
,
3730 CurRec
= NewRec
.get();
3731 Records
.addClass(std::move(NewRec
));
3733 Lex
.Lex(); // eat the name.
3735 // If there are template args, parse them.
3736 if (Lex
.getCode() == tgtok::less
)
3737 if (ParseTemplateArgList(CurRec
))
3740 if (ParseObjectBody(CurRec
))
3743 if (!NoWarnOnUnusedTemplateArgs
)
3744 CurRec
->checkUnusedTemplateArgs();
3748 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
3751 /// LetList ::= LetItem (',' LetItem)*
3752 /// LetItem ::= ID OptionalRangeList '=' Value
3754 void TGParser::ParseLetList(SmallVectorImpl
<LetRecord
> &Result
) {
3756 if (Lex
.getCode() != tgtok::Id
) {
3757 TokError("expected identifier in let definition");
3762 StringInit
*Name
= StringInit::get(Records
, Lex
.getCurStrVal());
3763 SMLoc NameLoc
= Lex
.getLoc();
3764 Lex
.Lex(); // Eat the identifier.
3766 // Check for an optional RangeList.
3767 SmallVector
<unsigned, 16> Bits
;
3768 if (ParseOptionalRangeList(Bits
)) {
3772 std::reverse(Bits
.begin(), Bits
.end());
3774 if (!consume(tgtok::equal
)) {
3775 TokError("expected '=' in let expression");
3780 Init
*Val
= ParseValue(nullptr);
3786 // Now that we have everything, add the record.
3787 Result
.emplace_back(Name
, Bits
, Val
, NameLoc
);
3788 } while (consume(tgtok::comma
));
3791 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
3792 /// different related productions. This works inside multiclasses too.
3794 /// Object ::= LET LetList IN '{' ObjectList '}'
3795 /// Object ::= LET LetList IN Object
3797 bool TGParser::ParseTopLevelLet(MultiClass
*CurMultiClass
) {
3798 assert(Lex
.getCode() == tgtok::Let
&& "Unexpected token");
3801 // Add this entry to the let stack.
3802 SmallVector
<LetRecord
, 8> LetInfo
;
3803 ParseLetList(LetInfo
);
3804 if (LetInfo
.empty()) return true;
3805 LetStack
.push_back(std::move(LetInfo
));
3807 if (!consume(tgtok::In
))
3808 return TokError("expected 'in' at end of top-level 'let'");
3810 TGLocalVarScope
*LetScope
= PushLocalScope();
3812 // If this is a scalar let, just handle it now
3813 if (Lex
.getCode() != tgtok::l_brace
) {
3814 // LET LetList IN Object
3815 if (ParseObject(CurMultiClass
))
3817 } else { // Object ::= LETCommand '{' ObjectList '}'
3818 SMLoc BraceLoc
= Lex
.getLoc();
3819 // Otherwise, this is a group let.
3820 Lex
.Lex(); // eat the '{'.
3822 // Parse the object list.
3823 if (ParseObjectList(CurMultiClass
))
3826 if (!consume(tgtok::r_brace
)) {
3827 TokError("expected '}' at end of top level let command");
3828 return Error(BraceLoc
, "to match this '{'");
3832 PopLocalScope(LetScope
);
3834 // Outside this let scope, this let block is not active.
3835 LetStack
.pop_back();
3839 /// ParseMultiClass - Parse a multiclass definition.
3841 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
3842 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
3843 /// MultiClassObject ::= Assert
3844 /// MultiClassObject ::= DefInst
3845 /// MultiClassObject ::= DefMInst
3846 /// MultiClassObject ::= Defvar
3847 /// MultiClassObject ::= Foreach
3848 /// MultiClassObject ::= If
3849 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
3850 /// MultiClassObject ::= LETCommand Object
3852 bool TGParser::ParseMultiClass() {
3853 assert(Lex
.getCode() == tgtok::MultiClass
&& "Unexpected token");
3854 Lex
.Lex(); // Eat the multiclass token.
3856 if (Lex
.getCode() != tgtok::Id
)
3857 return TokError("expected identifier after multiclass for name");
3858 std::string Name
= Lex
.getCurStrVal();
3861 MultiClasses
.insert(std::make_pair(Name
,
3862 std::make_unique
<MultiClass
>(Name
, Lex
.getLoc(),Records
)));
3865 return TokError("multiclass '" + Name
+ "' already defined");
3867 CurMultiClass
= Result
.first
->second
.get();
3868 Lex
.Lex(); // Eat the identifier.
3870 // If there are template args, parse them.
3871 if (Lex
.getCode() == tgtok::less
)
3872 if (ParseTemplateArgList(nullptr))
3875 bool inherits
= false;
3877 // If there are submulticlasses, parse them.
3878 if (consume(tgtok::colon
)) {
3881 // Read all of the submulticlasses.
3882 SubMultiClassReference SubMultiClass
=
3883 ParseSubMultiClassReference(CurMultiClass
);
3886 if (!SubMultiClass
.MC
) return true;
3889 if (AddSubMultiClass(CurMultiClass
, SubMultiClass
))
3892 if (!consume(tgtok::comma
))
3894 SubMultiClass
= ParseSubMultiClassReference(CurMultiClass
);
3898 if (Lex
.getCode() != tgtok::l_brace
) {
3900 return TokError("expected '{' in multiclass definition");
3901 if (!consume(tgtok::semi
))
3902 return TokError("expected ';' in multiclass definition");
3904 if (Lex
.Lex() == tgtok::r_brace
) // eat the '{'.
3905 return TokError("multiclass must contain at least one def");
3907 // A multiclass body introduces a new scope for local variables.
3908 TGLocalVarScope
*MulticlassScope
= PushLocalScope();
3910 while (Lex
.getCode() != tgtok::r_brace
) {
3911 switch (Lex
.getCode()) {
3913 return TokError("expected 'assert', 'def', 'defm', 'defvar', "
3914 "'foreach', 'if', or 'let' in multiclass body");
3920 case tgtok::Foreach
:
3923 if (ParseObject(CurMultiClass
))
3928 Lex
.Lex(); // eat the '}'.
3930 // If we have a semicolon, print a gentle error.
3931 SMLoc SemiLoc
= Lex
.getLoc();
3932 if (consume(tgtok::semi
)) {
3933 PrintError(SemiLoc
, "A multiclass body should not end with a semicolon");
3934 PrintNote("Semicolon ignored; remove to eliminate this error");
3937 PopLocalScope(MulticlassScope
);
3940 if (!NoWarnOnUnusedTemplateArgs
)
3941 CurMultiClass
->Rec
.checkUnusedTemplateArgs();
3943 CurMultiClass
= nullptr;
3947 /// ParseDefm - Parse the instantiation of a multiclass.
3949 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
3951 bool TGParser::ParseDefm(MultiClass
*CurMultiClass
) {
3952 assert(Lex
.getCode() == tgtok::Defm
&& "Unexpected token!");
3953 Lex
.Lex(); // eat the defm
3955 Init
*DefmName
= ParseObjectName(CurMultiClass
);
3958 if (isa
<UnsetInit
>(DefmName
)) {
3959 DefmName
= Records
.getNewAnonymousName();
3961 DefmName
= BinOpInit::getStrConcat(
3962 VarInit::get(QualifiedNameOfImplicitName(CurMultiClass
),
3963 StringRecTy::get(Records
)),
3967 if (Lex
.getCode() != tgtok::colon
)
3968 return TokError("expected ':' after defm identifier");
3970 // Keep track of the new generated record definitions.
3971 std::vector
<RecordsEntry
> NewEntries
;
3973 // This record also inherits from a regular class (non-multiclass)?
3974 bool InheritFromClass
= false;
3979 SMLoc SubClassLoc
= Lex
.getLoc();
3980 SubClassReference Ref
= ParseSubClassReference(nullptr, true);
3983 if (!Ref
.Rec
) return true;
3985 // To instantiate a multiclass, we get the multiclass and then loop
3986 // through its template argument names. Substs contains a substitution
3987 // value for each argument, either the value specified or the default.
3988 // Then we can resolve the template arguments.
3989 MultiClass
*MC
= MultiClasses
[std::string(Ref
.Rec
->getName())].get();
3990 assert(MC
&& "Didn't lookup multiclass correctly?");
3992 ArrayRef
<Init
*> TemplateVals
= Ref
.TemplateArgs
;
3993 ArrayRef
<Init
*> TArgs
= MC
->Rec
.getTemplateArgs();
3996 for (unsigned i
= 0, e
= TArgs
.size(); i
!= e
; ++i
) {
3997 if (i
< TemplateVals
.size()) {
3998 Substs
.emplace_back(TArgs
[i
], TemplateVals
[i
]);
4000 Init
*Default
= MC
->Rec
.getValue(TArgs
[i
])->getValue();
4001 if (!Default
->isComplete())
4002 return Error(SubClassLoc
,
4003 "value not specified for template argument '" +
4004 TArgs
[i
]->getAsUnquotedString() + "' (#" +
4005 Twine(i
) + ") of multiclass '" +
4006 MC
->Rec
.getNameInitAsString() + "'");
4007 Substs
.emplace_back(TArgs
[i
], Default
);
4011 Substs
.emplace_back(QualifiedNameOfImplicitName(MC
), DefmName
);
4013 if (resolve(MC
->Entries
, Substs
, !CurMultiClass
&& Loops
.empty(),
4014 &NewEntries
, &SubClassLoc
))
4017 if (!consume(tgtok::comma
))
4020 if (Lex
.getCode() != tgtok::Id
)
4021 return TokError("expected identifier");
4023 SubClassLoc
= Lex
.getLoc();
4025 // A defm can inherit from regular classes (non-multiclasses) as
4026 // long as they come in the end of the inheritance list.
4027 InheritFromClass
= (Records
.getClass(Lex
.getCurStrVal()) != nullptr);
4029 if (InheritFromClass
)
4032 Ref
= ParseSubClassReference(nullptr, true);
4035 if (InheritFromClass
) {
4036 // Process all the classes to inherit as if they were part of a
4037 // regular 'def' and inherit all record values.
4038 SubClassReference SubClass
= ParseSubClassReference(nullptr, false);
4041 if (!SubClass
.Rec
) return true;
4043 // Get the expanded definition prototypes and teach them about
4044 // the record values the current class to inherit has
4045 for (auto &E
: NewEntries
) {
4047 if (AddSubClass(E
, SubClass
))
4051 if (!consume(tgtok::comma
))
4053 SubClass
= ParseSubClassReference(nullptr, false);
4057 for (auto &E
: NewEntries
) {
4058 if (ApplyLetStack(E
))
4061 addEntry(std::move(E
));
4064 if (!consume(tgtok::semi
))
4065 return TokError("expected ';' at end of defm");
4071 /// Object ::= ClassInst
4072 /// Object ::= DefInst
4073 /// Object ::= MultiClassInst
4074 /// Object ::= DefMInst
4075 /// Object ::= LETCommand '{' ObjectList '}'
4076 /// Object ::= LETCommand Object
4077 /// Object ::= Defset
4078 /// Object ::= Defvar
4079 /// Object ::= Assert
4080 bool TGParser::ParseObject(MultiClass
*MC
) {
4081 switch (Lex
.getCode()) {
4084 "Expected assert, class, def, defm, defset, foreach, if, or let");
4085 case tgtok::Assert
: return ParseAssert(MC
);
4086 case tgtok::Def
: return ParseDef(MC
);
4087 case tgtok::Defm
: return ParseDefm(MC
);
4088 case tgtok::Defvar
: return ParseDefvar();
4089 case tgtok::Foreach
: return ParseForeach(MC
);
4090 case tgtok::If
: return ParseIf(MC
);
4091 case tgtok::Let
: return ParseTopLevelLet(MC
);
4094 return TokError("defset is not allowed inside multiclass");
4095 return ParseDefset();
4098 return TokError("class is not allowed inside multiclass");
4100 return TokError("class is not allowed inside foreach loop");
4101 return ParseClass();
4102 case tgtok::MultiClass
:
4104 return TokError("multiclass is not allowed inside foreach loop");
4105 return ParseMultiClass();
4110 /// ObjectList :== Object*
4111 bool TGParser::ParseObjectList(MultiClass
*MC
) {
4112 while (isObjectStart(Lex
.getCode())) {
4113 if (ParseObject(MC
))
4119 bool TGParser::ParseFile() {
4120 Lex
.Lex(); // Prime the lexer.
4121 if (ParseObjectList()) return true;
4123 // If we have unread input at the end of the file, report it.
4124 if (Lex
.getCode() == tgtok::Eof
)
4127 return TokError("Unexpected token at top level");
4130 // Check the types of the template argument values for a class
4131 // inheritance, multiclass invocation, or anonymous class invocation.
4132 // If necessary, replace an argument with a cast to the required type.
4133 // The argument count has already been checked.
4134 bool TGParser::CheckTemplateArgValues(SmallVectorImpl
<llvm::Init
*> &Values
,
4135 SMLoc Loc
, Record
*ArgsRec
) {
4137 ArrayRef
<Init
*> TArgs
= ArgsRec
->getTemplateArgs();
4139 for (unsigned I
= 0, E
= Values
.size(); I
< E
; ++I
) {
4140 RecordVal
*Arg
= ArgsRec
->getValue(TArgs
[I
]);
4141 RecTy
*ArgType
= Arg
->getType();
4142 auto *Value
= Values
[I
];
4144 if (TypedInit
*ArgValue
= dyn_cast
<TypedInit
>(Value
)) {
4145 auto *CastValue
= ArgValue
->getCastTo(ArgType
);
4147 assert((!isa
<TypedInit
>(CastValue
) ||
4148 cast
<TypedInit
>(CastValue
)->getType()->typeIsA(ArgType
)) &&
4149 "result of template arg value cast has wrong type");
4150 Values
[I
] = CastValue
;
4152 PrintFatalError(Loc
,
4153 "Value specified for template argument '" +
4154 Arg
->getNameInitAsString() + "' (#" + Twine(I
) +
4155 ") is of type " + ArgValue
->getType()->getAsString() +
4156 "; expected type " + ArgType
->getAsString() + ": " +
4157 ArgValue
->getAsString());
4165 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4166 LLVM_DUMP_METHOD
void RecordsEntry::dump() const {
4173 LLVM_DUMP_METHOD
void ForeachLoop::dump() const {
4174 errs() << "foreach " << IterVar
->getAsString() << " = "
4175 << ListValue
->getAsString() << " in {\n";
4177 for (const auto &E
: Entries
)
4183 LLVM_DUMP_METHOD
void MultiClass::dump() const {
4184 errs() << "Record:\n";
4187 errs() << "Defs:\n";
4188 for (const auto &E
: Entries
)