1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implement the Parser for TableGen.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/TableGen/Record.h"
16 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Support/CommandLine.h"
23 //===----------------------------------------------------------------------===//
24 // Support Code for the Semantic Actions.
25 //===----------------------------------------------------------------------===//
28 struct SubClassReference {
31 std::vector<Init*> TemplateArgs;
32 SubClassReference() : Rec(0) {}
34 bool isInvalid() const { return Rec == 0; }
37 struct SubMultiClassReference {
40 std::vector<Init*> TemplateArgs;
41 SubMultiClassReference() : MC(0) {}
43 bool isInvalid() const { return MC == 0; }
47 void SubMultiClassReference::dump() const {
48 errs() << "Multiclass:\n";
52 errs() << "Template args:\n";
53 for (std::vector<Init *>::const_iterator i = TemplateArgs.begin(),
54 iend = TemplateArgs.end();
61 } // end namespace llvm
63 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
65 CurRec = &CurMultiClass->Rec;
67 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
68 // The value already exists in the class, treat this as a set.
69 if (ERV->setValue(RV.getValue()))
70 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
71 RV.getType()->getAsString() + "' is incompatible with " +
72 "previous definition of type '" +
73 ERV->getType()->getAsString() + "'");
81 /// Return true on error, false on success.
82 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
83 const std::vector<unsigned> &BitList, Init *V) {
86 if (CurRec == 0) CurRec = &CurMultiClass->Rec;
88 RecordVal *RV = CurRec->getValue(ValName);
90 return Error(Loc, "Value '" + ValName->getAsUnquotedString()
93 // Do not allow assignments like 'X = X'. This will just cause infinite loops
94 // in the resolution machinery.
96 if (VarInit *VI = dynamic_cast<VarInit*>(V))
97 if (VI->getNameInit() == ValName)
100 // If we are assigning to a subset of the bits in the value... then we must be
101 // assigning to a field of BitsRecTy, which must have a BitsInit
104 if (!BitList.empty()) {
105 BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
107 return Error(Loc, "Value '" + ValName->getAsUnquotedString()
108 + "' is not a bits type");
110 // Convert the incoming value to a bits type of the appropriate size...
111 Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size()));
113 V->convertInitializerTo(BitsRecTy::get(BitList.size()));
114 return Error(Loc, "Initializer is not compatible with bit range");
117 // We should have a BitsInit type now.
118 BitsInit *BInit = dynamic_cast<BitsInit*>(BI);
121 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
123 // Loop over bits, assigning values as appropriate.
124 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
125 unsigned Bit = BitList[i];
127 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
128 ValName->getAsUnquotedString() + "' more than once");
129 NewBits[Bit] = BInit->getBit(i);
132 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
134 NewBits[i] = CurVal->getBit(i);
136 V = BitsInit::get(NewBits);
140 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of type '"
141 + RV->getType()->getAsString() +
142 "' is incompatible with initializer '" + V->getAsString()
147 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
148 /// args as SubClass's template arguments.
149 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
150 Record *SC = SubClass.Rec;
151 // Add all of the values in the subclass into the current class.
152 const std::vector<RecordVal> &Vals = SC->getValues();
153 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
154 if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
157 const std::vector<Init *> &TArgs = SC->getTemplateArgs();
159 // Ensure that an appropriate number of template arguments are specified.
160 if (TArgs.size() < SubClass.TemplateArgs.size())
161 return Error(SubClass.RefLoc, "More template args specified than expected");
163 // Loop over all of the template arguments, setting them to the specified
164 // value or leaving them as the default if necessary.
165 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
166 if (i < SubClass.TemplateArgs.size()) {
167 // If a value is specified for this template arg, set it now.
168 if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(),
169 SubClass.TemplateArgs[i]))
173 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
176 CurRec->removeValue(TArgs[i]);
178 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
179 return Error(SubClass.RefLoc,"Value not specified for template argument #"
180 + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
181 + ") of subclass '" + SC->getNameInitAsString() + "'!");
185 // Since everything went well, we can now set the "superclass" list for the
187 const std::vector<Record*> &SCs = SC->getSuperClasses();
188 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
189 if (CurRec->isSubClassOf(SCs[i]))
190 return Error(SubClass.RefLoc,
191 "Already subclass of '" + SCs[i]->getName() + "'!\n");
192 CurRec->addSuperClass(SCs[i]);
195 if (CurRec->isSubClassOf(SC))
196 return Error(SubClass.RefLoc,
197 "Already subclass of '" + SC->getName() + "'!\n");
198 CurRec->addSuperClass(SC);
202 /// AddSubMultiClass - Add SubMultiClass as a subclass to
203 /// CurMC, resolving its template args as SubMultiClass's
204 /// template arguments.
205 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
206 SubMultiClassReference &SubMultiClass) {
207 MultiClass *SMC = SubMultiClass.MC;
208 Record *CurRec = &CurMC->Rec;
210 const std::vector<RecordVal> &MCVals = CurRec->getValues();
212 // Add all of the values in the subclass into the current class.
213 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
214 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
215 if (AddValue(CurRec, SubMultiClass.RefLoc, SMCVals[i]))
218 int newDefStart = CurMC->DefPrototypes.size();
220 // Add all of the defs in the subclass into the current multiclass.
221 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
222 iend = SMC->DefPrototypes.end();
225 // Clone the def and add it to the current multiclass
226 Record *NewDef = new Record(**i);
228 // Add all of the values in the superclass into the current def.
229 for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
230 if (AddValue(NewDef, SubMultiClass.RefLoc, MCVals[i]))
233 CurMC->DefPrototypes.push_back(NewDef);
236 const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
238 // Ensure that an appropriate number of template arguments are
240 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
241 return Error(SubMultiClass.RefLoc,
242 "More template args specified than expected");
244 // Loop over all of the template arguments, setting them to the specified
245 // value or leaving them as the default if necessary.
246 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
247 if (i < SubMultiClass.TemplateArgs.size()) {
248 // If a value is specified for this template arg, set it in the
250 if (SetValue(CurRec, SubMultiClass.RefLoc, SMCTArgs[i],
251 std::vector<unsigned>(),
252 SubMultiClass.TemplateArgs[i]))
256 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
259 CurRec->removeValue(SMCTArgs[i]);
261 // If a value is specified for this template arg, set it in the
263 for (MultiClass::RecordVector::iterator j =
264 CurMC->DefPrototypes.begin() + newDefStart,
265 jend = CurMC->DefPrototypes.end();
270 if (SetValue(Def, SubMultiClass.RefLoc, SMCTArgs[i],
271 std::vector<unsigned>(),
272 SubMultiClass.TemplateArgs[i]))
276 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
279 Def->removeValue(SMCTArgs[i]);
281 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
282 return Error(SubMultiClass.RefLoc,
283 "Value not specified for template argument #"
284 + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
285 + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
292 //===----------------------------------------------------------------------===//
294 //===----------------------------------------------------------------------===//
296 /// isObjectStart - Return true if this is a valid first token for an Object.
297 static bool isObjectStart(tgtok::TokKind K) {
298 return K == tgtok::Class || K == tgtok::Def ||
299 K == tgtok::Defm || K == tgtok::Let || K == tgtok::MultiClass;
302 static std::string GetNewAnonymousName() {
303 static unsigned AnonCounter = 0;
304 return "anonymous."+utostr(AnonCounter++);
307 /// ParseObjectName - If an object name is specified, return it. Otherwise,
308 /// return an anonymous name.
309 /// ObjectName ::= Value [ '#' Value ]*
310 /// ObjectName ::= /*empty*/
312 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
313 switch (Lex.getCode()) {
317 // These are all of the tokens that can begin an object body.
318 // Some of these can also begin values but we disallow those cases
319 // because they are unlikely to be useful.
320 return StringInit::get(GetNewAnonymousName());
327 CurRec = &CurMultiClass->Rec;
331 const TypedInit *CurRecName =
332 dynamic_cast<const TypedInit *>(CurRec->getNameInit());
334 TokError("Record name is not typed!");
337 Type = CurRecName->getType();
340 return ParseValue(CurRec, Type, ParseNameMode);
343 /// ParseClassID - Parse and resolve a reference to a class name. This returns
348 Record *TGParser::ParseClassID() {
349 if (Lex.getCode() != tgtok::Id) {
350 TokError("expected name for ClassID");
354 Record *Result = Records.getClass(Lex.getCurStrVal());
356 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
362 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
363 /// This returns null on error.
365 /// MultiClassID ::= ID
367 MultiClass *TGParser::ParseMultiClassID() {
368 if (Lex.getCode() != tgtok::Id) {
369 TokError("expected name for ClassID");
373 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
375 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
381 Record *TGParser::ParseDefmID() {
382 if (Lex.getCode() != tgtok::Id) {
383 TokError("expected multiclass name");
387 MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
389 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
398 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
399 /// subclass. This returns a SubClassRefTy with a null Record* on error.
401 /// SubClassRef ::= ClassID
402 /// SubClassRef ::= ClassID '<' ValueList '>'
404 SubClassReference TGParser::
405 ParseSubClassReference(Record *CurRec, bool isDefm) {
406 SubClassReference Result;
407 Result.RefLoc = Lex.getLoc();
410 Result.Rec = ParseDefmID();
412 Result.Rec = ParseClassID();
413 if (Result.Rec == 0) return Result;
415 // If there is no template arg list, we're done.
416 if (Lex.getCode() != tgtok::less)
418 Lex.Lex(); // Eat the '<'
420 if (Lex.getCode() == tgtok::greater) {
421 TokError("subclass reference requires a non-empty list of template values");
426 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
427 if (Result.TemplateArgs.empty()) {
428 Result.Rec = 0; // Error parsing value list.
432 if (Lex.getCode() != tgtok::greater) {
433 TokError("expected '>' in template value list");
442 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
443 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
444 /// Record* on error.
446 /// SubMultiClassRef ::= MultiClassID
447 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
449 SubMultiClassReference TGParser::
450 ParseSubMultiClassReference(MultiClass *CurMC) {
451 SubMultiClassReference Result;
452 Result.RefLoc = Lex.getLoc();
454 Result.MC = ParseMultiClassID();
455 if (Result.MC == 0) return Result;
457 // If there is no template arg list, we're done.
458 if (Lex.getCode() != tgtok::less)
460 Lex.Lex(); // Eat the '<'
462 if (Lex.getCode() == tgtok::greater) {
463 TokError("subclass reference requires a non-empty list of template values");
468 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
469 if (Result.TemplateArgs.empty()) {
470 Result.MC = 0; // Error parsing value list.
474 if (Lex.getCode() != tgtok::greater) {
475 TokError("expected '>' in template value list");
484 /// ParseRangePiece - Parse a bit/value range.
485 /// RangePiece ::= INTVAL
486 /// RangePiece ::= INTVAL '-' INTVAL
487 /// RangePiece ::= INTVAL INTVAL
488 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
489 if (Lex.getCode() != tgtok::IntVal) {
490 TokError("expected integer or bitrange");
493 int64_t Start = Lex.getCurIntVal();
497 return TokError("invalid range, cannot be negative");
499 switch (Lex.Lex()) { // eat first character.
501 Ranges.push_back(Start);
504 if (Lex.Lex() != tgtok::IntVal) {
505 TokError("expected integer value as end of range");
508 End = Lex.getCurIntVal();
511 End = -Lex.getCurIntVal();
515 return TokError("invalid range, cannot be negative");
520 for (; Start <= End; ++Start)
521 Ranges.push_back(Start);
523 for (; Start >= End; --Start)
524 Ranges.push_back(Start);
529 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
531 /// RangeList ::= RangePiece (',' RangePiece)*
533 std::vector<unsigned> TGParser::ParseRangeList() {
534 std::vector<unsigned> Result;
536 // Parse the first piece.
537 if (ParseRangePiece(Result))
538 return std::vector<unsigned>();
539 while (Lex.getCode() == tgtok::comma) {
540 Lex.Lex(); // Eat the comma.
542 // Parse the next range piece.
543 if (ParseRangePiece(Result))
544 return std::vector<unsigned>();
549 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
550 /// OptionalRangeList ::= '<' RangeList '>'
551 /// OptionalRangeList ::= /*empty*/
552 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
553 if (Lex.getCode() != tgtok::less)
556 SMLoc StartLoc = Lex.getLoc();
557 Lex.Lex(); // eat the '<'
559 // Parse the range list.
560 Ranges = ParseRangeList();
561 if (Ranges.empty()) return true;
563 if (Lex.getCode() != tgtok::greater) {
564 TokError("expected '>' at end of range list");
565 return Error(StartLoc, "to match this '<'");
567 Lex.Lex(); // eat the '>'.
571 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
572 /// OptionalBitList ::= '{' RangeList '}'
573 /// OptionalBitList ::= /*empty*/
574 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
575 if (Lex.getCode() != tgtok::l_brace)
578 SMLoc StartLoc = Lex.getLoc();
579 Lex.Lex(); // eat the '{'
581 // Parse the range list.
582 Ranges = ParseRangeList();
583 if (Ranges.empty()) return true;
585 if (Lex.getCode() != tgtok::r_brace) {
586 TokError("expected '}' at end of bit list");
587 return Error(StartLoc, "to match this '{'");
589 Lex.Lex(); // eat the '}'.
594 /// ParseType - Parse and return a tblgen type. This returns null on error.
596 /// Type ::= STRING // string type
597 /// Type ::= CODE // code type
598 /// Type ::= BIT // bit type
599 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
600 /// Type ::= INT // int type
601 /// Type ::= LIST '<' Type '>' // list<x> type
602 /// Type ::= DAG // dag type
603 /// Type ::= ClassID // Record Type
605 RecTy *TGParser::ParseType() {
606 switch (Lex.getCode()) {
607 default: TokError("Unknown token when expecting a type"); return 0;
608 case tgtok::String: Lex.Lex(); return StringRecTy::get();
609 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
610 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
611 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
612 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
614 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
617 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
618 TokError("expected '<' after bits type");
621 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
622 TokError("expected integer in bits<n> type");
625 uint64_t Val = Lex.getCurIntVal();
626 if (Lex.Lex() != tgtok::greater) { // Eat count.
627 TokError("expected '>' at end of bits<n> type");
630 Lex.Lex(); // Eat '>'
631 return BitsRecTy::get(Val);
634 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
635 TokError("expected '<' after list type");
638 Lex.Lex(); // Eat '<'
639 RecTy *SubType = ParseType();
640 if (SubType == 0) return 0;
642 if (Lex.getCode() != tgtok::greater) {
643 TokError("expected '>' at end of list<ty> type");
646 Lex.Lex(); // Eat '>'
647 return ListRecTy::get(SubType);
652 /// ParseIDValue - Parse an ID as a value and decode what it means.
654 /// IDValue ::= ID [def local value]
655 /// IDValue ::= ID [def template arg]
656 /// IDValue ::= ID [multiclass local value]
657 /// IDValue ::= ID [multiclass template argument]
658 /// IDValue ::= ID [def name]
660 Init *TGParser::ParseIDValue(Record *CurRec, IDParseMode Mode) {
661 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
662 std::string Name = Lex.getCurStrVal();
663 SMLoc Loc = Lex.getLoc();
665 return ParseIDValue(CurRec, Name, Loc);
668 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
669 /// has already been read.
670 Init *TGParser::ParseIDValue(Record *CurRec,
671 const std::string &Name, SMLoc NameLoc,
674 if (const RecordVal *RV = CurRec->getValue(Name))
675 return VarInit::get(Name, RV->getType());
677 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
680 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
683 if (CurRec->isTemplateArg(TemplateArgName)) {
684 const RecordVal *RV = CurRec->getValue(TemplateArgName);
685 assert(RV && "Template arg doesn't exist??");
686 return VarInit::get(TemplateArgName, RV->getType());
691 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
694 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
695 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
696 assert(RV && "Template arg doesn't exist??");
697 return VarInit::get(MCName, RV->getType());
701 if (Mode == ParseNameMode)
702 return StringInit::get(Name);
704 if (Record *D = Records.getDef(Name))
705 return DefInit::get(D);
707 if (Mode == ParseValueMode) {
708 Error(NameLoc, "Variable not defined: '" + Name + "'");
712 return StringInit::get(Name);
715 /// ParseOperation - Parse an operator. This returns null on error.
717 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
719 Init *TGParser::ParseOperation(Record *CurRec) {
720 switch (Lex.getCode()) {
722 TokError("unknown operation");
727 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
728 UnOpInit::UnaryOp Code;
731 switch (Lex.getCode()) {
732 default: assert(0 && "Unhandled code!");
734 Lex.Lex(); // eat the operation
735 Code = UnOpInit::CAST;
737 Type = ParseOperatorType();
740 TokError("did not get type for unary operator");
746 Lex.Lex(); // eat the operation
747 Code = UnOpInit::HEAD;
750 Lex.Lex(); // eat the operation
751 Code = UnOpInit::TAIL;
754 Lex.Lex(); // eat the operation
755 Code = UnOpInit::EMPTY;
756 Type = IntRecTy::get();
759 if (Lex.getCode() != tgtok::l_paren) {
760 TokError("expected '(' after unary operator");
763 Lex.Lex(); // eat the '('
765 Init *LHS = ParseValue(CurRec);
766 if (LHS == 0) return 0;
768 if (Code == UnOpInit::HEAD
769 || Code == UnOpInit::TAIL
770 || Code == UnOpInit::EMPTY) {
771 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
772 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
773 TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
774 if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
775 TokError("expected list or string type argument in unary operator");
779 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
780 StringRecTy *SType = dynamic_cast<StringRecTy*>(LHSt->getType());
781 if (LType == 0 && SType == 0) {
782 TokError("expected list or string type argumnet in unary operator");
787 if (Code == UnOpInit::HEAD
788 || Code == UnOpInit::TAIL) {
789 if (LHSl == 0 && LHSt == 0) {
790 TokError("expected list type argumnet in unary operator");
794 if (LHSl && LHSl->getSize() == 0) {
795 TokError("empty list argument in unary operator");
799 Init *Item = LHSl->getElement(0);
800 TypedInit *Itemt = dynamic_cast<TypedInit*>(Item);
802 TokError("untyped list element in unary operator");
805 if (Code == UnOpInit::HEAD) {
806 Type = Itemt->getType();
808 Type = ListRecTy::get(Itemt->getType());
811 assert(LHSt && "expected list type argument in unary operator");
812 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
814 TokError("expected list type argumnet in unary operator");
817 if (Code == UnOpInit::HEAD) {
818 Type = LType->getElementType();
826 if (Lex.getCode() != tgtok::r_paren) {
827 TokError("expected ')' in unary operator");
830 Lex.Lex(); // eat the ')'
831 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
839 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
840 tgtok::TokKind OpTok = Lex.getCode();
841 SMLoc OpLoc = Lex.getLoc();
842 Lex.Lex(); // eat the operation
844 BinOpInit::BinaryOp Code;
848 default: assert(0 && "Unhandled code!");
849 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
850 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
851 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
852 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
853 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
854 case tgtok::XStrConcat:
855 Code = BinOpInit::STRCONCAT;
856 Type = StringRecTy::get();
860 if (Lex.getCode() != tgtok::l_paren) {
861 TokError("expected '(' after binary operator");
864 Lex.Lex(); // eat the '('
866 SmallVector<Init*, 2> InitList;
868 InitList.push_back(ParseValue(CurRec));
869 if (InitList.back() == 0) return 0;
871 while (Lex.getCode() == tgtok::comma) {
872 Lex.Lex(); // eat the ','
874 InitList.push_back(ParseValue(CurRec));
875 if (InitList.back() == 0) return 0;
878 if (Lex.getCode() != tgtok::r_paren) {
879 TokError("expected ')' in operator");
882 Lex.Lex(); // eat the ')'
884 // We allow multiple operands to associative operators like !strconcat as
885 // shorthand for nesting them.
886 if (Code == BinOpInit::STRCONCAT) {
887 while (InitList.size() > 2) {
888 Init *RHS = InitList.pop_back_val();
889 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
890 ->Fold(CurRec, CurMultiClass);
891 InitList.back() = RHS;
895 if (InitList.size() == 2)
896 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
897 ->Fold(CurRec, CurMultiClass);
899 Error(OpLoc, "expected two operands to operator");
904 case tgtok::XForEach:
905 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
906 TernOpInit::TernaryOp Code;
909 tgtok::TokKind LexCode = Lex.getCode();
910 Lex.Lex(); // eat the operation
912 default: assert(0 && "Unhandled code!");
914 Code = TernOpInit::IF;
916 case tgtok::XForEach:
917 Code = TernOpInit::FOREACH;
920 Code = TernOpInit::SUBST;
923 if (Lex.getCode() != tgtok::l_paren) {
924 TokError("expected '(' after ternary operator");
927 Lex.Lex(); // eat the '('
929 Init *LHS = ParseValue(CurRec);
930 if (LHS == 0) return 0;
932 if (Lex.getCode() != tgtok::comma) {
933 TokError("expected ',' in ternary operator");
936 Lex.Lex(); // eat the ','
938 Init *MHS = ParseValue(CurRec);
939 if (MHS == 0) return 0;
941 if (Lex.getCode() != tgtok::comma) {
942 TokError("expected ',' in ternary operator");
945 Lex.Lex(); // eat the ','
947 Init *RHS = ParseValue(CurRec);
948 if (RHS == 0) return 0;
950 if (Lex.getCode() != tgtok::r_paren) {
951 TokError("expected ')' in binary operator");
954 Lex.Lex(); // eat the ')'
957 default: assert(0 && "Unhandled code!");
959 // FIXME: The `!if' operator doesn't handle non-TypedInit well at
960 // all. This can be made much more robust.
961 TypedInit *MHSt = dynamic_cast<TypedInit*>(MHS);
962 TypedInit *RHSt = dynamic_cast<TypedInit*>(RHS);
967 if (MHSt == 0 && RHSt == 0) {
968 BitsInit *MHSbits = dynamic_cast<BitsInit*>(MHS);
969 BitsInit *RHSbits = dynamic_cast<BitsInit*>(RHS);
971 if (MHSbits && RHSbits &&
972 MHSbits->getNumBits() == RHSbits->getNumBits()) {
973 Type = BitRecTy::get();
976 BitInit *MHSbit = dynamic_cast<BitInit*>(MHS);
977 BitInit *RHSbit = dynamic_cast<BitInit*>(RHS);
979 if (MHSbit && RHSbit) {
980 Type = BitRecTy::get();
984 } else if (MHSt != 0 && RHSt != 0) {
985 MHSTy = MHSt->getType();
986 RHSTy = RHSt->getType();
989 if (!MHSTy || !RHSTy) {
990 TokError("could not get type for !if");
994 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
996 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
999 TokError("inconsistent types for !if");
1004 case tgtok::XForEach: {
1005 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
1007 TokError("could not get type for !foreach");
1010 Type = MHSt->getType();
1013 case tgtok::XSubst: {
1014 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
1016 TokError("could not get type for !subst");
1019 Type = RHSt->getType();
1023 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1029 /// ParseOperatorType - Parse a type for an operator. This returns
1032 /// OperatorType ::= '<' Type '>'
1034 RecTy *TGParser::ParseOperatorType() {
1037 if (Lex.getCode() != tgtok::less) {
1038 TokError("expected type name for operator");
1041 Lex.Lex(); // eat the <
1046 TokError("expected type name for operator");
1050 if (Lex.getCode() != tgtok::greater) {
1051 TokError("expected type name for operator");
1054 Lex.Lex(); // eat the >
1060 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1062 /// SimpleValue ::= IDValue
1063 /// SimpleValue ::= INTVAL
1064 /// SimpleValue ::= STRVAL+
1065 /// SimpleValue ::= CODEFRAGMENT
1066 /// SimpleValue ::= '?'
1067 /// SimpleValue ::= '{' ValueList '}'
1068 /// SimpleValue ::= ID '<' ValueListNE '>'
1069 /// SimpleValue ::= '[' ValueList ']'
1070 /// SimpleValue ::= '(' IDValue DagArgList ')'
1071 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1072 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1073 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1074 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1075 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1077 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1080 switch (Lex.getCode()) {
1081 default: TokError("Unknown token when parsing a value"); break;
1083 // This is a leading paste operation. This is deprecated but
1084 // still exists in some .td files. Ignore it.
1085 Lex.Lex(); // Skip '#'.
1086 return ParseSimpleValue(CurRec, ItemType, Mode);
1087 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1088 case tgtok::StrVal: {
1089 std::string Val = Lex.getCurStrVal();
1092 // Handle multiple consecutive concatenated strings.
1093 while (Lex.getCode() == tgtok::StrVal) {
1094 Val += Lex.getCurStrVal();
1098 R = StringInit::get(Val);
1101 case tgtok::CodeFragment:
1102 R = StringInit::get(Lex.getCurStrVal());
1105 case tgtok::question:
1106 R = UnsetInit::get();
1110 SMLoc NameLoc = Lex.getLoc();
1111 std::string Name = Lex.getCurStrVal();
1112 if (Lex.Lex() != tgtok::less) // consume the Id.
1113 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1115 // Value ::= ID '<' ValueListNE '>'
1116 if (Lex.Lex() == tgtok::greater) {
1117 TokError("expected non-empty value list");
1121 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1122 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1124 Record *Class = Records.getClass(Name);
1126 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1130 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1131 if (ValueList.empty()) return 0;
1133 if (Lex.getCode() != tgtok::greater) {
1134 TokError("expected '>' at end of value list");
1137 Lex.Lex(); // eat the '>'
1139 // Create the new record, set it as CurRec temporarily.
1140 static unsigned AnonCounter = 0;
1141 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),
1144 SubClassReference SCRef;
1145 SCRef.RefLoc = NameLoc;
1147 SCRef.TemplateArgs = ValueList;
1148 // Add info about the subclass to NewRec.
1149 if (AddSubClass(NewRec, SCRef))
1151 NewRec->resolveReferences();
1152 Records.addDef(NewRec);
1154 // The result of the expression is a reference to the new record.
1155 return DefInit::get(NewRec);
1157 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1158 SMLoc BraceLoc = Lex.getLoc();
1159 Lex.Lex(); // eat the '{'
1160 std::vector<Init*> Vals;
1162 if (Lex.getCode() != tgtok::r_brace) {
1163 Vals = ParseValueList(CurRec);
1164 if (Vals.empty()) return 0;
1166 if (Lex.getCode() != tgtok::r_brace) {
1167 TokError("expected '}' at end of bit list value");
1170 Lex.Lex(); // eat the '}'
1172 SmallVector<Init *, 16> NewBits(Vals.size());
1174 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1175 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1177 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1178 ") is not convertable to a bit");
1181 NewBits[Vals.size()-i-1] = Bit;
1183 return BitsInit::get(NewBits);
1185 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1186 Lex.Lex(); // eat the '['
1187 std::vector<Init*> Vals;
1189 RecTy *DeducedEltTy = 0;
1190 ListRecTy *GivenListTy = 0;
1192 if (ItemType != 0) {
1193 ListRecTy *ListType = dynamic_cast<ListRecTy*>(ItemType);
1194 if (ListType == 0) {
1195 std::stringstream s;
1196 s << "Type mismatch for list, expected list type, got "
1197 << ItemType->getAsString();
1201 GivenListTy = ListType;
1204 if (Lex.getCode() != tgtok::r_square) {
1205 Vals = ParseValueList(CurRec, 0,
1206 GivenListTy ? GivenListTy->getElementType() : 0);
1207 if (Vals.empty()) return 0;
1209 if (Lex.getCode() != tgtok::r_square) {
1210 TokError("expected ']' at end of list value");
1213 Lex.Lex(); // eat the ']'
1215 RecTy *GivenEltTy = 0;
1216 if (Lex.getCode() == tgtok::less) {
1217 // Optional list element type
1218 Lex.Lex(); // eat the '<'
1220 GivenEltTy = ParseType();
1221 if (GivenEltTy == 0) {
1222 // Couldn't parse element type
1226 if (Lex.getCode() != tgtok::greater) {
1227 TokError("expected '>' at end of list element type");
1230 Lex.Lex(); // eat the '>'
1235 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1238 TypedInit *TArg = dynamic_cast<TypedInit*>(*i);
1240 TokError("Untyped list element");
1244 EltTy = resolveTypes(EltTy, TArg->getType());
1246 TokError("Incompatible types in list elements");
1250 EltTy = TArg->getType();
1254 if (GivenEltTy != 0) {
1256 // Verify consistency
1257 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1258 TokError("Incompatible types in list elements");
1266 if (ItemType == 0) {
1267 TokError("No type for list");
1270 DeducedEltTy = GivenListTy->getElementType();
1272 // Make sure the deduced type is compatible with the given type
1274 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1275 TokError("Element type mismatch for list");
1279 DeducedEltTy = EltTy;
1282 return ListInit::get(Vals, DeducedEltTy);
1284 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1285 Lex.Lex(); // eat the '('
1286 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1287 TokError("expected identifier in dag init");
1291 Init *Operator = ParseValue(CurRec);
1292 if (Operator == 0) return 0;
1294 // If the operator name is present, parse it.
1295 std::string OperatorName;
1296 if (Lex.getCode() == tgtok::colon) {
1297 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1298 TokError("expected variable name in dag operator");
1301 OperatorName = Lex.getCurStrVal();
1302 Lex.Lex(); // eat the VarName.
1305 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1306 if (Lex.getCode() != tgtok::r_paren) {
1307 DagArgs = ParseDagArgList(CurRec);
1308 if (DagArgs.empty()) return 0;
1311 if (Lex.getCode() != tgtok::r_paren) {
1312 TokError("expected ')' in dag init");
1315 Lex.Lex(); // eat the ')'
1317 return DagInit::get(Operator, OperatorName, DagArgs);
1323 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1324 case tgtok::XConcat:
1329 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1331 case tgtok::XForEach:
1332 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1333 return ParseOperation(CurRec);
1340 /// ParseValue - Parse a tblgen value. This returns null on error.
1342 /// Value ::= SimpleValue ValueSuffix*
1343 /// ValueSuffix ::= '{' BitList '}'
1344 /// ValueSuffix ::= '[' BitList ']'
1345 /// ValueSuffix ::= '.' ID
1347 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1348 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1349 if (Result == 0) return 0;
1351 // Parse the suffixes now if present.
1353 switch (Lex.getCode()) {
1354 default: return Result;
1355 case tgtok::l_brace: {
1356 if (Mode == ParseNameMode)
1357 // This is the beginning of the object body.
1360 SMLoc CurlyLoc = Lex.getLoc();
1361 Lex.Lex(); // eat the '{'
1362 std::vector<unsigned> Ranges = ParseRangeList();
1363 if (Ranges.empty()) return 0;
1365 // Reverse the bitlist.
1366 std::reverse(Ranges.begin(), Ranges.end());
1367 Result = Result->convertInitializerBitRange(Ranges);
1369 Error(CurlyLoc, "Invalid bit range for value");
1374 if (Lex.getCode() != tgtok::r_brace) {
1375 TokError("expected '}' at end of bit range list");
1381 case tgtok::l_square: {
1382 SMLoc SquareLoc = Lex.getLoc();
1383 Lex.Lex(); // eat the '['
1384 std::vector<unsigned> Ranges = ParseRangeList();
1385 if (Ranges.empty()) return 0;
1387 Result = Result->convertInitListSlice(Ranges);
1389 Error(SquareLoc, "Invalid range for list slice");
1394 if (Lex.getCode() != tgtok::r_square) {
1395 TokError("expected ']' at end of list slice");
1402 if (Lex.Lex() != tgtok::Id) { // eat the .
1403 TokError("expected field identifier after '.'");
1406 if (!Result->getFieldType(Lex.getCurStrVal())) {
1407 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1408 Result->getAsString() + "'");
1411 Result = FieldInit::get(Result, Lex.getCurStrVal());
1412 Lex.Lex(); // eat field name
1416 SMLoc PasteLoc = Lex.getLoc();
1418 // Create a !strconcat() operation, first casting each operand to
1419 // a string if necessary.
1421 TypedInit *LHS = dynamic_cast<TypedInit *>(Result);
1423 Error(PasteLoc, "LHS of paste is not typed!");
1427 if (LHS->getType() != StringRecTy::get()) {
1428 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1433 Lex.Lex(); // Eat the '#'.
1434 switch (Lex.getCode()) {
1437 case tgtok::l_brace:
1438 // These are all of the tokens that can begin an object body.
1439 // Some of these can also begin values but we disallow those cases
1440 // because they are unlikely to be useful.
1442 // Trailing paste, concat with an empty string.
1443 RHS = StringInit::get("");
1447 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1448 RHS = dynamic_cast<TypedInit *>(RHSResult);
1450 Error(PasteLoc, "RHS of paste is not typed!");
1454 if (RHS->getType() != StringRecTy::get()) {
1455 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1461 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1462 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1468 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1470 /// ParseDagArgList ::= Value (':' VARNAME)?
1471 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1472 std::vector<std::pair<llvm::Init*, std::string> >
1473 TGParser::ParseDagArgList(Record *CurRec) {
1474 std::vector<std::pair<llvm::Init*, std::string> > Result;
1477 Init *Val = ParseValue(CurRec);
1478 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1480 // If the variable name is present, add it.
1481 std::string VarName;
1482 if (Lex.getCode() == tgtok::colon) {
1483 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1484 TokError("expected variable name in dag literal");
1485 return std::vector<std::pair<llvm::Init*, std::string> >();
1487 VarName = Lex.getCurStrVal();
1488 Lex.Lex(); // eat the VarName.
1491 Result.push_back(std::make_pair(Val, VarName));
1493 if (Lex.getCode() != tgtok::comma) break;
1494 Lex.Lex(); // eat the ','
1501 /// ParseValueList - Parse a comma separated list of values, returning them as a
1502 /// vector. Note that this always expects to be able to parse at least one
1503 /// value. It returns an empty list if this is not possible.
1505 /// ValueList ::= Value (',' Value)
1507 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1509 std::vector<Init*> Result;
1510 RecTy *ItemType = EltTy;
1511 unsigned int ArgN = 0;
1512 if (ArgsRec != 0 && EltTy == 0) {
1513 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1514 if (!TArgs.size()) {
1515 TokError("template argument provided to non-template class");
1516 return std::vector<Init*>();
1518 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1520 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1523 assert(RV && "Template argument record not found??");
1524 ItemType = RV->getType();
1527 Result.push_back(ParseValue(CurRec, ItemType));
1528 if (Result.back() == 0) return std::vector<Init*>();
1530 while (Lex.getCode() == tgtok::comma) {
1531 Lex.Lex(); // Eat the comma
1533 if (ArgsRec != 0 && EltTy == 0) {
1534 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1535 if (ArgN >= TArgs.size()) {
1536 TokError("too many template arguments");
1537 return std::vector<Init*>();
1539 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1540 assert(RV && "Template argument record not found??");
1541 ItemType = RV->getType();
1544 Result.push_back(ParseValue(CurRec, ItemType));
1545 if (Result.back() == 0) return std::vector<Init*>();
1552 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1553 /// empty string on error. This can happen in a number of different context's,
1554 /// including within a def or in the template args for a def (which which case
1555 /// CurRec will be non-null) and within the template args for a multiclass (in
1556 /// which case CurRec will be null, but CurMultiClass will be set). This can
1557 /// also happen within a def that is within a multiclass, which will set both
1558 /// CurRec and CurMultiClass.
1560 /// Declaration ::= FIELD? Type ID ('=' Value)?
1562 Init *TGParser::ParseDeclaration(Record *CurRec,
1563 bool ParsingTemplateArgs) {
1564 // Read the field prefix if present.
1565 bool HasField = Lex.getCode() == tgtok::Field;
1566 if (HasField) Lex.Lex();
1568 RecTy *Type = ParseType();
1569 if (Type == 0) return 0;
1571 if (Lex.getCode() != tgtok::Id) {
1572 TokError("Expected identifier in declaration");
1576 SMLoc IdLoc = Lex.getLoc();
1577 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1580 if (ParsingTemplateArgs) {
1582 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1584 assert(CurMultiClass);
1587 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1592 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1595 // If a value is present, parse it.
1596 if (Lex.getCode() == tgtok::equal) {
1598 SMLoc ValLoc = Lex.getLoc();
1599 Init *Val = ParseValue(CurRec, Type);
1601 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1608 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1609 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1610 /// template args for a def, which may or may not be in a multiclass. If null,
1611 /// these are the template args for a multiclass.
1613 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1615 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1616 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1617 Lex.Lex(); // eat the '<'
1619 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1621 // Read the first declaration.
1622 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1626 TheRecToAddTo->addTemplateArg(TemplArg);
1628 while (Lex.getCode() == tgtok::comma) {
1629 Lex.Lex(); // eat the ','
1631 // Read the following declarations.
1632 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1635 TheRecToAddTo->addTemplateArg(TemplArg);
1638 if (Lex.getCode() != tgtok::greater)
1639 return TokError("expected '>' at end of template argument list");
1640 Lex.Lex(); // eat the '>'.
1645 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1647 /// BodyItem ::= Declaration ';'
1648 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1649 bool TGParser::ParseBodyItem(Record *CurRec) {
1650 if (Lex.getCode() != tgtok::Let) {
1651 if (ParseDeclaration(CurRec, false) == 0)
1654 if (Lex.getCode() != tgtok::semi)
1655 return TokError("expected ';' after declaration");
1660 // LET ID OptionalRangeList '=' Value ';'
1661 if (Lex.Lex() != tgtok::Id)
1662 return TokError("expected field identifier after let");
1664 SMLoc IdLoc = Lex.getLoc();
1665 std::string FieldName = Lex.getCurStrVal();
1666 Lex.Lex(); // eat the field name.
1668 std::vector<unsigned> BitList;
1669 if (ParseOptionalBitList(BitList))
1671 std::reverse(BitList.begin(), BitList.end());
1673 if (Lex.getCode() != tgtok::equal)
1674 return TokError("expected '=' in let expression");
1675 Lex.Lex(); // eat the '='.
1677 RecordVal *Field = CurRec->getValue(FieldName);
1679 return TokError("Value '" + FieldName + "' unknown!");
1681 RecTy *Type = Field->getType();
1683 Init *Val = ParseValue(CurRec, Type);
1684 if (Val == 0) return true;
1686 if (Lex.getCode() != tgtok::semi)
1687 return TokError("expected ';' after let expression");
1690 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1693 /// ParseBody - Read the body of a class or def. Return true on error, false on
1697 /// Body ::= '{' BodyList '}'
1698 /// BodyList BodyItem*
1700 bool TGParser::ParseBody(Record *CurRec) {
1701 // If this is a null definition, just eat the semi and return.
1702 if (Lex.getCode() == tgtok::semi) {
1707 if (Lex.getCode() != tgtok::l_brace)
1708 return TokError("Expected ';' or '{' to start body");
1712 while (Lex.getCode() != tgtok::r_brace)
1713 if (ParseBodyItem(CurRec))
1721 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1722 /// optional ClassList followed by a Body. CurRec is the current def or class
1723 /// that is being parsed.
1725 /// ObjectBody ::= BaseClassList Body
1726 /// BaseClassList ::= /*empty*/
1727 /// BaseClassList ::= ':' BaseClassListNE
1728 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1730 bool TGParser::ParseObjectBody(Record *CurRec) {
1731 // If there is a baseclass list, read it.
1732 if (Lex.getCode() == tgtok::colon) {
1735 // Read all of the subclasses.
1736 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1739 if (SubClass.Rec == 0) return true;
1742 if (AddSubClass(CurRec, SubClass))
1745 if (Lex.getCode() != tgtok::comma) break;
1746 Lex.Lex(); // eat ','.
1747 SubClass = ParseSubClassReference(CurRec, false);
1751 // Process any variables on the let stack.
1752 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1753 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1754 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1755 LetStack[i][j].Bits, LetStack[i][j].Value))
1758 return ParseBody(CurRec);
1761 /// ParseDef - Parse and return a top level or multiclass def, return the record
1762 /// corresponding to it. This returns null on error.
1764 /// DefInst ::= DEF ObjectName ObjectBody
1766 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1767 SMLoc DefLoc = Lex.getLoc();
1768 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1769 Lex.Lex(); // Eat the 'def' token.
1771 // Parse ObjectName and make a record for it.
1772 Record *CurRec = new Record(ParseObjectName(CurMultiClass), DefLoc, Records);
1774 if (!CurMultiClass) {
1775 // Top-level def definition.
1777 // Ensure redefinition doesn't happen.
1778 if (Records.getDef(CurRec->getNameInitAsString())) {
1779 Error(DefLoc, "def '" + CurRec->getNameInitAsString()
1780 + "' already defined");
1783 Records.addDef(CurRec);
1785 // Otherwise, a def inside a multiclass, add it to the multiclass.
1786 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1787 if (CurMultiClass->DefPrototypes[i]->getNameInit()
1788 == CurRec->getNameInit()) {
1789 Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
1790 "' already defined in this multiclass!");
1793 CurMultiClass->DefPrototypes.push_back(CurRec);
1796 if (ParseObjectBody(CurRec))
1799 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1800 // See Record::setName(). This resolve step will see any new name
1801 // for the def that might have been created when resolving
1802 // inheritance, values and arguments above.
1803 CurRec->resolveReferences();
1805 // If ObjectBody has template arguments, it's an error.
1806 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1808 if (CurMultiClass) {
1809 // Copy the template arguments for the multiclass into the def.
1810 const std::vector<Init *> &TArgs =
1811 CurMultiClass->Rec.getTemplateArgs();
1813 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1814 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1815 assert(RV && "Template arg doesn't exist?");
1816 CurRec->addValue(*RV);
1823 /// ParseClass - Parse a tblgen class definition.
1825 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1827 bool TGParser::ParseClass() {
1828 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1831 if (Lex.getCode() != tgtok::Id)
1832 return TokError("expected class name after 'class' keyword");
1834 Record *CurRec = Records.getClass(Lex.getCurStrVal());
1836 // If the body was previously defined, this is an error.
1837 if (CurRec->getValues().size() > 1 || // Account for NAME.
1838 !CurRec->getSuperClasses().empty() ||
1839 !CurRec->getTemplateArgs().empty())
1840 return TokError("Class '" + CurRec->getNameInitAsString()
1841 + "' already defined");
1843 // If this is the first reference to this class, create and add it.
1844 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
1845 Records.addClass(CurRec);
1847 Lex.Lex(); // eat the name.
1849 // If there are template args, parse them.
1850 if (Lex.getCode() == tgtok::less)
1851 if (ParseTemplateArgList(CurRec))
1854 // Finally, parse the object body.
1855 return ParseObjectBody(CurRec);
1858 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1861 /// LetList ::= LetItem (',' LetItem)*
1862 /// LetItem ::= ID OptionalRangeList '=' Value
1864 std::vector<LetRecord> TGParser::ParseLetList() {
1865 std::vector<LetRecord> Result;
1868 if (Lex.getCode() != tgtok::Id) {
1869 TokError("expected identifier in let definition");
1870 return std::vector<LetRecord>();
1872 std::string Name = Lex.getCurStrVal();
1873 SMLoc NameLoc = Lex.getLoc();
1874 Lex.Lex(); // Eat the identifier.
1876 // Check for an optional RangeList.
1877 std::vector<unsigned> Bits;
1878 if (ParseOptionalRangeList(Bits))
1879 return std::vector<LetRecord>();
1880 std::reverse(Bits.begin(), Bits.end());
1882 if (Lex.getCode() != tgtok::equal) {
1883 TokError("expected '=' in let expression");
1884 return std::vector<LetRecord>();
1886 Lex.Lex(); // eat the '='.
1888 Init *Val = ParseValue(0);
1889 if (Val == 0) return std::vector<LetRecord>();
1891 // Now that we have everything, add the record.
1892 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1894 if (Lex.getCode() != tgtok::comma)
1896 Lex.Lex(); // eat the comma.
1900 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
1901 /// different related productions. This works inside multiclasses too.
1903 /// Object ::= LET LetList IN '{' ObjectList '}'
1904 /// Object ::= LET LetList IN Object
1906 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
1907 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1910 // Add this entry to the let stack.
1911 std::vector<LetRecord> LetInfo = ParseLetList();
1912 if (LetInfo.empty()) return true;
1913 LetStack.push_back(LetInfo);
1915 if (Lex.getCode() != tgtok::In)
1916 return TokError("expected 'in' at end of top-level 'let'");
1919 // If this is a scalar let, just handle it now
1920 if (Lex.getCode() != tgtok::l_brace) {
1921 // LET LetList IN Object
1922 if (ParseObject(CurMultiClass))
1924 } else { // Object ::= LETCommand '{' ObjectList '}'
1925 SMLoc BraceLoc = Lex.getLoc();
1926 // Otherwise, this is a group let.
1927 Lex.Lex(); // eat the '{'.
1929 // Parse the object list.
1930 if (ParseObjectList(CurMultiClass))
1933 if (Lex.getCode() != tgtok::r_brace) {
1934 TokError("expected '}' at end of top level let command");
1935 return Error(BraceLoc, "to match this '{'");
1940 // Outside this let scope, this let block is not active.
1941 LetStack.pop_back();
1945 /// ParseMultiClass - Parse a multiclass definition.
1947 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
1948 /// ':' BaseMultiClassList '{' MultiClassDef+ '}'
1950 bool TGParser::ParseMultiClass() {
1951 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1952 Lex.Lex(); // Eat the multiclass token.
1954 if (Lex.getCode() != tgtok::Id)
1955 return TokError("expected identifier after multiclass for name");
1956 std::string Name = Lex.getCurStrVal();
1958 if (MultiClasses.count(Name))
1959 return TokError("multiclass '" + Name + "' already defined");
1961 CurMultiClass = MultiClasses[Name] = new MultiClass(Name,
1962 Lex.getLoc(), Records);
1963 Lex.Lex(); // Eat the identifier.
1965 // If there are template args, parse them.
1966 if (Lex.getCode() == tgtok::less)
1967 if (ParseTemplateArgList(0))
1970 bool inherits = false;
1972 // If there are submulticlasses, parse them.
1973 if (Lex.getCode() == tgtok::colon) {
1978 // Read all of the submulticlasses.
1979 SubMultiClassReference SubMultiClass =
1980 ParseSubMultiClassReference(CurMultiClass);
1983 if (SubMultiClass.MC == 0) return true;
1986 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
1989 if (Lex.getCode() != tgtok::comma) break;
1990 Lex.Lex(); // eat ','.
1991 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
1995 if (Lex.getCode() != tgtok::l_brace) {
1997 return TokError("expected '{' in multiclass definition");
1998 else if (Lex.getCode() != tgtok::semi)
1999 return TokError("expected ';' in multiclass definition");
2001 Lex.Lex(); // eat the ';'.
2003 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2004 return TokError("multiclass must contain at least one def");
2006 while (Lex.getCode() != tgtok::r_brace) {
2007 switch (Lex.getCode()) {
2009 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2013 if (ParseObject(CurMultiClass))
2018 Lex.Lex(); // eat the '}'.
2026 InstantiateMulticlassDef(MultiClass &MC,
2029 SMLoc DefmPrefixLoc) {
2030 // We need to preserve DefProto so it can be reused for later
2031 // instantiations, so create a new Record to inherit from it.
2033 // Add in the defm name. If the defm prefix is empty, give each
2034 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2035 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2038 if (DefmPrefix == 0)
2039 DefmPrefix = StringInit::get(GetNewAnonymousName());
2041 Init *DefName = DefProto->getNameInit();
2043 StringInit *DefNameString = dynamic_cast<StringInit *>(DefName);
2045 if (DefNameString != 0) {
2046 // We have a fully expanded string so there are no operators to
2047 // resolve. We should concatenate the given prefix and name.
2049 BinOpInit::get(BinOpInit::STRCONCAT,
2050 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2051 StringRecTy::get())->Fold(DefProto, &MC),
2052 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2055 Record *CurRec = new Record(DefName, DefmPrefixLoc, Records);
2057 SubClassReference Ref;
2058 Ref.RefLoc = DefmPrefixLoc;
2060 AddSubClass(CurRec, Ref);
2062 if (DefNameString == 0) {
2063 // We must resolve references to NAME.
2064 if (SetValue(CurRec, Ref.RefLoc, "NAME", std::vector<unsigned>(),
2066 Error(DefmPrefixLoc, "Could not resolve "
2067 + CurRec->getNameInitAsString() + ":NAME to '"
2068 + DefmPrefix->getAsUnquotedString() + "'");
2072 RecordVal *DefNameRV = CurRec->getValue("NAME");
2073 CurRec->resolveReferencesTo(DefNameRV);
2076 if (!CurMultiClass) {
2077 // We do this after resolving NAME because before resolution, many
2078 // multiclass defs will have the same name expression. If we are
2079 // currently in a multiclass, it means this defm appears inside a
2080 // multiclass and its name won't be fully resolvable until we see
2081 // the top-level defm. Therefore, we don't add this to the
2082 // RecordKeeper at this point. If we did we could get duplicate
2083 // defs as more than one probably refers to NAME or some other
2084 // common internal placeholder.
2086 // Ensure redefinition doesn't happen.
2087 if (Records.getDef(CurRec->getNameInitAsString())) {
2088 Error(DefmPrefixLoc, "def '" + CurRec->getNameInitAsString() +
2089 "' already defined, instantiating defm with subdef '" +
2090 DefProto->getNameInitAsString() + "'");
2094 Records.addDef(CurRec);
2100 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2102 SMLoc DefmPrefixLoc,
2104 const std::vector<Init *> &TArgs,
2105 std::vector<Init *> &TemplateVals,
2107 // Loop over all of the template arguments, setting them to the specified
2108 // value or leaving them as the default if necessary.
2109 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2110 // Check if a value is specified for this temp-arg.
2111 if (i < TemplateVals.size()) {
2113 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2118 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2122 CurRec->removeValue(TArgs[i]);
2124 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2125 return Error(SubClassLoc, "value not specified for template argument #"+
2126 utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2127 + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2134 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2137 SMLoc DefmPrefixLoc) {
2138 // If the mdef is inside a 'let' expression, add to each def.
2139 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2140 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2141 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2142 LetStack[i][j].Bits, LetStack[i][j].Value))
2143 return Error(DefmPrefixLoc, "when instantiating this defm");
2145 // Don't create a top level definition for defm inside multiclasses,
2146 // instead, only update the prototypes and bind the template args
2147 // with the new created definition.
2148 if (CurMultiClass) {
2149 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2151 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2152 == CurRec->getNameInit())
2153 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2154 "' already defined in this multiclass!");
2155 CurMultiClass->DefPrototypes.push_back(CurRec);
2157 // Copy the template arguments for the multiclass into the new def.
2158 const std::vector<Init *> &TA =
2159 CurMultiClass->Rec.getTemplateArgs();
2161 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2162 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2163 assert(RV && "Template arg doesn't exist?");
2164 CurRec->addValue(*RV);
2171 /// ParseDefm - Parse the instantiation of a multiclass.
2173 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2175 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2176 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2178 Init *DefmPrefix = 0;
2180 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2181 DefmPrefix = ParseObjectName(CurMultiClass);
2184 SMLoc DefmPrefixLoc = Lex.getLoc();
2185 if (Lex.getCode() != tgtok::colon)
2186 return TokError("expected ':' after defm identifier");
2188 // Keep track of the new generated record definitions.
2189 std::vector<Record*> NewRecDefs;
2191 // This record also inherits from a regular class (non-multiclass)?
2192 bool InheritFromClass = false;
2197 SMLoc SubClassLoc = Lex.getLoc();
2198 SubClassReference Ref = ParseSubClassReference(0, true);
2201 if (Ref.Rec == 0) return true;
2203 // To instantiate a multiclass, we need to first get the multiclass, then
2204 // instantiate each def contained in the multiclass with the SubClassRef
2205 // template parameters.
2206 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2207 assert(MC && "Didn't lookup multiclass correctly?");
2208 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2210 // Verify that the correct number of template arguments were specified.
2211 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2212 if (TArgs.size() < TemplateVals.size())
2213 return Error(SubClassLoc,
2214 "more template args specified than multiclass expects");
2216 // Loop over all the def's in the multiclass, instantiating each one.
2217 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2218 Record *DefProto = MC->DefPrototypes[i];
2220 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix, DefmPrefixLoc);
2224 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmPrefixLoc, SubClassLoc,
2225 TArgs, TemplateVals, true/*Delete args*/))
2226 return Error(SubClassLoc, "could not instantiate def");
2228 if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmPrefixLoc))
2229 return Error(SubClassLoc, "could not instantiate def");
2231 NewRecDefs.push_back(CurRec);
2235 if (Lex.getCode() != tgtok::comma) break;
2236 Lex.Lex(); // eat ','.
2238 SubClassLoc = Lex.getLoc();
2240 // A defm can inherit from regular classes (non-multiclass) as
2241 // long as they come in the end of the inheritance list.
2242 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != 0);
2244 if (InheritFromClass)
2247 Ref = ParseSubClassReference(0, true);
2250 if (InheritFromClass) {
2251 // Process all the classes to inherit as if they were part of a
2252 // regular 'def' and inherit all record values.
2253 SubClassReference SubClass = ParseSubClassReference(0, false);
2256 if (SubClass.Rec == 0) return true;
2258 // Get the expanded definition prototypes and teach them about
2259 // the record values the current class to inherit has
2260 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2261 Record *CurRec = NewRecDefs[i];
2264 if (AddSubClass(CurRec, SubClass))
2267 // Process any variables on the let stack.
2268 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2269 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2270 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2271 LetStack[i][j].Bits, LetStack[i][j].Value))
2275 if (Lex.getCode() != tgtok::comma) break;
2276 Lex.Lex(); // eat ','.
2277 SubClass = ParseSubClassReference(0, false);
2282 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2283 // See Record::setName(). This resolve step will see any new
2284 // name for the def that might have been created when resolving
2285 // inheritance, values and arguments above.
2286 NewRecDefs[i]->resolveReferences();
2288 if (Lex.getCode() != tgtok::semi)
2289 return TokError("expected ';' at end of defm");
2296 /// Object ::= ClassInst
2297 /// Object ::= DefInst
2298 /// Object ::= MultiClassInst
2299 /// Object ::= DefMInst
2300 /// Object ::= LETCommand '{' ObjectList '}'
2301 /// Object ::= LETCommand Object
2302 bool TGParser::ParseObject(MultiClass *MC) {
2303 switch (Lex.getCode()) {
2305 return TokError("Expected class, def, defm, multiclass or let definition");
2306 case tgtok::Let: return ParseTopLevelLet(MC);
2307 case tgtok::Def: return ParseDef(MC);
2308 case tgtok::Defm: return ParseDefm(MC);
2309 case tgtok::Class: return ParseClass();
2310 case tgtok::MultiClass: return ParseMultiClass();
2315 /// ObjectList :== Object*
2316 bool TGParser::ParseObjectList(MultiClass *MC) {
2317 while (isObjectStart(Lex.getCode())) {
2318 if (ParseObject(MC))
2324 bool TGParser::ParseFile() {
2325 Lex.Lex(); // Prime the lexer.
2326 if (ParseObjectList()) return true;
2328 // If we have unread input at the end of the file, report it.
2329 if (Lex.getCode() == tgtok::Eof)
2332 return TokError("Unexpected input at top level");