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.getName())) {
68 // The value already exists in the class, treat this as a set.
69 if (ERV->setValue(RV.getValue()))
70 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
71 RV.getType()->getAsString() + "' is incompatible with " +
72 "previous definition of type '" +
73 ERV->getType()->getAsString() + "'");
81 /// Return true on error, false on success.
82 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, 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 ::= ID
310 /// ObjectName ::= /*empty*/
312 std::string TGParser::ParseObjectName() {
313 if (Lex.getCode() != tgtok::Id)
314 return GetNewAnonymousName();
316 std::string Ret = Lex.getCurStrVal();
322 /// ParseClassID - Parse and resolve a reference to a class name. This returns
327 Record *TGParser::ParseClassID() {
328 if (Lex.getCode() != tgtok::Id) {
329 TokError("expected name for ClassID");
333 Record *Result = Records.getClass(Lex.getCurStrVal());
335 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
341 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
342 /// This returns null on error.
344 /// MultiClassID ::= ID
346 MultiClass *TGParser::ParseMultiClassID() {
347 if (Lex.getCode() != tgtok::Id) {
348 TokError("expected name for ClassID");
352 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
354 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
360 Record *TGParser::ParseDefmID() {
361 if (Lex.getCode() != tgtok::Id) {
362 TokError("expected multiclass name");
366 MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
368 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
377 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
378 /// subclass. This returns a SubClassRefTy with a null Record* on error.
380 /// SubClassRef ::= ClassID
381 /// SubClassRef ::= ClassID '<' ValueList '>'
383 SubClassReference TGParser::
384 ParseSubClassReference(Record *CurRec, bool isDefm) {
385 SubClassReference Result;
386 Result.RefLoc = Lex.getLoc();
389 Result.Rec = ParseDefmID();
391 Result.Rec = ParseClassID();
392 if (Result.Rec == 0) return Result;
394 // If there is no template arg list, we're done.
395 if (Lex.getCode() != tgtok::less)
397 Lex.Lex(); // Eat the '<'
399 if (Lex.getCode() == tgtok::greater) {
400 TokError("subclass reference requires a non-empty list of template values");
405 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
406 if (Result.TemplateArgs.empty()) {
407 Result.Rec = 0; // Error parsing value list.
411 if (Lex.getCode() != tgtok::greater) {
412 TokError("expected '>' in template value list");
421 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
422 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
423 /// Record* on error.
425 /// SubMultiClassRef ::= MultiClassID
426 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
428 SubMultiClassReference TGParser::
429 ParseSubMultiClassReference(MultiClass *CurMC) {
430 SubMultiClassReference Result;
431 Result.RefLoc = Lex.getLoc();
433 Result.MC = ParseMultiClassID();
434 if (Result.MC == 0) return Result;
436 // If there is no template arg list, we're done.
437 if (Lex.getCode() != tgtok::less)
439 Lex.Lex(); // Eat the '<'
441 if (Lex.getCode() == tgtok::greater) {
442 TokError("subclass reference requires a non-empty list of template values");
447 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
448 if (Result.TemplateArgs.empty()) {
449 Result.MC = 0; // Error parsing value list.
453 if (Lex.getCode() != tgtok::greater) {
454 TokError("expected '>' in template value list");
463 /// ParseRangePiece - Parse a bit/value range.
464 /// RangePiece ::= INTVAL
465 /// RangePiece ::= INTVAL '-' INTVAL
466 /// RangePiece ::= INTVAL INTVAL
467 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
468 if (Lex.getCode() != tgtok::IntVal) {
469 TokError("expected integer or bitrange");
472 int64_t Start = Lex.getCurIntVal();
476 return TokError("invalid range, cannot be negative");
478 switch (Lex.Lex()) { // eat first character.
480 Ranges.push_back(Start);
483 if (Lex.Lex() != tgtok::IntVal) {
484 TokError("expected integer value as end of range");
487 End = Lex.getCurIntVal();
490 End = -Lex.getCurIntVal();
494 return TokError("invalid range, cannot be negative");
499 for (; Start <= End; ++Start)
500 Ranges.push_back(Start);
502 for (; Start >= End; --Start)
503 Ranges.push_back(Start);
508 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
510 /// RangeList ::= RangePiece (',' RangePiece)*
512 std::vector<unsigned> TGParser::ParseRangeList() {
513 std::vector<unsigned> Result;
515 // Parse the first piece.
516 if (ParseRangePiece(Result))
517 return std::vector<unsigned>();
518 while (Lex.getCode() == tgtok::comma) {
519 Lex.Lex(); // Eat the comma.
521 // Parse the next range piece.
522 if (ParseRangePiece(Result))
523 return std::vector<unsigned>();
528 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
529 /// OptionalRangeList ::= '<' RangeList '>'
530 /// OptionalRangeList ::= /*empty*/
531 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
532 if (Lex.getCode() != tgtok::less)
535 SMLoc StartLoc = Lex.getLoc();
536 Lex.Lex(); // eat the '<'
538 // Parse the range list.
539 Ranges = ParseRangeList();
540 if (Ranges.empty()) return true;
542 if (Lex.getCode() != tgtok::greater) {
543 TokError("expected '>' at end of range list");
544 return Error(StartLoc, "to match this '<'");
546 Lex.Lex(); // eat the '>'.
550 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
551 /// OptionalBitList ::= '{' RangeList '}'
552 /// OptionalBitList ::= /*empty*/
553 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
554 if (Lex.getCode() != tgtok::l_brace)
557 SMLoc StartLoc = Lex.getLoc();
558 Lex.Lex(); // eat the '{'
560 // Parse the range list.
561 Ranges = ParseRangeList();
562 if (Ranges.empty()) return true;
564 if (Lex.getCode() != tgtok::r_brace) {
565 TokError("expected '}' at end of bit list");
566 return Error(StartLoc, "to match this '{'");
568 Lex.Lex(); // eat the '}'.
573 /// ParseType - Parse and return a tblgen type. This returns null on error.
575 /// Type ::= STRING // string type
576 /// Type ::= BIT // bit type
577 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
578 /// Type ::= INT // int type
579 /// Type ::= LIST '<' Type '>' // list<x> type
580 /// Type ::= CODE // code type
581 /// Type ::= DAG // dag type
582 /// Type ::= ClassID // Record Type
584 RecTy *TGParser::ParseType() {
585 switch (Lex.getCode()) {
586 default: TokError("Unknown token when expecting a type"); return 0;
587 case tgtok::String: Lex.Lex(); return StringRecTy::get();
588 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
589 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
590 case tgtok::Code: Lex.Lex(); return CodeRecTy::get();
591 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
593 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
596 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
597 TokError("expected '<' after bits type");
600 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
601 TokError("expected integer in bits<n> type");
604 uint64_t Val = Lex.getCurIntVal();
605 if (Lex.Lex() != tgtok::greater) { // Eat count.
606 TokError("expected '>' at end of bits<n> type");
609 Lex.Lex(); // Eat '>'
610 return BitsRecTy::get(Val);
613 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
614 TokError("expected '<' after list type");
617 Lex.Lex(); // Eat '<'
618 RecTy *SubType = ParseType();
619 if (SubType == 0) return 0;
621 if (Lex.getCode() != tgtok::greater) {
622 TokError("expected '>' at end of list<ty> type");
625 Lex.Lex(); // Eat '>'
626 return ListRecTy::get(SubType);
631 /// ParseIDValue - Parse an ID as a value and decode what it means.
633 /// IDValue ::= ID [def local value]
634 /// IDValue ::= ID [def template arg]
635 /// IDValue ::= ID [multiclass local value]
636 /// IDValue ::= ID [multiclass template argument]
637 /// IDValue ::= ID [def name]
639 Init *TGParser::ParseIDValue(Record *CurRec) {
640 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
641 std::string Name = Lex.getCurStrVal();
642 SMLoc Loc = Lex.getLoc();
644 return ParseIDValue(CurRec, Name, Loc);
647 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
648 /// has already been read.
649 Init *TGParser::ParseIDValue(Record *CurRec,
650 const std::string &Name, SMLoc NameLoc) {
652 if (const RecordVal *RV = CurRec->getValue(Name))
653 return VarInit::get(Name, RV->getType());
655 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
658 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
661 if (CurRec->isTemplateArg(TemplateArgName)) {
662 const RecordVal *RV = CurRec->getValue(TemplateArgName);
663 assert(RV && "Template arg doesn't exist??");
664 return VarInit::get(TemplateArgName, RV->getType());
669 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
672 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
673 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
674 assert(RV && "Template arg doesn't exist??");
675 return VarInit::get(MCName, RV->getType());
679 if (Record *D = Records.getDef(Name))
680 return DefInit::get(D);
682 Error(NameLoc, "Variable not defined: '" + Name + "'");
686 /// ParseOperation - Parse an operator. This returns null on error.
688 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
690 Init *TGParser::ParseOperation(Record *CurRec) {
691 switch (Lex.getCode()) {
693 TokError("unknown operation");
699 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
700 UnOpInit::UnaryOp Code;
703 switch (Lex.getCode()) {
704 default: assert(0 && "Unhandled code!");
706 Lex.Lex(); // eat the operation
707 Code = UnOpInit::CAST;
709 Type = ParseOperatorType();
712 TokError("did not get type for unary operator");
718 Lex.Lex(); // eat the operation
719 Code = UnOpInit::HEAD;
722 Lex.Lex(); // eat the operation
723 Code = UnOpInit::TAIL;
726 Lex.Lex(); // eat the operation
727 Code = UnOpInit::EMPTY;
728 Type = IntRecTy::get();
731 if (Lex.getCode() != tgtok::l_paren) {
732 TokError("expected '(' after unary operator");
735 Lex.Lex(); // eat the '('
737 Init *LHS = ParseValue(CurRec);
738 if (LHS == 0) return 0;
740 if (Code == UnOpInit::HEAD
741 || Code == UnOpInit::TAIL
742 || Code == UnOpInit::EMPTY) {
743 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
744 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
745 TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
746 if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
747 TokError("expected list or string type argument in unary operator");
751 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
752 StringRecTy *SType = dynamic_cast<StringRecTy*>(LHSt->getType());
753 if (LType == 0 && SType == 0) {
754 TokError("expected list or string type argumnet in unary operator");
759 if (Code == UnOpInit::HEAD
760 || Code == UnOpInit::TAIL) {
761 if (LHSl == 0 && LHSt == 0) {
762 TokError("expected list type argumnet in unary operator");
766 if (LHSl && LHSl->getSize() == 0) {
767 TokError("empty list argument in unary operator");
771 Init *Item = LHSl->getElement(0);
772 TypedInit *Itemt = dynamic_cast<TypedInit*>(Item);
774 TokError("untyped list element in unary operator");
777 if (Code == UnOpInit::HEAD) {
778 Type = Itemt->getType();
780 Type = ListRecTy::get(Itemt->getType());
783 assert(LHSt && "expected list type argument in unary operator");
784 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
786 TokError("expected list type argumnet in unary operator");
789 if (Code == UnOpInit::HEAD) {
790 Type = LType->getElementType();
798 if (Lex.getCode() != tgtok::r_paren) {
799 TokError("expected ')' in unary operator");
802 Lex.Lex(); // eat the ')'
803 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
811 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
812 tgtok::TokKind OpTok = Lex.getCode();
813 SMLoc OpLoc = Lex.getLoc();
814 Lex.Lex(); // eat the operation
816 BinOpInit::BinaryOp Code;
820 default: assert(0 && "Unhandled code!");
821 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
822 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
823 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
824 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
825 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
826 case tgtok::XStrConcat:
827 Code = BinOpInit::STRCONCAT;
828 Type = StringRecTy::get();
832 if (Lex.getCode() != tgtok::l_paren) {
833 TokError("expected '(' after binary operator");
836 Lex.Lex(); // eat the '('
838 SmallVector<Init*, 2> InitList;
840 InitList.push_back(ParseValue(CurRec));
841 if (InitList.back() == 0) return 0;
843 while (Lex.getCode() == tgtok::comma) {
844 Lex.Lex(); // eat the ','
846 InitList.push_back(ParseValue(CurRec));
847 if (InitList.back() == 0) return 0;
850 if (Lex.getCode() != tgtok::r_paren) {
851 TokError("expected ')' in operator");
854 Lex.Lex(); // eat the ')'
856 // We allow multiple operands to associative operators like !strconcat as
857 // shorthand for nesting them.
858 if (Code == BinOpInit::STRCONCAT) {
859 while (InitList.size() > 2) {
860 Init *RHS = InitList.pop_back_val();
861 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
862 ->Fold(CurRec, CurMultiClass);
863 InitList.back() = RHS;
867 if (InitList.size() == 2)
868 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
869 ->Fold(CurRec, CurMultiClass);
871 Error(OpLoc, "expected two operands to operator");
876 case tgtok::XForEach:
877 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
878 TernOpInit::TernaryOp Code;
881 tgtok::TokKind LexCode = Lex.getCode();
882 Lex.Lex(); // eat the operation
884 default: assert(0 && "Unhandled code!");
886 Code = TernOpInit::IF;
888 case tgtok::XForEach:
889 Code = TernOpInit::FOREACH;
892 Code = TernOpInit::SUBST;
895 if (Lex.getCode() != tgtok::l_paren) {
896 TokError("expected '(' after ternary operator");
899 Lex.Lex(); // eat the '('
901 Init *LHS = ParseValue(CurRec);
902 if (LHS == 0) return 0;
904 if (Lex.getCode() != tgtok::comma) {
905 TokError("expected ',' in ternary operator");
908 Lex.Lex(); // eat the ','
910 Init *MHS = ParseValue(CurRec);
911 if (MHS == 0) return 0;
913 if (Lex.getCode() != tgtok::comma) {
914 TokError("expected ',' in ternary operator");
917 Lex.Lex(); // eat the ','
919 Init *RHS = ParseValue(CurRec);
920 if (RHS == 0) return 0;
922 if (Lex.getCode() != tgtok::r_paren) {
923 TokError("expected ')' in binary operator");
926 Lex.Lex(); // eat the ')'
929 default: assert(0 && "Unhandled code!");
931 // FIXME: The `!if' operator doesn't handle non-TypedInit well at
932 // all. This can be made much more robust.
933 TypedInit *MHSt = dynamic_cast<TypedInit*>(MHS);
934 TypedInit *RHSt = dynamic_cast<TypedInit*>(RHS);
939 if (MHSt == 0 && RHSt == 0) {
940 BitsInit *MHSbits = dynamic_cast<BitsInit*>(MHS);
941 BitsInit *RHSbits = dynamic_cast<BitsInit*>(RHS);
943 if (MHSbits && RHSbits &&
944 MHSbits->getNumBits() == RHSbits->getNumBits()) {
945 Type = BitRecTy::get();
948 BitInit *MHSbit = dynamic_cast<BitInit*>(MHS);
949 BitInit *RHSbit = dynamic_cast<BitInit*>(RHS);
951 if (MHSbit && RHSbit) {
952 Type = BitRecTy::get();
956 } else if (MHSt != 0 && RHSt != 0) {
957 MHSTy = MHSt->getType();
958 RHSTy = RHSt->getType();
961 if (!MHSTy || !RHSTy) {
962 TokError("could not get type for !if");
966 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
968 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
971 TokError("inconsistent types for !if");
976 case tgtok::XForEach: {
977 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
979 TokError("could not get type for !foreach");
982 Type = MHSt->getType();
985 case tgtok::XSubst: {
986 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
988 TokError("could not get type for !subst");
991 Type = RHSt->getType();
995 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
999 TokError("could not parse operation");
1003 /// ParseOperatorType - Parse a type for an operator. This returns
1006 /// OperatorType ::= '<' Type '>'
1008 RecTy *TGParser::ParseOperatorType() {
1011 if (Lex.getCode() != tgtok::less) {
1012 TokError("expected type name for operator");
1015 Lex.Lex(); // eat the <
1020 TokError("expected type name for operator");
1024 if (Lex.getCode() != tgtok::greater) {
1025 TokError("expected type name for operator");
1028 Lex.Lex(); // eat the >
1034 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1036 /// SimpleValue ::= IDValue
1037 /// SimpleValue ::= INTVAL
1038 /// SimpleValue ::= STRVAL+
1039 /// SimpleValue ::= CODEFRAGMENT
1040 /// SimpleValue ::= '?'
1041 /// SimpleValue ::= '{' ValueList '}'
1042 /// SimpleValue ::= ID '<' ValueListNE '>'
1043 /// SimpleValue ::= '[' ValueList ']'
1044 /// SimpleValue ::= '(' IDValue DagArgList ')'
1045 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1046 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1047 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1048 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1049 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1051 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType) {
1053 switch (Lex.getCode()) {
1054 default: TokError("Unknown token when parsing a value"); break;
1055 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1056 case tgtok::StrVal: {
1057 std::string Val = Lex.getCurStrVal();
1060 // Handle multiple consecutive concatenated strings.
1061 while (Lex.getCode() == tgtok::StrVal) {
1062 Val += Lex.getCurStrVal();
1066 R = StringInit::get(Val);
1069 case tgtok::CodeFragment:
1070 R = CodeInit::get(Lex.getCurStrVal());
1073 case tgtok::question:
1074 R = UnsetInit::get();
1078 SMLoc NameLoc = Lex.getLoc();
1079 std::string Name = Lex.getCurStrVal();
1080 if (Lex.Lex() != tgtok::less) // consume the Id.
1081 return ParseIDValue(CurRec, Name, NameLoc); // Value ::= IDValue
1083 // Value ::= ID '<' ValueListNE '>'
1084 if (Lex.Lex() == tgtok::greater) {
1085 TokError("expected non-empty value list");
1089 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1090 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1092 Record *Class = Records.getClass(Name);
1094 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1098 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1099 if (ValueList.empty()) return 0;
1101 if (Lex.getCode() != tgtok::greater) {
1102 TokError("expected '>' at end of value list");
1105 Lex.Lex(); // eat the '>'
1107 // Create the new record, set it as CurRec temporarily.
1108 static unsigned AnonCounter = 0;
1109 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),
1112 SubClassReference SCRef;
1113 SCRef.RefLoc = NameLoc;
1115 SCRef.TemplateArgs = ValueList;
1116 // Add info about the subclass to NewRec.
1117 if (AddSubClass(NewRec, SCRef))
1119 NewRec->resolveReferences();
1120 Records.addDef(NewRec);
1122 // The result of the expression is a reference to the new record.
1123 return DefInit::get(NewRec);
1125 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1126 SMLoc BraceLoc = Lex.getLoc();
1127 Lex.Lex(); // eat the '{'
1128 std::vector<Init*> Vals;
1130 if (Lex.getCode() != tgtok::r_brace) {
1131 Vals = ParseValueList(CurRec);
1132 if (Vals.empty()) return 0;
1134 if (Lex.getCode() != tgtok::r_brace) {
1135 TokError("expected '}' at end of bit list value");
1138 Lex.Lex(); // eat the '}'
1140 SmallVector<Init *, 16> NewBits(Vals.size());
1142 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1143 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1145 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1146 ") is not convertable to a bit");
1149 NewBits[Vals.size()-i-1] = Bit;
1151 return BitsInit::get(NewBits);
1153 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1154 Lex.Lex(); // eat the '['
1155 std::vector<Init*> Vals;
1157 RecTy *DeducedEltTy = 0;
1158 ListRecTy *GivenListTy = 0;
1160 if (ItemType != 0) {
1161 ListRecTy *ListType = dynamic_cast<ListRecTy*>(ItemType);
1162 if (ListType == 0) {
1163 std::stringstream s;
1164 s << "Type mismatch for list, expected list type, got "
1165 << ItemType->getAsString();
1169 GivenListTy = ListType;
1172 if (Lex.getCode() != tgtok::r_square) {
1173 Vals = ParseValueList(CurRec, 0,
1174 GivenListTy ? GivenListTy->getElementType() : 0);
1175 if (Vals.empty()) return 0;
1177 if (Lex.getCode() != tgtok::r_square) {
1178 TokError("expected ']' at end of list value");
1181 Lex.Lex(); // eat the ']'
1183 RecTy *GivenEltTy = 0;
1184 if (Lex.getCode() == tgtok::less) {
1185 // Optional list element type
1186 Lex.Lex(); // eat the '<'
1188 GivenEltTy = ParseType();
1189 if (GivenEltTy == 0) {
1190 // Couldn't parse element type
1194 if (Lex.getCode() != tgtok::greater) {
1195 TokError("expected '>' at end of list element type");
1198 Lex.Lex(); // eat the '>'
1203 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1206 TypedInit *TArg = dynamic_cast<TypedInit*>(*i);
1208 TokError("Untyped list element");
1212 EltTy = resolveTypes(EltTy, TArg->getType());
1214 TokError("Incompatible types in list elements");
1218 EltTy = TArg->getType();
1222 if (GivenEltTy != 0) {
1224 // Verify consistency
1225 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1226 TokError("Incompatible types in list elements");
1234 if (ItemType == 0) {
1235 TokError("No type for list");
1238 DeducedEltTy = GivenListTy->getElementType();
1240 // Make sure the deduced type is compatible with the given type
1242 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1243 TokError("Element type mismatch for list");
1247 DeducedEltTy = EltTy;
1250 return ListInit::get(Vals, DeducedEltTy);
1252 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1253 Lex.Lex(); // eat the '('
1254 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1255 TokError("expected identifier in dag init");
1259 Init *Operator = ParseValue(CurRec);
1260 if (Operator == 0) return 0;
1262 // If the operator name is present, parse it.
1263 std::string OperatorName;
1264 if (Lex.getCode() == tgtok::colon) {
1265 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1266 TokError("expected variable name in dag operator");
1269 OperatorName = Lex.getCurStrVal();
1270 Lex.Lex(); // eat the VarName.
1273 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1274 if (Lex.getCode() != tgtok::r_paren) {
1275 DagArgs = ParseDagArgList(CurRec);
1276 if (DagArgs.empty()) return 0;
1279 if (Lex.getCode() != tgtok::r_paren) {
1280 TokError("expected ')' in dag init");
1283 Lex.Lex(); // eat the ')'
1285 return DagInit::get(Operator, OperatorName, DagArgs);
1291 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1292 case tgtok::XConcat:
1297 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1299 case tgtok::XForEach:
1300 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1301 return ParseOperation(CurRec);
1308 /// ParseValue - Parse a tblgen value. This returns null on error.
1310 /// Value ::= SimpleValue ValueSuffix*
1311 /// ValueSuffix ::= '{' BitList '}'
1312 /// ValueSuffix ::= '[' BitList ']'
1313 /// ValueSuffix ::= '.' ID
1315 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType) {
1316 Init *Result = ParseSimpleValue(CurRec, ItemType);
1317 if (Result == 0) return 0;
1319 // Parse the suffixes now if present.
1321 switch (Lex.getCode()) {
1322 default: return Result;
1323 case tgtok::l_brace: {
1324 SMLoc CurlyLoc = Lex.getLoc();
1325 Lex.Lex(); // eat the '{'
1326 std::vector<unsigned> Ranges = ParseRangeList();
1327 if (Ranges.empty()) return 0;
1329 // Reverse the bitlist.
1330 std::reverse(Ranges.begin(), Ranges.end());
1331 Result = Result->convertInitializerBitRange(Ranges);
1333 Error(CurlyLoc, "Invalid bit range for value");
1338 if (Lex.getCode() != tgtok::r_brace) {
1339 TokError("expected '}' at end of bit range list");
1345 case tgtok::l_square: {
1346 SMLoc SquareLoc = Lex.getLoc();
1347 Lex.Lex(); // eat the '['
1348 std::vector<unsigned> Ranges = ParseRangeList();
1349 if (Ranges.empty()) return 0;
1351 Result = Result->convertInitListSlice(Ranges);
1353 Error(SquareLoc, "Invalid range for list slice");
1358 if (Lex.getCode() != tgtok::r_square) {
1359 TokError("expected ']' at end of list slice");
1366 if (Lex.Lex() != tgtok::Id) { // eat the .
1367 TokError("expected field identifier after '.'");
1370 if (!Result->getFieldType(Lex.getCurStrVal())) {
1371 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1372 Result->getAsString() + "'");
1375 Result = FieldInit::get(Result, Lex.getCurStrVal());
1376 Lex.Lex(); // eat field name
1382 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1384 /// ParseDagArgList ::= Value (':' VARNAME)?
1385 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1386 std::vector<std::pair<llvm::Init*, std::string> >
1387 TGParser::ParseDagArgList(Record *CurRec) {
1388 std::vector<std::pair<llvm::Init*, std::string> > Result;
1391 Init *Val = ParseValue(CurRec);
1392 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1394 // If the variable name is present, add it.
1395 std::string VarName;
1396 if (Lex.getCode() == tgtok::colon) {
1397 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1398 TokError("expected variable name in dag literal");
1399 return std::vector<std::pair<llvm::Init*, std::string> >();
1401 VarName = Lex.getCurStrVal();
1402 Lex.Lex(); // eat the VarName.
1405 Result.push_back(std::make_pair(Val, VarName));
1407 if (Lex.getCode() != tgtok::comma) break;
1408 Lex.Lex(); // eat the ','
1415 /// ParseValueList - Parse a comma separated list of values, returning them as a
1416 /// vector. Note that this always expects to be able to parse at least one
1417 /// value. It returns an empty list if this is not possible.
1419 /// ValueList ::= Value (',' Value)
1421 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1423 std::vector<Init*> Result;
1424 RecTy *ItemType = EltTy;
1425 unsigned int ArgN = 0;
1426 if (ArgsRec != 0 && EltTy == 0) {
1427 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1428 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1430 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1433 assert(RV && "Template argument record not found??");
1434 ItemType = RV->getType();
1437 Result.push_back(ParseValue(CurRec, ItemType));
1438 if (Result.back() == 0) return std::vector<Init*>();
1440 while (Lex.getCode() == tgtok::comma) {
1441 Lex.Lex(); // Eat the comma
1443 if (ArgsRec != 0 && EltTy == 0) {
1444 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1445 if (ArgN >= TArgs.size()) {
1446 TokError("too many template arguments");
1447 return std::vector<Init*>();
1449 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1450 assert(RV && "Template argument record not found??");
1451 ItemType = RV->getType();
1454 Result.push_back(ParseValue(CurRec, ItemType));
1455 if (Result.back() == 0) return std::vector<Init*>();
1462 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1463 /// empty string on error. This can happen in a number of different context's,
1464 /// including within a def or in the template args for a def (which which case
1465 /// CurRec will be non-null) and within the template args for a multiclass (in
1466 /// which case CurRec will be null, but CurMultiClass will be set). This can
1467 /// also happen within a def that is within a multiclass, which will set both
1468 /// CurRec and CurMultiClass.
1470 /// Declaration ::= FIELD? Type ID ('=' Value)?
1472 Init *TGParser::ParseDeclaration(Record *CurRec,
1473 bool ParsingTemplateArgs) {
1474 // Read the field prefix if present.
1475 bool HasField = Lex.getCode() == tgtok::Field;
1476 if (HasField) Lex.Lex();
1478 RecTy *Type = ParseType();
1479 if (Type == 0) return 0;
1481 if (Lex.getCode() != tgtok::Id) {
1482 TokError("Expected identifier in declaration");
1486 SMLoc IdLoc = Lex.getLoc();
1487 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1490 if (ParsingTemplateArgs) {
1492 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1494 assert(CurMultiClass);
1497 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1502 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1505 // If a value is present, parse it.
1506 if (Lex.getCode() == tgtok::equal) {
1508 SMLoc ValLoc = Lex.getLoc();
1509 Init *Val = ParseValue(CurRec, Type);
1511 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1518 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1519 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1520 /// template args for a def, which may or may not be in a multiclass. If null,
1521 /// these are the template args for a multiclass.
1523 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1525 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1526 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1527 Lex.Lex(); // eat the '<'
1529 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1531 // Read the first declaration.
1532 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1536 TheRecToAddTo->addTemplateArg(TemplArg);
1538 while (Lex.getCode() == tgtok::comma) {
1539 Lex.Lex(); // eat the ','
1541 // Read the following declarations.
1542 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1545 TheRecToAddTo->addTemplateArg(TemplArg);
1548 if (Lex.getCode() != tgtok::greater)
1549 return TokError("expected '>' at end of template argument list");
1550 Lex.Lex(); // eat the '>'.
1555 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1557 /// BodyItem ::= Declaration ';'
1558 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1559 bool TGParser::ParseBodyItem(Record *CurRec) {
1560 if (Lex.getCode() != tgtok::Let) {
1561 if (ParseDeclaration(CurRec, false) == 0)
1564 if (Lex.getCode() != tgtok::semi)
1565 return TokError("expected ';' after declaration");
1570 // LET ID OptionalRangeList '=' Value ';'
1571 if (Lex.Lex() != tgtok::Id)
1572 return TokError("expected field identifier after let");
1574 SMLoc IdLoc = Lex.getLoc();
1575 std::string FieldName = Lex.getCurStrVal();
1576 Lex.Lex(); // eat the field name.
1578 std::vector<unsigned> BitList;
1579 if (ParseOptionalBitList(BitList))
1581 std::reverse(BitList.begin(), BitList.end());
1583 if (Lex.getCode() != tgtok::equal)
1584 return TokError("expected '=' in let expression");
1585 Lex.Lex(); // eat the '='.
1587 RecordVal *Field = CurRec->getValue(FieldName);
1589 return TokError("Value '" + FieldName + "' unknown!");
1591 RecTy *Type = Field->getType();
1593 Init *Val = ParseValue(CurRec, Type);
1594 if (Val == 0) return true;
1596 if (Lex.getCode() != tgtok::semi)
1597 return TokError("expected ';' after let expression");
1600 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1603 /// ParseBody - Read the body of a class or def. Return true on error, false on
1607 /// Body ::= '{' BodyList '}'
1608 /// BodyList BodyItem*
1610 bool TGParser::ParseBody(Record *CurRec) {
1611 // If this is a null definition, just eat the semi and return.
1612 if (Lex.getCode() == tgtok::semi) {
1617 if (Lex.getCode() != tgtok::l_brace)
1618 return TokError("Expected ';' or '{' to start body");
1622 while (Lex.getCode() != tgtok::r_brace)
1623 if (ParseBodyItem(CurRec))
1631 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1632 /// optional ClassList followed by a Body. CurRec is the current def or class
1633 /// that is being parsed.
1635 /// ObjectBody ::= BaseClassList Body
1636 /// BaseClassList ::= /*empty*/
1637 /// BaseClassList ::= ':' BaseClassListNE
1638 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1640 bool TGParser::ParseObjectBody(Record *CurRec) {
1641 // If there is a baseclass list, read it.
1642 if (Lex.getCode() == tgtok::colon) {
1645 // Read all of the subclasses.
1646 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1649 if (SubClass.Rec == 0) return true;
1652 if (AddSubClass(CurRec, SubClass))
1655 if (Lex.getCode() != tgtok::comma) break;
1656 Lex.Lex(); // eat ','.
1657 SubClass = ParseSubClassReference(CurRec, false);
1661 // Process any variables on the let stack.
1662 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1663 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1664 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1665 LetStack[i][j].Bits, LetStack[i][j].Value))
1668 return ParseBody(CurRec);
1671 /// ParseDef - Parse and return a top level or multiclass def, return the record
1672 /// corresponding to it. This returns null on error.
1674 /// DefInst ::= DEF ObjectName ObjectBody
1676 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1677 SMLoc DefLoc = Lex.getLoc();
1678 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1679 Lex.Lex(); // Eat the 'def' token.
1681 // Parse ObjectName and make a record for it.
1682 Record *CurRec = new Record(ParseObjectName(), DefLoc, Records);
1684 if (!CurMultiClass) {
1685 // Top-level def definition.
1687 // Ensure redefinition doesn't happen.
1688 if (Records.getDef(CurRec->getName())) {
1689 Error(DefLoc, "def '" + CurRec->getNameInitAsString()
1690 + "' already defined");
1693 Records.addDef(CurRec);
1695 // Otherwise, a def inside a multiclass, add it to the multiclass.
1696 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1697 if (CurMultiClass->DefPrototypes[i]->getNameInit()
1698 == CurRec->getNameInit()) {
1699 Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
1700 "' already defined in this multiclass!");
1703 CurMultiClass->DefPrototypes.push_back(CurRec);
1706 if (ParseObjectBody(CurRec))
1709 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1710 // See Record::setName(). This resolve step will see any new name
1711 // for the def that might have been created when resolving
1712 // inheritance, values and arguments above.
1713 CurRec->resolveReferences();
1715 // If ObjectBody has template arguments, it's an error.
1716 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1718 if (CurMultiClass) {
1719 // Copy the template arguments for the multiclass into the def.
1720 const std::vector<Init *> &TArgs =
1721 CurMultiClass->Rec.getTemplateArgs();
1723 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1724 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1725 assert(RV && "Template arg doesn't exist?");
1726 CurRec->addValue(*RV);
1733 /// ParseClass - Parse a tblgen class definition.
1735 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1737 bool TGParser::ParseClass() {
1738 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1741 if (Lex.getCode() != tgtok::Id)
1742 return TokError("expected class name after 'class' keyword");
1744 Record *CurRec = Records.getClass(Lex.getCurStrVal());
1746 // If the body was previously defined, this is an error.
1747 if (!CurRec->getValues().empty() ||
1748 !CurRec->getSuperClasses().empty() ||
1749 !CurRec->getTemplateArgs().empty())
1750 return TokError("Class '" + CurRec->getName() + "' already defined");
1752 // If this is the first reference to this class, create and add it.
1753 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
1754 Records.addClass(CurRec);
1756 Lex.Lex(); // eat the name.
1758 // If there are template args, parse them.
1759 if (Lex.getCode() == tgtok::less)
1760 if (ParseTemplateArgList(CurRec))
1763 // Finally, parse the object body.
1764 return ParseObjectBody(CurRec);
1767 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1770 /// LetList ::= LetItem (',' LetItem)*
1771 /// LetItem ::= ID OptionalRangeList '=' Value
1773 std::vector<LetRecord> TGParser::ParseLetList() {
1774 std::vector<LetRecord> Result;
1777 if (Lex.getCode() != tgtok::Id) {
1778 TokError("expected identifier in let definition");
1779 return std::vector<LetRecord>();
1781 std::string Name = Lex.getCurStrVal();
1782 SMLoc NameLoc = Lex.getLoc();
1783 Lex.Lex(); // Eat the identifier.
1785 // Check for an optional RangeList.
1786 std::vector<unsigned> Bits;
1787 if (ParseOptionalRangeList(Bits))
1788 return std::vector<LetRecord>();
1789 std::reverse(Bits.begin(), Bits.end());
1791 if (Lex.getCode() != tgtok::equal) {
1792 TokError("expected '=' in let expression");
1793 return std::vector<LetRecord>();
1795 Lex.Lex(); // eat the '='.
1797 Init *Val = ParseValue(0);
1798 if (Val == 0) return std::vector<LetRecord>();
1800 // Now that we have everything, add the record.
1801 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1803 if (Lex.getCode() != tgtok::comma)
1805 Lex.Lex(); // eat the comma.
1809 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
1810 /// different related productions. This works inside multiclasses too.
1812 /// Object ::= LET LetList IN '{' ObjectList '}'
1813 /// Object ::= LET LetList IN Object
1815 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
1816 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1819 // Add this entry to the let stack.
1820 std::vector<LetRecord> LetInfo = ParseLetList();
1821 if (LetInfo.empty()) return true;
1822 LetStack.push_back(LetInfo);
1824 if (Lex.getCode() != tgtok::In)
1825 return TokError("expected 'in' at end of top-level 'let'");
1828 // If this is a scalar let, just handle it now
1829 if (Lex.getCode() != tgtok::l_brace) {
1830 // LET LetList IN Object
1831 if (ParseObject(CurMultiClass))
1833 } else { // Object ::= LETCommand '{' ObjectList '}'
1834 SMLoc BraceLoc = Lex.getLoc();
1835 // Otherwise, this is a group let.
1836 Lex.Lex(); // eat the '{'.
1838 // Parse the object list.
1839 if (ParseObjectList(CurMultiClass))
1842 if (Lex.getCode() != tgtok::r_brace) {
1843 TokError("expected '}' at end of top level let command");
1844 return Error(BraceLoc, "to match this '{'");
1849 // Outside this let scope, this let block is not active.
1850 LetStack.pop_back();
1854 /// ParseMultiClass - Parse a multiclass definition.
1856 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
1857 /// ':' BaseMultiClassList '{' MultiClassDef+ '}'
1859 bool TGParser::ParseMultiClass() {
1860 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1861 Lex.Lex(); // Eat the multiclass token.
1863 if (Lex.getCode() != tgtok::Id)
1864 return TokError("expected identifier after multiclass for name");
1865 std::string Name = Lex.getCurStrVal();
1867 if (MultiClasses.count(Name))
1868 return TokError("multiclass '" + Name + "' already defined");
1870 CurMultiClass = MultiClasses[Name] = new MultiClass(Name,
1871 Lex.getLoc(), Records);
1872 Lex.Lex(); // Eat the identifier.
1874 // If there are template args, parse them.
1875 if (Lex.getCode() == tgtok::less)
1876 if (ParseTemplateArgList(0))
1879 bool inherits = false;
1881 // If there are submulticlasses, parse them.
1882 if (Lex.getCode() == tgtok::colon) {
1887 // Read all of the submulticlasses.
1888 SubMultiClassReference SubMultiClass =
1889 ParseSubMultiClassReference(CurMultiClass);
1892 if (SubMultiClass.MC == 0) return true;
1895 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
1898 if (Lex.getCode() != tgtok::comma) break;
1899 Lex.Lex(); // eat ','.
1900 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
1904 if (Lex.getCode() != tgtok::l_brace) {
1906 return TokError("expected '{' in multiclass definition");
1907 else if (Lex.getCode() != tgtok::semi)
1908 return TokError("expected ';' in multiclass definition");
1910 Lex.Lex(); // eat the ';'.
1912 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
1913 return TokError("multiclass must contain at least one def");
1915 while (Lex.getCode() != tgtok::r_brace) {
1916 switch (Lex.getCode()) {
1918 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
1922 if (ParseObject(CurMultiClass))
1927 Lex.Lex(); // eat the '}'.
1935 InstantiateMulticlassDef(MultiClass &MC,
1937 const std::string &DefmPrefix,
1938 SMLoc DefmPrefixLoc) {
1939 // Add in the defm name. If the defm prefix is empty, give each
1940 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
1941 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
1943 std::string DefName = DefProto->getName();
1944 if (DefmPrefix.empty()) {
1945 DefName = GetNewAnonymousName();
1947 std::string::size_type idx = DefName.find("#NAME#");
1948 if (idx != std::string::npos) {
1949 DefName.replace(idx, 6, DefmPrefix);
1951 // Add the suffix to the defm name to get the new name.
1952 DefName = DefmPrefix + DefName;
1956 Record *CurRec = new Record(DefName, DefmPrefixLoc, Records);
1958 SubClassReference Ref;
1959 Ref.RefLoc = DefmPrefixLoc;
1961 AddSubClass(CurRec, Ref);
1966 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
1968 SMLoc DefmPrefixLoc,
1970 const std::vector<Init *> &TArgs,
1971 std::vector<Init *> &TemplateVals,
1973 // Loop over all of the template arguments, setting them to the specified
1974 // value or leaving them as the default if necessary.
1975 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1976 // Check if a value is specified for this temp-arg.
1977 if (i < TemplateVals.size()) {
1979 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
1984 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
1988 CurRec->removeValue(TArgs[i]);
1990 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
1991 return Error(SubClassLoc, "value not specified for template argument #"+
1992 utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
1993 + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2000 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2003 SMLoc DefmPrefixLoc) {
2004 // If the mdef is inside a 'let' expression, add to each def.
2005 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2006 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2007 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2008 LetStack[i][j].Bits, LetStack[i][j].Value))
2009 return Error(DefmPrefixLoc, "when instantiating this defm");
2011 // Ensure redefinition doesn't happen.
2012 if (Records.getDef(CurRec->getName()))
2013 return Error(DefmPrefixLoc, "def '" + CurRec->getName() +
2014 "' already defined, instantiating defm with subdef '" +
2015 DefProto->getName() + "'");
2017 // Don't create a top level definition for defm inside multiclasses,
2018 // instead, only update the prototypes and bind the template args
2019 // with the new created definition.
2020 if (CurMultiClass) {
2021 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2023 if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName())
2024 return Error(DefmPrefixLoc, "defm '" + CurRec->getName() +
2025 "' already defined in this multiclass!");
2026 CurMultiClass->DefPrototypes.push_back(CurRec);
2028 // Copy the template arguments for the multiclass into the new def.
2029 const std::vector<Init *> &TA =
2030 CurMultiClass->Rec.getTemplateArgs();
2032 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2033 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2034 assert(RV && "Template arg doesn't exist?");
2035 CurRec->addValue(*RV);
2038 Records.addDef(CurRec);
2044 /// ParseDefm - Parse the instantiation of a multiclass.
2046 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2048 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2049 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2051 std::string DefmPrefix;
2052 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2053 DefmPrefix = Lex.getCurStrVal();
2054 Lex.Lex(); // Eat the defm prefix.
2057 SMLoc DefmPrefixLoc = Lex.getLoc();
2058 if (Lex.getCode() != tgtok::colon)
2059 return TokError("expected ':' after defm identifier");
2061 // Keep track of the new generated record definitions.
2062 std::vector<Record*> NewRecDefs;
2064 // This record also inherits from a regular class (non-multiclass)?
2065 bool InheritFromClass = false;
2070 SMLoc SubClassLoc = Lex.getLoc();
2071 SubClassReference Ref = ParseSubClassReference(0, true);
2074 if (Ref.Rec == 0) return true;
2076 // To instantiate a multiclass, we need to first get the multiclass, then
2077 // instantiate each def contained in the multiclass with the SubClassRef
2078 // template parameters.
2079 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2080 assert(MC && "Didn't lookup multiclass correctly?");
2081 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2083 // Verify that the correct number of template arguments were specified.
2084 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2085 if (TArgs.size() < TemplateVals.size())
2086 return Error(SubClassLoc,
2087 "more template args specified than multiclass expects");
2089 // Loop over all the def's in the multiclass, instantiating each one.
2090 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2091 Record *DefProto = MC->DefPrototypes[i];
2093 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix, DefmPrefixLoc);
2095 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmPrefixLoc, SubClassLoc,
2096 TArgs, TemplateVals, true/*Delete args*/))
2097 return Error(SubClassLoc, "could not instantiate def");
2099 if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmPrefixLoc))
2100 return Error(SubClassLoc, "could not instantiate def");
2102 NewRecDefs.push_back(CurRec);
2106 if (Lex.getCode() != tgtok::comma) break;
2107 Lex.Lex(); // eat ','.
2109 SubClassLoc = Lex.getLoc();
2111 // A defm can inherit from regular classes (non-multiclass) as
2112 // long as they come in the end of the inheritance list.
2113 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != 0);
2115 if (InheritFromClass)
2118 Ref = ParseSubClassReference(0, true);
2121 if (InheritFromClass) {
2122 // Process all the classes to inherit as if they were part of a
2123 // regular 'def' and inherit all record values.
2124 SubClassReference SubClass = ParseSubClassReference(0, false);
2127 if (SubClass.Rec == 0) return true;
2129 // Get the expanded definition prototypes and teach them about
2130 // the record values the current class to inherit has
2131 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2132 Record *CurRec = NewRecDefs[i];
2135 if (AddSubClass(CurRec, SubClass))
2138 // Process any variables on the let stack.
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))
2146 if (Lex.getCode() != tgtok::comma) break;
2147 Lex.Lex(); // eat ','.
2148 SubClass = ParseSubClassReference(0, false);
2153 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2154 // See Record::setName(). This resolve step will see any new
2155 // name for the def that might have been created when resolving
2156 // inheritance, values and arguments above.
2157 NewRecDefs[i]->resolveReferences();
2159 if (Lex.getCode() != tgtok::semi)
2160 return TokError("expected ';' at end of defm");
2167 /// Object ::= ClassInst
2168 /// Object ::= DefInst
2169 /// Object ::= MultiClassInst
2170 /// Object ::= DefMInst
2171 /// Object ::= LETCommand '{' ObjectList '}'
2172 /// Object ::= LETCommand Object
2173 bool TGParser::ParseObject(MultiClass *MC) {
2174 switch (Lex.getCode()) {
2176 return TokError("Expected class, def, defm, multiclass or let definition");
2177 case tgtok::Let: return ParseTopLevelLet(MC);
2178 case tgtok::Def: return ParseDef(MC);
2179 case tgtok::Defm: return ParseDefm(MC);
2180 case tgtok::Class: return ParseClass();
2181 case tgtok::MultiClass: return ParseMultiClass();
2186 /// ObjectList :== Object*
2187 bool TGParser::ParseObjectList(MultiClass *MC) {
2188 while (isObjectStart(Lex.getCode())) {
2189 if (ParseObject(MC))
2195 bool TGParser::ParseFile() {
2196 Lex.Lex(); // Prime the lexer.
2197 if (ParseObjectList()) return true;
2199 // If we have unread input at the end of the file, report it.
2200 if (Lex.getCode() == tgtok::Eof)
2203 return TokError("Unexpected input at top level");