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.RefLoc, 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.RefLoc, "More template args specified than expected");
162 // Loop over all of the template arguments, setting them to the specified
163 // value or leaving them as the default if necessary.
164 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
165 if (i < SubClass.TemplateArgs.size()) {
166 // If a value is specified for this template arg, set it now.
167 if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(),
168 SubClass.TemplateArgs[i]))
172 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
175 CurRec->removeValue(TArgs[i]);
177 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
178 return Error(SubClass.RefLoc,"Value not specified for template argument #"
179 + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
180 + ") of subclass '" + SC->getNameInitAsString() + "'!");
184 // Since everything went well, we can now set the "superclass" list for the
186 const std::vector<Record*> &SCs = SC->getSuperClasses();
187 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
188 if (CurRec->isSubClassOf(SCs[i]))
189 return Error(SubClass.RefLoc,
190 "Already subclass of '" + SCs[i]->getName() + "'!\n");
191 CurRec->addSuperClass(SCs[i]);
194 if (CurRec->isSubClassOf(SC))
195 return Error(SubClass.RefLoc,
196 "Already subclass of '" + SC->getName() + "'!\n");
197 CurRec->addSuperClass(SC);
201 /// AddSubMultiClass - Add SubMultiClass as a subclass to
202 /// CurMC, resolving its template args as SubMultiClass's
203 /// template arguments.
204 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
205 SubMultiClassReference &SubMultiClass) {
206 MultiClass *SMC = SubMultiClass.MC;
207 Record *CurRec = &CurMC->Rec;
209 const std::vector<RecordVal> &MCVals = CurRec->getValues();
211 // Add all of the values in the subclass into the current class.
212 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
213 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
214 if (AddValue(CurRec, SubMultiClass.RefLoc, SMCVals[i]))
217 int newDefStart = CurMC->DefPrototypes.size();
219 // Add all of the defs in the subclass into the current multiclass.
220 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
221 iend = SMC->DefPrototypes.end();
224 // Clone the def and add it to the current multiclass
225 Record *NewDef = new Record(**i);
227 // Add all of the values in the superclass into the current def.
228 for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
229 if (AddValue(NewDef, SubMultiClass.RefLoc, MCVals[i]))
232 CurMC->DefPrototypes.push_back(NewDef);
235 const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
237 // Ensure that an appropriate number of template arguments are
239 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
240 return Error(SubMultiClass.RefLoc,
241 "More template args specified than expected");
243 // Loop over all of the template arguments, setting them to the specified
244 // value or leaving them as the default if necessary.
245 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
246 if (i < SubMultiClass.TemplateArgs.size()) {
247 // If a value is specified for this template arg, set it in the
249 if (SetValue(CurRec, SubMultiClass.RefLoc, SMCTArgs[i],
250 std::vector<unsigned>(),
251 SubMultiClass.TemplateArgs[i]))
255 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
258 CurRec->removeValue(SMCTArgs[i]);
260 // If a value is specified for this template arg, set it in the
262 for (MultiClass::RecordVector::iterator j =
263 CurMC->DefPrototypes.begin() + newDefStart,
264 jend = CurMC->DefPrototypes.end();
269 if (SetValue(Def, SubMultiClass.RefLoc, SMCTArgs[i],
270 std::vector<unsigned>(),
271 SubMultiClass.TemplateArgs[i]))
275 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
278 Def->removeValue(SMCTArgs[i]);
280 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
281 return Error(SubMultiClass.RefLoc,
282 "Value not specified for template argument #"
283 + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
284 + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
291 /// ProcessForeachDefs - Given a record, apply all of the variable
292 /// values in all surrounding foreach loops, creating new records for
293 /// each combination of values.
294 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
298 // We want to instantiate a new copy of CurRec for each combination
299 // of nested loop iterator values. We don't want top instantiate
300 // any copies until we have values for each loop iterator.
302 return ProcessForeachDefs(CurRec, Loc, IterVals);
305 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
306 /// apply each of the variable values in this loop and then process
308 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
309 // Recursively build a tuple of iterator values.
310 if (IterVals.size() != Loops.size()) {
311 assert(IterVals.size() < Loops.size());
312 ForeachLoop &CurLoop = Loops[IterVals.size()];
313 ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
315 Error(Loc, "Loop list is not a list");
319 // Process each value.
320 for (int64_t i = 0; i < List->getSize(); ++i) {
321 Init *ItemVal = List->resolveListElementReference(*CurRec, 0, i);
322 IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
323 if (ProcessForeachDefs(CurRec, Loc, IterVals))
330 // This is the bottom of the recursion. We have all of the iterator values
331 // for this point in the iteration space. Instantiate a new record to
332 // reflect this combination of values.
333 Record *IterRec = new Record(*CurRec);
335 // Set the iterator values now.
336 for (unsigned i = 0, e = IterVals.size(); i != e; ++i) {
337 VarInit *IterVar = IterVals[i].IterVar;
338 TypedInit *IVal = dyn_cast<TypedInit>(IterVals[i].IterValue);
340 Error(Loc, "foreach iterator value is untyped");
344 IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
346 if (SetValue(IterRec, Loc, IterVar->getName(),
347 std::vector<unsigned>(), IVal)) {
348 Error(Loc, "when instantiating this def");
353 IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
356 IterRec->removeValue(IterVar->getName());
359 if (Records.getDef(IterRec->getNameInitAsString())) {
360 Error(Loc, "def already exists: " + IterRec->getNameInitAsString());
364 Records.addDef(IterRec);
365 IterRec->resolveReferences();
369 //===----------------------------------------------------------------------===//
371 //===----------------------------------------------------------------------===//
373 /// isObjectStart - Return true if this is a valid first token for an Object.
374 static bool isObjectStart(tgtok::TokKind K) {
375 return K == tgtok::Class || K == tgtok::Def ||
376 K == tgtok::Defm || K == tgtok::Let ||
377 K == tgtok::MultiClass || K == tgtok::Foreach;
380 static std::string GetNewAnonymousName() {
381 static unsigned AnonCounter = 0;
382 return "anonymous."+utostr(AnonCounter++);
385 /// ParseObjectName - If an object name is specified, return it. Otherwise,
386 /// return an anonymous name.
387 /// ObjectName ::= Value [ '#' Value ]*
388 /// ObjectName ::= /*empty*/
390 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
391 switch (Lex.getCode()) {
395 // These are all of the tokens that can begin an object body.
396 // Some of these can also begin values but we disallow those cases
397 // because they are unlikely to be useful.
398 return StringInit::get(GetNewAnonymousName());
405 CurRec = &CurMultiClass->Rec;
409 const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
411 TokError("Record name is not typed!");
414 Type = CurRecName->getType();
417 return ParseValue(CurRec, Type, ParseNameMode);
420 /// ParseClassID - Parse and resolve a reference to a class name. This returns
425 Record *TGParser::ParseClassID() {
426 if (Lex.getCode() != tgtok::Id) {
427 TokError("expected name for ClassID");
431 Record *Result = Records.getClass(Lex.getCurStrVal());
433 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
439 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
440 /// This returns null on error.
442 /// MultiClassID ::= ID
444 MultiClass *TGParser::ParseMultiClassID() {
445 if (Lex.getCode() != tgtok::Id) {
446 TokError("expected name for MultiClassID");
450 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
452 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
458 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
459 /// subclass. This returns a SubClassRefTy with a null Record* on error.
461 /// SubClassRef ::= ClassID
462 /// SubClassRef ::= ClassID '<' ValueList '>'
464 SubClassReference TGParser::
465 ParseSubClassReference(Record *CurRec, bool isDefm) {
466 SubClassReference Result;
467 Result.RefLoc = Lex.getLoc();
470 if (MultiClass *MC = ParseMultiClassID())
471 Result.Rec = &MC->Rec;
473 Result.Rec = ParseClassID();
475 if (Result.Rec == 0) return Result;
477 // If there is no template arg list, we're done.
478 if (Lex.getCode() != tgtok::less)
480 Lex.Lex(); // Eat the '<'
482 if (Lex.getCode() == tgtok::greater) {
483 TokError("subclass reference requires a non-empty list of template values");
488 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
489 if (Result.TemplateArgs.empty()) {
490 Result.Rec = 0; // Error parsing value list.
494 if (Lex.getCode() != tgtok::greater) {
495 TokError("expected '>' in template value list");
504 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
505 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
506 /// Record* on error.
508 /// SubMultiClassRef ::= MultiClassID
509 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
511 SubMultiClassReference TGParser::
512 ParseSubMultiClassReference(MultiClass *CurMC) {
513 SubMultiClassReference Result;
514 Result.RefLoc = Lex.getLoc();
516 Result.MC = ParseMultiClassID();
517 if (Result.MC == 0) return Result;
519 // If there is no template arg list, we're done.
520 if (Lex.getCode() != tgtok::less)
522 Lex.Lex(); // Eat the '<'
524 if (Lex.getCode() == tgtok::greater) {
525 TokError("subclass reference requires a non-empty list of template values");
530 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
531 if (Result.TemplateArgs.empty()) {
532 Result.MC = 0; // Error parsing value list.
536 if (Lex.getCode() != tgtok::greater) {
537 TokError("expected '>' in template value list");
546 /// ParseRangePiece - Parse a bit/value range.
547 /// RangePiece ::= INTVAL
548 /// RangePiece ::= INTVAL '-' INTVAL
549 /// RangePiece ::= INTVAL INTVAL
550 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
551 if (Lex.getCode() != tgtok::IntVal) {
552 TokError("expected integer or bitrange");
555 int64_t Start = Lex.getCurIntVal();
559 return TokError("invalid range, cannot be negative");
561 switch (Lex.Lex()) { // eat first character.
563 Ranges.push_back(Start);
566 if (Lex.Lex() != tgtok::IntVal) {
567 TokError("expected integer value as end of range");
570 End = Lex.getCurIntVal();
573 End = -Lex.getCurIntVal();
577 return TokError("invalid range, cannot be negative");
582 for (; Start <= End; ++Start)
583 Ranges.push_back(Start);
585 for (; Start >= End; --Start)
586 Ranges.push_back(Start);
591 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
593 /// RangeList ::= RangePiece (',' RangePiece)*
595 std::vector<unsigned> TGParser::ParseRangeList() {
596 std::vector<unsigned> Result;
598 // Parse the first piece.
599 if (ParseRangePiece(Result))
600 return std::vector<unsigned>();
601 while (Lex.getCode() == tgtok::comma) {
602 Lex.Lex(); // Eat the comma.
604 // Parse the next range piece.
605 if (ParseRangePiece(Result))
606 return std::vector<unsigned>();
611 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
612 /// OptionalRangeList ::= '<' RangeList '>'
613 /// OptionalRangeList ::= /*empty*/
614 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
615 if (Lex.getCode() != tgtok::less)
618 SMLoc StartLoc = Lex.getLoc();
619 Lex.Lex(); // eat the '<'
621 // Parse the range list.
622 Ranges = ParseRangeList();
623 if (Ranges.empty()) return true;
625 if (Lex.getCode() != tgtok::greater) {
626 TokError("expected '>' at end of range list");
627 return Error(StartLoc, "to match this '<'");
629 Lex.Lex(); // eat the '>'.
633 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
634 /// OptionalBitList ::= '{' RangeList '}'
635 /// OptionalBitList ::= /*empty*/
636 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
637 if (Lex.getCode() != tgtok::l_brace)
640 SMLoc StartLoc = Lex.getLoc();
641 Lex.Lex(); // eat the '{'
643 // Parse the range list.
644 Ranges = ParseRangeList();
645 if (Ranges.empty()) return true;
647 if (Lex.getCode() != tgtok::r_brace) {
648 TokError("expected '}' at end of bit list");
649 return Error(StartLoc, "to match this '{'");
651 Lex.Lex(); // eat the '}'.
656 /// ParseType - Parse and return a tblgen type. This returns null on error.
658 /// Type ::= STRING // string type
659 /// Type ::= CODE // code type
660 /// Type ::= BIT // bit type
661 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
662 /// Type ::= INT // int type
663 /// Type ::= LIST '<' Type '>' // list<x> type
664 /// Type ::= DAG // dag type
665 /// Type ::= ClassID // Record Type
667 RecTy *TGParser::ParseType() {
668 switch (Lex.getCode()) {
669 default: TokError("Unknown token when expecting a type"); return 0;
670 case tgtok::String: Lex.Lex(); return StringRecTy::get();
671 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
672 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
673 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
674 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
676 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
679 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
680 TokError("expected '<' after bits type");
683 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
684 TokError("expected integer in bits<n> type");
687 uint64_t Val = Lex.getCurIntVal();
688 if (Lex.Lex() != tgtok::greater) { // Eat count.
689 TokError("expected '>' at end of bits<n> type");
692 Lex.Lex(); // Eat '>'
693 return BitsRecTy::get(Val);
696 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
697 TokError("expected '<' after list type");
700 Lex.Lex(); // Eat '<'
701 RecTy *SubType = ParseType();
702 if (SubType == 0) return 0;
704 if (Lex.getCode() != tgtok::greater) {
705 TokError("expected '>' at end of list<ty> type");
708 Lex.Lex(); // Eat '>'
709 return ListRecTy::get(SubType);
714 /// ParseIDValue - Parse an ID as a value and decode what it means.
716 /// IDValue ::= ID [def local value]
717 /// IDValue ::= ID [def template arg]
718 /// IDValue ::= ID [multiclass local value]
719 /// IDValue ::= ID [multiclass template argument]
720 /// IDValue ::= ID [def name]
722 Init *TGParser::ParseIDValue(Record *CurRec, IDParseMode Mode) {
723 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
724 std::string Name = Lex.getCurStrVal();
725 SMLoc Loc = Lex.getLoc();
727 return ParseIDValue(CurRec, Name, Loc);
730 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
731 /// has already been read.
732 Init *TGParser::ParseIDValue(Record *CurRec,
733 const std::string &Name, SMLoc NameLoc,
736 if (const RecordVal *RV = CurRec->getValue(Name))
737 return VarInit::get(Name, RV->getType());
739 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
742 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
745 if (CurRec->isTemplateArg(TemplateArgName)) {
746 const RecordVal *RV = CurRec->getValue(TemplateArgName);
747 assert(RV && "Template arg doesn't exist??");
748 return VarInit::get(TemplateArgName, RV->getType());
753 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
756 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
757 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
758 assert(RV && "Template arg doesn't exist??");
759 return VarInit::get(MCName, RV->getType());
763 // If this is in a foreach loop, make sure it's not a loop iterator
764 for (LoopVector::iterator i = Loops.begin(), iend = Loops.end();
767 VarInit *IterVar = dyn_cast<VarInit>(i->IterVar);
768 if (IterVar && IterVar->getName() == Name)
772 if (Mode == ParseNameMode)
773 return StringInit::get(Name);
775 if (Record *D = Records.getDef(Name))
776 return DefInit::get(D);
778 if (Mode == ParseValueMode) {
779 Error(NameLoc, "Variable not defined: '" + Name + "'");
783 return StringInit::get(Name);
786 /// ParseOperation - Parse an operator. This returns null on error.
788 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
790 Init *TGParser::ParseOperation(Record *CurRec) {
791 switch (Lex.getCode()) {
793 TokError("unknown operation");
798 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
799 UnOpInit::UnaryOp Code;
802 switch (Lex.getCode()) {
803 default: llvm_unreachable("Unhandled code!");
805 Lex.Lex(); // eat the operation
806 Code = UnOpInit::CAST;
808 Type = ParseOperatorType();
811 TokError("did not get type for unary operator");
817 Lex.Lex(); // eat the operation
818 Code = UnOpInit::HEAD;
821 Lex.Lex(); // eat the operation
822 Code = UnOpInit::TAIL;
825 Lex.Lex(); // eat the operation
826 Code = UnOpInit::EMPTY;
827 Type = IntRecTy::get();
830 if (Lex.getCode() != tgtok::l_paren) {
831 TokError("expected '(' after unary operator");
834 Lex.Lex(); // eat the '('
836 Init *LHS = ParseValue(CurRec);
837 if (LHS == 0) return 0;
839 if (Code == UnOpInit::HEAD
840 || Code == UnOpInit::TAIL
841 || Code == UnOpInit::EMPTY) {
842 ListInit *LHSl = dyn_cast<ListInit>(LHS);
843 StringInit *LHSs = dyn_cast<StringInit>(LHS);
844 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
845 if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
846 TokError("expected list or string type argument in unary operator");
850 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
851 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
852 if (LType == 0 && SType == 0) {
853 TokError("expected list or string type argumnet in unary operator");
858 if (Code == UnOpInit::HEAD
859 || Code == UnOpInit::TAIL) {
860 if (LHSl == 0 && LHSt == 0) {
861 TokError("expected list type argumnet in unary operator");
865 if (LHSl && LHSl->getSize() == 0) {
866 TokError("empty list argument in unary operator");
870 Init *Item = LHSl->getElement(0);
871 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
873 TokError("untyped list element in unary operator");
876 if (Code == UnOpInit::HEAD) {
877 Type = Itemt->getType();
879 Type = ListRecTy::get(Itemt->getType());
882 assert(LHSt && "expected list type argument in unary operator");
883 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
885 TokError("expected list type argumnet in unary operator");
888 if (Code == UnOpInit::HEAD) {
889 Type = LType->getElementType();
897 if (Lex.getCode() != tgtok::r_paren) {
898 TokError("expected ')' in unary operator");
901 Lex.Lex(); // eat the ')'
902 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
910 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
911 tgtok::TokKind OpTok = Lex.getCode();
912 SMLoc OpLoc = Lex.getLoc();
913 Lex.Lex(); // eat the operation
915 BinOpInit::BinaryOp Code;
919 default: llvm_unreachable("Unhandled code!");
920 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
921 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
922 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
923 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
924 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
925 case tgtok::XStrConcat:
926 Code = BinOpInit::STRCONCAT;
927 Type = StringRecTy::get();
931 if (Lex.getCode() != tgtok::l_paren) {
932 TokError("expected '(' after binary operator");
935 Lex.Lex(); // eat the '('
937 SmallVector<Init*, 2> InitList;
939 InitList.push_back(ParseValue(CurRec));
940 if (InitList.back() == 0) return 0;
942 while (Lex.getCode() == tgtok::comma) {
943 Lex.Lex(); // eat the ','
945 InitList.push_back(ParseValue(CurRec));
946 if (InitList.back() == 0) return 0;
949 if (Lex.getCode() != tgtok::r_paren) {
950 TokError("expected ')' in operator");
953 Lex.Lex(); // eat the ')'
955 // We allow multiple operands to associative operators like !strconcat as
956 // shorthand for nesting them.
957 if (Code == BinOpInit::STRCONCAT) {
958 while (InitList.size() > 2) {
959 Init *RHS = InitList.pop_back_val();
960 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
961 ->Fold(CurRec, CurMultiClass);
962 InitList.back() = RHS;
966 if (InitList.size() == 2)
967 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
968 ->Fold(CurRec, CurMultiClass);
970 Error(OpLoc, "expected two operands to operator");
975 case tgtok::XForEach:
976 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
977 TernOpInit::TernaryOp Code;
980 tgtok::TokKind LexCode = Lex.getCode();
981 Lex.Lex(); // eat the operation
983 default: llvm_unreachable("Unhandled code!");
985 Code = TernOpInit::IF;
987 case tgtok::XForEach:
988 Code = TernOpInit::FOREACH;
991 Code = TernOpInit::SUBST;
994 if (Lex.getCode() != tgtok::l_paren) {
995 TokError("expected '(' after ternary operator");
998 Lex.Lex(); // eat the '('
1000 Init *LHS = ParseValue(CurRec);
1001 if (LHS == 0) return 0;
1003 if (Lex.getCode() != tgtok::comma) {
1004 TokError("expected ',' in ternary operator");
1007 Lex.Lex(); // eat the ','
1009 Init *MHS = ParseValue(CurRec);
1010 if (MHS == 0) return 0;
1012 if (Lex.getCode() != tgtok::comma) {
1013 TokError("expected ',' in ternary operator");
1016 Lex.Lex(); // eat the ','
1018 Init *RHS = ParseValue(CurRec);
1019 if (RHS == 0) return 0;
1021 if (Lex.getCode() != tgtok::r_paren) {
1022 TokError("expected ')' in binary operator");
1025 Lex.Lex(); // eat the ')'
1028 default: llvm_unreachable("Unhandled code!");
1033 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1034 MHSTy = MHSt->getType();
1035 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1036 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1037 if (isa<BitInit>(MHS))
1038 MHSTy = BitRecTy::get();
1040 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1041 RHSTy = RHSt->getType();
1042 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1043 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1044 if (isa<BitInit>(RHS))
1045 RHSTy = BitRecTy::get();
1047 // For UnsetInit, it's typed from the other hand.
1048 if (isa<UnsetInit>(MHS))
1050 if (isa<UnsetInit>(RHS))
1053 if (!MHSTy || !RHSTy) {
1054 TokError("could not get type for !if");
1058 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1060 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1063 TokError("inconsistent types for !if");
1068 case tgtok::XForEach: {
1069 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1071 TokError("could not get type for !foreach");
1074 Type = MHSt->getType();
1077 case tgtok::XSubst: {
1078 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1080 TokError("could not get type for !subst");
1083 Type = RHSt->getType();
1087 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1093 /// ParseOperatorType - Parse a type for an operator. This returns
1096 /// OperatorType ::= '<' Type '>'
1098 RecTy *TGParser::ParseOperatorType() {
1101 if (Lex.getCode() != tgtok::less) {
1102 TokError("expected type name for operator");
1105 Lex.Lex(); // eat the <
1110 TokError("expected type name for operator");
1114 if (Lex.getCode() != tgtok::greater) {
1115 TokError("expected type name for operator");
1118 Lex.Lex(); // eat the >
1124 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1126 /// SimpleValue ::= IDValue
1127 /// SimpleValue ::= INTVAL
1128 /// SimpleValue ::= STRVAL+
1129 /// SimpleValue ::= CODEFRAGMENT
1130 /// SimpleValue ::= '?'
1131 /// SimpleValue ::= '{' ValueList '}'
1132 /// SimpleValue ::= ID '<' ValueListNE '>'
1133 /// SimpleValue ::= '[' ValueList ']'
1134 /// SimpleValue ::= '(' IDValue DagArgList ')'
1135 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1136 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1137 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1138 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1139 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1141 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1144 switch (Lex.getCode()) {
1145 default: TokError("Unknown token when parsing a value"); break;
1147 // This is a leading paste operation. This is deprecated but
1148 // still exists in some .td files. Ignore it.
1149 Lex.Lex(); // Skip '#'.
1150 return ParseSimpleValue(CurRec, ItemType, Mode);
1151 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1152 case tgtok::StrVal: {
1153 std::string Val = Lex.getCurStrVal();
1156 // Handle multiple consecutive concatenated strings.
1157 while (Lex.getCode() == tgtok::StrVal) {
1158 Val += Lex.getCurStrVal();
1162 R = StringInit::get(Val);
1165 case tgtok::CodeFragment:
1166 R = StringInit::get(Lex.getCurStrVal());
1169 case tgtok::question:
1170 R = UnsetInit::get();
1174 SMLoc NameLoc = Lex.getLoc();
1175 std::string Name = Lex.getCurStrVal();
1176 if (Lex.Lex() != tgtok::less) // consume the Id.
1177 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1179 // Value ::= ID '<' ValueListNE '>'
1180 if (Lex.Lex() == tgtok::greater) {
1181 TokError("expected non-empty value list");
1185 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1186 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1188 Record *Class = Records.getClass(Name);
1190 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1194 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1195 if (ValueList.empty()) return 0;
1197 if (Lex.getCode() != tgtok::greater) {
1198 TokError("expected '>' at end of value list");
1201 Lex.Lex(); // eat the '>'
1203 // Create the new record, set it as CurRec temporarily.
1204 static unsigned AnonCounter = 0;
1205 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),
1208 SubClassReference SCRef;
1209 SCRef.RefLoc = NameLoc;
1211 SCRef.TemplateArgs = ValueList;
1212 // Add info about the subclass to NewRec.
1213 if (AddSubClass(NewRec, SCRef))
1215 NewRec->resolveReferences();
1216 Records.addDef(NewRec);
1218 // The result of the expression is a reference to the new record.
1219 return DefInit::get(NewRec);
1221 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1222 SMLoc BraceLoc = Lex.getLoc();
1223 Lex.Lex(); // eat the '{'
1224 std::vector<Init*> Vals;
1226 if (Lex.getCode() != tgtok::r_brace) {
1227 Vals = ParseValueList(CurRec);
1228 if (Vals.empty()) return 0;
1230 if (Lex.getCode() != tgtok::r_brace) {
1231 TokError("expected '}' at end of bit list value");
1234 Lex.Lex(); // eat the '}'
1236 SmallVector<Init *, 16> NewBits(Vals.size());
1238 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1239 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1241 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1242 ") is not convertable to a bit");
1245 NewBits[Vals.size()-i-1] = Bit;
1247 return BitsInit::get(NewBits);
1249 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1250 Lex.Lex(); // eat the '['
1251 std::vector<Init*> Vals;
1253 RecTy *DeducedEltTy = 0;
1254 ListRecTy *GivenListTy = 0;
1256 if (ItemType != 0) {
1257 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1258 if (ListType == 0) {
1259 std::stringstream s;
1260 s << "Type mismatch for list, expected list type, got "
1261 << ItemType->getAsString();
1265 GivenListTy = ListType;
1268 if (Lex.getCode() != tgtok::r_square) {
1269 Vals = ParseValueList(CurRec, 0,
1270 GivenListTy ? GivenListTy->getElementType() : 0);
1271 if (Vals.empty()) return 0;
1273 if (Lex.getCode() != tgtok::r_square) {
1274 TokError("expected ']' at end of list value");
1277 Lex.Lex(); // eat the ']'
1279 RecTy *GivenEltTy = 0;
1280 if (Lex.getCode() == tgtok::less) {
1281 // Optional list element type
1282 Lex.Lex(); // eat the '<'
1284 GivenEltTy = ParseType();
1285 if (GivenEltTy == 0) {
1286 // Couldn't parse element type
1290 if (Lex.getCode() != tgtok::greater) {
1291 TokError("expected '>' at end of list element type");
1294 Lex.Lex(); // eat the '>'
1299 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1302 TypedInit *TArg = dyn_cast<TypedInit>(*i);
1304 TokError("Untyped list element");
1308 EltTy = resolveTypes(EltTy, TArg->getType());
1310 TokError("Incompatible types in list elements");
1314 EltTy = TArg->getType();
1318 if (GivenEltTy != 0) {
1320 // Verify consistency
1321 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1322 TokError("Incompatible types in list elements");
1330 if (ItemType == 0) {
1331 TokError("No type for list");
1334 DeducedEltTy = GivenListTy->getElementType();
1336 // Make sure the deduced type is compatible with the given type
1338 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1339 TokError("Element type mismatch for list");
1343 DeducedEltTy = EltTy;
1346 return ListInit::get(Vals, DeducedEltTy);
1348 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1349 Lex.Lex(); // eat the '('
1350 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1351 TokError("expected identifier in dag init");
1355 Init *Operator = ParseValue(CurRec);
1356 if (Operator == 0) return 0;
1358 // If the operator name is present, parse it.
1359 std::string OperatorName;
1360 if (Lex.getCode() == tgtok::colon) {
1361 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1362 TokError("expected variable name in dag operator");
1365 OperatorName = Lex.getCurStrVal();
1366 Lex.Lex(); // eat the VarName.
1369 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1370 if (Lex.getCode() != tgtok::r_paren) {
1371 DagArgs = ParseDagArgList(CurRec);
1372 if (DagArgs.empty()) return 0;
1375 if (Lex.getCode() != tgtok::r_paren) {
1376 TokError("expected ')' in dag init");
1379 Lex.Lex(); // eat the ')'
1381 return DagInit::get(Operator, OperatorName, DagArgs);
1387 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1388 case tgtok::XConcat:
1393 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1395 case tgtok::XForEach:
1396 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1397 return ParseOperation(CurRec);
1404 /// ParseValue - Parse a tblgen value. This returns null on error.
1406 /// Value ::= SimpleValue ValueSuffix*
1407 /// ValueSuffix ::= '{' BitList '}'
1408 /// ValueSuffix ::= '[' BitList ']'
1409 /// ValueSuffix ::= '.' ID
1411 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1412 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1413 if (Result == 0) return 0;
1415 // Parse the suffixes now if present.
1417 switch (Lex.getCode()) {
1418 default: return Result;
1419 case tgtok::l_brace: {
1420 if (Mode == ParseNameMode || Mode == ParseForeachMode)
1421 // This is the beginning of the object body.
1424 SMLoc CurlyLoc = Lex.getLoc();
1425 Lex.Lex(); // eat the '{'
1426 std::vector<unsigned> Ranges = ParseRangeList();
1427 if (Ranges.empty()) return 0;
1429 // Reverse the bitlist.
1430 std::reverse(Ranges.begin(), Ranges.end());
1431 Result = Result->convertInitializerBitRange(Ranges);
1433 Error(CurlyLoc, "Invalid bit range for value");
1438 if (Lex.getCode() != tgtok::r_brace) {
1439 TokError("expected '}' at end of bit range list");
1445 case tgtok::l_square: {
1446 SMLoc SquareLoc = Lex.getLoc();
1447 Lex.Lex(); // eat the '['
1448 std::vector<unsigned> Ranges = ParseRangeList();
1449 if (Ranges.empty()) return 0;
1451 Result = Result->convertInitListSlice(Ranges);
1453 Error(SquareLoc, "Invalid range for list slice");
1458 if (Lex.getCode() != tgtok::r_square) {
1459 TokError("expected ']' at end of list slice");
1466 if (Lex.Lex() != tgtok::Id) { // eat the .
1467 TokError("expected field identifier after '.'");
1470 if (!Result->getFieldType(Lex.getCurStrVal())) {
1471 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1472 Result->getAsString() + "'");
1475 Result = FieldInit::get(Result, Lex.getCurStrVal());
1476 Lex.Lex(); // eat field name
1480 SMLoc PasteLoc = Lex.getLoc();
1482 // Create a !strconcat() operation, first casting each operand to
1483 // a string if necessary.
1485 TypedInit *LHS = dyn_cast<TypedInit>(Result);
1487 Error(PasteLoc, "LHS of paste is not typed!");
1491 if (LHS->getType() != StringRecTy::get()) {
1492 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1497 Lex.Lex(); // Eat the '#'.
1498 switch (Lex.getCode()) {
1501 case tgtok::l_brace:
1502 // These are all of the tokens that can begin an object body.
1503 // Some of these can also begin values but we disallow those cases
1504 // because they are unlikely to be useful.
1506 // Trailing paste, concat with an empty string.
1507 RHS = StringInit::get("");
1511 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1512 RHS = dyn_cast<TypedInit>(RHSResult);
1514 Error(PasteLoc, "RHS of paste is not typed!");
1518 if (RHS->getType() != StringRecTy::get()) {
1519 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1525 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1526 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1532 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1534 /// ParseDagArgList ::= Value (':' VARNAME)?
1535 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1536 std::vector<std::pair<llvm::Init*, std::string> >
1537 TGParser::ParseDagArgList(Record *CurRec) {
1538 std::vector<std::pair<llvm::Init*, std::string> > Result;
1541 Init *Val = ParseValue(CurRec);
1542 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1544 // If the variable name is present, add it.
1545 std::string VarName;
1546 if (Lex.getCode() == tgtok::colon) {
1547 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1548 TokError("expected variable name in dag literal");
1549 return std::vector<std::pair<llvm::Init*, std::string> >();
1551 VarName = Lex.getCurStrVal();
1552 Lex.Lex(); // eat the VarName.
1555 Result.push_back(std::make_pair(Val, VarName));
1557 if (Lex.getCode() != tgtok::comma) break;
1558 Lex.Lex(); // eat the ','
1565 /// ParseValueList - Parse a comma separated list of values, returning them as a
1566 /// vector. Note that this always expects to be able to parse at least one
1567 /// value. It returns an empty list if this is not possible.
1569 /// ValueList ::= Value (',' Value)
1571 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1573 std::vector<Init*> Result;
1574 RecTy *ItemType = EltTy;
1575 unsigned int ArgN = 0;
1576 if (ArgsRec != 0 && EltTy == 0) {
1577 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1578 if (!TArgs.size()) {
1579 TokError("template argument provided to non-template class");
1580 return std::vector<Init*>();
1582 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1584 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1587 assert(RV && "Template argument record not found??");
1588 ItemType = RV->getType();
1591 Result.push_back(ParseValue(CurRec, ItemType));
1592 if (Result.back() == 0) return std::vector<Init*>();
1594 while (Lex.getCode() == tgtok::comma) {
1595 Lex.Lex(); // Eat the comma
1597 if (ArgsRec != 0 && EltTy == 0) {
1598 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1599 if (ArgN >= TArgs.size()) {
1600 TokError("too many template arguments");
1601 return std::vector<Init*>();
1603 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1604 assert(RV && "Template argument record not found??");
1605 ItemType = RV->getType();
1608 Result.push_back(ParseValue(CurRec, ItemType));
1609 if (Result.back() == 0) return std::vector<Init*>();
1616 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1617 /// empty string on error. This can happen in a number of different context's,
1618 /// including within a def or in the template args for a def (which which case
1619 /// CurRec will be non-null) and within the template args for a multiclass (in
1620 /// which case CurRec will be null, but CurMultiClass will be set). This can
1621 /// also happen within a def that is within a multiclass, which will set both
1622 /// CurRec and CurMultiClass.
1624 /// Declaration ::= FIELD? Type ID ('=' Value)?
1626 Init *TGParser::ParseDeclaration(Record *CurRec,
1627 bool ParsingTemplateArgs) {
1628 // Read the field prefix if present.
1629 bool HasField = Lex.getCode() == tgtok::Field;
1630 if (HasField) Lex.Lex();
1632 RecTy *Type = ParseType();
1633 if (Type == 0) return 0;
1635 if (Lex.getCode() != tgtok::Id) {
1636 TokError("Expected identifier in declaration");
1640 SMLoc IdLoc = Lex.getLoc();
1641 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1644 if (ParsingTemplateArgs) {
1646 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1648 assert(CurMultiClass);
1651 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1656 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1659 // If a value is present, parse it.
1660 if (Lex.getCode() == tgtok::equal) {
1662 SMLoc ValLoc = Lex.getLoc();
1663 Init *Val = ParseValue(CurRec, Type);
1665 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1672 /// ParseForeachDeclaration - Read a foreach declaration, returning
1673 /// the name of the declared object or a NULL Init on error. Return
1674 /// the name of the parsed initializer list through ForeachListName.
1676 /// ForeachDeclaration ::= ID '=' '[' ValueList ']'
1677 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
1678 /// ForeachDeclaration ::= ID '=' RangePiece
1680 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1681 if (Lex.getCode() != tgtok::Id) {
1682 TokError("Expected identifier in foreach declaration");
1686 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1689 // If a value is present, parse it.
1690 if (Lex.getCode() != tgtok::equal) {
1691 TokError("Expected '=' in foreach declaration");
1694 Lex.Lex(); // Eat the '='
1696 RecTy *IterType = 0;
1697 std::vector<unsigned> Ranges;
1699 switch (Lex.getCode()) {
1700 default: TokError("Unknown token when expecting a range list"); return 0;
1701 case tgtok::l_square: { // '[' ValueList ']'
1702 Init *List = ParseSimpleValue(0, 0, ParseForeachMode);
1703 ForeachListValue = dyn_cast<ListInit>(List);
1704 if (ForeachListValue == 0) {
1705 TokError("Expected a Value list");
1708 RecTy *ValueType = ForeachListValue->getType();
1709 ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1710 if (ListType == 0) {
1711 TokError("Value list is not of list type");
1714 IterType = ListType->getElementType();
1718 case tgtok::IntVal: { // RangePiece.
1719 if (ParseRangePiece(Ranges))
1724 case tgtok::l_brace: { // '{' RangeList '}'
1725 Lex.Lex(); // eat the '{'
1726 Ranges = ParseRangeList();
1727 if (Lex.getCode() != tgtok::r_brace) {
1728 TokError("expected '}' at end of bit range list");
1736 if (!Ranges.empty()) {
1737 assert(!IterType && "Type already initialized?");
1738 IterType = IntRecTy::get();
1739 std::vector<Init*> Values;
1740 for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
1741 Values.push_back(IntInit::get(Ranges[i]));
1742 ForeachListValue = ListInit::get(Values, IterType);
1748 return VarInit::get(DeclName, IterType);
1751 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1752 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1753 /// template args for a def, which may or may not be in a multiclass. If null,
1754 /// these are the template args for a multiclass.
1756 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1758 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1759 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1760 Lex.Lex(); // eat the '<'
1762 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1764 // Read the first declaration.
1765 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1769 TheRecToAddTo->addTemplateArg(TemplArg);
1771 while (Lex.getCode() == tgtok::comma) {
1772 Lex.Lex(); // eat the ','
1774 // Read the following declarations.
1775 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1778 TheRecToAddTo->addTemplateArg(TemplArg);
1781 if (Lex.getCode() != tgtok::greater)
1782 return TokError("expected '>' at end of template argument list");
1783 Lex.Lex(); // eat the '>'.
1788 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1790 /// BodyItem ::= Declaration ';'
1791 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1792 bool TGParser::ParseBodyItem(Record *CurRec) {
1793 if (Lex.getCode() != tgtok::Let) {
1794 if (ParseDeclaration(CurRec, false) == 0)
1797 if (Lex.getCode() != tgtok::semi)
1798 return TokError("expected ';' after declaration");
1803 // LET ID OptionalRangeList '=' Value ';'
1804 if (Lex.Lex() != tgtok::Id)
1805 return TokError("expected field identifier after let");
1807 SMLoc IdLoc = Lex.getLoc();
1808 std::string FieldName = Lex.getCurStrVal();
1809 Lex.Lex(); // eat the field name.
1811 std::vector<unsigned> BitList;
1812 if (ParseOptionalBitList(BitList))
1814 std::reverse(BitList.begin(), BitList.end());
1816 if (Lex.getCode() != tgtok::equal)
1817 return TokError("expected '=' in let expression");
1818 Lex.Lex(); // eat the '='.
1820 RecordVal *Field = CurRec->getValue(FieldName);
1822 return TokError("Value '" + FieldName + "' unknown!");
1824 RecTy *Type = Field->getType();
1826 Init *Val = ParseValue(CurRec, Type);
1827 if (Val == 0) return true;
1829 if (Lex.getCode() != tgtok::semi)
1830 return TokError("expected ';' after let expression");
1833 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1836 /// ParseBody - Read the body of a class or def. Return true on error, false on
1840 /// Body ::= '{' BodyList '}'
1841 /// BodyList BodyItem*
1843 bool TGParser::ParseBody(Record *CurRec) {
1844 // If this is a null definition, just eat the semi and return.
1845 if (Lex.getCode() == tgtok::semi) {
1850 if (Lex.getCode() != tgtok::l_brace)
1851 return TokError("Expected ';' or '{' to start body");
1855 while (Lex.getCode() != tgtok::r_brace)
1856 if (ParseBodyItem(CurRec))
1864 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1865 /// optional ClassList followed by a Body. CurRec is the current def or class
1866 /// that is being parsed.
1868 /// ObjectBody ::= BaseClassList Body
1869 /// BaseClassList ::= /*empty*/
1870 /// BaseClassList ::= ':' BaseClassListNE
1871 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1873 bool TGParser::ParseObjectBody(Record *CurRec) {
1874 // If there is a baseclass list, read it.
1875 if (Lex.getCode() == tgtok::colon) {
1878 // Read all of the subclasses.
1879 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1882 if (SubClass.Rec == 0) return true;
1885 if (AddSubClass(CurRec, SubClass))
1888 if (Lex.getCode() != tgtok::comma) break;
1889 Lex.Lex(); // eat ','.
1890 SubClass = ParseSubClassReference(CurRec, false);
1894 // Process any variables on the let stack.
1895 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1896 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1897 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1898 LetStack[i][j].Bits, LetStack[i][j].Value))
1901 return ParseBody(CurRec);
1904 /// ParseDef - Parse and return a top level or multiclass def, return the record
1905 /// corresponding to it. This returns null on error.
1907 /// DefInst ::= DEF ObjectName ObjectBody
1909 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1910 SMLoc DefLoc = Lex.getLoc();
1911 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1912 Lex.Lex(); // Eat the 'def' token.
1914 // Parse ObjectName and make a record for it.
1915 Record *CurRec = new Record(ParseObjectName(CurMultiClass), DefLoc, Records);
1917 if (!CurMultiClass && Loops.empty()) {
1918 // Top-level def definition.
1920 // Ensure redefinition doesn't happen.
1921 if (Records.getDef(CurRec->getNameInitAsString())) {
1922 Error(DefLoc, "def '" + CurRec->getNameInitAsString()
1923 + "' already defined");
1926 Records.addDef(CurRec);
1927 } else if (CurMultiClass) {
1928 // Otherwise, a def inside a multiclass, add it to the multiclass.
1929 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1930 if (CurMultiClass->DefPrototypes[i]->getNameInit()
1931 == CurRec->getNameInit()) {
1932 Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
1933 "' already defined in this multiclass!");
1936 CurMultiClass->DefPrototypes.push_back(CurRec);
1939 if (ParseObjectBody(CurRec))
1942 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1943 // See Record::setName(). This resolve step will see any new name
1944 // for the def that might have been created when resolving
1945 // inheritance, values and arguments above.
1946 CurRec->resolveReferences();
1948 // If ObjectBody has template arguments, it's an error.
1949 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1951 if (CurMultiClass) {
1952 // Copy the template arguments for the multiclass into the def.
1953 const std::vector<Init *> &TArgs =
1954 CurMultiClass->Rec.getTemplateArgs();
1956 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1957 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1958 assert(RV && "Template arg doesn't exist?");
1959 CurRec->addValue(*RV);
1963 if (ProcessForeachDefs(CurRec, DefLoc)) {
1965 "Could not process loops for def" + CurRec->getNameInitAsString());
1972 /// ParseForeach - Parse a for statement. Return the record corresponding
1973 /// to it. This returns true on error.
1975 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
1976 /// Foreach ::= FOREACH Declaration IN Object
1978 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
1979 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
1980 Lex.Lex(); // Eat the 'for' token.
1982 // Make a temporary object to record items associated with the for
1984 ListInit *ListValue = 0;
1985 VarInit *IterName = ParseForeachDeclaration(ListValue);
1987 return TokError("expected declaration in for");
1989 if (Lex.getCode() != tgtok::In)
1990 return TokError("Unknown tok");
1991 Lex.Lex(); // Eat the in
1993 // Create a loop object and remember it.
1994 Loops.push_back(ForeachLoop(IterName, ListValue));
1996 if (Lex.getCode() != tgtok::l_brace) {
1997 // FOREACH Declaration IN Object
1998 if (ParseObject(CurMultiClass))
2002 SMLoc BraceLoc = Lex.getLoc();
2003 // Otherwise, this is a group foreach.
2004 Lex.Lex(); // eat the '{'.
2006 // Parse the object list.
2007 if (ParseObjectList(CurMultiClass))
2010 if (Lex.getCode() != tgtok::r_brace) {
2011 TokError("expected '}' at end of foreach command");
2012 return Error(BraceLoc, "to match this '{'");
2014 Lex.Lex(); // Eat the }
2017 // We've processed everything in this loop.
2023 /// ParseClass - Parse a tblgen class definition.
2025 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2027 bool TGParser::ParseClass() {
2028 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2031 if (Lex.getCode() != tgtok::Id)
2032 return TokError("expected class name after 'class' keyword");
2034 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2036 // If the body was previously defined, this is an error.
2037 if (CurRec->getValues().size() > 1 || // Account for NAME.
2038 !CurRec->getSuperClasses().empty() ||
2039 !CurRec->getTemplateArgs().empty())
2040 return TokError("Class '" + CurRec->getNameInitAsString()
2041 + "' already defined");
2043 // If this is the first reference to this class, create and add it.
2044 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
2045 Records.addClass(CurRec);
2047 Lex.Lex(); // eat the name.
2049 // If there are template args, parse them.
2050 if (Lex.getCode() == tgtok::less)
2051 if (ParseTemplateArgList(CurRec))
2054 // Finally, parse the object body.
2055 return ParseObjectBody(CurRec);
2058 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2061 /// LetList ::= LetItem (',' LetItem)*
2062 /// LetItem ::= ID OptionalRangeList '=' Value
2064 std::vector<LetRecord> TGParser::ParseLetList() {
2065 std::vector<LetRecord> Result;
2068 if (Lex.getCode() != tgtok::Id) {
2069 TokError("expected identifier in let definition");
2070 return std::vector<LetRecord>();
2072 std::string Name = Lex.getCurStrVal();
2073 SMLoc NameLoc = Lex.getLoc();
2074 Lex.Lex(); // Eat the identifier.
2076 // Check for an optional RangeList.
2077 std::vector<unsigned> Bits;
2078 if (ParseOptionalRangeList(Bits))
2079 return std::vector<LetRecord>();
2080 std::reverse(Bits.begin(), Bits.end());
2082 if (Lex.getCode() != tgtok::equal) {
2083 TokError("expected '=' in let expression");
2084 return std::vector<LetRecord>();
2086 Lex.Lex(); // eat the '='.
2088 Init *Val = ParseValue(0);
2089 if (Val == 0) return std::vector<LetRecord>();
2091 // Now that we have everything, add the record.
2092 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2094 if (Lex.getCode() != tgtok::comma)
2096 Lex.Lex(); // eat the comma.
2100 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2101 /// different related productions. This works inside multiclasses too.
2103 /// Object ::= LET LetList IN '{' ObjectList '}'
2104 /// Object ::= LET LetList IN Object
2106 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2107 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2110 // Add this entry to the let stack.
2111 std::vector<LetRecord> LetInfo = ParseLetList();
2112 if (LetInfo.empty()) return true;
2113 LetStack.push_back(LetInfo);
2115 if (Lex.getCode() != tgtok::In)
2116 return TokError("expected 'in' at end of top-level 'let'");
2119 // If this is a scalar let, just handle it now
2120 if (Lex.getCode() != tgtok::l_brace) {
2121 // LET LetList IN Object
2122 if (ParseObject(CurMultiClass))
2124 } else { // Object ::= LETCommand '{' ObjectList '}'
2125 SMLoc BraceLoc = Lex.getLoc();
2126 // Otherwise, this is a group let.
2127 Lex.Lex(); // eat the '{'.
2129 // Parse the object list.
2130 if (ParseObjectList(CurMultiClass))
2133 if (Lex.getCode() != tgtok::r_brace) {
2134 TokError("expected '}' at end of top level let command");
2135 return Error(BraceLoc, "to match this '{'");
2140 // Outside this let scope, this let block is not active.
2141 LetStack.pop_back();
2145 /// ParseMultiClass - Parse a multiclass definition.
2147 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2148 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2149 /// MultiClassObject ::= DefInst
2150 /// MultiClassObject ::= MultiClassInst
2151 /// MultiClassObject ::= DefMInst
2152 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
2153 /// MultiClassObject ::= LETCommand Object
2155 bool TGParser::ParseMultiClass() {
2156 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2157 Lex.Lex(); // Eat the multiclass token.
2159 if (Lex.getCode() != tgtok::Id)
2160 return TokError("expected identifier after multiclass for name");
2161 std::string Name = Lex.getCurStrVal();
2163 if (MultiClasses.count(Name))
2164 return TokError("multiclass '" + Name + "' already defined");
2166 CurMultiClass = MultiClasses[Name] = new MultiClass(Name,
2167 Lex.getLoc(), Records);
2168 Lex.Lex(); // Eat the identifier.
2170 // If there are template args, parse them.
2171 if (Lex.getCode() == tgtok::less)
2172 if (ParseTemplateArgList(0))
2175 bool inherits = false;
2177 // If there are submulticlasses, parse them.
2178 if (Lex.getCode() == tgtok::colon) {
2183 // Read all of the submulticlasses.
2184 SubMultiClassReference SubMultiClass =
2185 ParseSubMultiClassReference(CurMultiClass);
2188 if (SubMultiClass.MC == 0) return true;
2191 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2194 if (Lex.getCode() != tgtok::comma) break;
2195 Lex.Lex(); // eat ','.
2196 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2200 if (Lex.getCode() != tgtok::l_brace) {
2202 return TokError("expected '{' in multiclass definition");
2203 else if (Lex.getCode() != tgtok::semi)
2204 return TokError("expected ';' in multiclass definition");
2206 Lex.Lex(); // eat the ';'.
2208 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2209 return TokError("multiclass must contain at least one def");
2211 while (Lex.getCode() != tgtok::r_brace) {
2212 switch (Lex.getCode()) {
2214 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2218 case tgtok::Foreach:
2219 if (ParseObject(CurMultiClass))
2224 Lex.Lex(); // eat the '}'.
2232 InstantiateMulticlassDef(MultiClass &MC,
2235 SMLoc DefmPrefixLoc) {
2236 // We need to preserve DefProto so it can be reused for later
2237 // instantiations, so create a new Record to inherit from it.
2239 // Add in the defm name. If the defm prefix is empty, give each
2240 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2241 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2244 if (DefmPrefix == 0)
2245 DefmPrefix = StringInit::get(GetNewAnonymousName());
2247 Init *DefName = DefProto->getNameInit();
2249 StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2251 if (DefNameString != 0) {
2252 // We have a fully expanded string so there are no operators to
2253 // resolve. We should concatenate the given prefix and name.
2255 BinOpInit::get(BinOpInit::STRCONCAT,
2256 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2257 StringRecTy::get())->Fold(DefProto, &MC),
2258 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2261 // Make a trail of SMLocs from the multiclass instantiations.
2262 SmallVector<SMLoc, 4> Locs(1, DefmPrefixLoc);
2263 Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2264 Record *CurRec = new Record(DefName, Locs, Records);
2266 SubClassReference Ref;
2267 Ref.RefLoc = DefmPrefixLoc;
2269 AddSubClass(CurRec, Ref);
2271 // Set the value for NAME. We don't resolve references to it 'til later,
2272 // though, so that uses in nested multiclass names don't get
2274 if (SetValue(CurRec, Ref.RefLoc, "NAME", std::vector<unsigned>(),
2276 Error(DefmPrefixLoc, "Could not resolve "
2277 + CurRec->getNameInitAsString() + ":NAME to '"
2278 + DefmPrefix->getAsUnquotedString() + "'");
2282 // If the DefNameString didn't resolve, we probably have a reference to
2283 // NAME and need to replace it. We need to do at least this much greedily,
2284 // otherwise nested multiclasses will end up with incorrect NAME expansions.
2285 if (DefNameString == 0) {
2286 RecordVal *DefNameRV = CurRec->getValue("NAME");
2287 CurRec->resolveReferencesTo(DefNameRV);
2290 if (!CurMultiClass) {
2291 // Now that we're at the top level, resolve all NAME references
2292 // in the resultant defs that weren't in the def names themselves.
2293 RecordVal *DefNameRV = CurRec->getValue("NAME");
2294 CurRec->resolveReferencesTo(DefNameRV);
2296 // Now that NAME references are resolved and we're at the top level of
2297 // any multiclass expansions, add the record to the RecordKeeper. If we are
2298 // currently in a multiclass, it means this defm appears inside a
2299 // multiclass and its name won't be fully resolvable until we see
2300 // the top-level defm. Therefore, we don't add this to the
2301 // RecordKeeper at this point. If we did we could get duplicate
2302 // defs as more than one probably refers to NAME or some other
2303 // common internal placeholder.
2305 // Ensure redefinition doesn't happen.
2306 if (Records.getDef(CurRec->getNameInitAsString())) {
2307 Error(DefmPrefixLoc, "def '" + CurRec->getNameInitAsString() +
2308 "' already defined, instantiating defm with subdef '" +
2309 DefProto->getNameInitAsString() + "'");
2313 Records.addDef(CurRec);
2319 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2321 SMLoc DefmPrefixLoc,
2323 const std::vector<Init *> &TArgs,
2324 std::vector<Init *> &TemplateVals,
2326 // Loop over all of the template arguments, setting them to the specified
2327 // value or leaving them as the default if necessary.
2328 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2329 // Check if a value is specified for this temp-arg.
2330 if (i < TemplateVals.size()) {
2332 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2337 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2341 CurRec->removeValue(TArgs[i]);
2343 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2344 return Error(SubClassLoc, "value not specified for template argument #"+
2345 utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2346 + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2353 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2356 SMLoc DefmPrefixLoc) {
2357 // If the mdef is inside a 'let' expression, add to each def.
2358 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2359 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2360 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2361 LetStack[i][j].Bits, LetStack[i][j].Value))
2362 return Error(DefmPrefixLoc, "when instantiating this defm");
2364 // Don't create a top level definition for defm inside multiclasses,
2365 // instead, only update the prototypes and bind the template args
2366 // with the new created definition.
2367 if (CurMultiClass) {
2368 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2370 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2371 == CurRec->getNameInit())
2372 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2373 "' already defined in this multiclass!");
2374 CurMultiClass->DefPrototypes.push_back(CurRec);
2376 // Copy the template arguments for the multiclass into the new def.
2377 const std::vector<Init *> &TA =
2378 CurMultiClass->Rec.getTemplateArgs();
2380 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2381 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2382 assert(RV && "Template arg doesn't exist?");
2383 CurRec->addValue(*RV);
2390 /// ParseDefm - Parse the instantiation of a multiclass.
2392 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2394 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2395 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2397 Init *DefmPrefix = 0;
2399 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2400 DefmPrefix = ParseObjectName(CurMultiClass);
2403 SMLoc DefmPrefixLoc = Lex.getLoc();
2404 if (Lex.getCode() != tgtok::colon)
2405 return TokError("expected ':' after defm identifier");
2407 // Keep track of the new generated record definitions.
2408 std::vector<Record*> NewRecDefs;
2410 // This record also inherits from a regular class (non-multiclass)?
2411 bool InheritFromClass = false;
2416 SMLoc SubClassLoc = Lex.getLoc();
2417 SubClassReference Ref = ParseSubClassReference(0, true);
2420 if (Ref.Rec == 0) return true;
2422 // To instantiate a multiclass, we need to first get the multiclass, then
2423 // instantiate each def contained in the multiclass with the SubClassRef
2424 // template parameters.
2425 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2426 assert(MC && "Didn't lookup multiclass correctly?");
2427 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2429 // Verify that the correct number of template arguments were specified.
2430 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2431 if (TArgs.size() < TemplateVals.size())
2432 return Error(SubClassLoc,
2433 "more template args specified than multiclass expects");
2435 // Loop over all the def's in the multiclass, instantiating each one.
2436 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2437 Record *DefProto = MC->DefPrototypes[i];
2439 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix, DefmPrefixLoc);
2443 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmPrefixLoc, SubClassLoc,
2444 TArgs, TemplateVals, true/*Delete args*/))
2445 return Error(SubClassLoc, "could not instantiate def");
2447 if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmPrefixLoc))
2448 return Error(SubClassLoc, "could not instantiate def");
2450 NewRecDefs.push_back(CurRec);
2454 if (Lex.getCode() != tgtok::comma) break;
2455 Lex.Lex(); // eat ','.
2457 SubClassLoc = Lex.getLoc();
2459 // A defm can inherit from regular classes (non-multiclass) as
2460 // long as they come in the end of the inheritance list.
2461 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != 0);
2463 if (InheritFromClass)
2466 Ref = ParseSubClassReference(0, true);
2469 if (InheritFromClass) {
2470 // Process all the classes to inherit as if they were part of a
2471 // regular 'def' and inherit all record values.
2472 SubClassReference SubClass = ParseSubClassReference(0, false);
2475 if (SubClass.Rec == 0) return true;
2477 // Get the expanded definition prototypes and teach them about
2478 // the record values the current class to inherit has
2479 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2480 Record *CurRec = NewRecDefs[i];
2483 if (AddSubClass(CurRec, SubClass))
2486 // Process any variables on the let stack.
2487 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2488 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2489 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2490 LetStack[i][j].Bits, LetStack[i][j].Value))
2494 if (Lex.getCode() != tgtok::comma) break;
2495 Lex.Lex(); // eat ','.
2496 SubClass = ParseSubClassReference(0, false);
2501 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2502 // See Record::setName(). This resolve step will see any new
2503 // name for the def that might have been created when resolving
2504 // inheritance, values and arguments above.
2505 NewRecDefs[i]->resolveReferences();
2507 if (Lex.getCode() != tgtok::semi)
2508 return TokError("expected ';' at end of defm");
2515 /// Object ::= ClassInst
2516 /// Object ::= DefInst
2517 /// Object ::= MultiClassInst
2518 /// Object ::= DefMInst
2519 /// Object ::= LETCommand '{' ObjectList '}'
2520 /// Object ::= LETCommand Object
2521 bool TGParser::ParseObject(MultiClass *MC) {
2522 switch (Lex.getCode()) {
2524 return TokError("Expected class, def, defm, multiclass or let definition");
2525 case tgtok::Let: return ParseTopLevelLet(MC);
2526 case tgtok::Def: return ParseDef(MC);
2527 case tgtok::Foreach: return ParseForeach(MC);
2528 case tgtok::Defm: return ParseDefm(MC);
2529 case tgtok::Class: return ParseClass();
2530 case tgtok::MultiClass: return ParseMultiClass();
2535 /// ObjectList :== Object*
2536 bool TGParser::ParseObjectList(MultiClass *MC) {
2537 while (isObjectStart(Lex.getCode())) {
2538 if (ParseObject(MC))
2544 bool TGParser::ParseFile() {
2545 Lex.Lex(); // Prime the lexer.
2546 if (ParseObjectList()) return true;
2548 // If we have unread input at the end of the file, report it.
2549 if (Lex.getCode() == tgtok::Eof)
2552 return TokError("Unexpected input at top level");