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/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/TableGen/Record.h"
24 //===----------------------------------------------------------------------===//
25 // Support Code for the Semantic Actions.
26 //===----------------------------------------------------------------------===//
29 struct SubClassReference {
32 std::vector<Init*> TemplateArgs;
33 SubClassReference() : Rec(nullptr) {}
35 bool isInvalid() const { return Rec == nullptr; }
38 struct SubMultiClassReference {
41 std::vector<Init*> TemplateArgs;
42 SubMultiClassReference() : MC(nullptr) {}
44 bool isInvalid() const { return MC == nullptr; }
48 void SubMultiClassReference::dump() const {
49 errs() << "Multiclass:\n";
53 errs() << "Template args:\n";
54 for (Init *TA : TemplateArgs)
58 } // end namespace llvm
60 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
62 CurRec = &CurMultiClass->Rec;
64 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
65 // The value already exists in the class, treat this as a set.
66 if (ERV->setValue(RV.getValue()))
67 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
68 RV.getType()->getAsString() + "' is incompatible with " +
69 "previous definition of type '" +
70 ERV->getType()->getAsString() + "'");
78 /// Return true on error, false on success.
79 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
80 const std::vector<unsigned> &BitList, Init *V) {
83 if (!CurRec) CurRec = &CurMultiClass->Rec;
85 RecordVal *RV = CurRec->getValue(ValName);
87 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
90 // Do not allow assignments like 'X = X'. This will just cause infinite loops
91 // in the resolution machinery.
93 if (VarInit *VI = dyn_cast<VarInit>(V))
94 if (VI->getNameInit() == ValName)
97 // If we are assigning to a subset of the bits in the value... then we must be
98 // assigning to a field of BitsRecTy, which must have a BitsInit
101 if (!BitList.empty()) {
102 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
104 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
105 "' is not a bits type");
107 // Convert the incoming value to a bits type of the appropriate size...
108 Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size()));
110 return Error(Loc, "Initializer is not compatible with bit range");
112 // We should have a BitsInit type now.
113 BitsInit *BInit = cast<BitsInit>(BI);
115 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
117 // Loop over bits, assigning values as appropriate.
118 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
119 unsigned Bit = BitList[i];
121 return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" +
122 ValName->getAsUnquotedString() + "' more than once");
123 NewBits[Bit] = BInit->getBit(i);
126 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
128 NewBits[i] = CurVal->getBit(i);
130 V = BitsInit::get(NewBits);
133 if (RV->setValue(V)) {
134 std::string InitType = "";
135 if (BitsInit *BI = dyn_cast<BitsInit>(V))
136 InitType = (Twine("' of type bit initializer with length ") +
137 Twine(BI->getNumBits())).str();
138 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
139 "' of type '" + RV->getType()->getAsString() +
140 "' 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 for (const RecordVal &Val : SC->getValues())
152 if (AddValue(CurRec, SubClass.RefRange.Start, Val))
155 const std::vector<Init *> &TArgs = SC->getTemplateArgs();
157 // Ensure that an appropriate number of template arguments are specified.
158 if (TArgs.size() < SubClass.TemplateArgs.size())
159 return Error(SubClass.RefRange.Start,
160 "More template args specified than expected");
162 // Loop over all of the template arguments, setting them to the specified
163 // value or leaving them as the default if necessary.
164 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
165 if (i < SubClass.TemplateArgs.size()) {
166 // If a value is specified for this template arg, set it now.
167 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
168 std::vector<unsigned>(), SubClass.TemplateArgs[i]))
172 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
175 CurRec->removeValue(TArgs[i]);
177 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
178 return Error(SubClass.RefRange.Start,
179 "Value not specified for template argument #" +
180 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
181 ") of subclass '" + SC->getNameInitAsString() + "'!");
185 // Since everything went well, we can now set the "superclass" list for the
187 const std::vector<Record*> &SCs = SC->getSuperClasses();
188 ArrayRef<SMRange> SCRanges = SC->getSuperClassRanges();
189 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
190 if (CurRec->isSubClassOf(SCs[i]))
191 return Error(SubClass.RefRange.Start,
192 "Already subclass of '" + SCs[i]->getName() + "'!\n");
193 CurRec->addSuperClass(SCs[i], SCRanges[i]);
196 if (CurRec->isSubClassOf(SC))
197 return Error(SubClass.RefRange.Start,
198 "Already subclass of '" + SC->getName() + "'!\n");
199 CurRec->addSuperClass(SC, SubClass.RefRange);
203 /// AddSubMultiClass - Add SubMultiClass as a subclass to
204 /// CurMC, resolving its template args as SubMultiClass's
205 /// template arguments.
206 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
207 SubMultiClassReference &SubMultiClass) {
208 MultiClass *SMC = SubMultiClass.MC;
209 Record *CurRec = &CurMC->Rec;
211 // Add all of the values in the subclass into the current class.
212 for (const auto &SMCVal : SMC->Rec.getValues())
213 if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVal))
216 unsigned newDefStart = CurMC->DefPrototypes.size();
218 // Add all of the defs in the subclass into the current multiclass.
219 for (const std::unique_ptr<Record> &R : SMC->DefPrototypes) {
220 // Clone the def and add it to the current multiclass
221 auto NewDef = make_unique<Record>(*R);
223 // Add all of the values in the superclass into the current def.
224 for (const auto &MCVal : CurRec->getValues())
225 if (AddValue(NewDef.get(), SubMultiClass.RefRange.Start, MCVal))
228 CurMC->DefPrototypes.push_back(std::move(NewDef));
231 const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
233 // Ensure that an appropriate number of template arguments are
235 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
236 return Error(SubMultiClass.RefRange.Start,
237 "More template args specified than expected");
239 // Loop over all of the template arguments, setting them to the specified
240 // value or leaving them as the default if necessary.
241 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
242 if (i < SubMultiClass.TemplateArgs.size()) {
243 // If a value is specified for this template arg, set it in the
245 if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i],
246 std::vector<unsigned>(),
247 SubMultiClass.TemplateArgs[i]))
251 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
254 CurRec->removeValue(SMCTArgs[i]);
256 // If a value is specified for this template arg, set it in the
258 for (const auto &Def :
259 makeArrayRef(CurMC->DefPrototypes).slice(newDefStart)) {
260 if (SetValue(Def.get(), SubMultiClass.RefRange.Start, SMCTArgs[i],
261 std::vector<unsigned>(),
262 SubMultiClass.TemplateArgs[i]))
266 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
269 Def->removeValue(SMCTArgs[i]);
271 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
272 return Error(SubMultiClass.RefRange.Start,
273 "Value not specified for template argument #" +
274 Twine(i) + " (" + SMCTArgs[i]->getAsUnquotedString() +
275 ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
282 /// ProcessForeachDefs - Given a record, apply all of the variable
283 /// values in all surrounding foreach loops, creating new records for
284 /// each combination of values.
285 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
289 // We want to instantiate a new copy of CurRec for each combination
290 // of nested loop iterator values. We don't want top instantiate
291 // any copies until we have values for each loop iterator.
293 return ProcessForeachDefs(CurRec, Loc, IterVals);
296 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
297 /// apply each of the variable values in this loop and then process
299 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
300 // Recursively build a tuple of iterator values.
301 if (IterVals.size() != Loops.size()) {
302 assert(IterVals.size() < Loops.size());
303 ForeachLoop &CurLoop = Loops[IterVals.size()];
304 ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
306 Error(Loc, "Loop list is not a list");
310 // Process each value.
311 for (unsigned i = 0; i < List->size(); ++i) {
312 Init *ItemVal = List->resolveListElementReference(*CurRec, nullptr, i);
313 IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
314 if (ProcessForeachDefs(CurRec, Loc, IterVals))
321 // This is the bottom of the recursion. We have all of the iterator values
322 // for this point in the iteration space. Instantiate a new record to
323 // reflect this combination of values.
324 auto IterRec = make_unique<Record>(*CurRec);
326 // Set the iterator values now.
327 for (IterRecord &IR : IterVals) {
328 VarInit *IterVar = IR.IterVar;
329 TypedInit *IVal = dyn_cast<TypedInit>(IR.IterValue);
331 return Error(Loc, "foreach iterator value is untyped");
333 IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
335 if (SetValue(IterRec.get(), Loc, IterVar->getName(),
336 std::vector<unsigned>(), IVal))
337 return Error(Loc, "when instantiating this def");
340 IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
343 IterRec->removeValue(IterVar->getName());
346 if (Records.getDef(IterRec->getNameInitAsString())) {
347 // If this record is anonymous, it's no problem, just generate a new name
348 if (!IterRec->isAnonymous())
349 return Error(Loc, "def already exists: " +IterRec->getNameInitAsString());
351 IterRec->setName(GetNewAnonymousName());
354 Record *IterRecSave = IterRec.get(); // Keep a copy before release.
355 Records.addDef(std::move(IterRec));
356 IterRecSave->resolveReferences();
360 //===----------------------------------------------------------------------===//
362 //===----------------------------------------------------------------------===//
364 /// isObjectStart - Return true if this is a valid first token for an Object.
365 static bool isObjectStart(tgtok::TokKind K) {
366 return K == tgtok::Class || K == tgtok::Def ||
367 K == tgtok::Defm || K == tgtok::Let ||
368 K == tgtok::MultiClass || K == tgtok::Foreach;
371 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
373 std::string TGParser::GetNewAnonymousName() {
374 return "anonymous_" + utostr(AnonCounter++);
377 /// ParseObjectName - If an object name is specified, return it. Otherwise,
379 /// ObjectName ::= Value [ '#' Value ]*
380 /// ObjectName ::= /*empty*/
382 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
383 switch (Lex.getCode()) {
387 // These are all of the tokens that can begin an object body.
388 // Some of these can also begin values but we disallow those cases
389 // because they are unlikely to be useful.
395 Record *CurRec = nullptr;
397 CurRec = &CurMultiClass->Rec;
399 RecTy *Type = nullptr;
401 const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
403 TokError("Record name is not typed!");
406 Type = CurRecName->getType();
409 return ParseValue(CurRec, Type, ParseNameMode);
412 /// ParseClassID - Parse and resolve a reference to a class name. This returns
417 Record *TGParser::ParseClassID() {
418 if (Lex.getCode() != tgtok::Id) {
419 TokError("expected name for ClassID");
423 Record *Result = Records.getClass(Lex.getCurStrVal());
425 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
431 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
432 /// This returns null on error.
434 /// MultiClassID ::= ID
436 MultiClass *TGParser::ParseMultiClassID() {
437 if (Lex.getCode() != tgtok::Id) {
438 TokError("expected name for MultiClassID");
442 MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
444 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
450 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
451 /// subclass. This returns a SubClassRefTy with a null Record* on error.
453 /// SubClassRef ::= ClassID
454 /// SubClassRef ::= ClassID '<' ValueList '>'
456 SubClassReference TGParser::
457 ParseSubClassReference(Record *CurRec, bool isDefm) {
458 SubClassReference Result;
459 Result.RefRange.Start = Lex.getLoc();
462 if (MultiClass *MC = ParseMultiClassID())
463 Result.Rec = &MC->Rec;
465 Result.Rec = ParseClassID();
467 if (!Result.Rec) return Result;
469 // If there is no template arg list, we're done.
470 if (Lex.getCode() != tgtok::less) {
471 Result.RefRange.End = Lex.getLoc();
474 Lex.Lex(); // Eat the '<'
476 if (Lex.getCode() == tgtok::greater) {
477 TokError("subclass reference requires a non-empty list of template values");
478 Result.Rec = nullptr;
482 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
483 if (Result.TemplateArgs.empty()) {
484 Result.Rec = nullptr; // Error parsing value list.
488 if (Lex.getCode() != tgtok::greater) {
489 TokError("expected '>' in template value list");
490 Result.Rec = nullptr;
494 Result.RefRange.End = Lex.getLoc();
499 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
500 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
501 /// Record* on error.
503 /// SubMultiClassRef ::= MultiClassID
504 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
506 SubMultiClassReference TGParser::
507 ParseSubMultiClassReference(MultiClass *CurMC) {
508 SubMultiClassReference Result;
509 Result.RefRange.Start = Lex.getLoc();
511 Result.MC = ParseMultiClassID();
512 if (!Result.MC) return Result;
514 // If there is no template arg list, we're done.
515 if (Lex.getCode() != tgtok::less) {
516 Result.RefRange.End = Lex.getLoc();
519 Lex.Lex(); // Eat the '<'
521 if (Lex.getCode() == tgtok::greater) {
522 TokError("subclass reference requires a non-empty list of template values");
527 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
528 if (Result.TemplateArgs.empty()) {
529 Result.MC = nullptr; // Error parsing value list.
533 if (Lex.getCode() != tgtok::greater) {
534 TokError("expected '>' in template value list");
539 Result.RefRange.End = Lex.getLoc();
544 /// ParseRangePiece - Parse a bit/value range.
545 /// RangePiece ::= INTVAL
546 /// RangePiece ::= INTVAL '-' INTVAL
547 /// RangePiece ::= INTVAL INTVAL
548 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
549 if (Lex.getCode() != tgtok::IntVal) {
550 TokError("expected integer or bitrange");
553 int64_t Start = Lex.getCurIntVal();
557 return TokError("invalid range, cannot be negative");
559 switch (Lex.Lex()) { // eat first character.
561 Ranges.push_back(Start);
564 if (Lex.Lex() != tgtok::IntVal) {
565 TokError("expected integer value as end of range");
568 End = Lex.getCurIntVal();
571 End = -Lex.getCurIntVal();
575 return TokError("invalid range, cannot be negative");
580 for (; Start <= End; ++Start)
581 Ranges.push_back(Start);
583 for (; Start >= End; --Start)
584 Ranges.push_back(Start);
588 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
590 /// RangeList ::= RangePiece (',' RangePiece)*
592 std::vector<unsigned> TGParser::ParseRangeList() {
593 std::vector<unsigned> Result;
595 // Parse the first piece.
596 if (ParseRangePiece(Result))
597 return std::vector<unsigned>();
598 while (Lex.getCode() == tgtok::comma) {
599 Lex.Lex(); // Eat the comma.
601 // Parse the next range piece.
602 if (ParseRangePiece(Result))
603 return std::vector<unsigned>();
608 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
609 /// OptionalRangeList ::= '<' RangeList '>'
610 /// OptionalRangeList ::= /*empty*/
611 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
612 if (Lex.getCode() != tgtok::less)
615 SMLoc StartLoc = Lex.getLoc();
616 Lex.Lex(); // eat the '<'
618 // Parse the range list.
619 Ranges = ParseRangeList();
620 if (Ranges.empty()) return true;
622 if (Lex.getCode() != tgtok::greater) {
623 TokError("expected '>' at end of range list");
624 return Error(StartLoc, "to match this '<'");
626 Lex.Lex(); // eat the '>'.
630 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
631 /// OptionalBitList ::= '{' RangeList '}'
632 /// OptionalBitList ::= /*empty*/
633 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
634 if (Lex.getCode() != tgtok::l_brace)
637 SMLoc StartLoc = Lex.getLoc();
638 Lex.Lex(); // eat the '{'
640 // Parse the range list.
641 Ranges = ParseRangeList();
642 if (Ranges.empty()) return true;
644 if (Lex.getCode() != tgtok::r_brace) {
645 TokError("expected '}' at end of bit list");
646 return Error(StartLoc, "to match this '{'");
648 Lex.Lex(); // eat the '}'.
653 /// ParseType - Parse and return a tblgen type. This returns null on error.
655 /// Type ::= STRING // string type
656 /// Type ::= CODE // code type
657 /// Type ::= BIT // bit type
658 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
659 /// Type ::= INT // int type
660 /// Type ::= LIST '<' Type '>' // list<x> type
661 /// Type ::= DAG // dag type
662 /// Type ::= ClassID // Record Type
664 RecTy *TGParser::ParseType() {
665 switch (Lex.getCode()) {
666 default: TokError("Unknown token when expecting a type"); return nullptr;
667 case tgtok::String: Lex.Lex(); return StringRecTy::get();
668 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
669 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
670 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
671 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
673 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
676 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
677 TokError("expected '<' after bits type");
680 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
681 TokError("expected integer in bits<n> type");
684 uint64_t Val = Lex.getCurIntVal();
685 if (Lex.Lex() != tgtok::greater) { // Eat count.
686 TokError("expected '>' at end of bits<n> type");
689 Lex.Lex(); // Eat '>'
690 return BitsRecTy::get(Val);
693 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
694 TokError("expected '<' after list type");
697 Lex.Lex(); // Eat '<'
698 RecTy *SubType = ParseType();
699 if (!SubType) return nullptr;
701 if (Lex.getCode() != tgtok::greater) {
702 TokError("expected '>' at end of list<ty> type");
705 Lex.Lex(); // Eat '>'
706 return ListRecTy::get(SubType);
711 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
712 /// has already been read.
713 Init *TGParser::ParseIDValue(Record *CurRec,
714 const std::string &Name, SMLoc NameLoc,
717 if (const RecordVal *RV = CurRec->getValue(Name))
718 return VarInit::get(Name, RV->getType());
720 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
723 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
726 if (CurRec->isTemplateArg(TemplateArgName)) {
727 const RecordVal *RV = CurRec->getValue(TemplateArgName);
728 assert(RV && "Template arg doesn't exist??");
729 return VarInit::get(TemplateArgName, RV->getType());
734 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
737 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
738 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
739 assert(RV && "Template arg doesn't exist??");
740 return VarInit::get(MCName, RV->getType());
744 // If this is in a foreach loop, make sure it's not a loop iterator
745 for (const auto &L : Loops) {
746 VarInit *IterVar = dyn_cast<VarInit>(L.IterVar);
747 if (IterVar && IterVar->getName() == Name)
751 if (Mode == ParseNameMode)
752 return StringInit::get(Name);
754 if (Record *D = Records.getDef(Name))
755 return DefInit::get(D);
757 if (Mode == ParseValueMode) {
758 Error(NameLoc, "Variable not defined: '" + Name + "'");
762 return StringInit::get(Name);
765 /// ParseOperation - Parse an operator. This returns null on error.
767 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
769 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
770 switch (Lex.getCode()) {
772 TokError("unknown operation");
777 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
778 UnOpInit::UnaryOp Code;
779 RecTy *Type = nullptr;
781 switch (Lex.getCode()) {
782 default: llvm_unreachable("Unhandled code!");
784 Lex.Lex(); // eat the operation
785 Code = UnOpInit::CAST;
787 Type = ParseOperatorType();
790 TokError("did not get type for unary operator");
796 Lex.Lex(); // eat the operation
797 Code = UnOpInit::HEAD;
800 Lex.Lex(); // eat the operation
801 Code = UnOpInit::TAIL;
804 Lex.Lex(); // eat the operation
805 Code = UnOpInit::EMPTY;
806 Type = IntRecTy::get();
809 if (Lex.getCode() != tgtok::l_paren) {
810 TokError("expected '(' after unary operator");
813 Lex.Lex(); // eat the '('
815 Init *LHS = ParseValue(CurRec);
816 if (!LHS) return nullptr;
818 if (Code == UnOpInit::HEAD ||
819 Code == UnOpInit::TAIL ||
820 Code == UnOpInit::EMPTY) {
821 ListInit *LHSl = dyn_cast<ListInit>(LHS);
822 StringInit *LHSs = dyn_cast<StringInit>(LHS);
823 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
824 if (!LHSl && !LHSs && !LHSt) {
825 TokError("expected list or string type argument in unary operator");
829 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
830 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
831 if (!LType && !SType) {
832 TokError("expected list or string type argument in unary operator");
837 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
838 if (!LHSl && !LHSt) {
839 TokError("expected list type argument in unary operator");
843 if (LHSl && LHSl->empty()) {
844 TokError("empty list argument in unary operator");
848 Init *Item = LHSl->getElement(0);
849 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
851 TokError("untyped list element in unary operator");
854 Type = (Code == UnOpInit::HEAD) ? Itemt->getType()
855 : ListRecTy::get(Itemt->getType());
857 assert(LHSt && "expected list type argument in unary operator");
858 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
860 TokError("expected list type argument in unary operator");
863 Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType;
868 if (Lex.getCode() != tgtok::r_paren) {
869 TokError("expected ')' in unary operator");
872 Lex.Lex(); // eat the ')'
873 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
883 case tgtok::XListConcat:
884 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
885 tgtok::TokKind OpTok = Lex.getCode();
886 SMLoc OpLoc = Lex.getLoc();
887 Lex.Lex(); // eat the operation
889 BinOpInit::BinaryOp Code;
890 RecTy *Type = nullptr;
893 default: llvm_unreachable("Unhandled code!");
894 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
895 case tgtok::XADD: Code = BinOpInit::ADD; Type = IntRecTy::get(); break;
896 case tgtok::XAND: Code = BinOpInit::AND; Type = IntRecTy::get(); break;
897 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
898 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
899 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
900 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
901 case tgtok::XListConcat:
902 Code = BinOpInit::LISTCONCAT;
903 // We don't know the list type until we parse the first argument
905 case tgtok::XStrConcat:
906 Code = BinOpInit::STRCONCAT;
907 Type = StringRecTy::get();
911 if (Lex.getCode() != tgtok::l_paren) {
912 TokError("expected '(' after binary operator");
915 Lex.Lex(); // eat the '('
917 SmallVector<Init*, 2> InitList;
919 InitList.push_back(ParseValue(CurRec));
920 if (!InitList.back()) return nullptr;
922 while (Lex.getCode() == tgtok::comma) {
923 Lex.Lex(); // eat the ','
925 InitList.push_back(ParseValue(CurRec));
926 if (!InitList.back()) return nullptr;
929 if (Lex.getCode() != tgtok::r_paren) {
930 TokError("expected ')' in operator");
933 Lex.Lex(); // eat the ')'
935 // If we are doing !listconcat, we should know the type by now
936 if (OpTok == tgtok::XListConcat) {
937 if (VarInit *Arg0 = dyn_cast<VarInit>(InitList[0]))
938 Type = Arg0->getType();
939 else if (ListInit *Arg0 = dyn_cast<ListInit>(InitList[0]))
940 Type = Arg0->getType();
943 Error(OpLoc, "expected a list");
948 // We allow multiple operands to associative operators like !strconcat as
949 // shorthand for nesting them.
950 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT) {
951 while (InitList.size() > 2) {
952 Init *RHS = InitList.pop_back_val();
953 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
954 ->Fold(CurRec, CurMultiClass);
955 InitList.back() = RHS;
959 if (InitList.size() == 2)
960 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
961 ->Fold(CurRec, CurMultiClass);
963 Error(OpLoc, "expected two operands to operator");
968 case tgtok::XForEach:
969 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
970 TernOpInit::TernaryOp Code;
971 RecTy *Type = nullptr;
973 tgtok::TokKind LexCode = Lex.getCode();
974 Lex.Lex(); // eat the operation
976 default: llvm_unreachable("Unhandled code!");
978 Code = TernOpInit::IF;
980 case tgtok::XForEach:
981 Code = TernOpInit::FOREACH;
984 Code = TernOpInit::SUBST;
987 if (Lex.getCode() != tgtok::l_paren) {
988 TokError("expected '(' after ternary operator");
991 Lex.Lex(); // eat the '('
993 Init *LHS = ParseValue(CurRec);
994 if (!LHS) return nullptr;
996 if (Lex.getCode() != tgtok::comma) {
997 TokError("expected ',' in ternary operator");
1000 Lex.Lex(); // eat the ','
1002 Init *MHS = ParseValue(CurRec, ItemType);
1006 if (Lex.getCode() != tgtok::comma) {
1007 TokError("expected ',' in ternary operator");
1010 Lex.Lex(); // eat the ','
1012 Init *RHS = ParseValue(CurRec, ItemType);
1016 if (Lex.getCode() != tgtok::r_paren) {
1017 TokError("expected ')' in binary operator");
1020 Lex.Lex(); // eat the ')'
1023 default: llvm_unreachable("Unhandled code!");
1025 RecTy *MHSTy = nullptr;
1026 RecTy *RHSTy = nullptr;
1028 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1029 MHSTy = MHSt->getType();
1030 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1031 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1032 if (isa<BitInit>(MHS))
1033 MHSTy = BitRecTy::get();
1035 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1036 RHSTy = RHSt->getType();
1037 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1038 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1039 if (isa<BitInit>(RHS))
1040 RHSTy = BitRecTy::get();
1042 // For UnsetInit, it's typed from the other hand.
1043 if (isa<UnsetInit>(MHS))
1045 if (isa<UnsetInit>(RHS))
1048 if (!MHSTy || !RHSTy) {
1049 TokError("could not get type for !if");
1053 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1055 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1058 TokError("inconsistent types for !if");
1063 case tgtok::XForEach: {
1064 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1066 TokError("could not get type for !foreach");
1069 Type = MHSt->getType();
1072 case tgtok::XSubst: {
1073 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1075 TokError("could not get type for !subst");
1078 Type = RHSt->getType();
1082 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1088 /// ParseOperatorType - Parse a type for an operator. This returns
1091 /// OperatorType ::= '<' Type '>'
1093 RecTy *TGParser::ParseOperatorType() {
1094 RecTy *Type = nullptr;
1096 if (Lex.getCode() != tgtok::less) {
1097 TokError("expected type name for operator");
1100 Lex.Lex(); // eat the <
1105 TokError("expected type name for operator");
1109 if (Lex.getCode() != tgtok::greater) {
1110 TokError("expected type name for operator");
1113 Lex.Lex(); // eat the >
1119 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1121 /// SimpleValue ::= IDValue
1122 /// SimpleValue ::= INTVAL
1123 /// SimpleValue ::= STRVAL+
1124 /// SimpleValue ::= CODEFRAGMENT
1125 /// SimpleValue ::= '?'
1126 /// SimpleValue ::= '{' ValueList '}'
1127 /// SimpleValue ::= ID '<' ValueListNE '>'
1128 /// SimpleValue ::= '[' ValueList ']'
1129 /// SimpleValue ::= '(' IDValue DagArgList ')'
1130 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1131 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1132 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1133 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1134 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1135 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1136 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1138 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1141 switch (Lex.getCode()) {
1142 default: TokError("Unknown token when parsing a value"); break;
1144 // This is a leading paste operation. This is deprecated but
1145 // still exists in some .td files. Ignore it.
1146 Lex.Lex(); // Skip '#'.
1147 return ParseSimpleValue(CurRec, ItemType, Mode);
1148 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1149 case tgtok::BinaryIntVal: {
1150 auto BinaryVal = Lex.getCurBinaryIntVal();
1151 SmallVector<Init*, 16> Bits(BinaryVal.second);
1152 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
1153 Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
1154 R = BitsInit::get(Bits);
1158 case tgtok::StrVal: {
1159 std::string Val = Lex.getCurStrVal();
1162 // Handle multiple consecutive concatenated strings.
1163 while (Lex.getCode() == tgtok::StrVal) {
1164 Val += Lex.getCurStrVal();
1168 R = StringInit::get(Val);
1171 case tgtok::CodeFragment:
1172 R = StringInit::get(Lex.getCurStrVal());
1175 case tgtok::question:
1176 R = UnsetInit::get();
1180 SMLoc NameLoc = Lex.getLoc();
1181 std::string Name = Lex.getCurStrVal();
1182 if (Lex.Lex() != tgtok::less) // consume the Id.
1183 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1185 // Value ::= ID '<' ValueListNE '>'
1186 if (Lex.Lex() == tgtok::greater) {
1187 TokError("expected non-empty value list");
1191 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1192 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1194 Record *Class = Records.getClass(Name);
1196 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1200 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1201 if (ValueList.empty()) return nullptr;
1203 if (Lex.getCode() != tgtok::greater) {
1204 TokError("expected '>' at end of value list");
1207 Lex.Lex(); // eat the '>'
1208 SMLoc EndLoc = Lex.getLoc();
1210 // Create the new record, set it as CurRec temporarily.
1211 auto NewRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), NameLoc,
1212 Records, /*IsAnonymous=*/true);
1213 Record *NewRec = NewRecOwner.get(); // Keep a copy since we may release.
1214 SubClassReference SCRef;
1215 SCRef.RefRange = SMRange(NameLoc, EndLoc);
1217 SCRef.TemplateArgs = ValueList;
1218 // Add info about the subclass to NewRec.
1219 if (AddSubClass(NewRec, SCRef))
1222 if (!CurMultiClass) {
1223 NewRec->resolveReferences();
1224 Records.addDef(std::move(NewRecOwner));
1226 // This needs to get resolved once the multiclass template arguments are
1227 // known before any use.
1228 NewRec->setResolveFirst(true);
1229 // Otherwise, we're inside a multiclass, add it to the multiclass.
1230 CurMultiClass->DefPrototypes.push_back(std::move(NewRecOwner));
1232 // Copy the template arguments for the multiclass into the def.
1233 for (Init *TArg : CurMultiClass->Rec.getTemplateArgs()) {
1234 const RecordVal *RV = CurMultiClass->Rec.getValue(TArg);
1235 assert(RV && "Template arg doesn't exist?");
1236 NewRec->addValue(*RV);
1239 // We can't return the prototype def here, instead return:
1240 // !cast<ItemType>(!strconcat(NAME, AnonName)).
1241 const RecordVal *MCNameRV = CurMultiClass->Rec.getValue("NAME");
1242 assert(MCNameRV && "multiclass record must have a NAME");
1244 return UnOpInit::get(UnOpInit::CAST,
1245 BinOpInit::get(BinOpInit::STRCONCAT,
1246 VarInit::get(MCNameRV->getName(),
1247 MCNameRV->getType()),
1248 NewRec->getNameInit(),
1249 StringRecTy::get()),
1250 Class->getDefInit()->getType());
1253 // The result of the expression is a reference to the new record.
1254 return DefInit::get(NewRec);
1256 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1257 SMLoc BraceLoc = Lex.getLoc();
1258 Lex.Lex(); // eat the '{'
1259 std::vector<Init*> Vals;
1261 if (Lex.getCode() != tgtok::r_brace) {
1262 Vals = ParseValueList(CurRec);
1263 if (Vals.empty()) return nullptr;
1265 if (Lex.getCode() != tgtok::r_brace) {
1266 TokError("expected '}' at end of bit list value");
1269 Lex.Lex(); // eat the '}'
1271 SmallVector<Init *, 16> NewBits;
1273 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1274 // first. We'll first read everything in to a vector, then we can reverse
1275 // it to get the bits in the correct order for the BitsInit value.
1276 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1277 // FIXME: The following two loops would not be duplicated
1278 // if the API was a little more orthogonal.
1280 // bits<n> values are allowed to initialize n bits.
1281 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
1282 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
1283 NewBits.push_back(BI->getBit((e - i) - 1));
1286 // bits<n> can also come from variable initializers.
1287 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
1288 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
1289 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
1290 NewBits.push_back(VI->getBit((e - i) - 1));
1293 // Fallthrough to try convert this to a bit.
1295 // All other values must be convertible to just a single bit.
1296 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1298 Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
1299 ") is not convertable to a bit");
1302 NewBits.push_back(Bit);
1304 std::reverse(NewBits.begin(), NewBits.end());
1305 return BitsInit::get(NewBits);
1307 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1308 Lex.Lex(); // eat the '['
1309 std::vector<Init*> Vals;
1311 RecTy *DeducedEltTy = nullptr;
1312 ListRecTy *GivenListTy = nullptr;
1315 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1317 TokError(Twine("Type mismatch for list, expected list type, got ") +
1318 ItemType->getAsString());
1321 GivenListTy = ListType;
1324 if (Lex.getCode() != tgtok::r_square) {
1325 Vals = ParseValueList(CurRec, nullptr,
1326 GivenListTy ? GivenListTy->getElementType() : nullptr);
1327 if (Vals.empty()) return nullptr;
1329 if (Lex.getCode() != tgtok::r_square) {
1330 TokError("expected ']' at end of list value");
1333 Lex.Lex(); // eat the ']'
1335 RecTy *GivenEltTy = nullptr;
1336 if (Lex.getCode() == tgtok::less) {
1337 // Optional list element type
1338 Lex.Lex(); // eat the '<'
1340 GivenEltTy = ParseType();
1342 // Couldn't parse element type
1346 if (Lex.getCode() != tgtok::greater) {
1347 TokError("expected '>' at end of list element type");
1350 Lex.Lex(); // eat the '>'
1354 RecTy *EltTy = nullptr;
1355 for (Init *V : Vals) {
1356 TypedInit *TArg = dyn_cast<TypedInit>(V);
1358 TokError("Untyped list element");
1362 EltTy = resolveTypes(EltTy, TArg->getType());
1364 TokError("Incompatible types in list elements");
1368 EltTy = TArg->getType();
1374 // Verify consistency
1375 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1376 TokError("Incompatible types in list elements");
1385 TokError("No type for list");
1388 DeducedEltTy = GivenListTy->getElementType();
1390 // Make sure the deduced type is compatible with the given type
1392 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1393 TokError("Element type mismatch for list");
1397 DeducedEltTy = EltTy;
1400 return ListInit::get(Vals, DeducedEltTy);
1402 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1403 Lex.Lex(); // eat the '('
1404 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1405 TokError("expected identifier in dag init");
1409 Init *Operator = ParseValue(CurRec);
1410 if (!Operator) return nullptr;
1412 // If the operator name is present, parse it.
1413 std::string OperatorName;
1414 if (Lex.getCode() == tgtok::colon) {
1415 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1416 TokError("expected variable name in dag operator");
1419 OperatorName = Lex.getCurStrVal();
1420 Lex.Lex(); // eat the VarName.
1423 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1424 if (Lex.getCode() != tgtok::r_paren) {
1425 DagArgs = ParseDagArgList(CurRec);
1426 if (DagArgs.empty()) return nullptr;
1429 if (Lex.getCode() != tgtok::r_paren) {
1430 TokError("expected ')' in dag init");
1433 Lex.Lex(); // eat the ')'
1435 return DagInit::get(Operator, OperatorName, DagArgs);
1441 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1442 case tgtok::XConcat:
1449 case tgtok::XListConcat:
1450 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1452 case tgtok::XForEach:
1453 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1454 return ParseOperation(CurRec, ItemType);
1461 /// ParseValue - Parse a tblgen value. This returns null on error.
1463 /// Value ::= SimpleValue ValueSuffix*
1464 /// ValueSuffix ::= '{' BitList '}'
1465 /// ValueSuffix ::= '[' BitList ']'
1466 /// ValueSuffix ::= '.' ID
1468 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1469 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1470 if (!Result) return nullptr;
1472 // Parse the suffixes now if present.
1474 switch (Lex.getCode()) {
1475 default: return Result;
1476 case tgtok::l_brace: {
1477 if (Mode == ParseNameMode || Mode == ParseForeachMode)
1478 // This is the beginning of the object body.
1481 SMLoc CurlyLoc = Lex.getLoc();
1482 Lex.Lex(); // eat the '{'
1483 std::vector<unsigned> Ranges = ParseRangeList();
1484 if (Ranges.empty()) return nullptr;
1486 // Reverse the bitlist.
1487 std::reverse(Ranges.begin(), Ranges.end());
1488 Result = Result->convertInitializerBitRange(Ranges);
1490 Error(CurlyLoc, "Invalid bit range for value");
1495 if (Lex.getCode() != tgtok::r_brace) {
1496 TokError("expected '}' at end of bit range list");
1502 case tgtok::l_square: {
1503 SMLoc SquareLoc = Lex.getLoc();
1504 Lex.Lex(); // eat the '['
1505 std::vector<unsigned> Ranges = ParseRangeList();
1506 if (Ranges.empty()) return nullptr;
1508 Result = Result->convertInitListSlice(Ranges);
1510 Error(SquareLoc, "Invalid range for list slice");
1515 if (Lex.getCode() != tgtok::r_square) {
1516 TokError("expected ']' at end of list slice");
1523 if (Lex.Lex() != tgtok::Id) { // eat the .
1524 TokError("expected field identifier after '.'");
1527 if (!Result->getFieldType(Lex.getCurStrVal())) {
1528 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1529 Result->getAsString() + "'");
1532 Result = FieldInit::get(Result, Lex.getCurStrVal());
1533 Lex.Lex(); // eat field name
1537 SMLoc PasteLoc = Lex.getLoc();
1539 // Create a !strconcat() operation, first casting each operand to
1540 // a string if necessary.
1542 TypedInit *LHS = dyn_cast<TypedInit>(Result);
1544 Error(PasteLoc, "LHS of paste is not typed!");
1548 if (LHS->getType() != StringRecTy::get()) {
1549 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1552 TypedInit *RHS = nullptr;
1554 Lex.Lex(); // Eat the '#'.
1555 switch (Lex.getCode()) {
1558 case tgtok::l_brace:
1559 // These are all of the tokens that can begin an object body.
1560 // Some of these can also begin values but we disallow those cases
1561 // because they are unlikely to be useful.
1563 // Trailing paste, concat with an empty string.
1564 RHS = StringInit::get("");
1568 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1569 RHS = dyn_cast<TypedInit>(RHSResult);
1571 Error(PasteLoc, "RHS of paste is not typed!");
1575 if (RHS->getType() != StringRecTy::get()) {
1576 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1582 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1583 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1589 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1591 /// DagArg ::= Value (':' VARNAME)?
1592 /// DagArg ::= VARNAME
1593 /// DagArgList ::= DagArg
1594 /// DagArgList ::= DagArgList ',' DagArg
1595 std::vector<std::pair<llvm::Init*, std::string> >
1596 TGParser::ParseDagArgList(Record *CurRec) {
1597 std::vector<std::pair<llvm::Init*, std::string> > Result;
1600 // DagArg ::= VARNAME
1601 if (Lex.getCode() == tgtok::VarName) {
1602 // A missing value is treated like '?'.
1603 Result.emplace_back(UnsetInit::get(), Lex.getCurStrVal());
1606 // DagArg ::= Value (':' VARNAME)?
1607 Init *Val = ParseValue(CurRec);
1609 return std::vector<std::pair<llvm::Init*, std::string> >();
1611 // If the variable name is present, add it.
1612 std::string VarName;
1613 if (Lex.getCode() == tgtok::colon) {
1614 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1615 TokError("expected variable name in dag literal");
1616 return std::vector<std::pair<llvm::Init*, std::string> >();
1618 VarName = Lex.getCurStrVal();
1619 Lex.Lex(); // eat the VarName.
1622 Result.push_back(std::make_pair(Val, VarName));
1624 if (Lex.getCode() != tgtok::comma) break;
1625 Lex.Lex(); // eat the ','
1632 /// ParseValueList - Parse a comma separated list of values, returning them as a
1633 /// vector. Note that this always expects to be able to parse at least one
1634 /// value. It returns an empty list if this is not possible.
1636 /// ValueList ::= Value (',' Value)
1638 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1640 std::vector<Init*> Result;
1641 RecTy *ItemType = EltTy;
1642 unsigned int ArgN = 0;
1643 if (ArgsRec && !EltTy) {
1644 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1645 if (TArgs.empty()) {
1646 TokError("template argument provided to non-template class");
1647 return std::vector<Init*>();
1649 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1651 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1654 assert(RV && "Template argument record not found??");
1655 ItemType = RV->getType();
1658 Result.push_back(ParseValue(CurRec, ItemType));
1659 if (!Result.back()) return std::vector<Init*>();
1661 while (Lex.getCode() == tgtok::comma) {
1662 Lex.Lex(); // Eat the comma
1664 if (ArgsRec && !EltTy) {
1665 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1666 if (ArgN >= TArgs.size()) {
1667 TokError("too many template arguments");
1668 return std::vector<Init*>();
1670 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1671 assert(RV && "Template argument record not found??");
1672 ItemType = RV->getType();
1675 Result.push_back(ParseValue(CurRec, ItemType));
1676 if (!Result.back()) return std::vector<Init*>();
1683 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1684 /// empty string on error. This can happen in a number of different context's,
1685 /// including within a def or in the template args for a def (which which case
1686 /// CurRec will be non-null) and within the template args for a multiclass (in
1687 /// which case CurRec will be null, but CurMultiClass will be set). This can
1688 /// also happen within a def that is within a multiclass, which will set both
1689 /// CurRec and CurMultiClass.
1691 /// Declaration ::= FIELD? Type ID ('=' Value)?
1693 Init *TGParser::ParseDeclaration(Record *CurRec,
1694 bool ParsingTemplateArgs) {
1695 // Read the field prefix if present.
1696 bool HasField = Lex.getCode() == tgtok::Field;
1697 if (HasField) Lex.Lex();
1699 RecTy *Type = ParseType();
1700 if (!Type) return nullptr;
1702 if (Lex.getCode() != tgtok::Id) {
1703 TokError("Expected identifier in declaration");
1707 SMLoc IdLoc = Lex.getLoc();
1708 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1711 if (ParsingTemplateArgs) {
1713 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1715 assert(CurMultiClass);
1717 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1722 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1725 // If a value is present, parse it.
1726 if (Lex.getCode() == tgtok::equal) {
1728 SMLoc ValLoc = Lex.getLoc();
1729 Init *Val = ParseValue(CurRec, Type);
1731 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1732 // Return the name, even if an error is thrown. This is so that we can
1733 // continue to make some progress, even without the value having been
1741 /// ParseForeachDeclaration - Read a foreach declaration, returning
1742 /// the name of the declared object or a NULL Init on error. Return
1743 /// the name of the parsed initializer list through ForeachListName.
1745 /// ForeachDeclaration ::= ID '=' '[' ValueList ']'
1746 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
1747 /// ForeachDeclaration ::= ID '=' RangePiece
1749 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1750 if (Lex.getCode() != tgtok::Id) {
1751 TokError("Expected identifier in foreach declaration");
1755 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1758 // If a value is present, parse it.
1759 if (Lex.getCode() != tgtok::equal) {
1760 TokError("Expected '=' in foreach declaration");
1763 Lex.Lex(); // Eat the '='
1765 RecTy *IterType = nullptr;
1766 std::vector<unsigned> Ranges;
1768 switch (Lex.getCode()) {
1769 default: TokError("Unknown token when expecting a range list"); return nullptr;
1770 case tgtok::l_square: { // '[' ValueList ']'
1771 Init *List = ParseSimpleValue(nullptr, nullptr, ParseForeachMode);
1772 ForeachListValue = dyn_cast<ListInit>(List);
1773 if (!ForeachListValue) {
1774 TokError("Expected a Value list");
1777 RecTy *ValueType = ForeachListValue->getType();
1778 ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1780 TokError("Value list is not of list type");
1783 IterType = ListType->getElementType();
1787 case tgtok::IntVal: { // RangePiece.
1788 if (ParseRangePiece(Ranges))
1793 case tgtok::l_brace: { // '{' RangeList '}'
1794 Lex.Lex(); // eat the '{'
1795 Ranges = ParseRangeList();
1796 if (Lex.getCode() != tgtok::r_brace) {
1797 TokError("expected '}' at end of bit range list");
1805 if (!Ranges.empty()) {
1806 assert(!IterType && "Type already initialized?");
1807 IterType = IntRecTy::get();
1808 std::vector<Init*> Values;
1809 for (unsigned R : Ranges)
1810 Values.push_back(IntInit::get(R));
1811 ForeachListValue = ListInit::get(Values, IterType);
1817 return VarInit::get(DeclName, IterType);
1820 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1821 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1822 /// template args for a def, which may or may not be in a multiclass. If null,
1823 /// these are the template args for a multiclass.
1825 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1827 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1828 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1829 Lex.Lex(); // eat the '<'
1831 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1833 // Read the first declaration.
1834 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1838 TheRecToAddTo->addTemplateArg(TemplArg);
1840 while (Lex.getCode() == tgtok::comma) {
1841 Lex.Lex(); // eat the ','
1843 // Read the following declarations.
1844 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1847 TheRecToAddTo->addTemplateArg(TemplArg);
1850 if (Lex.getCode() != tgtok::greater)
1851 return TokError("expected '>' at end of template argument list");
1852 Lex.Lex(); // eat the '>'.
1857 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1859 /// BodyItem ::= Declaration ';'
1860 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1861 bool TGParser::ParseBodyItem(Record *CurRec) {
1862 if (Lex.getCode() != tgtok::Let) {
1863 if (!ParseDeclaration(CurRec, false))
1866 if (Lex.getCode() != tgtok::semi)
1867 return TokError("expected ';' after declaration");
1872 // LET ID OptionalRangeList '=' Value ';'
1873 if (Lex.Lex() != tgtok::Id)
1874 return TokError("expected field identifier after let");
1876 SMLoc IdLoc = Lex.getLoc();
1877 std::string FieldName = Lex.getCurStrVal();
1878 Lex.Lex(); // eat the field name.
1880 std::vector<unsigned> BitList;
1881 if (ParseOptionalBitList(BitList))
1883 std::reverse(BitList.begin(), BitList.end());
1885 if (Lex.getCode() != tgtok::equal)
1886 return TokError("expected '=' in let expression");
1887 Lex.Lex(); // eat the '='.
1889 RecordVal *Field = CurRec->getValue(FieldName);
1891 return TokError("Value '" + FieldName + "' unknown!");
1893 RecTy *Type = Field->getType();
1895 Init *Val = ParseValue(CurRec, Type);
1896 if (!Val) return true;
1898 if (Lex.getCode() != tgtok::semi)
1899 return TokError("expected ';' after let expression");
1902 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1905 /// ParseBody - Read the body of a class or def. Return true on error, false on
1909 /// Body ::= '{' BodyList '}'
1910 /// BodyList BodyItem*
1912 bool TGParser::ParseBody(Record *CurRec) {
1913 // If this is a null definition, just eat the semi and return.
1914 if (Lex.getCode() == tgtok::semi) {
1919 if (Lex.getCode() != tgtok::l_brace)
1920 return TokError("Expected ';' or '{' to start body");
1924 while (Lex.getCode() != tgtok::r_brace)
1925 if (ParseBodyItem(CurRec))
1933 /// \brief Apply the current let bindings to \a CurRec.
1934 /// \returns true on error, false otherwise.
1935 bool TGParser::ApplyLetStack(Record *CurRec) {
1936 for (std::vector<LetRecord> &LetInfo : LetStack)
1937 for (LetRecord &LR : LetInfo)
1938 if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
1943 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1944 /// optional ClassList followed by a Body. CurRec is the current def or class
1945 /// that is being parsed.
1947 /// ObjectBody ::= BaseClassList Body
1948 /// BaseClassList ::= /*empty*/
1949 /// BaseClassList ::= ':' BaseClassListNE
1950 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1952 bool TGParser::ParseObjectBody(Record *CurRec) {
1953 // If there is a baseclass list, read it.
1954 if (Lex.getCode() == tgtok::colon) {
1957 // Read all of the subclasses.
1958 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1961 if (!SubClass.Rec) return true;
1964 if (AddSubClass(CurRec, SubClass))
1967 if (Lex.getCode() != tgtok::comma) break;
1968 Lex.Lex(); // eat ','.
1969 SubClass = ParseSubClassReference(CurRec, false);
1973 if (ApplyLetStack(CurRec))
1976 return ParseBody(CurRec);
1979 /// ParseDef - Parse and return a top level or multiclass def, return the record
1980 /// corresponding to it. This returns null on error.
1982 /// DefInst ::= DEF ObjectName ObjectBody
1984 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1985 SMLoc DefLoc = Lex.getLoc();
1986 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1987 Lex.Lex(); // Eat the 'def' token.
1989 // Parse ObjectName and make a record for it.
1990 std::unique_ptr<Record> CurRecOwner;
1991 Init *Name = ParseObjectName(CurMultiClass);
1993 CurRecOwner = make_unique<Record>(Name, DefLoc, Records);
1995 CurRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), DefLoc,
1996 Records, /*IsAnonymous=*/true);
1997 Record *CurRec = CurRecOwner.get(); // Keep a copy since we may release.
1999 if (!CurMultiClass && Loops.empty()) {
2000 // Top-level def definition.
2002 // Ensure redefinition doesn't happen.
2003 if (Records.getDef(CurRec->getNameInitAsString()))
2004 return Error(DefLoc, "def '" + CurRec->getNameInitAsString()+
2005 "' already defined");
2006 Records.addDef(std::move(CurRecOwner));
2008 if (ParseObjectBody(CurRec))
2010 } else if (CurMultiClass) {
2011 // Parse the body before adding this prototype to the DefPrototypes vector.
2012 // That way implicit definitions will be added to the DefPrototypes vector
2013 // before this object, instantiated prior to defs derived from this object,
2014 // and this available for indirect name resolution when defs derived from
2015 // this object are instantiated.
2016 if (ParseObjectBody(CurRec))
2019 // Otherwise, a def inside a multiclass, add it to the multiclass.
2020 for (const auto &Proto : CurMultiClass->DefPrototypes)
2021 if (Proto->getNameInit() == CurRec->getNameInit())
2022 return Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
2023 "' already defined in this multiclass!");
2024 CurMultiClass->DefPrototypes.push_back(std::move(CurRecOwner));
2025 } else if (ParseObjectBody(CurRec)) {
2029 if (!CurMultiClass) // Def's in multiclasses aren't really defs.
2030 // See Record::setName(). This resolve step will see any new name
2031 // for the def that might have been created when resolving
2032 // inheritance, values and arguments above.
2033 CurRec->resolveReferences();
2035 // If ObjectBody has template arguments, it's an error.
2036 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
2038 if (CurMultiClass) {
2039 // Copy the template arguments for the multiclass into the def.
2040 for (Init *TArg : CurMultiClass->Rec.getTemplateArgs()) {
2041 const RecordVal *RV = CurMultiClass->Rec.getValue(TArg);
2042 assert(RV && "Template arg doesn't exist?");
2043 CurRec->addValue(*RV);
2047 if (ProcessForeachDefs(CurRec, DefLoc))
2048 return Error(DefLoc, "Could not process loops for def" +
2049 CurRec->getNameInitAsString());
2054 /// ParseForeach - Parse a for statement. Return the record corresponding
2055 /// to it. This returns true on error.
2057 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2058 /// Foreach ::= FOREACH Declaration IN Object
2060 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2061 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2062 Lex.Lex(); // Eat the 'for' token.
2064 // Make a temporary object to record items associated with the for
2066 ListInit *ListValue = nullptr;
2067 VarInit *IterName = ParseForeachDeclaration(ListValue);
2069 return TokError("expected declaration in for");
2071 if (Lex.getCode() != tgtok::In)
2072 return TokError("Unknown tok");
2073 Lex.Lex(); // Eat the in
2075 // Create a loop object and remember it.
2076 Loops.push_back(ForeachLoop(IterName, ListValue));
2078 if (Lex.getCode() != tgtok::l_brace) {
2079 // FOREACH Declaration IN Object
2080 if (ParseObject(CurMultiClass))
2083 SMLoc BraceLoc = Lex.getLoc();
2084 // Otherwise, this is a group foreach.
2085 Lex.Lex(); // eat the '{'.
2087 // Parse the object list.
2088 if (ParseObjectList(CurMultiClass))
2091 if (Lex.getCode() != tgtok::r_brace) {
2092 TokError("expected '}' at end of foreach command");
2093 return Error(BraceLoc, "to match this '{'");
2095 Lex.Lex(); // Eat the }
2098 // We've processed everything in this loop.
2104 /// ParseClass - Parse a tblgen class definition.
2106 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2108 bool TGParser::ParseClass() {
2109 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2112 if (Lex.getCode() != tgtok::Id)
2113 return TokError("expected class name after 'class' keyword");
2115 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2117 // If the body was previously defined, this is an error.
2118 if (CurRec->getValues().size() > 1 || // Account for NAME.
2119 !CurRec->getSuperClasses().empty() ||
2120 !CurRec->getTemplateArgs().empty())
2121 return TokError("Class '" + CurRec->getNameInitAsString() +
2122 "' already defined");
2124 // If this is the first reference to this class, create and add it.
2126 llvm::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records);
2127 CurRec = NewRec.get();
2128 Records.addClass(std::move(NewRec));
2130 Lex.Lex(); // eat the name.
2132 // If there are template args, parse them.
2133 if (Lex.getCode() == tgtok::less)
2134 if (ParseTemplateArgList(CurRec))
2137 // Finally, parse the object body.
2138 return ParseObjectBody(CurRec);
2141 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2144 /// LetList ::= LetItem (',' LetItem)*
2145 /// LetItem ::= ID OptionalRangeList '=' Value
2147 std::vector<LetRecord> TGParser::ParseLetList() {
2148 std::vector<LetRecord> Result;
2151 if (Lex.getCode() != tgtok::Id) {
2152 TokError("expected identifier in let definition");
2153 return std::vector<LetRecord>();
2155 std::string Name = Lex.getCurStrVal();
2156 SMLoc NameLoc = Lex.getLoc();
2157 Lex.Lex(); // Eat the identifier.
2159 // Check for an optional RangeList.
2160 std::vector<unsigned> Bits;
2161 if (ParseOptionalRangeList(Bits))
2162 return std::vector<LetRecord>();
2163 std::reverse(Bits.begin(), Bits.end());
2165 if (Lex.getCode() != tgtok::equal) {
2166 TokError("expected '=' in let expression");
2167 return std::vector<LetRecord>();
2169 Lex.Lex(); // eat the '='.
2171 Init *Val = ParseValue(nullptr);
2172 if (!Val) return std::vector<LetRecord>();
2174 // Now that we have everything, add the record.
2175 Result.emplace_back(std::move(Name), std::move(Bits), Val, NameLoc);
2177 if (Lex.getCode() != tgtok::comma)
2179 Lex.Lex(); // eat the comma.
2183 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2184 /// different related productions. This works inside multiclasses too.
2186 /// Object ::= LET LetList IN '{' ObjectList '}'
2187 /// Object ::= LET LetList IN Object
2189 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2190 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2193 // Add this entry to the let stack.
2194 std::vector<LetRecord> LetInfo = ParseLetList();
2195 if (LetInfo.empty()) return true;
2196 LetStack.push_back(std::move(LetInfo));
2198 if (Lex.getCode() != tgtok::In)
2199 return TokError("expected 'in' at end of top-level 'let'");
2202 // If this is a scalar let, just handle it now
2203 if (Lex.getCode() != tgtok::l_brace) {
2204 // LET LetList IN Object
2205 if (ParseObject(CurMultiClass))
2207 } else { // Object ::= LETCommand '{' ObjectList '}'
2208 SMLoc BraceLoc = Lex.getLoc();
2209 // Otherwise, this is a group let.
2210 Lex.Lex(); // eat the '{'.
2212 // Parse the object list.
2213 if (ParseObjectList(CurMultiClass))
2216 if (Lex.getCode() != tgtok::r_brace) {
2217 TokError("expected '}' at end of top level let command");
2218 return Error(BraceLoc, "to match this '{'");
2223 // Outside this let scope, this let block is not active.
2224 LetStack.pop_back();
2228 /// ParseMultiClass - Parse a multiclass definition.
2230 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2231 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2232 /// MultiClassObject ::= DefInst
2233 /// MultiClassObject ::= MultiClassInst
2234 /// MultiClassObject ::= DefMInst
2235 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
2236 /// MultiClassObject ::= LETCommand Object
2238 bool TGParser::ParseMultiClass() {
2239 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2240 Lex.Lex(); // Eat the multiclass token.
2242 if (Lex.getCode() != tgtok::Id)
2243 return TokError("expected identifier after multiclass for name");
2244 std::string Name = Lex.getCurStrVal();
2247 MultiClasses.insert(std::make_pair(Name,
2248 llvm::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
2251 return TokError("multiclass '" + Name + "' already defined");
2253 CurMultiClass = Result.first->second.get();
2254 Lex.Lex(); // Eat the identifier.
2256 // If there are template args, parse them.
2257 if (Lex.getCode() == tgtok::less)
2258 if (ParseTemplateArgList(nullptr))
2261 bool inherits = false;
2263 // If there are submulticlasses, parse them.
2264 if (Lex.getCode() == tgtok::colon) {
2269 // Read all of the submulticlasses.
2270 SubMultiClassReference SubMultiClass =
2271 ParseSubMultiClassReference(CurMultiClass);
2274 if (!SubMultiClass.MC) return true;
2277 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2280 if (Lex.getCode() != tgtok::comma) break;
2281 Lex.Lex(); // eat ','.
2282 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2286 if (Lex.getCode() != tgtok::l_brace) {
2288 return TokError("expected '{' in multiclass definition");
2289 if (Lex.getCode() != tgtok::semi)
2290 return TokError("expected ';' in multiclass definition");
2291 Lex.Lex(); // eat the ';'.
2293 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2294 return TokError("multiclass must contain at least one def");
2296 while (Lex.getCode() != tgtok::r_brace) {
2297 switch (Lex.getCode()) {
2299 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2303 case tgtok::Foreach:
2304 if (ParseObject(CurMultiClass))
2309 Lex.Lex(); // eat the '}'.
2312 CurMultiClass = nullptr;
2317 InstantiateMulticlassDef(MultiClass &MC,
2320 SMRange DefmPrefixRange,
2321 const std::vector<Init *> &TArgs,
2322 std::vector<Init *> &TemplateVals) {
2323 // We need to preserve DefProto so it can be reused for later
2324 // instantiations, so create a new Record to inherit from it.
2326 // Add in the defm name. If the defm prefix is empty, give each
2327 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2328 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2331 bool IsAnonymous = false;
2333 DefmPrefix = StringInit::get(GetNewAnonymousName());
2337 Init *DefName = DefProto->getNameInit();
2338 StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2340 if (DefNameString) {
2341 // We have a fully expanded string so there are no operators to
2342 // resolve. We should concatenate the given prefix and name.
2344 BinOpInit::get(BinOpInit::STRCONCAT,
2345 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2346 StringRecTy::get())->Fold(DefProto, &MC),
2347 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2350 // Make a trail of SMLocs from the multiclass instantiations.
2351 SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
2352 Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2353 auto CurRec = make_unique<Record>(DefName, Locs, Records, IsAnonymous);
2355 SubClassReference Ref;
2356 Ref.RefRange = DefmPrefixRange;
2358 AddSubClass(CurRec.get(), Ref);
2360 // Set the value for NAME. We don't resolve references to it 'til later,
2361 // though, so that uses in nested multiclass names don't get
2363 if (SetValue(CurRec.get(), Ref.RefRange.Start, "NAME",
2364 std::vector<unsigned>(), DefmPrefix)) {
2365 Error(DefmPrefixRange.Start, "Could not resolve " +
2366 CurRec->getNameInitAsString() + ":NAME to '" +
2367 DefmPrefix->getAsUnquotedString() + "'");
2371 // If the DefNameString didn't resolve, we probably have a reference to
2372 // NAME and need to replace it. We need to do at least this much greedily,
2373 // otherwise nested multiclasses will end up with incorrect NAME expansions.
2374 if (!DefNameString) {
2375 RecordVal *DefNameRV = CurRec->getValue("NAME");
2376 CurRec->resolveReferencesTo(DefNameRV);
2379 if (!CurMultiClass) {
2380 // Now that we're at the top level, resolve all NAME references
2381 // in the resultant defs that weren't in the def names themselves.
2382 RecordVal *DefNameRV = CurRec->getValue("NAME");
2383 CurRec->resolveReferencesTo(DefNameRV);
2385 // Check if the name is a complex pattern.
2386 // If so, resolve it.
2387 DefName = CurRec->getNameInit();
2388 DefNameString = dyn_cast<StringInit>(DefName);
2390 // OK the pattern is more complex than simply using NAME.
2391 // Let's use the heavy weaponery.
2392 if (!DefNameString) {
2393 ResolveMulticlassDefArgs(MC, CurRec.get(), DefmPrefixRange.Start,
2394 Lex.getLoc(), TArgs, TemplateVals,
2395 false/*Delete args*/);
2396 DefName = CurRec->getNameInit();
2397 DefNameString = dyn_cast<StringInit>(DefName);
2400 DefName = DefName->convertInitializerTo(StringRecTy::get());
2402 // We ran out of options here...
2403 DefNameString = dyn_cast<StringInit>(DefName);
2404 if (!DefNameString) {
2405 PrintFatalError(CurRec->getLoc()[CurRec->getLoc().size() - 1],
2406 DefName->getAsUnquotedString() + " is not a string.");
2410 CurRec->setName(DefName);
2413 // Now that NAME references are resolved and we're at the top level of
2414 // any multiclass expansions, add the record to the RecordKeeper. If we are
2415 // currently in a multiclass, it means this defm appears inside a
2416 // multiclass and its name won't be fully resolvable until we see
2417 // the top-level defm. Therefore, we don't add this to the
2418 // RecordKeeper at this point. If we did we could get duplicate
2419 // defs as more than one probably refers to NAME or some other
2420 // common internal placeholder.
2422 // Ensure redefinition doesn't happen.
2423 if (Records.getDef(CurRec->getNameInitAsString())) {
2424 Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
2425 "' already defined, instantiating defm with subdef '" +
2426 DefProto->getNameInitAsString() + "'");
2430 Record *CurRecSave = CurRec.get(); // Keep a copy before we release.
2431 Records.addDef(std::move(CurRec));
2435 // FIXME This is bad but the ownership transfer to caller is pretty messy.
2436 // The unique_ptr in this function at least protects the exits above.
2437 return CurRec.release();
2440 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2442 SMLoc DefmPrefixLoc,
2444 const std::vector<Init *> &TArgs,
2445 std::vector<Init *> &TemplateVals,
2447 // Loop over all of the template arguments, setting them to the specified
2448 // value or leaving them as the default if necessary.
2449 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2450 // Check if a value is specified for this temp-arg.
2451 if (i < TemplateVals.size()) {
2453 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2458 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2462 CurRec->removeValue(TArgs[i]);
2464 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2465 return Error(SubClassLoc, "value not specified for template argument #" +
2466 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
2467 ") of multiclassclass '" + MC.Rec.getNameInitAsString() +
2474 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2477 SMLoc DefmPrefixLoc) {
2478 // If the mdef is inside a 'let' expression, add to each def.
2479 if (ApplyLetStack(CurRec))
2480 return Error(DefmPrefixLoc, "when instantiating this defm");
2482 // Don't create a top level definition for defm inside multiclasses,
2483 // instead, only update the prototypes and bind the template args
2484 // with the new created definition.
2487 for (const auto &Proto : CurMultiClass->DefPrototypes)
2488 if (Proto->getNameInit() == CurRec->getNameInit())
2489 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2490 "' already defined in this multiclass!");
2491 CurMultiClass->DefPrototypes.push_back(std::unique_ptr<Record>(CurRec));
2493 // Copy the template arguments for the multiclass into the new def.
2494 for (Init * TA : CurMultiClass->Rec.getTemplateArgs()) {
2495 const RecordVal *RV = CurMultiClass->Rec.getValue(TA);
2496 assert(RV && "Template arg doesn't exist?");
2497 CurRec->addValue(*RV);
2503 /// ParseDefm - Parse the instantiation of a multiclass.
2505 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2507 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2508 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2509 SMLoc DefmLoc = Lex.getLoc();
2510 Init *DefmPrefix = nullptr;
2512 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2513 DefmPrefix = ParseObjectName(CurMultiClass);
2516 SMLoc DefmPrefixEndLoc = Lex.getLoc();
2517 if (Lex.getCode() != tgtok::colon)
2518 return TokError("expected ':' after defm identifier");
2520 // Keep track of the new generated record definitions.
2521 std::vector<Record*> NewRecDefs;
2523 // This record also inherits from a regular class (non-multiclass)?
2524 bool InheritFromClass = false;
2529 SMLoc SubClassLoc = Lex.getLoc();
2530 SubClassReference Ref = ParseSubClassReference(nullptr, true);
2533 if (!Ref.Rec) return true;
2535 // To instantiate a multiclass, we need to first get the multiclass, then
2536 // instantiate each def contained in the multiclass with the SubClassRef
2537 // template parameters.
2538 MultiClass *MC = MultiClasses[Ref.Rec->getName()].get();
2539 assert(MC && "Didn't lookup multiclass correctly?");
2540 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2542 // Verify that the correct number of template arguments were specified.
2543 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2544 if (TArgs.size() < TemplateVals.size())
2545 return Error(SubClassLoc,
2546 "more template args specified than multiclass expects");
2548 // Loop over all the def's in the multiclass, instantiating each one.
2549 for (const std::unique_ptr<Record> &DefProto : MC->DefPrototypes) {
2550 // The record name construction goes as follow:
2551 // - If the def name is a string, prepend the prefix.
2552 // - If the def name is a more complex pattern, use that pattern.
2553 // As a result, the record is instanciated before resolving
2554 // arguments, as it would make its name a string.
2555 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto.get(), DefmPrefix,
2558 TArgs, TemplateVals);
2562 // Now that the record is instanciated, we can resolve arguments.
2563 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
2564 TArgs, TemplateVals, true/*Delete args*/))
2565 return Error(SubClassLoc, "could not instantiate def");
2567 if (ResolveMulticlassDef(*MC, CurRec, DefProto.get(), DefmLoc))
2568 return Error(SubClassLoc, "could not instantiate def");
2570 // Defs that can be used by other definitions should be fully resolved
2572 if (DefProto->isResolveFirst() && !CurMultiClass) {
2573 CurRec->resolveReferences();
2574 CurRec->setResolveFirst(false);
2576 NewRecDefs.push_back(CurRec);
2580 if (Lex.getCode() != tgtok::comma) break;
2581 Lex.Lex(); // eat ','.
2583 if (Lex.getCode() != tgtok::Id)
2584 return TokError("expected identifier");
2586 SubClassLoc = Lex.getLoc();
2588 // A defm can inherit from regular classes (non-multiclass) as
2589 // long as they come in the end of the inheritance list.
2590 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
2592 if (InheritFromClass)
2595 Ref = ParseSubClassReference(nullptr, true);
2598 if (InheritFromClass) {
2599 // Process all the classes to inherit as if they were part of a
2600 // regular 'def' and inherit all record values.
2601 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
2604 if (!SubClass.Rec) return true;
2606 // Get the expanded definition prototypes and teach them about
2607 // the record values the current class to inherit has
2608 for (Record *CurRec : NewRecDefs) {
2610 if (AddSubClass(CurRec, SubClass))
2613 if (ApplyLetStack(CurRec))
2617 if (Lex.getCode() != tgtok::comma) break;
2618 Lex.Lex(); // eat ','.
2619 SubClass = ParseSubClassReference(nullptr, false);
2624 for (Record *CurRec : NewRecDefs)
2625 // See Record::setName(). This resolve step will see any new
2626 // name for the def that might have been created when resolving
2627 // inheritance, values and arguments above.
2628 CurRec->resolveReferences();
2630 if (Lex.getCode() != tgtok::semi)
2631 return TokError("expected ';' at end of defm");
2638 /// Object ::= ClassInst
2639 /// Object ::= DefInst
2640 /// Object ::= MultiClassInst
2641 /// Object ::= DefMInst
2642 /// Object ::= LETCommand '{' ObjectList '}'
2643 /// Object ::= LETCommand Object
2644 bool TGParser::ParseObject(MultiClass *MC) {
2645 switch (Lex.getCode()) {
2647 return TokError("Expected class, def, defm, multiclass or let definition");
2648 case tgtok::Let: return ParseTopLevelLet(MC);
2649 case tgtok::Def: return ParseDef(MC);
2650 case tgtok::Foreach: return ParseForeach(MC);
2651 case tgtok::Defm: return ParseDefm(MC);
2652 case tgtok::Class: return ParseClass();
2653 case tgtok::MultiClass: return ParseMultiClass();
2658 /// ObjectList :== Object*
2659 bool TGParser::ParseObjectList(MultiClass *MC) {
2660 while (isObjectStart(Lex.getCode())) {
2661 if (ParseObject(MC))
2667 bool TGParser::ParseFile() {
2668 Lex.Lex(); // Prime the lexer.
2669 if (ParseObjectList()) return true;
2671 // If we have unread input at the end of the file, report it.
2672 if (Lex.getCode() == tgtok::Eof)
2675 return TokError("Unexpected input at top level");