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 /// ParseObjectName - If an object name is specified, return it. Otherwise,
298 /// return an anonymous name.
299 /// ObjectName ::= ID
300 /// ObjectName ::= /*empty*/
302 std::string
TGParser::ParseObjectName() {
303 if (Lex
.getCode() == tgtok::Id
) {
304 std::string Ret
= Lex
.getCurStrVal();
309 static unsigned AnonCounter
= 0;
310 return "anonymous."+utostr(AnonCounter
++);
314 /// ParseClassID - Parse and resolve a reference to a class name. This returns
319 Record
*TGParser::ParseClassID() {
320 if (Lex
.getCode() != tgtok::Id
) {
321 TokError("expected name for ClassID");
325 Record
*Result
= Records
.getClass(Lex
.getCurStrVal());
327 TokError("Couldn't find class '" + Lex
.getCurStrVal() + "'");
333 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
334 /// This returns null on error.
336 /// MultiClassID ::= ID
338 MultiClass
*TGParser::ParseMultiClassID() {
339 if (Lex
.getCode() != tgtok::Id
) {
340 TokError("expected name for ClassID");
344 MultiClass
*Result
= MultiClasses
[Lex
.getCurStrVal()];
346 TokError("Couldn't find class '" + Lex
.getCurStrVal() + "'");
352 Record
*TGParser::ParseDefmID() {
353 if (Lex
.getCode() != tgtok::Id
) {
354 TokError("expected multiclass name");
358 MultiClass
*MC
= MultiClasses
[Lex
.getCurStrVal()];
360 TokError("Couldn't find multiclass '" + Lex
.getCurStrVal() + "'");
369 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
370 /// subclass. This returns a SubClassRefTy with a null Record* on error.
372 /// SubClassRef ::= ClassID
373 /// SubClassRef ::= ClassID '<' ValueList '>'
375 SubClassReference
TGParser::
376 ParseSubClassReference(Record
*CurRec
, bool isDefm
) {
377 SubClassReference Result
;
378 Result
.RefLoc
= Lex
.getLoc();
381 Result
.Rec
= ParseDefmID();
383 Result
.Rec
= ParseClassID();
384 if (Result
.Rec
== 0) return Result
;
386 // If there is no template arg list, we're done.
387 if (Lex
.getCode() != tgtok::less
)
389 Lex
.Lex(); // Eat the '<'
391 if (Lex
.getCode() == tgtok::greater
) {
392 TokError("subclass reference requires a non-empty list of template values");
397 Result
.TemplateArgs
= ParseValueList(CurRec
, Result
.Rec
);
398 if (Result
.TemplateArgs
.empty()) {
399 Result
.Rec
= 0; // Error parsing value list.
403 if (Lex
.getCode() != tgtok::greater
) {
404 TokError("expected '>' in template value list");
413 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
414 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
415 /// Record* on error.
417 /// SubMultiClassRef ::= MultiClassID
418 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
420 SubMultiClassReference
TGParser::
421 ParseSubMultiClassReference(MultiClass
*CurMC
) {
422 SubMultiClassReference Result
;
423 Result
.RefLoc
= Lex
.getLoc();
425 Result
.MC
= ParseMultiClassID();
426 if (Result
.MC
== 0) return Result
;
428 // If there is no template arg list, we're done.
429 if (Lex
.getCode() != tgtok::less
)
431 Lex
.Lex(); // Eat the '<'
433 if (Lex
.getCode() == tgtok::greater
) {
434 TokError("subclass reference requires a non-empty list of template values");
439 Result
.TemplateArgs
= ParseValueList(&CurMC
->Rec
, &Result
.MC
->Rec
);
440 if (Result
.TemplateArgs
.empty()) {
441 Result
.MC
= 0; // Error parsing value list.
445 if (Lex
.getCode() != tgtok::greater
) {
446 TokError("expected '>' in template value list");
455 /// ParseRangePiece - Parse a bit/value range.
456 /// RangePiece ::= INTVAL
457 /// RangePiece ::= INTVAL '-' INTVAL
458 /// RangePiece ::= INTVAL INTVAL
459 bool TGParser::ParseRangePiece(std::vector
<unsigned> &Ranges
) {
460 if (Lex
.getCode() != tgtok::IntVal
) {
461 TokError("expected integer or bitrange");
464 int64_t Start
= Lex
.getCurIntVal();
468 return TokError("invalid range, cannot be negative");
470 switch (Lex
.Lex()) { // eat first character.
472 Ranges
.push_back(Start
);
475 if (Lex
.Lex() != tgtok::IntVal
) {
476 TokError("expected integer value as end of range");
479 End
= Lex
.getCurIntVal();
482 End
= -Lex
.getCurIntVal();
486 return TokError("invalid range, cannot be negative");
491 for (; Start
<= End
; ++Start
)
492 Ranges
.push_back(Start
);
494 for (; Start
>= End
; --Start
)
495 Ranges
.push_back(Start
);
500 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
502 /// RangeList ::= RangePiece (',' RangePiece)*
504 std::vector
<unsigned> TGParser::ParseRangeList() {
505 std::vector
<unsigned> Result
;
507 // Parse the first piece.
508 if (ParseRangePiece(Result
))
509 return std::vector
<unsigned>();
510 while (Lex
.getCode() == tgtok::comma
) {
511 Lex
.Lex(); // Eat the comma.
513 // Parse the next range piece.
514 if (ParseRangePiece(Result
))
515 return std::vector
<unsigned>();
520 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
521 /// OptionalRangeList ::= '<' RangeList '>'
522 /// OptionalRangeList ::= /*empty*/
523 bool TGParser::ParseOptionalRangeList(std::vector
<unsigned> &Ranges
) {
524 if (Lex
.getCode() != tgtok::less
)
527 SMLoc StartLoc
= Lex
.getLoc();
528 Lex
.Lex(); // eat the '<'
530 // Parse the range list.
531 Ranges
= ParseRangeList();
532 if (Ranges
.empty()) return true;
534 if (Lex
.getCode() != tgtok::greater
) {
535 TokError("expected '>' at end of range list");
536 return Error(StartLoc
, "to match this '<'");
538 Lex
.Lex(); // eat the '>'.
542 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
543 /// OptionalBitList ::= '{' RangeList '}'
544 /// OptionalBitList ::= /*empty*/
545 bool TGParser::ParseOptionalBitList(std::vector
<unsigned> &Ranges
) {
546 if (Lex
.getCode() != tgtok::l_brace
)
549 SMLoc StartLoc
= Lex
.getLoc();
550 Lex
.Lex(); // eat the '{'
552 // Parse the range list.
553 Ranges
= ParseRangeList();
554 if (Ranges
.empty()) return true;
556 if (Lex
.getCode() != tgtok::r_brace
) {
557 TokError("expected '}' at end of bit list");
558 return Error(StartLoc
, "to match this '{'");
560 Lex
.Lex(); // eat the '}'.
565 /// ParseType - Parse and return a tblgen type. This returns null on error.
567 /// Type ::= STRING // string type
568 /// Type ::= BIT // bit type
569 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
570 /// Type ::= INT // int type
571 /// Type ::= LIST '<' Type '>' // list<x> type
572 /// Type ::= CODE // code type
573 /// Type ::= DAG // dag type
574 /// Type ::= ClassID // Record Type
576 RecTy
*TGParser::ParseType() {
577 switch (Lex
.getCode()) {
578 default: TokError("Unknown token when expecting a type"); return 0;
579 case tgtok::String
: Lex
.Lex(); return new StringRecTy();
580 case tgtok::Bit
: Lex
.Lex(); return new BitRecTy();
581 case tgtok::Int
: Lex
.Lex(); return new IntRecTy();
582 case tgtok::Code
: Lex
.Lex(); return new CodeRecTy();
583 case tgtok::Dag
: Lex
.Lex(); return new DagRecTy();
585 if (Record
*R
= ParseClassID()) return new RecordRecTy(R
);
588 if (Lex
.Lex() != tgtok::less
) { // Eat 'bits'
589 TokError("expected '<' after bits type");
592 if (Lex
.Lex() != tgtok::IntVal
) { // Eat '<'
593 TokError("expected integer in bits<n> type");
596 uint64_t Val
= Lex
.getCurIntVal();
597 if (Lex
.Lex() != tgtok::greater
) { // Eat count.
598 TokError("expected '>' at end of bits<n> type");
601 Lex
.Lex(); // Eat '>'
602 return new BitsRecTy(Val
);
605 if (Lex
.Lex() != tgtok::less
) { // Eat 'bits'
606 TokError("expected '<' after list type");
609 Lex
.Lex(); // Eat '<'
610 RecTy
*SubType
= ParseType();
611 if (SubType
== 0) return 0;
613 if (Lex
.getCode() != tgtok::greater
) {
614 TokError("expected '>' at end of list<ty> type");
617 Lex
.Lex(); // Eat '>'
618 return new ListRecTy(SubType
);
623 /// ParseIDValue - Parse an ID as a value and decode what it means.
625 /// IDValue ::= ID [def local value]
626 /// IDValue ::= ID [def template arg]
627 /// IDValue ::= ID [multiclass local value]
628 /// IDValue ::= ID [multiclass template argument]
629 /// IDValue ::= ID [def name]
631 Init
*TGParser::ParseIDValue(Record
*CurRec
) {
632 assert(Lex
.getCode() == tgtok::Id
&& "Expected ID in ParseIDValue");
633 std::string Name
= Lex
.getCurStrVal();
634 SMLoc Loc
= Lex
.getLoc();
636 return ParseIDValue(CurRec
, Name
, Loc
);
639 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
640 /// has already been read.
641 Init
*TGParser::ParseIDValue(Record
*CurRec
,
642 const std::string
&Name
, SMLoc NameLoc
) {
644 if (const RecordVal
*RV
= CurRec
->getValue(Name
))
645 return new VarInit(Name
, RV
->getType());
647 std::string TemplateArgName
= CurRec
->getName()+":"+Name
;
648 if (CurRec
->isTemplateArg(TemplateArgName
)) {
649 const RecordVal
*RV
= CurRec
->getValue(TemplateArgName
);
650 assert(RV
&& "Template arg doesn't exist??");
651 return new VarInit(TemplateArgName
, RV
->getType());
656 std::string MCName
= CurMultiClass
->Rec
.getName()+"::"+Name
;
657 if (CurMultiClass
->Rec
.isTemplateArg(MCName
)) {
658 const RecordVal
*RV
= CurMultiClass
->Rec
.getValue(MCName
);
659 assert(RV
&& "Template arg doesn't exist??");
660 return new VarInit(MCName
, RV
->getType());
664 if (Record
*D
= Records
.getDef(Name
))
665 return new DefInit(D
);
667 Error(NameLoc
, "Variable not defined: '" + Name
+ "'");
671 /// ParseOperation - Parse an operator. This returns null on error.
673 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
675 Init
*TGParser::ParseOperation(Record
*CurRec
) {
676 switch (Lex
.getCode()) {
678 TokError("unknown operation");
684 case tgtok::XCast
: { // Value ::= !unop '(' Value ')'
685 UnOpInit::UnaryOp Code
;
688 switch (Lex
.getCode()) {
689 default: assert(0 && "Unhandled code!");
691 Lex
.Lex(); // eat the operation
692 Code
= UnOpInit::CAST
;
694 Type
= ParseOperatorType();
697 TokError("did not get type for unary operator");
703 Lex
.Lex(); // eat the operation
704 Code
= UnOpInit::CAR
;
707 Lex
.Lex(); // eat the operation
708 Code
= UnOpInit::CDR
;
711 Lex
.Lex(); // eat the operation
712 Code
= UnOpInit::LNULL
;
716 if (Lex
.getCode() != tgtok::l_paren
) {
717 TokError("expected '(' after unary operator");
720 Lex
.Lex(); // eat the '('
722 Init
*LHS
= ParseValue(CurRec
);
723 if (LHS
== 0) return 0;
725 if (Code
== UnOpInit::CAR
726 || Code
== UnOpInit::CDR
727 || Code
== UnOpInit::LNULL
) {
728 ListInit
*LHSl
= dynamic_cast<ListInit
*>(LHS
);
729 StringInit
*LHSs
= dynamic_cast<StringInit
*>(LHS
);
730 TypedInit
*LHSt
= dynamic_cast<TypedInit
*>(LHS
);
731 if (LHSl
== 0 && LHSs
== 0 && LHSt
== 0) {
732 TokError("expected list or string type argument in unary operator");
736 ListRecTy
*LType
= dynamic_cast<ListRecTy
*>(LHSt
->getType());
737 StringRecTy
*SType
= dynamic_cast<StringRecTy
*>(LHSt
->getType());
738 if (LType
== 0 && SType
== 0) {
739 TokError("expected list or string type argumnet in unary operator");
744 if (Code
== UnOpInit::CAR
745 || Code
== UnOpInit::CDR
) {
746 if (LHSl
== 0 && LHSt
== 0) {
747 TokError("expected list type argumnet in unary operator");
751 if (LHSl
&& LHSl
->getSize() == 0) {
752 TokError("empty list argument in unary operator");
756 Init
*Item
= LHSl
->getElement(0);
757 TypedInit
*Itemt
= dynamic_cast<TypedInit
*>(Item
);
759 TokError("untyped list element in unary operator");
762 if (Code
== UnOpInit::CAR
) {
763 Type
= Itemt
->getType();
765 Type
= new ListRecTy(Itemt
->getType());
768 assert(LHSt
&& "expected list type argument in unary operator");
769 ListRecTy
*LType
= dynamic_cast<ListRecTy
*>(LHSt
->getType());
771 TokError("expected list type argumnet in unary operator");
774 if (Code
== UnOpInit::CAR
) {
775 Type
= LType
->getElementType();
783 if (Lex
.getCode() != tgtok::r_paren
) {
784 TokError("expected ')' in unary operator");
787 Lex
.Lex(); // eat the ')'
788 return (new UnOpInit(Code
, LHS
, Type
))->Fold(CurRec
, CurMultiClass
);
796 case tgtok::XStrConcat
:
797 case tgtok::XNameConcat
: { // Value ::= !binop '(' Value ',' Value ')'
798 BinOpInit::BinaryOp Code
;
802 switch (Lex
.getCode()) {
803 default: assert(0 && "Unhandled code!");
805 Lex
.Lex(); // eat the operation
806 Code
= BinOpInit::CONCAT
;
807 Type
= new DagRecTy();
810 Lex
.Lex(); // eat the operation
811 Code
= BinOpInit::SRA
;
812 Type
= new IntRecTy();
815 Lex
.Lex(); // eat the operation
816 Code
= BinOpInit::SRL
;
817 Type
= new IntRecTy();
820 Lex
.Lex(); // eat the operation
821 Code
= BinOpInit::SHL
;
822 Type
= new IntRecTy();
825 Lex
.Lex(); // eat the operation
826 Code
= BinOpInit::EQ
;
827 Type
= new IntRecTy();
829 case tgtok::XStrConcat
:
830 Lex
.Lex(); // eat the operation
831 Code
= BinOpInit::STRCONCAT
;
832 Type
= new StringRecTy();
834 case tgtok::XNameConcat
:
835 Lex
.Lex(); // eat the operation
836 Code
= BinOpInit::NAMECONCAT
;
838 Type
= ParseOperatorType();
841 TokError("did not get type for binary operator");
847 if (Lex
.getCode() != tgtok::l_paren
) {
848 TokError("expected '(' after binary operator");
851 Lex
.Lex(); // eat the '('
853 Init
*LHS
= ParseValue(CurRec
);
854 if (LHS
== 0) return 0;
856 if (Lex
.getCode() != tgtok::comma
) {
857 TokError("expected ',' in binary operator");
860 Lex
.Lex(); // eat the ','
862 Init
*RHS
= ParseValue(CurRec
);
863 if (RHS
== 0) return 0;
865 if (Lex
.getCode() != tgtok::r_paren
) {
866 TokError("expected ')' in binary operator");
869 Lex
.Lex(); // eat the ')'
870 return (new BinOpInit(Code
, LHS
, RHS
, Type
))->Fold(CurRec
, CurMultiClass
);
874 case tgtok::XForEach
:
875 case tgtok::XSubst
: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
876 TernOpInit::TernaryOp Code
;
880 tgtok::TokKind LexCode
= Lex
.getCode();
881 Lex
.Lex(); // eat the operation
883 default: assert(0 && "Unhandled code!");
885 Code
= TernOpInit::IF
;
887 case tgtok::XForEach
:
888 Code
= TernOpInit::FOREACH
;
891 Code
= TernOpInit::SUBST
;
894 if (Lex
.getCode() != tgtok::l_paren
) {
895 TokError("expected '(' after ternary operator");
898 Lex
.Lex(); // eat the '('
900 Init
*LHS
= ParseValue(CurRec
);
901 if (LHS
== 0) return 0;
903 if (Lex
.getCode() != tgtok::comma
) {
904 TokError("expected ',' in ternary operator");
907 Lex
.Lex(); // eat the ','
909 Init
*MHS
= ParseValue(CurRec
);
910 if (MHS
== 0) return 0;
912 if (Lex
.getCode() != tgtok::comma
) {
913 TokError("expected ',' in ternary operator");
916 Lex
.Lex(); // eat the ','
918 Init
*RHS
= ParseValue(CurRec
);
919 if (RHS
== 0) return 0;
921 if (Lex
.getCode() != tgtok::r_paren
) {
922 TokError("expected ')' in binary operator");
925 Lex
.Lex(); // eat the ')'
928 default: assert(0 && "Unhandled code!");
930 TypedInit
*MHSt
= dynamic_cast<TypedInit
*>(MHS
);
931 TypedInit
*RHSt
= dynamic_cast<TypedInit
*>(RHS
);
932 if (MHSt
== 0 || RHSt
== 0) {
933 TokError("could not get type for !if");
936 if (MHSt
->getType()->typeIsConvertibleTo(RHSt
->getType())) {
937 Type
= RHSt
->getType();
938 } else if (RHSt
->getType()->typeIsConvertibleTo(MHSt
->getType())) {
939 Type
= MHSt
->getType();
941 TokError("inconsistent types for !if");
946 case tgtok::XForEach
: {
947 TypedInit
*MHSt
= dynamic_cast<TypedInit
*>(MHS
);
949 TokError("could not get type for !foreach");
952 Type
= MHSt
->getType();
955 case tgtok::XSubst
: {
956 TypedInit
*RHSt
= dynamic_cast<TypedInit
*>(RHS
);
958 TokError("could not get type for !subst");
961 Type
= RHSt
->getType();
965 return (new TernOpInit(Code
, LHS
, MHS
, RHS
, Type
))->Fold(CurRec
,
969 TokError("could not parse operation");
973 /// ParseOperatorType - Parse a type for an operator. This returns
976 /// OperatorType ::= '<' Type '>'
978 RecTy
*TGParser::ParseOperatorType() {
981 if (Lex
.getCode() != tgtok::less
) {
982 TokError("expected type name for operator");
985 Lex
.Lex(); // eat the <
990 TokError("expected type name for operator");
994 if (Lex
.getCode() != tgtok::greater
) {
995 TokError("expected type name for operator");
998 Lex
.Lex(); // eat the >
1004 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1006 /// SimpleValue ::= IDValue
1007 /// SimpleValue ::= INTVAL
1008 /// SimpleValue ::= STRVAL+
1009 /// SimpleValue ::= CODEFRAGMENT
1010 /// SimpleValue ::= '?'
1011 /// SimpleValue ::= '{' ValueList '}'
1012 /// SimpleValue ::= ID '<' ValueListNE '>'
1013 /// SimpleValue ::= '[' ValueList ']'
1014 /// SimpleValue ::= '(' IDValue DagArgList ')'
1015 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1016 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1017 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1018 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1019 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1021 Init
*TGParser::ParseSimpleValue(Record
*CurRec
, RecTy
*ItemType
) {
1023 switch (Lex
.getCode()) {
1024 default: TokError("Unknown token when parsing a value"); break;
1025 case tgtok::IntVal
: R
= new IntInit(Lex
.getCurIntVal()); Lex
.Lex(); break;
1026 case tgtok::StrVal
: {
1027 std::string Val
= Lex
.getCurStrVal();
1030 // Handle multiple consecutive concatenated strings.
1031 while (Lex
.getCode() == tgtok::StrVal
) {
1032 Val
+= Lex
.getCurStrVal();
1036 R
= new StringInit(Val
);
1039 case tgtok::CodeFragment
:
1040 R
= new CodeInit(Lex
.getCurStrVal()); Lex
.Lex(); break;
1041 case tgtok::question
: R
= new UnsetInit(); Lex
.Lex(); break;
1043 SMLoc NameLoc
= Lex
.getLoc();
1044 std::string Name
= Lex
.getCurStrVal();
1045 if (Lex
.Lex() != tgtok::less
) // consume the Id.
1046 return ParseIDValue(CurRec
, Name
, NameLoc
); // Value ::= IDValue
1048 // Value ::= ID '<' ValueListNE '>'
1049 if (Lex
.Lex() == tgtok::greater
) {
1050 TokError("expected non-empty value list");
1054 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1055 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1057 Record
*Class
= Records
.getClass(Name
);
1059 Error(NameLoc
, "Expected a class name, got '" + Name
+ "'");
1063 std::vector
<Init
*> ValueList
= ParseValueList(CurRec
, Class
);
1064 if (ValueList
.empty()) return 0;
1066 if (Lex
.getCode() != tgtok::greater
) {
1067 TokError("expected '>' at end of value list");
1070 Lex
.Lex(); // eat the '>'
1072 // Create the new record, set it as CurRec temporarily.
1073 static unsigned AnonCounter
= 0;
1074 Record
*NewRec
= new Record("anonymous.val."+utostr(AnonCounter
++),NameLoc
);
1075 SubClassReference SCRef
;
1076 SCRef
.RefLoc
= NameLoc
;
1078 SCRef
.TemplateArgs
= ValueList
;
1079 // Add info about the subclass to NewRec.
1080 if (AddSubClass(NewRec
, SCRef
))
1082 NewRec
->resolveReferences();
1083 Records
.addDef(NewRec
);
1085 // The result of the expression is a reference to the new record.
1086 return new DefInit(NewRec
);
1088 case tgtok::l_brace
: { // Value ::= '{' ValueList '}'
1089 SMLoc BraceLoc
= Lex
.getLoc();
1090 Lex
.Lex(); // eat the '{'
1091 std::vector
<Init
*> Vals
;
1093 if (Lex
.getCode() != tgtok::r_brace
) {
1094 Vals
= ParseValueList(CurRec
);
1095 if (Vals
.empty()) return 0;
1097 if (Lex
.getCode() != tgtok::r_brace
) {
1098 TokError("expected '}' at end of bit list value");
1101 Lex
.Lex(); // eat the '}'
1103 BitsInit
*Result
= new BitsInit(Vals
.size());
1104 for (unsigned i
= 0, e
= Vals
.size(); i
!= e
; ++i
) {
1105 Init
*Bit
= Vals
[i
]->convertInitializerTo(new BitRecTy());
1107 Error(BraceLoc
, "Element #" + utostr(i
) + " (" + Vals
[i
]->getAsString()+
1108 ") is not convertable to a bit");
1111 Result
->setBit(Vals
.size()-i
-1, Bit
);
1115 case tgtok::l_square
: { // Value ::= '[' ValueList ']'
1116 Lex
.Lex(); // eat the '['
1117 std::vector
<Init
*> Vals
;
1119 RecTy
*DeducedEltTy
= 0;
1120 ListRecTy
*GivenListTy
= 0;
1122 if (ItemType
!= 0) {
1123 ListRecTy
*ListType
= dynamic_cast<ListRecTy
*>(ItemType
);
1124 if (ListType
== 0) {
1125 std::stringstream s
;
1126 s
<< "Type mismatch for list, expected list type, got "
1127 << ItemType
->getAsString();
1130 GivenListTy
= ListType
;
1133 if (Lex
.getCode() != tgtok::r_square
) {
1134 Vals
= ParseValueList(CurRec
, 0,
1135 GivenListTy
? GivenListTy
->getElementType() : 0);
1136 if (Vals
.empty()) return 0;
1138 if (Lex
.getCode() != tgtok::r_square
) {
1139 TokError("expected ']' at end of list value");
1142 Lex
.Lex(); // eat the ']'
1144 RecTy
*GivenEltTy
= 0;
1145 if (Lex
.getCode() == tgtok::less
) {
1146 // Optional list element type
1147 Lex
.Lex(); // eat the '<'
1149 GivenEltTy
= ParseType();
1150 if (GivenEltTy
== 0) {
1151 // Couldn't parse element type
1155 if (Lex
.getCode() != tgtok::greater
) {
1156 TokError("expected '>' at end of list element type");
1159 Lex
.Lex(); // eat the '>'
1164 for (std::vector
<Init
*>::iterator i
= Vals
.begin(), ie
= Vals
.end();
1167 TypedInit
*TArg
= dynamic_cast<TypedInit
*>(*i
);
1169 TokError("Untyped list element");
1173 EltTy
= resolveTypes(EltTy
, TArg
->getType());
1175 TokError("Incompatible types in list elements");
1179 EltTy
= TArg
->getType();
1183 if (GivenEltTy
!= 0) {
1185 // Verify consistency
1186 if (!EltTy
->typeIsConvertibleTo(GivenEltTy
)) {
1187 TokError("Incompatible types in list elements");
1195 if (ItemType
== 0) {
1196 TokError("No type for list");
1199 DeducedEltTy
= GivenListTy
->getElementType();
1201 // Make sure the deduced type is compatible with the given type
1203 if (!EltTy
->typeIsConvertibleTo(GivenListTy
->getElementType())) {
1204 TokError("Element type mismatch for list");
1208 DeducedEltTy
= EltTy
;
1211 return new ListInit(Vals
, DeducedEltTy
);
1213 case tgtok::l_paren
: { // Value ::= '(' IDValue DagArgList ')'
1214 Lex
.Lex(); // eat the '('
1215 if (Lex
.getCode() != tgtok::Id
1216 && Lex
.getCode() != tgtok::XCast
1217 && Lex
.getCode() != tgtok::XNameConcat
) {
1218 TokError("expected identifier in dag init");
1223 if (Lex
.getCode() == tgtok::Id
) {
1224 Operator
= ParseIDValue(CurRec
);
1225 if (Operator
== 0) return 0;
1227 Operator
= ParseOperation(CurRec
);
1228 if (Operator
== 0) return 0;
1231 // If the operator name is present, parse it.
1232 std::string OperatorName
;
1233 if (Lex
.getCode() == tgtok::colon
) {
1234 if (Lex
.Lex() != tgtok::VarName
) { // eat the ':'
1235 TokError("expected variable name in dag operator");
1238 OperatorName
= Lex
.getCurStrVal();
1239 Lex
.Lex(); // eat the VarName.
1242 std::vector
<std::pair
<llvm::Init
*, std::string
> > DagArgs
;
1243 if (Lex
.getCode() != tgtok::r_paren
) {
1244 DagArgs
= ParseDagArgList(CurRec
);
1245 if (DagArgs
.empty()) return 0;
1248 if (Lex
.getCode() != tgtok::r_paren
) {
1249 TokError("expected ')' in dag init");
1252 Lex
.Lex(); // eat the ')'
1254 return new DagInit(Operator
, OperatorName
, DagArgs
);
1261 case tgtok::XCast
: // Value ::= !unop '(' Value ')'
1262 case tgtok::XConcat
:
1267 case tgtok::XStrConcat
:
1268 case tgtok::XNameConcat
: // Value ::= !binop '(' Value ',' Value ')'
1270 case tgtok::XForEach
:
1271 case tgtok::XSubst
: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1272 return ParseOperation(CurRec
);
1280 /// ParseValue - Parse a tblgen value. This returns null on error.
1282 /// Value ::= SimpleValue ValueSuffix*
1283 /// ValueSuffix ::= '{' BitList '}'
1284 /// ValueSuffix ::= '[' BitList ']'
1285 /// ValueSuffix ::= '.' ID
1287 Init
*TGParser::ParseValue(Record
*CurRec
, RecTy
*ItemType
) {
1288 Init
*Result
= ParseSimpleValue(CurRec
, ItemType
);
1289 if (Result
== 0) return 0;
1291 // Parse the suffixes now if present.
1293 switch (Lex
.getCode()) {
1294 default: return Result
;
1295 case tgtok::l_brace
: {
1296 SMLoc CurlyLoc
= Lex
.getLoc();
1297 Lex
.Lex(); // eat the '{'
1298 std::vector
<unsigned> Ranges
= ParseRangeList();
1299 if (Ranges
.empty()) return 0;
1301 // Reverse the bitlist.
1302 std::reverse(Ranges
.begin(), Ranges
.end());
1303 Result
= Result
->convertInitializerBitRange(Ranges
);
1305 Error(CurlyLoc
, "Invalid bit range for value");
1310 if (Lex
.getCode() != tgtok::r_brace
) {
1311 TokError("expected '}' at end of bit range list");
1317 case tgtok::l_square
: {
1318 SMLoc SquareLoc
= Lex
.getLoc();
1319 Lex
.Lex(); // eat the '['
1320 std::vector
<unsigned> Ranges
= ParseRangeList();
1321 if (Ranges
.empty()) return 0;
1323 Result
= Result
->convertInitListSlice(Ranges
);
1325 Error(SquareLoc
, "Invalid range for list slice");
1330 if (Lex
.getCode() != tgtok::r_square
) {
1331 TokError("expected ']' at end of list slice");
1338 if (Lex
.Lex() != tgtok::Id
) { // eat the .
1339 TokError("expected field identifier after '.'");
1342 if (!Result
->getFieldType(Lex
.getCurStrVal())) {
1343 TokError("Cannot access field '" + Lex
.getCurStrVal() + "' of value '" +
1344 Result
->getAsString() + "'");
1347 Result
= new FieldInit(Result
, Lex
.getCurStrVal());
1348 Lex
.Lex(); // eat field name
1354 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1356 /// ParseDagArgList ::= Value (':' VARNAME)?
1357 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1358 std::vector
<std::pair
<llvm::Init
*, std::string
> >
1359 TGParser::ParseDagArgList(Record
*CurRec
) {
1360 std::vector
<std::pair
<llvm::Init
*, std::string
> > Result
;
1363 Init
*Val
= ParseValue(CurRec
);
1364 if (Val
== 0) return std::vector
<std::pair
<llvm::Init
*, std::string
> >();
1366 // If the variable name is present, add it.
1367 std::string VarName
;
1368 if (Lex
.getCode() == tgtok::colon
) {
1369 if (Lex
.Lex() != tgtok::VarName
) { // eat the ':'
1370 TokError("expected variable name in dag literal");
1371 return std::vector
<std::pair
<llvm::Init
*, std::string
> >();
1373 VarName
= Lex
.getCurStrVal();
1374 Lex
.Lex(); // eat the VarName.
1377 Result
.push_back(std::make_pair(Val
, VarName
));
1379 if (Lex
.getCode() != tgtok::comma
) break;
1380 Lex
.Lex(); // eat the ','
1387 /// ParseValueList - Parse a comma separated list of values, returning them as a
1388 /// vector. Note that this always expects to be able to parse at least one
1389 /// value. It returns an empty list if this is not possible.
1391 /// ValueList ::= Value (',' Value)
1393 std::vector
<Init
*> TGParser::ParseValueList(Record
*CurRec
, Record
*ArgsRec
,
1395 std::vector
<Init
*> Result
;
1396 RecTy
*ItemType
= EltTy
;
1397 unsigned int ArgN
= 0;
1398 if (ArgsRec
!= 0 && EltTy
== 0) {
1399 const std::vector
<std::string
> &TArgs
= ArgsRec
->getTemplateArgs();
1400 const RecordVal
*RV
= ArgsRec
->getValue(TArgs
[ArgN
]);
1401 assert(RV
&& "Template argument record not found??");
1402 ItemType
= RV
->getType();
1405 Result
.push_back(ParseValue(CurRec
, ItemType
));
1406 if (Result
.back() == 0) return std::vector
<Init
*>();
1408 while (Lex
.getCode() == tgtok::comma
) {
1409 Lex
.Lex(); // Eat the comma
1411 if (ArgsRec
!= 0 && EltTy
== 0) {
1412 const std::vector
<std::string
> &TArgs
= ArgsRec
->getTemplateArgs();
1413 if (ArgN
>= TArgs
.size()) {
1414 TokError("too many template arguments");
1415 return std::vector
<Init
*>();
1417 const RecordVal
*RV
= ArgsRec
->getValue(TArgs
[ArgN
]);
1418 assert(RV
&& "Template argument record not found??");
1419 ItemType
= RV
->getType();
1422 Result
.push_back(ParseValue(CurRec
, ItemType
));
1423 if (Result
.back() == 0) return std::vector
<Init
*>();
1430 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1431 /// empty string on error. This can happen in a number of different context's,
1432 /// including within a def or in the template args for a def (which which case
1433 /// CurRec will be non-null) and within the template args for a multiclass (in
1434 /// which case CurRec will be null, but CurMultiClass will be set). This can
1435 /// also happen within a def that is within a multiclass, which will set both
1436 /// CurRec and CurMultiClass.
1438 /// Declaration ::= FIELD? Type ID ('=' Value)?
1440 std::string
TGParser::ParseDeclaration(Record
*CurRec
,
1441 bool ParsingTemplateArgs
) {
1442 // Read the field prefix if present.
1443 bool HasField
= Lex
.getCode() == tgtok::Field
;
1444 if (HasField
) Lex
.Lex();
1446 RecTy
*Type
= ParseType();
1447 if (Type
== 0) return "";
1449 if (Lex
.getCode() != tgtok::Id
) {
1450 TokError("Expected identifier in declaration");
1454 SMLoc IdLoc
= Lex
.getLoc();
1455 std::string DeclName
= Lex
.getCurStrVal();
1458 if (ParsingTemplateArgs
) {
1460 DeclName
= CurRec
->getName() + ":" + DeclName
;
1462 assert(CurMultiClass
);
1465 DeclName
= CurMultiClass
->Rec
.getName() + "::" + DeclName
;
1469 if (AddValue(CurRec
, IdLoc
, RecordVal(DeclName
, Type
, HasField
)))
1472 // If a value is present, parse it.
1473 if (Lex
.getCode() == tgtok::equal
) {
1475 SMLoc ValLoc
= Lex
.getLoc();
1476 Init
*Val
= ParseValue(CurRec
, Type
);
1478 SetValue(CurRec
, ValLoc
, DeclName
, std::vector
<unsigned>(), Val
))
1485 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1486 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1487 /// template args for a def, which may or may not be in a multiclass. If null,
1488 /// these are the template args for a multiclass.
1490 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1492 bool TGParser::ParseTemplateArgList(Record
*CurRec
) {
1493 assert(Lex
.getCode() == tgtok::less
&& "Not a template arg list!");
1494 Lex
.Lex(); // eat the '<'
1496 Record
*TheRecToAddTo
= CurRec
? CurRec
: &CurMultiClass
->Rec
;
1498 // Read the first declaration.
1499 std::string TemplArg
= ParseDeclaration(CurRec
, true/*templateargs*/);
1500 if (TemplArg
.empty())
1503 TheRecToAddTo
->addTemplateArg(TemplArg
);
1505 while (Lex
.getCode() == tgtok::comma
) {
1506 Lex
.Lex(); // eat the ','
1508 // Read the following declarations.
1509 TemplArg
= ParseDeclaration(CurRec
, true/*templateargs*/);
1510 if (TemplArg
.empty())
1512 TheRecToAddTo
->addTemplateArg(TemplArg
);
1515 if (Lex
.getCode() != tgtok::greater
)
1516 return TokError("expected '>' at end of template argument list");
1517 Lex
.Lex(); // eat the '>'.
1522 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1524 /// BodyItem ::= Declaration ';'
1525 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1526 bool TGParser::ParseBodyItem(Record
*CurRec
) {
1527 if (Lex
.getCode() != tgtok::Let
) {
1528 if (ParseDeclaration(CurRec
, false).empty())
1531 if (Lex
.getCode() != tgtok::semi
)
1532 return TokError("expected ';' after declaration");
1537 // LET ID OptionalRangeList '=' Value ';'
1538 if (Lex
.Lex() != tgtok::Id
)
1539 return TokError("expected field identifier after let");
1541 SMLoc IdLoc
= Lex
.getLoc();
1542 std::string FieldName
= Lex
.getCurStrVal();
1543 Lex
.Lex(); // eat the field name.
1545 std::vector
<unsigned> BitList
;
1546 if (ParseOptionalBitList(BitList
))
1548 std::reverse(BitList
.begin(), BitList
.end());
1550 if (Lex
.getCode() != tgtok::equal
)
1551 return TokError("expected '=' in let expression");
1552 Lex
.Lex(); // eat the '='.
1554 RecordVal
*Field
= CurRec
->getValue(FieldName
);
1556 return TokError("Value '" + FieldName
+ "' unknown!");
1558 RecTy
*Type
= Field
->getType();
1560 Init
*Val
= ParseValue(CurRec
, Type
);
1561 if (Val
== 0) return true;
1563 if (Lex
.getCode() != tgtok::semi
)
1564 return TokError("expected ';' after let expression");
1567 return SetValue(CurRec
, IdLoc
, FieldName
, BitList
, Val
);
1570 /// ParseBody - Read the body of a class or def. Return true on error, false on
1574 /// Body ::= '{' BodyList '}'
1575 /// BodyList BodyItem*
1577 bool TGParser::ParseBody(Record
*CurRec
) {
1578 // If this is a null definition, just eat the semi and return.
1579 if (Lex
.getCode() == tgtok::semi
) {
1584 if (Lex
.getCode() != tgtok::l_brace
)
1585 return TokError("Expected ';' or '{' to start body");
1589 while (Lex
.getCode() != tgtok::r_brace
)
1590 if (ParseBodyItem(CurRec
))
1598 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1599 /// optional ClassList followed by a Body. CurRec is the current def or class
1600 /// that is being parsed.
1602 /// ObjectBody ::= BaseClassList Body
1603 /// BaseClassList ::= /*empty*/
1604 /// BaseClassList ::= ':' BaseClassListNE
1605 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1607 bool TGParser::ParseObjectBody(Record
*CurRec
) {
1608 // If there is a baseclass list, read it.
1609 if (Lex
.getCode() == tgtok::colon
) {
1612 // Read all of the subclasses.
1613 SubClassReference SubClass
= ParseSubClassReference(CurRec
, false);
1616 if (SubClass
.Rec
== 0) return true;
1619 if (AddSubClass(CurRec
, SubClass
))
1622 if (Lex
.getCode() != tgtok::comma
) break;
1623 Lex
.Lex(); // eat ','.
1624 SubClass
= ParseSubClassReference(CurRec
, false);
1628 // Process any variables on the let stack.
1629 for (unsigned i
= 0, e
= LetStack
.size(); i
!= e
; ++i
)
1630 for (unsigned j
= 0, e
= LetStack
[i
].size(); j
!= e
; ++j
)
1631 if (SetValue(CurRec
, LetStack
[i
][j
].Loc
, LetStack
[i
][j
].Name
,
1632 LetStack
[i
][j
].Bits
, LetStack
[i
][j
].Value
))
1635 return ParseBody(CurRec
);
1639 /// ParseDef - Parse and return a top level or multiclass def, return the record
1640 /// corresponding to it. This returns null on error.
1642 /// DefInst ::= DEF ObjectName ObjectBody
1644 llvm::Record
*TGParser::ParseDef(MultiClass
*CurMultiClass
) {
1645 SMLoc DefLoc
= Lex
.getLoc();
1646 assert(Lex
.getCode() == tgtok::Def
&& "Unknown tok");
1647 Lex
.Lex(); // Eat the 'def' token.
1649 // Parse ObjectName and make a record for it.
1650 Record
*CurRec
= new Record(ParseObjectName(), DefLoc
);
1652 if (!CurMultiClass
) {
1653 // Top-level def definition.
1655 // Ensure redefinition doesn't happen.
1656 if (Records
.getDef(CurRec
->getName())) {
1657 Error(DefLoc
, "def '" + CurRec
->getName() + "' already defined");
1660 Records
.addDef(CurRec
);
1662 // Otherwise, a def inside a multiclass, add it to the multiclass.
1663 for (unsigned i
= 0, e
= CurMultiClass
->DefPrototypes
.size(); i
!= e
; ++i
)
1664 if (CurMultiClass
->DefPrototypes
[i
]->getName() == CurRec
->getName()) {
1665 Error(DefLoc
, "def '" + CurRec
->getName() +
1666 "' already defined in this multiclass!");
1669 CurMultiClass
->DefPrototypes
.push_back(CurRec
);
1672 if (ParseObjectBody(CurRec
))
1675 if (CurMultiClass
== 0) // Def's in multiclasses aren't really defs.
1676 CurRec
->resolveReferences();
1678 // If ObjectBody has template arguments, it's an error.
1679 assert(CurRec
->getTemplateArgs().empty() && "How'd this get template args?");
1684 /// ParseClass - Parse a tblgen class definition.
1686 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1688 bool TGParser::ParseClass() {
1689 assert(Lex
.getCode() == tgtok::Class
&& "Unexpected token!");
1692 if (Lex
.getCode() != tgtok::Id
)
1693 return TokError("expected class name after 'class' keyword");
1695 Record
*CurRec
= Records
.getClass(Lex
.getCurStrVal());
1697 // If the body was previously defined, this is an error.
1698 if (!CurRec
->getValues().empty() ||
1699 !CurRec
->getSuperClasses().empty() ||
1700 !CurRec
->getTemplateArgs().empty())
1701 return TokError("Class '" + CurRec
->getName() + "' already defined");
1703 // If this is the first reference to this class, create and add it.
1704 CurRec
= new Record(Lex
.getCurStrVal(), Lex
.getLoc());
1705 Records
.addClass(CurRec
);
1707 Lex
.Lex(); // eat the name.
1709 // If there are template args, parse them.
1710 if (Lex
.getCode() == tgtok::less
)
1711 if (ParseTemplateArgList(CurRec
))
1714 // Finally, parse the object body.
1715 return ParseObjectBody(CurRec
);
1718 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1721 /// LetList ::= LetItem (',' LetItem)*
1722 /// LetItem ::= ID OptionalRangeList '=' Value
1724 std::vector
<LetRecord
> TGParser::ParseLetList() {
1725 std::vector
<LetRecord
> Result
;
1728 if (Lex
.getCode() != tgtok::Id
) {
1729 TokError("expected identifier in let definition");
1730 return std::vector
<LetRecord
>();
1732 std::string Name
= Lex
.getCurStrVal();
1733 SMLoc NameLoc
= Lex
.getLoc();
1734 Lex
.Lex(); // Eat the identifier.
1736 // Check for an optional RangeList.
1737 std::vector
<unsigned> Bits
;
1738 if (ParseOptionalRangeList(Bits
))
1739 return std::vector
<LetRecord
>();
1740 std::reverse(Bits
.begin(), Bits
.end());
1742 if (Lex
.getCode() != tgtok::equal
) {
1743 TokError("expected '=' in let expression");
1744 return std::vector
<LetRecord
>();
1746 Lex
.Lex(); // eat the '='.
1748 Init
*Val
= ParseValue(0);
1749 if (Val
== 0) return std::vector
<LetRecord
>();
1751 // Now that we have everything, add the record.
1752 Result
.push_back(LetRecord(Name
, Bits
, Val
, NameLoc
));
1754 if (Lex
.getCode() != tgtok::comma
)
1756 Lex
.Lex(); // eat the comma.
1760 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
1761 /// different related productions.
1763 /// Object ::= LET LetList IN '{' ObjectList '}'
1764 /// Object ::= LET LetList IN Object
1766 bool TGParser::ParseTopLevelLet() {
1767 assert(Lex
.getCode() == tgtok::Let
&& "Unexpected token");
1770 // Add this entry to the let stack.
1771 std::vector
<LetRecord
> LetInfo
= ParseLetList();
1772 if (LetInfo
.empty()) return true;
1773 LetStack
.push_back(LetInfo
);
1775 if (Lex
.getCode() != tgtok::In
)
1776 return TokError("expected 'in' at end of top-level 'let'");
1779 // If this is a scalar let, just handle it now
1780 if (Lex
.getCode() != tgtok::l_brace
) {
1781 // LET LetList IN Object
1784 } else { // Object ::= LETCommand '{' ObjectList '}'
1785 SMLoc BraceLoc
= Lex
.getLoc();
1786 // Otherwise, this is a group let.
1787 Lex
.Lex(); // eat the '{'.
1789 // Parse the object list.
1790 if (ParseObjectList())
1793 if (Lex
.getCode() != tgtok::r_brace
) {
1794 TokError("expected '}' at end of top level let command");
1795 return Error(BraceLoc
, "to match this '{'");
1800 // Outside this let scope, this let block is not active.
1801 LetStack
.pop_back();
1805 /// ParseMultiClassDef - Parse a def in a multiclass context.
1807 /// MultiClassDef ::= DefInst
1809 bool TGParser::ParseMultiClassDef(MultiClass
*CurMC
) {
1810 if (Lex
.getCode() != tgtok::Def
)
1811 return TokError("expected 'def' in multiclass body");
1813 Record
*D
= ParseDef(CurMC
);
1814 if (D
== 0) return true;
1816 // Copy the template arguments for the multiclass into the def.
1817 const std::vector
<std::string
> &TArgs
= CurMC
->Rec
.getTemplateArgs();
1819 for (unsigned i
= 0, e
= TArgs
.size(); i
!= e
; ++i
) {
1820 const RecordVal
*RV
= CurMC
->Rec
.getValue(TArgs
[i
]);
1821 assert(RV
&& "Template arg doesn't exist?");
1828 /// ParseMultiClass - Parse a multiclass definition.
1830 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
1831 /// ':' BaseMultiClassList '{' MultiClassDef+ '}'
1833 bool TGParser::ParseMultiClass() {
1834 assert(Lex
.getCode() == tgtok::MultiClass
&& "Unexpected token");
1835 Lex
.Lex(); // Eat the multiclass token.
1837 if (Lex
.getCode() != tgtok::Id
)
1838 return TokError("expected identifier after multiclass for name");
1839 std::string Name
= Lex
.getCurStrVal();
1841 if (MultiClasses
.count(Name
))
1842 return TokError("multiclass '" + Name
+ "' already defined");
1844 CurMultiClass
= MultiClasses
[Name
] = new MultiClass(Name
, Lex
.getLoc());
1845 Lex
.Lex(); // Eat the identifier.
1847 // If there are template args, parse them.
1848 if (Lex
.getCode() == tgtok::less
)
1849 if (ParseTemplateArgList(0))
1852 bool inherits
= false;
1854 // If there are submulticlasses, parse them.
1855 if (Lex
.getCode() == tgtok::colon
) {
1860 // Read all of the submulticlasses.
1861 SubMultiClassReference SubMultiClass
=
1862 ParseSubMultiClassReference(CurMultiClass
);
1865 if (SubMultiClass
.MC
== 0) return true;
1868 if (AddSubMultiClass(CurMultiClass
, SubMultiClass
))
1871 if (Lex
.getCode() != tgtok::comma
) break;
1872 Lex
.Lex(); // eat ','.
1873 SubMultiClass
= ParseSubMultiClassReference(CurMultiClass
);
1877 if (Lex
.getCode() != tgtok::l_brace
) {
1879 return TokError("expected '{' in multiclass definition");
1880 else if (Lex
.getCode() != tgtok::semi
)
1881 return TokError("expected ';' in multiclass definition");
1883 Lex
.Lex(); // eat the ';'.
1885 if (Lex
.Lex() == tgtok::r_brace
) // eat the '{'.
1886 return TokError("multiclass must contain at least one def");
1888 while (Lex
.getCode() != tgtok::r_brace
)
1889 if (ParseMultiClassDef(CurMultiClass
))
1892 Lex
.Lex(); // eat the '}'.
1899 /// ParseDefm - Parse the instantiation of a multiclass.
1901 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
1903 bool TGParser::ParseDefm() {
1904 assert(Lex
.getCode() == tgtok::Defm
&& "Unexpected token!");
1905 if (Lex
.Lex() != tgtok::Id
) // eat the defm.
1906 return TokError("expected identifier after defm");
1908 SMLoc DefmPrefixLoc
= Lex
.getLoc();
1909 std::string DefmPrefix
= Lex
.getCurStrVal();
1910 if (Lex
.Lex() != tgtok::colon
)
1911 return TokError("expected ':' after defm identifier");
1916 SMLoc SubClassLoc
= Lex
.getLoc();
1917 SubClassReference Ref
= ParseSubClassReference(0, true);
1920 if (Ref
.Rec
== 0) return true;
1922 // To instantiate a multiclass, we need to first get the multiclass, then
1923 // instantiate each def contained in the multiclass with the SubClassRef
1924 // template parameters.
1925 MultiClass
*MC
= MultiClasses
[Ref
.Rec
->getName()];
1926 assert(MC
&& "Didn't lookup multiclass correctly?");
1927 std::vector
<Init
*> &TemplateVals
= Ref
.TemplateArgs
;
1929 // Verify that the correct number of template arguments were specified.
1930 const std::vector
<std::string
> &TArgs
= MC
->Rec
.getTemplateArgs();
1931 if (TArgs
.size() < TemplateVals
.size())
1932 return Error(SubClassLoc
,
1933 "more template args specified than multiclass expects");
1935 // Loop over all the def's in the multiclass, instantiating each one.
1936 for (unsigned i
= 0, e
= MC
->DefPrototypes
.size(); i
!= e
; ++i
) {
1937 Record
*DefProto
= MC
->DefPrototypes
[i
];
1939 // Add in the defm name
1940 std::string DefName
= DefProto
->getName();
1941 std::string::size_type idx
= DefName
.find("#NAME#");
1942 if (idx
!= std::string::npos
) {
1943 DefName
.replace(idx
, 6, DefmPrefix
);
1945 // Add the suffix to the defm name to get the new name.
1946 DefName
= DefmPrefix
+ DefName
;
1949 Record
*CurRec
= new Record(DefName
, DefmPrefixLoc
);
1951 SubClassReference Ref
;
1952 Ref
.RefLoc
= DefmPrefixLoc
;
1954 AddSubClass(CurRec
, Ref
);
1956 // Loop over all of the template arguments, setting them to the specified
1957 // value or leaving them as the default if necessary.
1958 for (unsigned i
= 0, e
= TArgs
.size(); i
!= e
; ++i
) {
1959 // Check if a value is specified for this temp-arg.
1960 if (i
< TemplateVals
.size()) {
1962 if (SetValue(CurRec
, DefmPrefixLoc
, TArgs
[i
], std::vector
<unsigned>(),
1967 CurRec
->resolveReferencesTo(CurRec
->getValue(TArgs
[i
]));
1970 CurRec
->removeValue(TArgs
[i
]);
1972 } else if (!CurRec
->getValue(TArgs
[i
])->getValue()->isComplete()) {
1973 return Error(SubClassLoc
,
1974 "value not specified for template argument #"+
1975 utostr(i
) + " (" + TArgs
[i
] + ") of multiclassclass '" +
1976 MC
->Rec
.getName() + "'");
1980 // If the mdef is inside a 'let' expression, add to each def.
1981 for (unsigned i
= 0, e
= LetStack
.size(); i
!= e
; ++i
)
1982 for (unsigned j
= 0, e
= LetStack
[i
].size(); j
!= e
; ++j
)
1983 if (SetValue(CurRec
, LetStack
[i
][j
].Loc
, LetStack
[i
][j
].Name
,
1984 LetStack
[i
][j
].Bits
, LetStack
[i
][j
].Value
)) {
1985 Error(DefmPrefixLoc
, "when instantiating this defm");
1989 // Ensure redefinition doesn't happen.
1990 if (Records
.getDef(CurRec
->getName()))
1991 return Error(DefmPrefixLoc
, "def '" + CurRec
->getName() +
1992 "' already defined, instantiating defm with subdef '" +
1993 DefProto
->getName() + "'");
1994 Records
.addDef(CurRec
);
1995 CurRec
->resolveReferences();
1998 if (Lex
.getCode() != tgtok::comma
) break;
1999 Lex
.Lex(); // eat ','.
2001 SubClassLoc
= Lex
.getLoc();
2002 Ref
= ParseSubClassReference(0, true);
2005 if (Lex
.getCode() != tgtok::semi
)
2006 return TokError("expected ';' at end of defm");
2013 /// Object ::= ClassInst
2014 /// Object ::= DefInst
2015 /// Object ::= MultiClassInst
2016 /// Object ::= DefMInst
2017 /// Object ::= LETCommand '{' ObjectList '}'
2018 /// Object ::= LETCommand Object
2019 bool TGParser::ParseObject() {
2020 switch (Lex
.getCode()) {
2021 default: assert(0 && "This is not an object");
2022 case tgtok::Let
: return ParseTopLevelLet();
2023 case tgtok::Def
: return ParseDef(0) == 0;
2024 case tgtok::Defm
: return ParseDefm();
2025 case tgtok::Class
: return ParseClass();
2026 case tgtok::MultiClass
: return ParseMultiClass();
2031 /// ObjectList :== Object*
2032 bool TGParser::ParseObjectList() {
2033 while (isObjectStart(Lex
.getCode())) {
2040 bool TGParser::ParseFile() {
2041 Lex
.Lex(); // Prime the lexer.
2042 if (ParseObjectList()) return true;
2044 // If we have unread input at the end of the file, report it.
2045 if (Lex
.getCode() == tgtok::Eof
)
2048 return TokError("Unexpected input at top level");