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 return Error(Loc, "Initializer is not compatible with bit range");
116 // We should have a BitsInit type now.
117 BitsInit *BInit = dynamic_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 = dynamic_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 = dynamic_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 =
410 dynamic_cast<const TypedInit *>(CurRec->getNameInit());
412 TokError("Record name is not typed!");
415 Type = CurRecName->getType();
418 return ParseValue(CurRec, Type, ParseNameMode);
421 /// ParseClassID - Parse and resolve a reference to a class name. This returns
426 Record *TGParser::ParseClassID() {
427 if (Lex.getCode() != tgtok::Id) {
428 TokError("expected name for ClassID");
432 Record *Result = Records.getClass(Lex.getCurStrVal());
434 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
440 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
441 /// This returns null on error.
443 /// MultiClassID ::= ID
445 MultiClass *TGParser::ParseMultiClassID() {
446 if (Lex.getCode() != tgtok::Id) {
447 TokError("expected name for ClassID");
451 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
453 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
459 Record *TGParser::ParseDefmID() {
460 if (Lex.getCode() != tgtok::Id) {
461 TokError("expected multiclass name");
465 MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
467 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
476 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
477 /// subclass. This returns a SubClassRefTy with a null Record* on error.
479 /// SubClassRef ::= ClassID
480 /// SubClassRef ::= ClassID '<' ValueList '>'
482 SubClassReference TGParser::
483 ParseSubClassReference(Record *CurRec, bool isDefm) {
484 SubClassReference Result;
485 Result.RefLoc = Lex.getLoc();
488 Result.Rec = ParseDefmID();
490 Result.Rec = ParseClassID();
491 if (Result.Rec == 0) return Result;
493 // If there is no template arg list, we're done.
494 if (Lex.getCode() != tgtok::less)
496 Lex.Lex(); // Eat the '<'
498 if (Lex.getCode() == tgtok::greater) {
499 TokError("subclass reference requires a non-empty list of template values");
504 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
505 if (Result.TemplateArgs.empty()) {
506 Result.Rec = 0; // Error parsing value list.
510 if (Lex.getCode() != tgtok::greater) {
511 TokError("expected '>' in template value list");
520 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
521 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
522 /// Record* on error.
524 /// SubMultiClassRef ::= MultiClassID
525 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
527 SubMultiClassReference TGParser::
528 ParseSubMultiClassReference(MultiClass *CurMC) {
529 SubMultiClassReference Result;
530 Result.RefLoc = Lex.getLoc();
532 Result.MC = ParseMultiClassID();
533 if (Result.MC == 0) return Result;
535 // If there is no template arg list, we're done.
536 if (Lex.getCode() != tgtok::less)
538 Lex.Lex(); // Eat the '<'
540 if (Lex.getCode() == tgtok::greater) {
541 TokError("subclass reference requires a non-empty list of template values");
546 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
547 if (Result.TemplateArgs.empty()) {
548 Result.MC = 0; // Error parsing value list.
552 if (Lex.getCode() != tgtok::greater) {
553 TokError("expected '>' in template value list");
562 /// ParseRangePiece - Parse a bit/value range.
563 /// RangePiece ::= INTVAL
564 /// RangePiece ::= INTVAL '-' INTVAL
565 /// RangePiece ::= INTVAL INTVAL
566 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
567 if (Lex.getCode() != tgtok::IntVal) {
568 TokError("expected integer or bitrange");
571 int64_t Start = Lex.getCurIntVal();
575 return TokError("invalid range, cannot be negative");
577 switch (Lex.Lex()) { // eat first character.
579 Ranges.push_back(Start);
582 if (Lex.Lex() != tgtok::IntVal) {
583 TokError("expected integer value as end of range");
586 End = Lex.getCurIntVal();
589 End = -Lex.getCurIntVal();
593 return TokError("invalid range, cannot be negative");
598 for (; Start <= End; ++Start)
599 Ranges.push_back(Start);
601 for (; Start >= End; --Start)
602 Ranges.push_back(Start);
607 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
609 /// RangeList ::= RangePiece (',' RangePiece)*
611 std::vector<unsigned> TGParser::ParseRangeList() {
612 std::vector<unsigned> Result;
614 // Parse the first piece.
615 if (ParseRangePiece(Result))
616 return std::vector<unsigned>();
617 while (Lex.getCode() == tgtok::comma) {
618 Lex.Lex(); // Eat the comma.
620 // Parse the next range piece.
621 if (ParseRangePiece(Result))
622 return std::vector<unsigned>();
627 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
628 /// OptionalRangeList ::= '<' RangeList '>'
629 /// OptionalRangeList ::= /*empty*/
630 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
631 if (Lex.getCode() != tgtok::less)
634 SMLoc StartLoc = Lex.getLoc();
635 Lex.Lex(); // eat the '<'
637 // Parse the range list.
638 Ranges = ParseRangeList();
639 if (Ranges.empty()) return true;
641 if (Lex.getCode() != tgtok::greater) {
642 TokError("expected '>' at end of range list");
643 return Error(StartLoc, "to match this '<'");
645 Lex.Lex(); // eat the '>'.
649 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
650 /// OptionalBitList ::= '{' RangeList '}'
651 /// OptionalBitList ::= /*empty*/
652 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
653 if (Lex.getCode() != tgtok::l_brace)
656 SMLoc StartLoc = Lex.getLoc();
657 Lex.Lex(); // eat the '{'
659 // Parse the range list.
660 Ranges = ParseRangeList();
661 if (Ranges.empty()) return true;
663 if (Lex.getCode() != tgtok::r_brace) {
664 TokError("expected '}' at end of bit list");
665 return Error(StartLoc, "to match this '{'");
667 Lex.Lex(); // eat the '}'.
672 /// ParseType - Parse and return a tblgen type. This returns null on error.
674 /// Type ::= STRING // string type
675 /// Type ::= CODE // code type
676 /// Type ::= BIT // bit type
677 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
678 /// Type ::= INT // int type
679 /// Type ::= LIST '<' Type '>' // list<x> type
680 /// Type ::= DAG // dag type
681 /// Type ::= ClassID // Record Type
683 RecTy *TGParser::ParseType() {
684 switch (Lex.getCode()) {
685 default: TokError("Unknown token when expecting a type"); return 0;
686 case tgtok::String: Lex.Lex(); return StringRecTy::get();
687 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
688 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
689 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
690 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
692 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
695 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
696 TokError("expected '<' after bits type");
699 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
700 TokError("expected integer in bits<n> type");
703 uint64_t Val = Lex.getCurIntVal();
704 if (Lex.Lex() != tgtok::greater) { // Eat count.
705 TokError("expected '>' at end of bits<n> type");
708 Lex.Lex(); // Eat '>'
709 return BitsRecTy::get(Val);
712 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
713 TokError("expected '<' after list type");
716 Lex.Lex(); // Eat '<'
717 RecTy *SubType = ParseType();
718 if (SubType == 0) return 0;
720 if (Lex.getCode() != tgtok::greater) {
721 TokError("expected '>' at end of list<ty> type");
724 Lex.Lex(); // Eat '>'
725 return ListRecTy::get(SubType);
730 /// ParseIDValue - Parse an ID as a value and decode what it means.
732 /// IDValue ::= ID [def local value]
733 /// IDValue ::= ID [def template arg]
734 /// IDValue ::= ID [multiclass local value]
735 /// IDValue ::= ID [multiclass template argument]
736 /// IDValue ::= ID [def name]
738 Init *TGParser::ParseIDValue(Record *CurRec, IDParseMode Mode) {
739 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
740 std::string Name = Lex.getCurStrVal();
741 SMLoc Loc = Lex.getLoc();
743 return ParseIDValue(CurRec, Name, Loc);
746 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
747 /// has already been read.
748 Init *TGParser::ParseIDValue(Record *CurRec,
749 const std::string &Name, SMLoc NameLoc,
752 if (const RecordVal *RV = CurRec->getValue(Name))
753 return VarInit::get(Name, RV->getType());
755 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
758 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
761 if (CurRec->isTemplateArg(TemplateArgName)) {
762 const RecordVal *RV = CurRec->getValue(TemplateArgName);
763 assert(RV && "Template arg doesn't exist??");
764 return VarInit::get(TemplateArgName, RV->getType());
769 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
772 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
773 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
774 assert(RV && "Template arg doesn't exist??");
775 return VarInit::get(MCName, RV->getType());
779 // If this is in a foreach loop, make sure it's not a loop iterator
780 for (LoopVector::iterator i = Loops.begin(), iend = Loops.end();
783 VarInit *IterVar = dynamic_cast<VarInit *>(i->IterVar);
784 if (IterVar && IterVar->getName() == Name)
788 if (Mode == ParseNameMode)
789 return StringInit::get(Name);
791 if (Record *D = Records.getDef(Name))
792 return DefInit::get(D);
794 if (Mode == ParseValueMode) {
795 Error(NameLoc, "Variable not defined: '" + Name + "'");
799 return StringInit::get(Name);
802 /// ParseOperation - Parse an operator. This returns null on error.
804 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
806 Init *TGParser::ParseOperation(Record *CurRec) {
807 switch (Lex.getCode()) {
809 TokError("unknown operation");
814 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
815 UnOpInit::UnaryOp Code;
818 switch (Lex.getCode()) {
819 default: llvm_unreachable("Unhandled code!");
821 Lex.Lex(); // eat the operation
822 Code = UnOpInit::CAST;
824 Type = ParseOperatorType();
827 TokError("did not get type for unary operator");
833 Lex.Lex(); // eat the operation
834 Code = UnOpInit::HEAD;
837 Lex.Lex(); // eat the operation
838 Code = UnOpInit::TAIL;
841 Lex.Lex(); // eat the operation
842 Code = UnOpInit::EMPTY;
843 Type = IntRecTy::get();
846 if (Lex.getCode() != tgtok::l_paren) {
847 TokError("expected '(' after unary operator");
850 Lex.Lex(); // eat the '('
852 Init *LHS = ParseValue(CurRec);
853 if (LHS == 0) return 0;
855 if (Code == UnOpInit::HEAD
856 || Code == UnOpInit::TAIL
857 || Code == UnOpInit::EMPTY) {
858 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
859 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
860 TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
861 if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
862 TokError("expected list or string type argument in unary operator");
866 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
867 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
868 if (LType == 0 && SType == 0) {
869 TokError("expected list or string type argumnet in unary operator");
874 if (Code == UnOpInit::HEAD
875 || Code == UnOpInit::TAIL) {
876 if (LHSl == 0 && LHSt == 0) {
877 TokError("expected list type argumnet in unary operator");
881 if (LHSl && LHSl->getSize() == 0) {
882 TokError("empty list argument in unary operator");
886 Init *Item = LHSl->getElement(0);
887 TypedInit *Itemt = dynamic_cast<TypedInit*>(Item);
889 TokError("untyped list element in unary operator");
892 if (Code == UnOpInit::HEAD) {
893 Type = Itemt->getType();
895 Type = ListRecTy::get(Itemt->getType());
898 assert(LHSt && "expected list type argument in unary operator");
899 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
901 TokError("expected list type argumnet in unary operator");
904 if (Code == UnOpInit::HEAD) {
905 Type = LType->getElementType();
913 if (Lex.getCode() != tgtok::r_paren) {
914 TokError("expected ')' in unary operator");
917 Lex.Lex(); // eat the ')'
918 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
926 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
927 tgtok::TokKind OpTok = Lex.getCode();
928 SMLoc OpLoc = Lex.getLoc();
929 Lex.Lex(); // eat the operation
931 BinOpInit::BinaryOp Code;
935 default: llvm_unreachable("Unhandled code!");
936 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
937 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
938 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
939 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
940 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
941 case tgtok::XStrConcat:
942 Code = BinOpInit::STRCONCAT;
943 Type = StringRecTy::get();
947 if (Lex.getCode() != tgtok::l_paren) {
948 TokError("expected '(' after binary operator");
951 Lex.Lex(); // eat the '('
953 SmallVector<Init*, 2> InitList;
955 InitList.push_back(ParseValue(CurRec));
956 if (InitList.back() == 0) return 0;
958 while (Lex.getCode() == tgtok::comma) {
959 Lex.Lex(); // eat the ','
961 InitList.push_back(ParseValue(CurRec));
962 if (InitList.back() == 0) return 0;
965 if (Lex.getCode() != tgtok::r_paren) {
966 TokError("expected ')' in operator");
969 Lex.Lex(); // eat the ')'
971 // We allow multiple operands to associative operators like !strconcat as
972 // shorthand for nesting them.
973 if (Code == BinOpInit::STRCONCAT) {
974 while (InitList.size() > 2) {
975 Init *RHS = InitList.pop_back_val();
976 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
977 ->Fold(CurRec, CurMultiClass);
978 InitList.back() = RHS;
982 if (InitList.size() == 2)
983 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
984 ->Fold(CurRec, CurMultiClass);
986 Error(OpLoc, "expected two operands to operator");
991 case tgtok::XForEach:
992 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
993 TernOpInit::TernaryOp Code;
996 tgtok::TokKind LexCode = Lex.getCode();
997 Lex.Lex(); // eat the operation
999 default: llvm_unreachable("Unhandled code!");
1001 Code = TernOpInit::IF;
1003 case tgtok::XForEach:
1004 Code = TernOpInit::FOREACH;
1007 Code = TernOpInit::SUBST;
1010 if (Lex.getCode() != tgtok::l_paren) {
1011 TokError("expected '(' after ternary operator");
1014 Lex.Lex(); // eat the '('
1016 Init *LHS = ParseValue(CurRec);
1017 if (LHS == 0) return 0;
1019 if (Lex.getCode() != tgtok::comma) {
1020 TokError("expected ',' in ternary operator");
1023 Lex.Lex(); // eat the ','
1025 Init *MHS = ParseValue(CurRec);
1026 if (MHS == 0) return 0;
1028 if (Lex.getCode() != tgtok::comma) {
1029 TokError("expected ',' in ternary operator");
1032 Lex.Lex(); // eat the ','
1034 Init *RHS = ParseValue(CurRec);
1035 if (RHS == 0) return 0;
1037 if (Lex.getCode() != tgtok::r_paren) {
1038 TokError("expected ')' in binary operator");
1041 Lex.Lex(); // eat the ')'
1044 default: llvm_unreachable("Unhandled code!");
1049 if (TypedInit *MHSt = dynamic_cast<TypedInit*>(MHS))
1050 MHSTy = MHSt->getType();
1051 if (BitsInit *MHSbits = dynamic_cast<BitsInit*>(MHS))
1052 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1053 if (dynamic_cast<BitInit*>(MHS))
1054 MHSTy = BitRecTy::get();
1056 if (TypedInit *RHSt = dynamic_cast<TypedInit*>(RHS))
1057 RHSTy = RHSt->getType();
1058 if (BitsInit *RHSbits = dynamic_cast<BitsInit*>(RHS))
1059 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1060 if (dynamic_cast<BitInit*>(RHS))
1061 RHSTy = BitRecTy::get();
1063 // For UnsetInit, it's typed from the other hand.
1064 if (dynamic_cast<UnsetInit*>(MHS))
1066 if (dynamic_cast<UnsetInit*>(RHS))
1069 if (!MHSTy || !RHSTy) {
1070 TokError("could not get type for !if");
1074 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1076 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1079 TokError("inconsistent types for !if");
1084 case tgtok::XForEach: {
1085 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
1087 TokError("could not get type for !foreach");
1090 Type = MHSt->getType();
1093 case tgtok::XSubst: {
1094 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
1096 TokError("could not get type for !subst");
1099 Type = RHSt->getType();
1103 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1109 /// ParseOperatorType - Parse a type for an operator. This returns
1112 /// OperatorType ::= '<' Type '>'
1114 RecTy *TGParser::ParseOperatorType() {
1117 if (Lex.getCode() != tgtok::less) {
1118 TokError("expected type name for operator");
1121 Lex.Lex(); // eat the <
1126 TokError("expected type name for operator");
1130 if (Lex.getCode() != tgtok::greater) {
1131 TokError("expected type name for operator");
1134 Lex.Lex(); // eat the >
1140 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1142 /// SimpleValue ::= IDValue
1143 /// SimpleValue ::= INTVAL
1144 /// SimpleValue ::= STRVAL+
1145 /// SimpleValue ::= CODEFRAGMENT
1146 /// SimpleValue ::= '?'
1147 /// SimpleValue ::= '{' ValueList '}'
1148 /// SimpleValue ::= ID '<' ValueListNE '>'
1149 /// SimpleValue ::= '[' ValueList ']'
1150 /// SimpleValue ::= '(' IDValue DagArgList ')'
1151 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1152 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1153 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1154 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1155 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1157 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1160 switch (Lex.getCode()) {
1161 default: TokError("Unknown token when parsing a value"); break;
1163 // This is a leading paste operation. This is deprecated but
1164 // still exists in some .td files. Ignore it.
1165 Lex.Lex(); // Skip '#'.
1166 return ParseSimpleValue(CurRec, ItemType, Mode);
1167 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1168 case tgtok::StrVal: {
1169 std::string Val = Lex.getCurStrVal();
1172 // Handle multiple consecutive concatenated strings.
1173 while (Lex.getCode() == tgtok::StrVal) {
1174 Val += Lex.getCurStrVal();
1178 R = StringInit::get(Val);
1181 case tgtok::CodeFragment:
1182 R = StringInit::get(Lex.getCurStrVal());
1185 case tgtok::question:
1186 R = UnsetInit::get();
1190 SMLoc NameLoc = Lex.getLoc();
1191 std::string Name = Lex.getCurStrVal();
1192 if (Lex.Lex() != tgtok::less) // consume the Id.
1193 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1195 // Value ::= ID '<' ValueListNE '>'
1196 if (Lex.Lex() == tgtok::greater) {
1197 TokError("expected non-empty value list");
1201 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1202 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1204 Record *Class = Records.getClass(Name);
1206 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1210 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1211 if (ValueList.empty()) return 0;
1213 if (Lex.getCode() != tgtok::greater) {
1214 TokError("expected '>' at end of value list");
1217 Lex.Lex(); // eat the '>'
1219 // Create the new record, set it as CurRec temporarily.
1220 static unsigned AnonCounter = 0;
1221 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),
1224 SubClassReference SCRef;
1225 SCRef.RefLoc = NameLoc;
1227 SCRef.TemplateArgs = ValueList;
1228 // Add info about the subclass to NewRec.
1229 if (AddSubClass(NewRec, SCRef))
1231 NewRec->resolveReferences();
1232 Records.addDef(NewRec);
1234 // The result of the expression is a reference to the new record.
1235 return DefInit::get(NewRec);
1237 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1238 SMLoc BraceLoc = Lex.getLoc();
1239 Lex.Lex(); // eat the '{'
1240 std::vector<Init*> Vals;
1242 if (Lex.getCode() != tgtok::r_brace) {
1243 Vals = ParseValueList(CurRec);
1244 if (Vals.empty()) return 0;
1246 if (Lex.getCode() != tgtok::r_brace) {
1247 TokError("expected '}' at end of bit list value");
1250 Lex.Lex(); // eat the '}'
1252 SmallVector<Init *, 16> NewBits(Vals.size());
1254 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1255 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1257 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1258 ") is not convertable to a bit");
1261 NewBits[Vals.size()-i-1] = Bit;
1263 return BitsInit::get(NewBits);
1265 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1266 Lex.Lex(); // eat the '['
1267 std::vector<Init*> Vals;
1269 RecTy *DeducedEltTy = 0;
1270 ListRecTy *GivenListTy = 0;
1272 if (ItemType != 0) {
1273 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1274 if (ListType == 0) {
1275 std::stringstream s;
1276 s << "Type mismatch for list, expected list type, got "
1277 << ItemType->getAsString();
1281 GivenListTy = ListType;
1284 if (Lex.getCode() != tgtok::r_square) {
1285 Vals = ParseValueList(CurRec, 0,
1286 GivenListTy ? GivenListTy->getElementType() : 0);
1287 if (Vals.empty()) return 0;
1289 if (Lex.getCode() != tgtok::r_square) {
1290 TokError("expected ']' at end of list value");
1293 Lex.Lex(); // eat the ']'
1295 RecTy *GivenEltTy = 0;
1296 if (Lex.getCode() == tgtok::less) {
1297 // Optional list element type
1298 Lex.Lex(); // eat the '<'
1300 GivenEltTy = ParseType();
1301 if (GivenEltTy == 0) {
1302 // Couldn't parse element type
1306 if (Lex.getCode() != tgtok::greater) {
1307 TokError("expected '>' at end of list element type");
1310 Lex.Lex(); // eat the '>'
1315 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1318 TypedInit *TArg = dynamic_cast<TypedInit*>(*i);
1320 TokError("Untyped list element");
1324 EltTy = resolveTypes(EltTy, TArg->getType());
1326 TokError("Incompatible types in list elements");
1330 EltTy = TArg->getType();
1334 if (GivenEltTy != 0) {
1336 // Verify consistency
1337 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1338 TokError("Incompatible types in list elements");
1346 if (ItemType == 0) {
1347 TokError("No type for list");
1350 DeducedEltTy = GivenListTy->getElementType();
1352 // Make sure the deduced type is compatible with the given type
1354 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1355 TokError("Element type mismatch for list");
1359 DeducedEltTy = EltTy;
1362 return ListInit::get(Vals, DeducedEltTy);
1364 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1365 Lex.Lex(); // eat the '('
1366 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1367 TokError("expected identifier in dag init");
1371 Init *Operator = ParseValue(CurRec);
1372 if (Operator == 0) return 0;
1374 // If the operator name is present, parse it.
1375 std::string OperatorName;
1376 if (Lex.getCode() == tgtok::colon) {
1377 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1378 TokError("expected variable name in dag operator");
1381 OperatorName = Lex.getCurStrVal();
1382 Lex.Lex(); // eat the VarName.
1385 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1386 if (Lex.getCode() != tgtok::r_paren) {
1387 DagArgs = ParseDagArgList(CurRec);
1388 if (DagArgs.empty()) return 0;
1391 if (Lex.getCode() != tgtok::r_paren) {
1392 TokError("expected ')' in dag init");
1395 Lex.Lex(); // eat the ')'
1397 return DagInit::get(Operator, OperatorName, DagArgs);
1403 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1404 case tgtok::XConcat:
1409 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1411 case tgtok::XForEach:
1412 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1413 return ParseOperation(CurRec);
1420 /// ParseValue - Parse a tblgen value. This returns null on error.
1422 /// Value ::= SimpleValue ValueSuffix*
1423 /// ValueSuffix ::= '{' BitList '}'
1424 /// ValueSuffix ::= '[' BitList ']'
1425 /// ValueSuffix ::= '.' ID
1427 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1428 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1429 if (Result == 0) return 0;
1431 // Parse the suffixes now if present.
1433 switch (Lex.getCode()) {
1434 default: return Result;
1435 case tgtok::l_brace: {
1436 if (Mode == ParseNameMode || Mode == ParseForeachMode)
1437 // This is the beginning of the object body.
1440 SMLoc CurlyLoc = Lex.getLoc();
1441 Lex.Lex(); // eat the '{'
1442 std::vector<unsigned> Ranges = ParseRangeList();
1443 if (Ranges.empty()) return 0;
1445 // Reverse the bitlist.
1446 std::reverse(Ranges.begin(), Ranges.end());
1447 Result = Result->convertInitializerBitRange(Ranges);
1449 Error(CurlyLoc, "Invalid bit range for value");
1454 if (Lex.getCode() != tgtok::r_brace) {
1455 TokError("expected '}' at end of bit range list");
1461 case tgtok::l_square: {
1462 SMLoc SquareLoc = Lex.getLoc();
1463 Lex.Lex(); // eat the '['
1464 std::vector<unsigned> Ranges = ParseRangeList();
1465 if (Ranges.empty()) return 0;
1467 Result = Result->convertInitListSlice(Ranges);
1469 Error(SquareLoc, "Invalid range for list slice");
1474 if (Lex.getCode() != tgtok::r_square) {
1475 TokError("expected ']' at end of list slice");
1482 if (Lex.Lex() != tgtok::Id) { // eat the .
1483 TokError("expected field identifier after '.'");
1486 if (!Result->getFieldType(Lex.getCurStrVal())) {
1487 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1488 Result->getAsString() + "'");
1491 Result = FieldInit::get(Result, Lex.getCurStrVal());
1492 Lex.Lex(); // eat field name
1496 SMLoc PasteLoc = Lex.getLoc();
1498 // Create a !strconcat() operation, first casting each operand to
1499 // a string if necessary.
1501 TypedInit *LHS = dynamic_cast<TypedInit *>(Result);
1503 Error(PasteLoc, "LHS of paste is not typed!");
1507 if (LHS->getType() != StringRecTy::get()) {
1508 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1513 Lex.Lex(); // Eat the '#'.
1514 switch (Lex.getCode()) {
1517 case tgtok::l_brace:
1518 // These are all of the tokens that can begin an object body.
1519 // Some of these can also begin values but we disallow those cases
1520 // because they are unlikely to be useful.
1522 // Trailing paste, concat with an empty string.
1523 RHS = StringInit::get("");
1527 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1528 RHS = dynamic_cast<TypedInit *>(RHSResult);
1530 Error(PasteLoc, "RHS of paste is not typed!");
1534 if (RHS->getType() != StringRecTy::get()) {
1535 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1541 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1542 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1548 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1550 /// ParseDagArgList ::= Value (':' VARNAME)?
1551 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1552 std::vector<std::pair<llvm::Init*, std::string> >
1553 TGParser::ParseDagArgList(Record *CurRec) {
1554 std::vector<std::pair<llvm::Init*, std::string> > Result;
1557 Init *Val = ParseValue(CurRec);
1558 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1560 // If the variable name is present, add it.
1561 std::string VarName;
1562 if (Lex.getCode() == tgtok::colon) {
1563 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1564 TokError("expected variable name in dag literal");
1565 return std::vector<std::pair<llvm::Init*, std::string> >();
1567 VarName = Lex.getCurStrVal();
1568 Lex.Lex(); // eat the VarName.
1571 Result.push_back(std::make_pair(Val, VarName));
1573 if (Lex.getCode() != tgtok::comma) break;
1574 Lex.Lex(); // eat the ','
1581 /// ParseValueList - Parse a comma separated list of values, returning them as a
1582 /// vector. Note that this always expects to be able to parse at least one
1583 /// value. It returns an empty list if this is not possible.
1585 /// ValueList ::= Value (',' Value)
1587 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1589 std::vector<Init*> Result;
1590 RecTy *ItemType = EltTy;
1591 unsigned int ArgN = 0;
1592 if (ArgsRec != 0 && EltTy == 0) {
1593 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1594 if (!TArgs.size()) {
1595 TokError("template argument provided to non-template class");
1596 return std::vector<Init*>();
1598 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1600 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1603 assert(RV && "Template argument record not found??");
1604 ItemType = RV->getType();
1607 Result.push_back(ParseValue(CurRec, ItemType));
1608 if (Result.back() == 0) return std::vector<Init*>();
1610 while (Lex.getCode() == tgtok::comma) {
1611 Lex.Lex(); // Eat the comma
1613 if (ArgsRec != 0 && EltTy == 0) {
1614 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1615 if (ArgN >= TArgs.size()) {
1616 TokError("too many template arguments");
1617 return std::vector<Init*>();
1619 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1620 assert(RV && "Template argument record not found??");
1621 ItemType = RV->getType();
1624 Result.push_back(ParseValue(CurRec, ItemType));
1625 if (Result.back() == 0) return std::vector<Init*>();
1632 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1633 /// empty string on error. This can happen in a number of different context's,
1634 /// including within a def or in the template args for a def (which which case
1635 /// CurRec will be non-null) and within the template args for a multiclass (in
1636 /// which case CurRec will be null, but CurMultiClass will be set). This can
1637 /// also happen within a def that is within a multiclass, which will set both
1638 /// CurRec and CurMultiClass.
1640 /// Declaration ::= FIELD? Type ID ('=' Value)?
1642 Init *TGParser::ParseDeclaration(Record *CurRec,
1643 bool ParsingTemplateArgs) {
1644 // Read the field prefix if present.
1645 bool HasField = Lex.getCode() == tgtok::Field;
1646 if (HasField) Lex.Lex();
1648 RecTy *Type = ParseType();
1649 if (Type == 0) return 0;
1651 if (Lex.getCode() != tgtok::Id) {
1652 TokError("Expected identifier in declaration");
1656 SMLoc IdLoc = Lex.getLoc();
1657 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1660 if (ParsingTemplateArgs) {
1662 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1664 assert(CurMultiClass);
1667 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1672 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1675 // If a value is present, parse it.
1676 if (Lex.getCode() == tgtok::equal) {
1678 SMLoc ValLoc = Lex.getLoc();
1679 Init *Val = ParseValue(CurRec, Type);
1681 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1688 /// ParseForeachDeclaration - Read a foreach declaration, returning
1689 /// the name of the declared object or a NULL Init on error. Return
1690 /// the name of the parsed initializer list through ForeachListName.
1692 /// ForeachDeclaration ::= ID '=' '[' ValueList ']'
1693 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
1694 /// ForeachDeclaration ::= ID '=' RangePiece
1696 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1697 if (Lex.getCode() != tgtok::Id) {
1698 TokError("Expected identifier in foreach declaration");
1702 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1705 // If a value is present, parse it.
1706 if (Lex.getCode() != tgtok::equal) {
1707 TokError("Expected '=' in foreach declaration");
1710 Lex.Lex(); // Eat the '='
1712 RecTy *IterType = 0;
1713 std::vector<unsigned> Ranges;
1715 switch (Lex.getCode()) {
1716 default: TokError("Unknown token when expecting a range list"); return 0;
1717 case tgtok::l_square: { // '[' ValueList ']'
1718 Init *List = ParseSimpleValue(0, 0, ParseForeachMode);
1719 ForeachListValue = dynamic_cast<ListInit*>(List);
1720 if (ForeachListValue == 0) {
1721 TokError("Expected a Value list");
1724 RecTy *ValueType = ForeachListValue->getType();
1725 ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1726 if (ListType == 0) {
1727 TokError("Value list is not of list type");
1730 IterType = ListType->getElementType();
1734 case tgtok::IntVal: { // RangePiece.
1735 if (ParseRangePiece(Ranges))
1740 case tgtok::l_brace: { // '{' RangeList '}'
1741 Lex.Lex(); // eat the '{'
1742 Ranges = ParseRangeList();
1743 if (Lex.getCode() != tgtok::r_brace) {
1744 TokError("expected '}' at end of bit range list");
1752 if (!Ranges.empty()) {
1753 assert(!IterType && "Type already initialized?");
1754 IterType = IntRecTy::get();
1755 std::vector<Init*> Values;
1756 for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
1757 Values.push_back(IntInit::get(Ranges[i]));
1758 ForeachListValue = ListInit::get(Values, IterType);
1764 return VarInit::get(DeclName, IterType);
1767 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1768 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1769 /// template args for a def, which may or may not be in a multiclass. If null,
1770 /// these are the template args for a multiclass.
1772 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1774 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1775 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1776 Lex.Lex(); // eat the '<'
1778 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1780 // Read the first declaration.
1781 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1785 TheRecToAddTo->addTemplateArg(TemplArg);
1787 while (Lex.getCode() == tgtok::comma) {
1788 Lex.Lex(); // eat the ','
1790 // Read the following declarations.
1791 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1794 TheRecToAddTo->addTemplateArg(TemplArg);
1797 if (Lex.getCode() != tgtok::greater)
1798 return TokError("expected '>' at end of template argument list");
1799 Lex.Lex(); // eat the '>'.
1804 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1806 /// BodyItem ::= Declaration ';'
1807 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1808 bool TGParser::ParseBodyItem(Record *CurRec) {
1809 if (Lex.getCode() != tgtok::Let) {
1810 if (ParseDeclaration(CurRec, false) == 0)
1813 if (Lex.getCode() != tgtok::semi)
1814 return TokError("expected ';' after declaration");
1819 // LET ID OptionalRangeList '=' Value ';'
1820 if (Lex.Lex() != tgtok::Id)
1821 return TokError("expected field identifier after let");
1823 SMLoc IdLoc = Lex.getLoc();
1824 std::string FieldName = Lex.getCurStrVal();
1825 Lex.Lex(); // eat the field name.
1827 std::vector<unsigned> BitList;
1828 if (ParseOptionalBitList(BitList))
1830 std::reverse(BitList.begin(), BitList.end());
1832 if (Lex.getCode() != tgtok::equal)
1833 return TokError("expected '=' in let expression");
1834 Lex.Lex(); // eat the '='.
1836 RecordVal *Field = CurRec->getValue(FieldName);
1838 return TokError("Value '" + FieldName + "' unknown!");
1840 RecTy *Type = Field->getType();
1842 Init *Val = ParseValue(CurRec, Type);
1843 if (Val == 0) return true;
1845 if (Lex.getCode() != tgtok::semi)
1846 return TokError("expected ';' after let expression");
1849 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1852 /// ParseBody - Read the body of a class or def. Return true on error, false on
1856 /// Body ::= '{' BodyList '}'
1857 /// BodyList BodyItem*
1859 bool TGParser::ParseBody(Record *CurRec) {
1860 // If this is a null definition, just eat the semi and return.
1861 if (Lex.getCode() == tgtok::semi) {
1866 if (Lex.getCode() != tgtok::l_brace)
1867 return TokError("Expected ';' or '{' to start body");
1871 while (Lex.getCode() != tgtok::r_brace)
1872 if (ParseBodyItem(CurRec))
1880 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1881 /// optional ClassList followed by a Body. CurRec is the current def or class
1882 /// that is being parsed.
1884 /// ObjectBody ::= BaseClassList Body
1885 /// BaseClassList ::= /*empty*/
1886 /// BaseClassList ::= ':' BaseClassListNE
1887 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1889 bool TGParser::ParseObjectBody(Record *CurRec) {
1890 // If there is a baseclass list, read it.
1891 if (Lex.getCode() == tgtok::colon) {
1894 // Read all of the subclasses.
1895 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1898 if (SubClass.Rec == 0) return true;
1901 if (AddSubClass(CurRec, SubClass))
1904 if (Lex.getCode() != tgtok::comma) break;
1905 Lex.Lex(); // eat ','.
1906 SubClass = ParseSubClassReference(CurRec, false);
1910 // Process any variables on the let stack.
1911 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1912 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1913 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1914 LetStack[i][j].Bits, LetStack[i][j].Value))
1917 return ParseBody(CurRec);
1920 /// ParseDef - Parse and return a top level or multiclass def, return the record
1921 /// corresponding to it. This returns null on error.
1923 /// DefInst ::= DEF ObjectName ObjectBody
1925 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1926 SMLoc DefLoc = Lex.getLoc();
1927 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1928 Lex.Lex(); // Eat the 'def' token.
1930 // Parse ObjectName and make a record for it.
1931 Record *CurRec = new Record(ParseObjectName(CurMultiClass), DefLoc, Records);
1933 if (!CurMultiClass && Loops.empty()) {
1934 // Top-level def definition.
1936 // Ensure redefinition doesn't happen.
1937 if (Records.getDef(CurRec->getNameInitAsString())) {
1938 Error(DefLoc, "def '" + CurRec->getNameInitAsString()
1939 + "' already defined");
1942 Records.addDef(CurRec);
1943 } else if (CurMultiClass) {
1944 // Otherwise, a def inside a multiclass, add it to the multiclass.
1945 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1946 if (CurMultiClass->DefPrototypes[i]->getNameInit()
1947 == CurRec->getNameInit()) {
1948 Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
1949 "' already defined in this multiclass!");
1952 CurMultiClass->DefPrototypes.push_back(CurRec);
1955 if (ParseObjectBody(CurRec))
1958 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1959 // See Record::setName(). This resolve step will see any new name
1960 // for the def that might have been created when resolving
1961 // inheritance, values and arguments above.
1962 CurRec->resolveReferences();
1964 // If ObjectBody has template arguments, it's an error.
1965 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1967 if (CurMultiClass) {
1968 // Copy the template arguments for the multiclass into the def.
1969 const std::vector<Init *> &TArgs =
1970 CurMultiClass->Rec.getTemplateArgs();
1972 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1973 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1974 assert(RV && "Template arg doesn't exist?");
1975 CurRec->addValue(*RV);
1979 if (ProcessForeachDefs(CurRec, DefLoc)) {
1981 "Could not process loops for def" + CurRec->getNameInitAsString());
1988 /// ParseForeach - Parse a for statement. Return the record corresponding
1989 /// to it. This returns true on error.
1991 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
1992 /// Foreach ::= FOREACH Declaration IN Object
1994 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
1995 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
1996 Lex.Lex(); // Eat the 'for' token.
1998 // Make a temporary object to record items associated with the for
2000 ListInit *ListValue = 0;
2001 VarInit *IterName = ParseForeachDeclaration(ListValue);
2003 return TokError("expected declaration in for");
2005 if (Lex.getCode() != tgtok::In)
2006 return TokError("Unknown tok");
2007 Lex.Lex(); // Eat the in
2009 // Create a loop object and remember it.
2010 Loops.push_back(ForeachLoop(IterName, ListValue));
2012 if (Lex.getCode() != tgtok::l_brace) {
2013 // FOREACH Declaration IN Object
2014 if (ParseObject(CurMultiClass))
2018 SMLoc BraceLoc = Lex.getLoc();
2019 // Otherwise, this is a group foreach.
2020 Lex.Lex(); // eat the '{'.
2022 // Parse the object list.
2023 if (ParseObjectList(CurMultiClass))
2026 if (Lex.getCode() != tgtok::r_brace) {
2027 TokError("expected '}' at end of foreach command");
2028 return Error(BraceLoc, "to match this '{'");
2030 Lex.Lex(); // Eat the }
2033 // We've processed everything in this loop.
2039 /// ParseClass - Parse a tblgen class definition.
2041 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2043 bool TGParser::ParseClass() {
2044 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2047 if (Lex.getCode() != tgtok::Id)
2048 return TokError("expected class name after 'class' keyword");
2050 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2052 // If the body was previously defined, this is an error.
2053 if (CurRec->getValues().size() > 1 || // Account for NAME.
2054 !CurRec->getSuperClasses().empty() ||
2055 !CurRec->getTemplateArgs().empty())
2056 return TokError("Class '" + CurRec->getNameInitAsString()
2057 + "' already defined");
2059 // If this is the first reference to this class, create and add it.
2060 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
2061 Records.addClass(CurRec);
2063 Lex.Lex(); // eat the name.
2065 // If there are template args, parse them.
2066 if (Lex.getCode() == tgtok::less)
2067 if (ParseTemplateArgList(CurRec))
2070 // Finally, parse the object body.
2071 return ParseObjectBody(CurRec);
2074 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2077 /// LetList ::= LetItem (',' LetItem)*
2078 /// LetItem ::= ID OptionalRangeList '=' Value
2080 std::vector<LetRecord> TGParser::ParseLetList() {
2081 std::vector<LetRecord> Result;
2084 if (Lex.getCode() != tgtok::Id) {
2085 TokError("expected identifier in let definition");
2086 return std::vector<LetRecord>();
2088 std::string Name = Lex.getCurStrVal();
2089 SMLoc NameLoc = Lex.getLoc();
2090 Lex.Lex(); // Eat the identifier.
2092 // Check for an optional RangeList.
2093 std::vector<unsigned> Bits;
2094 if (ParseOptionalRangeList(Bits))
2095 return std::vector<LetRecord>();
2096 std::reverse(Bits.begin(), Bits.end());
2098 if (Lex.getCode() != tgtok::equal) {
2099 TokError("expected '=' in let expression");
2100 return std::vector<LetRecord>();
2102 Lex.Lex(); // eat the '='.
2104 Init *Val = ParseValue(0);
2105 if (Val == 0) return std::vector<LetRecord>();
2107 // Now that we have everything, add the record.
2108 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2110 if (Lex.getCode() != tgtok::comma)
2112 Lex.Lex(); // eat the comma.
2116 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2117 /// different related productions. This works inside multiclasses too.
2119 /// Object ::= LET LetList IN '{' ObjectList '}'
2120 /// Object ::= LET LetList IN Object
2122 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2123 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2126 // Add this entry to the let stack.
2127 std::vector<LetRecord> LetInfo = ParseLetList();
2128 if (LetInfo.empty()) return true;
2129 LetStack.push_back(LetInfo);
2131 if (Lex.getCode() != tgtok::In)
2132 return TokError("expected 'in' at end of top-level 'let'");
2135 // If this is a scalar let, just handle it now
2136 if (Lex.getCode() != tgtok::l_brace) {
2137 // LET LetList IN Object
2138 if (ParseObject(CurMultiClass))
2140 } else { // Object ::= LETCommand '{' ObjectList '}'
2141 SMLoc BraceLoc = Lex.getLoc();
2142 // Otherwise, this is a group let.
2143 Lex.Lex(); // eat the '{'.
2145 // Parse the object list.
2146 if (ParseObjectList(CurMultiClass))
2149 if (Lex.getCode() != tgtok::r_brace) {
2150 TokError("expected '}' at end of top level let command");
2151 return Error(BraceLoc, "to match this '{'");
2156 // Outside this let scope, this let block is not active.
2157 LetStack.pop_back();
2161 /// ParseMultiClass - Parse a multiclass definition.
2163 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2164 /// ':' BaseMultiClassList '{' MultiClassDef+ '}'
2166 bool TGParser::ParseMultiClass() {
2167 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2168 Lex.Lex(); // Eat the multiclass token.
2170 if (Lex.getCode() != tgtok::Id)
2171 return TokError("expected identifier after multiclass for name");
2172 std::string Name = Lex.getCurStrVal();
2174 if (MultiClasses.count(Name))
2175 return TokError("multiclass '" + Name + "' already defined");
2177 CurMultiClass = MultiClasses[Name] = new MultiClass(Name,
2178 Lex.getLoc(), Records);
2179 Lex.Lex(); // Eat the identifier.
2181 // If there are template args, parse them.
2182 if (Lex.getCode() == tgtok::less)
2183 if (ParseTemplateArgList(0))
2186 bool inherits = false;
2188 // If there are submulticlasses, parse them.
2189 if (Lex.getCode() == tgtok::colon) {
2194 // Read all of the submulticlasses.
2195 SubMultiClassReference SubMultiClass =
2196 ParseSubMultiClassReference(CurMultiClass);
2199 if (SubMultiClass.MC == 0) return true;
2202 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2205 if (Lex.getCode() != tgtok::comma) break;
2206 Lex.Lex(); // eat ','.
2207 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2211 if (Lex.getCode() != tgtok::l_brace) {
2213 return TokError("expected '{' in multiclass definition");
2214 else if (Lex.getCode() != tgtok::semi)
2215 return TokError("expected ';' in multiclass definition");
2217 Lex.Lex(); // eat the ';'.
2219 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2220 return TokError("multiclass must contain at least one def");
2222 while (Lex.getCode() != tgtok::r_brace) {
2223 switch (Lex.getCode()) {
2225 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2229 case tgtok::Foreach:
2230 if (ParseObject(CurMultiClass))
2235 Lex.Lex(); // eat the '}'.
2243 InstantiateMulticlassDef(MultiClass &MC,
2246 SMLoc DefmPrefixLoc) {
2247 // We need to preserve DefProto so it can be reused for later
2248 // instantiations, so create a new Record to inherit from it.
2250 // Add in the defm name. If the defm prefix is empty, give each
2251 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2252 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2255 if (DefmPrefix == 0)
2256 DefmPrefix = StringInit::get(GetNewAnonymousName());
2258 Init *DefName = DefProto->getNameInit();
2260 StringInit *DefNameString = dynamic_cast<StringInit *>(DefName);
2262 if (DefNameString != 0) {
2263 // We have a fully expanded string so there are no operators to
2264 // resolve. We should concatenate the given prefix and name.
2266 BinOpInit::get(BinOpInit::STRCONCAT,
2267 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2268 StringRecTy::get())->Fold(DefProto, &MC),
2269 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2272 // Make a trail of SMLocs from the multiclass instantiations.
2273 SmallVector<SMLoc, 4> Locs(1, DefmPrefixLoc);
2274 Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2275 Record *CurRec = new Record(DefName, Locs, Records);
2277 SubClassReference Ref;
2278 Ref.RefLoc = DefmPrefixLoc;
2280 AddSubClass(CurRec, Ref);
2282 // Set the value for NAME. We don't resolve references to it 'til later,
2283 // though, so that uses in nested multiclass names don't get
2285 if (SetValue(CurRec, Ref.RefLoc, "NAME", std::vector<unsigned>(),
2287 Error(DefmPrefixLoc, "Could not resolve "
2288 + CurRec->getNameInitAsString() + ":NAME to '"
2289 + DefmPrefix->getAsUnquotedString() + "'");
2293 // If the DefNameString didn't resolve, we probably have a reference to
2294 // NAME and need to replace it. We need to do at least this much greedily,
2295 // otherwise nested multiclasses will end up with incorrect NAME expansions.
2296 if (DefNameString == 0) {
2297 RecordVal *DefNameRV = CurRec->getValue("NAME");
2298 CurRec->resolveReferencesTo(DefNameRV);
2301 if (!CurMultiClass) {
2302 // Now that we're at the top level, resolve all NAME references
2303 // in the resultant defs that weren't in the def names themselves.
2304 RecordVal *DefNameRV = CurRec->getValue("NAME");
2305 CurRec->resolveReferencesTo(DefNameRV);
2307 // Now that NAME references are resolved and we're at the top level of
2308 // any multiclass expansions, add the record to the RecordKeeper. If we are
2309 // currently in a multiclass, it means this defm appears inside a
2310 // multiclass and its name won't be fully resolvable until we see
2311 // the top-level defm. Therefore, we don't add this to the
2312 // RecordKeeper at this point. If we did we could get duplicate
2313 // defs as more than one probably refers to NAME or some other
2314 // common internal placeholder.
2316 // Ensure redefinition doesn't happen.
2317 if (Records.getDef(CurRec->getNameInitAsString())) {
2318 Error(DefmPrefixLoc, "def '" + CurRec->getNameInitAsString() +
2319 "' already defined, instantiating defm with subdef '" +
2320 DefProto->getNameInitAsString() + "'");
2324 Records.addDef(CurRec);
2330 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2332 SMLoc DefmPrefixLoc,
2334 const std::vector<Init *> &TArgs,
2335 std::vector<Init *> &TemplateVals,
2337 // Loop over all of the template arguments, setting them to the specified
2338 // value or leaving them as the default if necessary.
2339 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2340 // Check if a value is specified for this temp-arg.
2341 if (i < TemplateVals.size()) {
2343 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2348 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2352 CurRec->removeValue(TArgs[i]);
2354 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2355 return Error(SubClassLoc, "value not specified for template argument #"+
2356 utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2357 + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2364 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2367 SMLoc DefmPrefixLoc) {
2368 // If the mdef is inside a 'let' expression, add to each def.
2369 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2370 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2371 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2372 LetStack[i][j].Bits, LetStack[i][j].Value))
2373 return Error(DefmPrefixLoc, "when instantiating this defm");
2375 // Don't create a top level definition for defm inside multiclasses,
2376 // instead, only update the prototypes and bind the template args
2377 // with the new created definition.
2378 if (CurMultiClass) {
2379 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2381 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2382 == CurRec->getNameInit())
2383 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2384 "' already defined in this multiclass!");
2385 CurMultiClass->DefPrototypes.push_back(CurRec);
2387 // Copy the template arguments for the multiclass into the new def.
2388 const std::vector<Init *> &TA =
2389 CurMultiClass->Rec.getTemplateArgs();
2391 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2392 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2393 assert(RV && "Template arg doesn't exist?");
2394 CurRec->addValue(*RV);
2401 /// ParseDefm - Parse the instantiation of a multiclass.
2403 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2405 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2406 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2408 Init *DefmPrefix = 0;
2410 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2411 DefmPrefix = ParseObjectName(CurMultiClass);
2414 SMLoc DefmPrefixLoc = Lex.getLoc();
2415 if (Lex.getCode() != tgtok::colon)
2416 return TokError("expected ':' after defm identifier");
2418 // Keep track of the new generated record definitions.
2419 std::vector<Record*> NewRecDefs;
2421 // This record also inherits from a regular class (non-multiclass)?
2422 bool InheritFromClass = false;
2427 SMLoc SubClassLoc = Lex.getLoc();
2428 SubClassReference Ref = ParseSubClassReference(0, true);
2431 if (Ref.Rec == 0) return true;
2433 // To instantiate a multiclass, we need to first get the multiclass, then
2434 // instantiate each def contained in the multiclass with the SubClassRef
2435 // template parameters.
2436 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2437 assert(MC && "Didn't lookup multiclass correctly?");
2438 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2440 // Verify that the correct number of template arguments were specified.
2441 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2442 if (TArgs.size() < TemplateVals.size())
2443 return Error(SubClassLoc,
2444 "more template args specified than multiclass expects");
2446 // Loop over all the def's in the multiclass, instantiating each one.
2447 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2448 Record *DefProto = MC->DefPrototypes[i];
2450 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix, DefmPrefixLoc);
2454 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmPrefixLoc, SubClassLoc,
2455 TArgs, TemplateVals, true/*Delete args*/))
2456 return Error(SubClassLoc, "could not instantiate def");
2458 if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmPrefixLoc))
2459 return Error(SubClassLoc, "could not instantiate def");
2461 NewRecDefs.push_back(CurRec);
2465 if (Lex.getCode() != tgtok::comma) break;
2466 Lex.Lex(); // eat ','.
2468 SubClassLoc = Lex.getLoc();
2470 // A defm can inherit from regular classes (non-multiclass) as
2471 // long as they come in the end of the inheritance list.
2472 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != 0);
2474 if (InheritFromClass)
2477 Ref = ParseSubClassReference(0, true);
2480 if (InheritFromClass) {
2481 // Process all the classes to inherit as if they were part of a
2482 // regular 'def' and inherit all record values.
2483 SubClassReference SubClass = ParseSubClassReference(0, false);
2486 if (SubClass.Rec == 0) return true;
2488 // Get the expanded definition prototypes and teach them about
2489 // the record values the current class to inherit has
2490 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2491 Record *CurRec = NewRecDefs[i];
2494 if (AddSubClass(CurRec, SubClass))
2497 // Process any variables on the let stack.
2498 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2499 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2500 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2501 LetStack[i][j].Bits, LetStack[i][j].Value))
2505 if (Lex.getCode() != tgtok::comma) break;
2506 Lex.Lex(); // eat ','.
2507 SubClass = ParseSubClassReference(0, false);
2512 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2513 // See Record::setName(). This resolve step will see any new
2514 // name for the def that might have been created when resolving
2515 // inheritance, values and arguments above.
2516 NewRecDefs[i]->resolveReferences();
2518 if (Lex.getCode() != tgtok::semi)
2519 return TokError("expected ';' at end of defm");
2526 /// Object ::= ClassInst
2527 /// Object ::= DefInst
2528 /// Object ::= MultiClassInst
2529 /// Object ::= DefMInst
2530 /// Object ::= LETCommand '{' ObjectList '}'
2531 /// Object ::= LETCommand Object
2532 bool TGParser::ParseObject(MultiClass *MC) {
2533 switch (Lex.getCode()) {
2535 return TokError("Expected class, def, defm, multiclass or let definition");
2536 case tgtok::Let: return ParseTopLevelLet(MC);
2537 case tgtok::Def: return ParseDef(MC);
2538 case tgtok::Foreach: return ParseForeach(MC);
2539 case tgtok::Defm: return ParseDefm(MC);
2540 case tgtok::Class: return ParseClass();
2541 case tgtok::MultiClass: return ParseMultiClass();
2546 /// ObjectList :== Object*
2547 bool TGParser::ParseObjectList(MultiClass *MC) {
2548 while (isObjectStart(Lex.getCode())) {
2549 if (ParseObject(MC))
2555 bool TGParser::ParseFile() {
2556 Lex.Lex(); // Prime the lexer.
2557 if (ParseObjectList()) return true;
2559 // If we have unread input at the end of the file, report it.
2560 if (Lex.getCode() == tgtok::Eof)
2563 return TokError("Unexpected input at top level");