1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implement the Parser for TableGen.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/TableGen/Record.h"
23 //===----------------------------------------------------------------------===//
24 // Support Code for the Semantic Actions.
25 //===----------------------------------------------------------------------===//
28 struct SubClassReference {
31 std::vector<Init*> TemplateArgs;
32 SubClassReference() : Rec(0) {}
34 bool isInvalid() const { return Rec == 0; }
37 struct SubMultiClassReference {
40 std::vector<Init*> TemplateArgs;
41 SubMultiClassReference() : MC(0) {}
43 bool isInvalid() const { return MC == 0; }
47 void SubMultiClassReference::dump() const {
48 errs() << "Multiclass:\n";
52 errs() << "Template args:\n";
53 for (std::vector<Init *>::const_iterator i = TemplateArgs.begin(),
54 iend = TemplateArgs.end();
61 } // end namespace llvm
63 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
65 CurRec = &CurMultiClass->Rec;
67 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
68 // The value already exists in the class, treat this as a set.
69 if (ERV->setValue(RV.getValue()))
70 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
71 RV.getType()->getAsString() + "' is incompatible with " +
72 "previous definition of type '" +
73 ERV->getType()->getAsString() + "'");
81 /// Return true on error, false on success.
82 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
83 const std::vector<unsigned> &BitList, Init *V) {
86 if (CurRec == 0) CurRec = &CurMultiClass->Rec;
88 RecordVal *RV = CurRec->getValue(ValName);
90 return Error(Loc, "Value '" + ValName->getAsUnquotedString()
93 // Do not allow assignments like 'X = X'. This will just cause infinite loops
94 // in the resolution machinery.
96 if (VarInit *VI = dyn_cast<VarInit>(V))
97 if (VI->getNameInit() == ValName)
100 // If we are assigning to a subset of the bits in the value... then we must be
101 // assigning to a field of BitsRecTy, which must have a BitsInit
104 if (!BitList.empty()) {
105 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
107 return Error(Loc, "Value '" + ValName->getAsUnquotedString()
108 + "' is not a bits type");
110 // Convert the incoming value to a bits type of the appropriate size...
111 Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size()));
113 return Error(Loc, "Initializer is not compatible with bit range");
116 // We should have a BitsInit type now.
117 BitsInit *BInit = dyn_cast<BitsInit>(BI);
120 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
122 // Loop over bits, assigning values as appropriate.
123 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
124 unsigned Bit = BitList[i];
126 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
127 ValName->getAsUnquotedString() + "' more than once");
128 NewBits[Bit] = BInit->getBit(i);
131 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
133 NewBits[i] = CurVal->getBit(i);
135 V = BitsInit::get(NewBits);
139 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of type '"
140 + RV->getType()->getAsString() +
141 "' is incompatible with initializer '" + V->getAsString()
146 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
147 /// args as SubClass's template arguments.
148 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
149 Record *SC = SubClass.Rec;
150 // Add all of the values in the subclass into the current class.
151 const std::vector<RecordVal> &Vals = SC->getValues();
152 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
153 if (AddValue(CurRec, SubClass.RefRange.Start, Vals[i]))
156 const std::vector<Init *> &TArgs = SC->getTemplateArgs();
158 // Ensure that an appropriate number of template arguments are specified.
159 if (TArgs.size() < SubClass.TemplateArgs.size())
160 return Error(SubClass.RefRange.Start,
161 "More template args specified than expected");
163 // Loop over all of the template arguments, setting them to the specified
164 // value or leaving them as the default if necessary.
165 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
166 if (i < SubClass.TemplateArgs.size()) {
167 // If a value is specified for this template arg, set it now.
168 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
169 std::vector<unsigned>(), SubClass.TemplateArgs[i]))
173 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
176 CurRec->removeValue(TArgs[i]);
178 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
179 return Error(SubClass.RefRange.Start,
180 "Value not specified for template argument #"
181 + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
182 + ") of subclass '" + SC->getNameInitAsString() + "'!");
186 // Since everything went well, we can now set the "superclass" list for the
188 const std::vector<Record*> &SCs = SC->getSuperClasses();
189 ArrayRef<SMRange> SCRanges = SC->getSuperClassRanges();
190 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
191 if (CurRec->isSubClassOf(SCs[i]))
192 return Error(SubClass.RefRange.Start,
193 "Already subclass of '" + SCs[i]->getName() + "'!\n");
194 CurRec->addSuperClass(SCs[i], SCRanges[i]);
197 if (CurRec->isSubClassOf(SC))
198 return Error(SubClass.RefRange.Start,
199 "Already subclass of '" + SC->getName() + "'!\n");
200 CurRec->addSuperClass(SC, SubClass.RefRange);
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.RefRange.Start, 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.RefRange.Start, MCVals[i]))
235 CurMC->DefPrototypes.push_back(NewDef);
238 const std::vector<Init *> &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.RefRange.Start,
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.RefRange.Start, 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.RefRange.Start, 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.RefRange.Start,
285 "Value not specified for template argument #"
286 + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
287 + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
294 /// ProcessForeachDefs - Given a record, apply all of the variable
295 /// values in all surrounding foreach loops, creating new records for
296 /// each combination of values.
297 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
301 // We want to instantiate a new copy of CurRec for each combination
302 // of nested loop iterator values. We don't want top instantiate
303 // any copies until we have values for each loop iterator.
305 return ProcessForeachDefs(CurRec, Loc, IterVals);
308 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
309 /// apply each of the variable values in this loop and then process
311 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
312 // Recursively build a tuple of iterator values.
313 if (IterVals.size() != Loops.size()) {
314 assert(IterVals.size() < Loops.size());
315 ForeachLoop &CurLoop = Loops[IterVals.size()];
316 ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
318 Error(Loc, "Loop list is not a list");
322 // Process each value.
323 for (int64_t i = 0; i < List->getSize(); ++i) {
324 Init *ItemVal = List->resolveListElementReference(*CurRec, 0, i);
325 IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
326 if (ProcessForeachDefs(CurRec, Loc, IterVals))
333 // This is the bottom of the recursion. We have all of the iterator values
334 // for this point in the iteration space. Instantiate a new record to
335 // reflect this combination of values.
336 Record *IterRec = new Record(*CurRec);
338 // Set the iterator values now.
339 for (unsigned i = 0, e = IterVals.size(); i != e; ++i) {
340 VarInit *IterVar = IterVals[i].IterVar;
341 TypedInit *IVal = dyn_cast<TypedInit>(IterVals[i].IterValue);
343 Error(Loc, "foreach iterator value is untyped");
347 IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
349 if (SetValue(IterRec, Loc, IterVar->getName(),
350 std::vector<unsigned>(), IVal)) {
351 Error(Loc, "when instantiating this def");
356 IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
359 IterRec->removeValue(IterVar->getName());
362 if (Records.getDef(IterRec->getNameInitAsString())) {
363 Error(Loc, "def already exists: " + IterRec->getNameInitAsString());
367 Records.addDef(IterRec);
368 IterRec->resolveReferences();
372 //===----------------------------------------------------------------------===//
374 //===----------------------------------------------------------------------===//
376 /// isObjectStart - Return true if this is a valid first token for an Object.
377 static bool isObjectStart(tgtok::TokKind K) {
378 return K == tgtok::Class || K == tgtok::Def ||
379 K == tgtok::Defm || K == tgtok::Let ||
380 K == tgtok::MultiClass || K == tgtok::Foreach;
383 static std::string GetNewAnonymousName() {
384 static unsigned AnonCounter = 0;
385 return "anonymous."+utostr(AnonCounter++);
388 /// ParseObjectName - If an object name is specified, return it. Otherwise,
390 /// ObjectName ::= Value [ '#' Value ]*
391 /// ObjectName ::= /*empty*/
393 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
394 switch (Lex.getCode()) {
398 // These are all of the tokens that can begin an object body.
399 // Some of these can also begin values but we disallow those cases
400 // because they are unlikely to be useful.
408 CurRec = &CurMultiClass->Rec;
412 const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
414 TokError("Record name is not typed!");
417 Type = CurRecName->getType();
420 return ParseValue(CurRec, Type, ParseNameMode);
423 /// ParseClassID - Parse and resolve a reference to a class name. This returns
428 Record *TGParser::ParseClassID() {
429 if (Lex.getCode() != tgtok::Id) {
430 TokError("expected name for ClassID");
434 Record *Result = Records.getClass(Lex.getCurStrVal());
436 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
442 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
443 /// This returns null on error.
445 /// MultiClassID ::= ID
447 MultiClass *TGParser::ParseMultiClassID() {
448 if (Lex.getCode() != tgtok::Id) {
449 TokError("expected name for MultiClassID");
453 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
455 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
461 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
462 /// subclass. This returns a SubClassRefTy with a null Record* on error.
464 /// SubClassRef ::= ClassID
465 /// SubClassRef ::= ClassID '<' ValueList '>'
467 SubClassReference TGParser::
468 ParseSubClassReference(Record *CurRec, bool isDefm) {
469 SubClassReference Result;
470 Result.RefRange.Start = Lex.getLoc();
473 if (MultiClass *MC = ParseMultiClassID())
474 Result.Rec = &MC->Rec;
476 Result.Rec = ParseClassID();
478 if (Result.Rec == 0) return Result;
480 // If there is no template arg list, we're done.
481 if (Lex.getCode() != tgtok::less) {
482 Result.RefRange.End = Lex.getLoc();
485 Lex.Lex(); // Eat the '<'
487 if (Lex.getCode() == tgtok::greater) {
488 TokError("subclass reference requires a non-empty list of template values");
493 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
494 if (Result.TemplateArgs.empty()) {
495 Result.Rec = 0; // Error parsing value list.
499 if (Lex.getCode() != tgtok::greater) {
500 TokError("expected '>' in template value list");
505 Result.RefRange.End = Lex.getLoc();
510 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
511 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
512 /// Record* on error.
514 /// SubMultiClassRef ::= MultiClassID
515 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
517 SubMultiClassReference TGParser::
518 ParseSubMultiClassReference(MultiClass *CurMC) {
519 SubMultiClassReference Result;
520 Result.RefRange.Start = Lex.getLoc();
522 Result.MC = ParseMultiClassID();
523 if (Result.MC == 0) return Result;
525 // If there is no template arg list, we're done.
526 if (Lex.getCode() != tgtok::less) {
527 Result.RefRange.End = Lex.getLoc();
530 Lex.Lex(); // Eat the '<'
532 if (Lex.getCode() == tgtok::greater) {
533 TokError("subclass reference requires a non-empty list of template values");
538 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
539 if (Result.TemplateArgs.empty()) {
540 Result.MC = 0; // Error parsing value list.
544 if (Lex.getCode() != tgtok::greater) {
545 TokError("expected '>' in template value list");
550 Result.RefRange.End = Lex.getLoc();
555 /// ParseRangePiece - Parse a bit/value range.
556 /// RangePiece ::= INTVAL
557 /// RangePiece ::= INTVAL '-' INTVAL
558 /// RangePiece ::= INTVAL INTVAL
559 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
560 if (Lex.getCode() != tgtok::IntVal) {
561 TokError("expected integer or bitrange");
564 int64_t Start = Lex.getCurIntVal();
568 return TokError("invalid range, cannot be negative");
570 switch (Lex.Lex()) { // eat first character.
572 Ranges.push_back(Start);
575 if (Lex.Lex() != tgtok::IntVal) {
576 TokError("expected integer value as end of range");
579 End = Lex.getCurIntVal();
582 End = -Lex.getCurIntVal();
586 return TokError("invalid range, cannot be negative");
591 for (; Start <= End; ++Start)
592 Ranges.push_back(Start);
594 for (; Start >= End; --Start)
595 Ranges.push_back(Start);
600 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
602 /// RangeList ::= RangePiece (',' RangePiece)*
604 std::vector<unsigned> TGParser::ParseRangeList() {
605 std::vector<unsigned> Result;
607 // Parse the first piece.
608 if (ParseRangePiece(Result))
609 return std::vector<unsigned>();
610 while (Lex.getCode() == tgtok::comma) {
611 Lex.Lex(); // Eat the comma.
613 // Parse the next range piece.
614 if (ParseRangePiece(Result))
615 return std::vector<unsigned>();
620 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
621 /// OptionalRangeList ::= '<' RangeList '>'
622 /// OptionalRangeList ::= /*empty*/
623 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
624 if (Lex.getCode() != tgtok::less)
627 SMLoc StartLoc = Lex.getLoc();
628 Lex.Lex(); // eat the '<'
630 // Parse the range list.
631 Ranges = ParseRangeList();
632 if (Ranges.empty()) return true;
634 if (Lex.getCode() != tgtok::greater) {
635 TokError("expected '>' at end of range list");
636 return Error(StartLoc, "to match this '<'");
638 Lex.Lex(); // eat the '>'.
642 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
643 /// OptionalBitList ::= '{' RangeList '}'
644 /// OptionalBitList ::= /*empty*/
645 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
646 if (Lex.getCode() != tgtok::l_brace)
649 SMLoc StartLoc = Lex.getLoc();
650 Lex.Lex(); // eat the '{'
652 // Parse the range list.
653 Ranges = ParseRangeList();
654 if (Ranges.empty()) return true;
656 if (Lex.getCode() != tgtok::r_brace) {
657 TokError("expected '}' at end of bit list");
658 return Error(StartLoc, "to match this '{'");
660 Lex.Lex(); // eat the '}'.
665 /// ParseType - Parse and return a tblgen type. This returns null on error.
667 /// Type ::= STRING // string type
668 /// Type ::= CODE // code type
669 /// Type ::= BIT // bit type
670 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
671 /// Type ::= INT // int type
672 /// Type ::= LIST '<' Type '>' // list<x> type
673 /// Type ::= DAG // dag type
674 /// Type ::= ClassID // Record Type
676 RecTy *TGParser::ParseType() {
677 switch (Lex.getCode()) {
678 default: TokError("Unknown token when expecting a type"); return 0;
679 case tgtok::String: Lex.Lex(); return StringRecTy::get();
680 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
681 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
682 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
683 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
685 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
688 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
689 TokError("expected '<' after bits type");
692 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
693 TokError("expected integer in bits<n> type");
696 uint64_t Val = Lex.getCurIntVal();
697 if (Lex.Lex() != tgtok::greater) { // Eat count.
698 TokError("expected '>' at end of bits<n> type");
701 Lex.Lex(); // Eat '>'
702 return BitsRecTy::get(Val);
705 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
706 TokError("expected '<' after list type");
709 Lex.Lex(); // Eat '<'
710 RecTy *SubType = ParseType();
711 if (SubType == 0) return 0;
713 if (Lex.getCode() != tgtok::greater) {
714 TokError("expected '>' at end of list<ty> type");
717 Lex.Lex(); // Eat '>'
718 return ListRecTy::get(SubType);
723 /// ParseIDValue - Parse an ID as a value and decode what it means.
725 /// IDValue ::= ID [def local value]
726 /// IDValue ::= ID [def template arg]
727 /// IDValue ::= ID [multiclass local value]
728 /// IDValue ::= ID [multiclass template argument]
729 /// IDValue ::= ID [def name]
731 Init *TGParser::ParseIDValue(Record *CurRec, IDParseMode Mode) {
732 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
733 std::string Name = Lex.getCurStrVal();
734 SMLoc Loc = Lex.getLoc();
736 return ParseIDValue(CurRec, Name, Loc);
739 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
740 /// has already been read.
741 Init *TGParser::ParseIDValue(Record *CurRec,
742 const std::string &Name, SMLoc NameLoc,
745 if (const RecordVal *RV = CurRec->getValue(Name))
746 return VarInit::get(Name, RV->getType());
748 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
751 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
754 if (CurRec->isTemplateArg(TemplateArgName)) {
755 const RecordVal *RV = CurRec->getValue(TemplateArgName);
756 assert(RV && "Template arg doesn't exist??");
757 return VarInit::get(TemplateArgName, RV->getType());
762 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
765 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
766 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
767 assert(RV && "Template arg doesn't exist??");
768 return VarInit::get(MCName, RV->getType());
772 // If this is in a foreach loop, make sure it's not a loop iterator
773 for (LoopVector::iterator i = Loops.begin(), iend = Loops.end();
776 VarInit *IterVar = dyn_cast<VarInit>(i->IterVar);
777 if (IterVar && IterVar->getName() == Name)
781 if (Mode == ParseNameMode)
782 return StringInit::get(Name);
784 if (Record *D = Records.getDef(Name))
785 return DefInit::get(D);
787 if (Mode == ParseValueMode) {
788 Error(NameLoc, "Variable not defined: '" + Name + "'");
792 return StringInit::get(Name);
795 /// ParseOperation - Parse an operator. This returns null on error.
797 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
799 Init *TGParser::ParseOperation(Record *CurRec) {
800 switch (Lex.getCode()) {
802 TokError("unknown operation");
807 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
808 UnOpInit::UnaryOp Code;
811 switch (Lex.getCode()) {
812 default: llvm_unreachable("Unhandled code!");
814 Lex.Lex(); // eat the operation
815 Code = UnOpInit::CAST;
817 Type = ParseOperatorType();
820 TokError("did not get type for unary operator");
826 Lex.Lex(); // eat the operation
827 Code = UnOpInit::HEAD;
830 Lex.Lex(); // eat the operation
831 Code = UnOpInit::TAIL;
834 Lex.Lex(); // eat the operation
835 Code = UnOpInit::EMPTY;
836 Type = IntRecTy::get();
839 if (Lex.getCode() != tgtok::l_paren) {
840 TokError("expected '(' after unary operator");
843 Lex.Lex(); // eat the '('
845 Init *LHS = ParseValue(CurRec);
846 if (LHS == 0) return 0;
848 if (Code == UnOpInit::HEAD
849 || Code == UnOpInit::TAIL
850 || Code == UnOpInit::EMPTY) {
851 ListInit *LHSl = dyn_cast<ListInit>(LHS);
852 StringInit *LHSs = dyn_cast<StringInit>(LHS);
853 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
854 if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
855 TokError("expected list or string type argument in unary operator");
859 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
860 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
861 if (LType == 0 && SType == 0) {
862 TokError("expected list or string type argumnet in unary operator");
867 if (Code == UnOpInit::HEAD
868 || Code == UnOpInit::TAIL) {
869 if (LHSl == 0 && LHSt == 0) {
870 TokError("expected list type argumnet in unary operator");
874 if (LHSl && LHSl->getSize() == 0) {
875 TokError("empty list argument in unary operator");
879 Init *Item = LHSl->getElement(0);
880 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
882 TokError("untyped list element in unary operator");
885 if (Code == UnOpInit::HEAD) {
886 Type = Itemt->getType();
888 Type = ListRecTy::get(Itemt->getType());
891 assert(LHSt && "expected list type argument in unary operator");
892 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
894 TokError("expected list type argumnet in unary operator");
897 if (Code == UnOpInit::HEAD) {
898 Type = LType->getElementType();
906 if (Lex.getCode() != tgtok::r_paren) {
907 TokError("expected ')' in unary operator");
910 Lex.Lex(); // eat the ')'
911 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
920 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
921 tgtok::TokKind OpTok = Lex.getCode();
922 SMLoc OpLoc = Lex.getLoc();
923 Lex.Lex(); // eat the operation
925 BinOpInit::BinaryOp Code;
929 default: llvm_unreachable("Unhandled code!");
930 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
931 case tgtok::XADD: Code = BinOpInit::ADD; Type = IntRecTy::get(); break;
932 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
933 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
934 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
935 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
936 case tgtok::XStrConcat:
937 Code = BinOpInit::STRCONCAT;
938 Type = StringRecTy::get();
942 if (Lex.getCode() != tgtok::l_paren) {
943 TokError("expected '(' after binary operator");
946 Lex.Lex(); // eat the '('
948 SmallVector<Init*, 2> InitList;
950 InitList.push_back(ParseValue(CurRec));
951 if (InitList.back() == 0) return 0;
953 while (Lex.getCode() == tgtok::comma) {
954 Lex.Lex(); // eat the ','
956 InitList.push_back(ParseValue(CurRec));
957 if (InitList.back() == 0) return 0;
960 if (Lex.getCode() != tgtok::r_paren) {
961 TokError("expected ')' in operator");
964 Lex.Lex(); // eat the ')'
966 // We allow multiple operands to associative operators like !strconcat as
967 // shorthand for nesting them.
968 if (Code == BinOpInit::STRCONCAT) {
969 while (InitList.size() > 2) {
970 Init *RHS = InitList.pop_back_val();
971 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
972 ->Fold(CurRec, CurMultiClass);
973 InitList.back() = RHS;
977 if (InitList.size() == 2)
978 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
979 ->Fold(CurRec, CurMultiClass);
981 Error(OpLoc, "expected two operands to operator");
986 case tgtok::XForEach:
987 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
988 TernOpInit::TernaryOp Code;
991 tgtok::TokKind LexCode = Lex.getCode();
992 Lex.Lex(); // eat the operation
994 default: llvm_unreachable("Unhandled code!");
996 Code = TernOpInit::IF;
998 case tgtok::XForEach:
999 Code = TernOpInit::FOREACH;
1002 Code = TernOpInit::SUBST;
1005 if (Lex.getCode() != tgtok::l_paren) {
1006 TokError("expected '(' after ternary operator");
1009 Lex.Lex(); // eat the '('
1011 Init *LHS = ParseValue(CurRec);
1012 if (LHS == 0) return 0;
1014 if (Lex.getCode() != tgtok::comma) {
1015 TokError("expected ',' in ternary operator");
1018 Lex.Lex(); // eat the ','
1020 Init *MHS = ParseValue(CurRec);
1021 if (MHS == 0) return 0;
1023 if (Lex.getCode() != tgtok::comma) {
1024 TokError("expected ',' in ternary operator");
1027 Lex.Lex(); // eat the ','
1029 Init *RHS = ParseValue(CurRec);
1030 if (RHS == 0) return 0;
1032 if (Lex.getCode() != tgtok::r_paren) {
1033 TokError("expected ')' in binary operator");
1036 Lex.Lex(); // eat the ')'
1039 default: llvm_unreachable("Unhandled code!");
1044 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1045 MHSTy = MHSt->getType();
1046 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1047 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1048 if (isa<BitInit>(MHS))
1049 MHSTy = BitRecTy::get();
1051 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1052 RHSTy = RHSt->getType();
1053 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1054 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1055 if (isa<BitInit>(RHS))
1056 RHSTy = BitRecTy::get();
1058 // For UnsetInit, it's typed from the other hand.
1059 if (isa<UnsetInit>(MHS))
1061 if (isa<UnsetInit>(RHS))
1064 if (!MHSTy || !RHSTy) {
1065 TokError("could not get type for !if");
1069 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1071 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1074 TokError("inconsistent types for !if");
1079 case tgtok::XForEach: {
1080 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1082 TokError("could not get type for !foreach");
1085 Type = MHSt->getType();
1088 case tgtok::XSubst: {
1089 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1091 TokError("could not get type for !subst");
1094 Type = RHSt->getType();
1098 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1104 /// ParseOperatorType - Parse a type for an operator. This returns
1107 /// OperatorType ::= '<' Type '>'
1109 RecTy *TGParser::ParseOperatorType() {
1112 if (Lex.getCode() != tgtok::less) {
1113 TokError("expected type name for operator");
1116 Lex.Lex(); // eat the <
1121 TokError("expected type name for operator");
1125 if (Lex.getCode() != tgtok::greater) {
1126 TokError("expected type name for operator");
1129 Lex.Lex(); // eat the >
1135 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1137 /// SimpleValue ::= IDValue
1138 /// SimpleValue ::= INTVAL
1139 /// SimpleValue ::= STRVAL+
1140 /// SimpleValue ::= CODEFRAGMENT
1141 /// SimpleValue ::= '?'
1142 /// SimpleValue ::= '{' ValueList '}'
1143 /// SimpleValue ::= ID '<' ValueListNE '>'
1144 /// SimpleValue ::= '[' ValueList ']'
1145 /// SimpleValue ::= '(' IDValue DagArgList ')'
1146 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1147 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1148 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1149 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1150 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1151 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1153 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1156 switch (Lex.getCode()) {
1157 default: TokError("Unknown token when parsing a value"); break;
1159 // This is a leading paste operation. This is deprecated but
1160 // still exists in some .td files. Ignore it.
1161 Lex.Lex(); // Skip '#'.
1162 return ParseSimpleValue(CurRec, ItemType, Mode);
1163 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1164 case tgtok::StrVal: {
1165 std::string Val = Lex.getCurStrVal();
1168 // Handle multiple consecutive concatenated strings.
1169 while (Lex.getCode() == tgtok::StrVal) {
1170 Val += Lex.getCurStrVal();
1174 R = StringInit::get(Val);
1177 case tgtok::CodeFragment:
1178 R = StringInit::get(Lex.getCurStrVal());
1181 case tgtok::question:
1182 R = UnsetInit::get();
1186 SMLoc NameLoc = Lex.getLoc();
1187 std::string Name = Lex.getCurStrVal();
1188 if (Lex.Lex() != tgtok::less) // consume the Id.
1189 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1191 // Value ::= ID '<' ValueListNE '>'
1192 if (Lex.Lex() == tgtok::greater) {
1193 TokError("expected non-empty value list");
1197 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1198 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1200 Record *Class = Records.getClass(Name);
1202 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1206 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1207 if (ValueList.empty()) return 0;
1209 if (Lex.getCode() != tgtok::greater) {
1210 TokError("expected '>' at end of value list");
1213 Lex.Lex(); // eat the '>'
1214 SMLoc EndLoc = Lex.getLoc();
1216 // Create the new record, set it as CurRec temporarily.
1217 static unsigned AnonCounter = 0;
1218 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),
1221 /*IsAnonymous=*/true);
1222 SubClassReference SCRef;
1223 SCRef.RefRange = SMRange(NameLoc, EndLoc);
1225 SCRef.TemplateArgs = ValueList;
1226 // Add info about the subclass to NewRec.
1227 if (AddSubClass(NewRec, SCRef))
1229 NewRec->resolveReferences();
1230 Records.addDef(NewRec);
1232 // The result of the expression is a reference to the new record.
1233 return DefInit::get(NewRec);
1235 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1236 SMLoc BraceLoc = Lex.getLoc();
1237 Lex.Lex(); // eat the '{'
1238 std::vector<Init*> Vals;
1240 if (Lex.getCode() != tgtok::r_brace) {
1241 Vals = ParseValueList(CurRec);
1242 if (Vals.empty()) return 0;
1244 if (Lex.getCode() != tgtok::r_brace) {
1245 TokError("expected '}' at end of bit list value");
1248 Lex.Lex(); // eat the '}'
1250 SmallVector<Init *, 16> NewBits(Vals.size());
1252 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1253 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1255 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1256 ") is not convertable to a bit");
1259 NewBits[Vals.size()-i-1] = Bit;
1261 return BitsInit::get(NewBits);
1263 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1264 Lex.Lex(); // eat the '['
1265 std::vector<Init*> Vals;
1267 RecTy *DeducedEltTy = 0;
1268 ListRecTy *GivenListTy = 0;
1270 if (ItemType != 0) {
1271 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1272 if (ListType == 0) {
1273 std::stringstream s;
1274 s << "Type mismatch for list, expected list type, got "
1275 << ItemType->getAsString();
1279 GivenListTy = ListType;
1282 if (Lex.getCode() != tgtok::r_square) {
1283 Vals = ParseValueList(CurRec, 0,
1284 GivenListTy ? GivenListTy->getElementType() : 0);
1285 if (Vals.empty()) return 0;
1287 if (Lex.getCode() != tgtok::r_square) {
1288 TokError("expected ']' at end of list value");
1291 Lex.Lex(); // eat the ']'
1293 RecTy *GivenEltTy = 0;
1294 if (Lex.getCode() == tgtok::less) {
1295 // Optional list element type
1296 Lex.Lex(); // eat the '<'
1298 GivenEltTy = ParseType();
1299 if (GivenEltTy == 0) {
1300 // Couldn't parse element type
1304 if (Lex.getCode() != tgtok::greater) {
1305 TokError("expected '>' at end of list element type");
1308 Lex.Lex(); // eat the '>'
1313 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1316 TypedInit *TArg = dyn_cast<TypedInit>(*i);
1318 TokError("Untyped list element");
1322 EltTy = resolveTypes(EltTy, TArg->getType());
1324 TokError("Incompatible types in list elements");
1328 EltTy = TArg->getType();
1332 if (GivenEltTy != 0) {
1334 // Verify consistency
1335 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1336 TokError("Incompatible types in list elements");
1344 if (ItemType == 0) {
1345 TokError("No type for list");
1348 DeducedEltTy = GivenListTy->getElementType();
1350 // Make sure the deduced type is compatible with the given type
1352 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1353 TokError("Element type mismatch for list");
1357 DeducedEltTy = EltTy;
1360 return ListInit::get(Vals, DeducedEltTy);
1362 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1363 Lex.Lex(); // eat the '('
1364 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1365 TokError("expected identifier in dag init");
1369 Init *Operator = ParseValue(CurRec);
1370 if (Operator == 0) return 0;
1372 // If the operator name is present, parse it.
1373 std::string OperatorName;
1374 if (Lex.getCode() == tgtok::colon) {
1375 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1376 TokError("expected variable name in dag operator");
1379 OperatorName = Lex.getCurStrVal();
1380 Lex.Lex(); // eat the VarName.
1383 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1384 if (Lex.getCode() != tgtok::r_paren) {
1385 DagArgs = ParseDagArgList(CurRec);
1386 if (DagArgs.empty()) return 0;
1389 if (Lex.getCode() != tgtok::r_paren) {
1390 TokError("expected ')' in dag init");
1393 Lex.Lex(); // eat the ')'
1395 return DagInit::get(Operator, OperatorName, DagArgs);
1401 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1402 case tgtok::XConcat:
1408 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1410 case tgtok::XForEach:
1411 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1412 return ParseOperation(CurRec);
1419 /// ParseValue - Parse a tblgen value. This returns null on error.
1421 /// Value ::= SimpleValue ValueSuffix*
1422 /// ValueSuffix ::= '{' BitList '}'
1423 /// ValueSuffix ::= '[' BitList ']'
1424 /// ValueSuffix ::= '.' ID
1426 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1427 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1428 if (Result == 0) return 0;
1430 // Parse the suffixes now if present.
1432 switch (Lex.getCode()) {
1433 default: return Result;
1434 case tgtok::l_brace: {
1435 if (Mode == ParseNameMode || Mode == ParseForeachMode)
1436 // This is the beginning of the object body.
1439 SMLoc CurlyLoc = Lex.getLoc();
1440 Lex.Lex(); // eat the '{'
1441 std::vector<unsigned> Ranges = ParseRangeList();
1442 if (Ranges.empty()) return 0;
1444 // Reverse the bitlist.
1445 std::reverse(Ranges.begin(), Ranges.end());
1446 Result = Result->convertInitializerBitRange(Ranges);
1448 Error(CurlyLoc, "Invalid bit range for value");
1453 if (Lex.getCode() != tgtok::r_brace) {
1454 TokError("expected '}' at end of bit range list");
1460 case tgtok::l_square: {
1461 SMLoc SquareLoc = Lex.getLoc();
1462 Lex.Lex(); // eat the '['
1463 std::vector<unsigned> Ranges = ParseRangeList();
1464 if (Ranges.empty()) return 0;
1466 Result = Result->convertInitListSlice(Ranges);
1468 Error(SquareLoc, "Invalid range for list slice");
1473 if (Lex.getCode() != tgtok::r_square) {
1474 TokError("expected ']' at end of list slice");
1481 if (Lex.Lex() != tgtok::Id) { // eat the .
1482 TokError("expected field identifier after '.'");
1485 if (!Result->getFieldType(Lex.getCurStrVal())) {
1486 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1487 Result->getAsString() + "'");
1490 Result = FieldInit::get(Result, Lex.getCurStrVal());
1491 Lex.Lex(); // eat field name
1495 SMLoc PasteLoc = Lex.getLoc();
1497 // Create a !strconcat() operation, first casting each operand to
1498 // a string if necessary.
1500 TypedInit *LHS = dyn_cast<TypedInit>(Result);
1502 Error(PasteLoc, "LHS of paste is not typed!");
1506 if (LHS->getType() != StringRecTy::get()) {
1507 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1512 Lex.Lex(); // Eat the '#'.
1513 switch (Lex.getCode()) {
1516 case tgtok::l_brace:
1517 // These are all of the tokens that can begin an object body.
1518 // Some of these can also begin values but we disallow those cases
1519 // because they are unlikely to be useful.
1521 // Trailing paste, concat with an empty string.
1522 RHS = StringInit::get("");
1526 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1527 RHS = dyn_cast<TypedInit>(RHSResult);
1529 Error(PasteLoc, "RHS of paste is not typed!");
1533 if (RHS->getType() != StringRecTy::get()) {
1534 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1540 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1541 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1547 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1549 /// ParseDagArgList ::= Value (':' VARNAME)?
1550 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1551 std::vector<std::pair<llvm::Init*, std::string> >
1552 TGParser::ParseDagArgList(Record *CurRec) {
1553 std::vector<std::pair<llvm::Init*, std::string> > Result;
1556 Init *Val = ParseValue(CurRec);
1557 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1559 // If the variable name is present, add it.
1560 std::string VarName;
1561 if (Lex.getCode() == tgtok::colon) {
1562 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1563 TokError("expected variable name in dag literal");
1564 return std::vector<std::pair<llvm::Init*, std::string> >();
1566 VarName = Lex.getCurStrVal();
1567 Lex.Lex(); // eat the VarName.
1570 Result.push_back(std::make_pair(Val, VarName));
1572 if (Lex.getCode() != tgtok::comma) break;
1573 Lex.Lex(); // eat the ','
1580 /// ParseValueList - Parse a comma separated list of values, returning them as a
1581 /// vector. Note that this always expects to be able to parse at least one
1582 /// value. It returns an empty list if this is not possible.
1584 /// ValueList ::= Value (',' Value)
1586 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1588 std::vector<Init*> Result;
1589 RecTy *ItemType = EltTy;
1590 unsigned int ArgN = 0;
1591 if (ArgsRec != 0 && EltTy == 0) {
1592 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1593 if (!TArgs.size()) {
1594 TokError("template argument provided to non-template class");
1595 return std::vector<Init*>();
1597 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1599 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1602 assert(RV && "Template argument record not found??");
1603 ItemType = RV->getType();
1606 Result.push_back(ParseValue(CurRec, ItemType));
1607 if (Result.back() == 0) return std::vector<Init*>();
1609 while (Lex.getCode() == tgtok::comma) {
1610 Lex.Lex(); // Eat the comma
1612 if (ArgsRec != 0 && EltTy == 0) {
1613 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1614 if (ArgN >= TArgs.size()) {
1615 TokError("too many template arguments");
1616 return std::vector<Init*>();
1618 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1619 assert(RV && "Template argument record not found??");
1620 ItemType = RV->getType();
1623 Result.push_back(ParseValue(CurRec, ItemType));
1624 if (Result.back() == 0) return std::vector<Init*>();
1631 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1632 /// empty string on error. This can happen in a number of different context's,
1633 /// including within a def or in the template args for a def (which which case
1634 /// CurRec will be non-null) and within the template args for a multiclass (in
1635 /// which case CurRec will be null, but CurMultiClass will be set). This can
1636 /// also happen within a def that is within a multiclass, which will set both
1637 /// CurRec and CurMultiClass.
1639 /// Declaration ::= FIELD? Type ID ('=' Value)?
1641 Init *TGParser::ParseDeclaration(Record *CurRec,
1642 bool ParsingTemplateArgs) {
1643 // Read the field prefix if present.
1644 bool HasField = Lex.getCode() == tgtok::Field;
1645 if (HasField) Lex.Lex();
1647 RecTy *Type = ParseType();
1648 if (Type == 0) return 0;
1650 if (Lex.getCode() != tgtok::Id) {
1651 TokError("Expected identifier in declaration");
1655 SMLoc IdLoc = Lex.getLoc();
1656 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1659 if (ParsingTemplateArgs) {
1661 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1663 assert(CurMultiClass);
1666 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1671 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1674 // If a value is present, parse it.
1675 if (Lex.getCode() == tgtok::equal) {
1677 SMLoc ValLoc = Lex.getLoc();
1678 Init *Val = ParseValue(CurRec, Type);
1680 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1687 /// ParseForeachDeclaration - Read a foreach declaration, returning
1688 /// the name of the declared object or a NULL Init on error. Return
1689 /// the name of the parsed initializer list through ForeachListName.
1691 /// ForeachDeclaration ::= ID '=' '[' ValueList ']'
1692 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
1693 /// ForeachDeclaration ::= ID '=' RangePiece
1695 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1696 if (Lex.getCode() != tgtok::Id) {
1697 TokError("Expected identifier in foreach declaration");
1701 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1704 // If a value is present, parse it.
1705 if (Lex.getCode() != tgtok::equal) {
1706 TokError("Expected '=' in foreach declaration");
1709 Lex.Lex(); // Eat the '='
1711 RecTy *IterType = 0;
1712 std::vector<unsigned> Ranges;
1714 switch (Lex.getCode()) {
1715 default: TokError("Unknown token when expecting a range list"); return 0;
1716 case tgtok::l_square: { // '[' ValueList ']'
1717 Init *List = ParseSimpleValue(0, 0, ParseForeachMode);
1718 ForeachListValue = dyn_cast<ListInit>(List);
1719 if (ForeachListValue == 0) {
1720 TokError("Expected a Value list");
1723 RecTy *ValueType = ForeachListValue->getType();
1724 ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1725 if (ListType == 0) {
1726 TokError("Value list is not of list type");
1729 IterType = ListType->getElementType();
1733 case tgtok::IntVal: { // RangePiece.
1734 if (ParseRangePiece(Ranges))
1739 case tgtok::l_brace: { // '{' RangeList '}'
1740 Lex.Lex(); // eat the '{'
1741 Ranges = ParseRangeList();
1742 if (Lex.getCode() != tgtok::r_brace) {
1743 TokError("expected '}' at end of bit range list");
1751 if (!Ranges.empty()) {
1752 assert(!IterType && "Type already initialized?");
1753 IterType = IntRecTy::get();
1754 std::vector<Init*> Values;
1755 for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
1756 Values.push_back(IntInit::get(Ranges[i]));
1757 ForeachListValue = ListInit::get(Values, IterType);
1763 return VarInit::get(DeclName, IterType);
1766 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1767 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1768 /// template args for a def, which may or may not be in a multiclass. If null,
1769 /// these are the template args for a multiclass.
1771 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1773 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1774 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1775 Lex.Lex(); // eat the '<'
1777 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1779 // Read the first declaration.
1780 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1784 TheRecToAddTo->addTemplateArg(TemplArg);
1786 while (Lex.getCode() == tgtok::comma) {
1787 Lex.Lex(); // eat the ','
1789 // Read the following declarations.
1790 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1793 TheRecToAddTo->addTemplateArg(TemplArg);
1796 if (Lex.getCode() != tgtok::greater)
1797 return TokError("expected '>' at end of template argument list");
1798 Lex.Lex(); // eat the '>'.
1803 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1805 /// BodyItem ::= Declaration ';'
1806 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1807 bool TGParser::ParseBodyItem(Record *CurRec) {
1808 if (Lex.getCode() != tgtok::Let) {
1809 if (ParseDeclaration(CurRec, false) == 0)
1812 if (Lex.getCode() != tgtok::semi)
1813 return TokError("expected ';' after declaration");
1818 // LET ID OptionalRangeList '=' Value ';'
1819 if (Lex.Lex() != tgtok::Id)
1820 return TokError("expected field identifier after let");
1822 SMLoc IdLoc = Lex.getLoc();
1823 std::string FieldName = Lex.getCurStrVal();
1824 Lex.Lex(); // eat the field name.
1826 std::vector<unsigned> BitList;
1827 if (ParseOptionalBitList(BitList))
1829 std::reverse(BitList.begin(), BitList.end());
1831 if (Lex.getCode() != tgtok::equal)
1832 return TokError("expected '=' in let expression");
1833 Lex.Lex(); // eat the '='.
1835 RecordVal *Field = CurRec->getValue(FieldName);
1837 return TokError("Value '" + FieldName + "' unknown!");
1839 RecTy *Type = Field->getType();
1841 Init *Val = ParseValue(CurRec, Type);
1842 if (Val == 0) return true;
1844 if (Lex.getCode() != tgtok::semi)
1845 return TokError("expected ';' after let expression");
1848 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1851 /// ParseBody - Read the body of a class or def. Return true on error, false on
1855 /// Body ::= '{' BodyList '}'
1856 /// BodyList BodyItem*
1858 bool TGParser::ParseBody(Record *CurRec) {
1859 // If this is a null definition, just eat the semi and return.
1860 if (Lex.getCode() == tgtok::semi) {
1865 if (Lex.getCode() != tgtok::l_brace)
1866 return TokError("Expected ';' or '{' to start body");
1870 while (Lex.getCode() != tgtok::r_brace)
1871 if (ParseBodyItem(CurRec))
1879 /// \brief Apply the current let bindings to \a CurRec.
1880 /// \returns true on error, false otherwise.
1881 bool TGParser::ApplyLetStack(Record *CurRec) {
1882 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1883 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1884 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1885 LetStack[i][j].Bits, LetStack[i][j].Value))
1890 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1891 /// optional ClassList followed by a Body. CurRec is the current def or class
1892 /// that is being parsed.
1894 /// ObjectBody ::= BaseClassList Body
1895 /// BaseClassList ::= /*empty*/
1896 /// BaseClassList ::= ':' BaseClassListNE
1897 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1899 bool TGParser::ParseObjectBody(Record *CurRec) {
1900 // If there is a baseclass list, read it.
1901 if (Lex.getCode() == tgtok::colon) {
1904 // Read all of the subclasses.
1905 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1908 if (SubClass.Rec == 0) return true;
1911 if (AddSubClass(CurRec, SubClass))
1914 if (Lex.getCode() != tgtok::comma) break;
1915 Lex.Lex(); // eat ','.
1916 SubClass = ParseSubClassReference(CurRec, false);
1920 if (ApplyLetStack(CurRec))
1923 return ParseBody(CurRec);
1926 /// ParseDef - Parse and return a top level or multiclass def, return the record
1927 /// corresponding to it. This returns null on error.
1929 /// DefInst ::= DEF ObjectName ObjectBody
1931 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1932 SMLoc DefLoc = Lex.getLoc();
1933 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1934 Lex.Lex(); // Eat the 'def' token.
1936 // Parse ObjectName and make a record for it.
1938 Init *Name = ParseObjectName(CurMultiClass);
1940 CurRec = new Record(Name, DefLoc, Records);
1942 CurRec = new Record(GetNewAnonymousName(), DefLoc, Records,
1943 /*IsAnonymous=*/true);
1945 if (!CurMultiClass && Loops.empty()) {
1946 // Top-level def definition.
1948 // Ensure redefinition doesn't happen.
1949 if (Records.getDef(CurRec->getNameInitAsString())) {
1950 Error(DefLoc, "def '" + CurRec->getNameInitAsString()
1951 + "' already defined");
1954 Records.addDef(CurRec);
1955 } else if (CurMultiClass) {
1956 // Otherwise, a def inside a multiclass, add it to the multiclass.
1957 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1958 if (CurMultiClass->DefPrototypes[i]->getNameInit()
1959 == CurRec->getNameInit()) {
1960 Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
1961 "' already defined in this multiclass!");
1964 CurMultiClass->DefPrototypes.push_back(CurRec);
1967 if (ParseObjectBody(CurRec))
1970 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1971 // See Record::setName(). This resolve step will see any new name
1972 // for the def that might have been created when resolving
1973 // inheritance, values and arguments above.
1974 CurRec->resolveReferences();
1976 // If ObjectBody has template arguments, it's an error.
1977 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1979 if (CurMultiClass) {
1980 // Copy the template arguments for the multiclass into the def.
1981 const std::vector<Init *> &TArgs =
1982 CurMultiClass->Rec.getTemplateArgs();
1984 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1985 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1986 assert(RV && "Template arg doesn't exist?");
1987 CurRec->addValue(*RV);
1991 if (ProcessForeachDefs(CurRec, DefLoc)) {
1993 "Could not process loops for def" + CurRec->getNameInitAsString());
2000 /// ParseForeach - Parse a for statement. Return the record corresponding
2001 /// to it. This returns true on error.
2003 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2004 /// Foreach ::= FOREACH Declaration IN Object
2006 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2007 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2008 Lex.Lex(); // Eat the 'for' token.
2010 // Make a temporary object to record items associated with the for
2012 ListInit *ListValue = 0;
2013 VarInit *IterName = ParseForeachDeclaration(ListValue);
2015 return TokError("expected declaration in for");
2017 if (Lex.getCode() != tgtok::In)
2018 return TokError("Unknown tok");
2019 Lex.Lex(); // Eat the in
2021 // Create a loop object and remember it.
2022 Loops.push_back(ForeachLoop(IterName, ListValue));
2024 if (Lex.getCode() != tgtok::l_brace) {
2025 // FOREACH Declaration IN Object
2026 if (ParseObject(CurMultiClass))
2030 SMLoc BraceLoc = Lex.getLoc();
2031 // Otherwise, this is a group foreach.
2032 Lex.Lex(); // eat the '{'.
2034 // Parse the object list.
2035 if (ParseObjectList(CurMultiClass))
2038 if (Lex.getCode() != tgtok::r_brace) {
2039 TokError("expected '}' at end of foreach command");
2040 return Error(BraceLoc, "to match this '{'");
2042 Lex.Lex(); // Eat the }
2045 // We've processed everything in this loop.
2051 /// ParseClass - Parse a tblgen class definition.
2053 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2055 bool TGParser::ParseClass() {
2056 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2059 if (Lex.getCode() != tgtok::Id)
2060 return TokError("expected class name after 'class' keyword");
2062 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2064 // If the body was previously defined, this is an error.
2065 if (CurRec->getValues().size() > 1 || // Account for NAME.
2066 !CurRec->getSuperClasses().empty() ||
2067 !CurRec->getTemplateArgs().empty())
2068 return TokError("Class '" + CurRec->getNameInitAsString()
2069 + "' already defined");
2071 // If this is the first reference to this class, create and add it.
2072 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
2073 Records.addClass(CurRec);
2075 Lex.Lex(); // eat the name.
2077 // If there are template args, parse them.
2078 if (Lex.getCode() == tgtok::less)
2079 if (ParseTemplateArgList(CurRec))
2082 // Finally, parse the object body.
2083 return ParseObjectBody(CurRec);
2086 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2089 /// LetList ::= LetItem (',' LetItem)*
2090 /// LetItem ::= ID OptionalRangeList '=' Value
2092 std::vector<LetRecord> TGParser::ParseLetList() {
2093 std::vector<LetRecord> Result;
2096 if (Lex.getCode() != tgtok::Id) {
2097 TokError("expected identifier in let definition");
2098 return std::vector<LetRecord>();
2100 std::string Name = Lex.getCurStrVal();
2101 SMLoc NameLoc = Lex.getLoc();
2102 Lex.Lex(); // Eat the identifier.
2104 // Check for an optional RangeList.
2105 std::vector<unsigned> Bits;
2106 if (ParseOptionalRangeList(Bits))
2107 return std::vector<LetRecord>();
2108 std::reverse(Bits.begin(), Bits.end());
2110 if (Lex.getCode() != tgtok::equal) {
2111 TokError("expected '=' in let expression");
2112 return std::vector<LetRecord>();
2114 Lex.Lex(); // eat the '='.
2116 Init *Val = ParseValue(0);
2117 if (Val == 0) return std::vector<LetRecord>();
2119 // Now that we have everything, add the record.
2120 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2122 if (Lex.getCode() != tgtok::comma)
2124 Lex.Lex(); // eat the comma.
2128 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2129 /// different related productions. This works inside multiclasses too.
2131 /// Object ::= LET LetList IN '{' ObjectList '}'
2132 /// Object ::= LET LetList IN Object
2134 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2135 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2138 // Add this entry to the let stack.
2139 std::vector<LetRecord> LetInfo = ParseLetList();
2140 if (LetInfo.empty()) return true;
2141 LetStack.push_back(LetInfo);
2143 if (Lex.getCode() != tgtok::In)
2144 return TokError("expected 'in' at end of top-level 'let'");
2147 // If this is a scalar let, just handle it now
2148 if (Lex.getCode() != tgtok::l_brace) {
2149 // LET LetList IN Object
2150 if (ParseObject(CurMultiClass))
2152 } else { // Object ::= LETCommand '{' ObjectList '}'
2153 SMLoc BraceLoc = Lex.getLoc();
2154 // Otherwise, this is a group let.
2155 Lex.Lex(); // eat the '{'.
2157 // Parse the object list.
2158 if (ParseObjectList(CurMultiClass))
2161 if (Lex.getCode() != tgtok::r_brace) {
2162 TokError("expected '}' at end of top level let command");
2163 return Error(BraceLoc, "to match this '{'");
2168 // Outside this let scope, this let block is not active.
2169 LetStack.pop_back();
2173 /// ParseMultiClass - Parse a multiclass definition.
2175 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2176 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2177 /// MultiClassObject ::= DefInst
2178 /// MultiClassObject ::= MultiClassInst
2179 /// MultiClassObject ::= DefMInst
2180 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
2181 /// MultiClassObject ::= LETCommand Object
2183 bool TGParser::ParseMultiClass() {
2184 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2185 Lex.Lex(); // Eat the multiclass token.
2187 if (Lex.getCode() != tgtok::Id)
2188 return TokError("expected identifier after multiclass for name");
2189 std::string Name = Lex.getCurStrVal();
2191 if (MultiClasses.count(Name))
2192 return TokError("multiclass '" + Name + "' already defined");
2194 CurMultiClass = MultiClasses[Name] = new MultiClass(Name,
2195 Lex.getLoc(), Records);
2196 Lex.Lex(); // Eat the identifier.
2198 // If there are template args, parse them.
2199 if (Lex.getCode() == tgtok::less)
2200 if (ParseTemplateArgList(0))
2203 bool inherits = false;
2205 // If there are submulticlasses, parse them.
2206 if (Lex.getCode() == tgtok::colon) {
2211 // Read all of the submulticlasses.
2212 SubMultiClassReference SubMultiClass =
2213 ParseSubMultiClassReference(CurMultiClass);
2216 if (SubMultiClass.MC == 0) return true;
2219 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2222 if (Lex.getCode() != tgtok::comma) break;
2223 Lex.Lex(); // eat ','.
2224 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2228 if (Lex.getCode() != tgtok::l_brace) {
2230 return TokError("expected '{' in multiclass definition");
2231 else if (Lex.getCode() != tgtok::semi)
2232 return TokError("expected ';' in multiclass definition");
2234 Lex.Lex(); // eat the ';'.
2236 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2237 return TokError("multiclass must contain at least one def");
2239 while (Lex.getCode() != tgtok::r_brace) {
2240 switch (Lex.getCode()) {
2242 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2246 case tgtok::Foreach:
2247 if (ParseObject(CurMultiClass))
2252 Lex.Lex(); // eat the '}'.
2260 InstantiateMulticlassDef(MultiClass &MC,
2263 SMRange DefmPrefixRange) {
2264 // We need to preserve DefProto so it can be reused for later
2265 // instantiations, so create a new Record to inherit from it.
2267 // Add in the defm name. If the defm prefix is empty, give each
2268 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2269 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2272 bool IsAnonymous = false;
2273 if (DefmPrefix == 0) {
2274 DefmPrefix = StringInit::get(GetNewAnonymousName());
2278 Init *DefName = DefProto->getNameInit();
2280 StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2282 if (DefNameString != 0) {
2283 // We have a fully expanded string so there are no operators to
2284 // resolve. We should concatenate the given prefix and name.
2286 BinOpInit::get(BinOpInit::STRCONCAT,
2287 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2288 StringRecTy::get())->Fold(DefProto, &MC),
2289 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2292 // Make a trail of SMLocs from the multiclass instantiations.
2293 SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
2294 Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2295 Record *CurRec = new Record(DefName, Locs, Records, IsAnonymous);
2297 SubClassReference Ref;
2298 Ref.RefRange = DefmPrefixRange;
2300 AddSubClass(CurRec, Ref);
2302 // Set the value for NAME. We don't resolve references to it 'til later,
2303 // though, so that uses in nested multiclass names don't get
2305 if (SetValue(CurRec, Ref.RefRange.Start, "NAME", std::vector<unsigned>(),
2307 Error(DefmPrefixRange.Start, "Could not resolve "
2308 + CurRec->getNameInitAsString() + ":NAME to '"
2309 + DefmPrefix->getAsUnquotedString() + "'");
2313 // If the DefNameString didn't resolve, we probably have a reference to
2314 // NAME and need to replace it. We need to do at least this much greedily,
2315 // otherwise nested multiclasses will end up with incorrect NAME expansions.
2316 if (DefNameString == 0) {
2317 RecordVal *DefNameRV = CurRec->getValue("NAME");
2318 CurRec->resolveReferencesTo(DefNameRV);
2321 if (!CurMultiClass) {
2322 // Now that we're at the top level, resolve all NAME references
2323 // in the resultant defs that weren't in the def names themselves.
2324 RecordVal *DefNameRV = CurRec->getValue("NAME");
2325 CurRec->resolveReferencesTo(DefNameRV);
2327 // Now that NAME references are resolved and we're at the top level of
2328 // any multiclass expansions, add the record to the RecordKeeper. If we are
2329 // currently in a multiclass, it means this defm appears inside a
2330 // multiclass and its name won't be fully resolvable until we see
2331 // the top-level defm. Therefore, we don't add this to the
2332 // RecordKeeper at this point. If we did we could get duplicate
2333 // defs as more than one probably refers to NAME or some other
2334 // common internal placeholder.
2336 // Ensure redefinition doesn't happen.
2337 if (Records.getDef(CurRec->getNameInitAsString())) {
2338 Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
2339 "' already defined, instantiating defm with subdef '" +
2340 DefProto->getNameInitAsString() + "'");
2344 Records.addDef(CurRec);
2350 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2352 SMLoc DefmPrefixLoc,
2354 const std::vector<Init *> &TArgs,
2355 std::vector<Init *> &TemplateVals,
2357 // Loop over all of the template arguments, setting them to the specified
2358 // value or leaving them as the default if necessary.
2359 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2360 // Check if a value is specified for this temp-arg.
2361 if (i < TemplateVals.size()) {
2363 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2368 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2372 CurRec->removeValue(TArgs[i]);
2374 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2375 return Error(SubClassLoc, "value not specified for template argument #"+
2376 utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2377 + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2384 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2387 SMLoc DefmPrefixLoc) {
2388 // If the mdef is inside a 'let' expression, add to each def.
2389 if (ApplyLetStack(CurRec))
2390 return Error(DefmPrefixLoc, "when instantiating this defm");
2392 // Don't create a top level definition for defm inside multiclasses,
2393 // instead, only update the prototypes and bind the template args
2394 // with the new created definition.
2397 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2399 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2400 == CurRec->getNameInit())
2401 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2402 "' already defined in this multiclass!");
2403 CurMultiClass->DefPrototypes.push_back(CurRec);
2405 // Copy the template arguments for the multiclass into the new def.
2406 const std::vector<Init *> &TA =
2407 CurMultiClass->Rec.getTemplateArgs();
2409 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2410 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2411 assert(RV && "Template arg doesn't exist?");
2412 CurRec->addValue(*RV);
2418 /// ParseDefm - Parse the instantiation of a multiclass.
2420 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2422 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2423 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2424 SMLoc DefmLoc = Lex.getLoc();
2425 Init *DefmPrefix = 0;
2427 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2428 DefmPrefix = ParseObjectName(CurMultiClass);
2431 SMLoc DefmPrefixEndLoc = Lex.getLoc();
2432 if (Lex.getCode() != tgtok::colon)
2433 return TokError("expected ':' after defm identifier");
2435 // Keep track of the new generated record definitions.
2436 std::vector<Record*> NewRecDefs;
2438 // This record also inherits from a regular class (non-multiclass)?
2439 bool InheritFromClass = false;
2444 SMLoc SubClassLoc = Lex.getLoc();
2445 SubClassReference Ref = ParseSubClassReference(0, true);
2448 if (Ref.Rec == 0) return true;
2450 // To instantiate a multiclass, we need to first get the multiclass, then
2451 // instantiate each def contained in the multiclass with the SubClassRef
2452 // template parameters.
2453 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2454 assert(MC && "Didn't lookup multiclass correctly?");
2455 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2457 // Verify that the correct number of template arguments were specified.
2458 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2459 if (TArgs.size() < TemplateVals.size())
2460 return Error(SubClassLoc,
2461 "more template args specified than multiclass expects");
2463 // Loop over all the def's in the multiclass, instantiating each one.
2464 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2465 Record *DefProto = MC->DefPrototypes[i];
2467 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix,
2473 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
2474 TArgs, TemplateVals, true/*Delete args*/))
2475 return Error(SubClassLoc, "could not instantiate def");
2477 if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmLoc))
2478 return Error(SubClassLoc, "could not instantiate def");
2480 NewRecDefs.push_back(CurRec);
2484 if (Lex.getCode() != tgtok::comma) break;
2485 Lex.Lex(); // eat ','.
2487 SubClassLoc = Lex.getLoc();
2489 // A defm can inherit from regular classes (non-multiclass) as
2490 // long as they come in the end of the inheritance list.
2491 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != 0);
2493 if (InheritFromClass)
2496 Ref = ParseSubClassReference(0, true);
2499 if (InheritFromClass) {
2500 // Process all the classes to inherit as if they were part of a
2501 // regular 'def' and inherit all record values.
2502 SubClassReference SubClass = ParseSubClassReference(0, false);
2505 if (SubClass.Rec == 0) return true;
2507 // Get the expanded definition prototypes and teach them about
2508 // the record values the current class to inherit has
2509 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2510 Record *CurRec = NewRecDefs[i];
2513 if (AddSubClass(CurRec, SubClass))
2516 if (ApplyLetStack(CurRec))
2520 if (Lex.getCode() != tgtok::comma) break;
2521 Lex.Lex(); // eat ','.
2522 SubClass = ParseSubClassReference(0, false);
2527 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2528 // See Record::setName(). This resolve step will see any new
2529 // name for the def that might have been created when resolving
2530 // inheritance, values and arguments above.
2531 NewRecDefs[i]->resolveReferences();
2533 if (Lex.getCode() != tgtok::semi)
2534 return TokError("expected ';' at end of defm");
2541 /// Object ::= ClassInst
2542 /// Object ::= DefInst
2543 /// Object ::= MultiClassInst
2544 /// Object ::= DefMInst
2545 /// Object ::= LETCommand '{' ObjectList '}'
2546 /// Object ::= LETCommand Object
2547 bool TGParser::ParseObject(MultiClass *MC) {
2548 switch (Lex.getCode()) {
2550 return TokError("Expected class, def, defm, multiclass or let definition");
2551 case tgtok::Let: return ParseTopLevelLet(MC);
2552 case tgtok::Def: return ParseDef(MC);
2553 case tgtok::Foreach: return ParseForeach(MC);
2554 case tgtok::Defm: return ParseDefm(MC);
2555 case tgtok::Class: return ParseClass();
2556 case tgtok::MultiClass: return ParseMultiClass();
2561 /// ObjectList :== Object*
2562 bool TGParser::ParseObjectList(MultiClass *MC) {
2563 while (isObjectStart(Lex.getCode())) {
2564 if (ParseObject(MC))
2570 bool TGParser::ParseFile() {
2571 Lex.Lex(); // Prime the lexer.
2572 if (ParseObjectList()) return true;
2574 // If we have unread input at the end of the file, report it.
2575 if (Lex.getCode() == tgtok::Eof)
2578 return TokError("Unexpected input at top level");