1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implement the Parser for TableGen.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/TableGen/Record.h"
23 //===----------------------------------------------------------------------===//
24 // Support Code for the Semantic Actions.
25 //===----------------------------------------------------------------------===//
28 struct SubClassReference {
31 std::vector<Init*> TemplateArgs;
32 SubClassReference() : Rec(nullptr) {}
34 bool isInvalid() const { return Rec == nullptr; }
37 struct SubMultiClassReference {
40 std::vector<Init*> TemplateArgs;
41 SubMultiClassReference() : MC(nullptr) {}
43 bool isInvalid() const { return MC == nullptr; }
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) CurRec = &CurMultiClass->Rec;
88 RecordVal *RV = CurRec->getValue(ValName);
90 return Error(Loc, "Value '" + ValName->getAsUnquotedString()
93 // Do not allow assignments like 'X = X'. This will just cause infinite loops
94 // in the resolution machinery.
96 if (VarInit *VI = dyn_cast<VarInit>(V))
97 if (VI->getNameInit() == ValName)
100 // If we are assigning to a subset of the bits in the value... then we must be
101 // assigning to a field of BitsRecTy, which must have a BitsInit
104 if (!BitList.empty()) {
105 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
107 return Error(Loc, "Value '" + ValName->getAsUnquotedString()
108 + "' is not a bits type");
110 // Convert the incoming value to a bits type of the appropriate size...
111 Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size()));
113 return Error(Loc, "Initializer is not compatible with bit range");
116 // We should have a BitsInit type now.
117 BitsInit *BInit = dyn_cast<BitsInit>(BI);
118 assert(BInit != nullptr);
120 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
122 // Loop over bits, assigning values as appropriate.
123 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
124 unsigned Bit = BitList[i];
126 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
127 ValName->getAsUnquotedString() + "' more than once");
128 NewBits[Bit] = BInit->getBit(i);
131 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
133 NewBits[i] = CurVal->getBit(i);
135 V = BitsInit::get(NewBits);
139 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of type '"
140 + RV->getType()->getAsString() +
141 "' is incompatible with initializer '" + V->getAsString()
146 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
147 /// args as SubClass's template arguments.
148 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
149 Record *SC = SubClass.Rec;
150 // Add all of the values in the subclass into the current class.
151 const std::vector<RecordVal> &Vals = SC->getValues();
152 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
153 if (AddValue(CurRec, SubClass.RefRange.Start, Vals[i]))
156 const std::vector<Init *> &TArgs = SC->getTemplateArgs();
158 // Ensure that an appropriate number of template arguments are specified.
159 if (TArgs.size() < SubClass.TemplateArgs.size())
160 return Error(SubClass.RefRange.Start,
161 "More template args specified than expected");
163 // Loop over all of the template arguments, setting them to the specified
164 // value or leaving them as the default if necessary.
165 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
166 if (i < SubClass.TemplateArgs.size()) {
167 // If a value is specified for this template arg, set it now.
168 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
169 std::vector<unsigned>(), SubClass.TemplateArgs[i]))
173 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
176 CurRec->removeValue(TArgs[i]);
178 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
179 return Error(SubClass.RefRange.Start,
180 "Value not specified for template argument #"
181 + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
182 + ") of subclass '" + SC->getNameInitAsString() + "'!");
186 // Since everything went well, we can now set the "superclass" list for the
188 const std::vector<Record*> &SCs = SC->getSuperClasses();
189 ArrayRef<SMRange> SCRanges = SC->getSuperClassRanges();
190 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
191 if (CurRec->isSubClassOf(SCs[i]))
192 return Error(SubClass.RefRange.Start,
193 "Already subclass of '" + SCs[i]->getName() + "'!\n");
194 CurRec->addSuperClass(SCs[i], SCRanges[i]);
197 if (CurRec->isSubClassOf(SC))
198 return Error(SubClass.RefRange.Start,
199 "Already subclass of '" + SC->getName() + "'!\n");
200 CurRec->addSuperClass(SC, SubClass.RefRange);
204 /// AddSubMultiClass - Add SubMultiClass as a subclass to
205 /// CurMC, resolving its template args as SubMultiClass's
206 /// template arguments.
207 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
208 SubMultiClassReference &SubMultiClass) {
209 MultiClass *SMC = SubMultiClass.MC;
210 Record *CurRec = &CurMC->Rec;
212 const std::vector<RecordVal> &MCVals = CurRec->getValues();
214 // Add all of the values in the subclass into the current class.
215 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
216 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
217 if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVals[i]))
220 int newDefStart = CurMC->DefPrototypes.size();
222 // Add all of the defs in the subclass into the current multiclass.
223 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
224 iend = SMC->DefPrototypes.end();
227 // Clone the def and add it to the current multiclass
228 Record *NewDef = new Record(**i);
230 // Add all of the values in the superclass into the current def.
231 for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
232 if (AddValue(NewDef, SubMultiClass.RefRange.Start, MCVals[i]))
235 CurMC->DefPrototypes.push_back(NewDef);
238 const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
240 // Ensure that an appropriate number of template arguments are
242 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
243 return Error(SubMultiClass.RefRange.Start,
244 "More template args specified than expected");
246 // Loop over all of the template arguments, setting them to the specified
247 // value or leaving them as the default if necessary.
248 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
249 if (i < SubMultiClass.TemplateArgs.size()) {
250 // If a value is specified for this template arg, set it in the
252 if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i],
253 std::vector<unsigned>(),
254 SubMultiClass.TemplateArgs[i]))
258 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
261 CurRec->removeValue(SMCTArgs[i]);
263 // If a value is specified for this template arg, set it in the
265 for (MultiClass::RecordVector::iterator j =
266 CurMC->DefPrototypes.begin() + newDefStart,
267 jend = CurMC->DefPrototypes.end();
272 if (SetValue(Def, SubMultiClass.RefRange.Start, SMCTArgs[i],
273 std::vector<unsigned>(),
274 SubMultiClass.TemplateArgs[i]))
278 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
281 Def->removeValue(SMCTArgs[i]);
283 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
284 return Error(SubMultiClass.RefRange.Start,
285 "Value not specified for template argument #"
286 + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
287 + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
294 /// ProcessForeachDefs - Given a record, apply all of the variable
295 /// values in all surrounding foreach loops, creating new records for
296 /// each combination of values.
297 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
301 // We want to instantiate a new copy of CurRec for each combination
302 // of nested loop iterator values. We don't want top instantiate
303 // any copies until we have values for each loop iterator.
305 return ProcessForeachDefs(CurRec, Loc, IterVals);
308 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
309 /// apply each of the variable values in this loop and then process
311 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
312 // Recursively build a tuple of iterator values.
313 if (IterVals.size() != Loops.size()) {
314 assert(IterVals.size() < Loops.size());
315 ForeachLoop &CurLoop = Loops[IterVals.size()];
316 ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
318 Error(Loc, "Loop list is not a list");
322 // Process each value.
323 for (int64_t i = 0; i < List->getSize(); ++i) {
324 Init *ItemVal = List->resolveListElementReference(*CurRec, nullptr, i);
325 IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
326 if (ProcessForeachDefs(CurRec, Loc, IterVals))
333 // This is the bottom of the recursion. We have all of the iterator values
334 // for this point in the iteration space. Instantiate a new record to
335 // reflect this combination of values.
336 Record *IterRec = new Record(*CurRec);
338 // Set the iterator values now.
339 for (unsigned i = 0, e = IterVals.size(); i != e; ++i) {
340 VarInit *IterVar = IterVals[i].IterVar;
341 TypedInit *IVal = dyn_cast<TypedInit>(IterVals[i].IterValue);
343 Error(Loc, "foreach iterator value is untyped");
347 IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
349 if (SetValue(IterRec, Loc, IterVar->getName(),
350 std::vector<unsigned>(), IVal)) {
351 Error(Loc, "when instantiating this def");
356 IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
359 IterRec->removeValue(IterVar->getName());
362 if (Records.getDef(IterRec->getNameInitAsString())) {
363 // If this record is anonymous, it's no problem, just generate a new name
364 if (IterRec->isAnonymous())
365 IterRec->setName(GetNewAnonymousName());
367 Error(Loc, "def already exists: " + IterRec->getNameInitAsString());
372 Records.addDef(IterRec);
373 IterRec->resolveReferences();
377 //===----------------------------------------------------------------------===//
379 //===----------------------------------------------------------------------===//
381 /// isObjectStart - Return true if this is a valid first token for an Object.
382 static bool isObjectStart(tgtok::TokKind K) {
383 return K == tgtok::Class || K == tgtok::Def ||
384 K == tgtok::Defm || K == tgtok::Let ||
385 K == tgtok::MultiClass || K == tgtok::Foreach;
388 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
390 std::string TGParser::GetNewAnonymousName() {
391 unsigned Tmp = AnonCounter++; // MSVC2012 ICEs without this.
392 return "anonymous_" + utostr(Tmp);
395 /// ParseObjectName - If an object name is specified, return it. Otherwise,
397 /// ObjectName ::= Value [ '#' Value ]*
398 /// ObjectName ::= /*empty*/
400 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
401 switch (Lex.getCode()) {
405 // These are all of the tokens that can begin an object body.
406 // Some of these can also begin values but we disallow those cases
407 // because they are unlikely to be useful.
413 Record *CurRec = nullptr;
415 CurRec = &CurMultiClass->Rec;
417 RecTy *Type = nullptr;
419 const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
421 TokError("Record name is not typed!");
424 Type = CurRecName->getType();
427 return ParseValue(CurRec, Type, ParseNameMode);
430 /// ParseClassID - Parse and resolve a reference to a class name. This returns
435 Record *TGParser::ParseClassID() {
436 if (Lex.getCode() != tgtok::Id) {
437 TokError("expected name for ClassID");
441 Record *Result = Records.getClass(Lex.getCurStrVal());
443 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
449 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
450 /// This returns null on error.
452 /// MultiClassID ::= ID
454 MultiClass *TGParser::ParseMultiClassID() {
455 if (Lex.getCode() != tgtok::Id) {
456 TokError("expected name for MultiClassID");
460 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
462 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
468 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
469 /// subclass. This returns a SubClassRefTy with a null Record* on error.
471 /// SubClassRef ::= ClassID
472 /// SubClassRef ::= ClassID '<' ValueList '>'
474 SubClassReference TGParser::
475 ParseSubClassReference(Record *CurRec, bool isDefm) {
476 SubClassReference Result;
477 Result.RefRange.Start = Lex.getLoc();
480 if (MultiClass *MC = ParseMultiClassID())
481 Result.Rec = &MC->Rec;
483 Result.Rec = ParseClassID();
485 if (!Result.Rec) return Result;
487 // If there is no template arg list, we're done.
488 if (Lex.getCode() != tgtok::less) {
489 Result.RefRange.End = Lex.getLoc();
492 Lex.Lex(); // Eat the '<'
494 if (Lex.getCode() == tgtok::greater) {
495 TokError("subclass reference requires a non-empty list of template values");
496 Result.Rec = nullptr;
500 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
501 if (Result.TemplateArgs.empty()) {
502 Result.Rec = nullptr; // Error parsing value list.
506 if (Lex.getCode() != tgtok::greater) {
507 TokError("expected '>' in template value list");
508 Result.Rec = nullptr;
512 Result.RefRange.End = Lex.getLoc();
517 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
518 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
519 /// Record* on error.
521 /// SubMultiClassRef ::= MultiClassID
522 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
524 SubMultiClassReference TGParser::
525 ParseSubMultiClassReference(MultiClass *CurMC) {
526 SubMultiClassReference Result;
527 Result.RefRange.Start = Lex.getLoc();
529 Result.MC = ParseMultiClassID();
530 if (!Result.MC) return Result;
532 // If there is no template arg list, we're done.
533 if (Lex.getCode() != tgtok::less) {
534 Result.RefRange.End = Lex.getLoc();
537 Lex.Lex(); // Eat the '<'
539 if (Lex.getCode() == tgtok::greater) {
540 TokError("subclass reference requires a non-empty list of template values");
545 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
546 if (Result.TemplateArgs.empty()) {
547 Result.MC = nullptr; // Error parsing value list.
551 if (Lex.getCode() != tgtok::greater) {
552 TokError("expected '>' in template value list");
557 Result.RefRange.End = Lex.getLoc();
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 nullptr;
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) return nullptr;
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 - This is just like ParseIDValue above, but it assumes the ID
731 /// has already been read.
732 Init *TGParser::ParseIDValue(Record *CurRec,
733 const std::string &Name, SMLoc NameLoc,
736 if (const RecordVal *RV = CurRec->getValue(Name))
737 return VarInit::get(Name, RV->getType());
739 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
742 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
745 if (CurRec->isTemplateArg(TemplateArgName)) {
746 const RecordVal *RV = CurRec->getValue(TemplateArgName);
747 assert(RV && "Template arg doesn't exist??");
748 return VarInit::get(TemplateArgName, RV->getType());
753 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
756 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
757 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
758 assert(RV && "Template arg doesn't exist??");
759 return VarInit::get(MCName, RV->getType());
763 // If this is in a foreach loop, make sure it's not a loop iterator
764 for (LoopVector::iterator i = Loops.begin(), iend = Loops.end();
767 VarInit *IterVar = dyn_cast<VarInit>(i->IterVar);
768 if (IterVar && IterVar->getName() == Name)
772 if (Mode == ParseNameMode)
773 return StringInit::get(Name);
775 if (Record *D = Records.getDef(Name))
776 return DefInit::get(D);
778 if (Mode == ParseValueMode) {
779 Error(NameLoc, "Variable not defined: '" + Name + "'");
783 return StringInit::get(Name);
786 /// ParseOperation - Parse an operator. This returns null on error.
788 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
790 Init *TGParser::ParseOperation(Record *CurRec) {
791 switch (Lex.getCode()) {
793 TokError("unknown operation");
798 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
799 UnOpInit::UnaryOp Code;
800 RecTy *Type = nullptr;
802 switch (Lex.getCode()) {
803 default: llvm_unreachable("Unhandled code!");
805 Lex.Lex(); // eat the operation
806 Code = UnOpInit::CAST;
808 Type = ParseOperatorType();
811 TokError("did not get type for unary operator");
817 Lex.Lex(); // eat the operation
818 Code = UnOpInit::HEAD;
821 Lex.Lex(); // eat the operation
822 Code = UnOpInit::TAIL;
825 Lex.Lex(); // eat the operation
826 Code = UnOpInit::EMPTY;
827 Type = IntRecTy::get();
830 if (Lex.getCode() != tgtok::l_paren) {
831 TokError("expected '(' after unary operator");
834 Lex.Lex(); // eat the '('
836 Init *LHS = ParseValue(CurRec);
837 if (!LHS) return nullptr;
839 if (Code == UnOpInit::HEAD
840 || Code == UnOpInit::TAIL
841 || Code == UnOpInit::EMPTY) {
842 ListInit *LHSl = dyn_cast<ListInit>(LHS);
843 StringInit *LHSs = dyn_cast<StringInit>(LHS);
844 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
845 if (!LHSl && !LHSs && !LHSt) {
846 TokError("expected list or string type argument in unary operator");
850 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
851 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
852 if (!LType && !SType) {
853 TokError("expected list or string type argument in unary operator");
858 if (Code == UnOpInit::HEAD
859 || Code == UnOpInit::TAIL) {
860 if (!LHSl && !LHSt) {
861 TokError("expected list type argument in unary operator");
865 if (LHSl && LHSl->getSize() == 0) {
866 TokError("empty list argument in unary operator");
870 Init *Item = LHSl->getElement(0);
871 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
873 TokError("untyped list element in unary operator");
876 if (Code == UnOpInit::HEAD) {
877 Type = Itemt->getType();
879 Type = ListRecTy::get(Itemt->getType());
882 assert(LHSt && "expected list type argument in unary operator");
883 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
885 TokError("expected list type argument in unary operator");
888 if (Code == UnOpInit::HEAD) {
889 Type = LType->getElementType();
897 if (Lex.getCode() != tgtok::r_paren) {
898 TokError("expected ')' in unary operator");
901 Lex.Lex(); // eat the ')'
902 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
911 case tgtok::XListConcat:
912 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
913 tgtok::TokKind OpTok = Lex.getCode();
914 SMLoc OpLoc = Lex.getLoc();
915 Lex.Lex(); // eat the operation
917 BinOpInit::BinaryOp Code;
918 RecTy *Type = nullptr;
921 default: llvm_unreachable("Unhandled code!");
922 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
923 case tgtok::XADD: Code = BinOpInit::ADD; Type = IntRecTy::get(); break;
924 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
925 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
926 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
927 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
928 case tgtok::XListConcat:
929 Code = BinOpInit::LISTCONCAT;
930 // We don't know the list type until we parse the first argument
932 case tgtok::XStrConcat:
933 Code = BinOpInit::STRCONCAT;
934 Type = StringRecTy::get();
938 if (Lex.getCode() != tgtok::l_paren) {
939 TokError("expected '(' after binary operator");
942 Lex.Lex(); // eat the '('
944 SmallVector<Init*, 2> InitList;
946 InitList.push_back(ParseValue(CurRec));
947 if (!InitList.back()) return nullptr;
949 while (Lex.getCode() == tgtok::comma) {
950 Lex.Lex(); // eat the ','
952 InitList.push_back(ParseValue(CurRec));
953 if (!InitList.back()) return nullptr;
956 if (Lex.getCode() != tgtok::r_paren) {
957 TokError("expected ')' in operator");
960 Lex.Lex(); // eat the ')'
962 // If we are doing !listconcat, we should know the type by now
963 if (OpTok == tgtok::XListConcat) {
964 if (VarInit *Arg0 = dyn_cast<VarInit>(InitList[0]))
965 Type = Arg0->getType();
966 else if (ListInit *Arg0 = dyn_cast<ListInit>(InitList[0]))
967 Type = Arg0->getType();
970 Error(OpLoc, "expected a list");
975 // We allow multiple operands to associative operators like !strconcat as
976 // shorthand for nesting them.
977 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT) {
978 while (InitList.size() > 2) {
979 Init *RHS = InitList.pop_back_val();
980 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
981 ->Fold(CurRec, CurMultiClass);
982 InitList.back() = RHS;
986 if (InitList.size() == 2)
987 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
988 ->Fold(CurRec, CurMultiClass);
990 Error(OpLoc, "expected two operands to operator");
995 case tgtok::XForEach:
996 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
997 TernOpInit::TernaryOp Code;
998 RecTy *Type = nullptr;
1000 tgtok::TokKind LexCode = Lex.getCode();
1001 Lex.Lex(); // eat the operation
1003 default: llvm_unreachable("Unhandled code!");
1005 Code = TernOpInit::IF;
1007 case tgtok::XForEach:
1008 Code = TernOpInit::FOREACH;
1011 Code = TernOpInit::SUBST;
1014 if (Lex.getCode() != tgtok::l_paren) {
1015 TokError("expected '(' after ternary operator");
1018 Lex.Lex(); // eat the '('
1020 Init *LHS = ParseValue(CurRec);
1021 if (!LHS) return nullptr;
1023 if (Lex.getCode() != tgtok::comma) {
1024 TokError("expected ',' in ternary operator");
1027 Lex.Lex(); // eat the ','
1029 Init *MHS = ParseValue(CurRec);
1030 if (!MHS) return nullptr;
1032 if (Lex.getCode() != tgtok::comma) {
1033 TokError("expected ',' in ternary operator");
1036 Lex.Lex(); // eat the ','
1038 Init *RHS = ParseValue(CurRec);
1039 if (!RHS) return nullptr;
1041 if (Lex.getCode() != tgtok::r_paren) {
1042 TokError("expected ')' in binary operator");
1045 Lex.Lex(); // eat the ')'
1048 default: llvm_unreachable("Unhandled code!");
1050 RecTy *MHSTy = nullptr;
1051 RecTy *RHSTy = nullptr;
1053 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1054 MHSTy = MHSt->getType();
1055 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1056 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1057 if (isa<BitInit>(MHS))
1058 MHSTy = BitRecTy::get();
1060 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1061 RHSTy = RHSt->getType();
1062 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1063 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1064 if (isa<BitInit>(RHS))
1065 RHSTy = BitRecTy::get();
1067 // For UnsetInit, it's typed from the other hand.
1068 if (isa<UnsetInit>(MHS))
1070 if (isa<UnsetInit>(RHS))
1073 if (!MHSTy || !RHSTy) {
1074 TokError("could not get type for !if");
1078 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1080 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1083 TokError("inconsistent types for !if");
1088 case tgtok::XForEach: {
1089 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1091 TokError("could not get type for !foreach");
1094 Type = MHSt->getType();
1097 case tgtok::XSubst: {
1098 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1100 TokError("could not get type for !subst");
1103 Type = RHSt->getType();
1107 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1113 /// ParseOperatorType - Parse a type for an operator. This returns
1116 /// OperatorType ::= '<' Type '>'
1118 RecTy *TGParser::ParseOperatorType() {
1119 RecTy *Type = nullptr;
1121 if (Lex.getCode() != tgtok::less) {
1122 TokError("expected type name for operator");
1125 Lex.Lex(); // eat the <
1130 TokError("expected type name for operator");
1134 if (Lex.getCode() != tgtok::greater) {
1135 TokError("expected type name for operator");
1138 Lex.Lex(); // eat the >
1144 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1146 /// SimpleValue ::= IDValue
1147 /// SimpleValue ::= INTVAL
1148 /// SimpleValue ::= STRVAL+
1149 /// SimpleValue ::= CODEFRAGMENT
1150 /// SimpleValue ::= '?'
1151 /// SimpleValue ::= '{' ValueList '}'
1152 /// SimpleValue ::= ID '<' ValueListNE '>'
1153 /// SimpleValue ::= '[' ValueList ']'
1154 /// SimpleValue ::= '(' IDValue DagArgList ')'
1155 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1156 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1157 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1158 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1159 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1160 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1161 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1163 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1166 switch (Lex.getCode()) {
1167 default: TokError("Unknown token when parsing a value"); break;
1169 // This is a leading paste operation. This is deprecated but
1170 // still exists in some .td files. Ignore it.
1171 Lex.Lex(); // Skip '#'.
1172 return ParseSimpleValue(CurRec, ItemType, Mode);
1173 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1174 case tgtok::StrVal: {
1175 std::string Val = Lex.getCurStrVal();
1178 // Handle multiple consecutive concatenated strings.
1179 while (Lex.getCode() == tgtok::StrVal) {
1180 Val += Lex.getCurStrVal();
1184 R = StringInit::get(Val);
1187 case tgtok::CodeFragment:
1188 R = StringInit::get(Lex.getCurStrVal());
1191 case tgtok::question:
1192 R = UnsetInit::get();
1196 SMLoc NameLoc = Lex.getLoc();
1197 std::string Name = Lex.getCurStrVal();
1198 if (Lex.Lex() != tgtok::less) // consume the Id.
1199 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1201 // Value ::= ID '<' ValueListNE '>'
1202 if (Lex.Lex() == tgtok::greater) {
1203 TokError("expected non-empty value list");
1207 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1208 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1210 Record *Class = Records.getClass(Name);
1212 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1216 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1217 if (ValueList.empty()) return nullptr;
1219 if (Lex.getCode() != tgtok::greater) {
1220 TokError("expected '>' at end of value list");
1223 Lex.Lex(); // eat the '>'
1224 SMLoc EndLoc = Lex.getLoc();
1226 // Create the new record, set it as CurRec temporarily.
1227 Record *NewRec = new Record(GetNewAnonymousName(), NameLoc, Records,
1228 /*IsAnonymous=*/true);
1229 SubClassReference SCRef;
1230 SCRef.RefRange = SMRange(NameLoc, EndLoc);
1232 SCRef.TemplateArgs = ValueList;
1233 // Add info about the subclass to NewRec.
1234 if (AddSubClass(NewRec, SCRef))
1236 if (!CurMultiClass) {
1237 NewRec->resolveReferences();
1238 Records.addDef(NewRec);
1240 // Otherwise, we're inside a multiclass, add it to the multiclass.
1241 CurMultiClass->DefPrototypes.push_back(NewRec);
1243 // Copy the template arguments for the multiclass into the def.
1244 const std::vector<Init *> &TArgs =
1245 CurMultiClass->Rec.getTemplateArgs();
1247 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1248 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1249 assert(RV && "Template arg doesn't exist?");
1250 NewRec->addValue(*RV);
1253 // We can't return the prototype def here, instead return:
1254 // !cast<ItemType>(!strconcat(NAME, AnonName)).
1255 const RecordVal *MCNameRV = CurMultiClass->Rec.getValue("NAME");
1256 assert(MCNameRV && "multiclass record must have a NAME");
1258 return UnOpInit::get(UnOpInit::CAST,
1259 BinOpInit::get(BinOpInit::STRCONCAT,
1260 VarInit::get(MCNameRV->getName(),
1261 MCNameRV->getType()),
1262 NewRec->getNameInit(),
1263 StringRecTy::get()),
1264 Class->getDefInit()->getType());
1267 // The result of the expression is a reference to the new record.
1268 return DefInit::get(NewRec);
1270 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1271 SMLoc BraceLoc = Lex.getLoc();
1272 Lex.Lex(); // eat the '{'
1273 std::vector<Init*> Vals;
1275 if (Lex.getCode() != tgtok::r_brace) {
1276 Vals = ParseValueList(CurRec);
1277 if (Vals.empty()) return nullptr;
1279 if (Lex.getCode() != tgtok::r_brace) {
1280 TokError("expected '}' at end of bit list value");
1283 Lex.Lex(); // eat the '}'
1285 SmallVector<Init *, 16> NewBits(Vals.size());
1287 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1288 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1290 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1291 ") is not convertable to a bit");
1294 NewBits[Vals.size()-i-1] = Bit;
1296 return BitsInit::get(NewBits);
1298 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1299 Lex.Lex(); // eat the '['
1300 std::vector<Init*> Vals;
1302 RecTy *DeducedEltTy = nullptr;
1303 ListRecTy *GivenListTy = nullptr;
1306 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1309 raw_string_ostream ss(s);
1310 ss << "Type mismatch for list, expected list type, got "
1311 << ItemType->getAsString();
1315 GivenListTy = ListType;
1318 if (Lex.getCode() != tgtok::r_square) {
1319 Vals = ParseValueList(CurRec, nullptr,
1320 GivenListTy ? GivenListTy->getElementType() : nullptr);
1321 if (Vals.empty()) return nullptr;
1323 if (Lex.getCode() != tgtok::r_square) {
1324 TokError("expected ']' at end of list value");
1327 Lex.Lex(); // eat the ']'
1329 RecTy *GivenEltTy = nullptr;
1330 if (Lex.getCode() == tgtok::less) {
1331 // Optional list element type
1332 Lex.Lex(); // eat the '<'
1334 GivenEltTy = ParseType();
1336 // Couldn't parse element type
1340 if (Lex.getCode() != tgtok::greater) {
1341 TokError("expected '>' at end of list element type");
1344 Lex.Lex(); // eat the '>'
1348 RecTy *EltTy = nullptr;
1349 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1352 TypedInit *TArg = dyn_cast<TypedInit>(*i);
1354 TokError("Untyped list element");
1358 EltTy = resolveTypes(EltTy, TArg->getType());
1360 TokError("Incompatible types in list elements");
1364 EltTy = TArg->getType();
1370 // Verify consistency
1371 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1372 TokError("Incompatible types in list elements");
1381 TokError("No type for list");
1384 DeducedEltTy = GivenListTy->getElementType();
1386 // Make sure the deduced type is compatible with the given type
1388 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1389 TokError("Element type mismatch for list");
1393 DeducedEltTy = EltTy;
1396 return ListInit::get(Vals, DeducedEltTy);
1398 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1399 Lex.Lex(); // eat the '('
1400 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1401 TokError("expected identifier in dag init");
1405 Init *Operator = ParseValue(CurRec);
1406 if (!Operator) return nullptr;
1408 // If the operator name is present, parse it.
1409 std::string OperatorName;
1410 if (Lex.getCode() == tgtok::colon) {
1411 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1412 TokError("expected variable name in dag operator");
1415 OperatorName = Lex.getCurStrVal();
1416 Lex.Lex(); // eat the VarName.
1419 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1420 if (Lex.getCode() != tgtok::r_paren) {
1421 DagArgs = ParseDagArgList(CurRec);
1422 if (DagArgs.empty()) return nullptr;
1425 if (Lex.getCode() != tgtok::r_paren) {
1426 TokError("expected ')' in dag init");
1429 Lex.Lex(); // eat the ')'
1431 return DagInit::get(Operator, OperatorName, DagArgs);
1437 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1438 case tgtok::XConcat:
1444 case tgtok::XListConcat:
1445 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1447 case tgtok::XForEach:
1448 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1449 return ParseOperation(CurRec);
1456 /// ParseValue - Parse a tblgen value. This returns null on error.
1458 /// Value ::= SimpleValue ValueSuffix*
1459 /// ValueSuffix ::= '{' BitList '}'
1460 /// ValueSuffix ::= '[' BitList ']'
1461 /// ValueSuffix ::= '.' ID
1463 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1464 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1465 if (!Result) return nullptr;
1467 // Parse the suffixes now if present.
1469 switch (Lex.getCode()) {
1470 default: return Result;
1471 case tgtok::l_brace: {
1472 if (Mode == ParseNameMode || Mode == ParseForeachMode)
1473 // This is the beginning of the object body.
1476 SMLoc CurlyLoc = Lex.getLoc();
1477 Lex.Lex(); // eat the '{'
1478 std::vector<unsigned> Ranges = ParseRangeList();
1479 if (Ranges.empty()) return nullptr;
1481 // Reverse the bitlist.
1482 std::reverse(Ranges.begin(), Ranges.end());
1483 Result = Result->convertInitializerBitRange(Ranges);
1485 Error(CurlyLoc, "Invalid bit range for value");
1490 if (Lex.getCode() != tgtok::r_brace) {
1491 TokError("expected '}' at end of bit range list");
1497 case tgtok::l_square: {
1498 SMLoc SquareLoc = Lex.getLoc();
1499 Lex.Lex(); // eat the '['
1500 std::vector<unsigned> Ranges = ParseRangeList();
1501 if (Ranges.empty()) return nullptr;
1503 Result = Result->convertInitListSlice(Ranges);
1505 Error(SquareLoc, "Invalid range for list slice");
1510 if (Lex.getCode() != tgtok::r_square) {
1511 TokError("expected ']' at end of list slice");
1518 if (Lex.Lex() != tgtok::Id) { // eat the .
1519 TokError("expected field identifier after '.'");
1522 if (!Result->getFieldType(Lex.getCurStrVal())) {
1523 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1524 Result->getAsString() + "'");
1527 Result = FieldInit::get(Result, Lex.getCurStrVal());
1528 Lex.Lex(); // eat field name
1532 SMLoc PasteLoc = Lex.getLoc();
1534 // Create a !strconcat() operation, first casting each operand to
1535 // a string if necessary.
1537 TypedInit *LHS = dyn_cast<TypedInit>(Result);
1539 Error(PasteLoc, "LHS of paste is not typed!");
1543 if (LHS->getType() != StringRecTy::get()) {
1544 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1547 TypedInit *RHS = nullptr;
1549 Lex.Lex(); // Eat the '#'.
1550 switch (Lex.getCode()) {
1553 case tgtok::l_brace:
1554 // These are all of the tokens that can begin an object body.
1555 // Some of these can also begin values but we disallow those cases
1556 // because they are unlikely to be useful.
1558 // Trailing paste, concat with an empty string.
1559 RHS = StringInit::get("");
1563 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1564 RHS = dyn_cast<TypedInit>(RHSResult);
1566 Error(PasteLoc, "RHS of paste is not typed!");
1570 if (RHS->getType() != StringRecTy::get()) {
1571 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1577 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1578 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1584 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1586 /// DagArg ::= Value (':' VARNAME)?
1587 /// DagArg ::= VARNAME
1588 /// DagArgList ::= DagArg
1589 /// DagArgList ::= DagArgList ',' DagArg
1590 std::vector<std::pair<llvm::Init*, std::string> >
1591 TGParser::ParseDagArgList(Record *CurRec) {
1592 std::vector<std::pair<llvm::Init*, std::string> > Result;
1595 // DagArg ::= VARNAME
1596 if (Lex.getCode() == tgtok::VarName) {
1597 // A missing value is treated like '?'.
1598 Result.push_back(std::make_pair(UnsetInit::get(), Lex.getCurStrVal()));
1601 // DagArg ::= Value (':' VARNAME)?
1602 Init *Val = ParseValue(CurRec);
1604 return std::vector<std::pair<llvm::Init*, std::string> >();
1606 // If the variable name is present, add it.
1607 std::string VarName;
1608 if (Lex.getCode() == tgtok::colon) {
1609 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1610 TokError("expected variable name in dag literal");
1611 return std::vector<std::pair<llvm::Init*, std::string> >();
1613 VarName = Lex.getCurStrVal();
1614 Lex.Lex(); // eat the VarName.
1617 Result.push_back(std::make_pair(Val, VarName));
1619 if (Lex.getCode() != tgtok::comma) break;
1620 Lex.Lex(); // eat the ','
1627 /// ParseValueList - Parse a comma separated list of values, returning them as a
1628 /// vector. Note that this always expects to be able to parse at least one
1629 /// value. It returns an empty list if this is not possible.
1631 /// ValueList ::= Value (',' Value)
1633 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1635 std::vector<Init*> Result;
1636 RecTy *ItemType = EltTy;
1637 unsigned int ArgN = 0;
1638 if (ArgsRec && !EltTy) {
1639 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1640 if (!TArgs.size()) {
1641 TokError("template argument provided to non-template class");
1642 return std::vector<Init*>();
1644 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1646 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1649 assert(RV && "Template argument record not found??");
1650 ItemType = RV->getType();
1653 Result.push_back(ParseValue(CurRec, ItemType));
1654 if (!Result.back()) return std::vector<Init*>();
1656 while (Lex.getCode() == tgtok::comma) {
1657 Lex.Lex(); // Eat the comma
1659 if (ArgsRec && !EltTy) {
1660 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1661 if (ArgN >= TArgs.size()) {
1662 TokError("too many template arguments");
1663 return std::vector<Init*>();
1665 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1666 assert(RV && "Template argument record not found??");
1667 ItemType = RV->getType();
1670 Result.push_back(ParseValue(CurRec, ItemType));
1671 if (!Result.back()) return std::vector<Init*>();
1678 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1679 /// empty string on error. This can happen in a number of different context's,
1680 /// including within a def or in the template args for a def (which which case
1681 /// CurRec will be non-null) and within the template args for a multiclass (in
1682 /// which case CurRec will be null, but CurMultiClass will be set). This can
1683 /// also happen within a def that is within a multiclass, which will set both
1684 /// CurRec and CurMultiClass.
1686 /// Declaration ::= FIELD? Type ID ('=' Value)?
1688 Init *TGParser::ParseDeclaration(Record *CurRec,
1689 bool ParsingTemplateArgs) {
1690 // Read the field prefix if present.
1691 bool HasField = Lex.getCode() == tgtok::Field;
1692 if (HasField) Lex.Lex();
1694 RecTy *Type = ParseType();
1695 if (!Type) return nullptr;
1697 if (Lex.getCode() != tgtok::Id) {
1698 TokError("Expected identifier in declaration");
1702 SMLoc IdLoc = Lex.getLoc();
1703 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1706 if (ParsingTemplateArgs) {
1708 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1710 assert(CurMultiClass);
1713 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1718 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1721 // If a value is present, parse it.
1722 if (Lex.getCode() == tgtok::equal) {
1724 SMLoc ValLoc = Lex.getLoc();
1725 Init *Val = ParseValue(CurRec, Type);
1727 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1734 /// ParseForeachDeclaration - Read a foreach declaration, returning
1735 /// the name of the declared object or a NULL Init on error. Return
1736 /// the name of the parsed initializer list through ForeachListName.
1738 /// ForeachDeclaration ::= ID '=' '[' ValueList ']'
1739 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
1740 /// ForeachDeclaration ::= ID '=' RangePiece
1742 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1743 if (Lex.getCode() != tgtok::Id) {
1744 TokError("Expected identifier in foreach declaration");
1748 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1751 // If a value is present, parse it.
1752 if (Lex.getCode() != tgtok::equal) {
1753 TokError("Expected '=' in foreach declaration");
1756 Lex.Lex(); // Eat the '='
1758 RecTy *IterType = nullptr;
1759 std::vector<unsigned> Ranges;
1761 switch (Lex.getCode()) {
1762 default: TokError("Unknown token when expecting a range list"); return nullptr;
1763 case tgtok::l_square: { // '[' ValueList ']'
1764 Init *List = ParseSimpleValue(nullptr, nullptr, ParseForeachMode);
1765 ForeachListValue = dyn_cast<ListInit>(List);
1766 if (!ForeachListValue) {
1767 TokError("Expected a Value list");
1770 RecTy *ValueType = ForeachListValue->getType();
1771 ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1773 TokError("Value list is not of list type");
1776 IterType = ListType->getElementType();
1780 case tgtok::IntVal: { // RangePiece.
1781 if (ParseRangePiece(Ranges))
1786 case tgtok::l_brace: { // '{' RangeList '}'
1787 Lex.Lex(); // eat the '{'
1788 Ranges = ParseRangeList();
1789 if (Lex.getCode() != tgtok::r_brace) {
1790 TokError("expected '}' at end of bit range list");
1798 if (!Ranges.empty()) {
1799 assert(!IterType && "Type already initialized?");
1800 IterType = IntRecTy::get();
1801 std::vector<Init*> Values;
1802 for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
1803 Values.push_back(IntInit::get(Ranges[i]));
1804 ForeachListValue = ListInit::get(Values, IterType);
1810 return VarInit::get(DeclName, IterType);
1813 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1814 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1815 /// template args for a def, which may or may not be in a multiclass. If null,
1816 /// these are the template args for a multiclass.
1818 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1820 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1821 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1822 Lex.Lex(); // eat the '<'
1824 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1826 // Read the first declaration.
1827 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1831 TheRecToAddTo->addTemplateArg(TemplArg);
1833 while (Lex.getCode() == tgtok::comma) {
1834 Lex.Lex(); // eat the ','
1836 // Read the following declarations.
1837 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1840 TheRecToAddTo->addTemplateArg(TemplArg);
1843 if (Lex.getCode() != tgtok::greater)
1844 return TokError("expected '>' at end of template argument list");
1845 Lex.Lex(); // eat the '>'.
1850 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1852 /// BodyItem ::= Declaration ';'
1853 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1854 bool TGParser::ParseBodyItem(Record *CurRec) {
1855 if (Lex.getCode() != tgtok::Let) {
1856 if (!ParseDeclaration(CurRec, false))
1859 if (Lex.getCode() != tgtok::semi)
1860 return TokError("expected ';' after declaration");
1865 // LET ID OptionalRangeList '=' Value ';'
1866 if (Lex.Lex() != tgtok::Id)
1867 return TokError("expected field identifier after let");
1869 SMLoc IdLoc = Lex.getLoc();
1870 std::string FieldName = Lex.getCurStrVal();
1871 Lex.Lex(); // eat the field name.
1873 std::vector<unsigned> BitList;
1874 if (ParseOptionalBitList(BitList))
1876 std::reverse(BitList.begin(), BitList.end());
1878 if (Lex.getCode() != tgtok::equal)
1879 return TokError("expected '=' in let expression");
1880 Lex.Lex(); // eat the '='.
1882 RecordVal *Field = CurRec->getValue(FieldName);
1884 return TokError("Value '" + FieldName + "' unknown!");
1886 RecTy *Type = Field->getType();
1888 Init *Val = ParseValue(CurRec, Type);
1889 if (!Val) return true;
1891 if (Lex.getCode() != tgtok::semi)
1892 return TokError("expected ';' after let expression");
1895 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1898 /// ParseBody - Read the body of a class or def. Return true on error, false on
1902 /// Body ::= '{' BodyList '}'
1903 /// BodyList BodyItem*
1905 bool TGParser::ParseBody(Record *CurRec) {
1906 // If this is a null definition, just eat the semi and return.
1907 if (Lex.getCode() == tgtok::semi) {
1912 if (Lex.getCode() != tgtok::l_brace)
1913 return TokError("Expected ';' or '{' to start body");
1917 while (Lex.getCode() != tgtok::r_brace)
1918 if (ParseBodyItem(CurRec))
1926 /// \brief Apply the current let bindings to \a CurRec.
1927 /// \returns true on error, false otherwise.
1928 bool TGParser::ApplyLetStack(Record *CurRec) {
1929 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1930 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1931 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1932 LetStack[i][j].Bits, LetStack[i][j].Value))
1937 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1938 /// optional ClassList followed by a Body. CurRec is the current def or class
1939 /// that is being parsed.
1941 /// ObjectBody ::= BaseClassList Body
1942 /// BaseClassList ::= /*empty*/
1943 /// BaseClassList ::= ':' BaseClassListNE
1944 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1946 bool TGParser::ParseObjectBody(Record *CurRec) {
1947 // If there is a baseclass list, read it.
1948 if (Lex.getCode() == tgtok::colon) {
1951 // Read all of the subclasses.
1952 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1955 if (!SubClass.Rec) return true;
1958 if (AddSubClass(CurRec, SubClass))
1961 if (Lex.getCode() != tgtok::comma) break;
1962 Lex.Lex(); // eat ','.
1963 SubClass = ParseSubClassReference(CurRec, false);
1967 if (ApplyLetStack(CurRec))
1970 return ParseBody(CurRec);
1973 /// ParseDef - Parse and return a top level or multiclass def, return the record
1974 /// corresponding to it. This returns null on error.
1976 /// DefInst ::= DEF ObjectName ObjectBody
1978 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1979 SMLoc DefLoc = Lex.getLoc();
1980 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1981 Lex.Lex(); // Eat the 'def' token.
1983 // Parse ObjectName and make a record for it.
1985 Init *Name = ParseObjectName(CurMultiClass);
1987 CurRec = new Record(Name, DefLoc, Records);
1989 CurRec = new Record(GetNewAnonymousName(), DefLoc, Records,
1990 /*IsAnonymous=*/true);
1992 if (!CurMultiClass && Loops.empty()) {
1993 // Top-level def definition.
1995 // Ensure redefinition doesn't happen.
1996 if (Records.getDef(CurRec->getNameInitAsString())) {
1997 Error(DefLoc, "def '" + CurRec->getNameInitAsString()
1998 + "' already defined");
2001 Records.addDef(CurRec);
2003 if (ParseObjectBody(CurRec))
2005 } else if (CurMultiClass) {
2006 // Parse the body before adding this prototype to the DefPrototypes vector.
2007 // That way implicit definitions will be added to the DefPrototypes vector
2008 // before this object, instantiated prior to defs derived from this object,
2009 // and this available for indirect name resolution when defs derived from
2010 // this object are instantiated.
2011 if (ParseObjectBody(CurRec))
2014 // Otherwise, a def inside a multiclass, add it to the multiclass.
2015 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
2016 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2017 == CurRec->getNameInit()) {
2018 Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
2019 "' already defined in this multiclass!");
2022 CurMultiClass->DefPrototypes.push_back(CurRec);
2023 } else if (ParseObjectBody(CurRec))
2026 if (!CurMultiClass) // Def's in multiclasses aren't really defs.
2027 // See Record::setName(). This resolve step will see any new name
2028 // for the def that might have been created when resolving
2029 // inheritance, values and arguments above.
2030 CurRec->resolveReferences();
2032 // If ObjectBody has template arguments, it's an error.
2033 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
2035 if (CurMultiClass) {
2036 // Copy the template arguments for the multiclass into the def.
2037 const std::vector<Init *> &TArgs =
2038 CurMultiClass->Rec.getTemplateArgs();
2040 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2041 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
2042 assert(RV && "Template arg doesn't exist?");
2043 CurRec->addValue(*RV);
2047 if (ProcessForeachDefs(CurRec, DefLoc)) {
2049 "Could not process loops for def" + CurRec->getNameInitAsString());
2056 /// ParseForeach - Parse a for statement. Return the record corresponding
2057 /// to it. This returns true on error.
2059 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2060 /// Foreach ::= FOREACH Declaration IN Object
2062 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2063 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2064 Lex.Lex(); // Eat the 'for' token.
2066 // Make a temporary object to record items associated with the for
2068 ListInit *ListValue = nullptr;
2069 VarInit *IterName = ParseForeachDeclaration(ListValue);
2071 return TokError("expected declaration in for");
2073 if (Lex.getCode() != tgtok::In)
2074 return TokError("Unknown tok");
2075 Lex.Lex(); // Eat the in
2077 // Create a loop object and remember it.
2078 Loops.push_back(ForeachLoop(IterName, ListValue));
2080 if (Lex.getCode() != tgtok::l_brace) {
2081 // FOREACH Declaration IN Object
2082 if (ParseObject(CurMultiClass))
2086 SMLoc BraceLoc = Lex.getLoc();
2087 // Otherwise, this is a group foreach.
2088 Lex.Lex(); // eat the '{'.
2090 // Parse the object list.
2091 if (ParseObjectList(CurMultiClass))
2094 if (Lex.getCode() != tgtok::r_brace) {
2095 TokError("expected '}' at end of foreach command");
2096 return Error(BraceLoc, "to match this '{'");
2098 Lex.Lex(); // Eat the }
2101 // We've processed everything in this loop.
2107 /// ParseClass - Parse a tblgen class definition.
2109 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2111 bool TGParser::ParseClass() {
2112 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2115 if (Lex.getCode() != tgtok::Id)
2116 return TokError("expected class name after 'class' keyword");
2118 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2120 // If the body was previously defined, this is an error.
2121 if (CurRec->getValues().size() > 1 || // Account for NAME.
2122 !CurRec->getSuperClasses().empty() ||
2123 !CurRec->getTemplateArgs().empty())
2124 return TokError("Class '" + CurRec->getNameInitAsString()
2125 + "' already defined");
2127 // If this is the first reference to this class, create and add it.
2128 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
2129 Records.addClass(CurRec);
2131 Lex.Lex(); // eat the name.
2133 // If there are template args, parse them.
2134 if (Lex.getCode() == tgtok::less)
2135 if (ParseTemplateArgList(CurRec))
2138 // Finally, parse the object body.
2139 return ParseObjectBody(CurRec);
2142 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2145 /// LetList ::= LetItem (',' LetItem)*
2146 /// LetItem ::= ID OptionalRangeList '=' Value
2148 std::vector<LetRecord> TGParser::ParseLetList() {
2149 std::vector<LetRecord> Result;
2152 if (Lex.getCode() != tgtok::Id) {
2153 TokError("expected identifier in let definition");
2154 return std::vector<LetRecord>();
2156 std::string Name = Lex.getCurStrVal();
2157 SMLoc NameLoc = Lex.getLoc();
2158 Lex.Lex(); // Eat the identifier.
2160 // Check for an optional RangeList.
2161 std::vector<unsigned> Bits;
2162 if (ParseOptionalRangeList(Bits))
2163 return std::vector<LetRecord>();
2164 std::reverse(Bits.begin(), Bits.end());
2166 if (Lex.getCode() != tgtok::equal) {
2167 TokError("expected '=' in let expression");
2168 return std::vector<LetRecord>();
2170 Lex.Lex(); // eat the '='.
2172 Init *Val = ParseValue(nullptr);
2173 if (!Val) return std::vector<LetRecord>();
2175 // Now that we have everything, add the record.
2176 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2178 if (Lex.getCode() != tgtok::comma)
2180 Lex.Lex(); // eat the comma.
2184 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2185 /// different related productions. This works inside multiclasses too.
2187 /// Object ::= LET LetList IN '{' ObjectList '}'
2188 /// Object ::= LET LetList IN Object
2190 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2191 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2194 // Add this entry to the let stack.
2195 std::vector<LetRecord> LetInfo = ParseLetList();
2196 if (LetInfo.empty()) return true;
2197 LetStack.push_back(LetInfo);
2199 if (Lex.getCode() != tgtok::In)
2200 return TokError("expected 'in' at end of top-level 'let'");
2203 // If this is a scalar let, just handle it now
2204 if (Lex.getCode() != tgtok::l_brace) {
2205 // LET LetList IN Object
2206 if (ParseObject(CurMultiClass))
2208 } else { // Object ::= LETCommand '{' ObjectList '}'
2209 SMLoc BraceLoc = Lex.getLoc();
2210 // Otherwise, this is a group let.
2211 Lex.Lex(); // eat the '{'.
2213 // Parse the object list.
2214 if (ParseObjectList(CurMultiClass))
2217 if (Lex.getCode() != tgtok::r_brace) {
2218 TokError("expected '}' at end of top level let command");
2219 return Error(BraceLoc, "to match this '{'");
2224 // Outside this let scope, this let block is not active.
2225 LetStack.pop_back();
2229 /// ParseMultiClass - Parse a multiclass definition.
2231 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2232 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2233 /// MultiClassObject ::= DefInst
2234 /// MultiClassObject ::= MultiClassInst
2235 /// MultiClassObject ::= DefMInst
2236 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
2237 /// MultiClassObject ::= LETCommand Object
2239 bool TGParser::ParseMultiClass() {
2240 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2241 Lex.Lex(); // Eat the multiclass token.
2243 if (Lex.getCode() != tgtok::Id)
2244 return TokError("expected identifier after multiclass for name");
2245 std::string Name = Lex.getCurStrVal();
2247 if (MultiClasses.count(Name))
2248 return TokError("multiclass '" + Name + "' already defined");
2250 CurMultiClass = MultiClasses[Name] = new MultiClass(Name,
2251 Lex.getLoc(), Records);
2252 Lex.Lex(); // Eat the identifier.
2254 // If there are template args, parse them.
2255 if (Lex.getCode() == tgtok::less)
2256 if (ParseTemplateArgList(nullptr))
2259 bool inherits = false;
2261 // If there are submulticlasses, parse them.
2262 if (Lex.getCode() == tgtok::colon) {
2267 // Read all of the submulticlasses.
2268 SubMultiClassReference SubMultiClass =
2269 ParseSubMultiClassReference(CurMultiClass);
2272 if (!SubMultiClass.MC) return true;
2275 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2278 if (Lex.getCode() != tgtok::comma) break;
2279 Lex.Lex(); // eat ','.
2280 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2284 if (Lex.getCode() != tgtok::l_brace) {
2286 return TokError("expected '{' in multiclass definition");
2287 else if (Lex.getCode() != tgtok::semi)
2288 return TokError("expected ';' in multiclass definition");
2290 Lex.Lex(); // eat the ';'.
2292 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2293 return TokError("multiclass must contain at least one def");
2295 while (Lex.getCode() != tgtok::r_brace) {
2296 switch (Lex.getCode()) {
2298 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2302 case tgtok::Foreach:
2303 if (ParseObject(CurMultiClass))
2308 Lex.Lex(); // eat the '}'.
2311 CurMultiClass = nullptr;
2316 InstantiateMulticlassDef(MultiClass &MC,
2319 SMRange DefmPrefixRange) {
2320 // We need to preserve DefProto so it can be reused for later
2321 // instantiations, so create a new Record to inherit from it.
2323 // Add in the defm name. If the defm prefix is empty, give each
2324 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2325 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2328 bool IsAnonymous = false;
2330 DefmPrefix = StringInit::get(GetNewAnonymousName());
2334 Init *DefName = DefProto->getNameInit();
2336 StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2338 if (DefNameString) {
2339 // We have a fully expanded string so there are no operators to
2340 // resolve. We should concatenate the given prefix and name.
2342 BinOpInit::get(BinOpInit::STRCONCAT,
2343 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2344 StringRecTy::get())->Fold(DefProto, &MC),
2345 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2348 // Make a trail of SMLocs from the multiclass instantiations.
2349 SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
2350 Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2351 Record *CurRec = new Record(DefName, Locs, Records, IsAnonymous);
2353 SubClassReference Ref;
2354 Ref.RefRange = DefmPrefixRange;
2356 AddSubClass(CurRec, Ref);
2358 // Set the value for NAME. We don't resolve references to it 'til later,
2359 // though, so that uses in nested multiclass names don't get
2361 if (SetValue(CurRec, Ref.RefRange.Start, "NAME", std::vector<unsigned>(),
2363 Error(DefmPrefixRange.Start, "Could not resolve "
2364 + CurRec->getNameInitAsString() + ":NAME to '"
2365 + DefmPrefix->getAsUnquotedString() + "'");
2369 // If the DefNameString didn't resolve, we probably have a reference to
2370 // NAME and need to replace it. We need to do at least this much greedily,
2371 // otherwise nested multiclasses will end up with incorrect NAME expansions.
2372 if (!DefNameString) {
2373 RecordVal *DefNameRV = CurRec->getValue("NAME");
2374 CurRec->resolveReferencesTo(DefNameRV);
2377 if (!CurMultiClass) {
2378 // Now that we're at the top level, resolve all NAME references
2379 // in the resultant defs that weren't in the def names themselves.
2380 RecordVal *DefNameRV = CurRec->getValue("NAME");
2381 CurRec->resolveReferencesTo(DefNameRV);
2383 // Now that NAME references are resolved and we're at the top level of
2384 // any multiclass expansions, add the record to the RecordKeeper. If we are
2385 // currently in a multiclass, it means this defm appears inside a
2386 // multiclass and its name won't be fully resolvable until we see
2387 // the top-level defm. Therefore, we don't add this to the
2388 // RecordKeeper at this point. If we did we could get duplicate
2389 // defs as more than one probably refers to NAME or some other
2390 // common internal placeholder.
2392 // Ensure redefinition doesn't happen.
2393 if (Records.getDef(CurRec->getNameInitAsString())) {
2394 Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
2395 "' already defined, instantiating defm with subdef '" +
2396 DefProto->getNameInitAsString() + "'");
2400 Records.addDef(CurRec);
2406 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2408 SMLoc DefmPrefixLoc,
2410 const std::vector<Init *> &TArgs,
2411 std::vector<Init *> &TemplateVals,
2413 // Loop over all of the template arguments, setting them to the specified
2414 // value or leaving them as the default if necessary.
2415 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2416 // Check if a value is specified for this temp-arg.
2417 if (i < TemplateVals.size()) {
2419 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2424 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2428 CurRec->removeValue(TArgs[i]);
2430 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2431 return Error(SubClassLoc, "value not specified for template argument #"+
2432 utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2433 + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2440 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2443 SMLoc DefmPrefixLoc) {
2444 // If the mdef is inside a 'let' expression, add to each def.
2445 if (ApplyLetStack(CurRec))
2446 return Error(DefmPrefixLoc, "when instantiating this defm");
2448 // Don't create a top level definition for defm inside multiclasses,
2449 // instead, only update the prototypes and bind the template args
2450 // with the new created definition.
2453 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2455 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2456 == CurRec->getNameInit())
2457 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2458 "' already defined in this multiclass!");
2459 CurMultiClass->DefPrototypes.push_back(CurRec);
2461 // Copy the template arguments for the multiclass into the new def.
2462 const std::vector<Init *> &TA =
2463 CurMultiClass->Rec.getTemplateArgs();
2465 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2466 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2467 assert(RV && "Template arg doesn't exist?");
2468 CurRec->addValue(*RV);
2474 /// ParseDefm - Parse the instantiation of a multiclass.
2476 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2478 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2479 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2480 SMLoc DefmLoc = Lex.getLoc();
2481 Init *DefmPrefix = nullptr;
2483 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2484 DefmPrefix = ParseObjectName(CurMultiClass);
2487 SMLoc DefmPrefixEndLoc = Lex.getLoc();
2488 if (Lex.getCode() != tgtok::colon)
2489 return TokError("expected ':' after defm identifier");
2491 // Keep track of the new generated record definitions.
2492 std::vector<Record*> NewRecDefs;
2494 // This record also inherits from a regular class (non-multiclass)?
2495 bool InheritFromClass = false;
2500 SMLoc SubClassLoc = Lex.getLoc();
2501 SubClassReference Ref = ParseSubClassReference(nullptr, true);
2504 if (!Ref.Rec) return true;
2506 // To instantiate a multiclass, we need to first get the multiclass, then
2507 // instantiate each def contained in the multiclass with the SubClassRef
2508 // template parameters.
2509 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2510 assert(MC && "Didn't lookup multiclass correctly?");
2511 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2513 // Verify that the correct number of template arguments were specified.
2514 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2515 if (TArgs.size() < TemplateVals.size())
2516 return Error(SubClassLoc,
2517 "more template args specified than multiclass expects");
2519 // Loop over all the def's in the multiclass, instantiating each one.
2520 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2521 Record *DefProto = MC->DefPrototypes[i];
2523 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix,
2529 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
2530 TArgs, TemplateVals, true/*Delete args*/))
2531 return Error(SubClassLoc, "could not instantiate def");
2533 if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmLoc))
2534 return Error(SubClassLoc, "could not instantiate def");
2536 NewRecDefs.push_back(CurRec);
2540 if (Lex.getCode() != tgtok::comma) break;
2541 Lex.Lex(); // eat ','.
2543 if (Lex.getCode() != tgtok::Id)
2544 return TokError("expected identifier");
2546 SubClassLoc = Lex.getLoc();
2548 // A defm can inherit from regular classes (non-multiclass) as
2549 // long as they come in the end of the inheritance list.
2550 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
2552 if (InheritFromClass)
2555 Ref = ParseSubClassReference(nullptr, true);
2558 if (InheritFromClass) {
2559 // Process all the classes to inherit as if they were part of a
2560 // regular 'def' and inherit all record values.
2561 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
2564 if (!SubClass.Rec) return true;
2566 // Get the expanded definition prototypes and teach them about
2567 // the record values the current class to inherit has
2568 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2569 Record *CurRec = NewRecDefs[i];
2572 if (AddSubClass(CurRec, SubClass))
2575 if (ApplyLetStack(CurRec))
2579 if (Lex.getCode() != tgtok::comma) break;
2580 Lex.Lex(); // eat ','.
2581 SubClass = ParseSubClassReference(nullptr, false);
2586 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2587 // See Record::setName(). This resolve step will see any new
2588 // name for the def that might have been created when resolving
2589 // inheritance, values and arguments above.
2590 NewRecDefs[i]->resolveReferences();
2592 if (Lex.getCode() != tgtok::semi)
2593 return TokError("expected ';' at end of defm");
2600 /// Object ::= ClassInst
2601 /// Object ::= DefInst
2602 /// Object ::= MultiClassInst
2603 /// Object ::= DefMInst
2604 /// Object ::= LETCommand '{' ObjectList '}'
2605 /// Object ::= LETCommand Object
2606 bool TGParser::ParseObject(MultiClass *MC) {
2607 switch (Lex.getCode()) {
2609 return TokError("Expected class, def, defm, multiclass or let definition");
2610 case tgtok::Let: return ParseTopLevelLet(MC);
2611 case tgtok::Def: return ParseDef(MC);
2612 case tgtok::Foreach: return ParseForeach(MC);
2613 case tgtok::Defm: return ParseDefm(MC);
2614 case tgtok::Class: return ParseClass();
2615 case tgtok::MultiClass: return ParseMultiClass();
2620 /// ObjectList :== Object*
2621 bool TGParser::ParseObjectList(MultiClass *MC) {
2622 while (isObjectStart(Lex.getCode())) {
2623 if (ParseObject(MC))
2629 bool TGParser::ParseFile() {
2630 Lex.Lex(); // Prime the lexer.
2631 if (ParseObjectList()) return true;
2633 // If we have unread input at the end of the file, report it.
2634 if (Lex.getCode() == tgtok::Eof)
2637 return TokError("Unexpected input at top level");