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"
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 errs() << "Multiclass:\n";
51 errs() << "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, SMLoc 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, SMLoc 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 static std::string GetNewAnonymousName() {
299 static unsigned AnonCounter = 0;
300 return "anonymous."+utostr(AnonCounter++);
303 /// ParseObjectName - If an object name is specified, return it. Otherwise,
304 /// return an anonymous name.
305 /// ObjectName ::= ID
306 /// ObjectName ::= /*empty*/
308 std::string TGParser::ParseObjectName() {
309 if (Lex.getCode() != tgtok::Id)
310 return GetNewAnonymousName();
312 std::string Ret = Lex.getCurStrVal();
318 /// ParseClassID - Parse and resolve a reference to a class name. This returns
323 Record *TGParser::ParseClassID() {
324 if (Lex.getCode() != tgtok::Id) {
325 TokError("expected name for ClassID");
329 Record *Result = Records.getClass(Lex.getCurStrVal());
331 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
337 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
338 /// This returns null on error.
340 /// MultiClassID ::= ID
342 MultiClass *TGParser::ParseMultiClassID() {
343 if (Lex.getCode() != tgtok::Id) {
344 TokError("expected name for ClassID");
348 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
350 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
356 Record *TGParser::ParseDefmID() {
357 if (Lex.getCode() != tgtok::Id) {
358 TokError("expected multiclass name");
362 MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
364 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
373 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
374 /// subclass. This returns a SubClassRefTy with a null Record* on error.
376 /// SubClassRef ::= ClassID
377 /// SubClassRef ::= ClassID '<' ValueList '>'
379 SubClassReference TGParser::
380 ParseSubClassReference(Record *CurRec, bool isDefm) {
381 SubClassReference Result;
382 Result.RefLoc = Lex.getLoc();
385 Result.Rec = ParseDefmID();
387 Result.Rec = ParseClassID();
388 if (Result.Rec == 0) return Result;
390 // If there is no template arg list, we're done.
391 if (Lex.getCode() != tgtok::less)
393 Lex.Lex(); // Eat the '<'
395 if (Lex.getCode() == tgtok::greater) {
396 TokError("subclass reference requires a non-empty list of template values");
401 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
402 if (Result.TemplateArgs.empty()) {
403 Result.Rec = 0; // Error parsing value list.
407 if (Lex.getCode() != tgtok::greater) {
408 TokError("expected '>' in template value list");
417 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
418 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
419 /// Record* on error.
421 /// SubMultiClassRef ::= MultiClassID
422 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
424 SubMultiClassReference TGParser::
425 ParseSubMultiClassReference(MultiClass *CurMC) {
426 SubMultiClassReference Result;
427 Result.RefLoc = Lex.getLoc();
429 Result.MC = ParseMultiClassID();
430 if (Result.MC == 0) return Result;
432 // If there is no template arg list, we're done.
433 if (Lex.getCode() != tgtok::less)
435 Lex.Lex(); // Eat the '<'
437 if (Lex.getCode() == tgtok::greater) {
438 TokError("subclass reference requires a non-empty list of template values");
443 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
444 if (Result.TemplateArgs.empty()) {
445 Result.MC = 0; // Error parsing value list.
449 if (Lex.getCode() != tgtok::greater) {
450 TokError("expected '>' in template value list");
459 /// ParseRangePiece - Parse a bit/value range.
460 /// RangePiece ::= INTVAL
461 /// RangePiece ::= INTVAL '-' INTVAL
462 /// RangePiece ::= INTVAL INTVAL
463 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
464 if (Lex.getCode() != tgtok::IntVal) {
465 TokError("expected integer or bitrange");
468 int64_t Start = Lex.getCurIntVal();
472 return TokError("invalid range, cannot be negative");
474 switch (Lex.Lex()) { // eat first character.
476 Ranges.push_back(Start);
479 if (Lex.Lex() != tgtok::IntVal) {
480 TokError("expected integer value as end of range");
483 End = Lex.getCurIntVal();
486 End = -Lex.getCurIntVal();
490 return TokError("invalid range, cannot be negative");
495 for (; Start <= End; ++Start)
496 Ranges.push_back(Start);
498 for (; Start >= End; --Start)
499 Ranges.push_back(Start);
504 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
506 /// RangeList ::= RangePiece (',' RangePiece)*
508 std::vector<unsigned> TGParser::ParseRangeList() {
509 std::vector<unsigned> Result;
511 // Parse the first piece.
512 if (ParseRangePiece(Result))
513 return std::vector<unsigned>();
514 while (Lex.getCode() == tgtok::comma) {
515 Lex.Lex(); // Eat the comma.
517 // Parse the next range piece.
518 if (ParseRangePiece(Result))
519 return std::vector<unsigned>();
524 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
525 /// OptionalRangeList ::= '<' RangeList '>'
526 /// OptionalRangeList ::= /*empty*/
527 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
528 if (Lex.getCode() != tgtok::less)
531 SMLoc StartLoc = Lex.getLoc();
532 Lex.Lex(); // eat the '<'
534 // Parse the range list.
535 Ranges = ParseRangeList();
536 if (Ranges.empty()) return true;
538 if (Lex.getCode() != tgtok::greater) {
539 TokError("expected '>' at end of range list");
540 return Error(StartLoc, "to match this '<'");
542 Lex.Lex(); // eat the '>'.
546 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
547 /// OptionalBitList ::= '{' RangeList '}'
548 /// OptionalBitList ::= /*empty*/
549 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
550 if (Lex.getCode() != tgtok::l_brace)
553 SMLoc StartLoc = Lex.getLoc();
554 Lex.Lex(); // eat the '{'
556 // Parse the range list.
557 Ranges = ParseRangeList();
558 if (Ranges.empty()) return true;
560 if (Lex.getCode() != tgtok::r_brace) {
561 TokError("expected '}' at end of bit list");
562 return Error(StartLoc, "to match this '{'");
564 Lex.Lex(); // eat the '}'.
569 /// ParseType - Parse and return a tblgen type. This returns null on error.
571 /// Type ::= STRING // string type
572 /// Type ::= BIT // bit type
573 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
574 /// Type ::= INT // int type
575 /// Type ::= LIST '<' Type '>' // list<x> type
576 /// Type ::= CODE // code type
577 /// Type ::= DAG // dag type
578 /// Type ::= ClassID // Record Type
580 RecTy *TGParser::ParseType() {
581 switch (Lex.getCode()) {
582 default: TokError("Unknown token when expecting a type"); return 0;
583 case tgtok::String: Lex.Lex(); return new StringRecTy();
584 case tgtok::Bit: Lex.Lex(); return new BitRecTy();
585 case tgtok::Int: Lex.Lex(); return new IntRecTy();
586 case tgtok::Code: Lex.Lex(); return new CodeRecTy();
587 case tgtok::Dag: Lex.Lex(); return new DagRecTy();
589 if (Record *R = ParseClassID()) return new RecordRecTy(R);
592 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
593 TokError("expected '<' after bits type");
596 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
597 TokError("expected integer in bits<n> type");
600 uint64_t Val = Lex.getCurIntVal();
601 if (Lex.Lex() != tgtok::greater) { // Eat count.
602 TokError("expected '>' at end of bits<n> type");
605 Lex.Lex(); // Eat '>'
606 return new BitsRecTy(Val);
609 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
610 TokError("expected '<' after list type");
613 Lex.Lex(); // Eat '<'
614 RecTy *SubType = ParseType();
615 if (SubType == 0) return 0;
617 if (Lex.getCode() != tgtok::greater) {
618 TokError("expected '>' at end of list<ty> type");
621 Lex.Lex(); // Eat '>'
622 return new ListRecTy(SubType);
627 /// ParseIDValue - Parse an ID as a value and decode what it means.
629 /// IDValue ::= ID [def local value]
630 /// IDValue ::= ID [def template arg]
631 /// IDValue ::= ID [multiclass local value]
632 /// IDValue ::= ID [multiclass template argument]
633 /// IDValue ::= ID [def name]
635 Init *TGParser::ParseIDValue(Record *CurRec) {
636 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
637 std::string Name = Lex.getCurStrVal();
638 SMLoc Loc = Lex.getLoc();
640 return ParseIDValue(CurRec, Name, Loc);
643 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
644 /// has already been read.
645 Init *TGParser::ParseIDValue(Record *CurRec,
646 const std::string &Name, SMLoc NameLoc) {
648 if (const RecordVal *RV = CurRec->getValue(Name))
649 return new VarInit(Name, RV->getType());
651 std::string TemplateArgName = CurRec->getName()+":"+Name;
652 if (CurRec->isTemplateArg(TemplateArgName)) {
653 const RecordVal *RV = CurRec->getValue(TemplateArgName);
654 assert(RV && "Template arg doesn't exist??");
655 return new VarInit(TemplateArgName, RV->getType());
660 std::string MCName = CurMultiClass->Rec.getName()+"::"+Name;
661 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
662 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
663 assert(RV && "Template arg doesn't exist??");
664 return new VarInit(MCName, RV->getType());
668 if (Record *D = Records.getDef(Name))
669 return new DefInit(D);
671 Error(NameLoc, "Variable not defined: '" + Name + "'");
675 /// ParseOperation - Parse an operator. This returns null on error.
677 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
679 Init *TGParser::ParseOperation(Record *CurRec) {
680 switch (Lex.getCode()) {
682 TokError("unknown operation");
688 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
689 UnOpInit::UnaryOp Code;
692 switch (Lex.getCode()) {
693 default: assert(0 && "Unhandled code!");
695 Lex.Lex(); // eat the operation
696 Code = UnOpInit::CAST;
698 Type = ParseOperatorType();
701 TokError("did not get type for unary operator");
707 Lex.Lex(); // eat the operation
708 Code = UnOpInit::CAR;
711 Lex.Lex(); // eat the operation
712 Code = UnOpInit::CDR;
715 Lex.Lex(); // eat the operation
716 Code = UnOpInit::LNULL;
720 if (Lex.getCode() != tgtok::l_paren) {
721 TokError("expected '(' after unary operator");
724 Lex.Lex(); // eat the '('
726 Init *LHS = ParseValue(CurRec);
727 if (LHS == 0) return 0;
729 if (Code == UnOpInit::CAR
730 || Code == UnOpInit::CDR
731 || Code == UnOpInit::LNULL) {
732 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
733 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
734 TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
735 if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
736 TokError("expected list or string type argument in unary operator");
740 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
741 StringRecTy *SType = dynamic_cast<StringRecTy*>(LHSt->getType());
742 if (LType == 0 && SType == 0) {
743 TokError("expected list or string type argumnet in unary operator");
748 if (Code == UnOpInit::CAR
749 || Code == UnOpInit::CDR) {
750 if (LHSl == 0 && LHSt == 0) {
751 TokError("expected list type argumnet in unary operator");
755 if (LHSl && LHSl->getSize() == 0) {
756 TokError("empty list argument in unary operator");
760 Init *Item = LHSl->getElement(0);
761 TypedInit *Itemt = dynamic_cast<TypedInit*>(Item);
763 TokError("untyped list element in unary operator");
766 if (Code == UnOpInit::CAR) {
767 Type = Itemt->getType();
769 Type = new ListRecTy(Itemt->getType());
772 assert(LHSt && "expected list type argument in unary operator");
773 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
775 TokError("expected list type argumnet in unary operator");
778 if (Code == UnOpInit::CAR) {
779 Type = LType->getElementType();
787 if (Lex.getCode() != tgtok::r_paren) {
788 TokError("expected ')' in unary operator");
791 Lex.Lex(); // eat the ')'
792 return (new UnOpInit(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
800 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
801 tgtok::TokKind OpTok = Lex.getCode();
802 SMLoc OpLoc = Lex.getLoc();
803 Lex.Lex(); // eat the operation
805 BinOpInit::BinaryOp Code;
809 default: assert(0 && "Unhandled code!");
810 case tgtok::XConcat: Code = BinOpInit::CONCAT; Type = new DagRecTy(); break;
811 case tgtok::XSRA: Code = BinOpInit::SRA; Type = new IntRecTy(); break;
812 case tgtok::XSRL: Code = BinOpInit::SRL; Type = new IntRecTy(); break;
813 case tgtok::XSHL: Code = BinOpInit::SHL; Type = new IntRecTy(); break;
814 case tgtok::XEq: Code = BinOpInit::EQ; Type = new IntRecTy(); break;
815 case tgtok::XStrConcat:
816 Code = BinOpInit::STRCONCAT;
817 Type = new StringRecTy();
821 if (Lex.getCode() != tgtok::l_paren) {
822 TokError("expected '(' after binary operator");
825 Lex.Lex(); // eat the '('
827 SmallVector<Init*, 2> InitList;
829 InitList.push_back(ParseValue(CurRec));
830 if (InitList.back() == 0) return 0;
832 while (Lex.getCode() == tgtok::comma) {
833 Lex.Lex(); // eat the ','
835 InitList.push_back(ParseValue(CurRec));
836 if (InitList.back() == 0) return 0;
839 if (Lex.getCode() != tgtok::r_paren) {
840 TokError("expected ')' in operator");
843 Lex.Lex(); // eat the ')'
845 // We allow multiple operands to associative operators like !strconcat as
846 // shorthand for nesting them.
847 if (Code == BinOpInit::STRCONCAT) {
848 while (InitList.size() > 2) {
849 Init *RHS = InitList.pop_back_val();
850 RHS = (new BinOpInit(Code, InitList.back(), RHS, Type))
851 ->Fold(CurRec, CurMultiClass);
852 InitList.back() = RHS;
856 if (InitList.size() == 2)
857 return (new BinOpInit(Code, InitList[0], InitList[1], Type))
858 ->Fold(CurRec, CurMultiClass);
860 Error(OpLoc, "expected two operands to operator");
865 case tgtok::XForEach:
866 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
867 TernOpInit::TernaryOp Code;
871 tgtok::TokKind LexCode = Lex.getCode();
872 Lex.Lex(); // eat the operation
874 default: assert(0 && "Unhandled code!");
876 Code = TernOpInit::IF;
878 case tgtok::XForEach:
879 Code = TernOpInit::FOREACH;
882 Code = TernOpInit::SUBST;
885 if (Lex.getCode() != tgtok::l_paren) {
886 TokError("expected '(' after ternary operator");
889 Lex.Lex(); // eat the '('
891 Init *LHS = ParseValue(CurRec);
892 if (LHS == 0) return 0;
894 if (Lex.getCode() != tgtok::comma) {
895 TokError("expected ',' in ternary operator");
898 Lex.Lex(); // eat the ','
900 Init *MHS = ParseValue(CurRec);
901 if (MHS == 0) return 0;
903 if (Lex.getCode() != tgtok::comma) {
904 TokError("expected ',' in ternary operator");
907 Lex.Lex(); // eat the ','
909 Init *RHS = ParseValue(CurRec);
910 if (RHS == 0) return 0;
912 if (Lex.getCode() != tgtok::r_paren) {
913 TokError("expected ')' in binary operator");
916 Lex.Lex(); // eat the ')'
919 default: assert(0 && "Unhandled code!");
921 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
922 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
923 if (MHSt == 0 || RHSt == 0) {
924 TokError("could not get type for !if");
927 if (MHSt->getType()->typeIsConvertibleTo(RHSt->getType())) {
928 Type = RHSt->getType();
929 } else if (RHSt->getType()->typeIsConvertibleTo(MHSt->getType())) {
930 Type = MHSt->getType();
932 TokError("inconsistent types for !if");
937 case tgtok::XForEach: {
938 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
940 TokError("could not get type for !foreach");
943 Type = MHSt->getType();
946 case tgtok::XSubst: {
947 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
949 TokError("could not get type for !subst");
952 Type = RHSt->getType();
956 return (new TernOpInit(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
960 TokError("could not parse operation");
964 /// ParseOperatorType - Parse a type for an operator. This returns
967 /// OperatorType ::= '<' Type '>'
969 RecTy *TGParser::ParseOperatorType() {
972 if (Lex.getCode() != tgtok::less) {
973 TokError("expected type name for operator");
976 Lex.Lex(); // eat the <
981 TokError("expected type name for operator");
985 if (Lex.getCode() != tgtok::greater) {
986 TokError("expected type name for operator");
989 Lex.Lex(); // eat the >
995 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
997 /// SimpleValue ::= IDValue
998 /// SimpleValue ::= INTVAL
999 /// SimpleValue ::= STRVAL+
1000 /// SimpleValue ::= CODEFRAGMENT
1001 /// SimpleValue ::= '?'
1002 /// SimpleValue ::= '{' ValueList '}'
1003 /// SimpleValue ::= ID '<' ValueListNE '>'
1004 /// SimpleValue ::= '[' ValueList ']'
1005 /// SimpleValue ::= '(' IDValue DagArgList ')'
1006 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1007 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1008 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1009 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1010 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1012 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType) {
1014 switch (Lex.getCode()) {
1015 default: TokError("Unknown token when parsing a value"); break;
1016 case tgtok::IntVal: R = new IntInit(Lex.getCurIntVal()); Lex.Lex(); break;
1017 case tgtok::StrVal: {
1018 std::string Val = Lex.getCurStrVal();
1021 // Handle multiple consecutive concatenated strings.
1022 while (Lex.getCode() == tgtok::StrVal) {
1023 Val += Lex.getCurStrVal();
1027 R = new StringInit(Val);
1030 case tgtok::CodeFragment:
1031 R = new CodeInit(Lex.getCurStrVal()); Lex.Lex(); break;
1032 case tgtok::question: R = new UnsetInit(); Lex.Lex(); break;
1034 SMLoc NameLoc = Lex.getLoc();
1035 std::string Name = Lex.getCurStrVal();
1036 if (Lex.Lex() != tgtok::less) // consume the Id.
1037 return ParseIDValue(CurRec, Name, NameLoc); // Value ::= IDValue
1039 // Value ::= ID '<' ValueListNE '>'
1040 if (Lex.Lex() == tgtok::greater) {
1041 TokError("expected non-empty value list");
1045 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1046 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1048 Record *Class = Records.getClass(Name);
1050 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1054 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1055 if (ValueList.empty()) return 0;
1057 if (Lex.getCode() != tgtok::greater) {
1058 TokError("expected '>' at end of value list");
1061 Lex.Lex(); // eat the '>'
1063 // Create the new record, set it as CurRec temporarily.
1064 static unsigned AnonCounter = 0;
1065 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),NameLoc);
1066 SubClassReference SCRef;
1067 SCRef.RefLoc = NameLoc;
1069 SCRef.TemplateArgs = ValueList;
1070 // Add info about the subclass to NewRec.
1071 if (AddSubClass(NewRec, SCRef))
1073 NewRec->resolveReferences();
1074 Records.addDef(NewRec);
1076 // The result of the expression is a reference to the new record.
1077 return new DefInit(NewRec);
1079 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1080 SMLoc BraceLoc = Lex.getLoc();
1081 Lex.Lex(); // eat the '{'
1082 std::vector<Init*> Vals;
1084 if (Lex.getCode() != tgtok::r_brace) {
1085 Vals = ParseValueList(CurRec);
1086 if (Vals.empty()) return 0;
1088 if (Lex.getCode() != tgtok::r_brace) {
1089 TokError("expected '}' at end of bit list value");
1092 Lex.Lex(); // eat the '}'
1094 BitsInit *Result = new BitsInit(Vals.size());
1095 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1096 Init *Bit = Vals[i]->convertInitializerTo(new BitRecTy());
1098 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1099 ") is not convertable to a bit");
1102 Result->setBit(Vals.size()-i-1, Bit);
1106 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1107 Lex.Lex(); // eat the '['
1108 std::vector<Init*> Vals;
1110 RecTy *DeducedEltTy = 0;
1111 ListRecTy *GivenListTy = 0;
1113 if (ItemType != 0) {
1114 ListRecTy *ListType = dynamic_cast<ListRecTy*>(ItemType);
1115 if (ListType == 0) {
1116 std::stringstream s;
1117 s << "Type mismatch for list, expected list type, got "
1118 << ItemType->getAsString();
1121 GivenListTy = ListType;
1124 if (Lex.getCode() != tgtok::r_square) {
1125 Vals = ParseValueList(CurRec, 0,
1126 GivenListTy ? GivenListTy->getElementType() : 0);
1127 if (Vals.empty()) return 0;
1129 if (Lex.getCode() != tgtok::r_square) {
1130 TokError("expected ']' at end of list value");
1133 Lex.Lex(); // eat the ']'
1135 RecTy *GivenEltTy = 0;
1136 if (Lex.getCode() == tgtok::less) {
1137 // Optional list element type
1138 Lex.Lex(); // eat the '<'
1140 GivenEltTy = ParseType();
1141 if (GivenEltTy == 0) {
1142 // Couldn't parse element type
1146 if (Lex.getCode() != tgtok::greater) {
1147 TokError("expected '>' at end of list element type");
1150 Lex.Lex(); // eat the '>'
1155 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1158 TypedInit *TArg = dynamic_cast<TypedInit*>(*i);
1160 TokError("Untyped list element");
1164 EltTy = resolveTypes(EltTy, TArg->getType());
1166 TokError("Incompatible types in list elements");
1170 EltTy = TArg->getType();
1174 if (GivenEltTy != 0) {
1176 // Verify consistency
1177 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1178 TokError("Incompatible types in list elements");
1186 if (ItemType == 0) {
1187 TokError("No type for list");
1190 DeducedEltTy = GivenListTy->getElementType();
1192 // Make sure the deduced type is compatible with the given type
1194 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1195 TokError("Element type mismatch for list");
1199 DeducedEltTy = EltTy;
1202 return new ListInit(Vals, DeducedEltTy);
1204 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1205 Lex.Lex(); // eat the '('
1206 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1207 TokError("expected identifier in dag init");
1212 if (Lex.getCode() == tgtok::Id) {
1213 Operator = ParseIDValue(CurRec);
1214 if (Operator == 0) return 0;
1216 Operator = ParseOperation(CurRec);
1217 if (Operator == 0) return 0;
1220 // If the operator name is present, parse it.
1221 std::string OperatorName;
1222 if (Lex.getCode() == tgtok::colon) {
1223 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1224 TokError("expected variable name in dag operator");
1227 OperatorName = Lex.getCurStrVal();
1228 Lex.Lex(); // eat the VarName.
1231 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1232 if (Lex.getCode() != tgtok::r_paren) {
1233 DagArgs = ParseDagArgList(CurRec);
1234 if (DagArgs.empty()) return 0;
1237 if (Lex.getCode() != tgtok::r_paren) {
1238 TokError("expected ')' in dag init");
1241 Lex.Lex(); // eat the ')'
1243 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);
1268 /// ParseValue - Parse a tblgen value. This returns null on error.
1270 /// Value ::= SimpleValue ValueSuffix*
1271 /// ValueSuffix ::= '{' BitList '}'
1272 /// ValueSuffix ::= '[' BitList ']'
1273 /// ValueSuffix ::= '.' ID
1275 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType) {
1276 Init *Result = ParseSimpleValue(CurRec, ItemType);
1277 if (Result == 0) return 0;
1279 // Parse the suffixes now if present.
1281 switch (Lex.getCode()) {
1282 default: return Result;
1283 case tgtok::l_brace: {
1284 SMLoc CurlyLoc = Lex.getLoc();
1285 Lex.Lex(); // eat the '{'
1286 std::vector<unsigned> Ranges = ParseRangeList();
1287 if (Ranges.empty()) return 0;
1289 // Reverse the bitlist.
1290 std::reverse(Ranges.begin(), Ranges.end());
1291 Result = Result->convertInitializerBitRange(Ranges);
1293 Error(CurlyLoc, "Invalid bit range for value");
1298 if (Lex.getCode() != tgtok::r_brace) {
1299 TokError("expected '}' at end of bit range list");
1305 case tgtok::l_square: {
1306 SMLoc SquareLoc = Lex.getLoc();
1307 Lex.Lex(); // eat the '['
1308 std::vector<unsigned> Ranges = ParseRangeList();
1309 if (Ranges.empty()) return 0;
1311 Result = Result->convertInitListSlice(Ranges);
1313 Error(SquareLoc, "Invalid range for list slice");
1318 if (Lex.getCode() != tgtok::r_square) {
1319 TokError("expected ']' at end of list slice");
1326 if (Lex.Lex() != tgtok::Id) { // eat the .
1327 TokError("expected field identifier after '.'");
1330 if (!Result->getFieldType(Lex.getCurStrVal())) {
1331 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1332 Result->getAsString() + "'");
1335 Result = new FieldInit(Result, Lex.getCurStrVal());
1336 Lex.Lex(); // eat field name
1342 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1344 /// ParseDagArgList ::= Value (':' VARNAME)?
1345 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1346 std::vector<std::pair<llvm::Init*, std::string> >
1347 TGParser::ParseDagArgList(Record *CurRec) {
1348 std::vector<std::pair<llvm::Init*, std::string> > Result;
1351 Init *Val = ParseValue(CurRec);
1352 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1354 // If the variable name is present, add it.
1355 std::string VarName;
1356 if (Lex.getCode() == tgtok::colon) {
1357 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1358 TokError("expected variable name in dag literal");
1359 return std::vector<std::pair<llvm::Init*, std::string> >();
1361 VarName = Lex.getCurStrVal();
1362 Lex.Lex(); // eat the VarName.
1365 Result.push_back(std::make_pair(Val, VarName));
1367 if (Lex.getCode() != tgtok::comma) break;
1368 Lex.Lex(); // eat the ','
1375 /// ParseValueList - Parse a comma separated list of values, returning them as a
1376 /// vector. Note that this always expects to be able to parse at least one
1377 /// value. It returns an empty list if this is not possible.
1379 /// ValueList ::= Value (',' Value)
1381 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1383 std::vector<Init*> Result;
1384 RecTy *ItemType = EltTy;
1385 unsigned int ArgN = 0;
1386 if (ArgsRec != 0 && EltTy == 0) {
1387 const std::vector<std::string> &TArgs = ArgsRec->getTemplateArgs();
1388 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1389 assert(RV && "Template argument record not found??");
1390 ItemType = RV->getType();
1393 Result.push_back(ParseValue(CurRec, ItemType));
1394 if (Result.back() == 0) return std::vector<Init*>();
1396 while (Lex.getCode() == tgtok::comma) {
1397 Lex.Lex(); // Eat the comma
1399 if (ArgsRec != 0 && EltTy == 0) {
1400 const std::vector<std::string> &TArgs = ArgsRec->getTemplateArgs();
1401 if (ArgN >= TArgs.size()) {
1402 TokError("too many template arguments");
1403 return std::vector<Init*>();
1405 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1406 assert(RV && "Template argument record not found??");
1407 ItemType = RV->getType();
1410 Result.push_back(ParseValue(CurRec, ItemType));
1411 if (Result.back() == 0) return std::vector<Init*>();
1418 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1419 /// empty string on error. This can happen in a number of different context's,
1420 /// including within a def or in the template args for a def (which which case
1421 /// CurRec will be non-null) and within the template args for a multiclass (in
1422 /// which case CurRec will be null, but CurMultiClass will be set). This can
1423 /// also happen within a def that is within a multiclass, which will set both
1424 /// CurRec and CurMultiClass.
1426 /// Declaration ::= FIELD? Type ID ('=' Value)?
1428 std::string TGParser::ParseDeclaration(Record *CurRec,
1429 bool ParsingTemplateArgs) {
1430 // Read the field prefix if present.
1431 bool HasField = Lex.getCode() == tgtok::Field;
1432 if (HasField) Lex.Lex();
1434 RecTy *Type = ParseType();
1435 if (Type == 0) return "";
1437 if (Lex.getCode() != tgtok::Id) {
1438 TokError("Expected identifier in declaration");
1442 SMLoc IdLoc = Lex.getLoc();
1443 std::string DeclName = Lex.getCurStrVal();
1446 if (ParsingTemplateArgs) {
1448 DeclName = CurRec->getName() + ":" + DeclName;
1450 assert(CurMultiClass);
1453 DeclName = CurMultiClass->Rec.getName() + "::" + DeclName;
1457 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1460 // If a value is present, parse it.
1461 if (Lex.getCode() == tgtok::equal) {
1463 SMLoc ValLoc = Lex.getLoc();
1464 Init *Val = ParseValue(CurRec, Type);
1466 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1473 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1474 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1475 /// template args for a def, which may or may not be in a multiclass. If null,
1476 /// these are the template args for a multiclass.
1478 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1480 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1481 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1482 Lex.Lex(); // eat the '<'
1484 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1486 // Read the first declaration.
1487 std::string TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1488 if (TemplArg.empty())
1491 TheRecToAddTo->addTemplateArg(TemplArg);
1493 while (Lex.getCode() == tgtok::comma) {
1494 Lex.Lex(); // eat the ','
1496 // Read the following declarations.
1497 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1498 if (TemplArg.empty())
1500 TheRecToAddTo->addTemplateArg(TemplArg);
1503 if (Lex.getCode() != tgtok::greater)
1504 return TokError("expected '>' at end of template argument list");
1505 Lex.Lex(); // eat the '>'.
1510 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1512 /// BodyItem ::= Declaration ';'
1513 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1514 bool TGParser::ParseBodyItem(Record *CurRec) {
1515 if (Lex.getCode() != tgtok::Let) {
1516 if (ParseDeclaration(CurRec, false).empty())
1519 if (Lex.getCode() != tgtok::semi)
1520 return TokError("expected ';' after declaration");
1525 // LET ID OptionalRangeList '=' Value ';'
1526 if (Lex.Lex() != tgtok::Id)
1527 return TokError("expected field identifier after let");
1529 SMLoc IdLoc = Lex.getLoc();
1530 std::string FieldName = Lex.getCurStrVal();
1531 Lex.Lex(); // eat the field name.
1533 std::vector<unsigned> BitList;
1534 if (ParseOptionalBitList(BitList))
1536 std::reverse(BitList.begin(), BitList.end());
1538 if (Lex.getCode() != tgtok::equal)
1539 return TokError("expected '=' in let expression");
1540 Lex.Lex(); // eat the '='.
1542 RecordVal *Field = CurRec->getValue(FieldName);
1544 return TokError("Value '" + FieldName + "' unknown!");
1546 RecTy *Type = Field->getType();
1548 Init *Val = ParseValue(CurRec, Type);
1549 if (Val == 0) return true;
1551 if (Lex.getCode() != tgtok::semi)
1552 return TokError("expected ';' after let expression");
1555 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1558 /// ParseBody - Read the body of a class or def. Return true on error, false on
1562 /// Body ::= '{' BodyList '}'
1563 /// BodyList BodyItem*
1565 bool TGParser::ParseBody(Record *CurRec) {
1566 // If this is a null definition, just eat the semi and return.
1567 if (Lex.getCode() == tgtok::semi) {
1572 if (Lex.getCode() != tgtok::l_brace)
1573 return TokError("Expected ';' or '{' to start body");
1577 while (Lex.getCode() != tgtok::r_brace)
1578 if (ParseBodyItem(CurRec))
1586 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1587 /// optional ClassList followed by a Body. CurRec is the current def or class
1588 /// that is being parsed.
1590 /// ObjectBody ::= BaseClassList Body
1591 /// BaseClassList ::= /*empty*/
1592 /// BaseClassList ::= ':' BaseClassListNE
1593 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1595 bool TGParser::ParseObjectBody(Record *CurRec) {
1596 // If there is a baseclass list, read it.
1597 if (Lex.getCode() == tgtok::colon) {
1600 // Read all of the subclasses.
1601 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1604 if (SubClass.Rec == 0) return true;
1607 if (AddSubClass(CurRec, SubClass))
1610 if (Lex.getCode() != tgtok::comma) break;
1611 Lex.Lex(); // eat ','.
1612 SubClass = ParseSubClassReference(CurRec, false);
1616 // Process any variables on the let stack.
1617 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1618 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1619 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1620 LetStack[i][j].Bits, LetStack[i][j].Value))
1623 return ParseBody(CurRec);
1626 /// ParseDef - Parse and return a top level or multiclass def, return the record
1627 /// corresponding to it. This returns null on error.
1629 /// DefInst ::= DEF ObjectName ObjectBody
1631 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1632 SMLoc DefLoc = Lex.getLoc();
1633 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1634 Lex.Lex(); // Eat the 'def' token.
1636 // Parse ObjectName and make a record for it.
1637 Record *CurRec = new Record(ParseObjectName(), DefLoc);
1639 if (!CurMultiClass) {
1640 // Top-level def definition.
1642 // Ensure redefinition doesn't happen.
1643 if (Records.getDef(CurRec->getName())) {
1644 Error(DefLoc, "def '" + CurRec->getName() + "' already defined");
1647 Records.addDef(CurRec);
1649 // Otherwise, a def inside a multiclass, add it to the multiclass.
1650 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1651 if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
1652 Error(DefLoc, "def '" + CurRec->getName() +
1653 "' already defined in this multiclass!");
1656 CurMultiClass->DefPrototypes.push_back(CurRec);
1659 if (ParseObjectBody(CurRec))
1662 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1663 CurRec->resolveReferences();
1665 // If ObjectBody has template arguments, it's an error.
1666 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1668 if (CurMultiClass) {
1669 // Copy the template arguments for the multiclass into the def.
1670 const std::vector<std::string> &TArgs =
1671 CurMultiClass->Rec.getTemplateArgs();
1673 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1674 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1675 assert(RV && "Template arg doesn't exist?");
1676 CurRec->addValue(*RV);
1684 /// ParseClass - Parse a tblgen class definition.
1686 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1688 bool TGParser::ParseClass() {
1689 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1692 if (Lex.getCode() != tgtok::Id)
1693 return TokError("expected class name after 'class' keyword");
1695 Record *CurRec = Records.getClass(Lex.getCurStrVal());
1697 // If the body was previously defined, this is an error.
1698 if (!CurRec->getValues().empty() ||
1699 !CurRec->getSuperClasses().empty() ||
1700 !CurRec->getTemplateArgs().empty())
1701 return TokError("Class '" + CurRec->getName() + "' already defined");
1703 // If this is the first reference to this class, create and add it.
1704 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc());
1705 Records.addClass(CurRec);
1707 Lex.Lex(); // eat the name.
1709 // If there are template args, parse them.
1710 if (Lex.getCode() == tgtok::less)
1711 if (ParseTemplateArgList(CurRec))
1714 // Finally, parse the object body.
1715 return ParseObjectBody(CurRec);
1718 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1721 /// LetList ::= LetItem (',' LetItem)*
1722 /// LetItem ::= ID OptionalRangeList '=' Value
1724 std::vector<LetRecord> TGParser::ParseLetList() {
1725 std::vector<LetRecord> Result;
1728 if (Lex.getCode() != tgtok::Id) {
1729 TokError("expected identifier in let definition");
1730 return std::vector<LetRecord>();
1732 std::string Name = Lex.getCurStrVal();
1733 SMLoc NameLoc = Lex.getLoc();
1734 Lex.Lex(); // Eat the identifier.
1736 // Check for an optional RangeList.
1737 std::vector<unsigned> Bits;
1738 if (ParseOptionalRangeList(Bits))
1739 return std::vector<LetRecord>();
1740 std::reverse(Bits.begin(), Bits.end());
1742 if (Lex.getCode() != tgtok::equal) {
1743 TokError("expected '=' in let expression");
1744 return std::vector<LetRecord>();
1746 Lex.Lex(); // eat the '='.
1748 Init *Val = ParseValue(0);
1749 if (Val == 0) return std::vector<LetRecord>();
1751 // Now that we have everything, add the record.
1752 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1754 if (Lex.getCode() != tgtok::comma)
1756 Lex.Lex(); // eat the comma.
1760 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
1761 /// different related productions. This works inside multiclasses too.
1763 /// Object ::= LET LetList IN '{' ObjectList '}'
1764 /// Object ::= LET LetList IN Object
1766 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
1767 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1770 // Add this entry to the let stack.
1771 std::vector<LetRecord> LetInfo = ParseLetList();
1772 if (LetInfo.empty()) return true;
1773 LetStack.push_back(LetInfo);
1775 if (Lex.getCode() != tgtok::In)
1776 return TokError("expected 'in' at end of top-level 'let'");
1779 // If this is a scalar let, just handle it now
1780 if (Lex.getCode() != tgtok::l_brace) {
1781 // LET LetList IN Object
1782 if (ParseObject(CurMultiClass))
1784 } else { // Object ::= LETCommand '{' ObjectList '}'
1785 SMLoc BraceLoc = Lex.getLoc();
1786 // Otherwise, this is a group let.
1787 Lex.Lex(); // eat the '{'.
1789 // Parse the object list.
1790 if (ParseObjectList(CurMultiClass))
1793 if (Lex.getCode() != tgtok::r_brace) {
1794 TokError("expected '}' at end of top level let command");
1795 return Error(BraceLoc, "to match this '{'");
1800 // Outside this let scope, this let block is not active.
1801 LetStack.pop_back();
1805 /// ParseMultiClass - Parse a multiclass definition.
1807 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
1808 /// ':' BaseMultiClassList '{' MultiClassDef+ '}'
1810 bool TGParser::ParseMultiClass() {
1811 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1812 Lex.Lex(); // Eat the multiclass token.
1814 if (Lex.getCode() != tgtok::Id)
1815 return TokError("expected identifier after multiclass for name");
1816 std::string Name = Lex.getCurStrVal();
1818 if (MultiClasses.count(Name))
1819 return TokError("multiclass '" + Name + "' already defined");
1821 CurMultiClass = MultiClasses[Name] = new MultiClass(Name, Lex.getLoc());
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 = new Record(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()) {
2092 default: assert(0 && "This is not an object");
2093 case tgtok::Let: return ParseTopLevelLet(MC);
2094 case tgtok::Def: return ParseDef(MC);
2095 case tgtok::Defm: return ParseDefm(MC);
2096 case tgtok::Class: return ParseClass();
2097 case tgtok::MultiClass: return ParseMultiClass();
2102 /// ObjectList :== Object*
2103 bool TGParser::ParseObjectList(MultiClass *MC) {
2104 while (isObjectStart(Lex.getCode())) {
2105 if (ParseObject(MC))
2111 bool TGParser::ParseFile() {
2112 Lex.Lex(); // Prime the lexer.
2113 if (ParseObjectList()) return true;
2115 // If we have unread input at the end of the file, report it.
2116 if (Lex.getCode() == tgtok::Eof)
2119 return TokError("Unexpected input at top level");