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, IDParseMode Mode) {
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,
653 if (const RecordVal *RV = CurRec->getValue(Name))
654 return VarInit::get(Name, RV->getType());
656 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
659 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
662 if (CurRec->isTemplateArg(TemplateArgName)) {
663 const RecordVal *RV = CurRec->getValue(TemplateArgName);
664 assert(RV && "Template arg doesn't exist??");
665 return VarInit::get(TemplateArgName, RV->getType());
670 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
673 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
674 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
675 assert(RV && "Template arg doesn't exist??");
676 return VarInit::get(MCName, RV->getType());
680 if (Mode == ParseNameMode)
681 return StringInit::get(Name);
683 if (Record *D = Records.getDef(Name))
684 return DefInit::get(D);
686 if (Mode == ParseValueMode) {
687 Error(NameLoc, "Variable not defined: '" + Name + "'");
691 return StringInit::get(Name);
694 /// ParseOperation - Parse an operator. This returns null on error.
696 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
698 Init *TGParser::ParseOperation(Record *CurRec) {
699 switch (Lex.getCode()) {
701 TokError("unknown operation");
707 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
708 UnOpInit::UnaryOp Code;
711 switch (Lex.getCode()) {
712 default: assert(0 && "Unhandled code!");
714 Lex.Lex(); // eat the operation
715 Code = UnOpInit::CAST;
717 Type = ParseOperatorType();
720 TokError("did not get type for unary operator");
726 Lex.Lex(); // eat the operation
727 Code = UnOpInit::HEAD;
730 Lex.Lex(); // eat the operation
731 Code = UnOpInit::TAIL;
734 Lex.Lex(); // eat the operation
735 Code = UnOpInit::EMPTY;
736 Type = IntRecTy::get();
739 if (Lex.getCode() != tgtok::l_paren) {
740 TokError("expected '(' after unary operator");
743 Lex.Lex(); // eat the '('
745 Init *LHS = ParseValue(CurRec);
746 if (LHS == 0) return 0;
748 if (Code == UnOpInit::HEAD
749 || Code == UnOpInit::TAIL
750 || Code == UnOpInit::EMPTY) {
751 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
752 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
753 TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
754 if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
755 TokError("expected list or string type argument in unary operator");
759 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
760 StringRecTy *SType = dynamic_cast<StringRecTy*>(LHSt->getType());
761 if (LType == 0 && SType == 0) {
762 TokError("expected list or string type argumnet in unary operator");
767 if (Code == UnOpInit::HEAD
768 || Code == UnOpInit::TAIL) {
769 if (LHSl == 0 && LHSt == 0) {
770 TokError("expected list type argumnet in unary operator");
774 if (LHSl && LHSl->getSize() == 0) {
775 TokError("empty list argument in unary operator");
779 Init *Item = LHSl->getElement(0);
780 TypedInit *Itemt = dynamic_cast<TypedInit*>(Item);
782 TokError("untyped list element in unary operator");
785 if (Code == UnOpInit::HEAD) {
786 Type = Itemt->getType();
788 Type = ListRecTy::get(Itemt->getType());
791 assert(LHSt && "expected list type argument in unary operator");
792 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
794 TokError("expected list type argumnet in unary operator");
797 if (Code == UnOpInit::HEAD) {
798 Type = LType->getElementType();
806 if (Lex.getCode() != tgtok::r_paren) {
807 TokError("expected ')' in unary operator");
810 Lex.Lex(); // eat the ')'
811 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
819 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
820 tgtok::TokKind OpTok = Lex.getCode();
821 SMLoc OpLoc = Lex.getLoc();
822 Lex.Lex(); // eat the operation
824 BinOpInit::BinaryOp Code;
828 default: assert(0 && "Unhandled code!");
829 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
830 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
831 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
832 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
833 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
834 case tgtok::XStrConcat:
835 Code = BinOpInit::STRCONCAT;
836 Type = StringRecTy::get();
840 if (Lex.getCode() != tgtok::l_paren) {
841 TokError("expected '(' after binary operator");
844 Lex.Lex(); // eat the '('
846 SmallVector<Init*, 2> InitList;
848 InitList.push_back(ParseValue(CurRec));
849 if (InitList.back() == 0) return 0;
851 while (Lex.getCode() == tgtok::comma) {
852 Lex.Lex(); // eat the ','
854 InitList.push_back(ParseValue(CurRec));
855 if (InitList.back() == 0) return 0;
858 if (Lex.getCode() != tgtok::r_paren) {
859 TokError("expected ')' in operator");
862 Lex.Lex(); // eat the ')'
864 // We allow multiple operands to associative operators like !strconcat as
865 // shorthand for nesting them.
866 if (Code == BinOpInit::STRCONCAT) {
867 while (InitList.size() > 2) {
868 Init *RHS = InitList.pop_back_val();
869 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
870 ->Fold(CurRec, CurMultiClass);
871 InitList.back() = RHS;
875 if (InitList.size() == 2)
876 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
877 ->Fold(CurRec, CurMultiClass);
879 Error(OpLoc, "expected two operands to operator");
884 case tgtok::XForEach:
885 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
886 TernOpInit::TernaryOp Code;
889 tgtok::TokKind LexCode = Lex.getCode();
890 Lex.Lex(); // eat the operation
892 default: assert(0 && "Unhandled code!");
894 Code = TernOpInit::IF;
896 case tgtok::XForEach:
897 Code = TernOpInit::FOREACH;
900 Code = TernOpInit::SUBST;
903 if (Lex.getCode() != tgtok::l_paren) {
904 TokError("expected '(' after ternary operator");
907 Lex.Lex(); // eat the '('
909 Init *LHS = ParseValue(CurRec);
910 if (LHS == 0) return 0;
912 if (Lex.getCode() != tgtok::comma) {
913 TokError("expected ',' in ternary operator");
916 Lex.Lex(); // eat the ','
918 Init *MHS = ParseValue(CurRec);
919 if (MHS == 0) return 0;
921 if (Lex.getCode() != tgtok::comma) {
922 TokError("expected ',' in ternary operator");
925 Lex.Lex(); // eat the ','
927 Init *RHS = ParseValue(CurRec);
928 if (RHS == 0) return 0;
930 if (Lex.getCode() != tgtok::r_paren) {
931 TokError("expected ')' in binary operator");
934 Lex.Lex(); // eat the ')'
937 default: assert(0 && "Unhandled code!");
939 // FIXME: The `!if' operator doesn't handle non-TypedInit well at
940 // all. This can be made much more robust.
941 TypedInit *MHSt = dynamic_cast<TypedInit*>(MHS);
942 TypedInit *RHSt = dynamic_cast<TypedInit*>(RHS);
947 if (MHSt == 0 && RHSt == 0) {
948 BitsInit *MHSbits = dynamic_cast<BitsInit*>(MHS);
949 BitsInit *RHSbits = dynamic_cast<BitsInit*>(RHS);
951 if (MHSbits && RHSbits &&
952 MHSbits->getNumBits() == RHSbits->getNumBits()) {
953 Type = BitRecTy::get();
956 BitInit *MHSbit = dynamic_cast<BitInit*>(MHS);
957 BitInit *RHSbit = dynamic_cast<BitInit*>(RHS);
959 if (MHSbit && RHSbit) {
960 Type = BitRecTy::get();
964 } else if (MHSt != 0 && RHSt != 0) {
965 MHSTy = MHSt->getType();
966 RHSTy = RHSt->getType();
969 if (!MHSTy || !RHSTy) {
970 TokError("could not get type for !if");
974 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
976 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
979 TokError("inconsistent types for !if");
984 case tgtok::XForEach: {
985 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
987 TokError("could not get type for !foreach");
990 Type = MHSt->getType();
993 case tgtok::XSubst: {
994 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
996 TokError("could not get type for !subst");
999 Type = RHSt->getType();
1003 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1007 TokError("could not parse operation");
1011 /// ParseOperatorType - Parse a type for an operator. This returns
1014 /// OperatorType ::= '<' Type '>'
1016 RecTy *TGParser::ParseOperatorType() {
1019 if (Lex.getCode() != tgtok::less) {
1020 TokError("expected type name for operator");
1023 Lex.Lex(); // eat the <
1028 TokError("expected type name for operator");
1032 if (Lex.getCode() != tgtok::greater) {
1033 TokError("expected type name for operator");
1036 Lex.Lex(); // eat the >
1042 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1044 /// SimpleValue ::= IDValue
1045 /// SimpleValue ::= INTVAL
1046 /// SimpleValue ::= STRVAL+
1047 /// SimpleValue ::= CODEFRAGMENT
1048 /// SimpleValue ::= '?'
1049 /// SimpleValue ::= '{' ValueList '}'
1050 /// SimpleValue ::= ID '<' ValueListNE '>'
1051 /// SimpleValue ::= '[' ValueList ']'
1052 /// SimpleValue ::= '(' IDValue DagArgList ')'
1053 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1054 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1055 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1056 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1057 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1059 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1062 switch (Lex.getCode()) {
1063 default: TokError("Unknown token when parsing a value"); break;
1064 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1065 case tgtok::StrVal: {
1066 std::string Val = Lex.getCurStrVal();
1069 // Handle multiple consecutive concatenated strings.
1070 while (Lex.getCode() == tgtok::StrVal) {
1071 Val += Lex.getCurStrVal();
1075 R = StringInit::get(Val);
1078 case tgtok::CodeFragment:
1079 R = CodeInit::get(Lex.getCurStrVal());
1082 case tgtok::question:
1083 R = UnsetInit::get();
1087 SMLoc NameLoc = Lex.getLoc();
1088 std::string Name = Lex.getCurStrVal();
1089 if (Lex.Lex() != tgtok::less) // consume the Id.
1090 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1092 // Value ::= ID '<' ValueListNE '>'
1093 if (Lex.Lex() == tgtok::greater) {
1094 TokError("expected non-empty value list");
1098 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1099 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1101 Record *Class = Records.getClass(Name);
1103 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1107 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1108 if (ValueList.empty()) return 0;
1110 if (Lex.getCode() != tgtok::greater) {
1111 TokError("expected '>' at end of value list");
1114 Lex.Lex(); // eat the '>'
1116 // Create the new record, set it as CurRec temporarily.
1117 static unsigned AnonCounter = 0;
1118 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),
1121 SubClassReference SCRef;
1122 SCRef.RefLoc = NameLoc;
1124 SCRef.TemplateArgs = ValueList;
1125 // Add info about the subclass to NewRec.
1126 if (AddSubClass(NewRec, SCRef))
1128 NewRec->resolveReferences();
1129 Records.addDef(NewRec);
1131 // The result of the expression is a reference to the new record.
1132 return DefInit::get(NewRec);
1134 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1135 SMLoc BraceLoc = Lex.getLoc();
1136 Lex.Lex(); // eat the '{'
1137 std::vector<Init*> Vals;
1139 if (Lex.getCode() != tgtok::r_brace) {
1140 Vals = ParseValueList(CurRec);
1141 if (Vals.empty()) return 0;
1143 if (Lex.getCode() != tgtok::r_brace) {
1144 TokError("expected '}' at end of bit list value");
1147 Lex.Lex(); // eat the '}'
1149 SmallVector<Init *, 16> NewBits(Vals.size());
1151 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1152 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1154 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1155 ") is not convertable to a bit");
1158 NewBits[Vals.size()-i-1] = Bit;
1160 return BitsInit::get(NewBits);
1162 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1163 Lex.Lex(); // eat the '['
1164 std::vector<Init*> Vals;
1166 RecTy *DeducedEltTy = 0;
1167 ListRecTy *GivenListTy = 0;
1169 if (ItemType != 0) {
1170 ListRecTy *ListType = dynamic_cast<ListRecTy*>(ItemType);
1171 if (ListType == 0) {
1172 std::stringstream s;
1173 s << "Type mismatch for list, expected list type, got "
1174 << ItemType->getAsString();
1178 GivenListTy = ListType;
1181 if (Lex.getCode() != tgtok::r_square) {
1182 Vals = ParseValueList(CurRec, 0,
1183 GivenListTy ? GivenListTy->getElementType() : 0);
1184 if (Vals.empty()) return 0;
1186 if (Lex.getCode() != tgtok::r_square) {
1187 TokError("expected ']' at end of list value");
1190 Lex.Lex(); // eat the ']'
1192 RecTy *GivenEltTy = 0;
1193 if (Lex.getCode() == tgtok::less) {
1194 // Optional list element type
1195 Lex.Lex(); // eat the '<'
1197 GivenEltTy = ParseType();
1198 if (GivenEltTy == 0) {
1199 // Couldn't parse element type
1203 if (Lex.getCode() != tgtok::greater) {
1204 TokError("expected '>' at end of list element type");
1207 Lex.Lex(); // eat the '>'
1212 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1215 TypedInit *TArg = dynamic_cast<TypedInit*>(*i);
1217 TokError("Untyped list element");
1221 EltTy = resolveTypes(EltTy, TArg->getType());
1223 TokError("Incompatible types in list elements");
1227 EltTy = TArg->getType();
1231 if (GivenEltTy != 0) {
1233 // Verify consistency
1234 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1235 TokError("Incompatible types in list elements");
1243 if (ItemType == 0) {
1244 TokError("No type for list");
1247 DeducedEltTy = GivenListTy->getElementType();
1249 // Make sure the deduced type is compatible with the given type
1251 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1252 TokError("Element type mismatch for list");
1256 DeducedEltTy = EltTy;
1259 return ListInit::get(Vals, DeducedEltTy);
1261 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1262 Lex.Lex(); // eat the '('
1263 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1264 TokError("expected identifier in dag init");
1268 Init *Operator = ParseValue(CurRec);
1269 if (Operator == 0) return 0;
1271 // If the operator name is present, parse it.
1272 std::string OperatorName;
1273 if (Lex.getCode() == tgtok::colon) {
1274 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1275 TokError("expected variable name in dag operator");
1278 OperatorName = Lex.getCurStrVal();
1279 Lex.Lex(); // eat the VarName.
1282 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1283 if (Lex.getCode() != tgtok::r_paren) {
1284 DagArgs = ParseDagArgList(CurRec);
1285 if (DagArgs.empty()) return 0;
1288 if (Lex.getCode() != tgtok::r_paren) {
1289 TokError("expected ')' in dag init");
1292 Lex.Lex(); // eat the ')'
1294 return DagInit::get(Operator, OperatorName, DagArgs);
1300 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1301 case tgtok::XConcat:
1306 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1308 case tgtok::XForEach:
1309 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1310 return ParseOperation(CurRec);
1317 /// ParseValue - Parse a tblgen value. This returns null on error.
1319 /// Value ::= SimpleValue ValueSuffix*
1320 /// ValueSuffix ::= '{' BitList '}'
1321 /// ValueSuffix ::= '[' BitList ']'
1322 /// ValueSuffix ::= '.' ID
1324 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1325 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1326 if (Result == 0) return 0;
1328 // Parse the suffixes now if present.
1330 switch (Lex.getCode()) {
1331 default: return Result;
1332 case tgtok::l_brace: {
1333 SMLoc CurlyLoc = Lex.getLoc();
1334 Lex.Lex(); // eat the '{'
1335 std::vector<unsigned> Ranges = ParseRangeList();
1336 if (Ranges.empty()) return 0;
1338 // Reverse the bitlist.
1339 std::reverse(Ranges.begin(), Ranges.end());
1340 Result = Result->convertInitializerBitRange(Ranges);
1342 Error(CurlyLoc, "Invalid bit range for value");
1347 if (Lex.getCode() != tgtok::r_brace) {
1348 TokError("expected '}' at end of bit range list");
1354 case tgtok::l_square: {
1355 SMLoc SquareLoc = Lex.getLoc();
1356 Lex.Lex(); // eat the '['
1357 std::vector<unsigned> Ranges = ParseRangeList();
1358 if (Ranges.empty()) return 0;
1360 Result = Result->convertInitListSlice(Ranges);
1362 Error(SquareLoc, "Invalid range for list slice");
1367 if (Lex.getCode() != tgtok::r_square) {
1368 TokError("expected ']' at end of list slice");
1375 if (Lex.Lex() != tgtok::Id) { // eat the .
1376 TokError("expected field identifier after '.'");
1379 if (!Result->getFieldType(Lex.getCurStrVal())) {
1380 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1381 Result->getAsString() + "'");
1384 Result = FieldInit::get(Result, Lex.getCurStrVal());
1385 Lex.Lex(); // eat field name
1391 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1393 /// ParseDagArgList ::= Value (':' VARNAME)?
1394 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1395 std::vector<std::pair<llvm::Init*, std::string> >
1396 TGParser::ParseDagArgList(Record *CurRec) {
1397 std::vector<std::pair<llvm::Init*, std::string> > Result;
1400 Init *Val = ParseValue(CurRec);
1401 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1403 // If the variable name is present, add it.
1404 std::string VarName;
1405 if (Lex.getCode() == tgtok::colon) {
1406 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1407 TokError("expected variable name in dag literal");
1408 return std::vector<std::pair<llvm::Init*, std::string> >();
1410 VarName = Lex.getCurStrVal();
1411 Lex.Lex(); // eat the VarName.
1414 Result.push_back(std::make_pair(Val, VarName));
1416 if (Lex.getCode() != tgtok::comma) break;
1417 Lex.Lex(); // eat the ','
1424 /// ParseValueList - Parse a comma separated list of values, returning them as a
1425 /// vector. Note that this always expects to be able to parse at least one
1426 /// value. It returns an empty list if this is not possible.
1428 /// ValueList ::= Value (',' Value)
1430 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1432 std::vector<Init*> Result;
1433 RecTy *ItemType = EltTy;
1434 unsigned int ArgN = 0;
1435 if (ArgsRec != 0 && EltTy == 0) {
1436 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1437 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1439 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1442 assert(RV && "Template argument record not found??");
1443 ItemType = RV->getType();
1446 Result.push_back(ParseValue(CurRec, ItemType));
1447 if (Result.back() == 0) return std::vector<Init*>();
1449 while (Lex.getCode() == tgtok::comma) {
1450 Lex.Lex(); // Eat the comma
1452 if (ArgsRec != 0 && EltTy == 0) {
1453 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1454 if (ArgN >= TArgs.size()) {
1455 TokError("too many template arguments");
1456 return std::vector<Init*>();
1458 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1459 assert(RV && "Template argument record not found??");
1460 ItemType = RV->getType();
1463 Result.push_back(ParseValue(CurRec, ItemType));
1464 if (Result.back() == 0) return std::vector<Init*>();
1471 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1472 /// empty string on error. This can happen in a number of different context's,
1473 /// including within a def or in the template args for a def (which which case
1474 /// CurRec will be non-null) and within the template args for a multiclass (in
1475 /// which case CurRec will be null, but CurMultiClass will be set). This can
1476 /// also happen within a def that is within a multiclass, which will set both
1477 /// CurRec and CurMultiClass.
1479 /// Declaration ::= FIELD? Type ID ('=' Value)?
1481 Init *TGParser::ParseDeclaration(Record *CurRec,
1482 bool ParsingTemplateArgs) {
1483 // Read the field prefix if present.
1484 bool HasField = Lex.getCode() == tgtok::Field;
1485 if (HasField) Lex.Lex();
1487 RecTy *Type = ParseType();
1488 if (Type == 0) return 0;
1490 if (Lex.getCode() != tgtok::Id) {
1491 TokError("Expected identifier in declaration");
1495 SMLoc IdLoc = Lex.getLoc();
1496 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1499 if (ParsingTemplateArgs) {
1501 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1503 assert(CurMultiClass);
1506 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1511 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1514 // If a value is present, parse it.
1515 if (Lex.getCode() == tgtok::equal) {
1517 SMLoc ValLoc = Lex.getLoc();
1518 Init *Val = ParseValue(CurRec, Type);
1520 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1527 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1528 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1529 /// template args for a def, which may or may not be in a multiclass. If null,
1530 /// these are the template args for a multiclass.
1532 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1534 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1535 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1536 Lex.Lex(); // eat the '<'
1538 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1540 // Read the first declaration.
1541 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1545 TheRecToAddTo->addTemplateArg(TemplArg);
1547 while (Lex.getCode() == tgtok::comma) {
1548 Lex.Lex(); // eat the ','
1550 // Read the following declarations.
1551 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1554 TheRecToAddTo->addTemplateArg(TemplArg);
1557 if (Lex.getCode() != tgtok::greater)
1558 return TokError("expected '>' at end of template argument list");
1559 Lex.Lex(); // eat the '>'.
1564 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1566 /// BodyItem ::= Declaration ';'
1567 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1568 bool TGParser::ParseBodyItem(Record *CurRec) {
1569 if (Lex.getCode() != tgtok::Let) {
1570 if (ParseDeclaration(CurRec, false) == 0)
1573 if (Lex.getCode() != tgtok::semi)
1574 return TokError("expected ';' after declaration");
1579 // LET ID OptionalRangeList '=' Value ';'
1580 if (Lex.Lex() != tgtok::Id)
1581 return TokError("expected field identifier after let");
1583 SMLoc IdLoc = Lex.getLoc();
1584 std::string FieldName = Lex.getCurStrVal();
1585 Lex.Lex(); // eat the field name.
1587 std::vector<unsigned> BitList;
1588 if (ParseOptionalBitList(BitList))
1590 std::reverse(BitList.begin(), BitList.end());
1592 if (Lex.getCode() != tgtok::equal)
1593 return TokError("expected '=' in let expression");
1594 Lex.Lex(); // eat the '='.
1596 RecordVal *Field = CurRec->getValue(FieldName);
1598 return TokError("Value '" + FieldName + "' unknown!");
1600 RecTy *Type = Field->getType();
1602 Init *Val = ParseValue(CurRec, Type);
1603 if (Val == 0) return true;
1605 if (Lex.getCode() != tgtok::semi)
1606 return TokError("expected ';' after let expression");
1609 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1612 /// ParseBody - Read the body of a class or def. Return true on error, false on
1616 /// Body ::= '{' BodyList '}'
1617 /// BodyList BodyItem*
1619 bool TGParser::ParseBody(Record *CurRec) {
1620 // If this is a null definition, just eat the semi and return.
1621 if (Lex.getCode() == tgtok::semi) {
1626 if (Lex.getCode() != tgtok::l_brace)
1627 return TokError("Expected ';' or '{' to start body");
1631 while (Lex.getCode() != tgtok::r_brace)
1632 if (ParseBodyItem(CurRec))
1640 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1641 /// optional ClassList followed by a Body. CurRec is the current def or class
1642 /// that is being parsed.
1644 /// ObjectBody ::= BaseClassList Body
1645 /// BaseClassList ::= /*empty*/
1646 /// BaseClassList ::= ':' BaseClassListNE
1647 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1649 bool TGParser::ParseObjectBody(Record *CurRec) {
1650 // If there is a baseclass list, read it.
1651 if (Lex.getCode() == tgtok::colon) {
1654 // Read all of the subclasses.
1655 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1658 if (SubClass.Rec == 0) return true;
1661 if (AddSubClass(CurRec, SubClass))
1664 if (Lex.getCode() != tgtok::comma) break;
1665 Lex.Lex(); // eat ','.
1666 SubClass = ParseSubClassReference(CurRec, false);
1670 // Process any variables on the let stack.
1671 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1672 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1673 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1674 LetStack[i][j].Bits, LetStack[i][j].Value))
1677 return ParseBody(CurRec);
1680 /// ParseDef - Parse and return a top level or multiclass def, return the record
1681 /// corresponding to it. This returns null on error.
1683 /// DefInst ::= DEF ObjectName ObjectBody
1685 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1686 SMLoc DefLoc = Lex.getLoc();
1687 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1688 Lex.Lex(); // Eat the 'def' token.
1690 // Parse ObjectName and make a record for it.
1691 Record *CurRec = new Record(ParseObjectName(), DefLoc, Records);
1693 if (!CurMultiClass) {
1694 // Top-level def definition.
1696 // Ensure redefinition doesn't happen.
1697 if (Records.getDef(CurRec->getName())) {
1698 Error(DefLoc, "def '" + CurRec->getNameInitAsString()
1699 + "' already defined");
1702 Records.addDef(CurRec);
1704 // Otherwise, a def inside a multiclass, add it to the multiclass.
1705 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1706 if (CurMultiClass->DefPrototypes[i]->getNameInit()
1707 == CurRec->getNameInit()) {
1708 Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
1709 "' already defined in this multiclass!");
1712 CurMultiClass->DefPrototypes.push_back(CurRec);
1715 if (ParseObjectBody(CurRec))
1718 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1719 // See Record::setName(). This resolve step will see any new name
1720 // for the def that might have been created when resolving
1721 // inheritance, values and arguments above.
1722 CurRec->resolveReferences();
1724 // If ObjectBody has template arguments, it's an error.
1725 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1727 if (CurMultiClass) {
1728 // Copy the template arguments for the multiclass into the def.
1729 const std::vector<Init *> &TArgs =
1730 CurMultiClass->Rec.getTemplateArgs();
1732 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1733 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1734 assert(RV && "Template arg doesn't exist?");
1735 CurRec->addValue(*RV);
1742 /// ParseClass - Parse a tblgen class definition.
1744 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1746 bool TGParser::ParseClass() {
1747 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1750 if (Lex.getCode() != tgtok::Id)
1751 return TokError("expected class name after 'class' keyword");
1753 Record *CurRec = Records.getClass(Lex.getCurStrVal());
1755 // If the body was previously defined, this is an error.
1756 if (CurRec->getValues().size() > 1 || // Account for NAME.
1757 !CurRec->getSuperClasses().empty() ||
1758 !CurRec->getTemplateArgs().empty())
1759 return TokError("Class '" + CurRec->getNameInitAsString()
1760 + "' already defined");
1762 // If this is the first reference to this class, create and add it.
1763 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
1764 Records.addClass(CurRec);
1766 Lex.Lex(); // eat the name.
1768 // If there are template args, parse them.
1769 if (Lex.getCode() == tgtok::less)
1770 if (ParseTemplateArgList(CurRec))
1773 // Finally, parse the object body.
1774 return ParseObjectBody(CurRec);
1777 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1780 /// LetList ::= LetItem (',' LetItem)*
1781 /// LetItem ::= ID OptionalRangeList '=' Value
1783 std::vector<LetRecord> TGParser::ParseLetList() {
1784 std::vector<LetRecord> Result;
1787 if (Lex.getCode() != tgtok::Id) {
1788 TokError("expected identifier in let definition");
1789 return std::vector<LetRecord>();
1791 std::string Name = Lex.getCurStrVal();
1792 SMLoc NameLoc = Lex.getLoc();
1793 Lex.Lex(); // Eat the identifier.
1795 // Check for an optional RangeList.
1796 std::vector<unsigned> Bits;
1797 if (ParseOptionalRangeList(Bits))
1798 return std::vector<LetRecord>();
1799 std::reverse(Bits.begin(), Bits.end());
1801 if (Lex.getCode() != tgtok::equal) {
1802 TokError("expected '=' in let expression");
1803 return std::vector<LetRecord>();
1805 Lex.Lex(); // eat the '='.
1807 Init *Val = ParseValue(0);
1808 if (Val == 0) return std::vector<LetRecord>();
1810 // Now that we have everything, add the record.
1811 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1813 if (Lex.getCode() != tgtok::comma)
1815 Lex.Lex(); // eat the comma.
1819 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
1820 /// different related productions. This works inside multiclasses too.
1822 /// Object ::= LET LetList IN '{' ObjectList '}'
1823 /// Object ::= LET LetList IN Object
1825 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
1826 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1829 // Add this entry to the let stack.
1830 std::vector<LetRecord> LetInfo = ParseLetList();
1831 if (LetInfo.empty()) return true;
1832 LetStack.push_back(LetInfo);
1834 if (Lex.getCode() != tgtok::In)
1835 return TokError("expected 'in' at end of top-level 'let'");
1838 // If this is a scalar let, just handle it now
1839 if (Lex.getCode() != tgtok::l_brace) {
1840 // LET LetList IN Object
1841 if (ParseObject(CurMultiClass))
1843 } else { // Object ::= LETCommand '{' ObjectList '}'
1844 SMLoc BraceLoc = Lex.getLoc();
1845 // Otherwise, this is a group let.
1846 Lex.Lex(); // eat the '{'.
1848 // Parse the object list.
1849 if (ParseObjectList(CurMultiClass))
1852 if (Lex.getCode() != tgtok::r_brace) {
1853 TokError("expected '}' at end of top level let command");
1854 return Error(BraceLoc, "to match this '{'");
1859 // Outside this let scope, this let block is not active.
1860 LetStack.pop_back();
1864 /// ParseMultiClass - Parse a multiclass definition.
1866 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
1867 /// ':' BaseMultiClassList '{' MultiClassDef+ '}'
1869 bool TGParser::ParseMultiClass() {
1870 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1871 Lex.Lex(); // Eat the multiclass token.
1873 if (Lex.getCode() != tgtok::Id)
1874 return TokError("expected identifier after multiclass for name");
1875 std::string Name = Lex.getCurStrVal();
1877 if (MultiClasses.count(Name))
1878 return TokError("multiclass '" + Name + "' already defined");
1880 CurMultiClass = MultiClasses[Name] = new MultiClass(Name,
1881 Lex.getLoc(), Records);
1882 Lex.Lex(); // Eat the identifier.
1884 // If there are template args, parse them.
1885 if (Lex.getCode() == tgtok::less)
1886 if (ParseTemplateArgList(0))
1889 bool inherits = false;
1891 // If there are submulticlasses, parse them.
1892 if (Lex.getCode() == tgtok::colon) {
1897 // Read all of the submulticlasses.
1898 SubMultiClassReference SubMultiClass =
1899 ParseSubMultiClassReference(CurMultiClass);
1902 if (SubMultiClass.MC == 0) return true;
1905 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
1908 if (Lex.getCode() != tgtok::comma) break;
1909 Lex.Lex(); // eat ','.
1910 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
1914 if (Lex.getCode() != tgtok::l_brace) {
1916 return TokError("expected '{' in multiclass definition");
1917 else if (Lex.getCode() != tgtok::semi)
1918 return TokError("expected ';' in multiclass definition");
1920 Lex.Lex(); // eat the ';'.
1922 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
1923 return TokError("multiclass must contain at least one def");
1925 while (Lex.getCode() != tgtok::r_brace) {
1926 switch (Lex.getCode()) {
1928 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
1932 if (ParseObject(CurMultiClass))
1937 Lex.Lex(); // eat the '}'.
1945 InstantiateMulticlassDef(MultiClass &MC,
1947 const std::string &DefmPrefix,
1948 SMLoc DefmPrefixLoc) {
1949 // Add in the defm name. If the defm prefix is empty, give each
1950 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
1951 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
1953 std::string DefName = DefProto->getName();
1954 if (DefmPrefix.empty()) {
1955 DefName = GetNewAnonymousName();
1957 std::string::size_type idx = DefName.find("#NAME#");
1958 if (idx != std::string::npos) {
1959 DefName.replace(idx, 6, DefmPrefix);
1961 // Add the suffix to the defm name to get the new name.
1962 DefName = DefmPrefix + DefName;
1966 Record *CurRec = new Record(DefName, DefmPrefixLoc, Records);
1968 SubClassReference Ref;
1969 Ref.RefLoc = DefmPrefixLoc;
1971 AddSubClass(CurRec, Ref);
1976 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
1978 SMLoc DefmPrefixLoc,
1980 const std::vector<Init *> &TArgs,
1981 std::vector<Init *> &TemplateVals,
1983 // Loop over all of the template arguments, setting them to the specified
1984 // value or leaving them as the default if necessary.
1985 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1986 // Check if a value is specified for this temp-arg.
1987 if (i < TemplateVals.size()) {
1989 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
1994 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
1998 CurRec->removeValue(TArgs[i]);
2000 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2001 return Error(SubClassLoc, "value not specified for template argument #"+
2002 utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2003 + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2010 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2013 SMLoc DefmPrefixLoc) {
2014 // If the mdef is inside a 'let' expression, add to each def.
2015 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2016 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2017 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2018 LetStack[i][j].Bits, LetStack[i][j].Value))
2019 return Error(DefmPrefixLoc, "when instantiating this defm");
2021 // Ensure redefinition doesn't happen.
2022 if (Records.getDef(CurRec->getName()))
2023 return Error(DefmPrefixLoc, "def '" + CurRec->getName() +
2024 "' already defined, instantiating defm with subdef '" +
2025 DefProto->getName() + "'");
2027 // Don't create a top level definition for defm inside multiclasses,
2028 // instead, only update the prototypes and bind the template args
2029 // with the new created definition.
2030 if (CurMultiClass) {
2031 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2033 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2034 == CurRec->getNameInit())
2035 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2036 "' already defined in this multiclass!");
2037 CurMultiClass->DefPrototypes.push_back(CurRec);
2039 // Copy the template arguments for the multiclass into the new def.
2040 const std::vector<Init *> &TA =
2041 CurMultiClass->Rec.getTemplateArgs();
2043 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2044 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2045 assert(RV && "Template arg doesn't exist?");
2046 CurRec->addValue(*RV);
2049 Records.addDef(CurRec);
2055 /// ParseDefm - Parse the instantiation of a multiclass.
2057 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2059 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2060 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2062 std::string DefmPrefix;
2063 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2064 DefmPrefix = Lex.getCurStrVal();
2065 Lex.Lex(); // Eat the defm prefix.
2068 SMLoc DefmPrefixLoc = Lex.getLoc();
2069 if (Lex.getCode() != tgtok::colon)
2070 return TokError("expected ':' after defm identifier");
2072 // Keep track of the new generated record definitions.
2073 std::vector<Record*> NewRecDefs;
2075 // This record also inherits from a regular class (non-multiclass)?
2076 bool InheritFromClass = false;
2081 SMLoc SubClassLoc = Lex.getLoc();
2082 SubClassReference Ref = ParseSubClassReference(0, true);
2085 if (Ref.Rec == 0) return true;
2087 // To instantiate a multiclass, we need to first get the multiclass, then
2088 // instantiate each def contained in the multiclass with the SubClassRef
2089 // template parameters.
2090 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2091 assert(MC && "Didn't lookup multiclass correctly?");
2092 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2094 // Verify that the correct number of template arguments were specified.
2095 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2096 if (TArgs.size() < TemplateVals.size())
2097 return Error(SubClassLoc,
2098 "more template args specified than multiclass expects");
2100 // Loop over all the def's in the multiclass, instantiating each one.
2101 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2102 Record *DefProto = MC->DefPrototypes[i];
2104 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix, DefmPrefixLoc);
2106 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmPrefixLoc, SubClassLoc,
2107 TArgs, TemplateVals, true/*Delete args*/))
2108 return Error(SubClassLoc, "could not instantiate def");
2110 if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmPrefixLoc))
2111 return Error(SubClassLoc, "could not instantiate def");
2113 NewRecDefs.push_back(CurRec);
2117 if (Lex.getCode() != tgtok::comma) break;
2118 Lex.Lex(); // eat ','.
2120 SubClassLoc = Lex.getLoc();
2122 // A defm can inherit from regular classes (non-multiclass) as
2123 // long as they come in the end of the inheritance list.
2124 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != 0);
2126 if (InheritFromClass)
2129 Ref = ParseSubClassReference(0, true);
2132 if (InheritFromClass) {
2133 // Process all the classes to inherit as if they were part of a
2134 // regular 'def' and inherit all record values.
2135 SubClassReference SubClass = ParseSubClassReference(0, false);
2138 if (SubClass.Rec == 0) return true;
2140 // Get the expanded definition prototypes and teach them about
2141 // the record values the current class to inherit has
2142 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2143 Record *CurRec = NewRecDefs[i];
2146 if (AddSubClass(CurRec, SubClass))
2149 // Process any variables on the let stack.
2150 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2151 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2152 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2153 LetStack[i][j].Bits, LetStack[i][j].Value))
2157 if (Lex.getCode() != tgtok::comma) break;
2158 Lex.Lex(); // eat ','.
2159 SubClass = ParseSubClassReference(0, false);
2164 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2165 // See Record::setName(). This resolve step will see any new
2166 // name for the def that might have been created when resolving
2167 // inheritance, values and arguments above.
2168 NewRecDefs[i]->resolveReferences();
2170 if (Lex.getCode() != tgtok::semi)
2171 return TokError("expected ';' at end of defm");
2178 /// Object ::= ClassInst
2179 /// Object ::= DefInst
2180 /// Object ::= MultiClassInst
2181 /// Object ::= DefMInst
2182 /// Object ::= LETCommand '{' ObjectList '}'
2183 /// Object ::= LETCommand Object
2184 bool TGParser::ParseObject(MultiClass *MC) {
2185 switch (Lex.getCode()) {
2187 return TokError("Expected class, def, defm, multiclass or let definition");
2188 case tgtok::Let: return ParseTopLevelLet(MC);
2189 case tgtok::Def: return ParseDef(MC);
2190 case tgtok::Defm: return ParseDefm(MC);
2191 case tgtok::Class: return ParseClass();
2192 case tgtok::MultiClass: return ParseMultiClass();
2197 /// ObjectList :== Object*
2198 bool TGParser::ParseObjectList(MultiClass *MC) {
2199 while (isObjectStart(Lex.getCode())) {
2200 if (ParseObject(MC))
2206 bool TGParser::ParseFile() {
2207 Lex.Lex(); // Prime the lexer.
2208 if (ParseObjectList()) return true;
2210 // If we have unread input at the end of the file, report it.
2211 if (Lex.getCode() == tgtok::Eof)
2214 return TokError("Unexpected input at top level");