1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implement the Parser for TableGen.
12 //===----------------------------------------------------------------------===//
16 #include "llvm/ADT/StringExtras.h"
21 //===----------------------------------------------------------------------===//
22 // Support Code for the Semantic Actions.
23 //===----------------------------------------------------------------------===//
26 struct SubClassReference {
29 std::vector<Init*> TemplateArgs;
30 SubClassReference() : Rec(0) {}
32 bool isInvalid() const { return Rec == 0; }
35 struct SubMultiClassReference {
38 std::vector<Init*> TemplateArgs;
39 SubMultiClassReference() : MC(0) {}
41 bool isInvalid() const { return MC == 0; }
45 void SubMultiClassReference::dump() const {
46 errs() << "Multiclass:\n";
50 errs() << "Template args:\n";
51 for (std::vector<Init *>::const_iterator i = TemplateArgs.begin(),
52 iend = TemplateArgs.end();
59 } // end namespace llvm
61 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
63 CurRec = &CurMultiClass->Rec;
65 if (RecordVal *ERV = CurRec->getValue(RV.getName())) {
66 // The value already exists in the class, treat this as a set.
67 if (ERV->setValue(RV.getValue()))
68 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
69 RV.getType()->getAsString() + "' is incompatible with " +
70 "previous definition of type '" +
71 ERV->getType()->getAsString() + "'");
79 /// Return true on error, false on success.
80 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, const std::string &ValName,
81 const std::vector<unsigned> &BitList, Init *V) {
84 if (CurRec == 0) CurRec = &CurMultiClass->Rec;
86 RecordVal *RV = CurRec->getValue(ValName);
88 return Error(Loc, "Value '" + ValName + "' unknown!");
90 // Do not allow assignments like 'X = X'. This will just cause infinite loops
91 // in the resolution machinery.
93 if (VarInit *VI = dynamic_cast<VarInit*>(V))
94 if (VI->getName() == ValName)
97 // If we are assigning to a subset of the bits in the value... then we must be
98 // assigning to a field of BitsRecTy, which must have a BitsInit
101 if (!BitList.empty()) {
102 BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
104 return Error(Loc, "Value '" + ValName + "' is not a bits type");
106 // Convert the incoming value to a bits type of the appropriate size...
107 Init *BI = V->convertInitializerTo(new BitsRecTy(BitList.size()));
109 V->convertInitializerTo(new BitsRecTy(BitList.size()));
110 return Error(Loc, "Initializer is not compatible with bit range");
113 // We should have a BitsInit type now.
114 BitsInit *BInit = dynamic_cast<BitsInit*>(BI);
117 BitsInit *NewVal = new BitsInit(CurVal->getNumBits());
119 // Loop over bits, assigning values as appropriate.
120 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
121 unsigned Bit = BitList[i];
122 if (NewVal->getBit(Bit))
123 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
124 ValName + "' more than once");
125 NewVal->setBit(Bit, BInit->getBit(i));
128 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
129 if (NewVal->getBit(i) == 0)
130 NewVal->setBit(i, CurVal->getBit(i));
136 return Error(Loc, "Value '" + ValName + "' of type '" +
137 RV->getType()->getAsString() +
138 "' is incompatible with initializer '" + V->getAsString() +"'");
142 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
143 /// args as SubClass's template arguments.
144 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
145 Record *SC = SubClass.Rec;
146 // Add all of the values in the subclass into the current class.
147 const std::vector<RecordVal> &Vals = SC->getValues();
148 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
149 if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
152 const std::vector<std::string> &TArgs = SC->getTemplateArgs();
154 // Ensure that an appropriate number of template arguments are specified.
155 if (TArgs.size() < SubClass.TemplateArgs.size())
156 return Error(SubClass.RefLoc, "More template args specified than expected");
158 // Loop over all of the template arguments, setting them to the specified
159 // value or leaving them as the default if necessary.
160 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
161 if (i < SubClass.TemplateArgs.size()) {
162 // If a value is specified for this template arg, set it now.
163 if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(),
164 SubClass.TemplateArgs[i]))
168 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
171 CurRec->removeValue(TArgs[i]);
173 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
174 return Error(SubClass.RefLoc,"Value not specified for template argument #"
175 + utostr(i) + " (" + TArgs[i] + ") of subclass '" +
176 SC->getName() + "'!");
180 // Since everything went well, we can now set the "superclass" list for the
182 const std::vector<Record*> &SCs = SC->getSuperClasses();
183 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
184 if (CurRec->isSubClassOf(SCs[i]))
185 return Error(SubClass.RefLoc,
186 "Already subclass of '" + SCs[i]->getName() + "'!\n");
187 CurRec->addSuperClass(SCs[i]);
190 if (CurRec->isSubClassOf(SC))
191 return Error(SubClass.RefLoc,
192 "Already subclass of '" + SC->getName() + "'!\n");
193 CurRec->addSuperClass(SC);
197 /// AddSubMultiClass - Add SubMultiClass as a subclass to
198 /// CurMC, resolving its template args as SubMultiClass's
199 /// template arguments.
200 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
201 SubMultiClassReference &SubMultiClass) {
202 MultiClass *SMC = SubMultiClass.MC;
203 Record *CurRec = &CurMC->Rec;
205 const std::vector<RecordVal> &MCVals = CurRec->getValues();
207 // Add all of the values in the subclass into the current class.
208 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
209 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
210 if (AddValue(CurRec, SubMultiClass.RefLoc, SMCVals[i]))
213 int newDefStart = CurMC->DefPrototypes.size();
215 // Add all of the defs in the subclass into the current multiclass.
216 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
217 iend = SMC->DefPrototypes.end();
220 // Clone the def and add it to the current multiclass
221 Record *NewDef = new Record(**i);
223 // Add all of the values in the superclass into the current def.
224 for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
225 if (AddValue(NewDef, SubMultiClass.RefLoc, MCVals[i]))
228 CurMC->DefPrototypes.push_back(NewDef);
231 const std::vector<std::string> &SMCTArgs = SMC->Rec.getTemplateArgs();
233 // Ensure that an appropriate number of template arguments are
235 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
236 return Error(SubMultiClass.RefLoc,
237 "More template args specified than expected");
239 // Loop over all of the template arguments, setting them to the specified
240 // value or leaving them as the default if necessary.
241 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
242 if (i < SubMultiClass.TemplateArgs.size()) {
243 // If a value is specified for this template arg, set it in the
245 if (SetValue(CurRec, SubMultiClass.RefLoc, SMCTArgs[i],
246 std::vector<unsigned>(),
247 SubMultiClass.TemplateArgs[i]))
251 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
254 CurRec->removeValue(SMCTArgs[i]);
256 // If a value is specified for this template arg, set it in the
258 for (MultiClass::RecordVector::iterator j =
259 CurMC->DefPrototypes.begin() + newDefStart,
260 jend = CurMC->DefPrototypes.end();
265 if (SetValue(Def, SubMultiClass.RefLoc, SMCTArgs[i],
266 std::vector<unsigned>(),
267 SubMultiClass.TemplateArgs[i]))
271 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
274 Def->removeValue(SMCTArgs[i]);
276 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
277 return Error(SubMultiClass.RefLoc,
278 "Value not specified for template argument #"
279 + utostr(i) + " (" + SMCTArgs[i] + ") of subclass '" +
280 SMC->Rec.getName() + "'!");
287 //===----------------------------------------------------------------------===//
289 //===----------------------------------------------------------------------===//
291 /// isObjectStart - Return true if this is a valid first token for an Object.
292 static bool isObjectStart(tgtok::TokKind K) {
293 return K == tgtok::Class || K == tgtok::Def ||
294 K == tgtok::Defm || K == tgtok::Let || K == tgtok::MultiClass;
297 static std::string GetNewAnonymousName() {
298 static unsigned AnonCounter = 0;
299 return "anonymous."+utostr(AnonCounter++);
302 /// ParseObjectName - If an object name is specified, return it. Otherwise,
303 /// return an anonymous name.
304 /// ObjectName ::= ID
305 /// ObjectName ::= /*empty*/
307 std::string TGParser::ParseObjectName() {
308 if (Lex.getCode() != tgtok::Id)
309 return GetNewAnonymousName();
311 std::string Ret = Lex.getCurStrVal();
317 /// ParseClassID - Parse and resolve a reference to a class name. This returns
322 Record *TGParser::ParseClassID() {
323 if (Lex.getCode() != tgtok::Id) {
324 TokError("expected name for ClassID");
328 Record *Result = Records.getClass(Lex.getCurStrVal());
330 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
336 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
337 /// This returns null on error.
339 /// MultiClassID ::= ID
341 MultiClass *TGParser::ParseMultiClassID() {
342 if (Lex.getCode() != tgtok::Id) {
343 TokError("expected name for ClassID");
347 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
349 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
355 Record *TGParser::ParseDefmID() {
356 if (Lex.getCode() != tgtok::Id) {
357 TokError("expected multiclass name");
361 MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
363 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 SMLoc 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 SMLoc 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 SMLoc 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, SMLoc 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();
768 Type = new ListRecTy(Itemt->getType());
771 assert(LHSt && "expected list type argument in unary operator");
772 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
774 TokError("expected list type argumnet in unary operator");
777 if (Code == UnOpInit::CAR) {
778 Type = LType->getElementType();
786 if (Lex.getCode() != tgtok::r_paren) {
787 TokError("expected ')' in unary operator");
790 Lex.Lex(); // eat the ')'
791 return (new UnOpInit(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
799 case tgtok::XStrConcat:
800 case tgtok::XNameConcat: { // Value ::= !binop '(' Value ',' Value ')'
801 BinOpInit::BinaryOp Code;
805 switch (Lex.getCode()) {
806 default: assert(0 && "Unhandled code!");
808 Lex.Lex(); // eat the operation
809 Code = BinOpInit::CONCAT;
810 Type = new DagRecTy();
813 Lex.Lex(); // eat the operation
814 Code = BinOpInit::SRA;
815 Type = new IntRecTy();
818 Lex.Lex(); // eat the operation
819 Code = BinOpInit::SRL;
820 Type = new IntRecTy();
823 Lex.Lex(); // eat the operation
824 Code = BinOpInit::SHL;
825 Type = new IntRecTy();
828 Lex.Lex(); // eat the operation
829 Code = BinOpInit::EQ;
830 Type = new IntRecTy();
832 case tgtok::XStrConcat:
833 Lex.Lex(); // eat the operation
834 Code = BinOpInit::STRCONCAT;
835 Type = new StringRecTy();
837 case tgtok::XNameConcat:
838 Lex.Lex(); // eat the operation
839 Code = BinOpInit::NAMECONCAT;
841 Type = ParseOperatorType();
844 TokError("did not get type for binary operator");
850 if (Lex.getCode() != tgtok::l_paren) {
851 TokError("expected '(' after binary operator");
854 Lex.Lex(); // eat the '('
856 Init *LHS = ParseValue(CurRec);
857 if (LHS == 0) return 0;
859 if (Lex.getCode() != tgtok::comma) {
860 TokError("expected ',' in binary operator");
863 Lex.Lex(); // eat the ','
865 Init *RHS = ParseValue(CurRec);
866 if (RHS == 0) return 0;
868 if (Lex.getCode() != tgtok::r_paren) {
869 TokError("expected ')' in binary operator");
872 Lex.Lex(); // eat the ')'
873 return (new BinOpInit(Code, LHS, RHS, Type))->Fold(CurRec, CurMultiClass);
877 case tgtok::XForEach:
878 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
879 TernOpInit::TernaryOp Code;
883 tgtok::TokKind LexCode = Lex.getCode();
884 Lex.Lex(); // eat the operation
886 default: assert(0 && "Unhandled code!");
888 Code = TernOpInit::IF;
890 case tgtok::XForEach:
891 Code = TernOpInit::FOREACH;
894 Code = TernOpInit::SUBST;
897 if (Lex.getCode() != tgtok::l_paren) {
898 TokError("expected '(' after ternary operator");
901 Lex.Lex(); // eat the '('
903 Init *LHS = ParseValue(CurRec);
904 if (LHS == 0) return 0;
906 if (Lex.getCode() != tgtok::comma) {
907 TokError("expected ',' in ternary operator");
910 Lex.Lex(); // eat the ','
912 Init *MHS = ParseValue(CurRec);
913 if (MHS == 0) return 0;
915 if (Lex.getCode() != tgtok::comma) {
916 TokError("expected ',' in ternary operator");
919 Lex.Lex(); // eat the ','
921 Init *RHS = ParseValue(CurRec);
922 if (RHS == 0) return 0;
924 if (Lex.getCode() != tgtok::r_paren) {
925 TokError("expected ')' in binary operator");
928 Lex.Lex(); // eat the ')'
931 default: assert(0 && "Unhandled code!");
933 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
934 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
935 if (MHSt == 0 || RHSt == 0) {
936 TokError("could not get type for !if");
939 if (MHSt->getType()->typeIsConvertibleTo(RHSt->getType())) {
940 Type = RHSt->getType();
941 } else if (RHSt->getType()->typeIsConvertibleTo(MHSt->getType())) {
942 Type = MHSt->getType();
944 TokError("inconsistent types for !if");
949 case tgtok::XForEach: {
950 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
952 TokError("could not get type for !foreach");
955 Type = MHSt->getType();
958 case tgtok::XSubst: {
959 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
961 TokError("could not get type for !subst");
964 Type = RHSt->getType();
968 return (new TernOpInit(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
972 TokError("could not parse operation");
976 /// ParseOperatorType - Parse a type for an operator. This returns
979 /// OperatorType ::= '<' Type '>'
981 RecTy *TGParser::ParseOperatorType() {
984 if (Lex.getCode() != tgtok::less) {
985 TokError("expected type name for operator");
988 Lex.Lex(); // eat the <
993 TokError("expected type name for operator");
997 if (Lex.getCode() != tgtok::greater) {
998 TokError("expected type name for operator");
1001 Lex.Lex(); // eat the >
1007 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1009 /// SimpleValue ::= IDValue
1010 /// SimpleValue ::= INTVAL
1011 /// SimpleValue ::= STRVAL+
1012 /// SimpleValue ::= CODEFRAGMENT
1013 /// SimpleValue ::= '?'
1014 /// SimpleValue ::= '{' ValueList '}'
1015 /// SimpleValue ::= ID '<' ValueListNE '>'
1016 /// SimpleValue ::= '[' ValueList ']'
1017 /// SimpleValue ::= '(' IDValue DagArgList ')'
1018 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1019 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1020 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1021 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1022 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1024 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType) {
1026 switch (Lex.getCode()) {
1027 default: TokError("Unknown token when parsing a value"); break;
1028 case tgtok::IntVal: R = new IntInit(Lex.getCurIntVal()); Lex.Lex(); break;
1029 case tgtok::StrVal: {
1030 std::string Val = Lex.getCurStrVal();
1033 // Handle multiple consecutive concatenated strings.
1034 while (Lex.getCode() == tgtok::StrVal) {
1035 Val += Lex.getCurStrVal();
1039 R = new StringInit(Val);
1042 case tgtok::CodeFragment:
1043 R = new CodeInit(Lex.getCurStrVal()); Lex.Lex(); break;
1044 case tgtok::question: R = new UnsetInit(); Lex.Lex(); break;
1046 SMLoc NameLoc = Lex.getLoc();
1047 std::string Name = Lex.getCurStrVal();
1048 if (Lex.Lex() != tgtok::less) // consume the Id.
1049 return ParseIDValue(CurRec, Name, NameLoc); // Value ::= IDValue
1051 // Value ::= ID '<' ValueListNE '>'
1052 if (Lex.Lex() == tgtok::greater) {
1053 TokError("expected non-empty value list");
1057 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1058 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1060 Record *Class = Records.getClass(Name);
1062 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1066 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1067 if (ValueList.empty()) return 0;
1069 if (Lex.getCode() != tgtok::greater) {
1070 TokError("expected '>' at end of value list");
1073 Lex.Lex(); // eat the '>'
1075 // Create the new record, set it as CurRec temporarily.
1076 static unsigned AnonCounter = 0;
1077 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),NameLoc);
1078 SubClassReference SCRef;
1079 SCRef.RefLoc = NameLoc;
1081 SCRef.TemplateArgs = ValueList;
1082 // Add info about the subclass to NewRec.
1083 if (AddSubClass(NewRec, SCRef))
1085 NewRec->resolveReferences();
1086 Records.addDef(NewRec);
1088 // The result of the expression is a reference to the new record.
1089 return new DefInit(NewRec);
1091 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1092 SMLoc BraceLoc = Lex.getLoc();
1093 Lex.Lex(); // eat the '{'
1094 std::vector<Init*> Vals;
1096 if (Lex.getCode() != tgtok::r_brace) {
1097 Vals = ParseValueList(CurRec);
1098 if (Vals.empty()) return 0;
1100 if (Lex.getCode() != tgtok::r_brace) {
1101 TokError("expected '}' at end of bit list value");
1104 Lex.Lex(); // eat the '}'
1106 BitsInit *Result = new BitsInit(Vals.size());
1107 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1108 Init *Bit = Vals[i]->convertInitializerTo(new BitRecTy());
1110 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1111 ") is not convertable to a bit");
1114 Result->setBit(Vals.size()-i-1, Bit);
1118 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1119 Lex.Lex(); // eat the '['
1120 std::vector<Init*> Vals;
1122 RecTy *DeducedEltTy = 0;
1123 ListRecTy *GivenListTy = 0;
1125 if (ItemType != 0) {
1126 ListRecTy *ListType = dynamic_cast<ListRecTy*>(ItemType);
1127 if (ListType == 0) {
1128 std::stringstream s;
1129 s << "Type mismatch for list, expected list type, got "
1130 << ItemType->getAsString();
1133 GivenListTy = ListType;
1136 if (Lex.getCode() != tgtok::r_square) {
1137 Vals = ParseValueList(CurRec, 0,
1138 GivenListTy ? GivenListTy->getElementType() : 0);
1139 if (Vals.empty()) return 0;
1141 if (Lex.getCode() != tgtok::r_square) {
1142 TokError("expected ']' at end of list value");
1145 Lex.Lex(); // eat the ']'
1147 RecTy *GivenEltTy = 0;
1148 if (Lex.getCode() == tgtok::less) {
1149 // Optional list element type
1150 Lex.Lex(); // eat the '<'
1152 GivenEltTy = ParseType();
1153 if (GivenEltTy == 0) {
1154 // Couldn't parse element type
1158 if (Lex.getCode() != tgtok::greater) {
1159 TokError("expected '>' at end of list element type");
1162 Lex.Lex(); // eat the '>'
1167 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1170 TypedInit *TArg = dynamic_cast<TypedInit*>(*i);
1172 TokError("Untyped list element");
1176 EltTy = resolveTypes(EltTy, TArg->getType());
1178 TokError("Incompatible types in list elements");
1182 EltTy = TArg->getType();
1186 if (GivenEltTy != 0) {
1188 // Verify consistency
1189 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1190 TokError("Incompatible types in list elements");
1198 if (ItemType == 0) {
1199 TokError("No type for list");
1202 DeducedEltTy = GivenListTy->getElementType();
1204 // Make sure the deduced type is compatible with the given type
1206 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1207 TokError("Element type mismatch for list");
1211 DeducedEltTy = EltTy;
1214 return new ListInit(Vals, DeducedEltTy);
1216 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1217 Lex.Lex(); // eat the '('
1218 if (Lex.getCode() != tgtok::Id
1219 && Lex.getCode() != tgtok::XCast
1220 && Lex.getCode() != tgtok::XNameConcat) {
1221 TokError("expected identifier in dag init");
1226 if (Lex.getCode() == tgtok::Id) {
1227 Operator = ParseIDValue(CurRec);
1228 if (Operator == 0) return 0;
1230 Operator = ParseOperation(CurRec);
1231 if (Operator == 0) return 0;
1234 // If the operator name is present, parse it.
1235 std::string OperatorName;
1236 if (Lex.getCode() == tgtok::colon) {
1237 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1238 TokError("expected variable name in dag operator");
1241 OperatorName = Lex.getCurStrVal();
1242 Lex.Lex(); // eat the VarName.
1245 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1246 if (Lex.getCode() != tgtok::r_paren) {
1247 DagArgs = ParseDagArgList(CurRec);
1248 if (DagArgs.empty()) return 0;
1251 if (Lex.getCode() != tgtok::r_paren) {
1252 TokError("expected ')' in dag init");
1255 Lex.Lex(); // eat the ')'
1257 return new DagInit(Operator, OperatorName, DagArgs);
1264 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1265 case tgtok::XConcat:
1270 case tgtok::XStrConcat:
1271 case tgtok::XNameConcat: // Value ::= !binop '(' Value ',' Value ')'
1273 case tgtok::XForEach:
1274 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1275 return ParseOperation(CurRec);
1283 /// ParseValue - Parse a tblgen value. This returns null on error.
1285 /// Value ::= SimpleValue ValueSuffix*
1286 /// ValueSuffix ::= '{' BitList '}'
1287 /// ValueSuffix ::= '[' BitList ']'
1288 /// ValueSuffix ::= '.' ID
1290 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType) {
1291 Init *Result = ParseSimpleValue(CurRec, ItemType);
1292 if (Result == 0) return 0;
1294 // Parse the suffixes now if present.
1296 switch (Lex.getCode()) {
1297 default: return Result;
1298 case tgtok::l_brace: {
1299 SMLoc CurlyLoc = Lex.getLoc();
1300 Lex.Lex(); // eat the '{'
1301 std::vector<unsigned> Ranges = ParseRangeList();
1302 if (Ranges.empty()) return 0;
1304 // Reverse the bitlist.
1305 std::reverse(Ranges.begin(), Ranges.end());
1306 Result = Result->convertInitializerBitRange(Ranges);
1308 Error(CurlyLoc, "Invalid bit range for value");
1313 if (Lex.getCode() != tgtok::r_brace) {
1314 TokError("expected '}' at end of bit range list");
1320 case tgtok::l_square: {
1321 SMLoc SquareLoc = Lex.getLoc();
1322 Lex.Lex(); // eat the '['
1323 std::vector<unsigned> Ranges = ParseRangeList();
1324 if (Ranges.empty()) return 0;
1326 Result = Result->convertInitListSlice(Ranges);
1328 Error(SquareLoc, "Invalid range for list slice");
1333 if (Lex.getCode() != tgtok::r_square) {
1334 TokError("expected ']' at end of list slice");
1341 if (Lex.Lex() != tgtok::Id) { // eat the .
1342 TokError("expected field identifier after '.'");
1345 if (!Result->getFieldType(Lex.getCurStrVal())) {
1346 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1347 Result->getAsString() + "'");
1350 Result = new FieldInit(Result, Lex.getCurStrVal());
1351 Lex.Lex(); // eat field name
1357 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1359 /// ParseDagArgList ::= Value (':' VARNAME)?
1360 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1361 std::vector<std::pair<llvm::Init*, std::string> >
1362 TGParser::ParseDagArgList(Record *CurRec) {
1363 std::vector<std::pair<llvm::Init*, std::string> > Result;
1366 Init *Val = ParseValue(CurRec);
1367 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1369 // If the variable name is present, add it.
1370 std::string VarName;
1371 if (Lex.getCode() == tgtok::colon) {
1372 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1373 TokError("expected variable name in dag literal");
1374 return std::vector<std::pair<llvm::Init*, std::string> >();
1376 VarName = Lex.getCurStrVal();
1377 Lex.Lex(); // eat the VarName.
1380 Result.push_back(std::make_pair(Val, VarName));
1382 if (Lex.getCode() != tgtok::comma) break;
1383 Lex.Lex(); // eat the ','
1390 /// ParseValueList - Parse a comma separated list of values, returning them as a
1391 /// vector. Note that this always expects to be able to parse at least one
1392 /// value. It returns an empty list if this is not possible.
1394 /// ValueList ::= Value (',' Value)
1396 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1398 std::vector<Init*> Result;
1399 RecTy *ItemType = EltTy;
1400 unsigned int ArgN = 0;
1401 if (ArgsRec != 0 && EltTy == 0) {
1402 const std::vector<std::string> &TArgs = ArgsRec->getTemplateArgs();
1403 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1404 assert(RV && "Template argument record not found??");
1405 ItemType = RV->getType();
1408 Result.push_back(ParseValue(CurRec, ItemType));
1409 if (Result.back() == 0) return std::vector<Init*>();
1411 while (Lex.getCode() == tgtok::comma) {
1412 Lex.Lex(); // Eat the comma
1414 if (ArgsRec != 0 && EltTy == 0) {
1415 const std::vector<std::string> &TArgs = ArgsRec->getTemplateArgs();
1416 if (ArgN >= TArgs.size()) {
1417 TokError("too many template arguments");
1418 return std::vector<Init*>();
1420 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1421 assert(RV && "Template argument record not found??");
1422 ItemType = RV->getType();
1425 Result.push_back(ParseValue(CurRec, ItemType));
1426 if (Result.back() == 0) return std::vector<Init*>();
1433 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1434 /// empty string on error. This can happen in a number of different context's,
1435 /// including within a def or in the template args for a def (which which case
1436 /// CurRec will be non-null) and within the template args for a multiclass (in
1437 /// which case CurRec will be null, but CurMultiClass will be set). This can
1438 /// also happen within a def that is within a multiclass, which will set both
1439 /// CurRec and CurMultiClass.
1441 /// Declaration ::= FIELD? Type ID ('=' Value)?
1443 std::string TGParser::ParseDeclaration(Record *CurRec,
1444 bool ParsingTemplateArgs) {
1445 // Read the field prefix if present.
1446 bool HasField = Lex.getCode() == tgtok::Field;
1447 if (HasField) Lex.Lex();
1449 RecTy *Type = ParseType();
1450 if (Type == 0) return "";
1452 if (Lex.getCode() != tgtok::Id) {
1453 TokError("Expected identifier in declaration");
1457 SMLoc IdLoc = Lex.getLoc();
1458 std::string DeclName = Lex.getCurStrVal();
1461 if (ParsingTemplateArgs) {
1463 DeclName = CurRec->getName() + ":" + DeclName;
1465 assert(CurMultiClass);
1468 DeclName = CurMultiClass->Rec.getName() + "::" + DeclName;
1472 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1475 // If a value is present, parse it.
1476 if (Lex.getCode() == tgtok::equal) {
1478 SMLoc ValLoc = Lex.getLoc();
1479 Init *Val = ParseValue(CurRec, Type);
1481 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1488 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1489 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1490 /// template args for a def, which may or may not be in a multiclass. If null,
1491 /// these are the template args for a multiclass.
1493 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1495 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1496 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1497 Lex.Lex(); // eat the '<'
1499 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1501 // Read the first declaration.
1502 std::string TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1503 if (TemplArg.empty())
1506 TheRecToAddTo->addTemplateArg(TemplArg);
1508 while (Lex.getCode() == tgtok::comma) {
1509 Lex.Lex(); // eat the ','
1511 // Read the following declarations.
1512 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1513 if (TemplArg.empty())
1515 TheRecToAddTo->addTemplateArg(TemplArg);
1518 if (Lex.getCode() != tgtok::greater)
1519 return TokError("expected '>' at end of template argument list");
1520 Lex.Lex(); // eat the '>'.
1525 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1527 /// BodyItem ::= Declaration ';'
1528 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1529 bool TGParser::ParseBodyItem(Record *CurRec) {
1530 if (Lex.getCode() != tgtok::Let) {
1531 if (ParseDeclaration(CurRec, false).empty())
1534 if (Lex.getCode() != tgtok::semi)
1535 return TokError("expected ';' after declaration");
1540 // LET ID OptionalRangeList '=' Value ';'
1541 if (Lex.Lex() != tgtok::Id)
1542 return TokError("expected field identifier after let");
1544 SMLoc IdLoc = Lex.getLoc();
1545 std::string FieldName = Lex.getCurStrVal();
1546 Lex.Lex(); // eat the field name.
1548 std::vector<unsigned> BitList;
1549 if (ParseOptionalBitList(BitList))
1551 std::reverse(BitList.begin(), BitList.end());
1553 if (Lex.getCode() != tgtok::equal)
1554 return TokError("expected '=' in let expression");
1555 Lex.Lex(); // eat the '='.
1557 RecordVal *Field = CurRec->getValue(FieldName);
1559 return TokError("Value '" + FieldName + "' unknown!");
1561 RecTy *Type = Field->getType();
1563 Init *Val = ParseValue(CurRec, Type);
1564 if (Val == 0) return true;
1566 if (Lex.getCode() != tgtok::semi)
1567 return TokError("expected ';' after let expression");
1570 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1573 /// ParseBody - Read the body of a class or def. Return true on error, false on
1577 /// Body ::= '{' BodyList '}'
1578 /// BodyList BodyItem*
1580 bool TGParser::ParseBody(Record *CurRec) {
1581 // If this is a null definition, just eat the semi and return.
1582 if (Lex.getCode() == tgtok::semi) {
1587 if (Lex.getCode() != tgtok::l_brace)
1588 return TokError("Expected ';' or '{' to start body");
1592 while (Lex.getCode() != tgtok::r_brace)
1593 if (ParseBodyItem(CurRec))
1601 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1602 /// optional ClassList followed by a Body. CurRec is the current def or class
1603 /// that is being parsed.
1605 /// ObjectBody ::= BaseClassList Body
1606 /// BaseClassList ::= /*empty*/
1607 /// BaseClassList ::= ':' BaseClassListNE
1608 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1610 bool TGParser::ParseObjectBody(Record *CurRec) {
1611 // If there is a baseclass list, read it.
1612 if (Lex.getCode() == tgtok::colon) {
1615 // Read all of the subclasses.
1616 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1619 if (SubClass.Rec == 0) return true;
1622 if (AddSubClass(CurRec, SubClass))
1625 if (Lex.getCode() != tgtok::comma) break;
1626 Lex.Lex(); // eat ','.
1627 SubClass = ParseSubClassReference(CurRec, false);
1631 // Process any variables on the let stack.
1632 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1633 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1634 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1635 LetStack[i][j].Bits, LetStack[i][j].Value))
1638 return ParseBody(CurRec);
1641 /// ParseDef - Parse and return a top level or multiclass def, return the record
1642 /// corresponding to it. This returns null on error.
1644 /// DefInst ::= DEF ObjectName ObjectBody
1646 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1647 SMLoc DefLoc = Lex.getLoc();
1648 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1649 Lex.Lex(); // Eat the 'def' token.
1651 // Parse ObjectName and make a record for it.
1652 Record *CurRec = new Record(ParseObjectName(), DefLoc);
1654 if (!CurMultiClass) {
1655 // Top-level def definition.
1657 // Ensure redefinition doesn't happen.
1658 if (Records.getDef(CurRec->getName())) {
1659 Error(DefLoc, "def '" + CurRec->getName() + "' already defined");
1662 Records.addDef(CurRec);
1664 // Otherwise, a def inside a multiclass, add it to the multiclass.
1665 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1666 if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
1667 Error(DefLoc, "def '" + CurRec->getName() +
1668 "' already defined in this multiclass!");
1671 CurMultiClass->DefPrototypes.push_back(CurRec);
1674 if (ParseObjectBody(CurRec))
1677 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1678 CurRec->resolveReferences();
1680 // If ObjectBody has template arguments, it's an error.
1681 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1683 if (CurMultiClass) {
1684 // Copy the template arguments for the multiclass into the def.
1685 const std::vector<std::string> &TArgs =
1686 CurMultiClass->Rec.getTemplateArgs();
1688 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1689 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1690 assert(RV && "Template arg doesn't exist?");
1691 CurRec->addValue(*RV);
1699 /// ParseClass - Parse a tblgen class definition.
1701 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1703 bool TGParser::ParseClass() {
1704 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1707 if (Lex.getCode() != tgtok::Id)
1708 return TokError("expected class name after 'class' keyword");
1710 Record *CurRec = Records.getClass(Lex.getCurStrVal());
1712 // If the body was previously defined, this is an error.
1713 if (!CurRec->getValues().empty() ||
1714 !CurRec->getSuperClasses().empty() ||
1715 !CurRec->getTemplateArgs().empty())
1716 return TokError("Class '" + CurRec->getName() + "' already defined");
1718 // If this is the first reference to this class, create and add it.
1719 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc());
1720 Records.addClass(CurRec);
1722 Lex.Lex(); // eat the name.
1724 // If there are template args, parse them.
1725 if (Lex.getCode() == tgtok::less)
1726 if (ParseTemplateArgList(CurRec))
1729 // Finally, parse the object body.
1730 return ParseObjectBody(CurRec);
1733 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1736 /// LetList ::= LetItem (',' LetItem)*
1737 /// LetItem ::= ID OptionalRangeList '=' Value
1739 std::vector<LetRecord> TGParser::ParseLetList() {
1740 std::vector<LetRecord> Result;
1743 if (Lex.getCode() != tgtok::Id) {
1744 TokError("expected identifier in let definition");
1745 return std::vector<LetRecord>();
1747 std::string Name = Lex.getCurStrVal();
1748 SMLoc NameLoc = Lex.getLoc();
1749 Lex.Lex(); // Eat the identifier.
1751 // Check for an optional RangeList.
1752 std::vector<unsigned> Bits;
1753 if (ParseOptionalRangeList(Bits))
1754 return std::vector<LetRecord>();
1755 std::reverse(Bits.begin(), Bits.end());
1757 if (Lex.getCode() != tgtok::equal) {
1758 TokError("expected '=' in let expression");
1759 return std::vector<LetRecord>();
1761 Lex.Lex(); // eat the '='.
1763 Init *Val = ParseValue(0);
1764 if (Val == 0) return std::vector<LetRecord>();
1766 // Now that we have everything, add the record.
1767 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1769 if (Lex.getCode() != tgtok::comma)
1771 Lex.Lex(); // eat the comma.
1775 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
1776 /// different related productions. This works inside multiclasses too.
1778 /// Object ::= LET LetList IN '{' ObjectList '}'
1779 /// Object ::= LET LetList IN Object
1781 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
1782 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1785 // Add this entry to the let stack.
1786 std::vector<LetRecord> LetInfo = ParseLetList();
1787 if (LetInfo.empty()) return true;
1788 LetStack.push_back(LetInfo);
1790 if (Lex.getCode() != tgtok::In)
1791 return TokError("expected 'in' at end of top-level 'let'");
1794 // If this is a scalar let, just handle it now
1795 if (Lex.getCode() != tgtok::l_brace) {
1796 // LET LetList IN Object
1797 if (ParseObject(CurMultiClass))
1799 } else { // Object ::= LETCommand '{' ObjectList '}'
1800 SMLoc BraceLoc = Lex.getLoc();
1801 // Otherwise, this is a group let.
1802 Lex.Lex(); // eat the '{'.
1804 // Parse the object list.
1805 if (ParseObjectList(CurMultiClass))
1808 if (Lex.getCode() != tgtok::r_brace) {
1809 TokError("expected '}' at end of top level let command");
1810 return Error(BraceLoc, "to match this '{'");
1815 // Outside this let scope, this let block is not active.
1816 LetStack.pop_back();
1820 /// ParseMultiClass - Parse a multiclass definition.
1822 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
1823 /// ':' BaseMultiClassList '{' MultiClassDef+ '}'
1825 bool TGParser::ParseMultiClass() {
1826 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1827 Lex.Lex(); // Eat the multiclass token.
1829 if (Lex.getCode() != tgtok::Id)
1830 return TokError("expected identifier after multiclass for name");
1831 std::string Name = Lex.getCurStrVal();
1833 if (MultiClasses.count(Name))
1834 return TokError("multiclass '" + Name + "' already defined");
1836 CurMultiClass = MultiClasses[Name] = new MultiClass(Name, Lex.getLoc());
1837 Lex.Lex(); // Eat the identifier.
1839 // If there are template args, parse them.
1840 if (Lex.getCode() == tgtok::less)
1841 if (ParseTemplateArgList(0))
1844 bool inherits = false;
1846 // If there are submulticlasses, parse them.
1847 if (Lex.getCode() == tgtok::colon) {
1852 // Read all of the submulticlasses.
1853 SubMultiClassReference SubMultiClass =
1854 ParseSubMultiClassReference(CurMultiClass);
1857 if (SubMultiClass.MC == 0) return true;
1860 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
1863 if (Lex.getCode() != tgtok::comma) break;
1864 Lex.Lex(); // eat ','.
1865 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
1869 if (Lex.getCode() != tgtok::l_brace) {
1871 return TokError("expected '{' in multiclass definition");
1872 else if (Lex.getCode() != tgtok::semi)
1873 return TokError("expected ';' in multiclass definition");
1875 Lex.Lex(); // eat the ';'.
1877 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
1878 return TokError("multiclass must contain at least one def");
1880 while (Lex.getCode() != tgtok::r_brace) {
1881 switch (Lex.getCode()) {
1883 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
1887 if (ParseObject(CurMultiClass))
1892 Lex.Lex(); // eat the '}'.
1899 /// ParseDefm - Parse the instantiation of a multiclass.
1901 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
1903 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
1904 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
1906 std::string DefmPrefix;
1907 if (Lex.Lex() == tgtok::Id) { // eat the defm.
1908 DefmPrefix = Lex.getCurStrVal();
1909 Lex.Lex(); // Eat the defm prefix.
1912 SMLoc DefmPrefixLoc = Lex.getLoc();
1913 if (Lex.getCode() != tgtok::colon)
1914 return TokError("expected ':' after defm identifier");
1916 // Keep track of the new generated record definitions.
1917 std::vector<Record*> NewRecDefs;
1919 // This record also inherits from a regular class (non-multiclass)?
1920 bool InheritFromClass = false;
1925 SMLoc SubClassLoc = Lex.getLoc();
1926 SubClassReference Ref = ParseSubClassReference(0, true);
1929 if (Ref.Rec == 0) return true;
1931 // To instantiate a multiclass, we need to first get the multiclass, then
1932 // instantiate each def contained in the multiclass with the SubClassRef
1933 // template parameters.
1934 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
1935 assert(MC && "Didn't lookup multiclass correctly?");
1936 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
1938 // Verify that the correct number of template arguments were specified.
1939 const std::vector<std::string> &TArgs = MC->Rec.getTemplateArgs();
1940 if (TArgs.size() < TemplateVals.size())
1941 return Error(SubClassLoc,
1942 "more template args specified than multiclass expects");
1944 // Loop over all the def's in the multiclass, instantiating each one.
1945 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
1946 Record *DefProto = MC->DefPrototypes[i];
1948 // Add in the defm name. If the defm prefix is empty, give each
1949 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
1950 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
1952 std::string DefName = DefProto->getName();
1953 if (DefmPrefix.empty()) {
1954 DefName = GetNewAnonymousName();
1956 std::string::size_type idx = DefName.find("#NAME#");
1957 if (idx != std::string::npos) {
1958 DefName.replace(idx, 6, DefmPrefix);
1960 // Add the suffix to the defm name to get the new name.
1961 DefName = DefmPrefix + DefName;
1965 Record *CurRec = new Record(DefName, DefmPrefixLoc);
1967 SubClassReference Ref;
1968 Ref.RefLoc = DefmPrefixLoc;
1970 AddSubClass(CurRec, Ref);
1972 // Loop over all of the template arguments, setting them to the specified
1973 // value or leaving them as the default if necessary.
1974 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1975 // Check if a value is specified for this temp-arg.
1976 if (i < TemplateVals.size()) {
1978 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
1983 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
1986 CurRec->removeValue(TArgs[i]);
1988 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
1989 return Error(SubClassLoc,
1990 "value not specified for template argument #"+
1991 utostr(i) + " (" + TArgs[i] + ") of multiclassclass '" +
1992 MC->Rec.getName() + "'");
1996 // If the mdef is inside a 'let' expression, add to each def.
1997 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1998 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1999 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2000 LetStack[i][j].Bits, LetStack[i][j].Value)) {
2001 Error(DefmPrefixLoc, "when instantiating this defm");
2005 // Ensure redefinition doesn't happen.
2006 if (Records.getDef(CurRec->getName()))
2007 return Error(DefmPrefixLoc, "def '" + CurRec->getName() +
2008 "' already defined, instantiating defm with subdef '" +
2009 DefProto->getName() + "'");
2011 // Don't create a top level definition for defm inside multiclasses,
2012 // instead, only update the prototypes and bind the template args
2013 // with the new created definition.
2014 if (CurMultiClass) {
2015 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2017 if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
2018 Error(DefmPrefixLoc, "defm '" + CurRec->getName() +
2019 "' already defined in this multiclass!");
2023 CurMultiClass->DefPrototypes.push_back(CurRec);
2025 // Copy the template arguments for the multiclass into the new def.
2026 const std::vector<std::string> &TA =
2027 CurMultiClass->Rec.getTemplateArgs();
2029 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2030 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2031 assert(RV && "Template arg doesn't exist?");
2032 CurRec->addValue(*RV);
2035 Records.addDef(CurRec);
2038 NewRecDefs.push_back(CurRec);
2041 if (Lex.getCode() != tgtok::comma) break;
2042 Lex.Lex(); // eat ','.
2044 SubClassLoc = Lex.getLoc();
2046 // A defm can inherit from regular classes (non-multiclass) as
2047 // long as they come in the end of the inheritance list.
2048 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != 0);
2050 if (InheritFromClass)
2053 Ref = ParseSubClassReference(0, true);
2056 if (InheritFromClass) {
2057 // Process all the classes to inherit as if they were part of a
2058 // regular 'def' and inherit all record values.
2059 SubClassReference SubClass = ParseSubClassReference(0, false);
2062 if (SubClass.Rec == 0) return true;
2064 // Get the expanded definition prototypes and teach them about
2065 // the record values the current class to inherit has
2066 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2067 Record *CurRec = NewRecDefs[i];
2070 if (AddSubClass(CurRec, SubClass))
2073 // Process any variables on the let stack.
2074 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2075 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2076 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2077 LetStack[i][j].Bits, LetStack[i][j].Value))
2081 if (Lex.getCode() != tgtok::comma) break;
2082 Lex.Lex(); // eat ','.
2083 SubClass = ParseSubClassReference(0, false);
2088 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2089 NewRecDefs[i]->resolveReferences();
2091 if (Lex.getCode() != tgtok::semi)
2092 return TokError("expected ';' at end of defm");
2099 /// Object ::= ClassInst
2100 /// Object ::= DefInst
2101 /// Object ::= MultiClassInst
2102 /// Object ::= DefMInst
2103 /// Object ::= LETCommand '{' ObjectList '}'
2104 /// Object ::= LETCommand Object
2105 bool TGParser::ParseObject(MultiClass *MC) {
2106 switch (Lex.getCode()) {
2107 default: assert(0 && "This is not an object");
2108 case tgtok::Let: return ParseTopLevelLet(MC);
2109 case tgtok::Def: return ParseDef(MC);
2110 case tgtok::Defm: return ParseDefm(MC);
2111 case tgtok::Class: return ParseClass();
2112 case tgtok::MultiClass: return ParseMultiClass();
2117 /// ObjectList :== Object*
2118 bool TGParser::ParseObjectList(MultiClass *MC) {
2119 while (isObjectStart(Lex.getCode())) {
2120 if (ParseObject(MC))
2126 bool TGParser::ParseFile() {
2127 Lex.Lex(); // Prime the lexer.
2128 if (ParseObjectList()) return true;
2130 // If we have unread input at the end of the file, report it.
2131 if (Lex.getCode() == tgtok::Eof)
2134 return TokError("Unexpected input at top level");