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) {
59 } // end namespace llvm
61 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
63 CurRec = &CurMultiClass->Rec;
65 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
66 // The value already exists in the class, treat this as a set.
67 if (ERV->setValue(RV.getValue()))
68 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
69 RV.getType()->getAsString() + "' is incompatible with " +
70 "previous definition of type '" +
71 ERV->getType()->getAsString() + "'");
79 /// Return true on error, false on success.
80 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
81 const std::vector<unsigned> &BitList, Init *V) {
84 if (!CurRec) CurRec = &CurMultiClass->Rec;
86 RecordVal *RV = CurRec->getValue(ValName);
88 return Error(Loc, "Value '" + ValName->getAsUnquotedString()
91 // Do not allow assignments like 'X = X'. This will just cause infinite loops
92 // in the resolution machinery.
94 if (VarInit *VI = dyn_cast<VarInit>(V))
95 if (VI->getNameInit() == ValName)
98 // If we are assigning to a subset of the bits in the value... then we must be
99 // assigning to a field of BitsRecTy, which must have a BitsInit
102 if (!BitList.empty()) {
103 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
105 return Error(Loc, "Value '" + ValName->getAsUnquotedString()
106 + "' is not a bits type");
108 // Convert the incoming value to a bits type of the appropriate size...
109 Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size()));
111 return Error(Loc, "Initializer is not compatible with bit range");
114 // We should have a BitsInit type now.
115 BitsInit *BInit = dyn_cast<BitsInit>(BI);
116 assert(BInit != nullptr);
118 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
120 // Loop over bits, assigning values as appropriate.
121 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
122 unsigned Bit = BitList[i];
124 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
125 ValName->getAsUnquotedString() + "' more than once");
126 NewBits[Bit] = BInit->getBit(i);
129 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
131 NewBits[i] = CurVal->getBit(i);
133 V = BitsInit::get(NewBits);
136 if (RV->setValue(V)) {
137 std::string InitType = "";
138 if (BitsInit *BI = dyn_cast<BitsInit>(V)) {
139 InitType = (Twine("' of type bit initializer with length ") +
140 Twine(BI->getNumBits())).str();
142 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of type '"
143 + RV->getType()->getAsString() +
144 "' is incompatible with initializer '" + V->getAsString()
151 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
152 /// args as SubClass's template arguments.
153 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
154 Record *SC = SubClass.Rec;
155 // Add all of the values in the subclass into the current class.
156 const std::vector<RecordVal> &Vals = SC->getValues();
157 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
158 if (AddValue(CurRec, SubClass.RefRange.Start, Vals[i]))
161 const std::vector<Init *> &TArgs = SC->getTemplateArgs();
163 // Ensure that an appropriate number of template arguments are specified.
164 if (TArgs.size() < SubClass.TemplateArgs.size())
165 return Error(SubClass.RefRange.Start,
166 "More template args specified than expected");
168 // Loop over all of the template arguments, setting them to the specified
169 // value or leaving them as the default if necessary.
170 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
171 if (i < SubClass.TemplateArgs.size()) {
172 // If a value is specified for this template arg, set it now.
173 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
174 std::vector<unsigned>(), SubClass.TemplateArgs[i]))
178 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
181 CurRec->removeValue(TArgs[i]);
183 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
184 return Error(SubClass.RefRange.Start,
185 "Value not specified for template argument #"
186 + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
187 + ") of subclass '" + SC->getNameInitAsString() + "'!");
191 // Since everything went well, we can now set the "superclass" list for the
193 const std::vector<Record*> &SCs = SC->getSuperClasses();
194 ArrayRef<SMRange> SCRanges = SC->getSuperClassRanges();
195 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
196 if (CurRec->isSubClassOf(SCs[i]))
197 return Error(SubClass.RefRange.Start,
198 "Already subclass of '" + SCs[i]->getName() + "'!\n");
199 CurRec->addSuperClass(SCs[i], SCRanges[i]);
202 if (CurRec->isSubClassOf(SC))
203 return Error(SubClass.RefRange.Start,
204 "Already subclass of '" + SC->getName() + "'!\n");
205 CurRec->addSuperClass(SC, SubClass.RefRange);
209 /// AddSubMultiClass - Add SubMultiClass as a subclass to
210 /// CurMC, resolving its template args as SubMultiClass's
211 /// template arguments.
212 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
213 SubMultiClassReference &SubMultiClass) {
214 MultiClass *SMC = SubMultiClass.MC;
215 Record *CurRec = &CurMC->Rec;
217 // Add all of the values in the subclass into the current class.
218 for (const auto &SMCVal : SMC->Rec.getValues())
219 if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVal))
222 unsigned newDefStart = CurMC->DefPrototypes.size();
224 // Add all of the defs in the subclass into the current multiclass.
225 for (const std::unique_ptr<Record> &R : SMC->DefPrototypes) {
226 // Clone the def and add it to the current multiclass
227 auto NewDef = make_unique<Record>(*R);
229 // Add all of the values in the superclass into the current def.
230 for (const auto &MCVal : CurRec->getValues())
231 if (AddValue(NewDef.get(), SubMultiClass.RefRange.Start, MCVal))
234 CurMC->DefPrototypes.push_back(std::move(NewDef));
237 const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
239 // Ensure that an appropriate number of template arguments are
241 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
242 return Error(SubMultiClass.RefRange.Start,
243 "More template args specified than expected");
245 // Loop over all of the template arguments, setting them to the specified
246 // value or leaving them as the default if necessary.
247 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
248 if (i < SubMultiClass.TemplateArgs.size()) {
249 // If a value is specified for this template arg, set it in the
251 if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i],
252 std::vector<unsigned>(),
253 SubMultiClass.TemplateArgs[i]))
257 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
260 CurRec->removeValue(SMCTArgs[i]);
262 // If a value is specified for this template arg, set it in the
264 for (const auto &Def :
265 makeArrayRef(CurMC->DefPrototypes).slice(newDefStart)) {
266 if (SetValue(Def.get(), SubMultiClass.RefRange.Start, SMCTArgs[i],
267 std::vector<unsigned>(),
268 SubMultiClass.TemplateArgs[i]))
272 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
275 Def->removeValue(SMCTArgs[i]);
277 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
278 return Error(SubMultiClass.RefRange.Start,
279 "Value not specified for template argument #"
280 + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
281 + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
288 /// ProcessForeachDefs - Given a record, apply all of the variable
289 /// values in all surrounding foreach loops, creating new records for
290 /// each combination of values.
291 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
295 // We want to instantiate a new copy of CurRec for each combination
296 // of nested loop iterator values. We don't want top instantiate
297 // any copies until we have values for each loop iterator.
299 return ProcessForeachDefs(CurRec, Loc, IterVals);
302 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
303 /// apply each of the variable values in this loop and then process
305 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
306 // Recursively build a tuple of iterator values.
307 if (IterVals.size() != Loops.size()) {
308 assert(IterVals.size() < Loops.size());
309 ForeachLoop &CurLoop = Loops[IterVals.size()];
310 ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
312 Error(Loc, "Loop list is not a list");
316 // Process each value.
317 for (int64_t i = 0; i < List->getSize(); ++i) {
318 Init *ItemVal = List->resolveListElementReference(*CurRec, nullptr, i);
319 IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
320 if (ProcessForeachDefs(CurRec, Loc, IterVals))
327 // This is the bottom of the recursion. We have all of the iterator values
328 // for this point in the iteration space. Instantiate a new record to
329 // reflect this combination of values.
330 auto IterRec = make_unique<Record>(*CurRec);
332 // Set the iterator values now.
333 for (unsigned i = 0, e = IterVals.size(); i != e; ++i) {
334 VarInit *IterVar = IterVals[i].IterVar;
335 TypedInit *IVal = dyn_cast<TypedInit>(IterVals[i].IterValue);
337 return Error(Loc, "foreach iterator value is untyped");
339 IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
341 if (SetValue(IterRec.get(), Loc, IterVar->getName(),
342 std::vector<unsigned>(), IVal))
343 return Error(Loc, "when instantiating this def");
346 IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
349 IterRec->removeValue(IterVar->getName());
352 if (Records.getDef(IterRec->getNameInitAsString())) {
353 // If this record is anonymous, it's no problem, just generate a new name
354 if (!IterRec->isAnonymous())
355 return Error(Loc, "def already exists: " +IterRec->getNameInitAsString());
357 IterRec->setName(GetNewAnonymousName());
360 Record *IterRecSave = IterRec.get(); // Keep a copy before release.
361 Records.addDef(std::move(IterRec));
362 IterRecSave->resolveReferences();
366 //===----------------------------------------------------------------------===//
368 //===----------------------------------------------------------------------===//
370 /// isObjectStart - Return true if this is a valid first token for an Object.
371 static bool isObjectStart(tgtok::TokKind K) {
372 return K == tgtok::Class || K == tgtok::Def ||
373 K == tgtok::Defm || K == tgtok::Let ||
374 K == tgtok::MultiClass || K == tgtok::Foreach;
377 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
379 std::string TGParser::GetNewAnonymousName() {
380 return "anonymous_" + utostr(AnonCounter++);
383 /// ParseObjectName - If an object name is specified, return it. Otherwise,
385 /// ObjectName ::= Value [ '#' Value ]*
386 /// ObjectName ::= /*empty*/
388 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
389 switch (Lex.getCode()) {
393 // These are all of the tokens that can begin an object body.
394 // Some of these can also begin values but we disallow those cases
395 // because they are unlikely to be useful.
401 Record *CurRec = nullptr;
403 CurRec = &CurMultiClass->Rec;
405 RecTy *Type = nullptr;
407 const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
409 TokError("Record name is not typed!");
412 Type = CurRecName->getType();
415 return ParseValue(CurRec, Type, ParseNameMode);
418 /// ParseClassID - Parse and resolve a reference to a class name. This returns
423 Record *TGParser::ParseClassID() {
424 if (Lex.getCode() != tgtok::Id) {
425 TokError("expected name for ClassID");
429 Record *Result = Records.getClass(Lex.getCurStrVal());
431 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
437 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
438 /// This returns null on error.
440 /// MultiClassID ::= ID
442 MultiClass *TGParser::ParseMultiClassID() {
443 if (Lex.getCode() != tgtok::Id) {
444 TokError("expected name for MultiClassID");
448 MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
450 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
456 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
457 /// subclass. This returns a SubClassRefTy with a null Record* on error.
459 /// SubClassRef ::= ClassID
460 /// SubClassRef ::= ClassID '<' ValueList '>'
462 SubClassReference TGParser::
463 ParseSubClassReference(Record *CurRec, bool isDefm) {
464 SubClassReference Result;
465 Result.RefRange.Start = Lex.getLoc();
468 if (MultiClass *MC = ParseMultiClassID())
469 Result.Rec = &MC->Rec;
471 Result.Rec = ParseClassID();
473 if (!Result.Rec) return Result;
475 // If there is no template arg list, we're done.
476 if (Lex.getCode() != tgtok::less) {
477 Result.RefRange.End = Lex.getLoc();
480 Lex.Lex(); // Eat the '<'
482 if (Lex.getCode() == tgtok::greater) {
483 TokError("subclass reference requires a non-empty list of template values");
484 Result.Rec = nullptr;
488 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
489 if (Result.TemplateArgs.empty()) {
490 Result.Rec = nullptr; // Error parsing value list.
494 if (Lex.getCode() != tgtok::greater) {
495 TokError("expected '>' in template value list");
496 Result.Rec = nullptr;
500 Result.RefRange.End = Lex.getLoc();
505 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
506 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
507 /// Record* on error.
509 /// SubMultiClassRef ::= MultiClassID
510 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
512 SubMultiClassReference TGParser::
513 ParseSubMultiClassReference(MultiClass *CurMC) {
514 SubMultiClassReference Result;
515 Result.RefRange.Start = Lex.getLoc();
517 Result.MC = ParseMultiClassID();
518 if (!Result.MC) return Result;
520 // If there is no template arg list, we're done.
521 if (Lex.getCode() != tgtok::less) {
522 Result.RefRange.End = Lex.getLoc();
525 Lex.Lex(); // Eat the '<'
527 if (Lex.getCode() == tgtok::greater) {
528 TokError("subclass reference requires a non-empty list of template values");
533 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
534 if (Result.TemplateArgs.empty()) {
535 Result.MC = nullptr; // Error parsing value list.
539 if (Lex.getCode() != tgtok::greater) {
540 TokError("expected '>' in template value list");
545 Result.RefRange.End = Lex.getLoc();
550 /// ParseRangePiece - Parse a bit/value range.
551 /// RangePiece ::= INTVAL
552 /// RangePiece ::= INTVAL '-' INTVAL
553 /// RangePiece ::= INTVAL INTVAL
554 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
555 if (Lex.getCode() != tgtok::IntVal) {
556 TokError("expected integer or bitrange");
559 int64_t Start = Lex.getCurIntVal();
563 return TokError("invalid range, cannot be negative");
565 switch (Lex.Lex()) { // eat first character.
567 Ranges.push_back(Start);
570 if (Lex.Lex() != tgtok::IntVal) {
571 TokError("expected integer value as end of range");
574 End = Lex.getCurIntVal();
577 End = -Lex.getCurIntVal();
581 return TokError("invalid range, cannot be negative");
586 for (; Start <= End; ++Start)
587 Ranges.push_back(Start);
589 for (; Start >= End; --Start)
590 Ranges.push_back(Start);
595 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
597 /// RangeList ::= RangePiece (',' RangePiece)*
599 std::vector<unsigned> TGParser::ParseRangeList() {
600 std::vector<unsigned> Result;
602 // Parse the first piece.
603 if (ParseRangePiece(Result))
604 return std::vector<unsigned>();
605 while (Lex.getCode() == tgtok::comma) {
606 Lex.Lex(); // Eat the comma.
608 // Parse the next range piece.
609 if (ParseRangePiece(Result))
610 return std::vector<unsigned>();
615 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
616 /// OptionalRangeList ::= '<' RangeList '>'
617 /// OptionalRangeList ::= /*empty*/
618 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
619 if (Lex.getCode() != tgtok::less)
622 SMLoc StartLoc = Lex.getLoc();
623 Lex.Lex(); // eat the '<'
625 // Parse the range list.
626 Ranges = ParseRangeList();
627 if (Ranges.empty()) return true;
629 if (Lex.getCode() != tgtok::greater) {
630 TokError("expected '>' at end of range list");
631 return Error(StartLoc, "to match this '<'");
633 Lex.Lex(); // eat the '>'.
637 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
638 /// OptionalBitList ::= '{' RangeList '}'
639 /// OptionalBitList ::= /*empty*/
640 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
641 if (Lex.getCode() != tgtok::l_brace)
644 SMLoc StartLoc = Lex.getLoc();
645 Lex.Lex(); // eat the '{'
647 // Parse the range list.
648 Ranges = ParseRangeList();
649 if (Ranges.empty()) return true;
651 if (Lex.getCode() != tgtok::r_brace) {
652 TokError("expected '}' at end of bit list");
653 return Error(StartLoc, "to match this '{'");
655 Lex.Lex(); // eat the '}'.
660 /// ParseType - Parse and return a tblgen type. This returns null on error.
662 /// Type ::= STRING // string type
663 /// Type ::= CODE // code type
664 /// Type ::= BIT // bit type
665 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
666 /// Type ::= INT // int type
667 /// Type ::= LIST '<' Type '>' // list<x> type
668 /// Type ::= DAG // dag type
669 /// Type ::= ClassID // Record Type
671 RecTy *TGParser::ParseType() {
672 switch (Lex.getCode()) {
673 default: TokError("Unknown token when expecting a type"); return nullptr;
674 case tgtok::String: Lex.Lex(); return StringRecTy::get();
675 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
676 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
677 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
678 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
680 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
683 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
684 TokError("expected '<' after bits type");
687 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
688 TokError("expected integer in bits<n> type");
691 uint64_t Val = Lex.getCurIntVal();
692 if (Lex.Lex() != tgtok::greater) { // Eat count.
693 TokError("expected '>' at end of bits<n> type");
696 Lex.Lex(); // Eat '>'
697 return BitsRecTy::get(Val);
700 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
701 TokError("expected '<' after list type");
704 Lex.Lex(); // Eat '<'
705 RecTy *SubType = ParseType();
706 if (!SubType) return nullptr;
708 if (Lex.getCode() != tgtok::greater) {
709 TokError("expected '>' at end of list<ty> type");
712 Lex.Lex(); // Eat '>'
713 return ListRecTy::get(SubType);
718 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
719 /// has already been read.
720 Init *TGParser::ParseIDValue(Record *CurRec,
721 const std::string &Name, SMLoc NameLoc,
724 if (const RecordVal *RV = CurRec->getValue(Name))
725 return VarInit::get(Name, RV->getType());
727 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
730 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
733 if (CurRec->isTemplateArg(TemplateArgName)) {
734 const RecordVal *RV = CurRec->getValue(TemplateArgName);
735 assert(RV && "Template arg doesn't exist??");
736 return VarInit::get(TemplateArgName, RV->getType());
741 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
744 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
745 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
746 assert(RV && "Template arg doesn't exist??");
747 return VarInit::get(MCName, RV->getType());
751 // If this is in a foreach loop, make sure it's not a loop iterator
752 for (const auto &L : Loops) {
753 VarInit *IterVar = dyn_cast<VarInit>(L.IterVar);
754 if (IterVar && IterVar->getName() == Name)
758 if (Mode == ParseNameMode)
759 return StringInit::get(Name);
761 if (Record *D = Records.getDef(Name))
762 return DefInit::get(D);
764 if (Mode == ParseValueMode) {
765 Error(NameLoc, "Variable not defined: '" + Name + "'");
769 return StringInit::get(Name);
772 /// ParseOperation - Parse an operator. This returns null on error.
774 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
776 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
777 switch (Lex.getCode()) {
779 TokError("unknown operation");
784 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
785 UnOpInit::UnaryOp Code;
786 RecTy *Type = nullptr;
788 switch (Lex.getCode()) {
789 default: llvm_unreachable("Unhandled code!");
791 Lex.Lex(); // eat the operation
792 Code = UnOpInit::CAST;
794 Type = ParseOperatorType();
797 TokError("did not get type for unary operator");
803 Lex.Lex(); // eat the operation
804 Code = UnOpInit::HEAD;
807 Lex.Lex(); // eat the operation
808 Code = UnOpInit::TAIL;
811 Lex.Lex(); // eat the operation
812 Code = UnOpInit::EMPTY;
813 Type = IntRecTy::get();
816 if (Lex.getCode() != tgtok::l_paren) {
817 TokError("expected '(' after unary operator");
820 Lex.Lex(); // eat the '('
822 Init *LHS = ParseValue(CurRec);
823 if (!LHS) return nullptr;
825 if (Code == UnOpInit::HEAD
826 || Code == UnOpInit::TAIL
827 || Code == UnOpInit::EMPTY) {
828 ListInit *LHSl = dyn_cast<ListInit>(LHS);
829 StringInit *LHSs = dyn_cast<StringInit>(LHS);
830 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
831 if (!LHSl && !LHSs && !LHSt) {
832 TokError("expected list or string type argument in unary operator");
836 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
837 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
838 if (!LType && !SType) {
839 TokError("expected list or string type argument in unary operator");
844 if (Code == UnOpInit::HEAD
845 || Code == UnOpInit::TAIL) {
846 if (!LHSl && !LHSt) {
847 TokError("expected list type argument in unary operator");
851 if (LHSl && LHSl->getSize() == 0) {
852 TokError("empty list argument in unary operator");
856 Init *Item = LHSl->getElement(0);
857 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
859 TokError("untyped list element in unary operator");
862 if (Code == UnOpInit::HEAD) {
863 Type = Itemt->getType();
865 Type = ListRecTy::get(Itemt->getType());
868 assert(LHSt && "expected list type argument in unary operator");
869 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
871 TokError("expected list type argument in unary operator");
874 if (Code == UnOpInit::HEAD) {
875 Type = LType->getElementType();
883 if (Lex.getCode() != tgtok::r_paren) {
884 TokError("expected ')' in unary operator");
887 Lex.Lex(); // eat the ')'
888 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
898 case tgtok::XListConcat:
899 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
900 tgtok::TokKind OpTok = Lex.getCode();
901 SMLoc OpLoc = Lex.getLoc();
902 Lex.Lex(); // eat the operation
904 BinOpInit::BinaryOp Code;
905 RecTy *Type = nullptr;
908 default: llvm_unreachable("Unhandled code!");
909 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
910 case tgtok::XADD: Code = BinOpInit::ADD; Type = IntRecTy::get(); break;
911 case tgtok::XAND: Code = BinOpInit::AND; Type = IntRecTy::get(); break;
912 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
913 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
914 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
915 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
916 case tgtok::XListConcat:
917 Code = BinOpInit::LISTCONCAT;
918 // We don't know the list type until we parse the first argument
920 case tgtok::XStrConcat:
921 Code = BinOpInit::STRCONCAT;
922 Type = StringRecTy::get();
926 if (Lex.getCode() != tgtok::l_paren) {
927 TokError("expected '(' after binary operator");
930 Lex.Lex(); // eat the '('
932 SmallVector<Init*, 2> InitList;
934 InitList.push_back(ParseValue(CurRec));
935 if (!InitList.back()) return nullptr;
937 while (Lex.getCode() == tgtok::comma) {
938 Lex.Lex(); // eat the ','
940 InitList.push_back(ParseValue(CurRec));
941 if (!InitList.back()) return nullptr;
944 if (Lex.getCode() != tgtok::r_paren) {
945 TokError("expected ')' in operator");
948 Lex.Lex(); // eat the ')'
950 // If we are doing !listconcat, we should know the type by now
951 if (OpTok == tgtok::XListConcat) {
952 if (VarInit *Arg0 = dyn_cast<VarInit>(InitList[0]))
953 Type = Arg0->getType();
954 else if (ListInit *Arg0 = dyn_cast<ListInit>(InitList[0]))
955 Type = Arg0->getType();
958 Error(OpLoc, "expected a list");
963 // We allow multiple operands to associative operators like !strconcat as
964 // shorthand for nesting them.
965 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT) {
966 while (InitList.size() > 2) {
967 Init *RHS = InitList.pop_back_val();
968 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
969 ->Fold(CurRec, CurMultiClass);
970 InitList.back() = RHS;
974 if (InitList.size() == 2)
975 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
976 ->Fold(CurRec, CurMultiClass);
978 Error(OpLoc, "expected two operands to operator");
983 case tgtok::XForEach:
984 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
985 TernOpInit::TernaryOp Code;
986 RecTy *Type = nullptr;
988 tgtok::TokKind LexCode = Lex.getCode();
989 Lex.Lex(); // eat the operation
991 default: llvm_unreachable("Unhandled code!");
993 Code = TernOpInit::IF;
995 case tgtok::XForEach:
996 Code = TernOpInit::FOREACH;
999 Code = TernOpInit::SUBST;
1002 if (Lex.getCode() != tgtok::l_paren) {
1003 TokError("expected '(' after ternary operator");
1006 Lex.Lex(); // eat the '('
1008 Init *LHS = ParseValue(CurRec);
1009 if (!LHS) return nullptr;
1011 if (Lex.getCode() != tgtok::comma) {
1012 TokError("expected ',' in ternary operator");
1015 Lex.Lex(); // eat the ','
1017 Init *MHS = ParseValue(CurRec, ItemType);
1021 if (Lex.getCode() != tgtok::comma) {
1022 TokError("expected ',' in ternary operator");
1025 Lex.Lex(); // eat the ','
1027 Init *RHS = ParseValue(CurRec, ItemType);
1031 if (Lex.getCode() != tgtok::r_paren) {
1032 TokError("expected ')' in binary operator");
1035 Lex.Lex(); // eat the ')'
1038 default: llvm_unreachable("Unhandled code!");
1040 RecTy *MHSTy = nullptr;
1041 RecTy *RHSTy = nullptr;
1043 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1044 MHSTy = MHSt->getType();
1045 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1046 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1047 if (isa<BitInit>(MHS))
1048 MHSTy = BitRecTy::get();
1050 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1051 RHSTy = RHSt->getType();
1052 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1053 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1054 if (isa<BitInit>(RHS))
1055 RHSTy = BitRecTy::get();
1057 // For UnsetInit, it's typed from the other hand.
1058 if (isa<UnsetInit>(MHS))
1060 if (isa<UnsetInit>(RHS))
1063 if (!MHSTy || !RHSTy) {
1064 TokError("could not get type for !if");
1068 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1070 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1073 TokError("inconsistent types for !if");
1078 case tgtok::XForEach: {
1079 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1081 TokError("could not get type for !foreach");
1084 Type = MHSt->getType();
1087 case tgtok::XSubst: {
1088 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1090 TokError("could not get type for !subst");
1093 Type = RHSt->getType();
1097 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1103 /// ParseOperatorType - Parse a type for an operator. This returns
1106 /// OperatorType ::= '<' Type '>'
1108 RecTy *TGParser::ParseOperatorType() {
1109 RecTy *Type = nullptr;
1111 if (Lex.getCode() != tgtok::less) {
1112 TokError("expected type name for operator");
1115 Lex.Lex(); // eat the <
1120 TokError("expected type name for operator");
1124 if (Lex.getCode() != tgtok::greater) {
1125 TokError("expected type name for operator");
1128 Lex.Lex(); // eat the >
1134 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1136 /// SimpleValue ::= IDValue
1137 /// SimpleValue ::= INTVAL
1138 /// SimpleValue ::= STRVAL+
1139 /// SimpleValue ::= CODEFRAGMENT
1140 /// SimpleValue ::= '?'
1141 /// SimpleValue ::= '{' ValueList '}'
1142 /// SimpleValue ::= ID '<' ValueListNE '>'
1143 /// SimpleValue ::= '[' ValueList ']'
1144 /// SimpleValue ::= '(' IDValue DagArgList ')'
1145 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1146 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1147 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1148 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1149 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1150 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1151 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1153 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1156 switch (Lex.getCode()) {
1157 default: TokError("Unknown token when parsing a value"); break;
1159 // This is a leading paste operation. This is deprecated but
1160 // still exists in some .td files. Ignore it.
1161 Lex.Lex(); // Skip '#'.
1162 return ParseSimpleValue(CurRec, ItemType, Mode);
1163 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1164 case tgtok::BinaryIntVal: {
1165 auto BinaryVal = Lex.getCurBinaryIntVal();
1166 SmallVector<Init*, 16> Bits(BinaryVal.second);
1167 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
1168 Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
1169 R = BitsInit::get(Bits);
1173 case tgtok::StrVal: {
1174 std::string Val = Lex.getCurStrVal();
1177 // Handle multiple consecutive concatenated strings.
1178 while (Lex.getCode() == tgtok::StrVal) {
1179 Val += Lex.getCurStrVal();
1183 R = StringInit::get(Val);
1186 case tgtok::CodeFragment:
1187 R = StringInit::get(Lex.getCurStrVal());
1190 case tgtok::question:
1191 R = UnsetInit::get();
1195 SMLoc NameLoc = Lex.getLoc();
1196 std::string Name = Lex.getCurStrVal();
1197 if (Lex.Lex() != tgtok::less) // consume the Id.
1198 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1200 // Value ::= ID '<' ValueListNE '>'
1201 if (Lex.Lex() == tgtok::greater) {
1202 TokError("expected non-empty value list");
1206 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1207 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1209 Record *Class = Records.getClass(Name);
1211 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1215 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1216 if (ValueList.empty()) return nullptr;
1218 if (Lex.getCode() != tgtok::greater) {
1219 TokError("expected '>' at end of value list");
1222 Lex.Lex(); // eat the '>'
1223 SMLoc EndLoc = Lex.getLoc();
1225 // Create the new record, set it as CurRec temporarily.
1226 auto NewRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), NameLoc,
1227 Records, /*IsAnonymous=*/true);
1228 Record *NewRec = NewRecOwner.get(); // Keep a copy since we may release.
1229 SubClassReference SCRef;
1230 SCRef.RefRange = SMRange(NameLoc, EndLoc);
1232 SCRef.TemplateArgs = ValueList;
1233 // Add info about the subclass to NewRec.
1234 if (AddSubClass(NewRec, SCRef))
1237 if (!CurMultiClass) {
1238 NewRec->resolveReferences();
1239 Records.addDef(std::move(NewRecOwner));
1241 // This needs to get resolved once the multiclass template arguments are
1242 // known before any use.
1243 NewRec->setResolveFirst(true);
1244 // Otherwise, we're inside a multiclass, add it to the multiclass.
1245 CurMultiClass->DefPrototypes.push_back(std::move(NewRecOwner));
1247 // Copy the template arguments for the multiclass into the def.
1248 for (Init *TArg : CurMultiClass->Rec.getTemplateArgs()) {
1249 const RecordVal *RV = CurMultiClass->Rec.getValue(TArg);
1250 assert(RV && "Template arg doesn't exist?");
1251 NewRec->addValue(*RV);
1254 // We can't return the prototype def here, instead return:
1255 // !cast<ItemType>(!strconcat(NAME, AnonName)).
1256 const RecordVal *MCNameRV = CurMultiClass->Rec.getValue("NAME");
1257 assert(MCNameRV && "multiclass record must have a NAME");
1259 return UnOpInit::get(UnOpInit::CAST,
1260 BinOpInit::get(BinOpInit::STRCONCAT,
1261 VarInit::get(MCNameRV->getName(),
1262 MCNameRV->getType()),
1263 NewRec->getNameInit(),
1264 StringRecTy::get()),
1265 Class->getDefInit()->getType());
1268 // The result of the expression is a reference to the new record.
1269 return DefInit::get(NewRec);
1271 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1272 SMLoc BraceLoc = Lex.getLoc();
1273 Lex.Lex(); // eat the '{'
1274 std::vector<Init*> Vals;
1276 if (Lex.getCode() != tgtok::r_brace) {
1277 Vals = ParseValueList(CurRec);
1278 if (Vals.empty()) return nullptr;
1280 if (Lex.getCode() != tgtok::r_brace) {
1281 TokError("expected '}' at end of bit list value");
1284 Lex.Lex(); // eat the '}'
1286 SmallVector<Init *, 16> NewBits;
1288 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1289 // first. We'll first read everything in to a vector, then we can reverse
1290 // it to get the bits in the correct order for the BitsInit value.
1291 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1292 // FIXME: The following two loops would not be duplicated
1293 // if the API was a little more orthogonal.
1295 // bits<n> values are allowed to initialize n bits.
1296 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
1297 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
1298 NewBits.push_back(BI->getBit((e - i) - 1));
1301 // bits<n> can also come from variable initializers.
1302 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
1303 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
1304 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
1305 NewBits.push_back(VI->getBit((e - i) - 1));
1308 // Fallthrough to try convert this to a bit.
1310 // All other values must be convertible to just a single bit.
1311 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1313 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1314 ") is not convertable to a bit");
1317 NewBits.push_back(Bit);
1319 std::reverse(NewBits.begin(), NewBits.end());
1320 return BitsInit::get(NewBits);
1322 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1323 Lex.Lex(); // eat the '['
1324 std::vector<Init*> Vals;
1326 RecTy *DeducedEltTy = nullptr;
1327 ListRecTy *GivenListTy = nullptr;
1330 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1333 raw_string_ostream ss(s);
1334 ss << "Type mismatch for list, expected list type, got "
1335 << ItemType->getAsString();
1339 GivenListTy = ListType;
1342 if (Lex.getCode() != tgtok::r_square) {
1343 Vals = ParseValueList(CurRec, nullptr,
1344 GivenListTy ? GivenListTy->getElementType() : nullptr);
1345 if (Vals.empty()) return nullptr;
1347 if (Lex.getCode() != tgtok::r_square) {
1348 TokError("expected ']' at end of list value");
1351 Lex.Lex(); // eat the ']'
1353 RecTy *GivenEltTy = nullptr;
1354 if (Lex.getCode() == tgtok::less) {
1355 // Optional list element type
1356 Lex.Lex(); // eat the '<'
1358 GivenEltTy = ParseType();
1360 // Couldn't parse element type
1364 if (Lex.getCode() != tgtok::greater) {
1365 TokError("expected '>' at end of list element type");
1368 Lex.Lex(); // eat the '>'
1372 RecTy *EltTy = nullptr;
1373 for (Init *V : Vals) {
1374 TypedInit *TArg = dyn_cast<TypedInit>(V);
1376 TokError("Untyped list element");
1380 EltTy = resolveTypes(EltTy, TArg->getType());
1382 TokError("Incompatible types in list elements");
1386 EltTy = TArg->getType();
1392 // Verify consistency
1393 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1394 TokError("Incompatible types in list elements");
1403 TokError("No type for list");
1406 DeducedEltTy = GivenListTy->getElementType();
1408 // Make sure the deduced type is compatible with the given type
1410 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1411 TokError("Element type mismatch for list");
1415 DeducedEltTy = EltTy;
1418 return ListInit::get(Vals, DeducedEltTy);
1420 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1421 Lex.Lex(); // eat the '('
1422 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1423 TokError("expected identifier in dag init");
1427 Init *Operator = ParseValue(CurRec);
1428 if (!Operator) return nullptr;
1430 // If the operator name is present, parse it.
1431 std::string OperatorName;
1432 if (Lex.getCode() == tgtok::colon) {
1433 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1434 TokError("expected variable name in dag operator");
1437 OperatorName = Lex.getCurStrVal();
1438 Lex.Lex(); // eat the VarName.
1441 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1442 if (Lex.getCode() != tgtok::r_paren) {
1443 DagArgs = ParseDagArgList(CurRec);
1444 if (DagArgs.empty()) return nullptr;
1447 if (Lex.getCode() != tgtok::r_paren) {
1448 TokError("expected ')' in dag init");
1451 Lex.Lex(); // eat the ')'
1453 return DagInit::get(Operator, OperatorName, DagArgs);
1459 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1460 case tgtok::XConcat:
1467 case tgtok::XListConcat:
1468 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1470 case tgtok::XForEach:
1471 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1472 return ParseOperation(CurRec, ItemType);
1479 /// ParseValue - Parse a tblgen value. This returns null on error.
1481 /// Value ::= SimpleValue ValueSuffix*
1482 /// ValueSuffix ::= '{' BitList '}'
1483 /// ValueSuffix ::= '[' BitList ']'
1484 /// ValueSuffix ::= '.' ID
1486 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1487 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1488 if (!Result) return nullptr;
1490 // Parse the suffixes now if present.
1492 switch (Lex.getCode()) {
1493 default: return Result;
1494 case tgtok::l_brace: {
1495 if (Mode == ParseNameMode || Mode == ParseForeachMode)
1496 // This is the beginning of the object body.
1499 SMLoc CurlyLoc = Lex.getLoc();
1500 Lex.Lex(); // eat the '{'
1501 std::vector<unsigned> Ranges = ParseRangeList();
1502 if (Ranges.empty()) return nullptr;
1504 // Reverse the bitlist.
1505 std::reverse(Ranges.begin(), Ranges.end());
1506 Result = Result->convertInitializerBitRange(Ranges);
1508 Error(CurlyLoc, "Invalid bit range for value");
1513 if (Lex.getCode() != tgtok::r_brace) {
1514 TokError("expected '}' at end of bit range list");
1520 case tgtok::l_square: {
1521 SMLoc SquareLoc = Lex.getLoc();
1522 Lex.Lex(); // eat the '['
1523 std::vector<unsigned> Ranges = ParseRangeList();
1524 if (Ranges.empty()) return nullptr;
1526 Result = Result->convertInitListSlice(Ranges);
1528 Error(SquareLoc, "Invalid range for list slice");
1533 if (Lex.getCode() != tgtok::r_square) {
1534 TokError("expected ']' at end of list slice");
1541 if (Lex.Lex() != tgtok::Id) { // eat the .
1542 TokError("expected field identifier after '.'");
1545 if (!Result->getFieldType(Lex.getCurStrVal())) {
1546 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1547 Result->getAsString() + "'");
1550 Result = FieldInit::get(Result, Lex.getCurStrVal());
1551 Lex.Lex(); // eat field name
1555 SMLoc PasteLoc = Lex.getLoc();
1557 // Create a !strconcat() operation, first casting each operand to
1558 // a string if necessary.
1560 TypedInit *LHS = dyn_cast<TypedInit>(Result);
1562 Error(PasteLoc, "LHS of paste is not typed!");
1566 if (LHS->getType() != StringRecTy::get()) {
1567 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1570 TypedInit *RHS = nullptr;
1572 Lex.Lex(); // Eat the '#'.
1573 switch (Lex.getCode()) {
1576 case tgtok::l_brace:
1577 // These are all of the tokens that can begin an object body.
1578 // Some of these can also begin values but we disallow those cases
1579 // because they are unlikely to be useful.
1581 // Trailing paste, concat with an empty string.
1582 RHS = StringInit::get("");
1586 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1587 RHS = dyn_cast<TypedInit>(RHSResult);
1589 Error(PasteLoc, "RHS of paste is not typed!");
1593 if (RHS->getType() != StringRecTy::get()) {
1594 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1600 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1601 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1607 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1609 /// DagArg ::= Value (':' VARNAME)?
1610 /// DagArg ::= VARNAME
1611 /// DagArgList ::= DagArg
1612 /// DagArgList ::= DagArgList ',' DagArg
1613 std::vector<std::pair<llvm::Init*, std::string> >
1614 TGParser::ParseDagArgList(Record *CurRec) {
1615 std::vector<std::pair<llvm::Init*, std::string> > Result;
1618 // DagArg ::= VARNAME
1619 if (Lex.getCode() == tgtok::VarName) {
1620 // A missing value is treated like '?'.
1621 Result.push_back(std::make_pair(UnsetInit::get(), Lex.getCurStrVal()));
1624 // DagArg ::= Value (':' VARNAME)?
1625 Init *Val = ParseValue(CurRec);
1627 return std::vector<std::pair<llvm::Init*, std::string> >();
1629 // If the variable name is present, add it.
1630 std::string VarName;
1631 if (Lex.getCode() == tgtok::colon) {
1632 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1633 TokError("expected variable name in dag literal");
1634 return std::vector<std::pair<llvm::Init*, std::string> >();
1636 VarName = Lex.getCurStrVal();
1637 Lex.Lex(); // eat the VarName.
1640 Result.push_back(std::make_pair(Val, VarName));
1642 if (Lex.getCode() != tgtok::comma) break;
1643 Lex.Lex(); // eat the ','
1650 /// ParseValueList - Parse a comma separated list of values, returning them as a
1651 /// vector. Note that this always expects to be able to parse at least one
1652 /// value. It returns an empty list if this is not possible.
1654 /// ValueList ::= Value (',' Value)
1656 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1658 std::vector<Init*> Result;
1659 RecTy *ItemType = EltTy;
1660 unsigned int ArgN = 0;
1661 if (ArgsRec && !EltTy) {
1662 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1663 if (TArgs.empty()) {
1664 TokError("template argument provided to non-template class");
1665 return std::vector<Init*>();
1667 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1669 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1672 assert(RV && "Template argument record not found??");
1673 ItemType = RV->getType();
1676 Result.push_back(ParseValue(CurRec, ItemType));
1677 if (!Result.back()) return std::vector<Init*>();
1679 while (Lex.getCode() == tgtok::comma) {
1680 Lex.Lex(); // Eat the comma
1682 if (ArgsRec && !EltTy) {
1683 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1684 if (ArgN >= TArgs.size()) {
1685 TokError("too many template arguments");
1686 return std::vector<Init*>();
1688 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1689 assert(RV && "Template argument record not found??");
1690 ItemType = RV->getType();
1693 Result.push_back(ParseValue(CurRec, ItemType));
1694 if (!Result.back()) return std::vector<Init*>();
1701 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1702 /// empty string on error. This can happen in a number of different context's,
1703 /// including within a def or in the template args for a def (which which case
1704 /// CurRec will be non-null) and within the template args for a multiclass (in
1705 /// which case CurRec will be null, but CurMultiClass will be set). This can
1706 /// also happen within a def that is within a multiclass, which will set both
1707 /// CurRec and CurMultiClass.
1709 /// Declaration ::= FIELD? Type ID ('=' Value)?
1711 Init *TGParser::ParseDeclaration(Record *CurRec,
1712 bool ParsingTemplateArgs) {
1713 // Read the field prefix if present.
1714 bool HasField = Lex.getCode() == tgtok::Field;
1715 if (HasField) Lex.Lex();
1717 RecTy *Type = ParseType();
1718 if (!Type) return nullptr;
1720 if (Lex.getCode() != tgtok::Id) {
1721 TokError("Expected identifier in declaration");
1725 SMLoc IdLoc = Lex.getLoc();
1726 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1729 if (ParsingTemplateArgs) {
1731 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1733 assert(CurMultiClass);
1736 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1741 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1744 // If a value is present, parse it.
1745 if (Lex.getCode() == tgtok::equal) {
1747 SMLoc ValLoc = Lex.getLoc();
1748 Init *Val = ParseValue(CurRec, Type);
1750 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1751 // Return the name, even if an error is thrown. This is so that we can
1752 // continue to make some progress, even without the value having been
1760 /// ParseForeachDeclaration - Read a foreach declaration, returning
1761 /// the name of the declared object or a NULL Init on error. Return
1762 /// the name of the parsed initializer list through ForeachListName.
1764 /// ForeachDeclaration ::= ID '=' '[' ValueList ']'
1765 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
1766 /// ForeachDeclaration ::= ID '=' RangePiece
1768 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1769 if (Lex.getCode() != tgtok::Id) {
1770 TokError("Expected identifier in foreach declaration");
1774 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1777 // If a value is present, parse it.
1778 if (Lex.getCode() != tgtok::equal) {
1779 TokError("Expected '=' in foreach declaration");
1782 Lex.Lex(); // Eat the '='
1784 RecTy *IterType = nullptr;
1785 std::vector<unsigned> Ranges;
1787 switch (Lex.getCode()) {
1788 default: TokError("Unknown token when expecting a range list"); return nullptr;
1789 case tgtok::l_square: { // '[' ValueList ']'
1790 Init *List = ParseSimpleValue(nullptr, nullptr, ParseForeachMode);
1791 ForeachListValue = dyn_cast<ListInit>(List);
1792 if (!ForeachListValue) {
1793 TokError("Expected a Value list");
1796 RecTy *ValueType = ForeachListValue->getType();
1797 ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1799 TokError("Value list is not of list type");
1802 IterType = ListType->getElementType();
1806 case tgtok::IntVal: { // RangePiece.
1807 if (ParseRangePiece(Ranges))
1812 case tgtok::l_brace: { // '{' RangeList '}'
1813 Lex.Lex(); // eat the '{'
1814 Ranges = ParseRangeList();
1815 if (Lex.getCode() != tgtok::r_brace) {
1816 TokError("expected '}' at end of bit range list");
1824 if (!Ranges.empty()) {
1825 assert(!IterType && "Type already initialized?");
1826 IterType = IntRecTy::get();
1827 std::vector<Init*> Values;
1828 for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
1829 Values.push_back(IntInit::get(Ranges[i]));
1830 ForeachListValue = ListInit::get(Values, IterType);
1836 return VarInit::get(DeclName, IterType);
1839 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1840 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1841 /// template args for a def, which may or may not be in a multiclass. If null,
1842 /// these are the template args for a multiclass.
1844 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1846 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1847 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1848 Lex.Lex(); // eat the '<'
1850 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1852 // Read the first declaration.
1853 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1857 TheRecToAddTo->addTemplateArg(TemplArg);
1859 while (Lex.getCode() == tgtok::comma) {
1860 Lex.Lex(); // eat the ','
1862 // Read the following declarations.
1863 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1866 TheRecToAddTo->addTemplateArg(TemplArg);
1869 if (Lex.getCode() != tgtok::greater)
1870 return TokError("expected '>' at end of template argument list");
1871 Lex.Lex(); // eat the '>'.
1876 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1878 /// BodyItem ::= Declaration ';'
1879 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1880 bool TGParser::ParseBodyItem(Record *CurRec) {
1881 if (Lex.getCode() != tgtok::Let) {
1882 if (!ParseDeclaration(CurRec, false))
1885 if (Lex.getCode() != tgtok::semi)
1886 return TokError("expected ';' after declaration");
1891 // LET ID OptionalRangeList '=' Value ';'
1892 if (Lex.Lex() != tgtok::Id)
1893 return TokError("expected field identifier after let");
1895 SMLoc IdLoc = Lex.getLoc();
1896 std::string FieldName = Lex.getCurStrVal();
1897 Lex.Lex(); // eat the field name.
1899 std::vector<unsigned> BitList;
1900 if (ParseOptionalBitList(BitList))
1902 std::reverse(BitList.begin(), BitList.end());
1904 if (Lex.getCode() != tgtok::equal)
1905 return TokError("expected '=' in let expression");
1906 Lex.Lex(); // eat the '='.
1908 RecordVal *Field = CurRec->getValue(FieldName);
1910 return TokError("Value '" + FieldName + "' unknown!");
1912 RecTy *Type = Field->getType();
1914 Init *Val = ParseValue(CurRec, Type);
1915 if (!Val) return true;
1917 if (Lex.getCode() != tgtok::semi)
1918 return TokError("expected ';' after let expression");
1921 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1924 /// ParseBody - Read the body of a class or def. Return true on error, false on
1928 /// Body ::= '{' BodyList '}'
1929 /// BodyList BodyItem*
1931 bool TGParser::ParseBody(Record *CurRec) {
1932 // If this is a null definition, just eat the semi and return.
1933 if (Lex.getCode() == tgtok::semi) {
1938 if (Lex.getCode() != tgtok::l_brace)
1939 return TokError("Expected ';' or '{' to start body");
1943 while (Lex.getCode() != tgtok::r_brace)
1944 if (ParseBodyItem(CurRec))
1952 /// \brief Apply the current let bindings to \a CurRec.
1953 /// \returns true on error, false otherwise.
1954 bool TGParser::ApplyLetStack(Record *CurRec) {
1955 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1956 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1957 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1958 LetStack[i][j].Bits, LetStack[i][j].Value))
1963 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1964 /// optional ClassList followed by a Body. CurRec is the current def or class
1965 /// that is being parsed.
1967 /// ObjectBody ::= BaseClassList Body
1968 /// BaseClassList ::= /*empty*/
1969 /// BaseClassList ::= ':' BaseClassListNE
1970 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1972 bool TGParser::ParseObjectBody(Record *CurRec) {
1973 // If there is a baseclass list, read it.
1974 if (Lex.getCode() == tgtok::colon) {
1977 // Read all of the subclasses.
1978 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1981 if (!SubClass.Rec) return true;
1984 if (AddSubClass(CurRec, SubClass))
1987 if (Lex.getCode() != tgtok::comma) break;
1988 Lex.Lex(); // eat ','.
1989 SubClass = ParseSubClassReference(CurRec, false);
1993 if (ApplyLetStack(CurRec))
1996 return ParseBody(CurRec);
1999 /// ParseDef - Parse and return a top level or multiclass def, return the record
2000 /// corresponding to it. This returns null on error.
2002 /// DefInst ::= DEF ObjectName ObjectBody
2004 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
2005 SMLoc DefLoc = Lex.getLoc();
2006 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
2007 Lex.Lex(); // Eat the 'def' token.
2009 // Parse ObjectName and make a record for it.
2010 std::unique_ptr<Record> CurRecOwner;
2011 Init *Name = ParseObjectName(CurMultiClass);
2013 CurRecOwner = make_unique<Record>(Name, DefLoc, Records);
2015 CurRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), DefLoc,
2016 Records, /*IsAnonymous=*/true);
2017 Record *CurRec = CurRecOwner.get(); // Keep a copy since we may release.
2019 if (!CurMultiClass && Loops.empty()) {
2020 // Top-level def definition.
2022 // Ensure redefinition doesn't happen.
2023 if (Records.getDef(CurRec->getNameInitAsString()))
2024 return Error(DefLoc, "def '" + CurRec->getNameInitAsString()+
2025 "' already defined");
2026 Records.addDef(std::move(CurRecOwner));
2028 if (ParseObjectBody(CurRec))
2030 } else if (CurMultiClass) {
2031 // Parse the body before adding this prototype to the DefPrototypes vector.
2032 // That way implicit definitions will be added to the DefPrototypes vector
2033 // before this object, instantiated prior to defs derived from this object,
2034 // and this available for indirect name resolution when defs derived from
2035 // this object are instantiated.
2036 if (ParseObjectBody(CurRec))
2039 // Otherwise, a def inside a multiclass, add it to the multiclass.
2040 for (const auto &Proto : CurMultiClass->DefPrototypes)
2041 if (Proto->getNameInit() == CurRec->getNameInit())
2042 return Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
2043 "' already defined in this multiclass!");
2044 CurMultiClass->DefPrototypes.push_back(std::move(CurRecOwner));
2045 } else if (ParseObjectBody(CurRec)) {
2049 if (!CurMultiClass) // Def's in multiclasses aren't really defs.
2050 // See Record::setName(). This resolve step will see any new name
2051 // for the def that might have been created when resolving
2052 // inheritance, values and arguments above.
2053 CurRec->resolveReferences();
2055 // If ObjectBody has template arguments, it's an error.
2056 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
2058 if (CurMultiClass) {
2059 // Copy the template arguments for the multiclass into the def.
2060 for (Init *TArg : CurMultiClass->Rec.getTemplateArgs()) {
2061 const RecordVal *RV = CurMultiClass->Rec.getValue(TArg);
2062 assert(RV && "Template arg doesn't exist?");
2063 CurRec->addValue(*RV);
2067 if (ProcessForeachDefs(CurRec, DefLoc)) {
2068 return Error(DefLoc, "Could not process loops for def" +
2069 CurRec->getNameInitAsString());
2075 /// ParseForeach - Parse a for statement. Return the record corresponding
2076 /// to it. This returns true on error.
2078 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2079 /// Foreach ::= FOREACH Declaration IN Object
2081 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2082 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2083 Lex.Lex(); // Eat the 'for' token.
2085 // Make a temporary object to record items associated with the for
2087 ListInit *ListValue = nullptr;
2088 VarInit *IterName = ParseForeachDeclaration(ListValue);
2090 return TokError("expected declaration in for");
2092 if (Lex.getCode() != tgtok::In)
2093 return TokError("Unknown tok");
2094 Lex.Lex(); // Eat the in
2096 // Create a loop object and remember it.
2097 Loops.push_back(ForeachLoop(IterName, ListValue));
2099 if (Lex.getCode() != tgtok::l_brace) {
2100 // FOREACH Declaration IN Object
2101 if (ParseObject(CurMultiClass))
2105 SMLoc BraceLoc = Lex.getLoc();
2106 // Otherwise, this is a group foreach.
2107 Lex.Lex(); // eat the '{'.
2109 // Parse the object list.
2110 if (ParseObjectList(CurMultiClass))
2113 if (Lex.getCode() != tgtok::r_brace) {
2114 TokError("expected '}' at end of foreach command");
2115 return Error(BraceLoc, "to match this '{'");
2117 Lex.Lex(); // Eat the }
2120 // We've processed everything in this loop.
2126 /// ParseClass - Parse a tblgen class definition.
2128 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2130 bool TGParser::ParseClass() {
2131 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2134 if (Lex.getCode() != tgtok::Id)
2135 return TokError("expected class name after 'class' keyword");
2137 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2139 // If the body was previously defined, this is an error.
2140 if (CurRec->getValues().size() > 1 || // Account for NAME.
2141 !CurRec->getSuperClasses().empty() ||
2142 !CurRec->getTemplateArgs().empty())
2143 return TokError("Class '" + CurRec->getNameInitAsString()
2144 + "' already defined");
2146 // If this is the first reference to this class, create and add it.
2148 llvm::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records);
2149 CurRec = NewRec.get();
2150 Records.addClass(std::move(NewRec));
2152 Lex.Lex(); // eat the name.
2154 // If there are template args, parse them.
2155 if (Lex.getCode() == tgtok::less)
2156 if (ParseTemplateArgList(CurRec))
2159 // Finally, parse the object body.
2160 return ParseObjectBody(CurRec);
2163 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2166 /// LetList ::= LetItem (',' LetItem)*
2167 /// LetItem ::= ID OptionalRangeList '=' Value
2169 std::vector<LetRecord> TGParser::ParseLetList() {
2170 std::vector<LetRecord> Result;
2173 if (Lex.getCode() != tgtok::Id) {
2174 TokError("expected identifier in let definition");
2175 return std::vector<LetRecord>();
2177 std::string Name = Lex.getCurStrVal();
2178 SMLoc NameLoc = Lex.getLoc();
2179 Lex.Lex(); // Eat the identifier.
2181 // Check for an optional RangeList.
2182 std::vector<unsigned> Bits;
2183 if (ParseOptionalRangeList(Bits))
2184 return std::vector<LetRecord>();
2185 std::reverse(Bits.begin(), Bits.end());
2187 if (Lex.getCode() != tgtok::equal) {
2188 TokError("expected '=' in let expression");
2189 return std::vector<LetRecord>();
2191 Lex.Lex(); // eat the '='.
2193 Init *Val = ParseValue(nullptr);
2194 if (!Val) return std::vector<LetRecord>();
2196 // Now that we have everything, add the record.
2197 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2199 if (Lex.getCode() != tgtok::comma)
2201 Lex.Lex(); // eat the comma.
2205 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2206 /// different related productions. This works inside multiclasses too.
2208 /// Object ::= LET LetList IN '{' ObjectList '}'
2209 /// Object ::= LET LetList IN Object
2211 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2212 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2215 // Add this entry to the let stack.
2216 std::vector<LetRecord> LetInfo = ParseLetList();
2217 if (LetInfo.empty()) return true;
2218 LetStack.push_back(std::move(LetInfo));
2220 if (Lex.getCode() != tgtok::In)
2221 return TokError("expected 'in' at end of top-level 'let'");
2224 // If this is a scalar let, just handle it now
2225 if (Lex.getCode() != tgtok::l_brace) {
2226 // LET LetList IN Object
2227 if (ParseObject(CurMultiClass))
2229 } else { // Object ::= LETCommand '{' ObjectList '}'
2230 SMLoc BraceLoc = Lex.getLoc();
2231 // Otherwise, this is a group let.
2232 Lex.Lex(); // eat the '{'.
2234 // Parse the object list.
2235 if (ParseObjectList(CurMultiClass))
2238 if (Lex.getCode() != tgtok::r_brace) {
2239 TokError("expected '}' at end of top level let command");
2240 return Error(BraceLoc, "to match this '{'");
2245 // Outside this let scope, this let block is not active.
2246 LetStack.pop_back();
2250 /// ParseMultiClass - Parse a multiclass definition.
2252 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2253 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2254 /// MultiClassObject ::= DefInst
2255 /// MultiClassObject ::= MultiClassInst
2256 /// MultiClassObject ::= DefMInst
2257 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
2258 /// MultiClassObject ::= LETCommand Object
2260 bool TGParser::ParseMultiClass() {
2261 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2262 Lex.Lex(); // Eat the multiclass token.
2264 if (Lex.getCode() != tgtok::Id)
2265 return TokError("expected identifier after multiclass for name");
2266 std::string Name = Lex.getCurStrVal();
2269 MultiClasses.insert(std::make_pair(Name,
2270 llvm::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
2273 return TokError("multiclass '" + Name + "' already defined");
2275 CurMultiClass = Result.first->second.get();
2276 Lex.Lex(); // Eat the identifier.
2278 // If there are template args, parse them.
2279 if (Lex.getCode() == tgtok::less)
2280 if (ParseTemplateArgList(nullptr))
2283 bool inherits = false;
2285 // If there are submulticlasses, parse them.
2286 if (Lex.getCode() == tgtok::colon) {
2291 // Read all of the submulticlasses.
2292 SubMultiClassReference SubMultiClass =
2293 ParseSubMultiClassReference(CurMultiClass);
2296 if (!SubMultiClass.MC) return true;
2299 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2302 if (Lex.getCode() != tgtok::comma) break;
2303 Lex.Lex(); // eat ','.
2304 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2308 if (Lex.getCode() != tgtok::l_brace) {
2310 return TokError("expected '{' in multiclass definition");
2311 if (Lex.getCode() != tgtok::semi)
2312 return TokError("expected ';' in multiclass definition");
2313 Lex.Lex(); // eat the ';'.
2315 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2316 return TokError("multiclass must contain at least one def");
2318 while (Lex.getCode() != tgtok::r_brace) {
2319 switch (Lex.getCode()) {
2321 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2325 case tgtok::Foreach:
2326 if (ParseObject(CurMultiClass))
2331 Lex.Lex(); // eat the '}'.
2334 CurMultiClass = nullptr;
2339 InstantiateMulticlassDef(MultiClass &MC,
2342 SMRange DefmPrefixRange) {
2343 // We need to preserve DefProto so it can be reused for later
2344 // instantiations, so create a new Record to inherit from it.
2346 // Add in the defm name. If the defm prefix is empty, give each
2347 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2348 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2351 bool IsAnonymous = false;
2353 DefmPrefix = StringInit::get(GetNewAnonymousName());
2357 Init *DefName = DefProto->getNameInit();
2359 StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2361 if (DefNameString) {
2362 // We have a fully expanded string so there are no operators to
2363 // resolve. We should concatenate the given prefix and name.
2365 BinOpInit::get(BinOpInit::STRCONCAT,
2366 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2367 StringRecTy::get())->Fold(DefProto, &MC),
2368 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2371 // Make a trail of SMLocs from the multiclass instantiations.
2372 SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
2373 Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2374 auto CurRec = make_unique<Record>(DefName, Locs, Records, IsAnonymous);
2376 SubClassReference Ref;
2377 Ref.RefRange = DefmPrefixRange;
2379 AddSubClass(CurRec.get(), Ref);
2381 // Set the value for NAME. We don't resolve references to it 'til later,
2382 // though, so that uses in nested multiclass names don't get
2384 if (SetValue(CurRec.get(), Ref.RefRange.Start, "NAME",
2385 std::vector<unsigned>(), DefmPrefix)) {
2386 Error(DefmPrefixRange.Start, "Could not resolve "
2387 + CurRec->getNameInitAsString() + ":NAME to '"
2388 + DefmPrefix->getAsUnquotedString() + "'");
2392 // If the DefNameString didn't resolve, we probably have a reference to
2393 // NAME and need to replace it. We need to do at least this much greedily,
2394 // otherwise nested multiclasses will end up with incorrect NAME expansions.
2395 if (!DefNameString) {
2396 RecordVal *DefNameRV = CurRec->getValue("NAME");
2397 CurRec->resolveReferencesTo(DefNameRV);
2400 if (!CurMultiClass) {
2401 // Now that we're at the top level, resolve all NAME references
2402 // in the resultant defs that weren't in the def names themselves.
2403 RecordVal *DefNameRV = CurRec->getValue("NAME");
2404 CurRec->resolveReferencesTo(DefNameRV);
2406 // Now that NAME references are resolved and we're at the top level of
2407 // any multiclass expansions, add the record to the RecordKeeper. If we are
2408 // currently in a multiclass, it means this defm appears inside a
2409 // multiclass and its name won't be fully resolvable until we see
2410 // the top-level defm. Therefore, we don't add this to the
2411 // RecordKeeper at this point. If we did we could get duplicate
2412 // defs as more than one probably refers to NAME or some other
2413 // common internal placeholder.
2415 // Ensure redefinition doesn't happen.
2416 if (Records.getDef(CurRec->getNameInitAsString())) {
2417 Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
2418 "' already defined, instantiating defm with subdef '" +
2419 DefProto->getNameInitAsString() + "'");
2423 Record *CurRecSave = CurRec.get(); // Keep a copy before we release.
2424 Records.addDef(std::move(CurRec));
2428 // FIXME This is bad but the ownership transfer to caller is pretty messy.
2429 // The unique_ptr in this function at least protects the exits above.
2430 return CurRec.release();
2433 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2435 SMLoc DefmPrefixLoc,
2437 const std::vector<Init *> &TArgs,
2438 std::vector<Init *> &TemplateVals,
2440 // Loop over all of the template arguments, setting them to the specified
2441 // value or leaving them as the default if necessary.
2442 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2443 // Check if a value is specified for this temp-arg.
2444 if (i < TemplateVals.size()) {
2446 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2451 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2455 CurRec->removeValue(TArgs[i]);
2457 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2458 return Error(SubClassLoc, "value not specified for template argument #"+
2459 utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2460 + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2467 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2470 SMLoc DefmPrefixLoc) {
2471 // If the mdef is inside a 'let' expression, add to each def.
2472 if (ApplyLetStack(CurRec))
2473 return Error(DefmPrefixLoc, "when instantiating this defm");
2475 // Don't create a top level definition for defm inside multiclasses,
2476 // instead, only update the prototypes and bind the template args
2477 // with the new created definition.
2480 for (const auto &Proto : CurMultiClass->DefPrototypes)
2481 if (Proto->getNameInit() == CurRec->getNameInit())
2482 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2483 "' already defined in this multiclass!");
2484 CurMultiClass->DefPrototypes.push_back(std::unique_ptr<Record>(CurRec));
2486 // Copy the template arguments for the multiclass into the new def.
2487 for (Init * TA : CurMultiClass->Rec.getTemplateArgs()) {
2488 const RecordVal *RV = CurMultiClass->Rec.getValue(TA);
2489 assert(RV && "Template arg doesn't exist?");
2490 CurRec->addValue(*RV);
2496 /// ParseDefm - Parse the instantiation of a multiclass.
2498 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2500 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2501 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2502 SMLoc DefmLoc = Lex.getLoc();
2503 Init *DefmPrefix = nullptr;
2505 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2506 DefmPrefix = ParseObjectName(CurMultiClass);
2509 SMLoc DefmPrefixEndLoc = Lex.getLoc();
2510 if (Lex.getCode() != tgtok::colon)
2511 return TokError("expected ':' after defm identifier");
2513 // Keep track of the new generated record definitions.
2514 std::vector<Record*> NewRecDefs;
2516 // This record also inherits from a regular class (non-multiclass)?
2517 bool InheritFromClass = false;
2522 SMLoc SubClassLoc = Lex.getLoc();
2523 SubClassReference Ref = ParseSubClassReference(nullptr, true);
2526 if (!Ref.Rec) return true;
2528 // To instantiate a multiclass, we need to first get the multiclass, then
2529 // instantiate each def contained in the multiclass with the SubClassRef
2530 // template parameters.
2531 MultiClass *MC = MultiClasses[Ref.Rec->getName()].get();
2532 assert(MC && "Didn't lookup multiclass correctly?");
2533 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2535 // Verify that the correct number of template arguments were specified.
2536 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2537 if (TArgs.size() < TemplateVals.size())
2538 return Error(SubClassLoc,
2539 "more template args specified than multiclass expects");
2541 // Loop over all the def's in the multiclass, instantiating each one.
2542 for (const std::unique_ptr<Record> &DefProto : MC->DefPrototypes) {
2543 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto.get(), DefmPrefix,
2549 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
2550 TArgs, TemplateVals, true/*Delete args*/))
2551 return Error(SubClassLoc, "could not instantiate def");
2553 if (ResolveMulticlassDef(*MC, CurRec, DefProto.get(), DefmLoc))
2554 return Error(SubClassLoc, "could not instantiate def");
2556 // Defs that can be used by other definitions should be fully resolved
2558 if (DefProto->isResolveFirst() && !CurMultiClass) {
2559 CurRec->resolveReferences();
2560 CurRec->setResolveFirst(false);
2562 NewRecDefs.push_back(CurRec);
2566 if (Lex.getCode() != tgtok::comma) break;
2567 Lex.Lex(); // eat ','.
2569 if (Lex.getCode() != tgtok::Id)
2570 return TokError("expected identifier");
2572 SubClassLoc = Lex.getLoc();
2574 // A defm can inherit from regular classes (non-multiclass) as
2575 // long as they come in the end of the inheritance list.
2576 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
2578 if (InheritFromClass)
2581 Ref = ParseSubClassReference(nullptr, true);
2584 if (InheritFromClass) {
2585 // Process all the classes to inherit as if they were part of a
2586 // regular 'def' and inherit all record values.
2587 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
2590 if (!SubClass.Rec) return true;
2592 // Get the expanded definition prototypes and teach them about
2593 // the record values the current class to inherit has
2594 for (Record *CurRec : NewRecDefs) {
2596 if (AddSubClass(CurRec, SubClass))
2599 if (ApplyLetStack(CurRec))
2603 if (Lex.getCode() != tgtok::comma) break;
2604 Lex.Lex(); // eat ','.
2605 SubClass = ParseSubClassReference(nullptr, false);
2610 for (Record *CurRec : NewRecDefs)
2611 // See Record::setName(). This resolve step will see any new
2612 // name for the def that might have been created when resolving
2613 // inheritance, values and arguments above.
2614 CurRec->resolveReferences();
2616 if (Lex.getCode() != tgtok::semi)
2617 return TokError("expected ';' at end of defm");
2624 /// Object ::= ClassInst
2625 /// Object ::= DefInst
2626 /// Object ::= MultiClassInst
2627 /// Object ::= DefMInst
2628 /// Object ::= LETCommand '{' ObjectList '}'
2629 /// Object ::= LETCommand Object
2630 bool TGParser::ParseObject(MultiClass *MC) {
2631 switch (Lex.getCode()) {
2633 return TokError("Expected class, def, defm, multiclass or let definition");
2634 case tgtok::Let: return ParseTopLevelLet(MC);
2635 case tgtok::Def: return ParseDef(MC);
2636 case tgtok::Foreach: return ParseForeach(MC);
2637 case tgtok::Defm: return ParseDefm(MC);
2638 case tgtok::Class: return ParseClass();
2639 case tgtok::MultiClass: return ParseMultiClass();
2644 /// ObjectList :== Object*
2645 bool TGParser::ParseObjectList(MultiClass *MC) {
2646 while (isObjectStart(Lex.getCode())) {
2647 if (ParseObject(MC))
2653 bool TGParser::ParseFile() {
2654 Lex.Lex(); // Prime the lexer.
2655 if (ParseObjectList()) return true;
2657 // If we have unread input at the end of the file, report it.
2658 if (Lex.getCode() == tgtok::Eof)
2661 return TokError("Unexpected input at top level");