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/TableGen/Record.h"
16 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Support/CommandLine.h"
23 //===----------------------------------------------------------------------===//
24 // Support Code for the Semantic Actions.
25 //===----------------------------------------------------------------------===//
28 struct SubClassReference {
31 std::vector<Init*> TemplateArgs;
32 SubClassReference() : Rec(0) {}
34 bool isInvalid() const { return Rec == 0; }
37 struct SubMultiClassReference {
40 std::vector<Init*> TemplateArgs;
41 SubMultiClassReference() : MC(0) {}
43 bool isInvalid() const { return MC == 0; }
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 == 0) 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 = dynamic_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 = dynamic_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 V->convertInitializerTo(BitsRecTy::get(BitList.size()));
114 return Error(Loc, "Initializer is not compatible with bit range");
117 // We should have a BitsInit type now.
118 BitsInit *BInit = dynamic_cast<BitsInit*>(BI);
121 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
123 // Loop over bits, assigning values as appropriate.
124 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
125 unsigned Bit = BitList[i];
127 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
128 ValName->getAsUnquotedString() + "' more than once");
129 NewBits[Bit] = BInit->getBit(i);
132 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
134 NewBits[i] = CurVal->getBit(i);
136 V = BitsInit::get(NewBits);
140 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of type '"
141 + RV->getType()->getAsString() +
142 "' is incompatible with initializer '" + V->getAsString()
147 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
148 /// args as SubClass's template arguments.
149 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
150 Record *SC = SubClass.Rec;
151 // Add all of the values in the subclass into the current class.
152 const std::vector<RecordVal> &Vals = SC->getValues();
153 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
154 if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
157 const std::vector<Init *> &TArgs = SC->getTemplateArgs();
159 // Ensure that an appropriate number of template arguments are specified.
160 if (TArgs.size() < SubClass.TemplateArgs.size())
161 return Error(SubClass.RefLoc, "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.RefLoc, TArgs[i], std::vector<unsigned>(),
169 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.RefLoc,"Value not specified for template argument #"
180 + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
181 + ") of subclass '" + SC->getNameInitAsString() + "'!");
185 // Since everything went well, we can now set the "superclass" list for the
187 const std::vector<Record*> &SCs = SC->getSuperClasses();
188 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
189 if (CurRec->isSubClassOf(SCs[i]))
190 return Error(SubClass.RefLoc,
191 "Already subclass of '" + SCs[i]->getName() + "'!\n");
192 CurRec->addSuperClass(SCs[i]);
195 if (CurRec->isSubClassOf(SC))
196 return Error(SubClass.RefLoc,
197 "Already subclass of '" + SC->getName() + "'!\n");
198 CurRec->addSuperClass(SC);
202 /// AddSubMultiClass - Add SubMultiClass as a subclass to
203 /// CurMC, resolving its template args as SubMultiClass's
204 /// template arguments.
205 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
206 SubMultiClassReference &SubMultiClass) {
207 MultiClass *SMC = SubMultiClass.MC;
208 Record *CurRec = &CurMC->Rec;
210 const std::vector<RecordVal> &MCVals = CurRec->getValues();
212 // Add all of the values in the subclass into the current class.
213 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
214 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
215 if (AddValue(CurRec, SubMultiClass.RefLoc, SMCVals[i]))
218 int newDefStart = CurMC->DefPrototypes.size();
220 // Add all of the defs in the subclass into the current multiclass.
221 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
222 iend = SMC->DefPrototypes.end();
225 // Clone the def and add it to the current multiclass
226 Record *NewDef = new Record(**i);
228 // Add all of the values in the superclass into the current def.
229 for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
230 if (AddValue(NewDef, SubMultiClass.RefLoc, MCVals[i]))
233 CurMC->DefPrototypes.push_back(NewDef);
236 const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
238 // Ensure that an appropriate number of template arguments are
240 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
241 return Error(SubMultiClass.RefLoc,
242 "More template args specified than expected");
244 // Loop over all of the template arguments, setting them to the specified
245 // value or leaving them as the default if necessary.
246 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
247 if (i < SubMultiClass.TemplateArgs.size()) {
248 // If a value is specified for this template arg, set it in the
250 if (SetValue(CurRec, SubMultiClass.RefLoc, SMCTArgs[i],
251 std::vector<unsigned>(),
252 SubMultiClass.TemplateArgs[i]))
256 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
259 CurRec->removeValue(SMCTArgs[i]);
261 // If a value is specified for this template arg, set it in the
263 for (MultiClass::RecordVector::iterator j =
264 CurMC->DefPrototypes.begin() + newDefStart,
265 jend = CurMC->DefPrototypes.end();
270 if (SetValue(Def, SubMultiClass.RefLoc, SMCTArgs[i],
271 std::vector<unsigned>(),
272 SubMultiClass.TemplateArgs[i]))
276 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
279 Def->removeValue(SMCTArgs[i]);
281 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
282 return Error(SubMultiClass.RefLoc,
283 "Value not specified for template argument #"
284 + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
285 + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
292 /// ProcessForeachDefs - Given a record, apply all of the variable
293 /// values in all surrounding foreach loops, creating new records for
294 /// each combination of values.
295 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
299 // We want to instantiate a new copy of CurRec for each combination
300 // of nested loop iterator values. We don't want top instantiate
301 // any copies until we have values for each loop iterator.
303 return ProcessForeachDefs(CurRec, Loc, IterVals);
306 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
307 /// apply each of the variable values in this loop and then process
309 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
310 // Recursively build a tuple of iterator values.
311 if (IterVals.size() != Loops.size()) {
312 assert(IterVals.size() < Loops.size());
313 ForeachLoop &CurLoop = Loops[IterVals.size()];
314 ListInit *List = dynamic_cast<ListInit *>(CurLoop.ListValue);
316 Error(Loc, "Loop list is not a list");
320 // Process each value.
321 for (int64_t i = 0; i < List->getSize(); ++i) {
322 Init *ItemVal = List->resolveListElementReference(*CurRec, 0, i);
323 IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
324 if (ProcessForeachDefs(CurRec, Loc, IterVals))
331 // This is the bottom of the recursion. We have all of the iterator values
332 // for this point in the iteration space. Instantiate a new record to
333 // reflect this combination of values.
334 Record *IterRec = new Record(*CurRec);
336 // Set the iterator values now.
337 for (unsigned i = 0, e = IterVals.size(); i != e; ++i) {
338 VarInit *IterVar = IterVals[i].IterVar;
339 TypedInit *IVal = dynamic_cast<TypedInit *>(IterVals[i].IterValue);
341 Error(Loc, "foreach iterator value is untyped");
345 IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
347 if (SetValue(IterRec, Loc, IterVar->getName(),
348 std::vector<unsigned>(), IVal)) {
349 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 Error(Loc, "def already exists: " + IterRec->getNameInitAsString());
365 Records.addDef(IterRec);
366 IterRec->resolveReferences();
370 //===----------------------------------------------------------------------===//
372 //===----------------------------------------------------------------------===//
374 /// isObjectStart - Return true if this is a valid first token for an Object.
375 static bool isObjectStart(tgtok::TokKind K) {
376 return K == tgtok::Class || K == tgtok::Def ||
377 K == tgtok::Defm || K == tgtok::Let ||
378 K == tgtok::MultiClass || K == tgtok::Foreach;
381 static std::string GetNewAnonymousName() {
382 static unsigned AnonCounter = 0;
383 return "anonymous."+utostr(AnonCounter++);
386 /// ParseObjectName - If an object name is specified, return it. Otherwise,
387 /// return an anonymous name.
388 /// ObjectName ::= Value [ '#' Value ]*
389 /// ObjectName ::= /*empty*/
391 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
392 switch (Lex.getCode()) {
396 // These are all of the tokens that can begin an object body.
397 // Some of these can also begin values but we disallow those cases
398 // because they are unlikely to be useful.
399 return StringInit::get(GetNewAnonymousName());
406 CurRec = &CurMultiClass->Rec;
410 const TypedInit *CurRecName =
411 dynamic_cast<const TypedInit *>(CurRec->getNameInit());
413 TokError("Record name is not typed!");
416 Type = CurRecName->getType();
419 return ParseValue(CurRec, Type, ParseNameMode);
422 /// ParseClassID - Parse and resolve a reference to a class name. This returns
427 Record *TGParser::ParseClassID() {
428 if (Lex.getCode() != tgtok::Id) {
429 TokError("expected name for ClassID");
433 Record *Result = Records.getClass(Lex.getCurStrVal());
435 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
441 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
442 /// This returns null on error.
444 /// MultiClassID ::= ID
446 MultiClass *TGParser::ParseMultiClassID() {
447 if (Lex.getCode() != tgtok::Id) {
448 TokError("expected name for ClassID");
452 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
454 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
460 Record *TGParser::ParseDefmID() {
461 if (Lex.getCode() != tgtok::Id) {
462 TokError("expected multiclass name");
466 MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
468 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
477 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
478 /// subclass. This returns a SubClassRefTy with a null Record* on error.
480 /// SubClassRef ::= ClassID
481 /// SubClassRef ::= ClassID '<' ValueList '>'
483 SubClassReference TGParser::
484 ParseSubClassReference(Record *CurRec, bool isDefm) {
485 SubClassReference Result;
486 Result.RefLoc = Lex.getLoc();
489 Result.Rec = ParseDefmID();
491 Result.Rec = ParseClassID();
492 if (Result.Rec == 0) return Result;
494 // If there is no template arg list, we're done.
495 if (Lex.getCode() != tgtok::less)
497 Lex.Lex(); // Eat the '<'
499 if (Lex.getCode() == tgtok::greater) {
500 TokError("subclass reference requires a non-empty list of template values");
505 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
506 if (Result.TemplateArgs.empty()) {
507 Result.Rec = 0; // Error parsing value list.
511 if (Lex.getCode() != tgtok::greater) {
512 TokError("expected '>' in template value list");
521 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
522 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
523 /// Record* on error.
525 /// SubMultiClassRef ::= MultiClassID
526 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
528 SubMultiClassReference TGParser::
529 ParseSubMultiClassReference(MultiClass *CurMC) {
530 SubMultiClassReference Result;
531 Result.RefLoc = Lex.getLoc();
533 Result.MC = ParseMultiClassID();
534 if (Result.MC == 0) return Result;
536 // If there is no template arg list, we're done.
537 if (Lex.getCode() != tgtok::less)
539 Lex.Lex(); // Eat the '<'
541 if (Lex.getCode() == tgtok::greater) {
542 TokError("subclass reference requires a non-empty list of template values");
547 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
548 if (Result.TemplateArgs.empty()) {
549 Result.MC = 0; // Error parsing value list.
553 if (Lex.getCode() != tgtok::greater) {
554 TokError("expected '>' in template value list");
563 /// ParseRangePiece - Parse a bit/value range.
564 /// RangePiece ::= INTVAL
565 /// RangePiece ::= INTVAL '-' INTVAL
566 /// RangePiece ::= INTVAL INTVAL
567 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
568 if (Lex.getCode() != tgtok::IntVal) {
569 TokError("expected integer or bitrange");
572 int64_t Start = Lex.getCurIntVal();
576 return TokError("invalid range, cannot be negative");
578 switch (Lex.Lex()) { // eat first character.
580 Ranges.push_back(Start);
583 if (Lex.Lex() != tgtok::IntVal) {
584 TokError("expected integer value as end of range");
587 End = Lex.getCurIntVal();
590 End = -Lex.getCurIntVal();
594 return TokError("invalid range, cannot be negative");
599 for (; Start <= End; ++Start)
600 Ranges.push_back(Start);
602 for (; Start >= End; --Start)
603 Ranges.push_back(Start);
608 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
610 /// RangeList ::= RangePiece (',' RangePiece)*
612 std::vector<unsigned> TGParser::ParseRangeList() {
613 std::vector<unsigned> Result;
615 // Parse the first piece.
616 if (ParseRangePiece(Result))
617 return std::vector<unsigned>();
618 while (Lex.getCode() == tgtok::comma) {
619 Lex.Lex(); // Eat the comma.
621 // Parse the next range piece.
622 if (ParseRangePiece(Result))
623 return std::vector<unsigned>();
628 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
629 /// OptionalRangeList ::= '<' RangeList '>'
630 /// OptionalRangeList ::= /*empty*/
631 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
632 if (Lex.getCode() != tgtok::less)
635 SMLoc StartLoc = Lex.getLoc();
636 Lex.Lex(); // eat the '<'
638 // Parse the range list.
639 Ranges = ParseRangeList();
640 if (Ranges.empty()) return true;
642 if (Lex.getCode() != tgtok::greater) {
643 TokError("expected '>' at end of range list");
644 return Error(StartLoc, "to match this '<'");
646 Lex.Lex(); // eat the '>'.
650 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
651 /// OptionalBitList ::= '{' RangeList '}'
652 /// OptionalBitList ::= /*empty*/
653 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
654 if (Lex.getCode() != tgtok::l_brace)
657 SMLoc StartLoc = Lex.getLoc();
658 Lex.Lex(); // eat the '{'
660 // Parse the range list.
661 Ranges = ParseRangeList();
662 if (Ranges.empty()) return true;
664 if (Lex.getCode() != tgtok::r_brace) {
665 TokError("expected '}' at end of bit list");
666 return Error(StartLoc, "to match this '{'");
668 Lex.Lex(); // eat the '}'.
673 /// ParseType - Parse and return a tblgen type. This returns null on error.
675 /// Type ::= STRING // string type
676 /// Type ::= CODE // code type
677 /// Type ::= BIT // bit type
678 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
679 /// Type ::= INT // int type
680 /// Type ::= LIST '<' Type '>' // list<x> type
681 /// Type ::= DAG // dag type
682 /// Type ::= ClassID // Record Type
684 RecTy *TGParser::ParseType() {
685 switch (Lex.getCode()) {
686 default: TokError("Unknown token when expecting a type"); return 0;
687 case tgtok::String: Lex.Lex(); return StringRecTy::get();
688 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
689 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
690 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
691 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
693 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
696 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
697 TokError("expected '<' after bits type");
700 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
701 TokError("expected integer in bits<n> type");
704 uint64_t Val = Lex.getCurIntVal();
705 if (Lex.Lex() != tgtok::greater) { // Eat count.
706 TokError("expected '>' at end of bits<n> type");
709 Lex.Lex(); // Eat '>'
710 return BitsRecTy::get(Val);
713 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
714 TokError("expected '<' after list type");
717 Lex.Lex(); // Eat '<'
718 RecTy *SubType = ParseType();
719 if (SubType == 0) return 0;
721 if (Lex.getCode() != tgtok::greater) {
722 TokError("expected '>' at end of list<ty> type");
725 Lex.Lex(); // Eat '>'
726 return ListRecTy::get(SubType);
731 /// ParseIDValue - Parse an ID as a value and decode what it means.
733 /// IDValue ::= ID [def local value]
734 /// IDValue ::= ID [def template arg]
735 /// IDValue ::= ID [multiclass local value]
736 /// IDValue ::= ID [multiclass template argument]
737 /// IDValue ::= ID [def name]
739 Init *TGParser::ParseIDValue(Record *CurRec, IDParseMode Mode) {
740 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
741 std::string Name = Lex.getCurStrVal();
742 SMLoc Loc = Lex.getLoc();
744 return ParseIDValue(CurRec, Name, Loc);
747 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
748 /// has already been read.
749 Init *TGParser::ParseIDValue(Record *CurRec,
750 const std::string &Name, SMLoc NameLoc,
753 if (const RecordVal *RV = CurRec->getValue(Name))
754 return VarInit::get(Name, RV->getType());
756 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
759 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
762 if (CurRec->isTemplateArg(TemplateArgName)) {
763 const RecordVal *RV = CurRec->getValue(TemplateArgName);
764 assert(RV && "Template arg doesn't exist??");
765 return VarInit::get(TemplateArgName, RV->getType());
770 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
773 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
774 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
775 assert(RV && "Template arg doesn't exist??");
776 return VarInit::get(MCName, RV->getType());
780 // If this is in a foreach loop, make sure it's not a loop iterator
781 for (LoopVector::iterator i = Loops.begin(), iend = Loops.end();
784 VarInit *IterVar = dynamic_cast<VarInit *>(i->IterVar);
785 if (IterVar && IterVar->getName() == Name)
789 if (Mode == ParseNameMode)
790 return StringInit::get(Name);
792 if (Record *D = Records.getDef(Name))
793 return DefInit::get(D);
795 if (Mode == ParseValueMode) {
796 Error(NameLoc, "Variable not defined: '" + Name + "'");
800 return StringInit::get(Name);
803 /// ParseOperation - Parse an operator. This returns null on error.
805 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
807 Init *TGParser::ParseOperation(Record *CurRec) {
808 switch (Lex.getCode()) {
810 TokError("unknown operation");
815 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
816 UnOpInit::UnaryOp Code;
819 switch (Lex.getCode()) {
820 default: llvm_unreachable("Unhandled code!");
822 Lex.Lex(); // eat the operation
823 Code = UnOpInit::CAST;
825 Type = ParseOperatorType();
828 TokError("did not get type for unary operator");
834 Lex.Lex(); // eat the operation
835 Code = UnOpInit::HEAD;
838 Lex.Lex(); // eat the operation
839 Code = UnOpInit::TAIL;
842 Lex.Lex(); // eat the operation
843 Code = UnOpInit::EMPTY;
844 Type = IntRecTy::get();
847 if (Lex.getCode() != tgtok::l_paren) {
848 TokError("expected '(' after unary operator");
851 Lex.Lex(); // eat the '('
853 Init *LHS = ParseValue(CurRec);
854 if (LHS == 0) return 0;
856 if (Code == UnOpInit::HEAD
857 || Code == UnOpInit::TAIL
858 || Code == UnOpInit::EMPTY) {
859 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
860 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
861 TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
862 if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
863 TokError("expected list or string type argument in unary operator");
867 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
868 StringRecTy *SType = dynamic_cast<StringRecTy*>(LHSt->getType());
869 if (LType == 0 && SType == 0) {
870 TokError("expected list or string type argumnet in unary operator");
875 if (Code == UnOpInit::HEAD
876 || Code == UnOpInit::TAIL) {
877 if (LHSl == 0 && LHSt == 0) {
878 TokError("expected list type argumnet in unary operator");
882 if (LHSl && LHSl->getSize() == 0) {
883 TokError("empty list argument in unary operator");
887 Init *Item = LHSl->getElement(0);
888 TypedInit *Itemt = dynamic_cast<TypedInit*>(Item);
890 TokError("untyped list element in unary operator");
893 if (Code == UnOpInit::HEAD) {
894 Type = Itemt->getType();
896 Type = ListRecTy::get(Itemt->getType());
899 assert(LHSt && "expected list type argument in unary operator");
900 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
902 TokError("expected list type argumnet in unary operator");
905 if (Code == UnOpInit::HEAD) {
906 Type = LType->getElementType();
914 if (Lex.getCode() != tgtok::r_paren) {
915 TokError("expected ')' in unary operator");
918 Lex.Lex(); // eat the ')'
919 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
927 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
928 tgtok::TokKind OpTok = Lex.getCode();
929 SMLoc OpLoc = Lex.getLoc();
930 Lex.Lex(); // eat the operation
932 BinOpInit::BinaryOp Code;
936 default: llvm_unreachable("Unhandled code!");
937 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
938 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
939 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
940 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
941 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
942 case tgtok::XStrConcat:
943 Code = BinOpInit::STRCONCAT;
944 Type = StringRecTy::get();
948 if (Lex.getCode() != tgtok::l_paren) {
949 TokError("expected '(' after binary operator");
952 Lex.Lex(); // eat the '('
954 SmallVector<Init*, 2> InitList;
956 InitList.push_back(ParseValue(CurRec));
957 if (InitList.back() == 0) return 0;
959 while (Lex.getCode() == tgtok::comma) {
960 Lex.Lex(); // eat the ','
962 InitList.push_back(ParseValue(CurRec));
963 if (InitList.back() == 0) return 0;
966 if (Lex.getCode() != tgtok::r_paren) {
967 TokError("expected ')' in operator");
970 Lex.Lex(); // eat the ')'
972 // We allow multiple operands to associative operators like !strconcat as
973 // shorthand for nesting them.
974 if (Code == BinOpInit::STRCONCAT) {
975 while (InitList.size() > 2) {
976 Init *RHS = InitList.pop_back_val();
977 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
978 ->Fold(CurRec, CurMultiClass);
979 InitList.back() = RHS;
983 if (InitList.size() == 2)
984 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
985 ->Fold(CurRec, CurMultiClass);
987 Error(OpLoc, "expected two operands to operator");
992 case tgtok::XForEach:
993 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
994 TernOpInit::TernaryOp Code;
997 tgtok::TokKind LexCode = Lex.getCode();
998 Lex.Lex(); // eat the operation
1000 default: llvm_unreachable("Unhandled code!");
1002 Code = TernOpInit::IF;
1004 case tgtok::XForEach:
1005 Code = TernOpInit::FOREACH;
1008 Code = TernOpInit::SUBST;
1011 if (Lex.getCode() != tgtok::l_paren) {
1012 TokError("expected '(' after ternary operator");
1015 Lex.Lex(); // eat the '('
1017 Init *LHS = ParseValue(CurRec);
1018 if (LHS == 0) return 0;
1020 if (Lex.getCode() != tgtok::comma) {
1021 TokError("expected ',' in ternary operator");
1024 Lex.Lex(); // eat the ','
1026 Init *MHS = ParseValue(CurRec);
1027 if (MHS == 0) return 0;
1029 if (Lex.getCode() != tgtok::comma) {
1030 TokError("expected ',' in ternary operator");
1033 Lex.Lex(); // eat the ','
1035 Init *RHS = ParseValue(CurRec);
1036 if (RHS == 0) return 0;
1038 if (Lex.getCode() != tgtok::r_paren) {
1039 TokError("expected ')' in binary operator");
1042 Lex.Lex(); // eat the ')'
1045 default: llvm_unreachable("Unhandled code!");
1047 // FIXME: The `!if' operator doesn't handle non-TypedInit well at
1048 // all. This can be made much more robust.
1049 TypedInit *MHSt = dynamic_cast<TypedInit*>(MHS);
1050 TypedInit *RHSt = dynamic_cast<TypedInit*>(RHS);
1055 if (MHSt == 0 && RHSt == 0) {
1056 BitsInit *MHSbits = dynamic_cast<BitsInit*>(MHS);
1057 BitsInit *RHSbits = dynamic_cast<BitsInit*>(RHS);
1059 if (MHSbits && RHSbits &&
1060 MHSbits->getNumBits() == RHSbits->getNumBits()) {
1061 Type = BitRecTy::get();
1064 BitInit *MHSbit = dynamic_cast<BitInit*>(MHS);
1065 BitInit *RHSbit = dynamic_cast<BitInit*>(RHS);
1067 if (MHSbit && RHSbit) {
1068 Type = BitRecTy::get();
1072 } else if (MHSt != 0 && RHSt != 0) {
1073 MHSTy = MHSt->getType();
1074 RHSTy = RHSt->getType();
1077 if (!MHSTy || !RHSTy) {
1078 TokError("could not get type for !if");
1082 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1084 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1087 TokError("inconsistent types for !if");
1092 case tgtok::XForEach: {
1093 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
1095 TokError("could not get type for !foreach");
1098 Type = MHSt->getType();
1101 case tgtok::XSubst: {
1102 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
1104 TokError("could not get type for !subst");
1107 Type = RHSt->getType();
1111 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1117 /// ParseOperatorType - Parse a type for an operator. This returns
1120 /// OperatorType ::= '<' Type '>'
1122 RecTy *TGParser::ParseOperatorType() {
1125 if (Lex.getCode() != tgtok::less) {
1126 TokError("expected type name for operator");
1129 Lex.Lex(); // eat the <
1134 TokError("expected type name for operator");
1138 if (Lex.getCode() != tgtok::greater) {
1139 TokError("expected type name for operator");
1142 Lex.Lex(); // eat the >
1148 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1150 /// SimpleValue ::= IDValue
1151 /// SimpleValue ::= INTVAL
1152 /// SimpleValue ::= STRVAL+
1153 /// SimpleValue ::= CODEFRAGMENT
1154 /// SimpleValue ::= '?'
1155 /// SimpleValue ::= '{' ValueList '}'
1156 /// SimpleValue ::= ID '<' ValueListNE '>'
1157 /// SimpleValue ::= '[' ValueList ']'
1158 /// SimpleValue ::= '(' IDValue DagArgList ')'
1159 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1160 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1161 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1162 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1163 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1165 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1168 switch (Lex.getCode()) {
1169 default: TokError("Unknown token when parsing a value"); break;
1171 // This is a leading paste operation. This is deprecated but
1172 // still exists in some .td files. Ignore it.
1173 Lex.Lex(); // Skip '#'.
1174 return ParseSimpleValue(CurRec, ItemType, Mode);
1175 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1176 case tgtok::StrVal: {
1177 std::string Val = Lex.getCurStrVal();
1180 // Handle multiple consecutive concatenated strings.
1181 while (Lex.getCode() == tgtok::StrVal) {
1182 Val += Lex.getCurStrVal();
1186 R = StringInit::get(Val);
1189 case tgtok::CodeFragment:
1190 R = StringInit::get(Lex.getCurStrVal());
1193 case tgtok::question:
1194 R = UnsetInit::get();
1198 SMLoc NameLoc = Lex.getLoc();
1199 std::string Name = Lex.getCurStrVal();
1200 if (Lex.Lex() != tgtok::less) // consume the Id.
1201 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1203 // Value ::= ID '<' ValueListNE '>'
1204 if (Lex.Lex() == tgtok::greater) {
1205 TokError("expected non-empty value list");
1209 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1210 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1212 Record *Class = Records.getClass(Name);
1214 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1218 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1219 if (ValueList.empty()) return 0;
1221 if (Lex.getCode() != tgtok::greater) {
1222 TokError("expected '>' at end of value list");
1225 Lex.Lex(); // eat the '>'
1227 // Create the new record, set it as CurRec temporarily.
1228 static unsigned AnonCounter = 0;
1229 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),
1232 SubClassReference SCRef;
1233 SCRef.RefLoc = NameLoc;
1235 SCRef.TemplateArgs = ValueList;
1236 // Add info about the subclass to NewRec.
1237 if (AddSubClass(NewRec, SCRef))
1239 NewRec->resolveReferences();
1240 Records.addDef(NewRec);
1242 // The result of the expression is a reference to the new record.
1243 return DefInit::get(NewRec);
1245 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1246 SMLoc BraceLoc = Lex.getLoc();
1247 Lex.Lex(); // eat the '{'
1248 std::vector<Init*> Vals;
1250 if (Lex.getCode() != tgtok::r_brace) {
1251 Vals = ParseValueList(CurRec);
1252 if (Vals.empty()) return 0;
1254 if (Lex.getCode() != tgtok::r_brace) {
1255 TokError("expected '}' at end of bit list value");
1258 Lex.Lex(); // eat the '}'
1260 SmallVector<Init *, 16> NewBits(Vals.size());
1262 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1263 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1265 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1266 ") is not convertable to a bit");
1269 NewBits[Vals.size()-i-1] = Bit;
1271 return BitsInit::get(NewBits);
1273 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1274 Lex.Lex(); // eat the '['
1275 std::vector<Init*> Vals;
1277 RecTy *DeducedEltTy = 0;
1278 ListRecTy *GivenListTy = 0;
1280 if (ItemType != 0) {
1281 ListRecTy *ListType = dynamic_cast<ListRecTy*>(ItemType);
1282 if (ListType == 0) {
1283 std::stringstream s;
1284 s << "Type mismatch for list, expected list type, got "
1285 << ItemType->getAsString();
1289 GivenListTy = ListType;
1292 if (Lex.getCode() != tgtok::r_square) {
1293 Vals = ParseValueList(CurRec, 0,
1294 GivenListTy ? GivenListTy->getElementType() : 0);
1295 if (Vals.empty()) return 0;
1297 if (Lex.getCode() != tgtok::r_square) {
1298 TokError("expected ']' at end of list value");
1301 Lex.Lex(); // eat the ']'
1303 RecTy *GivenEltTy = 0;
1304 if (Lex.getCode() == tgtok::less) {
1305 // Optional list element type
1306 Lex.Lex(); // eat the '<'
1308 GivenEltTy = ParseType();
1309 if (GivenEltTy == 0) {
1310 // Couldn't parse element type
1314 if (Lex.getCode() != tgtok::greater) {
1315 TokError("expected '>' at end of list element type");
1318 Lex.Lex(); // eat the '>'
1323 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1326 TypedInit *TArg = dynamic_cast<TypedInit*>(*i);
1328 TokError("Untyped list element");
1332 EltTy = resolveTypes(EltTy, TArg->getType());
1334 TokError("Incompatible types in list elements");
1338 EltTy = TArg->getType();
1342 if (GivenEltTy != 0) {
1344 // Verify consistency
1345 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1346 TokError("Incompatible types in list elements");
1354 if (ItemType == 0) {
1355 TokError("No type for list");
1358 DeducedEltTy = GivenListTy->getElementType();
1360 // Make sure the deduced type is compatible with the given type
1362 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1363 TokError("Element type mismatch for list");
1367 DeducedEltTy = EltTy;
1370 return ListInit::get(Vals, DeducedEltTy);
1372 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1373 Lex.Lex(); // eat the '('
1374 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1375 TokError("expected identifier in dag init");
1379 Init *Operator = ParseValue(CurRec);
1380 if (Operator == 0) return 0;
1382 // If the operator name is present, parse it.
1383 std::string OperatorName;
1384 if (Lex.getCode() == tgtok::colon) {
1385 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1386 TokError("expected variable name in dag operator");
1389 OperatorName = Lex.getCurStrVal();
1390 Lex.Lex(); // eat the VarName.
1393 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1394 if (Lex.getCode() != tgtok::r_paren) {
1395 DagArgs = ParseDagArgList(CurRec);
1396 if (DagArgs.empty()) return 0;
1399 if (Lex.getCode() != tgtok::r_paren) {
1400 TokError("expected ')' in dag init");
1403 Lex.Lex(); // eat the ')'
1405 return DagInit::get(Operator, OperatorName, DagArgs);
1411 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1412 case tgtok::XConcat:
1417 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1419 case tgtok::XForEach:
1420 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1421 return ParseOperation(CurRec);
1428 /// ParseValue - Parse a tblgen value. This returns null on error.
1430 /// Value ::= SimpleValue ValueSuffix*
1431 /// ValueSuffix ::= '{' BitList '}'
1432 /// ValueSuffix ::= '[' BitList ']'
1433 /// ValueSuffix ::= '.' ID
1435 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1436 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1437 if (Result == 0) return 0;
1439 // Parse the suffixes now if present.
1441 switch (Lex.getCode()) {
1442 default: return Result;
1443 case tgtok::l_brace: {
1444 if (Mode == ParseNameMode || Mode == ParseForeachMode)
1445 // This is the beginning of the object body.
1448 SMLoc CurlyLoc = Lex.getLoc();
1449 Lex.Lex(); // eat the '{'
1450 std::vector<unsigned> Ranges = ParseRangeList();
1451 if (Ranges.empty()) return 0;
1453 // Reverse the bitlist.
1454 std::reverse(Ranges.begin(), Ranges.end());
1455 Result = Result->convertInitializerBitRange(Ranges);
1457 Error(CurlyLoc, "Invalid bit range for value");
1462 if (Lex.getCode() != tgtok::r_brace) {
1463 TokError("expected '}' at end of bit range list");
1469 case tgtok::l_square: {
1470 SMLoc SquareLoc = Lex.getLoc();
1471 Lex.Lex(); // eat the '['
1472 std::vector<unsigned> Ranges = ParseRangeList();
1473 if (Ranges.empty()) return 0;
1475 Result = Result->convertInitListSlice(Ranges);
1477 Error(SquareLoc, "Invalid range for list slice");
1482 if (Lex.getCode() != tgtok::r_square) {
1483 TokError("expected ']' at end of list slice");
1490 if (Lex.Lex() != tgtok::Id) { // eat the .
1491 TokError("expected field identifier after '.'");
1494 if (!Result->getFieldType(Lex.getCurStrVal())) {
1495 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1496 Result->getAsString() + "'");
1499 Result = FieldInit::get(Result, Lex.getCurStrVal());
1500 Lex.Lex(); // eat field name
1504 SMLoc PasteLoc = Lex.getLoc();
1506 // Create a !strconcat() operation, first casting each operand to
1507 // a string if necessary.
1509 TypedInit *LHS = dynamic_cast<TypedInit *>(Result);
1511 Error(PasteLoc, "LHS of paste is not typed!");
1515 if (LHS->getType() != StringRecTy::get()) {
1516 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1521 Lex.Lex(); // Eat the '#'.
1522 switch (Lex.getCode()) {
1525 case tgtok::l_brace:
1526 // These are all of the tokens that can begin an object body.
1527 // Some of these can also begin values but we disallow those cases
1528 // because they are unlikely to be useful.
1530 // Trailing paste, concat with an empty string.
1531 RHS = StringInit::get("");
1535 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1536 RHS = dynamic_cast<TypedInit *>(RHSResult);
1538 Error(PasteLoc, "RHS of paste is not typed!");
1542 if (RHS->getType() != StringRecTy::get()) {
1543 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1549 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1550 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1556 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1558 /// ParseDagArgList ::= Value (':' VARNAME)?
1559 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1560 std::vector<std::pair<llvm::Init*, std::string> >
1561 TGParser::ParseDagArgList(Record *CurRec) {
1562 std::vector<std::pair<llvm::Init*, std::string> > Result;
1565 Init *Val = ParseValue(CurRec);
1566 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1568 // If the variable name is present, add it.
1569 std::string VarName;
1570 if (Lex.getCode() == tgtok::colon) {
1571 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1572 TokError("expected variable name in dag literal");
1573 return std::vector<std::pair<llvm::Init*, std::string> >();
1575 VarName = Lex.getCurStrVal();
1576 Lex.Lex(); // eat the VarName.
1579 Result.push_back(std::make_pair(Val, VarName));
1581 if (Lex.getCode() != tgtok::comma) break;
1582 Lex.Lex(); // eat the ','
1589 /// ParseValueList - Parse a comma separated list of values, returning them as a
1590 /// vector. Note that this always expects to be able to parse at least one
1591 /// value. It returns an empty list if this is not possible.
1593 /// ValueList ::= Value (',' Value)
1595 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1597 std::vector<Init*> Result;
1598 RecTy *ItemType = EltTy;
1599 unsigned int ArgN = 0;
1600 if (ArgsRec != 0 && EltTy == 0) {
1601 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1602 if (!TArgs.size()) {
1603 TokError("template argument provided to non-template class");
1604 return std::vector<Init*>();
1606 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1608 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1611 assert(RV && "Template argument record not found??");
1612 ItemType = RV->getType();
1615 Result.push_back(ParseValue(CurRec, ItemType));
1616 if (Result.back() == 0) return std::vector<Init*>();
1618 while (Lex.getCode() == tgtok::comma) {
1619 Lex.Lex(); // Eat the comma
1621 if (ArgsRec != 0 && EltTy == 0) {
1622 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1623 if (ArgN >= TArgs.size()) {
1624 TokError("too many template arguments");
1625 return std::vector<Init*>();
1627 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1628 assert(RV && "Template argument record not found??");
1629 ItemType = RV->getType();
1632 Result.push_back(ParseValue(CurRec, ItemType));
1633 if (Result.back() == 0) return std::vector<Init*>();
1640 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1641 /// empty string on error. This can happen in a number of different context's,
1642 /// including within a def or in the template args for a def (which which case
1643 /// CurRec will be non-null) and within the template args for a multiclass (in
1644 /// which case CurRec will be null, but CurMultiClass will be set). This can
1645 /// also happen within a def that is within a multiclass, which will set both
1646 /// CurRec and CurMultiClass.
1648 /// Declaration ::= FIELD? Type ID ('=' Value)?
1650 Init *TGParser::ParseDeclaration(Record *CurRec,
1651 bool ParsingTemplateArgs) {
1652 // Read the field prefix if present.
1653 bool HasField = Lex.getCode() == tgtok::Field;
1654 if (HasField) Lex.Lex();
1656 RecTy *Type = ParseType();
1657 if (Type == 0) return 0;
1659 if (Lex.getCode() != tgtok::Id) {
1660 TokError("Expected identifier in declaration");
1664 SMLoc IdLoc = Lex.getLoc();
1665 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1668 if (ParsingTemplateArgs) {
1670 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1672 assert(CurMultiClass);
1675 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1680 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1683 // If a value is present, parse it.
1684 if (Lex.getCode() == tgtok::equal) {
1686 SMLoc ValLoc = Lex.getLoc();
1687 Init *Val = ParseValue(CurRec, Type);
1689 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1696 /// ParseForeachDeclaration - Read a foreach declaration, returning
1697 /// the name of the declared object or a NULL Init on error. Return
1698 /// the name of the parsed initializer list through ForeachListName.
1700 /// ForeachDeclaration ::= ID '=' Value
1702 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1703 if (Lex.getCode() != tgtok::Id) {
1704 TokError("Expected identifier in foreach declaration");
1708 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1711 // If a value is present, parse it.
1712 if (Lex.getCode() != tgtok::equal) {
1713 TokError("Expected '=' in foreach declaration");
1716 Lex.Lex(); // Eat the '='
1718 // Expect a list initializer.
1719 Init *List = ParseSimpleValue(0, 0, ParseForeachMode);
1721 ForeachListValue = dynamic_cast<ListInit*>(List);
1722 if (ForeachListValue == 0) {
1723 TokError("Expected a Value list");
1727 RecTy *ValueType = ForeachListValue->getType();
1728 ListRecTy *ListType = dynamic_cast<ListRecTy *>(ValueType);
1729 if (ListType == 0) {
1730 TokError("Value list is not of list type");
1734 RecTy *IterType = ListType->getElementType();
1735 VarInit *IterVar = VarInit::get(DeclName, IterType);
1740 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1741 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1742 /// template args for a def, which may or may not be in a multiclass. If null,
1743 /// these are the template args for a multiclass.
1745 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1747 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1748 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1749 Lex.Lex(); // eat the '<'
1751 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1753 // Read the first declaration.
1754 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1758 TheRecToAddTo->addTemplateArg(TemplArg);
1760 while (Lex.getCode() == tgtok::comma) {
1761 Lex.Lex(); // eat the ','
1763 // Read the following declarations.
1764 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1767 TheRecToAddTo->addTemplateArg(TemplArg);
1770 if (Lex.getCode() != tgtok::greater)
1771 return TokError("expected '>' at end of template argument list");
1772 Lex.Lex(); // eat the '>'.
1777 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1779 /// BodyItem ::= Declaration ';'
1780 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1781 bool TGParser::ParseBodyItem(Record *CurRec) {
1782 if (Lex.getCode() != tgtok::Let) {
1783 if (ParseDeclaration(CurRec, false) == 0)
1786 if (Lex.getCode() != tgtok::semi)
1787 return TokError("expected ';' after declaration");
1792 // LET ID OptionalRangeList '=' Value ';'
1793 if (Lex.Lex() != tgtok::Id)
1794 return TokError("expected field identifier after let");
1796 SMLoc IdLoc = Lex.getLoc();
1797 std::string FieldName = Lex.getCurStrVal();
1798 Lex.Lex(); // eat the field name.
1800 std::vector<unsigned> BitList;
1801 if (ParseOptionalBitList(BitList))
1803 std::reverse(BitList.begin(), BitList.end());
1805 if (Lex.getCode() != tgtok::equal)
1806 return TokError("expected '=' in let expression");
1807 Lex.Lex(); // eat the '='.
1809 RecordVal *Field = CurRec->getValue(FieldName);
1811 return TokError("Value '" + FieldName + "' unknown!");
1813 RecTy *Type = Field->getType();
1815 Init *Val = ParseValue(CurRec, Type);
1816 if (Val == 0) return true;
1818 if (Lex.getCode() != tgtok::semi)
1819 return TokError("expected ';' after let expression");
1822 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1825 /// ParseBody - Read the body of a class or def. Return true on error, false on
1829 /// Body ::= '{' BodyList '}'
1830 /// BodyList BodyItem*
1832 bool TGParser::ParseBody(Record *CurRec) {
1833 // If this is a null definition, just eat the semi and return.
1834 if (Lex.getCode() == tgtok::semi) {
1839 if (Lex.getCode() != tgtok::l_brace)
1840 return TokError("Expected ';' or '{' to start body");
1844 while (Lex.getCode() != tgtok::r_brace)
1845 if (ParseBodyItem(CurRec))
1853 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1854 /// optional ClassList followed by a Body. CurRec is the current def or class
1855 /// that is being parsed.
1857 /// ObjectBody ::= BaseClassList Body
1858 /// BaseClassList ::= /*empty*/
1859 /// BaseClassList ::= ':' BaseClassListNE
1860 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1862 bool TGParser::ParseObjectBody(Record *CurRec) {
1863 // If there is a baseclass list, read it.
1864 if (Lex.getCode() == tgtok::colon) {
1867 // Read all of the subclasses.
1868 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1871 if (SubClass.Rec == 0) return true;
1874 if (AddSubClass(CurRec, SubClass))
1877 if (Lex.getCode() != tgtok::comma) break;
1878 Lex.Lex(); // eat ','.
1879 SubClass = ParseSubClassReference(CurRec, false);
1883 // Process any variables on the let stack.
1884 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1885 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1886 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1887 LetStack[i][j].Bits, LetStack[i][j].Value))
1890 return ParseBody(CurRec);
1893 /// ParseDef - Parse and return a top level or multiclass def, return the record
1894 /// corresponding to it. This returns null on error.
1896 /// DefInst ::= DEF ObjectName ObjectBody
1898 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1899 SMLoc DefLoc = Lex.getLoc();
1900 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1901 Lex.Lex(); // Eat the 'def' token.
1903 // Parse ObjectName and make a record for it.
1904 Record *CurRec = new Record(ParseObjectName(CurMultiClass), DefLoc, Records);
1906 if (!CurMultiClass) {
1907 // Top-level def definition.
1909 // Ensure redefinition doesn't happen.
1910 if (Records.getDef(CurRec->getNameInitAsString())) {
1911 Error(DefLoc, "def '" + CurRec->getNameInitAsString()
1912 + "' already defined");
1915 Records.addDef(CurRec);
1917 // Otherwise, a def inside a multiclass, add it to the multiclass.
1918 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1919 if (CurMultiClass->DefPrototypes[i]->getNameInit()
1920 == CurRec->getNameInit()) {
1921 Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
1922 "' already defined in this multiclass!");
1925 CurMultiClass->DefPrototypes.push_back(CurRec);
1928 if (ParseObjectBody(CurRec))
1931 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1932 // See Record::setName(). This resolve step will see any new name
1933 // for the def that might have been created when resolving
1934 // inheritance, values and arguments above.
1935 CurRec->resolveReferences();
1937 // If ObjectBody has template arguments, it's an error.
1938 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1940 if (CurMultiClass) {
1941 // Copy the template arguments for the multiclass into the def.
1942 const std::vector<Init *> &TArgs =
1943 CurMultiClass->Rec.getTemplateArgs();
1945 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1946 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1947 assert(RV && "Template arg doesn't exist?");
1948 CurRec->addValue(*RV);
1952 if (ProcessForeachDefs(CurRec, DefLoc)) {
1954 "Could not process loops for def" + CurRec->getNameInitAsString());
1961 /// ParseForeach - Parse a for statement. Return the record corresponding
1962 /// to it. This returns true on error.
1964 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
1965 /// Foreach ::= FOREACH Declaration IN Object
1967 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
1968 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
1969 Lex.Lex(); // Eat the 'for' token.
1971 // Make a temporary object to record items associated with the for
1973 ListInit *ListValue = 0;
1974 VarInit *IterName = ParseForeachDeclaration(ListValue);
1976 return TokError("expected declaration in for");
1978 if (Lex.getCode() != tgtok::In)
1979 return TokError("Unknown tok");
1980 Lex.Lex(); // Eat the in
1982 // Create a loop object and remember it.
1983 Loops.push_back(ForeachLoop(IterName, ListValue));
1985 if (Lex.getCode() != tgtok::l_brace) {
1986 // FOREACH Declaration IN Object
1987 if (ParseObject(CurMultiClass))
1991 SMLoc BraceLoc = Lex.getLoc();
1992 // Otherwise, this is a group foreach.
1993 Lex.Lex(); // eat the '{'.
1995 // Parse the object list.
1996 if (ParseObjectList(CurMultiClass))
1999 if (Lex.getCode() != tgtok::r_brace) {
2000 TokError("expected '}' at end of foreach command");
2001 return Error(BraceLoc, "to match this '{'");
2003 Lex.Lex(); // Eat the }
2006 // We've processed everything in this loop.
2012 /// ParseClass - Parse a tblgen class definition.
2014 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2016 bool TGParser::ParseClass() {
2017 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2020 if (Lex.getCode() != tgtok::Id)
2021 return TokError("expected class name after 'class' keyword");
2023 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2025 // If the body was previously defined, this is an error.
2026 if (CurRec->getValues().size() > 1 || // Account for NAME.
2027 !CurRec->getSuperClasses().empty() ||
2028 !CurRec->getTemplateArgs().empty())
2029 return TokError("Class '" + CurRec->getNameInitAsString()
2030 + "' already defined");
2032 // If this is the first reference to this class, create and add it.
2033 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
2034 Records.addClass(CurRec);
2036 Lex.Lex(); // eat the name.
2038 // If there are template args, parse them.
2039 if (Lex.getCode() == tgtok::less)
2040 if (ParseTemplateArgList(CurRec))
2043 // Finally, parse the object body.
2044 return ParseObjectBody(CurRec);
2047 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2050 /// LetList ::= LetItem (',' LetItem)*
2051 /// LetItem ::= ID OptionalRangeList '=' Value
2053 std::vector<LetRecord> TGParser::ParseLetList() {
2054 std::vector<LetRecord> Result;
2057 if (Lex.getCode() != tgtok::Id) {
2058 TokError("expected identifier in let definition");
2059 return std::vector<LetRecord>();
2061 std::string Name = Lex.getCurStrVal();
2062 SMLoc NameLoc = Lex.getLoc();
2063 Lex.Lex(); // Eat the identifier.
2065 // Check for an optional RangeList.
2066 std::vector<unsigned> Bits;
2067 if (ParseOptionalRangeList(Bits))
2068 return std::vector<LetRecord>();
2069 std::reverse(Bits.begin(), Bits.end());
2071 if (Lex.getCode() != tgtok::equal) {
2072 TokError("expected '=' in let expression");
2073 return std::vector<LetRecord>();
2075 Lex.Lex(); // eat the '='.
2077 Init *Val = ParseValue(0);
2078 if (Val == 0) return std::vector<LetRecord>();
2080 // Now that we have everything, add the record.
2081 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2083 if (Lex.getCode() != tgtok::comma)
2085 Lex.Lex(); // eat the comma.
2089 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2090 /// different related productions. This works inside multiclasses too.
2092 /// Object ::= LET LetList IN '{' ObjectList '}'
2093 /// Object ::= LET LetList IN Object
2095 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2096 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2099 // Add this entry to the let stack.
2100 std::vector<LetRecord> LetInfo = ParseLetList();
2101 if (LetInfo.empty()) return true;
2102 LetStack.push_back(LetInfo);
2104 if (Lex.getCode() != tgtok::In)
2105 return TokError("expected 'in' at end of top-level 'let'");
2108 // If this is a scalar let, just handle it now
2109 if (Lex.getCode() != tgtok::l_brace) {
2110 // LET LetList IN Object
2111 if (ParseObject(CurMultiClass))
2113 } else { // Object ::= LETCommand '{' ObjectList '}'
2114 SMLoc BraceLoc = Lex.getLoc();
2115 // Otherwise, this is a group let.
2116 Lex.Lex(); // eat the '{'.
2118 // Parse the object list.
2119 if (ParseObjectList(CurMultiClass))
2122 if (Lex.getCode() != tgtok::r_brace) {
2123 TokError("expected '}' at end of top level let command");
2124 return Error(BraceLoc, "to match this '{'");
2129 // Outside this let scope, this let block is not active.
2130 LetStack.pop_back();
2134 /// ParseMultiClass - Parse a multiclass definition.
2136 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2137 /// ':' BaseMultiClassList '{' MultiClassDef+ '}'
2139 bool TGParser::ParseMultiClass() {
2140 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2141 Lex.Lex(); // Eat the multiclass token.
2143 if (Lex.getCode() != tgtok::Id)
2144 return TokError("expected identifier after multiclass for name");
2145 std::string Name = Lex.getCurStrVal();
2147 if (MultiClasses.count(Name))
2148 return TokError("multiclass '" + Name + "' already defined");
2150 CurMultiClass = MultiClasses[Name] = new MultiClass(Name,
2151 Lex.getLoc(), Records);
2152 Lex.Lex(); // Eat the identifier.
2154 // If there are template args, parse them.
2155 if (Lex.getCode() == tgtok::less)
2156 if (ParseTemplateArgList(0))
2159 bool inherits = false;
2161 // If there are submulticlasses, parse them.
2162 if (Lex.getCode() == tgtok::colon) {
2167 // Read all of the submulticlasses.
2168 SubMultiClassReference SubMultiClass =
2169 ParseSubMultiClassReference(CurMultiClass);
2172 if (SubMultiClass.MC == 0) return true;
2175 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2178 if (Lex.getCode() != tgtok::comma) break;
2179 Lex.Lex(); // eat ','.
2180 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2184 if (Lex.getCode() != tgtok::l_brace) {
2186 return TokError("expected '{' in multiclass definition");
2187 else if (Lex.getCode() != tgtok::semi)
2188 return TokError("expected ';' in multiclass definition");
2190 Lex.Lex(); // eat the ';'.
2192 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2193 return TokError("multiclass must contain at least one def");
2195 while (Lex.getCode() != tgtok::r_brace) {
2196 switch (Lex.getCode()) {
2198 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2202 case tgtok::Foreach:
2203 if (ParseObject(CurMultiClass))
2208 Lex.Lex(); // eat the '}'.
2216 InstantiateMulticlassDef(MultiClass &MC,
2219 SMLoc DefmPrefixLoc) {
2220 // We need to preserve DefProto so it can be reused for later
2221 // instantiations, so create a new Record to inherit from it.
2223 // Add in the defm name. If the defm prefix is empty, give each
2224 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2225 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2228 if (DefmPrefix == 0)
2229 DefmPrefix = StringInit::get(GetNewAnonymousName());
2231 Init *DefName = DefProto->getNameInit();
2233 StringInit *DefNameString = dynamic_cast<StringInit *>(DefName);
2235 if (DefNameString != 0) {
2236 // We have a fully expanded string so there are no operators to
2237 // resolve. We should concatenate the given prefix and name.
2239 BinOpInit::get(BinOpInit::STRCONCAT,
2240 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2241 StringRecTy::get())->Fold(DefProto, &MC),
2242 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2245 Record *CurRec = new Record(DefName, DefmPrefixLoc, Records);
2247 SubClassReference Ref;
2248 Ref.RefLoc = DefmPrefixLoc;
2250 AddSubClass(CurRec, Ref);
2252 if (DefNameString == 0) {
2253 // We must resolve references to NAME.
2254 if (SetValue(CurRec, Ref.RefLoc, "NAME", std::vector<unsigned>(),
2256 Error(DefmPrefixLoc, "Could not resolve "
2257 + CurRec->getNameInitAsString() + ":NAME to '"
2258 + DefmPrefix->getAsUnquotedString() + "'");
2262 RecordVal *DefNameRV = CurRec->getValue("NAME");
2263 CurRec->resolveReferencesTo(DefNameRV);
2266 if (!CurMultiClass) {
2267 // We do this after resolving NAME because before resolution, many
2268 // multiclass defs will have the same name expression. If we are
2269 // currently in a multiclass, it means this defm appears inside a
2270 // multiclass and its name won't be fully resolvable until we see
2271 // the top-level defm. Therefore, we don't add this to the
2272 // RecordKeeper at this point. If we did we could get duplicate
2273 // defs as more than one probably refers to NAME or some other
2274 // common internal placeholder.
2276 // Ensure redefinition doesn't happen.
2277 if (Records.getDef(CurRec->getNameInitAsString())) {
2278 Error(DefmPrefixLoc, "def '" + CurRec->getNameInitAsString() +
2279 "' already defined, instantiating defm with subdef '" +
2280 DefProto->getNameInitAsString() + "'");
2284 Records.addDef(CurRec);
2290 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2292 SMLoc DefmPrefixLoc,
2294 const std::vector<Init *> &TArgs,
2295 std::vector<Init *> &TemplateVals,
2297 // Loop over all of the template arguments, setting them to the specified
2298 // value or leaving them as the default if necessary.
2299 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2300 // Check if a value is specified for this temp-arg.
2301 if (i < TemplateVals.size()) {
2303 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2308 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2312 CurRec->removeValue(TArgs[i]);
2314 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2315 return Error(SubClassLoc, "value not specified for template argument #"+
2316 utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2317 + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2324 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2327 SMLoc DefmPrefixLoc) {
2328 // If the mdef is inside a 'let' expression, add to each def.
2329 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2330 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2331 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2332 LetStack[i][j].Bits, LetStack[i][j].Value))
2333 return Error(DefmPrefixLoc, "when instantiating this defm");
2335 // Don't create a top level definition for defm inside multiclasses,
2336 // instead, only update the prototypes and bind the template args
2337 // with the new created definition.
2338 if (CurMultiClass) {
2339 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2341 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2342 == CurRec->getNameInit())
2343 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2344 "' already defined in this multiclass!");
2345 CurMultiClass->DefPrototypes.push_back(CurRec);
2347 // Copy the template arguments for the multiclass into the new def.
2348 const std::vector<Init *> &TA =
2349 CurMultiClass->Rec.getTemplateArgs();
2351 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2352 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2353 assert(RV && "Template arg doesn't exist?");
2354 CurRec->addValue(*RV);
2361 /// ParseDefm - Parse the instantiation of a multiclass.
2363 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2365 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2366 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2368 Init *DefmPrefix = 0;
2370 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2371 DefmPrefix = ParseObjectName(CurMultiClass);
2374 SMLoc DefmPrefixLoc = Lex.getLoc();
2375 if (Lex.getCode() != tgtok::colon)
2376 return TokError("expected ':' after defm identifier");
2378 // Keep track of the new generated record definitions.
2379 std::vector<Record*> NewRecDefs;
2381 // This record also inherits from a regular class (non-multiclass)?
2382 bool InheritFromClass = false;
2387 SMLoc SubClassLoc = Lex.getLoc();
2388 SubClassReference Ref = ParseSubClassReference(0, true);
2391 if (Ref.Rec == 0) return true;
2393 // To instantiate a multiclass, we need to first get the multiclass, then
2394 // instantiate each def contained in the multiclass with the SubClassRef
2395 // template parameters.
2396 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2397 assert(MC && "Didn't lookup multiclass correctly?");
2398 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2400 // Verify that the correct number of template arguments were specified.
2401 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2402 if (TArgs.size() < TemplateVals.size())
2403 return Error(SubClassLoc,
2404 "more template args specified than multiclass expects");
2406 // Loop over all the def's in the multiclass, instantiating each one.
2407 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2408 Record *DefProto = MC->DefPrototypes[i];
2410 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix, DefmPrefixLoc);
2414 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmPrefixLoc, SubClassLoc,
2415 TArgs, TemplateVals, true/*Delete args*/))
2416 return Error(SubClassLoc, "could not instantiate def");
2418 if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmPrefixLoc))
2419 return Error(SubClassLoc, "could not instantiate def");
2421 NewRecDefs.push_back(CurRec);
2425 if (Lex.getCode() != tgtok::comma) break;
2426 Lex.Lex(); // eat ','.
2428 SubClassLoc = Lex.getLoc();
2430 // A defm can inherit from regular classes (non-multiclass) as
2431 // long as they come in the end of the inheritance list.
2432 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != 0);
2434 if (InheritFromClass)
2437 Ref = ParseSubClassReference(0, true);
2440 if (InheritFromClass) {
2441 // Process all the classes to inherit as if they were part of a
2442 // regular 'def' and inherit all record values.
2443 SubClassReference SubClass = ParseSubClassReference(0, false);
2446 if (SubClass.Rec == 0) return true;
2448 // Get the expanded definition prototypes and teach them about
2449 // the record values the current class to inherit has
2450 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2451 Record *CurRec = NewRecDefs[i];
2454 if (AddSubClass(CurRec, SubClass))
2457 // Process any variables on the let stack.
2458 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2459 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2460 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2461 LetStack[i][j].Bits, LetStack[i][j].Value))
2465 if (Lex.getCode() != tgtok::comma) break;
2466 Lex.Lex(); // eat ','.
2467 SubClass = ParseSubClassReference(0, false);
2472 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2473 // See Record::setName(). This resolve step will see any new
2474 // name for the def that might have been created when resolving
2475 // inheritance, values and arguments above.
2476 NewRecDefs[i]->resolveReferences();
2478 if (Lex.getCode() != tgtok::semi)
2479 return TokError("expected ';' at end of defm");
2486 /// Object ::= ClassInst
2487 /// Object ::= DefInst
2488 /// Object ::= MultiClassInst
2489 /// Object ::= DefMInst
2490 /// Object ::= LETCommand '{' ObjectList '}'
2491 /// Object ::= LETCommand Object
2492 bool TGParser::ParseObject(MultiClass *MC) {
2493 switch (Lex.getCode()) {
2495 return TokError("Expected class, def, defm, multiclass or let definition");
2496 case tgtok::Let: return ParseTopLevelLet(MC);
2497 case tgtok::Def: return ParseDef(MC);
2498 case tgtok::Foreach: return ParseForeach(MC);
2499 case tgtok::Defm: return ParseDefm(MC);
2500 case tgtok::Class: return ParseClass();
2501 case tgtok::MultiClass: return ParseMultiClass();
2506 /// ObjectList :== Object*
2507 bool TGParser::ParseObjectList(MultiClass *MC) {
2508 while (isObjectStart(Lex.getCode())) {
2509 if (ParseObject(MC))
2515 bool TGParser::ParseFile() {
2516 Lex.Lex(); // Prime the lexer.
2517 if (ParseObjectList()) return true;
2519 // If we have unread input at the end of the file, report it.
2520 if (Lex.getCode() == tgtok::Eof)
2523 return TokError("Unexpected input at top level");