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/SmallVector.h"
15 #include "llvm/ADT/StringExtras.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/Config/llvm-config.h"
18 #include "llvm/Support/Casting.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/raw_ostream.h"
29 //===----------------------------------------------------------------------===//
30 // Support Code for the Semantic Actions.
31 //===----------------------------------------------------------------------===//
35 struct SubClassReference
{
37 Record
*Rec
= nullptr;
38 SmallVector
<ArgumentInit
*, 4> TemplateArgs
;
40 SubClassReference() = default;
42 bool isInvalid() const { return Rec
== nullptr; }
45 struct SubMultiClassReference
{
47 MultiClass
*MC
= nullptr;
48 SmallVector
<ArgumentInit
*, 4> TemplateArgs
;
50 SubMultiClassReference() = default;
52 bool isInvalid() const { return MC
== nullptr; }
56 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
57 LLVM_DUMP_METHOD
void SubMultiClassReference::dump() const {
58 errs() << "Multiclass:\n";
62 errs() << "Template args:\n";
63 for (Init
*TA
: TemplateArgs
)
68 } // end namespace llvm
70 static bool checkBitsConcrete(Record
&R
, const RecordVal
&RV
) {
71 BitsInit
*BV
= cast
<BitsInit
>(RV
.getValue());
72 for (unsigned i
= 0, e
= BV
->getNumBits(); i
!= e
; ++i
) {
73 Init
*Bit
= BV
->getBit(i
);
74 bool IsReference
= false;
75 if (auto VBI
= dyn_cast
<VarBitInit
>(Bit
)) {
76 if (auto VI
= dyn_cast
<VarInit
>(VBI
->getBitVar())) {
77 if (R
.getValue(VI
->getName()))
80 } else if (isa
<VarInit
>(Bit
)) {
83 if (!(IsReference
|| Bit
->isConcrete()))
89 static void checkConcrete(Record
&R
) {
90 for (const RecordVal
&RV
: R
.getValues()) {
91 // HACK: Disable this check for variables declared with 'field'. This is
92 // done merely because existing targets have legitimate cases of
93 // non-concrete variables in helper defs. Ideally, we'd introduce a
94 // 'maybe' or 'optional' modifier instead of this.
95 if (RV
.isNonconcreteOK())
98 if (Init
*V
= RV
.getValue()) {
99 bool Ok
= isa
<BitsInit
>(V
) ? checkBitsConcrete(R
, RV
) : V
->isConcrete();
101 PrintError(R
.getLoc(),
102 Twine("Initializer of '") + RV
.getNameInitAsString() +
103 "' in '" + R
.getNameInitAsString() +
104 "' could not be fully resolved: " +
105 RV
.getValue()->getAsString());
111 /// Return an Init with a qualifier prefix referring
112 /// to CurRec's name.
113 static Init
*QualifyName(Record
&CurRec
, Init
*Name
) {
114 RecordKeeper
&RK
= CurRec
.getRecords();
115 Init
*NewName
= BinOpInit::getStrConcat(
116 CurRec
.getNameInit(),
117 StringInit::get(RK
, CurRec
.isMultiClass() ? "::" : ":"));
118 NewName
= BinOpInit::getStrConcat(NewName
, Name
);
120 if (BinOpInit
*BinOp
= dyn_cast
<BinOpInit
>(NewName
))
121 NewName
= BinOp
->Fold(&CurRec
);
125 static Init
*QualifyName(MultiClass
*MC
, Init
*Name
) {
126 return QualifyName(MC
->Rec
, Name
);
129 /// Return the qualified version of the implicit 'NAME' template argument.
130 static Init
*QualifiedNameOfImplicitName(Record
&Rec
) {
131 return QualifyName(Rec
, StringInit::get(Rec
.getRecords(), "NAME"));
134 static Init
*QualifiedNameOfImplicitName(MultiClass
*MC
) {
135 return QualifiedNameOfImplicitName(MC
->Rec
);
138 Init
*TGVarScope::getVar(RecordKeeper
&Records
, MultiClass
*ParsingMultiClass
,
139 StringInit
*Name
, SMRange NameLoc
,
140 bool TrackReferenceLocs
) const {
141 // First, we search in local variables.
142 auto It
= Vars
.find(Name
->getValue());
143 if (It
!= Vars
.end())
146 auto FindValueInArgs
= [&](Record
*Rec
, StringInit
*Name
) -> Init
* {
149 Init
*ArgName
= QualifyName(*Rec
, Name
);
150 if (Rec
->isTemplateArg(ArgName
)) {
151 RecordVal
*RV
= Rec
->getValue(ArgName
);
152 assert(RV
&& "Template arg doesn't exist??");
154 if (TrackReferenceLocs
)
155 RV
->addReferenceLoc(NameLoc
);
156 return VarInit::get(ArgName
, RV
->getType());
158 return Name
->getValue() == "NAME"
159 ? VarInit::get(ArgName
, StringRecTy::get(Records
))
163 // If not found, we try to find the variable in additional variables like
164 // arguments, loop iterator, etc.
167 break; /* do nothing. */
170 // The variable is a record field?
171 if (RecordVal
*RV
= CurRec
->getValue(Name
)) {
172 if (TrackReferenceLocs
)
173 RV
->addReferenceLoc(NameLoc
);
174 return VarInit::get(Name
, RV
->getType());
177 // The variable is a class template argument?
178 if (CurRec
->isClass())
179 if (auto *V
= FindValueInArgs(CurRec
, Name
))
184 case SK_ForeachLoop
: {
185 // The variable is a loop iterator?
186 if (CurLoop
->IterVar
) {
187 VarInit
*IterVar
= dyn_cast
<VarInit
>(CurLoop
->IterVar
);
188 if (IterVar
&& IterVar
->getNameInit() == Name
)
193 case SK_MultiClass
: {
194 // The variable is a multiclass template argument?
196 if (auto *V
= FindValueInArgs(&CurMultiClass
->Rec
, Name
))
202 // Then, we try to find the name in parent scope.
204 return Parent
->getVar(Records
, ParsingMultiClass
, Name
, NameLoc
,
210 bool TGParser::AddValue(Record
*CurRec
, SMLoc Loc
, const RecordVal
&RV
) {
212 CurRec
= &CurMultiClass
->Rec
;
214 if (RecordVal
*ERV
= CurRec
->getValue(RV
.getNameInit())) {
215 // The value already exists in the class, treat this as a set.
216 if (ERV
->setValue(RV
.getValue()))
217 return Error(Loc
, "New definition of '" + RV
.getName() + "' of type '" +
218 RV
.getType()->getAsString() + "' is incompatible with " +
219 "previous definition of type '" +
220 ERV
->getType()->getAsString() + "'");
222 CurRec
->addValue(RV
);
228 /// Return true on error, false on success.
229 bool TGParser::SetValue(Record
*CurRec
, SMLoc Loc
, Init
*ValName
,
230 ArrayRef
<unsigned> BitList
, Init
*V
,
231 bool AllowSelfAssignment
, bool OverrideDefLoc
) {
232 if (!V
) return false;
234 if (!CurRec
) CurRec
= &CurMultiClass
->Rec
;
236 RecordVal
*RV
= CurRec
->getValue(ValName
);
238 return Error(Loc
, "Value '" + ValName
->getAsUnquotedString() +
241 // Do not allow assignments like 'X = X'. This will just cause infinite loops
242 // in the resolution machinery.
244 if (VarInit
*VI
= dyn_cast
<VarInit
>(V
))
245 if (VI
->getNameInit() == ValName
&& !AllowSelfAssignment
)
246 return Error(Loc
, "Recursion / self-assignment forbidden");
248 // If we are assigning to a subset of the bits in the value... then we must be
249 // assigning to a field of BitsRecTy, which must have a BitsInit
252 if (!BitList
.empty()) {
253 BitsInit
*CurVal
= dyn_cast
<BitsInit
>(RV
->getValue());
255 return Error(Loc
, "Value '" + ValName
->getAsUnquotedString() +
256 "' is not a bits type");
258 // Convert the incoming value to a bits type of the appropriate size...
259 Init
*BI
= V
->getCastTo(BitsRecTy::get(Records
, BitList
.size()));
261 return Error(Loc
, "Initializer is not compatible with bit range");
263 SmallVector
<Init
*, 16> NewBits(CurVal
->getNumBits());
265 // Loop over bits, assigning values as appropriate.
266 for (unsigned i
= 0, e
= BitList
.size(); i
!= e
; ++i
) {
267 unsigned Bit
= BitList
[i
];
269 return Error(Loc
, "Cannot set bit #" + Twine(Bit
) + " of value '" +
270 ValName
->getAsUnquotedString() + "' more than once");
271 NewBits
[Bit
] = BI
->getBit(i
);
274 for (unsigned i
= 0, e
= CurVal
->getNumBits(); i
!= e
; ++i
)
276 NewBits
[i
] = CurVal
->getBit(i
);
278 V
= BitsInit::get(Records
, NewBits
);
281 if (OverrideDefLoc
? RV
->setValue(V
, Loc
) : RV
->setValue(V
)) {
282 std::string InitType
;
283 if (BitsInit
*BI
= dyn_cast
<BitsInit
>(V
))
284 InitType
= (Twine("' of type bit initializer with length ") +
285 Twine(BI
->getNumBits())).str();
286 else if (TypedInit
*TI
= dyn_cast
<TypedInit
>(V
))
287 InitType
= (Twine("' of type '") + TI
->getType()->getAsString()).str();
288 return Error(Loc
, "Field '" + ValName
->getAsUnquotedString() +
289 "' of type '" + RV
->getType()->getAsString() +
290 "' is incompatible with value '" +
291 V
->getAsString() + InitType
+ "'");
296 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
297 /// args as SubClass's template arguments.
298 bool TGParser::AddSubClass(Record
*CurRec
, SubClassReference
&SubClass
) {
299 Record
*SC
= SubClass
.Rec
;
300 MapResolver
R(CurRec
);
302 // Loop over all the subclass record's fields. Add regular fields to the new
304 for (const RecordVal
&Field
: SC
->getValues())
305 if (!Field
.isTemplateArg())
306 if (AddValue(CurRec
, SubClass
.RefRange
.Start
, Field
))
309 if (resolveArgumentsOfClass(R
, SC
, SubClass
.TemplateArgs
,
310 SubClass
.RefRange
.Start
))
313 // Copy the subclass record's assertions to the new record.
314 CurRec
->appendAssertions(SC
);
316 // Copy the subclass record's dumps to the new record.
317 CurRec
->appendDumps(SC
);
320 if (CurRec
->isClass())
321 Name
= VarInit::get(QualifiedNameOfImplicitName(*CurRec
),
322 StringRecTy::get(Records
));
324 Name
= CurRec
->getNameInit();
325 R
.set(QualifiedNameOfImplicitName(*SC
), Name
);
327 CurRec
->resolveReferences(R
);
329 // Since everything went well, we can now set the "superclass" list for the
331 ArrayRef
<std::pair
<Record
*, SMRange
>> SCs
= SC
->getSuperClasses();
332 for (const auto &SCPair
: SCs
) {
333 if (CurRec
->isSubClassOf(SCPair
.first
))
334 return Error(SubClass
.RefRange
.Start
,
335 "Already subclass of '" + SCPair
.first
->getName() + "'!\n");
336 CurRec
->addSuperClass(SCPair
.first
, SCPair
.second
);
339 if (CurRec
->isSubClassOf(SC
))
340 return Error(SubClass
.RefRange
.Start
,
341 "Already subclass of '" + SC
->getName() + "'!\n");
342 CurRec
->addSuperClass(SC
, SubClass
.RefRange
);
346 bool TGParser::AddSubClass(RecordsEntry
&Entry
, SubClassReference
&SubClass
) {
348 return AddSubClass(Entry
.Rec
.get(), SubClass
);
353 for (auto &E
: Entry
.Loop
->Entries
) {
354 if (AddSubClass(E
, SubClass
))
361 /// AddSubMultiClass - Add SubMultiClass as a subclass to
362 /// CurMC, resolving its template args as SubMultiClass's
363 /// template arguments.
364 bool TGParser::AddSubMultiClass(MultiClass
*CurMC
,
365 SubMultiClassReference
&SubMultiClass
) {
366 MultiClass
*SMC
= SubMultiClass
.MC
;
369 if (resolveArgumentsOfMultiClass(
370 Substs
, SMC
, SubMultiClass
.TemplateArgs
,
371 VarInit::get(QualifiedNameOfImplicitName(CurMC
),
372 StringRecTy::get(Records
)),
373 SubMultiClass
.RefRange
.Start
))
376 // Add all of the defs in the subclass into the current multiclass.
377 return resolve(SMC
->Entries
, Substs
, false, &CurMC
->Entries
);
380 /// Add a record, foreach loop, or assertion to the current context.
381 bool TGParser::addEntry(RecordsEntry E
) {
382 assert((!!E
.Rec
+ !!E
.Loop
+ !!E
.Assertion
+ !!E
.Dump
) == 1 &&
383 "RecordsEntry has invalid number of items");
385 // If we are parsing a loop, add it to the loop's entries.
386 if (!Loops
.empty()) {
387 Loops
.back()->Entries
.push_back(std::move(E
));
391 // If it is a loop, then resolve and perform the loop.
394 return resolve(*E
.Loop
, Stack
, CurMultiClass
== nullptr,
395 CurMultiClass
? &CurMultiClass
->Entries
: nullptr);
398 // If we are parsing a multiclass, add it to the multiclass's entries.
400 CurMultiClass
->Entries
.push_back(std::move(E
));
404 // If it is an assertion, then it's a top-level one, so check it.
406 CheckAssert(E
.Assertion
->Loc
, E
.Assertion
->Condition
, E
.Assertion
->Message
);
411 dumpMessage(E
.Dump
->Loc
, E
.Dump
->Message
);
415 // It must be a record, so finish it off.
416 return addDefOne(std::move(E
.Rec
));
419 /// Resolve the entries in \p Loop, going over inner loops recursively
420 /// and making the given subsitutions of (name, value) pairs.
422 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
423 /// are added to the global record keeper.
424 bool TGParser::resolve(const ForeachLoop
&Loop
, SubstStack
&Substs
,
425 bool Final
, std::vector
<RecordsEntry
> *Dest
,
429 for (const auto &S
: Substs
)
430 R
.set(S
.first
, S
.second
);
431 Init
*List
= Loop
.ListValue
->resolveReferences(R
);
433 // For if-then-else blocks, we lower to a foreach loop whose list is a
434 // ternary selection between lists of different length. Since we don't
435 // have a means to track variable length record lists, we *must* resolve
436 // the condition here. We want to defer final resolution of the arms
437 // until the resulting records are finalized.
438 // e.g. !if(!exists<SchedWrite>("__does_not_exist__"), [1], [])
439 if (auto *TI
= dyn_cast
<TernOpInit
>(List
);
440 TI
&& TI
->getOpcode() == TernOpInit::IF
&& Final
) {
441 Init
*OldLHS
= TI
->getLHS();
443 Init
*LHS
= OldLHS
->resolveReferences(R
);
446 Twine("unable to resolve if condition '") +
447 LHS
->getAsString() + "' at end of containing scope");
450 Init
*MHS
= TI
->getMHS();
451 Init
*RHS
= TI
->getRHS();
452 List
= TernOpInit::get(TernOpInit::IF
, LHS
, MHS
, RHS
, TI
->getType())
456 auto LI
= dyn_cast
<ListInit
>(List
);
459 Dest
->emplace_back(std::make_unique
<ForeachLoop
>(Loop
.Loc
, Loop
.IterVar
,
461 return resolve(Loop
.Entries
, Substs
, Final
, &Dest
->back().Loop
->Entries
,
465 PrintError(Loop
.Loc
, Twine("attempting to loop over '") +
466 List
->getAsString() + "', expected a list");
471 for (auto *Elt
: *LI
) {
473 Substs
.emplace_back(Loop
.IterVar
->getNameInit(), Elt
);
474 Error
= resolve(Loop
.Entries
, Substs
, Final
, Dest
);
483 /// Resolve the entries in \p Source, going over loops recursively and
484 /// making the given substitutions of (name, value) pairs.
486 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
487 /// are added to the global record keeper.
488 bool TGParser::resolve(const std::vector
<RecordsEntry
> &Source
,
489 SubstStack
&Substs
, bool Final
,
490 std::vector
<RecordsEntry
> *Dest
, SMLoc
*Loc
) {
492 for (auto &E
: Source
) {
494 Error
= resolve(*E
.Loop
, Substs
, Final
, Dest
);
496 } else if (E
.Assertion
) {
498 for (const auto &S
: Substs
)
499 R
.set(S
.first
, S
.second
);
500 Init
*Condition
= E
.Assertion
->Condition
->resolveReferences(R
);
501 Init
*Message
= E
.Assertion
->Message
->resolveReferences(R
);
504 Dest
->push_back(std::make_unique
<Record::AssertionInfo
>(
505 E
.Assertion
->Loc
, Condition
, Message
));
507 CheckAssert(E
.Assertion
->Loc
, Condition
, Message
);
511 for (const auto &S
: Substs
)
512 R
.set(S
.first
, S
.second
);
513 Init
*Message
= E
.Dump
->Message
->resolveReferences(R
);
517 std::make_unique
<Record::DumpInfo
>(E
.Dump
->Loc
, Message
));
519 dumpMessage(E
.Dump
->Loc
, Message
);
522 auto Rec
= std::make_unique
<Record
>(*E
.Rec
);
524 Rec
->appendLoc(*Loc
);
526 MapResolver
R(Rec
.get());
527 for (const auto &S
: Substs
)
528 R
.set(S
.first
, S
.second
);
529 Rec
->resolveReferences(R
);
532 Dest
->push_back(std::move(Rec
));
534 Error
= addDefOne(std::move(Rec
));
542 /// Resolve the record fully and add it to the record keeper.
543 bool TGParser::addDefOne(std::unique_ptr
<Record
> Rec
) {
544 Init
*NewName
= nullptr;
545 if (Record
*Prev
= Records
.getDef(Rec
->getNameInitAsString())) {
546 if (!Rec
->isAnonymous()) {
547 PrintError(Rec
->getLoc(),
548 "def already exists: " + Rec
->getNameInitAsString());
549 PrintNote(Prev
->getLoc(), "location of previous definition");
552 NewName
= Records
.getNewAnonymousName();
555 Rec
->resolveReferences(NewName
);
558 if (!isa
<StringInit
>(Rec
->getNameInit())) {
559 PrintError(Rec
->getLoc(), Twine("record name '") +
560 Rec
->getNameInit()->getAsString() +
561 "' could not be fully resolved");
565 // Check the assertions.
566 Rec
->checkRecordAssertions();
569 Rec
->emitRecordDumps();
571 // If ObjectBody has template arguments, it's an error.
572 assert(Rec
->getTemplateArgs().empty() && "How'd this get template args?");
574 for (DefsetRecord
*Defset
: Defsets
) {
575 DefInit
*I
= Rec
->getDefInit();
576 if (!I
->getType()->typeIsA(Defset
->EltTy
)) {
577 PrintError(Rec
->getLoc(), Twine("adding record of incompatible type '") +
578 I
->getType()->getAsString() +
580 PrintNote(Defset
->Loc
, "location of defset declaration");
583 Defset
->Elements
.push_back(I
);
586 Records
.addDef(std::move(Rec
));
590 bool TGParser::resolveArguments(Record
*Rec
, ArrayRef
<ArgumentInit
*> ArgValues
,
591 SMLoc Loc
, ArgValueHandler ArgValueHandler
) {
592 ArrayRef
<Init
*> ArgNames
= Rec
->getTemplateArgs();
593 assert(ArgValues
.size() <= ArgNames
.size() &&
594 "Too many template arguments allowed");
596 // Loop over the template arguments and handle the (name, value) pair.
597 SmallVector
<Init
*, 2> UnsolvedArgNames(ArgNames
);
598 for (auto *Arg
: ArgValues
) {
599 Init
*ArgName
= nullptr;
600 Init
*ArgValue
= Arg
->getValue();
601 if (Arg
->isPositional())
602 ArgName
= ArgNames
[Arg
->getIndex()];
604 ArgName
= Arg
->getName();
606 // We can only specify the template argument once.
607 if (!is_contained(UnsolvedArgNames
, ArgName
))
608 return Error(Loc
, "We can only specify the template argument '" +
609 ArgName
->getAsUnquotedString() + "' once");
611 ArgValueHandler(ArgName
, ArgValue
);
612 llvm::erase(UnsolvedArgNames
, ArgName
);
615 // For unsolved arguments, if there is no default value, complain.
616 for (auto *UnsolvedArgName
: UnsolvedArgNames
) {
617 Init
*Default
= Rec
->getValue(UnsolvedArgName
)->getValue();
618 if (!Default
->isComplete()) {
619 std::string Name
= UnsolvedArgName
->getAsUnquotedString();
620 Error(Loc
, "value not specified for template argument '" + Name
+ "'");
621 PrintNote(Rec
->getFieldLoc(Name
),
622 "declared in '" + Rec
->getNameInitAsString() + "'");
625 ArgValueHandler(UnsolvedArgName
, Default
);
631 /// Resolve the arguments of class and set them to MapResolver.
632 /// Returns true if failed.
633 bool TGParser::resolveArgumentsOfClass(MapResolver
&R
, Record
*Rec
,
634 ArrayRef
<ArgumentInit
*> ArgValues
,
636 return resolveArguments(Rec
, ArgValues
, Loc
,
637 [&](Init
*Name
, Init
*Value
) { R
.set(Name
, Value
); });
640 /// Resolve the arguments of multiclass and store them into SubstStack.
641 /// Returns true if failed.
642 bool TGParser::resolveArgumentsOfMultiClass(SubstStack
&Substs
, MultiClass
*MC
,
643 ArrayRef
<ArgumentInit
*> ArgValues
,
644 Init
*DefmName
, SMLoc Loc
) {
645 // Add an implicit argument NAME.
646 Substs
.emplace_back(QualifiedNameOfImplicitName(MC
), DefmName
);
647 return resolveArguments(
648 &MC
->Rec
, ArgValues
, Loc
,
649 [&](Init
*Name
, Init
*Value
) { Substs
.emplace_back(Name
, Value
); });
652 //===----------------------------------------------------------------------===//
654 //===----------------------------------------------------------------------===//
656 bool TGParser::consume(tgtok::TokKind K
) {
657 if (Lex
.getCode() == K
) {
664 /// ParseObjectName - If a valid object name is specified, return it. If no
665 /// name is specified, return the unset initializer. Return nullptr on parse
667 /// ObjectName ::= Value [ '#' Value ]*
668 /// ObjectName ::= /*empty*/
670 Init
*TGParser::ParseObjectName(MultiClass
*CurMultiClass
) {
671 switch (Lex
.getCode()) {
675 // These are all of the tokens that can begin an object body.
676 // Some of these can also begin values but we disallow those cases
677 // because they are unlikely to be useful.
678 return UnsetInit::get(Records
);
683 Record
*CurRec
= nullptr;
685 CurRec
= &CurMultiClass
->Rec
;
687 Init
*Name
= ParseValue(CurRec
, StringRecTy::get(Records
), ParseNameMode
);
692 Init
*NameStr
= QualifiedNameOfImplicitName(CurMultiClass
);
693 HasReferenceResolver
R(NameStr
);
694 Name
->resolveReferences(R
);
696 Name
= BinOpInit::getStrConcat(
697 VarInit::get(NameStr
, StringRecTy::get(Records
)), Name
);
703 /// ParseClassID - Parse and resolve a reference to a class name. This returns
708 Record
*TGParser::ParseClassID() {
709 if (Lex
.getCode() != tgtok::Id
) {
710 TokError("expected name for ClassID");
714 Record
*Result
= Records
.getClass(Lex
.getCurStrVal());
716 std::string
Msg("Couldn't find class '" + Lex
.getCurStrVal() + "'");
717 if (MultiClasses
[Lex
.getCurStrVal()].get())
718 TokError(Msg
+ ". Use 'defm' if you meant to use multiclass '" +
719 Lex
.getCurStrVal() + "'");
722 } else if (TrackReferenceLocs
) {
723 Result
->appendReferenceLoc(Lex
.getLocRange());
730 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
731 /// This returns null on error.
733 /// MultiClassID ::= ID
735 MultiClass
*TGParser::ParseMultiClassID() {
736 if (Lex
.getCode() != tgtok::Id
) {
737 TokError("expected name for MultiClassID");
741 MultiClass
*Result
= MultiClasses
[Lex
.getCurStrVal()].get();
743 TokError("Couldn't find multiclass '" + Lex
.getCurStrVal() + "'");
749 /// ParseSubClassReference - Parse a reference to a subclass or a
750 /// multiclass. This returns a SubClassRefTy with a null Record* on error.
752 /// SubClassRef ::= ClassID
753 /// SubClassRef ::= ClassID '<' ArgValueList '>'
755 SubClassReference
TGParser::
756 ParseSubClassReference(Record
*CurRec
, bool isDefm
) {
757 SubClassReference Result
;
758 Result
.RefRange
.Start
= Lex
.getLoc();
761 if (MultiClass
*MC
= ParseMultiClassID())
762 Result
.Rec
= &MC
->Rec
;
764 Result
.Rec
= ParseClassID();
766 if (!Result
.Rec
) return Result
;
768 // If there is no template arg list, we're done.
769 if (!consume(tgtok::less
)) {
770 Result
.RefRange
.End
= Lex
.getLoc();
774 if (ParseTemplateArgValueList(Result
.TemplateArgs
, CurRec
, Result
.Rec
)) {
775 Result
.Rec
= nullptr; // Error parsing value list.
779 if (CheckTemplateArgValues(Result
.TemplateArgs
, Result
.RefRange
.Start
,
781 Result
.Rec
= nullptr; // Error checking value list.
785 Result
.RefRange
.End
= Lex
.getLoc();
789 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
790 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
791 /// Record* on error.
793 /// SubMultiClassRef ::= MultiClassID
794 /// SubMultiClassRef ::= MultiClassID '<' ArgValueList '>'
796 SubMultiClassReference
TGParser::
797 ParseSubMultiClassReference(MultiClass
*CurMC
) {
798 SubMultiClassReference Result
;
799 Result
.RefRange
.Start
= Lex
.getLoc();
801 Result
.MC
= ParseMultiClassID();
802 if (!Result
.MC
) return Result
;
804 // If there is no template arg list, we're done.
805 if (!consume(tgtok::less
)) {
806 Result
.RefRange
.End
= Lex
.getLoc();
810 if (ParseTemplateArgValueList(Result
.TemplateArgs
, &CurMC
->Rec
,
812 Result
.MC
= nullptr; // Error parsing value list.
816 Result
.RefRange
.End
= Lex
.getLoc();
821 /// ParseSliceElement - Parse subscript or range
823 /// SliceElement ::= Value<list<int>>
824 /// SliceElement ::= Value<int>
825 /// SliceElement ::= Value<int> '...' Value<int>
826 /// SliceElement ::= Value<int> '-' Value<int> (deprecated)
827 /// SliceElement ::= Value<int> INTVAL(Negative; deprecated)
829 /// SliceElement is either IntRecTy, ListRecTy, or nullptr
831 TypedInit
*TGParser::ParseSliceElement(Record
*CurRec
) {
832 auto LHSLoc
= Lex
.getLoc();
833 auto *CurVal
= ParseValue(CurRec
);
836 auto *LHS
= cast
<TypedInit
>(CurVal
);
838 TypedInit
*RHS
= nullptr;
839 switch (Lex
.getCode()) {
840 case tgtok::dotdotdot
:
841 case tgtok::minus
: { // Deprecated
843 auto RHSLoc
= Lex
.getLoc();
844 CurVal
= ParseValue(CurRec
);
847 RHS
= cast
<TypedInit
>(CurVal
);
848 if (!isa
<IntRecTy
>(RHS
->getType())) {
850 "expected int...int, got " + Twine(RHS
->getType()->getAsString()));
855 case tgtok::IntVal
: { // Deprecated "-num"
856 auto i
= -Lex
.getCurIntVal();
858 TokError("invalid range, cannot be negative");
861 RHS
= IntInit::get(Records
, i
);
862 Lex
.Lex(); // eat IntVal
865 default: // Single value (IntRecTy or ListRecTy)
870 assert(isa
<IntRecTy
>(RHS
->getType()));
872 // Closed-interval range <LHS:IntRecTy>...<RHS:IntRecTy>
873 if (!isa
<IntRecTy
>(LHS
->getType())) {
875 "expected int...int, got " + Twine(LHS
->getType()->getAsString()));
879 return cast
<TypedInit
>(BinOpInit::get(BinOpInit::RANGEC
, LHS
, RHS
,
880 IntRecTy::get(Records
)->getListTy())
884 /// ParseSliceElements - Parse subscripts in square brackets.
886 /// SliceElements ::= ( SliceElement ',' )* SliceElement ','?
888 /// SliceElement is either IntRecTy, ListRecTy, or nullptr
890 /// Returns ListRecTy by defaut.
891 /// Returns IntRecTy if;
893 /// - SliceElements is Value<int> w/o trailing comma
895 TypedInit
*TGParser::ParseSliceElements(Record
*CurRec
, bool Single
) {
897 SmallVector
<Init
*, 2> Elems
; // int
898 SmallVector
<TypedInit
*, 2> Slices
; // list<int>
900 auto FlushElems
= [&] {
901 if (!Elems
.empty()) {
902 Slices
.push_back(ListInit::get(Elems
, IntRecTy::get(Records
)));
908 auto LHSLoc
= Lex
.getLoc();
909 CurVal
= ParseSliceElement(CurRec
);
912 auto *CurValTy
= CurVal
->getType();
914 if (auto *ListValTy
= dyn_cast
<ListRecTy
>(CurValTy
)) {
915 if (!isa
<IntRecTy
>(ListValTy
->getElementType())) {
917 "expected list<int>, got " + Twine(ListValTy
->getAsString()));
922 Slices
.push_back(CurVal
);
925 } else if (!isa
<IntRecTy
>(CurValTy
)) {
927 "unhandled type " + Twine(CurValTy
->getAsString()) + " in range");
931 if (Lex
.getCode() != tgtok::comma
)
934 Lex
.Lex(); // eat comma
936 // `[i,]` is not LISTELEM but LISTSLICE
939 Elems
.push_back(CurVal
);
941 } while (Lex
.getCode() != tgtok::r_square
);
948 Elems
.push_back(CurVal
);
953 // Concatenate lists in Slices
954 TypedInit
*Result
= nullptr;
955 for (auto *Slice
: Slices
) {
956 Result
= (Result
? cast
<TypedInit
>(BinOpInit::getListConcat(Result
, Slice
))
963 /// ParseRangePiece - Parse a bit/value range.
964 /// RangePiece ::= INTVAL
965 /// RangePiece ::= INTVAL '...' INTVAL
966 /// RangePiece ::= INTVAL '-' INTVAL
967 /// RangePiece ::= INTVAL INTVAL
968 // The last two forms are deprecated.
969 bool TGParser::ParseRangePiece(SmallVectorImpl
<unsigned> &Ranges
,
970 TypedInit
*FirstItem
) {
971 Init
*CurVal
= FirstItem
;
973 CurVal
= ParseValue(nullptr);
975 IntInit
*II
= dyn_cast_or_null
<IntInit
>(CurVal
);
977 return TokError("expected integer or bitrange");
979 int64_t Start
= II
->getValue();
983 return TokError("invalid range, cannot be negative");
985 switch (Lex
.getCode()) {
987 Ranges
.push_back(Start
);
990 case tgtok::dotdotdot
:
994 Init
*I_End
= ParseValue(nullptr);
995 IntInit
*II_End
= dyn_cast_or_null
<IntInit
>(I_End
);
997 TokError("expected integer value as end of range");
1001 End
= II_End
->getValue();
1004 case tgtok::IntVal
: {
1005 End
= -Lex
.getCurIntVal();
1011 return TokError("invalid range, cannot be negative");
1013 // Add to the range.
1015 for (; Start
<= End
; ++Start
)
1016 Ranges
.push_back(Start
);
1018 for (; Start
>= End
; --Start
)
1019 Ranges
.push_back(Start
);
1023 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
1025 /// RangeList ::= RangePiece (',' RangePiece)*
1027 void TGParser::ParseRangeList(SmallVectorImpl
<unsigned> &Result
) {
1028 // Parse the first piece.
1029 if (ParseRangePiece(Result
)) {
1033 while (consume(tgtok::comma
))
1034 // Parse the next range piece.
1035 if (ParseRangePiece(Result
)) {
1041 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
1042 /// OptionalRangeList ::= '<' RangeList '>'
1043 /// OptionalRangeList ::= /*empty*/
1044 bool TGParser::ParseOptionalRangeList(SmallVectorImpl
<unsigned> &Ranges
) {
1045 SMLoc StartLoc
= Lex
.getLoc();
1046 if (!consume(tgtok::less
))
1049 // Parse the range list.
1050 ParseRangeList(Ranges
);
1051 if (Ranges
.empty()) return true;
1053 if (!consume(tgtok::greater
)) {
1054 TokError("expected '>' at end of range list");
1055 return Error(StartLoc
, "to match this '<'");
1060 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
1061 /// OptionalBitList ::= '{' RangeList '}'
1062 /// OptionalBitList ::= /*empty*/
1063 bool TGParser::ParseOptionalBitList(SmallVectorImpl
<unsigned> &Ranges
) {
1064 SMLoc StartLoc
= Lex
.getLoc();
1065 if (!consume(tgtok::l_brace
))
1068 // Parse the range list.
1069 ParseRangeList(Ranges
);
1070 if (Ranges
.empty()) return true;
1072 if (!consume(tgtok::r_brace
)) {
1073 TokError("expected '}' at end of bit list");
1074 return Error(StartLoc
, "to match this '{'");
1079 /// ParseType - Parse and return a tblgen type. This returns null on error.
1081 /// Type ::= STRING // string type
1082 /// Type ::= CODE // code type
1083 /// Type ::= BIT // bit type
1084 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
1085 /// Type ::= INT // int type
1086 /// Type ::= LIST '<' Type '>' // list<x> type
1087 /// Type ::= DAG // dag type
1088 /// Type ::= ClassID // Record Type
1090 RecTy
*TGParser::ParseType() {
1091 switch (Lex
.getCode()) {
1092 default: TokError("Unknown token when expecting a type"); return nullptr;
1096 return StringRecTy::get(Records
);
1099 return BitRecTy::get(Records
);
1102 return IntRecTy::get(Records
);
1105 return DagRecTy::get(Records
);
1107 if (Record
*R
= ParseClassID())
1108 return RecordRecTy::get(R
);
1109 TokError("unknown class name");
1112 if (Lex
.Lex() != tgtok::less
) { // Eat 'bits'
1113 TokError("expected '<' after bits type");
1116 if (Lex
.Lex() != tgtok::IntVal
) { // Eat '<'
1117 TokError("expected integer in bits<n> type");
1120 uint64_t Val
= Lex
.getCurIntVal();
1121 if (Lex
.Lex() != tgtok::greater
) { // Eat count.
1122 TokError("expected '>' at end of bits<n> type");
1125 Lex
.Lex(); // Eat '>'
1126 return BitsRecTy::get(Records
, Val
);
1129 if (Lex
.Lex() != tgtok::less
) { // Eat 'bits'
1130 TokError("expected '<' after list type");
1133 Lex
.Lex(); // Eat '<'
1134 RecTy
*SubType
= ParseType();
1135 if (!SubType
) return nullptr;
1137 if (!consume(tgtok::greater
)) {
1138 TokError("expected '>' at end of list<ty> type");
1141 return ListRecTy::get(SubType
);
1147 Init
*TGParser::ParseIDValue(Record
*CurRec
, StringInit
*Name
, SMRange NameLoc
,
1149 if (Init
*I
= CurScope
->getVar(Records
, CurMultiClass
, Name
, NameLoc
,
1150 TrackReferenceLocs
))
1153 if (Mode
== ParseNameMode
)
1156 if (Init
*I
= Records
.getGlobal(Name
->getValue())) {
1157 // Add a reference to the global if it's a record.
1158 if (TrackReferenceLocs
) {
1159 if (auto *Def
= dyn_cast
<DefInit
>(I
))
1160 Def
->getDef()->appendReferenceLoc(NameLoc
);
1165 // Allow self-references of concrete defs, but delay the lookup so that we
1166 // get the correct type.
1167 if (CurRec
&& !CurRec
->isClass() && !CurMultiClass
&&
1168 CurRec
->getNameInit() == Name
)
1169 return UnOpInit::get(UnOpInit::CAST
, Name
, CurRec
->getType());
1171 Error(NameLoc
.Start
, "Variable not defined: '" + Name
->getValue() + "'");
1175 /// ParseOperation - Parse an operator. This returns null on error.
1177 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
1179 Init
*TGParser::ParseOperation(Record
*CurRec
, RecTy
*ItemType
) {
1180 switch (Lex
.getCode()) {
1182 TokError("unknown bang operator");
1185 case tgtok::XToLower
:
1186 case tgtok::XToUpper
:
1194 case tgtok::XGetDagOp
: { // Value ::= !unop '(' Value ')'
1195 UnOpInit::UnaryOp Code
;
1196 RecTy
*Type
= nullptr;
1198 switch (Lex
.getCode()) {
1199 default: llvm_unreachable("Unhandled code!");
1201 Lex
.Lex(); // eat the operation
1202 Code
= UnOpInit::CAST
;
1204 Type
= ParseOperatorType();
1207 TokError("did not get type for unary operator");
1213 Lex
.Lex(); // eat the operation
1214 Code
= UnOpInit::REPR
;
1215 Type
= StringRecTy::get(Records
);
1217 case tgtok::XToLower
:
1218 Lex
.Lex(); // eat the operation
1219 Code
= UnOpInit::TOLOWER
;
1220 Type
= StringRecTy::get(Records
);
1222 case tgtok::XToUpper
:
1223 Lex
.Lex(); // eat the operation
1224 Code
= UnOpInit::TOUPPER
;
1225 Type
= StringRecTy::get(Records
);
1228 Lex
.Lex(); // eat the operation
1229 Code
= UnOpInit::NOT
;
1230 Type
= IntRecTy::get(Records
);
1233 Lex
.Lex(); // eat the operation
1234 Code
= UnOpInit::LOG2
;
1235 Type
= IntRecTy::get(Records
);
1238 Lex
.Lex(); // eat the operation
1239 Code
= UnOpInit::HEAD
;
1242 Lex
.Lex(); // eat the operation
1243 Code
= UnOpInit::TAIL
;
1247 Code
= UnOpInit::SIZE
;
1248 Type
= IntRecTy::get(Records
);
1251 Lex
.Lex(); // eat the operation
1252 Code
= UnOpInit::EMPTY
;
1253 Type
= IntRecTy::get(Records
);
1255 case tgtok::XGetDagOp
:
1256 Lex
.Lex(); // eat the operation
1257 if (Lex
.getCode() == tgtok::less
) {
1258 // Parse an optional type suffix, so that you can say
1259 // !getdagop<BaseClass>(someDag) as a shorthand for
1260 // !cast<BaseClass>(!getdagop(someDag)).
1261 Type
= ParseOperatorType();
1264 TokError("did not get type for unary operator");
1268 if (!isa
<RecordRecTy
>(Type
)) {
1269 TokError("type for !getdagop must be a record type");
1270 // but keep parsing, to consume the operand
1273 Type
= RecordRecTy::get(Records
, {});
1275 Code
= UnOpInit::GETDAGOP
;
1278 if (!consume(tgtok::l_paren
)) {
1279 TokError("expected '(' after unary operator");
1283 Init
*LHS
= ParseValue(CurRec
);
1284 if (!LHS
) return nullptr;
1286 if (Code
== UnOpInit::EMPTY
|| Code
== UnOpInit::SIZE
) {
1287 ListInit
*LHSl
= dyn_cast
<ListInit
>(LHS
);
1288 StringInit
*LHSs
= dyn_cast
<StringInit
>(LHS
);
1289 DagInit
*LHSd
= dyn_cast
<DagInit
>(LHS
);
1290 TypedInit
*LHSt
= dyn_cast
<TypedInit
>(LHS
);
1291 if (!LHSl
&& !LHSs
&& !LHSd
&& !LHSt
) {
1292 TokError("expected string, list, or dag type argument in unary operator");
1296 ListRecTy
*LType
= dyn_cast
<ListRecTy
>(LHSt
->getType());
1297 StringRecTy
*SType
= dyn_cast
<StringRecTy
>(LHSt
->getType());
1298 DagRecTy
*DType
= dyn_cast
<DagRecTy
>(LHSt
->getType());
1299 if (!LType
&& !SType
&& !DType
) {
1300 TokError("expected string, list, or dag type argument in unary operator");
1306 if (Code
== UnOpInit::HEAD
|| Code
== UnOpInit::TAIL
) {
1307 ListInit
*LHSl
= dyn_cast
<ListInit
>(LHS
);
1308 TypedInit
*LHSt
= dyn_cast
<TypedInit
>(LHS
);
1309 if (!LHSl
&& !LHSt
) {
1310 TokError("expected list type argument in unary operator");
1314 ListRecTy
*LType
= dyn_cast
<ListRecTy
>(LHSt
->getType());
1316 TokError("expected list type argument in unary operator");
1321 if (LHSl
&& LHSl
->empty()) {
1322 TokError("empty list argument in unary operator");
1326 Init
*Item
= LHSl
->getElement(0);
1327 TypedInit
*Itemt
= dyn_cast
<TypedInit
>(Item
);
1329 TokError("untyped list element in unary operator");
1332 Type
= (Code
== UnOpInit::HEAD
) ? Itemt
->getType()
1333 : ListRecTy::get(Itemt
->getType());
1335 assert(LHSt
&& "expected list type argument in unary operator");
1336 ListRecTy
*LType
= dyn_cast
<ListRecTy
>(LHSt
->getType());
1337 Type
= (Code
== UnOpInit::HEAD
) ? LType
->getElementType() : LType
;
1341 if (!consume(tgtok::r_paren
)) {
1342 TokError("expected ')' in unary operator");
1345 return (UnOpInit::get(Code
, LHS
, Type
))->Fold(CurRec
);
1349 // Value ::= !isa '<' Type '>' '(' Value ')'
1350 Lex
.Lex(); // eat the operation
1352 RecTy
*Type
= ParseOperatorType();
1356 if (!consume(tgtok::l_paren
)) {
1357 TokError("expected '(' after type of !isa");
1361 Init
*LHS
= ParseValue(CurRec
);
1365 if (!consume(tgtok::r_paren
)) {
1366 TokError("expected ')' in !isa");
1370 return (IsAOpInit::get(Type
, LHS
))->Fold();
1373 case tgtok::XExists
: {
1374 // Value ::= !exists '<' Type '>' '(' Value ')'
1375 Lex
.Lex(); // eat the operation
1377 RecTy
*Type
= ParseOperatorType();
1381 if (!consume(tgtok::l_paren
)) {
1382 TokError("expected '(' after type of !exists");
1386 SMLoc ExprLoc
= Lex
.getLoc();
1387 Init
*Expr
= ParseValue(CurRec
);
1391 TypedInit
*ExprType
= dyn_cast
<TypedInit
>(Expr
);
1393 Error(ExprLoc
, "expected string type argument in !exists operator");
1397 RecordRecTy
*RecType
= dyn_cast
<RecordRecTy
>(ExprType
->getType());
1400 "expected string type argument in !exists operator, please "
1401 "use !isa instead");
1405 StringRecTy
*SType
= dyn_cast
<StringRecTy
>(ExprType
->getType());
1407 Error(ExprLoc
, "expected string type argument in !exists operator");
1411 if (!consume(tgtok::r_paren
)) {
1412 TokError("expected ')' in !exists");
1416 return (ExistsOpInit::get(Type
, Expr
))->Fold(CurRec
);
1419 case tgtok::XConcat
:
1436 case tgtok::XListConcat
:
1437 case tgtok::XListSplat
:
1438 case tgtok::XListRemove
:
1439 case tgtok::XStrConcat
:
1440 case tgtok::XInterleave
:
1441 case tgtok::XGetDagArg
:
1442 case tgtok::XGetDagName
:
1443 case tgtok::XSetDagOp
: { // Value ::= !binop '(' Value ',' Value ')'
1444 tgtok::TokKind OpTok
= Lex
.getCode();
1445 SMLoc OpLoc
= Lex
.getLoc();
1446 Lex
.Lex(); // eat the operation
1448 BinOpInit::BinaryOp Code
;
1450 default: llvm_unreachable("Unhandled code!");
1451 case tgtok::XConcat
: Code
= BinOpInit::CONCAT
; break;
1452 case tgtok::XADD
: Code
= BinOpInit::ADD
; break;
1453 case tgtok::XSUB
: Code
= BinOpInit::SUB
; break;
1454 case tgtok::XMUL
: Code
= BinOpInit::MUL
; break;
1455 case tgtok::XDIV
: Code
= BinOpInit::DIV
; break;
1456 case tgtok::XAND
: Code
= BinOpInit::AND
; break;
1457 case tgtok::XOR
: Code
= BinOpInit::OR
; break;
1458 case tgtok::XXOR
: Code
= BinOpInit::XOR
; break;
1459 case tgtok::XSRA
: Code
= BinOpInit::SRA
; break;
1460 case tgtok::XSRL
: Code
= BinOpInit::SRL
; break;
1461 case tgtok::XSHL
: Code
= BinOpInit::SHL
; break;
1462 case tgtok::XEq
: Code
= BinOpInit::EQ
; break;
1463 case tgtok::XNe
: Code
= BinOpInit::NE
; break;
1464 case tgtok::XLe
: Code
= BinOpInit::LE
; break;
1465 case tgtok::XLt
: Code
= BinOpInit::LT
; break;
1466 case tgtok::XGe
: Code
= BinOpInit::GE
; break;
1467 case tgtok::XGt
: Code
= BinOpInit::GT
; break;
1468 case tgtok::XListConcat
: Code
= BinOpInit::LISTCONCAT
; break;
1469 case tgtok::XListSplat
: Code
= BinOpInit::LISTSPLAT
; break;
1470 case tgtok::XListRemove
:
1471 Code
= BinOpInit::LISTREMOVE
;
1473 case tgtok::XStrConcat
: Code
= BinOpInit::STRCONCAT
; break;
1474 case tgtok::XInterleave
: Code
= BinOpInit::INTERLEAVE
; break;
1475 case tgtok::XSetDagOp
: Code
= BinOpInit::SETDAGOP
; break;
1476 case tgtok::XGetDagArg
:
1477 Code
= BinOpInit::GETDAGARG
;
1479 case tgtok::XGetDagName
:
1480 Code
= BinOpInit::GETDAGNAME
;
1484 RecTy
*Type
= nullptr;
1485 RecTy
*ArgType
= nullptr;
1488 llvm_unreachable("Unhandled code!");
1489 case tgtok::XConcat
:
1490 case tgtok::XSetDagOp
:
1491 Type
= DagRecTy::get(Records
);
1492 ArgType
= DagRecTy::get(Records
);
1494 case tgtok::XGetDagArg
:
1495 Type
= ParseOperatorType();
1497 TokError("did not get type for !getdagarg operator");
1500 ArgType
= DagRecTy::get(Records
);
1502 case tgtok::XGetDagName
:
1503 Type
= StringRecTy::get(Records
);
1504 ArgType
= DagRecTy::get(Records
);
1516 Type
= IntRecTy::get(Records
);
1517 ArgType
= IntRecTy::get(Records
);
1525 Type
= BitRecTy::get(Records
);
1526 // ArgType for the comparison operators is not yet known.
1528 case tgtok::XListConcat
:
1529 // We don't know the list type until we parse the first argument.
1532 case tgtok::XListSplat
:
1533 // Can't do any typechecking until we parse the first argument.
1535 case tgtok::XListRemove
:
1536 // We don't know the list type until we parse the first argument.
1539 case tgtok::XStrConcat
:
1540 Type
= StringRecTy::get(Records
);
1541 ArgType
= StringRecTy::get(Records
);
1543 case tgtok::XInterleave
:
1544 Type
= StringRecTy::get(Records
);
1545 // The first argument type is not yet known.
1548 if (Type
&& ItemType
&& !Type
->typeIsConvertibleTo(ItemType
)) {
1549 Error(OpLoc
, Twine("expected value of type '") +
1550 ItemType
->getAsString() + "', got '" +
1551 Type
->getAsString() + "'");
1555 if (!consume(tgtok::l_paren
)) {
1556 TokError("expected '(' after binary operator");
1560 SmallVector
<Init
*, 2> InitList
;
1562 // Note that this loop consumes an arbitrary number of arguments.
1563 // The actual count is checked later.
1565 SMLoc InitLoc
= Lex
.getLoc();
1566 InitList
.push_back(ParseValue(CurRec
, ArgType
));
1567 if (!InitList
.back()) return nullptr;
1569 TypedInit
*InitListBack
= dyn_cast
<TypedInit
>(InitList
.back());
1570 if (!InitListBack
) {
1571 Error(OpLoc
, Twine("expected value to be a typed value, got '" +
1572 InitList
.back()->getAsString() + "'"));
1575 RecTy
*ListType
= InitListBack
->getType();
1578 // Argument type must be determined from the argument itself.
1582 case BinOpInit::LISTCONCAT
:
1583 if (!isa
<ListRecTy
>(ArgType
)) {
1584 Error(InitLoc
, Twine("expected a list, got value of type '") +
1585 ArgType
->getAsString() + "'");
1589 case BinOpInit::LISTSPLAT
:
1590 if (ItemType
&& InitList
.size() == 1) {
1591 if (!isa
<ListRecTy
>(ItemType
)) {
1593 Twine("expected output type to be a list, got type '") +
1594 ItemType
->getAsString() + "'");
1597 if (!ArgType
->getListTy()->typeIsConvertibleTo(ItemType
)) {
1598 Error(OpLoc
, Twine("expected first arg type to be '") +
1599 ArgType
->getAsString() +
1600 "', got value of type '" +
1601 cast
<ListRecTy
>(ItemType
)
1608 if (InitList
.size() == 2 && !isa
<IntRecTy
>(ArgType
)) {
1609 Error(InitLoc
, Twine("expected second parameter to be an int, got "
1610 "value of type '") +
1611 ArgType
->getAsString() + "'");
1614 ArgType
= nullptr; // Broken invariant: types not identical.
1616 case BinOpInit::LISTREMOVE
:
1617 if (!isa
<ListRecTy
>(ArgType
)) {
1618 Error(InitLoc
, Twine("expected a list, got value of type '") +
1619 ArgType
->getAsString() + "'");
1625 if (!ArgType
->typeIsConvertibleTo(IntRecTy::get(Records
)) &&
1626 !ArgType
->typeIsConvertibleTo(StringRecTy::get(Records
)) &&
1627 !ArgType
->typeIsConvertibleTo(RecordRecTy::get(Records
, {}))) {
1628 Error(InitLoc
, Twine("expected bit, bits, int, string, or record; "
1629 "got value of type '") + ArgType
->getAsString() +
1634 case BinOpInit::GETDAGARG
: // The 2nd argument of !getdagarg could be
1640 if (!ArgType
->typeIsConvertibleTo(IntRecTy::get(Records
)) &&
1641 !ArgType
->typeIsConvertibleTo(StringRecTy::get(Records
))) {
1642 Error(InitLoc
, Twine("expected bit, bits, int, or string; "
1643 "got value of type '") + ArgType
->getAsString() +
1648 case BinOpInit::INTERLEAVE
:
1649 switch (InitList
.size()) {
1650 case 1: // First argument must be a list of strings or integers.
1651 if (ArgType
!= StringRecTy::get(Records
)->getListTy() &&
1652 !ArgType
->typeIsConvertibleTo(
1653 IntRecTy::get(Records
)->getListTy())) {
1654 Error(InitLoc
, Twine("expected list of string, int, bits, or bit; "
1655 "got value of type '") +
1656 ArgType
->getAsString() + "'");
1660 case 2: // Second argument must be a string.
1661 if (!isa
<StringRecTy
>(ArgType
)) {
1662 Error(InitLoc
, Twine("expected second argument to be a string, "
1663 "got value of type '") +
1664 ArgType
->getAsString() + "'");
1670 ArgType
= nullptr; // Broken invariant: types not identical.
1672 default: llvm_unreachable("other ops have fixed argument types");
1676 // Desired argument type is a known and in ArgType.
1677 RecTy
*Resolved
= resolveTypes(ArgType
, ListType
);
1679 Error(InitLoc
, Twine("expected value of type '") +
1680 ArgType
->getAsString() + "', got '" +
1681 ListType
->getAsString() + "'");
1684 if (Code
!= BinOpInit::ADD
&& Code
!= BinOpInit::SUB
&&
1685 Code
!= BinOpInit::AND
&& Code
!= BinOpInit::OR
&&
1686 Code
!= BinOpInit::XOR
&& Code
!= BinOpInit::SRA
&&
1687 Code
!= BinOpInit::SRL
&& Code
!= BinOpInit::SHL
&&
1688 Code
!= BinOpInit::MUL
&& Code
!= BinOpInit::DIV
)
1692 // Deal with BinOps whose arguments have different types, by
1693 // rewriting ArgType in between them.
1695 case BinOpInit::SETDAGOP
:
1696 // After parsing the first dag argument, switch to expecting
1697 // a record, with no restriction on its superclasses.
1698 ArgType
= RecordRecTy::get(Records
, {});
1700 case BinOpInit::GETDAGARG
:
1701 // After parsing the first dag argument, expect an index integer or a
1705 case BinOpInit::GETDAGNAME
:
1706 // After parsing the first dag argument, expect an index integer.
1707 ArgType
= IntRecTy::get(Records
);
1713 if (!consume(tgtok::comma
))
1717 if (!consume(tgtok::r_paren
)) {
1718 TokError("expected ')' in operator");
1722 // listconcat returns a list with type of the argument.
1723 if (Code
== BinOpInit::LISTCONCAT
)
1725 // listsplat returns a list of type of the *first* argument.
1726 if (Code
== BinOpInit::LISTSPLAT
)
1727 Type
= cast
<TypedInit
>(InitList
.front())->getType()->getListTy();
1728 // listremove returns a list with type of the argument.
1729 if (Code
== BinOpInit::LISTREMOVE
)
1732 // We allow multiple operands to associative operators like !strconcat as
1733 // shorthand for nesting them.
1734 if (Code
== BinOpInit::STRCONCAT
|| Code
== BinOpInit::LISTCONCAT
||
1735 Code
== BinOpInit::CONCAT
|| Code
== BinOpInit::ADD
||
1736 Code
== BinOpInit::AND
|| Code
== BinOpInit::OR
||
1737 Code
== BinOpInit::XOR
|| Code
== BinOpInit::MUL
) {
1738 while (InitList
.size() > 2) {
1739 Init
*RHS
= InitList
.pop_back_val();
1740 RHS
= (BinOpInit::get(Code
, InitList
.back(), RHS
, Type
))->Fold(CurRec
);
1741 InitList
.back() = RHS
;
1745 if (InitList
.size() == 2)
1746 return (BinOpInit::get(Code
, InitList
[0], InitList
[1], Type
))
1749 Error(OpLoc
, "expected two operands to operator");
1753 case tgtok::XForEach
:
1754 case tgtok::XFilter
: {
1755 return ParseOperationForEachFilter(CurRec
, ItemType
);
1758 case tgtok::XRange
: {
1759 SMLoc OpLoc
= Lex
.getLoc();
1760 Lex
.Lex(); // eat the operation
1762 if (!consume(tgtok::l_paren
)) {
1763 TokError("expected '(' after !range operator");
1767 SmallVector
<Init
*, 2> Args
;
1768 bool FirstArgIsList
= false;
1770 if (Args
.size() >= 3) {
1771 TokError("expected at most three values of integer");
1775 SMLoc InitLoc
= Lex
.getLoc();
1776 Args
.push_back(ParseValue(CurRec
));
1780 TypedInit
*ArgBack
= dyn_cast
<TypedInit
>(Args
.back());
1782 Error(OpLoc
, Twine("expected value to be a typed value, got '" +
1783 Args
.back()->getAsString() + "'"));
1787 RecTy
*ArgBackType
= ArgBack
->getType();
1788 if (!FirstArgIsList
|| Args
.size() == 1) {
1789 if (Args
.size() == 1 && isa
<ListRecTy
>(ArgBackType
)) {
1790 FirstArgIsList
= true; // Detect error if 2nd arg were present.
1791 } else if (isa
<IntRecTy
>(ArgBackType
)) {
1792 // Assume 2nd arg should be IntRecTy
1794 if (Args
.size() != 1)
1795 Error(InitLoc
, Twine("expected value of type 'int', got '" +
1796 ArgBackType
->getAsString() + "'"));
1798 Error(InitLoc
, Twine("expected list or int, got value of type '") +
1799 ArgBackType
->getAsString() + "'");
1803 // Don't come here unless 1st arg is ListRecTy.
1804 assert(isa
<ListRecTy
>(cast
<TypedInit
>(Args
[0])->getType()));
1805 Error(InitLoc
, Twine("expected one list, got extra value of type '") +
1806 ArgBackType
->getAsString() + "'");
1809 if (!consume(tgtok::comma
))
1813 if (!consume(tgtok::r_paren
)) {
1814 TokError("expected ')' in operator");
1818 Init
*LHS
, *MHS
, *RHS
;
1819 auto ArgCount
= Args
.size();
1820 assert(ArgCount
>= 1);
1821 auto *Arg0
= cast
<TypedInit
>(Args
[0]);
1822 auto *Arg0Ty
= Arg0
->getType();
1823 if (ArgCount
== 1) {
1824 if (isa
<ListRecTy
>(Arg0Ty
)) {
1825 // (0, !size(arg), 1)
1826 LHS
= IntInit::get(Records
, 0);
1827 MHS
= UnOpInit::get(UnOpInit::SIZE
, Arg0
, IntRecTy::get(Records
))
1829 RHS
= IntInit::get(Records
, 1);
1831 assert(isa
<IntRecTy
>(Arg0Ty
));
1833 LHS
= IntInit::get(Records
, 0);
1835 RHS
= IntInit::get(Records
, 1);
1838 assert(isa
<IntRecTy
>(Arg0Ty
));
1839 auto *Arg1
= cast
<TypedInit
>(Args
[1]);
1840 assert(isa
<IntRecTy
>(Arg1
->getType()));
1843 if (ArgCount
== 3) {
1844 // (start, end, step)
1845 auto *Arg2
= cast
<TypedInit
>(Args
[2]);
1846 assert(isa
<IntRecTy
>(Arg2
->getType()));
1850 RHS
= IntInit::get(Records
, 1);
1852 return TernOpInit::get(TernOpInit::RANGE
, LHS
, MHS
, RHS
,
1853 IntRecTy::get(Records
)->getListTy())
1857 case tgtok::XSetDagArg
:
1858 case tgtok::XSetDagName
:
1861 case tgtok::XSubst
: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1862 TernOpInit::TernaryOp Code
;
1863 RecTy
*Type
= nullptr;
1865 tgtok::TokKind LexCode
= Lex
.getCode();
1866 Lex
.Lex(); // eat the operation
1868 default: llvm_unreachable("Unhandled code!");
1870 Code
= TernOpInit::DAG
;
1871 Type
= DagRecTy::get(Records
);
1875 Code
= TernOpInit::IF
;
1878 Code
= TernOpInit::SUBST
;
1880 case tgtok::XSetDagArg
:
1881 Code
= TernOpInit::SETDAGARG
;
1882 Type
= DagRecTy::get(Records
);
1885 case tgtok::XSetDagName
:
1886 Code
= TernOpInit::SETDAGNAME
;
1887 Type
= DagRecTy::get(Records
);
1891 if (!consume(tgtok::l_paren
)) {
1892 TokError("expected '(' after ternary operator");
1896 Init
*LHS
= ParseValue(CurRec
);
1897 if (!LHS
) return nullptr;
1899 if (!consume(tgtok::comma
)) {
1900 TokError("expected ',' in ternary operator");
1904 SMLoc MHSLoc
= Lex
.getLoc();
1905 Init
*MHS
= ParseValue(CurRec
, ItemType
);
1909 if (!consume(tgtok::comma
)) {
1910 TokError("expected ',' in ternary operator");
1914 SMLoc RHSLoc
= Lex
.getLoc();
1915 Init
*RHS
= ParseValue(CurRec
, ItemType
);
1919 if (!consume(tgtok::r_paren
)) {
1920 TokError("expected ')' in binary operator");
1925 default: llvm_unreachable("Unhandled code!");
1927 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
1928 if (!MHSt
&& !isa
<UnsetInit
>(MHS
)) {
1929 Error(MHSLoc
, "could not determine type of the child list in !dag");
1932 if (MHSt
&& !isa
<ListRecTy
>(MHSt
->getType())) {
1933 Error(MHSLoc
, Twine("expected list of children, got type '") +
1934 MHSt
->getType()->getAsString() + "'");
1938 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
1939 if (!RHSt
&& !isa
<UnsetInit
>(RHS
)) {
1940 Error(RHSLoc
, "could not determine type of the name list in !dag");
1943 if (RHSt
&& StringRecTy::get(Records
)->getListTy() != RHSt
->getType()) {
1944 Error(RHSLoc
, Twine("expected list<string>, got type '") +
1945 RHSt
->getType()->getAsString() + "'");
1949 if (!MHSt
&& !RHSt
) {
1951 "cannot have both unset children and unset names in !dag");
1957 RecTy
*MHSTy
= nullptr;
1958 RecTy
*RHSTy
= nullptr;
1960 if (TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
))
1961 MHSTy
= MHSt
->getType();
1962 if (BitsInit
*MHSbits
= dyn_cast
<BitsInit
>(MHS
))
1963 MHSTy
= BitsRecTy::get(Records
, MHSbits
->getNumBits());
1964 if (isa
<BitInit
>(MHS
))
1965 MHSTy
= BitRecTy::get(Records
);
1967 if (TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
))
1968 RHSTy
= RHSt
->getType();
1969 if (BitsInit
*RHSbits
= dyn_cast
<BitsInit
>(RHS
))
1970 RHSTy
= BitsRecTy::get(Records
, RHSbits
->getNumBits());
1971 if (isa
<BitInit
>(RHS
))
1972 RHSTy
= BitRecTy::get(Records
);
1974 // For UnsetInit, it's typed from the other hand.
1975 if (isa
<UnsetInit
>(MHS
))
1977 if (isa
<UnsetInit
>(RHS
))
1980 if (!MHSTy
|| !RHSTy
) {
1981 TokError("could not get type for !if");
1985 Type
= resolveTypes(MHSTy
, RHSTy
);
1987 TokError(Twine("inconsistent types '") + MHSTy
->getAsString() +
1988 "' and '" + RHSTy
->getAsString() + "' for !if");
1993 case tgtok::XSubst
: {
1994 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
1996 TokError("could not get type for !subst");
1999 Type
= RHSt
->getType();
2002 case tgtok::XSetDagArg
: {
2003 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
2004 if (!MHSt
|| !isa
<IntRecTy
, StringRecTy
>(MHSt
->getType())) {
2005 Error(MHSLoc
, Twine("expected integer index or string name, got ") +
2006 (MHSt
? ("type '" + MHSt
->getType()->getAsString())
2007 : ("'" + MHS
->getAsString())) +
2013 case tgtok::XSetDagName
: {
2014 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
2015 if (!MHSt
|| !isa
<IntRecTy
, StringRecTy
>(MHSt
->getType())) {
2016 Error(MHSLoc
, Twine("expected integer index or string name, got ") +
2017 (MHSt
? ("type '" + MHSt
->getType()->getAsString())
2018 : ("'" + MHS
->getAsString())) +
2022 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
2023 // The name could be a string or unset.
2024 if (RHSt
&& !isa
<StringRecTy
>(RHSt
->getType())) {
2025 Error(RHSLoc
, Twine("expected string or unset name, got type '") +
2026 RHSt
->getType()->getAsString() + "'");
2032 return (TernOpInit::get(Code
, LHS
, MHS
, RHS
, Type
))->Fold(CurRec
);
2035 case tgtok::XSubstr
:
2036 return ParseOperationSubstr(CurRec
, ItemType
);
2039 return ParseOperationFind(CurRec
, ItemType
);
2042 return ParseOperationCond(CurRec
, ItemType
);
2044 case tgtok::XFoldl
: {
2045 // Value ::= !foldl '(' Value ',' Value ',' Id ',' Id ',' Expr ')'
2046 Lex
.Lex(); // eat the operation
2047 if (!consume(tgtok::l_paren
)) {
2048 TokError("expected '(' after !foldl");
2052 Init
*StartUntyped
= ParseValue(CurRec
);
2056 TypedInit
*Start
= dyn_cast
<TypedInit
>(StartUntyped
);
2058 TokError(Twine("could not get type of !foldl start: '") +
2059 StartUntyped
->getAsString() + "'");
2063 if (!consume(tgtok::comma
)) {
2064 TokError("expected ',' in !foldl");
2068 Init
*ListUntyped
= ParseValue(CurRec
);
2072 TypedInit
*List
= dyn_cast
<TypedInit
>(ListUntyped
);
2074 TokError(Twine("could not get type of !foldl list: '") +
2075 ListUntyped
->getAsString() + "'");
2079 ListRecTy
*ListType
= dyn_cast
<ListRecTy
>(List
->getType());
2081 TokError(Twine("!foldl list must be a list, but is of type '") +
2082 List
->getType()->getAsString());
2086 if (Lex
.getCode() != tgtok::comma
) {
2087 TokError("expected ',' in !foldl");
2091 if (Lex
.Lex() != tgtok::Id
) { // eat the ','
2092 TokError("third argument of !foldl must be an identifier");
2096 Init
*A
= StringInit::get(Records
, Lex
.getCurStrVal());
2097 if (CurRec
&& CurRec
->getValue(A
)) {
2098 TokError((Twine("left !foldl variable '") + A
->getAsString() +
2099 "' already defined")
2104 if (Lex
.Lex() != tgtok::comma
) { // eat the id
2105 TokError("expected ',' in !foldl");
2109 if (Lex
.Lex() != tgtok::Id
) { // eat the ','
2110 TokError("fourth argument of !foldl must be an identifier");
2114 Init
*B
= StringInit::get(Records
, Lex
.getCurStrVal());
2115 if (CurRec
&& CurRec
->getValue(B
)) {
2116 TokError((Twine("right !foldl variable '") + B
->getAsString() +
2117 "' already defined")
2122 if (Lex
.Lex() != tgtok::comma
) { // eat the id
2123 TokError("expected ',' in !foldl");
2126 Lex
.Lex(); // eat the ','
2128 // We need to create a temporary record to provide a scope for the
2130 std::unique_ptr
<Record
> ParseRecTmp
;
2131 Record
*ParseRec
= CurRec
;
2133 ParseRecTmp
= std::make_unique
<Record
>(".parse", ArrayRef
<SMLoc
>{}, Records
);
2134 ParseRec
= ParseRecTmp
.get();
2137 TGVarScope
*FoldScope
= PushScope(ParseRec
);
2138 ParseRec
->addValue(RecordVal(A
, Start
->getType(), RecordVal::FK_Normal
));
2140 RecordVal(B
, ListType
->getElementType(), RecordVal::FK_Normal
));
2141 Init
*ExprUntyped
= ParseValue(ParseRec
);
2142 ParseRec
->removeValue(A
);
2143 ParseRec
->removeValue(B
);
2144 PopScope(FoldScope
);
2148 TypedInit
*Expr
= dyn_cast
<TypedInit
>(ExprUntyped
);
2150 TokError("could not get type of !foldl expression");
2154 if (Expr
->getType() != Start
->getType()) {
2155 TokError(Twine("!foldl expression must be of same type as start (") +
2156 Start
->getType()->getAsString() + "), but is of type " +
2157 Expr
->getType()->getAsString());
2161 if (!consume(tgtok::r_paren
)) {
2162 TokError("expected ')' in fold operator");
2166 return FoldOpInit::get(Start
, List
, A
, B
, Expr
, Start
->getType())
2172 /// ParseOperatorType - Parse a type for an operator. This returns
2175 /// OperatorType ::= '<' Type '>'
2177 RecTy
*TGParser::ParseOperatorType() {
2178 RecTy
*Type
= nullptr;
2180 if (!consume(tgtok::less
)) {
2181 TokError("expected type name for operator");
2185 if (Lex
.getCode() == tgtok::Code
)
2186 TokError("the 'code' type is not allowed in bang operators; use 'string'");
2191 TokError("expected type name for operator");
2195 if (!consume(tgtok::greater
)) {
2196 TokError("expected type name for operator");
2203 /// Parse the !substr operation. Return null on error.
2205 /// Substr ::= !substr(string, start-int [, length-int]) => string
2206 Init
*TGParser::ParseOperationSubstr(Record
*CurRec
, RecTy
*ItemType
) {
2207 TernOpInit::TernaryOp Code
= TernOpInit::SUBSTR
;
2208 RecTy
*Type
= StringRecTy::get(Records
);
2210 Lex
.Lex(); // eat the operation
2212 if (!consume(tgtok::l_paren
)) {
2213 TokError("expected '(' after !substr operator");
2217 Init
*LHS
= ParseValue(CurRec
);
2221 if (!consume(tgtok::comma
)) {
2222 TokError("expected ',' in !substr operator");
2226 SMLoc MHSLoc
= Lex
.getLoc();
2227 Init
*MHS
= ParseValue(CurRec
);
2231 SMLoc RHSLoc
= Lex
.getLoc();
2233 if (consume(tgtok::comma
)) {
2234 RHSLoc
= Lex
.getLoc();
2235 RHS
= ParseValue(CurRec
);
2239 RHS
= IntInit::get(Records
, std::numeric_limits
<int64_t>::max());
2242 if (!consume(tgtok::r_paren
)) {
2243 TokError("expected ')' in !substr operator");
2247 if (ItemType
&& !Type
->typeIsConvertibleTo(ItemType
)) {
2248 Error(RHSLoc
, Twine("expected value of type '") +
2249 ItemType
->getAsString() + "', got '" +
2250 Type
->getAsString() + "'");
2253 TypedInit
*LHSt
= dyn_cast
<TypedInit
>(LHS
);
2254 if (!LHSt
&& !isa
<UnsetInit
>(LHS
)) {
2255 TokError("could not determine type of the string in !substr");
2258 if (LHSt
&& !isa
<StringRecTy
>(LHSt
->getType())) {
2259 TokError(Twine("expected string, got type '") +
2260 LHSt
->getType()->getAsString() + "'");
2264 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
2265 if (!MHSt
&& !isa
<UnsetInit
>(MHS
)) {
2266 TokError("could not determine type of the start position in !substr");
2269 if (MHSt
&& !isa
<IntRecTy
>(MHSt
->getType())) {
2270 Error(MHSLoc
, Twine("expected int, got type '") +
2271 MHSt
->getType()->getAsString() + "'");
2276 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
2277 if (!RHSt
&& !isa
<UnsetInit
>(RHS
)) {
2278 TokError("could not determine type of the length in !substr");
2281 if (RHSt
&& !isa
<IntRecTy
>(RHSt
->getType())) {
2282 TokError(Twine("expected int, got type '") +
2283 RHSt
->getType()->getAsString() + "'");
2288 return (TernOpInit::get(Code
, LHS
, MHS
, RHS
, Type
))->Fold(CurRec
);
2291 /// Parse the !find operation. Return null on error.
2293 /// Substr ::= !find(string, string [, start-int]) => int
2294 Init
*TGParser::ParseOperationFind(Record
*CurRec
, RecTy
*ItemType
) {
2295 TernOpInit::TernaryOp Code
= TernOpInit::FIND
;
2296 RecTy
*Type
= IntRecTy::get(Records
);
2298 Lex
.Lex(); // eat the operation
2300 if (!consume(tgtok::l_paren
)) {
2301 TokError("expected '(' after !find operator");
2305 Init
*LHS
= ParseValue(CurRec
);
2309 if (!consume(tgtok::comma
)) {
2310 TokError("expected ',' in !find operator");
2314 SMLoc MHSLoc
= Lex
.getLoc();
2315 Init
*MHS
= ParseValue(CurRec
);
2319 SMLoc RHSLoc
= Lex
.getLoc();
2321 if (consume(tgtok::comma
)) {
2322 RHSLoc
= Lex
.getLoc();
2323 RHS
= ParseValue(CurRec
);
2327 RHS
= IntInit::get(Records
, 0);
2330 if (!consume(tgtok::r_paren
)) {
2331 TokError("expected ')' in !find operator");
2335 if (ItemType
&& !Type
->typeIsConvertibleTo(ItemType
)) {
2336 Error(RHSLoc
, Twine("expected value of type '") +
2337 ItemType
->getAsString() + "', got '" +
2338 Type
->getAsString() + "'");
2341 TypedInit
*LHSt
= dyn_cast
<TypedInit
>(LHS
);
2342 if (!LHSt
&& !isa
<UnsetInit
>(LHS
)) {
2343 TokError("could not determine type of the source string in !find");
2346 if (LHSt
&& !isa
<StringRecTy
>(LHSt
->getType())) {
2347 TokError(Twine("expected string, got type '") +
2348 LHSt
->getType()->getAsString() + "'");
2352 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
2353 if (!MHSt
&& !isa
<UnsetInit
>(MHS
)) {
2354 TokError("could not determine type of the target string in !find");
2357 if (MHSt
&& !isa
<StringRecTy
>(MHSt
->getType())) {
2358 Error(MHSLoc
, Twine("expected string, got type '") +
2359 MHSt
->getType()->getAsString() + "'");
2364 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
2365 if (!RHSt
&& !isa
<UnsetInit
>(RHS
)) {
2366 TokError("could not determine type of the start position in !find");
2369 if (RHSt
&& !isa
<IntRecTy
>(RHSt
->getType())) {
2370 TokError(Twine("expected int, got type '") +
2371 RHSt
->getType()->getAsString() + "'");
2376 return (TernOpInit::get(Code
, LHS
, MHS
, RHS
, Type
))->Fold(CurRec
);
2379 /// Parse the !foreach and !filter operations. Return null on error.
2381 /// ForEach ::= !foreach(ID, list-or-dag, expr) => list<expr type>
2382 /// Filter ::= !foreach(ID, list, predicate) ==> list<list type>
2383 Init
*TGParser::ParseOperationForEachFilter(Record
*CurRec
, RecTy
*ItemType
) {
2384 SMLoc OpLoc
= Lex
.getLoc();
2385 tgtok::TokKind Operation
= Lex
.getCode();
2386 Lex
.Lex(); // eat the operation
2387 if (Lex
.getCode() != tgtok::l_paren
) {
2388 TokError("expected '(' after !foreach/!filter");
2392 if (Lex
.Lex() != tgtok::Id
) { // eat the '('
2393 TokError("first argument of !foreach/!filter must be an identifier");
2397 Init
*LHS
= StringInit::get(Records
, Lex
.getCurStrVal());
2398 Lex
.Lex(); // eat the ID.
2400 if (CurRec
&& CurRec
->getValue(LHS
)) {
2401 TokError((Twine("iteration variable '") + LHS
->getAsString() +
2402 "' is already defined")
2407 if (!consume(tgtok::comma
)) {
2408 TokError("expected ',' in !foreach/!filter");
2412 Init
*MHS
= ParseValue(CurRec
);
2416 if (!consume(tgtok::comma
)) {
2417 TokError("expected ',' in !foreach/!filter");
2421 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
2423 TokError("could not get type of !foreach/!filter list or dag");
2427 RecTy
*InEltType
= nullptr;
2428 RecTy
*ExprEltType
= nullptr;
2431 if (ListRecTy
*InListTy
= dyn_cast
<ListRecTy
>(MHSt
->getType())) {
2432 InEltType
= InListTy
->getElementType();
2434 if (ListRecTy
*OutListTy
= dyn_cast
<ListRecTy
>(ItemType
)) {
2435 ExprEltType
= (Operation
== tgtok::XForEach
)
2436 ? OutListTy
->getElementType()
2437 : IntRecTy::get(Records
);
2440 "expected value of type '" +
2441 Twine(ItemType
->getAsString()) +
2442 "', but got list type");
2446 } else if (DagRecTy
*InDagTy
= dyn_cast
<DagRecTy
>(MHSt
->getType())) {
2447 if (Operation
== tgtok::XFilter
) {
2448 TokError("!filter must have a list argument");
2451 InEltType
= InDagTy
;
2452 if (ItemType
&& !isa
<DagRecTy
>(ItemType
)) {
2454 "expected value of type '" + Twine(ItemType
->getAsString()) +
2455 "', but got dag type");
2460 if (Operation
== tgtok::XForEach
)
2461 TokError("!foreach must have a list or dag argument");
2463 TokError("!filter must have a list argument");
2467 // We need to create a temporary record to provide a scope for the
2468 // iteration variable.
2469 std::unique_ptr
<Record
> ParseRecTmp
;
2470 Record
*ParseRec
= CurRec
;
2473 std::make_unique
<Record
>(".parse", ArrayRef
<SMLoc
>{}, Records
);
2474 ParseRec
= ParseRecTmp
.get();
2476 TGVarScope
*TempScope
= PushScope(ParseRec
);
2477 ParseRec
->addValue(RecordVal(LHS
, InEltType
, RecordVal::FK_Normal
));
2478 Init
*RHS
= ParseValue(ParseRec
, ExprEltType
);
2479 ParseRec
->removeValue(LHS
);
2480 PopScope(TempScope
);
2484 if (!consume(tgtok::r_paren
)) {
2485 TokError("expected ')' in !foreach/!filter");
2489 RecTy
*OutType
= InEltType
;
2490 if (Operation
== tgtok::XForEach
&& !IsDAG
) {
2491 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
2493 TokError("could not get type of !foreach result expression");
2496 OutType
= RHSt
->getType()->getListTy();
2497 } else if (Operation
== tgtok::XFilter
) {
2498 OutType
= InEltType
->getListTy();
2501 return (TernOpInit::get((Operation
== tgtok::XForEach
) ? TernOpInit::FOREACH
2502 : TernOpInit::FILTER
,
2503 LHS
, MHS
, RHS
, OutType
))
2507 Init
*TGParser::ParseOperationCond(Record
*CurRec
, RecTy
*ItemType
) {
2508 Lex
.Lex(); // eat the operation 'cond'
2510 if (!consume(tgtok::l_paren
)) {
2511 TokError("expected '(' after !cond operator");
2515 // Parse through '[Case: Val,]+'
2516 SmallVector
<Init
*, 4> Case
;
2517 SmallVector
<Init
*, 4> Val
;
2519 if (consume(tgtok::r_paren
))
2522 Init
*V
= ParseValue(CurRec
);
2527 if (!consume(tgtok::colon
)) {
2528 TokError("expected ':' following a condition in !cond operator");
2532 V
= ParseValue(CurRec
, ItemType
);
2537 if (consume(tgtok::r_paren
))
2540 if (!consume(tgtok::comma
)) {
2541 TokError("expected ',' or ')' following a value in !cond operator");
2546 if (Case
.size() < 1) {
2547 TokError("there should be at least 1 'condition : value' in the !cond operator");
2552 RecTy
*Type
= nullptr;
2553 for (Init
*V
: Val
) {
2554 RecTy
*VTy
= nullptr;
2555 if (TypedInit
*Vt
= dyn_cast
<TypedInit
>(V
))
2556 VTy
= Vt
->getType();
2557 if (BitsInit
*Vbits
= dyn_cast
<BitsInit
>(V
))
2558 VTy
= BitsRecTy::get(Records
, Vbits
->getNumBits());
2559 if (isa
<BitInit
>(V
))
2560 VTy
= BitRecTy::get(Records
);
2562 if (Type
== nullptr) {
2563 if (!isa
<UnsetInit
>(V
))
2566 if (!isa
<UnsetInit
>(V
)) {
2567 RecTy
*RType
= resolveTypes(Type
, VTy
);
2569 TokError(Twine("inconsistent types '") + Type
->getAsString() +
2570 "' and '" + VTy
->getAsString() + "' for !cond");
2579 TokError("could not determine type for !cond from its arguments");
2582 return CondOpInit::get(Case
, Val
, Type
)->Fold(CurRec
);
2585 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
2587 /// SimpleValue ::= IDValue
2588 /// SimpleValue ::= INTVAL
2589 /// SimpleValue ::= STRVAL+
2590 /// SimpleValue ::= CODEFRAGMENT
2591 /// SimpleValue ::= '?'
2592 /// SimpleValue ::= '{' ValueList '}'
2593 /// SimpleValue ::= ID '<' ValueListNE '>'
2594 /// SimpleValue ::= '[' ValueList ']'
2595 /// SimpleValue ::= '(' IDValue DagArgList ')'
2596 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
2597 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
2598 /// SimpleValue ::= DIVTOK '(' Value ',' Value ')'
2599 /// SimpleValue ::= SUBTOK '(' Value ',' Value ')'
2600 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
2601 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
2602 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
2603 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
2604 /// SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')'
2605 /// SimpleValue ::= LISTREMOVETOK '(' Value ',' Value ')'
2606 /// SimpleValue ::= RANGE '(' Value ')'
2607 /// SimpleValue ::= RANGE '(' Value ',' Value ')'
2608 /// SimpleValue ::= RANGE '(' Value ',' Value ',' Value ')'
2609 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
2610 /// SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
2612 Init
*TGParser::ParseSimpleValue(Record
*CurRec
, RecTy
*ItemType
,
2615 tgtok::TokKind Code
= Lex
.getCode();
2617 // Parse bang operators.
2618 if (tgtok::isBangOperator(Code
))
2619 return ParseOperation(CurRec
, ItemType
);
2622 default: TokError("Unknown or reserved token when parsing a value"); break;
2624 case tgtok::TrueVal
:
2625 R
= IntInit::get(Records
, 1);
2628 case tgtok::FalseVal
:
2629 R
= IntInit::get(Records
, 0);
2633 R
= IntInit::get(Records
, Lex
.getCurIntVal());
2636 case tgtok::BinaryIntVal
: {
2637 auto BinaryVal
= Lex
.getCurBinaryIntVal();
2638 SmallVector
<Init
*, 16> Bits(BinaryVal
.second
);
2639 for (unsigned i
= 0, e
= BinaryVal
.second
; i
!= e
; ++i
)
2640 Bits
[i
] = BitInit::get(Records
, BinaryVal
.first
& (1LL << i
));
2641 R
= BitsInit::get(Records
, Bits
);
2645 case tgtok::StrVal
: {
2646 std::string Val
= Lex
.getCurStrVal();
2649 // Handle multiple consecutive concatenated strings.
2650 while (Lex
.getCode() == tgtok::StrVal
) {
2651 Val
+= Lex
.getCurStrVal();
2655 R
= StringInit::get(Records
, Val
);
2658 case tgtok::CodeFragment
:
2659 R
= StringInit::get(Records
, Lex
.getCurStrVal(), StringInit::SF_Code
);
2662 case tgtok::question
:
2663 R
= UnsetInit::get(Records
);
2667 SMRange NameLoc
= Lex
.getLocRange();
2668 StringInit
*Name
= StringInit::get(Records
, Lex
.getCurStrVal());
2669 tgtok::TokKind Next
= Lex
.Lex();
2670 if (Next
== tgtok::equal
) // Named argument.
2672 if (Next
!= tgtok::less
) // consume the Id.
2673 return ParseIDValue(CurRec
, Name
, NameLoc
, Mode
); // Value ::= IDValue
2675 // Value ::= CLASSID '<' ArgValueList '>' (CLASSID has been consumed)
2676 // This is supposed to synthesize a new anonymous definition, deriving
2677 // from the class with the template arguments, but no body.
2678 Record
*Class
= Records
.getClass(Name
->getValue());
2680 Error(NameLoc
.Start
,
2681 "Expected a class name, got '" + Name
->getValue() + "'");
2685 SmallVector
<ArgumentInit
*, 8> Args
;
2686 Lex
.Lex(); // consume the <
2687 if (ParseTemplateArgValueList(Args
, CurRec
, Class
))
2688 return nullptr; // Error parsing value list.
2690 if (CheckTemplateArgValues(Args
, NameLoc
.Start
, Class
))
2691 return nullptr; // Error checking template argument values.
2693 if (resolveArguments(Class
, Args
, NameLoc
.Start
))
2696 if (TrackReferenceLocs
)
2697 Class
->appendReferenceLoc(NameLoc
);
2698 return VarDefInit::get(Class
, Args
)->Fold();
2700 case tgtok::l_brace
: { // Value ::= '{' ValueList '}'
2701 SMLoc BraceLoc
= Lex
.getLoc();
2702 Lex
.Lex(); // eat the '{'
2703 SmallVector
<Init
*, 16> Vals
;
2705 if (Lex
.getCode() != tgtok::r_brace
) {
2706 ParseValueList(Vals
, CurRec
);
2707 if (Vals
.empty()) return nullptr;
2709 if (!consume(tgtok::r_brace
)) {
2710 TokError("expected '}' at end of bit list value");
2714 SmallVector
<Init
*, 16> NewBits
;
2716 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
2717 // first. We'll first read everything in to a vector, then we can reverse
2718 // it to get the bits in the correct order for the BitsInit value.
2719 for (unsigned i
= 0, e
= Vals
.size(); i
!= e
; ++i
) {
2720 // FIXME: The following two loops would not be duplicated
2721 // if the API was a little more orthogonal.
2723 // bits<n> values are allowed to initialize n bits.
2724 if (BitsInit
*BI
= dyn_cast
<BitsInit
>(Vals
[i
])) {
2725 for (unsigned i
= 0, e
= BI
->getNumBits(); i
!= e
; ++i
)
2726 NewBits
.push_back(BI
->getBit((e
- i
) - 1));
2729 // bits<n> can also come from variable initializers.
2730 if (VarInit
*VI
= dyn_cast
<VarInit
>(Vals
[i
])) {
2731 if (BitsRecTy
*BitsRec
= dyn_cast
<BitsRecTy
>(VI
->getType())) {
2732 for (unsigned i
= 0, e
= BitsRec
->getNumBits(); i
!= e
; ++i
)
2733 NewBits
.push_back(VI
->getBit((e
- i
) - 1));
2736 // Fallthrough to try convert this to a bit.
2738 // All other values must be convertible to just a single bit.
2739 Init
*Bit
= Vals
[i
]->getCastTo(BitRecTy::get(Records
));
2741 Error(BraceLoc
, "Element #" + Twine(i
) + " (" + Vals
[i
]->getAsString() +
2742 ") is not convertable to a bit");
2745 NewBits
.push_back(Bit
);
2747 std::reverse(NewBits
.begin(), NewBits
.end());
2748 return BitsInit::get(Records
, NewBits
);
2750 case tgtok::l_square
: { // Value ::= '[' ValueList ']'
2751 Lex
.Lex(); // eat the '['
2752 SmallVector
<Init
*, 16> Vals
;
2754 RecTy
*DeducedEltTy
= nullptr;
2755 ListRecTy
*GivenListTy
= nullptr;
2758 ListRecTy
*ListType
= dyn_cast
<ListRecTy
>(ItemType
);
2760 TokError(Twine("Encountered a list when expecting a ") +
2761 ItemType
->getAsString());
2764 GivenListTy
= ListType
;
2767 if (Lex
.getCode() != tgtok::r_square
) {
2768 ParseValueList(Vals
, CurRec
,
2769 GivenListTy
? GivenListTy
->getElementType() : nullptr);
2770 if (Vals
.empty()) return nullptr;
2772 if (!consume(tgtok::r_square
)) {
2773 TokError("expected ']' at end of list value");
2777 RecTy
*GivenEltTy
= nullptr;
2778 if (consume(tgtok::less
)) {
2779 // Optional list element type
2780 GivenEltTy
= ParseType();
2782 // Couldn't parse element type
2786 if (!consume(tgtok::greater
)) {
2787 TokError("expected '>' at end of list element type");
2793 RecTy
*EltTy
= nullptr;
2794 for (Init
*V
: Vals
) {
2795 TypedInit
*TArg
= dyn_cast
<TypedInit
>(V
);
2798 EltTy
= resolveTypes(EltTy
, TArg
->getType());
2800 TokError("Incompatible types in list elements");
2804 EltTy
= TArg
->getType();
2811 // Verify consistency
2812 if (!EltTy
->typeIsConvertibleTo(GivenEltTy
)) {
2813 TokError("Incompatible types in list elements");
2822 TokError("No type for list");
2825 DeducedEltTy
= GivenListTy
->getElementType();
2827 // Make sure the deduced type is compatible with the given type
2829 if (!EltTy
->typeIsConvertibleTo(GivenListTy
->getElementType())) {
2830 TokError(Twine("Element type mismatch for list: element type '") +
2831 EltTy
->getAsString() + "' not convertible to '" +
2832 GivenListTy
->getElementType()->getAsString());
2836 DeducedEltTy
= EltTy
;
2839 return ListInit::get(Vals
, DeducedEltTy
);
2841 case tgtok::l_paren
: { // Value ::= '(' IDValue DagArgList ')'
2842 Lex
.Lex(); // eat the '('
2843 if (Lex
.getCode() != tgtok::Id
&& Lex
.getCode() != tgtok::XCast
&&
2844 Lex
.getCode() != tgtok::question
&& Lex
.getCode() != tgtok::XGetDagOp
) {
2845 TokError("expected identifier in dag init");
2849 Init
*Operator
= ParseValue(CurRec
);
2850 if (!Operator
) return nullptr;
2852 // If the operator name is present, parse it.
2853 StringInit
*OperatorName
= nullptr;
2854 if (consume(tgtok::colon
)) {
2855 if (Lex
.getCode() != tgtok::VarName
) { // eat the ':'
2856 TokError("expected variable name in dag operator");
2859 OperatorName
= StringInit::get(Records
, Lex
.getCurStrVal());
2860 Lex
.Lex(); // eat the VarName.
2863 SmallVector
<std::pair
<llvm::Init
*, StringInit
*>, 8> DagArgs
;
2864 if (Lex
.getCode() != tgtok::r_paren
) {
2865 ParseDagArgList(DagArgs
, CurRec
);
2866 if (DagArgs
.empty()) return nullptr;
2869 if (!consume(tgtok::r_paren
)) {
2870 TokError("expected ')' in dag init");
2874 return DagInit::get(Operator
, OperatorName
, DagArgs
);
2881 /// ParseValue - Parse a TableGen value. This returns null on error.
2883 /// Value ::= SimpleValue ValueSuffix*
2884 /// ValueSuffix ::= '{' BitList '}'
2885 /// ValueSuffix ::= '[' SliceElements ']'
2886 /// ValueSuffix ::= '.' ID
2888 Init
*TGParser::ParseValue(Record
*CurRec
, RecTy
*ItemType
, IDParseMode Mode
) {
2889 SMLoc LHSLoc
= Lex
.getLoc();
2890 Init
*Result
= ParseSimpleValue(CurRec
, ItemType
, Mode
);
2891 if (!Result
) return nullptr;
2893 // Parse the suffixes now if present.
2895 switch (Lex
.getCode()) {
2896 default: return Result
;
2897 case tgtok::l_brace
: {
2898 if (Mode
== ParseNameMode
)
2899 // This is the beginning of the object body.
2902 SMLoc CurlyLoc
= Lex
.getLoc();
2903 Lex
.Lex(); // eat the '{'
2904 SmallVector
<unsigned, 16> Ranges
;
2905 ParseRangeList(Ranges
);
2906 if (Ranges
.empty()) return nullptr;
2908 // Reverse the bitlist.
2909 std::reverse(Ranges
.begin(), Ranges
.end());
2910 Result
= Result
->convertInitializerBitRange(Ranges
);
2912 Error(CurlyLoc
, "Invalid bit range for value");
2917 if (!consume(tgtok::r_brace
)) {
2918 TokError("expected '}' at end of bit range list");
2923 case tgtok::l_square
: {
2924 auto *LHS
= dyn_cast
<TypedInit
>(Result
);
2926 Error(LHSLoc
, "Invalid value, list expected");
2930 auto *LHSTy
= dyn_cast
<ListRecTy
>(LHS
->getType());
2932 Error(LHSLoc
, "Type '" + Twine(LHS
->getType()->getAsString()) +
2933 "' is invalid, list expected");
2937 Lex
.Lex(); // eat the '['
2938 TypedInit
*RHS
= ParseSliceElements(CurRec
, /*Single=*/true);
2942 if (isa
<ListRecTy
>(RHS
->getType())) {
2944 BinOpInit::get(BinOpInit::LISTSLICE
, LHS
, RHS
, LHSTy
)->Fold(CurRec
);
2946 Result
= BinOpInit::get(BinOpInit::LISTELEM
, LHS
, RHS
,
2947 LHSTy
->getElementType())
2954 if (!consume(tgtok::r_square
)) {
2955 TokError("expected ']' at end of list slice");
2961 if (Lex
.Lex() != tgtok::Id
) { // eat the .
2962 TokError("expected field identifier after '.'");
2965 SMRange FieldNameLoc
= Lex
.getLocRange();
2966 StringInit
*FieldName
= StringInit::get(Records
, Lex
.getCurStrVal());
2967 if (!Result
->getFieldType(FieldName
)) {
2968 TokError("Cannot access field '" + Lex
.getCurStrVal() + "' of value '" +
2969 Result
->getAsString() + "'");
2973 // Add a reference to this field if we know the record class.
2974 if (TrackReferenceLocs
) {
2975 if (auto *DI
= dyn_cast
<DefInit
>(Result
)) {
2976 DI
->getDef()->getValue(FieldName
)->addReferenceLoc(FieldNameLoc
);
2977 } else if (auto *TI
= dyn_cast
<TypedInit
>(Result
)) {
2978 if (auto *RecTy
= dyn_cast
<RecordRecTy
>(TI
->getType())) {
2979 for (Record
*R
: RecTy
->getClasses())
2980 if (auto *RV
= R
->getValue(FieldName
))
2981 RV
->addReferenceLoc(FieldNameLoc
);
2986 Result
= FieldInit::get(Result
, FieldName
)->Fold(CurRec
);
2987 Lex
.Lex(); // eat field name
2992 SMLoc PasteLoc
= Lex
.getLoc();
2993 TypedInit
*LHS
= dyn_cast
<TypedInit
>(Result
);
2995 Error(PasteLoc
, "LHS of paste is not typed!");
2999 // Check if it's a 'listA # listB'
3000 if (isa
<ListRecTy
>(LHS
->getType())) {
3001 Lex
.Lex(); // Eat the '#'.
3003 assert(Mode
== ParseValueMode
&& "encountered paste of lists in name");
3005 switch (Lex
.getCode()) {
3008 case tgtok::l_brace
:
3009 Result
= LHS
; // trailing paste, ignore.
3012 Init
*RHSResult
= ParseValue(CurRec
, ItemType
, ParseValueMode
);
3015 Result
= BinOpInit::getListConcat(LHS
, RHSResult
);
3021 // Create a !strconcat() operation, first casting each operand to
3022 // a string if necessary.
3023 if (LHS
->getType() != StringRecTy::get(Records
)) {
3024 auto CastLHS
= dyn_cast
<TypedInit
>(
3025 UnOpInit::get(UnOpInit::CAST
, LHS
, StringRecTy::get(Records
))
3029 Twine("can't cast '") + LHS
->getAsString() + "' to string");
3035 TypedInit
*RHS
= nullptr;
3037 Lex
.Lex(); // Eat the '#'.
3038 switch (Lex
.getCode()) {
3041 case tgtok::l_brace
:
3042 // These are all of the tokens that can begin an object body.
3043 // Some of these can also begin values but we disallow those cases
3044 // because they are unlikely to be useful.
3046 // Trailing paste, concat with an empty string.
3047 RHS
= StringInit::get(Records
, "");
3051 Init
*RHSResult
= ParseValue(CurRec
, nullptr, ParseNameMode
);
3054 RHS
= dyn_cast
<TypedInit
>(RHSResult
);
3056 Error(PasteLoc
, "RHS of paste is not typed!");
3060 if (RHS
->getType() != StringRecTy::get(Records
)) {
3061 auto CastRHS
= dyn_cast
<TypedInit
>(
3062 UnOpInit::get(UnOpInit::CAST
, RHS
, StringRecTy::get(Records
))
3066 Twine("can't cast '") + RHS
->getAsString() + "' to string");
3075 Result
= BinOpInit::getStrConcat(LHS
, RHS
);
3081 /// ParseDagArgList - Parse the argument list for a dag literal expression.
3083 /// DagArg ::= Value (':' VARNAME)?
3084 /// DagArg ::= VARNAME
3085 /// DagArgList ::= DagArg
3086 /// DagArgList ::= DagArgList ',' DagArg
3087 void TGParser::ParseDagArgList(
3088 SmallVectorImpl
<std::pair
<llvm::Init
*, StringInit
*>> &Result
,
3092 // DagArg ::= VARNAME
3093 if (Lex
.getCode() == tgtok::VarName
) {
3094 // A missing value is treated like '?'.
3095 StringInit
*VarName
= StringInit::get(Records
, Lex
.getCurStrVal());
3096 Result
.emplace_back(UnsetInit::get(Records
), VarName
);
3099 // DagArg ::= Value (':' VARNAME)?
3100 Init
*Val
= ParseValue(CurRec
);
3106 // If the variable name is present, add it.
3107 StringInit
*VarName
= nullptr;
3108 if (Lex
.getCode() == tgtok::colon
) {
3109 if (Lex
.Lex() != tgtok::VarName
) { // eat the ':'
3110 TokError("expected variable name in dag literal");
3114 VarName
= StringInit::get(Records
, Lex
.getCurStrVal());
3115 Lex
.Lex(); // eat the VarName.
3118 Result
.push_back(std::make_pair(Val
, VarName
));
3120 if (!consume(tgtok::comma
))
3125 /// ParseValueList - Parse a comma separated list of values, returning them
3126 /// in a vector. Note that this always expects to be able to parse at least one
3127 /// value. It returns an empty list if this is not possible.
3129 /// ValueList ::= Value (',' Value)
3131 void TGParser::ParseValueList(SmallVectorImpl
<Init
*> &Result
, Record
*CurRec
,
3134 Result
.push_back(ParseValue(CurRec
, ItemType
));
3135 if (!Result
.back()) {
3140 while (consume(tgtok::comma
)) {
3141 // ignore trailing comma for lists
3142 if (Lex
.getCode() == tgtok::r_square
)
3144 Result
.push_back(ParseValue(CurRec
, ItemType
));
3145 if (!Result
.back()) {
3152 // ParseTemplateArgValueList - Parse a template argument list with the syntax
3153 // shown, filling in the Result vector. The open angle has been consumed.
3154 // An empty argument list is allowed. Return false if okay, true if an
3155 // error was detected.
3157 // ArgValueList ::= '<' PostionalArgValueList [','] NamedArgValueList '>'
3158 // PostionalArgValueList ::= [Value {',' Value}*]
3159 // NamedArgValueList ::= [NameValue '=' Value {',' NameValue '=' Value}*]
3160 bool TGParser::ParseTemplateArgValueList(
3161 SmallVectorImpl
<ArgumentInit
*> &Result
, Record
*CurRec
, Record
*ArgsRec
) {
3162 assert(Result
.empty() && "Result vector is not empty");
3163 ArrayRef
<Init
*> TArgs
= ArgsRec
->getTemplateArgs();
3165 if (consume(tgtok::greater
)) // empty value list
3168 bool HasNamedArg
= false;
3169 unsigned ArgIndex
= 0;
3171 if (ArgIndex
>= TArgs
.size()) {
3172 TokError("Too many template arguments: " + utostr(ArgIndex
+ 1));
3176 SMLoc ValueLoc
= Lex
.getLoc();
3177 // If we are parsing named argument, we don't need to know the argument name
3178 // and argument type will be resolved after we know the name.
3179 Init
*Value
= ParseValue(
3181 HasNamedArg
? nullptr : ArgsRec
->getValue(TArgs
[ArgIndex
])->getType());
3185 // If we meet '=', then we are parsing named arguments.
3186 if (Lex
.getCode() == tgtok::equal
) {
3187 if (!isa
<StringInit
>(Value
))
3188 return Error(ValueLoc
,
3189 "The name of named argument should be a valid identifier");
3191 auto *Name
= cast
<StringInit
>(Value
);
3192 Init
*QualifiedName
= QualifyName(*ArgsRec
, Name
);
3193 auto *NamedArg
= ArgsRec
->getValue(QualifiedName
);
3195 return Error(ValueLoc
,
3196 "Argument " + Name
->getAsString() + " doesn't exist");
3198 Lex
.Lex(); // eat the '='.
3199 ValueLoc
= Lex
.getLoc();
3200 Value
= ParseValue(CurRec
, NamedArg
->getType());
3201 // Named value can't be uninitialized.
3202 if (isa
<UnsetInit
>(Value
))
3203 return Error(ValueLoc
,
3204 "The value of named argument should be initialized, "
3206 Value
->getAsString() + "'");
3208 Result
.push_back(ArgumentInit::get(Value
, QualifiedName
));
3211 // Positional arguments should be put before named arguments.
3213 return Error(ValueLoc
,
3214 "Positional argument should be put before named argument");
3216 Result
.push_back(ArgumentInit::get(Value
, ArgIndex
));
3219 if (consume(tgtok::greater
)) // end of argument list?
3221 if (!consume(tgtok::comma
))
3222 return TokError("Expected comma before next argument");
3227 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
3228 /// empty string on error. This can happen in a number of different contexts,
3229 /// including within a def or in the template args for a class (in which case
3230 /// CurRec will be non-null) and within the template args for a multiclass (in
3231 /// which case CurRec will be null, but CurMultiClass will be set). This can
3232 /// also happen within a def that is within a multiclass, which will set both
3233 /// CurRec and CurMultiClass.
3235 /// Declaration ::= FIELD? Type ID ('=' Value)?
3237 Init
*TGParser::ParseDeclaration(Record
*CurRec
,
3238 bool ParsingTemplateArgs
) {
3239 // Read the field prefix if present.
3240 bool HasField
= consume(tgtok::Field
);
3242 RecTy
*Type
= ParseType();
3243 if (!Type
) return nullptr;
3245 if (Lex
.getCode() != tgtok::Id
) {
3246 TokError("Expected identifier in declaration");
3250 std::string Str
= Lex
.getCurStrVal();
3251 if (Str
== "NAME") {
3252 TokError("'" + Str
+ "' is a reserved variable name");
3256 if (!ParsingTemplateArgs
&& CurScope
->varAlreadyDefined(Str
)) {
3257 TokError("local variable of this name already exists");
3261 SMLoc IdLoc
= Lex
.getLoc();
3262 Init
*DeclName
= StringInit::get(Records
, Str
);
3266 if (!ParsingTemplateArgs
) { // def, possibly in a multiclass
3267 BadField
= AddValue(CurRec
, IdLoc
,
3268 RecordVal(DeclName
, IdLoc
, Type
,
3269 HasField
? RecordVal::FK_NonconcreteOK
3270 : RecordVal::FK_Normal
));
3271 } else if (CurRec
) { // class template argument
3272 DeclName
= QualifyName(*CurRec
, DeclName
);
3274 AddValue(CurRec
, IdLoc
,
3275 RecordVal(DeclName
, IdLoc
, Type
, RecordVal::FK_TemplateArg
));
3276 } else { // multiclass template argument
3277 assert(CurMultiClass
&& "invalid context for template argument");
3278 DeclName
= QualifyName(CurMultiClass
, DeclName
);
3280 AddValue(CurRec
, IdLoc
,
3281 RecordVal(DeclName
, IdLoc
, Type
, RecordVal::FK_TemplateArg
));
3286 // If a value is present, parse it and set new field's value.
3287 if (consume(tgtok::equal
)) {
3288 SMLoc ValLoc
= Lex
.getLoc();
3289 Init
*Val
= ParseValue(CurRec
, Type
);
3291 SetValue(CurRec
, ValLoc
, DeclName
, std::nullopt
, Val
,
3292 /*AllowSelfAssignment=*/false, /*OverrideDefLoc=*/false)) {
3293 // Return the name, even if an error is thrown. This is so that we can
3294 // continue to make some progress, even without the value having been
3303 /// ParseForeachDeclaration - Read a foreach declaration, returning
3304 /// the name of the declared object or a NULL Init on error. Return
3305 /// the name of the parsed initializer list through ForeachListName.
3307 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
3308 /// ForeachDeclaration ::= ID '=' RangePiece
3309 /// ForeachDeclaration ::= ID '=' Value
3311 VarInit
*TGParser::ParseForeachDeclaration(Init
*&ForeachListValue
) {
3312 if (Lex
.getCode() != tgtok::Id
) {
3313 TokError("Expected identifier in foreach declaration");
3317 Init
*DeclName
= StringInit::get(Records
, Lex
.getCurStrVal());
3320 // If a value is present, parse it.
3321 if (!consume(tgtok::equal
)) {
3322 TokError("Expected '=' in foreach declaration");
3326 RecTy
*IterType
= nullptr;
3327 SmallVector
<unsigned, 16> Ranges
;
3329 switch (Lex
.getCode()) {
3330 case tgtok::l_brace
: { // '{' RangeList '}'
3331 Lex
.Lex(); // eat the '{'
3332 ParseRangeList(Ranges
);
3333 if (!consume(tgtok::r_brace
)) {
3334 TokError("expected '}' at end of bit range list");
3341 SMLoc ValueLoc
= Lex
.getLoc();
3342 Init
*I
= ParseValue(nullptr);
3346 TypedInit
*TI
= dyn_cast
<TypedInit
>(I
);
3347 if (TI
&& isa
<ListRecTy
>(TI
->getType())) {
3348 ForeachListValue
= I
;
3349 IterType
= cast
<ListRecTy
>(TI
->getType())->getElementType();
3354 if (ParseRangePiece(Ranges
, TI
))
3359 Error(ValueLoc
, "expected a list, got '" + I
->getAsString() + "'");
3360 if (CurMultiClass
) {
3361 PrintNote({}, "references to multiclass template arguments cannot be "
3362 "resolved at this time");
3369 if (!Ranges
.empty()) {
3370 assert(!IterType
&& "Type already initialized?");
3371 IterType
= IntRecTy::get(Records
);
3372 std::vector
<Init
*> Values
;
3373 for (unsigned R
: Ranges
)
3374 Values
.push_back(IntInit::get(Records
, R
));
3375 ForeachListValue
= ListInit::get(Values
, IterType
);
3381 return VarInit::get(DeclName
, IterType
);
3384 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
3385 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
3386 /// template args for a class. If null, these are the template args for a
3389 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
3391 bool TGParser::ParseTemplateArgList(Record
*CurRec
) {
3392 assert(Lex
.getCode() == tgtok::less
&& "Not a template arg list!");
3393 Lex
.Lex(); // eat the '<'
3395 Record
*TheRecToAddTo
= CurRec
? CurRec
: &CurMultiClass
->Rec
;
3397 // Read the first declaration.
3398 Init
*TemplArg
= ParseDeclaration(CurRec
, true/*templateargs*/);
3402 TheRecToAddTo
->addTemplateArg(TemplArg
);
3404 while (consume(tgtok::comma
)) {
3405 // Read the following declarations.
3406 SMLoc Loc
= Lex
.getLoc();
3407 TemplArg
= ParseDeclaration(CurRec
, true/*templateargs*/);
3411 if (TheRecToAddTo
->isTemplateArg(TemplArg
))
3412 return Error(Loc
, "template argument with the same name has already been "
3415 TheRecToAddTo
->addTemplateArg(TemplArg
);
3418 if (!consume(tgtok::greater
))
3419 return TokError("expected '>' at end of template argument list");
3423 /// ParseBodyItem - Parse a single item within the body of a def or class.
3425 /// BodyItem ::= Declaration ';'
3426 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
3427 /// BodyItem ::= Defvar
3428 /// BodyItem ::= Dump
3429 /// BodyItem ::= Assert
3431 bool TGParser::ParseBodyItem(Record
*CurRec
) {
3432 if (Lex
.getCode() == tgtok::Assert
)
3433 return ParseAssert(nullptr, CurRec
);
3435 if (Lex
.getCode() == tgtok::Defvar
)
3436 return ParseDefvar(CurRec
);
3438 if (Lex
.getCode() == tgtok::Dump
)
3439 return ParseDump(nullptr, CurRec
);
3441 if (Lex
.getCode() != tgtok::Let
) {
3442 if (!ParseDeclaration(CurRec
, false))
3445 if (!consume(tgtok::semi
))
3446 return TokError("expected ';' after declaration");
3450 // LET ID OptionalRangeList '=' Value ';'
3451 if (Lex
.Lex() != tgtok::Id
)
3452 return TokError("expected field identifier after let");
3454 SMLoc IdLoc
= Lex
.getLoc();
3455 StringInit
*FieldName
= StringInit::get(Records
, Lex
.getCurStrVal());
3456 Lex
.Lex(); // eat the field name.
3458 SmallVector
<unsigned, 16> BitList
;
3459 if (ParseOptionalBitList(BitList
))
3461 std::reverse(BitList
.begin(), BitList
.end());
3463 if (!consume(tgtok::equal
))
3464 return TokError("expected '=' in let expression");
3466 RecordVal
*Field
= CurRec
->getValue(FieldName
);
3468 return TokError("Value '" + FieldName
->getValue() + "' unknown!");
3470 RecTy
*Type
= Field
->getType();
3471 if (!BitList
.empty() && isa
<BitsRecTy
>(Type
)) {
3472 // When assigning to a subset of a 'bits' object, expect the RHS to have
3473 // the type of that subset instead of the type of the whole object.
3474 Type
= BitsRecTy::get(Records
, BitList
.size());
3477 Init
*Val
= ParseValue(CurRec
, Type
);
3478 if (!Val
) return true;
3480 if (!consume(tgtok::semi
))
3481 return TokError("expected ';' after let expression");
3483 return SetValue(CurRec
, IdLoc
, FieldName
, BitList
, Val
);
3486 /// ParseBody - Read the body of a class or def. Return true on error, false on
3490 /// Body ::= '{' BodyList '}'
3491 /// BodyList BodyItem*
3493 bool TGParser::ParseBody(Record
*CurRec
) {
3494 // If this is a null definition, just eat the semi and return.
3495 if (consume(tgtok::semi
))
3498 if (!consume(tgtok::l_brace
))
3499 return TokError("Expected '{' to start body or ';' for declaration only");
3501 while (Lex
.getCode() != tgtok::r_brace
)
3502 if (ParseBodyItem(CurRec
))
3508 // If we have a semicolon, print a gentle error.
3509 SMLoc SemiLoc
= Lex
.getLoc();
3510 if (consume(tgtok::semi
)) {
3511 PrintError(SemiLoc
, "A class or def body should not end with a semicolon");
3512 PrintNote("Semicolon ignored; remove to eliminate this error");
3518 /// Apply the current let bindings to \a CurRec.
3519 /// \returns true on error, false otherwise.
3520 bool TGParser::ApplyLetStack(Record
*CurRec
) {
3521 for (SmallVectorImpl
<LetRecord
> &LetInfo
: LetStack
)
3522 for (LetRecord
&LR
: LetInfo
)
3523 if (SetValue(CurRec
, LR
.Loc
, LR
.Name
, LR
.Bits
, LR
.Value
))
3528 /// Apply the current let bindings to the RecordsEntry.
3529 bool TGParser::ApplyLetStack(RecordsEntry
&Entry
) {
3531 return ApplyLetStack(Entry
.Rec
.get());
3533 // Let bindings are not applied to assertions.
3534 if (Entry
.Assertion
)
3537 // Let bindings are not applied to dumps.
3541 for (auto &E
: Entry
.Loop
->Entries
) {
3542 if (ApplyLetStack(E
))
3549 /// ParseObjectBody - Parse the body of a def or class. This consists of an
3550 /// optional ClassList followed by a Body. CurRec is the current def or class
3551 /// that is being parsed.
3553 /// ObjectBody ::= BaseClassList Body
3554 /// BaseClassList ::= /*empty*/
3555 /// BaseClassList ::= ':' BaseClassListNE
3556 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
3558 bool TGParser::ParseObjectBody(Record
*CurRec
) {
3559 // An object body introduces a new scope for local variables.
3560 TGVarScope
*ObjectScope
= PushScope(CurRec
);
3561 // If there is a baseclass list, read it.
3562 if (consume(tgtok::colon
)) {
3564 // Read all of the subclasses.
3565 SubClassReference SubClass
= ParseSubClassReference(CurRec
, false);
3568 if (!SubClass
.Rec
) return true;
3571 if (AddSubClass(CurRec
, SubClass
))
3574 if (!consume(tgtok::comma
))
3576 SubClass
= ParseSubClassReference(CurRec
, false);
3580 if (ApplyLetStack(CurRec
))
3583 bool Result
= ParseBody(CurRec
);
3584 PopScope(ObjectScope
);
3588 /// ParseDef - Parse and return a top level or multiclass record definition.
3589 /// Return false if okay, true if error.
3591 /// DefInst ::= DEF ObjectName ObjectBody
3593 bool TGParser::ParseDef(MultiClass
*CurMultiClass
) {
3594 SMLoc DefLoc
= Lex
.getLoc();
3595 assert(Lex
.getCode() == tgtok::Def
&& "Unknown tok");
3596 Lex
.Lex(); // Eat the 'def' token.
3598 // If the name of the def is an Id token, use that for the location.
3599 // Otherwise, the name is more complex and we use the location of the 'def'
3601 SMLoc NameLoc
= Lex
.getCode() == tgtok::Id
? Lex
.getLoc() : DefLoc
;
3603 // Parse ObjectName and make a record for it.
3604 std::unique_ptr
<Record
> CurRec
;
3605 Init
*Name
= ParseObjectName(CurMultiClass
);
3609 if (isa
<UnsetInit
>(Name
)) {
3610 CurRec
= std::make_unique
<Record
>(Records
.getNewAnonymousName(), DefLoc
,
3611 Records
, Record::RK_AnonymousDef
);
3613 CurRec
= std::make_unique
<Record
>(Name
, NameLoc
, Records
);
3616 if (ParseObjectBody(CurRec
.get()))
3619 return addEntry(std::move(CurRec
));
3622 /// ParseDefset - Parse a defset statement.
3624 /// Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
3626 bool TGParser::ParseDefset() {
3627 assert(Lex
.getCode() == tgtok::Defset
);
3628 Lex
.Lex(); // Eat the 'defset' token
3630 DefsetRecord Defset
;
3631 Defset
.Loc
= Lex
.getLoc();
3632 RecTy
*Type
= ParseType();
3635 if (!isa
<ListRecTy
>(Type
))
3636 return Error(Defset
.Loc
, "expected list type");
3637 Defset
.EltTy
= cast
<ListRecTy
>(Type
)->getElementType();
3639 if (Lex
.getCode() != tgtok::Id
)
3640 return TokError("expected identifier");
3641 StringInit
*DeclName
= StringInit::get(Records
, Lex
.getCurStrVal());
3642 if (Records
.getGlobal(DeclName
->getValue()))
3643 return TokError("def or global variable of this name already exists");
3645 if (Lex
.Lex() != tgtok::equal
) // Eat the identifier
3646 return TokError("expected '='");
3647 if (Lex
.Lex() != tgtok::l_brace
) // Eat the '='
3648 return TokError("expected '{'");
3649 SMLoc BraceLoc
= Lex
.getLoc();
3650 Lex
.Lex(); // Eat the '{'
3652 Defsets
.push_back(&Defset
);
3653 bool Err
= ParseObjectList(nullptr);
3658 if (!consume(tgtok::r_brace
)) {
3659 TokError("expected '}' at end of defset");
3660 return Error(BraceLoc
, "to match this '{'");
3663 Records
.addExtraGlobal(DeclName
->getValue(),
3664 ListInit::get(Defset
.Elements
, Defset
.EltTy
));
3668 /// ParseDefvar - Parse a defvar statement.
3670 /// Defvar ::= DEFVAR Id '=' Value ';'
3672 bool TGParser::ParseDefvar(Record
*CurRec
) {
3673 assert(Lex
.getCode() == tgtok::Defvar
);
3674 Lex
.Lex(); // Eat the 'defvar' token
3676 if (Lex
.getCode() != tgtok::Id
)
3677 return TokError("expected identifier");
3678 StringInit
*DeclName
= StringInit::get(Records
, Lex
.getCurStrVal());
3679 if (CurScope
->varAlreadyDefined(DeclName
->getValue()))
3680 return TokError("local variable of this name already exists");
3682 // The name should not be conflicted with existed field names.
3684 auto *V
= CurRec
->getValue(DeclName
->getValue());
3685 if (V
&& !V
->isTemplateArg())
3686 return TokError("field of this name already exists");
3689 // If this defvar is in the top level, the name should not be conflicted
3690 // with existed global names.
3691 if (CurScope
->isOutermost() && Records
.getGlobal(DeclName
->getValue()))
3692 return TokError("def or global variable of this name already exists");
3695 if (!consume(tgtok::equal
))
3696 return TokError("expected '='");
3698 Init
*Value
= ParseValue(CurRec
);
3702 if (!consume(tgtok::semi
))
3703 return TokError("expected ';'");
3705 if (!CurScope
->isOutermost())
3706 CurScope
->addVar(DeclName
->getValue(), Value
);
3708 Records
.addExtraGlobal(DeclName
->getValue(), Value
);
3713 /// ParseForeach - Parse a for statement. Return the record corresponding
3714 /// to it. This returns true on error.
3716 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
3717 /// Foreach ::= FOREACH Declaration IN Object
3719 bool TGParser::ParseForeach(MultiClass
*CurMultiClass
) {
3720 SMLoc Loc
= Lex
.getLoc();
3721 assert(Lex
.getCode() == tgtok::Foreach
&& "Unknown tok");
3722 Lex
.Lex(); // Eat the 'for' token.
3724 // Make a temporary object to record items associated with the for
3726 Init
*ListValue
= nullptr;
3727 VarInit
*IterName
= ParseForeachDeclaration(ListValue
);
3729 return TokError("expected declaration in for");
3731 if (!consume(tgtok::In
))
3732 return TokError("Unknown tok");
3734 // Create a loop object and remember it.
3735 auto TheLoop
= std::make_unique
<ForeachLoop
>(Loc
, IterName
, ListValue
);
3736 // A foreach loop introduces a new scope for local variables.
3737 TGVarScope
*ForeachScope
= PushScope(TheLoop
.get());
3738 Loops
.push_back(std::move(TheLoop
));
3740 if (Lex
.getCode() != tgtok::l_brace
) {
3741 // FOREACH Declaration IN Object
3742 if (ParseObject(CurMultiClass
))
3745 SMLoc BraceLoc
= Lex
.getLoc();
3746 // Otherwise, this is a group foreach.
3747 Lex
.Lex(); // eat the '{'.
3749 // Parse the object list.
3750 if (ParseObjectList(CurMultiClass
))
3753 if (!consume(tgtok::r_brace
)) {
3754 TokError("expected '}' at end of foreach command");
3755 return Error(BraceLoc
, "to match this '{'");
3759 PopScope(ForeachScope
);
3761 // Resolve the loop or store it for later resolution.
3762 std::unique_ptr
<ForeachLoop
> Loop
= std::move(Loops
.back());
3765 return addEntry(std::move(Loop
));
3768 /// ParseIf - Parse an if statement.
3770 /// If ::= IF Value THEN IfBody
3771 /// If ::= IF Value THEN IfBody ELSE IfBody
3773 bool TGParser::ParseIf(MultiClass
*CurMultiClass
) {
3774 SMLoc Loc
= Lex
.getLoc();
3775 assert(Lex
.getCode() == tgtok::If
&& "Unknown tok");
3776 Lex
.Lex(); // Eat the 'if' token.
3778 // Make a temporary object to record items associated with the for
3780 Init
*Condition
= ParseValue(nullptr);
3784 if (!consume(tgtok::Then
))
3785 return TokError("Unknown tok");
3787 // We have to be able to save if statements to execute later, and they have
3788 // to live on the same stack as foreach loops. The simplest implementation
3789 // technique is to convert each 'then' or 'else' clause *into* a foreach
3790 // loop, over a list of length 0 or 1 depending on the condition, and with no
3791 // iteration variable being assigned.
3793 ListInit
*EmptyList
= ListInit::get({}, BitRecTy::get(Records
));
3794 ListInit
*SingletonList
=
3795 ListInit::get({BitInit::get(Records
, true)}, BitRecTy::get(Records
));
3796 RecTy
*BitListTy
= ListRecTy::get(BitRecTy::get(Records
));
3798 // The foreach containing the then-clause selects SingletonList if
3799 // the condition is true.
3800 Init
*ThenClauseList
=
3801 TernOpInit::get(TernOpInit::IF
, Condition
, SingletonList
, EmptyList
,
3804 Loops
.push_back(std::make_unique
<ForeachLoop
>(Loc
, nullptr, ThenClauseList
));
3806 if (ParseIfBody(CurMultiClass
, "then"))
3809 std::unique_ptr
<ForeachLoop
> Loop
= std::move(Loops
.back());
3812 if (addEntry(std::move(Loop
)))
3815 // Now look for an optional else clause. The if-else syntax has the usual
3816 // dangling-else ambiguity, and by greedily matching an else here if we can,
3817 // we implement the usual resolution of pairing with the innermost unmatched
3819 if (consume(tgtok::ElseKW
)) {
3820 // The foreach containing the else-clause uses the same pair of lists as
3821 // above, but this time, selects SingletonList if the condition is *false*.
3822 Init
*ElseClauseList
=
3823 TernOpInit::get(TernOpInit::IF
, Condition
, EmptyList
, SingletonList
,
3827 std::make_unique
<ForeachLoop
>(Loc
, nullptr, ElseClauseList
));
3829 if (ParseIfBody(CurMultiClass
, "else"))
3832 Loop
= std::move(Loops
.back());
3835 if (addEntry(std::move(Loop
)))
3842 /// ParseIfBody - Parse the then-clause or else-clause of an if statement.
3844 /// IfBody ::= Object
3845 /// IfBody ::= '{' ObjectList '}'
3847 bool TGParser::ParseIfBody(MultiClass
*CurMultiClass
, StringRef Kind
) {
3848 // An if-statement introduces a new scope for local variables.
3849 TGVarScope
*BodyScope
= PushScope();
3851 if (Lex
.getCode() != tgtok::l_brace
) {
3853 if (ParseObject(CurMultiClass
))
3856 SMLoc BraceLoc
= Lex
.getLoc();
3858 Lex
.Lex(); // eat the '{'.
3860 // Parse the object list.
3861 if (ParseObjectList(CurMultiClass
))
3864 if (!consume(tgtok::r_brace
)) {
3865 TokError("expected '}' at end of '" + Kind
+ "' clause");
3866 return Error(BraceLoc
, "to match this '{'");
3870 PopScope(BodyScope
);
3874 /// ParseAssert - Parse an assert statement.
3876 /// Assert ::= ASSERT condition , message ;
3877 bool TGParser::ParseAssert(MultiClass
*CurMultiClass
, Record
*CurRec
) {
3878 assert(Lex
.getCode() == tgtok::Assert
&& "Unknown tok");
3879 Lex
.Lex(); // Eat the 'assert' token.
3881 SMLoc ConditionLoc
= Lex
.getLoc();
3882 Init
*Condition
= ParseValue(CurRec
);
3886 if (!consume(tgtok::comma
)) {
3887 TokError("expected ',' in assert statement");
3891 Init
*Message
= ParseValue(CurRec
);
3895 if (!consume(tgtok::semi
))
3896 return TokError("expected ';'");
3899 CurRec
->addAssertion(ConditionLoc
, Condition
, Message
);
3901 addEntry(std::make_unique
<Record::AssertionInfo
>(ConditionLoc
, Condition
,
3906 /// ParseClass - Parse a tblgen class definition.
3908 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
3910 bool TGParser::ParseClass() {
3911 assert(Lex
.getCode() == tgtok::Class
&& "Unexpected token!");
3914 if (Lex
.getCode() != tgtok::Id
)
3915 return TokError("expected class name after 'class' keyword");
3917 Record
*CurRec
= Records
.getClass(Lex
.getCurStrVal());
3919 // If the body was previously defined, this is an error.
3920 if (!CurRec
->getValues().empty() ||
3921 !CurRec
->getSuperClasses().empty() ||
3922 !CurRec
->getTemplateArgs().empty())
3923 return TokError("Class '" + CurRec
->getNameInitAsString() +
3924 "' already defined");
3926 CurRec
->updateClassLoc(Lex
.getLoc());
3928 // If this is the first reference to this class, create and add it.
3929 auto NewRec
= std::make_unique
<Record
>(Lex
.getCurStrVal(), Lex
.getLoc(),
3930 Records
, Record::RK_Class
);
3931 CurRec
= NewRec
.get();
3932 Records
.addClass(std::move(NewRec
));
3934 Lex
.Lex(); // eat the name.
3936 // A class definition introduces a new scope.
3937 TGVarScope
*ClassScope
= PushScope(CurRec
);
3938 // If there are template args, parse them.
3939 if (Lex
.getCode() == tgtok::less
)
3940 if (ParseTemplateArgList(CurRec
))
3943 if (ParseObjectBody(CurRec
))
3946 if (!NoWarnOnUnusedTemplateArgs
)
3947 CurRec
->checkUnusedTemplateArgs();
3949 PopScope(ClassScope
);
3953 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
3956 /// LetList ::= LetItem (',' LetItem)*
3957 /// LetItem ::= ID OptionalRangeList '=' Value
3959 void TGParser::ParseLetList(SmallVectorImpl
<LetRecord
> &Result
) {
3961 if (Lex
.getCode() != tgtok::Id
) {
3962 TokError("expected identifier in let definition");
3967 StringInit
*Name
= StringInit::get(Records
, Lex
.getCurStrVal());
3968 SMLoc NameLoc
= Lex
.getLoc();
3969 Lex
.Lex(); // Eat the identifier.
3971 // Check for an optional RangeList.
3972 SmallVector
<unsigned, 16> Bits
;
3973 if (ParseOptionalRangeList(Bits
)) {
3977 std::reverse(Bits
.begin(), Bits
.end());
3979 if (!consume(tgtok::equal
)) {
3980 TokError("expected '=' in let expression");
3985 Init
*Val
= ParseValue(nullptr);
3991 // Now that we have everything, add the record.
3992 Result
.emplace_back(Name
, Bits
, Val
, NameLoc
);
3993 } while (consume(tgtok::comma
));
3996 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
3997 /// different related productions. This works inside multiclasses too.
3999 /// Object ::= LET LetList IN '{' ObjectList '}'
4000 /// Object ::= LET LetList IN Object
4002 bool TGParser::ParseTopLevelLet(MultiClass
*CurMultiClass
) {
4003 assert(Lex
.getCode() == tgtok::Let
&& "Unexpected token");
4006 // Add this entry to the let stack.
4007 SmallVector
<LetRecord
, 8> LetInfo
;
4008 ParseLetList(LetInfo
);
4009 if (LetInfo
.empty()) return true;
4010 LetStack
.push_back(std::move(LetInfo
));
4012 if (!consume(tgtok::In
))
4013 return TokError("expected 'in' at end of top-level 'let'");
4015 // If this is a scalar let, just handle it now
4016 if (Lex
.getCode() != tgtok::l_brace
) {
4017 // LET LetList IN Object
4018 if (ParseObject(CurMultiClass
))
4020 } else { // Object ::= LETCommand '{' ObjectList '}'
4021 SMLoc BraceLoc
= Lex
.getLoc();
4022 // Otherwise, this is a group let.
4023 Lex
.Lex(); // eat the '{'.
4025 // A group let introduces a new scope for local variables.
4026 TGVarScope
*LetScope
= PushScope();
4028 // Parse the object list.
4029 if (ParseObjectList(CurMultiClass
))
4032 if (!consume(tgtok::r_brace
)) {
4033 TokError("expected '}' at end of top level let command");
4034 return Error(BraceLoc
, "to match this '{'");
4040 // Outside this let scope, this let block is not active.
4041 LetStack
.pop_back();
4045 /// ParseMultiClass - Parse a multiclass definition.
4047 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
4048 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
4049 /// MultiClassObject ::= Assert
4050 /// MultiClassObject ::= DefInst
4051 /// MultiClassObject ::= DefMInst
4052 /// MultiClassObject ::= Defvar
4053 /// MultiClassObject ::= Foreach
4054 /// MultiClassObject ::= If
4055 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
4056 /// MultiClassObject ::= LETCommand Object
4058 bool TGParser::ParseMultiClass() {
4059 assert(Lex
.getCode() == tgtok::MultiClass
&& "Unexpected token");
4060 Lex
.Lex(); // Eat the multiclass token.
4062 if (Lex
.getCode() != tgtok::Id
)
4063 return TokError("expected identifier after multiclass for name");
4064 std::string Name
= Lex
.getCurStrVal();
4067 MultiClasses
.insert(std::make_pair(Name
,
4068 std::make_unique
<MultiClass
>(Name
, Lex
.getLoc(),Records
)));
4071 return TokError("multiclass '" + Name
+ "' already defined");
4073 CurMultiClass
= Result
.first
->second
.get();
4074 Lex
.Lex(); // Eat the identifier.
4076 // A multiclass body introduces a new scope for local variables.
4077 TGVarScope
*MulticlassScope
= PushScope(CurMultiClass
);
4079 // If there are template args, parse them.
4080 if (Lex
.getCode() == tgtok::less
)
4081 if (ParseTemplateArgList(nullptr))
4084 bool inherits
= false;
4086 // If there are submulticlasses, parse them.
4087 if (consume(tgtok::colon
)) {
4090 // Read all of the submulticlasses.
4091 SubMultiClassReference SubMultiClass
=
4092 ParseSubMultiClassReference(CurMultiClass
);
4095 if (!SubMultiClass
.MC
) return true;
4098 if (AddSubMultiClass(CurMultiClass
, SubMultiClass
))
4101 if (!consume(tgtok::comma
))
4103 SubMultiClass
= ParseSubMultiClassReference(CurMultiClass
);
4107 if (Lex
.getCode() != tgtok::l_brace
) {
4109 return TokError("expected '{' in multiclass definition");
4110 if (!consume(tgtok::semi
))
4111 return TokError("expected ';' in multiclass definition");
4113 if (Lex
.Lex() == tgtok::r_brace
) // eat the '{'.
4114 return TokError("multiclass must contain at least one def");
4116 while (Lex
.getCode() != tgtok::r_brace
) {
4117 switch (Lex
.getCode()) {
4119 return TokError("expected 'assert', 'def', 'defm', 'defvar', 'dump', "
4120 "'foreach', 'if', or 'let' in multiclass body");
4127 case tgtok::Foreach
:
4130 if (ParseObject(CurMultiClass
))
4135 Lex
.Lex(); // eat the '}'.
4137 // If we have a semicolon, print a gentle error.
4138 SMLoc SemiLoc
= Lex
.getLoc();
4139 if (consume(tgtok::semi
)) {
4140 PrintError(SemiLoc
, "A multiclass body should not end with a semicolon");
4141 PrintNote("Semicolon ignored; remove to eliminate this error");
4145 if (!NoWarnOnUnusedTemplateArgs
)
4146 CurMultiClass
->Rec
.checkUnusedTemplateArgs();
4148 PopScope(MulticlassScope
);
4149 CurMultiClass
= nullptr;
4153 /// ParseDefm - Parse the instantiation of a multiclass.
4155 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
4157 bool TGParser::ParseDefm(MultiClass
*CurMultiClass
) {
4158 assert(Lex
.getCode() == tgtok::Defm
&& "Unexpected token!");
4159 Lex
.Lex(); // eat the defm
4161 Init
*DefmName
= ParseObjectName(CurMultiClass
);
4164 if (isa
<UnsetInit
>(DefmName
)) {
4165 DefmName
= Records
.getNewAnonymousName();
4167 DefmName
= BinOpInit::getStrConcat(
4168 VarInit::get(QualifiedNameOfImplicitName(CurMultiClass
),
4169 StringRecTy::get(Records
)),
4173 if (Lex
.getCode() != tgtok::colon
)
4174 return TokError("expected ':' after defm identifier");
4176 // Keep track of the new generated record definitions.
4177 std::vector
<RecordsEntry
> NewEntries
;
4179 // This record also inherits from a regular class (non-multiclass)?
4180 bool InheritFromClass
= false;
4185 SMLoc SubClassLoc
= Lex
.getLoc();
4186 SubClassReference Ref
= ParseSubClassReference(nullptr, true);
4189 if (!Ref
.Rec
) return true;
4191 // To instantiate a multiclass, we get the multiclass and then loop
4192 // through its template argument names. Substs contains a substitution
4193 // value for each argument, either the value specified or the default.
4194 // Then we can resolve the template arguments.
4195 MultiClass
*MC
= MultiClasses
[std::string(Ref
.Rec
->getName())].get();
4196 assert(MC
&& "Didn't lookup multiclass correctly?");
4199 if (resolveArgumentsOfMultiClass(Substs
, MC
, Ref
.TemplateArgs
, DefmName
,
4203 if (resolve(MC
->Entries
, Substs
, !CurMultiClass
&& Loops
.empty(),
4204 &NewEntries
, &SubClassLoc
))
4207 if (!consume(tgtok::comma
))
4210 if (Lex
.getCode() != tgtok::Id
)
4211 return TokError("expected identifier");
4213 SubClassLoc
= Lex
.getLoc();
4215 // A defm can inherit from regular classes (non-multiclasses) as
4216 // long as they come in the end of the inheritance list.
4217 InheritFromClass
= (Records
.getClass(Lex
.getCurStrVal()) != nullptr);
4219 if (InheritFromClass
)
4222 Ref
= ParseSubClassReference(nullptr, true);
4225 if (InheritFromClass
) {
4226 // Process all the classes to inherit as if they were part of a
4227 // regular 'def' and inherit all record values.
4228 SubClassReference SubClass
= ParseSubClassReference(nullptr, false);
4231 if (!SubClass
.Rec
) return true;
4233 // Get the expanded definition prototypes and teach them about
4234 // the record values the current class to inherit has
4235 for (auto &E
: NewEntries
) {
4237 if (AddSubClass(E
, SubClass
))
4241 if (!consume(tgtok::comma
))
4243 SubClass
= ParseSubClassReference(nullptr, false);
4247 for (auto &E
: NewEntries
) {
4248 if (ApplyLetStack(E
))
4251 addEntry(std::move(E
));
4254 if (!consume(tgtok::semi
))
4255 return TokError("expected ';' at end of defm");
4261 /// Object ::= ClassInst
4262 /// Object ::= DefInst
4263 /// Object ::= MultiClassInst
4264 /// Object ::= DefMInst
4265 /// Object ::= LETCommand '{' ObjectList '}'
4266 /// Object ::= LETCommand Object
4267 /// Object ::= Defset
4268 /// Object ::= Defvar
4269 /// Object ::= Assert
4271 bool TGParser::ParseObject(MultiClass
*MC
) {
4272 switch (Lex
.getCode()) {
4275 "Expected assert, class, def, defm, defset, dump, foreach, if, or let");
4276 case tgtok::Assert
: return ParseAssert(MC
);
4277 case tgtok::Def
: return ParseDef(MC
);
4278 case tgtok::Defm
: return ParseDefm(MC
);
4279 case tgtok::Defvar
: return ParseDefvar();
4281 return ParseDump(MC
);
4282 case tgtok::Foreach
: return ParseForeach(MC
);
4283 case tgtok::If
: return ParseIf(MC
);
4284 case tgtok::Let
: return ParseTopLevelLet(MC
);
4287 return TokError("defset is not allowed inside multiclass");
4288 return ParseDefset();
4291 return TokError("class is not allowed inside multiclass");
4293 return TokError("class is not allowed inside foreach loop");
4294 return ParseClass();
4295 case tgtok::MultiClass
:
4297 return TokError("multiclass is not allowed inside foreach loop");
4298 return ParseMultiClass();
4303 /// ObjectList :== Object*
4304 bool TGParser::ParseObjectList(MultiClass
*MC
) {
4305 while (tgtok::isObjectStart(Lex
.getCode())) {
4306 if (ParseObject(MC
))
4312 bool TGParser::ParseFile() {
4313 Lex
.Lex(); // Prime the lexer.
4314 TGVarScope
*GlobalScope
= PushScope();
4315 if (ParseObjectList())
4317 PopScope(GlobalScope
);
4319 // If we have unread input at the end of the file, report it.
4320 if (Lex
.getCode() == tgtok::Eof
)
4323 return TokError("Unexpected token at top level");
4326 // Check the types of the template argument values for a class
4327 // inheritance, multiclass invocation, or anonymous class invocation.
4328 // If necessary, replace an argument with a cast to the required type.
4329 // The argument count has already been checked.
4330 bool TGParser::CheckTemplateArgValues(
4331 SmallVectorImpl
<llvm::ArgumentInit
*> &Values
, SMLoc Loc
, Record
*ArgsRec
) {
4332 ArrayRef
<Init
*> TArgs
= ArgsRec
->getTemplateArgs();
4334 for (unsigned I
= 0, E
= Values
.size(); I
< E
; ++I
) {
4335 auto *Value
= Values
[I
];
4336 Init
*ArgName
= nullptr;
4337 if (Value
->isPositional())
4338 ArgName
= TArgs
[Value
->getIndex()];
4339 if (Value
->isNamed())
4340 ArgName
= Value
->getName();
4342 RecordVal
*Arg
= ArgsRec
->getValue(ArgName
);
4343 RecTy
*ArgType
= Arg
->getType();
4345 if (TypedInit
*ArgValue
= dyn_cast
<TypedInit
>(Value
->getValue())) {
4346 auto *CastValue
= ArgValue
->getCastTo(ArgType
);
4348 assert((!isa
<TypedInit
>(CastValue
) ||
4349 cast
<TypedInit
>(CastValue
)->getType()->typeIsA(ArgType
)) &&
4350 "result of template arg value cast has wrong type");
4351 Values
[I
] = Value
->cloneWithValue(CastValue
);
4353 PrintFatalError(Loc
, "Value specified for template argument '" +
4354 Arg
->getNameInitAsString() + "' is of type " +
4355 ArgValue
->getType()->getAsString() +
4356 "; expected type " + ArgType
->getAsString() +
4357 ": " + ArgValue
->getAsString());
4365 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4366 LLVM_DUMP_METHOD
void RecordsEntry::dump() const {
4373 LLVM_DUMP_METHOD
void ForeachLoop::dump() const {
4374 errs() << "foreach " << IterVar
->getAsString() << " = "
4375 << ListValue
->getAsString() << " in {\n";
4377 for (const auto &E
: Entries
)
4383 LLVM_DUMP_METHOD
void MultiClass::dump() const {
4384 errs() << "Record:\n";
4387 errs() << "Defs:\n";
4388 for (const auto &E
: Entries
)
4393 bool TGParser::ParseDump(MultiClass
*CurMultiClass
, Record
*CurRec
) {
4394 // Location of the `dump` statement.
4395 SMLoc Loc
= Lex
.getLoc();
4396 assert(Lex
.getCode() == tgtok::Dump
&& "Unknown tok");
4397 Lex
.Lex(); // eat the operation
4399 Init
*Message
= ParseValue(CurRec
);
4403 // Allow to use dump directly on `defvar` and `def`, by wrapping
4404 // them with a `!repl`.
4405 if (isa
<DefInit
>(Message
))
4406 Message
= UnOpInit::get(UnOpInit::REPR
, Message
, StringRecTy::get(Records
))
4409 if (!consume(tgtok::semi
))
4410 return TokError("expected ';'");
4413 CurRec
->addDump(Loc
, Message
);
4415 addEntry(std::make_unique
<Record::DumpInfo
>(Loc
, Message
));