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 //===----------------------------------------------------------------------===//
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Support/Streams.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 cerr << "Multiclass:\n";
52 cerr << "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, TGLoc 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, TGLoc Loc, const std::string &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 + "' unknown!");
92 // Do not allow assignments like 'X = X'. This will just cause infinite loops
93 // in the resolution machinery.
95 if (VarInit *VI = dynamic_cast<VarInit*>(V))
96 if (VI->getName() == ValName)
99 // If we are assigning to a subset of the bits in the value... then we must be
100 // assigning to a field of BitsRecTy, which must have a BitsInit
103 if (!BitList.empty()) {
104 BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
106 return Error(Loc, "Value '" + ValName + "' is not a bits type");
108 // Convert the incoming value to a bits type of the appropriate size...
109 Init *BI = V->convertInitializerTo(new BitsRecTy(BitList.size()));
111 V->convertInitializerTo(new BitsRecTy(BitList.size()));
112 return Error(Loc, "Initializer is not compatible with bit range");
115 // We should have a BitsInit type now.
116 BitsInit *BInit = dynamic_cast<BitsInit*>(BI);
119 BitsInit *NewVal = new BitsInit(CurVal->getNumBits());
121 // Loop over bits, assigning values as appropriate.
122 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
123 unsigned Bit = BitList[i];
124 if (NewVal->getBit(Bit))
125 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
126 ValName + "' more than once");
127 NewVal->setBit(Bit, BInit->getBit(i));
130 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
131 if (NewVal->getBit(i) == 0)
132 NewVal->setBit(i, CurVal->getBit(i));
138 return Error(Loc, "Value '" + ValName + "' of type '" +
139 RV->getType()->getAsString() +
140 "' is incompatible with initializer '" + V->getAsString() +"'");
144 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
145 /// args as SubClass's template arguments.
146 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
147 Record *SC = SubClass.Rec;
148 // Add all of the values in the subclass into the current class.
149 const std::vector<RecordVal> &Vals = SC->getValues();
150 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
151 if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
154 const std::vector<std::string> &TArgs = SC->getTemplateArgs();
156 // Ensure that an appropriate number of template arguments are specified.
157 if (TArgs.size() < SubClass.TemplateArgs.size())
158 return Error(SubClass.RefLoc, "More template args specified than expected");
160 // Loop over all of the template arguments, setting them to the specified
161 // value or leaving them as the default if necessary.
162 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
163 if (i < SubClass.TemplateArgs.size()) {
164 // If a value is specified for this template arg, set it now.
165 if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(),
166 SubClass.TemplateArgs[i]))
170 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
173 CurRec->removeValue(TArgs[i]);
175 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
176 return Error(SubClass.RefLoc,"Value not specified for template argument #"
177 + utostr(i) + " (" + TArgs[i] + ") of subclass '" +
178 SC->getName() + "'!");
182 // Since everything went well, we can now set the "superclass" list for the
184 const std::vector<Record*> &SCs = SC->getSuperClasses();
185 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
186 if (CurRec->isSubClassOf(SCs[i]))
187 return Error(SubClass.RefLoc,
188 "Already subclass of '" + SCs[i]->getName() + "'!\n");
189 CurRec->addSuperClass(SCs[i]);
192 if (CurRec->isSubClassOf(SC))
193 return Error(SubClass.RefLoc,
194 "Already subclass of '" + SC->getName() + "'!\n");
195 CurRec->addSuperClass(SC);
199 /// AddSubMultiClass - Add SubMultiClass as a subclass to
200 /// CurMC, resolving its template args as SubMultiClass's
201 /// template arguments.
202 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
203 SubMultiClassReference &SubMultiClass) {
204 MultiClass *SMC = SubMultiClass.MC;
205 Record *CurRec = &CurMC->Rec;
207 const std::vector<RecordVal> &MCVals = CurRec->getValues();
209 // Add all of the values in the subclass into the current class.
210 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
211 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
212 if (AddValue(CurRec, SubMultiClass.RefLoc, SMCVals[i]))
215 int newDefStart = CurMC->DefPrototypes.size();
217 // Add all of the defs in the subclass into the current multiclass.
218 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
219 iend = SMC->DefPrototypes.end();
222 // Clone the def and add it to the current multiclass
223 Record *NewDef = new Record(**i);
225 // Add all of the values in the superclass into the current def.
226 for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
227 if (AddValue(NewDef, SubMultiClass.RefLoc, MCVals[i]))
230 CurMC->DefPrototypes.push_back(NewDef);
233 const std::vector<std::string> &SMCTArgs = SMC->Rec.getTemplateArgs();
235 // Ensure that an appropriate number of template arguments are
237 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
238 return Error(SubMultiClass.RefLoc,
239 "More template args specified than expected");
241 // Loop over all of the template arguments, setting them to the specified
242 // value or leaving them as the default if necessary.
243 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
244 if (i < SubMultiClass.TemplateArgs.size()) {
245 // If a value is specified for this template arg, set it in the
247 if (SetValue(CurRec, SubMultiClass.RefLoc, SMCTArgs[i],
248 std::vector<unsigned>(),
249 SubMultiClass.TemplateArgs[i]))
253 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
256 CurRec->removeValue(SMCTArgs[i]);
258 // If a value is specified for this template arg, set it in the
260 for (MultiClass::RecordVector::iterator j =
261 CurMC->DefPrototypes.begin() + newDefStart,
262 jend = CurMC->DefPrototypes.end();
267 if (SetValue(Def, SubMultiClass.RefLoc, SMCTArgs[i],
268 std::vector<unsigned>(),
269 SubMultiClass.TemplateArgs[i]))
273 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
276 Def->removeValue(SMCTArgs[i]);
278 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
279 return Error(SubMultiClass.RefLoc,
280 "Value not specified for template argument #"
281 + utostr(i) + " (" + SMCTArgs[i] + ") of subclass '" +
282 SMC->Rec.getName() + "'!");
289 //===----------------------------------------------------------------------===//
291 //===----------------------------------------------------------------------===//
293 /// isObjectStart - Return true if this is a valid first token for an Object.
294 static bool isObjectStart(tgtok::TokKind K) {
295 return K == tgtok::Class || K == tgtok::Def ||
296 K == tgtok::Defm || K == tgtok::Let || K == tgtok::MultiClass;
299 /// ParseObjectName - If an object name is specified, return it. Otherwise,
300 /// return an anonymous name.
301 /// ObjectName ::= ID
302 /// ObjectName ::= /*empty*/
304 std::string TGParser::ParseObjectName() {
305 if (Lex.getCode() == tgtok::Id) {
306 std::string Ret = Lex.getCurStrVal();
311 static unsigned AnonCounter = 0;
312 return "anonymous."+utostr(AnonCounter++);
316 /// ParseClassID - Parse and resolve a reference to a class name. This returns
321 Record *TGParser::ParseClassID() {
322 if (Lex.getCode() != tgtok::Id) {
323 TokError("expected name for ClassID");
327 Record *Result = Records.getClass(Lex.getCurStrVal());
329 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
335 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
336 /// This returns null on error.
338 /// MultiClassID ::= ID
340 MultiClass *TGParser::ParseMultiClassID() {
341 if (Lex.getCode() != tgtok::Id) {
342 TokError("expected name for ClassID");
346 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
348 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
354 Record *TGParser::ParseDefmID() {
355 if (Lex.getCode() != tgtok::Id) {
356 TokError("expected multiclass name");
360 MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
362 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
372 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
373 /// subclass. This returns a SubClassRefTy with a null Record* on error.
375 /// SubClassRef ::= ClassID
376 /// SubClassRef ::= ClassID '<' ValueList '>'
378 SubClassReference TGParser::
379 ParseSubClassReference(Record *CurRec, bool isDefm) {
380 SubClassReference Result;
381 Result.RefLoc = Lex.getLoc();
384 Result.Rec = ParseDefmID();
386 Result.Rec = ParseClassID();
387 if (Result.Rec == 0) return Result;
389 // If there is no template arg list, we're done.
390 if (Lex.getCode() != tgtok::less)
392 Lex.Lex(); // Eat the '<'
394 if (Lex.getCode() == tgtok::greater) {
395 TokError("subclass reference requires a non-empty list of template values");
400 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
401 if (Result.TemplateArgs.empty()) {
402 Result.Rec = 0; // Error parsing value list.
406 if (Lex.getCode() != tgtok::greater) {
407 TokError("expected '>' in template value list");
416 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
417 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
418 /// Record* on error.
420 /// SubMultiClassRef ::= MultiClassID
421 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
423 SubMultiClassReference TGParser::
424 ParseSubMultiClassReference(MultiClass *CurMC) {
425 SubMultiClassReference Result;
426 Result.RefLoc = Lex.getLoc();
428 Result.MC = ParseMultiClassID();
429 if (Result.MC == 0) return Result;
431 // If there is no template arg list, we're done.
432 if (Lex.getCode() != tgtok::less)
434 Lex.Lex(); // Eat the '<'
436 if (Lex.getCode() == tgtok::greater) {
437 TokError("subclass reference requires a non-empty list of template values");
442 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
443 if (Result.TemplateArgs.empty()) {
444 Result.MC = 0; // Error parsing value list.
448 if (Lex.getCode() != tgtok::greater) {
449 TokError("expected '>' in template value list");
458 /// ParseRangePiece - Parse a bit/value range.
459 /// RangePiece ::= INTVAL
460 /// RangePiece ::= INTVAL '-' INTVAL
461 /// RangePiece ::= INTVAL INTVAL
462 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
463 if (Lex.getCode() != tgtok::IntVal) {
464 TokError("expected integer or bitrange");
467 int64_t Start = Lex.getCurIntVal();
471 return TokError("invalid range, cannot be negative");
473 switch (Lex.Lex()) { // eat first character.
475 Ranges.push_back(Start);
478 if (Lex.Lex() != tgtok::IntVal) {
479 TokError("expected integer value as end of range");
482 End = Lex.getCurIntVal();
485 End = -Lex.getCurIntVal();
489 return TokError("invalid range, cannot be negative");
494 for (; Start <= End; ++Start)
495 Ranges.push_back(Start);
497 for (; Start >= End; --Start)
498 Ranges.push_back(Start);
503 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
505 /// RangeList ::= RangePiece (',' RangePiece)*
507 std::vector<unsigned> TGParser::ParseRangeList() {
508 std::vector<unsigned> Result;
510 // Parse the first piece.
511 if (ParseRangePiece(Result))
512 return std::vector<unsigned>();
513 while (Lex.getCode() == tgtok::comma) {
514 Lex.Lex(); // Eat the comma.
516 // Parse the next range piece.
517 if (ParseRangePiece(Result))
518 return std::vector<unsigned>();
523 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
524 /// OptionalRangeList ::= '<' RangeList '>'
525 /// OptionalRangeList ::= /*empty*/
526 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
527 if (Lex.getCode() != tgtok::less)
530 TGLoc StartLoc = Lex.getLoc();
531 Lex.Lex(); // eat the '<'
533 // Parse the range list.
534 Ranges = ParseRangeList();
535 if (Ranges.empty()) return true;
537 if (Lex.getCode() != tgtok::greater) {
538 TokError("expected '>' at end of range list");
539 return Error(StartLoc, "to match this '<'");
541 Lex.Lex(); // eat the '>'.
545 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
546 /// OptionalBitList ::= '{' RangeList '}'
547 /// OptionalBitList ::= /*empty*/
548 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
549 if (Lex.getCode() != tgtok::l_brace)
552 TGLoc StartLoc = Lex.getLoc();
553 Lex.Lex(); // eat the '{'
555 // Parse the range list.
556 Ranges = ParseRangeList();
557 if (Ranges.empty()) return true;
559 if (Lex.getCode() != tgtok::r_brace) {
560 TokError("expected '}' at end of bit list");
561 return Error(StartLoc, "to match this '{'");
563 Lex.Lex(); // eat the '}'.
568 /// ParseType - Parse and return a tblgen type. This returns null on error.
570 /// Type ::= STRING // string type
571 /// Type ::= BIT // bit type
572 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
573 /// Type ::= INT // int type
574 /// Type ::= LIST '<' Type '>' // list<x> type
575 /// Type ::= CODE // code type
576 /// Type ::= DAG // dag type
577 /// Type ::= ClassID // Record Type
579 RecTy *TGParser::ParseType() {
580 switch (Lex.getCode()) {
581 default: TokError("Unknown token when expecting a type"); return 0;
582 case tgtok::String: Lex.Lex(); return new StringRecTy();
583 case tgtok::Bit: Lex.Lex(); return new BitRecTy();
584 case tgtok::Int: Lex.Lex(); return new IntRecTy();
585 case tgtok::Code: Lex.Lex(); return new CodeRecTy();
586 case tgtok::Dag: Lex.Lex(); return new DagRecTy();
588 if (Record *R = ParseClassID()) return new RecordRecTy(R);
591 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
592 TokError("expected '<' after bits type");
595 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
596 TokError("expected integer in bits<n> type");
599 uint64_t Val = Lex.getCurIntVal();
600 if (Lex.Lex() != tgtok::greater) { // Eat count.
601 TokError("expected '>' at end of bits<n> type");
604 Lex.Lex(); // Eat '>'
605 return new BitsRecTy(Val);
608 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
609 TokError("expected '<' after list type");
612 Lex.Lex(); // Eat '<'
613 RecTy *SubType = ParseType();
614 if (SubType == 0) return 0;
616 if (Lex.getCode() != tgtok::greater) {
617 TokError("expected '>' at end of list<ty> type");
620 Lex.Lex(); // Eat '>'
621 return new ListRecTy(SubType);
626 /// ParseIDValue - Parse an ID as a value and decode what it means.
628 /// IDValue ::= ID [def local value]
629 /// IDValue ::= ID [def template arg]
630 /// IDValue ::= ID [multiclass local value]
631 /// IDValue ::= ID [multiclass template argument]
632 /// IDValue ::= ID [def name]
634 Init *TGParser::ParseIDValue(Record *CurRec) {
635 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
636 std::string Name = Lex.getCurStrVal();
637 TGLoc Loc = Lex.getLoc();
639 return ParseIDValue(CurRec, Name, Loc);
642 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
643 /// has already been read.
644 Init *TGParser::ParseIDValue(Record *CurRec,
645 const std::string &Name, TGLoc NameLoc) {
647 if (const RecordVal *RV = CurRec->getValue(Name))
648 return new VarInit(Name, RV->getType());
650 std::string TemplateArgName = CurRec->getName()+":"+Name;
651 if (CurRec->isTemplateArg(TemplateArgName)) {
652 const RecordVal *RV = CurRec->getValue(TemplateArgName);
653 assert(RV && "Template arg doesn't exist??");
654 return new VarInit(TemplateArgName, RV->getType());
659 std::string MCName = CurMultiClass->Rec.getName()+"::"+Name;
660 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
661 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
662 assert(RV && "Template arg doesn't exist??");
663 return new VarInit(MCName, RV->getType());
667 if (Record *D = Records.getDef(Name))
668 return new DefInit(D);
670 Error(NameLoc, "Variable not defined: '" + Name + "'");
674 /// ParseOperation - Parse an operator. This returns null on error.
676 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
678 Init *TGParser::ParseOperation(Record *CurRec) {
679 switch (Lex.getCode()) {
681 TokError("unknown operation");
687 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
688 UnOpInit::UnaryOp Code;
691 switch (Lex.getCode()) {
692 default: assert(0 && "Unhandled code!");
694 Lex.Lex(); // eat the operation
695 Code = UnOpInit::CAST;
697 Type = ParseOperatorType();
700 TokError("did not get type for unary operator");
706 Lex.Lex(); // eat the operation
707 Code = UnOpInit::CAR;
710 Lex.Lex(); // eat the operation
711 Code = UnOpInit::CDR;
714 Lex.Lex(); // eat the operation
715 Code = UnOpInit::LNULL;
719 if (Lex.getCode() != tgtok::l_paren) {
720 TokError("expected '(' after unary operator");
723 Lex.Lex(); // eat the '('
725 Init *LHS = ParseValue(CurRec);
726 if (LHS == 0) return 0;
728 if (Code == UnOpInit::CAR
729 || Code == UnOpInit::CDR
730 || Code == UnOpInit::LNULL) {
731 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
732 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
733 TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
734 if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
735 TokError("expected list or string type argument in unary operator");
739 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
740 StringRecTy *SType = dynamic_cast<StringRecTy*>(LHSt->getType());
741 if (LType == 0 && SType == 0) {
742 TokError("expected list or string type argumnet in unary operator");
747 if (Code == UnOpInit::CAR
748 || Code == UnOpInit::CDR) {
749 if (LHSl == 0 && LHSt == 0) {
750 TokError("expected list type argumnet in unary operator");
754 if (LHSl && LHSl->getSize() == 0) {
755 TokError("empty list argument in unary operator");
759 Init *Item = LHSl->getElement(0);
760 TypedInit *Itemt = dynamic_cast<TypedInit*>(Item);
762 TokError("untyped list element in unary operator");
765 if (Code == UnOpInit::CAR) {
766 Type = Itemt->getType();
769 Type = new ListRecTy(Itemt->getType());
773 assert(LHSt && "expected list type argument in unary operator");
774 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
776 TokError("expected list type argumnet in unary operator");
779 if (Code == UnOpInit::CAR) {
780 Type = LType->getElementType();
789 if (Lex.getCode() != tgtok::r_paren) {
790 TokError("expected ')' in unary operator");
793 Lex.Lex(); // eat the ')'
794 return (new UnOpInit(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
801 case tgtok::XStrConcat:
802 case tgtok::XRegMatch:
803 case tgtok::XNameConcat: { // Value ::= !binop '(' Value ',' Value ')'
804 BinOpInit::BinaryOp Code;
808 switch (Lex.getCode()) {
809 default: assert(0 && "Unhandled code!");
811 Lex.Lex(); // eat the operation
812 Code = BinOpInit::CONCAT;
813 Type = new DagRecTy();
816 Lex.Lex(); // eat the operation
817 Code = BinOpInit::SRA;
818 Type = new IntRecTy();
821 Lex.Lex(); // eat the operation
822 Code = BinOpInit::SRL;
823 Type = new IntRecTy();
826 Lex.Lex(); // eat the operation
827 Code = BinOpInit::SHL;
828 Type = new IntRecTy();
830 case tgtok::XStrConcat:
831 Lex.Lex(); // eat the operation
832 Code = BinOpInit::STRCONCAT;
833 Type = new StringRecTy();
835 case tgtok::XRegMatch:
836 Lex.Lex(); // eat the operation
837 Code = BinOpInit::REGMATCH;
838 Type = new IntRecTy();
840 case tgtok::XNameConcat:
841 Lex.Lex(); // eat the operation
842 Code = BinOpInit::NAMECONCAT;
844 Type = ParseOperatorType();
847 TokError("did not get type for binary operator");
853 if (Lex.getCode() != tgtok::l_paren) {
854 TokError("expected '(' after binary operator");
857 Lex.Lex(); // eat the '('
859 Init *LHS = ParseValue(CurRec);
860 if (LHS == 0) return 0;
862 if (Lex.getCode() != tgtok::comma) {
863 TokError("expected ',' in binary operator");
866 Lex.Lex(); // eat the ','
868 Init *RHS = ParseValue(CurRec);
869 if (RHS == 0) return 0;
871 if (Lex.getCode() != tgtok::r_paren) {
872 TokError("expected ')' in binary operator");
875 Lex.Lex(); // eat the ')'
876 return (new BinOpInit(Code, LHS, RHS, Type))->Fold(CurRec, CurMultiClass);
880 case tgtok::XForEach:
881 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
882 TernOpInit::TernaryOp Code;
886 tgtok::TokKind LexCode = Lex.getCode();
887 Lex.Lex(); // eat the operation
889 default: assert(0 && "Unhandled code!");
891 Code = TernOpInit::IF;
893 case tgtok::XForEach:
894 Code = TernOpInit::FOREACH;
897 Code = TernOpInit::SUBST;
900 if (Lex.getCode() != tgtok::l_paren) {
901 TokError("expected '(' after ternary operator");
904 Lex.Lex(); // eat the '('
906 Init *LHS = ParseValue(CurRec);
907 if (LHS == 0) return 0;
909 if (Lex.getCode() != tgtok::comma) {
910 TokError("expected ',' in ternary operator");
913 Lex.Lex(); // eat the ','
915 Init *MHS = ParseValue(CurRec);
916 if (MHS == 0) return 0;
918 if (Lex.getCode() != tgtok::comma) {
919 TokError("expected ',' in ternary operator");
922 Lex.Lex(); // eat the ','
924 Init *RHS = ParseValue(CurRec);
925 if (RHS == 0) return 0;
927 if (Lex.getCode() != tgtok::r_paren) {
928 TokError("expected ')' in binary operator");
931 Lex.Lex(); // eat the ')'
934 default: assert(0 && "Unhandled code!");
936 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
937 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
938 if (MHSt == 0 || RHSt == 0) {
939 TokError("could not get type for !if");
942 if (MHSt->getType()->typeIsConvertibleTo(RHSt->getType())) {
943 Type = RHSt->getType();
945 else if (RHSt->getType()->typeIsConvertibleTo(MHSt->getType())) {
946 Type = MHSt->getType();
949 TokError("inconsistent types for !if");
954 case tgtok::XForEach: {
955 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
957 TokError("could not get type for !foreach");
960 Type = MHSt->getType();
963 case tgtok::XSubst: {
964 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
966 TokError("could not get type for !subst");
969 Type = RHSt->getType();
973 return (new TernOpInit(Code, LHS, MHS, RHS, Type))->Fold(CurRec, CurMultiClass);
976 TokError("could not parse operation");
980 /// ParseOperatorType - Parse a type for an operator. This returns
983 /// OperatorType ::= '<' Type '>'
985 RecTy *TGParser::ParseOperatorType(void) {
988 if (Lex.getCode() != tgtok::less) {
989 TokError("expected type name for operator");
992 Lex.Lex(); // eat the <
997 TokError("expected type name for operator");
1001 if (Lex.getCode() != tgtok::greater) {
1002 TokError("expected type name for operator");
1005 Lex.Lex(); // eat the >
1011 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1013 /// SimpleValue ::= IDValue
1014 /// SimpleValue ::= INTVAL
1015 /// SimpleValue ::= STRVAL+
1016 /// SimpleValue ::= CODEFRAGMENT
1017 /// SimpleValue ::= '?'
1018 /// SimpleValue ::= '{' ValueList '}'
1019 /// SimpleValue ::= ID '<' ValueListNE '>'
1020 /// SimpleValue ::= '[' ValueList ']'
1021 /// SimpleValue ::= '(' IDValue DagArgList ')'
1022 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1023 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1024 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1025 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1026 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1028 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType) {
1030 switch (Lex.getCode()) {
1031 default: TokError("Unknown token when parsing a value"); break;
1032 case tgtok::IntVal: R = new IntInit(Lex.getCurIntVal()); Lex.Lex(); break;
1033 case tgtok::StrVal: {
1034 std::string Val = Lex.getCurStrVal();
1037 // Handle multiple consecutive concatenated strings.
1038 while (Lex.getCode() == tgtok::StrVal) {
1039 Val += Lex.getCurStrVal();
1043 R = new StringInit(Val);
1046 case tgtok::CodeFragment:
1047 R = new CodeInit(Lex.getCurStrVal()); Lex.Lex(); break;
1048 case tgtok::question: R = new UnsetInit(); Lex.Lex(); break;
1050 TGLoc NameLoc = Lex.getLoc();
1051 std::string Name = Lex.getCurStrVal();
1052 if (Lex.Lex() != tgtok::less) // consume the Id.
1053 return ParseIDValue(CurRec, Name, NameLoc); // Value ::= IDValue
1055 // Value ::= ID '<' ValueListNE '>'
1056 if (Lex.Lex() == tgtok::greater) {
1057 TokError("expected non-empty value list");
1061 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1062 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1064 Record *Class = Records.getClass(Name);
1066 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1070 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1071 if (ValueList.empty()) return 0;
1073 if (Lex.getCode() != tgtok::greater) {
1074 TokError("expected '>' at end of value list");
1077 Lex.Lex(); // eat the '>'
1079 // Create the new record, set it as CurRec temporarily.
1080 static unsigned AnonCounter = 0;
1081 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),NameLoc);
1082 SubClassReference SCRef;
1083 SCRef.RefLoc = NameLoc;
1085 SCRef.TemplateArgs = ValueList;
1086 // Add info about the subclass to NewRec.
1087 if (AddSubClass(NewRec, SCRef))
1089 NewRec->resolveReferences();
1090 Records.addDef(NewRec);
1092 // The result of the expression is a reference to the new record.
1093 return new DefInit(NewRec);
1095 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1096 TGLoc BraceLoc = Lex.getLoc();
1097 Lex.Lex(); // eat the '{'
1098 std::vector<Init*> Vals;
1100 if (Lex.getCode() != tgtok::r_brace) {
1101 Vals = ParseValueList(CurRec);
1102 if (Vals.empty()) return 0;
1104 if (Lex.getCode() != tgtok::r_brace) {
1105 TokError("expected '}' at end of bit list value");
1108 Lex.Lex(); // eat the '}'
1110 BitsInit *Result = new BitsInit(Vals.size());
1111 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1112 Init *Bit = Vals[i]->convertInitializerTo(new BitRecTy());
1114 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1115 ") is not convertable to a bit");
1118 Result->setBit(Vals.size()-i-1, Bit);
1122 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1123 Lex.Lex(); // eat the '['
1124 std::vector<Init*> Vals;
1126 RecTy *DeducedEltTy = 0;
1127 ListRecTy *GivenListTy = 0;
1129 if (ItemType != 0) {
1130 ListRecTy *ListType = dynamic_cast<ListRecTy*>(ItemType);
1131 if (ListType == 0) {
1132 std::stringstream s;
1133 s << "Type mismatch for list, expected list type, got "
1134 << ItemType->getAsString();
1137 GivenListTy = ListType;
1140 if (Lex.getCode() != tgtok::r_square) {
1141 Vals = ParseValueList(CurRec, 0, GivenListTy ? GivenListTy->getElementType() : 0);
1142 if (Vals.empty()) return 0;
1144 if (Lex.getCode() != tgtok::r_square) {
1145 TokError("expected ']' at end of list value");
1148 Lex.Lex(); // eat the ']'
1150 RecTy *GivenEltTy = 0;
1151 if (Lex.getCode() == tgtok::less) {
1152 // Optional list element type
1153 Lex.Lex(); // eat the '<'
1155 GivenEltTy = ParseType();
1156 if (GivenEltTy == 0) {
1157 // Couldn't parse element type
1161 if (Lex.getCode() != tgtok::greater) {
1162 TokError("expected '>' at end of list element type");
1165 Lex.Lex(); // eat the '>'
1170 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1173 TypedInit *TArg = dynamic_cast<TypedInit*>(*i);
1175 TokError("Untyped list element");
1179 EltTy = resolveTypes(EltTy, TArg->getType());
1181 TokError("Incompatible types in list elements");
1186 EltTy = TArg->getType();
1190 if (GivenEltTy != 0) {
1192 // Verify consistency
1193 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1194 TokError("Incompatible types in list elements");
1202 if (ItemType == 0) {
1203 TokError("No type for list");
1206 DeducedEltTy = GivenListTy->getElementType();
1209 // Make sure the deduced type is compatible with the given type
1211 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1212 TokError("Element type mismatch for list");
1216 DeducedEltTy = EltTy;
1219 return new ListInit(Vals, DeducedEltTy);
1221 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1222 Lex.Lex(); // eat the '('
1223 if (Lex.getCode() != tgtok::Id
1224 && Lex.getCode() != tgtok::XCast
1225 && Lex.getCode() != tgtok::XNameConcat) {
1226 TokError("expected identifier in dag init");
1231 if (Lex.getCode() == tgtok::Id) {
1232 Operator = ParseIDValue(CurRec);
1233 if (Operator == 0) return 0;
1236 Operator = ParseOperation(CurRec);
1237 if (Operator == 0) return 0;
1240 // If the operator name is present, parse it.
1241 std::string OperatorName;
1242 if (Lex.getCode() == tgtok::colon) {
1243 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1244 TokError("expected variable name in dag operator");
1247 OperatorName = Lex.getCurStrVal();
1248 Lex.Lex(); // eat the VarName.
1251 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1252 if (Lex.getCode() != tgtok::r_paren) {
1253 DagArgs = ParseDagArgList(CurRec);
1254 if (DagArgs.empty()) return 0;
1257 if (Lex.getCode() != tgtok::r_paren) {
1258 TokError("expected ')' in dag init");
1261 Lex.Lex(); // eat the ')'
1263 return new DagInit(Operator, OperatorName, DagArgs);
1270 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1271 case tgtok::XConcat:
1275 case tgtok::XStrConcat:
1276 case tgtok::XRegMatch:
1277 case tgtok::XNameConcat: // Value ::= !binop '(' Value ',' Value ')'
1279 case tgtok::XForEach:
1280 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1281 return ParseOperation(CurRec);
1289 /// ParseValue - Parse a tblgen value. This returns null on error.
1291 /// Value ::= SimpleValue ValueSuffix*
1292 /// ValueSuffix ::= '{' BitList '}'
1293 /// ValueSuffix ::= '[' BitList ']'
1294 /// ValueSuffix ::= '.' ID
1296 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType) {
1297 Init *Result = ParseSimpleValue(CurRec, ItemType);
1298 if (Result == 0) return 0;
1300 // Parse the suffixes now if present.
1302 switch (Lex.getCode()) {
1303 default: return Result;
1304 case tgtok::l_brace: {
1305 TGLoc CurlyLoc = Lex.getLoc();
1306 Lex.Lex(); // eat the '{'
1307 std::vector<unsigned> Ranges = ParseRangeList();
1308 if (Ranges.empty()) return 0;
1310 // Reverse the bitlist.
1311 std::reverse(Ranges.begin(), Ranges.end());
1312 Result = Result->convertInitializerBitRange(Ranges);
1314 Error(CurlyLoc, "Invalid bit range for value");
1319 if (Lex.getCode() != tgtok::r_brace) {
1320 TokError("expected '}' at end of bit range list");
1326 case tgtok::l_square: {
1327 TGLoc SquareLoc = Lex.getLoc();
1328 Lex.Lex(); // eat the '['
1329 std::vector<unsigned> Ranges = ParseRangeList();
1330 if (Ranges.empty()) return 0;
1332 Result = Result->convertInitListSlice(Ranges);
1334 Error(SquareLoc, "Invalid range for list slice");
1339 if (Lex.getCode() != tgtok::r_square) {
1340 TokError("expected ']' at end of list slice");
1347 if (Lex.Lex() != tgtok::Id) { // eat the .
1348 TokError("expected field identifier after '.'");
1351 if (!Result->getFieldType(Lex.getCurStrVal())) {
1352 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1353 Result->getAsString() + "'");
1356 Result = new FieldInit(Result, Lex.getCurStrVal());
1357 Lex.Lex(); // eat field name
1363 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1365 /// ParseDagArgList ::= Value (':' VARNAME)?
1366 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1367 std::vector<std::pair<llvm::Init*, std::string> >
1368 TGParser::ParseDagArgList(Record *CurRec) {
1369 std::vector<std::pair<llvm::Init*, std::string> > Result;
1372 Init *Val = ParseValue(CurRec);
1373 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1375 // If the variable name is present, add it.
1376 std::string VarName;
1377 if (Lex.getCode() == tgtok::colon) {
1378 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1379 TokError("expected variable name in dag literal");
1380 return std::vector<std::pair<llvm::Init*, std::string> >();
1382 VarName = Lex.getCurStrVal();
1383 Lex.Lex(); // eat the VarName.
1386 Result.push_back(std::make_pair(Val, VarName));
1388 if (Lex.getCode() != tgtok::comma) break;
1389 Lex.Lex(); // eat the ','
1396 /// ParseValueList - Parse a comma separated list of values, returning them as a
1397 /// vector. Note that this always expects to be able to parse at least one
1398 /// value. It returns an empty list if this is not possible.
1400 /// ValueList ::= Value (',' Value)
1402 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec, RecTy *EltTy) {
1403 std::vector<Init*> Result;
1404 RecTy *ItemType = EltTy;
1406 if (ArgsRec != 0 && EltTy == 0) {
1407 const std::vector<std::string> &TArgs = ArgsRec->getTemplateArgs();
1408 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1409 assert(RV && "Template argument record not found??");
1410 ItemType = RV->getType();
1413 Result.push_back(ParseValue(CurRec, ItemType));
1414 if (Result.back() == 0) return std::vector<Init*>();
1416 while (Lex.getCode() == tgtok::comma) {
1417 Lex.Lex(); // Eat the comma
1419 if (ArgsRec != 0 && EltTy == 0) {
1420 const std::vector<std::string> &TArgs = ArgsRec->getTemplateArgs();
1421 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1422 assert(RV && "Template argument record not found??");
1423 ItemType = RV->getType();
1426 Result.push_back(ParseValue(CurRec, ItemType));
1427 if (Result.back() == 0) return std::vector<Init*>();
1435 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1436 /// empty string on error. This can happen in a number of different context's,
1437 /// including within a def or in the template args for a def (which which case
1438 /// CurRec will be non-null) and within the template args for a multiclass (in
1439 /// which case CurRec will be null, but CurMultiClass will be set). This can
1440 /// also happen within a def that is within a multiclass, which will set both
1441 /// CurRec and CurMultiClass.
1443 /// Declaration ::= FIELD? Type ID ('=' Value)?
1445 std::string TGParser::ParseDeclaration(Record *CurRec,
1446 bool ParsingTemplateArgs) {
1447 // Read the field prefix if present.
1448 bool HasField = Lex.getCode() == tgtok::Field;
1449 if (HasField) Lex.Lex();
1451 RecTy *Type = ParseType();
1452 if (Type == 0) return "";
1454 if (Lex.getCode() != tgtok::Id) {
1455 TokError("Expected identifier in declaration");
1459 TGLoc IdLoc = Lex.getLoc();
1460 std::string DeclName = Lex.getCurStrVal();
1463 if (ParsingTemplateArgs) {
1465 DeclName = CurRec->getName() + ":" + DeclName;
1467 assert(CurMultiClass);
1470 DeclName = CurMultiClass->Rec.getName() + "::" + DeclName;
1474 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1477 // If a value is present, parse it.
1478 if (Lex.getCode() == tgtok::equal) {
1480 TGLoc ValLoc = Lex.getLoc();
1481 Init *Val = ParseValue(CurRec, Type);
1483 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1490 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1491 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1492 /// template args for a def, which may or may not be in a multiclass. If null,
1493 /// these are the template args for a multiclass.
1495 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1497 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1498 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1499 Lex.Lex(); // eat the '<'
1501 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1503 // Read the first declaration.
1504 std::string TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1505 if (TemplArg.empty())
1508 TheRecToAddTo->addTemplateArg(TemplArg);
1510 while (Lex.getCode() == tgtok::comma) {
1511 Lex.Lex(); // eat the ','
1513 // Read the following declarations.
1514 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1515 if (TemplArg.empty())
1517 TheRecToAddTo->addTemplateArg(TemplArg);
1520 if (Lex.getCode() != tgtok::greater)
1521 return TokError("expected '>' at end of template argument list");
1522 Lex.Lex(); // eat the '>'.
1527 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1529 /// BodyItem ::= Declaration ';'
1530 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1531 bool TGParser::ParseBodyItem(Record *CurRec) {
1532 if (Lex.getCode() != tgtok::Let) {
1533 if (ParseDeclaration(CurRec, false).empty())
1536 if (Lex.getCode() != tgtok::semi)
1537 return TokError("expected ';' after declaration");
1542 // LET ID OptionalRangeList '=' Value ';'
1543 if (Lex.Lex() != tgtok::Id)
1544 return TokError("expected field identifier after let");
1546 TGLoc IdLoc = Lex.getLoc();
1547 std::string FieldName = Lex.getCurStrVal();
1548 Lex.Lex(); // eat the field name.
1550 std::vector<unsigned> BitList;
1551 if (ParseOptionalBitList(BitList))
1553 std::reverse(BitList.begin(), BitList.end());
1555 if (Lex.getCode() != tgtok::equal)
1556 return TokError("expected '=' in let expression");
1557 Lex.Lex(); // eat the '='.
1559 RecordVal *Field = CurRec->getValue(FieldName);
1561 return TokError("Value '" + FieldName + "' unknown!");
1563 RecTy *Type = Field->getType();
1565 Init *Val = ParseValue(CurRec, Type);
1566 if (Val == 0) return true;
1568 if (Lex.getCode() != tgtok::semi)
1569 return TokError("expected ';' after let expression");
1572 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1575 /// ParseBody - Read the body of a class or def. Return true on error, false on
1579 /// Body ::= '{' BodyList '}'
1580 /// BodyList BodyItem*
1582 bool TGParser::ParseBody(Record *CurRec) {
1583 // If this is a null definition, just eat the semi and return.
1584 if (Lex.getCode() == tgtok::semi) {
1589 if (Lex.getCode() != tgtok::l_brace)
1590 return TokError("Expected ';' or '{' to start body");
1594 while (Lex.getCode() != tgtok::r_brace)
1595 if (ParseBodyItem(CurRec))
1603 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1604 /// optional ClassList followed by a Body. CurRec is the current def or class
1605 /// that is being parsed.
1607 /// ObjectBody ::= BaseClassList Body
1608 /// BaseClassList ::= /*empty*/
1609 /// BaseClassList ::= ':' BaseClassListNE
1610 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1612 bool TGParser::ParseObjectBody(Record *CurRec) {
1613 // If there is a baseclass list, read it.
1614 if (Lex.getCode() == tgtok::colon) {
1617 // Read all of the subclasses.
1618 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1621 if (SubClass.Rec == 0) return true;
1624 if (AddSubClass(CurRec, SubClass))
1627 if (Lex.getCode() != tgtok::comma) break;
1628 Lex.Lex(); // eat ','.
1629 SubClass = ParseSubClassReference(CurRec, false);
1633 // Process any variables on the let stack.
1634 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1635 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1636 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1637 LetStack[i][j].Bits, LetStack[i][j].Value))
1640 return ParseBody(CurRec);
1644 /// ParseDef - Parse and return a top level or multiclass def, return the record
1645 /// corresponding to it. This returns null on error.
1647 /// DefInst ::= DEF ObjectName ObjectBody
1649 llvm::Record *TGParser::ParseDef(MultiClass *CurMultiClass) {
1650 TGLoc DefLoc = Lex.getLoc();
1651 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1652 Lex.Lex(); // Eat the 'def' token.
1654 // Parse ObjectName and make a record for it.
1655 Record *CurRec = new Record(ParseObjectName(), DefLoc);
1657 if (!CurMultiClass) {
1658 // Top-level def definition.
1660 // Ensure redefinition doesn't happen.
1661 if (Records.getDef(CurRec->getName())) {
1662 Error(DefLoc, "def '" + CurRec->getName() + "' already defined");
1665 Records.addDef(CurRec);
1667 // Otherwise, a def inside a multiclass, add it to the multiclass.
1668 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1669 if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
1670 Error(DefLoc, "def '" + CurRec->getName() +
1671 "' already defined in this multiclass!");
1674 CurMultiClass->DefPrototypes.push_back(CurRec);
1677 if (ParseObjectBody(CurRec))
1680 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1681 CurRec->resolveReferences();
1683 // If ObjectBody has template arguments, it's an error.
1684 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1689 /// ParseClass - Parse a tblgen class definition.
1691 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1693 bool TGParser::ParseClass() {
1694 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1697 if (Lex.getCode() != tgtok::Id)
1698 return TokError("expected class name after 'class' keyword");
1700 Record *CurRec = Records.getClass(Lex.getCurStrVal());
1702 // If the body was previously defined, this is an error.
1703 if (!CurRec->getValues().empty() ||
1704 !CurRec->getSuperClasses().empty() ||
1705 !CurRec->getTemplateArgs().empty())
1706 return TokError("Class '" + CurRec->getName() + "' already defined");
1708 // If this is the first reference to this class, create and add it.
1709 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc());
1710 Records.addClass(CurRec);
1712 Lex.Lex(); // eat the name.
1714 // If there are template args, parse them.
1715 if (Lex.getCode() == tgtok::less)
1716 if (ParseTemplateArgList(CurRec))
1719 // Finally, parse the object body.
1720 return ParseObjectBody(CurRec);
1723 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1726 /// LetList ::= LetItem (',' LetItem)*
1727 /// LetItem ::= ID OptionalRangeList '=' Value
1729 std::vector<LetRecord> TGParser::ParseLetList() {
1730 std::vector<LetRecord> Result;
1733 if (Lex.getCode() != tgtok::Id) {
1734 TokError("expected identifier in let definition");
1735 return std::vector<LetRecord>();
1737 std::string Name = Lex.getCurStrVal();
1738 TGLoc NameLoc = Lex.getLoc();
1739 Lex.Lex(); // Eat the identifier.
1741 // Check for an optional RangeList.
1742 std::vector<unsigned> Bits;
1743 if (ParseOptionalRangeList(Bits))
1744 return std::vector<LetRecord>();
1745 std::reverse(Bits.begin(), Bits.end());
1747 if (Lex.getCode() != tgtok::equal) {
1748 TokError("expected '=' in let expression");
1749 return std::vector<LetRecord>();
1751 Lex.Lex(); // eat the '='.
1753 Init *Val = ParseValue(0);
1754 if (Val == 0) return std::vector<LetRecord>();
1756 // Now that we have everything, add the record.
1757 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1759 if (Lex.getCode() != tgtok::comma)
1761 Lex.Lex(); // eat the comma.
1765 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
1766 /// different related productions.
1768 /// Object ::= LET LetList IN '{' ObjectList '}'
1769 /// Object ::= LET LetList IN Object
1771 bool TGParser::ParseTopLevelLet() {
1772 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1775 // Add this entry to the let stack.
1776 std::vector<LetRecord> LetInfo = ParseLetList();
1777 if (LetInfo.empty()) return true;
1778 LetStack.push_back(LetInfo);
1780 if (Lex.getCode() != tgtok::In)
1781 return TokError("expected 'in' at end of top-level 'let'");
1784 // If this is a scalar let, just handle it now
1785 if (Lex.getCode() != tgtok::l_brace) {
1786 // LET LetList IN Object
1789 } else { // Object ::= LETCommand '{' ObjectList '}'
1790 TGLoc BraceLoc = Lex.getLoc();
1791 // Otherwise, this is a group let.
1792 Lex.Lex(); // eat the '{'.
1794 // Parse the object list.
1795 if (ParseObjectList())
1798 if (Lex.getCode() != tgtok::r_brace) {
1799 TokError("expected '}' at end of top level let command");
1800 return Error(BraceLoc, "to match this '{'");
1805 // Outside this let scope, this let block is not active.
1806 LetStack.pop_back();
1810 /// ParseMultiClassDef - Parse a def in a multiclass context.
1812 /// MultiClassDef ::= DefInst
1814 bool TGParser::ParseMultiClassDef(MultiClass *CurMC) {
1815 if (Lex.getCode() != tgtok::Def)
1816 return TokError("expected 'def' in multiclass body");
1818 Record *D = ParseDef(CurMC);
1819 if (D == 0) return true;
1821 // Copy the template arguments for the multiclass into the def.
1822 const std::vector<std::string> &TArgs = CurMC->Rec.getTemplateArgs();
1824 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1825 const RecordVal *RV = CurMC->Rec.getValue(TArgs[i]);
1826 assert(RV && "Template arg doesn't exist?");
1833 /// ParseMultiClass - Parse a multiclass definition.
1835 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
1836 /// ':' BaseMultiClassList '{' MultiClassDef+ '}'
1838 bool TGParser::ParseMultiClass() {
1839 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1840 Lex.Lex(); // Eat the multiclass token.
1842 if (Lex.getCode() != tgtok::Id)
1843 return TokError("expected identifier after multiclass for name");
1844 std::string Name = Lex.getCurStrVal();
1846 if (MultiClasses.count(Name))
1847 return TokError("multiclass '" + Name + "' already defined");
1849 CurMultiClass = MultiClasses[Name] = new MultiClass(Name, Lex.getLoc());
1850 Lex.Lex(); // Eat the identifier.
1852 // If there are template args, parse them.
1853 if (Lex.getCode() == tgtok::less)
1854 if (ParseTemplateArgList(0))
1857 bool inherits = false;
1859 // If there are submulticlasses, parse them.
1860 if (Lex.getCode() == tgtok::colon) {
1865 // Read all of the submulticlasses.
1866 SubMultiClassReference SubMultiClass =
1867 ParseSubMultiClassReference(CurMultiClass);
1870 if (SubMultiClass.MC == 0) return true;
1873 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
1876 if (Lex.getCode() != tgtok::comma) break;
1877 Lex.Lex(); // eat ','.
1878 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
1882 if (Lex.getCode() != tgtok::l_brace) {
1884 return TokError("expected '{' in multiclass definition");
1886 if (Lex.getCode() != tgtok::semi)
1887 return TokError("expected ';' in multiclass definition");
1889 Lex.Lex(); // eat the ';'.
1892 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
1893 return TokError("multiclass must contain at least one def");
1895 while (Lex.getCode() != tgtok::r_brace)
1896 if (ParseMultiClassDef(CurMultiClass))
1899 Lex.Lex(); // eat the '}'.
1906 /// ParseDefm - Parse the instantiation of a multiclass.
1908 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
1910 bool TGParser::ParseDefm() {
1911 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
1912 if (Lex.Lex() != tgtok::Id) // eat the defm.
1913 return TokError("expected identifier after defm");
1915 TGLoc DefmPrefixLoc = Lex.getLoc();
1916 std::string DefmPrefix = Lex.getCurStrVal();
1917 if (Lex.Lex() != tgtok::colon)
1918 return TokError("expected ':' after defm identifier");
1923 TGLoc SubClassLoc = Lex.getLoc();
1924 SubClassReference Ref = ParseSubClassReference(0, true);
1927 if (Ref.Rec == 0) return true;
1929 // To instantiate a multiclass, we need to first get the multiclass, then
1930 // instantiate each def contained in the multiclass with the SubClassRef
1931 // template parameters.
1932 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
1933 assert(MC && "Didn't lookup multiclass correctly?");
1934 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
1936 // Verify that the correct number of template arguments were specified.
1937 const std::vector<std::string> &TArgs = MC->Rec.getTemplateArgs();
1938 if (TArgs.size() < TemplateVals.size())
1939 return Error(SubClassLoc,
1940 "more template args specified than multiclass expects");
1942 // Loop over all the def's in the multiclass, instantiating each one.
1943 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
1944 Record *DefProto = MC->DefPrototypes[i];
1946 // Add in the defm name
1947 std::string DefName = DefProto->getName();
1948 std::string::size_type idx = DefName.find("#NAME#");
1949 if (idx != std::string::npos) {
1950 DefName.replace(idx, 6, DefmPrefix);
1953 // Add the suffix to the defm name to get the new name.
1954 DefName = DefmPrefix + DefName;
1957 Record *CurRec = new Record(DefName, DefmPrefixLoc);
1959 SubClassReference Ref;
1960 Ref.RefLoc = DefmPrefixLoc;
1962 AddSubClass(CurRec, Ref);
1964 // Loop over all of the template arguments, setting them to the specified
1965 // value or leaving them as the default if necessary.
1966 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1967 // Check if a value is specified for this temp-arg.
1968 if (i < TemplateVals.size()) {
1970 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
1975 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
1978 CurRec->removeValue(TArgs[i]);
1980 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
1981 return Error(SubClassLoc,
1982 "value not specified for template argument #"+
1983 utostr(i) + " (" + TArgs[i] + ") of multiclassclass '" +
1984 MC->Rec.getName() + "'");
1988 // If the mdef is inside a 'let' expression, add to each def.
1989 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1990 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1991 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1992 LetStack[i][j].Bits, LetStack[i][j].Value)) {
1993 Error(DefmPrefixLoc, "when instantiating this defm");
1997 // Ensure redefinition doesn't happen.
1998 if (Records.getDef(CurRec->getName()))
1999 return Error(DefmPrefixLoc, "def '" + CurRec->getName() +
2000 "' already defined, instantiating defm with subdef '" +
2001 DefProto->getName() + "'");
2002 Records.addDef(CurRec);
2003 CurRec->resolveReferences();
2006 if (Lex.getCode() != tgtok::comma) break;
2007 Lex.Lex(); // eat ','.
2009 SubClassLoc = Lex.getLoc();
2010 Ref = ParseSubClassReference(0, true);
2013 if (Lex.getCode() != tgtok::semi)
2014 return TokError("expected ';' at end of defm");
2021 /// Object ::= ClassInst
2022 /// Object ::= DefInst
2023 /// Object ::= MultiClassInst
2024 /// Object ::= DefMInst
2025 /// Object ::= LETCommand '{' ObjectList '}'
2026 /// Object ::= LETCommand Object
2027 bool TGParser::ParseObject() {
2028 switch (Lex.getCode()) {
2029 default: assert(0 && "This is not an object");
2030 case tgtok::Let: return ParseTopLevelLet();
2031 case tgtok::Def: return ParseDef(0) == 0;
2032 case tgtok::Defm: return ParseDefm();
2033 case tgtok::Class: return ParseClass();
2034 case tgtok::MultiClass: return ParseMultiClass();
2039 /// ObjectList :== Object*
2040 bool TGParser::ParseObjectList() {
2041 while (isObjectStart(Lex.getCode())) {
2049 bool TGParser::ParseFile() {
2050 Lex.Lex(); // Prime the lexer.
2051 if (ParseObjectList()) return true;
2053 // If we have unread input at the end of the file, report it.
2054 if (Lex.getCode() == tgtok::Eof)
2057 return TokError("Unexpected input at top level");