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/TableGen/Record.h"
16 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Support/CommandLine.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 = dynamic_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 = dynamic_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 V->convertInitializerTo(BitsRecTy::get(BitList.size()));
114 return Error(Loc, "Initializer is not compatible with bit range");
117 // We should have a BitsInit type now.
118 BitsInit *BInit = dynamic_cast<BitsInit*>(BI);
121 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
123 // Loop over bits, assigning values as appropriate.
124 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
125 unsigned Bit = BitList[i];
127 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
128 ValName->getAsUnquotedString() + "' more than once");
129 NewBits[Bit] = BInit->getBit(i);
132 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
134 NewBits[i] = CurVal->getBit(i);
136 V = BitsInit::get(NewBits);
140 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of type '"
141 + RV->getType()->getAsString() +
142 "' is incompatible with initializer '" + V->getAsString()
147 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
148 /// args as SubClass's template arguments.
149 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
150 Record *SC = SubClass.Rec;
151 // Add all of the values in the subclass into the current class.
152 const std::vector<RecordVal> &Vals = SC->getValues();
153 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
154 if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
157 const std::vector<Init *> &TArgs = SC->getTemplateArgs();
159 // Ensure that an appropriate number of template arguments are specified.
160 if (TArgs.size() < SubClass.TemplateArgs.size())
161 return Error(SubClass.RefLoc, "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.RefLoc, TArgs[i], std::vector<unsigned>(),
169 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.RefLoc,"Value not specified for template argument #"
180 + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
181 + ") of subclass '" + SC->getNameInitAsString() + "'!");
185 // Since everything went well, we can now set the "superclass" list for the
187 const std::vector<Record*> &SCs = SC->getSuperClasses();
188 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
189 if (CurRec->isSubClassOf(SCs[i]))
190 return Error(SubClass.RefLoc,
191 "Already subclass of '" + SCs[i]->getName() + "'!\n");
192 CurRec->addSuperClass(SCs[i]);
195 if (CurRec->isSubClassOf(SC))
196 return Error(SubClass.RefLoc,
197 "Already subclass of '" + SC->getName() + "'!\n");
198 CurRec->addSuperClass(SC);
202 /// AddSubMultiClass - Add SubMultiClass as a subclass to
203 /// CurMC, resolving its template args as SubMultiClass's
204 /// template arguments.
205 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
206 SubMultiClassReference &SubMultiClass) {
207 MultiClass *SMC = SubMultiClass.MC;
208 Record *CurRec = &CurMC->Rec;
210 const std::vector<RecordVal> &MCVals = CurRec->getValues();
212 // Add all of the values in the subclass into the current class.
213 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
214 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
215 if (AddValue(CurRec, SubMultiClass.RefLoc, SMCVals[i]))
218 int newDefStart = CurMC->DefPrototypes.size();
220 // Add all of the defs in the subclass into the current multiclass.
221 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
222 iend = SMC->DefPrototypes.end();
225 // Clone the def and add it to the current multiclass
226 Record *NewDef = new Record(**i);
228 // Add all of the values in the superclass into the current def.
229 for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
230 if (AddValue(NewDef, SubMultiClass.RefLoc, MCVals[i]))
233 CurMC->DefPrototypes.push_back(NewDef);
236 const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
238 // Ensure that an appropriate number of template arguments are
240 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
241 return Error(SubMultiClass.RefLoc,
242 "More template args specified than expected");
244 // Loop over all of the template arguments, setting them to the specified
245 // value or leaving them as the default if necessary.
246 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
247 if (i < SubMultiClass.TemplateArgs.size()) {
248 // If a value is specified for this template arg, set it in the
250 if (SetValue(CurRec, SubMultiClass.RefLoc, SMCTArgs[i],
251 std::vector<unsigned>(),
252 SubMultiClass.TemplateArgs[i]))
256 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
259 CurRec->removeValue(SMCTArgs[i]);
261 // If a value is specified for this template arg, set it in the
263 for (MultiClass::RecordVector::iterator j =
264 CurMC->DefPrototypes.begin() + newDefStart,
265 jend = CurMC->DefPrototypes.end();
270 if (SetValue(Def, SubMultiClass.RefLoc, SMCTArgs[i],
271 std::vector<unsigned>(),
272 SubMultiClass.TemplateArgs[i]))
276 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
279 Def->removeValue(SMCTArgs[i]);
281 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
282 return Error(SubMultiClass.RefLoc,
283 "Value not specified for template argument #"
284 + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
285 + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
292 /// ProcessForeachDefs - Given a record, apply all of the variable
293 /// values in all surrounding foreach loops, creating new records for
294 /// each combination of values.
295 bool TGParser::ProcessForeachDefs(Record *CurRec, MultiClass *CurMultiClass,
297 // We want to instantiate a new copy of CurRec for each combination
298 // of nested loop iterator values. We don't want top instantiate
299 // any copies until we have values for each loop iterator.
301 for (LoopVector::iterator Loop = Loops.begin(), LoopEnd = Loops.end();
304 // Process this loop.
305 if (ProcessForeachDefs(CurRec, CurMultiClass, Loc,
306 IterVals, *Loop, Loop+1)) {
308 "Could not process loops for def " + CurRec->getNameInitAsString());
316 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
317 /// apply each of the variable values in this loop and then process
319 bool TGParser::ProcessForeachDefs(Record *CurRec, MultiClass *CurMultiClass,
320 SMLoc Loc, IterSet &IterVals,
321 ForeachLoop &CurLoop,
322 LoopVector::iterator NextLoop) {
323 Init *IterVar = CurLoop.IterVar;
324 ListInit *List = dynamic_cast<ListInit *>(CurLoop.ListValue);
327 Error(Loc, "Loop list is not a list");
331 // Process each value.
332 for (int64_t i = 0; i < List->getSize(); ++i) {
333 Init *ItemVal = List->resolveListElementReference(*CurRec, 0, i);
334 IterVals.push_back(IterRecord(IterVar, ItemVal));
336 if (IterVals.size() == Loops.size()) {
337 // Ok, we have all of the iterator values for this point in the
338 // iteration space. Instantiate a new record to reflect this
339 // combination of values.
340 Record *IterRec = new Record(*CurRec);
342 // Set the iterator values now.
343 for (IterSet::iterator i = IterVals.begin(), iend = IterVals.end();
346 VarInit *IterVar = dynamic_cast<VarInit *>(i->IterVar);
348 Error(Loc, "foreach iterator is unresolved");
352 TypedInit *IVal = dynamic_cast<TypedInit *>(i->IterValue);
354 Error(Loc, "foreach iterator value is untyped");
358 IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
360 if (SetValue(IterRec, Loc, IterVar->getName(),
361 std::vector<unsigned>(), IVal)) {
362 Error(Loc, "when instantiating this def");
367 IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
370 IterRec->removeValue(IterVar->getName());
373 if (Records.getDef(IterRec->getNameInitAsString())) {
374 Error(Loc, "def already exists: " + IterRec->getNameInitAsString());
378 Records.addDef(IterRec);
379 IterRec->resolveReferences();
382 if (NextLoop != Loops.end()) {
383 // Process nested loops.
384 if (ProcessForeachDefs(CurRec, CurMultiClass, Loc, IterVals, *NextLoop,
387 "Could not process loops for def " +
388 CurRec->getNameInitAsString());
393 // We're done with this iterator.
399 //===----------------------------------------------------------------------===//
401 //===----------------------------------------------------------------------===//
403 /// isObjectStart - Return true if this is a valid first token for an Object.
404 static bool isObjectStart(tgtok::TokKind K) {
405 return K == tgtok::Class || K == tgtok::Def ||
406 K == tgtok::Defm || K == tgtok::Let ||
407 K == tgtok::MultiClass || K == tgtok::Foreach;
410 static std::string GetNewAnonymousName() {
411 static unsigned AnonCounter = 0;
412 return "anonymous."+utostr(AnonCounter++);
415 /// ParseObjectName - If an object name is specified, return it. Otherwise,
416 /// return an anonymous name.
417 /// ObjectName ::= Value [ '#' Value ]*
418 /// ObjectName ::= /*empty*/
420 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
421 switch (Lex.getCode()) {
425 // These are all of the tokens that can begin an object body.
426 // Some of these can also begin values but we disallow those cases
427 // because they are unlikely to be useful.
428 return StringInit::get(GetNewAnonymousName());
435 CurRec = &CurMultiClass->Rec;
439 const TypedInit *CurRecName =
440 dynamic_cast<const TypedInit *>(CurRec->getNameInit());
442 TokError("Record name is not typed!");
445 Type = CurRecName->getType();
448 return ParseValue(CurRec, Type, ParseNameMode);
451 /// ParseClassID - Parse and resolve a reference to a class name. This returns
456 Record *TGParser::ParseClassID() {
457 if (Lex.getCode() != tgtok::Id) {
458 TokError("expected name for ClassID");
462 Record *Result = Records.getClass(Lex.getCurStrVal());
464 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
470 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
471 /// This returns null on error.
473 /// MultiClassID ::= ID
475 MultiClass *TGParser::ParseMultiClassID() {
476 if (Lex.getCode() != tgtok::Id) {
477 TokError("expected name for ClassID");
481 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
483 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
489 Record *TGParser::ParseDefmID() {
490 if (Lex.getCode() != tgtok::Id) {
491 TokError("expected multiclass name");
495 MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
497 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
506 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
507 /// subclass. This returns a SubClassRefTy with a null Record* on error.
509 /// SubClassRef ::= ClassID
510 /// SubClassRef ::= ClassID '<' ValueList '>'
512 SubClassReference TGParser::
513 ParseSubClassReference(Record *CurRec, bool isDefm) {
514 SubClassReference Result;
515 Result.RefLoc = Lex.getLoc();
518 Result.Rec = ParseDefmID();
520 Result.Rec = ParseClassID();
521 if (Result.Rec == 0) return Result;
523 // If there is no template arg list, we're done.
524 if (Lex.getCode() != tgtok::less)
526 Lex.Lex(); // Eat the '<'
528 if (Lex.getCode() == tgtok::greater) {
529 TokError("subclass reference requires a non-empty list of template values");
534 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
535 if (Result.TemplateArgs.empty()) {
536 Result.Rec = 0; // Error parsing value list.
540 if (Lex.getCode() != tgtok::greater) {
541 TokError("expected '>' in template value list");
550 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
551 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
552 /// Record* on error.
554 /// SubMultiClassRef ::= MultiClassID
555 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
557 SubMultiClassReference TGParser::
558 ParseSubMultiClassReference(MultiClass *CurMC) {
559 SubMultiClassReference Result;
560 Result.RefLoc = Lex.getLoc();
562 Result.MC = ParseMultiClassID();
563 if (Result.MC == 0) return Result;
565 // If there is no template arg list, we're done.
566 if (Lex.getCode() != tgtok::less)
568 Lex.Lex(); // Eat the '<'
570 if (Lex.getCode() == tgtok::greater) {
571 TokError("subclass reference requires a non-empty list of template values");
576 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
577 if (Result.TemplateArgs.empty()) {
578 Result.MC = 0; // Error parsing value list.
582 if (Lex.getCode() != tgtok::greater) {
583 TokError("expected '>' in template value list");
592 /// ParseRangePiece - Parse a bit/value range.
593 /// RangePiece ::= INTVAL
594 /// RangePiece ::= INTVAL '-' INTVAL
595 /// RangePiece ::= INTVAL INTVAL
596 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
597 if (Lex.getCode() != tgtok::IntVal) {
598 TokError("expected integer or bitrange");
601 int64_t Start = Lex.getCurIntVal();
605 return TokError("invalid range, cannot be negative");
607 switch (Lex.Lex()) { // eat first character.
609 Ranges.push_back(Start);
612 if (Lex.Lex() != tgtok::IntVal) {
613 TokError("expected integer value as end of range");
616 End = Lex.getCurIntVal();
619 End = -Lex.getCurIntVal();
623 return TokError("invalid range, cannot be negative");
628 for (; Start <= End; ++Start)
629 Ranges.push_back(Start);
631 for (; Start >= End; --Start)
632 Ranges.push_back(Start);
637 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
639 /// RangeList ::= RangePiece (',' RangePiece)*
641 std::vector<unsigned> TGParser::ParseRangeList() {
642 std::vector<unsigned> Result;
644 // Parse the first piece.
645 if (ParseRangePiece(Result))
646 return std::vector<unsigned>();
647 while (Lex.getCode() == tgtok::comma) {
648 Lex.Lex(); // Eat the comma.
650 // Parse the next range piece.
651 if (ParseRangePiece(Result))
652 return std::vector<unsigned>();
657 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
658 /// OptionalRangeList ::= '<' RangeList '>'
659 /// OptionalRangeList ::= /*empty*/
660 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
661 if (Lex.getCode() != tgtok::less)
664 SMLoc StartLoc = Lex.getLoc();
665 Lex.Lex(); // eat the '<'
667 // Parse the range list.
668 Ranges = ParseRangeList();
669 if (Ranges.empty()) return true;
671 if (Lex.getCode() != tgtok::greater) {
672 TokError("expected '>' at end of range list");
673 return Error(StartLoc, "to match this '<'");
675 Lex.Lex(); // eat the '>'.
679 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
680 /// OptionalBitList ::= '{' RangeList '}'
681 /// OptionalBitList ::= /*empty*/
682 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
683 if (Lex.getCode() != tgtok::l_brace)
686 SMLoc StartLoc = Lex.getLoc();
687 Lex.Lex(); // eat the '{'
689 // Parse the range list.
690 Ranges = ParseRangeList();
691 if (Ranges.empty()) return true;
693 if (Lex.getCode() != tgtok::r_brace) {
694 TokError("expected '}' at end of bit list");
695 return Error(StartLoc, "to match this '{'");
697 Lex.Lex(); // eat the '}'.
702 /// ParseType - Parse and return a tblgen type. This returns null on error.
704 /// Type ::= STRING // string type
705 /// Type ::= CODE // code type
706 /// Type ::= BIT // bit type
707 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
708 /// Type ::= INT // int type
709 /// Type ::= LIST '<' Type '>' // list<x> type
710 /// Type ::= DAG // dag type
711 /// Type ::= ClassID // Record Type
713 RecTy *TGParser::ParseType() {
714 switch (Lex.getCode()) {
715 default: TokError("Unknown token when expecting a type"); return 0;
716 case tgtok::String: Lex.Lex(); return StringRecTy::get();
717 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
718 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
719 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
720 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
722 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
725 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
726 TokError("expected '<' after bits type");
729 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
730 TokError("expected integer in bits<n> type");
733 uint64_t Val = Lex.getCurIntVal();
734 if (Lex.Lex() != tgtok::greater) { // Eat count.
735 TokError("expected '>' at end of bits<n> type");
738 Lex.Lex(); // Eat '>'
739 return BitsRecTy::get(Val);
742 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
743 TokError("expected '<' after list type");
746 Lex.Lex(); // Eat '<'
747 RecTy *SubType = ParseType();
748 if (SubType == 0) return 0;
750 if (Lex.getCode() != tgtok::greater) {
751 TokError("expected '>' at end of list<ty> type");
754 Lex.Lex(); // Eat '>'
755 return ListRecTy::get(SubType);
760 /// ParseIDValue - Parse an ID as a value and decode what it means.
762 /// IDValue ::= ID [def local value]
763 /// IDValue ::= ID [def template arg]
764 /// IDValue ::= ID [multiclass local value]
765 /// IDValue ::= ID [multiclass template argument]
766 /// IDValue ::= ID [def name]
768 Init *TGParser::ParseIDValue(Record *CurRec, IDParseMode Mode) {
769 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
770 std::string Name = Lex.getCurStrVal();
771 SMLoc Loc = Lex.getLoc();
773 return ParseIDValue(CurRec, Name, Loc);
776 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
777 /// has already been read.
778 Init *TGParser::ParseIDValue(Record *CurRec,
779 const std::string &Name, SMLoc NameLoc,
782 if (const RecordVal *RV = CurRec->getValue(Name))
783 return VarInit::get(Name, RV->getType());
785 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
788 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
791 if (CurRec->isTemplateArg(TemplateArgName)) {
792 const RecordVal *RV = CurRec->getValue(TemplateArgName);
793 assert(RV && "Template arg doesn't exist??");
794 return VarInit::get(TemplateArgName, RV->getType());
799 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
802 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
803 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
804 assert(RV && "Template arg doesn't exist??");
805 return VarInit::get(MCName, RV->getType());
809 // If this is in a foreach loop, make sure it's not a loop iterator
810 for (LoopVector::iterator i = Loops.begin(), iend = Loops.end();
813 VarInit *IterVar = dynamic_cast<VarInit *>(i->IterVar);
814 if (IterVar && IterVar->getName() == Name)
818 if (Mode == ParseNameMode)
819 return StringInit::get(Name);
821 if (Record *D = Records.getDef(Name))
822 return DefInit::get(D);
824 if (Mode == ParseValueMode) {
825 Error(NameLoc, "Variable not defined: '" + Name + "'");
829 return StringInit::get(Name);
832 /// ParseOperation - Parse an operator. This returns null on error.
834 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
836 Init *TGParser::ParseOperation(Record *CurRec) {
837 switch (Lex.getCode()) {
839 TokError("unknown operation");
844 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
845 UnOpInit::UnaryOp Code;
848 switch (Lex.getCode()) {
849 default: llvm_unreachable("Unhandled code!");
851 Lex.Lex(); // eat the operation
852 Code = UnOpInit::CAST;
854 Type = ParseOperatorType();
857 TokError("did not get type for unary operator");
863 Lex.Lex(); // eat the operation
864 Code = UnOpInit::HEAD;
867 Lex.Lex(); // eat the operation
868 Code = UnOpInit::TAIL;
871 Lex.Lex(); // eat the operation
872 Code = UnOpInit::EMPTY;
873 Type = IntRecTy::get();
876 if (Lex.getCode() != tgtok::l_paren) {
877 TokError("expected '(' after unary operator");
880 Lex.Lex(); // eat the '('
882 Init *LHS = ParseValue(CurRec);
883 if (LHS == 0) return 0;
885 if (Code == UnOpInit::HEAD
886 || Code == UnOpInit::TAIL
887 || Code == UnOpInit::EMPTY) {
888 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
889 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
890 TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
891 if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
892 TokError("expected list or string type argument in unary operator");
896 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
897 StringRecTy *SType = dynamic_cast<StringRecTy*>(LHSt->getType());
898 if (LType == 0 && SType == 0) {
899 TokError("expected list or string type argumnet in unary operator");
904 if (Code == UnOpInit::HEAD
905 || Code == UnOpInit::TAIL) {
906 if (LHSl == 0 && LHSt == 0) {
907 TokError("expected list type argumnet in unary operator");
911 if (LHSl && LHSl->getSize() == 0) {
912 TokError("empty list argument in unary operator");
916 Init *Item = LHSl->getElement(0);
917 TypedInit *Itemt = dynamic_cast<TypedInit*>(Item);
919 TokError("untyped list element in unary operator");
922 if (Code == UnOpInit::HEAD) {
923 Type = Itemt->getType();
925 Type = ListRecTy::get(Itemt->getType());
928 assert(LHSt && "expected list type argument in unary operator");
929 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
931 TokError("expected list type argumnet in unary operator");
934 if (Code == UnOpInit::HEAD) {
935 Type = LType->getElementType();
943 if (Lex.getCode() != tgtok::r_paren) {
944 TokError("expected ')' in unary operator");
947 Lex.Lex(); // eat the ')'
948 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
956 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
957 tgtok::TokKind OpTok = Lex.getCode();
958 SMLoc OpLoc = Lex.getLoc();
959 Lex.Lex(); // eat the operation
961 BinOpInit::BinaryOp Code;
965 default: llvm_unreachable("Unhandled code!");
966 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
967 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
968 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
969 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
970 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
971 case tgtok::XStrConcat:
972 Code = BinOpInit::STRCONCAT;
973 Type = StringRecTy::get();
977 if (Lex.getCode() != tgtok::l_paren) {
978 TokError("expected '(' after binary operator");
981 Lex.Lex(); // eat the '('
983 SmallVector<Init*, 2> InitList;
985 InitList.push_back(ParseValue(CurRec));
986 if (InitList.back() == 0) return 0;
988 while (Lex.getCode() == tgtok::comma) {
989 Lex.Lex(); // eat the ','
991 InitList.push_back(ParseValue(CurRec));
992 if (InitList.back() == 0) return 0;
995 if (Lex.getCode() != tgtok::r_paren) {
996 TokError("expected ')' in operator");
999 Lex.Lex(); // eat the ')'
1001 // We allow multiple operands to associative operators like !strconcat as
1002 // shorthand for nesting them.
1003 if (Code == BinOpInit::STRCONCAT) {
1004 while (InitList.size() > 2) {
1005 Init *RHS = InitList.pop_back_val();
1006 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
1007 ->Fold(CurRec, CurMultiClass);
1008 InitList.back() = RHS;
1012 if (InitList.size() == 2)
1013 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
1014 ->Fold(CurRec, CurMultiClass);
1016 Error(OpLoc, "expected two operands to operator");
1021 case tgtok::XForEach:
1022 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1023 TernOpInit::TernaryOp Code;
1026 tgtok::TokKind LexCode = Lex.getCode();
1027 Lex.Lex(); // eat the operation
1029 default: llvm_unreachable("Unhandled code!");
1031 Code = TernOpInit::IF;
1033 case tgtok::XForEach:
1034 Code = TernOpInit::FOREACH;
1037 Code = TernOpInit::SUBST;
1040 if (Lex.getCode() != tgtok::l_paren) {
1041 TokError("expected '(' after ternary operator");
1044 Lex.Lex(); // eat the '('
1046 Init *LHS = ParseValue(CurRec);
1047 if (LHS == 0) return 0;
1049 if (Lex.getCode() != tgtok::comma) {
1050 TokError("expected ',' in ternary operator");
1053 Lex.Lex(); // eat the ','
1055 Init *MHS = ParseValue(CurRec);
1056 if (MHS == 0) return 0;
1058 if (Lex.getCode() != tgtok::comma) {
1059 TokError("expected ',' in ternary operator");
1062 Lex.Lex(); // eat the ','
1064 Init *RHS = ParseValue(CurRec);
1065 if (RHS == 0) return 0;
1067 if (Lex.getCode() != tgtok::r_paren) {
1068 TokError("expected ')' in binary operator");
1071 Lex.Lex(); // eat the ')'
1074 default: llvm_unreachable("Unhandled code!");
1076 // FIXME: The `!if' operator doesn't handle non-TypedInit well at
1077 // all. This can be made much more robust.
1078 TypedInit *MHSt = dynamic_cast<TypedInit*>(MHS);
1079 TypedInit *RHSt = dynamic_cast<TypedInit*>(RHS);
1084 if (MHSt == 0 && RHSt == 0) {
1085 BitsInit *MHSbits = dynamic_cast<BitsInit*>(MHS);
1086 BitsInit *RHSbits = dynamic_cast<BitsInit*>(RHS);
1088 if (MHSbits && RHSbits &&
1089 MHSbits->getNumBits() == RHSbits->getNumBits()) {
1090 Type = BitRecTy::get();
1093 BitInit *MHSbit = dynamic_cast<BitInit*>(MHS);
1094 BitInit *RHSbit = dynamic_cast<BitInit*>(RHS);
1096 if (MHSbit && RHSbit) {
1097 Type = BitRecTy::get();
1101 } else if (MHSt != 0 && RHSt != 0) {
1102 MHSTy = MHSt->getType();
1103 RHSTy = RHSt->getType();
1106 if (!MHSTy || !RHSTy) {
1107 TokError("could not get type for !if");
1111 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1113 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1116 TokError("inconsistent types for !if");
1121 case tgtok::XForEach: {
1122 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
1124 TokError("could not get type for !foreach");
1127 Type = MHSt->getType();
1130 case tgtok::XSubst: {
1131 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
1133 TokError("could not get type for !subst");
1136 Type = RHSt->getType();
1140 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1146 /// ParseOperatorType - Parse a type for an operator. This returns
1149 /// OperatorType ::= '<' Type '>'
1151 RecTy *TGParser::ParseOperatorType() {
1154 if (Lex.getCode() != tgtok::less) {
1155 TokError("expected type name for operator");
1158 Lex.Lex(); // eat the <
1163 TokError("expected type name for operator");
1167 if (Lex.getCode() != tgtok::greater) {
1168 TokError("expected type name for operator");
1171 Lex.Lex(); // eat the >
1177 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1179 /// SimpleValue ::= IDValue
1180 /// SimpleValue ::= INTVAL
1181 /// SimpleValue ::= STRVAL+
1182 /// SimpleValue ::= CODEFRAGMENT
1183 /// SimpleValue ::= '?'
1184 /// SimpleValue ::= '{' ValueList '}'
1185 /// SimpleValue ::= ID '<' ValueListNE '>'
1186 /// SimpleValue ::= '[' ValueList ']'
1187 /// SimpleValue ::= '(' IDValue DagArgList ')'
1188 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1189 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1190 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1191 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1192 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1194 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1197 switch (Lex.getCode()) {
1198 default: TokError("Unknown token when parsing a value"); break;
1200 // This is a leading paste operation. This is deprecated but
1201 // still exists in some .td files. Ignore it.
1202 Lex.Lex(); // Skip '#'.
1203 return ParseSimpleValue(CurRec, ItemType, Mode);
1204 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1205 case tgtok::StrVal: {
1206 std::string Val = Lex.getCurStrVal();
1209 // Handle multiple consecutive concatenated strings.
1210 while (Lex.getCode() == tgtok::StrVal) {
1211 Val += Lex.getCurStrVal();
1215 R = StringInit::get(Val);
1218 case tgtok::CodeFragment:
1219 R = StringInit::get(Lex.getCurStrVal());
1222 case tgtok::question:
1223 R = UnsetInit::get();
1227 SMLoc NameLoc = Lex.getLoc();
1228 std::string Name = Lex.getCurStrVal();
1229 if (Lex.Lex() != tgtok::less) // consume the Id.
1230 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1232 // Value ::= ID '<' ValueListNE '>'
1233 if (Lex.Lex() == tgtok::greater) {
1234 TokError("expected non-empty value list");
1238 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1239 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1241 Record *Class = Records.getClass(Name);
1243 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1247 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1248 if (ValueList.empty()) return 0;
1250 if (Lex.getCode() != tgtok::greater) {
1251 TokError("expected '>' at end of value list");
1254 Lex.Lex(); // eat the '>'
1256 // Create the new record, set it as CurRec temporarily.
1257 static unsigned AnonCounter = 0;
1258 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),
1261 SubClassReference SCRef;
1262 SCRef.RefLoc = NameLoc;
1264 SCRef.TemplateArgs = ValueList;
1265 // Add info about the subclass to NewRec.
1266 if (AddSubClass(NewRec, SCRef))
1268 NewRec->resolveReferences();
1269 Records.addDef(NewRec);
1271 // The result of the expression is a reference to the new record.
1272 return DefInit::get(NewRec);
1274 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1275 SMLoc BraceLoc = Lex.getLoc();
1276 Lex.Lex(); // eat the '{'
1277 std::vector<Init*> Vals;
1279 if (Lex.getCode() != tgtok::r_brace) {
1280 Vals = ParseValueList(CurRec);
1281 if (Vals.empty()) return 0;
1283 if (Lex.getCode() != tgtok::r_brace) {
1284 TokError("expected '}' at end of bit list value");
1287 Lex.Lex(); // eat the '}'
1289 SmallVector<Init *, 16> NewBits(Vals.size());
1291 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1292 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1294 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1295 ") is not convertable to a bit");
1298 NewBits[Vals.size()-i-1] = Bit;
1300 return BitsInit::get(NewBits);
1302 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1303 Lex.Lex(); // eat the '['
1304 std::vector<Init*> Vals;
1306 RecTy *DeducedEltTy = 0;
1307 ListRecTy *GivenListTy = 0;
1309 if (ItemType != 0) {
1310 ListRecTy *ListType = dynamic_cast<ListRecTy*>(ItemType);
1311 if (ListType == 0) {
1312 std::stringstream s;
1313 s << "Type mismatch for list, expected list type, got "
1314 << ItemType->getAsString();
1318 GivenListTy = ListType;
1321 if (Lex.getCode() != tgtok::r_square) {
1322 Vals = ParseValueList(CurRec, 0,
1323 GivenListTy ? GivenListTy->getElementType() : 0);
1324 if (Vals.empty()) return 0;
1326 if (Lex.getCode() != tgtok::r_square) {
1327 TokError("expected ']' at end of list value");
1330 Lex.Lex(); // eat the ']'
1332 RecTy *GivenEltTy = 0;
1333 if (Lex.getCode() == tgtok::less) {
1334 // Optional list element type
1335 Lex.Lex(); // eat the '<'
1337 GivenEltTy = ParseType();
1338 if (GivenEltTy == 0) {
1339 // Couldn't parse element type
1343 if (Lex.getCode() != tgtok::greater) {
1344 TokError("expected '>' at end of list element type");
1347 Lex.Lex(); // eat the '>'
1352 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1355 TypedInit *TArg = dynamic_cast<TypedInit*>(*i);
1357 TokError("Untyped list element");
1361 EltTy = resolveTypes(EltTy, TArg->getType());
1363 TokError("Incompatible types in list elements");
1367 EltTy = TArg->getType();
1371 if (GivenEltTy != 0) {
1373 // Verify consistency
1374 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1375 TokError("Incompatible types in list elements");
1383 if (ItemType == 0) {
1384 TokError("No type for list");
1387 DeducedEltTy = GivenListTy->getElementType();
1389 // Make sure the deduced type is compatible with the given type
1391 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1392 TokError("Element type mismatch for list");
1396 DeducedEltTy = EltTy;
1399 return ListInit::get(Vals, DeducedEltTy);
1401 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1402 Lex.Lex(); // eat the '('
1403 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1404 TokError("expected identifier in dag init");
1408 Init *Operator = ParseValue(CurRec);
1409 if (Operator == 0) return 0;
1411 // If the operator name is present, parse it.
1412 std::string OperatorName;
1413 if (Lex.getCode() == tgtok::colon) {
1414 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1415 TokError("expected variable name in dag operator");
1418 OperatorName = Lex.getCurStrVal();
1419 Lex.Lex(); // eat the VarName.
1422 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1423 if (Lex.getCode() != tgtok::r_paren) {
1424 DagArgs = ParseDagArgList(CurRec);
1425 if (DagArgs.empty()) return 0;
1428 if (Lex.getCode() != tgtok::r_paren) {
1429 TokError("expected ')' in dag init");
1432 Lex.Lex(); // eat the ')'
1434 return DagInit::get(Operator, OperatorName, DagArgs);
1440 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1441 case tgtok::XConcat:
1446 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1448 case tgtok::XForEach:
1449 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1450 return ParseOperation(CurRec);
1457 /// ParseValue - Parse a tblgen value. This returns null on error.
1459 /// Value ::= SimpleValue ValueSuffix*
1460 /// ValueSuffix ::= '{' BitList '}'
1461 /// ValueSuffix ::= '[' BitList ']'
1462 /// ValueSuffix ::= '.' ID
1464 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1465 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1466 if (Result == 0) return 0;
1468 // Parse the suffixes now if present.
1470 switch (Lex.getCode()) {
1471 default: return Result;
1472 case tgtok::l_brace: {
1473 if (Mode == ParseNameMode || Mode == ParseForeachMode)
1474 // This is the beginning of the object body.
1477 SMLoc CurlyLoc = Lex.getLoc();
1478 Lex.Lex(); // eat the '{'
1479 std::vector<unsigned> Ranges = ParseRangeList();
1480 if (Ranges.empty()) return 0;
1482 // Reverse the bitlist.
1483 std::reverse(Ranges.begin(), Ranges.end());
1484 Result = Result->convertInitializerBitRange(Ranges);
1486 Error(CurlyLoc, "Invalid bit range for value");
1491 if (Lex.getCode() != tgtok::r_brace) {
1492 TokError("expected '}' at end of bit range list");
1498 case tgtok::l_square: {
1499 SMLoc SquareLoc = Lex.getLoc();
1500 Lex.Lex(); // eat the '['
1501 std::vector<unsigned> Ranges = ParseRangeList();
1502 if (Ranges.empty()) return 0;
1504 Result = Result->convertInitListSlice(Ranges);
1506 Error(SquareLoc, "Invalid range for list slice");
1511 if (Lex.getCode() != tgtok::r_square) {
1512 TokError("expected ']' at end of list slice");
1519 if (Lex.Lex() != tgtok::Id) { // eat the .
1520 TokError("expected field identifier after '.'");
1523 if (!Result->getFieldType(Lex.getCurStrVal())) {
1524 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1525 Result->getAsString() + "'");
1528 Result = FieldInit::get(Result, Lex.getCurStrVal());
1529 Lex.Lex(); // eat field name
1533 SMLoc PasteLoc = Lex.getLoc();
1535 // Create a !strconcat() operation, first casting each operand to
1536 // a string if necessary.
1538 TypedInit *LHS = dynamic_cast<TypedInit *>(Result);
1540 Error(PasteLoc, "LHS of paste is not typed!");
1544 if (LHS->getType() != StringRecTy::get()) {
1545 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1550 Lex.Lex(); // Eat the '#'.
1551 switch (Lex.getCode()) {
1554 case tgtok::l_brace:
1555 // These are all of the tokens that can begin an object body.
1556 // Some of these can also begin values but we disallow those cases
1557 // because they are unlikely to be useful.
1559 // Trailing paste, concat with an empty string.
1560 RHS = StringInit::get("");
1564 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1565 RHS = dynamic_cast<TypedInit *>(RHSResult);
1567 Error(PasteLoc, "RHS of paste is not typed!");
1571 if (RHS->getType() != StringRecTy::get()) {
1572 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1578 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1579 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1585 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1587 /// ParseDagArgList ::= Value (':' VARNAME)?
1588 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1589 std::vector<std::pair<llvm::Init*, std::string> >
1590 TGParser::ParseDagArgList(Record *CurRec) {
1591 std::vector<std::pair<llvm::Init*, std::string> > Result;
1594 Init *Val = ParseValue(CurRec);
1595 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1597 // If the variable name is present, add it.
1598 std::string VarName;
1599 if (Lex.getCode() == tgtok::colon) {
1600 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1601 TokError("expected variable name in dag literal");
1602 return std::vector<std::pair<llvm::Init*, std::string> >();
1604 VarName = Lex.getCurStrVal();
1605 Lex.Lex(); // eat the VarName.
1608 Result.push_back(std::make_pair(Val, VarName));
1610 if (Lex.getCode() != tgtok::comma) break;
1611 Lex.Lex(); // eat the ','
1618 /// ParseValueList - Parse a comma separated list of values, returning them as a
1619 /// vector. Note that this always expects to be able to parse at least one
1620 /// value. It returns an empty list if this is not possible.
1622 /// ValueList ::= Value (',' Value)
1624 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1626 std::vector<Init*> Result;
1627 RecTy *ItemType = EltTy;
1628 unsigned int ArgN = 0;
1629 if (ArgsRec != 0 && EltTy == 0) {
1630 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1631 if (!TArgs.size()) {
1632 TokError("template argument provided to non-template class");
1633 return std::vector<Init*>();
1635 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1637 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1640 assert(RV && "Template argument record not found??");
1641 ItemType = RV->getType();
1644 Result.push_back(ParseValue(CurRec, ItemType));
1645 if (Result.back() == 0) return std::vector<Init*>();
1647 while (Lex.getCode() == tgtok::comma) {
1648 Lex.Lex(); // Eat the comma
1650 if (ArgsRec != 0 && EltTy == 0) {
1651 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1652 if (ArgN >= TArgs.size()) {
1653 TokError("too many template arguments");
1654 return std::vector<Init*>();
1656 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1657 assert(RV && "Template argument record not found??");
1658 ItemType = RV->getType();
1661 Result.push_back(ParseValue(CurRec, ItemType));
1662 if (Result.back() == 0) return std::vector<Init*>();
1669 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1670 /// empty string on error. This can happen in a number of different context's,
1671 /// including within a def or in the template args for a def (which which case
1672 /// CurRec will be non-null) and within the template args for a multiclass (in
1673 /// which case CurRec will be null, but CurMultiClass will be set). This can
1674 /// also happen within a def that is within a multiclass, which will set both
1675 /// CurRec and CurMultiClass.
1677 /// Declaration ::= FIELD? Type ID ('=' Value)?
1679 Init *TGParser::ParseDeclaration(Record *CurRec,
1680 bool ParsingTemplateArgs) {
1681 // Read the field prefix if present.
1682 bool HasField = Lex.getCode() == tgtok::Field;
1683 if (HasField) Lex.Lex();
1685 RecTy *Type = ParseType();
1686 if (Type == 0) return 0;
1688 if (Lex.getCode() != tgtok::Id) {
1689 TokError("Expected identifier in declaration");
1693 SMLoc IdLoc = Lex.getLoc();
1694 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1697 if (ParsingTemplateArgs) {
1699 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1701 assert(CurMultiClass);
1704 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1709 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1712 // If a value is present, parse it.
1713 if (Lex.getCode() == tgtok::equal) {
1715 SMLoc ValLoc = Lex.getLoc();
1716 Init *Val = ParseValue(CurRec, Type);
1718 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1725 /// ParseForeachDeclaration - Read a foreach declaration, returning
1726 /// the name of the declared object or a NULL Init on error. Return
1727 /// the name of the parsed initializer list through ForeachListName.
1729 /// ForeachDeclaration ::= ID '=' Value
1731 Init *TGParser::ParseForeachDeclaration(Init *&ForeachListValue) {
1732 if (Lex.getCode() != tgtok::Id) {
1733 TokError("Expected identifier in foreach declaration");
1737 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1740 // If a value is present, parse it.
1741 if (Lex.getCode() != tgtok::equal) {
1742 TokError("Expected '=' in foreach declaration");
1745 Lex.Lex(); // Eat the '='
1747 // Expect a list initializer.
1748 ForeachListValue = ParseValue(0, 0, ParseForeachMode);
1750 TypedInit *TypedList = dynamic_cast<TypedInit *>(ForeachListValue);
1751 if (TypedList == 0) {
1752 TokError("Value list is untyped");
1756 RecTy *ValueType = TypedList->getType();
1757 ListRecTy *ListType = dynamic_cast<ListRecTy *>(ValueType);
1758 if (ListType == 0) {
1759 TokError("Value list is not of list type");
1763 RecTy *IterType = ListType->getElementType();
1764 VarInit *IterVar = VarInit::get(DeclName, IterType);
1769 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1770 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1771 /// template args for a def, which may or may not be in a multiclass. If null,
1772 /// these are the template args for a multiclass.
1774 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1776 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1777 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1778 Lex.Lex(); // eat the '<'
1780 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1782 // Read the first declaration.
1783 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1787 TheRecToAddTo->addTemplateArg(TemplArg);
1789 while (Lex.getCode() == tgtok::comma) {
1790 Lex.Lex(); // eat the ','
1792 // Read the following declarations.
1793 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1796 TheRecToAddTo->addTemplateArg(TemplArg);
1799 if (Lex.getCode() != tgtok::greater)
1800 return TokError("expected '>' at end of template argument list");
1801 Lex.Lex(); // eat the '>'.
1806 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1808 /// BodyItem ::= Declaration ';'
1809 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1810 bool TGParser::ParseBodyItem(Record *CurRec) {
1811 if (Lex.getCode() != tgtok::Let) {
1812 if (ParseDeclaration(CurRec, false) == 0)
1815 if (Lex.getCode() != tgtok::semi)
1816 return TokError("expected ';' after declaration");
1821 // LET ID OptionalRangeList '=' Value ';'
1822 if (Lex.Lex() != tgtok::Id)
1823 return TokError("expected field identifier after let");
1825 SMLoc IdLoc = Lex.getLoc();
1826 std::string FieldName = Lex.getCurStrVal();
1827 Lex.Lex(); // eat the field name.
1829 std::vector<unsigned> BitList;
1830 if (ParseOptionalBitList(BitList))
1832 std::reverse(BitList.begin(), BitList.end());
1834 if (Lex.getCode() != tgtok::equal)
1835 return TokError("expected '=' in let expression");
1836 Lex.Lex(); // eat the '='.
1838 RecordVal *Field = CurRec->getValue(FieldName);
1840 return TokError("Value '" + FieldName + "' unknown!");
1842 RecTy *Type = Field->getType();
1844 Init *Val = ParseValue(CurRec, Type);
1845 if (Val == 0) return true;
1847 if (Lex.getCode() != tgtok::semi)
1848 return TokError("expected ';' after let expression");
1851 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1854 /// ParseBody - Read the body of a class or def. Return true on error, false on
1858 /// Body ::= '{' BodyList '}'
1859 /// BodyList BodyItem*
1861 bool TGParser::ParseBody(Record *CurRec) {
1862 // If this is a null definition, just eat the semi and return.
1863 if (Lex.getCode() == tgtok::semi) {
1868 if (Lex.getCode() != tgtok::l_brace)
1869 return TokError("Expected ';' or '{' to start body");
1873 while (Lex.getCode() != tgtok::r_brace)
1874 if (ParseBodyItem(CurRec))
1882 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1883 /// optional ClassList followed by a Body. CurRec is the current def or class
1884 /// that is being parsed.
1886 /// ObjectBody ::= BaseClassList Body
1887 /// BaseClassList ::= /*empty*/
1888 /// BaseClassList ::= ':' BaseClassListNE
1889 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1891 bool TGParser::ParseObjectBody(Record *CurRec) {
1892 // If there is a baseclass list, read it.
1893 if (Lex.getCode() == tgtok::colon) {
1896 // Read all of the subclasses.
1897 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1900 if (SubClass.Rec == 0) return true;
1903 if (AddSubClass(CurRec, SubClass))
1906 if (Lex.getCode() != tgtok::comma) break;
1907 Lex.Lex(); // eat ','.
1908 SubClass = ParseSubClassReference(CurRec, false);
1912 // Process any variables on the let stack.
1913 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1914 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1915 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1916 LetStack[i][j].Bits, LetStack[i][j].Value))
1919 return ParseBody(CurRec);
1922 /// ParseDef - Parse and return a top level or multiclass def, return the record
1923 /// corresponding to it. This returns null on error.
1925 /// DefInst ::= DEF ObjectName ObjectBody
1927 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1928 SMLoc DefLoc = Lex.getLoc();
1929 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1930 Lex.Lex(); // Eat the 'def' token.
1932 // Parse ObjectName and make a record for it.
1933 Record *CurRec = new Record(ParseObjectName(CurMultiClass), DefLoc, Records);
1935 if (!CurMultiClass) {
1936 // Top-level def definition.
1938 // Ensure redefinition doesn't happen.
1939 if (Records.getDef(CurRec->getNameInitAsString())) {
1940 Error(DefLoc, "def '" + CurRec->getNameInitAsString()
1941 + "' already defined");
1944 Records.addDef(CurRec);
1946 // Otherwise, a def inside a multiclass, add it to the multiclass.
1947 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1948 if (CurMultiClass->DefPrototypes[i]->getNameInit()
1949 == CurRec->getNameInit()) {
1950 Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
1951 "' already defined in this multiclass!");
1954 CurMultiClass->DefPrototypes.push_back(CurRec);
1957 if (ParseObjectBody(CurRec))
1960 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1961 // See Record::setName(). This resolve step will see any new name
1962 // for the def that might have been created when resolving
1963 // inheritance, values and arguments above.
1964 CurRec->resolveReferences();
1966 // If ObjectBody has template arguments, it's an error.
1967 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1969 if (CurMultiClass) {
1970 // Copy the template arguments for the multiclass into the def.
1971 const std::vector<Init *> &TArgs =
1972 CurMultiClass->Rec.getTemplateArgs();
1974 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1975 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1976 assert(RV && "Template arg doesn't exist?");
1977 CurRec->addValue(*RV);
1981 if (ProcessForeachDefs(CurRec, CurMultiClass, DefLoc)) {
1983 "Could not process loops for def" + CurRec->getNameInitAsString());
1990 /// ParseForeach - Parse a for statement. Return the record corresponding
1991 /// to it. This returns true on error.
1993 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
1994 /// Foreach ::= FOREACH Declaration IN Object
1996 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
1997 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
1998 Lex.Lex(); // Eat the 'for' token.
2000 // Make a temporary object to record items associated with the for
2002 Init *ListValue = 0;
2003 Init *IterName = ParseForeachDeclaration(ListValue);
2005 return TokError("expected declaration in for");
2007 if (Lex.getCode() != tgtok::In)
2008 return TokError("Unknown tok");
2009 Lex.Lex(); // Eat the in
2011 // Create a loop object and remember it.
2012 Loops.push_back(ForeachLoop(IterName, ListValue));
2014 if (Lex.getCode() != tgtok::l_brace) {
2015 // FOREACH Declaration IN Object
2016 if (ParseObject(CurMultiClass))
2020 SMLoc BraceLoc = Lex.getLoc();
2021 // Otherwise, this is a group foreach.
2022 Lex.Lex(); // eat the '{'.
2024 // Parse the object list.
2025 if (ParseObjectList(CurMultiClass))
2028 if (Lex.getCode() != tgtok::r_brace) {
2029 TokError("expected '}' at end of foreach command");
2030 return Error(BraceLoc, "to match this '{'");
2032 Lex.Lex(); // Eat the }
2035 // We've processed everything in this loop.
2041 /// ParseClass - Parse a tblgen class definition.
2043 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2045 bool TGParser::ParseClass() {
2046 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2049 if (Lex.getCode() != tgtok::Id)
2050 return TokError("expected class name after 'class' keyword");
2052 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2054 // If the body was previously defined, this is an error.
2055 if (CurRec->getValues().size() > 1 || // Account for NAME.
2056 !CurRec->getSuperClasses().empty() ||
2057 !CurRec->getTemplateArgs().empty())
2058 return TokError("Class '" + CurRec->getNameInitAsString()
2059 + "' already defined");
2061 // If this is the first reference to this class, create and add it.
2062 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
2063 Records.addClass(CurRec);
2065 Lex.Lex(); // eat the name.
2067 // If there are template args, parse them.
2068 if (Lex.getCode() == tgtok::less)
2069 if (ParseTemplateArgList(CurRec))
2072 // Finally, parse the object body.
2073 return ParseObjectBody(CurRec);
2076 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2079 /// LetList ::= LetItem (',' LetItem)*
2080 /// LetItem ::= ID OptionalRangeList '=' Value
2082 std::vector<LetRecord> TGParser::ParseLetList() {
2083 std::vector<LetRecord> Result;
2086 if (Lex.getCode() != tgtok::Id) {
2087 TokError("expected identifier in let definition");
2088 return std::vector<LetRecord>();
2090 std::string Name = Lex.getCurStrVal();
2091 SMLoc NameLoc = Lex.getLoc();
2092 Lex.Lex(); // Eat the identifier.
2094 // Check for an optional RangeList.
2095 std::vector<unsigned> Bits;
2096 if (ParseOptionalRangeList(Bits))
2097 return std::vector<LetRecord>();
2098 std::reverse(Bits.begin(), Bits.end());
2100 if (Lex.getCode() != tgtok::equal) {
2101 TokError("expected '=' in let expression");
2102 return std::vector<LetRecord>();
2104 Lex.Lex(); // eat the '='.
2106 Init *Val = ParseValue(0);
2107 if (Val == 0) return std::vector<LetRecord>();
2109 // Now that we have everything, add the record.
2110 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2112 if (Lex.getCode() != tgtok::comma)
2114 Lex.Lex(); // eat the comma.
2118 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2119 /// different related productions. This works inside multiclasses too.
2121 /// Object ::= LET LetList IN '{' ObjectList '}'
2122 /// Object ::= LET LetList IN Object
2124 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2125 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2128 // Add this entry to the let stack.
2129 std::vector<LetRecord> LetInfo = ParseLetList();
2130 if (LetInfo.empty()) return true;
2131 LetStack.push_back(LetInfo);
2133 if (Lex.getCode() != tgtok::In)
2134 return TokError("expected 'in' at end of top-level 'let'");
2137 // If this is a scalar let, just handle it now
2138 if (Lex.getCode() != tgtok::l_brace) {
2139 // LET LetList IN Object
2140 if (ParseObject(CurMultiClass))
2142 } else { // Object ::= LETCommand '{' ObjectList '}'
2143 SMLoc BraceLoc = Lex.getLoc();
2144 // Otherwise, this is a group let.
2145 Lex.Lex(); // eat the '{'.
2147 // Parse the object list.
2148 if (ParseObjectList(CurMultiClass))
2151 if (Lex.getCode() != tgtok::r_brace) {
2152 TokError("expected '}' at end of top level let command");
2153 return Error(BraceLoc, "to match this '{'");
2158 // Outside this let scope, this let block is not active.
2159 LetStack.pop_back();
2163 /// ParseMultiClass - Parse a multiclass definition.
2165 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2166 /// ':' BaseMultiClassList '{' MultiClassDef+ '}'
2168 bool TGParser::ParseMultiClass() {
2169 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2170 Lex.Lex(); // Eat the multiclass token.
2172 if (Lex.getCode() != tgtok::Id)
2173 return TokError("expected identifier after multiclass for name");
2174 std::string Name = Lex.getCurStrVal();
2176 if (MultiClasses.count(Name))
2177 return TokError("multiclass '" + Name + "' already defined");
2179 CurMultiClass = MultiClasses[Name] = new MultiClass(Name,
2180 Lex.getLoc(), Records);
2181 Lex.Lex(); // Eat the identifier.
2183 // If there are template args, parse them.
2184 if (Lex.getCode() == tgtok::less)
2185 if (ParseTemplateArgList(0))
2188 bool inherits = false;
2190 // If there are submulticlasses, parse them.
2191 if (Lex.getCode() == tgtok::colon) {
2196 // Read all of the submulticlasses.
2197 SubMultiClassReference SubMultiClass =
2198 ParseSubMultiClassReference(CurMultiClass);
2201 if (SubMultiClass.MC == 0) return true;
2204 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2207 if (Lex.getCode() != tgtok::comma) break;
2208 Lex.Lex(); // eat ','.
2209 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2213 if (Lex.getCode() != tgtok::l_brace) {
2215 return TokError("expected '{' in multiclass definition");
2216 else if (Lex.getCode() != tgtok::semi)
2217 return TokError("expected ';' in multiclass definition");
2219 Lex.Lex(); // eat the ';'.
2221 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2222 return TokError("multiclass must contain at least one def");
2224 while (Lex.getCode() != tgtok::r_brace) {
2225 switch (Lex.getCode()) {
2227 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2231 case tgtok::Foreach:
2232 if (ParseObject(CurMultiClass))
2237 Lex.Lex(); // eat the '}'.
2245 InstantiateMulticlassDef(MultiClass &MC,
2248 SMLoc DefmPrefixLoc) {
2249 // We need to preserve DefProto so it can be reused for later
2250 // instantiations, so create a new Record to inherit from it.
2252 // Add in the defm name. If the defm prefix is empty, give each
2253 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2254 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2257 if (DefmPrefix == 0)
2258 DefmPrefix = StringInit::get(GetNewAnonymousName());
2260 Init *DefName = DefProto->getNameInit();
2262 StringInit *DefNameString = dynamic_cast<StringInit *>(DefName);
2264 if (DefNameString != 0) {
2265 // We have a fully expanded string so there are no operators to
2266 // resolve. We should concatenate the given prefix and name.
2268 BinOpInit::get(BinOpInit::STRCONCAT,
2269 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2270 StringRecTy::get())->Fold(DefProto, &MC),
2271 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2274 Record *CurRec = new Record(DefName, DefmPrefixLoc, Records);
2276 SubClassReference Ref;
2277 Ref.RefLoc = DefmPrefixLoc;
2279 AddSubClass(CurRec, Ref);
2281 if (DefNameString == 0) {
2282 // We must resolve references to NAME.
2283 if (SetValue(CurRec, Ref.RefLoc, "NAME", std::vector<unsigned>(),
2285 Error(DefmPrefixLoc, "Could not resolve "
2286 + CurRec->getNameInitAsString() + ":NAME to '"
2287 + DefmPrefix->getAsUnquotedString() + "'");
2291 RecordVal *DefNameRV = CurRec->getValue("NAME");
2292 CurRec->resolveReferencesTo(DefNameRV);
2295 if (!CurMultiClass) {
2296 // We do this after resolving NAME because before resolution, many
2297 // multiclass defs will have the same name expression. 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");