1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implement the Parser for TableGen.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/TableGen/Record.h"
24 //===----------------------------------------------------------------------===//
25 // Support Code for the Semantic Actions.
26 //===----------------------------------------------------------------------===//
29 struct SubClassReference {
32 std::vector<Init*> TemplateArgs;
33 SubClassReference() : Rec(nullptr) {}
35 bool isInvalid() const { return Rec == nullptr; }
38 struct SubMultiClassReference {
41 std::vector<Init*> TemplateArgs;
42 SubMultiClassReference() : MC(nullptr) {}
44 bool isInvalid() const { return MC == nullptr; }
48 void SubMultiClassReference::dump() const {
49 errs() << "Multiclass:\n";
53 errs() << "Template args:\n";
54 for (Init *TA : TemplateArgs) {
59 } // end namespace llvm
61 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
63 CurRec = &CurMultiClass->Rec;
65 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
66 // The value already exists in the class, treat this as a set.
67 if (ERV->setValue(RV.getValue()))
68 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
69 RV.getType()->getAsString() + "' is incompatible with " +
70 "previous definition of type '" +
71 ERV->getType()->getAsString() + "'");
79 /// Return true on error, false on success.
80 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
81 const std::vector<unsigned> &BitList, Init *V) {
84 if (!CurRec) CurRec = &CurMultiClass->Rec;
86 RecordVal *RV = CurRec->getValue(ValName);
88 return Error(Loc, "Value '" + ValName->getAsUnquotedString()
91 // Do not allow assignments like 'X = X'. This will just cause infinite loops
92 // in the resolution machinery.
94 if (VarInit *VI = dyn_cast<VarInit>(V))
95 if (VI->getNameInit() == ValName)
98 // If we are assigning to a subset of the bits in the value... then we must be
99 // assigning to a field of BitsRecTy, which must have a BitsInit
102 if (!BitList.empty()) {
103 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
105 return Error(Loc, "Value '" + ValName->getAsUnquotedString()
106 + "' is not a bits type");
108 // Convert the incoming value to a bits type of the appropriate size...
109 Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size()));
111 return Error(Loc, "Initializer is not compatible with bit range");
114 // We should have a BitsInit type now.
115 BitsInit *BInit = cast<BitsInit>(BI);
117 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
119 // Loop over bits, assigning values as appropriate.
120 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
121 unsigned Bit = BitList[i];
123 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
124 ValName->getAsUnquotedString() + "' more than once");
125 NewBits[Bit] = BInit->getBit(i);
128 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
130 NewBits[i] = CurVal->getBit(i);
132 V = BitsInit::get(NewBits);
135 if (RV->setValue(V)) {
136 std::string InitType = "";
137 if (BitsInit *BI = dyn_cast<BitsInit>(V)) {
138 InitType = (Twine("' of type bit initializer with length ") +
139 Twine(BI->getNumBits())).str();
141 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of type '"
142 + RV->getType()->getAsString() +
143 "' is incompatible with initializer '" + V->getAsString()
150 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
151 /// args as SubClass's template arguments.
152 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
153 Record *SC = SubClass.Rec;
154 // Add all of the values in the subclass into the current class.
155 const std::vector<RecordVal> &Vals = SC->getValues();
156 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
157 if (AddValue(CurRec, SubClass.RefRange.Start, Vals[i]))
160 const std::vector<Init *> &TArgs = SC->getTemplateArgs();
162 // Ensure that an appropriate number of template arguments are specified.
163 if (TArgs.size() < SubClass.TemplateArgs.size())
164 return Error(SubClass.RefRange.Start,
165 "More template args specified than expected");
167 // Loop over all of the template arguments, setting them to the specified
168 // value or leaving them as the default if necessary.
169 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
170 if (i < SubClass.TemplateArgs.size()) {
171 // If a value is specified for this template arg, set it now.
172 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
173 std::vector<unsigned>(), SubClass.TemplateArgs[i]))
177 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
180 CurRec->removeValue(TArgs[i]);
182 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
183 return Error(SubClass.RefRange.Start,
184 "Value not specified for template argument #"
185 + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
186 + ") of subclass '" + SC->getNameInitAsString() + "'!");
190 // Since everything went well, we can now set the "superclass" list for the
192 const std::vector<Record*> &SCs = SC->getSuperClasses();
193 ArrayRef<SMRange> SCRanges = SC->getSuperClassRanges();
194 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
195 if (CurRec->isSubClassOf(SCs[i]))
196 return Error(SubClass.RefRange.Start,
197 "Already subclass of '" + SCs[i]->getName() + "'!\n");
198 CurRec->addSuperClass(SCs[i], SCRanges[i]);
201 if (CurRec->isSubClassOf(SC))
202 return Error(SubClass.RefRange.Start,
203 "Already subclass of '" + SC->getName() + "'!\n");
204 CurRec->addSuperClass(SC, SubClass.RefRange);
208 /// AddSubMultiClass - Add SubMultiClass as a subclass to
209 /// CurMC, resolving its template args as SubMultiClass's
210 /// template arguments.
211 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
212 SubMultiClassReference &SubMultiClass) {
213 MultiClass *SMC = SubMultiClass.MC;
214 Record *CurRec = &CurMC->Rec;
216 // Add all of the values in the subclass into the current class.
217 for (const auto &SMCVal : SMC->Rec.getValues())
218 if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVal))
221 unsigned newDefStart = CurMC->DefPrototypes.size();
223 // Add all of the defs in the subclass into the current multiclass.
224 for (const std::unique_ptr<Record> &R : SMC->DefPrototypes) {
225 // Clone the def and add it to the current multiclass
226 auto NewDef = make_unique<Record>(*R);
228 // Add all of the values in the superclass into the current def.
229 for (const auto &MCVal : CurRec->getValues())
230 if (AddValue(NewDef.get(), SubMultiClass.RefRange.Start, MCVal))
233 CurMC->DefPrototypes.push_back(std::move(NewDef));
236 const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
238 // Ensure that an appropriate number of template arguments are
240 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
241 return Error(SubMultiClass.RefRange.Start,
242 "More template args specified than expected");
244 // Loop over all of the template arguments, setting them to the specified
245 // value or leaving them as the default if necessary.
246 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
247 if (i < SubMultiClass.TemplateArgs.size()) {
248 // If a value is specified for this template arg, set it in the
250 if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i],
251 std::vector<unsigned>(),
252 SubMultiClass.TemplateArgs[i]))
256 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
259 CurRec->removeValue(SMCTArgs[i]);
261 // If a value is specified for this template arg, set it in the
263 for (const auto &Def :
264 makeArrayRef(CurMC->DefPrototypes).slice(newDefStart)) {
265 if (SetValue(Def.get(), SubMultiClass.RefRange.Start, SMCTArgs[i],
266 std::vector<unsigned>(),
267 SubMultiClass.TemplateArgs[i]))
271 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
274 Def->removeValue(SMCTArgs[i]);
276 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
277 return Error(SubMultiClass.RefRange.Start,
278 "Value not specified for template argument #"
279 + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
280 + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
287 /// ProcessForeachDefs - Given a record, apply all of the variable
288 /// values in all surrounding foreach loops, creating new records for
289 /// each combination of values.
290 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
294 // We want to instantiate a new copy of CurRec for each combination
295 // of nested loop iterator values. We don't want top instantiate
296 // any copies until we have values for each loop iterator.
298 return ProcessForeachDefs(CurRec, Loc, IterVals);
301 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
302 /// apply each of the variable values in this loop and then process
304 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
305 // Recursively build a tuple of iterator values.
306 if (IterVals.size() != Loops.size()) {
307 assert(IterVals.size() < Loops.size());
308 ForeachLoop &CurLoop = Loops[IterVals.size()];
309 ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
311 Error(Loc, "Loop list is not a list");
315 // Process each value.
316 for (int64_t i = 0; i < List->getSize(); ++i) {
317 Init *ItemVal = List->resolveListElementReference(*CurRec, nullptr, i);
318 IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
319 if (ProcessForeachDefs(CurRec, Loc, IterVals))
326 // This is the bottom of the recursion. We have all of the iterator values
327 // for this point in the iteration space. Instantiate a new record to
328 // reflect this combination of values.
329 auto IterRec = make_unique<Record>(*CurRec);
331 // Set the iterator values now.
332 for (unsigned i = 0, e = IterVals.size(); i != e; ++i) {
333 VarInit *IterVar = IterVals[i].IterVar;
334 TypedInit *IVal = dyn_cast<TypedInit>(IterVals[i].IterValue);
336 return Error(Loc, "foreach iterator value is untyped");
338 IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
340 if (SetValue(IterRec.get(), Loc, IterVar->getName(),
341 std::vector<unsigned>(), IVal))
342 return Error(Loc, "when instantiating this def");
345 IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
348 IterRec->removeValue(IterVar->getName());
351 if (Records.getDef(IterRec->getNameInitAsString())) {
352 // If this record is anonymous, it's no problem, just generate a new name
353 if (!IterRec->isAnonymous())
354 return Error(Loc, "def already exists: " +IterRec->getNameInitAsString());
356 IterRec->setName(GetNewAnonymousName());
359 Record *IterRecSave = IterRec.get(); // Keep a copy before release.
360 Records.addDef(std::move(IterRec));
361 IterRecSave->resolveReferences();
365 //===----------------------------------------------------------------------===//
367 //===----------------------------------------------------------------------===//
369 /// isObjectStart - Return true if this is a valid first token for an Object.
370 static bool isObjectStart(tgtok::TokKind K) {
371 return K == tgtok::Class || K == tgtok::Def ||
372 K == tgtok::Defm || K == tgtok::Let ||
373 K == tgtok::MultiClass || K == tgtok::Foreach;
376 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
378 std::string TGParser::GetNewAnonymousName() {
379 return "anonymous_" + utostr(AnonCounter++);
382 /// ParseObjectName - If an object name is specified, return it. Otherwise,
384 /// ObjectName ::= Value [ '#' Value ]*
385 /// ObjectName ::= /*empty*/
387 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
388 switch (Lex.getCode()) {
392 // These are all of the tokens that can begin an object body.
393 // Some of these can also begin values but we disallow those cases
394 // because they are unlikely to be useful.
400 Record *CurRec = nullptr;
402 CurRec = &CurMultiClass->Rec;
404 RecTy *Type = nullptr;
406 const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
408 TokError("Record name is not typed!");
411 Type = CurRecName->getType();
414 return ParseValue(CurRec, Type, ParseNameMode);
417 /// ParseClassID - Parse and resolve a reference to a class name. This returns
422 Record *TGParser::ParseClassID() {
423 if (Lex.getCode() != tgtok::Id) {
424 TokError("expected name for ClassID");
428 Record *Result = Records.getClass(Lex.getCurStrVal());
430 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
436 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
437 /// This returns null on error.
439 /// MultiClassID ::= ID
441 MultiClass *TGParser::ParseMultiClassID() {
442 if (Lex.getCode() != tgtok::Id) {
443 TokError("expected name for MultiClassID");
447 MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
449 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
455 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
456 /// subclass. This returns a SubClassRefTy with a null Record* on error.
458 /// SubClassRef ::= ClassID
459 /// SubClassRef ::= ClassID '<' ValueList '>'
461 SubClassReference TGParser::
462 ParseSubClassReference(Record *CurRec, bool isDefm) {
463 SubClassReference Result;
464 Result.RefRange.Start = Lex.getLoc();
467 if (MultiClass *MC = ParseMultiClassID())
468 Result.Rec = &MC->Rec;
470 Result.Rec = ParseClassID();
472 if (!Result.Rec) return Result;
474 // If there is no template arg list, we're done.
475 if (Lex.getCode() != tgtok::less) {
476 Result.RefRange.End = Lex.getLoc();
479 Lex.Lex(); // Eat the '<'
481 if (Lex.getCode() == tgtok::greater) {
482 TokError("subclass reference requires a non-empty list of template values");
483 Result.Rec = nullptr;
487 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
488 if (Result.TemplateArgs.empty()) {
489 Result.Rec = nullptr; // Error parsing value list.
493 if (Lex.getCode() != tgtok::greater) {
494 TokError("expected '>' in template value list");
495 Result.Rec = nullptr;
499 Result.RefRange.End = Lex.getLoc();
504 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
505 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
506 /// Record* on error.
508 /// SubMultiClassRef ::= MultiClassID
509 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
511 SubMultiClassReference TGParser::
512 ParseSubMultiClassReference(MultiClass *CurMC) {
513 SubMultiClassReference Result;
514 Result.RefRange.Start = Lex.getLoc();
516 Result.MC = ParseMultiClassID();
517 if (!Result.MC) return Result;
519 // If there is no template arg list, we're done.
520 if (Lex.getCode() != tgtok::less) {
521 Result.RefRange.End = Lex.getLoc();
524 Lex.Lex(); // Eat the '<'
526 if (Lex.getCode() == tgtok::greater) {
527 TokError("subclass reference requires a non-empty list of template values");
532 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
533 if (Result.TemplateArgs.empty()) {
534 Result.MC = nullptr; // Error parsing value list.
538 if (Lex.getCode() != tgtok::greater) {
539 TokError("expected '>' in template value list");
544 Result.RefRange.End = Lex.getLoc();
549 /// ParseRangePiece - Parse a bit/value range.
550 /// RangePiece ::= INTVAL
551 /// RangePiece ::= INTVAL '-' INTVAL
552 /// RangePiece ::= INTVAL INTVAL
553 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
554 if (Lex.getCode() != tgtok::IntVal) {
555 TokError("expected integer or bitrange");
558 int64_t Start = Lex.getCurIntVal();
562 return TokError("invalid range, cannot be negative");
564 switch (Lex.Lex()) { // eat first character.
566 Ranges.push_back(Start);
569 if (Lex.Lex() != tgtok::IntVal) {
570 TokError("expected integer value as end of range");
573 End = Lex.getCurIntVal();
576 End = -Lex.getCurIntVal();
580 return TokError("invalid range, cannot be negative");
585 for (; Start <= End; ++Start)
586 Ranges.push_back(Start);
588 for (; Start >= End; --Start)
589 Ranges.push_back(Start);
594 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
596 /// RangeList ::= RangePiece (',' RangePiece)*
598 std::vector<unsigned> TGParser::ParseRangeList() {
599 std::vector<unsigned> Result;
601 // Parse the first piece.
602 if (ParseRangePiece(Result))
603 return std::vector<unsigned>();
604 while (Lex.getCode() == tgtok::comma) {
605 Lex.Lex(); // Eat the comma.
607 // Parse the next range piece.
608 if (ParseRangePiece(Result))
609 return std::vector<unsigned>();
614 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
615 /// OptionalRangeList ::= '<' RangeList '>'
616 /// OptionalRangeList ::= /*empty*/
617 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
618 if (Lex.getCode() != tgtok::less)
621 SMLoc StartLoc = Lex.getLoc();
622 Lex.Lex(); // eat the '<'
624 // Parse the range list.
625 Ranges = ParseRangeList();
626 if (Ranges.empty()) return true;
628 if (Lex.getCode() != tgtok::greater) {
629 TokError("expected '>' at end of range list");
630 return Error(StartLoc, "to match this '<'");
632 Lex.Lex(); // eat the '>'.
636 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
637 /// OptionalBitList ::= '{' RangeList '}'
638 /// OptionalBitList ::= /*empty*/
639 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
640 if (Lex.getCode() != tgtok::l_brace)
643 SMLoc StartLoc = Lex.getLoc();
644 Lex.Lex(); // eat the '{'
646 // Parse the range list.
647 Ranges = ParseRangeList();
648 if (Ranges.empty()) return true;
650 if (Lex.getCode() != tgtok::r_brace) {
651 TokError("expected '}' at end of bit list");
652 return Error(StartLoc, "to match this '{'");
654 Lex.Lex(); // eat the '}'.
659 /// ParseType - Parse and return a tblgen type. This returns null on error.
661 /// Type ::= STRING // string type
662 /// Type ::= CODE // code type
663 /// Type ::= BIT // bit type
664 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
665 /// Type ::= INT // int type
666 /// Type ::= LIST '<' Type '>' // list<x> type
667 /// Type ::= DAG // dag type
668 /// Type ::= ClassID // Record Type
670 RecTy *TGParser::ParseType() {
671 switch (Lex.getCode()) {
672 default: TokError("Unknown token when expecting a type"); return nullptr;
673 case tgtok::String: Lex.Lex(); return StringRecTy::get();
674 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
675 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
676 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
677 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
679 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
682 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
683 TokError("expected '<' after bits type");
686 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
687 TokError("expected integer in bits<n> type");
690 uint64_t Val = Lex.getCurIntVal();
691 if (Lex.Lex() != tgtok::greater) { // Eat count.
692 TokError("expected '>' at end of bits<n> type");
695 Lex.Lex(); // Eat '>'
696 return BitsRecTy::get(Val);
699 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
700 TokError("expected '<' after list type");
703 Lex.Lex(); // Eat '<'
704 RecTy *SubType = ParseType();
705 if (!SubType) return nullptr;
707 if (Lex.getCode() != tgtok::greater) {
708 TokError("expected '>' at end of list<ty> type");
711 Lex.Lex(); // Eat '>'
712 return ListRecTy::get(SubType);
717 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
718 /// has already been read.
719 Init *TGParser::ParseIDValue(Record *CurRec,
720 const std::string &Name, SMLoc NameLoc,
723 if (const RecordVal *RV = CurRec->getValue(Name))
724 return VarInit::get(Name, RV->getType());
726 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
729 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
732 if (CurRec->isTemplateArg(TemplateArgName)) {
733 const RecordVal *RV = CurRec->getValue(TemplateArgName);
734 assert(RV && "Template arg doesn't exist??");
735 return VarInit::get(TemplateArgName, RV->getType());
740 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
743 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
744 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
745 assert(RV && "Template arg doesn't exist??");
746 return VarInit::get(MCName, RV->getType());
750 // If this is in a foreach loop, make sure it's not a loop iterator
751 for (const auto &L : Loops) {
752 VarInit *IterVar = dyn_cast<VarInit>(L.IterVar);
753 if (IterVar && IterVar->getName() == Name)
757 if (Mode == ParseNameMode)
758 return StringInit::get(Name);
760 if (Record *D = Records.getDef(Name))
761 return DefInit::get(D);
763 if (Mode == ParseValueMode) {
764 Error(NameLoc, "Variable not defined: '" + Name + "'");
768 return StringInit::get(Name);
771 /// ParseOperation - Parse an operator. This returns null on error.
773 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
775 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
776 switch (Lex.getCode()) {
778 TokError("unknown operation");
783 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
784 UnOpInit::UnaryOp Code;
785 RecTy *Type = nullptr;
787 switch (Lex.getCode()) {
788 default: llvm_unreachable("Unhandled code!");
790 Lex.Lex(); // eat the operation
791 Code = UnOpInit::CAST;
793 Type = ParseOperatorType();
796 TokError("did not get type for unary operator");
802 Lex.Lex(); // eat the operation
803 Code = UnOpInit::HEAD;
806 Lex.Lex(); // eat the operation
807 Code = UnOpInit::TAIL;
810 Lex.Lex(); // eat the operation
811 Code = UnOpInit::EMPTY;
812 Type = IntRecTy::get();
815 if (Lex.getCode() != tgtok::l_paren) {
816 TokError("expected '(' after unary operator");
819 Lex.Lex(); // eat the '('
821 Init *LHS = ParseValue(CurRec);
822 if (!LHS) return nullptr;
824 if (Code == UnOpInit::HEAD
825 || Code == UnOpInit::TAIL
826 || Code == UnOpInit::EMPTY) {
827 ListInit *LHSl = dyn_cast<ListInit>(LHS);
828 StringInit *LHSs = dyn_cast<StringInit>(LHS);
829 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
830 if (!LHSl && !LHSs && !LHSt) {
831 TokError("expected list or string type argument in unary operator");
835 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
836 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
837 if (!LType && !SType) {
838 TokError("expected list or string type argument in unary operator");
843 if (Code == UnOpInit::HEAD
844 || Code == UnOpInit::TAIL) {
845 if (!LHSl && !LHSt) {
846 TokError("expected list type argument in unary operator");
850 if (LHSl && LHSl->getSize() == 0) {
851 TokError("empty list argument in unary operator");
855 Init *Item = LHSl->getElement(0);
856 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
858 TokError("untyped list element in unary operator");
861 if (Code == UnOpInit::HEAD) {
862 Type = Itemt->getType();
864 Type = ListRecTy::get(Itemt->getType());
867 assert(LHSt && "expected list type argument in unary operator");
868 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
870 TokError("expected list type argument in unary operator");
873 if (Code == UnOpInit::HEAD) {
874 Type = LType->getElementType();
882 if (Lex.getCode() != tgtok::r_paren) {
883 TokError("expected ')' in unary operator");
886 Lex.Lex(); // eat the ')'
887 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
897 case tgtok::XListConcat:
898 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
899 tgtok::TokKind OpTok = Lex.getCode();
900 SMLoc OpLoc = Lex.getLoc();
901 Lex.Lex(); // eat the operation
903 BinOpInit::BinaryOp Code;
904 RecTy *Type = nullptr;
907 default: llvm_unreachable("Unhandled code!");
908 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
909 case tgtok::XADD: Code = BinOpInit::ADD; Type = IntRecTy::get(); break;
910 case tgtok::XAND: Code = BinOpInit::AND; Type = IntRecTy::get(); break;
911 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
912 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
913 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
914 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
915 case tgtok::XListConcat:
916 Code = BinOpInit::LISTCONCAT;
917 // We don't know the list type until we parse the first argument
919 case tgtok::XStrConcat:
920 Code = BinOpInit::STRCONCAT;
921 Type = StringRecTy::get();
925 if (Lex.getCode() != tgtok::l_paren) {
926 TokError("expected '(' after binary operator");
929 Lex.Lex(); // eat the '('
931 SmallVector<Init*, 2> InitList;
933 InitList.push_back(ParseValue(CurRec));
934 if (!InitList.back()) return nullptr;
936 while (Lex.getCode() == tgtok::comma) {
937 Lex.Lex(); // eat the ','
939 InitList.push_back(ParseValue(CurRec));
940 if (!InitList.back()) return nullptr;
943 if (Lex.getCode() != tgtok::r_paren) {
944 TokError("expected ')' in operator");
947 Lex.Lex(); // eat the ')'
949 // If we are doing !listconcat, we should know the type by now
950 if (OpTok == tgtok::XListConcat) {
951 if (VarInit *Arg0 = dyn_cast<VarInit>(InitList[0]))
952 Type = Arg0->getType();
953 else if (ListInit *Arg0 = dyn_cast<ListInit>(InitList[0]))
954 Type = Arg0->getType();
957 Error(OpLoc, "expected a list");
962 // We allow multiple operands to associative operators like !strconcat as
963 // shorthand for nesting them.
964 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT) {
965 while (InitList.size() > 2) {
966 Init *RHS = InitList.pop_back_val();
967 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
968 ->Fold(CurRec, CurMultiClass);
969 InitList.back() = RHS;
973 if (InitList.size() == 2)
974 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
975 ->Fold(CurRec, CurMultiClass);
977 Error(OpLoc, "expected two operands to operator");
982 case tgtok::XForEach:
983 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
984 TernOpInit::TernaryOp Code;
985 RecTy *Type = nullptr;
987 tgtok::TokKind LexCode = Lex.getCode();
988 Lex.Lex(); // eat the operation
990 default: llvm_unreachable("Unhandled code!");
992 Code = TernOpInit::IF;
994 case tgtok::XForEach:
995 Code = TernOpInit::FOREACH;
998 Code = TernOpInit::SUBST;
1001 if (Lex.getCode() != tgtok::l_paren) {
1002 TokError("expected '(' after ternary operator");
1005 Lex.Lex(); // eat the '('
1007 Init *LHS = ParseValue(CurRec);
1008 if (!LHS) return nullptr;
1010 if (Lex.getCode() != tgtok::comma) {
1011 TokError("expected ',' in ternary operator");
1014 Lex.Lex(); // eat the ','
1016 Init *MHS = ParseValue(CurRec, ItemType);
1020 if (Lex.getCode() != tgtok::comma) {
1021 TokError("expected ',' in ternary operator");
1024 Lex.Lex(); // eat the ','
1026 Init *RHS = ParseValue(CurRec, ItemType);
1030 if (Lex.getCode() != tgtok::r_paren) {
1031 TokError("expected ')' in binary operator");
1034 Lex.Lex(); // eat the ')'
1037 default: llvm_unreachable("Unhandled code!");
1039 RecTy *MHSTy = nullptr;
1040 RecTy *RHSTy = nullptr;
1042 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1043 MHSTy = MHSt->getType();
1044 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1045 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1046 if (isa<BitInit>(MHS))
1047 MHSTy = BitRecTy::get();
1049 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1050 RHSTy = RHSt->getType();
1051 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1052 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1053 if (isa<BitInit>(RHS))
1054 RHSTy = BitRecTy::get();
1056 // For UnsetInit, it's typed from the other hand.
1057 if (isa<UnsetInit>(MHS))
1059 if (isa<UnsetInit>(RHS))
1062 if (!MHSTy || !RHSTy) {
1063 TokError("could not get type for !if");
1067 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1069 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1072 TokError("inconsistent types for !if");
1077 case tgtok::XForEach: {
1078 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1080 TokError("could not get type for !foreach");
1083 Type = MHSt->getType();
1086 case tgtok::XSubst: {
1087 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1089 TokError("could not get type for !subst");
1092 Type = RHSt->getType();
1096 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1102 /// ParseOperatorType - Parse a type for an operator. This returns
1105 /// OperatorType ::= '<' Type '>'
1107 RecTy *TGParser::ParseOperatorType() {
1108 RecTy *Type = nullptr;
1110 if (Lex.getCode() != tgtok::less) {
1111 TokError("expected type name for operator");
1114 Lex.Lex(); // eat the <
1119 TokError("expected type name for operator");
1123 if (Lex.getCode() != tgtok::greater) {
1124 TokError("expected type name for operator");
1127 Lex.Lex(); // eat the >
1133 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1135 /// SimpleValue ::= IDValue
1136 /// SimpleValue ::= INTVAL
1137 /// SimpleValue ::= STRVAL+
1138 /// SimpleValue ::= CODEFRAGMENT
1139 /// SimpleValue ::= '?'
1140 /// SimpleValue ::= '{' ValueList '}'
1141 /// SimpleValue ::= ID '<' ValueListNE '>'
1142 /// SimpleValue ::= '[' ValueList ']'
1143 /// SimpleValue ::= '(' IDValue DagArgList ')'
1144 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1145 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1146 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1147 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1148 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1149 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1150 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1152 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1155 switch (Lex.getCode()) {
1156 default: TokError("Unknown token when parsing a value"); break;
1158 // This is a leading paste operation. This is deprecated but
1159 // still exists in some .td files. Ignore it.
1160 Lex.Lex(); // Skip '#'.
1161 return ParseSimpleValue(CurRec, ItemType, Mode);
1162 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1163 case tgtok::BinaryIntVal: {
1164 auto BinaryVal = Lex.getCurBinaryIntVal();
1165 SmallVector<Init*, 16> Bits(BinaryVal.second);
1166 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
1167 Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
1168 R = BitsInit::get(Bits);
1172 case tgtok::StrVal: {
1173 std::string Val = Lex.getCurStrVal();
1176 // Handle multiple consecutive concatenated strings.
1177 while (Lex.getCode() == tgtok::StrVal) {
1178 Val += Lex.getCurStrVal();
1182 R = StringInit::get(Val);
1185 case tgtok::CodeFragment:
1186 R = StringInit::get(Lex.getCurStrVal());
1189 case tgtok::question:
1190 R = UnsetInit::get();
1194 SMLoc NameLoc = Lex.getLoc();
1195 std::string Name = Lex.getCurStrVal();
1196 if (Lex.Lex() != tgtok::less) // consume the Id.
1197 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1199 // Value ::= ID '<' ValueListNE '>'
1200 if (Lex.Lex() == tgtok::greater) {
1201 TokError("expected non-empty value list");
1205 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1206 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1208 Record *Class = Records.getClass(Name);
1210 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1214 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1215 if (ValueList.empty()) return nullptr;
1217 if (Lex.getCode() != tgtok::greater) {
1218 TokError("expected '>' at end of value list");
1221 Lex.Lex(); // eat the '>'
1222 SMLoc EndLoc = Lex.getLoc();
1224 // Create the new record, set it as CurRec temporarily.
1225 auto NewRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), NameLoc,
1226 Records, /*IsAnonymous=*/true);
1227 Record *NewRec = NewRecOwner.get(); // Keep a copy since we may release.
1228 SubClassReference SCRef;
1229 SCRef.RefRange = SMRange(NameLoc, EndLoc);
1231 SCRef.TemplateArgs = ValueList;
1232 // Add info about the subclass to NewRec.
1233 if (AddSubClass(NewRec, SCRef))
1236 if (!CurMultiClass) {
1237 NewRec->resolveReferences();
1238 Records.addDef(std::move(NewRecOwner));
1240 // This needs to get resolved once the multiclass template arguments are
1241 // known before any use.
1242 NewRec->setResolveFirst(true);
1243 // Otherwise, we're inside a multiclass, add it to the multiclass.
1244 CurMultiClass->DefPrototypes.push_back(std::move(NewRecOwner));
1246 // Copy the template arguments for the multiclass into the def.
1247 for (Init *TArg : CurMultiClass->Rec.getTemplateArgs()) {
1248 const RecordVal *RV = CurMultiClass->Rec.getValue(TArg);
1249 assert(RV && "Template arg doesn't exist?");
1250 NewRec->addValue(*RV);
1253 // We can't return the prototype def here, instead return:
1254 // !cast<ItemType>(!strconcat(NAME, AnonName)).
1255 const RecordVal *MCNameRV = CurMultiClass->Rec.getValue("NAME");
1256 assert(MCNameRV && "multiclass record must have a NAME");
1258 return UnOpInit::get(UnOpInit::CAST,
1259 BinOpInit::get(BinOpInit::STRCONCAT,
1260 VarInit::get(MCNameRV->getName(),
1261 MCNameRV->getType()),
1262 NewRec->getNameInit(),
1263 StringRecTy::get()),
1264 Class->getDefInit()->getType());
1267 // The result of the expression is a reference to the new record.
1268 return DefInit::get(NewRec);
1270 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1271 SMLoc BraceLoc = Lex.getLoc();
1272 Lex.Lex(); // eat the '{'
1273 std::vector<Init*> Vals;
1275 if (Lex.getCode() != tgtok::r_brace) {
1276 Vals = ParseValueList(CurRec);
1277 if (Vals.empty()) return nullptr;
1279 if (Lex.getCode() != tgtok::r_brace) {
1280 TokError("expected '}' at end of bit list value");
1283 Lex.Lex(); // eat the '}'
1285 SmallVector<Init *, 16> NewBits;
1287 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1288 // first. We'll first read everything in to a vector, then we can reverse
1289 // it to get the bits in the correct order for the BitsInit value.
1290 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1291 // FIXME: The following two loops would not be duplicated
1292 // if the API was a little more orthogonal.
1294 // bits<n> values are allowed to initialize n bits.
1295 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
1296 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
1297 NewBits.push_back(BI->getBit((e - i) - 1));
1300 // bits<n> can also come from variable initializers.
1301 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
1302 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
1303 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
1304 NewBits.push_back(VI->getBit((e - i) - 1));
1307 // Fallthrough to try convert this to a bit.
1309 // All other values must be convertible to just a single bit.
1310 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1312 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1313 ") is not convertable to a bit");
1316 NewBits.push_back(Bit);
1318 std::reverse(NewBits.begin(), NewBits.end());
1319 return BitsInit::get(NewBits);
1321 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1322 Lex.Lex(); // eat the '['
1323 std::vector<Init*> Vals;
1325 RecTy *DeducedEltTy = nullptr;
1326 ListRecTy *GivenListTy = nullptr;
1329 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1332 raw_string_ostream ss(s);
1333 ss << "Type mismatch for list, expected list type, got "
1334 << ItemType->getAsString();
1338 GivenListTy = ListType;
1341 if (Lex.getCode() != tgtok::r_square) {
1342 Vals = ParseValueList(CurRec, nullptr,
1343 GivenListTy ? GivenListTy->getElementType() : nullptr);
1344 if (Vals.empty()) return nullptr;
1346 if (Lex.getCode() != tgtok::r_square) {
1347 TokError("expected ']' at end of list value");
1350 Lex.Lex(); // eat the ']'
1352 RecTy *GivenEltTy = nullptr;
1353 if (Lex.getCode() == tgtok::less) {
1354 // Optional list element type
1355 Lex.Lex(); // eat the '<'
1357 GivenEltTy = ParseType();
1359 // Couldn't parse element type
1363 if (Lex.getCode() != tgtok::greater) {
1364 TokError("expected '>' at end of list element type");
1367 Lex.Lex(); // eat the '>'
1371 RecTy *EltTy = nullptr;
1372 for (Init *V : Vals) {
1373 TypedInit *TArg = dyn_cast<TypedInit>(V);
1375 TokError("Untyped list element");
1379 EltTy = resolveTypes(EltTy, TArg->getType());
1381 TokError("Incompatible types in list elements");
1385 EltTy = TArg->getType();
1391 // Verify consistency
1392 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1393 TokError("Incompatible types in list elements");
1402 TokError("No type for list");
1405 DeducedEltTy = GivenListTy->getElementType();
1407 // Make sure the deduced type is compatible with the given type
1409 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1410 TokError("Element type mismatch for list");
1414 DeducedEltTy = EltTy;
1417 return ListInit::get(Vals, DeducedEltTy);
1419 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1420 Lex.Lex(); // eat the '('
1421 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1422 TokError("expected identifier in dag init");
1426 Init *Operator = ParseValue(CurRec);
1427 if (!Operator) return nullptr;
1429 // If the operator name is present, parse it.
1430 std::string OperatorName;
1431 if (Lex.getCode() == tgtok::colon) {
1432 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1433 TokError("expected variable name in dag operator");
1436 OperatorName = Lex.getCurStrVal();
1437 Lex.Lex(); // eat the VarName.
1440 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1441 if (Lex.getCode() != tgtok::r_paren) {
1442 DagArgs = ParseDagArgList(CurRec);
1443 if (DagArgs.empty()) return nullptr;
1446 if (Lex.getCode() != tgtok::r_paren) {
1447 TokError("expected ')' in dag init");
1450 Lex.Lex(); // eat the ')'
1452 return DagInit::get(Operator, OperatorName, DagArgs);
1458 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1459 case tgtok::XConcat:
1466 case tgtok::XListConcat:
1467 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1469 case tgtok::XForEach:
1470 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1471 return ParseOperation(CurRec, ItemType);
1478 /// ParseValue - Parse a tblgen value. This returns null on error.
1480 /// Value ::= SimpleValue ValueSuffix*
1481 /// ValueSuffix ::= '{' BitList '}'
1482 /// ValueSuffix ::= '[' BitList ']'
1483 /// ValueSuffix ::= '.' ID
1485 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1486 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1487 if (!Result) return nullptr;
1489 // Parse the suffixes now if present.
1491 switch (Lex.getCode()) {
1492 default: return Result;
1493 case tgtok::l_brace: {
1494 if (Mode == ParseNameMode || Mode == ParseForeachMode)
1495 // This is the beginning of the object body.
1498 SMLoc CurlyLoc = Lex.getLoc();
1499 Lex.Lex(); // eat the '{'
1500 std::vector<unsigned> Ranges = ParseRangeList();
1501 if (Ranges.empty()) return nullptr;
1503 // Reverse the bitlist.
1504 std::reverse(Ranges.begin(), Ranges.end());
1505 Result = Result->convertInitializerBitRange(Ranges);
1507 Error(CurlyLoc, "Invalid bit range for value");
1512 if (Lex.getCode() != tgtok::r_brace) {
1513 TokError("expected '}' at end of bit range list");
1519 case tgtok::l_square: {
1520 SMLoc SquareLoc = Lex.getLoc();
1521 Lex.Lex(); // eat the '['
1522 std::vector<unsigned> Ranges = ParseRangeList();
1523 if (Ranges.empty()) return nullptr;
1525 Result = Result->convertInitListSlice(Ranges);
1527 Error(SquareLoc, "Invalid range for list slice");
1532 if (Lex.getCode() != tgtok::r_square) {
1533 TokError("expected ']' at end of list slice");
1540 if (Lex.Lex() != tgtok::Id) { // eat the .
1541 TokError("expected field identifier after '.'");
1544 if (!Result->getFieldType(Lex.getCurStrVal())) {
1545 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1546 Result->getAsString() + "'");
1549 Result = FieldInit::get(Result, Lex.getCurStrVal());
1550 Lex.Lex(); // eat field name
1554 SMLoc PasteLoc = Lex.getLoc();
1556 // Create a !strconcat() operation, first casting each operand to
1557 // a string if necessary.
1559 TypedInit *LHS = dyn_cast<TypedInit>(Result);
1561 Error(PasteLoc, "LHS of paste is not typed!");
1565 if (LHS->getType() != StringRecTy::get()) {
1566 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1569 TypedInit *RHS = nullptr;
1571 Lex.Lex(); // Eat the '#'.
1572 switch (Lex.getCode()) {
1575 case tgtok::l_brace:
1576 // These are all of the tokens that can begin an object body.
1577 // Some of these can also begin values but we disallow those cases
1578 // because they are unlikely to be useful.
1580 // Trailing paste, concat with an empty string.
1581 RHS = StringInit::get("");
1585 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1586 RHS = dyn_cast<TypedInit>(RHSResult);
1588 Error(PasteLoc, "RHS of paste is not typed!");
1592 if (RHS->getType() != StringRecTy::get()) {
1593 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1599 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1600 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1606 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1608 /// DagArg ::= Value (':' VARNAME)?
1609 /// DagArg ::= VARNAME
1610 /// DagArgList ::= DagArg
1611 /// DagArgList ::= DagArgList ',' DagArg
1612 std::vector<std::pair<llvm::Init*, std::string> >
1613 TGParser::ParseDagArgList(Record *CurRec) {
1614 std::vector<std::pair<llvm::Init*, std::string> > Result;
1617 // DagArg ::= VARNAME
1618 if (Lex.getCode() == tgtok::VarName) {
1619 // A missing value is treated like '?'.
1620 Result.push_back(std::make_pair(UnsetInit::get(), Lex.getCurStrVal()));
1623 // DagArg ::= Value (':' VARNAME)?
1624 Init *Val = ParseValue(CurRec);
1626 return std::vector<std::pair<llvm::Init*, std::string> >();
1628 // If the variable name is present, add it.
1629 std::string VarName;
1630 if (Lex.getCode() == tgtok::colon) {
1631 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1632 TokError("expected variable name in dag literal");
1633 return std::vector<std::pair<llvm::Init*, std::string> >();
1635 VarName = Lex.getCurStrVal();
1636 Lex.Lex(); // eat the VarName.
1639 Result.push_back(std::make_pair(Val, VarName));
1641 if (Lex.getCode() != tgtok::comma) break;
1642 Lex.Lex(); // eat the ','
1649 /// ParseValueList - Parse a comma separated list of values, returning them as a
1650 /// vector. Note that this always expects to be able to parse at least one
1651 /// value. It returns an empty list if this is not possible.
1653 /// ValueList ::= Value (',' Value)
1655 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1657 std::vector<Init*> Result;
1658 RecTy *ItemType = EltTy;
1659 unsigned int ArgN = 0;
1660 if (ArgsRec && !EltTy) {
1661 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1662 if (TArgs.empty()) {
1663 TokError("template argument provided to non-template class");
1664 return std::vector<Init*>();
1666 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1668 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1671 assert(RV && "Template argument record not found??");
1672 ItemType = RV->getType();
1675 Result.push_back(ParseValue(CurRec, ItemType));
1676 if (!Result.back()) return std::vector<Init*>();
1678 while (Lex.getCode() == tgtok::comma) {
1679 Lex.Lex(); // Eat the comma
1681 if (ArgsRec && !EltTy) {
1682 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1683 if (ArgN >= TArgs.size()) {
1684 TokError("too many template arguments");
1685 return std::vector<Init*>();
1687 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1688 assert(RV && "Template argument record not found??");
1689 ItemType = RV->getType();
1692 Result.push_back(ParseValue(CurRec, ItemType));
1693 if (!Result.back()) return std::vector<Init*>();
1700 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1701 /// empty string on error. This can happen in a number of different context's,
1702 /// including within a def or in the template args for a def (which which case
1703 /// CurRec will be non-null) and within the template args for a multiclass (in
1704 /// which case CurRec will be null, but CurMultiClass will be set). This can
1705 /// also happen within a def that is within a multiclass, which will set both
1706 /// CurRec and CurMultiClass.
1708 /// Declaration ::= FIELD? Type ID ('=' Value)?
1710 Init *TGParser::ParseDeclaration(Record *CurRec,
1711 bool ParsingTemplateArgs) {
1712 // Read the field prefix if present.
1713 bool HasField = Lex.getCode() == tgtok::Field;
1714 if (HasField) Lex.Lex();
1716 RecTy *Type = ParseType();
1717 if (!Type) return nullptr;
1719 if (Lex.getCode() != tgtok::Id) {
1720 TokError("Expected identifier in declaration");
1724 SMLoc IdLoc = Lex.getLoc();
1725 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1728 if (ParsingTemplateArgs) {
1730 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1732 assert(CurMultiClass);
1735 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1740 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1743 // If a value is present, parse it.
1744 if (Lex.getCode() == tgtok::equal) {
1746 SMLoc ValLoc = Lex.getLoc();
1747 Init *Val = ParseValue(CurRec, Type);
1749 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1750 // Return the name, even if an error is thrown. This is so that we can
1751 // continue to make some progress, even without the value having been
1759 /// ParseForeachDeclaration - Read a foreach declaration, returning
1760 /// the name of the declared object or a NULL Init on error. Return
1761 /// the name of the parsed initializer list through ForeachListName.
1763 /// ForeachDeclaration ::= ID '=' '[' ValueList ']'
1764 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
1765 /// ForeachDeclaration ::= ID '=' RangePiece
1767 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1768 if (Lex.getCode() != tgtok::Id) {
1769 TokError("Expected identifier in foreach declaration");
1773 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1776 // If a value is present, parse it.
1777 if (Lex.getCode() != tgtok::equal) {
1778 TokError("Expected '=' in foreach declaration");
1781 Lex.Lex(); // Eat the '='
1783 RecTy *IterType = nullptr;
1784 std::vector<unsigned> Ranges;
1786 switch (Lex.getCode()) {
1787 default: TokError("Unknown token when expecting a range list"); return nullptr;
1788 case tgtok::l_square: { // '[' ValueList ']'
1789 Init *List = ParseSimpleValue(nullptr, nullptr, ParseForeachMode);
1790 ForeachListValue = dyn_cast<ListInit>(List);
1791 if (!ForeachListValue) {
1792 TokError("Expected a Value list");
1795 RecTy *ValueType = ForeachListValue->getType();
1796 ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1798 TokError("Value list is not of list type");
1801 IterType = ListType->getElementType();
1805 case tgtok::IntVal: { // RangePiece.
1806 if (ParseRangePiece(Ranges))
1811 case tgtok::l_brace: { // '{' RangeList '}'
1812 Lex.Lex(); // eat the '{'
1813 Ranges = ParseRangeList();
1814 if (Lex.getCode() != tgtok::r_brace) {
1815 TokError("expected '}' at end of bit range list");
1823 if (!Ranges.empty()) {
1824 assert(!IterType && "Type already initialized?");
1825 IterType = IntRecTy::get();
1826 std::vector<Init*> Values;
1827 for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
1828 Values.push_back(IntInit::get(Ranges[i]));
1829 ForeachListValue = ListInit::get(Values, IterType);
1835 return VarInit::get(DeclName, IterType);
1838 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1839 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1840 /// template args for a def, which may or may not be in a multiclass. If null,
1841 /// these are the template args for a multiclass.
1843 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1845 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1846 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1847 Lex.Lex(); // eat the '<'
1849 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1851 // Read the first declaration.
1852 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1856 TheRecToAddTo->addTemplateArg(TemplArg);
1858 while (Lex.getCode() == tgtok::comma) {
1859 Lex.Lex(); // eat the ','
1861 // Read the following declarations.
1862 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1865 TheRecToAddTo->addTemplateArg(TemplArg);
1868 if (Lex.getCode() != tgtok::greater)
1869 return TokError("expected '>' at end of template argument list");
1870 Lex.Lex(); // eat the '>'.
1875 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1877 /// BodyItem ::= Declaration ';'
1878 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1879 bool TGParser::ParseBodyItem(Record *CurRec) {
1880 if (Lex.getCode() != tgtok::Let) {
1881 if (!ParseDeclaration(CurRec, false))
1884 if (Lex.getCode() != tgtok::semi)
1885 return TokError("expected ';' after declaration");
1890 // LET ID OptionalRangeList '=' Value ';'
1891 if (Lex.Lex() != tgtok::Id)
1892 return TokError("expected field identifier after let");
1894 SMLoc IdLoc = Lex.getLoc();
1895 std::string FieldName = Lex.getCurStrVal();
1896 Lex.Lex(); // eat the field name.
1898 std::vector<unsigned> BitList;
1899 if (ParseOptionalBitList(BitList))
1901 std::reverse(BitList.begin(), BitList.end());
1903 if (Lex.getCode() != tgtok::equal)
1904 return TokError("expected '=' in let expression");
1905 Lex.Lex(); // eat the '='.
1907 RecordVal *Field = CurRec->getValue(FieldName);
1909 return TokError("Value '" + FieldName + "' unknown!");
1911 RecTy *Type = Field->getType();
1913 Init *Val = ParseValue(CurRec, Type);
1914 if (!Val) return true;
1916 if (Lex.getCode() != tgtok::semi)
1917 return TokError("expected ';' after let expression");
1920 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1923 /// ParseBody - Read the body of a class or def. Return true on error, false on
1927 /// Body ::= '{' BodyList '}'
1928 /// BodyList BodyItem*
1930 bool TGParser::ParseBody(Record *CurRec) {
1931 // If this is a null definition, just eat the semi and return.
1932 if (Lex.getCode() == tgtok::semi) {
1937 if (Lex.getCode() != tgtok::l_brace)
1938 return TokError("Expected ';' or '{' to start body");
1942 while (Lex.getCode() != tgtok::r_brace)
1943 if (ParseBodyItem(CurRec))
1951 /// \brief Apply the current let bindings to \a CurRec.
1952 /// \returns true on error, false otherwise.
1953 bool TGParser::ApplyLetStack(Record *CurRec) {
1954 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1955 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1956 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1957 LetStack[i][j].Bits, LetStack[i][j].Value))
1962 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1963 /// optional ClassList followed by a Body. CurRec is the current def or class
1964 /// that is being parsed.
1966 /// ObjectBody ::= BaseClassList Body
1967 /// BaseClassList ::= /*empty*/
1968 /// BaseClassList ::= ':' BaseClassListNE
1969 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1971 bool TGParser::ParseObjectBody(Record *CurRec) {
1972 // If there is a baseclass list, read it.
1973 if (Lex.getCode() == tgtok::colon) {
1976 // Read all of the subclasses.
1977 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1980 if (!SubClass.Rec) return true;
1983 if (AddSubClass(CurRec, SubClass))
1986 if (Lex.getCode() != tgtok::comma) break;
1987 Lex.Lex(); // eat ','.
1988 SubClass = ParseSubClassReference(CurRec, false);
1992 if (ApplyLetStack(CurRec))
1995 return ParseBody(CurRec);
1998 /// ParseDef - Parse and return a top level or multiclass def, return the record
1999 /// corresponding to it. This returns null on error.
2001 /// DefInst ::= DEF ObjectName ObjectBody
2003 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
2004 SMLoc DefLoc = Lex.getLoc();
2005 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
2006 Lex.Lex(); // Eat the 'def' token.
2008 // Parse ObjectName and make a record for it.
2009 std::unique_ptr<Record> CurRecOwner;
2010 Init *Name = ParseObjectName(CurMultiClass);
2012 CurRecOwner = make_unique<Record>(Name, DefLoc, Records);
2014 CurRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), DefLoc,
2015 Records, /*IsAnonymous=*/true);
2016 Record *CurRec = CurRecOwner.get(); // Keep a copy since we may release.
2018 if (!CurMultiClass && Loops.empty()) {
2019 // Top-level def definition.
2021 // Ensure redefinition doesn't happen.
2022 if (Records.getDef(CurRec->getNameInitAsString()))
2023 return Error(DefLoc, "def '" + CurRec->getNameInitAsString()+
2024 "' already defined");
2025 Records.addDef(std::move(CurRecOwner));
2027 if (ParseObjectBody(CurRec))
2029 } else if (CurMultiClass) {
2030 // Parse the body before adding this prototype to the DefPrototypes vector.
2031 // That way implicit definitions will be added to the DefPrototypes vector
2032 // before this object, instantiated prior to defs derived from this object,
2033 // and this available for indirect name resolution when defs derived from
2034 // this object are instantiated.
2035 if (ParseObjectBody(CurRec))
2038 // Otherwise, a def inside a multiclass, add it to the multiclass.
2039 for (const auto &Proto : CurMultiClass->DefPrototypes)
2040 if (Proto->getNameInit() == CurRec->getNameInit())
2041 return Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
2042 "' already defined in this multiclass!");
2043 CurMultiClass->DefPrototypes.push_back(std::move(CurRecOwner));
2044 } else if (ParseObjectBody(CurRec)) {
2048 if (!CurMultiClass) // Def's in multiclasses aren't really defs.
2049 // See Record::setName(). This resolve step will see any new name
2050 // for the def that might have been created when resolving
2051 // inheritance, values and arguments above.
2052 CurRec->resolveReferences();
2054 // If ObjectBody has template arguments, it's an error.
2055 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
2057 if (CurMultiClass) {
2058 // Copy the template arguments for the multiclass into the def.
2059 for (Init *TArg : CurMultiClass->Rec.getTemplateArgs()) {
2060 const RecordVal *RV = CurMultiClass->Rec.getValue(TArg);
2061 assert(RV && "Template arg doesn't exist?");
2062 CurRec->addValue(*RV);
2066 if (ProcessForeachDefs(CurRec, DefLoc)) {
2067 return Error(DefLoc, "Could not process loops for def" +
2068 CurRec->getNameInitAsString());
2074 /// ParseForeach - Parse a for statement. Return the record corresponding
2075 /// to it. This returns true on error.
2077 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2078 /// Foreach ::= FOREACH Declaration IN Object
2080 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2081 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2082 Lex.Lex(); // Eat the 'for' token.
2084 // Make a temporary object to record items associated with the for
2086 ListInit *ListValue = nullptr;
2087 VarInit *IterName = ParseForeachDeclaration(ListValue);
2089 return TokError("expected declaration in for");
2091 if (Lex.getCode() != tgtok::In)
2092 return TokError("Unknown tok");
2093 Lex.Lex(); // Eat the in
2095 // Create a loop object and remember it.
2096 Loops.push_back(ForeachLoop(IterName, ListValue));
2098 if (Lex.getCode() != tgtok::l_brace) {
2099 // FOREACH Declaration IN Object
2100 if (ParseObject(CurMultiClass))
2104 SMLoc BraceLoc = Lex.getLoc();
2105 // Otherwise, this is a group foreach.
2106 Lex.Lex(); // eat the '{'.
2108 // Parse the object list.
2109 if (ParseObjectList(CurMultiClass))
2112 if (Lex.getCode() != tgtok::r_brace) {
2113 TokError("expected '}' at end of foreach command");
2114 return Error(BraceLoc, "to match this '{'");
2116 Lex.Lex(); // Eat the }
2119 // We've processed everything in this loop.
2125 /// ParseClass - Parse a tblgen class definition.
2127 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2129 bool TGParser::ParseClass() {
2130 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2133 if (Lex.getCode() != tgtok::Id)
2134 return TokError("expected class name after 'class' keyword");
2136 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2138 // If the body was previously defined, this is an error.
2139 if (CurRec->getValues().size() > 1 || // Account for NAME.
2140 !CurRec->getSuperClasses().empty() ||
2141 !CurRec->getTemplateArgs().empty())
2142 return TokError("Class '" + CurRec->getNameInitAsString()
2143 + "' already defined");
2145 // If this is the first reference to this class, create and add it.
2147 llvm::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records);
2148 CurRec = NewRec.get();
2149 Records.addClass(std::move(NewRec));
2151 Lex.Lex(); // eat the name.
2153 // If there are template args, parse them.
2154 if (Lex.getCode() == tgtok::less)
2155 if (ParseTemplateArgList(CurRec))
2158 // Finally, parse the object body.
2159 return ParseObjectBody(CurRec);
2162 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2165 /// LetList ::= LetItem (',' LetItem)*
2166 /// LetItem ::= ID OptionalRangeList '=' Value
2168 std::vector<LetRecord> TGParser::ParseLetList() {
2169 std::vector<LetRecord> Result;
2172 if (Lex.getCode() != tgtok::Id) {
2173 TokError("expected identifier in let definition");
2174 return std::vector<LetRecord>();
2176 std::string Name = Lex.getCurStrVal();
2177 SMLoc NameLoc = Lex.getLoc();
2178 Lex.Lex(); // Eat the identifier.
2180 // Check for an optional RangeList.
2181 std::vector<unsigned> Bits;
2182 if (ParseOptionalRangeList(Bits))
2183 return std::vector<LetRecord>();
2184 std::reverse(Bits.begin(), Bits.end());
2186 if (Lex.getCode() != tgtok::equal) {
2187 TokError("expected '=' in let expression");
2188 return std::vector<LetRecord>();
2190 Lex.Lex(); // eat the '='.
2192 Init *Val = ParseValue(nullptr);
2193 if (!Val) return std::vector<LetRecord>();
2195 // Now that we have everything, add the record.
2196 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2198 if (Lex.getCode() != tgtok::comma)
2200 Lex.Lex(); // eat the comma.
2204 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2205 /// different related productions. This works inside multiclasses too.
2207 /// Object ::= LET LetList IN '{' ObjectList '}'
2208 /// Object ::= LET LetList IN Object
2210 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2211 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2214 // Add this entry to the let stack.
2215 std::vector<LetRecord> LetInfo = ParseLetList();
2216 if (LetInfo.empty()) return true;
2217 LetStack.push_back(std::move(LetInfo));
2219 if (Lex.getCode() != tgtok::In)
2220 return TokError("expected 'in' at end of top-level 'let'");
2223 // If this is a scalar let, just handle it now
2224 if (Lex.getCode() != tgtok::l_brace) {
2225 // LET LetList IN Object
2226 if (ParseObject(CurMultiClass))
2228 } else { // Object ::= LETCommand '{' ObjectList '}'
2229 SMLoc BraceLoc = Lex.getLoc();
2230 // Otherwise, this is a group let.
2231 Lex.Lex(); // eat the '{'.
2233 // Parse the object list.
2234 if (ParseObjectList(CurMultiClass))
2237 if (Lex.getCode() != tgtok::r_brace) {
2238 TokError("expected '}' at end of top level let command");
2239 return Error(BraceLoc, "to match this '{'");
2244 // Outside this let scope, this let block is not active.
2245 LetStack.pop_back();
2249 /// ParseMultiClass - Parse a multiclass definition.
2251 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2252 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2253 /// MultiClassObject ::= DefInst
2254 /// MultiClassObject ::= MultiClassInst
2255 /// MultiClassObject ::= DefMInst
2256 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
2257 /// MultiClassObject ::= LETCommand Object
2259 bool TGParser::ParseMultiClass() {
2260 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2261 Lex.Lex(); // Eat the multiclass token.
2263 if (Lex.getCode() != tgtok::Id)
2264 return TokError("expected identifier after multiclass for name");
2265 std::string Name = Lex.getCurStrVal();
2268 MultiClasses.insert(std::make_pair(Name,
2269 llvm::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
2272 return TokError("multiclass '" + Name + "' already defined");
2274 CurMultiClass = Result.first->second.get();
2275 Lex.Lex(); // Eat the identifier.
2277 // If there are template args, parse them.
2278 if (Lex.getCode() == tgtok::less)
2279 if (ParseTemplateArgList(nullptr))
2282 bool inherits = false;
2284 // If there are submulticlasses, parse them.
2285 if (Lex.getCode() == tgtok::colon) {
2290 // Read all of the submulticlasses.
2291 SubMultiClassReference SubMultiClass =
2292 ParseSubMultiClassReference(CurMultiClass);
2295 if (!SubMultiClass.MC) return true;
2298 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2301 if (Lex.getCode() != tgtok::comma) break;
2302 Lex.Lex(); // eat ','.
2303 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2307 if (Lex.getCode() != tgtok::l_brace) {
2309 return TokError("expected '{' in multiclass definition");
2310 if (Lex.getCode() != tgtok::semi)
2311 return TokError("expected ';' in multiclass definition");
2312 Lex.Lex(); // eat the ';'.
2314 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2315 return TokError("multiclass must contain at least one def");
2317 while (Lex.getCode() != tgtok::r_brace) {
2318 switch (Lex.getCode()) {
2320 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2324 case tgtok::Foreach:
2325 if (ParseObject(CurMultiClass))
2330 Lex.Lex(); // eat the '}'.
2333 CurMultiClass = nullptr;
2338 InstantiateMulticlassDef(MultiClass &MC,
2341 SMRange DefmPrefixRange) {
2342 // We need to preserve DefProto so it can be reused for later
2343 // instantiations, so create a new Record to inherit from it.
2345 // Add in the defm name. If the defm prefix is empty, give each
2346 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2347 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2350 bool IsAnonymous = false;
2352 DefmPrefix = StringInit::get(GetNewAnonymousName());
2356 Init *DefName = DefProto->getNameInit();
2358 StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2360 if (DefNameString) {
2361 // We have a fully expanded string so there are no operators to
2362 // resolve. We should concatenate the given prefix and name.
2364 BinOpInit::get(BinOpInit::STRCONCAT,
2365 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2366 StringRecTy::get())->Fold(DefProto, &MC),
2367 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2370 // Make a trail of SMLocs from the multiclass instantiations.
2371 SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
2372 Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2373 auto CurRec = make_unique<Record>(DefName, Locs, Records, IsAnonymous);
2375 SubClassReference Ref;
2376 Ref.RefRange = DefmPrefixRange;
2378 AddSubClass(CurRec.get(), Ref);
2380 // Set the value for NAME. We don't resolve references to it 'til later,
2381 // though, so that uses in nested multiclass names don't get
2383 if (SetValue(CurRec.get(), Ref.RefRange.Start, "NAME",
2384 std::vector<unsigned>(), DefmPrefix)) {
2385 Error(DefmPrefixRange.Start, "Could not resolve "
2386 + CurRec->getNameInitAsString() + ":NAME to '"
2387 + DefmPrefix->getAsUnquotedString() + "'");
2391 // If the DefNameString didn't resolve, we probably have a reference to
2392 // NAME and need to replace it. We need to do at least this much greedily,
2393 // otherwise nested multiclasses will end up with incorrect NAME expansions.
2394 if (!DefNameString) {
2395 RecordVal *DefNameRV = CurRec->getValue("NAME");
2396 CurRec->resolveReferencesTo(DefNameRV);
2399 if (!CurMultiClass) {
2400 // Now that we're at the top level, resolve all NAME references
2401 // in the resultant defs that weren't in the def names themselves.
2402 RecordVal *DefNameRV = CurRec->getValue("NAME");
2403 CurRec->resolveReferencesTo(DefNameRV);
2405 // Now that NAME references are resolved and we're at the top level of
2406 // any multiclass expansions, add the record to the RecordKeeper. If we are
2407 // currently in a multiclass, it means this defm appears inside a
2408 // multiclass and its name won't be fully resolvable until we see
2409 // the top-level defm. Therefore, we don't add this to the
2410 // RecordKeeper at this point. If we did we could get duplicate
2411 // defs as more than one probably refers to NAME or some other
2412 // common internal placeholder.
2414 // Ensure redefinition doesn't happen.
2415 if (Records.getDef(CurRec->getNameInitAsString())) {
2416 Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
2417 "' already defined, instantiating defm with subdef '" +
2418 DefProto->getNameInitAsString() + "'");
2422 Record *CurRecSave = CurRec.get(); // Keep a copy before we release.
2423 Records.addDef(std::move(CurRec));
2427 // FIXME This is bad but the ownership transfer to caller is pretty messy.
2428 // The unique_ptr in this function at least protects the exits above.
2429 return CurRec.release();
2432 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2434 SMLoc DefmPrefixLoc,
2436 const std::vector<Init *> &TArgs,
2437 std::vector<Init *> &TemplateVals,
2439 // Loop over all of the template arguments, setting them to the specified
2440 // value or leaving them as the default if necessary.
2441 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2442 // Check if a value is specified for this temp-arg.
2443 if (i < TemplateVals.size()) {
2445 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2450 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2454 CurRec->removeValue(TArgs[i]);
2456 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2457 return Error(SubClassLoc, "value not specified for template argument #"+
2458 utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2459 + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2466 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2469 SMLoc DefmPrefixLoc) {
2470 // If the mdef is inside a 'let' expression, add to each def.
2471 if (ApplyLetStack(CurRec))
2472 return Error(DefmPrefixLoc, "when instantiating this defm");
2474 // Don't create a top level definition for defm inside multiclasses,
2475 // instead, only update the prototypes and bind the template args
2476 // with the new created definition.
2479 for (const auto &Proto : CurMultiClass->DefPrototypes)
2480 if (Proto->getNameInit() == CurRec->getNameInit())
2481 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2482 "' already defined in this multiclass!");
2483 CurMultiClass->DefPrototypes.push_back(std::unique_ptr<Record>(CurRec));
2485 // Copy the template arguments for the multiclass into the new def.
2486 for (Init * TA : CurMultiClass->Rec.getTemplateArgs()) {
2487 const RecordVal *RV = CurMultiClass->Rec.getValue(TA);
2488 assert(RV && "Template arg doesn't exist?");
2489 CurRec->addValue(*RV);
2495 /// ParseDefm - Parse the instantiation of a multiclass.
2497 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2499 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2500 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2501 SMLoc DefmLoc = Lex.getLoc();
2502 Init *DefmPrefix = nullptr;
2504 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2505 DefmPrefix = ParseObjectName(CurMultiClass);
2508 SMLoc DefmPrefixEndLoc = Lex.getLoc();
2509 if (Lex.getCode() != tgtok::colon)
2510 return TokError("expected ':' after defm identifier");
2512 // Keep track of the new generated record definitions.
2513 std::vector<Record*> NewRecDefs;
2515 // This record also inherits from a regular class (non-multiclass)?
2516 bool InheritFromClass = false;
2521 SMLoc SubClassLoc = Lex.getLoc();
2522 SubClassReference Ref = ParseSubClassReference(nullptr, true);
2525 if (!Ref.Rec) return true;
2527 // To instantiate a multiclass, we need to first get the multiclass, then
2528 // instantiate each def contained in the multiclass with the SubClassRef
2529 // template parameters.
2530 MultiClass *MC = MultiClasses[Ref.Rec->getName()].get();
2531 assert(MC && "Didn't lookup multiclass correctly?");
2532 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2534 // Verify that the correct number of template arguments were specified.
2535 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2536 if (TArgs.size() < TemplateVals.size())
2537 return Error(SubClassLoc,
2538 "more template args specified than multiclass expects");
2540 // Loop over all the def's in the multiclass, instantiating each one.
2541 for (const std::unique_ptr<Record> &DefProto : MC->DefPrototypes) {
2542 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto.get(), DefmPrefix,
2548 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
2549 TArgs, TemplateVals, true/*Delete args*/))
2550 return Error(SubClassLoc, "could not instantiate def");
2552 if (ResolveMulticlassDef(*MC, CurRec, DefProto.get(), DefmLoc))
2553 return Error(SubClassLoc, "could not instantiate def");
2555 // Defs that can be used by other definitions should be fully resolved
2557 if (DefProto->isResolveFirst() && !CurMultiClass) {
2558 CurRec->resolveReferences();
2559 CurRec->setResolveFirst(false);
2561 NewRecDefs.push_back(CurRec);
2565 if (Lex.getCode() != tgtok::comma) break;
2566 Lex.Lex(); // eat ','.
2568 if (Lex.getCode() != tgtok::Id)
2569 return TokError("expected identifier");
2571 SubClassLoc = Lex.getLoc();
2573 // A defm can inherit from regular classes (non-multiclass) as
2574 // long as they come in the end of the inheritance list.
2575 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
2577 if (InheritFromClass)
2580 Ref = ParseSubClassReference(nullptr, true);
2583 if (InheritFromClass) {
2584 // Process all the classes to inherit as if they were part of a
2585 // regular 'def' and inherit all record values.
2586 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
2589 if (!SubClass.Rec) return true;
2591 // Get the expanded definition prototypes and teach them about
2592 // the record values the current class to inherit has
2593 for (Record *CurRec : NewRecDefs) {
2595 if (AddSubClass(CurRec, SubClass))
2598 if (ApplyLetStack(CurRec))
2602 if (Lex.getCode() != tgtok::comma) break;
2603 Lex.Lex(); // eat ','.
2604 SubClass = ParseSubClassReference(nullptr, false);
2609 for (Record *CurRec : NewRecDefs)
2610 // See Record::setName(). This resolve step will see any new
2611 // name for the def that might have been created when resolving
2612 // inheritance, values and arguments above.
2613 CurRec->resolveReferences();
2615 if (Lex.getCode() != tgtok::semi)
2616 return TokError("expected ';' at end of defm");
2623 /// Object ::= ClassInst
2624 /// Object ::= DefInst
2625 /// Object ::= MultiClassInst
2626 /// Object ::= DefMInst
2627 /// Object ::= LETCommand '{' ObjectList '}'
2628 /// Object ::= LETCommand Object
2629 bool TGParser::ParseObject(MultiClass *MC) {
2630 switch (Lex.getCode()) {
2632 return TokError("Expected class, def, defm, multiclass or let definition");
2633 case tgtok::Let: return ParseTopLevelLet(MC);
2634 case tgtok::Def: return ParseDef(MC);
2635 case tgtok::Foreach: return ParseForeach(MC);
2636 case tgtok::Defm: return ParseDefm(MC);
2637 case tgtok::Class: return ParseClass();
2638 case tgtok::MultiClass: return ParseMultiClass();
2643 /// ObjectList :== Object*
2644 bool TGParser::ParseObjectList(MultiClass *MC) {
2645 while (isObjectStart(Lex.getCode())) {
2646 if (ParseObject(MC))
2652 bool TGParser::ParseFile() {
2653 Lex.Lex(); // Prime the lexer.
2654 if (ParseObjectList()) return true;
2656 // If we have unread input at the end of the file, report it.
2657 if (Lex.getCode() == tgtok::Eof)
2660 return TokError("Unexpected input at top level");