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/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/TableGen/Record.h"
23 //===----------------------------------------------------------------------===//
24 // Support Code for the Semantic Actions.
25 //===----------------------------------------------------------------------===//
28 struct SubClassReference {
31 std::vector<Init*> TemplateArgs;
32 SubClassReference() : Rec(nullptr) {}
34 bool isInvalid() const { return Rec == nullptr; }
37 struct SubMultiClassReference {
40 std::vector<Init*> TemplateArgs;
41 SubMultiClassReference() : MC(nullptr) {}
43 bool isInvalid() const { return MC == nullptr; }
47 void SubMultiClassReference::dump() const {
48 errs() << "Multiclass:\n";
52 errs() << "Template args:\n";
53 for (std::vector<Init *>::const_iterator i = TemplateArgs.begin(),
54 iend = TemplateArgs.end();
61 } // end namespace llvm
63 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
65 CurRec = &CurMultiClass->Rec;
67 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
68 // The value already exists in the class, treat this as a set.
69 if (ERV->setValue(RV.getValue()))
70 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
71 RV.getType()->getAsString() + "' is incompatible with " +
72 "previous definition of type '" +
73 ERV->getType()->getAsString() + "'");
81 /// Return true on error, false on success.
82 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
83 const std::vector<unsigned> &BitList, Init *V) {
86 if (!CurRec) CurRec = &CurMultiClass->Rec;
88 RecordVal *RV = CurRec->getValue(ValName);
90 return Error(Loc, "Value '" + ValName->getAsUnquotedString()
93 // Do not allow assignments like 'X = X'. This will just cause infinite loops
94 // in the resolution machinery.
96 if (VarInit *VI = dyn_cast<VarInit>(V))
97 if (VI->getNameInit() == ValName)
100 // If we are assigning to a subset of the bits in the value... then we must be
101 // assigning to a field of BitsRecTy, which must have a BitsInit
104 if (!BitList.empty()) {
105 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
107 return Error(Loc, "Value '" + ValName->getAsUnquotedString()
108 + "' is not a bits type");
110 // Convert the incoming value to a bits type of the appropriate size...
111 Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size()));
113 return Error(Loc, "Initializer is not compatible with bit range");
116 // We should have a BitsInit type now.
117 BitsInit *BInit = dyn_cast<BitsInit>(BI);
118 assert(BInit != nullptr);
120 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
122 // Loop over bits, assigning values as appropriate.
123 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
124 unsigned Bit = BitList[i];
126 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
127 ValName->getAsUnquotedString() + "' more than once");
128 NewBits[Bit] = BInit->getBit(i);
131 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
133 NewBits[i] = CurVal->getBit(i);
135 V = BitsInit::get(NewBits);
138 if (RV->setValue(V)) {
139 std::string InitType = "";
140 if (BitsInit *BI = dyn_cast<BitsInit>(V)) {
141 InitType = (Twine("' of type bit initializer with length ") +
142 Twine(BI->getNumBits())).str();
144 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of type '"
145 + RV->getType()->getAsString() +
146 "' is incompatible with initializer '" + V->getAsString()
153 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
154 /// args as SubClass's template arguments.
155 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
156 Record *SC = SubClass.Rec;
157 // Add all of the values in the subclass into the current class.
158 const std::vector<RecordVal> &Vals = SC->getValues();
159 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
160 if (AddValue(CurRec, SubClass.RefRange.Start, Vals[i]))
163 const std::vector<Init *> &TArgs = SC->getTemplateArgs();
165 // Ensure that an appropriate number of template arguments are specified.
166 if (TArgs.size() < SubClass.TemplateArgs.size())
167 return Error(SubClass.RefRange.Start,
168 "More template args specified than expected");
170 // Loop over all of the template arguments, setting them to the specified
171 // value or leaving them as the default if necessary.
172 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
173 if (i < SubClass.TemplateArgs.size()) {
174 // If a value is specified for this template arg, set it now.
175 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
176 std::vector<unsigned>(), SubClass.TemplateArgs[i]))
180 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
183 CurRec->removeValue(TArgs[i]);
185 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
186 return Error(SubClass.RefRange.Start,
187 "Value not specified for template argument #"
188 + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
189 + ") of subclass '" + SC->getNameInitAsString() + "'!");
193 // Since everything went well, we can now set the "superclass" list for the
195 const std::vector<Record*> &SCs = SC->getSuperClasses();
196 ArrayRef<SMRange> SCRanges = SC->getSuperClassRanges();
197 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
198 if (CurRec->isSubClassOf(SCs[i]))
199 return Error(SubClass.RefRange.Start,
200 "Already subclass of '" + SCs[i]->getName() + "'!\n");
201 CurRec->addSuperClass(SCs[i], SCRanges[i]);
204 if (CurRec->isSubClassOf(SC))
205 return Error(SubClass.RefRange.Start,
206 "Already subclass of '" + SC->getName() + "'!\n");
207 CurRec->addSuperClass(SC, SubClass.RefRange);
211 /// AddSubMultiClass - Add SubMultiClass as a subclass to
212 /// CurMC, resolving its template args as SubMultiClass's
213 /// template arguments.
214 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
215 SubMultiClassReference &SubMultiClass) {
216 MultiClass *SMC = SubMultiClass.MC;
217 Record *CurRec = &CurMC->Rec;
219 const std::vector<RecordVal> &MCVals = CurRec->getValues();
221 // Add all of the values in the subclass into the current class.
222 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
223 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
224 if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVals[i]))
227 unsigned newDefStart = CurMC->DefPrototypes.size();
229 // Add all of the defs in the subclass into the current multiclass.
230 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
231 iend = SMC->DefPrototypes.end();
234 // Clone the def and add it to the current multiclass
235 auto NewDef = make_unique<Record>(**i);
237 // Add all of the values in the superclass into the current def.
238 for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
239 if (AddValue(NewDef.get(), SubMultiClass.RefRange.Start, MCVals[i]))
242 CurMC->DefPrototypes.push_back(std::move(NewDef));
245 const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
247 // Ensure that an appropriate number of template arguments are
249 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
250 return Error(SubMultiClass.RefRange.Start,
251 "More template args specified than expected");
253 // Loop over all of the template arguments, setting them to the specified
254 // value or leaving them as the default if necessary.
255 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
256 if (i < SubMultiClass.TemplateArgs.size()) {
257 // If a value is specified for this template arg, set it in the
259 if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i],
260 std::vector<unsigned>(),
261 SubMultiClass.TemplateArgs[i]))
265 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
268 CurRec->removeValue(SMCTArgs[i]);
270 // If a value is specified for this template arg, set it in the
272 for (const auto &Def :
273 makeArrayRef(CurMC->DefPrototypes).slice(newDefStart)) {
274 if (SetValue(Def.get(), SubMultiClass.RefRange.Start, SMCTArgs[i],
275 std::vector<unsigned>(),
276 SubMultiClass.TemplateArgs[i]))
280 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
283 Def->removeValue(SMCTArgs[i]);
285 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
286 return Error(SubMultiClass.RefRange.Start,
287 "Value not specified for template argument #"
288 + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
289 + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
296 /// ProcessForeachDefs - Given a record, apply all of the variable
297 /// values in all surrounding foreach loops, creating new records for
298 /// each combination of values.
299 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
303 // We want to instantiate a new copy of CurRec for each combination
304 // of nested loop iterator values. We don't want top instantiate
305 // any copies until we have values for each loop iterator.
307 return ProcessForeachDefs(CurRec, Loc, IterVals);
310 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
311 /// apply each of the variable values in this loop and then process
313 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
314 // Recursively build a tuple of iterator values.
315 if (IterVals.size() != Loops.size()) {
316 assert(IterVals.size() < Loops.size());
317 ForeachLoop &CurLoop = Loops[IterVals.size()];
318 ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
320 Error(Loc, "Loop list is not a list");
324 // Process each value.
325 for (int64_t i = 0; i < List->getSize(); ++i) {
326 Init *ItemVal = List->resolveListElementReference(*CurRec, nullptr, i);
327 IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
328 if (ProcessForeachDefs(CurRec, Loc, IterVals))
335 // This is the bottom of the recursion. We have all of the iterator values
336 // for this point in the iteration space. Instantiate a new record to
337 // reflect this combination of values.
338 auto IterRec = make_unique<Record>(*CurRec);
340 // Set the iterator values now.
341 for (unsigned i = 0, e = IterVals.size(); i != e; ++i) {
342 VarInit *IterVar = IterVals[i].IterVar;
343 TypedInit *IVal = dyn_cast<TypedInit>(IterVals[i].IterValue);
345 return Error(Loc, "foreach iterator value is untyped");
347 IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
349 if (SetValue(IterRec.get(), Loc, IterVar->getName(),
350 std::vector<unsigned>(), IVal))
351 return Error(Loc, "when instantiating this def");
354 IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
357 IterRec->removeValue(IterVar->getName());
360 if (Records.getDef(IterRec->getNameInitAsString())) {
361 // If this record is anonymous, it's no problem, just generate a new name
362 if (!IterRec->isAnonymous())
363 return Error(Loc, "def already exists: " +IterRec->getNameInitAsString());
365 IterRec->setName(GetNewAnonymousName());
368 Record *IterRecSave = IterRec.get(); // Keep a copy before release.
369 Records.addDef(std::move(IterRec));
370 IterRecSave->resolveReferences();
374 //===----------------------------------------------------------------------===//
376 //===----------------------------------------------------------------------===//
378 /// isObjectStart - Return true if this is a valid first token for an Object.
379 static bool isObjectStart(tgtok::TokKind K) {
380 return K == tgtok::Class || K == tgtok::Def ||
381 K == tgtok::Defm || K == tgtok::Let ||
382 K == tgtok::MultiClass || K == tgtok::Foreach;
385 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
387 std::string TGParser::GetNewAnonymousName() {
388 return "anonymous_" + utostr(AnonCounter++);
391 /// ParseObjectName - If an object name is specified, return it. Otherwise,
393 /// ObjectName ::= Value [ '#' Value ]*
394 /// ObjectName ::= /*empty*/
396 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
397 switch (Lex.getCode()) {
401 // These are all of the tokens that can begin an object body.
402 // Some of these can also begin values but we disallow those cases
403 // because they are unlikely to be useful.
409 Record *CurRec = nullptr;
411 CurRec = &CurMultiClass->Rec;
413 RecTy *Type = nullptr;
415 const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
417 TokError("Record name is not typed!");
420 Type = CurRecName->getType();
423 return ParseValue(CurRec, Type, ParseNameMode);
426 /// ParseClassID - Parse and resolve a reference to a class name. This returns
431 Record *TGParser::ParseClassID() {
432 if (Lex.getCode() != tgtok::Id) {
433 TokError("expected name for ClassID");
437 Record *Result = Records.getClass(Lex.getCurStrVal());
439 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
445 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
446 /// This returns null on error.
448 /// MultiClassID ::= ID
450 MultiClass *TGParser::ParseMultiClassID() {
451 if (Lex.getCode() != tgtok::Id) {
452 TokError("expected name for MultiClassID");
456 MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
458 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
464 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
465 /// subclass. This returns a SubClassRefTy with a null Record* on error.
467 /// SubClassRef ::= ClassID
468 /// SubClassRef ::= ClassID '<' ValueList '>'
470 SubClassReference TGParser::
471 ParseSubClassReference(Record *CurRec, bool isDefm) {
472 SubClassReference Result;
473 Result.RefRange.Start = Lex.getLoc();
476 if (MultiClass *MC = ParseMultiClassID())
477 Result.Rec = &MC->Rec;
479 Result.Rec = ParseClassID();
481 if (!Result.Rec) return Result;
483 // If there is no template arg list, we're done.
484 if (Lex.getCode() != tgtok::less) {
485 Result.RefRange.End = Lex.getLoc();
488 Lex.Lex(); // Eat the '<'
490 if (Lex.getCode() == tgtok::greater) {
491 TokError("subclass reference requires a non-empty list of template values");
492 Result.Rec = nullptr;
496 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
497 if (Result.TemplateArgs.empty()) {
498 Result.Rec = nullptr; // Error parsing value list.
502 if (Lex.getCode() != tgtok::greater) {
503 TokError("expected '>' in template value list");
504 Result.Rec = nullptr;
508 Result.RefRange.End = Lex.getLoc();
513 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
514 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
515 /// Record* on error.
517 /// SubMultiClassRef ::= MultiClassID
518 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
520 SubMultiClassReference TGParser::
521 ParseSubMultiClassReference(MultiClass *CurMC) {
522 SubMultiClassReference Result;
523 Result.RefRange.Start = Lex.getLoc();
525 Result.MC = ParseMultiClassID();
526 if (!Result.MC) return Result;
528 // If there is no template arg list, we're done.
529 if (Lex.getCode() != tgtok::less) {
530 Result.RefRange.End = Lex.getLoc();
533 Lex.Lex(); // Eat the '<'
535 if (Lex.getCode() == tgtok::greater) {
536 TokError("subclass reference requires a non-empty list of template values");
541 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
542 if (Result.TemplateArgs.empty()) {
543 Result.MC = nullptr; // Error parsing value list.
547 if (Lex.getCode() != tgtok::greater) {
548 TokError("expected '>' in template value list");
553 Result.RefRange.End = Lex.getLoc();
558 /// ParseRangePiece - Parse a bit/value range.
559 /// RangePiece ::= INTVAL
560 /// RangePiece ::= INTVAL '-' INTVAL
561 /// RangePiece ::= INTVAL INTVAL
562 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
563 if (Lex.getCode() != tgtok::IntVal) {
564 TokError("expected integer or bitrange");
567 int64_t Start = Lex.getCurIntVal();
571 return TokError("invalid range, cannot be negative");
573 switch (Lex.Lex()) { // eat first character.
575 Ranges.push_back(Start);
578 if (Lex.Lex() != tgtok::IntVal) {
579 TokError("expected integer value as end of range");
582 End = Lex.getCurIntVal();
585 End = -Lex.getCurIntVal();
589 return TokError("invalid range, cannot be negative");
594 for (; Start <= End; ++Start)
595 Ranges.push_back(Start);
597 for (; Start >= End; --Start)
598 Ranges.push_back(Start);
603 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
605 /// RangeList ::= RangePiece (',' RangePiece)*
607 std::vector<unsigned> TGParser::ParseRangeList() {
608 std::vector<unsigned> Result;
610 // Parse the first piece.
611 if (ParseRangePiece(Result))
612 return std::vector<unsigned>();
613 while (Lex.getCode() == tgtok::comma) {
614 Lex.Lex(); // Eat the comma.
616 // Parse the next range piece.
617 if (ParseRangePiece(Result))
618 return std::vector<unsigned>();
623 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
624 /// OptionalRangeList ::= '<' RangeList '>'
625 /// OptionalRangeList ::= /*empty*/
626 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
627 if (Lex.getCode() != tgtok::less)
630 SMLoc StartLoc = Lex.getLoc();
631 Lex.Lex(); // eat the '<'
633 // Parse the range list.
634 Ranges = ParseRangeList();
635 if (Ranges.empty()) return true;
637 if (Lex.getCode() != tgtok::greater) {
638 TokError("expected '>' at end of range list");
639 return Error(StartLoc, "to match this '<'");
641 Lex.Lex(); // eat the '>'.
645 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
646 /// OptionalBitList ::= '{' RangeList '}'
647 /// OptionalBitList ::= /*empty*/
648 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
649 if (Lex.getCode() != tgtok::l_brace)
652 SMLoc StartLoc = Lex.getLoc();
653 Lex.Lex(); // eat the '{'
655 // Parse the range list.
656 Ranges = ParseRangeList();
657 if (Ranges.empty()) return true;
659 if (Lex.getCode() != tgtok::r_brace) {
660 TokError("expected '}' at end of bit list");
661 return Error(StartLoc, "to match this '{'");
663 Lex.Lex(); // eat the '}'.
668 /// ParseType - Parse and return a tblgen type. This returns null on error.
670 /// Type ::= STRING // string type
671 /// Type ::= CODE // code type
672 /// Type ::= BIT // bit type
673 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
674 /// Type ::= INT // int type
675 /// Type ::= LIST '<' Type '>' // list<x> type
676 /// Type ::= DAG // dag type
677 /// Type ::= ClassID // Record Type
679 RecTy *TGParser::ParseType() {
680 switch (Lex.getCode()) {
681 default: TokError("Unknown token when expecting a type"); return nullptr;
682 case tgtok::String: Lex.Lex(); return StringRecTy::get();
683 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
684 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
685 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
686 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
688 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
691 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
692 TokError("expected '<' after bits type");
695 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
696 TokError("expected integer in bits<n> type");
699 uint64_t Val = Lex.getCurIntVal();
700 if (Lex.Lex() != tgtok::greater) { // Eat count.
701 TokError("expected '>' at end of bits<n> type");
704 Lex.Lex(); // Eat '>'
705 return BitsRecTy::get(Val);
708 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
709 TokError("expected '<' after list type");
712 Lex.Lex(); // Eat '<'
713 RecTy *SubType = ParseType();
714 if (!SubType) return nullptr;
716 if (Lex.getCode() != tgtok::greater) {
717 TokError("expected '>' at end of list<ty> type");
720 Lex.Lex(); // Eat '>'
721 return ListRecTy::get(SubType);
726 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
727 /// has already been read.
728 Init *TGParser::ParseIDValue(Record *CurRec,
729 const std::string &Name, SMLoc NameLoc,
732 if (const RecordVal *RV = CurRec->getValue(Name))
733 return VarInit::get(Name, RV->getType());
735 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
738 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
741 if (CurRec->isTemplateArg(TemplateArgName)) {
742 const RecordVal *RV = CurRec->getValue(TemplateArgName);
743 assert(RV && "Template arg doesn't exist??");
744 return VarInit::get(TemplateArgName, RV->getType());
749 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
752 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
753 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
754 assert(RV && "Template arg doesn't exist??");
755 return VarInit::get(MCName, RV->getType());
759 // If this is in a foreach loop, make sure it's not a loop iterator
760 for (LoopVector::iterator i = Loops.begin(), iend = Loops.end();
763 VarInit *IterVar = dyn_cast<VarInit>(i->IterVar);
764 if (IterVar && IterVar->getName() == Name)
768 if (Mode == ParseNameMode)
769 return StringInit::get(Name);
771 if (Record *D = Records.getDef(Name))
772 return DefInit::get(D);
774 if (Mode == ParseValueMode) {
775 Error(NameLoc, "Variable not defined: '" + Name + "'");
779 return StringInit::get(Name);
782 /// ParseOperation - Parse an operator. This returns null on error.
784 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
786 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
787 switch (Lex.getCode()) {
789 TokError("unknown operation");
794 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
795 UnOpInit::UnaryOp Code;
796 RecTy *Type = nullptr;
798 switch (Lex.getCode()) {
799 default: llvm_unreachable("Unhandled code!");
801 Lex.Lex(); // eat the operation
802 Code = UnOpInit::CAST;
804 Type = ParseOperatorType();
807 TokError("did not get type for unary operator");
813 Lex.Lex(); // eat the operation
814 Code = UnOpInit::HEAD;
817 Lex.Lex(); // eat the operation
818 Code = UnOpInit::TAIL;
821 Lex.Lex(); // eat the operation
822 Code = UnOpInit::EMPTY;
823 Type = IntRecTy::get();
826 if (Lex.getCode() != tgtok::l_paren) {
827 TokError("expected '(' after unary operator");
830 Lex.Lex(); // eat the '('
832 Init *LHS = ParseValue(CurRec);
833 if (!LHS) return nullptr;
835 if (Code == UnOpInit::HEAD
836 || Code == UnOpInit::TAIL
837 || Code == UnOpInit::EMPTY) {
838 ListInit *LHSl = dyn_cast<ListInit>(LHS);
839 StringInit *LHSs = dyn_cast<StringInit>(LHS);
840 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
841 if (!LHSl && !LHSs && !LHSt) {
842 TokError("expected list or string type argument in unary operator");
846 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
847 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
848 if (!LType && !SType) {
849 TokError("expected list or string type argument in unary operator");
854 if (Code == UnOpInit::HEAD
855 || Code == UnOpInit::TAIL) {
856 if (!LHSl && !LHSt) {
857 TokError("expected list type argument in unary operator");
861 if (LHSl && LHSl->getSize() == 0) {
862 TokError("empty list argument in unary operator");
866 Init *Item = LHSl->getElement(0);
867 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
869 TokError("untyped list element in unary operator");
872 if (Code == UnOpInit::HEAD) {
873 Type = Itemt->getType();
875 Type = ListRecTy::get(Itemt->getType());
878 assert(LHSt && "expected list type argument in unary operator");
879 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
881 TokError("expected list type argument in unary operator");
884 if (Code == UnOpInit::HEAD) {
885 Type = LType->getElementType();
893 if (Lex.getCode() != tgtok::r_paren) {
894 TokError("expected ')' in unary operator");
897 Lex.Lex(); // eat the ')'
898 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
908 case tgtok::XListConcat:
909 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
910 tgtok::TokKind OpTok = Lex.getCode();
911 SMLoc OpLoc = Lex.getLoc();
912 Lex.Lex(); // eat the operation
914 BinOpInit::BinaryOp Code;
915 RecTy *Type = nullptr;
918 default: llvm_unreachable("Unhandled code!");
919 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
920 case tgtok::XADD: Code = BinOpInit::ADD; Type = IntRecTy::get(); break;
921 case tgtok::XAND: Code = BinOpInit::AND; Type = IntRecTy::get(); break;
922 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
923 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
924 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
925 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
926 case tgtok::XListConcat:
927 Code = BinOpInit::LISTCONCAT;
928 // We don't know the list type until we parse the first argument
930 case tgtok::XStrConcat:
931 Code = BinOpInit::STRCONCAT;
932 Type = StringRecTy::get();
936 if (Lex.getCode() != tgtok::l_paren) {
937 TokError("expected '(' after binary operator");
940 Lex.Lex(); // eat the '('
942 SmallVector<Init*, 2> InitList;
944 InitList.push_back(ParseValue(CurRec));
945 if (!InitList.back()) return nullptr;
947 while (Lex.getCode() == tgtok::comma) {
948 Lex.Lex(); // eat the ','
950 InitList.push_back(ParseValue(CurRec));
951 if (!InitList.back()) return nullptr;
954 if (Lex.getCode() != tgtok::r_paren) {
955 TokError("expected ')' in operator");
958 Lex.Lex(); // eat the ')'
960 // If we are doing !listconcat, we should know the type by now
961 if (OpTok == tgtok::XListConcat) {
962 if (VarInit *Arg0 = dyn_cast<VarInit>(InitList[0]))
963 Type = Arg0->getType();
964 else if (ListInit *Arg0 = dyn_cast<ListInit>(InitList[0]))
965 Type = Arg0->getType();
968 Error(OpLoc, "expected a list");
973 // We allow multiple operands to associative operators like !strconcat as
974 // shorthand for nesting them.
975 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT) {
976 while (InitList.size() > 2) {
977 Init *RHS = InitList.pop_back_val();
978 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
979 ->Fold(CurRec, CurMultiClass);
980 InitList.back() = RHS;
984 if (InitList.size() == 2)
985 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
986 ->Fold(CurRec, CurMultiClass);
988 Error(OpLoc, "expected two operands to operator");
993 case tgtok::XForEach:
994 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
995 TernOpInit::TernaryOp Code;
996 RecTy *Type = nullptr;
998 tgtok::TokKind LexCode = Lex.getCode();
999 Lex.Lex(); // eat the operation
1001 default: llvm_unreachable("Unhandled code!");
1003 Code = TernOpInit::IF;
1005 case tgtok::XForEach:
1006 Code = TernOpInit::FOREACH;
1009 Code = TernOpInit::SUBST;
1012 if (Lex.getCode() != tgtok::l_paren) {
1013 TokError("expected '(' after ternary operator");
1016 Lex.Lex(); // eat the '('
1018 Init *LHS = ParseValue(CurRec);
1019 if (!LHS) return nullptr;
1021 if (Lex.getCode() != tgtok::comma) {
1022 TokError("expected ',' in ternary operator");
1025 Lex.Lex(); // eat the ','
1027 Init *MHS = ParseValue(CurRec, ItemType);
1031 if (Lex.getCode() != tgtok::comma) {
1032 TokError("expected ',' in ternary operator");
1035 Lex.Lex(); // eat the ','
1037 Init *RHS = ParseValue(CurRec, ItemType);
1041 if (Lex.getCode() != tgtok::r_paren) {
1042 TokError("expected ')' in binary operator");
1045 Lex.Lex(); // eat the ')'
1048 default: llvm_unreachable("Unhandled code!");
1050 RecTy *MHSTy = nullptr;
1051 RecTy *RHSTy = nullptr;
1053 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1054 MHSTy = MHSt->getType();
1055 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1056 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1057 if (isa<BitInit>(MHS))
1058 MHSTy = BitRecTy::get();
1060 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1061 RHSTy = RHSt->getType();
1062 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1063 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1064 if (isa<BitInit>(RHS))
1065 RHSTy = BitRecTy::get();
1067 // For UnsetInit, it's typed from the other hand.
1068 if (isa<UnsetInit>(MHS))
1070 if (isa<UnsetInit>(RHS))
1073 if (!MHSTy || !RHSTy) {
1074 TokError("could not get type for !if");
1078 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1080 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1083 TokError("inconsistent types for !if");
1088 case tgtok::XForEach: {
1089 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1091 TokError("could not get type for !foreach");
1094 Type = MHSt->getType();
1097 case tgtok::XSubst: {
1098 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1100 TokError("could not get type for !subst");
1103 Type = RHSt->getType();
1107 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1113 /// ParseOperatorType - Parse a type for an operator. This returns
1116 /// OperatorType ::= '<' Type '>'
1118 RecTy *TGParser::ParseOperatorType() {
1119 RecTy *Type = nullptr;
1121 if (Lex.getCode() != tgtok::less) {
1122 TokError("expected type name for operator");
1125 Lex.Lex(); // eat the <
1130 TokError("expected type name for operator");
1134 if (Lex.getCode() != tgtok::greater) {
1135 TokError("expected type name for operator");
1138 Lex.Lex(); // eat the >
1144 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1146 /// SimpleValue ::= IDValue
1147 /// SimpleValue ::= INTVAL
1148 /// SimpleValue ::= STRVAL+
1149 /// SimpleValue ::= CODEFRAGMENT
1150 /// SimpleValue ::= '?'
1151 /// SimpleValue ::= '{' ValueList '}'
1152 /// SimpleValue ::= ID '<' ValueListNE '>'
1153 /// SimpleValue ::= '[' ValueList ']'
1154 /// SimpleValue ::= '(' IDValue DagArgList ')'
1155 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1156 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1157 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1158 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1159 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1160 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1161 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1163 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1166 switch (Lex.getCode()) {
1167 default: TokError("Unknown token when parsing a value"); break;
1169 // This is a leading paste operation. This is deprecated but
1170 // still exists in some .td files. Ignore it.
1171 Lex.Lex(); // Skip '#'.
1172 return ParseSimpleValue(CurRec, ItemType, Mode);
1173 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1174 case tgtok::BinaryIntVal: {
1175 auto BinaryVal = Lex.getCurBinaryIntVal();
1176 SmallVector<Init*, 16> Bits(BinaryVal.second);
1177 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
1178 Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
1179 R = BitsInit::get(Bits);
1183 case tgtok::StrVal: {
1184 std::string Val = Lex.getCurStrVal();
1187 // Handle multiple consecutive concatenated strings.
1188 while (Lex.getCode() == tgtok::StrVal) {
1189 Val += Lex.getCurStrVal();
1193 R = StringInit::get(Val);
1196 case tgtok::CodeFragment:
1197 R = StringInit::get(Lex.getCurStrVal());
1200 case tgtok::question:
1201 R = UnsetInit::get();
1205 SMLoc NameLoc = Lex.getLoc();
1206 std::string Name = Lex.getCurStrVal();
1207 if (Lex.Lex() != tgtok::less) // consume the Id.
1208 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1210 // Value ::= ID '<' ValueListNE '>'
1211 if (Lex.Lex() == tgtok::greater) {
1212 TokError("expected non-empty value list");
1216 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1217 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1219 Record *Class = Records.getClass(Name);
1221 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1225 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1226 if (ValueList.empty()) return nullptr;
1228 if (Lex.getCode() != tgtok::greater) {
1229 TokError("expected '>' at end of value list");
1232 Lex.Lex(); // eat the '>'
1233 SMLoc EndLoc = Lex.getLoc();
1235 // Create the new record, set it as CurRec temporarily.
1236 auto NewRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), NameLoc,
1237 Records, /*IsAnonymous=*/true);
1238 Record *NewRec = NewRecOwner.get(); // Keep a copy since we may release.
1239 SubClassReference SCRef;
1240 SCRef.RefRange = SMRange(NameLoc, EndLoc);
1242 SCRef.TemplateArgs = ValueList;
1243 // Add info about the subclass to NewRec.
1244 if (AddSubClass(NewRec, SCRef))
1247 if (!CurMultiClass) {
1248 NewRec->resolveReferences();
1249 Records.addDef(std::move(NewRecOwner));
1251 // This needs to get resolved once the multiclass template arguments are
1252 // known before any use.
1253 NewRec->setResolveFirst(true);
1254 // Otherwise, we're inside a multiclass, add it to the multiclass.
1255 CurMultiClass->DefPrototypes.push_back(std::move(NewRecOwner));
1257 // Copy the template arguments for the multiclass into the def.
1258 const std::vector<Init *> &TArgs =
1259 CurMultiClass->Rec.getTemplateArgs();
1261 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1262 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1263 assert(RV && "Template arg doesn't exist?");
1264 NewRec->addValue(*RV);
1267 // We can't return the prototype def here, instead return:
1268 // !cast<ItemType>(!strconcat(NAME, AnonName)).
1269 const RecordVal *MCNameRV = CurMultiClass->Rec.getValue("NAME");
1270 assert(MCNameRV && "multiclass record must have a NAME");
1272 return UnOpInit::get(UnOpInit::CAST,
1273 BinOpInit::get(BinOpInit::STRCONCAT,
1274 VarInit::get(MCNameRV->getName(),
1275 MCNameRV->getType()),
1276 NewRec->getNameInit(),
1277 StringRecTy::get()),
1278 Class->getDefInit()->getType());
1281 // The result of the expression is a reference to the new record.
1282 return DefInit::get(NewRec);
1284 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1285 SMLoc BraceLoc = Lex.getLoc();
1286 Lex.Lex(); // eat the '{'
1287 std::vector<Init*> Vals;
1289 if (Lex.getCode() != tgtok::r_brace) {
1290 Vals = ParseValueList(CurRec);
1291 if (Vals.empty()) return nullptr;
1293 if (Lex.getCode() != tgtok::r_brace) {
1294 TokError("expected '}' at end of bit list value");
1297 Lex.Lex(); // eat the '}'
1299 SmallVector<Init *, 16> NewBits;
1301 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1302 // first. We'll first read everything in to a vector, then we can reverse
1303 // it to get the bits in the correct order for the BitsInit value.
1304 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1305 // FIXME: The following two loops would not be duplicated
1306 // if the API was a little more orthogonal.
1308 // bits<n> values are allowed to initialize n bits.
1309 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
1310 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
1311 NewBits.push_back(BI->getBit((e - i) - 1));
1314 // bits<n> can also come from variable initializers.
1315 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
1316 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
1317 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
1318 NewBits.push_back(VI->getBit((e - i) - 1));
1321 // Fallthrough to try convert this to a bit.
1323 // All other values must be convertible to just a single bit.
1324 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1326 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1327 ") is not convertable to a bit");
1330 NewBits.push_back(Bit);
1332 std::reverse(NewBits.begin(), NewBits.end());
1333 return BitsInit::get(NewBits);
1335 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1336 Lex.Lex(); // eat the '['
1337 std::vector<Init*> Vals;
1339 RecTy *DeducedEltTy = nullptr;
1340 ListRecTy *GivenListTy = nullptr;
1343 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1346 raw_string_ostream ss(s);
1347 ss << "Type mismatch for list, expected list type, got "
1348 << ItemType->getAsString();
1352 GivenListTy = ListType;
1355 if (Lex.getCode() != tgtok::r_square) {
1356 Vals = ParseValueList(CurRec, nullptr,
1357 GivenListTy ? GivenListTy->getElementType() : nullptr);
1358 if (Vals.empty()) return nullptr;
1360 if (Lex.getCode() != tgtok::r_square) {
1361 TokError("expected ']' at end of list value");
1364 Lex.Lex(); // eat the ']'
1366 RecTy *GivenEltTy = nullptr;
1367 if (Lex.getCode() == tgtok::less) {
1368 // Optional list element type
1369 Lex.Lex(); // eat the '<'
1371 GivenEltTy = ParseType();
1373 // Couldn't parse element type
1377 if (Lex.getCode() != tgtok::greater) {
1378 TokError("expected '>' at end of list element type");
1381 Lex.Lex(); // eat the '>'
1385 RecTy *EltTy = nullptr;
1386 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1389 TypedInit *TArg = dyn_cast<TypedInit>(*i);
1391 TokError("Untyped list element");
1395 EltTy = resolveTypes(EltTy, TArg->getType());
1397 TokError("Incompatible types in list elements");
1401 EltTy = TArg->getType();
1407 // Verify consistency
1408 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1409 TokError("Incompatible types in list elements");
1418 TokError("No type for list");
1421 DeducedEltTy = GivenListTy->getElementType();
1423 // Make sure the deduced type is compatible with the given type
1425 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1426 TokError("Element type mismatch for list");
1430 DeducedEltTy = EltTy;
1433 return ListInit::get(Vals, DeducedEltTy);
1435 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1436 Lex.Lex(); // eat the '('
1437 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1438 TokError("expected identifier in dag init");
1442 Init *Operator = ParseValue(CurRec);
1443 if (!Operator) return nullptr;
1445 // If the operator name is present, parse it.
1446 std::string OperatorName;
1447 if (Lex.getCode() == tgtok::colon) {
1448 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1449 TokError("expected variable name in dag operator");
1452 OperatorName = Lex.getCurStrVal();
1453 Lex.Lex(); // eat the VarName.
1456 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1457 if (Lex.getCode() != tgtok::r_paren) {
1458 DagArgs = ParseDagArgList(CurRec);
1459 if (DagArgs.empty()) return nullptr;
1462 if (Lex.getCode() != tgtok::r_paren) {
1463 TokError("expected ')' in dag init");
1466 Lex.Lex(); // eat the ')'
1468 return DagInit::get(Operator, OperatorName, DagArgs);
1474 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1475 case tgtok::XConcat:
1482 case tgtok::XListConcat:
1483 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1485 case tgtok::XForEach:
1486 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1487 return ParseOperation(CurRec, ItemType);
1494 /// ParseValue - Parse a tblgen value. This returns null on error.
1496 /// Value ::= SimpleValue ValueSuffix*
1497 /// ValueSuffix ::= '{' BitList '}'
1498 /// ValueSuffix ::= '[' BitList ']'
1499 /// ValueSuffix ::= '.' ID
1501 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1502 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1503 if (!Result) return nullptr;
1505 // Parse the suffixes now if present.
1507 switch (Lex.getCode()) {
1508 default: return Result;
1509 case tgtok::l_brace: {
1510 if (Mode == ParseNameMode || Mode == ParseForeachMode)
1511 // This is the beginning of the object body.
1514 SMLoc CurlyLoc = Lex.getLoc();
1515 Lex.Lex(); // eat the '{'
1516 std::vector<unsigned> Ranges = ParseRangeList();
1517 if (Ranges.empty()) return nullptr;
1519 // Reverse the bitlist.
1520 std::reverse(Ranges.begin(), Ranges.end());
1521 Result = Result->convertInitializerBitRange(Ranges);
1523 Error(CurlyLoc, "Invalid bit range for value");
1528 if (Lex.getCode() != tgtok::r_brace) {
1529 TokError("expected '}' at end of bit range list");
1535 case tgtok::l_square: {
1536 SMLoc SquareLoc = Lex.getLoc();
1537 Lex.Lex(); // eat the '['
1538 std::vector<unsigned> Ranges = ParseRangeList();
1539 if (Ranges.empty()) return nullptr;
1541 Result = Result->convertInitListSlice(Ranges);
1543 Error(SquareLoc, "Invalid range for list slice");
1548 if (Lex.getCode() != tgtok::r_square) {
1549 TokError("expected ']' at end of list slice");
1556 if (Lex.Lex() != tgtok::Id) { // eat the .
1557 TokError("expected field identifier after '.'");
1560 if (!Result->getFieldType(Lex.getCurStrVal())) {
1561 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1562 Result->getAsString() + "'");
1565 Result = FieldInit::get(Result, Lex.getCurStrVal());
1566 Lex.Lex(); // eat field name
1570 SMLoc PasteLoc = Lex.getLoc();
1572 // Create a !strconcat() operation, first casting each operand to
1573 // a string if necessary.
1575 TypedInit *LHS = dyn_cast<TypedInit>(Result);
1577 Error(PasteLoc, "LHS of paste is not typed!");
1581 if (LHS->getType() != StringRecTy::get()) {
1582 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1585 TypedInit *RHS = nullptr;
1587 Lex.Lex(); // Eat the '#'.
1588 switch (Lex.getCode()) {
1591 case tgtok::l_brace:
1592 // These are all of the tokens that can begin an object body.
1593 // Some of these can also begin values but we disallow those cases
1594 // because they are unlikely to be useful.
1596 // Trailing paste, concat with an empty string.
1597 RHS = StringInit::get("");
1601 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1602 RHS = dyn_cast<TypedInit>(RHSResult);
1604 Error(PasteLoc, "RHS of paste is not typed!");
1608 if (RHS->getType() != StringRecTy::get()) {
1609 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1615 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1616 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1622 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1624 /// DagArg ::= Value (':' VARNAME)?
1625 /// DagArg ::= VARNAME
1626 /// DagArgList ::= DagArg
1627 /// DagArgList ::= DagArgList ',' DagArg
1628 std::vector<std::pair<llvm::Init*, std::string> >
1629 TGParser::ParseDagArgList(Record *CurRec) {
1630 std::vector<std::pair<llvm::Init*, std::string> > Result;
1633 // DagArg ::= VARNAME
1634 if (Lex.getCode() == tgtok::VarName) {
1635 // A missing value is treated like '?'.
1636 Result.push_back(std::make_pair(UnsetInit::get(), Lex.getCurStrVal()));
1639 // DagArg ::= Value (':' VARNAME)?
1640 Init *Val = ParseValue(CurRec);
1642 return std::vector<std::pair<llvm::Init*, std::string> >();
1644 // If the variable name is present, add it.
1645 std::string VarName;
1646 if (Lex.getCode() == tgtok::colon) {
1647 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1648 TokError("expected variable name in dag literal");
1649 return std::vector<std::pair<llvm::Init*, std::string> >();
1651 VarName = Lex.getCurStrVal();
1652 Lex.Lex(); // eat the VarName.
1655 Result.push_back(std::make_pair(Val, VarName));
1657 if (Lex.getCode() != tgtok::comma) break;
1658 Lex.Lex(); // eat the ','
1665 /// ParseValueList - Parse a comma separated list of values, returning them as a
1666 /// vector. Note that this always expects to be able to parse at least one
1667 /// value. It returns an empty list if this is not possible.
1669 /// ValueList ::= Value (',' Value)
1671 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1673 std::vector<Init*> Result;
1674 RecTy *ItemType = EltTy;
1675 unsigned int ArgN = 0;
1676 if (ArgsRec && !EltTy) {
1677 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1678 if (TArgs.empty()) {
1679 TokError("template argument provided to non-template class");
1680 return std::vector<Init*>();
1682 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1684 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1687 assert(RV && "Template argument record not found??");
1688 ItemType = RV->getType();
1691 Result.push_back(ParseValue(CurRec, ItemType));
1692 if (!Result.back()) return std::vector<Init*>();
1694 while (Lex.getCode() == tgtok::comma) {
1695 Lex.Lex(); // Eat the comma
1697 if (ArgsRec && !EltTy) {
1698 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1699 if (ArgN >= TArgs.size()) {
1700 TokError("too many template arguments");
1701 return std::vector<Init*>();
1703 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1704 assert(RV && "Template argument record not found??");
1705 ItemType = RV->getType();
1708 Result.push_back(ParseValue(CurRec, ItemType));
1709 if (!Result.back()) return std::vector<Init*>();
1716 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1717 /// empty string on error. This can happen in a number of different context's,
1718 /// including within a def or in the template args for a def (which which case
1719 /// CurRec will be non-null) and within the template args for a multiclass (in
1720 /// which case CurRec will be null, but CurMultiClass will be set). This can
1721 /// also happen within a def that is within a multiclass, which will set both
1722 /// CurRec and CurMultiClass.
1724 /// Declaration ::= FIELD? Type ID ('=' Value)?
1726 Init *TGParser::ParseDeclaration(Record *CurRec,
1727 bool ParsingTemplateArgs) {
1728 // Read the field prefix if present.
1729 bool HasField = Lex.getCode() == tgtok::Field;
1730 if (HasField) Lex.Lex();
1732 RecTy *Type = ParseType();
1733 if (!Type) return nullptr;
1735 if (Lex.getCode() != tgtok::Id) {
1736 TokError("Expected identifier in declaration");
1740 SMLoc IdLoc = Lex.getLoc();
1741 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1744 if (ParsingTemplateArgs) {
1746 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1748 assert(CurMultiClass);
1751 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1756 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1759 // If a value is present, parse it.
1760 if (Lex.getCode() == tgtok::equal) {
1762 SMLoc ValLoc = Lex.getLoc();
1763 Init *Val = ParseValue(CurRec, Type);
1765 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1766 // Return the name, even if an error is thrown. This is so that we can
1767 // continue to make some progress, even without the value having been
1775 /// ParseForeachDeclaration - Read a foreach declaration, returning
1776 /// the name of the declared object or a NULL Init on error. Return
1777 /// the name of the parsed initializer list through ForeachListName.
1779 /// ForeachDeclaration ::= ID '=' '[' ValueList ']'
1780 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
1781 /// ForeachDeclaration ::= ID '=' RangePiece
1783 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1784 if (Lex.getCode() != tgtok::Id) {
1785 TokError("Expected identifier in foreach declaration");
1789 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1792 // If a value is present, parse it.
1793 if (Lex.getCode() != tgtok::equal) {
1794 TokError("Expected '=' in foreach declaration");
1797 Lex.Lex(); // Eat the '='
1799 RecTy *IterType = nullptr;
1800 std::vector<unsigned> Ranges;
1802 switch (Lex.getCode()) {
1803 default: TokError("Unknown token when expecting a range list"); return nullptr;
1804 case tgtok::l_square: { // '[' ValueList ']'
1805 Init *List = ParseSimpleValue(nullptr, nullptr, ParseForeachMode);
1806 ForeachListValue = dyn_cast<ListInit>(List);
1807 if (!ForeachListValue) {
1808 TokError("Expected a Value list");
1811 RecTy *ValueType = ForeachListValue->getType();
1812 ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1814 TokError("Value list is not of list type");
1817 IterType = ListType->getElementType();
1821 case tgtok::IntVal: { // RangePiece.
1822 if (ParseRangePiece(Ranges))
1827 case tgtok::l_brace: { // '{' RangeList '}'
1828 Lex.Lex(); // eat the '{'
1829 Ranges = ParseRangeList();
1830 if (Lex.getCode() != tgtok::r_brace) {
1831 TokError("expected '}' at end of bit range list");
1839 if (!Ranges.empty()) {
1840 assert(!IterType && "Type already initialized?");
1841 IterType = IntRecTy::get();
1842 std::vector<Init*> Values;
1843 for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
1844 Values.push_back(IntInit::get(Ranges[i]));
1845 ForeachListValue = ListInit::get(Values, IterType);
1851 return VarInit::get(DeclName, IterType);
1854 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1855 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1856 /// template args for a def, which may or may not be in a multiclass. If null,
1857 /// these are the template args for a multiclass.
1859 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1861 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1862 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1863 Lex.Lex(); // eat the '<'
1865 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1867 // Read the first declaration.
1868 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1872 TheRecToAddTo->addTemplateArg(TemplArg);
1874 while (Lex.getCode() == tgtok::comma) {
1875 Lex.Lex(); // eat the ','
1877 // Read the following declarations.
1878 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1881 TheRecToAddTo->addTemplateArg(TemplArg);
1884 if (Lex.getCode() != tgtok::greater)
1885 return TokError("expected '>' at end of template argument list");
1886 Lex.Lex(); // eat the '>'.
1891 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1893 /// BodyItem ::= Declaration ';'
1894 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1895 bool TGParser::ParseBodyItem(Record *CurRec) {
1896 if (Lex.getCode() != tgtok::Let) {
1897 if (!ParseDeclaration(CurRec, false))
1900 if (Lex.getCode() != tgtok::semi)
1901 return TokError("expected ';' after declaration");
1906 // LET ID OptionalRangeList '=' Value ';'
1907 if (Lex.Lex() != tgtok::Id)
1908 return TokError("expected field identifier after let");
1910 SMLoc IdLoc = Lex.getLoc();
1911 std::string FieldName = Lex.getCurStrVal();
1912 Lex.Lex(); // eat the field name.
1914 std::vector<unsigned> BitList;
1915 if (ParseOptionalBitList(BitList))
1917 std::reverse(BitList.begin(), BitList.end());
1919 if (Lex.getCode() != tgtok::equal)
1920 return TokError("expected '=' in let expression");
1921 Lex.Lex(); // eat the '='.
1923 RecordVal *Field = CurRec->getValue(FieldName);
1925 return TokError("Value '" + FieldName + "' unknown!");
1927 RecTy *Type = Field->getType();
1929 Init *Val = ParseValue(CurRec, Type);
1930 if (!Val) return true;
1932 if (Lex.getCode() != tgtok::semi)
1933 return TokError("expected ';' after let expression");
1936 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1939 /// ParseBody - Read the body of a class or def. Return true on error, false on
1943 /// Body ::= '{' BodyList '}'
1944 /// BodyList BodyItem*
1946 bool TGParser::ParseBody(Record *CurRec) {
1947 // If this is a null definition, just eat the semi and return.
1948 if (Lex.getCode() == tgtok::semi) {
1953 if (Lex.getCode() != tgtok::l_brace)
1954 return TokError("Expected ';' or '{' to start body");
1958 while (Lex.getCode() != tgtok::r_brace)
1959 if (ParseBodyItem(CurRec))
1967 /// \brief Apply the current let bindings to \a CurRec.
1968 /// \returns true on error, false otherwise.
1969 bool TGParser::ApplyLetStack(Record *CurRec) {
1970 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1971 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1972 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1973 LetStack[i][j].Bits, LetStack[i][j].Value))
1978 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1979 /// optional ClassList followed by a Body. CurRec is the current def or class
1980 /// that is being parsed.
1982 /// ObjectBody ::= BaseClassList Body
1983 /// BaseClassList ::= /*empty*/
1984 /// BaseClassList ::= ':' BaseClassListNE
1985 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1987 bool TGParser::ParseObjectBody(Record *CurRec) {
1988 // If there is a baseclass list, read it.
1989 if (Lex.getCode() == tgtok::colon) {
1992 // Read all of the subclasses.
1993 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1996 if (!SubClass.Rec) return true;
1999 if (AddSubClass(CurRec, SubClass))
2002 if (Lex.getCode() != tgtok::comma) break;
2003 Lex.Lex(); // eat ','.
2004 SubClass = ParseSubClassReference(CurRec, false);
2008 if (ApplyLetStack(CurRec))
2011 return ParseBody(CurRec);
2014 /// ParseDef - Parse and return a top level or multiclass def, return the record
2015 /// corresponding to it. This returns null on error.
2017 /// DefInst ::= DEF ObjectName ObjectBody
2019 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
2020 SMLoc DefLoc = Lex.getLoc();
2021 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
2022 Lex.Lex(); // Eat the 'def' token.
2024 // Parse ObjectName and make a record for it.
2025 std::unique_ptr<Record> CurRecOwner;
2026 Init *Name = ParseObjectName(CurMultiClass);
2028 CurRecOwner = make_unique<Record>(Name, DefLoc, Records);
2030 CurRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), DefLoc,
2031 Records, /*IsAnonymous=*/true);
2032 Record *CurRec = CurRecOwner.get(); // Keep a copy since we may release.
2034 if (!CurMultiClass && Loops.empty()) {
2035 // Top-level def definition.
2037 // Ensure redefinition doesn't happen.
2038 if (Records.getDef(CurRec->getNameInitAsString()))
2039 return Error(DefLoc, "def '" + CurRec->getNameInitAsString()+
2040 "' already defined");
2041 Records.addDef(std::move(CurRecOwner));
2043 if (ParseObjectBody(CurRec))
2045 } else if (CurMultiClass) {
2046 // Parse the body before adding this prototype to the DefPrototypes vector.
2047 // That way implicit definitions will be added to the DefPrototypes vector
2048 // before this object, instantiated prior to defs derived from this object,
2049 // and this available for indirect name resolution when defs derived from
2050 // this object are instantiated.
2051 if (ParseObjectBody(CurRec))
2054 // Otherwise, a def inside a multiclass, add it to the multiclass.
2055 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
2056 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2057 == CurRec->getNameInit())
2058 return Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
2059 "' already defined in this multiclass!");
2060 CurMultiClass->DefPrototypes.push_back(std::move(CurRecOwner));
2061 } else if (ParseObjectBody(CurRec)) {
2065 if (!CurMultiClass) // Def's in multiclasses aren't really defs.
2066 // See Record::setName(). This resolve step will see any new name
2067 // for the def that might have been created when resolving
2068 // inheritance, values and arguments above.
2069 CurRec->resolveReferences();
2071 // If ObjectBody has template arguments, it's an error.
2072 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
2074 if (CurMultiClass) {
2075 // Copy the template arguments for the multiclass into the def.
2076 const std::vector<Init *> &TArgs =
2077 CurMultiClass->Rec.getTemplateArgs();
2079 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2080 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
2081 assert(RV && "Template arg doesn't exist?");
2082 CurRec->addValue(*RV);
2086 if (ProcessForeachDefs(CurRec, DefLoc)) {
2087 return Error(DefLoc, "Could not process loops for def" +
2088 CurRec->getNameInitAsString());
2094 /// ParseForeach - Parse a for statement. Return the record corresponding
2095 /// to it. This returns true on error.
2097 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2098 /// Foreach ::= FOREACH Declaration IN Object
2100 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2101 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2102 Lex.Lex(); // Eat the 'for' token.
2104 // Make a temporary object to record items associated with the for
2106 ListInit *ListValue = nullptr;
2107 VarInit *IterName = ParseForeachDeclaration(ListValue);
2109 return TokError("expected declaration in for");
2111 if (Lex.getCode() != tgtok::In)
2112 return TokError("Unknown tok");
2113 Lex.Lex(); // Eat the in
2115 // Create a loop object and remember it.
2116 Loops.push_back(ForeachLoop(IterName, ListValue));
2118 if (Lex.getCode() != tgtok::l_brace) {
2119 // FOREACH Declaration IN Object
2120 if (ParseObject(CurMultiClass))
2124 SMLoc BraceLoc = Lex.getLoc();
2125 // Otherwise, this is a group foreach.
2126 Lex.Lex(); // eat the '{'.
2128 // Parse the object list.
2129 if (ParseObjectList(CurMultiClass))
2132 if (Lex.getCode() != tgtok::r_brace) {
2133 TokError("expected '}' at end of foreach command");
2134 return Error(BraceLoc, "to match this '{'");
2136 Lex.Lex(); // Eat the }
2139 // We've processed everything in this loop.
2145 /// ParseClass - Parse a tblgen class definition.
2147 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2149 bool TGParser::ParseClass() {
2150 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2153 if (Lex.getCode() != tgtok::Id)
2154 return TokError("expected class name after 'class' keyword");
2156 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2158 // If the body was previously defined, this is an error.
2159 if (CurRec->getValues().size() > 1 || // Account for NAME.
2160 !CurRec->getSuperClasses().empty() ||
2161 !CurRec->getTemplateArgs().empty())
2162 return TokError("Class '" + CurRec->getNameInitAsString()
2163 + "' already defined");
2165 // If this is the first reference to this class, create and add it.
2167 llvm::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records);
2168 CurRec = NewRec.get();
2169 Records.addClass(std::move(NewRec));
2171 Lex.Lex(); // eat the name.
2173 // If there are template args, parse them.
2174 if (Lex.getCode() == tgtok::less)
2175 if (ParseTemplateArgList(CurRec))
2178 // Finally, parse the object body.
2179 return ParseObjectBody(CurRec);
2182 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2185 /// LetList ::= LetItem (',' LetItem)*
2186 /// LetItem ::= ID OptionalRangeList '=' Value
2188 std::vector<LetRecord> TGParser::ParseLetList() {
2189 std::vector<LetRecord> Result;
2192 if (Lex.getCode() != tgtok::Id) {
2193 TokError("expected identifier in let definition");
2194 return std::vector<LetRecord>();
2196 std::string Name = Lex.getCurStrVal();
2197 SMLoc NameLoc = Lex.getLoc();
2198 Lex.Lex(); // Eat the identifier.
2200 // Check for an optional RangeList.
2201 std::vector<unsigned> Bits;
2202 if (ParseOptionalRangeList(Bits))
2203 return std::vector<LetRecord>();
2204 std::reverse(Bits.begin(), Bits.end());
2206 if (Lex.getCode() != tgtok::equal) {
2207 TokError("expected '=' in let expression");
2208 return std::vector<LetRecord>();
2210 Lex.Lex(); // eat the '='.
2212 Init *Val = ParseValue(nullptr);
2213 if (!Val) return std::vector<LetRecord>();
2215 // Now that we have everything, add the record.
2216 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2218 if (Lex.getCode() != tgtok::comma)
2220 Lex.Lex(); // eat the comma.
2224 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2225 /// different related productions. This works inside multiclasses too.
2227 /// Object ::= LET LetList IN '{' ObjectList '}'
2228 /// Object ::= LET LetList IN Object
2230 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2231 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2234 // Add this entry to the let stack.
2235 std::vector<LetRecord> LetInfo = ParseLetList();
2236 if (LetInfo.empty()) return true;
2237 LetStack.push_back(std::move(LetInfo));
2239 if (Lex.getCode() != tgtok::In)
2240 return TokError("expected 'in' at end of top-level 'let'");
2243 // If this is a scalar let, just handle it now
2244 if (Lex.getCode() != tgtok::l_brace) {
2245 // LET LetList IN Object
2246 if (ParseObject(CurMultiClass))
2248 } else { // Object ::= LETCommand '{' ObjectList '}'
2249 SMLoc BraceLoc = Lex.getLoc();
2250 // Otherwise, this is a group let.
2251 Lex.Lex(); // eat the '{'.
2253 // Parse the object list.
2254 if (ParseObjectList(CurMultiClass))
2257 if (Lex.getCode() != tgtok::r_brace) {
2258 TokError("expected '}' at end of top level let command");
2259 return Error(BraceLoc, "to match this '{'");
2264 // Outside this let scope, this let block is not active.
2265 LetStack.pop_back();
2269 /// ParseMultiClass - Parse a multiclass definition.
2271 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2272 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2273 /// MultiClassObject ::= DefInst
2274 /// MultiClassObject ::= MultiClassInst
2275 /// MultiClassObject ::= DefMInst
2276 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
2277 /// MultiClassObject ::= LETCommand Object
2279 bool TGParser::ParseMultiClass() {
2280 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2281 Lex.Lex(); // Eat the multiclass token.
2283 if (Lex.getCode() != tgtok::Id)
2284 return TokError("expected identifier after multiclass for name");
2285 std::string Name = Lex.getCurStrVal();
2288 MultiClasses.insert(std::make_pair(Name,
2289 llvm::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
2292 return TokError("multiclass '" + Name + "' already defined");
2294 CurMultiClass = Result.first->second.get();
2295 Lex.Lex(); // Eat the identifier.
2297 // If there are template args, parse them.
2298 if (Lex.getCode() == tgtok::less)
2299 if (ParseTemplateArgList(nullptr))
2302 bool inherits = false;
2304 // If there are submulticlasses, parse them.
2305 if (Lex.getCode() == tgtok::colon) {
2310 // Read all of the submulticlasses.
2311 SubMultiClassReference SubMultiClass =
2312 ParseSubMultiClassReference(CurMultiClass);
2315 if (!SubMultiClass.MC) return true;
2318 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2321 if (Lex.getCode() != tgtok::comma) break;
2322 Lex.Lex(); // eat ','.
2323 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2327 if (Lex.getCode() != tgtok::l_brace) {
2329 return TokError("expected '{' in multiclass definition");
2330 if (Lex.getCode() != tgtok::semi)
2331 return TokError("expected ';' in multiclass definition");
2332 Lex.Lex(); // eat the ';'.
2334 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2335 return TokError("multiclass must contain at least one def");
2337 while (Lex.getCode() != tgtok::r_brace) {
2338 switch (Lex.getCode()) {
2340 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2344 case tgtok::Foreach:
2345 if (ParseObject(CurMultiClass))
2350 Lex.Lex(); // eat the '}'.
2353 CurMultiClass = nullptr;
2358 InstantiateMulticlassDef(MultiClass &MC,
2361 SMRange DefmPrefixRange) {
2362 // We need to preserve DefProto so it can be reused for later
2363 // instantiations, so create a new Record to inherit from it.
2365 // Add in the defm name. If the defm prefix is empty, give each
2366 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2367 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2370 bool IsAnonymous = false;
2372 DefmPrefix = StringInit::get(GetNewAnonymousName());
2376 Init *DefName = DefProto->getNameInit();
2378 StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2380 if (DefNameString) {
2381 // We have a fully expanded string so there are no operators to
2382 // resolve. We should concatenate the given prefix and name.
2384 BinOpInit::get(BinOpInit::STRCONCAT,
2385 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2386 StringRecTy::get())->Fold(DefProto, &MC),
2387 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2390 // Make a trail of SMLocs from the multiclass instantiations.
2391 SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
2392 Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2393 auto CurRec = make_unique<Record>(DefName, Locs, Records, IsAnonymous);
2395 SubClassReference Ref;
2396 Ref.RefRange = DefmPrefixRange;
2398 AddSubClass(CurRec.get(), Ref);
2400 // Set the value for NAME. We don't resolve references to it 'til later,
2401 // though, so that uses in nested multiclass names don't get
2403 if (SetValue(CurRec.get(), Ref.RefRange.Start, "NAME",
2404 std::vector<unsigned>(), DefmPrefix)) {
2405 Error(DefmPrefixRange.Start, "Could not resolve "
2406 + CurRec->getNameInitAsString() + ":NAME to '"
2407 + DefmPrefix->getAsUnquotedString() + "'");
2411 // If the DefNameString didn't resolve, we probably have a reference to
2412 // NAME and need to replace it. We need to do at least this much greedily,
2413 // otherwise nested multiclasses will end up with incorrect NAME expansions.
2414 if (!DefNameString) {
2415 RecordVal *DefNameRV = CurRec->getValue("NAME");
2416 CurRec->resolveReferencesTo(DefNameRV);
2419 if (!CurMultiClass) {
2420 // Now that we're at the top level, resolve all NAME references
2421 // in the resultant defs that weren't in the def names themselves.
2422 RecordVal *DefNameRV = CurRec->getValue("NAME");
2423 CurRec->resolveReferencesTo(DefNameRV);
2425 // Now that NAME references are resolved and we're at the top level of
2426 // any multiclass expansions, add the record to the RecordKeeper. If we are
2427 // currently in a multiclass, it means this defm appears inside a
2428 // multiclass and its name won't be fully resolvable until we see
2429 // the top-level defm. Therefore, we don't add this to the
2430 // RecordKeeper at this point. If we did we could get duplicate
2431 // defs as more than one probably refers to NAME or some other
2432 // common internal placeholder.
2434 // Ensure redefinition doesn't happen.
2435 if (Records.getDef(CurRec->getNameInitAsString())) {
2436 Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
2437 "' already defined, instantiating defm with subdef '" +
2438 DefProto->getNameInitAsString() + "'");
2442 Record *CurRecSave = CurRec.get(); // Keep a copy before we release.
2443 Records.addDef(std::move(CurRec));
2447 // FIXME This is bad but the ownership transfer to caller is pretty messy.
2448 // The unique_ptr in this function at least protects the exits above.
2449 return CurRec.release();
2452 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2454 SMLoc DefmPrefixLoc,
2456 const std::vector<Init *> &TArgs,
2457 std::vector<Init *> &TemplateVals,
2459 // Loop over all of the template arguments, setting them to the specified
2460 // value or leaving them as the default if necessary.
2461 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2462 // Check if a value is specified for this temp-arg.
2463 if (i < TemplateVals.size()) {
2465 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2470 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2474 CurRec->removeValue(TArgs[i]);
2476 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2477 return Error(SubClassLoc, "value not specified for template argument #"+
2478 utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2479 + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2486 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2489 SMLoc DefmPrefixLoc) {
2490 // If the mdef is inside a 'let' expression, add to each def.
2491 if (ApplyLetStack(CurRec))
2492 return Error(DefmPrefixLoc, "when instantiating this defm");
2494 // Don't create a top level definition for defm inside multiclasses,
2495 // instead, only update the prototypes and bind the template args
2496 // with the new created definition.
2499 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2501 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2502 == CurRec->getNameInit())
2503 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2504 "' already defined in this multiclass!");
2505 CurMultiClass->DefPrototypes.push_back(std::unique_ptr<Record>(CurRec));
2507 // Copy the template arguments for the multiclass into the new def.
2508 const std::vector<Init *> &TA =
2509 CurMultiClass->Rec.getTemplateArgs();
2511 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2512 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2513 assert(RV && "Template arg doesn't exist?");
2514 CurRec->addValue(*RV);
2520 /// ParseDefm - Parse the instantiation of a multiclass.
2522 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2524 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2525 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2526 SMLoc DefmLoc = Lex.getLoc();
2527 Init *DefmPrefix = nullptr;
2529 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2530 DefmPrefix = ParseObjectName(CurMultiClass);
2533 SMLoc DefmPrefixEndLoc = Lex.getLoc();
2534 if (Lex.getCode() != tgtok::colon)
2535 return TokError("expected ':' after defm identifier");
2537 // Keep track of the new generated record definitions.
2538 std::vector<Record*> NewRecDefs;
2540 // This record also inherits from a regular class (non-multiclass)?
2541 bool InheritFromClass = false;
2546 SMLoc SubClassLoc = Lex.getLoc();
2547 SubClassReference Ref = ParseSubClassReference(nullptr, true);
2550 if (!Ref.Rec) return true;
2552 // To instantiate a multiclass, we need to first get the multiclass, then
2553 // instantiate each def contained in the multiclass with the SubClassRef
2554 // template parameters.
2555 MultiClass *MC = MultiClasses[Ref.Rec->getName()].get();
2556 assert(MC && "Didn't lookup multiclass correctly?");
2557 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2559 // Verify that the correct number of template arguments were specified.
2560 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2561 if (TArgs.size() < TemplateVals.size())
2562 return Error(SubClassLoc,
2563 "more template args specified than multiclass expects");
2565 // Loop over all the def's in the multiclass, instantiating each one.
2566 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2567 Record *DefProto = MC->DefPrototypes[i].get();
2569 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix,
2575 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
2576 TArgs, TemplateVals, true/*Delete args*/))
2577 return Error(SubClassLoc, "could not instantiate def");
2579 if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmLoc))
2580 return Error(SubClassLoc, "could not instantiate def");
2582 // Defs that can be used by other definitions should be fully resolved
2584 if (DefProto->isResolveFirst() && !CurMultiClass) {
2585 CurRec->resolveReferences();
2586 CurRec->setResolveFirst(false);
2588 NewRecDefs.push_back(CurRec);
2592 if (Lex.getCode() != tgtok::comma) break;
2593 Lex.Lex(); // eat ','.
2595 if (Lex.getCode() != tgtok::Id)
2596 return TokError("expected identifier");
2598 SubClassLoc = Lex.getLoc();
2600 // A defm can inherit from regular classes (non-multiclass) as
2601 // long as they come in the end of the inheritance list.
2602 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
2604 if (InheritFromClass)
2607 Ref = ParseSubClassReference(nullptr, true);
2610 if (InheritFromClass) {
2611 // Process all the classes to inherit as if they were part of a
2612 // regular 'def' and inherit all record values.
2613 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
2616 if (!SubClass.Rec) return true;
2618 // Get the expanded definition prototypes and teach them about
2619 // the record values the current class to inherit has
2620 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2621 Record *CurRec = NewRecDefs[i];
2624 if (AddSubClass(CurRec, SubClass))
2627 if (ApplyLetStack(CurRec))
2631 if (Lex.getCode() != tgtok::comma) break;
2632 Lex.Lex(); // eat ','.
2633 SubClass = ParseSubClassReference(nullptr, false);
2638 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2639 // See Record::setName(). This resolve step will see any new
2640 // name for the def that might have been created when resolving
2641 // inheritance, values and arguments above.
2642 NewRecDefs[i]->resolveReferences();
2644 if (Lex.getCode() != tgtok::semi)
2645 return TokError("expected ';' at end of defm");
2652 /// Object ::= ClassInst
2653 /// Object ::= DefInst
2654 /// Object ::= MultiClassInst
2655 /// Object ::= DefMInst
2656 /// Object ::= LETCommand '{' ObjectList '}'
2657 /// Object ::= LETCommand Object
2658 bool TGParser::ParseObject(MultiClass *MC) {
2659 switch (Lex.getCode()) {
2661 return TokError("Expected class, def, defm, multiclass or let definition");
2662 case tgtok::Let: return ParseTopLevelLet(MC);
2663 case tgtok::Def: return ParseDef(MC);
2664 case tgtok::Foreach: return ParseForeach(MC);
2665 case tgtok::Defm: return ParseDefm(MC);
2666 case tgtok::Class: return ParseClass();
2667 case tgtok::MultiClass: return ParseMultiClass();
2672 /// ObjectList :== Object*
2673 bool TGParser::ParseObjectList(MultiClass *MC) {
2674 while (isObjectStart(Lex.getCode())) {
2675 if (ParseObject(MC))
2681 bool TGParser::ParseFile() {
2682 Lex.Lex(); // Prime the lexer.
2683 if (ParseObjectList()) return true;
2685 // If we have unread input at the end of the file, report it.
2686 if (Lex.getCode() == tgtok::Eof)
2689 return TokError("Unexpected input at top level");