1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implement the Parser for TableGen.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/TableGen/Record.h"
23 //===----------------------------------------------------------------------===//
24 // Support Code for the Semantic Actions.
25 //===----------------------------------------------------------------------===//
28 struct SubClassReference {
31 std::vector<Init*> TemplateArgs;
32 SubClassReference() : Rec(nullptr) {}
34 bool isInvalid() const { return Rec == nullptr; }
37 struct SubMultiClassReference {
40 std::vector<Init*> TemplateArgs;
41 SubMultiClassReference() : MC(nullptr) {}
43 bool isInvalid() const { return MC == nullptr; }
47 void SubMultiClassReference::dump() const {
48 errs() << "Multiclass:\n";
52 errs() << "Template args:\n";
53 for (std::vector<Init *>::const_iterator i = TemplateArgs.begin(),
54 iend = TemplateArgs.end();
61 } // end namespace llvm
63 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
65 CurRec = &CurMultiClass->Rec;
67 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
68 // The value already exists in the class, treat this as a set.
69 if (ERV->setValue(RV.getValue()))
70 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
71 RV.getType()->getAsString() + "' is incompatible with " +
72 "previous definition of type '" +
73 ERV->getType()->getAsString() + "'");
81 /// Return true on error, false on success.
82 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
83 const std::vector<unsigned> &BitList, Init *V) {
86 if (!CurRec) CurRec = &CurMultiClass->Rec;
88 RecordVal *RV = CurRec->getValue(ValName);
90 return Error(Loc, "Value '" + ValName->getAsUnquotedString()
93 // Do not allow assignments like 'X = X'. This will just cause infinite loops
94 // in the resolution machinery.
96 if (VarInit *VI = dyn_cast<VarInit>(V))
97 if (VI->getNameInit() == ValName)
100 // If we are assigning to a subset of the bits in the value... then we must be
101 // assigning to a field of BitsRecTy, which must have a BitsInit
104 if (!BitList.empty()) {
105 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
107 return Error(Loc, "Value '" + ValName->getAsUnquotedString()
108 + "' is not a bits type");
110 // Convert the incoming value to a bits type of the appropriate size...
111 Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size()));
113 return Error(Loc, "Initializer is not compatible with bit range");
116 // We should have a BitsInit type now.
117 BitsInit *BInit = dyn_cast<BitsInit>(BI);
118 assert(BInit != nullptr);
120 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
122 // Loop over bits, assigning values as appropriate.
123 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
124 unsigned Bit = BitList[i];
126 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
127 ValName->getAsUnquotedString() + "' more than once");
128 NewBits[Bit] = BInit->getBit(i);
131 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
133 NewBits[i] = CurVal->getBit(i);
135 V = BitsInit::get(NewBits);
138 if (RV->setValue(V)) {
139 std::string InitType = "";
140 if (BitsInit *BI = dyn_cast<BitsInit>(V)) {
141 InitType = (Twine("' of type bit initializer with length ") +
142 Twine(BI->getNumBits())).str();
144 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of type '"
145 + RV->getType()->getAsString() +
146 "' is incompatible with initializer '" + V->getAsString()
153 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
154 /// args as SubClass's template arguments.
155 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
156 Record *SC = SubClass.Rec;
157 // Add all of the values in the subclass into the current class.
158 const std::vector<RecordVal> &Vals = SC->getValues();
159 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
160 if (AddValue(CurRec, SubClass.RefRange.Start, Vals[i]))
163 const std::vector<Init *> &TArgs = SC->getTemplateArgs();
165 // Ensure that an appropriate number of template arguments are specified.
166 if (TArgs.size() < SubClass.TemplateArgs.size())
167 return Error(SubClass.RefRange.Start,
168 "More template args specified than expected");
170 // Loop over all of the template arguments, setting them to the specified
171 // value or leaving them as the default if necessary.
172 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
173 if (i < SubClass.TemplateArgs.size()) {
174 // If a value is specified for this template arg, set it now.
175 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
176 std::vector<unsigned>(), SubClass.TemplateArgs[i]))
180 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
183 CurRec->removeValue(TArgs[i]);
185 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
186 return Error(SubClass.RefRange.Start,
187 "Value not specified for template argument #"
188 + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
189 + ") of subclass '" + SC->getNameInitAsString() + "'!");
193 // Since everything went well, we can now set the "superclass" list for the
195 const std::vector<Record*> &SCs = SC->getSuperClasses();
196 ArrayRef<SMRange> SCRanges = SC->getSuperClassRanges();
197 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
198 if (CurRec->isSubClassOf(SCs[i]))
199 return Error(SubClass.RefRange.Start,
200 "Already subclass of '" + SCs[i]->getName() + "'!\n");
201 CurRec->addSuperClass(SCs[i], SCRanges[i]);
204 if (CurRec->isSubClassOf(SC))
205 return Error(SubClass.RefRange.Start,
206 "Already subclass of '" + SC->getName() + "'!\n");
207 CurRec->addSuperClass(SC, SubClass.RefRange);
211 /// AddSubMultiClass - Add SubMultiClass as a subclass to
212 /// CurMC, resolving its template args as SubMultiClass's
213 /// template arguments.
214 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
215 SubMultiClassReference &SubMultiClass) {
216 MultiClass *SMC = SubMultiClass.MC;
217 Record *CurRec = &CurMC->Rec;
219 const std::vector<RecordVal> &MCVals = CurRec->getValues();
221 // Add all of the values in the subclass into the current class.
222 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
223 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
224 if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVals[i]))
227 int newDefStart = CurMC->DefPrototypes.size();
229 // Add all of the defs in the subclass into the current multiclass.
230 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
231 iend = SMC->DefPrototypes.end();
234 // Clone the def and add it to the current multiclass
235 Record *NewDef = new Record(**i);
237 // Add all of the values in the superclass into the current def.
238 for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
239 if (AddValue(NewDef, SubMultiClass.RefRange.Start, MCVals[i])) {
244 CurMC->DefPrototypes.push_back(NewDef);
247 const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
249 // Ensure that an appropriate number of template arguments are
251 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
252 return Error(SubMultiClass.RefRange.Start,
253 "More template args specified than expected");
255 // Loop over all of the template arguments, setting them to the specified
256 // value or leaving them as the default if necessary.
257 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
258 if (i < SubMultiClass.TemplateArgs.size()) {
259 // If a value is specified for this template arg, set it in the
261 if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i],
262 std::vector<unsigned>(),
263 SubMultiClass.TemplateArgs[i]))
267 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
270 CurRec->removeValue(SMCTArgs[i]);
272 // If a value is specified for this template arg, set it in the
274 for (MultiClass::RecordVector::iterator j =
275 CurMC->DefPrototypes.begin() + newDefStart,
276 jend = CurMC->DefPrototypes.end();
281 if (SetValue(Def, SubMultiClass.RefRange.Start, SMCTArgs[i],
282 std::vector<unsigned>(),
283 SubMultiClass.TemplateArgs[i]))
287 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
290 Def->removeValue(SMCTArgs[i]);
292 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
293 return Error(SubMultiClass.RefRange.Start,
294 "Value not specified for template argument #"
295 + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
296 + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
303 /// ProcessForeachDefs - Given a record, apply all of the variable
304 /// values in all surrounding foreach loops, creating new records for
305 /// each combination of values.
306 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
310 // We want to instantiate a new copy of CurRec for each combination
311 // of nested loop iterator values. We don't want top instantiate
312 // any copies until we have values for each loop iterator.
314 return ProcessForeachDefs(CurRec, Loc, IterVals);
317 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
318 /// apply each of the variable values in this loop and then process
320 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
321 // Recursively build a tuple of iterator values.
322 if (IterVals.size() != Loops.size()) {
323 assert(IterVals.size() < Loops.size());
324 ForeachLoop &CurLoop = Loops[IterVals.size()];
325 ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
327 Error(Loc, "Loop list is not a list");
331 // Process each value.
332 for (int64_t i = 0; i < List->getSize(); ++i) {
333 Init *ItemVal = List->resolveListElementReference(*CurRec, nullptr, i);
334 IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
335 if (ProcessForeachDefs(CurRec, Loc, IterVals))
342 // This is the bottom of the recursion. We have all of the iterator values
343 // for this point in the iteration space. Instantiate a new record to
344 // reflect this combination of values.
345 Record *IterRec = new Record(*CurRec);
347 // Set the iterator values now.
348 for (unsigned i = 0, e = IterVals.size(); i != e; ++i) {
349 VarInit *IterVar = IterVals[i].IterVar;
350 TypedInit *IVal = dyn_cast<TypedInit>(IterVals[i].IterValue);
352 Error(Loc, "foreach iterator value is untyped");
357 IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
359 if (SetValue(IterRec, Loc, IterVar->getName(),
360 std::vector<unsigned>(), IVal)) {
361 Error(Loc, "when instantiating this def");
367 IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
370 IterRec->removeValue(IterVar->getName());
373 if (Records.getDef(IterRec->getNameInitAsString())) {
374 // If this record is anonymous, it's no problem, just generate a new name
375 if (IterRec->isAnonymous())
376 IterRec->setName(GetNewAnonymousName());
378 Error(Loc, "def already exists: " + IterRec->getNameInitAsString());
384 Records.addDef(IterRec);
385 IterRec->resolveReferences();
389 //===----------------------------------------------------------------------===//
391 //===----------------------------------------------------------------------===//
393 /// isObjectStart - Return true if this is a valid first token for an Object.
394 static bool isObjectStart(tgtok::TokKind K) {
395 return K == tgtok::Class || K == tgtok::Def ||
396 K == tgtok::Defm || K == tgtok::Let ||
397 K == tgtok::MultiClass || K == tgtok::Foreach;
400 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
402 std::string TGParser::GetNewAnonymousName() {
403 unsigned Tmp = AnonCounter++; // MSVC2012 ICEs without this.
404 return "anonymous_" + utostr(Tmp);
407 /// ParseObjectName - If an object name is specified, return it. Otherwise,
409 /// ObjectName ::= Value [ '#' Value ]*
410 /// ObjectName ::= /*empty*/
412 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
413 switch (Lex.getCode()) {
417 // These are all of the tokens that can begin an object body.
418 // Some of these can also begin values but we disallow those cases
419 // because they are unlikely to be useful.
425 Record *CurRec = nullptr;
427 CurRec = &CurMultiClass->Rec;
429 RecTy *Type = nullptr;
431 const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
433 TokError("Record name is not typed!");
436 Type = CurRecName->getType();
439 return ParseValue(CurRec, Type, ParseNameMode);
442 /// ParseClassID - Parse and resolve a reference to a class name. This returns
447 Record *TGParser::ParseClassID() {
448 if (Lex.getCode() != tgtok::Id) {
449 TokError("expected name for ClassID");
453 Record *Result = Records.getClass(Lex.getCurStrVal());
455 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
461 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
462 /// This returns null on error.
464 /// MultiClassID ::= ID
466 MultiClass *TGParser::ParseMultiClassID() {
467 if (Lex.getCode() != tgtok::Id) {
468 TokError("expected name for MultiClassID");
472 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
474 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
480 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
481 /// subclass. This returns a SubClassRefTy with a null Record* on error.
483 /// SubClassRef ::= ClassID
484 /// SubClassRef ::= ClassID '<' ValueList '>'
486 SubClassReference TGParser::
487 ParseSubClassReference(Record *CurRec, bool isDefm) {
488 SubClassReference Result;
489 Result.RefRange.Start = Lex.getLoc();
492 if (MultiClass *MC = ParseMultiClassID())
493 Result.Rec = &MC->Rec;
495 Result.Rec = ParseClassID();
497 if (!Result.Rec) return Result;
499 // If there is no template arg list, we're done.
500 if (Lex.getCode() != tgtok::less) {
501 Result.RefRange.End = Lex.getLoc();
504 Lex.Lex(); // Eat the '<'
506 if (Lex.getCode() == tgtok::greater) {
507 TokError("subclass reference requires a non-empty list of template values");
508 Result.Rec = nullptr;
512 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
513 if (Result.TemplateArgs.empty()) {
514 Result.Rec = nullptr; // Error parsing value list.
518 if (Lex.getCode() != tgtok::greater) {
519 TokError("expected '>' in template value list");
520 Result.Rec = nullptr;
524 Result.RefRange.End = Lex.getLoc();
529 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
530 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
531 /// Record* on error.
533 /// SubMultiClassRef ::= MultiClassID
534 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
536 SubMultiClassReference TGParser::
537 ParseSubMultiClassReference(MultiClass *CurMC) {
538 SubMultiClassReference Result;
539 Result.RefRange.Start = Lex.getLoc();
541 Result.MC = ParseMultiClassID();
542 if (!Result.MC) return Result;
544 // If there is no template arg list, we're done.
545 if (Lex.getCode() != tgtok::less) {
546 Result.RefRange.End = Lex.getLoc();
549 Lex.Lex(); // Eat the '<'
551 if (Lex.getCode() == tgtok::greater) {
552 TokError("subclass reference requires a non-empty list of template values");
557 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
558 if (Result.TemplateArgs.empty()) {
559 Result.MC = nullptr; // Error parsing value list.
563 if (Lex.getCode() != tgtok::greater) {
564 TokError("expected '>' in template value list");
569 Result.RefRange.End = Lex.getLoc();
574 /// ParseRangePiece - Parse a bit/value range.
575 /// RangePiece ::= INTVAL
576 /// RangePiece ::= INTVAL '-' INTVAL
577 /// RangePiece ::= INTVAL INTVAL
578 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
579 if (Lex.getCode() != tgtok::IntVal) {
580 TokError("expected integer or bitrange");
583 int64_t Start = Lex.getCurIntVal();
587 return TokError("invalid range, cannot be negative");
589 switch (Lex.Lex()) { // eat first character.
591 Ranges.push_back(Start);
594 if (Lex.Lex() != tgtok::IntVal) {
595 TokError("expected integer value as end of range");
598 End = Lex.getCurIntVal();
601 End = -Lex.getCurIntVal();
605 return TokError("invalid range, cannot be negative");
610 for (; Start <= End; ++Start)
611 Ranges.push_back(Start);
613 for (; Start >= End; --Start)
614 Ranges.push_back(Start);
619 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
621 /// RangeList ::= RangePiece (',' RangePiece)*
623 std::vector<unsigned> TGParser::ParseRangeList() {
624 std::vector<unsigned> Result;
626 // Parse the first piece.
627 if (ParseRangePiece(Result))
628 return std::vector<unsigned>();
629 while (Lex.getCode() == tgtok::comma) {
630 Lex.Lex(); // Eat the comma.
632 // Parse the next range piece.
633 if (ParseRangePiece(Result))
634 return std::vector<unsigned>();
639 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
640 /// OptionalRangeList ::= '<' RangeList '>'
641 /// OptionalRangeList ::= /*empty*/
642 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
643 if (Lex.getCode() != tgtok::less)
646 SMLoc StartLoc = Lex.getLoc();
647 Lex.Lex(); // eat the '<'
649 // Parse the range list.
650 Ranges = ParseRangeList();
651 if (Ranges.empty()) return true;
653 if (Lex.getCode() != tgtok::greater) {
654 TokError("expected '>' at end of range list");
655 return Error(StartLoc, "to match this '<'");
657 Lex.Lex(); // eat the '>'.
661 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
662 /// OptionalBitList ::= '{' RangeList '}'
663 /// OptionalBitList ::= /*empty*/
664 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
665 if (Lex.getCode() != tgtok::l_brace)
668 SMLoc StartLoc = Lex.getLoc();
669 Lex.Lex(); // eat the '{'
671 // Parse the range list.
672 Ranges = ParseRangeList();
673 if (Ranges.empty()) return true;
675 if (Lex.getCode() != tgtok::r_brace) {
676 TokError("expected '}' at end of bit list");
677 return Error(StartLoc, "to match this '{'");
679 Lex.Lex(); // eat the '}'.
684 /// ParseType - Parse and return a tblgen type. This returns null on error.
686 /// Type ::= STRING // string type
687 /// Type ::= CODE // code type
688 /// Type ::= BIT // bit type
689 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
690 /// Type ::= INT // int type
691 /// Type ::= LIST '<' Type '>' // list<x> type
692 /// Type ::= DAG // dag type
693 /// Type ::= ClassID // Record Type
695 RecTy *TGParser::ParseType() {
696 switch (Lex.getCode()) {
697 default: TokError("Unknown token when expecting a type"); return nullptr;
698 case tgtok::String: Lex.Lex(); return StringRecTy::get();
699 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
700 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
701 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
702 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
704 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
707 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
708 TokError("expected '<' after bits type");
711 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
712 TokError("expected integer in bits<n> type");
715 uint64_t Val = Lex.getCurIntVal();
716 if (Lex.Lex() != tgtok::greater) { // Eat count.
717 TokError("expected '>' at end of bits<n> type");
720 Lex.Lex(); // Eat '>'
721 return BitsRecTy::get(Val);
724 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
725 TokError("expected '<' after list type");
728 Lex.Lex(); // Eat '<'
729 RecTy *SubType = ParseType();
730 if (!SubType) return nullptr;
732 if (Lex.getCode() != tgtok::greater) {
733 TokError("expected '>' at end of list<ty> type");
736 Lex.Lex(); // Eat '>'
737 return ListRecTy::get(SubType);
742 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
743 /// has already been read.
744 Init *TGParser::ParseIDValue(Record *CurRec,
745 const std::string &Name, SMLoc NameLoc,
748 if (const RecordVal *RV = CurRec->getValue(Name))
749 return VarInit::get(Name, RV->getType());
751 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
754 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
757 if (CurRec->isTemplateArg(TemplateArgName)) {
758 const RecordVal *RV = CurRec->getValue(TemplateArgName);
759 assert(RV && "Template arg doesn't exist??");
760 return VarInit::get(TemplateArgName, RV->getType());
765 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
768 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
769 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
770 assert(RV && "Template arg doesn't exist??");
771 return VarInit::get(MCName, RV->getType());
775 // If this is in a foreach loop, make sure it's not a loop iterator
776 for (LoopVector::iterator i = Loops.begin(), iend = Loops.end();
779 VarInit *IterVar = dyn_cast<VarInit>(i->IterVar);
780 if (IterVar && IterVar->getName() == Name)
784 if (Mode == ParseNameMode)
785 return StringInit::get(Name);
787 if (Record *D = Records.getDef(Name))
788 return DefInit::get(D);
790 if (Mode == ParseValueMode) {
791 Error(NameLoc, "Variable not defined: '" + Name + "'");
795 return StringInit::get(Name);
798 /// ParseOperation - Parse an operator. This returns null on error.
800 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
802 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
803 switch (Lex.getCode()) {
805 TokError("unknown operation");
810 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
811 UnOpInit::UnaryOp Code;
812 RecTy *Type = nullptr;
814 switch (Lex.getCode()) {
815 default: llvm_unreachable("Unhandled code!");
817 Lex.Lex(); // eat the operation
818 Code = UnOpInit::CAST;
820 Type = ParseOperatorType();
823 TokError("did not get type for unary operator");
829 Lex.Lex(); // eat the operation
830 Code = UnOpInit::HEAD;
833 Lex.Lex(); // eat the operation
834 Code = UnOpInit::TAIL;
837 Lex.Lex(); // eat the operation
838 Code = UnOpInit::EMPTY;
839 Type = IntRecTy::get();
842 if (Lex.getCode() != tgtok::l_paren) {
843 TokError("expected '(' after unary operator");
846 Lex.Lex(); // eat the '('
848 Init *LHS = ParseValue(CurRec);
849 if (!LHS) return nullptr;
851 if (Code == UnOpInit::HEAD
852 || Code == UnOpInit::TAIL
853 || Code == UnOpInit::EMPTY) {
854 ListInit *LHSl = dyn_cast<ListInit>(LHS);
855 StringInit *LHSs = dyn_cast<StringInit>(LHS);
856 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
857 if (!LHSl && !LHSs && !LHSt) {
858 TokError("expected list or string type argument in unary operator");
862 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
863 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
864 if (!LType && !SType) {
865 TokError("expected list or string type argument in unary operator");
870 if (Code == UnOpInit::HEAD
871 || Code == UnOpInit::TAIL) {
872 if (!LHSl && !LHSt) {
873 TokError("expected list type argument in unary operator");
877 if (LHSl && LHSl->getSize() == 0) {
878 TokError("empty list argument in unary operator");
882 Init *Item = LHSl->getElement(0);
883 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
885 TokError("untyped list element in unary operator");
888 if (Code == UnOpInit::HEAD) {
889 Type = Itemt->getType();
891 Type = ListRecTy::get(Itemt->getType());
894 assert(LHSt && "expected list type argument in unary operator");
895 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
897 TokError("expected list type argument in unary operator");
900 if (Code == UnOpInit::HEAD) {
901 Type = LType->getElementType();
909 if (Lex.getCode() != tgtok::r_paren) {
910 TokError("expected ')' in unary operator");
913 Lex.Lex(); // eat the ')'
914 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
924 case tgtok::XListConcat:
925 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
926 tgtok::TokKind OpTok = Lex.getCode();
927 SMLoc OpLoc = Lex.getLoc();
928 Lex.Lex(); // eat the operation
930 BinOpInit::BinaryOp Code;
931 RecTy *Type = nullptr;
934 default: llvm_unreachable("Unhandled code!");
935 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
936 case tgtok::XADD: Code = BinOpInit::ADD; Type = IntRecTy::get(); break;
937 case tgtok::XAND: Code = BinOpInit::AND; Type = IntRecTy::get(); break;
938 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
939 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
940 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
941 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
942 case tgtok::XListConcat:
943 Code = BinOpInit::LISTCONCAT;
944 // We don't know the list type until we parse the first argument
946 case tgtok::XStrConcat:
947 Code = BinOpInit::STRCONCAT;
948 Type = StringRecTy::get();
952 if (Lex.getCode() != tgtok::l_paren) {
953 TokError("expected '(' after binary operator");
956 Lex.Lex(); // eat the '('
958 SmallVector<Init*, 2> InitList;
960 InitList.push_back(ParseValue(CurRec));
961 if (!InitList.back()) return nullptr;
963 while (Lex.getCode() == tgtok::comma) {
964 Lex.Lex(); // eat the ','
966 InitList.push_back(ParseValue(CurRec));
967 if (!InitList.back()) return nullptr;
970 if (Lex.getCode() != tgtok::r_paren) {
971 TokError("expected ')' in operator");
974 Lex.Lex(); // eat the ')'
976 // If we are doing !listconcat, we should know the type by now
977 if (OpTok == tgtok::XListConcat) {
978 if (VarInit *Arg0 = dyn_cast<VarInit>(InitList[0]))
979 Type = Arg0->getType();
980 else if (ListInit *Arg0 = dyn_cast<ListInit>(InitList[0]))
981 Type = Arg0->getType();
984 Error(OpLoc, "expected a list");
989 // We allow multiple operands to associative operators like !strconcat as
990 // shorthand for nesting them.
991 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT) {
992 while (InitList.size() > 2) {
993 Init *RHS = InitList.pop_back_val();
994 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
995 ->Fold(CurRec, CurMultiClass);
996 InitList.back() = RHS;
1000 if (InitList.size() == 2)
1001 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
1002 ->Fold(CurRec, CurMultiClass);
1004 Error(OpLoc, "expected two operands to operator");
1009 case tgtok::XForEach:
1010 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1011 TernOpInit::TernaryOp Code;
1012 RecTy *Type = nullptr;
1014 tgtok::TokKind LexCode = Lex.getCode();
1015 Lex.Lex(); // eat the operation
1017 default: llvm_unreachable("Unhandled code!");
1019 Code = TernOpInit::IF;
1021 case tgtok::XForEach:
1022 Code = TernOpInit::FOREACH;
1025 Code = TernOpInit::SUBST;
1028 if (Lex.getCode() != tgtok::l_paren) {
1029 TokError("expected '(' after ternary operator");
1032 Lex.Lex(); // eat the '('
1034 Init *LHS = ParseValue(CurRec);
1035 if (!LHS) return nullptr;
1037 if (Lex.getCode() != tgtok::comma) {
1038 TokError("expected ',' in ternary operator");
1041 Lex.Lex(); // eat the ','
1043 Init *MHS = ParseValue(CurRec, ItemType);
1047 if (Lex.getCode() != tgtok::comma) {
1048 TokError("expected ',' in ternary operator");
1051 Lex.Lex(); // eat the ','
1053 Init *RHS = ParseValue(CurRec, ItemType);
1057 if (Lex.getCode() != tgtok::r_paren) {
1058 TokError("expected ')' in binary operator");
1061 Lex.Lex(); // eat the ')'
1064 default: llvm_unreachable("Unhandled code!");
1066 RecTy *MHSTy = nullptr;
1067 RecTy *RHSTy = nullptr;
1069 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1070 MHSTy = MHSt->getType();
1071 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1072 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1073 if (isa<BitInit>(MHS))
1074 MHSTy = BitRecTy::get();
1076 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1077 RHSTy = RHSt->getType();
1078 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1079 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1080 if (isa<BitInit>(RHS))
1081 RHSTy = BitRecTy::get();
1083 // For UnsetInit, it's typed from the other hand.
1084 if (isa<UnsetInit>(MHS))
1086 if (isa<UnsetInit>(RHS))
1089 if (!MHSTy || !RHSTy) {
1090 TokError("could not get type for !if");
1094 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1096 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1099 TokError("inconsistent types for !if");
1104 case tgtok::XForEach: {
1105 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1107 TokError("could not get type for !foreach");
1110 Type = MHSt->getType();
1113 case tgtok::XSubst: {
1114 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1116 TokError("could not get type for !subst");
1119 Type = RHSt->getType();
1123 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1129 /// ParseOperatorType - Parse a type for an operator. This returns
1132 /// OperatorType ::= '<' Type '>'
1134 RecTy *TGParser::ParseOperatorType() {
1135 RecTy *Type = nullptr;
1137 if (Lex.getCode() != tgtok::less) {
1138 TokError("expected type name for operator");
1141 Lex.Lex(); // eat the <
1146 TokError("expected type name for operator");
1150 if (Lex.getCode() != tgtok::greater) {
1151 TokError("expected type name for operator");
1154 Lex.Lex(); // eat the >
1160 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1162 /// SimpleValue ::= IDValue
1163 /// SimpleValue ::= INTVAL
1164 /// SimpleValue ::= STRVAL+
1165 /// SimpleValue ::= CODEFRAGMENT
1166 /// SimpleValue ::= '?'
1167 /// SimpleValue ::= '{' ValueList '}'
1168 /// SimpleValue ::= ID '<' ValueListNE '>'
1169 /// SimpleValue ::= '[' ValueList ']'
1170 /// SimpleValue ::= '(' IDValue DagArgList ')'
1171 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1172 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1173 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1174 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1175 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1176 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1177 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1179 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1182 switch (Lex.getCode()) {
1183 default: TokError("Unknown token when parsing a value"); break;
1185 // This is a leading paste operation. This is deprecated but
1186 // still exists in some .td files. Ignore it.
1187 Lex.Lex(); // Skip '#'.
1188 return ParseSimpleValue(CurRec, ItemType, Mode);
1189 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1190 case tgtok::BinaryIntVal: {
1191 auto BinaryVal = Lex.getCurBinaryIntVal();
1192 SmallVector<Init*, 16> Bits(BinaryVal.second);
1193 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
1194 Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
1195 R = BitsInit::get(Bits);
1199 case tgtok::StrVal: {
1200 std::string Val = Lex.getCurStrVal();
1203 // Handle multiple consecutive concatenated strings.
1204 while (Lex.getCode() == tgtok::StrVal) {
1205 Val += Lex.getCurStrVal();
1209 R = StringInit::get(Val);
1212 case tgtok::CodeFragment:
1213 R = StringInit::get(Lex.getCurStrVal());
1216 case tgtok::question:
1217 R = UnsetInit::get();
1221 SMLoc NameLoc = Lex.getLoc();
1222 std::string Name = Lex.getCurStrVal();
1223 if (Lex.Lex() != tgtok::less) // consume the Id.
1224 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1226 // Value ::= ID '<' ValueListNE '>'
1227 if (Lex.Lex() == tgtok::greater) {
1228 TokError("expected non-empty value list");
1232 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1233 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1235 Record *Class = Records.getClass(Name);
1237 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1241 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1242 if (ValueList.empty()) return nullptr;
1244 if (Lex.getCode() != tgtok::greater) {
1245 TokError("expected '>' at end of value list");
1248 Lex.Lex(); // eat the '>'
1249 SMLoc EndLoc = Lex.getLoc();
1251 // Create the new record, set it as CurRec temporarily.
1252 Record *NewRec = new Record(GetNewAnonymousName(), NameLoc, Records,
1253 /*IsAnonymous=*/true);
1254 SubClassReference SCRef;
1255 SCRef.RefRange = SMRange(NameLoc, EndLoc);
1257 SCRef.TemplateArgs = ValueList;
1258 // Add info about the subclass to NewRec.
1259 if (AddSubClass(NewRec, SCRef)) {
1263 if (!CurMultiClass) {
1264 NewRec->resolveReferences();
1265 Records.addDef(NewRec);
1267 // Otherwise, we're inside a multiclass, add it to the multiclass.
1268 CurMultiClass->DefPrototypes.push_back(NewRec);
1270 // Copy the template arguments for the multiclass into the def.
1271 const std::vector<Init *> &TArgs =
1272 CurMultiClass->Rec.getTemplateArgs();
1274 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1275 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1276 assert(RV && "Template arg doesn't exist?");
1277 NewRec->addValue(*RV);
1280 // We can't return the prototype def here, instead return:
1281 // !cast<ItemType>(!strconcat(NAME, AnonName)).
1282 const RecordVal *MCNameRV = CurMultiClass->Rec.getValue("NAME");
1283 assert(MCNameRV && "multiclass record must have a NAME");
1285 return UnOpInit::get(UnOpInit::CAST,
1286 BinOpInit::get(BinOpInit::STRCONCAT,
1287 VarInit::get(MCNameRV->getName(),
1288 MCNameRV->getType()),
1289 NewRec->getNameInit(),
1290 StringRecTy::get()),
1291 Class->getDefInit()->getType());
1294 // The result of the expression is a reference to the new record.
1295 return DefInit::get(NewRec);
1297 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1298 SMLoc BraceLoc = Lex.getLoc();
1299 Lex.Lex(); // eat the '{'
1300 std::vector<Init*> Vals;
1302 if (Lex.getCode() != tgtok::r_brace) {
1303 Vals = ParseValueList(CurRec);
1304 if (Vals.empty()) return nullptr;
1306 if (Lex.getCode() != tgtok::r_brace) {
1307 TokError("expected '}' at end of bit list value");
1310 Lex.Lex(); // eat the '}'
1312 SmallVector<Init *, 16> NewBits;
1314 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1315 // first. We'll first read everything in to a vector, then we can reverse
1316 // it to get the bits in the correct order for the BitsInit value.
1317 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1318 // FIXME: The following two loops would not be duplicated
1319 // if the API was a little more orthogonal.
1321 // bits<n> values are allowed to initialize n bits.
1322 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
1323 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
1324 NewBits.push_back(BI->getBit((e - i) - 1));
1327 // bits<n> can also come from variable initializers.
1328 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
1329 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
1330 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
1331 NewBits.push_back(VI->getBit((e - i) - 1));
1334 // Fallthrough to try convert this to a bit.
1336 // All other values must be convertible to just a single bit.
1337 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1339 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1340 ") is not convertable to a bit");
1343 NewBits.push_back(Bit);
1345 std::reverse(NewBits.begin(), NewBits.end());
1346 return BitsInit::get(NewBits);
1348 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1349 Lex.Lex(); // eat the '['
1350 std::vector<Init*> Vals;
1352 RecTy *DeducedEltTy = nullptr;
1353 ListRecTy *GivenListTy = nullptr;
1356 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1359 raw_string_ostream ss(s);
1360 ss << "Type mismatch for list, expected list type, got "
1361 << ItemType->getAsString();
1365 GivenListTy = ListType;
1368 if (Lex.getCode() != tgtok::r_square) {
1369 Vals = ParseValueList(CurRec, nullptr,
1370 GivenListTy ? GivenListTy->getElementType() : nullptr);
1371 if (Vals.empty()) return nullptr;
1373 if (Lex.getCode() != tgtok::r_square) {
1374 TokError("expected ']' at end of list value");
1377 Lex.Lex(); // eat the ']'
1379 RecTy *GivenEltTy = nullptr;
1380 if (Lex.getCode() == tgtok::less) {
1381 // Optional list element type
1382 Lex.Lex(); // eat the '<'
1384 GivenEltTy = ParseType();
1386 // Couldn't parse element type
1390 if (Lex.getCode() != tgtok::greater) {
1391 TokError("expected '>' at end of list element type");
1394 Lex.Lex(); // eat the '>'
1398 RecTy *EltTy = nullptr;
1399 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1402 TypedInit *TArg = dyn_cast<TypedInit>(*i);
1404 TokError("Untyped list element");
1408 EltTy = resolveTypes(EltTy, TArg->getType());
1410 TokError("Incompatible types in list elements");
1414 EltTy = TArg->getType();
1420 // Verify consistency
1421 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1422 TokError("Incompatible types in list elements");
1431 TokError("No type for list");
1434 DeducedEltTy = GivenListTy->getElementType();
1436 // Make sure the deduced type is compatible with the given type
1438 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1439 TokError("Element type mismatch for list");
1443 DeducedEltTy = EltTy;
1446 return ListInit::get(Vals, DeducedEltTy);
1448 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1449 Lex.Lex(); // eat the '('
1450 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1451 TokError("expected identifier in dag init");
1455 Init *Operator = ParseValue(CurRec);
1456 if (!Operator) return nullptr;
1458 // If the operator name is present, parse it.
1459 std::string OperatorName;
1460 if (Lex.getCode() == tgtok::colon) {
1461 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1462 TokError("expected variable name in dag operator");
1465 OperatorName = Lex.getCurStrVal();
1466 Lex.Lex(); // eat the VarName.
1469 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1470 if (Lex.getCode() != tgtok::r_paren) {
1471 DagArgs = ParseDagArgList(CurRec);
1472 if (DagArgs.empty()) return nullptr;
1475 if (Lex.getCode() != tgtok::r_paren) {
1476 TokError("expected ')' in dag init");
1479 Lex.Lex(); // eat the ')'
1481 return DagInit::get(Operator, OperatorName, DagArgs);
1487 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1488 case tgtok::XConcat:
1495 case tgtok::XListConcat:
1496 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1498 case tgtok::XForEach:
1499 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1500 return ParseOperation(CurRec, ItemType);
1507 /// ParseValue - Parse a tblgen value. This returns null on error.
1509 /// Value ::= SimpleValue ValueSuffix*
1510 /// ValueSuffix ::= '{' BitList '}'
1511 /// ValueSuffix ::= '[' BitList ']'
1512 /// ValueSuffix ::= '.' ID
1514 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1515 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1516 if (!Result) return nullptr;
1518 // Parse the suffixes now if present.
1520 switch (Lex.getCode()) {
1521 default: return Result;
1522 case tgtok::l_brace: {
1523 if (Mode == ParseNameMode || Mode == ParseForeachMode)
1524 // This is the beginning of the object body.
1527 SMLoc CurlyLoc = Lex.getLoc();
1528 Lex.Lex(); // eat the '{'
1529 std::vector<unsigned> Ranges = ParseRangeList();
1530 if (Ranges.empty()) return nullptr;
1532 // Reverse the bitlist.
1533 std::reverse(Ranges.begin(), Ranges.end());
1534 Result = Result->convertInitializerBitRange(Ranges);
1536 Error(CurlyLoc, "Invalid bit range for value");
1541 if (Lex.getCode() != tgtok::r_brace) {
1542 TokError("expected '}' at end of bit range list");
1548 case tgtok::l_square: {
1549 SMLoc SquareLoc = Lex.getLoc();
1550 Lex.Lex(); // eat the '['
1551 std::vector<unsigned> Ranges = ParseRangeList();
1552 if (Ranges.empty()) return nullptr;
1554 Result = Result->convertInitListSlice(Ranges);
1556 Error(SquareLoc, "Invalid range for list slice");
1561 if (Lex.getCode() != tgtok::r_square) {
1562 TokError("expected ']' at end of list slice");
1569 if (Lex.Lex() != tgtok::Id) { // eat the .
1570 TokError("expected field identifier after '.'");
1573 if (!Result->getFieldType(Lex.getCurStrVal())) {
1574 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1575 Result->getAsString() + "'");
1578 Result = FieldInit::get(Result, Lex.getCurStrVal());
1579 Lex.Lex(); // eat field name
1583 SMLoc PasteLoc = Lex.getLoc();
1585 // Create a !strconcat() operation, first casting each operand to
1586 // a string if necessary.
1588 TypedInit *LHS = dyn_cast<TypedInit>(Result);
1590 Error(PasteLoc, "LHS of paste is not typed!");
1594 if (LHS->getType() != StringRecTy::get()) {
1595 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1598 TypedInit *RHS = nullptr;
1600 Lex.Lex(); // Eat the '#'.
1601 switch (Lex.getCode()) {
1604 case tgtok::l_brace:
1605 // These are all of the tokens that can begin an object body.
1606 // Some of these can also begin values but we disallow those cases
1607 // because they are unlikely to be useful.
1609 // Trailing paste, concat with an empty string.
1610 RHS = StringInit::get("");
1614 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1615 RHS = dyn_cast<TypedInit>(RHSResult);
1617 Error(PasteLoc, "RHS of paste is not typed!");
1621 if (RHS->getType() != StringRecTy::get()) {
1622 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1628 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1629 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1635 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1637 /// DagArg ::= Value (':' VARNAME)?
1638 /// DagArg ::= VARNAME
1639 /// DagArgList ::= DagArg
1640 /// DagArgList ::= DagArgList ',' DagArg
1641 std::vector<std::pair<llvm::Init*, std::string> >
1642 TGParser::ParseDagArgList(Record *CurRec) {
1643 std::vector<std::pair<llvm::Init*, std::string> > Result;
1646 // DagArg ::= VARNAME
1647 if (Lex.getCode() == tgtok::VarName) {
1648 // A missing value is treated like '?'.
1649 Result.push_back(std::make_pair(UnsetInit::get(), Lex.getCurStrVal()));
1652 // DagArg ::= Value (':' VARNAME)?
1653 Init *Val = ParseValue(CurRec);
1655 return std::vector<std::pair<llvm::Init*, std::string> >();
1657 // If the variable name is present, add it.
1658 std::string VarName;
1659 if (Lex.getCode() == tgtok::colon) {
1660 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1661 TokError("expected variable name in dag literal");
1662 return std::vector<std::pair<llvm::Init*, std::string> >();
1664 VarName = Lex.getCurStrVal();
1665 Lex.Lex(); // eat the VarName.
1668 Result.push_back(std::make_pair(Val, VarName));
1670 if (Lex.getCode() != tgtok::comma) break;
1671 Lex.Lex(); // eat the ','
1678 /// ParseValueList - Parse a comma separated list of values, returning them as a
1679 /// vector. Note that this always expects to be able to parse at least one
1680 /// value. It returns an empty list if this is not possible.
1682 /// ValueList ::= Value (',' Value)
1684 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1686 std::vector<Init*> Result;
1687 RecTy *ItemType = EltTy;
1688 unsigned int ArgN = 0;
1689 if (ArgsRec && !EltTy) {
1690 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1691 if (!TArgs.size()) {
1692 TokError("template argument provided to non-template class");
1693 return std::vector<Init*>();
1695 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1697 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1700 assert(RV && "Template argument record not found??");
1701 ItemType = RV->getType();
1704 Result.push_back(ParseValue(CurRec, ItemType));
1705 if (!Result.back()) return std::vector<Init*>();
1707 while (Lex.getCode() == tgtok::comma) {
1708 Lex.Lex(); // Eat the comma
1710 if (ArgsRec && !EltTy) {
1711 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1712 if (ArgN >= TArgs.size()) {
1713 TokError("too many template arguments");
1714 return std::vector<Init*>();
1716 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1717 assert(RV && "Template argument record not found??");
1718 ItemType = RV->getType();
1721 Result.push_back(ParseValue(CurRec, ItemType));
1722 if (!Result.back()) return std::vector<Init*>();
1729 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1730 /// empty string on error. This can happen in a number of different context's,
1731 /// including within a def or in the template args for a def (which which case
1732 /// CurRec will be non-null) and within the template args for a multiclass (in
1733 /// which case CurRec will be null, but CurMultiClass will be set). This can
1734 /// also happen within a def that is within a multiclass, which will set both
1735 /// CurRec and CurMultiClass.
1737 /// Declaration ::= FIELD? Type ID ('=' Value)?
1739 Init *TGParser::ParseDeclaration(Record *CurRec,
1740 bool ParsingTemplateArgs) {
1741 // Read the field prefix if present.
1742 bool HasField = Lex.getCode() == tgtok::Field;
1743 if (HasField) Lex.Lex();
1745 RecTy *Type = ParseType();
1746 if (!Type) return nullptr;
1748 if (Lex.getCode() != tgtok::Id) {
1749 TokError("Expected identifier in declaration");
1753 SMLoc IdLoc = Lex.getLoc();
1754 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1757 if (ParsingTemplateArgs) {
1759 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1761 assert(CurMultiClass);
1764 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1769 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1772 // If a value is present, parse it.
1773 if (Lex.getCode() == tgtok::equal) {
1775 SMLoc ValLoc = Lex.getLoc();
1776 Init *Val = ParseValue(CurRec, Type);
1778 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1779 // Return the name, even if an error is thrown. This is so that we can
1780 // continue to make some progress, even without the value having been
1788 /// ParseForeachDeclaration - Read a foreach declaration, returning
1789 /// the name of the declared object or a NULL Init on error. Return
1790 /// the name of the parsed initializer list through ForeachListName.
1792 /// ForeachDeclaration ::= ID '=' '[' ValueList ']'
1793 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
1794 /// ForeachDeclaration ::= ID '=' RangePiece
1796 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1797 if (Lex.getCode() != tgtok::Id) {
1798 TokError("Expected identifier in foreach declaration");
1802 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1805 // If a value is present, parse it.
1806 if (Lex.getCode() != tgtok::equal) {
1807 TokError("Expected '=' in foreach declaration");
1810 Lex.Lex(); // Eat the '='
1812 RecTy *IterType = nullptr;
1813 std::vector<unsigned> Ranges;
1815 switch (Lex.getCode()) {
1816 default: TokError("Unknown token when expecting a range list"); return nullptr;
1817 case tgtok::l_square: { // '[' ValueList ']'
1818 Init *List = ParseSimpleValue(nullptr, nullptr, ParseForeachMode);
1819 ForeachListValue = dyn_cast<ListInit>(List);
1820 if (!ForeachListValue) {
1821 TokError("Expected a Value list");
1824 RecTy *ValueType = ForeachListValue->getType();
1825 ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1827 TokError("Value list is not of list type");
1830 IterType = ListType->getElementType();
1834 case tgtok::IntVal: { // RangePiece.
1835 if (ParseRangePiece(Ranges))
1840 case tgtok::l_brace: { // '{' RangeList '}'
1841 Lex.Lex(); // eat the '{'
1842 Ranges = ParseRangeList();
1843 if (Lex.getCode() != tgtok::r_brace) {
1844 TokError("expected '}' at end of bit range list");
1852 if (!Ranges.empty()) {
1853 assert(!IterType && "Type already initialized?");
1854 IterType = IntRecTy::get();
1855 std::vector<Init*> Values;
1856 for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
1857 Values.push_back(IntInit::get(Ranges[i]));
1858 ForeachListValue = ListInit::get(Values, IterType);
1864 return VarInit::get(DeclName, IterType);
1867 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1868 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1869 /// template args for a def, which may or may not be in a multiclass. If null,
1870 /// these are the template args for a multiclass.
1872 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1874 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1875 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1876 Lex.Lex(); // eat the '<'
1878 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1880 // Read the first declaration.
1881 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1885 TheRecToAddTo->addTemplateArg(TemplArg);
1887 while (Lex.getCode() == tgtok::comma) {
1888 Lex.Lex(); // eat the ','
1890 // Read the following declarations.
1891 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1894 TheRecToAddTo->addTemplateArg(TemplArg);
1897 if (Lex.getCode() != tgtok::greater)
1898 return TokError("expected '>' at end of template argument list");
1899 Lex.Lex(); // eat the '>'.
1904 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1906 /// BodyItem ::= Declaration ';'
1907 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1908 bool TGParser::ParseBodyItem(Record *CurRec) {
1909 if (Lex.getCode() != tgtok::Let) {
1910 if (!ParseDeclaration(CurRec, false))
1913 if (Lex.getCode() != tgtok::semi)
1914 return TokError("expected ';' after declaration");
1919 // LET ID OptionalRangeList '=' Value ';'
1920 if (Lex.Lex() != tgtok::Id)
1921 return TokError("expected field identifier after let");
1923 SMLoc IdLoc = Lex.getLoc();
1924 std::string FieldName = Lex.getCurStrVal();
1925 Lex.Lex(); // eat the field name.
1927 std::vector<unsigned> BitList;
1928 if (ParseOptionalBitList(BitList))
1930 std::reverse(BitList.begin(), BitList.end());
1932 if (Lex.getCode() != tgtok::equal)
1933 return TokError("expected '=' in let expression");
1934 Lex.Lex(); // eat the '='.
1936 RecordVal *Field = CurRec->getValue(FieldName);
1938 return TokError("Value '" + FieldName + "' unknown!");
1940 RecTy *Type = Field->getType();
1942 Init *Val = ParseValue(CurRec, Type);
1943 if (!Val) return true;
1945 if (Lex.getCode() != tgtok::semi)
1946 return TokError("expected ';' after let expression");
1949 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1952 /// ParseBody - Read the body of a class or def. Return true on error, false on
1956 /// Body ::= '{' BodyList '}'
1957 /// BodyList BodyItem*
1959 bool TGParser::ParseBody(Record *CurRec) {
1960 // If this is a null definition, just eat the semi and return.
1961 if (Lex.getCode() == tgtok::semi) {
1966 if (Lex.getCode() != tgtok::l_brace)
1967 return TokError("Expected ';' or '{' to start body");
1971 while (Lex.getCode() != tgtok::r_brace)
1972 if (ParseBodyItem(CurRec))
1980 /// \brief Apply the current let bindings to \a CurRec.
1981 /// \returns true on error, false otherwise.
1982 bool TGParser::ApplyLetStack(Record *CurRec) {
1983 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1984 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1985 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1986 LetStack[i][j].Bits, LetStack[i][j].Value))
1991 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1992 /// optional ClassList followed by a Body. CurRec is the current def or class
1993 /// that is being parsed.
1995 /// ObjectBody ::= BaseClassList Body
1996 /// BaseClassList ::= /*empty*/
1997 /// BaseClassList ::= ':' BaseClassListNE
1998 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
2000 bool TGParser::ParseObjectBody(Record *CurRec) {
2001 // If there is a baseclass list, read it.
2002 if (Lex.getCode() == tgtok::colon) {
2005 // Read all of the subclasses.
2006 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
2009 if (!SubClass.Rec) return true;
2012 if (AddSubClass(CurRec, SubClass))
2015 if (Lex.getCode() != tgtok::comma) break;
2016 Lex.Lex(); // eat ','.
2017 SubClass = ParseSubClassReference(CurRec, false);
2021 if (ApplyLetStack(CurRec))
2024 return ParseBody(CurRec);
2027 /// ParseDef - Parse and return a top level or multiclass def, return the record
2028 /// corresponding to it. This returns null on error.
2030 /// DefInst ::= DEF ObjectName ObjectBody
2032 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
2033 SMLoc DefLoc = Lex.getLoc();
2034 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
2035 Lex.Lex(); // Eat the 'def' token.
2037 // Parse ObjectName and make a record for it.
2039 bool CurRecOwnershipTransferred = false;
2040 Init *Name = ParseObjectName(CurMultiClass);
2042 CurRec = new Record(Name, DefLoc, Records);
2044 CurRec = new Record(GetNewAnonymousName(), DefLoc, Records,
2045 /*IsAnonymous=*/true);
2047 if (!CurMultiClass && Loops.empty()) {
2048 // Top-level def definition.
2050 // Ensure redefinition doesn't happen.
2051 if (Records.getDef(CurRec->getNameInitAsString())) {
2052 Error(DefLoc, "def '" + CurRec->getNameInitAsString()
2053 + "' already defined");
2057 Records.addDef(CurRec);
2058 CurRecOwnershipTransferred = true;
2060 if (ParseObjectBody(CurRec))
2062 } else if (CurMultiClass) {
2063 // Parse the body before adding this prototype to the DefPrototypes vector.
2064 // That way implicit definitions will be added to the DefPrototypes vector
2065 // before this object, instantiated prior to defs derived from this object,
2066 // and this available for indirect name resolution when defs derived from
2067 // this object are instantiated.
2068 if (ParseObjectBody(CurRec)) {
2073 // Otherwise, a def inside a multiclass, add it to the multiclass.
2074 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
2075 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2076 == CurRec->getNameInit()) {
2077 Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
2078 "' already defined in this multiclass!");
2082 CurMultiClass->DefPrototypes.push_back(CurRec);
2083 CurRecOwnershipTransferred = true;
2084 } else if (ParseObjectBody(CurRec)) {
2089 if (!CurMultiClass) // Def's in multiclasses aren't really defs.
2090 // See Record::setName(). This resolve step will see any new name
2091 // for the def that might have been created when resolving
2092 // inheritance, values and arguments above.
2093 CurRec->resolveReferences();
2095 // If ObjectBody has template arguments, it's an error.
2096 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
2098 if (CurMultiClass) {
2099 // Copy the template arguments for the multiclass into the def.
2100 const std::vector<Init *> &TArgs =
2101 CurMultiClass->Rec.getTemplateArgs();
2103 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2104 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
2105 assert(RV && "Template arg doesn't exist?");
2106 CurRec->addValue(*RV);
2110 if (ProcessForeachDefs(CurRec, DefLoc)) {
2112 "Could not process loops for def" + CurRec->getNameInitAsString());
2113 if (!CurRecOwnershipTransferred)
2118 if (!CurRecOwnershipTransferred)
2123 /// ParseForeach - Parse a for statement. Return the record corresponding
2124 /// to it. This returns true on error.
2126 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2127 /// Foreach ::= FOREACH Declaration IN Object
2129 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2130 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2131 Lex.Lex(); // Eat the 'for' token.
2133 // Make a temporary object to record items associated with the for
2135 ListInit *ListValue = nullptr;
2136 VarInit *IterName = ParseForeachDeclaration(ListValue);
2138 return TokError("expected declaration in for");
2140 if (Lex.getCode() != tgtok::In)
2141 return TokError("Unknown tok");
2142 Lex.Lex(); // Eat the in
2144 // Create a loop object and remember it.
2145 Loops.push_back(ForeachLoop(IterName, ListValue));
2147 if (Lex.getCode() != tgtok::l_brace) {
2148 // FOREACH Declaration IN Object
2149 if (ParseObject(CurMultiClass))
2153 SMLoc BraceLoc = Lex.getLoc();
2154 // Otherwise, this is a group foreach.
2155 Lex.Lex(); // eat the '{'.
2157 // Parse the object list.
2158 if (ParseObjectList(CurMultiClass))
2161 if (Lex.getCode() != tgtok::r_brace) {
2162 TokError("expected '}' at end of foreach command");
2163 return Error(BraceLoc, "to match this '{'");
2165 Lex.Lex(); // Eat the }
2168 // We've processed everything in this loop.
2174 /// ParseClass - Parse a tblgen class definition.
2176 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2178 bool TGParser::ParseClass() {
2179 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2182 if (Lex.getCode() != tgtok::Id)
2183 return TokError("expected class name after 'class' keyword");
2185 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2187 // If the body was previously defined, this is an error.
2188 if (CurRec->getValues().size() > 1 || // Account for NAME.
2189 !CurRec->getSuperClasses().empty() ||
2190 !CurRec->getTemplateArgs().empty())
2191 return TokError("Class '" + CurRec->getNameInitAsString()
2192 + "' already defined");
2194 // If this is the first reference to this class, create and add it.
2195 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
2196 Records.addClass(CurRec);
2198 Lex.Lex(); // eat the name.
2200 // If there are template args, parse them.
2201 if (Lex.getCode() == tgtok::less)
2202 if (ParseTemplateArgList(CurRec))
2205 // Finally, parse the object body.
2206 return ParseObjectBody(CurRec);
2209 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2212 /// LetList ::= LetItem (',' LetItem)*
2213 /// LetItem ::= ID OptionalRangeList '=' Value
2215 std::vector<LetRecord> TGParser::ParseLetList() {
2216 std::vector<LetRecord> Result;
2219 if (Lex.getCode() != tgtok::Id) {
2220 TokError("expected identifier in let definition");
2221 return std::vector<LetRecord>();
2223 std::string Name = Lex.getCurStrVal();
2224 SMLoc NameLoc = Lex.getLoc();
2225 Lex.Lex(); // Eat the identifier.
2227 // Check for an optional RangeList.
2228 std::vector<unsigned> Bits;
2229 if (ParseOptionalRangeList(Bits))
2230 return std::vector<LetRecord>();
2231 std::reverse(Bits.begin(), Bits.end());
2233 if (Lex.getCode() != tgtok::equal) {
2234 TokError("expected '=' in let expression");
2235 return std::vector<LetRecord>();
2237 Lex.Lex(); // eat the '='.
2239 Init *Val = ParseValue(nullptr);
2240 if (!Val) return std::vector<LetRecord>();
2242 // Now that we have everything, add the record.
2243 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2245 if (Lex.getCode() != tgtok::comma)
2247 Lex.Lex(); // eat the comma.
2251 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2252 /// different related productions. This works inside multiclasses too.
2254 /// Object ::= LET LetList IN '{' ObjectList '}'
2255 /// Object ::= LET LetList IN Object
2257 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2258 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2261 // Add this entry to the let stack.
2262 std::vector<LetRecord> LetInfo = ParseLetList();
2263 if (LetInfo.empty()) return true;
2264 LetStack.push_back(LetInfo);
2266 if (Lex.getCode() != tgtok::In)
2267 return TokError("expected 'in' at end of top-level 'let'");
2270 // If this is a scalar let, just handle it now
2271 if (Lex.getCode() != tgtok::l_brace) {
2272 // LET LetList IN Object
2273 if (ParseObject(CurMultiClass))
2275 } else { // Object ::= LETCommand '{' ObjectList '}'
2276 SMLoc BraceLoc = Lex.getLoc();
2277 // Otherwise, this is a group let.
2278 Lex.Lex(); // eat the '{'.
2280 // Parse the object list.
2281 if (ParseObjectList(CurMultiClass))
2284 if (Lex.getCode() != tgtok::r_brace) {
2285 TokError("expected '}' at end of top level let command");
2286 return Error(BraceLoc, "to match this '{'");
2291 // Outside this let scope, this let block is not active.
2292 LetStack.pop_back();
2296 /// ParseMultiClass - Parse a multiclass definition.
2298 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2299 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2300 /// MultiClassObject ::= DefInst
2301 /// MultiClassObject ::= MultiClassInst
2302 /// MultiClassObject ::= DefMInst
2303 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
2304 /// MultiClassObject ::= LETCommand Object
2306 bool TGParser::ParseMultiClass() {
2307 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2308 Lex.Lex(); // Eat the multiclass token.
2310 if (Lex.getCode() != tgtok::Id)
2311 return TokError("expected identifier after multiclass for name");
2312 std::string Name = Lex.getCurStrVal();
2314 if (MultiClasses.count(Name))
2315 return TokError("multiclass '" + Name + "' already defined");
2317 CurMultiClass = MultiClasses[Name] = new MultiClass(Name,
2318 Lex.getLoc(), Records);
2319 Lex.Lex(); // Eat the identifier.
2321 // If there are template args, parse them.
2322 if (Lex.getCode() == tgtok::less)
2323 if (ParseTemplateArgList(nullptr))
2326 bool inherits = false;
2328 // If there are submulticlasses, parse them.
2329 if (Lex.getCode() == tgtok::colon) {
2334 // Read all of the submulticlasses.
2335 SubMultiClassReference SubMultiClass =
2336 ParseSubMultiClassReference(CurMultiClass);
2339 if (!SubMultiClass.MC) return true;
2342 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2345 if (Lex.getCode() != tgtok::comma) break;
2346 Lex.Lex(); // eat ','.
2347 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2351 if (Lex.getCode() != tgtok::l_brace) {
2353 return TokError("expected '{' in multiclass definition");
2354 else if (Lex.getCode() != tgtok::semi)
2355 return TokError("expected ';' in multiclass definition");
2357 Lex.Lex(); // eat the ';'.
2359 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2360 return TokError("multiclass must contain at least one def");
2362 while (Lex.getCode() != tgtok::r_brace) {
2363 switch (Lex.getCode()) {
2365 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2369 case tgtok::Foreach:
2370 if (ParseObject(CurMultiClass))
2375 Lex.Lex(); // eat the '}'.
2378 CurMultiClass = nullptr;
2383 InstantiateMulticlassDef(MultiClass &MC,
2386 SMRange DefmPrefixRange) {
2387 // We need to preserve DefProto so it can be reused for later
2388 // instantiations, so create a new Record to inherit from it.
2390 // Add in the defm name. If the defm prefix is empty, give each
2391 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2392 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2395 bool IsAnonymous = false;
2397 DefmPrefix = StringInit::get(GetNewAnonymousName());
2401 Init *DefName = DefProto->getNameInit();
2403 StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2405 if (DefNameString) {
2406 // We have a fully expanded string so there are no operators to
2407 // resolve. We should concatenate the given prefix and name.
2409 BinOpInit::get(BinOpInit::STRCONCAT,
2410 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2411 StringRecTy::get())->Fold(DefProto, &MC),
2412 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2415 // Make a trail of SMLocs from the multiclass instantiations.
2416 SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
2417 Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2418 Record *CurRec = new Record(DefName, Locs, Records, IsAnonymous);
2420 SubClassReference Ref;
2421 Ref.RefRange = DefmPrefixRange;
2423 AddSubClass(CurRec, Ref);
2425 // Set the value for NAME. We don't resolve references to it 'til later,
2426 // though, so that uses in nested multiclass names don't get
2428 if (SetValue(CurRec, Ref.RefRange.Start, "NAME", std::vector<unsigned>(),
2430 Error(DefmPrefixRange.Start, "Could not resolve "
2431 + CurRec->getNameInitAsString() + ":NAME to '"
2432 + DefmPrefix->getAsUnquotedString() + "'");
2437 // If the DefNameString didn't resolve, we probably have a reference to
2438 // NAME and need to replace it. We need to do at least this much greedily,
2439 // otherwise nested multiclasses will end up with incorrect NAME expansions.
2440 if (!DefNameString) {
2441 RecordVal *DefNameRV = CurRec->getValue("NAME");
2442 CurRec->resolveReferencesTo(DefNameRV);
2445 if (!CurMultiClass) {
2446 // Now that we're at the top level, resolve all NAME references
2447 // in the resultant defs that weren't in the def names themselves.
2448 RecordVal *DefNameRV = CurRec->getValue("NAME");
2449 CurRec->resolveReferencesTo(DefNameRV);
2451 // Now that NAME references are resolved and we're at the top level of
2452 // any multiclass expansions, add the record to the RecordKeeper. If we are
2453 // currently in a multiclass, it means this defm appears inside a
2454 // multiclass and its name won't be fully resolvable until we see
2455 // the top-level defm. Therefore, we don't add this to the
2456 // RecordKeeper at this point. If we did we could get duplicate
2457 // defs as more than one probably refers to NAME or some other
2458 // common internal placeholder.
2460 // Ensure redefinition doesn't happen.
2461 if (Records.getDef(CurRec->getNameInitAsString())) {
2462 Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
2463 "' already defined, instantiating defm with subdef '" +
2464 DefProto->getNameInitAsString() + "'");
2469 Records.addDef(CurRec);
2475 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2477 SMLoc DefmPrefixLoc,
2479 const std::vector<Init *> &TArgs,
2480 std::vector<Init *> &TemplateVals,
2482 // Loop over all of the template arguments, setting them to the specified
2483 // value or leaving them as the default if necessary.
2484 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2485 // Check if a value is specified for this temp-arg.
2486 if (i < TemplateVals.size()) {
2488 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2493 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2497 CurRec->removeValue(TArgs[i]);
2499 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2500 return Error(SubClassLoc, "value not specified for template argument #"+
2501 utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2502 + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2509 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2512 SMLoc DefmPrefixLoc) {
2513 // If the mdef is inside a 'let' expression, add to each def.
2514 if (ApplyLetStack(CurRec))
2515 return Error(DefmPrefixLoc, "when instantiating this defm");
2517 // Don't create a top level definition for defm inside multiclasses,
2518 // instead, only update the prototypes and bind the template args
2519 // with the new created definition.
2522 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2524 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2525 == CurRec->getNameInit())
2526 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2527 "' already defined in this multiclass!");
2528 CurMultiClass->DefPrototypes.push_back(CurRec);
2530 // Copy the template arguments for the multiclass into the new def.
2531 const std::vector<Init *> &TA =
2532 CurMultiClass->Rec.getTemplateArgs();
2534 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2535 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2536 assert(RV && "Template arg doesn't exist?");
2537 CurRec->addValue(*RV);
2543 /// ParseDefm - Parse the instantiation of a multiclass.
2545 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2547 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2548 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2549 SMLoc DefmLoc = Lex.getLoc();
2550 Init *DefmPrefix = nullptr;
2552 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2553 DefmPrefix = ParseObjectName(CurMultiClass);
2556 SMLoc DefmPrefixEndLoc = Lex.getLoc();
2557 if (Lex.getCode() != tgtok::colon)
2558 return TokError("expected ':' after defm identifier");
2560 // Keep track of the new generated record definitions.
2561 std::vector<Record*> NewRecDefs;
2563 // This record also inherits from a regular class (non-multiclass)?
2564 bool InheritFromClass = false;
2569 SMLoc SubClassLoc = Lex.getLoc();
2570 SubClassReference Ref = ParseSubClassReference(nullptr, true);
2573 if (!Ref.Rec) return true;
2575 // To instantiate a multiclass, we need to first get the multiclass, then
2576 // instantiate each def contained in the multiclass with the SubClassRef
2577 // template parameters.
2578 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2579 assert(MC && "Didn't lookup multiclass correctly?");
2580 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2582 // Verify that the correct number of template arguments were specified.
2583 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2584 if (TArgs.size() < TemplateVals.size())
2585 return Error(SubClassLoc,
2586 "more template args specified than multiclass expects");
2588 // Loop over all the def's in the multiclass, instantiating each one.
2589 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2590 Record *DefProto = MC->DefPrototypes[i];
2592 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix,
2598 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
2599 TArgs, TemplateVals, true/*Delete args*/))
2600 return Error(SubClassLoc, "could not instantiate def");
2602 if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmLoc))
2603 return Error(SubClassLoc, "could not instantiate def");
2605 NewRecDefs.push_back(CurRec);
2609 if (Lex.getCode() != tgtok::comma) break;
2610 Lex.Lex(); // eat ','.
2612 if (Lex.getCode() != tgtok::Id)
2613 return TokError("expected identifier");
2615 SubClassLoc = Lex.getLoc();
2617 // A defm can inherit from regular classes (non-multiclass) as
2618 // long as they come in the end of the inheritance list.
2619 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
2621 if (InheritFromClass)
2624 Ref = ParseSubClassReference(nullptr, true);
2627 if (InheritFromClass) {
2628 // Process all the classes to inherit as if they were part of a
2629 // regular 'def' and inherit all record values.
2630 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
2633 if (!SubClass.Rec) return true;
2635 // Get the expanded definition prototypes and teach them about
2636 // the record values the current class to inherit has
2637 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2638 Record *CurRec = NewRecDefs[i];
2641 if (AddSubClass(CurRec, SubClass))
2644 if (ApplyLetStack(CurRec))
2648 if (Lex.getCode() != tgtok::comma) break;
2649 Lex.Lex(); // eat ','.
2650 SubClass = ParseSubClassReference(nullptr, false);
2655 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2656 // See Record::setName(). This resolve step will see any new
2657 // name for the def that might have been created when resolving
2658 // inheritance, values and arguments above.
2659 NewRecDefs[i]->resolveReferences();
2661 if (Lex.getCode() != tgtok::semi)
2662 return TokError("expected ';' at end of defm");
2669 /// Object ::= ClassInst
2670 /// Object ::= DefInst
2671 /// Object ::= MultiClassInst
2672 /// Object ::= DefMInst
2673 /// Object ::= LETCommand '{' ObjectList '}'
2674 /// Object ::= LETCommand Object
2675 bool TGParser::ParseObject(MultiClass *MC) {
2676 switch (Lex.getCode()) {
2678 return TokError("Expected class, def, defm, multiclass or let definition");
2679 case tgtok::Let: return ParseTopLevelLet(MC);
2680 case tgtok::Def: return ParseDef(MC);
2681 case tgtok::Foreach: return ParseForeach(MC);
2682 case tgtok::Defm: return ParseDefm(MC);
2683 case tgtok::Class: return ParseClass();
2684 case tgtok::MultiClass: return ParseMultiClass();
2689 /// ObjectList :== Object*
2690 bool TGParser::ParseObjectList(MultiClass *MC) {
2691 while (isObjectStart(Lex.getCode())) {
2692 if (ParseObject(MC))
2698 bool TGParser::ParseFile() {
2699 Lex.Lex(); // Prime the lexer.
2700 if (ParseObjectList()) return true;
2702 // If we have unread input at the end of the file, report it.
2703 if (Lex.getCode() == tgtok::Eof)
2706 return TokError("Unexpected input at top level");