[ORC] Add std::tuple support to SimplePackedSerialization.
[llvm-project.git] / llvm / lib / TableGen / TGParser.cpp
blobed7963031b24285fdd8ade341b26fc4b0acec1fd
1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Implement the Parser for TableGen.
11 //===----------------------------------------------------------------------===//
13 #include "TGParser.h"
14 #include "llvm/ADT/None.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Config/llvm-config.h"
20 #include "llvm/Support/Casting.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include <algorithm>
26 #include <cassert>
27 #include <cstdint>
28 #include <limits>
30 using namespace llvm;
32 //===----------------------------------------------------------------------===//
33 // Support Code for the Semantic Actions.
34 //===----------------------------------------------------------------------===//
36 namespace llvm {
38 struct SubClassReference {
39 SMRange RefRange;
40 Record *Rec;
41 SmallVector<Init*, 4> TemplateArgs;
43 SubClassReference() : Rec(nullptr) {}
45 bool isInvalid() const { return Rec == nullptr; }
48 struct SubMultiClassReference {
49 SMRange RefRange;
50 MultiClass *MC;
51 SmallVector<Init*, 4> TemplateArgs;
53 SubMultiClassReference() : MC(nullptr) {}
55 bool isInvalid() const { return MC == nullptr; }
56 void dump() const;
59 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
60 LLVM_DUMP_METHOD void SubMultiClassReference::dump() const {
61 errs() << "Multiclass:\n";
63 MC->dump();
65 errs() << "Template args:\n";
66 for (Init *TA : TemplateArgs)
67 TA->dump();
69 #endif
71 } // end namespace llvm
73 static bool checkBitsConcrete(Record &R, const RecordVal &RV) {
74 BitsInit *BV = cast<BitsInit>(RV.getValue());
75 for (unsigned i = 0, e = BV->getNumBits(); i != e; ++i) {
76 Init *Bit = BV->getBit(i);
77 bool IsReference = false;
78 if (auto VBI = dyn_cast<VarBitInit>(Bit)) {
79 if (auto VI = dyn_cast<VarInit>(VBI->getBitVar())) {
80 if (R.getValue(VI->getName()))
81 IsReference = true;
83 } else if (isa<VarInit>(Bit)) {
84 IsReference = true;
86 if (!(IsReference || Bit->isConcrete()))
87 return false;
89 return true;
92 static void checkConcrete(Record &R) {
93 for (const RecordVal &RV : R.getValues()) {
94 // HACK: Disable this check for variables declared with 'field'. This is
95 // done merely because existing targets have legitimate cases of
96 // non-concrete variables in helper defs. Ideally, we'd introduce a
97 // 'maybe' or 'optional' modifier instead of this.
98 if (RV.isNonconcreteOK())
99 continue;
101 if (Init *V = RV.getValue()) {
102 bool Ok = isa<BitsInit>(V) ? checkBitsConcrete(R, RV) : V->isConcrete();
103 if (!Ok) {
104 PrintError(R.getLoc(),
105 Twine("Initializer of '") + RV.getNameInitAsString() +
106 "' in '" + R.getNameInitAsString() +
107 "' could not be fully resolved: " +
108 RV.getValue()->getAsString());
114 /// Return an Init with a qualifier prefix referring
115 /// to CurRec's name.
116 static Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass,
117 Init *Name, StringRef Scoper) {
118 Init *NewName =
119 BinOpInit::getStrConcat(CurRec.getNameInit(), StringInit::get(Scoper));
120 NewName = BinOpInit::getStrConcat(NewName, Name);
121 if (CurMultiClass && Scoper != "::") {
122 Init *Prefix = BinOpInit::getStrConcat(CurMultiClass->Rec.getNameInit(),
123 StringInit::get("::"));
124 NewName = BinOpInit::getStrConcat(Prefix, NewName);
127 if (BinOpInit *BinOp = dyn_cast<BinOpInit>(NewName))
128 NewName = BinOp->Fold(&CurRec);
129 return NewName;
132 /// Return the qualified version of the implicit 'NAME' template argument.
133 static Init *QualifiedNameOfImplicitName(Record &Rec,
134 MultiClass *MC = nullptr) {
135 return QualifyName(Rec, MC, StringInit::get("NAME"), MC ? "::" : ":");
138 static Init *QualifiedNameOfImplicitName(MultiClass *MC) {
139 return QualifiedNameOfImplicitName(MC->Rec, MC);
142 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
143 if (!CurRec)
144 CurRec = &CurMultiClass->Rec;
146 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
147 // The value already exists in the class, treat this as a set.
148 if (ERV->setValue(RV.getValue()))
149 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
150 RV.getType()->getAsString() + "' is incompatible with " +
151 "previous definition of type '" +
152 ERV->getType()->getAsString() + "'");
153 } else {
154 CurRec->addValue(RV);
156 return false;
159 /// SetValue -
160 /// Return true on error, false on success.
161 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
162 ArrayRef<unsigned> BitList, Init *V,
163 bool AllowSelfAssignment) {
164 if (!V) return false;
166 if (!CurRec) CurRec = &CurMultiClass->Rec;
168 RecordVal *RV = CurRec->getValue(ValName);
169 if (!RV)
170 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
171 "' unknown!");
173 // Do not allow assignments like 'X = X'. This will just cause infinite loops
174 // in the resolution machinery.
175 if (BitList.empty())
176 if (VarInit *VI = dyn_cast<VarInit>(V))
177 if (VI->getNameInit() == ValName && !AllowSelfAssignment)
178 return Error(Loc, "Recursion / self-assignment forbidden");
180 // If we are assigning to a subset of the bits in the value... then we must be
181 // assigning to a field of BitsRecTy, which must have a BitsInit
182 // initializer.
184 if (!BitList.empty()) {
185 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
186 if (!CurVal)
187 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
188 "' is not a bits type");
190 // Convert the incoming value to a bits type of the appropriate size...
191 Init *BI = V->getCastTo(BitsRecTy::get(BitList.size()));
192 if (!BI)
193 return Error(Loc, "Initializer is not compatible with bit range");
195 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
197 // Loop over bits, assigning values as appropriate.
198 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
199 unsigned Bit = BitList[i];
200 if (NewBits[Bit])
201 return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" +
202 ValName->getAsUnquotedString() + "' more than once");
203 NewBits[Bit] = BI->getBit(i);
206 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
207 if (!NewBits[i])
208 NewBits[i] = CurVal->getBit(i);
210 V = BitsInit::get(NewBits);
213 if (RV->setValue(V, Loc)) {
214 std::string InitType;
215 if (BitsInit *BI = dyn_cast<BitsInit>(V))
216 InitType = (Twine("' of type bit initializer with length ") +
217 Twine(BI->getNumBits())).str();
218 else if (TypedInit *TI = dyn_cast<TypedInit>(V))
219 InitType = (Twine("' of type '") + TI->getType()->getAsString()).str();
220 return Error(Loc, "Field '" + ValName->getAsUnquotedString() +
221 "' of type '" + RV->getType()->getAsString() +
222 "' is incompatible with value '" +
223 V->getAsString() + InitType + "'");
225 return false;
228 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
229 /// args as SubClass's template arguments.
230 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
231 Record *SC = SubClass.Rec;
232 MapResolver R(CurRec);
234 // Loop over all the subclass record's fields. Add template arguments
235 // to the resolver map. Add regular fields to the new record.
236 for (const RecordVal &Field : SC->getValues()) {
237 if (Field.isTemplateArg()) {
238 R.set(Field.getNameInit(), Field.getValue());
239 } else {
240 if (AddValue(CurRec, SubClass.RefRange.Start, Field))
241 return true;
245 ArrayRef<Init *> TArgs = SC->getTemplateArgs();
246 assert(SubClass.TemplateArgs.size() <= TArgs.size() &&
247 "Too many template arguments allowed");
249 // Loop over the template argument names. If a value was specified,
250 // reset the map value. If not and there was no default, complain.
251 for (unsigned I = 0, E = TArgs.size(); I != E; ++I) {
252 if (I < SubClass.TemplateArgs.size())
253 R.set(TArgs[I], SubClass.TemplateArgs[I]);
254 else if (!R.isComplete(TArgs[I]))
255 return Error(SubClass.RefRange.Start,
256 "Value not specified for template argument '" +
257 TArgs[I]->getAsUnquotedString() + "' (#" + Twine(I) +
258 ") of parent class '" + SC->getNameInitAsString() + "'");
261 // Copy the subclass record's assertions to the new record.
262 CurRec->appendAssertions(SC);
264 Init *Name;
265 if (CurRec->isClass())
266 Name =
267 VarInit::get(QualifiedNameOfImplicitName(*CurRec), StringRecTy::get());
268 else
269 Name = CurRec->getNameInit();
270 R.set(QualifiedNameOfImplicitName(*SC), Name);
272 CurRec->resolveReferences(R);
274 // Since everything went well, we can now set the "superclass" list for the
275 // current record.
276 ArrayRef<std::pair<Record *, SMRange>> SCs = SC->getSuperClasses();
277 for (const auto &SCPair : SCs) {
278 if (CurRec->isSubClassOf(SCPair.first))
279 return Error(SubClass.RefRange.Start,
280 "Already subclass of '" + SCPair.first->getName() + "'!\n");
281 CurRec->addSuperClass(SCPair.first, SCPair.second);
284 if (CurRec->isSubClassOf(SC))
285 return Error(SubClass.RefRange.Start,
286 "Already subclass of '" + SC->getName() + "'!\n");
287 CurRec->addSuperClass(SC, SubClass.RefRange);
288 return false;
291 bool TGParser::AddSubClass(RecordsEntry &Entry, SubClassReference &SubClass) {
292 if (Entry.Rec)
293 return AddSubClass(Entry.Rec.get(), SubClass);
295 if (Entry.Assertion)
296 return false;
298 for (auto &E : Entry.Loop->Entries) {
299 if (AddSubClass(E, SubClass))
300 return true;
303 return false;
306 /// AddSubMultiClass - Add SubMultiClass as a subclass to
307 /// CurMC, resolving its template args as SubMultiClass's
308 /// template arguments.
309 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
310 SubMultiClassReference &SubMultiClass) {
311 MultiClass *SMC = SubMultiClass.MC;
313 ArrayRef<Init *> SMCTArgs = SMC->Rec.getTemplateArgs();
314 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
315 return Error(SubMultiClass.RefRange.Start,
316 "More template args specified than expected");
318 // Prepare the mapping of template argument name to value, filling in default
319 // values if necessary.
320 SubstStack TemplateArgs;
321 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
322 if (i < SubMultiClass.TemplateArgs.size()) {
323 TemplateArgs.emplace_back(SMCTArgs[i], SubMultiClass.TemplateArgs[i]);
324 } else {
325 Init *Default = SMC->Rec.getValue(SMCTArgs[i])->getValue();
326 if (!Default->isComplete()) {
327 return Error(SubMultiClass.RefRange.Start,
328 "value not specified for template argument #" + Twine(i) +
329 " (" + SMCTArgs[i]->getAsUnquotedString() +
330 ") of multiclass '" + SMC->Rec.getNameInitAsString() +
331 "'");
333 TemplateArgs.emplace_back(SMCTArgs[i], Default);
337 TemplateArgs.emplace_back(
338 QualifiedNameOfImplicitName(SMC),
339 VarInit::get(QualifiedNameOfImplicitName(CurMC), StringRecTy::get()));
341 // Add all of the defs in the subclass into the current multiclass.
342 return resolve(SMC->Entries, TemplateArgs, false, &CurMC->Entries);
345 /// Add a record, foreach loop, or assertion to the current context.
346 bool TGParser::addEntry(RecordsEntry E) {
347 assert((!!E.Rec + !!E.Loop + !!E.Assertion) == 1 &&
348 "RecordsEntry has invalid number of items");
350 // If we are parsing a loop, add it to the loop's entries.
351 if (!Loops.empty()) {
352 Loops.back()->Entries.push_back(std::move(E));
353 return false;
356 // If it is a loop, then resolve and perform the loop.
357 if (E.Loop) {
358 SubstStack Stack;
359 return resolve(*E.Loop, Stack, CurMultiClass == nullptr,
360 CurMultiClass ? &CurMultiClass->Entries : nullptr);
363 // If we are parsing a multiclass, add it to the multiclass's entries.
364 if (CurMultiClass) {
365 CurMultiClass->Entries.push_back(std::move(E));
366 return false;
369 // If it is an assertion, then it's a top-level one, so check it.
370 if (E.Assertion) {
371 CheckAssert(E.Assertion->Loc, E.Assertion->Condition, E.Assertion->Message);
372 return false;
375 // It must be a record, so finish it off.
376 return addDefOne(std::move(E.Rec));
379 /// Resolve the entries in \p Loop, going over inner loops recursively
380 /// and making the given subsitutions of (name, value) pairs.
382 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
383 /// are added to the global record keeper.
384 bool TGParser::resolve(const ForeachLoop &Loop, SubstStack &Substs,
385 bool Final, std::vector<RecordsEntry> *Dest,
386 SMLoc *Loc) {
387 MapResolver R;
388 for (const auto &S : Substs)
389 R.set(S.first, S.second);
390 Init *List = Loop.ListValue->resolveReferences(R);
391 auto LI = dyn_cast<ListInit>(List);
392 if (!LI) {
393 if (!Final) {
394 Dest->emplace_back(std::make_unique<ForeachLoop>(Loop.Loc, Loop.IterVar,
395 List));
396 return resolve(Loop.Entries, Substs, Final, &Dest->back().Loop->Entries,
397 Loc);
400 PrintError(Loop.Loc, Twine("attempting to loop over '") +
401 List->getAsString() + "', expected a list");
402 return true;
405 bool Error = false;
406 for (auto Elt : *LI) {
407 if (Loop.IterVar)
408 Substs.emplace_back(Loop.IterVar->getNameInit(), Elt);
409 Error = resolve(Loop.Entries, Substs, Final, Dest);
410 if (Loop.IterVar)
411 Substs.pop_back();
412 if (Error)
413 break;
415 return Error;
418 /// Resolve the entries in \p Source, going over loops recursively and
419 /// making the given substitutions of (name, value) pairs.
421 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
422 /// are added to the global record keeper.
423 bool TGParser::resolve(const std::vector<RecordsEntry> &Source,
424 SubstStack &Substs, bool Final,
425 std::vector<RecordsEntry> *Dest, SMLoc *Loc) {
426 bool Error = false;
427 for (auto &E : Source) {
428 if (E.Loop) {
429 Error = resolve(*E.Loop, Substs, Final, Dest);
431 } else if (E.Assertion) {
432 MapResolver R;
433 for (const auto &S : Substs)
434 R.set(S.first, S.second);
435 Init *Condition = E.Assertion->Condition->resolveReferences(R);
436 Init *Message = E.Assertion->Message->resolveReferences(R);
438 if (Dest)
439 Dest->push_back(std::make_unique<Record::AssertionInfo>(
440 E.Assertion->Loc, Condition, Message));
441 else
442 CheckAssert(E.Assertion->Loc, Condition, Message);
444 } else {
445 auto Rec = std::make_unique<Record>(*E.Rec);
446 if (Loc)
447 Rec->appendLoc(*Loc);
449 MapResolver R(Rec.get());
450 for (const auto &S : Substs)
451 R.set(S.first, S.second);
452 Rec->resolveReferences(R);
454 if (Dest)
455 Dest->push_back(std::move(Rec));
456 else
457 Error = addDefOne(std::move(Rec));
459 if (Error)
460 break;
462 return Error;
465 /// Resolve the record fully and add it to the record keeper.
466 bool TGParser::addDefOne(std::unique_ptr<Record> Rec) {
467 Init *NewName = nullptr;
468 if (Record *Prev = Records.getDef(Rec->getNameInitAsString())) {
469 if (!Rec->isAnonymous()) {
470 PrintError(Rec->getLoc(),
471 "def already exists: " + Rec->getNameInitAsString());
472 PrintNote(Prev->getLoc(), "location of previous definition");
473 return true;
475 NewName = Records.getNewAnonymousName();
478 Rec->resolveReferences(NewName);
479 checkConcrete(*Rec);
481 if (!isa<StringInit>(Rec->getNameInit())) {
482 PrintError(Rec->getLoc(), Twine("record name '") +
483 Rec->getNameInit()->getAsString() +
484 "' could not be fully resolved");
485 return true;
488 // Check the assertions.
489 Rec->checkRecordAssertions();
491 // If ObjectBody has template arguments, it's an error.
492 assert(Rec->getTemplateArgs().empty() && "How'd this get template args?");
494 for (DefsetRecord *Defset : Defsets) {
495 DefInit *I = Rec->getDefInit();
496 if (!I->getType()->typeIsA(Defset->EltTy)) {
497 PrintError(Rec->getLoc(), Twine("adding record of incompatible type '") +
498 I->getType()->getAsString() +
499 "' to defset");
500 PrintNote(Defset->Loc, "location of defset declaration");
501 return true;
503 Defset->Elements.push_back(I);
506 Records.addDef(std::move(Rec));
507 return false;
510 //===----------------------------------------------------------------------===//
511 // Parser Code
512 //===----------------------------------------------------------------------===//
514 /// isObjectStart - Return true if this is a valid first token for a statement.
515 static bool isObjectStart(tgtok::TokKind K) {
516 return K == tgtok::Assert || K == tgtok::Class || K == tgtok::Def ||
517 K == tgtok::Defm || K == tgtok::Defset || K == tgtok::Defvar ||
518 K == tgtok::Foreach || K == tgtok::If || K == tgtok::Let ||
519 K == tgtok::MultiClass;
522 bool TGParser::consume(tgtok::TokKind K) {
523 if (Lex.getCode() == K) {
524 Lex.Lex();
525 return true;
527 return false;
530 /// ParseObjectName - If a valid object name is specified, return it. If no
531 /// name is specified, return the unset initializer. Return nullptr on parse
532 /// error.
533 /// ObjectName ::= Value [ '#' Value ]*
534 /// ObjectName ::= /*empty*/
536 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
537 switch (Lex.getCode()) {
538 case tgtok::colon:
539 case tgtok::semi:
540 case tgtok::l_brace:
541 // These are all of the tokens that can begin an object body.
542 // Some of these can also begin values but we disallow those cases
543 // because they are unlikely to be useful.
544 return UnsetInit::get();
545 default:
546 break;
549 Record *CurRec = nullptr;
550 if (CurMultiClass)
551 CurRec = &CurMultiClass->Rec;
553 Init *Name = ParseValue(CurRec, StringRecTy::get(), ParseNameMode);
554 if (!Name)
555 return nullptr;
557 if (CurMultiClass) {
558 Init *NameStr = QualifiedNameOfImplicitName(CurMultiClass);
559 HasReferenceResolver R(NameStr);
560 Name->resolveReferences(R);
561 if (!R.found())
562 Name = BinOpInit::getStrConcat(VarInit::get(NameStr, StringRecTy::get()),
563 Name);
566 return Name;
569 /// ParseClassID - Parse and resolve a reference to a class name. This returns
570 /// null on error.
572 /// ClassID ::= ID
574 Record *TGParser::ParseClassID() {
575 if (Lex.getCode() != tgtok::Id) {
576 TokError("expected name for ClassID");
577 return nullptr;
580 Record *Result = Records.getClass(Lex.getCurStrVal());
581 if (!Result) {
582 std::string Msg("Couldn't find class '" + Lex.getCurStrVal() + "'");
583 if (MultiClasses[Lex.getCurStrVal()].get())
584 TokError(Msg + ". Use 'defm' if you meant to use multiclass '" +
585 Lex.getCurStrVal() + "'");
586 else
587 TokError(Msg);
590 Lex.Lex();
591 return Result;
594 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
595 /// This returns null on error.
597 /// MultiClassID ::= ID
599 MultiClass *TGParser::ParseMultiClassID() {
600 if (Lex.getCode() != tgtok::Id) {
601 TokError("expected name for MultiClassID");
602 return nullptr;
605 MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
606 if (!Result)
607 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
609 Lex.Lex();
610 return Result;
613 /// ParseSubClassReference - Parse a reference to a subclass or a
614 /// multiclass. This returns a SubClassRefTy with a null Record* on error.
616 /// SubClassRef ::= ClassID
617 /// SubClassRef ::= ClassID '<' ValueList '>'
619 SubClassReference TGParser::
620 ParseSubClassReference(Record *CurRec, bool isDefm) {
621 SubClassReference Result;
622 Result.RefRange.Start = Lex.getLoc();
624 if (isDefm) {
625 if (MultiClass *MC = ParseMultiClassID())
626 Result.Rec = &MC->Rec;
627 } else {
628 Result.Rec = ParseClassID();
630 if (!Result.Rec) return Result;
632 // If there is no template arg list, we're done.
633 if (!consume(tgtok::less)) {
634 Result.RefRange.End = Lex.getLoc();
635 return Result;
638 if (ParseTemplateArgValueList(Result.TemplateArgs, CurRec, Result.Rec)) {
639 Result.Rec = nullptr; // Error parsing value list.
640 return Result;
643 if (CheckTemplateArgValues(Result.TemplateArgs, Result.RefRange.Start,
644 Result.Rec)) {
645 Result.Rec = nullptr; // Error checking value list.
646 return Result;
649 Result.RefRange.End = Lex.getLoc();
650 return Result;
653 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
654 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
655 /// Record* on error.
657 /// SubMultiClassRef ::= MultiClassID
658 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
660 SubMultiClassReference TGParser::
661 ParseSubMultiClassReference(MultiClass *CurMC) {
662 SubMultiClassReference Result;
663 Result.RefRange.Start = Lex.getLoc();
665 Result.MC = ParseMultiClassID();
666 if (!Result.MC) return Result;
668 // If there is no template arg list, we're done.
669 if (!consume(tgtok::less)) {
670 Result.RefRange.End = Lex.getLoc();
671 return Result;
674 if (ParseTemplateArgValueList(Result.TemplateArgs, &CurMC->Rec,
675 &Result.MC->Rec)) {
676 Result.MC = nullptr; // Error parsing value list.
677 return Result;
680 Result.RefRange.End = Lex.getLoc();
682 return Result;
685 /// ParseRangePiece - Parse a bit/value range.
686 /// RangePiece ::= INTVAL
687 /// RangePiece ::= INTVAL '...' INTVAL
688 /// RangePiece ::= INTVAL '-' INTVAL
689 /// RangePiece ::= INTVAL INTVAL
690 // The last two forms are deprecated.
691 bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
692 TypedInit *FirstItem) {
693 Init *CurVal = FirstItem;
694 if (!CurVal)
695 CurVal = ParseValue(nullptr);
697 IntInit *II = dyn_cast_or_null<IntInit>(CurVal);
698 if (!II)
699 return TokError("expected integer or bitrange");
701 int64_t Start = II->getValue();
702 int64_t End;
704 if (Start < 0)
705 return TokError("invalid range, cannot be negative");
707 switch (Lex.getCode()) {
708 default:
709 Ranges.push_back(Start);
710 return false;
712 case tgtok::dotdotdot:
713 case tgtok::minus: {
714 Lex.Lex(); // eat
716 Init *I_End = ParseValue(nullptr);
717 IntInit *II_End = dyn_cast_or_null<IntInit>(I_End);
718 if (!II_End) {
719 TokError("expected integer value as end of range");
720 return true;
723 End = II_End->getValue();
724 break;
726 case tgtok::IntVal: {
727 End = -Lex.getCurIntVal();
728 Lex.Lex();
729 break;
732 if (End < 0)
733 return TokError("invalid range, cannot be negative");
735 // Add to the range.
736 if (Start < End)
737 for (; Start <= End; ++Start)
738 Ranges.push_back(Start);
739 else
740 for (; Start >= End; --Start)
741 Ranges.push_back(Start);
742 return false;
745 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
747 /// RangeList ::= RangePiece (',' RangePiece)*
749 void TGParser::ParseRangeList(SmallVectorImpl<unsigned> &Result) {
750 // Parse the first piece.
751 if (ParseRangePiece(Result)) {
752 Result.clear();
753 return;
755 while (consume(tgtok::comma))
756 // Parse the next range piece.
757 if (ParseRangePiece(Result)) {
758 Result.clear();
759 return;
763 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
764 /// OptionalRangeList ::= '<' RangeList '>'
765 /// OptionalRangeList ::= /*empty*/
766 bool TGParser::ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges) {
767 SMLoc StartLoc = Lex.getLoc();
768 if (!consume(tgtok::less))
769 return false;
771 // Parse the range list.
772 ParseRangeList(Ranges);
773 if (Ranges.empty()) return true;
775 if (!consume(tgtok::greater)) {
776 TokError("expected '>' at end of range list");
777 return Error(StartLoc, "to match this '<'");
779 return false;
782 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
783 /// OptionalBitList ::= '{' RangeList '}'
784 /// OptionalBitList ::= /*empty*/
785 bool TGParser::ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges) {
786 SMLoc StartLoc = Lex.getLoc();
787 if (!consume(tgtok::l_brace))
788 return false;
790 // Parse the range list.
791 ParseRangeList(Ranges);
792 if (Ranges.empty()) return true;
794 if (!consume(tgtok::r_brace)) {
795 TokError("expected '}' at end of bit list");
796 return Error(StartLoc, "to match this '{'");
798 return false;
801 /// ParseType - Parse and return a tblgen type. This returns null on error.
803 /// Type ::= STRING // string type
804 /// Type ::= CODE // code type
805 /// Type ::= BIT // bit type
806 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
807 /// Type ::= INT // int type
808 /// Type ::= LIST '<' Type '>' // list<x> type
809 /// Type ::= DAG // dag type
810 /// Type ::= ClassID // Record Type
812 RecTy *TGParser::ParseType() {
813 switch (Lex.getCode()) {
814 default: TokError("Unknown token when expecting a type"); return nullptr;
815 case tgtok::String:
816 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
817 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
818 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
819 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
820 case tgtok::Id:
821 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
822 TokError("unknown class name");
823 return nullptr;
824 case tgtok::Bits: {
825 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
826 TokError("expected '<' after bits type");
827 return nullptr;
829 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
830 TokError("expected integer in bits<n> type");
831 return nullptr;
833 uint64_t Val = Lex.getCurIntVal();
834 if (Lex.Lex() != tgtok::greater) { // Eat count.
835 TokError("expected '>' at end of bits<n> type");
836 return nullptr;
838 Lex.Lex(); // Eat '>'
839 return BitsRecTy::get(Val);
841 case tgtok::List: {
842 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
843 TokError("expected '<' after list type");
844 return nullptr;
846 Lex.Lex(); // Eat '<'
847 RecTy *SubType = ParseType();
848 if (!SubType) return nullptr;
850 if (!consume(tgtok::greater)) {
851 TokError("expected '>' at end of list<ty> type");
852 return nullptr;
854 return ListRecTy::get(SubType);
859 /// ParseIDValue
860 Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMLoc NameLoc,
861 IDParseMode Mode) {
862 if (CurRec) {
863 if (const RecordVal *RV = CurRec->getValue(Name))
864 return VarInit::get(Name, RV->getType());
867 if ((CurRec && CurRec->isClass()) || CurMultiClass) {
868 Init *TemplateArgName;
869 if (CurMultiClass) {
870 TemplateArgName =
871 QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
872 } else
873 TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
875 Record *TemplateRec = CurMultiClass ? &CurMultiClass->Rec : CurRec;
876 if (TemplateRec->isTemplateArg(TemplateArgName)) {
877 const RecordVal *RV = TemplateRec->getValue(TemplateArgName);
878 assert(RV && "Template arg doesn't exist??");
879 return VarInit::get(TemplateArgName, RV->getType());
880 } else if (Name->getValue() == "NAME") {
881 return VarInit::get(TemplateArgName, StringRecTy::get());
885 if (CurLocalScope)
886 if (Init *I = CurLocalScope->getVar(Name->getValue()))
887 return I;
889 // If this is in a foreach loop, make sure it's not a loop iterator
890 for (const auto &L : Loops) {
891 if (L->IterVar) {
892 VarInit *IterVar = dyn_cast<VarInit>(L->IterVar);
893 if (IterVar && IterVar->getNameInit() == Name)
894 return IterVar;
898 if (Mode == ParseNameMode)
899 return Name;
901 if (Init *I = Records.getGlobal(Name->getValue()))
902 return I;
904 // Allow self-references of concrete defs, but delay the lookup so that we
905 // get the correct type.
906 if (CurRec && !CurRec->isClass() && !CurMultiClass &&
907 CurRec->getNameInit() == Name)
908 return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType());
910 Error(NameLoc, "Variable not defined: '" + Name->getValue() + "'");
911 return nullptr;
914 /// ParseOperation - Parse an operator. This returns null on error.
916 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
918 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
919 switch (Lex.getCode()) {
920 default:
921 TokError("unknown bang operator");
922 return nullptr;
923 case tgtok::XNOT:
924 case tgtok::XHead:
925 case tgtok::XTail:
926 case tgtok::XSize:
927 case tgtok::XEmpty:
928 case tgtok::XCast:
929 case tgtok::XGetDagOp: { // Value ::= !unop '(' Value ')'
930 UnOpInit::UnaryOp Code;
931 RecTy *Type = nullptr;
933 switch (Lex.getCode()) {
934 default: llvm_unreachable("Unhandled code!");
935 case tgtok::XCast:
936 Lex.Lex(); // eat the operation
937 Code = UnOpInit::CAST;
939 Type = ParseOperatorType();
941 if (!Type) {
942 TokError("did not get type for unary operator");
943 return nullptr;
946 break;
947 case tgtok::XNOT:
948 Lex.Lex(); // eat the operation
949 Code = UnOpInit::NOT;
950 Type = IntRecTy::get();
951 break;
952 case tgtok::XHead:
953 Lex.Lex(); // eat the operation
954 Code = UnOpInit::HEAD;
955 break;
956 case tgtok::XTail:
957 Lex.Lex(); // eat the operation
958 Code = UnOpInit::TAIL;
959 break;
960 case tgtok::XSize:
961 Lex.Lex();
962 Code = UnOpInit::SIZE;
963 Type = IntRecTy::get();
964 break;
965 case tgtok::XEmpty:
966 Lex.Lex(); // eat the operation
967 Code = UnOpInit::EMPTY;
968 Type = IntRecTy::get();
969 break;
970 case tgtok::XGetDagOp:
971 Lex.Lex(); // eat the operation
972 if (Lex.getCode() == tgtok::less) {
973 // Parse an optional type suffix, so that you can say
974 // !getdagop<BaseClass>(someDag) as a shorthand for
975 // !cast<BaseClass>(!getdagop(someDag)).
976 Type = ParseOperatorType();
978 if (!Type) {
979 TokError("did not get type for unary operator");
980 return nullptr;
983 if (!isa<RecordRecTy>(Type)) {
984 TokError("type for !getdagop must be a record type");
985 // but keep parsing, to consume the operand
987 } else {
988 Type = RecordRecTy::get({});
990 Code = UnOpInit::GETDAGOP;
991 break;
993 if (!consume(tgtok::l_paren)) {
994 TokError("expected '(' after unary operator");
995 return nullptr;
998 Init *LHS = ParseValue(CurRec);
999 if (!LHS) return nullptr;
1001 if (Code == UnOpInit::EMPTY || Code == UnOpInit::SIZE) {
1002 ListInit *LHSl = dyn_cast<ListInit>(LHS);
1003 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1004 DagInit *LHSd = dyn_cast<DagInit>(LHS);
1005 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1006 if (!LHSl && !LHSs && !LHSd && !LHSt) {
1007 TokError("expected string, list, or dag type argument in unary operator");
1008 return nullptr;
1010 if (LHSt) {
1011 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1012 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
1013 DagRecTy *DType = dyn_cast<DagRecTy>(LHSt->getType());
1014 if (!LType && !SType && !DType) {
1015 TokError("expected string, list, or dag type argument in unary operator");
1016 return nullptr;
1021 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
1022 ListInit *LHSl = dyn_cast<ListInit>(LHS);
1023 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1024 if (!LHSl && !LHSt) {
1025 TokError("expected list type argument in unary operator");
1026 return nullptr;
1028 if (LHSt) {
1029 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1030 if (!LType) {
1031 TokError("expected list type argument in unary operator");
1032 return nullptr;
1036 if (LHSl && LHSl->empty()) {
1037 TokError("empty list argument in unary operator");
1038 return nullptr;
1040 if (LHSl) {
1041 Init *Item = LHSl->getElement(0);
1042 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
1043 if (!Itemt) {
1044 TokError("untyped list element in unary operator");
1045 return nullptr;
1047 Type = (Code == UnOpInit::HEAD) ? Itemt->getType()
1048 : ListRecTy::get(Itemt->getType());
1049 } else {
1050 assert(LHSt && "expected list type argument in unary operator");
1051 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1052 Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType;
1056 if (!consume(tgtok::r_paren)) {
1057 TokError("expected ')' in unary operator");
1058 return nullptr;
1060 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec);
1063 case tgtok::XIsA: {
1064 // Value ::= !isa '<' Type '>' '(' Value ')'
1065 Lex.Lex(); // eat the operation
1067 RecTy *Type = ParseOperatorType();
1068 if (!Type)
1069 return nullptr;
1071 if (!consume(tgtok::l_paren)) {
1072 TokError("expected '(' after type of !isa");
1073 return nullptr;
1076 Init *LHS = ParseValue(CurRec);
1077 if (!LHS)
1078 return nullptr;
1080 if (!consume(tgtok::r_paren)) {
1081 TokError("expected ')' in !isa");
1082 return nullptr;
1085 return (IsAOpInit::get(Type, LHS))->Fold();
1088 case tgtok::XConcat:
1089 case tgtok::XADD:
1090 case tgtok::XSUB:
1091 case tgtok::XMUL:
1092 case tgtok::XAND:
1093 case tgtok::XOR:
1094 case tgtok::XXOR:
1095 case tgtok::XSRA:
1096 case tgtok::XSRL:
1097 case tgtok::XSHL:
1098 case tgtok::XEq:
1099 case tgtok::XNe:
1100 case tgtok::XLe:
1101 case tgtok::XLt:
1102 case tgtok::XGe:
1103 case tgtok::XGt:
1104 case tgtok::XListConcat:
1105 case tgtok::XListSplat:
1106 case tgtok::XStrConcat:
1107 case tgtok::XInterleave:
1108 case tgtok::XSetDagOp: { // Value ::= !binop '(' Value ',' Value ')'
1109 tgtok::TokKind OpTok = Lex.getCode();
1110 SMLoc OpLoc = Lex.getLoc();
1111 Lex.Lex(); // eat the operation
1113 BinOpInit::BinaryOp Code;
1114 switch (OpTok) {
1115 default: llvm_unreachable("Unhandled code!");
1116 case tgtok::XConcat: Code = BinOpInit::CONCAT; break;
1117 case tgtok::XADD: Code = BinOpInit::ADD; break;
1118 case tgtok::XSUB: Code = BinOpInit::SUB; break;
1119 case tgtok::XMUL: Code = BinOpInit::MUL; break;
1120 case tgtok::XAND: Code = BinOpInit::AND; break;
1121 case tgtok::XOR: Code = BinOpInit::OR; break;
1122 case tgtok::XXOR: Code = BinOpInit::XOR; break;
1123 case tgtok::XSRA: Code = BinOpInit::SRA; break;
1124 case tgtok::XSRL: Code = BinOpInit::SRL; break;
1125 case tgtok::XSHL: Code = BinOpInit::SHL; break;
1126 case tgtok::XEq: Code = BinOpInit::EQ; break;
1127 case tgtok::XNe: Code = BinOpInit::NE; break;
1128 case tgtok::XLe: Code = BinOpInit::LE; break;
1129 case tgtok::XLt: Code = BinOpInit::LT; break;
1130 case tgtok::XGe: Code = BinOpInit::GE; break;
1131 case tgtok::XGt: Code = BinOpInit::GT; break;
1132 case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break;
1133 case tgtok::XListSplat: Code = BinOpInit::LISTSPLAT; break;
1134 case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break;
1135 case tgtok::XInterleave: Code = BinOpInit::INTERLEAVE; break;
1136 case tgtok::XSetDagOp: Code = BinOpInit::SETDAGOP; break;
1139 RecTy *Type = nullptr;
1140 RecTy *ArgType = nullptr;
1141 switch (OpTok) {
1142 default:
1143 llvm_unreachable("Unhandled code!");
1144 case tgtok::XConcat:
1145 case tgtok::XSetDagOp:
1146 Type = DagRecTy::get();
1147 ArgType = DagRecTy::get();
1148 break;
1149 case tgtok::XAND:
1150 case tgtok::XOR:
1151 case tgtok::XXOR:
1152 case tgtok::XSRA:
1153 case tgtok::XSRL:
1154 case tgtok::XSHL:
1155 case tgtok::XADD:
1156 case tgtok::XSUB:
1157 case tgtok::XMUL:
1158 Type = IntRecTy::get();
1159 ArgType = IntRecTy::get();
1160 break;
1161 case tgtok::XEq:
1162 case tgtok::XNe:
1163 case tgtok::XLe:
1164 case tgtok::XLt:
1165 case tgtok::XGe:
1166 case tgtok::XGt:
1167 Type = BitRecTy::get();
1168 // ArgType for the comparison operators is not yet known.
1169 break;
1170 case tgtok::XListConcat:
1171 // We don't know the list type until we parse the first argument
1172 ArgType = ItemType;
1173 break;
1174 case tgtok::XListSplat:
1175 // Can't do any typechecking until we parse the first argument.
1176 break;
1177 case tgtok::XStrConcat:
1178 Type = StringRecTy::get();
1179 ArgType = StringRecTy::get();
1180 break;
1181 case tgtok::XInterleave:
1182 Type = StringRecTy::get();
1183 // The first argument type is not yet known.
1186 if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) {
1187 Error(OpLoc, Twine("expected value of type '") +
1188 ItemType->getAsString() + "', got '" +
1189 Type->getAsString() + "'");
1190 return nullptr;
1193 if (!consume(tgtok::l_paren)) {
1194 TokError("expected '(' after binary operator");
1195 return nullptr;
1198 SmallVector<Init*, 2> InitList;
1200 // Note that this loop consumes an arbitrary number of arguments.
1201 // The actual count is checked later.
1202 for (;;) {
1203 SMLoc InitLoc = Lex.getLoc();
1204 InitList.push_back(ParseValue(CurRec, ArgType));
1205 if (!InitList.back()) return nullptr;
1207 TypedInit *InitListBack = dyn_cast<TypedInit>(InitList.back());
1208 if (!InitListBack) {
1209 Error(OpLoc, Twine("expected value to be a typed value, got '" +
1210 InitList.back()->getAsString() + "'"));
1211 return nullptr;
1213 RecTy *ListType = InitListBack->getType();
1215 if (!ArgType) {
1216 // Argument type must be determined from the argument itself.
1217 ArgType = ListType;
1219 switch (Code) {
1220 case BinOpInit::LISTCONCAT:
1221 if (!isa<ListRecTy>(ArgType)) {
1222 Error(InitLoc, Twine("expected a list, got value of type '") +
1223 ArgType->getAsString() + "'");
1224 return nullptr;
1226 break;
1227 case BinOpInit::LISTSPLAT:
1228 if (ItemType && InitList.size() == 1) {
1229 if (!isa<ListRecTy>(ItemType)) {
1230 Error(OpLoc,
1231 Twine("expected output type to be a list, got type '") +
1232 ItemType->getAsString() + "'");
1233 return nullptr;
1235 if (!ArgType->getListTy()->typeIsConvertibleTo(ItemType)) {
1236 Error(OpLoc, Twine("expected first arg type to be '") +
1237 ArgType->getAsString() +
1238 "', got value of type '" +
1239 cast<ListRecTy>(ItemType)
1240 ->getElementType()
1241 ->getAsString() +
1242 "'");
1243 return nullptr;
1246 if (InitList.size() == 2 && !isa<IntRecTy>(ArgType)) {
1247 Error(InitLoc, Twine("expected second parameter to be an int, got "
1248 "value of type '") +
1249 ArgType->getAsString() + "'");
1250 return nullptr;
1252 ArgType = nullptr; // Broken invariant: types not identical.
1253 break;
1254 case BinOpInit::EQ:
1255 case BinOpInit::NE:
1256 if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) &&
1257 !ArgType->typeIsConvertibleTo(StringRecTy::get()) &&
1258 !ArgType->typeIsConvertibleTo(RecordRecTy::get({}))) {
1259 Error(InitLoc, Twine("expected bit, bits, int, string, or record; "
1260 "got value of type '") + ArgType->getAsString() +
1261 "'");
1262 return nullptr;
1264 break;
1265 case BinOpInit::LE:
1266 case BinOpInit::LT:
1267 case BinOpInit::GE:
1268 case BinOpInit::GT:
1269 if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) &&
1270 !ArgType->typeIsConvertibleTo(StringRecTy::get())) {
1271 Error(InitLoc, Twine("expected bit, bits, int, or string; "
1272 "got value of type '") + ArgType->getAsString() +
1273 "'");
1274 return nullptr;
1276 break;
1277 case BinOpInit::INTERLEAVE:
1278 switch (InitList.size()) {
1279 case 1: // First argument must be a list of strings or integers.
1280 if (ArgType != StringRecTy::get()->getListTy() &&
1281 !ArgType->typeIsConvertibleTo(IntRecTy::get()->getListTy())) {
1282 Error(InitLoc, Twine("expected list of string, int, bits, or bit; "
1283 "got value of type '") +
1284 ArgType->getAsString() + "'");
1285 return nullptr;
1287 break;
1288 case 2: // Second argument must be a string.
1289 if (!isa<StringRecTy>(ArgType)) {
1290 Error(InitLoc, Twine("expected second argument to be a string, "
1291 "got value of type '") +
1292 ArgType->getAsString() + "'");
1293 return nullptr;
1295 break;
1296 default: ;
1298 ArgType = nullptr; // Broken invariant: types not identical.
1299 break;
1300 default: llvm_unreachable("other ops have fixed argument types");
1303 } else {
1304 // Desired argument type is a known and in ArgType.
1305 RecTy *Resolved = resolveTypes(ArgType, ListType);
1306 if (!Resolved) {
1307 Error(InitLoc, Twine("expected value of type '") +
1308 ArgType->getAsString() + "', got '" +
1309 ListType->getAsString() + "'");
1310 return nullptr;
1312 if (Code != BinOpInit::ADD && Code != BinOpInit::SUB &&
1313 Code != BinOpInit::AND && Code != BinOpInit::OR &&
1314 Code != BinOpInit::XOR && Code != BinOpInit::SRA &&
1315 Code != BinOpInit::SRL && Code != BinOpInit::SHL &&
1316 Code != BinOpInit::MUL)
1317 ArgType = Resolved;
1320 // Deal with BinOps whose arguments have different types, by
1321 // rewriting ArgType in between them.
1322 switch (Code) {
1323 case BinOpInit::SETDAGOP:
1324 // After parsing the first dag argument, switch to expecting
1325 // a record, with no restriction on its superclasses.
1326 ArgType = RecordRecTy::get({});
1327 break;
1328 default:
1329 break;
1332 if (!consume(tgtok::comma))
1333 break;
1336 if (!consume(tgtok::r_paren)) {
1337 TokError("expected ')' in operator");
1338 return nullptr;
1341 // listconcat returns a list with type of the argument.
1342 if (Code == BinOpInit::LISTCONCAT)
1343 Type = ArgType;
1344 // listsplat returns a list of type of the *first* argument.
1345 if (Code == BinOpInit::LISTSPLAT)
1346 Type = cast<TypedInit>(InitList.front())->getType()->getListTy();
1348 // We allow multiple operands to associative operators like !strconcat as
1349 // shorthand for nesting them.
1350 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT ||
1351 Code == BinOpInit::CONCAT || Code == BinOpInit::ADD ||
1352 Code == BinOpInit::AND || Code == BinOpInit::OR ||
1353 Code == BinOpInit::XOR || Code == BinOpInit::MUL) {
1354 while (InitList.size() > 2) {
1355 Init *RHS = InitList.pop_back_val();
1356 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec);
1357 InitList.back() = RHS;
1361 if (InitList.size() == 2)
1362 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
1363 ->Fold(CurRec);
1365 Error(OpLoc, "expected two operands to operator");
1366 return nullptr;
1369 case tgtok::XForEach:
1370 case tgtok::XFilter: {
1371 return ParseOperationForEachFilter(CurRec, ItemType);
1374 case tgtok::XDag:
1375 case tgtok::XIf:
1376 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1377 TernOpInit::TernaryOp Code;
1378 RecTy *Type = nullptr;
1380 tgtok::TokKind LexCode = Lex.getCode();
1381 Lex.Lex(); // eat the operation
1382 switch (LexCode) {
1383 default: llvm_unreachable("Unhandled code!");
1384 case tgtok::XDag:
1385 Code = TernOpInit::DAG;
1386 Type = DagRecTy::get();
1387 ItemType = nullptr;
1388 break;
1389 case tgtok::XIf:
1390 Code = TernOpInit::IF;
1391 break;
1392 case tgtok::XSubst:
1393 Code = TernOpInit::SUBST;
1394 break;
1396 if (!consume(tgtok::l_paren)) {
1397 TokError("expected '(' after ternary operator");
1398 return nullptr;
1401 Init *LHS = ParseValue(CurRec);
1402 if (!LHS) return nullptr;
1404 if (!consume(tgtok::comma)) {
1405 TokError("expected ',' in ternary operator");
1406 return nullptr;
1409 SMLoc MHSLoc = Lex.getLoc();
1410 Init *MHS = ParseValue(CurRec, ItemType);
1411 if (!MHS)
1412 return nullptr;
1414 if (!consume(tgtok::comma)) {
1415 TokError("expected ',' in ternary operator");
1416 return nullptr;
1419 SMLoc RHSLoc = Lex.getLoc();
1420 Init *RHS = ParseValue(CurRec, ItemType);
1421 if (!RHS)
1422 return nullptr;
1424 if (!consume(tgtok::r_paren)) {
1425 TokError("expected ')' in binary operator");
1426 return nullptr;
1429 switch (LexCode) {
1430 default: llvm_unreachable("Unhandled code!");
1431 case tgtok::XDag: {
1432 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1433 if (!MHSt && !isa<UnsetInit>(MHS)) {
1434 Error(MHSLoc, "could not determine type of the child list in !dag");
1435 return nullptr;
1437 if (MHSt && !isa<ListRecTy>(MHSt->getType())) {
1438 Error(MHSLoc, Twine("expected list of children, got type '") +
1439 MHSt->getType()->getAsString() + "'");
1440 return nullptr;
1443 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1444 if (!RHSt && !isa<UnsetInit>(RHS)) {
1445 Error(RHSLoc, "could not determine type of the name list in !dag");
1446 return nullptr;
1448 if (RHSt && StringRecTy::get()->getListTy() != RHSt->getType()) {
1449 Error(RHSLoc, Twine("expected list<string>, got type '") +
1450 RHSt->getType()->getAsString() + "'");
1451 return nullptr;
1454 if (!MHSt && !RHSt) {
1455 Error(MHSLoc,
1456 "cannot have both unset children and unset names in !dag");
1457 return nullptr;
1459 break;
1461 case tgtok::XIf: {
1462 RecTy *MHSTy = nullptr;
1463 RecTy *RHSTy = nullptr;
1465 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1466 MHSTy = MHSt->getType();
1467 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1468 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1469 if (isa<BitInit>(MHS))
1470 MHSTy = BitRecTy::get();
1472 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1473 RHSTy = RHSt->getType();
1474 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1475 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1476 if (isa<BitInit>(RHS))
1477 RHSTy = BitRecTy::get();
1479 // For UnsetInit, it's typed from the other hand.
1480 if (isa<UnsetInit>(MHS))
1481 MHSTy = RHSTy;
1482 if (isa<UnsetInit>(RHS))
1483 RHSTy = MHSTy;
1485 if (!MHSTy || !RHSTy) {
1486 TokError("could not get type for !if");
1487 return nullptr;
1490 Type = resolveTypes(MHSTy, RHSTy);
1491 if (!Type) {
1492 TokError(Twine("inconsistent types '") + MHSTy->getAsString() +
1493 "' and '" + RHSTy->getAsString() + "' for !if");
1494 return nullptr;
1496 break;
1498 case tgtok::XSubst: {
1499 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1500 if (!RHSt) {
1501 TokError("could not get type for !subst");
1502 return nullptr;
1504 Type = RHSt->getType();
1505 break;
1508 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
1511 case tgtok::XSubstr:
1512 return ParseOperationSubstr(CurRec, ItemType);
1514 case tgtok::XFind:
1515 return ParseOperationFind(CurRec, ItemType);
1517 case tgtok::XCond:
1518 return ParseOperationCond(CurRec, ItemType);
1520 case tgtok::XFoldl: {
1521 // Value ::= !foldl '(' Value ',' Value ',' Id ',' Id ',' Expr ')'
1522 Lex.Lex(); // eat the operation
1523 if (!consume(tgtok::l_paren)) {
1524 TokError("expected '(' after !foldl");
1525 return nullptr;
1528 Init *StartUntyped = ParseValue(CurRec);
1529 if (!StartUntyped)
1530 return nullptr;
1532 TypedInit *Start = dyn_cast<TypedInit>(StartUntyped);
1533 if (!Start) {
1534 TokError(Twine("could not get type of !foldl start: '") +
1535 StartUntyped->getAsString() + "'");
1536 return nullptr;
1539 if (!consume(tgtok::comma)) {
1540 TokError("expected ',' in !foldl");
1541 return nullptr;
1544 Init *ListUntyped = ParseValue(CurRec);
1545 if (!ListUntyped)
1546 return nullptr;
1548 TypedInit *List = dyn_cast<TypedInit>(ListUntyped);
1549 if (!List) {
1550 TokError(Twine("could not get type of !foldl list: '") +
1551 ListUntyped->getAsString() + "'");
1552 return nullptr;
1555 ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType());
1556 if (!ListType) {
1557 TokError(Twine("!foldl list must be a list, but is of type '") +
1558 List->getType()->getAsString());
1559 return nullptr;
1562 if (Lex.getCode() != tgtok::comma) {
1563 TokError("expected ',' in !foldl");
1564 return nullptr;
1567 if (Lex.Lex() != tgtok::Id) { // eat the ','
1568 TokError("third argument of !foldl must be an identifier");
1569 return nullptr;
1572 Init *A = StringInit::get(Lex.getCurStrVal());
1573 if (CurRec && CurRec->getValue(A)) {
1574 TokError((Twine("left !foldl variable '") + A->getAsString() +
1575 "' already defined")
1576 .str());
1577 return nullptr;
1580 if (Lex.Lex() != tgtok::comma) { // eat the id
1581 TokError("expected ',' in !foldl");
1582 return nullptr;
1585 if (Lex.Lex() != tgtok::Id) { // eat the ','
1586 TokError("fourth argument of !foldl must be an identifier");
1587 return nullptr;
1590 Init *B = StringInit::get(Lex.getCurStrVal());
1591 if (CurRec && CurRec->getValue(B)) {
1592 TokError((Twine("right !foldl variable '") + B->getAsString() +
1593 "' already defined")
1594 .str());
1595 return nullptr;
1598 if (Lex.Lex() != tgtok::comma) { // eat the id
1599 TokError("expected ',' in !foldl");
1600 return nullptr;
1602 Lex.Lex(); // eat the ','
1604 // We need to create a temporary record to provide a scope for the
1605 // two variables.
1606 std::unique_ptr<Record> ParseRecTmp;
1607 Record *ParseRec = CurRec;
1608 if (!ParseRec) {
1609 ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1610 ParseRec = ParseRecTmp.get();
1613 ParseRec->addValue(RecordVal(A, Start->getType(), RecordVal::FK_Normal));
1614 ParseRec->addValue(RecordVal(B, ListType->getElementType(),
1615 RecordVal::FK_Normal));
1616 Init *ExprUntyped = ParseValue(ParseRec);
1617 ParseRec->removeValue(A);
1618 ParseRec->removeValue(B);
1619 if (!ExprUntyped)
1620 return nullptr;
1622 TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped);
1623 if (!Expr) {
1624 TokError("could not get type of !foldl expression");
1625 return nullptr;
1628 if (Expr->getType() != Start->getType()) {
1629 TokError(Twine("!foldl expression must be of same type as start (") +
1630 Start->getType()->getAsString() + "), but is of type " +
1631 Expr->getType()->getAsString());
1632 return nullptr;
1635 if (!consume(tgtok::r_paren)) {
1636 TokError("expected ')' in fold operator");
1637 return nullptr;
1640 return FoldOpInit::get(Start, List, A, B, Expr, Start->getType())
1641 ->Fold(CurRec);
1646 /// ParseOperatorType - Parse a type for an operator. This returns
1647 /// null on error.
1649 /// OperatorType ::= '<' Type '>'
1651 RecTy *TGParser::ParseOperatorType() {
1652 RecTy *Type = nullptr;
1654 if (!consume(tgtok::less)) {
1655 TokError("expected type name for operator");
1656 return nullptr;
1659 if (Lex.getCode() == tgtok::Code)
1660 TokError("the 'code' type is not allowed in bang operators; use 'string'");
1662 Type = ParseType();
1664 if (!Type) {
1665 TokError("expected type name for operator");
1666 return nullptr;
1669 if (!consume(tgtok::greater)) {
1670 TokError("expected type name for operator");
1671 return nullptr;
1674 return Type;
1677 /// Parse the !substr operation. Return null on error.
1679 /// Substr ::= !substr(string, start-int [, length-int]) => string
1680 Init *TGParser::ParseOperationSubstr(Record *CurRec, RecTy *ItemType) {
1681 TernOpInit::TernaryOp Code = TernOpInit::SUBSTR;
1682 RecTy *Type = StringRecTy::get();
1684 Lex.Lex(); // eat the operation
1686 if (!consume(tgtok::l_paren)) {
1687 TokError("expected '(' after !substr operator");
1688 return nullptr;
1691 Init *LHS = ParseValue(CurRec);
1692 if (!LHS)
1693 return nullptr;
1695 if (!consume(tgtok::comma)) {
1696 TokError("expected ',' in !substr operator");
1697 return nullptr;
1700 SMLoc MHSLoc = Lex.getLoc();
1701 Init *MHS = ParseValue(CurRec);
1702 if (!MHS)
1703 return nullptr;
1705 SMLoc RHSLoc = Lex.getLoc();
1706 Init *RHS;
1707 if (consume(tgtok::comma)) {
1708 RHSLoc = Lex.getLoc();
1709 RHS = ParseValue(CurRec);
1710 if (!RHS)
1711 return nullptr;
1712 } else {
1713 RHS = IntInit::get(std::numeric_limits<int64_t>::max());
1716 if (!consume(tgtok::r_paren)) {
1717 TokError("expected ')' in !substr operator");
1718 return nullptr;
1721 if (ItemType && !Type->typeIsConvertibleTo(ItemType)) {
1722 Error(RHSLoc, Twine("expected value of type '") +
1723 ItemType->getAsString() + "', got '" +
1724 Type->getAsString() + "'");
1727 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1728 if (!LHSt && !isa<UnsetInit>(LHS)) {
1729 TokError("could not determine type of the string in !substr");
1730 return nullptr;
1732 if (LHSt && !isa<StringRecTy>(LHSt->getType())) {
1733 TokError(Twine("expected string, got type '") +
1734 LHSt->getType()->getAsString() + "'");
1735 return nullptr;
1738 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1739 if (!MHSt && !isa<UnsetInit>(MHS)) {
1740 TokError("could not determine type of the start position in !substr");
1741 return nullptr;
1743 if (MHSt && !isa<IntRecTy>(MHSt->getType())) {
1744 Error(MHSLoc, Twine("expected int, got type '") +
1745 MHSt->getType()->getAsString() + "'");
1746 return nullptr;
1749 if (RHS) {
1750 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1751 if (!RHSt && !isa<UnsetInit>(RHS)) {
1752 TokError("could not determine type of the length in !substr");
1753 return nullptr;
1755 if (RHSt && !isa<IntRecTy>(RHSt->getType())) {
1756 TokError(Twine("expected int, got type '") +
1757 RHSt->getType()->getAsString() + "'");
1758 return nullptr;
1762 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
1765 /// Parse the !find operation. Return null on error.
1767 /// Substr ::= !find(string, string [, start-int]) => int
1768 Init *TGParser::ParseOperationFind(Record *CurRec, RecTy *ItemType) {
1769 TernOpInit::TernaryOp Code = TernOpInit::FIND;
1770 RecTy *Type = IntRecTy::get();
1772 Lex.Lex(); // eat the operation
1774 if (!consume(tgtok::l_paren)) {
1775 TokError("expected '(' after !find operator");
1776 return nullptr;
1779 Init *LHS = ParseValue(CurRec);
1780 if (!LHS)
1781 return nullptr;
1783 if (!consume(tgtok::comma)) {
1784 TokError("expected ',' in !find operator");
1785 return nullptr;
1788 SMLoc MHSLoc = Lex.getLoc();
1789 Init *MHS = ParseValue(CurRec);
1790 if (!MHS)
1791 return nullptr;
1793 SMLoc RHSLoc = Lex.getLoc();
1794 Init *RHS;
1795 if (consume(tgtok::comma)) {
1796 RHSLoc = Lex.getLoc();
1797 RHS = ParseValue(CurRec);
1798 if (!RHS)
1799 return nullptr;
1800 } else {
1801 RHS = IntInit::get(0);
1804 if (!consume(tgtok::r_paren)) {
1805 TokError("expected ')' in !find operator");
1806 return nullptr;
1809 if (ItemType && !Type->typeIsConvertibleTo(ItemType)) {
1810 Error(RHSLoc, Twine("expected value of type '") +
1811 ItemType->getAsString() + "', got '" +
1812 Type->getAsString() + "'");
1815 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1816 if (!LHSt && !isa<UnsetInit>(LHS)) {
1817 TokError("could not determine type of the source string in !find");
1818 return nullptr;
1820 if (LHSt && !isa<StringRecTy>(LHSt->getType())) {
1821 TokError(Twine("expected string, got type '") +
1822 LHSt->getType()->getAsString() + "'");
1823 return nullptr;
1826 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1827 if (!MHSt && !isa<UnsetInit>(MHS)) {
1828 TokError("could not determine type of the target string in !find");
1829 return nullptr;
1831 if (MHSt && !isa<StringRecTy>(MHSt->getType())) {
1832 Error(MHSLoc, Twine("expected string, got type '") +
1833 MHSt->getType()->getAsString() + "'");
1834 return nullptr;
1837 if (RHS) {
1838 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1839 if (!RHSt && !isa<UnsetInit>(RHS)) {
1840 TokError("could not determine type of the start position in !find");
1841 return nullptr;
1843 if (RHSt && !isa<IntRecTy>(RHSt->getType())) {
1844 TokError(Twine("expected int, got type '") +
1845 RHSt->getType()->getAsString() + "'");
1846 return nullptr;
1850 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
1853 /// Parse the !foreach and !filter operations. Return null on error.
1855 /// ForEach ::= !foreach(ID, list-or-dag, expr) => list<expr type>
1856 /// Filter ::= !foreach(ID, list, predicate) ==> list<list type>
1857 Init *TGParser::ParseOperationForEachFilter(Record *CurRec, RecTy *ItemType) {
1858 SMLoc OpLoc = Lex.getLoc();
1859 tgtok::TokKind Operation = Lex.getCode();
1860 Lex.Lex(); // eat the operation
1861 if (Lex.getCode() != tgtok::l_paren) {
1862 TokError("expected '(' after !foreach/!filter");
1863 return nullptr;
1866 if (Lex.Lex() != tgtok::Id) { // eat the '('
1867 TokError("first argument of !foreach/!filter must be an identifier");
1868 return nullptr;
1871 Init *LHS = StringInit::get(Lex.getCurStrVal());
1872 Lex.Lex(); // eat the ID.
1874 if (CurRec && CurRec->getValue(LHS)) {
1875 TokError((Twine("iteration variable '") + LHS->getAsString() +
1876 "' is already defined")
1877 .str());
1878 return nullptr;
1881 if (!consume(tgtok::comma)) {
1882 TokError("expected ',' in !foreach/!filter");
1883 return nullptr;
1886 Init *MHS = ParseValue(CurRec);
1887 if (!MHS)
1888 return nullptr;
1890 if (!consume(tgtok::comma)) {
1891 TokError("expected ',' in !foreach/!filter");
1892 return nullptr;
1895 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1896 if (!MHSt) {
1897 TokError("could not get type of !foreach/!filter list or dag");
1898 return nullptr;
1901 RecTy *InEltType = nullptr;
1902 RecTy *ExprEltType = nullptr;
1903 bool IsDAG = false;
1905 if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) {
1906 InEltType = InListTy->getElementType();
1907 if (ItemType) {
1908 if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) {
1909 ExprEltType = (Operation == tgtok::XForEach)
1910 ? OutListTy->getElementType()
1911 : IntRecTy::get();
1912 } else {
1913 Error(OpLoc,
1914 "expected value of type '" +
1915 Twine(ItemType->getAsString()) +
1916 "', but got list type");
1917 return nullptr;
1920 } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) {
1921 if (Operation == tgtok::XFilter) {
1922 TokError("!filter must have a list argument");
1923 return nullptr;
1925 InEltType = InDagTy;
1926 if (ItemType && !isa<DagRecTy>(ItemType)) {
1927 Error(OpLoc,
1928 "expected value of type '" + Twine(ItemType->getAsString()) +
1929 "', but got dag type");
1930 return nullptr;
1932 IsDAG = true;
1933 } else {
1934 if (Operation == tgtok::XForEach)
1935 TokError("!foreach must have a list or dag argument");
1936 else
1937 TokError("!filter must have a list argument");
1938 return nullptr;
1941 // We need to create a temporary record to provide a scope for the
1942 // iteration variable.
1943 std::unique_ptr<Record> ParseRecTmp;
1944 Record *ParseRec = CurRec;
1945 if (!ParseRec) {
1946 ParseRecTmp =
1947 std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1948 ParseRec = ParseRecTmp.get();
1951 ParseRec->addValue(RecordVal(LHS, InEltType, RecordVal::FK_Normal));
1952 Init *RHS = ParseValue(ParseRec, ExprEltType);
1953 ParseRec->removeValue(LHS);
1954 if (!RHS)
1955 return nullptr;
1957 if (!consume(tgtok::r_paren)) {
1958 TokError("expected ')' in !foreach/!filter");
1959 return nullptr;
1962 RecTy *OutType = InEltType;
1963 if (Operation == tgtok::XForEach && !IsDAG) {
1964 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1965 if (!RHSt) {
1966 TokError("could not get type of !foreach result expression");
1967 return nullptr;
1969 OutType = RHSt->getType()->getListTy();
1970 } else if (Operation == tgtok::XFilter) {
1971 OutType = InEltType->getListTy();
1974 return (TernOpInit::get((Operation == tgtok::XForEach) ? TernOpInit::FOREACH
1975 : TernOpInit::FILTER,
1976 LHS, MHS, RHS, OutType))
1977 ->Fold(CurRec);
1980 Init *TGParser::ParseOperationCond(Record *CurRec, RecTy *ItemType) {
1981 Lex.Lex(); // eat the operation 'cond'
1983 if (!consume(tgtok::l_paren)) {
1984 TokError("expected '(' after !cond operator");
1985 return nullptr;
1988 // Parse through '[Case: Val,]+'
1989 SmallVector<Init *, 4> Case;
1990 SmallVector<Init *, 4> Val;
1991 while (true) {
1992 if (consume(tgtok::r_paren))
1993 break;
1995 Init *V = ParseValue(CurRec);
1996 if (!V)
1997 return nullptr;
1998 Case.push_back(V);
2000 if (!consume(tgtok::colon)) {
2001 TokError("expected ':' following a condition in !cond operator");
2002 return nullptr;
2005 V = ParseValue(CurRec, ItemType);
2006 if (!V)
2007 return nullptr;
2008 Val.push_back(V);
2010 if (consume(tgtok::r_paren))
2011 break;
2013 if (!consume(tgtok::comma)) {
2014 TokError("expected ',' or ')' following a value in !cond operator");
2015 return nullptr;
2019 if (Case.size() < 1) {
2020 TokError("there should be at least 1 'condition : value' in the !cond operator");
2021 return nullptr;
2024 // resolve type
2025 RecTy *Type = nullptr;
2026 for (Init *V : Val) {
2027 RecTy *VTy = nullptr;
2028 if (TypedInit *Vt = dyn_cast<TypedInit>(V))
2029 VTy = Vt->getType();
2030 if (BitsInit *Vbits = dyn_cast<BitsInit>(V))
2031 VTy = BitsRecTy::get(Vbits->getNumBits());
2032 if (isa<BitInit>(V))
2033 VTy = BitRecTy::get();
2035 if (Type == nullptr) {
2036 if (!isa<UnsetInit>(V))
2037 Type = VTy;
2038 } else {
2039 if (!isa<UnsetInit>(V)) {
2040 RecTy *RType = resolveTypes(Type, VTy);
2041 if (!RType) {
2042 TokError(Twine("inconsistent types '") + Type->getAsString() +
2043 "' and '" + VTy->getAsString() + "' for !cond");
2044 return nullptr;
2046 Type = RType;
2051 if (!Type) {
2052 TokError("could not determine type for !cond from its arguments");
2053 return nullptr;
2055 return CondOpInit::get(Case, Val, Type)->Fold(CurRec);
2058 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
2060 /// SimpleValue ::= IDValue
2061 /// SimpleValue ::= INTVAL
2062 /// SimpleValue ::= STRVAL+
2063 /// SimpleValue ::= CODEFRAGMENT
2064 /// SimpleValue ::= '?'
2065 /// SimpleValue ::= '{' ValueList '}'
2066 /// SimpleValue ::= ID '<' ValueListNE '>'
2067 /// SimpleValue ::= '[' ValueList ']'
2068 /// SimpleValue ::= '(' IDValue DagArgList ')'
2069 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
2070 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
2071 /// SimpleValue ::= SUBTOK '(' Value ',' Value ')'
2072 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
2073 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
2074 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
2075 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
2076 /// SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')'
2077 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
2078 /// SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
2080 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
2081 IDParseMode Mode) {
2082 Init *R = nullptr;
2083 switch (Lex.getCode()) {
2084 default: TokError("Unknown or reserved token when parsing a value"); break;
2086 case tgtok::TrueVal:
2087 R = IntInit::get(1);
2088 Lex.Lex();
2089 break;
2090 case tgtok::FalseVal:
2091 R = IntInit::get(0);
2092 Lex.Lex();
2093 break;
2094 case tgtok::IntVal:
2095 R = IntInit::get(Lex.getCurIntVal());
2096 Lex.Lex();
2097 break;
2098 case tgtok::BinaryIntVal: {
2099 auto BinaryVal = Lex.getCurBinaryIntVal();
2100 SmallVector<Init*, 16> Bits(BinaryVal.second);
2101 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
2102 Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
2103 R = BitsInit::get(Bits);
2104 Lex.Lex();
2105 break;
2107 case tgtok::StrVal: {
2108 std::string Val = Lex.getCurStrVal();
2109 Lex.Lex();
2111 // Handle multiple consecutive concatenated strings.
2112 while (Lex.getCode() == tgtok::StrVal) {
2113 Val += Lex.getCurStrVal();
2114 Lex.Lex();
2117 R = StringInit::get(Val);
2118 break;
2120 case tgtok::CodeFragment:
2121 R = StringInit::get(Lex.getCurStrVal(), StringInit::SF_Code);
2122 Lex.Lex();
2123 break;
2124 case tgtok::question:
2125 R = UnsetInit::get();
2126 Lex.Lex();
2127 break;
2128 case tgtok::Id: {
2129 SMLoc NameLoc = Lex.getLoc();
2130 StringInit *Name = StringInit::get(Lex.getCurStrVal());
2131 if (Lex.Lex() != tgtok::less) // consume the Id.
2132 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
2134 // Value ::= CLASSID '<' ValueListNE '>' (CLASSID has been consumed)
2135 // This is supposed to synthesize a new anonymous definition, deriving
2136 // from the class with the template arguments, but no body.
2137 Record *Class = Records.getClass(Name->getValue());
2138 if (!Class) {
2139 Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'");
2140 return nullptr;
2143 SmallVector<Init *, 8> Args;
2144 Lex.Lex(); // consume the <
2145 if (ParseTemplateArgValueList(Args, CurRec, Class))
2146 return nullptr; // Error parsing value list.
2148 if (CheckTemplateArgValues(Args, NameLoc, Class))
2149 return nullptr; // Error checking template argument values.
2151 // Loop through the arguments that were not specified and make sure
2152 // they have a complete value.
2153 ArrayRef<Init *> TArgs = Class->getTemplateArgs();
2154 for (unsigned I = Args.size(), E = TArgs.size(); I < E; ++I) {
2155 RecordVal *Arg = Class->getValue(TArgs[I]);
2156 if (!Arg->getValue()->isComplete())
2157 Error(NameLoc, "Value not specified for template argument '" +
2158 TArgs[I]->getAsUnquotedString() + "' (#" + Twine(I) +
2159 ") of parent class '" +
2160 Class->getNameInitAsString() + "'");
2164 return VarDefInit::get(Class, Args)->Fold();
2166 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
2167 SMLoc BraceLoc = Lex.getLoc();
2168 Lex.Lex(); // eat the '{'
2169 SmallVector<Init*, 16> Vals;
2171 if (Lex.getCode() != tgtok::r_brace) {
2172 ParseValueList(Vals, CurRec);
2173 if (Vals.empty()) return nullptr;
2175 if (!consume(tgtok::r_brace)) {
2176 TokError("expected '}' at end of bit list value");
2177 return nullptr;
2180 SmallVector<Init *, 16> NewBits;
2182 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
2183 // first. We'll first read everything in to a vector, then we can reverse
2184 // it to get the bits in the correct order for the BitsInit value.
2185 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2186 // FIXME: The following two loops would not be duplicated
2187 // if the API was a little more orthogonal.
2189 // bits<n> values are allowed to initialize n bits.
2190 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
2191 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
2192 NewBits.push_back(BI->getBit((e - i) - 1));
2193 continue;
2195 // bits<n> can also come from variable initializers.
2196 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
2197 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
2198 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
2199 NewBits.push_back(VI->getBit((e - i) - 1));
2200 continue;
2202 // Fallthrough to try convert this to a bit.
2204 // All other values must be convertible to just a single bit.
2205 Init *Bit = Vals[i]->getCastTo(BitRecTy::get());
2206 if (!Bit) {
2207 Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
2208 ") is not convertable to a bit");
2209 return nullptr;
2211 NewBits.push_back(Bit);
2213 std::reverse(NewBits.begin(), NewBits.end());
2214 return BitsInit::get(NewBits);
2216 case tgtok::l_square: { // Value ::= '[' ValueList ']'
2217 Lex.Lex(); // eat the '['
2218 SmallVector<Init*, 16> Vals;
2220 RecTy *DeducedEltTy = nullptr;
2221 ListRecTy *GivenListTy = nullptr;
2223 if (ItemType) {
2224 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
2225 if (!ListType) {
2226 TokError(Twine("Encountered a list when expecting a ") +
2227 ItemType->getAsString());
2228 return nullptr;
2230 GivenListTy = ListType;
2233 if (Lex.getCode() != tgtok::r_square) {
2234 ParseValueList(Vals, CurRec,
2235 GivenListTy ? GivenListTy->getElementType() : nullptr);
2236 if (Vals.empty()) return nullptr;
2238 if (!consume(tgtok::r_square)) {
2239 TokError("expected ']' at end of list value");
2240 return nullptr;
2243 RecTy *GivenEltTy = nullptr;
2244 if (consume(tgtok::less)) {
2245 // Optional list element type
2246 GivenEltTy = ParseType();
2247 if (!GivenEltTy) {
2248 // Couldn't parse element type
2249 return nullptr;
2252 if (!consume(tgtok::greater)) {
2253 TokError("expected '>' at end of list element type");
2254 return nullptr;
2258 // Check elements
2259 RecTy *EltTy = nullptr;
2260 for (Init *V : Vals) {
2261 TypedInit *TArg = dyn_cast<TypedInit>(V);
2262 if (TArg) {
2263 if (EltTy) {
2264 EltTy = resolveTypes(EltTy, TArg->getType());
2265 if (!EltTy) {
2266 TokError("Incompatible types in list elements");
2267 return nullptr;
2269 } else {
2270 EltTy = TArg->getType();
2275 if (GivenEltTy) {
2276 if (EltTy) {
2277 // Verify consistency
2278 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
2279 TokError("Incompatible types in list elements");
2280 return nullptr;
2283 EltTy = GivenEltTy;
2286 if (!EltTy) {
2287 if (!ItemType) {
2288 TokError("No type for list");
2289 return nullptr;
2291 DeducedEltTy = GivenListTy->getElementType();
2292 } else {
2293 // Make sure the deduced type is compatible with the given type
2294 if (GivenListTy) {
2295 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
2296 TokError(Twine("Element type mismatch for list: element type '") +
2297 EltTy->getAsString() + "' not convertible to '" +
2298 GivenListTy->getElementType()->getAsString());
2299 return nullptr;
2302 DeducedEltTy = EltTy;
2305 return ListInit::get(Vals, DeducedEltTy);
2307 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
2308 Lex.Lex(); // eat the '('
2309 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast &&
2310 Lex.getCode() != tgtok::question && Lex.getCode() != tgtok::XGetDagOp) {
2311 TokError("expected identifier in dag init");
2312 return nullptr;
2315 Init *Operator = ParseValue(CurRec);
2316 if (!Operator) return nullptr;
2318 // If the operator name is present, parse it.
2319 StringInit *OperatorName = nullptr;
2320 if (consume(tgtok::colon)) {
2321 if (Lex.getCode() != tgtok::VarName) { // eat the ':'
2322 TokError("expected variable name in dag operator");
2323 return nullptr;
2325 OperatorName = StringInit::get(Lex.getCurStrVal());
2326 Lex.Lex(); // eat the VarName.
2329 SmallVector<std::pair<llvm::Init*, StringInit*>, 8> DagArgs;
2330 if (Lex.getCode() != tgtok::r_paren) {
2331 ParseDagArgList(DagArgs, CurRec);
2332 if (DagArgs.empty()) return nullptr;
2335 if (!consume(tgtok::r_paren)) {
2336 TokError("expected ')' in dag init");
2337 return nullptr;
2340 return DagInit::get(Operator, OperatorName, DagArgs);
2343 case tgtok::XHead:
2344 case tgtok::XTail:
2345 case tgtok::XSize:
2346 case tgtok::XEmpty:
2347 case tgtok::XCast:
2348 case tgtok::XGetDagOp: // Value ::= !unop '(' Value ')'
2349 case tgtok::XIsA:
2350 case tgtok::XConcat:
2351 case tgtok::XDag:
2352 case tgtok::XADD:
2353 case tgtok::XSUB:
2354 case tgtok::XMUL:
2355 case tgtok::XNOT:
2356 case tgtok::XAND:
2357 case tgtok::XOR:
2358 case tgtok::XXOR:
2359 case tgtok::XSRA:
2360 case tgtok::XSRL:
2361 case tgtok::XSHL:
2362 case tgtok::XEq:
2363 case tgtok::XNe:
2364 case tgtok::XLe:
2365 case tgtok::XLt:
2366 case tgtok::XGe:
2367 case tgtok::XGt:
2368 case tgtok::XListConcat:
2369 case tgtok::XListSplat:
2370 case tgtok::XStrConcat:
2371 case tgtok::XInterleave:
2372 case tgtok::XSetDagOp: // Value ::= !binop '(' Value ',' Value ')'
2373 case tgtok::XIf:
2374 case tgtok::XCond:
2375 case tgtok::XFoldl:
2376 case tgtok::XForEach:
2377 case tgtok::XFilter:
2378 case tgtok::XSubst:
2379 case tgtok::XSubstr:
2380 case tgtok::XFind: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
2381 return ParseOperation(CurRec, ItemType);
2385 return R;
2388 /// ParseValue - Parse a TableGen value. This returns null on error.
2390 /// Value ::= SimpleValue ValueSuffix*
2391 /// ValueSuffix ::= '{' BitList '}'
2392 /// ValueSuffix ::= '[' BitList ']'
2393 /// ValueSuffix ::= '.' ID
2395 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
2396 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
2397 if (!Result) return nullptr;
2399 // Parse the suffixes now if present.
2400 while (true) {
2401 switch (Lex.getCode()) {
2402 default: return Result;
2403 case tgtok::l_brace: {
2404 if (Mode == ParseNameMode)
2405 // This is the beginning of the object body.
2406 return Result;
2408 SMLoc CurlyLoc = Lex.getLoc();
2409 Lex.Lex(); // eat the '{'
2410 SmallVector<unsigned, 16> Ranges;
2411 ParseRangeList(Ranges);
2412 if (Ranges.empty()) return nullptr;
2414 // Reverse the bitlist.
2415 std::reverse(Ranges.begin(), Ranges.end());
2416 Result = Result->convertInitializerBitRange(Ranges);
2417 if (!Result) {
2418 Error(CurlyLoc, "Invalid bit range for value");
2419 return nullptr;
2422 // Eat the '}'.
2423 if (!consume(tgtok::r_brace)) {
2424 TokError("expected '}' at end of bit range list");
2425 return nullptr;
2427 break;
2429 case tgtok::l_square: {
2430 SMLoc SquareLoc = Lex.getLoc();
2431 Lex.Lex(); // eat the '['
2432 SmallVector<unsigned, 16> Ranges;
2433 ParseRangeList(Ranges);
2434 if (Ranges.empty()) return nullptr;
2436 Result = Result->convertInitListSlice(Ranges);
2437 if (!Result) {
2438 Error(SquareLoc, "Invalid range for list slice");
2439 return nullptr;
2442 // Eat the ']'.
2443 if (!consume(tgtok::r_square)) {
2444 TokError("expected ']' at end of list slice");
2445 return nullptr;
2447 break;
2449 case tgtok::dot: {
2450 if (Lex.Lex() != tgtok::Id) { // eat the .
2451 TokError("expected field identifier after '.'");
2452 return nullptr;
2454 StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2455 if (!Result->getFieldType(FieldName)) {
2456 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
2457 Result->getAsString() + "'");
2458 return nullptr;
2460 Result = FieldInit::get(Result, FieldName)->Fold(CurRec);
2461 Lex.Lex(); // eat field name
2462 break;
2465 case tgtok::paste:
2466 SMLoc PasteLoc = Lex.getLoc();
2467 TypedInit *LHS = dyn_cast<TypedInit>(Result);
2468 if (!LHS) {
2469 Error(PasteLoc, "LHS of paste is not typed!");
2470 return nullptr;
2473 // Check if it's a 'listA # listB'
2474 if (isa<ListRecTy>(LHS->getType())) {
2475 Lex.Lex(); // Eat the '#'.
2477 assert(Mode == ParseValueMode && "encountered paste of lists in name");
2479 switch (Lex.getCode()) {
2480 case tgtok::colon:
2481 case tgtok::semi:
2482 case tgtok::l_brace:
2483 Result = LHS; // trailing paste, ignore.
2484 break;
2485 default:
2486 Init *RHSResult = ParseValue(CurRec, ItemType, ParseValueMode);
2487 if (!RHSResult)
2488 return nullptr;
2489 Result = BinOpInit::getListConcat(LHS, RHSResult);
2490 break;
2492 break;
2495 // Create a !strconcat() operation, first casting each operand to
2496 // a string if necessary.
2497 if (LHS->getType() != StringRecTy::get()) {
2498 auto CastLHS = dyn_cast<TypedInit>(
2499 UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get())
2500 ->Fold(CurRec));
2501 if (!CastLHS) {
2502 Error(PasteLoc,
2503 Twine("can't cast '") + LHS->getAsString() + "' to string");
2504 return nullptr;
2506 LHS = CastLHS;
2509 TypedInit *RHS = nullptr;
2511 Lex.Lex(); // Eat the '#'.
2512 switch (Lex.getCode()) {
2513 case tgtok::colon:
2514 case tgtok::semi:
2515 case tgtok::l_brace:
2516 // These are all of the tokens that can begin an object body.
2517 // Some of these can also begin values but we disallow those cases
2518 // because they are unlikely to be useful.
2520 // Trailing paste, concat with an empty string.
2521 RHS = StringInit::get("");
2522 break;
2524 default:
2525 Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode);
2526 if (!RHSResult)
2527 return nullptr;
2528 RHS = dyn_cast<TypedInit>(RHSResult);
2529 if (!RHS) {
2530 Error(PasteLoc, "RHS of paste is not typed!");
2531 return nullptr;
2534 if (RHS->getType() != StringRecTy::get()) {
2535 auto CastRHS = dyn_cast<TypedInit>(
2536 UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get())
2537 ->Fold(CurRec));
2538 if (!CastRHS) {
2539 Error(PasteLoc,
2540 Twine("can't cast '") + RHS->getAsString() + "' to string");
2541 return nullptr;
2543 RHS = CastRHS;
2546 break;
2549 Result = BinOpInit::getStrConcat(LHS, RHS);
2550 break;
2555 /// ParseDagArgList - Parse the argument list for a dag literal expression.
2557 /// DagArg ::= Value (':' VARNAME)?
2558 /// DagArg ::= VARNAME
2559 /// DagArgList ::= DagArg
2560 /// DagArgList ::= DagArgList ',' DagArg
2561 void TGParser::ParseDagArgList(
2562 SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result,
2563 Record *CurRec) {
2565 while (true) {
2566 // DagArg ::= VARNAME
2567 if (Lex.getCode() == tgtok::VarName) {
2568 // A missing value is treated like '?'.
2569 StringInit *VarName = StringInit::get(Lex.getCurStrVal());
2570 Result.emplace_back(UnsetInit::get(), VarName);
2571 Lex.Lex();
2572 } else {
2573 // DagArg ::= Value (':' VARNAME)?
2574 Init *Val = ParseValue(CurRec);
2575 if (!Val) {
2576 Result.clear();
2577 return;
2580 // If the variable name is present, add it.
2581 StringInit *VarName = nullptr;
2582 if (Lex.getCode() == tgtok::colon) {
2583 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
2584 TokError("expected variable name in dag literal");
2585 Result.clear();
2586 return;
2588 VarName = StringInit::get(Lex.getCurStrVal());
2589 Lex.Lex(); // eat the VarName.
2592 Result.push_back(std::make_pair(Val, VarName));
2594 if (!consume(tgtok::comma))
2595 break;
2599 /// ParseValueList - Parse a comma separated list of values, returning them
2600 /// in a vector. Note that this always expects to be able to parse at least one
2601 /// value. It returns an empty list if this is not possible.
2603 /// ValueList ::= Value (',' Value)
2605 void TGParser::ParseValueList(SmallVectorImpl<Init *> &Result, Record *CurRec,
2606 RecTy *ItemType) {
2608 Result.push_back(ParseValue(CurRec, ItemType));
2609 if (!Result.back()) {
2610 Result.clear();
2611 return;
2614 while (consume(tgtok::comma)) {
2615 // ignore trailing comma for lists
2616 if (Lex.getCode() == tgtok::r_square)
2617 return;
2618 Result.push_back(ParseValue(CurRec, ItemType));
2619 if (!Result.back()) {
2620 Result.clear();
2621 return;
2626 // ParseTemplateArgValueList - Parse a template argument list with the syntax
2627 // shown, filling in the Result vector. The open angle has been consumed.
2628 // An empty argument list is allowed. Return false if okay, true if an
2629 // error was detected.
2631 // TemplateArgList ::= '<' [Value {',' Value}*] '>'
2632 bool TGParser::ParseTemplateArgValueList(SmallVectorImpl<Init *> &Result,
2633 Record *CurRec, Record *ArgsRec) {
2635 assert(Result.empty() && "Result vector is not empty");
2636 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2637 unsigned ArgIndex = 0;
2638 RecTy *ItemType;
2640 if (consume(tgtok::greater)) // empty value list
2641 return false;
2643 while (true) {
2644 if (ArgIndex >= TArgs.size()) {
2645 TokError("Too many template arguments: " + utostr(ArgIndex + 1));
2646 return true;
2648 const RecordVal *Arg = ArgsRec->getValue(TArgs[ArgIndex]);
2649 assert(Arg && "Template argument record not found");
2651 ItemType = Arg->getType();
2652 Init *Value = ParseValue(CurRec, ItemType);
2653 if (!Value)
2654 return true;
2655 Result.push_back(Value);
2657 if (consume(tgtok::greater)) // end of argument list?
2658 return false;
2659 if (!consume(tgtok::comma))
2660 return TokError("Expected comma before next argument");
2661 ++ArgIndex;
2665 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
2666 /// empty string on error. This can happen in a number of different contexts,
2667 /// including within a def or in the template args for a class (in which case
2668 /// CurRec will be non-null) and within the template args for a multiclass (in
2669 /// which case CurRec will be null, but CurMultiClass will be set). This can
2670 /// also happen within a def that is within a multiclass, which will set both
2671 /// CurRec and CurMultiClass.
2673 /// Declaration ::= FIELD? Type ID ('=' Value)?
2675 Init *TGParser::ParseDeclaration(Record *CurRec,
2676 bool ParsingTemplateArgs) {
2677 // Read the field prefix if present.
2678 bool HasField = consume(tgtok::Field);
2680 RecTy *Type = ParseType();
2681 if (!Type) return nullptr;
2683 if (Lex.getCode() != tgtok::Id) {
2684 TokError("Expected identifier in declaration");
2685 return nullptr;
2688 std::string Str = Lex.getCurStrVal();
2689 if (Str == "NAME") {
2690 TokError("'" + Str + "' is a reserved variable name");
2691 return nullptr;
2694 SMLoc IdLoc = Lex.getLoc();
2695 Init *DeclName = StringInit::get(Str);
2696 Lex.Lex();
2698 bool BadField;
2699 if (!ParsingTemplateArgs) { // def, possibly in a multiclass
2700 BadField = AddValue(CurRec, IdLoc,
2701 RecordVal(DeclName, IdLoc, Type,
2702 HasField ? RecordVal::FK_NonconcreteOK
2703 : RecordVal::FK_Normal));
2705 } else if (CurRec) { // class template argument
2706 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
2707 BadField = AddValue(CurRec, IdLoc, RecordVal(DeclName, IdLoc, Type,
2708 RecordVal::FK_TemplateArg));
2710 } else { // multiclass template argument
2711 assert(CurMultiClass && "invalid context for template argument");
2712 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName, "::");
2713 BadField = AddValue(CurRec, IdLoc, RecordVal(DeclName, IdLoc, Type,
2714 RecordVal::FK_TemplateArg));
2716 if (BadField)
2717 return nullptr;
2719 // If a value is present, parse it and set new field's value.
2720 if (consume(tgtok::equal)) {
2721 SMLoc ValLoc = Lex.getLoc();
2722 Init *Val = ParseValue(CurRec, Type);
2723 if (!Val ||
2724 SetValue(CurRec, ValLoc, DeclName, None, Val))
2725 // Return the name, even if an error is thrown. This is so that we can
2726 // continue to make some progress, even without the value having been
2727 // initialized.
2728 return DeclName;
2731 return DeclName;
2734 /// ParseForeachDeclaration - Read a foreach declaration, returning
2735 /// the name of the declared object or a NULL Init on error. Return
2736 /// the name of the parsed initializer list through ForeachListName.
2738 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
2739 /// ForeachDeclaration ::= ID '=' RangePiece
2740 /// ForeachDeclaration ::= ID '=' Value
2742 VarInit *TGParser::ParseForeachDeclaration(Init *&ForeachListValue) {
2743 if (Lex.getCode() != tgtok::Id) {
2744 TokError("Expected identifier in foreach declaration");
2745 return nullptr;
2748 Init *DeclName = StringInit::get(Lex.getCurStrVal());
2749 Lex.Lex();
2751 // If a value is present, parse it.
2752 if (!consume(tgtok::equal)) {
2753 TokError("Expected '=' in foreach declaration");
2754 return nullptr;
2757 RecTy *IterType = nullptr;
2758 SmallVector<unsigned, 16> Ranges;
2760 switch (Lex.getCode()) {
2761 case tgtok::l_brace: { // '{' RangeList '}'
2762 Lex.Lex(); // eat the '{'
2763 ParseRangeList(Ranges);
2764 if (!consume(tgtok::r_brace)) {
2765 TokError("expected '}' at end of bit range list");
2766 return nullptr;
2768 break;
2771 default: {
2772 SMLoc ValueLoc = Lex.getLoc();
2773 Init *I = ParseValue(nullptr);
2774 if (!I)
2775 return nullptr;
2777 TypedInit *TI = dyn_cast<TypedInit>(I);
2778 if (TI && isa<ListRecTy>(TI->getType())) {
2779 ForeachListValue = I;
2780 IterType = cast<ListRecTy>(TI->getType())->getElementType();
2781 break;
2784 if (TI) {
2785 if (ParseRangePiece(Ranges, TI))
2786 return nullptr;
2787 break;
2790 Error(ValueLoc, "expected a list, got '" + I->getAsString() + "'");
2791 if (CurMultiClass) {
2792 PrintNote({}, "references to multiclass template arguments cannot be "
2793 "resolved at this time");
2795 return nullptr;
2800 if (!Ranges.empty()) {
2801 assert(!IterType && "Type already initialized?");
2802 IterType = IntRecTy::get();
2803 std::vector<Init *> Values;
2804 for (unsigned R : Ranges)
2805 Values.push_back(IntInit::get(R));
2806 ForeachListValue = ListInit::get(Values, IterType);
2809 if (!IterType)
2810 return nullptr;
2812 return VarInit::get(DeclName, IterType);
2815 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
2816 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
2817 /// template args for a class. If null, these are the template args for a
2818 /// multiclass.
2820 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
2822 bool TGParser::ParseTemplateArgList(Record *CurRec) {
2823 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
2824 Lex.Lex(); // eat the '<'
2826 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
2828 // Read the first declaration.
2829 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2830 if (!TemplArg)
2831 return true;
2833 TheRecToAddTo->addTemplateArg(TemplArg);
2835 while (consume(tgtok::comma)) {
2836 // Read the following declarations.
2837 SMLoc Loc = Lex.getLoc();
2838 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2839 if (!TemplArg)
2840 return true;
2842 if (TheRecToAddTo->isTemplateArg(TemplArg))
2843 return Error(Loc, "template argument with the same name has already been "
2844 "defined");
2846 TheRecToAddTo->addTemplateArg(TemplArg);
2849 if (!consume(tgtok::greater))
2850 return TokError("expected '>' at end of template argument list");
2851 return false;
2854 /// ParseBodyItem - Parse a single item within the body of a def or class.
2856 /// BodyItem ::= Declaration ';'
2857 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
2858 /// BodyItem ::= Defvar
2859 /// BodyItem ::= Assert
2861 bool TGParser::ParseBodyItem(Record *CurRec) {
2862 if (Lex.getCode() == tgtok::Assert)
2863 return ParseAssert(nullptr, CurRec);
2865 if (Lex.getCode() == tgtok::Defvar)
2866 return ParseDefvar();
2868 if (Lex.getCode() != tgtok::Let) {
2869 if (!ParseDeclaration(CurRec, false))
2870 return true;
2872 if (!consume(tgtok::semi))
2873 return TokError("expected ';' after declaration");
2874 return false;
2877 // LET ID OptionalRangeList '=' Value ';'
2878 if (Lex.Lex() != tgtok::Id)
2879 return TokError("expected field identifier after let");
2881 SMLoc IdLoc = Lex.getLoc();
2882 StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2883 Lex.Lex(); // eat the field name.
2885 SmallVector<unsigned, 16> BitList;
2886 if (ParseOptionalBitList(BitList))
2887 return true;
2888 std::reverse(BitList.begin(), BitList.end());
2890 if (!consume(tgtok::equal))
2891 return TokError("expected '=' in let expression");
2893 RecordVal *Field = CurRec->getValue(FieldName);
2894 if (!Field)
2895 return TokError("Value '" + FieldName->getValue() + "' unknown!");
2897 RecTy *Type = Field->getType();
2898 if (!BitList.empty() && isa<BitsRecTy>(Type)) {
2899 // When assigning to a subset of a 'bits' object, expect the RHS to have
2900 // the type of that subset instead of the type of the whole object.
2901 Type = BitsRecTy::get(BitList.size());
2904 Init *Val = ParseValue(CurRec, Type);
2905 if (!Val) return true;
2907 if (!consume(tgtok::semi))
2908 return TokError("expected ';' after let expression");
2910 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
2913 /// ParseBody - Read the body of a class or def. Return true on error, false on
2914 /// success.
2916 /// Body ::= ';'
2917 /// Body ::= '{' BodyList '}'
2918 /// BodyList BodyItem*
2920 bool TGParser::ParseBody(Record *CurRec) {
2921 // If this is a null definition, just eat the semi and return.
2922 if (consume(tgtok::semi))
2923 return false;
2925 if (!consume(tgtok::l_brace))
2926 return TokError("Expected '{' to start body or ';' for declaration only");
2928 // An object body introduces a new scope for local variables.
2929 TGLocalVarScope *BodyScope = PushLocalScope();
2931 while (Lex.getCode() != tgtok::r_brace)
2932 if (ParseBodyItem(CurRec))
2933 return true;
2935 PopLocalScope(BodyScope);
2937 // Eat the '}'.
2938 Lex.Lex();
2940 // If we have a semicolon, print a gentle error.
2941 SMLoc SemiLoc = Lex.getLoc();
2942 if (consume(tgtok::semi)) {
2943 PrintError(SemiLoc, "A class or def body should not end with a semicolon");
2944 PrintNote("Semicolon ignored; remove to eliminate this error");
2947 return false;
2950 /// Apply the current let bindings to \a CurRec.
2951 /// \returns true on error, false otherwise.
2952 bool TGParser::ApplyLetStack(Record *CurRec) {
2953 for (SmallVectorImpl<LetRecord> &LetInfo : LetStack)
2954 for (LetRecord &LR : LetInfo)
2955 if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
2956 return true;
2957 return false;
2960 /// Apply the current let bindings to the RecordsEntry.
2961 bool TGParser::ApplyLetStack(RecordsEntry &Entry) {
2962 if (Entry.Rec)
2963 return ApplyLetStack(Entry.Rec.get());
2965 // Let bindings are not applied to assertions.
2966 if (Entry.Assertion)
2967 return false;
2969 for (auto &E : Entry.Loop->Entries) {
2970 if (ApplyLetStack(E))
2971 return true;
2974 return false;
2977 /// ParseObjectBody - Parse the body of a def or class. This consists of an
2978 /// optional ClassList followed by a Body. CurRec is the current def or class
2979 /// that is being parsed.
2981 /// ObjectBody ::= BaseClassList Body
2982 /// BaseClassList ::= /*empty*/
2983 /// BaseClassList ::= ':' BaseClassListNE
2984 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
2986 bool TGParser::ParseObjectBody(Record *CurRec) {
2987 // If there is a baseclass list, read it.
2988 if (consume(tgtok::colon)) {
2990 // Read all of the subclasses.
2991 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
2992 while (true) {
2993 // Check for error.
2994 if (!SubClass.Rec) return true;
2996 // Add it.
2997 if (AddSubClass(CurRec, SubClass))
2998 return true;
3000 if (!consume(tgtok::comma))
3001 break;
3002 SubClass = ParseSubClassReference(CurRec, false);
3006 if (ApplyLetStack(CurRec))
3007 return true;
3009 return ParseBody(CurRec);
3012 /// ParseDef - Parse and return a top level or multiclass record definition.
3013 /// Return false if okay, true if error.
3015 /// DefInst ::= DEF ObjectName ObjectBody
3017 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
3018 SMLoc DefLoc = Lex.getLoc();
3019 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
3020 Lex.Lex(); // Eat the 'def' token.
3022 // Parse ObjectName and make a record for it.
3023 std::unique_ptr<Record> CurRec;
3024 Init *Name = ParseObjectName(CurMultiClass);
3025 if (!Name)
3026 return true;
3028 if (isa<UnsetInit>(Name))
3029 CurRec = std::make_unique<Record>(Records.getNewAnonymousName(), DefLoc, Records,
3030 /*Anonymous=*/true);
3031 else
3032 CurRec = std::make_unique<Record>(Name, DefLoc, Records);
3034 if (ParseObjectBody(CurRec.get()))
3035 return true;
3037 return addEntry(std::move(CurRec));
3040 /// ParseDefset - Parse a defset statement.
3042 /// Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
3044 bool TGParser::ParseDefset() {
3045 assert(Lex.getCode() == tgtok::Defset);
3046 Lex.Lex(); // Eat the 'defset' token
3048 DefsetRecord Defset;
3049 Defset.Loc = Lex.getLoc();
3050 RecTy *Type = ParseType();
3051 if (!Type)
3052 return true;
3053 if (!isa<ListRecTy>(Type))
3054 return Error(Defset.Loc, "expected list type");
3055 Defset.EltTy = cast<ListRecTy>(Type)->getElementType();
3057 if (Lex.getCode() != tgtok::Id)
3058 return TokError("expected identifier");
3059 StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
3060 if (Records.getGlobal(DeclName->getValue()))
3061 return TokError("def or global variable of this name already exists");
3063 if (Lex.Lex() != tgtok::equal) // Eat the identifier
3064 return TokError("expected '='");
3065 if (Lex.Lex() != tgtok::l_brace) // Eat the '='
3066 return TokError("expected '{'");
3067 SMLoc BraceLoc = Lex.getLoc();
3068 Lex.Lex(); // Eat the '{'
3070 Defsets.push_back(&Defset);
3071 bool Err = ParseObjectList(nullptr);
3072 Defsets.pop_back();
3073 if (Err)
3074 return true;
3076 if (!consume(tgtok::r_brace)) {
3077 TokError("expected '}' at end of defset");
3078 return Error(BraceLoc, "to match this '{'");
3081 Records.addExtraGlobal(DeclName->getValue(),
3082 ListInit::get(Defset.Elements, Defset.EltTy));
3083 return false;
3086 /// ParseDefvar - Parse a defvar statement.
3088 /// Defvar ::= DEFVAR Id '=' Value ';'
3090 bool TGParser::ParseDefvar() {
3091 assert(Lex.getCode() == tgtok::Defvar);
3092 Lex.Lex(); // Eat the 'defvar' token
3094 if (Lex.getCode() != tgtok::Id)
3095 return TokError("expected identifier");
3096 StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
3097 if (CurLocalScope) {
3098 if (CurLocalScope->varAlreadyDefined(DeclName->getValue()))
3099 return TokError("local variable of this name already exists");
3100 } else {
3101 if (Records.getGlobal(DeclName->getValue()))
3102 return TokError("def or global variable of this name already exists");
3105 Lex.Lex();
3106 if (!consume(tgtok::equal))
3107 return TokError("expected '='");
3109 Init *Value = ParseValue(nullptr);
3110 if (!Value)
3111 return true;
3113 if (!consume(tgtok::semi))
3114 return TokError("expected ';'");
3116 if (CurLocalScope)
3117 CurLocalScope->addVar(DeclName->getValue(), Value);
3118 else
3119 Records.addExtraGlobal(DeclName->getValue(), Value);
3121 return false;
3124 /// ParseForeach - Parse a for statement. Return the record corresponding
3125 /// to it. This returns true on error.
3127 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
3128 /// Foreach ::= FOREACH Declaration IN Object
3130 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
3131 SMLoc Loc = Lex.getLoc();
3132 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
3133 Lex.Lex(); // Eat the 'for' token.
3135 // Make a temporary object to record items associated with the for
3136 // loop.
3137 Init *ListValue = nullptr;
3138 VarInit *IterName = ParseForeachDeclaration(ListValue);
3139 if (!IterName)
3140 return TokError("expected declaration in for");
3142 if (!consume(tgtok::In))
3143 return TokError("Unknown tok");
3145 // Create a loop object and remember it.
3146 Loops.push_back(std::make_unique<ForeachLoop>(Loc, IterName, ListValue));
3148 // A foreach loop introduces a new scope for local variables.
3149 TGLocalVarScope *ForeachScope = PushLocalScope();
3151 if (Lex.getCode() != tgtok::l_brace) {
3152 // FOREACH Declaration IN Object
3153 if (ParseObject(CurMultiClass))
3154 return true;
3155 } else {
3156 SMLoc BraceLoc = Lex.getLoc();
3157 // Otherwise, this is a group foreach.
3158 Lex.Lex(); // eat the '{'.
3160 // Parse the object list.
3161 if (ParseObjectList(CurMultiClass))
3162 return true;
3164 if (!consume(tgtok::r_brace)) {
3165 TokError("expected '}' at end of foreach command");
3166 return Error(BraceLoc, "to match this '{'");
3170 PopLocalScope(ForeachScope);
3172 // Resolve the loop or store it for later resolution.
3173 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
3174 Loops.pop_back();
3176 return addEntry(std::move(Loop));
3179 /// ParseIf - Parse an if statement.
3181 /// If ::= IF Value THEN IfBody
3182 /// If ::= IF Value THEN IfBody ELSE IfBody
3184 bool TGParser::ParseIf(MultiClass *CurMultiClass) {
3185 SMLoc Loc = Lex.getLoc();
3186 assert(Lex.getCode() == tgtok::If && "Unknown tok");
3187 Lex.Lex(); // Eat the 'if' token.
3189 // Make a temporary object to record items associated with the for
3190 // loop.
3191 Init *Condition = ParseValue(nullptr);
3192 if (!Condition)
3193 return true;
3195 if (!consume(tgtok::Then))
3196 return TokError("Unknown tok");
3198 // We have to be able to save if statements to execute later, and they have
3199 // to live on the same stack as foreach loops. The simplest implementation
3200 // technique is to convert each 'then' or 'else' clause *into* a foreach
3201 // loop, over a list of length 0 or 1 depending on the condition, and with no
3202 // iteration variable being assigned.
3204 ListInit *EmptyList = ListInit::get({}, BitRecTy::get());
3205 ListInit *SingletonList = ListInit::get({BitInit::get(1)}, BitRecTy::get());
3206 RecTy *BitListTy = ListRecTy::get(BitRecTy::get());
3208 // The foreach containing the then-clause selects SingletonList if
3209 // the condition is true.
3210 Init *ThenClauseList =
3211 TernOpInit::get(TernOpInit::IF, Condition, SingletonList, EmptyList,
3212 BitListTy)
3213 ->Fold(nullptr);
3214 Loops.push_back(std::make_unique<ForeachLoop>(Loc, nullptr, ThenClauseList));
3216 if (ParseIfBody(CurMultiClass, "then"))
3217 return true;
3219 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
3220 Loops.pop_back();
3222 if (addEntry(std::move(Loop)))
3223 return true;
3225 // Now look for an optional else clause. The if-else syntax has the usual
3226 // dangling-else ambiguity, and by greedily matching an else here if we can,
3227 // we implement the usual resolution of pairing with the innermost unmatched
3228 // if.
3229 if (consume(tgtok::ElseKW)) {
3230 // The foreach containing the else-clause uses the same pair of lists as
3231 // above, but this time, selects SingletonList if the condition is *false*.
3232 Init *ElseClauseList =
3233 TernOpInit::get(TernOpInit::IF, Condition, EmptyList, SingletonList,
3234 BitListTy)
3235 ->Fold(nullptr);
3236 Loops.push_back(
3237 std::make_unique<ForeachLoop>(Loc, nullptr, ElseClauseList));
3239 if (ParseIfBody(CurMultiClass, "else"))
3240 return true;
3242 Loop = std::move(Loops.back());
3243 Loops.pop_back();
3245 if (addEntry(std::move(Loop)))
3246 return true;
3249 return false;
3252 /// ParseIfBody - Parse the then-clause or else-clause of an if statement.
3254 /// IfBody ::= Object
3255 /// IfBody ::= '{' ObjectList '}'
3257 bool TGParser::ParseIfBody(MultiClass *CurMultiClass, StringRef Kind) {
3258 TGLocalVarScope *BodyScope = PushLocalScope();
3260 if (Lex.getCode() != tgtok::l_brace) {
3261 // A single object.
3262 if (ParseObject(CurMultiClass))
3263 return true;
3264 } else {
3265 SMLoc BraceLoc = Lex.getLoc();
3266 // A braced block.
3267 Lex.Lex(); // eat the '{'.
3269 // Parse the object list.
3270 if (ParseObjectList(CurMultiClass))
3271 return true;
3273 if (!consume(tgtok::r_brace)) {
3274 TokError("expected '}' at end of '" + Kind + "' clause");
3275 return Error(BraceLoc, "to match this '{'");
3279 PopLocalScope(BodyScope);
3280 return false;
3283 /// ParseAssert - Parse an assert statement.
3285 /// Assert ::= ASSERT condition , message ;
3286 bool TGParser::ParseAssert(MultiClass *CurMultiClass, Record *CurRec) {
3287 assert(Lex.getCode() == tgtok::Assert && "Unknown tok");
3288 Lex.Lex(); // Eat the 'assert' token.
3290 SMLoc ConditionLoc = Lex.getLoc();
3291 Init *Condition = ParseValue(CurRec);
3292 if (!Condition)
3293 return true;
3295 if (!consume(tgtok::comma)) {
3296 TokError("expected ',' in assert statement");
3297 return true;
3300 Init *Message = ParseValue(CurRec);
3301 if (!Message)
3302 return true;
3304 if (!consume(tgtok::semi))
3305 return TokError("expected ';'");
3307 if (CurRec)
3308 CurRec->addAssertion(ConditionLoc, Condition, Message);
3309 else
3310 addEntry(std::make_unique<Record::AssertionInfo>(ConditionLoc, Condition,
3311 Message));
3312 return false;
3315 /// ParseClass - Parse a tblgen class definition.
3317 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
3319 bool TGParser::ParseClass() {
3320 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
3321 Lex.Lex();
3323 if (Lex.getCode() != tgtok::Id)
3324 return TokError("expected class name after 'class' keyword");
3326 Record *CurRec = Records.getClass(Lex.getCurStrVal());
3327 if (CurRec) {
3328 // If the body was previously defined, this is an error.
3329 if (!CurRec->getValues().empty() ||
3330 !CurRec->getSuperClasses().empty() ||
3331 !CurRec->getTemplateArgs().empty())
3332 return TokError("Class '" + CurRec->getNameInitAsString() +
3333 "' already defined");
3334 } else {
3335 // If this is the first reference to this class, create and add it.
3336 auto NewRec =
3337 std::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records,
3338 /*Class=*/true);
3339 CurRec = NewRec.get();
3340 Records.addClass(std::move(NewRec));
3342 Lex.Lex(); // eat the name.
3344 // If there are template args, parse them.
3345 if (Lex.getCode() == tgtok::less)
3346 if (ParseTemplateArgList(CurRec))
3347 return true;
3349 return ParseObjectBody(CurRec);
3352 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
3353 /// of LetRecords.
3355 /// LetList ::= LetItem (',' LetItem)*
3356 /// LetItem ::= ID OptionalRangeList '=' Value
3358 void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) {
3359 do {
3360 if (Lex.getCode() != tgtok::Id) {
3361 TokError("expected identifier in let definition");
3362 Result.clear();
3363 return;
3366 StringInit *Name = StringInit::get(Lex.getCurStrVal());
3367 SMLoc NameLoc = Lex.getLoc();
3368 Lex.Lex(); // Eat the identifier.
3370 // Check for an optional RangeList.
3371 SmallVector<unsigned, 16> Bits;
3372 if (ParseOptionalRangeList(Bits)) {
3373 Result.clear();
3374 return;
3376 std::reverse(Bits.begin(), Bits.end());
3378 if (!consume(tgtok::equal)) {
3379 TokError("expected '=' in let expression");
3380 Result.clear();
3381 return;
3384 Init *Val = ParseValue(nullptr);
3385 if (!Val) {
3386 Result.clear();
3387 return;
3390 // Now that we have everything, add the record.
3391 Result.emplace_back(Name, Bits, Val, NameLoc);
3392 } while (consume(tgtok::comma));
3395 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
3396 /// different related productions. This works inside multiclasses too.
3398 /// Object ::= LET LetList IN '{' ObjectList '}'
3399 /// Object ::= LET LetList IN Object
3401 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
3402 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
3403 Lex.Lex();
3405 // Add this entry to the let stack.
3406 SmallVector<LetRecord, 8> LetInfo;
3407 ParseLetList(LetInfo);
3408 if (LetInfo.empty()) return true;
3409 LetStack.push_back(std::move(LetInfo));
3411 if (!consume(tgtok::In))
3412 return TokError("expected 'in' at end of top-level 'let'");
3414 TGLocalVarScope *LetScope = PushLocalScope();
3416 // If this is a scalar let, just handle it now
3417 if (Lex.getCode() != tgtok::l_brace) {
3418 // LET LetList IN Object
3419 if (ParseObject(CurMultiClass))
3420 return true;
3421 } else { // Object ::= LETCommand '{' ObjectList '}'
3422 SMLoc BraceLoc = Lex.getLoc();
3423 // Otherwise, this is a group let.
3424 Lex.Lex(); // eat the '{'.
3426 // Parse the object list.
3427 if (ParseObjectList(CurMultiClass))
3428 return true;
3430 if (!consume(tgtok::r_brace)) {
3431 TokError("expected '}' at end of top level let command");
3432 return Error(BraceLoc, "to match this '{'");
3436 PopLocalScope(LetScope);
3438 // Outside this let scope, this let block is not active.
3439 LetStack.pop_back();
3440 return false;
3443 /// ParseMultiClass - Parse a multiclass definition.
3445 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
3446 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
3447 /// MultiClassObject ::= Assert
3448 /// MultiClassObject ::= DefInst
3449 /// MultiClassObject ::= DefMInst
3450 /// MultiClassObject ::= Defvar
3451 /// MultiClassObject ::= Foreach
3452 /// MultiClassObject ::= If
3453 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
3454 /// MultiClassObject ::= LETCommand Object
3456 bool TGParser::ParseMultiClass() {
3457 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
3458 Lex.Lex(); // Eat the multiclass token.
3460 if (Lex.getCode() != tgtok::Id)
3461 return TokError("expected identifier after multiclass for name");
3462 std::string Name = Lex.getCurStrVal();
3464 auto Result =
3465 MultiClasses.insert(std::make_pair(Name,
3466 std::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
3468 if (!Result.second)
3469 return TokError("multiclass '" + Name + "' already defined");
3471 CurMultiClass = Result.first->second.get();
3472 Lex.Lex(); // Eat the identifier.
3474 // If there are template args, parse them.
3475 if (Lex.getCode() == tgtok::less)
3476 if (ParseTemplateArgList(nullptr))
3477 return true;
3479 bool inherits = false;
3481 // If there are submulticlasses, parse them.
3482 if (consume(tgtok::colon)) {
3483 inherits = true;
3485 // Read all of the submulticlasses.
3486 SubMultiClassReference SubMultiClass =
3487 ParseSubMultiClassReference(CurMultiClass);
3488 while (true) {
3489 // Check for error.
3490 if (!SubMultiClass.MC) return true;
3492 // Add it.
3493 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
3494 return true;
3496 if (!consume(tgtok::comma))
3497 break;
3498 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
3502 if (Lex.getCode() != tgtok::l_brace) {
3503 if (!inherits)
3504 return TokError("expected '{' in multiclass definition");
3505 if (!consume(tgtok::semi))
3506 return TokError("expected ';' in multiclass definition");
3507 } else {
3508 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
3509 return TokError("multiclass must contain at least one def");
3511 // A multiclass body introduces a new scope for local variables.
3512 TGLocalVarScope *MulticlassScope = PushLocalScope();
3514 while (Lex.getCode() != tgtok::r_brace) {
3515 switch (Lex.getCode()) {
3516 default:
3517 return TokError("expected 'assert', 'def', 'defm', 'defvar', "
3518 "'foreach', 'if', or 'let' in multiclass body");
3520 case tgtok::Assert:
3521 case tgtok::Def:
3522 case tgtok::Defm:
3523 case tgtok::Defvar:
3524 case tgtok::Foreach:
3525 case tgtok::If:
3526 case tgtok::Let:
3527 if (ParseObject(CurMultiClass))
3528 return true;
3529 break;
3532 Lex.Lex(); // eat the '}'.
3534 // If we have a semicolon, print a gentle error.
3535 SMLoc SemiLoc = Lex.getLoc();
3536 if (consume(tgtok::semi)) {
3537 PrintError(SemiLoc, "A multiclass body should not end with a semicolon");
3538 PrintNote("Semicolon ignored; remove to eliminate this error");
3541 PopLocalScope(MulticlassScope);
3544 CurMultiClass = nullptr;
3545 return false;
3548 /// ParseDefm - Parse the instantiation of a multiclass.
3550 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
3552 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
3553 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
3554 Lex.Lex(); // eat the defm
3556 Init *DefmName = ParseObjectName(CurMultiClass);
3557 if (!DefmName)
3558 return true;
3559 if (isa<UnsetInit>(DefmName)) {
3560 DefmName = Records.getNewAnonymousName();
3561 if (CurMultiClass)
3562 DefmName = BinOpInit::getStrConcat(
3563 VarInit::get(QualifiedNameOfImplicitName(CurMultiClass),
3564 StringRecTy::get()),
3565 DefmName);
3568 if (Lex.getCode() != tgtok::colon)
3569 return TokError("expected ':' after defm identifier");
3571 // Keep track of the new generated record definitions.
3572 std::vector<RecordsEntry> NewEntries;
3574 // This record also inherits from a regular class (non-multiclass)?
3575 bool InheritFromClass = false;
3577 // eat the colon.
3578 Lex.Lex();
3580 SMLoc SubClassLoc = Lex.getLoc();
3581 SubClassReference Ref = ParseSubClassReference(nullptr, true);
3583 while (true) {
3584 if (!Ref.Rec) return true;
3586 // To instantiate a multiclass, we get the multiclass and then loop
3587 // through its template argument names. Substs contains a substitution
3588 // value for each argument, either the value specified or the default.
3589 // Then we can resolve the template arguments.
3590 MultiClass *MC = MultiClasses[std::string(Ref.Rec->getName())].get();
3591 assert(MC && "Didn't lookup multiclass correctly?");
3593 ArrayRef<Init *> TemplateVals = Ref.TemplateArgs;
3594 ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs();
3595 SubstStack Substs;
3597 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
3598 if (i < TemplateVals.size()) {
3599 Substs.emplace_back(TArgs[i], TemplateVals[i]);
3600 } else {
3601 Init *Default = MC->Rec.getValue(TArgs[i])->getValue();
3602 if (!Default->isComplete())
3603 return Error(SubClassLoc,
3604 "value not specified for template argument '" +
3605 TArgs[i]->getAsUnquotedString() + "' (#" +
3606 Twine(i) + ") of multiclass '" +
3607 MC->Rec.getNameInitAsString() + "'");
3608 Substs.emplace_back(TArgs[i], Default);
3612 Substs.emplace_back(QualifiedNameOfImplicitName(MC), DefmName);
3614 if (resolve(MC->Entries, Substs, !CurMultiClass && Loops.empty(),
3615 &NewEntries, &SubClassLoc))
3616 return true;
3618 if (!consume(tgtok::comma))
3619 break;
3621 if (Lex.getCode() != tgtok::Id)
3622 return TokError("expected identifier");
3624 SubClassLoc = Lex.getLoc();
3626 // A defm can inherit from regular classes (non-multiclasses) as
3627 // long as they come in the end of the inheritance list.
3628 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
3630 if (InheritFromClass)
3631 break;
3633 Ref = ParseSubClassReference(nullptr, true);
3636 if (InheritFromClass) {
3637 // Process all the classes to inherit as if they were part of a
3638 // regular 'def' and inherit all record values.
3639 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
3640 while (true) {
3641 // Check for error.
3642 if (!SubClass.Rec) return true;
3644 // Get the expanded definition prototypes and teach them about
3645 // the record values the current class to inherit has
3646 for (auto &E : NewEntries) {
3647 // Add it.
3648 if (AddSubClass(E, SubClass))
3649 return true;
3652 if (!consume(tgtok::comma))
3653 break;
3654 SubClass = ParseSubClassReference(nullptr, false);
3658 for (auto &E : NewEntries) {
3659 if (ApplyLetStack(E))
3660 return true;
3662 addEntry(std::move(E));
3665 if (!consume(tgtok::semi))
3666 return TokError("expected ';' at end of defm");
3668 return false;
3671 /// ParseObject
3672 /// Object ::= ClassInst
3673 /// Object ::= DefInst
3674 /// Object ::= MultiClassInst
3675 /// Object ::= DefMInst
3676 /// Object ::= LETCommand '{' ObjectList '}'
3677 /// Object ::= LETCommand Object
3678 /// Object ::= Defset
3679 /// Object ::= Defvar
3680 /// Object ::= Assert
3681 bool TGParser::ParseObject(MultiClass *MC) {
3682 switch (Lex.getCode()) {
3683 default:
3684 return TokError(
3685 "Expected assert, class, def, defm, defset, foreach, if, or let");
3686 case tgtok::Assert: return ParseAssert(MC);
3687 case tgtok::Def: return ParseDef(MC);
3688 case tgtok::Defm: return ParseDefm(MC);
3689 case tgtok::Defvar: return ParseDefvar();
3690 case tgtok::Foreach: return ParseForeach(MC);
3691 case tgtok::If: return ParseIf(MC);
3692 case tgtok::Let: return ParseTopLevelLet(MC);
3693 case tgtok::Defset:
3694 if (MC)
3695 return TokError("defset is not allowed inside multiclass");
3696 return ParseDefset();
3697 case tgtok::Class:
3698 if (MC)
3699 return TokError("class is not allowed inside multiclass");
3700 if (!Loops.empty())
3701 return TokError("class is not allowed inside foreach loop");
3702 return ParseClass();
3703 case tgtok::MultiClass:
3704 if (!Loops.empty())
3705 return TokError("multiclass is not allowed inside foreach loop");
3706 return ParseMultiClass();
3710 /// ParseObjectList
3711 /// ObjectList :== Object*
3712 bool TGParser::ParseObjectList(MultiClass *MC) {
3713 while (isObjectStart(Lex.getCode())) {
3714 if (ParseObject(MC))
3715 return true;
3717 return false;
3720 bool TGParser::ParseFile() {
3721 Lex.Lex(); // Prime the lexer.
3722 if (ParseObjectList()) return true;
3724 // If we have unread input at the end of the file, report it.
3725 if (Lex.getCode() == tgtok::Eof)
3726 return false;
3728 return TokError("Unexpected token at top level");
3731 // Check the types of the template argument values for a class
3732 // inheritance, multiclass invocation, or anonymous class invocation.
3733 // If necessary, replace an argument with a cast to the required type.
3734 // The argument count has already been checked.
3735 bool TGParser::CheckTemplateArgValues(SmallVectorImpl<llvm::Init *> &Values,
3736 SMLoc Loc, Record *ArgsRec) {
3738 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
3740 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
3741 RecordVal *Arg = ArgsRec->getValue(TArgs[I]);
3742 RecTy *ArgType = Arg->getType();
3743 auto *Value = Values[I];
3745 if (TypedInit *ArgValue = dyn_cast<TypedInit>(Value)) {
3746 auto *CastValue = ArgValue->getCastTo(ArgType);
3747 if (CastValue) {
3748 assert((!isa<TypedInit>(CastValue) ||
3749 cast<TypedInit>(CastValue)->getType()->typeIsA(ArgType)) &&
3750 "result of template arg value cast has wrong type");
3751 Values[I] = CastValue;
3752 } else {
3753 PrintFatalError(Loc,
3754 "Value specified for template argument '" +
3755 Arg->getNameInitAsString() + "' (#" + Twine(I) +
3756 ") is of type " + ArgValue->getType()->getAsString() +
3757 "; expected type " + ArgType->getAsString() + ": " +
3758 ArgValue->getAsString());
3763 return false;
3766 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3767 LLVM_DUMP_METHOD void RecordsEntry::dump() const {
3768 if (Loop)
3769 Loop->dump();
3770 if (Rec)
3771 Rec->dump();
3774 LLVM_DUMP_METHOD void ForeachLoop::dump() const {
3775 errs() << "foreach " << IterVar->getAsString() << " = "
3776 << ListValue->getAsString() << " in {\n";
3778 for (const auto &E : Entries)
3779 E.dump();
3781 errs() << "}\n";
3784 LLVM_DUMP_METHOD void MultiClass::dump() const {
3785 errs() << "Record:\n";
3786 Rec.dump();
3788 errs() << "Defs:\n";
3789 for (const auto &E : Entries)
3790 E.dump();
3792 #endif