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 //===----------------------------------------------------------------------===//
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Support/Streams.h"
22 //===----------------------------------------------------------------------===//
23 // Support Code for the Semantic Actions.
24 //===----------------------------------------------------------------------===//
27 struct SubClassReference {
30 std::vector<Init*> TemplateArgs;
31 SubClassReference() : Rec(0) {}
33 bool isInvalid() const { return Rec == 0; }
36 struct SubMultiClassReference {
39 std::vector<Init*> TemplateArgs;
40 SubMultiClassReference() : MC(0) {}
42 bool isInvalid() const { return MC == 0; }
46 void SubMultiClassReference::dump() const {
47 cerr << "Multiclass:\n";
51 cerr << "Template args:\n";
52 for (std::vector<Init *>::const_iterator i = TemplateArgs.begin(),
53 iend = TemplateArgs.end();
60 } // end namespace llvm
62 bool TGParser::AddValue(Record *CurRec, TGLoc Loc, const RecordVal &RV) {
64 CurRec = &CurMultiClass->Rec;
66 if (RecordVal *ERV = CurRec->getValue(RV.getName())) {
67 // The value already exists in the class, treat this as a set.
68 if (ERV->setValue(RV.getValue()))
69 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
70 RV.getType()->getAsString() + "' is incompatible with " +
71 "previous definition of type '" +
72 ERV->getType()->getAsString() + "'");
80 /// Return true on error, false on success.
81 bool TGParser::SetValue(Record *CurRec, TGLoc Loc, const std::string &ValName,
82 const std::vector<unsigned> &BitList, Init *V) {
85 if (CurRec == 0) CurRec = &CurMultiClass->Rec;
87 RecordVal *RV = CurRec->getValue(ValName);
89 return Error(Loc, "Value '" + ValName + "' unknown!");
91 // Do not allow assignments like 'X = X'. This will just cause infinite loops
92 // in the resolution machinery.
94 if (VarInit *VI = dynamic_cast<VarInit*>(V))
95 if (VI->getName() == ValName)
98 // If we are assigning to a subset of the bits in the value... then we must be
99 // assigning to a field of BitsRecTy, which must have a BitsInit
102 if (!BitList.empty()) {
103 BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
105 return Error(Loc, "Value '" + ValName + "' is not a bits type");
107 // Convert the incoming value to a bits type of the appropriate size...
108 Init *BI = V->convertInitializerTo(new BitsRecTy(BitList.size()));
110 V->convertInitializerTo(new BitsRecTy(BitList.size()));
111 return Error(Loc, "Initializer is not compatible with bit range");
114 // We should have a BitsInit type now.
115 BitsInit *BInit = dynamic_cast<BitsInit*>(BI);
118 BitsInit *NewVal = new BitsInit(CurVal->getNumBits());
120 // Loop over bits, assigning values as appropriate.
121 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
122 unsigned Bit = BitList[i];
123 if (NewVal->getBit(Bit))
124 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
125 ValName + "' more than once");
126 NewVal->setBit(Bit, BInit->getBit(i));
129 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
130 if (NewVal->getBit(i) == 0)
131 NewVal->setBit(i, CurVal->getBit(i));
137 return Error(Loc, "Value '" + ValName + "' of type '" +
138 RV->getType()->getAsString() +
139 "' is incompatible with initializer '" + V->getAsString() +"'");
143 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
144 /// args as SubClass's template arguments.
145 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
146 Record *SC = SubClass.Rec;
147 // Add all of the values in the subclass into the current class.
148 const std::vector<RecordVal> &Vals = SC->getValues();
149 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
150 if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
153 const std::vector<std::string> &TArgs = SC->getTemplateArgs();
155 // Ensure that an appropriate number of template arguments are specified.
156 if (TArgs.size() < SubClass.TemplateArgs.size())
157 return Error(SubClass.RefLoc, "More template args specified than expected");
159 // Loop over all of the template arguments, setting them to the specified
160 // value or leaving them as the default if necessary.
161 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
162 if (i < SubClass.TemplateArgs.size()) {
163 // If a value is specified for this template arg, set it now.
164 if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(),
165 SubClass.TemplateArgs[i]))
169 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
172 CurRec->removeValue(TArgs[i]);
174 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
175 return Error(SubClass.RefLoc,"Value not specified for template argument #"
176 + utostr(i) + " (" + TArgs[i] + ") of subclass '" +
177 SC->getName() + "'!");
181 // Since everything went well, we can now set the "superclass" list for the
183 const std::vector<Record*> &SCs = SC->getSuperClasses();
184 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
185 if (CurRec->isSubClassOf(SCs[i]))
186 return Error(SubClass.RefLoc,
187 "Already subclass of '" + SCs[i]->getName() + "'!\n");
188 CurRec->addSuperClass(SCs[i]);
191 if (CurRec->isSubClassOf(SC))
192 return Error(SubClass.RefLoc,
193 "Already subclass of '" + SC->getName() + "'!\n");
194 CurRec->addSuperClass(SC);
198 /// AddSubMultiClass - Add SubMultiClass as a subclass to
199 /// CurMC, resolving its template args as SubMultiClass's
200 /// template arguments.
201 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
202 SubMultiClassReference &SubMultiClass) {
203 MultiClass *SMC = SubMultiClass.MC;
204 Record *CurRec = &CurMC->Rec;
206 const std::vector<RecordVal> &MCVals = CurRec->getValues();
208 // Add all of the values in the subclass into the current class.
209 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
210 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
211 if (AddValue(CurRec, SubMultiClass.RefLoc, SMCVals[i]))
214 int newDefStart = CurMC->DefPrototypes.size();
216 // Add all of the defs in the subclass into the current multiclass.
217 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
218 iend = SMC->DefPrototypes.end();
221 // Clone the def and add it to the current multiclass
222 Record *NewDef = new Record(**i);
224 // Add all of the values in the superclass into the current def.
225 for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
226 if (AddValue(NewDef, SubMultiClass.RefLoc, MCVals[i]))
229 CurMC->DefPrototypes.push_back(NewDef);
232 const std::vector<std::string> &SMCTArgs = SMC->Rec.getTemplateArgs();
234 // Ensure that an appropriate number of template arguments are
236 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
237 return Error(SubMultiClass.RefLoc,
238 "More template args specified than expected");
240 // Loop over all of the template arguments, setting them to the specified
241 // value or leaving them as the default if necessary.
242 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
243 if (i < SubMultiClass.TemplateArgs.size()) {
244 // If a value is specified for this template arg, set it in the
246 if (SetValue(CurRec, SubMultiClass.RefLoc, SMCTArgs[i],
247 std::vector<unsigned>(),
248 SubMultiClass.TemplateArgs[i]))
252 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
255 CurRec->removeValue(SMCTArgs[i]);
257 // If a value is specified for this template arg, set it in the
259 for (MultiClass::RecordVector::iterator j =
260 CurMC->DefPrototypes.begin() + newDefStart,
261 jend = CurMC->DefPrototypes.end();
266 if (SetValue(Def, SubMultiClass.RefLoc, SMCTArgs[i],
267 std::vector<unsigned>(),
268 SubMultiClass.TemplateArgs[i]))
272 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
275 Def->removeValue(SMCTArgs[i]);
277 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
278 return Error(SubMultiClass.RefLoc,
279 "Value not specified for template argument #"
280 + utostr(i) + " (" + SMCTArgs[i] + ") of subclass '" +
281 SMC->Rec.getName() + "'!");
288 //===----------------------------------------------------------------------===//
290 //===----------------------------------------------------------------------===//
292 /// isObjectStart - Return true if this is a valid first token for an Object.
293 static bool isObjectStart(tgtok::TokKind K) {
294 return K == tgtok::Class || K == tgtok::Def ||
295 K == tgtok::Defm || K == tgtok::Let || K == tgtok::MultiClass;
298 /// ParseObjectName - If an object name is specified, return it. Otherwise,
299 /// return an anonymous name.
300 /// ObjectName ::= ID
301 /// ObjectName ::= /*empty*/
303 std::string TGParser::ParseObjectName() {
304 if (Lex.getCode() == tgtok::Id) {
305 std::string Ret = Lex.getCurStrVal();
310 static unsigned AnonCounter = 0;
311 return "anonymous."+utostr(AnonCounter++);
315 /// ParseClassID - Parse and resolve a reference to a class name. This returns
320 Record *TGParser::ParseClassID() {
321 if (Lex.getCode() != tgtok::Id) {
322 TokError("expected name for ClassID");
326 Record *Result = Records.getClass(Lex.getCurStrVal());
328 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
334 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
335 /// This returns null on error.
337 /// MultiClassID ::= ID
339 MultiClass *TGParser::ParseMultiClassID() {
340 if (Lex.getCode() != tgtok::Id) {
341 TokError("expected name for ClassID");
345 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
347 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
353 Record *TGParser::ParseDefmID() {
354 if (Lex.getCode() != tgtok::Id) {
355 TokError("expected multiclass name");
359 MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
361 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
371 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
372 /// subclass. This returns a SubClassRefTy with a null Record* on error.
374 /// SubClassRef ::= ClassID
375 /// SubClassRef ::= ClassID '<' ValueList '>'
377 SubClassReference TGParser::
378 ParseSubClassReference(Record *CurRec, bool isDefm) {
379 SubClassReference Result;
380 Result.RefLoc = Lex.getLoc();
383 Result.Rec = ParseDefmID();
385 Result.Rec = ParseClassID();
386 if (Result.Rec == 0) return Result;
388 // If there is no template arg list, we're done.
389 if (Lex.getCode() != tgtok::less)
391 Lex.Lex(); // Eat the '<'
393 if (Lex.getCode() == tgtok::greater) {
394 TokError("subclass reference requires a non-empty list of template values");
399 Result.TemplateArgs = ParseValueList(CurRec);
400 if (Result.TemplateArgs.empty()) {
401 Result.Rec = 0; // Error parsing value list.
405 if (Lex.getCode() != tgtok::greater) {
406 TokError("expected '>' in template value list");
415 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
416 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
417 /// Record* on error.
419 /// SubMultiClassRef ::= MultiClassID
420 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
422 SubMultiClassReference TGParser::
423 ParseSubMultiClassReference(MultiClass *CurMC) {
424 SubMultiClassReference Result;
425 Result.RefLoc = Lex.getLoc();
427 Result.MC = ParseMultiClassID();
428 if (Result.MC == 0) return Result;
430 // If there is no template arg list, we're done.
431 if (Lex.getCode() != tgtok::less)
433 Lex.Lex(); // Eat the '<'
435 if (Lex.getCode() == tgtok::greater) {
436 TokError("subclass reference requires a non-empty list of template values");
441 Result.TemplateArgs = ParseValueList(&CurMC->Rec);
442 if (Result.TemplateArgs.empty()) {
443 Result.MC = 0; // Error parsing value list.
447 if (Lex.getCode() != tgtok::greater) {
448 TokError("expected '>' in template value list");
457 /// ParseRangePiece - Parse a bit/value range.
458 /// RangePiece ::= INTVAL
459 /// RangePiece ::= INTVAL '-' INTVAL
460 /// RangePiece ::= INTVAL INTVAL
461 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
462 if (Lex.getCode() != tgtok::IntVal) {
463 TokError("expected integer or bitrange");
466 int64_t Start = Lex.getCurIntVal();
470 return TokError("invalid range, cannot be negative");
472 switch (Lex.Lex()) { // eat first character.
474 Ranges.push_back(Start);
477 if (Lex.Lex() != tgtok::IntVal) {
478 TokError("expected integer value as end of range");
481 End = Lex.getCurIntVal();
484 End = -Lex.getCurIntVal();
488 return TokError("invalid range, cannot be negative");
493 for (; Start <= End; ++Start)
494 Ranges.push_back(Start);
496 for (; Start >= End; --Start)
497 Ranges.push_back(Start);
502 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
504 /// RangeList ::= RangePiece (',' RangePiece)*
506 std::vector<unsigned> TGParser::ParseRangeList() {
507 std::vector<unsigned> Result;
509 // Parse the first piece.
510 if (ParseRangePiece(Result))
511 return std::vector<unsigned>();
512 while (Lex.getCode() == tgtok::comma) {
513 Lex.Lex(); // Eat the comma.
515 // Parse the next range piece.
516 if (ParseRangePiece(Result))
517 return std::vector<unsigned>();
522 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
523 /// OptionalRangeList ::= '<' RangeList '>'
524 /// OptionalRangeList ::= /*empty*/
525 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
526 if (Lex.getCode() != tgtok::less)
529 TGLoc StartLoc = Lex.getLoc();
530 Lex.Lex(); // eat the '<'
532 // Parse the range list.
533 Ranges = ParseRangeList();
534 if (Ranges.empty()) return true;
536 if (Lex.getCode() != tgtok::greater) {
537 TokError("expected '>' at end of range list");
538 return Error(StartLoc, "to match this '<'");
540 Lex.Lex(); // eat the '>'.
544 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
545 /// OptionalBitList ::= '{' RangeList '}'
546 /// OptionalBitList ::= /*empty*/
547 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
548 if (Lex.getCode() != tgtok::l_brace)
551 TGLoc StartLoc = Lex.getLoc();
552 Lex.Lex(); // eat the '{'
554 // Parse the range list.
555 Ranges = ParseRangeList();
556 if (Ranges.empty()) return true;
558 if (Lex.getCode() != tgtok::r_brace) {
559 TokError("expected '}' at end of bit list");
560 return Error(StartLoc, "to match this '{'");
562 Lex.Lex(); // eat the '}'.
567 /// ParseType - Parse and return a tblgen type. This returns null on error.
569 /// Type ::= STRING // string type
570 /// Type ::= BIT // bit type
571 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
572 /// Type ::= INT // int type
573 /// Type ::= LIST '<' Type '>' // list<x> type
574 /// Type ::= CODE // code type
575 /// Type ::= DAG // dag type
576 /// Type ::= ClassID // Record Type
578 RecTy *TGParser::ParseType() {
579 switch (Lex.getCode()) {
580 default: TokError("Unknown token when expecting a type"); return 0;
581 case tgtok::String: Lex.Lex(); return new StringRecTy();
582 case tgtok::Bit: Lex.Lex(); return new BitRecTy();
583 case tgtok::Int: Lex.Lex(); return new IntRecTy();
584 case tgtok::Code: Lex.Lex(); return new CodeRecTy();
585 case tgtok::Dag: Lex.Lex(); return new DagRecTy();
587 if (Record *R = ParseClassID()) return new RecordRecTy(R);
590 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
591 TokError("expected '<' after bits type");
594 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
595 TokError("expected integer in bits<n> type");
598 uint64_t Val = Lex.getCurIntVal();
599 if (Lex.Lex() != tgtok::greater) { // Eat count.
600 TokError("expected '>' at end of bits<n> type");
603 Lex.Lex(); // Eat '>'
604 return new BitsRecTy(Val);
607 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
608 TokError("expected '<' after list type");
611 Lex.Lex(); // Eat '<'
612 RecTy *SubType = ParseType();
613 if (SubType == 0) return 0;
615 if (Lex.getCode() != tgtok::greater) {
616 TokError("expected '>' at end of list<ty> type");
619 Lex.Lex(); // Eat '>'
620 return new ListRecTy(SubType);
625 /// ParseIDValue - Parse an ID as a value and decode what it means.
627 /// IDValue ::= ID [def local value]
628 /// IDValue ::= ID [def template arg]
629 /// IDValue ::= ID [multiclass local value]
630 /// IDValue ::= ID [multiclass template argument]
631 /// IDValue ::= ID [def name]
633 Init *TGParser::ParseIDValue(Record *CurRec) {
634 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
635 std::string Name = Lex.getCurStrVal();
636 TGLoc Loc = Lex.getLoc();
638 return ParseIDValue(CurRec, Name, Loc);
641 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
642 /// has already been read.
643 Init *TGParser::ParseIDValue(Record *CurRec,
644 const std::string &Name, TGLoc NameLoc) {
646 if (const RecordVal *RV = CurRec->getValue(Name))
647 return new VarInit(Name, RV->getType());
649 std::string TemplateArgName = CurRec->getName()+":"+Name;
650 if (CurRec->isTemplateArg(TemplateArgName)) {
651 const RecordVal *RV = CurRec->getValue(TemplateArgName);
652 assert(RV && "Template arg doesn't exist??");
653 return new VarInit(TemplateArgName, RV->getType());
658 std::string MCName = CurMultiClass->Rec.getName()+"::"+Name;
659 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
660 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
661 assert(RV && "Template arg doesn't exist??");
662 return new VarInit(MCName, RV->getType());
666 if (Record *D = Records.getDef(Name))
667 return new DefInit(D);
669 Error(NameLoc, "Variable not defined: '" + Name + "'");
673 /// ParseOperation - Parse an operator. This returns null on error.
675 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
677 Init *TGParser::ParseOperation(Record *CurRec) {
678 switch (Lex.getCode()) {
680 TokError("unknown operation");
686 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
687 UnOpInit::UnaryOp Code;
690 switch (Lex.getCode()) {
691 default: assert(0 && "Unhandled code!");
693 Lex.Lex(); // eat the operation
694 Code = UnOpInit::CAST;
696 Type = ParseOperatorType();
699 TokError("did not get type for unary operator");
705 Lex.Lex(); // eat the operation
706 Code = UnOpInit::CAR;
709 Lex.Lex(); // eat the operation
710 Code = UnOpInit::CDR;
713 Lex.Lex(); // eat the operation
714 Code = UnOpInit::LNULL;
718 if (Lex.getCode() != tgtok::l_paren) {
719 TokError("expected '(' after unary operator");
722 Lex.Lex(); // eat the '('
724 Init *LHS = ParseValue(CurRec);
725 if (LHS == 0) return 0;
727 if (Code == UnOpInit::CAR
728 || Code == UnOpInit::CDR
729 || Code == UnOpInit::LNULL) {
730 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
731 TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
732 if (LHSl == 0 && LHSt == 0) {
733 TokError("expected list type argument in unary operator");
737 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
739 TokError("expected list type argumnet in unary operator");
744 if (Code == UnOpInit::CAR
745 || Code == UnOpInit::CDR) {
746 if (LHSl && LHSl->getSize() == 0) {
747 TokError("empty list argument in unary operator");
751 Init *Item = LHSl->getElement(0);
752 TypedInit *Itemt = dynamic_cast<TypedInit*>(Item);
754 TokError("untyped list element in unary operator");
757 if (Code == UnOpInit::CAR) {
758 Type = Itemt->getType();
761 Type = new ListRecTy(Itemt->getType());
765 assert(LHSt && "expected list type argument in unary operator");
766 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
768 TokError("expected list type argumnet in unary operator");
771 if (Code == UnOpInit::CAR) {
772 Type = LType->getElementType();
781 if (Lex.getCode() != tgtok::r_paren) {
782 TokError("expected ')' in unary operator");
785 Lex.Lex(); // eat the ')'
786 return (new UnOpInit(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
793 case tgtok::XStrConcat:
794 case tgtok::XRegMatch:
795 case tgtok::XNameConcat: { // Value ::= !binop '(' Value ',' Value ')'
796 BinOpInit::BinaryOp Code;
800 switch (Lex.getCode()) {
801 default: assert(0 && "Unhandled code!");
803 Lex.Lex(); // eat the operation
804 Code = BinOpInit::CONCAT;
805 Type = new DagRecTy();
808 Lex.Lex(); // eat the operation
809 Code = BinOpInit::SRA;
810 Type = new IntRecTy();
813 Lex.Lex(); // eat the operation
814 Code = BinOpInit::SRL;
815 Type = new IntRecTy();
818 Lex.Lex(); // eat the operation
819 Code = BinOpInit::SHL;
820 Type = new IntRecTy();
822 case tgtok::XStrConcat:
823 Lex.Lex(); // eat the operation
824 Code = BinOpInit::STRCONCAT;
825 Type = new StringRecTy();
827 case tgtok::XRegMatch:
828 Lex.Lex(); // eat the operation
829 Code = BinOpInit::REGMATCH;
830 Type = new IntRecTy();
832 case tgtok::XNameConcat:
833 Lex.Lex(); // eat the operation
834 Code = BinOpInit::NAMECONCAT;
836 Type = ParseOperatorType();
839 TokError("did not get type for binary operator");
845 if (Lex.getCode() != tgtok::l_paren) {
846 TokError("expected '(' after binary operator");
849 Lex.Lex(); // eat the '('
851 Init *LHS = ParseValue(CurRec);
852 if (LHS == 0) return 0;
854 if (Lex.getCode() != tgtok::comma) {
855 TokError("expected ',' in binary operator");
858 Lex.Lex(); // eat the ','
860 Init *RHS = ParseValue(CurRec);
861 if (RHS == 0) return 0;
863 if (Lex.getCode() != tgtok::r_paren) {
864 TokError("expected ')' in binary operator");
867 Lex.Lex(); // eat the ')'
868 return (new BinOpInit(Code, LHS, RHS, Type))->Fold(CurRec, CurMultiClass);
872 case tgtok::XForEach:
873 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
874 TernOpInit::TernaryOp Code;
878 tgtok::TokKind LexCode = Lex.getCode();
879 Lex.Lex(); // eat the operation
881 default: assert(0 && "Unhandled code!");
883 Code = TernOpInit::IF;
885 case tgtok::XForEach:
886 Code = TernOpInit::FOREACH;
889 Code = TernOpInit::SUBST;
892 if (Lex.getCode() != tgtok::l_paren) {
893 TokError("expected '(' after ternary operator");
896 Lex.Lex(); // eat the '('
898 Init *LHS = ParseValue(CurRec);
899 if (LHS == 0) return 0;
901 if (Lex.getCode() != tgtok::comma) {
902 TokError("expected ',' in ternary operator");
905 Lex.Lex(); // eat the ','
907 Init *MHS = ParseValue(CurRec);
908 if (MHS == 0) return 0;
910 if (Lex.getCode() != tgtok::comma) {
911 TokError("expected ',' in ternary operator");
914 Lex.Lex(); // eat the ','
916 Init *RHS = ParseValue(CurRec);
917 if (RHS == 0) return 0;
919 if (Lex.getCode() != tgtok::r_paren) {
920 TokError("expected ')' in binary operator");
923 Lex.Lex(); // eat the ')'
926 default: assert(0 && "Unhandled code!");
928 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
929 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
930 if (MHSt == 0 || RHSt == 0) {
931 TokError("could not get type for !if");
934 if (MHSt->getType()->typeIsConvertibleTo(RHSt->getType())) {
935 Type = RHSt->getType();
937 else if (RHSt->getType()->typeIsConvertibleTo(MHSt->getType())) {
938 Type = MHSt->getType();
941 TokError("inconsistent types for !if");
946 case tgtok::XForEach: {
947 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
949 TokError("could not get type for !foreach");
952 Type = MHSt->getType();
955 case tgtok::XSubst: {
956 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
958 TokError("could not get type for !subst");
961 Type = RHSt->getType();
965 return (new TernOpInit(Code, LHS, MHS, RHS, Type))->Fold(CurRec, CurMultiClass);
968 TokError("could not parse operation");
972 /// ParseOperatorType - Parse a type for an operator. This returns
975 /// OperatorType ::= '<' Type '>'
977 RecTy *TGParser::ParseOperatorType(void) {
980 if (Lex.getCode() != tgtok::less) {
981 TokError("expected type name for operator");
984 Lex.Lex(); // eat the <
989 TokError("expected type name for operator");
993 if (Lex.getCode() != tgtok::greater) {
994 TokError("expected type name for operator");
997 Lex.Lex(); // eat the >
1003 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1005 /// SimpleValue ::= IDValue
1006 /// SimpleValue ::= INTVAL
1007 /// SimpleValue ::= STRVAL+
1008 /// SimpleValue ::= CODEFRAGMENT
1009 /// SimpleValue ::= '?'
1010 /// SimpleValue ::= '{' ValueList '}'
1011 /// SimpleValue ::= ID '<' ValueListNE '>'
1012 /// SimpleValue ::= '[' ValueList ']'
1013 /// SimpleValue ::= '(' IDValue DagArgList ')'
1014 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1015 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1016 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1017 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1018 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1020 Init *TGParser::ParseSimpleValue(Record *CurRec) {
1022 switch (Lex.getCode()) {
1023 default: TokError("Unknown token when parsing a value"); break;
1024 case tgtok::IntVal: R = new IntInit(Lex.getCurIntVal()); Lex.Lex(); break;
1025 case tgtok::StrVal: {
1026 std::string Val = Lex.getCurStrVal();
1029 // Handle multiple consecutive concatenated strings.
1030 while (Lex.getCode() == tgtok::StrVal) {
1031 Val += Lex.getCurStrVal();
1035 R = new StringInit(Val);
1038 case tgtok::CodeFragment:
1039 R = new CodeInit(Lex.getCurStrVal()); Lex.Lex(); break;
1040 case tgtok::question: R = new UnsetInit(); Lex.Lex(); break;
1042 TGLoc NameLoc = Lex.getLoc();
1043 std::string Name = Lex.getCurStrVal();
1044 if (Lex.Lex() != tgtok::less) // consume the Id.
1045 return ParseIDValue(CurRec, Name, NameLoc); // Value ::= IDValue
1047 // Value ::= ID '<' ValueListNE '>'
1048 if (Lex.Lex() == tgtok::greater) {
1049 TokError("expected non-empty value list");
1052 std::vector<Init*> ValueList = ParseValueList(CurRec);
1053 if (ValueList.empty()) return 0;
1055 if (Lex.getCode() != tgtok::greater) {
1056 TokError("expected '>' at end of value list");
1059 Lex.Lex(); // eat the '>'
1061 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1062 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1064 Record *Class = Records.getClass(Name);
1066 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1070 // Create the new record, set it as CurRec temporarily.
1071 static unsigned AnonCounter = 0;
1072 Record *NewRec = new Record("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 TGLoc 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 if (Lex.getCode() != tgtok::r_square) {
1118 Vals = ParseValueList(CurRec);
1119 if (Vals.empty()) return 0;
1121 if (Lex.getCode() != tgtok::r_square) {
1122 TokError("expected ']' at end of list value");
1125 Lex.Lex(); // eat the ']'
1126 return new ListInit(Vals);
1128 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1129 Lex.Lex(); // eat the '('
1130 if (Lex.getCode() != tgtok::Id
1131 && Lex.getCode() != tgtok::XCast
1132 && Lex.getCode() != tgtok::XNameConcat) {
1133 TokError("expected identifier in dag init");
1138 if (Lex.getCode() == tgtok::Id) {
1139 Operator = ParseIDValue(CurRec);
1140 if (Operator == 0) return 0;
1143 Operator = ParseOperation(CurRec);
1144 if (Operator == 0) return 0;
1147 // If the operator name is present, parse it.
1148 std::string OperatorName;
1149 if (Lex.getCode() == tgtok::colon) {
1150 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1151 TokError("expected variable name in dag operator");
1154 OperatorName = Lex.getCurStrVal();
1155 Lex.Lex(); // eat the VarName.
1158 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1159 if (Lex.getCode() != tgtok::r_paren) {
1160 DagArgs = ParseDagArgList(CurRec);
1161 if (DagArgs.empty()) return 0;
1164 if (Lex.getCode() != tgtok::r_paren) {
1165 TokError("expected ')' in dag init");
1168 Lex.Lex(); // eat the ')'
1170 return new DagInit(Operator, OperatorName, DagArgs);
1177 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1178 case tgtok::XConcat:
1182 case tgtok::XStrConcat:
1183 case tgtok::XRegMatch:
1184 case tgtok::XNameConcat: // Value ::= !binop '(' Value ',' Value ')'
1186 case tgtok::XForEach:
1187 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1188 return ParseOperation(CurRec);
1196 /// ParseValue - Parse a tblgen value. This returns null on error.
1198 /// Value ::= SimpleValue ValueSuffix*
1199 /// ValueSuffix ::= '{' BitList '}'
1200 /// ValueSuffix ::= '[' BitList ']'
1201 /// ValueSuffix ::= '.' ID
1203 Init *TGParser::ParseValue(Record *CurRec) {
1204 Init *Result = ParseSimpleValue(CurRec);
1205 if (Result == 0) return 0;
1207 // Parse the suffixes now if present.
1209 switch (Lex.getCode()) {
1210 default: return Result;
1211 case tgtok::l_brace: {
1212 TGLoc CurlyLoc = Lex.getLoc();
1213 Lex.Lex(); // eat the '{'
1214 std::vector<unsigned> Ranges = ParseRangeList();
1215 if (Ranges.empty()) return 0;
1217 // Reverse the bitlist.
1218 std::reverse(Ranges.begin(), Ranges.end());
1219 Result = Result->convertInitializerBitRange(Ranges);
1221 Error(CurlyLoc, "Invalid bit range for value");
1226 if (Lex.getCode() != tgtok::r_brace) {
1227 TokError("expected '}' at end of bit range list");
1233 case tgtok::l_square: {
1234 TGLoc SquareLoc = Lex.getLoc();
1235 Lex.Lex(); // eat the '['
1236 std::vector<unsigned> Ranges = ParseRangeList();
1237 if (Ranges.empty()) return 0;
1239 Result = Result->convertInitListSlice(Ranges);
1241 Error(SquareLoc, "Invalid range for list slice");
1246 if (Lex.getCode() != tgtok::r_square) {
1247 TokError("expected ']' at end of list slice");
1254 if (Lex.Lex() != tgtok::Id) { // eat the .
1255 TokError("expected field identifier after '.'");
1258 if (!Result->getFieldType(Lex.getCurStrVal())) {
1259 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1260 Result->getAsString() + "'");
1263 Result = new FieldInit(Result, Lex.getCurStrVal());
1264 Lex.Lex(); // eat field name
1270 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1272 /// ParseDagArgList ::= Value (':' VARNAME)?
1273 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1274 std::vector<std::pair<llvm::Init*, std::string> >
1275 TGParser::ParseDagArgList(Record *CurRec) {
1276 std::vector<std::pair<llvm::Init*, std::string> > Result;
1279 Init *Val = ParseValue(CurRec);
1280 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1282 // If the variable name is present, add it.
1283 std::string VarName;
1284 if (Lex.getCode() == tgtok::colon) {
1285 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1286 TokError("expected variable name in dag literal");
1287 return std::vector<std::pair<llvm::Init*, std::string> >();
1289 VarName = Lex.getCurStrVal();
1290 Lex.Lex(); // eat the VarName.
1293 Result.push_back(std::make_pair(Val, VarName));
1295 if (Lex.getCode() != tgtok::comma) break;
1296 Lex.Lex(); // eat the ','
1303 /// ParseValueList - Parse a comma separated list of values, returning them as a
1304 /// vector. Note that this always expects to be able to parse at least one
1305 /// value. It returns an empty list if this is not possible.
1307 /// ValueList ::= Value (',' Value)
1309 std::vector<Init*> TGParser::ParseValueList(Record *CurRec) {
1310 std::vector<Init*> Result;
1311 Result.push_back(ParseValue(CurRec));
1312 if (Result.back() == 0) return std::vector<Init*>();
1314 while (Lex.getCode() == tgtok::comma) {
1315 Lex.Lex(); // Eat the comma
1317 Result.push_back(ParseValue(CurRec));
1318 if (Result.back() == 0) return std::vector<Init*>();
1326 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1327 /// empty string on error. This can happen in a number of different context's,
1328 /// including within a def or in the template args for a def (which which case
1329 /// CurRec will be non-null) and within the template args for a multiclass (in
1330 /// which case CurRec will be null, but CurMultiClass will be set). This can
1331 /// also happen within a def that is within a multiclass, which will set both
1332 /// CurRec and CurMultiClass.
1334 /// Declaration ::= FIELD? Type ID ('=' Value)?
1336 std::string TGParser::ParseDeclaration(Record *CurRec,
1337 bool ParsingTemplateArgs) {
1338 // Read the field prefix if present.
1339 bool HasField = Lex.getCode() == tgtok::Field;
1340 if (HasField) Lex.Lex();
1342 RecTy *Type = ParseType();
1343 if (Type == 0) return "";
1345 if (Lex.getCode() != tgtok::Id) {
1346 TokError("Expected identifier in declaration");
1350 TGLoc IdLoc = Lex.getLoc();
1351 std::string DeclName = Lex.getCurStrVal();
1354 if (ParsingTemplateArgs) {
1356 DeclName = CurRec->getName() + ":" + DeclName;
1358 assert(CurMultiClass);
1361 DeclName = CurMultiClass->Rec.getName() + "::" + DeclName;
1365 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1368 // If a value is present, parse it.
1369 if (Lex.getCode() == tgtok::equal) {
1371 TGLoc ValLoc = Lex.getLoc();
1372 Init *Val = ParseValue(CurRec);
1374 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1381 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1382 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1383 /// template args for a def, which may or may not be in a multiclass. If null,
1384 /// these are the template args for a multiclass.
1386 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1388 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1389 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1390 Lex.Lex(); // eat the '<'
1392 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1394 // Read the first declaration.
1395 std::string TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1396 if (TemplArg.empty())
1399 TheRecToAddTo->addTemplateArg(TemplArg);
1401 while (Lex.getCode() == tgtok::comma) {
1402 Lex.Lex(); // eat the ','
1404 // Read the following declarations.
1405 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1406 if (TemplArg.empty())
1408 TheRecToAddTo->addTemplateArg(TemplArg);
1411 if (Lex.getCode() != tgtok::greater)
1412 return TokError("expected '>' at end of template argument list");
1413 Lex.Lex(); // eat the '>'.
1418 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1420 /// BodyItem ::= Declaration ';'
1421 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1422 bool TGParser::ParseBodyItem(Record *CurRec) {
1423 if (Lex.getCode() != tgtok::Let) {
1424 if (ParseDeclaration(CurRec, false).empty())
1427 if (Lex.getCode() != tgtok::semi)
1428 return TokError("expected ';' after declaration");
1433 // LET ID OptionalRangeList '=' Value ';'
1434 if (Lex.Lex() != tgtok::Id)
1435 return TokError("expected field identifier after let");
1437 TGLoc IdLoc = Lex.getLoc();
1438 std::string FieldName = Lex.getCurStrVal();
1439 Lex.Lex(); // eat the field name.
1441 std::vector<unsigned> BitList;
1442 if (ParseOptionalBitList(BitList))
1444 std::reverse(BitList.begin(), BitList.end());
1446 if (Lex.getCode() != tgtok::equal)
1447 return TokError("expected '=' in let expression");
1448 Lex.Lex(); // eat the '='.
1450 Init *Val = ParseValue(CurRec);
1451 if (Val == 0) return true;
1453 if (Lex.getCode() != tgtok::semi)
1454 return TokError("expected ';' after let expression");
1457 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1460 /// ParseBody - Read the body of a class or def. Return true on error, false on
1464 /// Body ::= '{' BodyList '}'
1465 /// BodyList BodyItem*
1467 bool TGParser::ParseBody(Record *CurRec) {
1468 // If this is a null definition, just eat the semi and return.
1469 if (Lex.getCode() == tgtok::semi) {
1474 if (Lex.getCode() != tgtok::l_brace)
1475 return TokError("Expected ';' or '{' to start body");
1479 while (Lex.getCode() != tgtok::r_brace)
1480 if (ParseBodyItem(CurRec))
1488 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1489 /// optional ClassList followed by a Body. CurRec is the current def or class
1490 /// that is being parsed.
1492 /// ObjectBody ::= BaseClassList Body
1493 /// BaseClassList ::= /*empty*/
1494 /// BaseClassList ::= ':' BaseClassListNE
1495 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1497 bool TGParser::ParseObjectBody(Record *CurRec) {
1498 // If there is a baseclass list, read it.
1499 if (Lex.getCode() == tgtok::colon) {
1502 // Read all of the subclasses.
1503 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1506 if (SubClass.Rec == 0) return true;
1509 if (AddSubClass(CurRec, SubClass))
1512 if (Lex.getCode() != tgtok::comma) break;
1513 Lex.Lex(); // eat ','.
1514 SubClass = ParseSubClassReference(CurRec, false);
1518 // Process any variables on the let stack.
1519 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1520 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1521 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1522 LetStack[i][j].Bits, LetStack[i][j].Value))
1525 return ParseBody(CurRec);
1529 /// ParseDef - Parse and return a top level or multiclass def, return the record
1530 /// corresponding to it. This returns null on error.
1532 /// DefInst ::= DEF ObjectName ObjectBody
1534 llvm::Record *TGParser::ParseDef(MultiClass *CurMultiClass) {
1535 TGLoc DefLoc = Lex.getLoc();
1536 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1537 Lex.Lex(); // Eat the 'def' token.
1539 // Parse ObjectName and make a record for it.
1540 Record *CurRec = new Record(ParseObjectName(), DefLoc);
1542 if (!CurMultiClass) {
1543 // Top-level def definition.
1545 // Ensure redefinition doesn't happen.
1546 if (Records.getDef(CurRec->getName())) {
1547 Error(DefLoc, "def '" + CurRec->getName() + "' already defined");
1550 Records.addDef(CurRec);
1552 // Otherwise, a def inside a multiclass, add it to the multiclass.
1553 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1554 if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
1555 Error(DefLoc, "def '" + CurRec->getName() +
1556 "' already defined in this multiclass!");
1559 CurMultiClass->DefPrototypes.push_back(CurRec);
1562 if (ParseObjectBody(CurRec))
1565 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1566 CurRec->resolveReferences();
1568 // If ObjectBody has template arguments, it's an error.
1569 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1574 /// ParseClass - Parse a tblgen class definition.
1576 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1578 bool TGParser::ParseClass() {
1579 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1582 if (Lex.getCode() != tgtok::Id)
1583 return TokError("expected class name after 'class' keyword");
1585 Record *CurRec = Records.getClass(Lex.getCurStrVal());
1587 // If the body was previously defined, this is an error.
1588 if (!CurRec->getValues().empty() ||
1589 !CurRec->getSuperClasses().empty() ||
1590 !CurRec->getTemplateArgs().empty())
1591 return TokError("Class '" + CurRec->getName() + "' already defined");
1593 // If this is the first reference to this class, create and add it.
1594 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc());
1595 Records.addClass(CurRec);
1597 Lex.Lex(); // eat the name.
1599 // If there are template args, parse them.
1600 if (Lex.getCode() == tgtok::less)
1601 if (ParseTemplateArgList(CurRec))
1604 // Finally, parse the object body.
1605 return ParseObjectBody(CurRec);
1608 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1611 /// LetList ::= LetItem (',' LetItem)*
1612 /// LetItem ::= ID OptionalRangeList '=' Value
1614 std::vector<LetRecord> TGParser::ParseLetList() {
1615 std::vector<LetRecord> Result;
1618 if (Lex.getCode() != tgtok::Id) {
1619 TokError("expected identifier in let definition");
1620 return std::vector<LetRecord>();
1622 std::string Name = Lex.getCurStrVal();
1623 TGLoc NameLoc = Lex.getLoc();
1624 Lex.Lex(); // Eat the identifier.
1626 // Check for an optional RangeList.
1627 std::vector<unsigned> Bits;
1628 if (ParseOptionalRangeList(Bits))
1629 return std::vector<LetRecord>();
1630 std::reverse(Bits.begin(), Bits.end());
1632 if (Lex.getCode() != tgtok::equal) {
1633 TokError("expected '=' in let expression");
1634 return std::vector<LetRecord>();
1636 Lex.Lex(); // eat the '='.
1638 Init *Val = ParseValue(0);
1639 if (Val == 0) return std::vector<LetRecord>();
1641 // Now that we have everything, add the record.
1642 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1644 if (Lex.getCode() != tgtok::comma)
1646 Lex.Lex(); // eat the comma.
1650 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
1651 /// different related productions.
1653 /// Object ::= LET LetList IN '{' ObjectList '}'
1654 /// Object ::= LET LetList IN Object
1656 bool TGParser::ParseTopLevelLet() {
1657 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1660 // Add this entry to the let stack.
1661 std::vector<LetRecord> LetInfo = ParseLetList();
1662 if (LetInfo.empty()) return true;
1663 LetStack.push_back(LetInfo);
1665 if (Lex.getCode() != tgtok::In)
1666 return TokError("expected 'in' at end of top-level 'let'");
1669 // If this is a scalar let, just handle it now
1670 if (Lex.getCode() != tgtok::l_brace) {
1671 // LET LetList IN Object
1674 } else { // Object ::= LETCommand '{' ObjectList '}'
1675 TGLoc BraceLoc = Lex.getLoc();
1676 // Otherwise, this is a group let.
1677 Lex.Lex(); // eat the '{'.
1679 // Parse the object list.
1680 if (ParseObjectList())
1683 if (Lex.getCode() != tgtok::r_brace) {
1684 TokError("expected '}' at end of top level let command");
1685 return Error(BraceLoc, "to match this '{'");
1690 // Outside this let scope, this let block is not active.
1691 LetStack.pop_back();
1695 /// ParseMultiClassDef - Parse a def in a multiclass context.
1697 /// MultiClassDef ::= DefInst
1699 bool TGParser::ParseMultiClassDef(MultiClass *CurMC) {
1700 if (Lex.getCode() != tgtok::Def)
1701 return TokError("expected 'def' in multiclass body");
1703 Record *D = ParseDef(CurMC);
1704 if (D == 0) return true;
1706 // Copy the template arguments for the multiclass into the def.
1707 const std::vector<std::string> &TArgs = CurMC->Rec.getTemplateArgs();
1709 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1710 const RecordVal *RV = CurMC->Rec.getValue(TArgs[i]);
1711 assert(RV && "Template arg doesn't exist?");
1718 /// ParseMultiClass - Parse a multiclass definition.
1720 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
1721 /// ':' BaseMultiClassList '{' MultiClassDef+ '}'
1723 bool TGParser::ParseMultiClass() {
1724 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1725 Lex.Lex(); // Eat the multiclass token.
1727 if (Lex.getCode() != tgtok::Id)
1728 return TokError("expected identifier after multiclass for name");
1729 std::string Name = Lex.getCurStrVal();
1731 if (MultiClasses.count(Name))
1732 return TokError("multiclass '" + Name + "' already defined");
1734 CurMultiClass = MultiClasses[Name] = new MultiClass(Name, Lex.getLoc());
1735 Lex.Lex(); // Eat the identifier.
1737 // If there are template args, parse them.
1738 if (Lex.getCode() == tgtok::less)
1739 if (ParseTemplateArgList(0))
1742 bool inherits = false;
1744 // If there are submulticlasses, parse them.
1745 if (Lex.getCode() == tgtok::colon) {
1750 // Read all of the submulticlasses.
1751 SubMultiClassReference SubMultiClass =
1752 ParseSubMultiClassReference(CurMultiClass);
1755 if (SubMultiClass.MC == 0) return true;
1758 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
1761 if (Lex.getCode() != tgtok::comma) break;
1762 Lex.Lex(); // eat ','.
1763 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
1767 if (Lex.getCode() != tgtok::l_brace) {
1769 return TokError("expected '{' in multiclass definition");
1771 if (Lex.getCode() != tgtok::semi)
1772 return TokError("expected ';' in multiclass definition");
1774 Lex.Lex(); // eat the ';'.
1777 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
1778 return TokError("multiclass must contain at least one def");
1780 while (Lex.getCode() != tgtok::r_brace)
1781 if (ParseMultiClassDef(CurMultiClass))
1784 Lex.Lex(); // eat the '}'.
1791 /// ParseDefm - Parse the instantiation of a multiclass.
1793 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
1795 bool TGParser::ParseDefm() {
1796 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
1797 if (Lex.Lex() != tgtok::Id) // eat the defm.
1798 return TokError("expected identifier after defm");
1800 TGLoc DefmPrefixLoc = Lex.getLoc();
1801 std::string DefmPrefix = Lex.getCurStrVal();
1802 if (Lex.Lex() != tgtok::colon)
1803 return TokError("expected ':' after defm identifier");
1808 TGLoc SubClassLoc = Lex.getLoc();
1809 SubClassReference Ref = ParseSubClassReference(0, true);
1812 if (Ref.Rec == 0) return true;
1814 // To instantiate a multiclass, we need to first get the multiclass, then
1815 // instantiate each def contained in the multiclass with the SubClassRef
1816 // template parameters.
1817 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
1818 assert(MC && "Didn't lookup multiclass correctly?");
1819 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
1821 // Verify that the correct number of template arguments were specified.
1822 const std::vector<std::string> &TArgs = MC->Rec.getTemplateArgs();
1823 if (TArgs.size() < TemplateVals.size())
1824 return Error(SubClassLoc,
1825 "more template args specified than multiclass expects");
1827 // Loop over all the def's in the multiclass, instantiating each one.
1828 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
1829 Record *DefProto = MC->DefPrototypes[i];
1831 // Add in the defm name
1832 std::string DefName = DefProto->getName();
1833 std::string::size_type idx = DefName.find("#NAME#");
1834 if (idx != std::string::npos) {
1835 DefName.replace(idx, 6, DefmPrefix);
1838 // Add the suffix to the defm name to get the new name.
1839 DefName = DefmPrefix + DefName;
1842 Record *CurRec = new Record(DefName, DefmPrefixLoc);
1844 SubClassReference Ref;
1845 Ref.RefLoc = DefmPrefixLoc;
1847 AddSubClass(CurRec, Ref);
1849 // Loop over all of the template arguments, setting them to the specified
1850 // value or leaving them as the default if necessary.
1851 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1852 // Check if a value is specified for this temp-arg.
1853 if (i < TemplateVals.size()) {
1855 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
1860 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
1863 CurRec->removeValue(TArgs[i]);
1865 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
1866 return Error(SubClassLoc,
1867 "value not specified for template argument #"+
1868 utostr(i) + " (" + TArgs[i] + ") of multiclassclass '" +
1869 MC->Rec.getName() + "'");
1873 // If the mdef is inside a 'let' expression, add to each def.
1874 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1875 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1876 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1877 LetStack[i][j].Bits, LetStack[i][j].Value)) {
1878 Error(DefmPrefixLoc, "when instantiating this defm");
1882 // Ensure redefinition doesn't happen.
1883 if (Records.getDef(CurRec->getName()))
1884 return Error(DefmPrefixLoc, "def '" + CurRec->getName() +
1885 "' already defined, instantiating defm with subdef '" +
1886 DefProto->getName() + "'");
1887 Records.addDef(CurRec);
1888 CurRec->resolveReferences();
1891 if (Lex.getCode() != tgtok::comma) break;
1892 Lex.Lex(); // eat ','.
1894 SubClassLoc = Lex.getLoc();
1895 Ref = ParseSubClassReference(0, true);
1898 if (Lex.getCode() != tgtok::semi)
1899 return TokError("expected ';' at end of defm");
1906 /// Object ::= ClassInst
1907 /// Object ::= DefInst
1908 /// Object ::= MultiClassInst
1909 /// Object ::= DefMInst
1910 /// Object ::= LETCommand '{' ObjectList '}'
1911 /// Object ::= LETCommand Object
1912 bool TGParser::ParseObject() {
1913 switch (Lex.getCode()) {
1914 default: assert(0 && "This is not an object");
1915 case tgtok::Let: return ParseTopLevelLet();
1916 case tgtok::Def: return ParseDef(0) == 0;
1917 case tgtok::Defm: return ParseDefm();
1918 case tgtok::Class: return ParseClass();
1919 case tgtok::MultiClass: return ParseMultiClass();
1924 /// ObjectList :== Object*
1925 bool TGParser::ParseObjectList() {
1926 while (isObjectStart(Lex.getCode())) {
1934 bool TGParser::ParseFile() {
1935 Lex.Lex(); // Prime the lexer.
1936 if (ParseObjectList()) return true;
1938 // If we have unread input at the end of the file, report it.
1939 if (Lex.getCode() == tgtok::Eof)
1942 return TokError("Unexpected input at top level");