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);
139 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of type '"
140 + RV->getType()->getAsString() +
141 "' is incompatible with initializer '" + V->getAsString()
146 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
147 /// args as SubClass's template arguments.
148 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
149 Record *SC = SubClass.Rec;
150 // Add all of the values in the subclass into the current class.
151 const std::vector<RecordVal> &Vals = SC->getValues();
152 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
153 if (AddValue(CurRec, SubClass.RefRange.Start, Vals[i]))
156 const std::vector<Init *> &TArgs = SC->getTemplateArgs();
158 // Ensure that an appropriate number of template arguments are specified.
159 if (TArgs.size() < SubClass.TemplateArgs.size())
160 return Error(SubClass.RefRange.Start,
161 "More template args specified than expected");
163 // Loop over all of the template arguments, setting them to the specified
164 // value or leaving them as the default if necessary.
165 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
166 if (i < SubClass.TemplateArgs.size()) {
167 // If a value is specified for this template arg, set it now.
168 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
169 std::vector<unsigned>(), SubClass.TemplateArgs[i]))
173 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
176 CurRec->removeValue(TArgs[i]);
178 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
179 return Error(SubClass.RefRange.Start,
180 "Value not specified for template argument #"
181 + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
182 + ") of subclass '" + SC->getNameInitAsString() + "'!");
186 // Since everything went well, we can now set the "superclass" list for the
188 const std::vector<Record*> &SCs = SC->getSuperClasses();
189 ArrayRef<SMRange> SCRanges = SC->getSuperClassRanges();
190 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
191 if (CurRec->isSubClassOf(SCs[i]))
192 return Error(SubClass.RefRange.Start,
193 "Already subclass of '" + SCs[i]->getName() + "'!\n");
194 CurRec->addSuperClass(SCs[i], SCRanges[i]);
197 if (CurRec->isSubClassOf(SC))
198 return Error(SubClass.RefRange.Start,
199 "Already subclass of '" + SC->getName() + "'!\n");
200 CurRec->addSuperClass(SC, SubClass.RefRange);
204 /// AddSubMultiClass - Add SubMultiClass as a subclass to
205 /// CurMC, resolving its template args as SubMultiClass's
206 /// template arguments.
207 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
208 SubMultiClassReference &SubMultiClass) {
209 MultiClass *SMC = SubMultiClass.MC;
210 Record *CurRec = &CurMC->Rec;
212 const std::vector<RecordVal> &MCVals = CurRec->getValues();
214 // Add all of the values in the subclass into the current class.
215 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
216 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
217 if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVals[i]))
220 int newDefStart = CurMC->DefPrototypes.size();
222 // Add all of the defs in the subclass into the current multiclass.
223 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
224 iend = SMC->DefPrototypes.end();
227 // Clone the def and add it to the current multiclass
228 Record *NewDef = new Record(**i);
230 // Add all of the values in the superclass into the current def.
231 for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
232 if (AddValue(NewDef, SubMultiClass.RefRange.Start, MCVals[i]))
235 CurMC->DefPrototypes.push_back(NewDef);
238 const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
240 // Ensure that an appropriate number of template arguments are
242 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
243 return Error(SubMultiClass.RefRange.Start,
244 "More template args specified than expected");
246 // Loop over all of the template arguments, setting them to the specified
247 // value or leaving them as the default if necessary.
248 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
249 if (i < SubMultiClass.TemplateArgs.size()) {
250 // If a value is specified for this template arg, set it in the
252 if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i],
253 std::vector<unsigned>(),
254 SubMultiClass.TemplateArgs[i]))
258 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
261 CurRec->removeValue(SMCTArgs[i]);
263 // If a value is specified for this template arg, set it in the
265 for (MultiClass::RecordVector::iterator j =
266 CurMC->DefPrototypes.begin() + newDefStart,
267 jend = CurMC->DefPrototypes.end();
272 if (SetValue(Def, SubMultiClass.RefRange.Start, SMCTArgs[i],
273 std::vector<unsigned>(),
274 SubMultiClass.TemplateArgs[i]))
278 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
281 Def->removeValue(SMCTArgs[i]);
283 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
284 return Error(SubMultiClass.RefRange.Start,
285 "Value not specified for template argument #"
286 + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
287 + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
294 /// ProcessForeachDefs - Given a record, apply all of the variable
295 /// values in all surrounding foreach loops, creating new records for
296 /// each combination of values.
297 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
301 // We want to instantiate a new copy of CurRec for each combination
302 // of nested loop iterator values. We don't want top instantiate
303 // any copies until we have values for each loop iterator.
305 return ProcessForeachDefs(CurRec, Loc, IterVals);
308 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
309 /// apply each of the variable values in this loop and then process
311 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
312 // Recursively build a tuple of iterator values.
313 if (IterVals.size() != Loops.size()) {
314 assert(IterVals.size() < Loops.size());
315 ForeachLoop &CurLoop = Loops[IterVals.size()];
316 ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
318 Error(Loc, "Loop list is not a list");
322 // Process each value.
323 for (int64_t i = 0; i < List->getSize(); ++i) {
324 Init *ItemVal = List->resolveListElementReference(*CurRec, nullptr, i);
325 IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
326 if (ProcessForeachDefs(CurRec, Loc, IterVals))
333 // This is the bottom of the recursion. We have all of the iterator values
334 // for this point in the iteration space. Instantiate a new record to
335 // reflect this combination of values.
336 Record *IterRec = new Record(*CurRec);
338 // Set the iterator values now.
339 for (unsigned i = 0, e = IterVals.size(); i != e; ++i) {
340 VarInit *IterVar = IterVals[i].IterVar;
341 TypedInit *IVal = dyn_cast<TypedInit>(IterVals[i].IterValue);
343 Error(Loc, "foreach iterator value is untyped");
347 IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
349 if (SetValue(IterRec, Loc, IterVar->getName(),
350 std::vector<unsigned>(), IVal)) {
351 Error(Loc, "when instantiating this def");
356 IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
359 IterRec->removeValue(IterVar->getName());
362 if (Records.getDef(IterRec->getNameInitAsString())) {
363 Error(Loc, "def already exists: " + IterRec->getNameInitAsString());
367 Records.addDef(IterRec);
368 IterRec->resolveReferences();
372 //===----------------------------------------------------------------------===//
374 //===----------------------------------------------------------------------===//
376 /// isObjectStart - Return true if this is a valid first token for an Object.
377 static bool isObjectStart(tgtok::TokKind K) {
378 return K == tgtok::Class || K == tgtok::Def ||
379 K == tgtok::Defm || K == tgtok::Let ||
380 K == tgtok::MultiClass || K == tgtok::Foreach;
383 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
385 std::string TGParser::GetNewAnonymousName() {
386 unsigned Tmp = AnonCounter++; // MSVC2012 ICEs without this.
387 return "anonymous_" + utostr(Tmp);
390 /// ParseObjectName - If an object name is specified, return it. Otherwise,
392 /// ObjectName ::= Value [ '#' Value ]*
393 /// ObjectName ::= /*empty*/
395 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
396 switch (Lex.getCode()) {
400 // These are all of the tokens that can begin an object body.
401 // Some of these can also begin values but we disallow those cases
402 // because they are unlikely to be useful.
408 Record *CurRec = nullptr;
410 CurRec = &CurMultiClass->Rec;
412 RecTy *Type = nullptr;
414 const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
416 TokError("Record name is not typed!");
419 Type = CurRecName->getType();
422 return ParseValue(CurRec, Type, ParseNameMode);
425 /// ParseClassID - Parse and resolve a reference to a class name. This returns
430 Record *TGParser::ParseClassID() {
431 if (Lex.getCode() != tgtok::Id) {
432 TokError("expected name for ClassID");
436 Record *Result = Records.getClass(Lex.getCurStrVal());
438 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
444 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
445 /// This returns null on error.
447 /// MultiClassID ::= ID
449 MultiClass *TGParser::ParseMultiClassID() {
450 if (Lex.getCode() != tgtok::Id) {
451 TokError("expected name for MultiClassID");
455 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
457 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
463 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
464 /// subclass. This returns a SubClassRefTy with a null Record* on error.
466 /// SubClassRef ::= ClassID
467 /// SubClassRef ::= ClassID '<' ValueList '>'
469 SubClassReference TGParser::
470 ParseSubClassReference(Record *CurRec, bool isDefm) {
471 SubClassReference Result;
472 Result.RefRange.Start = Lex.getLoc();
475 if (MultiClass *MC = ParseMultiClassID())
476 Result.Rec = &MC->Rec;
478 Result.Rec = ParseClassID();
480 if (!Result.Rec) return Result;
482 // If there is no template arg list, we're done.
483 if (Lex.getCode() != tgtok::less) {
484 Result.RefRange.End = Lex.getLoc();
487 Lex.Lex(); // Eat the '<'
489 if (Lex.getCode() == tgtok::greater) {
490 TokError("subclass reference requires a non-empty list of template values");
491 Result.Rec = nullptr;
495 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
496 if (Result.TemplateArgs.empty()) {
497 Result.Rec = nullptr; // Error parsing value list.
501 if (Lex.getCode() != tgtok::greater) {
502 TokError("expected '>' in template value list");
503 Result.Rec = nullptr;
507 Result.RefRange.End = Lex.getLoc();
512 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
513 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
514 /// Record* on error.
516 /// SubMultiClassRef ::= MultiClassID
517 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
519 SubMultiClassReference TGParser::
520 ParseSubMultiClassReference(MultiClass *CurMC) {
521 SubMultiClassReference Result;
522 Result.RefRange.Start = Lex.getLoc();
524 Result.MC = ParseMultiClassID();
525 if (!Result.MC) return Result;
527 // If there is no template arg list, we're done.
528 if (Lex.getCode() != tgtok::less) {
529 Result.RefRange.End = Lex.getLoc();
532 Lex.Lex(); // Eat the '<'
534 if (Lex.getCode() == tgtok::greater) {
535 TokError("subclass reference requires a non-empty list of template values");
540 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
541 if (Result.TemplateArgs.empty()) {
542 Result.MC = nullptr; // Error parsing value list.
546 if (Lex.getCode() != tgtok::greater) {
547 TokError("expected '>' in template value list");
552 Result.RefRange.End = Lex.getLoc();
557 /// ParseRangePiece - Parse a bit/value range.
558 /// RangePiece ::= INTVAL
559 /// RangePiece ::= INTVAL '-' INTVAL
560 /// RangePiece ::= INTVAL INTVAL
561 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
562 if (Lex.getCode() != tgtok::IntVal) {
563 TokError("expected integer or bitrange");
566 int64_t Start = Lex.getCurIntVal();
570 return TokError("invalid range, cannot be negative");
572 switch (Lex.Lex()) { // eat first character.
574 Ranges.push_back(Start);
577 if (Lex.Lex() != tgtok::IntVal) {
578 TokError("expected integer value as end of range");
581 End = Lex.getCurIntVal();
584 End = -Lex.getCurIntVal();
588 return TokError("invalid range, cannot be negative");
593 for (; Start <= End; ++Start)
594 Ranges.push_back(Start);
596 for (; Start >= End; --Start)
597 Ranges.push_back(Start);
602 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
604 /// RangeList ::= RangePiece (',' RangePiece)*
606 std::vector<unsigned> TGParser::ParseRangeList() {
607 std::vector<unsigned> Result;
609 // Parse the first piece.
610 if (ParseRangePiece(Result))
611 return std::vector<unsigned>();
612 while (Lex.getCode() == tgtok::comma) {
613 Lex.Lex(); // Eat the comma.
615 // Parse the next range piece.
616 if (ParseRangePiece(Result))
617 return std::vector<unsigned>();
622 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
623 /// OptionalRangeList ::= '<' RangeList '>'
624 /// OptionalRangeList ::= /*empty*/
625 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
626 if (Lex.getCode() != tgtok::less)
629 SMLoc StartLoc = Lex.getLoc();
630 Lex.Lex(); // eat the '<'
632 // Parse the range list.
633 Ranges = ParseRangeList();
634 if (Ranges.empty()) return true;
636 if (Lex.getCode() != tgtok::greater) {
637 TokError("expected '>' at end of range list");
638 return Error(StartLoc, "to match this '<'");
640 Lex.Lex(); // eat the '>'.
644 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
645 /// OptionalBitList ::= '{' RangeList '}'
646 /// OptionalBitList ::= /*empty*/
647 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
648 if (Lex.getCode() != tgtok::l_brace)
651 SMLoc StartLoc = Lex.getLoc();
652 Lex.Lex(); // eat the '{'
654 // Parse the range list.
655 Ranges = ParseRangeList();
656 if (Ranges.empty()) return true;
658 if (Lex.getCode() != tgtok::r_brace) {
659 TokError("expected '}' at end of bit list");
660 return Error(StartLoc, "to match this '{'");
662 Lex.Lex(); // eat the '}'.
667 /// ParseType - Parse and return a tblgen type. This returns null on error.
669 /// Type ::= STRING // string type
670 /// Type ::= CODE // code type
671 /// Type ::= BIT // bit type
672 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
673 /// Type ::= INT // int type
674 /// Type ::= LIST '<' Type '>' // list<x> type
675 /// Type ::= DAG // dag type
676 /// Type ::= ClassID // Record Type
678 RecTy *TGParser::ParseType() {
679 switch (Lex.getCode()) {
680 default: TokError("Unknown token when expecting a type"); return nullptr;
681 case tgtok::String: Lex.Lex(); return StringRecTy::get();
682 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
683 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
684 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
685 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
687 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
690 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
691 TokError("expected '<' after bits type");
694 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
695 TokError("expected integer in bits<n> type");
698 uint64_t Val = Lex.getCurIntVal();
699 if (Lex.Lex() != tgtok::greater) { // Eat count.
700 TokError("expected '>' at end of bits<n> type");
703 Lex.Lex(); // Eat '>'
704 return BitsRecTy::get(Val);
707 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
708 TokError("expected '<' after list type");
711 Lex.Lex(); // Eat '<'
712 RecTy *SubType = ParseType();
713 if (!SubType) return nullptr;
715 if (Lex.getCode() != tgtok::greater) {
716 TokError("expected '>' at end of list<ty> type");
719 Lex.Lex(); // Eat '>'
720 return ListRecTy::get(SubType);
725 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
726 /// has already been read.
727 Init *TGParser::ParseIDValue(Record *CurRec,
728 const std::string &Name, SMLoc NameLoc,
731 if (const RecordVal *RV = CurRec->getValue(Name))
732 return VarInit::get(Name, RV->getType());
734 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
737 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
740 if (CurRec->isTemplateArg(TemplateArgName)) {
741 const RecordVal *RV = CurRec->getValue(TemplateArgName);
742 assert(RV && "Template arg doesn't exist??");
743 return VarInit::get(TemplateArgName, RV->getType());
748 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
751 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
752 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
753 assert(RV && "Template arg doesn't exist??");
754 return VarInit::get(MCName, RV->getType());
758 // If this is in a foreach loop, make sure it's not a loop iterator
759 for (LoopVector::iterator i = Loops.begin(), iend = Loops.end();
762 VarInit *IterVar = dyn_cast<VarInit>(i->IterVar);
763 if (IterVar && IterVar->getName() == Name)
767 if (Mode == ParseNameMode)
768 return StringInit::get(Name);
770 if (Record *D = Records.getDef(Name))
771 return DefInit::get(D);
773 if (Mode == ParseValueMode) {
774 Error(NameLoc, "Variable not defined: '" + Name + "'");
778 return StringInit::get(Name);
781 /// ParseOperation - Parse an operator. This returns null on error.
783 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
785 Init *TGParser::ParseOperation(Record *CurRec) {
786 switch (Lex.getCode()) {
788 TokError("unknown operation");
793 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
794 UnOpInit::UnaryOp Code;
795 RecTy *Type = nullptr;
797 switch (Lex.getCode()) {
798 default: llvm_unreachable("Unhandled code!");
800 Lex.Lex(); // eat the operation
801 Code = UnOpInit::CAST;
803 Type = ParseOperatorType();
806 TokError("did not get type for unary operator");
812 Lex.Lex(); // eat the operation
813 Code = UnOpInit::HEAD;
816 Lex.Lex(); // eat the operation
817 Code = UnOpInit::TAIL;
820 Lex.Lex(); // eat the operation
821 Code = UnOpInit::EMPTY;
822 Type = IntRecTy::get();
825 if (Lex.getCode() != tgtok::l_paren) {
826 TokError("expected '(' after unary operator");
829 Lex.Lex(); // eat the '('
831 Init *LHS = ParseValue(CurRec);
832 if (!LHS) return nullptr;
834 if (Code == UnOpInit::HEAD
835 || Code == UnOpInit::TAIL
836 || Code == UnOpInit::EMPTY) {
837 ListInit *LHSl = dyn_cast<ListInit>(LHS);
838 StringInit *LHSs = dyn_cast<StringInit>(LHS);
839 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
840 if (!LHSl && !LHSs && !LHSt) {
841 TokError("expected list or string type argument in unary operator");
845 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
846 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
847 if (!LType && !SType) {
848 TokError("expected list or string type argumnet in unary operator");
853 if (Code == UnOpInit::HEAD
854 || Code == UnOpInit::TAIL) {
855 if (!LHSl && !LHSt) {
856 TokError("expected list type argumnet in unary operator");
860 if (LHSl && LHSl->getSize() == 0) {
861 TokError("empty list argument in unary operator");
865 Init *Item = LHSl->getElement(0);
866 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
868 TokError("untyped list element in unary operator");
871 if (Code == UnOpInit::HEAD) {
872 Type = Itemt->getType();
874 Type = ListRecTy::get(Itemt->getType());
877 assert(LHSt && "expected list type argument in unary operator");
878 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
880 TokError("expected list type argumnet in unary operator");
883 if (Code == UnOpInit::HEAD) {
884 Type = LType->getElementType();
892 if (Lex.getCode() != tgtok::r_paren) {
893 TokError("expected ')' in unary operator");
896 Lex.Lex(); // eat the ')'
897 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
906 case tgtok::XListConcat:
907 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
908 tgtok::TokKind OpTok = Lex.getCode();
909 SMLoc OpLoc = Lex.getLoc();
910 Lex.Lex(); // eat the operation
912 BinOpInit::BinaryOp Code;
913 RecTy *Type = nullptr;
916 default: llvm_unreachable("Unhandled code!");
917 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
918 case tgtok::XADD: Code = BinOpInit::ADD; Type = IntRecTy::get(); break;
919 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
920 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
921 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
922 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
923 case tgtok::XListConcat:
924 Code = BinOpInit::LISTCONCAT;
925 // We don't know the list type until we parse the first argument
927 case tgtok::XStrConcat:
928 Code = BinOpInit::STRCONCAT;
929 Type = StringRecTy::get();
933 if (Lex.getCode() != tgtok::l_paren) {
934 TokError("expected '(' after binary operator");
937 Lex.Lex(); // eat the '('
939 SmallVector<Init*, 2> InitList;
941 InitList.push_back(ParseValue(CurRec));
942 if (!InitList.back()) return nullptr;
944 while (Lex.getCode() == tgtok::comma) {
945 Lex.Lex(); // eat the ','
947 InitList.push_back(ParseValue(CurRec));
948 if (!InitList.back()) return nullptr;
951 if (Lex.getCode() != tgtok::r_paren) {
952 TokError("expected ')' in operator");
955 Lex.Lex(); // eat the ')'
957 // If we are doing !listconcat, we should know the type by now
958 if (OpTok == tgtok::XListConcat) {
959 if (VarInit *Arg0 = dyn_cast<VarInit>(InitList[0]))
960 Type = Arg0->getType();
961 else if (ListInit *Arg0 = dyn_cast<ListInit>(InitList[0]))
962 Type = Arg0->getType();
965 Error(OpLoc, "expected a list");
970 // We allow multiple operands to associative operators like !strconcat as
971 // shorthand for nesting them.
972 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT) {
973 while (InitList.size() > 2) {
974 Init *RHS = InitList.pop_back_val();
975 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
976 ->Fold(CurRec, CurMultiClass);
977 InitList.back() = RHS;
981 if (InitList.size() == 2)
982 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
983 ->Fold(CurRec, CurMultiClass);
985 Error(OpLoc, "expected two operands to operator");
990 case tgtok::XForEach:
991 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
992 TernOpInit::TernaryOp Code;
993 RecTy *Type = nullptr;
995 tgtok::TokKind LexCode = Lex.getCode();
996 Lex.Lex(); // eat the operation
998 default: llvm_unreachable("Unhandled code!");
1000 Code = TernOpInit::IF;
1002 case tgtok::XForEach:
1003 Code = TernOpInit::FOREACH;
1006 Code = TernOpInit::SUBST;
1009 if (Lex.getCode() != tgtok::l_paren) {
1010 TokError("expected '(' after ternary operator");
1013 Lex.Lex(); // eat the '('
1015 Init *LHS = ParseValue(CurRec);
1016 if (!LHS) return nullptr;
1018 if (Lex.getCode() != tgtok::comma) {
1019 TokError("expected ',' in ternary operator");
1022 Lex.Lex(); // eat the ','
1024 Init *MHS = ParseValue(CurRec);
1025 if (!MHS) return nullptr;
1027 if (Lex.getCode() != tgtok::comma) {
1028 TokError("expected ',' in ternary operator");
1031 Lex.Lex(); // eat the ','
1033 Init *RHS = ParseValue(CurRec);
1034 if (!RHS) return nullptr;
1036 if (Lex.getCode() != tgtok::r_paren) {
1037 TokError("expected ')' in binary operator");
1040 Lex.Lex(); // eat the ')'
1043 default: llvm_unreachable("Unhandled code!");
1045 RecTy *MHSTy = nullptr;
1046 RecTy *RHSTy = nullptr;
1048 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1049 MHSTy = MHSt->getType();
1050 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1051 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1052 if (isa<BitInit>(MHS))
1053 MHSTy = BitRecTy::get();
1055 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1056 RHSTy = RHSt->getType();
1057 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1058 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1059 if (isa<BitInit>(RHS))
1060 RHSTy = BitRecTy::get();
1062 // For UnsetInit, it's typed from the other hand.
1063 if (isa<UnsetInit>(MHS))
1065 if (isa<UnsetInit>(RHS))
1068 if (!MHSTy || !RHSTy) {
1069 TokError("could not get type for !if");
1073 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1075 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1078 TokError("inconsistent types for !if");
1083 case tgtok::XForEach: {
1084 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1086 TokError("could not get type for !foreach");
1089 Type = MHSt->getType();
1092 case tgtok::XSubst: {
1093 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1095 TokError("could not get type for !subst");
1098 Type = RHSt->getType();
1102 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1108 /// ParseOperatorType - Parse a type for an operator. This returns
1111 /// OperatorType ::= '<' Type '>'
1113 RecTy *TGParser::ParseOperatorType() {
1114 RecTy *Type = nullptr;
1116 if (Lex.getCode() != tgtok::less) {
1117 TokError("expected type name for operator");
1120 Lex.Lex(); // eat the <
1125 TokError("expected type name for operator");
1129 if (Lex.getCode() != tgtok::greater) {
1130 TokError("expected type name for operator");
1133 Lex.Lex(); // eat the >
1139 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1141 /// SimpleValue ::= IDValue
1142 /// SimpleValue ::= INTVAL
1143 /// SimpleValue ::= STRVAL+
1144 /// SimpleValue ::= CODEFRAGMENT
1145 /// SimpleValue ::= '?'
1146 /// SimpleValue ::= '{' ValueList '}'
1147 /// SimpleValue ::= ID '<' ValueListNE '>'
1148 /// SimpleValue ::= '[' ValueList ']'
1149 /// SimpleValue ::= '(' IDValue DagArgList ')'
1150 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1151 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1152 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1153 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1154 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1155 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1156 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1158 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1161 switch (Lex.getCode()) {
1162 default: TokError("Unknown token when parsing a value"); break;
1164 // This is a leading paste operation. This is deprecated but
1165 // still exists in some .td files. Ignore it.
1166 Lex.Lex(); // Skip '#'.
1167 return ParseSimpleValue(CurRec, ItemType, Mode);
1168 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1169 case tgtok::StrVal: {
1170 std::string Val = Lex.getCurStrVal();
1173 // Handle multiple consecutive concatenated strings.
1174 while (Lex.getCode() == tgtok::StrVal) {
1175 Val += Lex.getCurStrVal();
1179 R = StringInit::get(Val);
1182 case tgtok::CodeFragment:
1183 R = StringInit::get(Lex.getCurStrVal());
1186 case tgtok::question:
1187 R = UnsetInit::get();
1191 SMLoc NameLoc = Lex.getLoc();
1192 std::string Name = Lex.getCurStrVal();
1193 if (Lex.Lex() != tgtok::less) // consume the Id.
1194 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1196 // Value ::= ID '<' ValueListNE '>'
1197 if (Lex.Lex() == tgtok::greater) {
1198 TokError("expected non-empty value list");
1202 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1203 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1205 Record *Class = Records.getClass(Name);
1207 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1211 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1212 if (ValueList.empty()) return nullptr;
1214 if (Lex.getCode() != tgtok::greater) {
1215 TokError("expected '>' at end of value list");
1218 Lex.Lex(); // eat the '>'
1219 SMLoc EndLoc = Lex.getLoc();
1221 // Create the new record, set it as CurRec temporarily.
1222 Record *NewRec = new Record(GetNewAnonymousName(), NameLoc, Records,
1223 /*IsAnonymous=*/true);
1224 SubClassReference SCRef;
1225 SCRef.RefRange = SMRange(NameLoc, EndLoc);
1227 SCRef.TemplateArgs = ValueList;
1228 // Add info about the subclass to NewRec.
1229 if (AddSubClass(NewRec, SCRef))
1231 if (!CurMultiClass) {
1232 NewRec->resolveReferences();
1233 Records.addDef(NewRec);
1235 // Otherwise, we're inside a multiclass, add it to the multiclass.
1236 CurMultiClass->DefPrototypes.push_back(NewRec);
1238 // Copy the template arguments for the multiclass into the def.
1239 const std::vector<Init *> &TArgs =
1240 CurMultiClass->Rec.getTemplateArgs();
1242 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1243 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1244 assert(RV && "Template arg doesn't exist?");
1245 NewRec->addValue(*RV);
1248 // We can't return the prototype def here, instead return:
1249 // !cast<ItemType>(!strconcat(NAME, AnonName)).
1250 const RecordVal *MCNameRV = CurMultiClass->Rec.getValue("NAME");
1251 assert(MCNameRV && "multiclass record must have a NAME");
1253 return UnOpInit::get(UnOpInit::CAST,
1254 BinOpInit::get(BinOpInit::STRCONCAT,
1255 VarInit::get(MCNameRV->getName(),
1256 MCNameRV->getType()),
1257 NewRec->getNameInit(),
1258 StringRecTy::get()),
1259 Class->getDefInit()->getType());
1262 // The result of the expression is a reference to the new record.
1263 return DefInit::get(NewRec);
1265 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1266 SMLoc BraceLoc = Lex.getLoc();
1267 Lex.Lex(); // eat the '{'
1268 std::vector<Init*> Vals;
1270 if (Lex.getCode() != tgtok::r_brace) {
1271 Vals = ParseValueList(CurRec);
1272 if (Vals.empty()) return nullptr;
1274 if (Lex.getCode() != tgtok::r_brace) {
1275 TokError("expected '}' at end of bit list value");
1278 Lex.Lex(); // eat the '}'
1280 SmallVector<Init *, 16> NewBits(Vals.size());
1282 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1283 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1285 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1286 ") is not convertable to a bit");
1289 NewBits[Vals.size()-i-1] = Bit;
1291 return BitsInit::get(NewBits);
1293 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1294 Lex.Lex(); // eat the '['
1295 std::vector<Init*> Vals;
1297 RecTy *DeducedEltTy = nullptr;
1298 ListRecTy *GivenListTy = nullptr;
1301 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1304 raw_string_ostream ss(s);
1305 ss << "Type mismatch for list, expected list type, got "
1306 << ItemType->getAsString();
1310 GivenListTy = ListType;
1313 if (Lex.getCode() != tgtok::r_square) {
1314 Vals = ParseValueList(CurRec, nullptr,
1315 GivenListTy ? GivenListTy->getElementType() : nullptr);
1316 if (Vals.empty()) return nullptr;
1318 if (Lex.getCode() != tgtok::r_square) {
1319 TokError("expected ']' at end of list value");
1322 Lex.Lex(); // eat the ']'
1324 RecTy *GivenEltTy = nullptr;
1325 if (Lex.getCode() == tgtok::less) {
1326 // Optional list element type
1327 Lex.Lex(); // eat the '<'
1329 GivenEltTy = ParseType();
1331 // Couldn't parse element type
1335 if (Lex.getCode() != tgtok::greater) {
1336 TokError("expected '>' at end of list element type");
1339 Lex.Lex(); // eat the '>'
1343 RecTy *EltTy = nullptr;
1344 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1347 TypedInit *TArg = dyn_cast<TypedInit>(*i);
1349 TokError("Untyped list element");
1353 EltTy = resolveTypes(EltTy, TArg->getType());
1355 TokError("Incompatible types in list elements");
1359 EltTy = TArg->getType();
1365 // Verify consistency
1366 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1367 TokError("Incompatible types in list elements");
1376 TokError("No type for list");
1379 DeducedEltTy = GivenListTy->getElementType();
1381 // Make sure the deduced type is compatible with the given type
1383 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1384 TokError("Element type mismatch for list");
1388 DeducedEltTy = EltTy;
1391 return ListInit::get(Vals, DeducedEltTy);
1393 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1394 Lex.Lex(); // eat the '('
1395 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1396 TokError("expected identifier in dag init");
1400 Init *Operator = ParseValue(CurRec);
1401 if (!Operator) return nullptr;
1403 // If the operator name is present, parse it.
1404 std::string OperatorName;
1405 if (Lex.getCode() == tgtok::colon) {
1406 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1407 TokError("expected variable name in dag operator");
1410 OperatorName = Lex.getCurStrVal();
1411 Lex.Lex(); // eat the VarName.
1414 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1415 if (Lex.getCode() != tgtok::r_paren) {
1416 DagArgs = ParseDagArgList(CurRec);
1417 if (DagArgs.empty()) return nullptr;
1420 if (Lex.getCode() != tgtok::r_paren) {
1421 TokError("expected ')' in dag init");
1424 Lex.Lex(); // eat the ')'
1426 return DagInit::get(Operator, OperatorName, DagArgs);
1432 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1433 case tgtok::XConcat:
1439 case tgtok::XListConcat:
1440 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1442 case tgtok::XForEach:
1443 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1444 return ParseOperation(CurRec);
1451 /// ParseValue - Parse a tblgen value. This returns null on error.
1453 /// Value ::= SimpleValue ValueSuffix*
1454 /// ValueSuffix ::= '{' BitList '}'
1455 /// ValueSuffix ::= '[' BitList ']'
1456 /// ValueSuffix ::= '.' ID
1458 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1459 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1460 if (!Result) return nullptr;
1462 // Parse the suffixes now if present.
1464 switch (Lex.getCode()) {
1465 default: return Result;
1466 case tgtok::l_brace: {
1467 if (Mode == ParseNameMode || Mode == ParseForeachMode)
1468 // This is the beginning of the object body.
1471 SMLoc CurlyLoc = Lex.getLoc();
1472 Lex.Lex(); // eat the '{'
1473 std::vector<unsigned> Ranges = ParseRangeList();
1474 if (Ranges.empty()) return nullptr;
1476 // Reverse the bitlist.
1477 std::reverse(Ranges.begin(), Ranges.end());
1478 Result = Result->convertInitializerBitRange(Ranges);
1480 Error(CurlyLoc, "Invalid bit range for value");
1485 if (Lex.getCode() != tgtok::r_brace) {
1486 TokError("expected '}' at end of bit range list");
1492 case tgtok::l_square: {
1493 SMLoc SquareLoc = Lex.getLoc();
1494 Lex.Lex(); // eat the '['
1495 std::vector<unsigned> Ranges = ParseRangeList();
1496 if (Ranges.empty()) return nullptr;
1498 Result = Result->convertInitListSlice(Ranges);
1500 Error(SquareLoc, "Invalid range for list slice");
1505 if (Lex.getCode() != tgtok::r_square) {
1506 TokError("expected ']' at end of list slice");
1513 if (Lex.Lex() != tgtok::Id) { // eat the .
1514 TokError("expected field identifier after '.'");
1517 if (!Result->getFieldType(Lex.getCurStrVal())) {
1518 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1519 Result->getAsString() + "'");
1522 Result = FieldInit::get(Result, Lex.getCurStrVal());
1523 Lex.Lex(); // eat field name
1527 SMLoc PasteLoc = Lex.getLoc();
1529 // Create a !strconcat() operation, first casting each operand to
1530 // a string if necessary.
1532 TypedInit *LHS = dyn_cast<TypedInit>(Result);
1534 Error(PasteLoc, "LHS of paste is not typed!");
1538 if (LHS->getType() != StringRecTy::get()) {
1539 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1542 TypedInit *RHS = nullptr;
1544 Lex.Lex(); // Eat the '#'.
1545 switch (Lex.getCode()) {
1548 case tgtok::l_brace:
1549 // These are all of the tokens that can begin an object body.
1550 // Some of these can also begin values but we disallow those cases
1551 // because they are unlikely to be useful.
1553 // Trailing paste, concat with an empty string.
1554 RHS = StringInit::get("");
1558 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1559 RHS = dyn_cast<TypedInit>(RHSResult);
1561 Error(PasteLoc, "RHS of paste is not typed!");
1565 if (RHS->getType() != StringRecTy::get()) {
1566 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1572 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1573 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1579 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1581 /// DagArg ::= Value (':' VARNAME)?
1582 /// DagArg ::= VARNAME
1583 /// DagArgList ::= DagArg
1584 /// DagArgList ::= DagArgList ',' DagArg
1585 std::vector<std::pair<llvm::Init*, std::string> >
1586 TGParser::ParseDagArgList(Record *CurRec) {
1587 std::vector<std::pair<llvm::Init*, std::string> > Result;
1590 // DagArg ::= VARNAME
1591 if (Lex.getCode() == tgtok::VarName) {
1592 // A missing value is treated like '?'.
1593 Result.push_back(std::make_pair(UnsetInit::get(), Lex.getCurStrVal()));
1596 // DagArg ::= Value (':' VARNAME)?
1597 Init *Val = ParseValue(CurRec);
1599 return std::vector<std::pair<llvm::Init*, std::string> >();
1601 // If the variable name is present, add it.
1602 std::string VarName;
1603 if (Lex.getCode() == tgtok::colon) {
1604 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1605 TokError("expected variable name in dag literal");
1606 return std::vector<std::pair<llvm::Init*, std::string> >();
1608 VarName = Lex.getCurStrVal();
1609 Lex.Lex(); // eat the VarName.
1612 Result.push_back(std::make_pair(Val, VarName));
1614 if (Lex.getCode() != tgtok::comma) break;
1615 Lex.Lex(); // eat the ','
1622 /// ParseValueList - Parse a comma separated list of values, returning them as a
1623 /// vector. Note that this always expects to be able to parse at least one
1624 /// value. It returns an empty list if this is not possible.
1626 /// ValueList ::= Value (',' Value)
1628 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1630 std::vector<Init*> Result;
1631 RecTy *ItemType = EltTy;
1632 unsigned int ArgN = 0;
1633 if (ArgsRec && !EltTy) {
1634 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1635 if (!TArgs.size()) {
1636 TokError("template argument provided to non-template class");
1637 return std::vector<Init*>();
1639 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1641 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1644 assert(RV && "Template argument record not found??");
1645 ItemType = RV->getType();
1648 Result.push_back(ParseValue(CurRec, ItemType));
1649 if (!Result.back()) return std::vector<Init*>();
1651 while (Lex.getCode() == tgtok::comma) {
1652 Lex.Lex(); // Eat the comma
1654 if (ArgsRec && !EltTy) {
1655 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1656 if (ArgN >= TArgs.size()) {
1657 TokError("too many template arguments");
1658 return std::vector<Init*>();
1660 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1661 assert(RV && "Template argument record not found??");
1662 ItemType = RV->getType();
1665 Result.push_back(ParseValue(CurRec, ItemType));
1666 if (!Result.back()) return std::vector<Init*>();
1673 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1674 /// empty string on error. This can happen in a number of different context's,
1675 /// including within a def or in the template args for a def (which which case
1676 /// CurRec will be non-null) and within the template args for a multiclass (in
1677 /// which case CurRec will be null, but CurMultiClass will be set). This can
1678 /// also happen within a def that is within a multiclass, which will set both
1679 /// CurRec and CurMultiClass.
1681 /// Declaration ::= FIELD? Type ID ('=' Value)?
1683 Init *TGParser::ParseDeclaration(Record *CurRec,
1684 bool ParsingTemplateArgs) {
1685 // Read the field prefix if present.
1686 bool HasField = Lex.getCode() == tgtok::Field;
1687 if (HasField) Lex.Lex();
1689 RecTy *Type = ParseType();
1690 if (!Type) return nullptr;
1692 if (Lex.getCode() != tgtok::Id) {
1693 TokError("Expected identifier in declaration");
1697 SMLoc IdLoc = Lex.getLoc();
1698 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1701 if (ParsingTemplateArgs) {
1703 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1705 assert(CurMultiClass);
1708 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1713 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1716 // If a value is present, parse it.
1717 if (Lex.getCode() == tgtok::equal) {
1719 SMLoc ValLoc = Lex.getLoc();
1720 Init *Val = ParseValue(CurRec, Type);
1722 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1729 /// ParseForeachDeclaration - Read a foreach declaration, returning
1730 /// the name of the declared object or a NULL Init on error. Return
1731 /// the name of the parsed initializer list through ForeachListName.
1733 /// ForeachDeclaration ::= ID '=' '[' ValueList ']'
1734 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
1735 /// ForeachDeclaration ::= ID '=' RangePiece
1737 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1738 if (Lex.getCode() != tgtok::Id) {
1739 TokError("Expected identifier in foreach declaration");
1743 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1746 // If a value is present, parse it.
1747 if (Lex.getCode() != tgtok::equal) {
1748 TokError("Expected '=' in foreach declaration");
1751 Lex.Lex(); // Eat the '='
1753 RecTy *IterType = nullptr;
1754 std::vector<unsigned> Ranges;
1756 switch (Lex.getCode()) {
1757 default: TokError("Unknown token when expecting a range list"); return nullptr;
1758 case tgtok::l_square: { // '[' ValueList ']'
1759 Init *List = ParseSimpleValue(nullptr, nullptr, ParseForeachMode);
1760 ForeachListValue = dyn_cast<ListInit>(List);
1761 if (!ForeachListValue) {
1762 TokError("Expected a Value list");
1765 RecTy *ValueType = ForeachListValue->getType();
1766 ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1768 TokError("Value list is not of list type");
1771 IterType = ListType->getElementType();
1775 case tgtok::IntVal: { // RangePiece.
1776 if (ParseRangePiece(Ranges))
1781 case tgtok::l_brace: { // '{' RangeList '}'
1782 Lex.Lex(); // eat the '{'
1783 Ranges = ParseRangeList();
1784 if (Lex.getCode() != tgtok::r_brace) {
1785 TokError("expected '}' at end of bit range list");
1793 if (!Ranges.empty()) {
1794 assert(!IterType && "Type already initialized?");
1795 IterType = IntRecTy::get();
1796 std::vector<Init*> Values;
1797 for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
1798 Values.push_back(IntInit::get(Ranges[i]));
1799 ForeachListValue = ListInit::get(Values, IterType);
1805 return VarInit::get(DeclName, IterType);
1808 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1809 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1810 /// template args for a def, which may or may not be in a multiclass. If null,
1811 /// these are the template args for a multiclass.
1813 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1815 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1816 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1817 Lex.Lex(); // eat the '<'
1819 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1821 // Read the first declaration.
1822 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1826 TheRecToAddTo->addTemplateArg(TemplArg);
1828 while (Lex.getCode() == tgtok::comma) {
1829 Lex.Lex(); // eat the ','
1831 // Read the following declarations.
1832 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1835 TheRecToAddTo->addTemplateArg(TemplArg);
1838 if (Lex.getCode() != tgtok::greater)
1839 return TokError("expected '>' at end of template argument list");
1840 Lex.Lex(); // eat the '>'.
1845 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1847 /// BodyItem ::= Declaration ';'
1848 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1849 bool TGParser::ParseBodyItem(Record *CurRec) {
1850 if (Lex.getCode() != tgtok::Let) {
1851 if (!ParseDeclaration(CurRec, false))
1854 if (Lex.getCode() != tgtok::semi)
1855 return TokError("expected ';' after declaration");
1860 // LET ID OptionalRangeList '=' Value ';'
1861 if (Lex.Lex() != tgtok::Id)
1862 return TokError("expected field identifier after let");
1864 SMLoc IdLoc = Lex.getLoc();
1865 std::string FieldName = Lex.getCurStrVal();
1866 Lex.Lex(); // eat the field name.
1868 std::vector<unsigned> BitList;
1869 if (ParseOptionalBitList(BitList))
1871 std::reverse(BitList.begin(), BitList.end());
1873 if (Lex.getCode() != tgtok::equal)
1874 return TokError("expected '=' in let expression");
1875 Lex.Lex(); // eat the '='.
1877 RecordVal *Field = CurRec->getValue(FieldName);
1879 return TokError("Value '" + FieldName + "' unknown!");
1881 RecTy *Type = Field->getType();
1883 Init *Val = ParseValue(CurRec, Type);
1884 if (!Val) return true;
1886 if (Lex.getCode() != tgtok::semi)
1887 return TokError("expected ';' after let expression");
1890 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1893 /// ParseBody - Read the body of a class or def. Return true on error, false on
1897 /// Body ::= '{' BodyList '}'
1898 /// BodyList BodyItem*
1900 bool TGParser::ParseBody(Record *CurRec) {
1901 // If this is a null definition, just eat the semi and return.
1902 if (Lex.getCode() == tgtok::semi) {
1907 if (Lex.getCode() != tgtok::l_brace)
1908 return TokError("Expected ';' or '{' to start body");
1912 while (Lex.getCode() != tgtok::r_brace)
1913 if (ParseBodyItem(CurRec))
1921 /// \brief Apply the current let bindings to \a CurRec.
1922 /// \returns true on error, false otherwise.
1923 bool TGParser::ApplyLetStack(Record *CurRec) {
1924 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1925 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1926 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1927 LetStack[i][j].Bits, LetStack[i][j].Value))
1932 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1933 /// optional ClassList followed by a Body. CurRec is the current def or class
1934 /// that is being parsed.
1936 /// ObjectBody ::= BaseClassList Body
1937 /// BaseClassList ::= /*empty*/
1938 /// BaseClassList ::= ':' BaseClassListNE
1939 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1941 bool TGParser::ParseObjectBody(Record *CurRec) {
1942 // If there is a baseclass list, read it.
1943 if (Lex.getCode() == tgtok::colon) {
1946 // Read all of the subclasses.
1947 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1950 if (!SubClass.Rec) return true;
1953 if (AddSubClass(CurRec, SubClass))
1956 if (Lex.getCode() != tgtok::comma) break;
1957 Lex.Lex(); // eat ','.
1958 SubClass = ParseSubClassReference(CurRec, false);
1962 if (ApplyLetStack(CurRec))
1965 return ParseBody(CurRec);
1968 /// ParseDef - Parse and return a top level or multiclass def, return the record
1969 /// corresponding to it. This returns null on error.
1971 /// DefInst ::= DEF ObjectName ObjectBody
1973 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1974 SMLoc DefLoc = Lex.getLoc();
1975 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1976 Lex.Lex(); // Eat the 'def' token.
1978 // Parse ObjectName and make a record for it.
1980 Init *Name = ParseObjectName(CurMultiClass);
1982 CurRec = new Record(Name, DefLoc, Records);
1984 CurRec = new Record(GetNewAnonymousName(), DefLoc, Records,
1985 /*IsAnonymous=*/true);
1987 if (!CurMultiClass && Loops.empty()) {
1988 // Top-level def definition.
1990 // Ensure redefinition doesn't happen.
1991 if (Records.getDef(CurRec->getNameInitAsString())) {
1992 Error(DefLoc, "def '" + CurRec->getNameInitAsString()
1993 + "' already defined");
1996 Records.addDef(CurRec);
1998 if (ParseObjectBody(CurRec))
2000 } else if (CurMultiClass) {
2001 // Parse the body before adding this prototype to the DefPrototypes vector.
2002 // That way implicit definitions will be added to the DefPrototypes vector
2003 // before this object, instantiated prior to defs derived from this object,
2004 // and this available for indirect name resolution when defs derived from
2005 // this object are instantiated.
2006 if (ParseObjectBody(CurRec))
2009 // Otherwise, a def inside a multiclass, add it to the multiclass.
2010 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
2011 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2012 == CurRec->getNameInit()) {
2013 Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
2014 "' already defined in this multiclass!");
2017 CurMultiClass->DefPrototypes.push_back(CurRec);
2018 } else if (ParseObjectBody(CurRec))
2021 if (!CurMultiClass) // Def's in multiclasses aren't really defs.
2022 // See Record::setName(). This resolve step will see any new name
2023 // for the def that might have been created when resolving
2024 // inheritance, values and arguments above.
2025 CurRec->resolveReferences();
2027 // If ObjectBody has template arguments, it's an error.
2028 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
2030 if (CurMultiClass) {
2031 // Copy the template arguments for the multiclass into the def.
2032 const std::vector<Init *> &TArgs =
2033 CurMultiClass->Rec.getTemplateArgs();
2035 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2036 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
2037 assert(RV && "Template arg doesn't exist?");
2038 CurRec->addValue(*RV);
2042 if (ProcessForeachDefs(CurRec, DefLoc)) {
2044 "Could not process loops for def" + CurRec->getNameInitAsString());
2051 /// ParseForeach - Parse a for statement. Return the record corresponding
2052 /// to it. This returns true on error.
2054 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2055 /// Foreach ::= FOREACH Declaration IN Object
2057 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2058 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2059 Lex.Lex(); // Eat the 'for' token.
2061 // Make a temporary object to record items associated with the for
2063 ListInit *ListValue = nullptr;
2064 VarInit *IterName = ParseForeachDeclaration(ListValue);
2066 return TokError("expected declaration in for");
2068 if (Lex.getCode() != tgtok::In)
2069 return TokError("Unknown tok");
2070 Lex.Lex(); // Eat the in
2072 // Create a loop object and remember it.
2073 Loops.push_back(ForeachLoop(IterName, ListValue));
2075 if (Lex.getCode() != tgtok::l_brace) {
2076 // FOREACH Declaration IN Object
2077 if (ParseObject(CurMultiClass))
2081 SMLoc BraceLoc = Lex.getLoc();
2082 // Otherwise, this is a group foreach.
2083 Lex.Lex(); // eat the '{'.
2085 // Parse the object list.
2086 if (ParseObjectList(CurMultiClass))
2089 if (Lex.getCode() != tgtok::r_brace) {
2090 TokError("expected '}' at end of foreach command");
2091 return Error(BraceLoc, "to match this '{'");
2093 Lex.Lex(); // Eat the }
2096 // We've processed everything in this loop.
2102 /// ParseClass - Parse a tblgen class definition.
2104 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2106 bool TGParser::ParseClass() {
2107 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2110 if (Lex.getCode() != tgtok::Id)
2111 return TokError("expected class name after 'class' keyword");
2113 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2115 // If the body was previously defined, this is an error.
2116 if (CurRec->getValues().size() > 1 || // Account for NAME.
2117 !CurRec->getSuperClasses().empty() ||
2118 !CurRec->getTemplateArgs().empty())
2119 return TokError("Class '" + CurRec->getNameInitAsString()
2120 + "' already defined");
2122 // If this is the first reference to this class, create and add it.
2123 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
2124 Records.addClass(CurRec);
2126 Lex.Lex(); // eat the name.
2128 // If there are template args, parse them.
2129 if (Lex.getCode() == tgtok::less)
2130 if (ParseTemplateArgList(CurRec))
2133 // Finally, parse the object body.
2134 return ParseObjectBody(CurRec);
2137 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2140 /// LetList ::= LetItem (',' LetItem)*
2141 /// LetItem ::= ID OptionalRangeList '=' Value
2143 std::vector<LetRecord> TGParser::ParseLetList() {
2144 std::vector<LetRecord> Result;
2147 if (Lex.getCode() != tgtok::Id) {
2148 TokError("expected identifier in let definition");
2149 return std::vector<LetRecord>();
2151 std::string Name = Lex.getCurStrVal();
2152 SMLoc NameLoc = Lex.getLoc();
2153 Lex.Lex(); // Eat the identifier.
2155 // Check for an optional RangeList.
2156 std::vector<unsigned> Bits;
2157 if (ParseOptionalRangeList(Bits))
2158 return std::vector<LetRecord>();
2159 std::reverse(Bits.begin(), Bits.end());
2161 if (Lex.getCode() != tgtok::equal) {
2162 TokError("expected '=' in let expression");
2163 return std::vector<LetRecord>();
2165 Lex.Lex(); // eat the '='.
2167 Init *Val = ParseValue(nullptr);
2168 if (!Val) return std::vector<LetRecord>();
2170 // Now that we have everything, add the record.
2171 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2173 if (Lex.getCode() != tgtok::comma)
2175 Lex.Lex(); // eat the comma.
2179 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2180 /// different related productions. This works inside multiclasses too.
2182 /// Object ::= LET LetList IN '{' ObjectList '}'
2183 /// Object ::= LET LetList IN Object
2185 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2186 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2189 // Add this entry to the let stack.
2190 std::vector<LetRecord> LetInfo = ParseLetList();
2191 if (LetInfo.empty()) return true;
2192 LetStack.push_back(LetInfo);
2194 if (Lex.getCode() != tgtok::In)
2195 return TokError("expected 'in' at end of top-level 'let'");
2198 // If this is a scalar let, just handle it now
2199 if (Lex.getCode() != tgtok::l_brace) {
2200 // LET LetList IN Object
2201 if (ParseObject(CurMultiClass))
2203 } else { // Object ::= LETCommand '{' ObjectList '}'
2204 SMLoc BraceLoc = Lex.getLoc();
2205 // Otherwise, this is a group let.
2206 Lex.Lex(); // eat the '{'.
2208 // Parse the object list.
2209 if (ParseObjectList(CurMultiClass))
2212 if (Lex.getCode() != tgtok::r_brace) {
2213 TokError("expected '}' at end of top level let command");
2214 return Error(BraceLoc, "to match this '{'");
2219 // Outside this let scope, this let block is not active.
2220 LetStack.pop_back();
2224 /// ParseMultiClass - Parse a multiclass definition.
2226 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2227 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2228 /// MultiClassObject ::= DefInst
2229 /// MultiClassObject ::= MultiClassInst
2230 /// MultiClassObject ::= DefMInst
2231 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
2232 /// MultiClassObject ::= LETCommand Object
2234 bool TGParser::ParseMultiClass() {
2235 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2236 Lex.Lex(); // Eat the multiclass token.
2238 if (Lex.getCode() != tgtok::Id)
2239 return TokError("expected identifier after multiclass for name");
2240 std::string Name = Lex.getCurStrVal();
2242 if (MultiClasses.count(Name))
2243 return TokError("multiclass '" + Name + "' already defined");
2245 CurMultiClass = MultiClasses[Name] = new MultiClass(Name,
2246 Lex.getLoc(), Records);
2247 Lex.Lex(); // Eat the identifier.
2249 // If there are template args, parse them.
2250 if (Lex.getCode() == tgtok::less)
2251 if (ParseTemplateArgList(nullptr))
2254 bool inherits = false;
2256 // If there are submulticlasses, parse them.
2257 if (Lex.getCode() == tgtok::colon) {
2262 // Read all of the submulticlasses.
2263 SubMultiClassReference SubMultiClass =
2264 ParseSubMultiClassReference(CurMultiClass);
2267 if (!SubMultiClass.MC) return true;
2270 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2273 if (Lex.getCode() != tgtok::comma) break;
2274 Lex.Lex(); // eat ','.
2275 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2279 if (Lex.getCode() != tgtok::l_brace) {
2281 return TokError("expected '{' in multiclass definition");
2282 else if (Lex.getCode() != tgtok::semi)
2283 return TokError("expected ';' in multiclass definition");
2285 Lex.Lex(); // eat the ';'.
2287 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2288 return TokError("multiclass must contain at least one def");
2290 while (Lex.getCode() != tgtok::r_brace) {
2291 switch (Lex.getCode()) {
2293 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2297 case tgtok::Foreach:
2298 if (ParseObject(CurMultiClass))
2303 Lex.Lex(); // eat the '}'.
2306 CurMultiClass = nullptr;
2311 InstantiateMulticlassDef(MultiClass &MC,
2314 SMRange DefmPrefixRange) {
2315 // We need to preserve DefProto so it can be reused for later
2316 // instantiations, so create a new Record to inherit from it.
2318 // Add in the defm name. If the defm prefix is empty, give each
2319 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2320 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2323 bool IsAnonymous = false;
2325 DefmPrefix = StringInit::get(GetNewAnonymousName());
2329 Init *DefName = DefProto->getNameInit();
2331 StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2333 if (DefNameString) {
2334 // We have a fully expanded string so there are no operators to
2335 // resolve. We should concatenate the given prefix and name.
2337 BinOpInit::get(BinOpInit::STRCONCAT,
2338 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2339 StringRecTy::get())->Fold(DefProto, &MC),
2340 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2343 // Make a trail of SMLocs from the multiclass instantiations.
2344 SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
2345 Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2346 Record *CurRec = new Record(DefName, Locs, Records, IsAnonymous);
2348 SubClassReference Ref;
2349 Ref.RefRange = DefmPrefixRange;
2351 AddSubClass(CurRec, Ref);
2353 // Set the value for NAME. We don't resolve references to it 'til later,
2354 // though, so that uses in nested multiclass names don't get
2356 if (SetValue(CurRec, Ref.RefRange.Start, "NAME", std::vector<unsigned>(),
2358 Error(DefmPrefixRange.Start, "Could not resolve "
2359 + CurRec->getNameInitAsString() + ":NAME to '"
2360 + DefmPrefix->getAsUnquotedString() + "'");
2364 // If the DefNameString didn't resolve, we probably have a reference to
2365 // NAME and need to replace it. We need to do at least this much greedily,
2366 // otherwise nested multiclasses will end up with incorrect NAME expansions.
2367 if (!DefNameString) {
2368 RecordVal *DefNameRV = CurRec->getValue("NAME");
2369 CurRec->resolveReferencesTo(DefNameRV);
2372 if (!CurMultiClass) {
2373 // Now that we're at the top level, resolve all NAME references
2374 // in the resultant defs that weren't in the def names themselves.
2375 RecordVal *DefNameRV = CurRec->getValue("NAME");
2376 CurRec->resolveReferencesTo(DefNameRV);
2378 // Now that NAME references are resolved and we're at the top level of
2379 // any multiclass expansions, add the record to the RecordKeeper. If we are
2380 // currently in a multiclass, it means this defm appears inside a
2381 // multiclass and its name won't be fully resolvable until we see
2382 // the top-level defm. Therefore, we don't add this to the
2383 // RecordKeeper at this point. If we did we could get duplicate
2384 // defs as more than one probably refers to NAME or some other
2385 // common internal placeholder.
2387 // Ensure redefinition doesn't happen.
2388 if (Records.getDef(CurRec->getNameInitAsString())) {
2389 Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
2390 "' already defined, instantiating defm with subdef '" +
2391 DefProto->getNameInitAsString() + "'");
2395 Records.addDef(CurRec);
2401 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2403 SMLoc DefmPrefixLoc,
2405 const std::vector<Init *> &TArgs,
2406 std::vector<Init *> &TemplateVals,
2408 // Loop over all of the template arguments, setting them to the specified
2409 // value or leaving them as the default if necessary.
2410 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2411 // Check if a value is specified for this temp-arg.
2412 if (i < TemplateVals.size()) {
2414 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2419 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2423 CurRec->removeValue(TArgs[i]);
2425 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2426 return Error(SubClassLoc, "value not specified for template argument #"+
2427 utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2428 + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2435 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2438 SMLoc DefmPrefixLoc) {
2439 // If the mdef is inside a 'let' expression, add to each def.
2440 if (ApplyLetStack(CurRec))
2441 return Error(DefmPrefixLoc, "when instantiating this defm");
2443 // Don't create a top level definition for defm inside multiclasses,
2444 // instead, only update the prototypes and bind the template args
2445 // with the new created definition.
2448 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2450 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2451 == CurRec->getNameInit())
2452 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2453 "' already defined in this multiclass!");
2454 CurMultiClass->DefPrototypes.push_back(CurRec);
2456 // Copy the template arguments for the multiclass into the new def.
2457 const std::vector<Init *> &TA =
2458 CurMultiClass->Rec.getTemplateArgs();
2460 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2461 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2462 assert(RV && "Template arg doesn't exist?");
2463 CurRec->addValue(*RV);
2469 /// ParseDefm - Parse the instantiation of a multiclass.
2471 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2473 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2474 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2475 SMLoc DefmLoc = Lex.getLoc();
2476 Init *DefmPrefix = nullptr;
2478 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2479 DefmPrefix = ParseObjectName(CurMultiClass);
2482 SMLoc DefmPrefixEndLoc = Lex.getLoc();
2483 if (Lex.getCode() != tgtok::colon)
2484 return TokError("expected ':' after defm identifier");
2486 // Keep track of the new generated record definitions.
2487 std::vector<Record*> NewRecDefs;
2489 // This record also inherits from a regular class (non-multiclass)?
2490 bool InheritFromClass = false;
2495 SMLoc SubClassLoc = Lex.getLoc();
2496 SubClassReference Ref = ParseSubClassReference(nullptr, true);
2499 if (!Ref.Rec) return true;
2501 // To instantiate a multiclass, we need to first get the multiclass, then
2502 // instantiate each def contained in the multiclass with the SubClassRef
2503 // template parameters.
2504 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2505 assert(MC && "Didn't lookup multiclass correctly?");
2506 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2508 // Verify that the correct number of template arguments were specified.
2509 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2510 if (TArgs.size() < TemplateVals.size())
2511 return Error(SubClassLoc,
2512 "more template args specified than multiclass expects");
2514 // Loop over all the def's in the multiclass, instantiating each one.
2515 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2516 Record *DefProto = MC->DefPrototypes[i];
2518 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix,
2524 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
2525 TArgs, TemplateVals, true/*Delete args*/))
2526 return Error(SubClassLoc, "could not instantiate def");
2528 if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmLoc))
2529 return Error(SubClassLoc, "could not instantiate def");
2531 NewRecDefs.push_back(CurRec);
2535 if (Lex.getCode() != tgtok::comma) break;
2536 Lex.Lex(); // eat ','.
2538 if (Lex.getCode() != tgtok::Id)
2539 return TokError("expected identifier");
2541 SubClassLoc = Lex.getLoc();
2543 // A defm can inherit from regular classes (non-multiclass) as
2544 // long as they come in the end of the inheritance list.
2545 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
2547 if (InheritFromClass)
2550 Ref = ParseSubClassReference(nullptr, true);
2553 if (InheritFromClass) {
2554 // Process all the classes to inherit as if they were part of a
2555 // regular 'def' and inherit all record values.
2556 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
2559 if (!SubClass.Rec) return true;
2561 // Get the expanded definition prototypes and teach them about
2562 // the record values the current class to inherit has
2563 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2564 Record *CurRec = NewRecDefs[i];
2567 if (AddSubClass(CurRec, SubClass))
2570 if (ApplyLetStack(CurRec))
2574 if (Lex.getCode() != tgtok::comma) break;
2575 Lex.Lex(); // eat ','.
2576 SubClass = ParseSubClassReference(nullptr, false);
2581 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2582 // See Record::setName(). This resolve step will see any new
2583 // name for the def that might have been created when resolving
2584 // inheritance, values and arguments above.
2585 NewRecDefs[i]->resolveReferences();
2587 if (Lex.getCode() != tgtok::semi)
2588 return TokError("expected ';' at end of defm");
2595 /// Object ::= ClassInst
2596 /// Object ::= DefInst
2597 /// Object ::= MultiClassInst
2598 /// Object ::= DefMInst
2599 /// Object ::= LETCommand '{' ObjectList '}'
2600 /// Object ::= LETCommand Object
2601 bool TGParser::ParseObject(MultiClass *MC) {
2602 switch (Lex.getCode()) {
2604 return TokError("Expected class, def, defm, multiclass or let definition");
2605 case tgtok::Let: return ParseTopLevelLet(MC);
2606 case tgtok::Def: return ParseDef(MC);
2607 case tgtok::Foreach: return ParseForeach(MC);
2608 case tgtok::Defm: return ParseDefm(MC);
2609 case tgtok::Class: return ParseClass();
2610 case tgtok::MultiClass: return ParseMultiClass();
2615 /// ObjectList :== Object*
2616 bool TGParser::ParseObjectList(MultiClass *MC) {
2617 while (isObjectStart(Lex.getCode())) {
2618 if (ParseObject(MC))
2624 bool TGParser::ParseFile() {
2625 Lex.Lex(); // Prime the lexer.
2626 if (ParseObjectList()) return true;
2628 // If we have unread input at the end of the file, report it.
2629 if (Lex.getCode() == tgtok::Eof)
2632 return TokError("Unexpected input at top level");