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);
138 if (RV->setValue(V)) {
139 std::string InitType = "";
140 if (BitsInit *BI = dyn_cast<BitsInit>(V)) {
141 InitType = (Twine("' of type bit initializer with length ") +
142 Twine(BI->getNumBits())).str();
144 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of type '"
145 + RV->getType()->getAsString() +
146 "' is incompatible with initializer '" + V->getAsString()
153 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
154 /// args as SubClass's template arguments.
155 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
156 Record *SC = SubClass.Rec;
157 // Add all of the values in the subclass into the current class.
158 const std::vector<RecordVal> &Vals = SC->getValues();
159 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
160 if (AddValue(CurRec, SubClass.RefRange.Start, Vals[i]))
163 const std::vector<Init *> &TArgs = SC->getTemplateArgs();
165 // Ensure that an appropriate number of template arguments are specified.
166 if (TArgs.size() < SubClass.TemplateArgs.size())
167 return Error(SubClass.RefRange.Start,
168 "More template args specified than expected");
170 // Loop over all of the template arguments, setting them to the specified
171 // value or leaving them as the default if necessary.
172 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
173 if (i < SubClass.TemplateArgs.size()) {
174 // If a value is specified for this template arg, set it now.
175 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
176 std::vector<unsigned>(), SubClass.TemplateArgs[i]))
180 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
183 CurRec->removeValue(TArgs[i]);
185 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
186 return Error(SubClass.RefRange.Start,
187 "Value not specified for template argument #"
188 + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
189 + ") of subclass '" + SC->getNameInitAsString() + "'!");
193 // Since everything went well, we can now set the "superclass" list for the
195 const std::vector<Record*> &SCs = SC->getSuperClasses();
196 ArrayRef<SMRange> SCRanges = SC->getSuperClassRanges();
197 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
198 if (CurRec->isSubClassOf(SCs[i]))
199 return Error(SubClass.RefRange.Start,
200 "Already subclass of '" + SCs[i]->getName() + "'!\n");
201 CurRec->addSuperClass(SCs[i], SCRanges[i]);
204 if (CurRec->isSubClassOf(SC))
205 return Error(SubClass.RefRange.Start,
206 "Already subclass of '" + SC->getName() + "'!\n");
207 CurRec->addSuperClass(SC, SubClass.RefRange);
211 /// AddSubMultiClass - Add SubMultiClass as a subclass to
212 /// CurMC, resolving its template args as SubMultiClass's
213 /// template arguments.
214 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
215 SubMultiClassReference &SubMultiClass) {
216 MultiClass *SMC = SubMultiClass.MC;
217 Record *CurRec = &CurMC->Rec;
219 const std::vector<RecordVal> &MCVals = CurRec->getValues();
221 // Add all of the values in the subclass into the current class.
222 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
223 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
224 if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVals[i]))
227 int newDefStart = CurMC->DefPrototypes.size();
229 // Add all of the defs in the subclass into the current multiclass.
230 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
231 iend = SMC->DefPrototypes.end();
234 // Clone the def and add it to the current multiclass
235 Record *NewDef = new Record(**i);
237 // Add all of the values in the superclass into the current def.
238 for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
239 if (AddValue(NewDef, SubMultiClass.RefRange.Start, MCVals[i]))
242 CurMC->DefPrototypes.push_back(NewDef);
245 const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
247 // Ensure that an appropriate number of template arguments are
249 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
250 return Error(SubMultiClass.RefRange.Start,
251 "More template args specified than expected");
253 // Loop over all of the template arguments, setting them to the specified
254 // value or leaving them as the default if necessary.
255 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
256 if (i < SubMultiClass.TemplateArgs.size()) {
257 // If a value is specified for this template arg, set it in the
259 if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i],
260 std::vector<unsigned>(),
261 SubMultiClass.TemplateArgs[i]))
265 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
268 CurRec->removeValue(SMCTArgs[i]);
270 // If a value is specified for this template arg, set it in the
272 for (MultiClass::RecordVector::iterator j =
273 CurMC->DefPrototypes.begin() + newDefStart,
274 jend = CurMC->DefPrototypes.end();
279 if (SetValue(Def, SubMultiClass.RefRange.Start, SMCTArgs[i],
280 std::vector<unsigned>(),
281 SubMultiClass.TemplateArgs[i]))
285 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
288 Def->removeValue(SMCTArgs[i]);
290 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
291 return Error(SubMultiClass.RefRange.Start,
292 "Value not specified for template argument #"
293 + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
294 + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
301 /// ProcessForeachDefs - Given a record, apply all of the variable
302 /// values in all surrounding foreach loops, creating new records for
303 /// each combination of values.
304 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
308 // We want to instantiate a new copy of CurRec for each combination
309 // of nested loop iterator values. We don't want top instantiate
310 // any copies until we have values for each loop iterator.
312 return ProcessForeachDefs(CurRec, Loc, IterVals);
315 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
316 /// apply each of the variable values in this loop and then process
318 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
319 // Recursively build a tuple of iterator values.
320 if (IterVals.size() != Loops.size()) {
321 assert(IterVals.size() < Loops.size());
322 ForeachLoop &CurLoop = Loops[IterVals.size()];
323 ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
325 Error(Loc, "Loop list is not a list");
329 // Process each value.
330 for (int64_t i = 0; i < List->getSize(); ++i) {
331 Init *ItemVal = List->resolveListElementReference(*CurRec, nullptr, i);
332 IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
333 if (ProcessForeachDefs(CurRec, Loc, IterVals))
340 // This is the bottom of the recursion. We have all of the iterator values
341 // for this point in the iteration space. Instantiate a new record to
342 // reflect this combination of values.
343 Record *IterRec = new Record(*CurRec);
345 // Set the iterator values now.
346 for (unsigned i = 0, e = IterVals.size(); i != e; ++i) {
347 VarInit *IterVar = IterVals[i].IterVar;
348 TypedInit *IVal = dyn_cast<TypedInit>(IterVals[i].IterValue);
350 Error(Loc, "foreach iterator value is untyped");
354 IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
356 if (SetValue(IterRec, Loc, IterVar->getName(),
357 std::vector<unsigned>(), IVal)) {
358 Error(Loc, "when instantiating this def");
363 IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
366 IterRec->removeValue(IterVar->getName());
369 if (Records.getDef(IterRec->getNameInitAsString())) {
370 // If this record is anonymous, it's no problem, just generate a new name
371 if (IterRec->isAnonymous())
372 IterRec->setName(GetNewAnonymousName());
374 Error(Loc, "def already exists: " + IterRec->getNameInitAsString());
379 Records.addDef(IterRec);
380 IterRec->resolveReferences();
384 //===----------------------------------------------------------------------===//
386 //===----------------------------------------------------------------------===//
388 /// isObjectStart - Return true if this is a valid first token for an Object.
389 static bool isObjectStart(tgtok::TokKind K) {
390 return K == tgtok::Class || K == tgtok::Def ||
391 K == tgtok::Defm || K == tgtok::Let ||
392 K == tgtok::MultiClass || K == tgtok::Foreach;
395 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
397 std::string TGParser::GetNewAnonymousName() {
398 unsigned Tmp = AnonCounter++; // MSVC2012 ICEs without this.
399 return "anonymous_" + utostr(Tmp);
402 /// ParseObjectName - If an object name is specified, return it. Otherwise,
404 /// ObjectName ::= Value [ '#' Value ]*
405 /// ObjectName ::= /*empty*/
407 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
408 switch (Lex.getCode()) {
412 // These are all of the tokens that can begin an object body.
413 // Some of these can also begin values but we disallow those cases
414 // because they are unlikely to be useful.
420 Record *CurRec = nullptr;
422 CurRec = &CurMultiClass->Rec;
424 RecTy *Type = nullptr;
426 const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
428 TokError("Record name is not typed!");
431 Type = CurRecName->getType();
434 return ParseValue(CurRec, Type, ParseNameMode);
437 /// ParseClassID - Parse and resolve a reference to a class name. This returns
442 Record *TGParser::ParseClassID() {
443 if (Lex.getCode() != tgtok::Id) {
444 TokError("expected name for ClassID");
448 Record *Result = Records.getClass(Lex.getCurStrVal());
450 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
456 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
457 /// This returns null on error.
459 /// MultiClassID ::= ID
461 MultiClass *TGParser::ParseMultiClassID() {
462 if (Lex.getCode() != tgtok::Id) {
463 TokError("expected name for MultiClassID");
467 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
469 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
475 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
476 /// subclass. This returns a SubClassRefTy with a null Record* on error.
478 /// SubClassRef ::= ClassID
479 /// SubClassRef ::= ClassID '<' ValueList '>'
481 SubClassReference TGParser::
482 ParseSubClassReference(Record *CurRec, bool isDefm) {
483 SubClassReference Result;
484 Result.RefRange.Start = Lex.getLoc();
487 if (MultiClass *MC = ParseMultiClassID())
488 Result.Rec = &MC->Rec;
490 Result.Rec = ParseClassID();
492 if (!Result.Rec) return Result;
494 // If there is no template arg list, we're done.
495 if (Lex.getCode() != tgtok::less) {
496 Result.RefRange.End = Lex.getLoc();
499 Lex.Lex(); // Eat the '<'
501 if (Lex.getCode() == tgtok::greater) {
502 TokError("subclass reference requires a non-empty list of template values");
503 Result.Rec = nullptr;
507 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
508 if (Result.TemplateArgs.empty()) {
509 Result.Rec = nullptr; // Error parsing value list.
513 if (Lex.getCode() != tgtok::greater) {
514 TokError("expected '>' in template value list");
515 Result.Rec = nullptr;
519 Result.RefRange.End = Lex.getLoc();
524 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
525 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
526 /// Record* on error.
528 /// SubMultiClassRef ::= MultiClassID
529 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
531 SubMultiClassReference TGParser::
532 ParseSubMultiClassReference(MultiClass *CurMC) {
533 SubMultiClassReference Result;
534 Result.RefRange.Start = Lex.getLoc();
536 Result.MC = ParseMultiClassID();
537 if (!Result.MC) return Result;
539 // If there is no template arg list, we're done.
540 if (Lex.getCode() != tgtok::less) {
541 Result.RefRange.End = Lex.getLoc();
544 Lex.Lex(); // Eat the '<'
546 if (Lex.getCode() == tgtok::greater) {
547 TokError("subclass reference requires a non-empty list of template values");
552 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
553 if (Result.TemplateArgs.empty()) {
554 Result.MC = nullptr; // Error parsing value list.
558 if (Lex.getCode() != tgtok::greater) {
559 TokError("expected '>' in template value list");
564 Result.RefRange.End = Lex.getLoc();
569 /// ParseRangePiece - Parse a bit/value range.
570 /// RangePiece ::= INTVAL
571 /// RangePiece ::= INTVAL '-' INTVAL
572 /// RangePiece ::= INTVAL INTVAL
573 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
574 if (Lex.getCode() != tgtok::IntVal) {
575 TokError("expected integer or bitrange");
578 int64_t Start = Lex.getCurIntVal();
582 return TokError("invalid range, cannot be negative");
584 switch (Lex.Lex()) { // eat first character.
586 Ranges.push_back(Start);
589 if (Lex.Lex() != tgtok::IntVal) {
590 TokError("expected integer value as end of range");
593 End = Lex.getCurIntVal();
596 End = -Lex.getCurIntVal();
600 return TokError("invalid range, cannot be negative");
605 for (; Start <= End; ++Start)
606 Ranges.push_back(Start);
608 for (; Start >= End; --Start)
609 Ranges.push_back(Start);
614 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
616 /// RangeList ::= RangePiece (',' RangePiece)*
618 std::vector<unsigned> TGParser::ParseRangeList() {
619 std::vector<unsigned> Result;
621 // Parse the first piece.
622 if (ParseRangePiece(Result))
623 return std::vector<unsigned>();
624 while (Lex.getCode() == tgtok::comma) {
625 Lex.Lex(); // Eat the comma.
627 // Parse the next range piece.
628 if (ParseRangePiece(Result))
629 return std::vector<unsigned>();
634 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
635 /// OptionalRangeList ::= '<' RangeList '>'
636 /// OptionalRangeList ::= /*empty*/
637 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
638 if (Lex.getCode() != tgtok::less)
641 SMLoc StartLoc = Lex.getLoc();
642 Lex.Lex(); // eat the '<'
644 // Parse the range list.
645 Ranges = ParseRangeList();
646 if (Ranges.empty()) return true;
648 if (Lex.getCode() != tgtok::greater) {
649 TokError("expected '>' at end of range list");
650 return Error(StartLoc, "to match this '<'");
652 Lex.Lex(); // eat the '>'.
656 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
657 /// OptionalBitList ::= '{' RangeList '}'
658 /// OptionalBitList ::= /*empty*/
659 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
660 if (Lex.getCode() != tgtok::l_brace)
663 SMLoc StartLoc = Lex.getLoc();
664 Lex.Lex(); // eat the '{'
666 // Parse the range list.
667 Ranges = ParseRangeList();
668 if (Ranges.empty()) return true;
670 if (Lex.getCode() != tgtok::r_brace) {
671 TokError("expected '}' at end of bit list");
672 return Error(StartLoc, "to match this '{'");
674 Lex.Lex(); // eat the '}'.
679 /// ParseType - Parse and return a tblgen type. This returns null on error.
681 /// Type ::= STRING // string type
682 /// Type ::= CODE // code type
683 /// Type ::= BIT // bit type
684 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
685 /// Type ::= INT // int type
686 /// Type ::= LIST '<' Type '>' // list<x> type
687 /// Type ::= DAG // dag type
688 /// Type ::= ClassID // Record Type
690 RecTy *TGParser::ParseType() {
691 switch (Lex.getCode()) {
692 default: TokError("Unknown token when expecting a type"); return nullptr;
693 case tgtok::String: Lex.Lex(); return StringRecTy::get();
694 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
695 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
696 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
697 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
699 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
702 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
703 TokError("expected '<' after bits type");
706 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
707 TokError("expected integer in bits<n> type");
710 uint64_t Val = Lex.getCurIntVal();
711 if (Lex.Lex() != tgtok::greater) { // Eat count.
712 TokError("expected '>' at end of bits<n> type");
715 Lex.Lex(); // Eat '>'
716 return BitsRecTy::get(Val);
719 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
720 TokError("expected '<' after list type");
723 Lex.Lex(); // Eat '<'
724 RecTy *SubType = ParseType();
725 if (!SubType) return nullptr;
727 if (Lex.getCode() != tgtok::greater) {
728 TokError("expected '>' at end of list<ty> type");
731 Lex.Lex(); // Eat '>'
732 return ListRecTy::get(SubType);
737 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
738 /// has already been read.
739 Init *TGParser::ParseIDValue(Record *CurRec,
740 const std::string &Name, SMLoc NameLoc,
743 if (const RecordVal *RV = CurRec->getValue(Name))
744 return VarInit::get(Name, RV->getType());
746 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
749 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
752 if (CurRec->isTemplateArg(TemplateArgName)) {
753 const RecordVal *RV = CurRec->getValue(TemplateArgName);
754 assert(RV && "Template arg doesn't exist??");
755 return VarInit::get(TemplateArgName, RV->getType());
760 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
763 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
764 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
765 assert(RV && "Template arg doesn't exist??");
766 return VarInit::get(MCName, RV->getType());
770 // If this is in a foreach loop, make sure it's not a loop iterator
771 for (LoopVector::iterator i = Loops.begin(), iend = Loops.end();
774 VarInit *IterVar = dyn_cast<VarInit>(i->IterVar);
775 if (IterVar && IterVar->getName() == Name)
779 if (Mode == ParseNameMode)
780 return StringInit::get(Name);
782 if (Record *D = Records.getDef(Name))
783 return DefInit::get(D);
785 if (Mode == ParseValueMode) {
786 Error(NameLoc, "Variable not defined: '" + Name + "'");
790 return StringInit::get(Name);
793 /// ParseOperation - Parse an operator. This returns null on error.
795 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
797 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
798 switch (Lex.getCode()) {
800 TokError("unknown operation");
805 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
806 UnOpInit::UnaryOp Code;
807 RecTy *Type = nullptr;
809 switch (Lex.getCode()) {
810 default: llvm_unreachable("Unhandled code!");
812 Lex.Lex(); // eat the operation
813 Code = UnOpInit::CAST;
815 Type = ParseOperatorType();
818 TokError("did not get type for unary operator");
824 Lex.Lex(); // eat the operation
825 Code = UnOpInit::HEAD;
828 Lex.Lex(); // eat the operation
829 Code = UnOpInit::TAIL;
832 Lex.Lex(); // eat the operation
833 Code = UnOpInit::EMPTY;
834 Type = IntRecTy::get();
837 if (Lex.getCode() != tgtok::l_paren) {
838 TokError("expected '(' after unary operator");
841 Lex.Lex(); // eat the '('
843 Init *LHS = ParseValue(CurRec);
844 if (!LHS) return nullptr;
846 if (Code == UnOpInit::HEAD
847 || Code == UnOpInit::TAIL
848 || Code == UnOpInit::EMPTY) {
849 ListInit *LHSl = dyn_cast<ListInit>(LHS);
850 StringInit *LHSs = dyn_cast<StringInit>(LHS);
851 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
852 if (!LHSl && !LHSs && !LHSt) {
853 TokError("expected list or string type argument in unary operator");
857 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
858 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
859 if (!LType && !SType) {
860 TokError("expected list or string type argument in unary operator");
865 if (Code == UnOpInit::HEAD
866 || Code == UnOpInit::TAIL) {
867 if (!LHSl && !LHSt) {
868 TokError("expected list type argument in unary operator");
872 if (LHSl && LHSl->getSize() == 0) {
873 TokError("empty list argument in unary operator");
877 Init *Item = LHSl->getElement(0);
878 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
880 TokError("untyped list element in unary operator");
883 if (Code == UnOpInit::HEAD) {
884 Type = Itemt->getType();
886 Type = ListRecTy::get(Itemt->getType());
889 assert(LHSt && "expected list type argument in unary operator");
890 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
892 TokError("expected list type argument in unary operator");
895 if (Code == UnOpInit::HEAD) {
896 Type = LType->getElementType();
904 if (Lex.getCode() != tgtok::r_paren) {
905 TokError("expected ')' in unary operator");
908 Lex.Lex(); // eat the ')'
909 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
919 case tgtok::XListConcat:
920 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
921 tgtok::TokKind OpTok = Lex.getCode();
922 SMLoc OpLoc = Lex.getLoc();
923 Lex.Lex(); // eat the operation
925 BinOpInit::BinaryOp Code;
926 RecTy *Type = nullptr;
929 default: llvm_unreachable("Unhandled code!");
930 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
931 case tgtok::XADD: Code = BinOpInit::ADD; Type = IntRecTy::get(); break;
932 case tgtok::XAND: Code = BinOpInit::AND; Type = IntRecTy::get(); break;
933 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
934 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
935 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
936 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
937 case tgtok::XListConcat:
938 Code = BinOpInit::LISTCONCAT;
939 // We don't know the list type until we parse the first argument
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()) return nullptr;
958 while (Lex.getCode() == tgtok::comma) {
959 Lex.Lex(); // eat the ','
961 InitList.push_back(ParseValue(CurRec));
962 if (!InitList.back()) return nullptr;
965 if (Lex.getCode() != tgtok::r_paren) {
966 TokError("expected ')' in operator");
969 Lex.Lex(); // eat the ')'
971 // If we are doing !listconcat, we should know the type by now
972 if (OpTok == tgtok::XListConcat) {
973 if (VarInit *Arg0 = dyn_cast<VarInit>(InitList[0]))
974 Type = Arg0->getType();
975 else if (ListInit *Arg0 = dyn_cast<ListInit>(InitList[0]))
976 Type = Arg0->getType();
979 Error(OpLoc, "expected a list");
984 // We allow multiple operands to associative operators like !strconcat as
985 // shorthand for nesting them.
986 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT) {
987 while (InitList.size() > 2) {
988 Init *RHS = InitList.pop_back_val();
989 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
990 ->Fold(CurRec, CurMultiClass);
991 InitList.back() = RHS;
995 if (InitList.size() == 2)
996 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
997 ->Fold(CurRec, CurMultiClass);
999 Error(OpLoc, "expected two operands to operator");
1004 case tgtok::XForEach:
1005 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1006 TernOpInit::TernaryOp Code;
1007 RecTy *Type = nullptr;
1009 tgtok::TokKind LexCode = Lex.getCode();
1010 Lex.Lex(); // eat the operation
1012 default: llvm_unreachable("Unhandled code!");
1014 Code = TernOpInit::IF;
1016 case tgtok::XForEach:
1017 Code = TernOpInit::FOREACH;
1020 Code = TernOpInit::SUBST;
1023 if (Lex.getCode() != tgtok::l_paren) {
1024 TokError("expected '(' after ternary operator");
1027 Lex.Lex(); // eat the '('
1029 Init *LHS = ParseValue(CurRec);
1030 if (!LHS) return nullptr;
1032 if (Lex.getCode() != tgtok::comma) {
1033 TokError("expected ',' in ternary operator");
1036 Lex.Lex(); // eat the ','
1038 Init *MHS = ParseValue(CurRec, ItemType);
1042 if (Lex.getCode() != tgtok::comma) {
1043 TokError("expected ',' in ternary operator");
1046 Lex.Lex(); // eat the ','
1048 Init *RHS = ParseValue(CurRec, ItemType);
1052 if (Lex.getCode() != tgtok::r_paren) {
1053 TokError("expected ')' in binary operator");
1056 Lex.Lex(); // eat the ')'
1059 default: llvm_unreachable("Unhandled code!");
1061 RecTy *MHSTy = nullptr;
1062 RecTy *RHSTy = nullptr;
1064 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1065 MHSTy = MHSt->getType();
1066 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1067 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1068 if (isa<BitInit>(MHS))
1069 MHSTy = BitRecTy::get();
1071 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1072 RHSTy = RHSt->getType();
1073 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1074 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1075 if (isa<BitInit>(RHS))
1076 RHSTy = BitRecTy::get();
1078 // For UnsetInit, it's typed from the other hand.
1079 if (isa<UnsetInit>(MHS))
1081 if (isa<UnsetInit>(RHS))
1084 if (!MHSTy || !RHSTy) {
1085 TokError("could not get type for !if");
1089 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1091 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1094 TokError("inconsistent types for !if");
1099 case tgtok::XForEach: {
1100 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1102 TokError("could not get type for !foreach");
1105 Type = MHSt->getType();
1108 case tgtok::XSubst: {
1109 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1111 TokError("could not get type for !subst");
1114 Type = RHSt->getType();
1118 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1124 /// ParseOperatorType - Parse a type for an operator. This returns
1127 /// OperatorType ::= '<' Type '>'
1129 RecTy *TGParser::ParseOperatorType() {
1130 RecTy *Type = nullptr;
1132 if (Lex.getCode() != tgtok::less) {
1133 TokError("expected type name for operator");
1136 Lex.Lex(); // eat the <
1141 TokError("expected type name for operator");
1145 if (Lex.getCode() != tgtok::greater) {
1146 TokError("expected type name for operator");
1149 Lex.Lex(); // eat the >
1155 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1157 /// SimpleValue ::= IDValue
1158 /// SimpleValue ::= INTVAL
1159 /// SimpleValue ::= STRVAL+
1160 /// SimpleValue ::= CODEFRAGMENT
1161 /// SimpleValue ::= '?'
1162 /// SimpleValue ::= '{' ValueList '}'
1163 /// SimpleValue ::= ID '<' ValueListNE '>'
1164 /// SimpleValue ::= '[' ValueList ']'
1165 /// SimpleValue ::= '(' IDValue DagArgList ')'
1166 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1167 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1168 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1169 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1170 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1171 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1172 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1174 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1177 switch (Lex.getCode()) {
1178 default: TokError("Unknown token when parsing a value"); break;
1180 // This is a leading paste operation. This is deprecated but
1181 // still exists in some .td files. Ignore it.
1182 Lex.Lex(); // Skip '#'.
1183 return ParseSimpleValue(CurRec, ItemType, Mode);
1184 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1185 case tgtok::BinaryIntVal: {
1186 auto BinaryVal = Lex.getCurBinaryIntVal();
1187 SmallVector<Init*, 16> Bits(BinaryVal.second);
1188 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
1189 Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
1190 R = BitsInit::get(Bits);
1194 case tgtok::StrVal: {
1195 std::string Val = Lex.getCurStrVal();
1198 // Handle multiple consecutive concatenated strings.
1199 while (Lex.getCode() == tgtok::StrVal) {
1200 Val += Lex.getCurStrVal();
1204 R = StringInit::get(Val);
1207 case tgtok::CodeFragment:
1208 R = StringInit::get(Lex.getCurStrVal());
1211 case tgtok::question:
1212 R = UnsetInit::get();
1216 SMLoc NameLoc = Lex.getLoc();
1217 std::string Name = Lex.getCurStrVal();
1218 if (Lex.Lex() != tgtok::less) // consume the Id.
1219 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1221 // Value ::= ID '<' ValueListNE '>'
1222 if (Lex.Lex() == tgtok::greater) {
1223 TokError("expected non-empty value list");
1227 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1228 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1230 Record *Class = Records.getClass(Name);
1232 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1236 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1237 if (ValueList.empty()) return nullptr;
1239 if (Lex.getCode() != tgtok::greater) {
1240 TokError("expected '>' at end of value list");
1243 Lex.Lex(); // eat the '>'
1244 SMLoc EndLoc = Lex.getLoc();
1246 // Create the new record, set it as CurRec temporarily.
1247 Record *NewRec = new Record(GetNewAnonymousName(), NameLoc, Records,
1248 /*IsAnonymous=*/true);
1249 SubClassReference SCRef;
1250 SCRef.RefRange = SMRange(NameLoc, EndLoc);
1252 SCRef.TemplateArgs = ValueList;
1253 // Add info about the subclass to NewRec.
1254 if (AddSubClass(NewRec, SCRef))
1256 if (!CurMultiClass) {
1257 NewRec->resolveReferences();
1258 Records.addDef(NewRec);
1260 // Otherwise, we're inside a multiclass, add it to the multiclass.
1261 CurMultiClass->DefPrototypes.push_back(NewRec);
1263 // Copy the template arguments for the multiclass into the def.
1264 const std::vector<Init *> &TArgs =
1265 CurMultiClass->Rec.getTemplateArgs();
1267 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1268 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1269 assert(RV && "Template arg doesn't exist?");
1270 NewRec->addValue(*RV);
1273 // We can't return the prototype def here, instead return:
1274 // !cast<ItemType>(!strconcat(NAME, AnonName)).
1275 const RecordVal *MCNameRV = CurMultiClass->Rec.getValue("NAME");
1276 assert(MCNameRV && "multiclass record must have a NAME");
1278 return UnOpInit::get(UnOpInit::CAST,
1279 BinOpInit::get(BinOpInit::STRCONCAT,
1280 VarInit::get(MCNameRV->getName(),
1281 MCNameRV->getType()),
1282 NewRec->getNameInit(),
1283 StringRecTy::get()),
1284 Class->getDefInit()->getType());
1287 // The result of the expression is a reference to the new record.
1288 return DefInit::get(NewRec);
1290 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1291 SMLoc BraceLoc = Lex.getLoc();
1292 Lex.Lex(); // eat the '{'
1293 std::vector<Init*> Vals;
1295 if (Lex.getCode() != tgtok::r_brace) {
1296 Vals = ParseValueList(CurRec);
1297 if (Vals.empty()) return nullptr;
1299 if (Lex.getCode() != tgtok::r_brace) {
1300 TokError("expected '}' at end of bit list value");
1303 Lex.Lex(); // eat the '}'
1305 SmallVector<Init *, 16> NewBits;
1307 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1308 // first. We'll first read everything in to a vector, then we can reverse
1309 // it to get the bits in the correct order for the BitsInit value.
1310 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1311 // bits<n> values are allowed to initialize n bits.
1312 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
1313 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
1314 NewBits.push_back(BI->getBit((e - i) - 1));
1317 // All other values must be convertible to just a single bit.
1318 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1320 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1321 ") is not convertable to a bit");
1324 NewBits.push_back(Bit);
1326 std::reverse(NewBits.begin(), NewBits.end());
1327 return BitsInit::get(NewBits);
1329 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1330 Lex.Lex(); // eat the '['
1331 std::vector<Init*> Vals;
1333 RecTy *DeducedEltTy = nullptr;
1334 ListRecTy *GivenListTy = nullptr;
1337 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1340 raw_string_ostream ss(s);
1341 ss << "Type mismatch for list, expected list type, got "
1342 << ItemType->getAsString();
1346 GivenListTy = ListType;
1349 if (Lex.getCode() != tgtok::r_square) {
1350 Vals = ParseValueList(CurRec, nullptr,
1351 GivenListTy ? GivenListTy->getElementType() : nullptr);
1352 if (Vals.empty()) return nullptr;
1354 if (Lex.getCode() != tgtok::r_square) {
1355 TokError("expected ']' at end of list value");
1358 Lex.Lex(); // eat the ']'
1360 RecTy *GivenEltTy = nullptr;
1361 if (Lex.getCode() == tgtok::less) {
1362 // Optional list element type
1363 Lex.Lex(); // eat the '<'
1365 GivenEltTy = ParseType();
1367 // Couldn't parse element type
1371 if (Lex.getCode() != tgtok::greater) {
1372 TokError("expected '>' at end of list element type");
1375 Lex.Lex(); // eat the '>'
1379 RecTy *EltTy = nullptr;
1380 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1383 TypedInit *TArg = dyn_cast<TypedInit>(*i);
1385 TokError("Untyped list element");
1389 EltTy = resolveTypes(EltTy, TArg->getType());
1391 TokError("Incompatible types in list elements");
1395 EltTy = TArg->getType();
1401 // Verify consistency
1402 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1403 TokError("Incompatible types in list elements");
1412 TokError("No type for list");
1415 DeducedEltTy = GivenListTy->getElementType();
1417 // Make sure the deduced type is compatible with the given type
1419 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1420 TokError("Element type mismatch for list");
1424 DeducedEltTy = EltTy;
1427 return ListInit::get(Vals, DeducedEltTy);
1429 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1430 Lex.Lex(); // eat the '('
1431 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1432 TokError("expected identifier in dag init");
1436 Init *Operator = ParseValue(CurRec);
1437 if (!Operator) return nullptr;
1439 // If the operator name is present, parse it.
1440 std::string OperatorName;
1441 if (Lex.getCode() == tgtok::colon) {
1442 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1443 TokError("expected variable name in dag operator");
1446 OperatorName = Lex.getCurStrVal();
1447 Lex.Lex(); // eat the VarName.
1450 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1451 if (Lex.getCode() != tgtok::r_paren) {
1452 DagArgs = ParseDagArgList(CurRec);
1453 if (DagArgs.empty()) return nullptr;
1456 if (Lex.getCode() != tgtok::r_paren) {
1457 TokError("expected ')' in dag init");
1460 Lex.Lex(); // eat the ')'
1462 return DagInit::get(Operator, OperatorName, DagArgs);
1468 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1469 case tgtok::XConcat:
1476 case tgtok::XListConcat:
1477 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1479 case tgtok::XForEach:
1480 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1481 return ParseOperation(CurRec, ItemType);
1488 /// ParseValue - Parse a tblgen value. This returns null on error.
1490 /// Value ::= SimpleValue ValueSuffix*
1491 /// ValueSuffix ::= '{' BitList '}'
1492 /// ValueSuffix ::= '[' BitList ']'
1493 /// ValueSuffix ::= '.' ID
1495 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1496 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1497 if (!Result) return nullptr;
1499 // Parse the suffixes now if present.
1501 switch (Lex.getCode()) {
1502 default: return Result;
1503 case tgtok::l_brace: {
1504 if (Mode == ParseNameMode || Mode == ParseForeachMode)
1505 // This is the beginning of the object body.
1508 SMLoc CurlyLoc = Lex.getLoc();
1509 Lex.Lex(); // eat the '{'
1510 std::vector<unsigned> Ranges = ParseRangeList();
1511 if (Ranges.empty()) return nullptr;
1513 // Reverse the bitlist.
1514 std::reverse(Ranges.begin(), Ranges.end());
1515 Result = Result->convertInitializerBitRange(Ranges);
1517 Error(CurlyLoc, "Invalid bit range for value");
1522 if (Lex.getCode() != tgtok::r_brace) {
1523 TokError("expected '}' at end of bit range list");
1529 case tgtok::l_square: {
1530 SMLoc SquareLoc = Lex.getLoc();
1531 Lex.Lex(); // eat the '['
1532 std::vector<unsigned> Ranges = ParseRangeList();
1533 if (Ranges.empty()) return nullptr;
1535 Result = Result->convertInitListSlice(Ranges);
1537 Error(SquareLoc, "Invalid range for list slice");
1542 if (Lex.getCode() != tgtok::r_square) {
1543 TokError("expected ']' at end of list slice");
1550 if (Lex.Lex() != tgtok::Id) { // eat the .
1551 TokError("expected field identifier after '.'");
1554 if (!Result->getFieldType(Lex.getCurStrVal())) {
1555 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1556 Result->getAsString() + "'");
1559 Result = FieldInit::get(Result, Lex.getCurStrVal());
1560 Lex.Lex(); // eat field name
1564 SMLoc PasteLoc = Lex.getLoc();
1566 // Create a !strconcat() operation, first casting each operand to
1567 // a string if necessary.
1569 TypedInit *LHS = dyn_cast<TypedInit>(Result);
1571 Error(PasteLoc, "LHS of paste is not typed!");
1575 if (LHS->getType() != StringRecTy::get()) {
1576 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1579 TypedInit *RHS = nullptr;
1581 Lex.Lex(); // Eat the '#'.
1582 switch (Lex.getCode()) {
1585 case tgtok::l_brace:
1586 // These are all of the tokens that can begin an object body.
1587 // Some of these can also begin values but we disallow those cases
1588 // because they are unlikely to be useful.
1590 // Trailing paste, concat with an empty string.
1591 RHS = StringInit::get("");
1595 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1596 RHS = dyn_cast<TypedInit>(RHSResult);
1598 Error(PasteLoc, "RHS of paste is not typed!");
1602 if (RHS->getType() != StringRecTy::get()) {
1603 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1609 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1610 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1616 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1618 /// DagArg ::= Value (':' VARNAME)?
1619 /// DagArg ::= VARNAME
1620 /// DagArgList ::= DagArg
1621 /// DagArgList ::= DagArgList ',' DagArg
1622 std::vector<std::pair<llvm::Init*, std::string> >
1623 TGParser::ParseDagArgList(Record *CurRec) {
1624 std::vector<std::pair<llvm::Init*, std::string> > Result;
1627 // DagArg ::= VARNAME
1628 if (Lex.getCode() == tgtok::VarName) {
1629 // A missing value is treated like '?'.
1630 Result.push_back(std::make_pair(UnsetInit::get(), Lex.getCurStrVal()));
1633 // DagArg ::= Value (':' VARNAME)?
1634 Init *Val = ParseValue(CurRec);
1636 return std::vector<std::pair<llvm::Init*, std::string> >();
1638 // If the variable name is present, add it.
1639 std::string VarName;
1640 if (Lex.getCode() == tgtok::colon) {
1641 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1642 TokError("expected variable name in dag literal");
1643 return std::vector<std::pair<llvm::Init*, std::string> >();
1645 VarName = Lex.getCurStrVal();
1646 Lex.Lex(); // eat the VarName.
1649 Result.push_back(std::make_pair(Val, VarName));
1651 if (Lex.getCode() != tgtok::comma) break;
1652 Lex.Lex(); // eat the ','
1659 /// ParseValueList - Parse a comma separated list of values, returning them as a
1660 /// vector. Note that this always expects to be able to parse at least one
1661 /// value. It returns an empty list if this is not possible.
1663 /// ValueList ::= Value (',' Value)
1665 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1667 std::vector<Init*> Result;
1668 RecTy *ItemType = EltTy;
1669 unsigned int ArgN = 0;
1670 if (ArgsRec && !EltTy) {
1671 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1672 if (!TArgs.size()) {
1673 TokError("template argument provided to non-template class");
1674 return std::vector<Init*>();
1676 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1678 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1681 assert(RV && "Template argument record not found??");
1682 ItemType = RV->getType();
1685 Result.push_back(ParseValue(CurRec, ItemType));
1686 if (!Result.back()) return std::vector<Init*>();
1688 while (Lex.getCode() == tgtok::comma) {
1689 Lex.Lex(); // Eat the comma
1691 if (ArgsRec && !EltTy) {
1692 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1693 if (ArgN >= TArgs.size()) {
1694 TokError("too many template arguments");
1695 return std::vector<Init*>();
1697 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1698 assert(RV && "Template argument record not found??");
1699 ItemType = RV->getType();
1702 Result.push_back(ParseValue(CurRec, ItemType));
1703 if (!Result.back()) return std::vector<Init*>();
1710 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1711 /// empty string on error. This can happen in a number of different context's,
1712 /// including within a def or in the template args for a def (which which case
1713 /// CurRec will be non-null) and within the template args for a multiclass (in
1714 /// which case CurRec will be null, but CurMultiClass will be set). This can
1715 /// also happen within a def that is within a multiclass, which will set both
1716 /// CurRec and CurMultiClass.
1718 /// Declaration ::= FIELD? Type ID ('=' Value)?
1720 Init *TGParser::ParseDeclaration(Record *CurRec,
1721 bool ParsingTemplateArgs) {
1722 // Read the field prefix if present.
1723 bool HasField = Lex.getCode() == tgtok::Field;
1724 if (HasField) Lex.Lex();
1726 RecTy *Type = ParseType();
1727 if (!Type) return nullptr;
1729 if (Lex.getCode() != tgtok::Id) {
1730 TokError("Expected identifier in declaration");
1734 SMLoc IdLoc = Lex.getLoc();
1735 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1738 if (ParsingTemplateArgs) {
1740 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1742 assert(CurMultiClass);
1745 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1750 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1753 // If a value is present, parse it.
1754 if (Lex.getCode() == tgtok::equal) {
1756 SMLoc ValLoc = Lex.getLoc();
1757 Init *Val = ParseValue(CurRec, Type);
1759 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1760 // Return the name, even if an error is thrown. This is so that we can
1761 // continue to make some progress, even without the value having been
1769 /// ParseForeachDeclaration - Read a foreach declaration, returning
1770 /// the name of the declared object or a NULL Init on error. Return
1771 /// the name of the parsed initializer list through ForeachListName.
1773 /// ForeachDeclaration ::= ID '=' '[' ValueList ']'
1774 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
1775 /// ForeachDeclaration ::= ID '=' RangePiece
1777 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1778 if (Lex.getCode() != tgtok::Id) {
1779 TokError("Expected identifier in foreach declaration");
1783 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1786 // If a value is present, parse it.
1787 if (Lex.getCode() != tgtok::equal) {
1788 TokError("Expected '=' in foreach declaration");
1791 Lex.Lex(); // Eat the '='
1793 RecTy *IterType = nullptr;
1794 std::vector<unsigned> Ranges;
1796 switch (Lex.getCode()) {
1797 default: TokError("Unknown token when expecting a range list"); return nullptr;
1798 case tgtok::l_square: { // '[' ValueList ']'
1799 Init *List = ParseSimpleValue(nullptr, nullptr, ParseForeachMode);
1800 ForeachListValue = dyn_cast<ListInit>(List);
1801 if (!ForeachListValue) {
1802 TokError("Expected a Value list");
1805 RecTy *ValueType = ForeachListValue->getType();
1806 ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1808 TokError("Value list is not of list type");
1811 IterType = ListType->getElementType();
1815 case tgtok::IntVal: { // RangePiece.
1816 if (ParseRangePiece(Ranges))
1821 case tgtok::l_brace: { // '{' RangeList '}'
1822 Lex.Lex(); // eat the '{'
1823 Ranges = ParseRangeList();
1824 if (Lex.getCode() != tgtok::r_brace) {
1825 TokError("expected '}' at end of bit range list");
1833 if (!Ranges.empty()) {
1834 assert(!IterType && "Type already initialized?");
1835 IterType = IntRecTy::get();
1836 std::vector<Init*> Values;
1837 for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
1838 Values.push_back(IntInit::get(Ranges[i]));
1839 ForeachListValue = ListInit::get(Values, IterType);
1845 return VarInit::get(DeclName, IterType);
1848 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1849 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1850 /// template args for a def, which may or may not be in a multiclass. If null,
1851 /// these are the template args for a multiclass.
1853 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1855 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1856 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1857 Lex.Lex(); // eat the '<'
1859 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1861 // Read the first declaration.
1862 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1866 TheRecToAddTo->addTemplateArg(TemplArg);
1868 while (Lex.getCode() == tgtok::comma) {
1869 Lex.Lex(); // eat the ','
1871 // Read the following declarations.
1872 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1875 TheRecToAddTo->addTemplateArg(TemplArg);
1878 if (Lex.getCode() != tgtok::greater)
1879 return TokError("expected '>' at end of template argument list");
1880 Lex.Lex(); // eat the '>'.
1885 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1887 /// BodyItem ::= Declaration ';'
1888 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1889 bool TGParser::ParseBodyItem(Record *CurRec) {
1890 if (Lex.getCode() != tgtok::Let) {
1891 if (!ParseDeclaration(CurRec, false))
1894 if (Lex.getCode() != tgtok::semi)
1895 return TokError("expected ';' after declaration");
1900 // LET ID OptionalRangeList '=' Value ';'
1901 if (Lex.Lex() != tgtok::Id)
1902 return TokError("expected field identifier after let");
1904 SMLoc IdLoc = Lex.getLoc();
1905 std::string FieldName = Lex.getCurStrVal();
1906 Lex.Lex(); // eat the field name.
1908 std::vector<unsigned> BitList;
1909 if (ParseOptionalBitList(BitList))
1911 std::reverse(BitList.begin(), BitList.end());
1913 if (Lex.getCode() != tgtok::equal)
1914 return TokError("expected '=' in let expression");
1915 Lex.Lex(); // eat the '='.
1917 RecordVal *Field = CurRec->getValue(FieldName);
1919 return TokError("Value '" + FieldName + "' unknown!");
1921 RecTy *Type = Field->getType();
1923 Init *Val = ParseValue(CurRec, Type);
1924 if (!Val) return true;
1926 if (Lex.getCode() != tgtok::semi)
1927 return TokError("expected ';' after let expression");
1930 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1933 /// ParseBody - Read the body of a class or def. Return true on error, false on
1937 /// Body ::= '{' BodyList '}'
1938 /// BodyList BodyItem*
1940 bool TGParser::ParseBody(Record *CurRec) {
1941 // If this is a null definition, just eat the semi and return.
1942 if (Lex.getCode() == tgtok::semi) {
1947 if (Lex.getCode() != tgtok::l_brace)
1948 return TokError("Expected ';' or '{' to start body");
1952 while (Lex.getCode() != tgtok::r_brace)
1953 if (ParseBodyItem(CurRec))
1961 /// \brief Apply the current let bindings to \a CurRec.
1962 /// \returns true on error, false otherwise.
1963 bool TGParser::ApplyLetStack(Record *CurRec) {
1964 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1965 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1966 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1967 LetStack[i][j].Bits, LetStack[i][j].Value))
1972 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1973 /// optional ClassList followed by a Body. CurRec is the current def or class
1974 /// that is being parsed.
1976 /// ObjectBody ::= BaseClassList Body
1977 /// BaseClassList ::= /*empty*/
1978 /// BaseClassList ::= ':' BaseClassListNE
1979 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1981 bool TGParser::ParseObjectBody(Record *CurRec) {
1982 // If there is a baseclass list, read it.
1983 if (Lex.getCode() == tgtok::colon) {
1986 // Read all of the subclasses.
1987 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1990 if (!SubClass.Rec) return true;
1993 if (AddSubClass(CurRec, SubClass))
1996 if (Lex.getCode() != tgtok::comma) break;
1997 Lex.Lex(); // eat ','.
1998 SubClass = ParseSubClassReference(CurRec, false);
2002 if (ApplyLetStack(CurRec))
2005 return ParseBody(CurRec);
2008 /// ParseDef - Parse and return a top level or multiclass def, return the record
2009 /// corresponding to it. This returns null on error.
2011 /// DefInst ::= DEF ObjectName ObjectBody
2013 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
2014 SMLoc DefLoc = Lex.getLoc();
2015 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
2016 Lex.Lex(); // Eat the 'def' token.
2018 // Parse ObjectName and make a record for it.
2020 Init *Name = ParseObjectName(CurMultiClass);
2022 CurRec = new Record(Name, DefLoc, Records);
2024 CurRec = new Record(GetNewAnonymousName(), DefLoc, Records,
2025 /*IsAnonymous=*/true);
2027 if (!CurMultiClass && Loops.empty()) {
2028 // Top-level def definition.
2030 // Ensure redefinition doesn't happen.
2031 if (Records.getDef(CurRec->getNameInitAsString())) {
2032 Error(DefLoc, "def '" + CurRec->getNameInitAsString()
2033 + "' already defined");
2036 Records.addDef(CurRec);
2038 if (ParseObjectBody(CurRec))
2040 } else if (CurMultiClass) {
2041 // Parse the body before adding this prototype to the DefPrototypes vector.
2042 // That way implicit definitions will be added to the DefPrototypes vector
2043 // before this object, instantiated prior to defs derived from this object,
2044 // and this available for indirect name resolution when defs derived from
2045 // this object are instantiated.
2046 if (ParseObjectBody(CurRec))
2049 // Otherwise, a def inside a multiclass, add it to the multiclass.
2050 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
2051 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2052 == CurRec->getNameInit()) {
2053 Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
2054 "' already defined in this multiclass!");
2057 CurMultiClass->DefPrototypes.push_back(CurRec);
2058 } else if (ParseObjectBody(CurRec))
2061 if (!CurMultiClass) // Def's in multiclasses aren't really defs.
2062 // See Record::setName(). This resolve step will see any new name
2063 // for the def that might have been created when resolving
2064 // inheritance, values and arguments above.
2065 CurRec->resolveReferences();
2067 // If ObjectBody has template arguments, it's an error.
2068 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
2070 if (CurMultiClass) {
2071 // Copy the template arguments for the multiclass into the def.
2072 const std::vector<Init *> &TArgs =
2073 CurMultiClass->Rec.getTemplateArgs();
2075 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2076 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
2077 assert(RV && "Template arg doesn't exist?");
2078 CurRec->addValue(*RV);
2082 if (ProcessForeachDefs(CurRec, DefLoc)) {
2084 "Could not process loops for def" + CurRec->getNameInitAsString());
2091 /// ParseForeach - Parse a for statement. Return the record corresponding
2092 /// to it. This returns true on error.
2094 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2095 /// Foreach ::= FOREACH Declaration IN Object
2097 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2098 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2099 Lex.Lex(); // Eat the 'for' token.
2101 // Make a temporary object to record items associated with the for
2103 ListInit *ListValue = nullptr;
2104 VarInit *IterName = ParseForeachDeclaration(ListValue);
2106 return TokError("expected declaration in for");
2108 if (Lex.getCode() != tgtok::In)
2109 return TokError("Unknown tok");
2110 Lex.Lex(); // Eat the in
2112 // Create a loop object and remember it.
2113 Loops.push_back(ForeachLoop(IterName, ListValue));
2115 if (Lex.getCode() != tgtok::l_brace) {
2116 // FOREACH Declaration IN Object
2117 if (ParseObject(CurMultiClass))
2121 SMLoc BraceLoc = Lex.getLoc();
2122 // Otherwise, this is a group foreach.
2123 Lex.Lex(); // eat the '{'.
2125 // Parse the object list.
2126 if (ParseObjectList(CurMultiClass))
2129 if (Lex.getCode() != tgtok::r_brace) {
2130 TokError("expected '}' at end of foreach command");
2131 return Error(BraceLoc, "to match this '{'");
2133 Lex.Lex(); // Eat the }
2136 // We've processed everything in this loop.
2142 /// ParseClass - Parse a tblgen class definition.
2144 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2146 bool TGParser::ParseClass() {
2147 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2150 if (Lex.getCode() != tgtok::Id)
2151 return TokError("expected class name after 'class' keyword");
2153 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2155 // If the body was previously defined, this is an error.
2156 if (CurRec->getValues().size() > 1 || // Account for NAME.
2157 !CurRec->getSuperClasses().empty() ||
2158 !CurRec->getTemplateArgs().empty())
2159 return TokError("Class '" + CurRec->getNameInitAsString()
2160 + "' already defined");
2162 // If this is the first reference to this class, create and add it.
2163 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
2164 Records.addClass(CurRec);
2166 Lex.Lex(); // eat the name.
2168 // If there are template args, parse them.
2169 if (Lex.getCode() == tgtok::less)
2170 if (ParseTemplateArgList(CurRec))
2173 // Finally, parse the object body.
2174 return ParseObjectBody(CurRec);
2177 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2180 /// LetList ::= LetItem (',' LetItem)*
2181 /// LetItem ::= ID OptionalRangeList '=' Value
2183 std::vector<LetRecord> TGParser::ParseLetList() {
2184 std::vector<LetRecord> Result;
2187 if (Lex.getCode() != tgtok::Id) {
2188 TokError("expected identifier in let definition");
2189 return std::vector<LetRecord>();
2191 std::string Name = Lex.getCurStrVal();
2192 SMLoc NameLoc = Lex.getLoc();
2193 Lex.Lex(); // Eat the identifier.
2195 // Check for an optional RangeList.
2196 std::vector<unsigned> Bits;
2197 if (ParseOptionalRangeList(Bits))
2198 return std::vector<LetRecord>();
2199 std::reverse(Bits.begin(), Bits.end());
2201 if (Lex.getCode() != tgtok::equal) {
2202 TokError("expected '=' in let expression");
2203 return std::vector<LetRecord>();
2205 Lex.Lex(); // eat the '='.
2207 Init *Val = ParseValue(nullptr);
2208 if (!Val) return std::vector<LetRecord>();
2210 // Now that we have everything, add the record.
2211 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2213 if (Lex.getCode() != tgtok::comma)
2215 Lex.Lex(); // eat the comma.
2219 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2220 /// different related productions. This works inside multiclasses too.
2222 /// Object ::= LET LetList IN '{' ObjectList '}'
2223 /// Object ::= LET LetList IN Object
2225 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2226 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2229 // Add this entry to the let stack.
2230 std::vector<LetRecord> LetInfo = ParseLetList();
2231 if (LetInfo.empty()) return true;
2232 LetStack.push_back(LetInfo);
2234 if (Lex.getCode() != tgtok::In)
2235 return TokError("expected 'in' at end of top-level 'let'");
2238 // If this is a scalar let, just handle it now
2239 if (Lex.getCode() != tgtok::l_brace) {
2240 // LET LetList IN Object
2241 if (ParseObject(CurMultiClass))
2243 } else { // Object ::= LETCommand '{' ObjectList '}'
2244 SMLoc BraceLoc = Lex.getLoc();
2245 // Otherwise, this is a group let.
2246 Lex.Lex(); // eat the '{'.
2248 // Parse the object list.
2249 if (ParseObjectList(CurMultiClass))
2252 if (Lex.getCode() != tgtok::r_brace) {
2253 TokError("expected '}' at end of top level let command");
2254 return Error(BraceLoc, "to match this '{'");
2259 // Outside this let scope, this let block is not active.
2260 LetStack.pop_back();
2264 /// ParseMultiClass - Parse a multiclass definition.
2266 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2267 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2268 /// MultiClassObject ::= DefInst
2269 /// MultiClassObject ::= MultiClassInst
2270 /// MultiClassObject ::= DefMInst
2271 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
2272 /// MultiClassObject ::= LETCommand Object
2274 bool TGParser::ParseMultiClass() {
2275 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2276 Lex.Lex(); // Eat the multiclass token.
2278 if (Lex.getCode() != tgtok::Id)
2279 return TokError("expected identifier after multiclass for name");
2280 std::string Name = Lex.getCurStrVal();
2282 if (MultiClasses.count(Name))
2283 return TokError("multiclass '" + Name + "' already defined");
2285 CurMultiClass = MultiClasses[Name] = new MultiClass(Name,
2286 Lex.getLoc(), Records);
2287 Lex.Lex(); // Eat the identifier.
2289 // If there are template args, parse them.
2290 if (Lex.getCode() == tgtok::less)
2291 if (ParseTemplateArgList(nullptr))
2294 bool inherits = false;
2296 // If there are submulticlasses, parse them.
2297 if (Lex.getCode() == tgtok::colon) {
2302 // Read all of the submulticlasses.
2303 SubMultiClassReference SubMultiClass =
2304 ParseSubMultiClassReference(CurMultiClass);
2307 if (!SubMultiClass.MC) return true;
2310 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2313 if (Lex.getCode() != tgtok::comma) break;
2314 Lex.Lex(); // eat ','.
2315 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2319 if (Lex.getCode() != tgtok::l_brace) {
2321 return TokError("expected '{' in multiclass definition");
2322 else if (Lex.getCode() != tgtok::semi)
2323 return TokError("expected ';' in multiclass definition");
2325 Lex.Lex(); // eat the ';'.
2327 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2328 return TokError("multiclass must contain at least one def");
2330 while (Lex.getCode() != tgtok::r_brace) {
2331 switch (Lex.getCode()) {
2333 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2337 case tgtok::Foreach:
2338 if (ParseObject(CurMultiClass))
2343 Lex.Lex(); // eat the '}'.
2346 CurMultiClass = nullptr;
2351 InstantiateMulticlassDef(MultiClass &MC,
2354 SMRange DefmPrefixRange) {
2355 // We need to preserve DefProto so it can be reused for later
2356 // instantiations, so create a new Record to inherit from it.
2358 // Add in the defm name. If the defm prefix is empty, give each
2359 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2360 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2363 bool IsAnonymous = false;
2365 DefmPrefix = StringInit::get(GetNewAnonymousName());
2369 Init *DefName = DefProto->getNameInit();
2371 StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2373 if (DefNameString) {
2374 // We have a fully expanded string so there are no operators to
2375 // resolve. We should concatenate the given prefix and name.
2377 BinOpInit::get(BinOpInit::STRCONCAT,
2378 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2379 StringRecTy::get())->Fold(DefProto, &MC),
2380 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2383 // Make a trail of SMLocs from the multiclass instantiations.
2384 SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
2385 Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2386 Record *CurRec = new Record(DefName, Locs, Records, IsAnonymous);
2388 SubClassReference Ref;
2389 Ref.RefRange = DefmPrefixRange;
2391 AddSubClass(CurRec, Ref);
2393 // Set the value for NAME. We don't resolve references to it 'til later,
2394 // though, so that uses in nested multiclass names don't get
2396 if (SetValue(CurRec, Ref.RefRange.Start, "NAME", std::vector<unsigned>(),
2398 Error(DefmPrefixRange.Start, "Could not resolve "
2399 + CurRec->getNameInitAsString() + ":NAME to '"
2400 + DefmPrefix->getAsUnquotedString() + "'");
2404 // If the DefNameString didn't resolve, we probably have a reference to
2405 // NAME and need to replace it. We need to do at least this much greedily,
2406 // otherwise nested multiclasses will end up with incorrect NAME expansions.
2407 if (!DefNameString) {
2408 RecordVal *DefNameRV = CurRec->getValue("NAME");
2409 CurRec->resolveReferencesTo(DefNameRV);
2412 if (!CurMultiClass) {
2413 // Now that we're at the top level, resolve all NAME references
2414 // in the resultant defs that weren't in the def names themselves.
2415 RecordVal *DefNameRV = CurRec->getValue("NAME");
2416 CurRec->resolveReferencesTo(DefNameRV);
2418 // Now that NAME references are resolved and we're at the top level of
2419 // any multiclass expansions, add the record to the RecordKeeper. If we are
2420 // currently in a multiclass, it means this defm appears inside a
2421 // multiclass and its name won't be fully resolvable until we see
2422 // the top-level defm. Therefore, we don't add this to the
2423 // RecordKeeper at this point. If we did we could get duplicate
2424 // defs as more than one probably refers to NAME or some other
2425 // common internal placeholder.
2427 // Ensure redefinition doesn't happen.
2428 if (Records.getDef(CurRec->getNameInitAsString())) {
2429 Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
2430 "' already defined, instantiating defm with subdef '" +
2431 DefProto->getNameInitAsString() + "'");
2435 Records.addDef(CurRec);
2441 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2443 SMLoc DefmPrefixLoc,
2445 const std::vector<Init *> &TArgs,
2446 std::vector<Init *> &TemplateVals,
2448 // Loop over all of the template arguments, setting them to the specified
2449 // value or leaving them as the default if necessary.
2450 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2451 // Check if a value is specified for this temp-arg.
2452 if (i < TemplateVals.size()) {
2454 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2459 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2463 CurRec->removeValue(TArgs[i]);
2465 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2466 return Error(SubClassLoc, "value not specified for template argument #"+
2467 utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2468 + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2475 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2478 SMLoc DefmPrefixLoc) {
2479 // If the mdef is inside a 'let' expression, add to each def.
2480 if (ApplyLetStack(CurRec))
2481 return Error(DefmPrefixLoc, "when instantiating this defm");
2483 // Don't create a top level definition for defm inside multiclasses,
2484 // instead, only update the prototypes and bind the template args
2485 // with the new created definition.
2488 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2490 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2491 == CurRec->getNameInit())
2492 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2493 "' already defined in this multiclass!");
2494 CurMultiClass->DefPrototypes.push_back(CurRec);
2496 // Copy the template arguments for the multiclass into the new def.
2497 const std::vector<Init *> &TA =
2498 CurMultiClass->Rec.getTemplateArgs();
2500 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2501 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2502 assert(RV && "Template arg doesn't exist?");
2503 CurRec->addValue(*RV);
2509 /// ParseDefm - Parse the instantiation of a multiclass.
2511 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2513 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2514 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2515 SMLoc DefmLoc = Lex.getLoc();
2516 Init *DefmPrefix = nullptr;
2518 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2519 DefmPrefix = ParseObjectName(CurMultiClass);
2522 SMLoc DefmPrefixEndLoc = Lex.getLoc();
2523 if (Lex.getCode() != tgtok::colon)
2524 return TokError("expected ':' after defm identifier");
2526 // Keep track of the new generated record definitions.
2527 std::vector<Record*> NewRecDefs;
2529 // This record also inherits from a regular class (non-multiclass)?
2530 bool InheritFromClass = false;
2535 SMLoc SubClassLoc = Lex.getLoc();
2536 SubClassReference Ref = ParseSubClassReference(nullptr, true);
2539 if (!Ref.Rec) return true;
2541 // To instantiate a multiclass, we need to first get the multiclass, then
2542 // instantiate each def contained in the multiclass with the SubClassRef
2543 // template parameters.
2544 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2545 assert(MC && "Didn't lookup multiclass correctly?");
2546 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2548 // Verify that the correct number of template arguments were specified.
2549 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2550 if (TArgs.size() < TemplateVals.size())
2551 return Error(SubClassLoc,
2552 "more template args specified than multiclass expects");
2554 // Loop over all the def's in the multiclass, instantiating each one.
2555 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2556 Record *DefProto = MC->DefPrototypes[i];
2558 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix,
2564 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
2565 TArgs, TemplateVals, true/*Delete args*/))
2566 return Error(SubClassLoc, "could not instantiate def");
2568 if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmLoc))
2569 return Error(SubClassLoc, "could not instantiate def");
2571 NewRecDefs.push_back(CurRec);
2575 if (Lex.getCode() != tgtok::comma) break;
2576 Lex.Lex(); // eat ','.
2578 if (Lex.getCode() != tgtok::Id)
2579 return TokError("expected identifier");
2581 SubClassLoc = Lex.getLoc();
2583 // A defm can inherit from regular classes (non-multiclass) as
2584 // long as they come in the end of the inheritance list.
2585 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
2587 if (InheritFromClass)
2590 Ref = ParseSubClassReference(nullptr, true);
2593 if (InheritFromClass) {
2594 // Process all the classes to inherit as if they were part of a
2595 // regular 'def' and inherit all record values.
2596 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
2599 if (!SubClass.Rec) return true;
2601 // Get the expanded definition prototypes and teach them about
2602 // the record values the current class to inherit has
2603 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2604 Record *CurRec = NewRecDefs[i];
2607 if (AddSubClass(CurRec, SubClass))
2610 if (ApplyLetStack(CurRec))
2614 if (Lex.getCode() != tgtok::comma) break;
2615 Lex.Lex(); // eat ','.
2616 SubClass = ParseSubClassReference(nullptr, false);
2621 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2622 // See Record::setName(). This resolve step will see any new
2623 // name for the def that might have been created when resolving
2624 // inheritance, values and arguments above.
2625 NewRecDefs[i]->resolveReferences();
2627 if (Lex.getCode() != tgtok::semi)
2628 return TokError("expected ';' at end of defm");
2635 /// Object ::= ClassInst
2636 /// Object ::= DefInst
2637 /// Object ::= MultiClassInst
2638 /// Object ::= DefMInst
2639 /// Object ::= LETCommand '{' ObjectList '}'
2640 /// Object ::= LETCommand Object
2641 bool TGParser::ParseObject(MultiClass *MC) {
2642 switch (Lex.getCode()) {
2644 return TokError("Expected class, def, defm, multiclass or let definition");
2645 case tgtok::Let: return ParseTopLevelLet(MC);
2646 case tgtok::Def: return ParseDef(MC);
2647 case tgtok::Foreach: return ParseForeach(MC);
2648 case tgtok::Defm: return ParseDefm(MC);
2649 case tgtok::Class: return ParseClass();
2650 case tgtok::MultiClass: return ParseMultiClass();
2655 /// ObjectList :== Object*
2656 bool TGParser::ParseObjectList(MultiClass *MC) {
2657 while (isObjectStart(Lex.getCode())) {
2658 if (ParseObject(MC))
2664 bool TGParser::ParseFile() {
2665 Lex.Lex(); // Prime the lexer.
2666 if (ParseObjectList()) return true;
2668 // If we have unread input at the end of the file, report it.
2669 if (Lex.getCode() == tgtok::Eof)
2672 return TokError("Unexpected input at top level");