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"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Support/CommandLine.h"
23 /// LLVMCHack - This is a temporary hack that changes how "(foo [1, 2, 3])"
25 /// FIXME: REMOVE THIS.
26 static cl::opt<bool> LLVMCHack("llvmc-temp-hack", cl::ReallyHidden);
28 //===----------------------------------------------------------------------===//
29 // Support Code for the Semantic Actions.
30 //===----------------------------------------------------------------------===//
33 struct SubClassReference {
36 std::vector<Init*> TemplateArgs;
37 SubClassReference() : Rec(0) {}
39 bool isInvalid() const { return Rec == 0; }
42 struct SubMultiClassReference {
45 std::vector<Init*> TemplateArgs;
46 SubMultiClassReference() : MC(0) {}
48 bool isInvalid() const { return MC == 0; }
52 void SubMultiClassReference::dump() const {
53 errs() << "Multiclass:\n";
57 errs() << "Template args:\n";
58 for (std::vector<Init *>::const_iterator i = TemplateArgs.begin(),
59 iend = TemplateArgs.end();
66 } // end namespace llvm
68 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
70 CurRec = &CurMultiClass->Rec;
72 if (RecordVal *ERV = CurRec->getValue(RV.getName())) {
73 // The value already exists in the class, treat this as a set.
74 if (ERV->setValue(RV.getValue()))
75 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
76 RV.getType()->getAsString() + "' is incompatible with " +
77 "previous definition of type '" +
78 ERV->getType()->getAsString() + "'");
86 /// Return true on error, false on success.
87 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, const std::string &ValName,
88 const std::vector<unsigned> &BitList, Init *V) {
91 if (CurRec == 0) CurRec = &CurMultiClass->Rec;
93 RecordVal *RV = CurRec->getValue(ValName);
95 return Error(Loc, "Value '" + ValName + "' unknown!");
97 // Do not allow assignments like 'X = X'. This will just cause infinite loops
98 // in the resolution machinery.
100 if (VarInit *VI = dynamic_cast<VarInit*>(V))
101 if (VI->getName() == ValName)
104 // If we are assigning to a subset of the bits in the value... then we must be
105 // assigning to a field of BitsRecTy, which must have a BitsInit
108 if (!BitList.empty()) {
109 BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
111 return Error(Loc, "Value '" + ValName + "' is not a bits type");
113 // Convert the incoming value to a bits type of the appropriate size...
114 Init *BI = V->convertInitializerTo(new BitsRecTy(BitList.size()));
116 V->convertInitializerTo(new BitsRecTy(BitList.size()));
117 return Error(Loc, "Initializer is not compatible with bit range");
120 // We should have a BitsInit type now.
121 BitsInit *BInit = dynamic_cast<BitsInit*>(BI);
124 BitsInit *NewVal = new BitsInit(CurVal->getNumBits());
126 // Loop over bits, assigning values as appropriate.
127 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
128 unsigned Bit = BitList[i];
129 if (NewVal->getBit(Bit))
130 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
131 ValName + "' more than once");
132 NewVal->setBit(Bit, BInit->getBit(i));
135 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
136 if (NewVal->getBit(i) == 0)
137 NewVal->setBit(i, CurVal->getBit(i));
143 return Error(Loc, "Value '" + ValName + "' of type '" +
144 RV->getType()->getAsString() +
145 "' is incompatible with initializer '" + V->getAsString() +"'");
149 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
150 /// args as SubClass's template arguments.
151 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
152 Record *SC = SubClass.Rec;
153 // Add all of the values in the subclass into the current class.
154 const std::vector<RecordVal> &Vals = SC->getValues();
155 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
156 if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
159 const std::vector<std::string> &TArgs = SC->getTemplateArgs();
161 // Ensure that an appropriate number of template arguments are specified.
162 if (TArgs.size() < SubClass.TemplateArgs.size())
163 return Error(SubClass.RefLoc, "More template args specified than expected");
165 // Loop over all of the template arguments, setting them to the specified
166 // value or leaving them as the default if necessary.
167 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
168 if (i < SubClass.TemplateArgs.size()) {
169 // If a value is specified for this template arg, set it now.
170 if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(),
171 SubClass.TemplateArgs[i]))
175 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
178 CurRec->removeValue(TArgs[i]);
180 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
181 return Error(SubClass.RefLoc,"Value not specified for template argument #"
182 + utostr(i) + " (" + TArgs[i] + ") of subclass '" +
183 SC->getName() + "'!");
187 // Since everything went well, we can now set the "superclass" list for the
189 const std::vector<Record*> &SCs = SC->getSuperClasses();
190 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
191 if (CurRec->isSubClassOf(SCs[i]))
192 return Error(SubClass.RefLoc,
193 "Already subclass of '" + SCs[i]->getName() + "'!\n");
194 CurRec->addSuperClass(SCs[i]);
197 if (CurRec->isSubClassOf(SC))
198 return Error(SubClass.RefLoc,
199 "Already subclass of '" + SC->getName() + "'!\n");
200 CurRec->addSuperClass(SC);
204 /// AddSubMultiClass - Add SubMultiClass as a subclass to
205 /// CurMC, resolving its template args as SubMultiClass's
206 /// template arguments.
207 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
208 SubMultiClassReference &SubMultiClass) {
209 MultiClass *SMC = SubMultiClass.MC;
210 Record *CurRec = &CurMC->Rec;
212 const std::vector<RecordVal> &MCVals = CurRec->getValues();
214 // Add all of the values in the subclass into the current class.
215 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
216 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
217 if (AddValue(CurRec, SubMultiClass.RefLoc, SMCVals[i]))
220 int newDefStart = CurMC->DefPrototypes.size();
222 // Add all of the defs in the subclass into the current multiclass.
223 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
224 iend = SMC->DefPrototypes.end();
227 // Clone the def and add it to the current multiclass
228 Record *NewDef = new Record(**i);
230 // Add all of the values in the superclass into the current def.
231 for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
232 if (AddValue(NewDef, SubMultiClass.RefLoc, MCVals[i]))
235 CurMC->DefPrototypes.push_back(NewDef);
238 const std::vector<std::string> &SMCTArgs = SMC->Rec.getTemplateArgs();
240 // Ensure that an appropriate number of template arguments are
242 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
243 return Error(SubMultiClass.RefLoc,
244 "More template args specified than expected");
246 // Loop over all of the template arguments, setting them to the specified
247 // value or leaving them as the default if necessary.
248 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
249 if (i < SubMultiClass.TemplateArgs.size()) {
250 // If a value is specified for this template arg, set it in the
252 if (SetValue(CurRec, SubMultiClass.RefLoc, SMCTArgs[i],
253 std::vector<unsigned>(),
254 SubMultiClass.TemplateArgs[i]))
258 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
261 CurRec->removeValue(SMCTArgs[i]);
263 // If a value is specified for this template arg, set it in the
265 for (MultiClass::RecordVector::iterator j =
266 CurMC->DefPrototypes.begin() + newDefStart,
267 jend = CurMC->DefPrototypes.end();
272 if (SetValue(Def, SubMultiClass.RefLoc, SMCTArgs[i],
273 std::vector<unsigned>(),
274 SubMultiClass.TemplateArgs[i]))
278 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
281 Def->removeValue(SMCTArgs[i]);
283 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
284 return Error(SubMultiClass.RefLoc,
285 "Value not specified for template argument #"
286 + utostr(i) + " (" + SMCTArgs[i] + ") of subclass '" +
287 SMC->Rec.getName() + "'!");
294 //===----------------------------------------------------------------------===//
296 //===----------------------------------------------------------------------===//
298 /// isObjectStart - Return true if this is a valid first token for an Object.
299 static bool isObjectStart(tgtok::TokKind K) {
300 return K == tgtok::Class || K == tgtok::Def ||
301 K == tgtok::Defm || K == tgtok::Let || K == tgtok::MultiClass;
304 static std::string GetNewAnonymousName() {
305 static unsigned AnonCounter = 0;
306 return "anonymous."+utostr(AnonCounter++);
309 /// ParseObjectName - If an object name is specified, return it. Otherwise,
310 /// return an anonymous name.
311 /// ObjectName ::= ID
312 /// ObjectName ::= /*empty*/
314 std::string TGParser::ParseObjectName() {
315 if (Lex.getCode() != tgtok::Id)
316 return GetNewAnonymousName();
318 std::string Ret = Lex.getCurStrVal();
324 /// ParseClassID - Parse and resolve a reference to a class name. This returns
329 Record *TGParser::ParseClassID() {
330 if (Lex.getCode() != tgtok::Id) {
331 TokError("expected name for ClassID");
335 Record *Result = Records.getClass(Lex.getCurStrVal());
337 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
343 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
344 /// This returns null on error.
346 /// MultiClassID ::= ID
348 MultiClass *TGParser::ParseMultiClassID() {
349 if (Lex.getCode() != tgtok::Id) {
350 TokError("expected name for ClassID");
354 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
356 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
362 Record *TGParser::ParseDefmID() {
363 if (Lex.getCode() != tgtok::Id) {
364 TokError("expected multiclass name");
368 MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
370 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
379 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
380 /// subclass. This returns a SubClassRefTy with a null Record* on error.
382 /// SubClassRef ::= ClassID
383 /// SubClassRef ::= ClassID '<' ValueList '>'
385 SubClassReference TGParser::
386 ParseSubClassReference(Record *CurRec, bool isDefm) {
387 SubClassReference Result;
388 Result.RefLoc = Lex.getLoc();
391 Result.Rec = ParseDefmID();
393 Result.Rec = ParseClassID();
394 if (Result.Rec == 0) return Result;
396 // If there is no template arg list, we're done.
397 if (Lex.getCode() != tgtok::less)
399 Lex.Lex(); // Eat the '<'
401 if (Lex.getCode() == tgtok::greater) {
402 TokError("subclass reference requires a non-empty list of template values");
407 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
408 if (Result.TemplateArgs.empty()) {
409 Result.Rec = 0; // Error parsing value list.
413 if (Lex.getCode() != tgtok::greater) {
414 TokError("expected '>' in template value list");
423 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
424 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
425 /// Record* on error.
427 /// SubMultiClassRef ::= MultiClassID
428 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
430 SubMultiClassReference TGParser::
431 ParseSubMultiClassReference(MultiClass *CurMC) {
432 SubMultiClassReference Result;
433 Result.RefLoc = Lex.getLoc();
435 Result.MC = ParseMultiClassID();
436 if (Result.MC == 0) return Result;
438 // If there is no template arg list, we're done.
439 if (Lex.getCode() != tgtok::less)
441 Lex.Lex(); // Eat the '<'
443 if (Lex.getCode() == tgtok::greater) {
444 TokError("subclass reference requires a non-empty list of template values");
449 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
450 if (Result.TemplateArgs.empty()) {
451 Result.MC = 0; // Error parsing value list.
455 if (Lex.getCode() != tgtok::greater) {
456 TokError("expected '>' in template value list");
465 /// ParseRangePiece - Parse a bit/value range.
466 /// RangePiece ::= INTVAL
467 /// RangePiece ::= INTVAL '-' INTVAL
468 /// RangePiece ::= INTVAL INTVAL
469 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
470 if (Lex.getCode() != tgtok::IntVal) {
471 TokError("expected integer or bitrange");
474 int64_t Start = Lex.getCurIntVal();
478 return TokError("invalid range, cannot be negative");
480 switch (Lex.Lex()) { // eat first character.
482 Ranges.push_back(Start);
485 if (Lex.Lex() != tgtok::IntVal) {
486 TokError("expected integer value as end of range");
489 End = Lex.getCurIntVal();
492 End = -Lex.getCurIntVal();
496 return TokError("invalid range, cannot be negative");
501 for (; Start <= End; ++Start)
502 Ranges.push_back(Start);
504 for (; Start >= End; --Start)
505 Ranges.push_back(Start);
510 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
512 /// RangeList ::= RangePiece (',' RangePiece)*
514 std::vector<unsigned> TGParser::ParseRangeList() {
515 std::vector<unsigned> Result;
517 // Parse the first piece.
518 if (ParseRangePiece(Result))
519 return std::vector<unsigned>();
520 while (Lex.getCode() == tgtok::comma) {
521 Lex.Lex(); // Eat the comma.
523 // Parse the next range piece.
524 if (ParseRangePiece(Result))
525 return std::vector<unsigned>();
530 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
531 /// OptionalRangeList ::= '<' RangeList '>'
532 /// OptionalRangeList ::= /*empty*/
533 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
534 if (Lex.getCode() != tgtok::less)
537 SMLoc StartLoc = Lex.getLoc();
538 Lex.Lex(); // eat the '<'
540 // Parse the range list.
541 Ranges = ParseRangeList();
542 if (Ranges.empty()) return true;
544 if (Lex.getCode() != tgtok::greater) {
545 TokError("expected '>' at end of range list");
546 return Error(StartLoc, "to match this '<'");
548 Lex.Lex(); // eat the '>'.
552 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
553 /// OptionalBitList ::= '{' RangeList '}'
554 /// OptionalBitList ::= /*empty*/
555 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
556 if (Lex.getCode() != tgtok::l_brace)
559 SMLoc StartLoc = Lex.getLoc();
560 Lex.Lex(); // eat the '{'
562 // Parse the range list.
563 Ranges = ParseRangeList();
564 if (Ranges.empty()) return true;
566 if (Lex.getCode() != tgtok::r_brace) {
567 TokError("expected '}' at end of bit list");
568 return Error(StartLoc, "to match this '{'");
570 Lex.Lex(); // eat the '}'.
575 /// ParseType - Parse and return a tblgen type. This returns null on error.
577 /// Type ::= STRING // string type
578 /// Type ::= BIT // bit type
579 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
580 /// Type ::= INT // int type
581 /// Type ::= LIST '<' Type '>' // list<x> type
582 /// Type ::= CODE // code type
583 /// Type ::= DAG // dag type
584 /// Type ::= ClassID // Record Type
586 RecTy *TGParser::ParseType() {
587 switch (Lex.getCode()) {
588 default: TokError("Unknown token when expecting a type"); return 0;
589 case tgtok::String: Lex.Lex(); return new StringRecTy();
590 case tgtok::Bit: Lex.Lex(); return new BitRecTy();
591 case tgtok::Int: Lex.Lex(); return new IntRecTy();
592 case tgtok::Code: Lex.Lex(); return new CodeRecTy();
593 case tgtok::Dag: Lex.Lex(); return new DagRecTy();
595 if (Record *R = ParseClassID()) return new RecordRecTy(R);
598 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
599 TokError("expected '<' after bits type");
602 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
603 TokError("expected integer in bits<n> type");
606 uint64_t Val = Lex.getCurIntVal();
607 if (Lex.Lex() != tgtok::greater) { // Eat count.
608 TokError("expected '>' at end of bits<n> type");
611 Lex.Lex(); // Eat '>'
612 return new BitsRecTy(Val);
615 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
616 TokError("expected '<' after list type");
619 Lex.Lex(); // Eat '<'
620 RecTy *SubType = ParseType();
621 if (SubType == 0) return 0;
623 if (Lex.getCode() != tgtok::greater) {
624 TokError("expected '>' at end of list<ty> type");
627 Lex.Lex(); // Eat '>'
628 return new ListRecTy(SubType);
633 /// ParseIDValue - Parse an ID as a value and decode what it means.
635 /// IDValue ::= ID [def local value]
636 /// IDValue ::= ID [def template arg]
637 /// IDValue ::= ID [multiclass local value]
638 /// IDValue ::= ID [multiclass template argument]
639 /// IDValue ::= ID [def name]
641 Init *TGParser::ParseIDValue(Record *CurRec) {
642 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
643 std::string Name = Lex.getCurStrVal();
644 SMLoc Loc = Lex.getLoc();
646 return ParseIDValue(CurRec, Name, Loc);
649 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
650 /// has already been read.
651 Init *TGParser::ParseIDValue(Record *CurRec,
652 const std::string &Name, SMLoc NameLoc) {
654 if (const RecordVal *RV = CurRec->getValue(Name))
655 return new VarInit(Name, RV->getType());
657 std::string TemplateArgName = CurRec->getName()+":"+Name;
658 if (CurRec->isTemplateArg(TemplateArgName)) {
659 const RecordVal *RV = CurRec->getValue(TemplateArgName);
660 assert(RV && "Template arg doesn't exist??");
661 return new VarInit(TemplateArgName, RV->getType());
666 std::string MCName = CurMultiClass->Rec.getName()+"::"+Name;
667 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
668 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
669 assert(RV && "Template arg doesn't exist??");
670 return new VarInit(MCName, RV->getType());
674 if (Record *D = Records.getDef(Name))
675 return new DefInit(D);
677 Error(NameLoc, "Variable not defined: '" + Name + "'");
681 /// ParseOperation - Parse an operator. This returns null on error.
683 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
685 Init *TGParser::ParseOperation(Record *CurRec) {
686 switch (Lex.getCode()) {
688 TokError("unknown operation");
694 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
695 UnOpInit::UnaryOp Code;
698 switch (Lex.getCode()) {
699 default: assert(0 && "Unhandled code!");
701 Lex.Lex(); // eat the operation
702 Code = UnOpInit::CAST;
704 Type = ParseOperatorType();
707 TokError("did not get type for unary operator");
713 Lex.Lex(); // eat the operation
714 Code = UnOpInit::CAR;
717 Lex.Lex(); // eat the operation
718 Code = UnOpInit::CDR;
721 Lex.Lex(); // eat the operation
722 Code = UnOpInit::LNULL;
726 if (Lex.getCode() != tgtok::l_paren) {
727 TokError("expected '(' after unary operator");
730 Lex.Lex(); // eat the '('
732 Init *LHS = ParseValue(CurRec);
733 if (LHS == 0) return 0;
735 if (Code == UnOpInit::CAR
736 || Code == UnOpInit::CDR
737 || Code == UnOpInit::LNULL) {
738 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
739 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
740 TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
741 if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
742 TokError("expected list or string type argument in unary operator");
746 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
747 StringRecTy *SType = dynamic_cast<StringRecTy*>(LHSt->getType());
748 if (LType == 0 && SType == 0) {
749 TokError("expected list or string type argumnet in unary operator");
754 if (Code == UnOpInit::CAR
755 || Code == UnOpInit::CDR) {
756 if (LHSl == 0 && LHSt == 0) {
757 TokError("expected list type argumnet in unary operator");
761 if (LHSl && LHSl->getSize() == 0) {
762 TokError("empty list argument in unary operator");
766 Init *Item = LHSl->getElement(0);
767 TypedInit *Itemt = dynamic_cast<TypedInit*>(Item);
769 TokError("untyped list element in unary operator");
772 if (Code == UnOpInit::CAR) {
773 Type = Itemt->getType();
775 Type = new ListRecTy(Itemt->getType());
778 assert(LHSt && "expected list type argument in unary operator");
779 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
781 TokError("expected list type argumnet in unary operator");
784 if (Code == UnOpInit::CAR) {
785 Type = LType->getElementType();
793 if (Lex.getCode() != tgtok::r_paren) {
794 TokError("expected ')' in unary operator");
797 Lex.Lex(); // eat the ')'
798 return (new UnOpInit(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
806 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
807 tgtok::TokKind OpTok = Lex.getCode();
808 SMLoc OpLoc = Lex.getLoc();
809 Lex.Lex(); // eat the operation
811 BinOpInit::BinaryOp Code;
815 default: assert(0 && "Unhandled code!");
816 case tgtok::XConcat: Code = BinOpInit::CONCAT; Type = new DagRecTy(); break;
817 case tgtok::XSRA: Code = BinOpInit::SRA; Type = new IntRecTy(); break;
818 case tgtok::XSRL: Code = BinOpInit::SRL; Type = new IntRecTy(); break;
819 case tgtok::XSHL: Code = BinOpInit::SHL; Type = new IntRecTy(); break;
820 case tgtok::XEq: Code = BinOpInit::EQ; Type = new IntRecTy(); break;
821 case tgtok::XStrConcat:
822 Code = BinOpInit::STRCONCAT;
823 Type = new StringRecTy();
827 if (Lex.getCode() != tgtok::l_paren) {
828 TokError("expected '(' after binary operator");
831 Lex.Lex(); // eat the '('
833 SmallVector<Init*, 2> InitList;
835 InitList.push_back(ParseValue(CurRec));
836 if (InitList.back() == 0) return 0;
838 while (Lex.getCode() == tgtok::comma) {
839 Lex.Lex(); // eat the ','
841 InitList.push_back(ParseValue(CurRec));
842 if (InitList.back() == 0) return 0;
845 if (Lex.getCode() != tgtok::r_paren) {
846 TokError("expected ')' in operator");
849 Lex.Lex(); // eat the ')'
851 // We allow multiple operands to associative operators like !strconcat as
852 // shorthand for nesting them.
853 if (Code == BinOpInit::STRCONCAT) {
854 while (InitList.size() > 2) {
855 Init *RHS = InitList.pop_back_val();
856 RHS = (new BinOpInit(Code, InitList.back(), RHS, Type))
857 ->Fold(CurRec, CurMultiClass);
858 InitList.back() = RHS;
862 if (InitList.size() == 2)
863 return (new BinOpInit(Code, InitList[0], InitList[1], Type))
864 ->Fold(CurRec, CurMultiClass);
866 Error(OpLoc, "expected two operands to operator");
871 case tgtok::XForEach:
872 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
873 TernOpInit::TernaryOp Code;
877 tgtok::TokKind LexCode = Lex.getCode();
878 Lex.Lex(); // eat the operation
880 default: assert(0 && "Unhandled code!");
882 Code = TernOpInit::IF;
884 case tgtok::XForEach:
885 Code = TernOpInit::FOREACH;
888 Code = TernOpInit::SUBST;
891 if (Lex.getCode() != tgtok::l_paren) {
892 TokError("expected '(' after ternary operator");
895 Lex.Lex(); // eat the '('
897 Init *LHS = ParseValue(CurRec);
898 if (LHS == 0) return 0;
900 if (Lex.getCode() != tgtok::comma) {
901 TokError("expected ',' in ternary operator");
904 Lex.Lex(); // eat the ','
906 Init *MHS = ParseValue(CurRec);
907 if (MHS == 0) return 0;
909 if (Lex.getCode() != tgtok::comma) {
910 TokError("expected ',' in ternary operator");
913 Lex.Lex(); // eat the ','
915 Init *RHS = ParseValue(CurRec);
916 if (RHS == 0) return 0;
918 if (Lex.getCode() != tgtok::r_paren) {
919 TokError("expected ')' in binary operator");
922 Lex.Lex(); // eat the ')'
925 default: assert(0 && "Unhandled code!");
927 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
928 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
929 if (MHSt == 0 || RHSt == 0) {
930 TokError("could not get type for !if");
933 if (MHSt->getType()->typeIsConvertibleTo(RHSt->getType())) {
934 Type = RHSt->getType();
935 } else if (RHSt->getType()->typeIsConvertibleTo(MHSt->getType())) {
936 Type = MHSt->getType();
938 TokError("inconsistent types for !if");
943 case tgtok::XForEach: {
944 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
946 TokError("could not get type for !foreach");
949 Type = MHSt->getType();
952 case tgtok::XSubst: {
953 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
955 TokError("could not get type for !subst");
958 Type = RHSt->getType();
962 return (new TernOpInit(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
966 TokError("could not parse operation");
970 /// ParseOperatorType - Parse a type for an operator. This returns
973 /// OperatorType ::= '<' Type '>'
975 RecTy *TGParser::ParseOperatorType() {
978 if (Lex.getCode() != tgtok::less) {
979 TokError("expected type name for operator");
982 Lex.Lex(); // eat the <
987 TokError("expected type name for operator");
991 if (Lex.getCode() != tgtok::greater) {
992 TokError("expected type name for operator");
995 Lex.Lex(); // eat the >
1001 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1003 /// SimpleValue ::= IDValue
1004 /// SimpleValue ::= INTVAL
1005 /// SimpleValue ::= STRVAL+
1006 /// SimpleValue ::= CODEFRAGMENT
1007 /// SimpleValue ::= '?'
1008 /// SimpleValue ::= '{' ValueList '}'
1009 /// SimpleValue ::= ID '<' ValueListNE '>'
1010 /// SimpleValue ::= '[' ValueList ']'
1011 /// SimpleValue ::= '(' IDValue DagArgList ')'
1012 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1013 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1014 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1015 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1016 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1018 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType) {
1020 switch (Lex.getCode()) {
1021 default: TokError("Unknown token when parsing a value"); break;
1022 case tgtok::IntVal: R = new IntInit(Lex.getCurIntVal()); Lex.Lex(); break;
1023 case tgtok::StrVal: {
1024 std::string Val = Lex.getCurStrVal();
1027 // Handle multiple consecutive concatenated strings.
1028 while (Lex.getCode() == tgtok::StrVal) {
1029 Val += Lex.getCurStrVal();
1033 R = new StringInit(Val);
1036 case tgtok::CodeFragment:
1037 R = new CodeInit(Lex.getCurStrVal());
1040 case tgtok::question:
1041 R = new UnsetInit();
1045 SMLoc NameLoc = Lex.getLoc();
1046 std::string Name = Lex.getCurStrVal();
1047 if (Lex.Lex() != tgtok::less) // consume the Id.
1048 return ParseIDValue(CurRec, Name, NameLoc); // Value ::= IDValue
1050 // Value ::= ID '<' ValueListNE '>'
1051 if (Lex.Lex() == tgtok::greater) {
1052 TokError("expected non-empty value list");
1056 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1057 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1059 Record *Class = Records.getClass(Name);
1061 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1065 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1066 if (ValueList.empty()) return 0;
1068 if (Lex.getCode() != tgtok::greater) {
1069 TokError("expected '>' at end of value list");
1072 Lex.Lex(); // eat the '>'
1074 // Create the new record, set it as CurRec temporarily.
1075 static unsigned AnonCounter = 0;
1076 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),NameLoc);
1077 SubClassReference SCRef;
1078 SCRef.RefLoc = NameLoc;
1080 SCRef.TemplateArgs = ValueList;
1081 // Add info about the subclass to NewRec.
1082 if (AddSubClass(NewRec, SCRef))
1084 NewRec->resolveReferences();
1085 Records.addDef(NewRec);
1087 // The result of the expression is a reference to the new record.
1088 return new DefInit(NewRec);
1090 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1091 SMLoc BraceLoc = Lex.getLoc();
1092 Lex.Lex(); // eat the '{'
1093 std::vector<Init*> Vals;
1095 if (Lex.getCode() != tgtok::r_brace) {
1096 Vals = ParseValueList(CurRec);
1097 if (Vals.empty()) return 0;
1099 if (Lex.getCode() != tgtok::r_brace) {
1100 TokError("expected '}' at end of bit list value");
1103 Lex.Lex(); // eat the '}'
1105 BitsInit *Result = new BitsInit(Vals.size());
1106 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1107 Init *Bit = Vals[i]->convertInitializerTo(new BitRecTy());
1109 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1110 ") is not convertable to a bit");
1113 Result->setBit(Vals.size()-i-1, Bit);
1117 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1118 Lex.Lex(); // eat the '['
1119 std::vector<Init*> Vals;
1121 RecTy *DeducedEltTy = 0;
1122 ListRecTy *GivenListTy = 0;
1124 if (ItemType != 0) {
1125 ListRecTy *ListType = dynamic_cast<ListRecTy*>(ItemType);
1126 if (ListType == 0) {
1127 std::stringstream s;
1128 s << "Type mismatch for list, expected list type, got "
1129 << ItemType->getAsString();
1132 GivenListTy = ListType;
1135 if (Lex.getCode() != tgtok::r_square) {
1136 Vals = ParseValueList(CurRec, 0,
1137 GivenListTy ? GivenListTy->getElementType() : 0);
1138 if (Vals.empty()) return 0;
1140 if (Lex.getCode() != tgtok::r_square) {
1141 TokError("expected ']' at end of list value");
1144 Lex.Lex(); // eat the ']'
1146 RecTy *GivenEltTy = 0;
1147 if (Lex.getCode() == tgtok::less) {
1148 // Optional list element type
1149 Lex.Lex(); // eat the '<'
1151 GivenEltTy = ParseType();
1152 if (GivenEltTy == 0) {
1153 // Couldn't parse element type
1157 if (Lex.getCode() != tgtok::greater) {
1158 TokError("expected '>' at end of list element type");
1161 Lex.Lex(); // eat the '>'
1166 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1169 TypedInit *TArg = dynamic_cast<TypedInit*>(*i);
1171 TokError("Untyped list element");
1175 EltTy = resolveTypes(EltTy, TArg->getType());
1177 TokError("Incompatible types in list elements");
1181 EltTy = TArg->getType();
1185 if (GivenEltTy != 0) {
1187 // Verify consistency
1188 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1189 TokError("Incompatible types in list elements");
1197 if (ItemType == 0) {
1198 TokError("No type for list");
1201 DeducedEltTy = GivenListTy->getElementType();
1203 // Make sure the deduced type is compatible with the given type
1205 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1206 TokError("Element type mismatch for list");
1210 DeducedEltTy = EltTy;
1213 return new ListInit(Vals, DeducedEltTy);
1215 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1216 Lex.Lex(); // eat the '('
1217 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1218 TokError("expected identifier in dag init");
1223 /// LLVMC Requires an old grammar and I don't know how to update it, placate
1224 /// it in the short term by changing the grammar specifically for llvmc.
1225 /// FIXME: REMOVE THIS.
1227 Operator = ParseValue(CurRec);
1229 if (Lex.getCode() == tgtok::Id)
1230 Operator = ParseIDValue(CurRec);
1232 Operator = ParseOperation(CurRec);
1234 if (Operator == 0) return 0;
1236 // If the operator name is present, parse it.
1237 std::string OperatorName;
1238 if (Lex.getCode() == tgtok::colon) {
1239 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1240 TokError("expected variable name in dag operator");
1243 OperatorName = Lex.getCurStrVal();
1244 Lex.Lex(); // eat the VarName.
1247 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1248 if (Lex.getCode() != tgtok::r_paren) {
1249 DagArgs = ParseDagArgList(CurRec);
1250 if (DagArgs.empty()) return 0;
1253 if (Lex.getCode() != tgtok::r_paren) {
1254 TokError("expected ')' in dag init");
1257 Lex.Lex(); // eat the ')'
1259 return new DagInit(Operator, OperatorName, DagArgs);
1265 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1266 case tgtok::XConcat:
1271 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1273 case tgtok::XForEach:
1274 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1275 return ParseOperation(CurRec);
1282 /// ParseValue - Parse a tblgen value. This returns null on error.
1284 /// Value ::= SimpleValue ValueSuffix*
1285 /// ValueSuffix ::= '{' BitList '}'
1286 /// ValueSuffix ::= '[' BitList ']'
1287 /// ValueSuffix ::= '.' ID
1289 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType) {
1290 Init *Result = ParseSimpleValue(CurRec, ItemType);
1291 if (Result == 0) return 0;
1293 // Parse the suffixes now if present.
1295 switch (Lex.getCode()) {
1296 default: return Result;
1297 case tgtok::l_brace: {
1298 SMLoc CurlyLoc = Lex.getLoc();
1299 Lex.Lex(); // eat the '{'
1300 std::vector<unsigned> Ranges = ParseRangeList();
1301 if (Ranges.empty()) return 0;
1303 // Reverse the bitlist.
1304 std::reverse(Ranges.begin(), Ranges.end());
1305 Result = Result->convertInitializerBitRange(Ranges);
1307 Error(CurlyLoc, "Invalid bit range for value");
1312 if (Lex.getCode() != tgtok::r_brace) {
1313 TokError("expected '}' at end of bit range list");
1319 case tgtok::l_square: {
1320 SMLoc SquareLoc = Lex.getLoc();
1321 Lex.Lex(); // eat the '['
1322 std::vector<unsigned> Ranges = ParseRangeList();
1323 if (Ranges.empty()) return 0;
1325 Result = Result->convertInitListSlice(Ranges);
1327 Error(SquareLoc, "Invalid range for list slice");
1332 if (Lex.getCode() != tgtok::r_square) {
1333 TokError("expected ']' at end of list slice");
1340 if (Lex.Lex() != tgtok::Id) { // eat the .
1341 TokError("expected field identifier after '.'");
1344 if (!Result->getFieldType(Lex.getCurStrVal())) {
1345 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1346 Result->getAsString() + "'");
1349 Result = new FieldInit(Result, Lex.getCurStrVal());
1350 Lex.Lex(); // eat field name
1356 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1358 /// ParseDagArgList ::= Value (':' VARNAME)?
1359 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1360 std::vector<std::pair<llvm::Init*, std::string> >
1361 TGParser::ParseDagArgList(Record *CurRec) {
1362 std::vector<std::pair<llvm::Init*, std::string> > Result;
1365 Init *Val = ParseValue(CurRec);
1366 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1368 // If the variable name is present, add it.
1369 std::string VarName;
1370 if (Lex.getCode() == tgtok::colon) {
1371 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1372 TokError("expected variable name in dag literal");
1373 return std::vector<std::pair<llvm::Init*, std::string> >();
1375 VarName = Lex.getCurStrVal();
1376 Lex.Lex(); // eat the VarName.
1379 Result.push_back(std::make_pair(Val, VarName));
1381 if (Lex.getCode() != tgtok::comma) break;
1382 Lex.Lex(); // eat the ','
1389 /// ParseValueList - Parse a comma separated list of values, returning them as a
1390 /// vector. Note that this always expects to be able to parse at least one
1391 /// value. It returns an empty list if this is not possible.
1393 /// ValueList ::= Value (',' Value)
1395 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1397 std::vector<Init*> Result;
1398 RecTy *ItemType = EltTy;
1399 unsigned int ArgN = 0;
1400 if (ArgsRec != 0 && EltTy == 0) {
1401 const std::vector<std::string> &TArgs = ArgsRec->getTemplateArgs();
1402 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1403 assert(RV && "Template argument record not found??");
1404 ItemType = RV->getType();
1407 Result.push_back(ParseValue(CurRec, ItemType));
1408 if (Result.back() == 0) return std::vector<Init*>();
1410 while (Lex.getCode() == tgtok::comma) {
1411 Lex.Lex(); // Eat the comma
1413 if (ArgsRec != 0 && EltTy == 0) {
1414 const std::vector<std::string> &TArgs = ArgsRec->getTemplateArgs();
1415 if (ArgN >= TArgs.size()) {
1416 TokError("too many template arguments");
1417 return std::vector<Init*>();
1419 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1420 assert(RV && "Template argument record not found??");
1421 ItemType = RV->getType();
1424 Result.push_back(ParseValue(CurRec, ItemType));
1425 if (Result.back() == 0) return std::vector<Init*>();
1432 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1433 /// empty string on error. This can happen in a number of different context's,
1434 /// including within a def or in the template args for a def (which which case
1435 /// CurRec will be non-null) and within the template args for a multiclass (in
1436 /// which case CurRec will be null, but CurMultiClass will be set). This can
1437 /// also happen within a def that is within a multiclass, which will set both
1438 /// CurRec and CurMultiClass.
1440 /// Declaration ::= FIELD? Type ID ('=' Value)?
1442 std::string TGParser::ParseDeclaration(Record *CurRec,
1443 bool ParsingTemplateArgs) {
1444 // Read the field prefix if present.
1445 bool HasField = Lex.getCode() == tgtok::Field;
1446 if (HasField) Lex.Lex();
1448 RecTy *Type = ParseType();
1449 if (Type == 0) return "";
1451 if (Lex.getCode() != tgtok::Id) {
1452 TokError("Expected identifier in declaration");
1456 SMLoc IdLoc = Lex.getLoc();
1457 std::string DeclName = Lex.getCurStrVal();
1460 if (ParsingTemplateArgs) {
1462 DeclName = CurRec->getName() + ":" + DeclName;
1464 assert(CurMultiClass);
1467 DeclName = CurMultiClass->Rec.getName() + "::" + DeclName;
1471 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1474 // If a value is present, parse it.
1475 if (Lex.getCode() == tgtok::equal) {
1477 SMLoc ValLoc = Lex.getLoc();
1478 Init *Val = ParseValue(CurRec, Type);
1480 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1487 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1488 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1489 /// template args for a def, which may or may not be in a multiclass. If null,
1490 /// these are the template args for a multiclass.
1492 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1494 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1495 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1496 Lex.Lex(); // eat the '<'
1498 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1500 // Read the first declaration.
1501 std::string TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1502 if (TemplArg.empty())
1505 TheRecToAddTo->addTemplateArg(TemplArg);
1507 while (Lex.getCode() == tgtok::comma) {
1508 Lex.Lex(); // eat the ','
1510 // Read the following declarations.
1511 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1512 if (TemplArg.empty())
1514 TheRecToAddTo->addTemplateArg(TemplArg);
1517 if (Lex.getCode() != tgtok::greater)
1518 return TokError("expected '>' at end of template argument list");
1519 Lex.Lex(); // eat the '>'.
1524 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1526 /// BodyItem ::= Declaration ';'
1527 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1528 bool TGParser::ParseBodyItem(Record *CurRec) {
1529 if (Lex.getCode() != tgtok::Let) {
1530 if (ParseDeclaration(CurRec, false).empty())
1533 if (Lex.getCode() != tgtok::semi)
1534 return TokError("expected ';' after declaration");
1539 // LET ID OptionalRangeList '=' Value ';'
1540 if (Lex.Lex() != tgtok::Id)
1541 return TokError("expected field identifier after let");
1543 SMLoc IdLoc = Lex.getLoc();
1544 std::string FieldName = Lex.getCurStrVal();
1545 Lex.Lex(); // eat the field name.
1547 std::vector<unsigned> BitList;
1548 if (ParseOptionalBitList(BitList))
1550 std::reverse(BitList.begin(), BitList.end());
1552 if (Lex.getCode() != tgtok::equal)
1553 return TokError("expected '=' in let expression");
1554 Lex.Lex(); // eat the '='.
1556 RecordVal *Field = CurRec->getValue(FieldName);
1558 return TokError("Value '" + FieldName + "' unknown!");
1560 RecTy *Type = Field->getType();
1562 Init *Val = ParseValue(CurRec, Type);
1563 if (Val == 0) return true;
1565 if (Lex.getCode() != tgtok::semi)
1566 return TokError("expected ';' after let expression");
1569 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1572 /// ParseBody - Read the body of a class or def. Return true on error, false on
1576 /// Body ::= '{' BodyList '}'
1577 /// BodyList BodyItem*
1579 bool TGParser::ParseBody(Record *CurRec) {
1580 // If this is a null definition, just eat the semi and return.
1581 if (Lex.getCode() == tgtok::semi) {
1586 if (Lex.getCode() != tgtok::l_brace)
1587 return TokError("Expected ';' or '{' to start body");
1591 while (Lex.getCode() != tgtok::r_brace)
1592 if (ParseBodyItem(CurRec))
1600 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1601 /// optional ClassList followed by a Body. CurRec is the current def or class
1602 /// that is being parsed.
1604 /// ObjectBody ::= BaseClassList Body
1605 /// BaseClassList ::= /*empty*/
1606 /// BaseClassList ::= ':' BaseClassListNE
1607 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1609 bool TGParser::ParseObjectBody(Record *CurRec) {
1610 // If there is a baseclass list, read it.
1611 if (Lex.getCode() == tgtok::colon) {
1614 // Read all of the subclasses.
1615 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1618 if (SubClass.Rec == 0) return true;
1621 if (AddSubClass(CurRec, SubClass))
1624 if (Lex.getCode() != tgtok::comma) break;
1625 Lex.Lex(); // eat ','.
1626 SubClass = ParseSubClassReference(CurRec, false);
1630 // Process any variables on the let stack.
1631 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1632 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1633 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1634 LetStack[i][j].Bits, LetStack[i][j].Value))
1637 return ParseBody(CurRec);
1640 /// ParseDef - Parse and return a top level or multiclass def, return the record
1641 /// corresponding to it. This returns null on error.
1643 /// DefInst ::= DEF ObjectName ObjectBody
1645 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1646 SMLoc DefLoc = Lex.getLoc();
1647 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1648 Lex.Lex(); // Eat the 'def' token.
1650 // Parse ObjectName and make a record for it.
1651 Record *CurRec = new Record(ParseObjectName(), DefLoc);
1653 if (!CurMultiClass) {
1654 // Top-level def definition.
1656 // Ensure redefinition doesn't happen.
1657 if (Records.getDef(CurRec->getName())) {
1658 Error(DefLoc, "def '" + CurRec->getName() + "' already defined");
1661 Records.addDef(CurRec);
1663 // Otherwise, a def inside a multiclass, add it to the multiclass.
1664 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1665 if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
1666 Error(DefLoc, "def '" + CurRec->getName() +
1667 "' already defined in this multiclass!");
1670 CurMultiClass->DefPrototypes.push_back(CurRec);
1673 if (ParseObjectBody(CurRec))
1676 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1677 CurRec->resolveReferences();
1679 // If ObjectBody has template arguments, it's an error.
1680 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1682 if (CurMultiClass) {
1683 // Copy the template arguments for the multiclass into the def.
1684 const std::vector<std::string> &TArgs =
1685 CurMultiClass->Rec.getTemplateArgs();
1687 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1688 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1689 assert(RV && "Template arg doesn't exist?");
1690 CurRec->addValue(*RV);
1698 /// ParseClass - Parse a tblgen class definition.
1700 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1702 bool TGParser::ParseClass() {
1703 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1706 if (Lex.getCode() != tgtok::Id)
1707 return TokError("expected class name after 'class' keyword");
1709 Record *CurRec = Records.getClass(Lex.getCurStrVal());
1711 // If the body was previously defined, this is an error.
1712 if (!CurRec->getValues().empty() ||
1713 !CurRec->getSuperClasses().empty() ||
1714 !CurRec->getTemplateArgs().empty())
1715 return TokError("Class '" + CurRec->getName() + "' already defined");
1717 // If this is the first reference to this class, create and add it.
1718 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc());
1719 Records.addClass(CurRec);
1721 Lex.Lex(); // eat the name.
1723 // If there are template args, parse them.
1724 if (Lex.getCode() == tgtok::less)
1725 if (ParseTemplateArgList(CurRec))
1728 // Finally, parse the object body.
1729 return ParseObjectBody(CurRec);
1732 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1735 /// LetList ::= LetItem (',' LetItem)*
1736 /// LetItem ::= ID OptionalRangeList '=' Value
1738 std::vector<LetRecord> TGParser::ParseLetList() {
1739 std::vector<LetRecord> Result;
1742 if (Lex.getCode() != tgtok::Id) {
1743 TokError("expected identifier in let definition");
1744 return std::vector<LetRecord>();
1746 std::string Name = Lex.getCurStrVal();
1747 SMLoc NameLoc = Lex.getLoc();
1748 Lex.Lex(); // Eat the identifier.
1750 // Check for an optional RangeList.
1751 std::vector<unsigned> Bits;
1752 if (ParseOptionalRangeList(Bits))
1753 return std::vector<LetRecord>();
1754 std::reverse(Bits.begin(), Bits.end());
1756 if (Lex.getCode() != tgtok::equal) {
1757 TokError("expected '=' in let expression");
1758 return std::vector<LetRecord>();
1760 Lex.Lex(); // eat the '='.
1762 Init *Val = ParseValue(0);
1763 if (Val == 0) return std::vector<LetRecord>();
1765 // Now that we have everything, add the record.
1766 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1768 if (Lex.getCode() != tgtok::comma)
1770 Lex.Lex(); // eat the comma.
1774 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
1775 /// different related productions. This works inside multiclasses too.
1777 /// Object ::= LET LetList IN '{' ObjectList '}'
1778 /// Object ::= LET LetList IN Object
1780 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
1781 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1784 // Add this entry to the let stack.
1785 std::vector<LetRecord> LetInfo = ParseLetList();
1786 if (LetInfo.empty()) return true;
1787 LetStack.push_back(LetInfo);
1789 if (Lex.getCode() != tgtok::In)
1790 return TokError("expected 'in' at end of top-level 'let'");
1793 // If this is a scalar let, just handle it now
1794 if (Lex.getCode() != tgtok::l_brace) {
1795 // LET LetList IN Object
1796 if (ParseObject(CurMultiClass))
1798 } else { // Object ::= LETCommand '{' ObjectList '}'
1799 SMLoc BraceLoc = Lex.getLoc();
1800 // Otherwise, this is a group let.
1801 Lex.Lex(); // eat the '{'.
1803 // Parse the object list.
1804 if (ParseObjectList(CurMultiClass))
1807 if (Lex.getCode() != tgtok::r_brace) {
1808 TokError("expected '}' at end of top level let command");
1809 return Error(BraceLoc, "to match this '{'");
1814 // Outside this let scope, this let block is not active.
1815 LetStack.pop_back();
1819 /// ParseMultiClass - Parse a multiclass definition.
1821 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
1822 /// ':' BaseMultiClassList '{' MultiClassDef+ '}'
1824 bool TGParser::ParseMultiClass() {
1825 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1826 Lex.Lex(); // Eat the multiclass token.
1828 if (Lex.getCode() != tgtok::Id)
1829 return TokError("expected identifier after multiclass for name");
1830 std::string Name = Lex.getCurStrVal();
1832 if (MultiClasses.count(Name))
1833 return TokError("multiclass '" + Name + "' already defined");
1835 CurMultiClass = MultiClasses[Name] = new MultiClass(Name, Lex.getLoc());
1836 Lex.Lex(); // Eat the identifier.
1838 // If there are template args, parse them.
1839 if (Lex.getCode() == tgtok::less)
1840 if (ParseTemplateArgList(0))
1843 bool inherits = false;
1845 // If there are submulticlasses, parse them.
1846 if (Lex.getCode() == tgtok::colon) {
1851 // Read all of the submulticlasses.
1852 SubMultiClassReference SubMultiClass =
1853 ParseSubMultiClassReference(CurMultiClass);
1856 if (SubMultiClass.MC == 0) return true;
1859 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
1862 if (Lex.getCode() != tgtok::comma) break;
1863 Lex.Lex(); // eat ','.
1864 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
1868 if (Lex.getCode() != tgtok::l_brace) {
1870 return TokError("expected '{' in multiclass definition");
1871 else if (Lex.getCode() != tgtok::semi)
1872 return TokError("expected ';' in multiclass definition");
1874 Lex.Lex(); // eat the ';'.
1876 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
1877 return TokError("multiclass must contain at least one def");
1879 while (Lex.getCode() != tgtok::r_brace) {
1880 switch (Lex.getCode()) {
1882 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
1886 if (ParseObject(CurMultiClass))
1891 Lex.Lex(); // eat the '}'.
1898 /// ParseDefm - Parse the instantiation of a multiclass.
1900 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
1902 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
1903 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
1905 std::string DefmPrefix;
1906 if (Lex.Lex() == tgtok::Id) { // eat the defm.
1907 DefmPrefix = Lex.getCurStrVal();
1908 Lex.Lex(); // Eat the defm prefix.
1911 SMLoc DefmPrefixLoc = Lex.getLoc();
1912 if (Lex.getCode() != tgtok::colon)
1913 return TokError("expected ':' after defm identifier");
1915 // Keep track of the new generated record definitions.
1916 std::vector<Record*> NewRecDefs;
1918 // This record also inherits from a regular class (non-multiclass)?
1919 bool InheritFromClass = false;
1924 SMLoc SubClassLoc = Lex.getLoc();
1925 SubClassReference Ref = ParseSubClassReference(0, true);
1928 if (Ref.Rec == 0) return true;
1930 // To instantiate a multiclass, we need to first get the multiclass, then
1931 // instantiate each def contained in the multiclass with the SubClassRef
1932 // template parameters.
1933 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
1934 assert(MC && "Didn't lookup multiclass correctly?");
1935 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
1937 // Verify that the correct number of template arguments were specified.
1938 const std::vector<std::string> &TArgs = MC->Rec.getTemplateArgs();
1939 if (TArgs.size() < TemplateVals.size())
1940 return Error(SubClassLoc,
1941 "more template args specified than multiclass expects");
1943 // Loop over all the def's in the multiclass, instantiating each one.
1944 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
1945 Record *DefProto = MC->DefPrototypes[i];
1947 // Add in the defm name. If the defm prefix is empty, give each
1948 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
1949 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
1951 std::string DefName = DefProto->getName();
1952 if (DefmPrefix.empty()) {
1953 DefName = GetNewAnonymousName();
1955 std::string::size_type idx = DefName.find("#NAME#");
1956 if (idx != std::string::npos) {
1957 DefName.replace(idx, 6, DefmPrefix);
1959 // Add the suffix to the defm name to get the new name.
1960 DefName = DefmPrefix + DefName;
1964 Record *CurRec = new Record(DefName, DefmPrefixLoc);
1966 SubClassReference Ref;
1967 Ref.RefLoc = DefmPrefixLoc;
1969 AddSubClass(CurRec, Ref);
1971 // Loop over all of the template arguments, setting them to the specified
1972 // value or leaving them as the default if necessary.
1973 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1974 // Check if a value is specified for this temp-arg.
1975 if (i < TemplateVals.size()) {
1977 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
1982 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
1985 CurRec->removeValue(TArgs[i]);
1987 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
1988 return Error(SubClassLoc,
1989 "value not specified for template argument #"+
1990 utostr(i) + " (" + TArgs[i] + ") of multiclassclass '" +
1991 MC->Rec.getName() + "'");
1995 // If the mdef is inside a 'let' expression, add to each def.
1996 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1997 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1998 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1999 LetStack[i][j].Bits, LetStack[i][j].Value)) {
2000 Error(DefmPrefixLoc, "when instantiating this defm");
2004 // Ensure redefinition doesn't happen.
2005 if (Records.getDef(CurRec->getName()))
2006 return Error(DefmPrefixLoc, "def '" + CurRec->getName() +
2007 "' already defined, instantiating defm with subdef '" +
2008 DefProto->getName() + "'");
2010 // Don't create a top level definition for defm inside multiclasses,
2011 // instead, only update the prototypes and bind the template args
2012 // with the new created definition.
2013 if (CurMultiClass) {
2014 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2016 if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
2017 Error(DefmPrefixLoc, "defm '" + CurRec->getName() +
2018 "' already defined in this multiclass!");
2022 CurMultiClass->DefPrototypes.push_back(CurRec);
2024 // Copy the template arguments for the multiclass into the new def.
2025 const std::vector<std::string> &TA =
2026 CurMultiClass->Rec.getTemplateArgs();
2028 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2029 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2030 assert(RV && "Template arg doesn't exist?");
2031 CurRec->addValue(*RV);
2034 Records.addDef(CurRec);
2037 NewRecDefs.push_back(CurRec);
2040 if (Lex.getCode() != tgtok::comma) break;
2041 Lex.Lex(); // eat ','.
2043 SubClassLoc = Lex.getLoc();
2045 // A defm can inherit from regular classes (non-multiclass) as
2046 // long as they come in the end of the inheritance list.
2047 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != 0);
2049 if (InheritFromClass)
2052 Ref = ParseSubClassReference(0, true);
2055 if (InheritFromClass) {
2056 // Process all the classes to inherit as if they were part of a
2057 // regular 'def' and inherit all record values.
2058 SubClassReference SubClass = ParseSubClassReference(0, false);
2061 if (SubClass.Rec == 0) return true;
2063 // Get the expanded definition prototypes and teach them about
2064 // the record values the current class to inherit has
2065 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2066 Record *CurRec = NewRecDefs[i];
2069 if (AddSubClass(CurRec, SubClass))
2072 // Process any variables on the let stack.
2073 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2074 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2075 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2076 LetStack[i][j].Bits, LetStack[i][j].Value))
2080 if (Lex.getCode() != tgtok::comma) break;
2081 Lex.Lex(); // eat ','.
2082 SubClass = ParseSubClassReference(0, false);
2087 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2088 NewRecDefs[i]->resolveReferences();
2090 if (Lex.getCode() != tgtok::semi)
2091 return TokError("expected ';' at end of defm");
2098 /// Object ::= ClassInst
2099 /// Object ::= DefInst
2100 /// Object ::= MultiClassInst
2101 /// Object ::= DefMInst
2102 /// Object ::= LETCommand '{' ObjectList '}'
2103 /// Object ::= LETCommand Object
2104 bool TGParser::ParseObject(MultiClass *MC) {
2105 switch (Lex.getCode()) {
2106 default: assert(0 && "This is not an object");
2107 case tgtok::Let: return ParseTopLevelLet(MC);
2108 case tgtok::Def: return ParseDef(MC);
2109 case tgtok::Defm: return ParseDefm(MC);
2110 case tgtok::Class: return ParseClass();
2111 case tgtok::MultiClass: return ParseMultiClass();
2116 /// ObjectList :== Object*
2117 bool TGParser::ParseObjectList(MultiClass *MC) {
2118 while (isObjectStart(Lex.getCode())) {
2119 if (ParseObject(MC))
2125 bool TGParser::ParseFile() {
2126 Lex.Lex(); // Prime the lexer.
2127 if (ParseObjectList()) return true;
2129 // If we have unread input at the end of the file, report it.
2130 if (Lex.getCode() == tgtok::Eof)
2133 return TokError("Unexpected input at top level");