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 //===----------------------------------------------------------------------===//
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.getName())) {
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, const std::string &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 + "' unknown!");
92 // Do not allow assignments like 'X = X'. This will just cause infinite loops
93 // in the resolution machinery.
95 if (VarInit *VI = dynamic_cast<VarInit*>(V))
96 if (VI->getName() == ValName)
99 // If we are assigning to a subset of the bits in the value... then we must be
100 // assigning to a field of BitsRecTy, which must have a BitsInit
103 if (!BitList.empty()) {
104 BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
106 return Error(Loc, "Value '" + ValName + "' is not a bits type");
108 // Convert the incoming value to a bits type of the appropriate size...
109 Init *BI = V->convertInitializerTo(new BitsRecTy(BitList.size()));
111 V->convertInitializerTo(new BitsRecTy(BitList.size()));
112 return Error(Loc, "Initializer is not compatible with bit range");
115 // We should have a BitsInit type now.
116 BitsInit *BInit = dynamic_cast<BitsInit*>(BI);
119 BitsInit *NewVal = new BitsInit(CurVal->getNumBits());
121 // Loop over bits, assigning values as appropriate.
122 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
123 unsigned Bit = BitList[i];
124 if (NewVal->getBit(Bit))
125 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
126 ValName + "' more than once");
127 NewVal->setBit(Bit, BInit->getBit(i));
130 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
131 if (NewVal->getBit(i) == 0)
132 NewVal->setBit(i, CurVal->getBit(i));
138 return Error(Loc, "Value '" + ValName + "' of type '" +
139 RV->getType()->getAsString() +
140 "' is incompatible with initializer '" + V->getAsString() +"'");
144 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
145 /// args as SubClass's template arguments.
146 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
147 Record *SC = SubClass.Rec;
148 // Add all of the values in the subclass into the current class.
149 const std::vector<RecordVal> &Vals = SC->getValues();
150 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
151 if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
154 const std::vector<std::string> &TArgs = SC->getTemplateArgs();
156 // Ensure that an appropriate number of template arguments are specified.
157 if (TArgs.size() < SubClass.TemplateArgs.size())
158 return Error(SubClass.RefLoc, "More template args specified than expected");
160 // Loop over all of the template arguments, setting them to the specified
161 // value or leaving them as the default if necessary.
162 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
163 if (i < SubClass.TemplateArgs.size()) {
164 // If a value is specified for this template arg, set it now.
165 if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(),
166 SubClass.TemplateArgs[i]))
170 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
173 CurRec->removeValue(TArgs[i]);
175 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
176 return Error(SubClass.RefLoc,"Value not specified for template argument #"
177 + utostr(i) + " (" + TArgs[i] + ") of subclass '" +
178 SC->getName() + "'!");
182 // Since everything went well, we can now set the "superclass" list for the
184 const std::vector<Record*> &SCs = SC->getSuperClasses();
185 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
186 if (CurRec->isSubClassOf(SCs[i]))
187 return Error(SubClass.RefLoc,
188 "Already subclass of '" + SCs[i]->getName() + "'!\n");
189 CurRec->addSuperClass(SCs[i]);
192 if (CurRec->isSubClassOf(SC))
193 return Error(SubClass.RefLoc,
194 "Already subclass of '" + SC->getName() + "'!\n");
195 CurRec->addSuperClass(SC);
199 /// AddSubMultiClass - Add SubMultiClass as a subclass to
200 /// CurMC, resolving its template args as SubMultiClass's
201 /// template arguments.
202 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
203 SubMultiClassReference &SubMultiClass) {
204 MultiClass *SMC = SubMultiClass.MC;
205 Record *CurRec = &CurMC->Rec;
207 const std::vector<RecordVal> &MCVals = CurRec->getValues();
209 // Add all of the values in the subclass into the current class.
210 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
211 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
212 if (AddValue(CurRec, SubMultiClass.RefLoc, SMCVals[i]))
215 int newDefStart = CurMC->DefPrototypes.size();
217 // Add all of the defs in the subclass into the current multiclass.
218 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
219 iend = SMC->DefPrototypes.end();
222 // Clone the def and add it to the current multiclass
223 Record *NewDef = new Record(**i);
225 // Add all of the values in the superclass into the current def.
226 for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
227 if (AddValue(NewDef, SubMultiClass.RefLoc, MCVals[i]))
230 CurMC->DefPrototypes.push_back(NewDef);
233 const std::vector<std::string> &SMCTArgs = SMC->Rec.getTemplateArgs();
235 // Ensure that an appropriate number of template arguments are
237 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
238 return Error(SubMultiClass.RefLoc,
239 "More template args specified than expected");
241 // Loop over all of the template arguments, setting them to the specified
242 // value or leaving them as the default if necessary.
243 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
244 if (i < SubMultiClass.TemplateArgs.size()) {
245 // If a value is specified for this template arg, set it in the
247 if (SetValue(CurRec, SubMultiClass.RefLoc, SMCTArgs[i],
248 std::vector<unsigned>(),
249 SubMultiClass.TemplateArgs[i]))
253 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
256 CurRec->removeValue(SMCTArgs[i]);
258 // If a value is specified for this template arg, set it in the
260 for (MultiClass::RecordVector::iterator j =
261 CurMC->DefPrototypes.begin() + newDefStart,
262 jend = CurMC->DefPrototypes.end();
267 if (SetValue(Def, SubMultiClass.RefLoc, SMCTArgs[i],
268 std::vector<unsigned>(),
269 SubMultiClass.TemplateArgs[i]))
273 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
276 Def->removeValue(SMCTArgs[i]);
278 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
279 return Error(SubMultiClass.RefLoc,
280 "Value not specified for template argument #"
281 + utostr(i) + " (" + SMCTArgs[i] + ") of subclass '" +
282 SMC->Rec.getName() + "'!");
289 //===----------------------------------------------------------------------===//
291 //===----------------------------------------------------------------------===//
293 /// isObjectStart - Return true if this is a valid first token for an Object.
294 static bool isObjectStart(tgtok::TokKind K) {
295 return K == tgtok::Class || K == tgtok::Def ||
296 K == tgtok::Defm || K == tgtok::Let || K == tgtok::MultiClass;
299 static std::string GetNewAnonymousName() {
300 static unsigned AnonCounter = 0;
301 return "anonymous."+utostr(AnonCounter++);
304 /// ParseObjectName - If an object name is specified, return it. Otherwise,
305 /// return an anonymous name.
306 /// ObjectName ::= ID
307 /// ObjectName ::= /*empty*/
309 std::string TGParser::ParseObjectName() {
310 if (Lex.getCode() != tgtok::Id)
311 return GetNewAnonymousName();
313 std::string Ret = Lex.getCurStrVal();
319 /// ParseClassID - Parse and resolve a reference to a class name. This returns
324 Record *TGParser::ParseClassID() {
325 if (Lex.getCode() != tgtok::Id) {
326 TokError("expected name for ClassID");
330 Record *Result = Records.getClass(Lex.getCurStrVal());
332 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
338 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
339 /// This returns null on error.
341 /// MultiClassID ::= ID
343 MultiClass *TGParser::ParseMultiClassID() {
344 if (Lex.getCode() != tgtok::Id) {
345 TokError("expected name for ClassID");
349 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
351 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
357 Record *TGParser::ParseDefmID() {
358 if (Lex.getCode() != tgtok::Id) {
359 TokError("expected multiclass name");
363 MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
365 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
374 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
375 /// subclass. This returns a SubClassRefTy with a null Record* on error.
377 /// SubClassRef ::= ClassID
378 /// SubClassRef ::= ClassID '<' ValueList '>'
380 SubClassReference TGParser::
381 ParseSubClassReference(Record *CurRec, bool isDefm) {
382 SubClassReference Result;
383 Result.RefLoc = Lex.getLoc();
386 Result.Rec = ParseDefmID();
388 Result.Rec = ParseClassID();
389 if (Result.Rec == 0) return Result;
391 // If there is no template arg list, we're done.
392 if (Lex.getCode() != tgtok::less)
394 Lex.Lex(); // Eat the '<'
396 if (Lex.getCode() == tgtok::greater) {
397 TokError("subclass reference requires a non-empty list of template values");
402 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
403 if (Result.TemplateArgs.empty()) {
404 Result.Rec = 0; // Error parsing value list.
408 if (Lex.getCode() != tgtok::greater) {
409 TokError("expected '>' in template value list");
418 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
419 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
420 /// Record* on error.
422 /// SubMultiClassRef ::= MultiClassID
423 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
425 SubMultiClassReference TGParser::
426 ParseSubMultiClassReference(MultiClass *CurMC) {
427 SubMultiClassReference Result;
428 Result.RefLoc = Lex.getLoc();
430 Result.MC = ParseMultiClassID();
431 if (Result.MC == 0) return Result;
433 // If there is no template arg list, we're done.
434 if (Lex.getCode() != tgtok::less)
436 Lex.Lex(); // Eat the '<'
438 if (Lex.getCode() == tgtok::greater) {
439 TokError("subclass reference requires a non-empty list of template values");
444 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
445 if (Result.TemplateArgs.empty()) {
446 Result.MC = 0; // Error parsing value list.
450 if (Lex.getCode() != tgtok::greater) {
451 TokError("expected '>' in template value list");
460 /// ParseRangePiece - Parse a bit/value range.
461 /// RangePiece ::= INTVAL
462 /// RangePiece ::= INTVAL '-' INTVAL
463 /// RangePiece ::= INTVAL INTVAL
464 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
465 if (Lex.getCode() != tgtok::IntVal) {
466 TokError("expected integer or bitrange");
469 int64_t Start = Lex.getCurIntVal();
473 return TokError("invalid range, cannot be negative");
475 switch (Lex.Lex()) { // eat first character.
477 Ranges.push_back(Start);
480 if (Lex.Lex() != tgtok::IntVal) {
481 TokError("expected integer value as end of range");
484 End = Lex.getCurIntVal();
487 End = -Lex.getCurIntVal();
491 return TokError("invalid range, cannot be negative");
496 for (; Start <= End; ++Start)
497 Ranges.push_back(Start);
499 for (; Start >= End; --Start)
500 Ranges.push_back(Start);
505 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
507 /// RangeList ::= RangePiece (',' RangePiece)*
509 std::vector<unsigned> TGParser::ParseRangeList() {
510 std::vector<unsigned> Result;
512 // Parse the first piece.
513 if (ParseRangePiece(Result))
514 return std::vector<unsigned>();
515 while (Lex.getCode() == tgtok::comma) {
516 Lex.Lex(); // Eat the comma.
518 // Parse the next range piece.
519 if (ParseRangePiece(Result))
520 return std::vector<unsigned>();
525 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
526 /// OptionalRangeList ::= '<' RangeList '>'
527 /// OptionalRangeList ::= /*empty*/
528 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
529 if (Lex.getCode() != tgtok::less)
532 SMLoc StartLoc = Lex.getLoc();
533 Lex.Lex(); // eat the '<'
535 // Parse the range list.
536 Ranges = ParseRangeList();
537 if (Ranges.empty()) return true;
539 if (Lex.getCode() != tgtok::greater) {
540 TokError("expected '>' at end of range list");
541 return Error(StartLoc, "to match this '<'");
543 Lex.Lex(); // eat the '>'.
547 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
548 /// OptionalBitList ::= '{' RangeList '}'
549 /// OptionalBitList ::= /*empty*/
550 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
551 if (Lex.getCode() != tgtok::l_brace)
554 SMLoc StartLoc = Lex.getLoc();
555 Lex.Lex(); // eat the '{'
557 // Parse the range list.
558 Ranges = ParseRangeList();
559 if (Ranges.empty()) return true;
561 if (Lex.getCode() != tgtok::r_brace) {
562 TokError("expected '}' at end of bit list");
563 return Error(StartLoc, "to match this '{'");
565 Lex.Lex(); // eat the '}'.
570 /// ParseType - Parse and return a tblgen type. This returns null on error.
572 /// Type ::= STRING // string type
573 /// Type ::= BIT // bit type
574 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
575 /// Type ::= INT // int type
576 /// Type ::= LIST '<' Type '>' // list<x> type
577 /// Type ::= CODE // code type
578 /// Type ::= DAG // dag type
579 /// Type ::= ClassID // Record Type
581 RecTy *TGParser::ParseType() {
582 switch (Lex.getCode()) {
583 default: TokError("Unknown token when expecting a type"); return 0;
584 case tgtok::String: Lex.Lex(); return new StringRecTy();
585 case tgtok::Bit: Lex.Lex(); return new BitRecTy();
586 case tgtok::Int: Lex.Lex(); return new IntRecTy();
587 case tgtok::Code: Lex.Lex(); return new CodeRecTy();
588 case tgtok::Dag: Lex.Lex(); return new DagRecTy();
590 if (Record *R = ParseClassID()) return new RecordRecTy(R);
593 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
594 TokError("expected '<' after bits type");
597 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
598 TokError("expected integer in bits<n> type");
601 uint64_t Val = Lex.getCurIntVal();
602 if (Lex.Lex() != tgtok::greater) { // Eat count.
603 TokError("expected '>' at end of bits<n> type");
606 Lex.Lex(); // Eat '>'
607 return new BitsRecTy(Val);
610 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
611 TokError("expected '<' after list type");
614 Lex.Lex(); // Eat '<'
615 RecTy *SubType = ParseType();
616 if (SubType == 0) return 0;
618 if (Lex.getCode() != tgtok::greater) {
619 TokError("expected '>' at end of list<ty> type");
622 Lex.Lex(); // Eat '>'
623 return new ListRecTy(SubType);
628 /// ParseIDValue - Parse an ID as a value and decode what it means.
630 /// IDValue ::= ID [def local value]
631 /// IDValue ::= ID [def template arg]
632 /// IDValue ::= ID [multiclass local value]
633 /// IDValue ::= ID [multiclass template argument]
634 /// IDValue ::= ID [def name]
636 Init *TGParser::ParseIDValue(Record *CurRec) {
637 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
638 std::string Name = Lex.getCurStrVal();
639 SMLoc Loc = Lex.getLoc();
641 return ParseIDValue(CurRec, Name, Loc);
644 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
645 /// has already been read.
646 Init *TGParser::ParseIDValue(Record *CurRec,
647 const std::string &Name, SMLoc NameLoc) {
649 if (const RecordVal *RV = CurRec->getValue(Name))
650 return new VarInit(Name, RV->getType());
652 std::string TemplateArgName = CurRec->getName()+":"+Name;
653 if (CurRec->isTemplateArg(TemplateArgName)) {
654 const RecordVal *RV = CurRec->getValue(TemplateArgName);
655 assert(RV && "Template arg doesn't exist??");
656 return new VarInit(TemplateArgName, RV->getType());
661 std::string MCName = CurMultiClass->Rec.getName()+"::"+Name;
662 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
663 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
664 assert(RV && "Template arg doesn't exist??");
665 return new VarInit(MCName, RV->getType());
669 if (Record *D = Records.getDef(Name))
670 return new DefInit(D);
672 Error(NameLoc, "Variable not defined: '" + Name + "'");
676 /// ParseOperation - Parse an operator. This returns null on error.
678 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
680 Init *TGParser::ParseOperation(Record *CurRec) {
681 switch (Lex.getCode()) {
683 TokError("unknown operation");
689 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
690 UnOpInit::UnaryOp Code;
693 switch (Lex.getCode()) {
694 default: assert(0 && "Unhandled code!");
696 Lex.Lex(); // eat the operation
697 Code = UnOpInit::CAST;
699 Type = ParseOperatorType();
702 TokError("did not get type for unary operator");
708 Lex.Lex(); // eat the operation
709 Code = UnOpInit::CAR;
712 Lex.Lex(); // eat the operation
713 Code = UnOpInit::CDR;
716 Lex.Lex(); // eat the operation
717 Code = UnOpInit::LNULL;
721 if (Lex.getCode() != tgtok::l_paren) {
722 TokError("expected '(' after unary operator");
725 Lex.Lex(); // eat the '('
727 Init *LHS = ParseValue(CurRec);
728 if (LHS == 0) return 0;
730 if (Code == UnOpInit::CAR
731 || Code == UnOpInit::CDR
732 || Code == UnOpInit::LNULL) {
733 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
734 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
735 TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
736 if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
737 TokError("expected list or string type argument in unary operator");
741 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
742 StringRecTy *SType = dynamic_cast<StringRecTy*>(LHSt->getType());
743 if (LType == 0 && SType == 0) {
744 TokError("expected list or string type argumnet in unary operator");
749 if (Code == UnOpInit::CAR
750 || Code == UnOpInit::CDR) {
751 if (LHSl == 0 && LHSt == 0) {
752 TokError("expected list type argumnet in unary operator");
756 if (LHSl && LHSl->getSize() == 0) {
757 TokError("empty list argument in unary operator");
761 Init *Item = LHSl->getElement(0);
762 TypedInit *Itemt = dynamic_cast<TypedInit*>(Item);
764 TokError("untyped list element in unary operator");
767 if (Code == UnOpInit::CAR) {
768 Type = Itemt->getType();
770 Type = new ListRecTy(Itemt->getType());
773 assert(LHSt && "expected list type argument in unary operator");
774 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
776 TokError("expected list type argumnet in unary operator");
779 if (Code == UnOpInit::CAR) {
780 Type = LType->getElementType();
788 if (Lex.getCode() != tgtok::r_paren) {
789 TokError("expected ')' in unary operator");
792 Lex.Lex(); // eat the ')'
793 return (new UnOpInit(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
801 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
802 tgtok::TokKind OpTok = Lex.getCode();
803 SMLoc OpLoc = Lex.getLoc();
804 Lex.Lex(); // eat the operation
806 BinOpInit::BinaryOp Code;
810 default: assert(0 && "Unhandled code!");
811 case tgtok::XConcat: Code = BinOpInit::CONCAT; Type = new DagRecTy(); break;
812 case tgtok::XSRA: Code = BinOpInit::SRA; Type = new IntRecTy(); break;
813 case tgtok::XSRL: Code = BinOpInit::SRL; Type = new IntRecTy(); break;
814 case tgtok::XSHL: Code = BinOpInit::SHL; Type = new IntRecTy(); break;
815 case tgtok::XEq: Code = BinOpInit::EQ; Type = new BitRecTy(); break;
816 case tgtok::XStrConcat:
817 Code = BinOpInit::STRCONCAT;
818 Type = new StringRecTy();
822 if (Lex.getCode() != tgtok::l_paren) {
823 TokError("expected '(' after binary operator");
826 Lex.Lex(); // eat the '('
828 SmallVector<Init*, 2> InitList;
830 InitList.push_back(ParseValue(CurRec));
831 if (InitList.back() == 0) return 0;
833 while (Lex.getCode() == tgtok::comma) {
834 Lex.Lex(); // eat the ','
836 InitList.push_back(ParseValue(CurRec));
837 if (InitList.back() == 0) return 0;
840 if (Lex.getCode() != tgtok::r_paren) {
841 TokError("expected ')' in operator");
844 Lex.Lex(); // eat the ')'
846 // We allow multiple operands to associative operators like !strconcat as
847 // shorthand for nesting them.
848 if (Code == BinOpInit::STRCONCAT) {
849 while (InitList.size() > 2) {
850 Init *RHS = InitList.pop_back_val();
851 RHS = (new BinOpInit(Code, InitList.back(), RHS, Type))
852 ->Fold(CurRec, CurMultiClass);
853 InitList.back() = RHS;
857 if (InitList.size() == 2)
858 return (new BinOpInit(Code, InitList[0], InitList[1], Type))
859 ->Fold(CurRec, CurMultiClass);
861 Error(OpLoc, "expected two operands to operator");
866 case tgtok::XForEach:
867 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
868 TernOpInit::TernaryOp Code;
872 tgtok::TokKind LexCode = Lex.getCode();
873 Lex.Lex(); // eat the operation
875 default: assert(0 && "Unhandled code!");
877 Code = TernOpInit::IF;
879 case tgtok::XForEach:
880 Code = TernOpInit::FOREACH;
883 Code = TernOpInit::SUBST;
886 if (Lex.getCode() != tgtok::l_paren) {
887 TokError("expected '(' after ternary operator");
890 Lex.Lex(); // eat the '('
892 Init *LHS = ParseValue(CurRec);
893 if (LHS == 0) return 0;
895 if (Lex.getCode() != tgtok::comma) {
896 TokError("expected ',' in ternary operator");
899 Lex.Lex(); // eat the ','
901 Init *MHS = ParseValue(CurRec);
902 if (MHS == 0) return 0;
904 if (Lex.getCode() != tgtok::comma) {
905 TokError("expected ',' in ternary operator");
908 Lex.Lex(); // eat the ','
910 Init *RHS = ParseValue(CurRec);
911 if (RHS == 0) return 0;
913 if (Lex.getCode() != tgtok::r_paren) {
914 TokError("expected ')' in binary operator");
917 Lex.Lex(); // eat the ')'
920 default: assert(0 && "Unhandled code!");
922 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
923 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
924 if (MHSt == 0 || RHSt == 0) {
925 TokError("could not get type for !if");
928 if (MHSt->getType()->typeIsConvertibleTo(RHSt->getType())) {
929 Type = RHSt->getType();
930 } else if (RHSt->getType()->typeIsConvertibleTo(MHSt->getType())) {
931 Type = MHSt->getType();
933 TokError("inconsistent types for !if");
938 case tgtok::XForEach: {
939 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
941 TokError("could not get type for !foreach");
944 Type = MHSt->getType();
947 case tgtok::XSubst: {
948 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
950 TokError("could not get type for !subst");
953 Type = RHSt->getType();
957 return (new TernOpInit(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
961 TokError("could not parse operation");
965 /// ParseOperatorType - Parse a type for an operator. This returns
968 /// OperatorType ::= '<' Type '>'
970 RecTy *TGParser::ParseOperatorType() {
973 if (Lex.getCode() != tgtok::less) {
974 TokError("expected type name for operator");
977 Lex.Lex(); // eat the <
982 TokError("expected type name for operator");
986 if (Lex.getCode() != tgtok::greater) {
987 TokError("expected type name for operator");
990 Lex.Lex(); // eat the >
996 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
998 /// SimpleValue ::= IDValue
999 /// SimpleValue ::= INTVAL
1000 /// SimpleValue ::= STRVAL+
1001 /// SimpleValue ::= CODEFRAGMENT
1002 /// SimpleValue ::= '?'
1003 /// SimpleValue ::= '{' ValueList '}'
1004 /// SimpleValue ::= ID '<' ValueListNE '>'
1005 /// SimpleValue ::= '[' ValueList ']'
1006 /// SimpleValue ::= '(' IDValue DagArgList ')'
1007 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1008 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1009 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1010 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1011 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1013 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType) {
1015 switch (Lex.getCode()) {
1016 default: TokError("Unknown token when parsing a value"); break;
1017 case tgtok::IntVal: R = new IntInit(Lex.getCurIntVal()); Lex.Lex(); break;
1018 case tgtok::StrVal: {
1019 std::string Val = Lex.getCurStrVal();
1022 // Handle multiple consecutive concatenated strings.
1023 while (Lex.getCode() == tgtok::StrVal) {
1024 Val += Lex.getCurStrVal();
1028 R = new StringInit(Val);
1031 case tgtok::CodeFragment:
1032 R = new CodeInit(Lex.getCurStrVal());
1035 case tgtok::question:
1036 R = new UnsetInit();
1040 SMLoc NameLoc = Lex.getLoc();
1041 std::string Name = Lex.getCurStrVal();
1042 if (Lex.Lex() != tgtok::less) // consume the Id.
1043 return ParseIDValue(CurRec, Name, NameLoc); // Value ::= IDValue
1045 // Value ::= ID '<' ValueListNE '>'
1046 if (Lex.Lex() == tgtok::greater) {
1047 TokError("expected non-empty value list");
1051 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1052 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1054 Record *Class = Records.getClass(Name);
1056 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1060 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1061 if (ValueList.empty()) return 0;
1063 if (Lex.getCode() != tgtok::greater) {
1064 TokError("expected '>' at end of value list");
1067 Lex.Lex(); // eat the '>'
1069 // Create the new record, set it as CurRec temporarily.
1070 static unsigned AnonCounter = 0;
1071 Record *NewRec = Records.createRecord(
1072 "anonymous.val."+utostr(AnonCounter++),NameLoc);
1073 SubClassReference SCRef;
1074 SCRef.RefLoc = NameLoc;
1076 SCRef.TemplateArgs = ValueList;
1077 // Add info about the subclass to NewRec.
1078 if (AddSubClass(NewRec, SCRef))
1080 NewRec->resolveReferences();
1081 Records.addDef(NewRec);
1083 // The result of the expression is a reference to the new record.
1084 return new DefInit(NewRec);
1086 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1087 SMLoc BraceLoc = Lex.getLoc();
1088 Lex.Lex(); // eat the '{'
1089 std::vector<Init*> Vals;
1091 if (Lex.getCode() != tgtok::r_brace) {
1092 Vals = ParseValueList(CurRec);
1093 if (Vals.empty()) return 0;
1095 if (Lex.getCode() != tgtok::r_brace) {
1096 TokError("expected '}' at end of bit list value");
1099 Lex.Lex(); // eat the '}'
1101 BitsInit *Result = new BitsInit(Vals.size());
1102 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1103 Init *Bit = Vals[i]->convertInitializerTo(new BitRecTy());
1105 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1106 ") is not convertable to a bit");
1109 Result->setBit(Vals.size()-i-1, Bit);
1113 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1114 Lex.Lex(); // eat the '['
1115 std::vector<Init*> Vals;
1117 RecTy *DeducedEltTy = 0;
1118 ListRecTy *GivenListTy = 0;
1120 if (ItemType != 0) {
1121 ListRecTy *ListType = dynamic_cast<ListRecTy*>(ItemType);
1122 if (ListType == 0) {
1123 std::stringstream s;
1124 s << "Type mismatch for list, expected list type, got "
1125 << ItemType->getAsString();
1128 GivenListTy = ListType;
1131 if (Lex.getCode() != tgtok::r_square) {
1132 Vals = ParseValueList(CurRec, 0,
1133 GivenListTy ? GivenListTy->getElementType() : 0);
1134 if (Vals.empty()) return 0;
1136 if (Lex.getCode() != tgtok::r_square) {
1137 TokError("expected ']' at end of list value");
1140 Lex.Lex(); // eat the ']'
1142 RecTy *GivenEltTy = 0;
1143 if (Lex.getCode() == tgtok::less) {
1144 // Optional list element type
1145 Lex.Lex(); // eat the '<'
1147 GivenEltTy = ParseType();
1148 if (GivenEltTy == 0) {
1149 // Couldn't parse element type
1153 if (Lex.getCode() != tgtok::greater) {
1154 TokError("expected '>' at end of list element type");
1157 Lex.Lex(); // eat the '>'
1162 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1165 TypedInit *TArg = dynamic_cast<TypedInit*>(*i);
1167 TokError("Untyped list element");
1171 EltTy = resolveTypes(EltTy, TArg->getType());
1173 TokError("Incompatible types in list elements");
1177 EltTy = TArg->getType();
1181 if (GivenEltTy != 0) {
1183 // Verify consistency
1184 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1185 TokError("Incompatible types in list elements");
1193 if (ItemType == 0) {
1194 TokError("No type for list");
1197 DeducedEltTy = GivenListTy->getElementType();
1199 // Make sure the deduced type is compatible with the given type
1201 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1202 TokError("Element type mismatch for list");
1206 DeducedEltTy = EltTy;
1209 return new ListInit(Vals, DeducedEltTy);
1211 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1212 Lex.Lex(); // eat the '('
1213 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1214 TokError("expected identifier in dag init");
1218 Init *Operator = ParseValue(CurRec);
1219 if (Operator == 0) return 0;
1221 // If the operator name is present, parse it.
1222 std::string OperatorName;
1223 if (Lex.getCode() == tgtok::colon) {
1224 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1225 TokError("expected variable name in dag operator");
1228 OperatorName = Lex.getCurStrVal();
1229 Lex.Lex(); // eat the VarName.
1232 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1233 if (Lex.getCode() != tgtok::r_paren) {
1234 DagArgs = ParseDagArgList(CurRec);
1235 if (DagArgs.empty()) return 0;
1238 if (Lex.getCode() != tgtok::r_paren) {
1239 TokError("expected ')' in dag init");
1242 Lex.Lex(); // eat the ')'
1244 return new DagInit(Operator, OperatorName, DagArgs);
1250 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1251 case tgtok::XConcat:
1256 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1258 case tgtok::XForEach:
1259 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1260 return ParseOperation(CurRec);
1267 /// ParseValue - Parse a tblgen value. This returns null on error.
1269 /// Value ::= SimpleValue ValueSuffix*
1270 /// ValueSuffix ::= '{' BitList '}'
1271 /// ValueSuffix ::= '[' BitList ']'
1272 /// ValueSuffix ::= '.' ID
1274 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType) {
1275 Init *Result = ParseSimpleValue(CurRec, ItemType);
1276 if (Result == 0) return 0;
1278 // Parse the suffixes now if present.
1280 switch (Lex.getCode()) {
1281 default: return Result;
1282 case tgtok::l_brace: {
1283 SMLoc CurlyLoc = Lex.getLoc();
1284 Lex.Lex(); // eat the '{'
1285 std::vector<unsigned> Ranges = ParseRangeList();
1286 if (Ranges.empty()) return 0;
1288 // Reverse the bitlist.
1289 std::reverse(Ranges.begin(), Ranges.end());
1290 Result = Result->convertInitializerBitRange(Ranges);
1292 Error(CurlyLoc, "Invalid bit range for value");
1297 if (Lex.getCode() != tgtok::r_brace) {
1298 TokError("expected '}' at end of bit range list");
1304 case tgtok::l_square: {
1305 SMLoc SquareLoc = Lex.getLoc();
1306 Lex.Lex(); // eat the '['
1307 std::vector<unsigned> Ranges = ParseRangeList();
1308 if (Ranges.empty()) return 0;
1310 Result = Result->convertInitListSlice(Ranges);
1312 Error(SquareLoc, "Invalid range for list slice");
1317 if (Lex.getCode() != tgtok::r_square) {
1318 TokError("expected ']' at end of list slice");
1325 if (Lex.Lex() != tgtok::Id) { // eat the .
1326 TokError("expected field identifier after '.'");
1329 if (!Result->getFieldType(Lex.getCurStrVal())) {
1330 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1331 Result->getAsString() + "'");
1334 Result = new FieldInit(Result, Lex.getCurStrVal());
1335 Lex.Lex(); // eat field name
1341 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1343 /// ParseDagArgList ::= Value (':' VARNAME)?
1344 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1345 std::vector<std::pair<llvm::Init*, std::string> >
1346 TGParser::ParseDagArgList(Record *CurRec) {
1347 std::vector<std::pair<llvm::Init*, std::string> > Result;
1350 Init *Val = ParseValue(CurRec);
1351 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1353 // If the variable name is present, add it.
1354 std::string VarName;
1355 if (Lex.getCode() == tgtok::colon) {
1356 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1357 TokError("expected variable name in dag literal");
1358 return std::vector<std::pair<llvm::Init*, std::string> >();
1360 VarName = Lex.getCurStrVal();
1361 Lex.Lex(); // eat the VarName.
1364 Result.push_back(std::make_pair(Val, VarName));
1366 if (Lex.getCode() != tgtok::comma) break;
1367 Lex.Lex(); // eat the ','
1374 /// ParseValueList - Parse a comma separated list of values, returning them as a
1375 /// vector. Note that this always expects to be able to parse at least one
1376 /// value. It returns an empty list if this is not possible.
1378 /// ValueList ::= Value (',' Value)
1380 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1382 std::vector<Init*> Result;
1383 RecTy *ItemType = EltTy;
1384 unsigned int ArgN = 0;
1385 if (ArgsRec != 0 && EltTy == 0) {
1386 const std::vector<std::string> &TArgs = ArgsRec->getTemplateArgs();
1387 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1388 assert(RV && "Template argument record not found??");
1389 ItemType = RV->getType();
1392 Result.push_back(ParseValue(CurRec, ItemType));
1393 if (Result.back() == 0) return std::vector<Init*>();
1395 while (Lex.getCode() == tgtok::comma) {
1396 Lex.Lex(); // Eat the comma
1398 if (ArgsRec != 0 && EltTy == 0) {
1399 const std::vector<std::string> &TArgs = ArgsRec->getTemplateArgs();
1400 if (ArgN >= TArgs.size()) {
1401 TokError("too many template arguments");
1402 return std::vector<Init*>();
1404 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1405 assert(RV && "Template argument record not found??");
1406 ItemType = RV->getType();
1409 Result.push_back(ParseValue(CurRec, ItemType));
1410 if (Result.back() == 0) return std::vector<Init*>();
1417 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1418 /// empty string on error. This can happen in a number of different context's,
1419 /// including within a def or in the template args for a def (which which case
1420 /// CurRec will be non-null) and within the template args for a multiclass (in
1421 /// which case CurRec will be null, but CurMultiClass will be set). This can
1422 /// also happen within a def that is within a multiclass, which will set both
1423 /// CurRec and CurMultiClass.
1425 /// Declaration ::= FIELD? Type ID ('=' Value)?
1427 std::string TGParser::ParseDeclaration(Record *CurRec,
1428 bool ParsingTemplateArgs) {
1429 // Read the field prefix if present.
1430 bool HasField = Lex.getCode() == tgtok::Field;
1431 if (HasField) Lex.Lex();
1433 RecTy *Type = ParseType();
1434 if (Type == 0) return "";
1436 if (Lex.getCode() != tgtok::Id) {
1437 TokError("Expected identifier in declaration");
1441 SMLoc IdLoc = Lex.getLoc();
1442 std::string DeclName = Lex.getCurStrVal();
1445 if (ParsingTemplateArgs) {
1447 DeclName = CurRec->getName() + ":" + DeclName;
1449 assert(CurMultiClass);
1452 DeclName = CurMultiClass->Rec.getName() + "::" + DeclName;
1456 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1459 // If a value is present, parse it.
1460 if (Lex.getCode() == tgtok::equal) {
1462 SMLoc ValLoc = Lex.getLoc();
1463 Init *Val = ParseValue(CurRec, Type);
1465 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1472 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1473 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1474 /// template args for a def, which may or may not be in a multiclass. If null,
1475 /// these are the template args for a multiclass.
1477 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1479 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1480 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1481 Lex.Lex(); // eat the '<'
1483 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1485 // Read the first declaration.
1486 std::string TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1487 if (TemplArg.empty())
1490 TheRecToAddTo->addTemplateArg(TemplArg);
1492 while (Lex.getCode() == tgtok::comma) {
1493 Lex.Lex(); // eat the ','
1495 // Read the following declarations.
1496 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1497 if (TemplArg.empty())
1499 TheRecToAddTo->addTemplateArg(TemplArg);
1502 if (Lex.getCode() != tgtok::greater)
1503 return TokError("expected '>' at end of template argument list");
1504 Lex.Lex(); // eat the '>'.
1509 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1511 /// BodyItem ::= Declaration ';'
1512 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1513 bool TGParser::ParseBodyItem(Record *CurRec) {
1514 if (Lex.getCode() != tgtok::Let) {
1515 if (ParseDeclaration(CurRec, false).empty())
1518 if (Lex.getCode() != tgtok::semi)
1519 return TokError("expected ';' after declaration");
1524 // LET ID OptionalRangeList '=' Value ';'
1525 if (Lex.Lex() != tgtok::Id)
1526 return TokError("expected field identifier after let");
1528 SMLoc IdLoc = Lex.getLoc();
1529 std::string FieldName = Lex.getCurStrVal();
1530 Lex.Lex(); // eat the field name.
1532 std::vector<unsigned> BitList;
1533 if (ParseOptionalBitList(BitList))
1535 std::reverse(BitList.begin(), BitList.end());
1537 if (Lex.getCode() != tgtok::equal)
1538 return TokError("expected '=' in let expression");
1539 Lex.Lex(); // eat the '='.
1541 RecordVal *Field = CurRec->getValue(FieldName);
1543 return TokError("Value '" + FieldName + "' unknown!");
1545 RecTy *Type = Field->getType();
1547 Init *Val = ParseValue(CurRec, Type);
1548 if (Val == 0) return true;
1550 if (Lex.getCode() != tgtok::semi)
1551 return TokError("expected ';' after let expression");
1554 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1557 /// ParseBody - Read the body of a class or def. Return true on error, false on
1561 /// Body ::= '{' BodyList '}'
1562 /// BodyList BodyItem*
1564 bool TGParser::ParseBody(Record *CurRec) {
1565 // If this is a null definition, just eat the semi and return.
1566 if (Lex.getCode() == tgtok::semi) {
1571 if (Lex.getCode() != tgtok::l_brace)
1572 return TokError("Expected ';' or '{' to start body");
1576 while (Lex.getCode() != tgtok::r_brace)
1577 if (ParseBodyItem(CurRec))
1585 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1586 /// optional ClassList followed by a Body. CurRec is the current def or class
1587 /// that is being parsed.
1589 /// ObjectBody ::= BaseClassList Body
1590 /// BaseClassList ::= /*empty*/
1591 /// BaseClassList ::= ':' BaseClassListNE
1592 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1594 bool TGParser::ParseObjectBody(Record *CurRec) {
1595 // If there is a baseclass list, read it.
1596 if (Lex.getCode() == tgtok::colon) {
1599 // Read all of the subclasses.
1600 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1603 if (SubClass.Rec == 0) return true;
1606 if (AddSubClass(CurRec, SubClass))
1609 if (Lex.getCode() != tgtok::comma) break;
1610 Lex.Lex(); // eat ','.
1611 SubClass = ParseSubClassReference(CurRec, false);
1615 // Process any variables on the let stack.
1616 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1617 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1618 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1619 LetStack[i][j].Bits, LetStack[i][j].Value))
1622 return ParseBody(CurRec);
1625 /// ParseDef - Parse and return a top level or multiclass def, return the record
1626 /// corresponding to it. This returns null on error.
1628 /// DefInst ::= DEF ObjectName ObjectBody
1630 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1631 SMLoc DefLoc = Lex.getLoc();
1632 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1633 Lex.Lex(); // Eat the 'def' token.
1635 // Parse ObjectName and make a record for it.
1636 Record *CurRec = Records.createRecord(ParseObjectName(), DefLoc);
1638 if (!CurMultiClass) {
1639 // Top-level def definition.
1641 // Ensure redefinition doesn't happen.
1642 if (Records.getDef(CurRec->getName())) {
1643 Error(DefLoc, "def '" + CurRec->getName() + "' already defined");
1646 Records.addDef(CurRec);
1648 // Otherwise, a def inside a multiclass, add it to the multiclass.
1649 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1650 if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
1651 Error(DefLoc, "def '" + CurRec->getName() +
1652 "' already defined in this multiclass!");
1655 CurMultiClass->DefPrototypes.push_back(CurRec);
1658 if (ParseObjectBody(CurRec))
1661 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1662 CurRec->resolveReferences();
1664 // If ObjectBody has template arguments, it's an error.
1665 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1667 if (CurMultiClass) {
1668 // Copy the template arguments for the multiclass into the def.
1669 const std::vector<std::string> &TArgs =
1670 CurMultiClass->Rec.getTemplateArgs();
1672 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1673 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1674 assert(RV && "Template arg doesn't exist?");
1675 CurRec->addValue(*RV);
1683 /// ParseClass - Parse a tblgen class definition.
1685 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1687 bool TGParser::ParseClass() {
1688 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1691 if (Lex.getCode() != tgtok::Id)
1692 return TokError("expected class name after 'class' keyword");
1694 Record *CurRec = Records.getClass(Lex.getCurStrVal());
1696 // If the body was previously defined, this is an error.
1697 if (!CurRec->getValues().empty() ||
1698 !CurRec->getSuperClasses().empty() ||
1699 !CurRec->getTemplateArgs().empty())
1700 return TokError("Class '" + CurRec->getName() + "' already defined");
1702 // If this is the first reference to this class, create and add it.
1703 CurRec = Records.createRecord(Lex.getCurStrVal(), Lex.getLoc());
1704 Records.addClass(CurRec);
1706 Lex.Lex(); // eat the name.
1708 // If there are template args, parse them.
1709 if (Lex.getCode() == tgtok::less)
1710 if (ParseTemplateArgList(CurRec))
1713 // Finally, parse the object body.
1714 return ParseObjectBody(CurRec);
1717 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1720 /// LetList ::= LetItem (',' LetItem)*
1721 /// LetItem ::= ID OptionalRangeList '=' Value
1723 std::vector<LetRecord> TGParser::ParseLetList() {
1724 std::vector<LetRecord> Result;
1727 if (Lex.getCode() != tgtok::Id) {
1728 TokError("expected identifier in let definition");
1729 return std::vector<LetRecord>();
1731 std::string Name = Lex.getCurStrVal();
1732 SMLoc NameLoc = Lex.getLoc();
1733 Lex.Lex(); // Eat the identifier.
1735 // Check for an optional RangeList.
1736 std::vector<unsigned> Bits;
1737 if (ParseOptionalRangeList(Bits))
1738 return std::vector<LetRecord>();
1739 std::reverse(Bits.begin(), Bits.end());
1741 if (Lex.getCode() != tgtok::equal) {
1742 TokError("expected '=' in let expression");
1743 return std::vector<LetRecord>();
1745 Lex.Lex(); // eat the '='.
1747 Init *Val = ParseValue(0);
1748 if (Val == 0) return std::vector<LetRecord>();
1750 // Now that we have everything, add the record.
1751 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1753 if (Lex.getCode() != tgtok::comma)
1755 Lex.Lex(); // eat the comma.
1759 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
1760 /// different related productions. This works inside multiclasses too.
1762 /// Object ::= LET LetList IN '{' ObjectList '}'
1763 /// Object ::= LET LetList IN Object
1765 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
1766 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1769 // Add this entry to the let stack.
1770 std::vector<LetRecord> LetInfo = ParseLetList();
1771 if (LetInfo.empty()) return true;
1772 LetStack.push_back(LetInfo);
1774 if (Lex.getCode() != tgtok::In)
1775 return TokError("expected 'in' at end of top-level 'let'");
1778 // If this is a scalar let, just handle it now
1779 if (Lex.getCode() != tgtok::l_brace) {
1780 // LET LetList IN Object
1781 if (ParseObject(CurMultiClass))
1783 } else { // Object ::= LETCommand '{' ObjectList '}'
1784 SMLoc BraceLoc = Lex.getLoc();
1785 // Otherwise, this is a group let.
1786 Lex.Lex(); // eat the '{'.
1788 // Parse the object list.
1789 if (ParseObjectList(CurMultiClass))
1792 if (Lex.getCode() != tgtok::r_brace) {
1793 TokError("expected '}' at end of top level let command");
1794 return Error(BraceLoc, "to match this '{'");
1799 // Outside this let scope, this let block is not active.
1800 LetStack.pop_back();
1804 /// ParseMultiClass - Parse a multiclass definition.
1806 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
1807 /// ':' BaseMultiClassList '{' MultiClassDef+ '}'
1809 bool TGParser::ParseMultiClass() {
1810 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1811 Lex.Lex(); // Eat the multiclass token.
1813 if (Lex.getCode() != tgtok::Id)
1814 return TokError("expected identifier after multiclass for name");
1815 std::string Name = Lex.getCurStrVal();
1817 if (MultiClasses.count(Name))
1818 return TokError("multiclass '" + Name + "' already defined");
1820 CurMultiClass = MultiClasses[Name] = new MultiClass(Name,
1821 Lex.getLoc(), Records);
1822 Lex.Lex(); // Eat the identifier.
1824 // If there are template args, parse them.
1825 if (Lex.getCode() == tgtok::less)
1826 if (ParseTemplateArgList(0))
1829 bool inherits = false;
1831 // If there are submulticlasses, parse them.
1832 if (Lex.getCode() == tgtok::colon) {
1837 // Read all of the submulticlasses.
1838 SubMultiClassReference SubMultiClass =
1839 ParseSubMultiClassReference(CurMultiClass);
1842 if (SubMultiClass.MC == 0) return true;
1845 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
1848 if (Lex.getCode() != tgtok::comma) break;
1849 Lex.Lex(); // eat ','.
1850 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
1854 if (Lex.getCode() != tgtok::l_brace) {
1856 return TokError("expected '{' in multiclass definition");
1857 else if (Lex.getCode() != tgtok::semi)
1858 return TokError("expected ';' in multiclass definition");
1860 Lex.Lex(); // eat the ';'.
1862 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
1863 return TokError("multiclass must contain at least one def");
1865 while (Lex.getCode() != tgtok::r_brace) {
1866 switch (Lex.getCode()) {
1868 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
1872 if (ParseObject(CurMultiClass))
1877 Lex.Lex(); // eat the '}'.
1884 /// ParseDefm - Parse the instantiation of a multiclass.
1886 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
1888 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
1889 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
1891 std::string DefmPrefix;
1892 if (Lex.Lex() == tgtok::Id) { // eat the defm.
1893 DefmPrefix = Lex.getCurStrVal();
1894 Lex.Lex(); // Eat the defm prefix.
1897 SMLoc DefmPrefixLoc = Lex.getLoc();
1898 if (Lex.getCode() != tgtok::colon)
1899 return TokError("expected ':' after defm identifier");
1901 // Keep track of the new generated record definitions.
1902 std::vector<Record*> NewRecDefs;
1904 // This record also inherits from a regular class (non-multiclass)?
1905 bool InheritFromClass = false;
1910 SMLoc SubClassLoc = Lex.getLoc();
1911 SubClassReference Ref = ParseSubClassReference(0, true);
1914 if (Ref.Rec == 0) return true;
1916 // To instantiate a multiclass, we need to first get the multiclass, then
1917 // instantiate each def contained in the multiclass with the SubClassRef
1918 // template parameters.
1919 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
1920 assert(MC && "Didn't lookup multiclass correctly?");
1921 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
1923 // Verify that the correct number of template arguments were specified.
1924 const std::vector<std::string> &TArgs = MC->Rec.getTemplateArgs();
1925 if (TArgs.size() < TemplateVals.size())
1926 return Error(SubClassLoc,
1927 "more template args specified than multiclass expects");
1929 // Loop over all the def's in the multiclass, instantiating each one.
1930 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
1931 Record *DefProto = MC->DefPrototypes[i];
1933 // Add in the defm name. If the defm prefix is empty, give each
1934 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
1935 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
1937 std::string DefName = DefProto->getName();
1938 if (DefmPrefix.empty()) {
1939 DefName = GetNewAnonymousName();
1941 std::string::size_type idx = DefName.find("#NAME#");
1942 if (idx != std::string::npos) {
1943 DefName.replace(idx, 6, DefmPrefix);
1945 // Add the suffix to the defm name to get the new name.
1946 DefName = DefmPrefix + DefName;
1950 Record *CurRec = Records.createRecord(DefName, DefmPrefixLoc);
1952 SubClassReference Ref;
1953 Ref.RefLoc = DefmPrefixLoc;
1955 AddSubClass(CurRec, Ref);
1957 // Loop over all of the template arguments, setting them to the specified
1958 // value or leaving them as the default if necessary.
1959 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1960 // Check if a value is specified for this temp-arg.
1961 if (i < TemplateVals.size()) {
1963 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
1968 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
1971 CurRec->removeValue(TArgs[i]);
1973 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
1974 return Error(SubClassLoc,
1975 "value not specified for template argument #"+
1976 utostr(i) + " (" + TArgs[i] + ") of multiclassclass '" +
1977 MC->Rec.getName() + "'");
1981 // If the mdef is inside a 'let' expression, add to each def.
1982 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1983 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1984 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1985 LetStack[i][j].Bits, LetStack[i][j].Value)) {
1986 Error(DefmPrefixLoc, "when instantiating this defm");
1990 // Ensure redefinition doesn't happen.
1991 if (Records.getDef(CurRec->getName()))
1992 return Error(DefmPrefixLoc, "def '" + CurRec->getName() +
1993 "' already defined, instantiating defm with subdef '" +
1994 DefProto->getName() + "'");
1996 // Don't create a top level definition for defm inside multiclasses,
1997 // instead, only update the prototypes and bind the template args
1998 // with the new created definition.
1999 if (CurMultiClass) {
2000 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2002 if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
2003 Error(DefmPrefixLoc, "defm '" + CurRec->getName() +
2004 "' already defined in this multiclass!");
2008 CurMultiClass->DefPrototypes.push_back(CurRec);
2010 // Copy the template arguments for the multiclass into the new def.
2011 const std::vector<std::string> &TA =
2012 CurMultiClass->Rec.getTemplateArgs();
2014 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2015 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2016 assert(RV && "Template arg doesn't exist?");
2017 CurRec->addValue(*RV);
2020 Records.addDef(CurRec);
2023 NewRecDefs.push_back(CurRec);
2026 if (Lex.getCode() != tgtok::comma) break;
2027 Lex.Lex(); // eat ','.
2029 SubClassLoc = Lex.getLoc();
2031 // A defm can inherit from regular classes (non-multiclass) as
2032 // long as they come in the end of the inheritance list.
2033 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != 0);
2035 if (InheritFromClass)
2038 Ref = ParseSubClassReference(0, true);
2041 if (InheritFromClass) {
2042 // Process all the classes to inherit as if they were part of a
2043 // regular 'def' and inherit all record values.
2044 SubClassReference SubClass = ParseSubClassReference(0, false);
2047 if (SubClass.Rec == 0) return true;
2049 // Get the expanded definition prototypes and teach them about
2050 // the record values the current class to inherit has
2051 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2052 Record *CurRec = NewRecDefs[i];
2055 if (AddSubClass(CurRec, SubClass))
2058 // Process any variables on the let stack.
2059 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2060 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2061 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2062 LetStack[i][j].Bits, LetStack[i][j].Value))
2066 if (Lex.getCode() != tgtok::comma) break;
2067 Lex.Lex(); // eat ','.
2068 SubClass = ParseSubClassReference(0, false);
2073 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2074 NewRecDefs[i]->resolveReferences();
2076 if (Lex.getCode() != tgtok::semi)
2077 return TokError("expected ';' at end of defm");
2084 /// Object ::= ClassInst
2085 /// Object ::= DefInst
2086 /// Object ::= MultiClassInst
2087 /// Object ::= DefMInst
2088 /// Object ::= LETCommand '{' ObjectList '}'
2089 /// Object ::= LETCommand Object
2090 bool TGParser::ParseObject(MultiClass *MC) {
2091 switch (Lex.getCode()) {
2093 return TokError("Expected class, def, defm, multiclass or let definition");
2094 case tgtok::Let: return ParseTopLevelLet(MC);
2095 case tgtok::Def: return ParseDef(MC);
2096 case tgtok::Defm: return ParseDefm(MC);
2097 case tgtok::Class: return ParseClass();
2098 case tgtok::MultiClass: return ParseMultiClass();
2103 /// ObjectList :== Object*
2104 bool TGParser::ParseObjectList(MultiClass *MC) {
2105 while (isObjectStart(Lex.getCode())) {
2106 if (ParseObject(MC))
2112 bool TGParser::ParseFile() {
2113 Lex.Lex(); // Prime the lexer.
2114 if (ParseObjectList()) return true;
2116 // If we have unread input at the end of the file, report it.
2117 if (Lex.getCode() == tgtok::Eof)
2120 return TokError("Unexpected input at top level");