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.
10 //
11 //===----------------------------------------------------------------------===//
12 
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>
29 
30 using namespace llvm;
31 
32 //===----------------------------------------------------------------------===//
33 // Support Code for the Semantic Actions.
34 //===----------------------------------------------------------------------===//
35 
36 namespace llvm {
37 
38 struct SubClassReference {
39   SMRange RefRange;
40   Record *Rec;
41   SmallVector<Init*, 4> TemplateArgs;
42 
43   SubClassReference() : Rec(nullptr) {}
44 
45   bool isInvalid() const { return Rec == nullptr; }
46 };
47 
48 struct SubMultiClassReference {
49   SMRange RefRange;
50   MultiClass *MC;
51   SmallVector<Init*, 4> TemplateArgs;
52 
53   SubMultiClassReference() : MC(nullptr) {}
54 
55   bool isInvalid() const { return MC == nullptr; }
56   void dump() const;
57 };
58 
59 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
60 LLVM_DUMP_METHOD void SubMultiClassReference::dump() const {
61   errs() << "Multiclass:\n";
62 
63   MC->dump();
64 
65   errs() << "Template args:\n";
66   for (Init *TA : TemplateArgs)
67     TA->dump();
68 }
69 #endif
70 
71 } // end namespace llvm
72 
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;
82       }
83     } else if (isa<VarInit>(Bit)) {
84       IsReference = true;
85     }
86     if (!(IsReference || Bit->isConcrete()))
87       return false;
88   }
89   return true;
90 }
91 
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;
100 
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());
109       }
110     }
111   }
112 }
113 
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);
125   }
126 
127   if (BinOpInit *BinOp = dyn_cast<BinOpInit>(NewName))
128     NewName = BinOp->Fold(&CurRec);
129   return NewName;
130 }
131 
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 ? "::" : ":");
136 }
137 
138 static Init *QualifiedNameOfImplicitName(MultiClass *MC) {
139   return QualifiedNameOfImplicitName(MC->Rec, MC);
140 }
141 
142 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
143   if (!CurRec)
144     CurRec = &CurMultiClass->Rec;
145 
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);
155   }
156   return false;
157 }
158 
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;
165 
166   if (!CurRec) CurRec = &CurMultiClass->Rec;
167 
168   RecordVal *RV = CurRec->getValue(ValName);
169   if (!RV)
170     return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
171                  "' unknown!");
172 
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");
179 
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.
183   //
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");
189 
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");
194 
195     SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
196 
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);
204     }
205 
206     for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
207       if (!NewBits[i])
208         NewBits[i] = CurVal->getBit(i);
209 
210     V = BitsInit::get(NewBits);
211   }
212 
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 + "'");
224   }
225   return false;
226 }
227 
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   // Add all of the values in the subclass into the current class.
233   for (const RecordVal &Val : SC->getValues())
234     if (AddValue(CurRec, SubClass.RefRange.Start, Val))
235       return true;
236 
237   ArrayRef<Init *> TArgs = SC->getTemplateArgs();
238 
239   // Ensure that an appropriate number of template arguments are specified.
240   if (TArgs.size() < SubClass.TemplateArgs.size())
241     return Error(SubClass.RefRange.Start,
242                  "More template args specified than expected");
243 
244   // Loop over all of the template arguments, setting them to the specified
245   // value or leaving them as the default if necessary.
246   MapResolver R(CurRec);
247 
248   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
249     if (i < SubClass.TemplateArgs.size()) {
250       // If a value is specified for this template arg, set it now.
251       if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
252                    None, SubClass.TemplateArgs[i]))
253         return true;
254     } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
255       return Error(SubClass.RefRange.Start,
256                    "Value not specified for template argument #" +
257                    Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
258                    ") of subclass '" + SC->getNameInitAsString() + "'!");
259     }
260 
261     R.set(TArgs[i], CurRec->getValue(TArgs[i])->getValue());
262 
263     CurRec->removeValue(TArgs[i]);
264   }
265 
266   Init *Name;
267   if (CurRec->isClass())
268     Name =
269         VarInit::get(QualifiedNameOfImplicitName(*CurRec), StringRecTy::get());
270   else
271     Name = CurRec->getNameInit();
272   R.set(QualifiedNameOfImplicitName(*SC), Name);
273 
274   CurRec->resolveReferences(R);
275 
276   // Since everything went well, we can now set the "superclass" list for the
277   // current record.
278   ArrayRef<std::pair<Record *, SMRange>> SCs = SC->getSuperClasses();
279   for (const auto &SCPair : SCs) {
280     if (CurRec->isSubClassOf(SCPair.first))
281       return Error(SubClass.RefRange.Start,
282                    "Already subclass of '" + SCPair.first->getName() + "'!\n");
283     CurRec->addSuperClass(SCPair.first, SCPair.second);
284   }
285 
286   if (CurRec->isSubClassOf(SC))
287     return Error(SubClass.RefRange.Start,
288                  "Already subclass of '" + SC->getName() + "'!\n");
289   CurRec->addSuperClass(SC, SubClass.RefRange);
290   return false;
291 }
292 
293 bool TGParser::AddSubClass(RecordsEntry &Entry, SubClassReference &SubClass) {
294   if (Entry.Rec)
295     return AddSubClass(Entry.Rec.get(), SubClass);
296 
297   for (auto &E : Entry.Loop->Entries) {
298     if (AddSubClass(E, SubClass))
299       return true;
300   }
301 
302   return false;
303 }
304 
305 /// AddSubMultiClass - Add SubMultiClass as a subclass to
306 /// CurMC, resolving its template args as SubMultiClass's
307 /// template arguments.
308 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
309                                 SubMultiClassReference &SubMultiClass) {
310   MultiClass *SMC = SubMultiClass.MC;
311 
312   ArrayRef<Init *> SMCTArgs = SMC->Rec.getTemplateArgs();
313   if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
314     return Error(SubMultiClass.RefRange.Start,
315                  "More template args specified than expected");
316 
317   // Prepare the mapping of template argument name to value, filling in default
318   // values if necessary.
319   SubstStack TemplateArgs;
320   for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
321     if (i < SubMultiClass.TemplateArgs.size()) {
322       TemplateArgs.emplace_back(SMCTArgs[i], SubMultiClass.TemplateArgs[i]);
323     } else {
324       Init *Default = SMC->Rec.getValue(SMCTArgs[i])->getValue();
325       if (!Default->isComplete()) {
326         return Error(SubMultiClass.RefRange.Start,
327                      "value not specified for template argument #" + Twine(i) +
328                          " (" + SMCTArgs[i]->getAsUnquotedString() +
329                          ") of multiclass '" + SMC->Rec.getNameInitAsString() +
330                          "'");
331       }
332       TemplateArgs.emplace_back(SMCTArgs[i], Default);
333     }
334   }
335 
336   TemplateArgs.emplace_back(
337       QualifiedNameOfImplicitName(SMC),
338       VarInit::get(QualifiedNameOfImplicitName(CurMC), StringRecTy::get()));
339 
340   // Add all of the defs in the subclass into the current multiclass.
341   return resolve(SMC->Entries, TemplateArgs, false, &CurMC->Entries);
342 }
343 
344 /// Add a record or foreach loop to the current context (global record keeper,
345 /// current inner-most foreach loop, or multiclass).
346 bool TGParser::addEntry(RecordsEntry E) {
347   assert(!E.Rec || !E.Loop);
348 
349   if (!Loops.empty()) {
350     Loops.back()->Entries.push_back(std::move(E));
351     return false;
352   }
353 
354   if (E.Loop) {
355     SubstStack Stack;
356     return resolve(*E.Loop, Stack, CurMultiClass == nullptr,
357                    CurMultiClass ? &CurMultiClass->Entries : nullptr);
358   }
359 
360   if (CurMultiClass) {
361     CurMultiClass->Entries.push_back(std::move(E));
362     return false;
363   }
364 
365   return addDefOne(std::move(E.Rec));
366 }
367 
368 /// Resolve the entries in \p Loop, going over inner loops recursively
369 /// and making the given subsitutions of (name, value) pairs.
370 ///
371 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
372 /// are added to the global record keeper.
373 bool TGParser::resolve(const ForeachLoop &Loop, SubstStack &Substs,
374                        bool Final, std::vector<RecordsEntry> *Dest,
375                        SMLoc *Loc) {
376   MapResolver R;
377   for (const auto &S : Substs)
378     R.set(S.first, S.second);
379   Init *List = Loop.ListValue->resolveReferences(R);
380   auto LI = dyn_cast<ListInit>(List);
381   if (!LI) {
382     if (!Final) {
383       Dest->emplace_back(std::make_unique<ForeachLoop>(Loop.Loc, Loop.IterVar,
384                                                   List));
385       return resolve(Loop.Entries, Substs, Final, &Dest->back().Loop->Entries,
386                      Loc);
387     }
388 
389     PrintError(Loop.Loc, Twine("attempting to loop over '") +
390                               List->getAsString() + "', expected a list");
391     return true;
392   }
393 
394   bool Error = false;
395   for (auto Elt : *LI) {
396     if (Loop.IterVar)
397       Substs.emplace_back(Loop.IterVar->getNameInit(), Elt);
398     Error = resolve(Loop.Entries, Substs, Final, Dest);
399     if (Loop.IterVar)
400       Substs.pop_back();
401     if (Error)
402       break;
403   }
404   return Error;
405 }
406 
407 /// Resolve the entries in \p Source, going over loops recursively and
408 /// making the given substitutions of (name, value) pairs.
409 ///
410 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
411 /// are added to the global record keeper.
412 bool TGParser::resolve(const std::vector<RecordsEntry> &Source,
413                        SubstStack &Substs, bool Final,
414                        std::vector<RecordsEntry> *Dest, SMLoc *Loc) {
415   bool Error = false;
416   for (auto &E : Source) {
417     if (E.Loop) {
418       Error = resolve(*E.Loop, Substs, Final, Dest);
419     } else {
420       auto Rec = std::make_unique<Record>(*E.Rec);
421       if (Loc)
422         Rec->appendLoc(*Loc);
423 
424       MapResolver R(Rec.get());
425       for (const auto &S : Substs)
426         R.set(S.first, S.second);
427       Rec->resolveReferences(R);
428 
429       if (Dest)
430         Dest->push_back(std::move(Rec));
431       else
432         Error = addDefOne(std::move(Rec));
433     }
434     if (Error)
435       break;
436   }
437   return Error;
438 }
439 
440 /// Resolve the record fully and add it to the record keeper.
441 bool TGParser::addDefOne(std::unique_ptr<Record> Rec) {
442   Init *NewName = nullptr;
443   if (Record *Prev = Records.getDef(Rec->getNameInitAsString())) {
444     if (!Rec->isAnonymous()) {
445       PrintError(Rec->getLoc(),
446                  "def already exists: " + Rec->getNameInitAsString());
447       PrintNote(Prev->getLoc(), "location of previous definition");
448       return true;
449     }
450     NewName = Records.getNewAnonymousName();
451   }
452 
453   Rec->resolveReferences(NewName);
454   checkConcrete(*Rec);
455 
456   CheckRecordAsserts(*Rec);
457 
458   if (!isa<StringInit>(Rec->getNameInit())) {
459     PrintError(Rec->getLoc(), Twine("record name '") +
460                                   Rec->getNameInit()->getAsString() +
461                                   "' could not be fully resolved");
462     return true;
463   }
464 
465   // If ObjectBody has template arguments, it's an error.
466   assert(Rec->getTemplateArgs().empty() && "How'd this get template args?");
467 
468   for (DefsetRecord *Defset : Defsets) {
469     DefInit *I = Rec->getDefInit();
470     if (!I->getType()->typeIsA(Defset->EltTy)) {
471       PrintError(Rec->getLoc(), Twine("adding record of incompatible type '") +
472                                     I->getType()->getAsString() +
473                                      "' to defset");
474       PrintNote(Defset->Loc, "location of defset declaration");
475       return true;
476     }
477     Defset->Elements.push_back(I);
478   }
479 
480   Records.addDef(std::move(Rec));
481   return false;
482 }
483 
484 //===----------------------------------------------------------------------===//
485 // Parser Code
486 //===----------------------------------------------------------------------===//
487 
488 /// isObjectStart - Return true if this is a valid first token for a statement.
489 static bool isObjectStart(tgtok::TokKind K) {
490   return K == tgtok::Assert || K == tgtok::Class || K == tgtok::Def ||
491          K == tgtok::Defm || K == tgtok::Defset || K == tgtok::Defvar ||
492          K == tgtok::Foreach || K == tgtok::If || K == tgtok::Let ||
493          K == tgtok::MultiClass;
494 }
495 
496 bool TGParser::consume(tgtok::TokKind K) {
497   if (Lex.getCode() == K) {
498     Lex.Lex();
499     return true;
500   }
501   return false;
502 }
503 
504 /// ParseObjectName - If a valid object name is specified, return it. If no
505 /// name is specified, return the unset initializer. Return nullptr on parse
506 /// error.
507 ///   ObjectName ::= Value [ '#' Value ]*
508 ///   ObjectName ::= /*empty*/
509 ///
510 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
511   switch (Lex.getCode()) {
512   case tgtok::colon:
513   case tgtok::semi:
514   case tgtok::l_brace:
515     // These are all of the tokens that can begin an object body.
516     // Some of these can also begin values but we disallow those cases
517     // because they are unlikely to be useful.
518     return UnsetInit::get();
519   default:
520     break;
521   }
522 
523   Record *CurRec = nullptr;
524   if (CurMultiClass)
525     CurRec = &CurMultiClass->Rec;
526 
527   Init *Name = ParseValue(CurRec, StringRecTy::get(), ParseNameMode);
528   if (!Name)
529     return nullptr;
530 
531   if (CurMultiClass) {
532     Init *NameStr = QualifiedNameOfImplicitName(CurMultiClass);
533     HasReferenceResolver R(NameStr);
534     Name->resolveReferences(R);
535     if (!R.found())
536       Name = BinOpInit::getStrConcat(VarInit::get(NameStr, StringRecTy::get()),
537                                      Name);
538   }
539 
540   return Name;
541 }
542 
543 /// ParseClassID - Parse and resolve a reference to a class name.  This returns
544 /// null on error.
545 ///
546 ///    ClassID ::= ID
547 ///
548 Record *TGParser::ParseClassID() {
549   if (Lex.getCode() != tgtok::Id) {
550     TokError("expected name for ClassID");
551     return nullptr;
552   }
553 
554   Record *Result = Records.getClass(Lex.getCurStrVal());
555   if (!Result) {
556     std::string Msg("Couldn't find class '" + Lex.getCurStrVal() + "'");
557     if (MultiClasses[Lex.getCurStrVal()].get())
558       TokError(Msg + ". Use 'defm' if you meant to use multiclass '" +
559                Lex.getCurStrVal() + "'");
560     else
561       TokError(Msg);
562   }
563 
564   Lex.Lex();
565   return Result;
566 }
567 
568 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
569 /// This returns null on error.
570 ///
571 ///    MultiClassID ::= ID
572 ///
573 MultiClass *TGParser::ParseMultiClassID() {
574   if (Lex.getCode() != tgtok::Id) {
575     TokError("expected name for MultiClassID");
576     return nullptr;
577   }
578 
579   MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
580   if (!Result)
581     TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
582 
583   Lex.Lex();
584   return Result;
585 }
586 
587 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
588 /// subclass.  This returns a SubClassRefTy with a null Record* on error.
589 ///
590 ///  SubClassRef ::= ClassID
591 ///  SubClassRef ::= ClassID '<' ValueList '>'
592 ///
593 SubClassReference TGParser::
594 ParseSubClassReference(Record *CurRec, bool isDefm) {
595   SubClassReference Result;
596   Result.RefRange.Start = Lex.getLoc();
597 
598   if (isDefm) {
599     if (MultiClass *MC = ParseMultiClassID())
600       Result.Rec = &MC->Rec;
601   } else {
602     Result.Rec = ParseClassID();
603   }
604   if (!Result.Rec) return Result;
605 
606   // If there is no template arg list, we're done.
607   if (!consume(tgtok::less)) {
608     Result.RefRange.End = Lex.getLoc();
609     return Result;
610   }
611 
612   if (Lex.getCode() == tgtok::greater) {
613     TokError("subclass reference requires a non-empty list of template values");
614     Result.Rec = nullptr;
615     return Result;
616   }
617 
618   ParseValueList(Result.TemplateArgs, CurRec, Result.Rec);
619   if (Result.TemplateArgs.empty()) {
620     Result.Rec = nullptr;   // Error parsing value list.
621     return Result;
622   }
623 
624   if (!consume(tgtok::greater)) {
625     TokError("expected '>' in template value list");
626     Result.Rec = nullptr;
627     return Result;
628   }
629   Result.RefRange.End = Lex.getLoc();
630 
631   return Result;
632 }
633 
634 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
635 /// templated submulticlass.  This returns a SubMultiClassRefTy with a null
636 /// Record* on error.
637 ///
638 ///  SubMultiClassRef ::= MultiClassID
639 ///  SubMultiClassRef ::= MultiClassID '<' ValueList '>'
640 ///
641 SubMultiClassReference TGParser::
642 ParseSubMultiClassReference(MultiClass *CurMC) {
643   SubMultiClassReference Result;
644   Result.RefRange.Start = Lex.getLoc();
645 
646   Result.MC = ParseMultiClassID();
647   if (!Result.MC) return Result;
648 
649   // If there is no template arg list, we're done.
650   if (!consume(tgtok::less)) {
651     Result.RefRange.End = Lex.getLoc();
652     return Result;
653   }
654 
655   if (Lex.getCode() == tgtok::greater) {
656     TokError("subclass reference requires a non-empty list of template values");
657     Result.MC = nullptr;
658     return Result;
659   }
660 
661   ParseValueList(Result.TemplateArgs, &CurMC->Rec, &Result.MC->Rec);
662   if (Result.TemplateArgs.empty()) {
663     Result.MC = nullptr;   // Error parsing value list.
664     return Result;
665   }
666 
667   if (!consume(tgtok::greater)) {
668     TokError("expected '>' in template value list");
669     Result.MC = nullptr;
670     return Result;
671   }
672   Result.RefRange.End = Lex.getLoc();
673 
674   return Result;
675 }
676 
677 /// ParseRangePiece - Parse a bit/value range.
678 ///   RangePiece ::= INTVAL
679 ///   RangePiece ::= INTVAL '...' INTVAL
680 ///   RangePiece ::= INTVAL '-' INTVAL
681 ///   RangePiece ::= INTVAL INTVAL
682 // The last two forms are deprecated.
683 bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
684                                TypedInit *FirstItem) {
685   Init *CurVal = FirstItem;
686   if (!CurVal)
687     CurVal = ParseValue(nullptr);
688 
689   IntInit *II = dyn_cast_or_null<IntInit>(CurVal);
690   if (!II)
691     return TokError("expected integer or bitrange");
692 
693   int64_t Start = II->getValue();
694   int64_t End;
695 
696   if (Start < 0)
697     return TokError("invalid range, cannot be negative");
698 
699   switch (Lex.getCode()) {
700   default:
701     Ranges.push_back(Start);
702     return false;
703 
704   case tgtok::dotdotdot:
705   case tgtok::minus: {
706     Lex.Lex(); // eat
707 
708     Init *I_End = ParseValue(nullptr);
709     IntInit *II_End = dyn_cast_or_null<IntInit>(I_End);
710     if (!II_End) {
711       TokError("expected integer value as end of range");
712       return true;
713     }
714 
715     End = II_End->getValue();
716     break;
717   }
718   case tgtok::IntVal: {
719     End = -Lex.getCurIntVal();
720     Lex.Lex();
721     break;
722   }
723   }
724   if (End < 0)
725     return TokError("invalid range, cannot be negative");
726 
727   // Add to the range.
728   if (Start < End)
729     for (; Start <= End; ++Start)
730       Ranges.push_back(Start);
731   else
732     for (; Start >= End; --Start)
733       Ranges.push_back(Start);
734   return false;
735 }
736 
737 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
738 ///
739 ///   RangeList ::= RangePiece (',' RangePiece)*
740 ///
741 void TGParser::ParseRangeList(SmallVectorImpl<unsigned> &Result) {
742   // Parse the first piece.
743   if (ParseRangePiece(Result)) {
744     Result.clear();
745     return;
746   }
747   while (consume(tgtok::comma))
748     // Parse the next range piece.
749     if (ParseRangePiece(Result)) {
750       Result.clear();
751       return;
752     }
753 }
754 
755 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
756 ///   OptionalRangeList ::= '<' RangeList '>'
757 ///   OptionalRangeList ::= /*empty*/
758 bool TGParser::ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges) {
759   SMLoc StartLoc = Lex.getLoc();
760   if (!consume(tgtok::less))
761     return false;
762 
763   // Parse the range list.
764   ParseRangeList(Ranges);
765   if (Ranges.empty()) return true;
766 
767   if (!consume(tgtok::greater)) {
768     TokError("expected '>' at end of range list");
769     return Error(StartLoc, "to match this '<'");
770   }
771   return false;
772 }
773 
774 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
775 ///   OptionalBitList ::= '{' RangeList '}'
776 ///   OptionalBitList ::= /*empty*/
777 bool TGParser::ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges) {
778   SMLoc StartLoc = Lex.getLoc();
779   if (!consume(tgtok::l_brace))
780     return false;
781 
782   // Parse the range list.
783   ParseRangeList(Ranges);
784   if (Ranges.empty()) return true;
785 
786   if (!consume(tgtok::r_brace)) {
787     TokError("expected '}' at end of bit list");
788     return Error(StartLoc, "to match this '{'");
789   }
790   return false;
791 }
792 
793 /// ParseType - Parse and return a tblgen type.  This returns null on error.
794 ///
795 ///   Type ::= STRING                       // string type
796 ///   Type ::= CODE                         // code type
797 ///   Type ::= BIT                          // bit type
798 ///   Type ::= BITS '<' INTVAL '>'          // bits<x> type
799 ///   Type ::= INT                          // int type
800 ///   Type ::= LIST '<' Type '>'            // list<x> type
801 ///   Type ::= DAG                          // dag type
802 ///   Type ::= ClassID                      // Record Type
803 ///
804 RecTy *TGParser::ParseType() {
805   switch (Lex.getCode()) {
806   default: TokError("Unknown token when expecting a type"); return nullptr;
807   case tgtok::String:
808   case tgtok::Code:   Lex.Lex(); return StringRecTy::get();
809   case tgtok::Bit:    Lex.Lex(); return BitRecTy::get();
810   case tgtok::Int:    Lex.Lex(); return IntRecTy::get();
811   case tgtok::Dag:    Lex.Lex(); return DagRecTy::get();
812   case tgtok::Id:
813     if (Record *R = ParseClassID()) return RecordRecTy::get(R);
814     TokError("unknown class name");
815     return nullptr;
816   case tgtok::Bits: {
817     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
818       TokError("expected '<' after bits type");
819       return nullptr;
820     }
821     if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
822       TokError("expected integer in bits<n> type");
823       return nullptr;
824     }
825     uint64_t Val = Lex.getCurIntVal();
826     if (Lex.Lex() != tgtok::greater) { // Eat count.
827       TokError("expected '>' at end of bits<n> type");
828       return nullptr;
829     }
830     Lex.Lex();  // Eat '>'
831     return BitsRecTy::get(Val);
832   }
833   case tgtok::List: {
834     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
835       TokError("expected '<' after list type");
836       return nullptr;
837     }
838     Lex.Lex();  // Eat '<'
839     RecTy *SubType = ParseType();
840     if (!SubType) return nullptr;
841 
842     if (!consume(tgtok::greater)) {
843       TokError("expected '>' at end of list<ty> type");
844       return nullptr;
845     }
846     return ListRecTy::get(SubType);
847   }
848   }
849 }
850 
851 /// ParseIDValue
852 Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMLoc NameLoc,
853                              IDParseMode Mode) {
854   if (CurRec) {
855     if (const RecordVal *RV = CurRec->getValue(Name))
856       return VarInit::get(Name, RV->getType());
857   }
858 
859   if ((CurRec && CurRec->isClass()) || CurMultiClass) {
860     Init *TemplateArgName;
861     if (CurMultiClass) {
862       TemplateArgName =
863           QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
864     } else
865       TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
866 
867     Record *TemplateRec = CurMultiClass ? &CurMultiClass->Rec : CurRec;
868     if (TemplateRec->isTemplateArg(TemplateArgName)) {
869       const RecordVal *RV = TemplateRec->getValue(TemplateArgName);
870       assert(RV && "Template arg doesn't exist??");
871       return VarInit::get(TemplateArgName, RV->getType());
872     } else if (Name->getValue() == "NAME") {
873       return VarInit::get(TemplateArgName, StringRecTy::get());
874     }
875   }
876 
877   if (CurLocalScope)
878     if (Init *I = CurLocalScope->getVar(Name->getValue()))
879       return I;
880 
881   // If this is in a foreach loop, make sure it's not a loop iterator
882   for (const auto &L : Loops) {
883     if (L->IterVar) {
884       VarInit *IterVar = dyn_cast<VarInit>(L->IterVar);
885       if (IterVar && IterVar->getNameInit() == Name)
886         return IterVar;
887     }
888   }
889 
890   if (Mode == ParseNameMode)
891     return Name;
892 
893   if (Init *I = Records.getGlobal(Name->getValue()))
894     return I;
895 
896   // Allow self-references of concrete defs, but delay the lookup so that we
897   // get the correct type.
898   if (CurRec && !CurRec->isClass() && !CurMultiClass &&
899       CurRec->getNameInit() == Name)
900     return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType());
901 
902   Error(NameLoc, "Variable not defined: '" + Name->getValue() + "'");
903   return nullptr;
904 }
905 
906 /// ParseOperation - Parse an operator.  This returns null on error.
907 ///
908 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
909 ///
910 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
911   switch (Lex.getCode()) {
912   default:
913     TokError("unknown bang operator");
914     return nullptr;
915   case tgtok::XNOT:
916   case tgtok::XHead:
917   case tgtok::XTail:
918   case tgtok::XSize:
919   case tgtok::XEmpty:
920   case tgtok::XCast:
921   case tgtok::XGetDagOp: { // Value ::= !unop '(' Value ')'
922     UnOpInit::UnaryOp Code;
923     RecTy *Type = nullptr;
924 
925     switch (Lex.getCode()) {
926     default: llvm_unreachable("Unhandled code!");
927     case tgtok::XCast:
928       Lex.Lex();  // eat the operation
929       Code = UnOpInit::CAST;
930 
931       Type = ParseOperatorType();
932 
933       if (!Type) {
934         TokError("did not get type for unary operator");
935         return nullptr;
936       }
937 
938       break;
939     case tgtok::XNOT:
940       Lex.Lex();  // eat the operation
941       Code = UnOpInit::NOT;
942       Type = IntRecTy::get();
943       break;
944     case tgtok::XHead:
945       Lex.Lex();  // eat the operation
946       Code = UnOpInit::HEAD;
947       break;
948     case tgtok::XTail:
949       Lex.Lex();  // eat the operation
950       Code = UnOpInit::TAIL;
951       break;
952     case tgtok::XSize:
953       Lex.Lex();
954       Code = UnOpInit::SIZE;
955       Type = IntRecTy::get();
956       break;
957     case tgtok::XEmpty:
958       Lex.Lex();  // eat the operation
959       Code = UnOpInit::EMPTY;
960       Type = IntRecTy::get();
961       break;
962     case tgtok::XGetDagOp:
963       Lex.Lex();  // eat the operation
964       if (Lex.getCode() == tgtok::less) {
965         // Parse an optional type suffix, so that you can say
966         // !getdagop<BaseClass>(someDag) as a shorthand for
967         // !cast<BaseClass>(!getdagop(someDag)).
968         Type = ParseOperatorType();
969 
970         if (!Type) {
971           TokError("did not get type for unary operator");
972           return nullptr;
973         }
974 
975         if (!isa<RecordRecTy>(Type)) {
976           TokError("type for !getdagop must be a record type");
977           // but keep parsing, to consume the operand
978         }
979       } else {
980         Type = RecordRecTy::get({});
981       }
982       Code = UnOpInit::GETDAGOP;
983       break;
984     }
985     if (!consume(tgtok::l_paren)) {
986       TokError("expected '(' after unary operator");
987       return nullptr;
988     }
989 
990     Init *LHS = ParseValue(CurRec);
991     if (!LHS) return nullptr;
992 
993     if (Code == UnOpInit::EMPTY || Code == UnOpInit::SIZE) {
994       ListInit *LHSl = dyn_cast<ListInit>(LHS);
995       StringInit *LHSs = dyn_cast<StringInit>(LHS);
996       DagInit *LHSd = dyn_cast<DagInit>(LHS);
997       TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
998       if (!LHSl && !LHSs && !LHSd && !LHSt) {
999         TokError("expected string, list, or dag type argument in unary operator");
1000         return nullptr;
1001       }
1002       if (LHSt) {
1003         ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1004         StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
1005         DagRecTy *DType = dyn_cast<DagRecTy>(LHSt->getType());
1006         if (!LType && !SType && !DType) {
1007           TokError("expected string, list, or dag type argument in unary operator");
1008           return nullptr;
1009         }
1010       }
1011     }
1012 
1013     if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
1014       ListInit *LHSl = dyn_cast<ListInit>(LHS);
1015       TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1016       if (!LHSl && !LHSt) {
1017         TokError("expected list type argument in unary operator");
1018         return nullptr;
1019       }
1020       if (LHSt) {
1021         ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1022         if (!LType) {
1023           TokError("expected list type argument in unary operator");
1024           return nullptr;
1025         }
1026       }
1027 
1028       if (LHSl && LHSl->empty()) {
1029         TokError("empty list argument in unary operator");
1030         return nullptr;
1031       }
1032       if (LHSl) {
1033         Init *Item = LHSl->getElement(0);
1034         TypedInit *Itemt = dyn_cast<TypedInit>(Item);
1035         if (!Itemt) {
1036           TokError("untyped list element in unary operator");
1037           return nullptr;
1038         }
1039         Type = (Code == UnOpInit::HEAD) ? Itemt->getType()
1040                                         : ListRecTy::get(Itemt->getType());
1041       } else {
1042         assert(LHSt && "expected list type argument in unary operator");
1043         ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1044         Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType;
1045       }
1046     }
1047 
1048     if (!consume(tgtok::r_paren)) {
1049       TokError("expected ')' in unary operator");
1050       return nullptr;
1051     }
1052     return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec);
1053   }
1054 
1055   case tgtok::XIsA: {
1056     // Value ::= !isa '<' Type '>' '(' Value ')'
1057     Lex.Lex(); // eat the operation
1058 
1059     RecTy *Type = ParseOperatorType();
1060     if (!Type)
1061       return nullptr;
1062 
1063     if (!consume(tgtok::l_paren)) {
1064       TokError("expected '(' after type of !isa");
1065       return nullptr;
1066     }
1067 
1068     Init *LHS = ParseValue(CurRec);
1069     if (!LHS)
1070       return nullptr;
1071 
1072     if (!consume(tgtok::r_paren)) {
1073       TokError("expected ')' in !isa");
1074       return nullptr;
1075     }
1076 
1077     return (IsAOpInit::get(Type, LHS))->Fold();
1078   }
1079 
1080   case tgtok::XConcat:
1081   case tgtok::XADD:
1082   case tgtok::XSUB:
1083   case tgtok::XMUL:
1084   case tgtok::XAND:
1085   case tgtok::XOR:
1086   case tgtok::XXOR:
1087   case tgtok::XSRA:
1088   case tgtok::XSRL:
1089   case tgtok::XSHL:
1090   case tgtok::XEq:
1091   case tgtok::XNe:
1092   case tgtok::XLe:
1093   case tgtok::XLt:
1094   case tgtok::XGe:
1095   case tgtok::XGt:
1096   case tgtok::XListConcat:
1097   case tgtok::XListSplat:
1098   case tgtok::XStrConcat:
1099   case tgtok::XInterleave:
1100   case tgtok::XSetDagOp: { // Value ::= !binop '(' Value ',' Value ')'
1101     tgtok::TokKind OpTok = Lex.getCode();
1102     SMLoc OpLoc = Lex.getLoc();
1103     Lex.Lex();  // eat the operation
1104 
1105     BinOpInit::BinaryOp Code;
1106     switch (OpTok) {
1107     default: llvm_unreachable("Unhandled code!");
1108     case tgtok::XConcat: Code = BinOpInit::CONCAT; break;
1109     case tgtok::XADD:    Code = BinOpInit::ADD; break;
1110     case tgtok::XSUB:    Code = BinOpInit::SUB; break;
1111     case tgtok::XMUL:    Code = BinOpInit::MUL; break;
1112     case tgtok::XAND:    Code = BinOpInit::AND; break;
1113     case tgtok::XOR:     Code = BinOpInit::OR; break;
1114     case tgtok::XXOR:    Code = BinOpInit::XOR; break;
1115     case tgtok::XSRA:    Code = BinOpInit::SRA; break;
1116     case tgtok::XSRL:    Code = BinOpInit::SRL; break;
1117     case tgtok::XSHL:    Code = BinOpInit::SHL; break;
1118     case tgtok::XEq:     Code = BinOpInit::EQ; break;
1119     case tgtok::XNe:     Code = BinOpInit::NE; break;
1120     case tgtok::XLe:     Code = BinOpInit::LE; break;
1121     case tgtok::XLt:     Code = BinOpInit::LT; break;
1122     case tgtok::XGe:     Code = BinOpInit::GE; break;
1123     case tgtok::XGt:     Code = BinOpInit::GT; break;
1124     case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break;
1125     case tgtok::XListSplat:  Code = BinOpInit::LISTSPLAT; break;
1126     case tgtok::XStrConcat:  Code = BinOpInit::STRCONCAT; break;
1127     case tgtok::XInterleave: Code = BinOpInit::INTERLEAVE; break;
1128     case tgtok::XSetDagOp:   Code = BinOpInit::SETDAGOP; break;
1129     }
1130 
1131     RecTy *Type = nullptr;
1132     RecTy *ArgType = nullptr;
1133     switch (OpTok) {
1134     default:
1135       llvm_unreachable("Unhandled code!");
1136     case tgtok::XConcat:
1137     case tgtok::XSetDagOp:
1138       Type = DagRecTy::get();
1139       ArgType = DagRecTy::get();
1140       break;
1141     case tgtok::XAND:
1142     case tgtok::XOR:
1143     case tgtok::XXOR:
1144     case tgtok::XSRA:
1145     case tgtok::XSRL:
1146     case tgtok::XSHL:
1147     case tgtok::XADD:
1148     case tgtok::XSUB:
1149     case tgtok::XMUL:
1150       Type = IntRecTy::get();
1151       ArgType = IntRecTy::get();
1152       break;
1153     case tgtok::XEq:
1154     case tgtok::XNe:
1155     case tgtok::XLe:
1156     case tgtok::XLt:
1157     case tgtok::XGe:
1158     case tgtok::XGt:
1159       Type = BitRecTy::get();
1160       // ArgType for the comparison operators is not yet known.
1161       break;
1162     case tgtok::XListConcat:
1163       // We don't know the list type until we parse the first argument
1164       ArgType = ItemType;
1165       break;
1166     case tgtok::XListSplat:
1167       // Can't do any typechecking until we parse the first argument.
1168       break;
1169     case tgtok::XStrConcat:
1170       Type = StringRecTy::get();
1171       ArgType = StringRecTy::get();
1172       break;
1173     case tgtok::XInterleave:
1174       Type = StringRecTy::get();
1175       // The first argument type is not yet known.
1176     }
1177 
1178     if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) {
1179       Error(OpLoc, Twine("expected value of type '") +
1180                    ItemType->getAsString() + "', got '" +
1181                    Type->getAsString() + "'");
1182       return nullptr;
1183     }
1184 
1185     if (!consume(tgtok::l_paren)) {
1186       TokError("expected '(' after binary operator");
1187       return nullptr;
1188     }
1189 
1190     SmallVector<Init*, 2> InitList;
1191 
1192     // Note that this loop consumes an arbitrary number of arguments.
1193     // The actual count is checked later.
1194     for (;;) {
1195       SMLoc InitLoc = Lex.getLoc();
1196       InitList.push_back(ParseValue(CurRec, ArgType));
1197       if (!InitList.back()) return nullptr;
1198 
1199       TypedInit *InitListBack = dyn_cast<TypedInit>(InitList.back());
1200       if (!InitListBack) {
1201         Error(OpLoc, Twine("expected value to be a typed value, got '" +
1202                            InitList.back()->getAsString() + "'"));
1203         return nullptr;
1204       }
1205       RecTy *ListType = InitListBack->getType();
1206 
1207       if (!ArgType) {
1208         // Argument type must be determined from the argument itself.
1209         ArgType = ListType;
1210 
1211         switch (Code) {
1212         case BinOpInit::LISTCONCAT:
1213           if (!isa<ListRecTy>(ArgType)) {
1214             Error(InitLoc, Twine("expected a list, got value of type '") +
1215                            ArgType->getAsString() + "'");
1216             return nullptr;
1217           }
1218           break;
1219         case BinOpInit::LISTSPLAT:
1220           if (ItemType && InitList.size() == 1) {
1221             if (!isa<ListRecTy>(ItemType)) {
1222               Error(OpLoc,
1223                     Twine("expected output type to be a list, got type '") +
1224                         ItemType->getAsString() + "'");
1225               return nullptr;
1226             }
1227             if (!ArgType->getListTy()->typeIsConvertibleTo(ItemType)) {
1228               Error(OpLoc, Twine("expected first arg type to be '") +
1229                                ArgType->getAsString() +
1230                                "', got value of type '" +
1231                                cast<ListRecTy>(ItemType)
1232                                    ->getElementType()
1233                                    ->getAsString() +
1234                                "'");
1235               return nullptr;
1236             }
1237           }
1238           if (InitList.size() == 2 && !isa<IntRecTy>(ArgType)) {
1239             Error(InitLoc, Twine("expected second parameter to be an int, got "
1240                                  "value of type '") +
1241                                ArgType->getAsString() + "'");
1242             return nullptr;
1243           }
1244           ArgType = nullptr; // Broken invariant: types not identical.
1245           break;
1246         case BinOpInit::EQ:
1247         case BinOpInit::NE:
1248           if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) &&
1249               !ArgType->typeIsConvertibleTo(StringRecTy::get()) &&
1250               !ArgType->typeIsConvertibleTo(RecordRecTy::get({}))) {
1251             Error(InitLoc, Twine("expected bit, bits, int, string, or record; "
1252                                  "got value of type '") + ArgType->getAsString() +
1253                                  "'");
1254             return nullptr;
1255           }
1256           break;
1257         case BinOpInit::LE:
1258         case BinOpInit::LT:
1259         case BinOpInit::GE:
1260         case BinOpInit::GT:
1261           if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) &&
1262               !ArgType->typeIsConvertibleTo(StringRecTy::get())) {
1263             Error(InitLoc, Twine("expected bit, bits, int, or string; "
1264                                  "got value of type '") + ArgType->getAsString() +
1265                                  "'");
1266             return nullptr;
1267           }
1268           break;
1269         case BinOpInit::INTERLEAVE:
1270           switch (InitList.size()) {
1271           case 1: // First argument must be a list of strings or integers.
1272             if (ArgType != StringRecTy::get()->getListTy() &&
1273                 !ArgType->typeIsConvertibleTo(IntRecTy::get()->getListTy())) {
1274               Error(InitLoc, Twine("expected list of string, int, bits, or bit; "
1275                                    "got value of type '") +
1276                                    ArgType->getAsString() + "'");
1277               return nullptr;
1278             }
1279             break;
1280           case 2: // Second argument must be a string.
1281             if (!isa<StringRecTy>(ArgType)) {
1282               Error(InitLoc, Twine("expected second argument to be a string, "
1283                                    "got value of type '") +
1284                                  ArgType->getAsString() + "'");
1285               return nullptr;
1286             }
1287             break;
1288           default: ;
1289           }
1290           ArgType = nullptr; // Broken invariant: types not identical.
1291           break;
1292         default: llvm_unreachable("other ops have fixed argument types");
1293         }
1294 
1295       } else {
1296         // Desired argument type is a known and in ArgType.
1297         RecTy *Resolved = resolveTypes(ArgType, ListType);
1298         if (!Resolved) {
1299           Error(InitLoc, Twine("expected value of type '") +
1300                              ArgType->getAsString() + "', got '" +
1301                              ListType->getAsString() + "'");
1302           return nullptr;
1303         }
1304         if (Code != BinOpInit::ADD && Code != BinOpInit::SUB &&
1305             Code != BinOpInit::AND && Code != BinOpInit::OR &&
1306             Code != BinOpInit::XOR && Code != BinOpInit::SRA &&
1307             Code != BinOpInit::SRL && Code != BinOpInit::SHL &&
1308             Code != BinOpInit::MUL)
1309           ArgType = Resolved;
1310       }
1311 
1312       // Deal with BinOps whose arguments have different types, by
1313       // rewriting ArgType in between them.
1314       switch (Code) {
1315         case BinOpInit::SETDAGOP:
1316           // After parsing the first dag argument, switch to expecting
1317           // a record, with no restriction on its superclasses.
1318           ArgType = RecordRecTy::get({});
1319           break;
1320         default:
1321           break;
1322       }
1323 
1324       if (!consume(tgtok::comma))
1325         break;
1326     }
1327 
1328     if (!consume(tgtok::r_paren)) {
1329       TokError("expected ')' in operator");
1330       return nullptr;
1331     }
1332 
1333     // listconcat returns a list with type of the argument.
1334     if (Code == BinOpInit::LISTCONCAT)
1335       Type = ArgType;
1336     // listsplat returns a list of type of the *first* argument.
1337     if (Code == BinOpInit::LISTSPLAT)
1338       Type = cast<TypedInit>(InitList.front())->getType()->getListTy();
1339 
1340     // We allow multiple operands to associative operators like !strconcat as
1341     // shorthand for nesting them.
1342     if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT ||
1343         Code == BinOpInit::CONCAT || Code == BinOpInit::ADD ||
1344         Code == BinOpInit::AND || Code == BinOpInit::OR ||
1345         Code == BinOpInit::XOR || Code == BinOpInit::MUL) {
1346       while (InitList.size() > 2) {
1347         Init *RHS = InitList.pop_back_val();
1348         RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec);
1349         InitList.back() = RHS;
1350       }
1351     }
1352 
1353     if (InitList.size() == 2)
1354       return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
1355           ->Fold(CurRec);
1356 
1357     Error(OpLoc, "expected two operands to operator");
1358     return nullptr;
1359   }
1360 
1361   case tgtok::XForEach:
1362   case tgtok::XFilter: {
1363     return ParseOperationForEachFilter(CurRec, ItemType);
1364   }
1365 
1366   case tgtok::XDag:
1367   case tgtok::XIf:
1368   case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1369     TernOpInit::TernaryOp Code;
1370     RecTy *Type = nullptr;
1371 
1372     tgtok::TokKind LexCode = Lex.getCode();
1373     Lex.Lex();  // eat the operation
1374     switch (LexCode) {
1375     default: llvm_unreachable("Unhandled code!");
1376     case tgtok::XDag:
1377       Code = TernOpInit::DAG;
1378       Type = DagRecTy::get();
1379       ItemType = nullptr;
1380       break;
1381     case tgtok::XIf:
1382       Code = TernOpInit::IF;
1383       break;
1384     case tgtok::XSubst:
1385       Code = TernOpInit::SUBST;
1386       break;
1387     }
1388     if (!consume(tgtok::l_paren)) {
1389       TokError("expected '(' after ternary operator");
1390       return nullptr;
1391     }
1392 
1393     Init *LHS = ParseValue(CurRec);
1394     if (!LHS) return nullptr;
1395 
1396     if (!consume(tgtok::comma)) {
1397       TokError("expected ',' in ternary operator");
1398       return nullptr;
1399     }
1400 
1401     SMLoc MHSLoc = Lex.getLoc();
1402     Init *MHS = ParseValue(CurRec, ItemType);
1403     if (!MHS)
1404       return nullptr;
1405 
1406     if (!consume(tgtok::comma)) {
1407       TokError("expected ',' in ternary operator");
1408       return nullptr;
1409     }
1410 
1411     SMLoc RHSLoc = Lex.getLoc();
1412     Init *RHS = ParseValue(CurRec, ItemType);
1413     if (!RHS)
1414       return nullptr;
1415 
1416     if (!consume(tgtok::r_paren)) {
1417       TokError("expected ')' in binary operator");
1418       return nullptr;
1419     }
1420 
1421     switch (LexCode) {
1422     default: llvm_unreachable("Unhandled code!");
1423     case tgtok::XDag: {
1424       TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1425       if (!MHSt && !isa<UnsetInit>(MHS)) {
1426         Error(MHSLoc, "could not determine type of the child list in !dag");
1427         return nullptr;
1428       }
1429       if (MHSt && !isa<ListRecTy>(MHSt->getType())) {
1430         Error(MHSLoc, Twine("expected list of children, got type '") +
1431                           MHSt->getType()->getAsString() + "'");
1432         return nullptr;
1433       }
1434 
1435       TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1436       if (!RHSt && !isa<UnsetInit>(RHS)) {
1437         Error(RHSLoc, "could not determine type of the name list in !dag");
1438         return nullptr;
1439       }
1440       if (RHSt && StringRecTy::get()->getListTy() != RHSt->getType()) {
1441         Error(RHSLoc, Twine("expected list<string>, got type '") +
1442                           RHSt->getType()->getAsString() + "'");
1443         return nullptr;
1444       }
1445 
1446       if (!MHSt && !RHSt) {
1447         Error(MHSLoc,
1448               "cannot have both unset children and unset names in !dag");
1449         return nullptr;
1450       }
1451       break;
1452     }
1453     case tgtok::XIf: {
1454       RecTy *MHSTy = nullptr;
1455       RecTy *RHSTy = nullptr;
1456 
1457       if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1458         MHSTy = MHSt->getType();
1459       if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1460         MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1461       if (isa<BitInit>(MHS))
1462         MHSTy = BitRecTy::get();
1463 
1464       if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1465         RHSTy = RHSt->getType();
1466       if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1467         RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1468       if (isa<BitInit>(RHS))
1469         RHSTy = BitRecTy::get();
1470 
1471       // For UnsetInit, it's typed from the other hand.
1472       if (isa<UnsetInit>(MHS))
1473         MHSTy = RHSTy;
1474       if (isa<UnsetInit>(RHS))
1475         RHSTy = MHSTy;
1476 
1477       if (!MHSTy || !RHSTy) {
1478         TokError("could not get type for !if");
1479         return nullptr;
1480       }
1481 
1482       Type = resolveTypes(MHSTy, RHSTy);
1483       if (!Type) {
1484         TokError(Twine("inconsistent types '") + MHSTy->getAsString() +
1485                  "' and '" + RHSTy->getAsString() + "' for !if");
1486         return nullptr;
1487       }
1488       break;
1489     }
1490     case tgtok::XSubst: {
1491       TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1492       if (!RHSt) {
1493         TokError("could not get type for !subst");
1494         return nullptr;
1495       }
1496       Type = RHSt->getType();
1497       break;
1498     }
1499     }
1500     return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
1501   }
1502 
1503   case tgtok::XSubstr:
1504     return ParseOperationSubstr(CurRec, ItemType);
1505 
1506   case tgtok::XCond:
1507     return ParseOperationCond(CurRec, ItemType);
1508 
1509   case tgtok::XFoldl: {
1510     // Value ::= !foldl '(' Value ',' Value ',' Id ',' Id ',' Expr ')'
1511     Lex.Lex(); // eat the operation
1512     if (!consume(tgtok::l_paren)) {
1513       TokError("expected '(' after !foldl");
1514       return nullptr;
1515     }
1516 
1517     Init *StartUntyped = ParseValue(CurRec);
1518     if (!StartUntyped)
1519       return nullptr;
1520 
1521     TypedInit *Start = dyn_cast<TypedInit>(StartUntyped);
1522     if (!Start) {
1523       TokError(Twine("could not get type of !foldl start: '") +
1524                StartUntyped->getAsString() + "'");
1525       return nullptr;
1526     }
1527 
1528     if (!consume(tgtok::comma)) {
1529       TokError("expected ',' in !foldl");
1530       return nullptr;
1531     }
1532 
1533     Init *ListUntyped = ParseValue(CurRec);
1534     if (!ListUntyped)
1535       return nullptr;
1536 
1537     TypedInit *List = dyn_cast<TypedInit>(ListUntyped);
1538     if (!List) {
1539       TokError(Twine("could not get type of !foldl list: '") +
1540                ListUntyped->getAsString() + "'");
1541       return nullptr;
1542     }
1543 
1544     ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType());
1545     if (!ListType) {
1546       TokError(Twine("!foldl list must be a list, but is of type '") +
1547                List->getType()->getAsString());
1548       return nullptr;
1549     }
1550 
1551     if (Lex.getCode() != tgtok::comma) {
1552       TokError("expected ',' in !foldl");
1553       return nullptr;
1554     }
1555 
1556     if (Lex.Lex() != tgtok::Id) { // eat the ','
1557       TokError("third argument of !foldl must be an identifier");
1558       return nullptr;
1559     }
1560 
1561     Init *A = StringInit::get(Lex.getCurStrVal());
1562     if (CurRec && CurRec->getValue(A)) {
1563       TokError((Twine("left !foldl variable '") + A->getAsString() +
1564                 "' already defined")
1565                    .str());
1566       return nullptr;
1567     }
1568 
1569     if (Lex.Lex() != tgtok::comma) { // eat the id
1570       TokError("expected ',' in !foldl");
1571       return nullptr;
1572     }
1573 
1574     if (Lex.Lex() != tgtok::Id) { // eat the ','
1575       TokError("fourth argument of !foldl must be an identifier");
1576       return nullptr;
1577     }
1578 
1579     Init *B = StringInit::get(Lex.getCurStrVal());
1580     if (CurRec && CurRec->getValue(B)) {
1581       TokError((Twine("right !foldl variable '") + B->getAsString() +
1582                 "' already defined")
1583                    .str());
1584       return nullptr;
1585     }
1586 
1587     if (Lex.Lex() != tgtok::comma) { // eat the id
1588       TokError("expected ',' in !foldl");
1589       return nullptr;
1590     }
1591     Lex.Lex(); // eat the ','
1592 
1593     // We need to create a temporary record to provide a scope for the
1594     // two variables.
1595     std::unique_ptr<Record> ParseRecTmp;
1596     Record *ParseRec = CurRec;
1597     if (!ParseRec) {
1598       ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1599       ParseRec = ParseRecTmp.get();
1600     }
1601 
1602     ParseRec->addValue(RecordVal(A, Start->getType(), RecordVal::FK_Normal));
1603     ParseRec->addValue(RecordVal(B, ListType->getElementType(),
1604                                  RecordVal::FK_Normal));
1605     Init *ExprUntyped = ParseValue(ParseRec);
1606     ParseRec->removeValue(A);
1607     ParseRec->removeValue(B);
1608     if (!ExprUntyped)
1609       return nullptr;
1610 
1611     TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped);
1612     if (!Expr) {
1613       TokError("could not get type of !foldl expression");
1614       return nullptr;
1615     }
1616 
1617     if (Expr->getType() != Start->getType()) {
1618       TokError(Twine("!foldl expression must be of same type as start (") +
1619                Start->getType()->getAsString() + "), but is of type " +
1620                Expr->getType()->getAsString());
1621       return nullptr;
1622     }
1623 
1624     if (!consume(tgtok::r_paren)) {
1625       TokError("expected ')' in fold operator");
1626       return nullptr;
1627     }
1628 
1629     return FoldOpInit::get(Start, List, A, B, Expr, Start->getType())
1630         ->Fold(CurRec);
1631   }
1632   }
1633 }
1634 
1635 /// ParseOperatorType - Parse a type for an operator.  This returns
1636 /// null on error.
1637 ///
1638 /// OperatorType ::= '<' Type '>'
1639 ///
1640 RecTy *TGParser::ParseOperatorType() {
1641   RecTy *Type = nullptr;
1642 
1643   if (!consume(tgtok::less)) {
1644     TokError("expected type name for operator");
1645     return nullptr;
1646   }
1647 
1648   if (Lex.getCode() == tgtok::Code)
1649     TokError("the 'code' type is not allowed in bang operators; use 'string'");
1650 
1651   Type = ParseType();
1652 
1653   if (!Type) {
1654     TokError("expected type name for operator");
1655     return nullptr;
1656   }
1657 
1658   if (!consume(tgtok::greater)) {
1659     TokError("expected type name for operator");
1660     return nullptr;
1661   }
1662 
1663   return Type;
1664 }
1665 
1666 /// Parse the !substr operation. Return null on error.
1667 ///
1668 /// Substr ::= !substr(string, start-int [, length-int]) => string
1669 Init *TGParser::ParseOperationSubstr(Record *CurRec, RecTy *ItemType) {
1670   TernOpInit::TernaryOp Code = TernOpInit::SUBSTR;
1671   RecTy *Type = StringRecTy::get();
1672 
1673   Lex.Lex(); // eat the operation
1674 
1675   if (!consume(tgtok::l_paren)) {
1676     TokError("expected '(' after !substr operator");
1677     return nullptr;
1678   }
1679 
1680   Init *LHS = ParseValue(CurRec);
1681   if (!LHS)
1682     return nullptr;
1683 
1684   if (!consume(tgtok::comma)) {
1685     TokError("expected ',' in !substr operator");
1686     return nullptr;
1687   }
1688 
1689   SMLoc MHSLoc = Lex.getLoc();
1690   Init *MHS = ParseValue(CurRec);
1691   if (!MHS)
1692     return nullptr;
1693 
1694   SMLoc RHSLoc = Lex.getLoc();
1695   Init *RHS;
1696   if (consume(tgtok::comma)) {
1697     RHSLoc = Lex.getLoc();
1698     RHS = ParseValue(CurRec);
1699     if (!RHS)
1700       return nullptr;
1701   } else {
1702     RHS = IntInit::get(std::numeric_limits<int64_t>::max());
1703   }
1704 
1705   if (!consume(tgtok::r_paren)) {
1706     TokError("expected ')' in !substr operator");
1707     return nullptr;
1708   }
1709 
1710   if (ItemType && !Type->typeIsConvertibleTo(ItemType)) {
1711     Error(RHSLoc, Twine("expected value of type '") +
1712                   ItemType->getAsString() + "', got '" +
1713                   Type->getAsString() + "'");
1714   }
1715 
1716   TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1717   if (!LHSt && !isa<UnsetInit>(LHS)) {
1718     TokError("could not determine type of the string in !substr");
1719     return nullptr;
1720   }
1721   if (LHSt && !isa<StringRecTy>(LHSt->getType())) {
1722     TokError(Twine("expected string, got type '") +
1723              LHSt->getType()->getAsString() + "'");
1724     return nullptr;
1725   }
1726 
1727   TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1728   if (!MHSt && !isa<UnsetInit>(MHS)) {
1729     TokError("could not determine type of the start position in !substr");
1730     return nullptr;
1731   }
1732   if (MHSt && !isa<IntRecTy>(MHSt->getType())) {
1733     Error(MHSLoc, Twine("expected int, got type '") +
1734                       MHSt->getType()->getAsString() + "'");
1735     return nullptr;
1736   }
1737 
1738   if (RHS) {
1739     TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1740     if (!RHSt && !isa<UnsetInit>(RHS)) {
1741       TokError("could not determine type of the length in !substr");
1742       return nullptr;
1743     }
1744     if (RHSt && !isa<IntRecTy>(RHSt->getType())) {
1745       TokError(Twine("expected int, got type '") +
1746                RHSt->getType()->getAsString() + "'");
1747       return nullptr;
1748     }
1749   }
1750 
1751   return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
1752 }
1753 
1754 /// Parse the !foreach and !filter operations. Return null on error.
1755 ///
1756 /// ForEach ::= !foreach(ID, list-or-dag, expr) => list<expr type>
1757 /// Filter  ::= !foreach(ID, list, predicate) ==> list<list type>
1758 Init *TGParser::ParseOperationForEachFilter(Record *CurRec, RecTy *ItemType) {
1759   SMLoc OpLoc = Lex.getLoc();
1760   tgtok::TokKind Operation = Lex.getCode();
1761   Lex.Lex(); // eat the operation
1762   if (Lex.getCode() != tgtok::l_paren) {
1763     TokError("expected '(' after !foreach/!filter");
1764     return nullptr;
1765   }
1766 
1767   if (Lex.Lex() != tgtok::Id) { // eat the '('
1768     TokError("first argument of !foreach/!filter must be an identifier");
1769     return nullptr;
1770   }
1771 
1772   Init *LHS = StringInit::get(Lex.getCurStrVal());
1773   Lex.Lex(); // eat the ID.
1774 
1775   if (CurRec && CurRec->getValue(LHS)) {
1776     TokError((Twine("iteration variable '") + LHS->getAsString() +
1777               "' is already defined")
1778                  .str());
1779     return nullptr;
1780   }
1781 
1782   if (!consume(tgtok::comma)) {
1783     TokError("expected ',' in !foreach/!filter");
1784     return nullptr;
1785   }
1786 
1787   Init *MHS = ParseValue(CurRec);
1788   if (!MHS)
1789     return nullptr;
1790 
1791   if (!consume(tgtok::comma)) {
1792     TokError("expected ',' in !foreach/!filter");
1793     return nullptr;
1794   }
1795 
1796   TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1797   if (!MHSt) {
1798     TokError("could not get type of !foreach/!filter list or dag");
1799     return nullptr;
1800   }
1801 
1802   RecTy *InEltType = nullptr;
1803   RecTy *ExprEltType = nullptr;
1804   bool IsDAG = false;
1805 
1806   if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) {
1807     InEltType = InListTy->getElementType();
1808     if (ItemType) {
1809       if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) {
1810         ExprEltType = (Operation == tgtok::XForEach)
1811                           ? OutListTy->getElementType()
1812                           : IntRecTy::get();
1813       } else {
1814         Error(OpLoc,
1815               "expected value of type '" +
1816                   Twine(ItemType->getAsString()) +
1817                   "', but got list type");
1818         return nullptr;
1819       }
1820     }
1821   } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) {
1822     if (Operation == tgtok::XFilter) {
1823       TokError("!filter must have a list argument");
1824       return nullptr;
1825     }
1826     InEltType = InDagTy;
1827     if (ItemType && !isa<DagRecTy>(ItemType)) {
1828       Error(OpLoc,
1829             "expected value of type '" + Twine(ItemType->getAsString()) +
1830                 "', but got dag type");
1831       return nullptr;
1832     }
1833     IsDAG = true;
1834   } else {
1835     if (Operation == tgtok::XForEach)
1836       TokError("!foreach must have a list or dag argument");
1837     else
1838       TokError("!filter must have a list argument");
1839     return nullptr;
1840   }
1841 
1842   // We need to create a temporary record to provide a scope for the
1843   // iteration variable.
1844   std::unique_ptr<Record> ParseRecTmp;
1845   Record *ParseRec = CurRec;
1846   if (!ParseRec) {
1847     ParseRecTmp =
1848         std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1849     ParseRec = ParseRecTmp.get();
1850   }
1851 
1852   ParseRec->addValue(RecordVal(LHS, InEltType, RecordVal::FK_Normal));
1853   Init *RHS = ParseValue(ParseRec, ExprEltType);
1854   ParseRec->removeValue(LHS);
1855   if (!RHS)
1856     return nullptr;
1857 
1858   if (!consume(tgtok::r_paren)) {
1859     TokError("expected ')' in !foreach/!filter");
1860     return nullptr;
1861   }
1862 
1863   RecTy *OutType = InEltType;
1864   if (Operation == tgtok::XForEach && !IsDAG) {
1865     TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1866     if (!RHSt) {
1867       TokError("could not get type of !foreach result expression");
1868       return nullptr;
1869     }
1870     OutType = RHSt->getType()->getListTy();
1871   } else if (Operation == tgtok::XFilter) {
1872     OutType = InEltType->getListTy();
1873   }
1874 
1875   return (TernOpInit::get((Operation == tgtok::XForEach) ? TernOpInit::FOREACH
1876                                                          : TernOpInit::FILTER,
1877                           LHS, MHS, RHS, OutType))
1878       ->Fold(CurRec);
1879 }
1880 
1881 Init *TGParser::ParseOperationCond(Record *CurRec, RecTy *ItemType) {
1882   Lex.Lex();  // eat the operation 'cond'
1883 
1884   if (!consume(tgtok::l_paren)) {
1885     TokError("expected '(' after !cond operator");
1886     return nullptr;
1887   }
1888 
1889   // Parse through '[Case: Val,]+'
1890   SmallVector<Init *, 4> Case;
1891   SmallVector<Init *, 4> Val;
1892   while (true) {
1893     if (consume(tgtok::r_paren))
1894       break;
1895 
1896     Init *V = ParseValue(CurRec);
1897     if (!V)
1898       return nullptr;
1899     Case.push_back(V);
1900 
1901     if (!consume(tgtok::colon)) {
1902       TokError("expected ':'  following a condition in !cond operator");
1903       return nullptr;
1904     }
1905 
1906     V = ParseValue(CurRec, ItemType);
1907     if (!V)
1908       return nullptr;
1909     Val.push_back(V);
1910 
1911     if (consume(tgtok::r_paren))
1912       break;
1913 
1914     if (!consume(tgtok::comma)) {
1915       TokError("expected ',' or ')' following a value in !cond operator");
1916       return nullptr;
1917     }
1918   }
1919 
1920   if (Case.size() < 1) {
1921     TokError("there should be at least 1 'condition : value' in the !cond operator");
1922     return nullptr;
1923   }
1924 
1925   // resolve type
1926   RecTy *Type = nullptr;
1927   for (Init *V : Val) {
1928     RecTy *VTy = nullptr;
1929     if (TypedInit *Vt = dyn_cast<TypedInit>(V))
1930       VTy = Vt->getType();
1931     if (BitsInit *Vbits = dyn_cast<BitsInit>(V))
1932       VTy = BitsRecTy::get(Vbits->getNumBits());
1933     if (isa<BitInit>(V))
1934       VTy = BitRecTy::get();
1935 
1936     if (Type == nullptr) {
1937       if (!isa<UnsetInit>(V))
1938         Type = VTy;
1939     } else {
1940       if (!isa<UnsetInit>(V)) {
1941         RecTy *RType = resolveTypes(Type, VTy);
1942         if (!RType) {
1943           TokError(Twine("inconsistent types '") + Type->getAsString() +
1944                          "' and '" + VTy->getAsString() + "' for !cond");
1945           return nullptr;
1946         }
1947         Type = RType;
1948       }
1949     }
1950   }
1951 
1952   if (!Type) {
1953     TokError("could not determine type for !cond from its arguments");
1954     return nullptr;
1955   }
1956   return CondOpInit::get(Case, Val, Type)->Fold(CurRec);
1957 }
1958 
1959 /// ParseSimpleValue - Parse a tblgen value.  This returns null on error.
1960 ///
1961 ///   SimpleValue ::= IDValue
1962 ///   SimpleValue ::= INTVAL
1963 ///   SimpleValue ::= STRVAL+
1964 ///   SimpleValue ::= CODEFRAGMENT
1965 ///   SimpleValue ::= '?'
1966 ///   SimpleValue ::= '{' ValueList '}'
1967 ///   SimpleValue ::= ID '<' ValueListNE '>'
1968 ///   SimpleValue ::= '[' ValueList ']'
1969 ///   SimpleValue ::= '(' IDValue DagArgList ')'
1970 ///   SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1971 ///   SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1972 ///   SimpleValue ::= SUBTOK '(' Value ',' Value ')'
1973 ///   SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1974 ///   SimpleValue ::= SRATOK '(' Value ',' Value ')'
1975 ///   SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1976 ///   SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1977 ///   SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')'
1978 ///   SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1979 ///   SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
1980 ///
1981 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1982                                  IDParseMode Mode) {
1983   Init *R = nullptr;
1984   switch (Lex.getCode()) {
1985   default: TokError("Unknown or reserved token when parsing a value"); break;
1986 
1987   case tgtok::TrueVal:
1988     R = IntInit::get(1);
1989     Lex.Lex();
1990     break;
1991   case tgtok::FalseVal:
1992     R = IntInit::get(0);
1993     Lex.Lex();
1994     break;
1995   case tgtok::IntVal:
1996     R = IntInit::get(Lex.getCurIntVal());
1997     Lex.Lex();
1998     break;
1999   case tgtok::BinaryIntVal: {
2000     auto BinaryVal = Lex.getCurBinaryIntVal();
2001     SmallVector<Init*, 16> Bits(BinaryVal.second);
2002     for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
2003       Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
2004     R = BitsInit::get(Bits);
2005     Lex.Lex();
2006     break;
2007   }
2008   case tgtok::StrVal: {
2009     std::string Val = Lex.getCurStrVal();
2010     Lex.Lex();
2011 
2012     // Handle multiple consecutive concatenated strings.
2013     while (Lex.getCode() == tgtok::StrVal) {
2014       Val += Lex.getCurStrVal();
2015       Lex.Lex();
2016     }
2017 
2018     R = StringInit::get(Val);
2019     break;
2020   }
2021   case tgtok::CodeFragment:
2022     R = StringInit::get(Lex.getCurStrVal(), StringInit::SF_Code);
2023     Lex.Lex();
2024     break;
2025   case tgtok::question:
2026     R = UnsetInit::get();
2027     Lex.Lex();
2028     break;
2029   case tgtok::Id: {
2030     SMLoc NameLoc = Lex.getLoc();
2031     StringInit *Name = StringInit::get(Lex.getCurStrVal());
2032     if (Lex.Lex() != tgtok::less)  // consume the Id.
2033       return ParseIDValue(CurRec, Name, NameLoc, Mode);    // Value ::= IDValue
2034 
2035     // Value ::= ID '<' ValueListNE '>'
2036     if (Lex.Lex() == tgtok::greater) {
2037       TokError("expected non-empty value list");
2038       return nullptr;
2039     }
2040 
2041     // This is a CLASS<initvalslist> expression.  This is supposed to synthesize
2042     // a new anonymous definition, deriving from CLASS<initvalslist> with no
2043     // body.
2044     Record *Class = Records.getClass(Name->getValue());
2045     if (!Class) {
2046       Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'");
2047       return nullptr;
2048     }
2049 
2050     SmallVector<Init *, 8> Args;
2051     ParseValueList(Args, CurRec, Class);
2052     if (Args.empty()) return nullptr;
2053 
2054     if (!consume(tgtok::greater)) {
2055       TokError("expected '>' at end of value list");
2056       return nullptr;
2057     }
2058 
2059     // Typecheck the template arguments list
2060     ArrayRef<Init *> ExpectedArgs = Class->getTemplateArgs();
2061     if (ExpectedArgs.size() < Args.size()) {
2062       Error(NameLoc,
2063             "More template args specified than expected");
2064       return nullptr;
2065     }
2066 
2067     for (unsigned i = 0, e = ExpectedArgs.size(); i != e; ++i) {
2068       RecordVal *ExpectedArg = Class->getValue(ExpectedArgs[i]);
2069       if (i < Args.size()) {
2070         if (TypedInit *TI = dyn_cast<TypedInit>(Args[i])) {
2071           RecTy *ExpectedType = ExpectedArg->getType();
2072           if (!TI->getType()->typeIsConvertibleTo(ExpectedType)) {
2073             Error(NameLoc,
2074                   "Value specified for template argument #" + Twine(i) + " (" +
2075                   ExpectedArg->getNameInitAsString() + ") is of type '" +
2076                   TI->getType()->getAsString() + "', expected '" +
2077                   ExpectedType->getAsString() + "': " + TI->getAsString());
2078             return nullptr;
2079           }
2080           continue;
2081         }
2082       } else if (ExpectedArg->getValue()->isComplete())
2083         continue;
2084 
2085       Error(NameLoc,
2086             "Value not specified for template argument #" + Twine(i) + " (" +
2087             ExpectedArgs[i]->getAsUnquotedString() + ")");
2088       return nullptr;
2089     }
2090 
2091     return VarDefInit::get(Class, Args)->Fold();
2092   }
2093   case tgtok::l_brace: {           // Value ::= '{' ValueList '}'
2094     SMLoc BraceLoc = Lex.getLoc();
2095     Lex.Lex(); // eat the '{'
2096     SmallVector<Init*, 16> Vals;
2097 
2098     if (Lex.getCode() != tgtok::r_brace) {
2099       ParseValueList(Vals, CurRec);
2100       if (Vals.empty()) return nullptr;
2101     }
2102     if (!consume(tgtok::r_brace)) {
2103       TokError("expected '}' at end of bit list value");
2104       return nullptr;
2105     }
2106 
2107     SmallVector<Init *, 16> NewBits;
2108 
2109     // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
2110     // first.  We'll first read everything in to a vector, then we can reverse
2111     // it to get the bits in the correct order for the BitsInit value.
2112     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2113       // FIXME: The following two loops would not be duplicated
2114       //        if the API was a little more orthogonal.
2115 
2116       // bits<n> values are allowed to initialize n bits.
2117       if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
2118         for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
2119           NewBits.push_back(BI->getBit((e - i) - 1));
2120         continue;
2121       }
2122       // bits<n> can also come from variable initializers.
2123       if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
2124         if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
2125           for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
2126             NewBits.push_back(VI->getBit((e - i) - 1));
2127           continue;
2128         }
2129         // Fallthrough to try convert this to a bit.
2130       }
2131       // All other values must be convertible to just a single bit.
2132       Init *Bit = Vals[i]->getCastTo(BitRecTy::get());
2133       if (!Bit) {
2134         Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
2135               ") is not convertable to a bit");
2136         return nullptr;
2137       }
2138       NewBits.push_back(Bit);
2139     }
2140     std::reverse(NewBits.begin(), NewBits.end());
2141     return BitsInit::get(NewBits);
2142   }
2143   case tgtok::l_square: {          // Value ::= '[' ValueList ']'
2144     Lex.Lex(); // eat the '['
2145     SmallVector<Init*, 16> Vals;
2146 
2147     RecTy *DeducedEltTy = nullptr;
2148     ListRecTy *GivenListTy = nullptr;
2149 
2150     if (ItemType) {
2151       ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
2152       if (!ListType) {
2153         TokError(Twine("Encountered a list when expecting a ") +
2154                  ItemType->getAsString());
2155         return nullptr;
2156       }
2157       GivenListTy = ListType;
2158     }
2159 
2160     if (Lex.getCode() != tgtok::r_square) {
2161       ParseValueList(Vals, CurRec, nullptr,
2162                      GivenListTy ? GivenListTy->getElementType() : nullptr);
2163       if (Vals.empty()) return nullptr;
2164     }
2165     if (!consume(tgtok::r_square)) {
2166       TokError("expected ']' at end of list value");
2167       return nullptr;
2168     }
2169 
2170     RecTy *GivenEltTy = nullptr;
2171     if (consume(tgtok::less)) {
2172       // Optional list element type
2173       GivenEltTy = ParseType();
2174       if (!GivenEltTy) {
2175         // Couldn't parse element type
2176         return nullptr;
2177       }
2178 
2179       if (!consume(tgtok::greater)) {
2180         TokError("expected '>' at end of list element type");
2181         return nullptr;
2182       }
2183     }
2184 
2185     // Check elements
2186     RecTy *EltTy = nullptr;
2187     for (Init *V : Vals) {
2188       TypedInit *TArg = dyn_cast<TypedInit>(V);
2189       if (TArg) {
2190         if (EltTy) {
2191           EltTy = resolveTypes(EltTy, TArg->getType());
2192           if (!EltTy) {
2193             TokError("Incompatible types in list elements");
2194             return nullptr;
2195           }
2196         } else {
2197           EltTy = TArg->getType();
2198         }
2199       }
2200     }
2201 
2202     if (GivenEltTy) {
2203       if (EltTy) {
2204         // Verify consistency
2205         if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
2206           TokError("Incompatible types in list elements");
2207           return nullptr;
2208         }
2209       }
2210       EltTy = GivenEltTy;
2211     }
2212 
2213     if (!EltTy) {
2214       if (!ItemType) {
2215         TokError("No type for list");
2216         return nullptr;
2217       }
2218       DeducedEltTy = GivenListTy->getElementType();
2219     } else {
2220       // Make sure the deduced type is compatible with the given type
2221       if (GivenListTy) {
2222         if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
2223           TokError(Twine("Element type mismatch for list: element type '") +
2224                    EltTy->getAsString() + "' not convertible to '" +
2225                    GivenListTy->getElementType()->getAsString());
2226           return nullptr;
2227         }
2228       }
2229       DeducedEltTy = EltTy;
2230     }
2231 
2232     return ListInit::get(Vals, DeducedEltTy);
2233   }
2234   case tgtok::l_paren: {         // Value ::= '(' IDValue DagArgList ')'
2235     Lex.Lex();   // eat the '('
2236     if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast &&
2237         Lex.getCode() != tgtok::question && Lex.getCode() != tgtok::XGetDagOp) {
2238       TokError("expected identifier in dag init");
2239       return nullptr;
2240     }
2241 
2242     Init *Operator = ParseValue(CurRec);
2243     if (!Operator) return nullptr;
2244 
2245     // If the operator name is present, parse it.
2246     StringInit *OperatorName = nullptr;
2247     if (consume(tgtok::colon)) {
2248       if (Lex.getCode() != tgtok::VarName) { // eat the ':'
2249         TokError("expected variable name in dag operator");
2250         return nullptr;
2251       }
2252       OperatorName = StringInit::get(Lex.getCurStrVal());
2253       Lex.Lex();  // eat the VarName.
2254     }
2255 
2256     SmallVector<std::pair<llvm::Init*, StringInit*>, 8> DagArgs;
2257     if (Lex.getCode() != tgtok::r_paren) {
2258       ParseDagArgList(DagArgs, CurRec);
2259       if (DagArgs.empty()) return nullptr;
2260     }
2261 
2262     if (!consume(tgtok::r_paren)) {
2263       TokError("expected ')' in dag init");
2264       return nullptr;
2265     }
2266 
2267     return DagInit::get(Operator, OperatorName, DagArgs);
2268   }
2269 
2270   case tgtok::XHead:
2271   case tgtok::XTail:
2272   case tgtok::XSize:
2273   case tgtok::XEmpty:
2274   case tgtok::XCast:
2275   case tgtok::XGetDagOp: // Value ::= !unop '(' Value ')'
2276   case tgtok::XIsA:
2277   case tgtok::XConcat:
2278   case tgtok::XDag:
2279   case tgtok::XADD:
2280   case tgtok::XSUB:
2281   case tgtok::XMUL:
2282   case tgtok::XNOT:
2283   case tgtok::XAND:
2284   case tgtok::XOR:
2285   case tgtok::XXOR:
2286   case tgtok::XSRA:
2287   case tgtok::XSRL:
2288   case tgtok::XSHL:
2289   case tgtok::XEq:
2290   case tgtok::XNe:
2291   case tgtok::XLe:
2292   case tgtok::XLt:
2293   case tgtok::XGe:
2294   case tgtok::XGt:
2295   case tgtok::XListConcat:
2296   case tgtok::XListSplat:
2297   case tgtok::XStrConcat:
2298   case tgtok::XInterleave:
2299   case tgtok::XSetDagOp: // Value ::= !binop '(' Value ',' Value ')'
2300   case tgtok::XIf:
2301   case tgtok::XCond:
2302   case tgtok::XFoldl:
2303   case tgtok::XForEach:
2304   case tgtok::XFilter:
2305   case tgtok::XSubst:
2306   case tgtok::XSubstr: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
2307     return ParseOperation(CurRec, ItemType);
2308   }
2309   }
2310 
2311   return R;
2312 }
2313 
2314 /// ParseValue - Parse a TableGen value. This returns null on error.
2315 ///
2316 ///   Value       ::= SimpleValue ValueSuffix*
2317 ///   ValueSuffix ::= '{' BitList '}'
2318 ///   ValueSuffix ::= '[' BitList ']'
2319 ///   ValueSuffix ::= '.' ID
2320 ///
2321 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
2322   Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
2323   if (!Result) return nullptr;
2324 
2325   // Parse the suffixes now if present.
2326   while (true) {
2327     switch (Lex.getCode()) {
2328     default: return Result;
2329     case tgtok::l_brace: {
2330       if (Mode == ParseNameMode)
2331         // This is the beginning of the object body.
2332         return Result;
2333 
2334       SMLoc CurlyLoc = Lex.getLoc();
2335       Lex.Lex(); // eat the '{'
2336       SmallVector<unsigned, 16> Ranges;
2337       ParseRangeList(Ranges);
2338       if (Ranges.empty()) return nullptr;
2339 
2340       // Reverse the bitlist.
2341       std::reverse(Ranges.begin(), Ranges.end());
2342       Result = Result->convertInitializerBitRange(Ranges);
2343       if (!Result) {
2344         Error(CurlyLoc, "Invalid bit range for value");
2345         return nullptr;
2346       }
2347 
2348       // Eat the '}'.
2349       if (!consume(tgtok::r_brace)) {
2350         TokError("expected '}' at end of bit range list");
2351         return nullptr;
2352       }
2353       break;
2354     }
2355     case tgtok::l_square: {
2356       SMLoc SquareLoc = Lex.getLoc();
2357       Lex.Lex(); // eat the '['
2358       SmallVector<unsigned, 16> Ranges;
2359       ParseRangeList(Ranges);
2360       if (Ranges.empty()) return nullptr;
2361 
2362       Result = Result->convertInitListSlice(Ranges);
2363       if (!Result) {
2364         Error(SquareLoc, "Invalid range for list slice");
2365         return nullptr;
2366       }
2367 
2368       // Eat the ']'.
2369       if (!consume(tgtok::r_square)) {
2370         TokError("expected ']' at end of list slice");
2371         return nullptr;
2372       }
2373       break;
2374     }
2375     case tgtok::dot: {
2376       if (Lex.Lex() != tgtok::Id) { // eat the .
2377         TokError("expected field identifier after '.'");
2378         return nullptr;
2379       }
2380       StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2381       if (!Result->getFieldType(FieldName)) {
2382         TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
2383                  Result->getAsString() + "'");
2384         return nullptr;
2385       }
2386       Result = FieldInit::get(Result, FieldName)->Fold(CurRec);
2387       Lex.Lex();  // eat field name
2388       break;
2389     }
2390 
2391     case tgtok::paste:
2392       SMLoc PasteLoc = Lex.getLoc();
2393       TypedInit *LHS = dyn_cast<TypedInit>(Result);
2394       if (!LHS) {
2395         Error(PasteLoc, "LHS of paste is not typed!");
2396         return nullptr;
2397       }
2398 
2399       // Check if it's a 'listA # listB'
2400       if (isa<ListRecTy>(LHS->getType())) {
2401         Lex.Lex();  // Eat the '#'.
2402 
2403         assert(Mode == ParseValueMode && "encountered paste of lists in name");
2404 
2405         switch (Lex.getCode()) {
2406         case tgtok::colon:
2407         case tgtok::semi:
2408         case tgtok::l_brace:
2409           Result = LHS; // trailing paste, ignore.
2410           break;
2411         default:
2412           Init *RHSResult = ParseValue(CurRec, ItemType, ParseValueMode);
2413           if (!RHSResult)
2414             return nullptr;
2415           Result = BinOpInit::getListConcat(LHS, RHSResult);
2416           break;
2417         }
2418         break;
2419       }
2420 
2421       // Create a !strconcat() operation, first casting each operand to
2422       // a string if necessary.
2423       if (LHS->getType() != StringRecTy::get()) {
2424         auto CastLHS = dyn_cast<TypedInit>(
2425             UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get())
2426                 ->Fold(CurRec));
2427         if (!CastLHS) {
2428           Error(PasteLoc,
2429                 Twine("can't cast '") + LHS->getAsString() + "' to string");
2430           return nullptr;
2431         }
2432         LHS = CastLHS;
2433       }
2434 
2435       TypedInit *RHS = nullptr;
2436 
2437       Lex.Lex();  // Eat the '#'.
2438       switch (Lex.getCode()) {
2439       case tgtok::colon:
2440       case tgtok::semi:
2441       case tgtok::l_brace:
2442         // These are all of the tokens that can begin an object body.
2443         // Some of these can also begin values but we disallow those cases
2444         // because they are unlikely to be useful.
2445 
2446         // Trailing paste, concat with an empty string.
2447         RHS = StringInit::get("");
2448         break;
2449 
2450       default:
2451         Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode);
2452         if (!RHSResult)
2453           return nullptr;
2454         RHS = dyn_cast<TypedInit>(RHSResult);
2455         if (!RHS) {
2456           Error(PasteLoc, "RHS of paste is not typed!");
2457           return nullptr;
2458         }
2459 
2460         if (RHS->getType() != StringRecTy::get()) {
2461           auto CastRHS = dyn_cast<TypedInit>(
2462               UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get())
2463                   ->Fold(CurRec));
2464           if (!CastRHS) {
2465             Error(PasteLoc,
2466                   Twine("can't cast '") + RHS->getAsString() + "' to string");
2467             return nullptr;
2468           }
2469           RHS = CastRHS;
2470         }
2471 
2472         break;
2473       }
2474 
2475       Result = BinOpInit::getStrConcat(LHS, RHS);
2476       break;
2477     }
2478   }
2479 }
2480 
2481 /// ParseDagArgList - Parse the argument list for a dag literal expression.
2482 ///
2483 ///    DagArg     ::= Value (':' VARNAME)?
2484 ///    DagArg     ::= VARNAME
2485 ///    DagArgList ::= DagArg
2486 ///    DagArgList ::= DagArgList ',' DagArg
2487 void TGParser::ParseDagArgList(
2488     SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result,
2489     Record *CurRec) {
2490 
2491   while (true) {
2492     // DagArg ::= VARNAME
2493     if (Lex.getCode() == tgtok::VarName) {
2494       // A missing value is treated like '?'.
2495       StringInit *VarName = StringInit::get(Lex.getCurStrVal());
2496       Result.emplace_back(UnsetInit::get(), VarName);
2497       Lex.Lex();
2498     } else {
2499       // DagArg ::= Value (':' VARNAME)?
2500       Init *Val = ParseValue(CurRec);
2501       if (!Val) {
2502         Result.clear();
2503         return;
2504       }
2505 
2506       // If the variable name is present, add it.
2507       StringInit *VarName = nullptr;
2508       if (Lex.getCode() == tgtok::colon) {
2509         if (Lex.Lex() != tgtok::VarName) { // eat the ':'
2510           TokError("expected variable name in dag literal");
2511           Result.clear();
2512           return;
2513         }
2514         VarName = StringInit::get(Lex.getCurStrVal());
2515         Lex.Lex();  // eat the VarName.
2516       }
2517 
2518       Result.push_back(std::make_pair(Val, VarName));
2519     }
2520     if (!consume(tgtok::comma))
2521       break;
2522   }
2523 }
2524 
2525 /// ParseValueList - Parse a comma separated list of values, returning them as a
2526 /// vector.  Note that this always expects to be able to parse at least one
2527 /// value.  It returns an empty list if this is not possible.
2528 ///
2529 ///   ValueList ::= Value (',' Value)
2530 ///
2531 void TGParser::ParseValueList(SmallVectorImpl<Init*> &Result, Record *CurRec,
2532                               Record *ArgsRec, RecTy *EltTy) {
2533   RecTy *ItemType = EltTy;
2534   unsigned int ArgN = 0;
2535   if (ArgsRec && !EltTy) {
2536     ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2537     if (TArgs.empty()) {
2538       TokError("template argument provided to non-template class");
2539       Result.clear();
2540       return;
2541     }
2542     const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2543     if (!RV) {
2544       errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
2545         << ")\n";
2546     }
2547     assert(RV && "Template argument record not found??");
2548     ItemType = RV->getType();
2549     ++ArgN;
2550   }
2551   Result.push_back(ParseValue(CurRec, ItemType));
2552   if (!Result.back()) {
2553     Result.clear();
2554     return;
2555   }
2556 
2557   while (consume(tgtok::comma)) {
2558     // ignore trailing comma for lists
2559     if (Lex.getCode() == tgtok::r_square)
2560       return;
2561 
2562     if (ArgsRec && !EltTy) {
2563       ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2564       if (ArgN >= TArgs.size()) {
2565         TokError("too many template arguments");
2566         Result.clear();
2567         return;
2568       }
2569       const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2570       assert(RV && "Template argument record not found??");
2571       ItemType = RV->getType();
2572       ++ArgN;
2573     }
2574     Result.push_back(ParseValue(CurRec, ItemType));
2575     if (!Result.back()) {
2576       Result.clear();
2577       return;
2578     }
2579   }
2580 }
2581 
2582 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
2583 /// empty string on error.  This can happen in a number of different context's,
2584 /// including within a def or in the template args for a def (which which case
2585 /// CurRec will be non-null) and within the template args for a multiclass (in
2586 /// which case CurRec will be null, but CurMultiClass will be set).  This can
2587 /// also happen within a def that is within a multiclass, which will set both
2588 /// CurRec and CurMultiClass.
2589 ///
2590 ///  Declaration ::= FIELD? Type ID ('=' Value)?
2591 ///
2592 Init *TGParser::ParseDeclaration(Record *CurRec,
2593                                        bool ParsingTemplateArgs) {
2594   // Read the field prefix if present.
2595   bool HasField = consume(tgtok::Field);
2596 
2597   RecTy *Type = ParseType();
2598   if (!Type) return nullptr;
2599 
2600   if (Lex.getCode() != tgtok::Id) {
2601     TokError("Expected identifier in declaration");
2602     return nullptr;
2603   }
2604 
2605   std::string Str = Lex.getCurStrVal();
2606   if (Str == "NAME") {
2607     TokError("'" + Str + "' is a reserved variable name");
2608     return nullptr;
2609   }
2610 
2611   SMLoc IdLoc = Lex.getLoc();
2612   Init *DeclName = StringInit::get(Str);
2613   Lex.Lex();
2614 
2615   if (ParsingTemplateArgs) {
2616     if (CurRec)
2617       DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
2618     else
2619       assert(CurMultiClass);
2620     if (CurMultiClass)
2621       DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
2622                              "::");
2623   }
2624 
2625   // Add the field to the record.
2626   if (AddValue(CurRec, IdLoc, RecordVal(DeclName, IdLoc, Type,
2627                                         HasField ? RecordVal::FK_NonconcreteOK
2628                                                  : RecordVal::FK_Normal)))
2629     return nullptr;
2630 
2631   // If a value is present, parse it.
2632   if (consume(tgtok::equal)) {
2633     SMLoc ValLoc = Lex.getLoc();
2634     Init *Val = ParseValue(CurRec, Type);
2635     if (!Val ||
2636         SetValue(CurRec, ValLoc, DeclName, None, Val))
2637       // Return the name, even if an error is thrown.  This is so that we can
2638       // continue to make some progress, even without the value having been
2639       // initialized.
2640       return DeclName;
2641   }
2642 
2643   return DeclName;
2644 }
2645 
2646 /// ParseForeachDeclaration - Read a foreach declaration, returning
2647 /// the name of the declared object or a NULL Init on error.  Return
2648 /// the name of the parsed initializer list through ForeachListName.
2649 ///
2650 ///  ForeachDeclaration ::= ID '=' '{' RangeList '}'
2651 ///  ForeachDeclaration ::= ID '=' RangePiece
2652 ///  ForeachDeclaration ::= ID '=' Value
2653 ///
2654 VarInit *TGParser::ParseForeachDeclaration(Init *&ForeachListValue) {
2655   if (Lex.getCode() != tgtok::Id) {
2656     TokError("Expected identifier in foreach declaration");
2657     return nullptr;
2658   }
2659 
2660   Init *DeclName = StringInit::get(Lex.getCurStrVal());
2661   Lex.Lex();
2662 
2663   // If a value is present, parse it.
2664   if (!consume(tgtok::equal)) {
2665     TokError("Expected '=' in foreach declaration");
2666     return nullptr;
2667   }
2668 
2669   RecTy *IterType = nullptr;
2670   SmallVector<unsigned, 16> Ranges;
2671 
2672   switch (Lex.getCode()) {
2673   case tgtok::l_brace: { // '{' RangeList '}'
2674     Lex.Lex(); // eat the '{'
2675     ParseRangeList(Ranges);
2676     if (!consume(tgtok::r_brace)) {
2677       TokError("expected '}' at end of bit range list");
2678       return nullptr;
2679     }
2680     break;
2681   }
2682 
2683   default: {
2684     SMLoc ValueLoc = Lex.getLoc();
2685     Init *I = ParseValue(nullptr);
2686     if (!I)
2687       return nullptr;
2688 
2689     TypedInit *TI = dyn_cast<TypedInit>(I);
2690     if (TI && isa<ListRecTy>(TI->getType())) {
2691       ForeachListValue = I;
2692       IterType = cast<ListRecTy>(TI->getType())->getElementType();
2693       break;
2694     }
2695 
2696     if (TI) {
2697       if (ParseRangePiece(Ranges, TI))
2698         return nullptr;
2699       break;
2700     }
2701 
2702     std::string Type;
2703     if (TI)
2704       Type = (Twine("' of type '") + TI->getType()->getAsString()).str();
2705     Error(ValueLoc, "expected a list, got '" + I->getAsString() + Type + "'");
2706     if (CurMultiClass) {
2707       PrintNote({}, "references to multiclass template arguments cannot be "
2708                 "resolved at this time");
2709     }
2710     return nullptr;
2711   }
2712   }
2713 
2714 
2715   if (!Ranges.empty()) {
2716     assert(!IterType && "Type already initialized?");
2717     IterType = IntRecTy::get();
2718     std::vector<Init*> Values;
2719     for (unsigned R : Ranges)
2720       Values.push_back(IntInit::get(R));
2721     ForeachListValue = ListInit::get(Values, IterType);
2722   }
2723 
2724   if (!IterType)
2725     return nullptr;
2726 
2727   return VarInit::get(DeclName, IterType);
2728 }
2729 
2730 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
2731 /// sequence of template-declarations in <>'s.  If CurRec is non-null, these are
2732 /// template args for a def, which may or may not be in a multiclass.  If null,
2733 /// these are the template args for a multiclass.
2734 ///
2735 ///    TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
2736 ///
2737 bool TGParser::ParseTemplateArgList(Record *CurRec) {
2738   assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
2739   Lex.Lex(); // eat the '<'
2740 
2741   Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
2742 
2743   // Read the first declaration.
2744   Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2745   if (!TemplArg)
2746     return true;
2747 
2748   TheRecToAddTo->addTemplateArg(TemplArg);
2749 
2750   while (consume(tgtok::comma)) {
2751     // Read the following declarations.
2752     SMLoc Loc = Lex.getLoc();
2753     TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2754     if (!TemplArg)
2755       return true;
2756 
2757     if (TheRecToAddTo->isTemplateArg(TemplArg))
2758       return Error(Loc, "template argument with the same name has already been "
2759                         "defined");
2760 
2761     TheRecToAddTo->addTemplateArg(TemplArg);
2762   }
2763 
2764   if (!consume(tgtok::greater))
2765     return TokError("expected '>' at end of template argument list");
2766   return false;
2767 }
2768 
2769 /// ParseBodyItem - Parse a single item within the body of a def or class.
2770 ///
2771 ///   BodyItem ::= Declaration ';'
2772 ///   BodyItem ::= LET ID OptionalBitList '=' Value ';'
2773 ///   BodyItem ::= Defvar
2774 ///   BodyItem ::= Assert
2775 bool TGParser::ParseBodyItem(Record *CurRec) {
2776   if (Lex.getCode() == tgtok::Assert)
2777     return ParseAssert(nullptr, CurRec);
2778 
2779   if (Lex.getCode() == tgtok::Defvar)
2780     return ParseDefvar();
2781 
2782   if (Lex.getCode() != tgtok::Let) {
2783     if (!ParseDeclaration(CurRec, false))
2784       return true;
2785 
2786     if (!consume(tgtok::semi))
2787       return TokError("expected ';' after declaration");
2788     return false;
2789   }
2790 
2791   // LET ID OptionalRangeList '=' Value ';'
2792   if (Lex.Lex() != tgtok::Id)
2793     return TokError("expected field identifier after let");
2794 
2795   SMLoc IdLoc = Lex.getLoc();
2796   StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2797   Lex.Lex();  // eat the field name.
2798 
2799   SmallVector<unsigned, 16> BitList;
2800   if (ParseOptionalBitList(BitList))
2801     return true;
2802   std::reverse(BitList.begin(), BitList.end());
2803 
2804   if (!consume(tgtok::equal))
2805     return TokError("expected '=' in let expression");
2806 
2807   RecordVal *Field = CurRec->getValue(FieldName);
2808   if (!Field)
2809     return TokError("Value '" + FieldName->getValue() + "' unknown!");
2810 
2811   RecTy *Type = Field->getType();
2812   if (!BitList.empty() && isa<BitsRecTy>(Type)) {
2813     // When assigning to a subset of a 'bits' object, expect the RHS to have
2814     // the type of that subset instead of the type of the whole object.
2815     Type = BitsRecTy::get(BitList.size());
2816   }
2817 
2818   Init *Val = ParseValue(CurRec, Type);
2819   if (!Val) return true;
2820 
2821   if (!consume(tgtok::semi))
2822     return TokError("expected ';' after let expression");
2823 
2824   return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
2825 }
2826 
2827 /// ParseBody - Read the body of a class or def.  Return true on error, false on
2828 /// success.
2829 ///
2830 ///   Body     ::= ';'
2831 ///   Body     ::= '{' BodyList '}'
2832 ///   BodyList BodyItem*
2833 ///
2834 bool TGParser::ParseBody(Record *CurRec) {
2835   // If this is a null definition, just eat the semi and return.
2836   if (consume(tgtok::semi))
2837     return false;
2838 
2839   if (!consume(tgtok::l_brace))
2840     return TokError("Expected '{' to start body or ';' for declaration only");
2841 
2842   // An object body introduces a new scope for local variables.
2843   TGLocalVarScope *BodyScope = PushLocalScope();
2844 
2845   while (Lex.getCode() != tgtok::r_brace)
2846     if (ParseBodyItem(CurRec))
2847       return true;
2848 
2849   PopLocalScope(BodyScope);
2850 
2851   // Eat the '}'.
2852   Lex.Lex();
2853 
2854   // If we have a semicolon, print a gentle error.
2855   SMLoc SemiLoc = Lex.getLoc();
2856   if (consume(tgtok::semi)) {
2857     PrintError(SemiLoc, "A class or def body should not end with a semicolon");
2858     PrintNote("Semicolon ignored; remove to eliminate this error");
2859   }
2860 
2861   return false;
2862 }
2863 
2864 /// Apply the current let bindings to \a CurRec.
2865 /// \returns true on error, false otherwise.
2866 bool TGParser::ApplyLetStack(Record *CurRec) {
2867   for (SmallVectorImpl<LetRecord> &LetInfo : LetStack)
2868     for (LetRecord &LR : LetInfo)
2869       if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
2870         return true;
2871   return false;
2872 }
2873 
2874 bool TGParser::ApplyLetStack(RecordsEntry &Entry) {
2875   if (Entry.Rec)
2876     return ApplyLetStack(Entry.Rec.get());
2877 
2878   for (auto &E : Entry.Loop->Entries) {
2879     if (ApplyLetStack(E))
2880       return true;
2881   }
2882 
2883   return false;
2884 }
2885 
2886 /// ParseObjectBody - Parse the body of a def or class.  This consists of an
2887 /// optional ClassList followed by a Body.  CurRec is the current def or class
2888 /// that is being parsed.
2889 ///
2890 ///   ObjectBody      ::= BaseClassList Body
2891 ///   BaseClassList   ::= /*empty*/
2892 ///   BaseClassList   ::= ':' BaseClassListNE
2893 ///   BaseClassListNE ::= SubClassRef (',' SubClassRef)*
2894 ///
2895 bool TGParser::ParseObjectBody(Record *CurRec) {
2896   // If there is a baseclass list, read it.
2897   if (consume(tgtok::colon)) {
2898 
2899     // Read all of the subclasses.
2900     SubClassReference SubClass = ParseSubClassReference(CurRec, false);
2901     while (true) {
2902       // Check for error.
2903       if (!SubClass.Rec) return true;
2904 
2905       // Add it.
2906       if (AddSubClass(CurRec, SubClass))
2907         return true;
2908 
2909       if (!consume(tgtok::comma))
2910         break;
2911       SubClass = ParseSubClassReference(CurRec, false);
2912     }
2913   }
2914 
2915   if (ApplyLetStack(CurRec))
2916     return true;
2917 
2918   return ParseBody(CurRec);
2919 }
2920 
2921 /// ParseDef - Parse and return a top level or multiclass def, return the record
2922 /// corresponding to it.  This returns null on error.
2923 ///
2924 ///   DefInst ::= DEF ObjectName ObjectBody
2925 ///
2926 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
2927   SMLoc DefLoc = Lex.getLoc();
2928   assert(Lex.getCode() == tgtok::Def && "Unknown tok");
2929   Lex.Lex();  // Eat the 'def' token.
2930 
2931   // Parse ObjectName and make a record for it.
2932   std::unique_ptr<Record> CurRec;
2933   Init *Name = ParseObjectName(CurMultiClass);
2934   if (!Name)
2935     return true;
2936 
2937   if (isa<UnsetInit>(Name))
2938     CurRec = std::make_unique<Record>(Records.getNewAnonymousName(), DefLoc, Records,
2939                                  /*Anonymous=*/true);
2940   else
2941     CurRec = std::make_unique<Record>(Name, DefLoc, Records);
2942 
2943   if (ParseObjectBody(CurRec.get()))
2944     return true;
2945 
2946   return addEntry(std::move(CurRec));
2947 }
2948 
2949 /// ParseDefset - Parse a defset statement.
2950 ///
2951 ///   Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
2952 ///
2953 bool TGParser::ParseDefset() {
2954   assert(Lex.getCode() == tgtok::Defset);
2955   Lex.Lex(); // Eat the 'defset' token
2956 
2957   DefsetRecord Defset;
2958   Defset.Loc = Lex.getLoc();
2959   RecTy *Type = ParseType();
2960   if (!Type)
2961     return true;
2962   if (!isa<ListRecTy>(Type))
2963     return Error(Defset.Loc, "expected list type");
2964   Defset.EltTy = cast<ListRecTy>(Type)->getElementType();
2965 
2966   if (Lex.getCode() != tgtok::Id)
2967     return TokError("expected identifier");
2968   StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
2969   if (Records.getGlobal(DeclName->getValue()))
2970     return TokError("def or global variable of this name already exists");
2971 
2972   if (Lex.Lex() != tgtok::equal) // Eat the identifier
2973     return TokError("expected '='");
2974   if (Lex.Lex() != tgtok::l_brace) // Eat the '='
2975     return TokError("expected '{'");
2976   SMLoc BraceLoc = Lex.getLoc();
2977   Lex.Lex(); // Eat the '{'
2978 
2979   Defsets.push_back(&Defset);
2980   bool Err = ParseObjectList(nullptr);
2981   Defsets.pop_back();
2982   if (Err)
2983     return true;
2984 
2985   if (!consume(tgtok::r_brace)) {
2986     TokError("expected '}' at end of defset");
2987     return Error(BraceLoc, "to match this '{'");
2988   }
2989 
2990   Records.addExtraGlobal(DeclName->getValue(),
2991                          ListInit::get(Defset.Elements, Defset.EltTy));
2992   return false;
2993 }
2994 
2995 /// ParseDefvar - Parse a defvar statement.
2996 ///
2997 ///   Defvar ::= DEFVAR Id '=' Value ';'
2998 ///
2999 bool TGParser::ParseDefvar() {
3000   assert(Lex.getCode() == tgtok::Defvar);
3001   Lex.Lex(); // Eat the 'defvar' token
3002 
3003   if (Lex.getCode() != tgtok::Id)
3004     return TokError("expected identifier");
3005   StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
3006   if (CurLocalScope) {
3007     if (CurLocalScope->varAlreadyDefined(DeclName->getValue()))
3008       return TokError("local variable of this name already exists");
3009   } else {
3010     if (Records.getGlobal(DeclName->getValue()))
3011       return TokError("def or global variable of this name already exists");
3012   }
3013 
3014   Lex.Lex();
3015   if (!consume(tgtok::equal))
3016     return TokError("expected '='");
3017 
3018   Init *Value = ParseValue(nullptr);
3019   if (!Value)
3020     return true;
3021 
3022   if (!consume(tgtok::semi))
3023     return TokError("expected ';'");
3024 
3025   if (CurLocalScope)
3026     CurLocalScope->addVar(DeclName->getValue(), Value);
3027   else
3028     Records.addExtraGlobal(DeclName->getValue(), Value);
3029 
3030   return false;
3031 }
3032 
3033 /// ParseForeach - Parse a for statement.  Return the record corresponding
3034 /// to it.  This returns true on error.
3035 ///
3036 ///   Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
3037 ///   Foreach ::= FOREACH Declaration IN Object
3038 ///
3039 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
3040   SMLoc Loc = Lex.getLoc();
3041   assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
3042   Lex.Lex();  // Eat the 'for' token.
3043 
3044   // Make a temporary object to record items associated with the for
3045   // loop.
3046   Init *ListValue = nullptr;
3047   VarInit *IterName = ParseForeachDeclaration(ListValue);
3048   if (!IterName)
3049     return TokError("expected declaration in for");
3050 
3051   if (!consume(tgtok::In))
3052     return TokError("Unknown tok");
3053 
3054   // Create a loop object and remember it.
3055   Loops.push_back(std::make_unique<ForeachLoop>(Loc, IterName, ListValue));
3056 
3057   // A foreach loop introduces a new scope for local variables.
3058   TGLocalVarScope *ForeachScope = PushLocalScope();
3059 
3060   if (Lex.getCode() != tgtok::l_brace) {
3061     // FOREACH Declaration IN Object
3062     if (ParseObject(CurMultiClass))
3063       return true;
3064   } else {
3065     SMLoc BraceLoc = Lex.getLoc();
3066     // Otherwise, this is a group foreach.
3067     Lex.Lex();  // eat the '{'.
3068 
3069     // Parse the object list.
3070     if (ParseObjectList(CurMultiClass))
3071       return true;
3072 
3073     if (!consume(tgtok::r_brace)) {
3074       TokError("expected '}' at end of foreach command");
3075       return Error(BraceLoc, "to match this '{'");
3076     }
3077   }
3078 
3079   PopLocalScope(ForeachScope);
3080 
3081   // Resolve the loop or store it for later resolution.
3082   std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
3083   Loops.pop_back();
3084 
3085   return addEntry(std::move(Loop));
3086 }
3087 
3088 /// ParseIf - Parse an if statement.
3089 ///
3090 ///   If ::= IF Value THEN IfBody
3091 ///   If ::= IF Value THEN IfBody ELSE IfBody
3092 ///
3093 bool TGParser::ParseIf(MultiClass *CurMultiClass) {
3094   SMLoc Loc = Lex.getLoc();
3095   assert(Lex.getCode() == tgtok::If && "Unknown tok");
3096   Lex.Lex(); // Eat the 'if' token.
3097 
3098   // Make a temporary object to record items associated with the for
3099   // loop.
3100   Init *Condition = ParseValue(nullptr);
3101   if (!Condition)
3102     return true;
3103 
3104   if (!consume(tgtok::Then))
3105     return TokError("Unknown tok");
3106 
3107   // We have to be able to save if statements to execute later, and they have
3108   // to live on the same stack as foreach loops. The simplest implementation
3109   // technique is to convert each 'then' or 'else' clause *into* a foreach
3110   // loop, over a list of length 0 or 1 depending on the condition, and with no
3111   // iteration variable being assigned.
3112 
3113   ListInit *EmptyList = ListInit::get({}, BitRecTy::get());
3114   ListInit *SingletonList = ListInit::get({BitInit::get(1)}, BitRecTy::get());
3115   RecTy *BitListTy = ListRecTy::get(BitRecTy::get());
3116 
3117   // The foreach containing the then-clause selects SingletonList if
3118   // the condition is true.
3119   Init *ThenClauseList =
3120       TernOpInit::get(TernOpInit::IF, Condition, SingletonList, EmptyList,
3121                       BitListTy)
3122           ->Fold(nullptr);
3123   Loops.push_back(std::make_unique<ForeachLoop>(Loc, nullptr, ThenClauseList));
3124 
3125   if (ParseIfBody(CurMultiClass, "then"))
3126     return true;
3127 
3128   std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
3129   Loops.pop_back();
3130 
3131   if (addEntry(std::move(Loop)))
3132     return true;
3133 
3134   // Now look for an optional else clause. The if-else syntax has the usual
3135   // dangling-else ambiguity, and by greedily matching an else here if we can,
3136   // we implement the usual resolution of pairing with the innermost unmatched
3137   // if.
3138   if (consume(tgtok::ElseKW)) {
3139     // The foreach containing the else-clause uses the same pair of lists as
3140     // above, but this time, selects SingletonList if the condition is *false*.
3141     Init *ElseClauseList =
3142         TernOpInit::get(TernOpInit::IF, Condition, EmptyList, SingletonList,
3143                         BitListTy)
3144             ->Fold(nullptr);
3145     Loops.push_back(
3146         std::make_unique<ForeachLoop>(Loc, nullptr, ElseClauseList));
3147 
3148     if (ParseIfBody(CurMultiClass, "else"))
3149       return true;
3150 
3151     Loop = std::move(Loops.back());
3152     Loops.pop_back();
3153 
3154     if (addEntry(std::move(Loop)))
3155       return true;
3156   }
3157 
3158   return false;
3159 }
3160 
3161 /// ParseIfBody - Parse the then-clause or else-clause of an if statement.
3162 ///
3163 ///   IfBody ::= Object
3164 ///   IfBody ::= '{' ObjectList '}'
3165 ///
3166 bool TGParser::ParseIfBody(MultiClass *CurMultiClass, StringRef Kind) {
3167   TGLocalVarScope *BodyScope = PushLocalScope();
3168 
3169   if (Lex.getCode() != tgtok::l_brace) {
3170     // A single object.
3171     if (ParseObject(CurMultiClass))
3172       return true;
3173   } else {
3174     SMLoc BraceLoc = Lex.getLoc();
3175     // A braced block.
3176     Lex.Lex(); // eat the '{'.
3177 
3178     // Parse the object list.
3179     if (ParseObjectList(CurMultiClass))
3180       return true;
3181 
3182     if (!consume(tgtok::r_brace)) {
3183       TokError("expected '}' at end of '" + Kind + "' clause");
3184       return Error(BraceLoc, "to match this '{'");
3185     }
3186   }
3187 
3188   PopLocalScope(BodyScope);
3189   return false;
3190 }
3191 
3192 /// ParseAssert - Parse an assert statement.
3193 ///
3194 ///   Assert ::= ASSERT condition , message ;
3195 bool TGParser::ParseAssert(MultiClass *CurMultiClass, Record *CurRec) {
3196   assert(Lex.getCode() == tgtok::Assert && "Unknown tok");
3197   Lex.Lex(); // Eat the 'assert' token.
3198 
3199   SMLoc ConditionLoc = Lex.getLoc();
3200   Init *Condition = ParseValue(CurRec);
3201   if (!Condition)
3202     return true;
3203 
3204   if (!consume(tgtok::comma)) {
3205     TokError("expected ',' in assert statement");
3206     return true;
3207   }
3208 
3209   Init *Message = ParseValue(CurRec);
3210   if (!Message)
3211     return true;
3212 
3213   if (!consume(tgtok::semi))
3214     return TokError("expected ';'");
3215 
3216   if (CurMultiClass) {
3217     assert(false && "assert in multiclass not yet supported");
3218   } else if (CurRec) {
3219     CurRec->addAssertion(ConditionLoc, Condition, Message);
3220   } else { // at top level
3221     CheckAssert(ConditionLoc, Condition, Message);
3222   }
3223 
3224   return false;
3225 }
3226 
3227 /// ParseClass - Parse a tblgen class definition.
3228 ///
3229 ///   ClassInst ::= CLASS ID TemplateArgList? ObjectBody
3230 ///
3231 bool TGParser::ParseClass() {
3232   assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
3233   Lex.Lex();
3234 
3235   if (Lex.getCode() != tgtok::Id)
3236     return TokError("expected class name after 'class' keyword");
3237 
3238   Record *CurRec = Records.getClass(Lex.getCurStrVal());
3239   if (CurRec) {
3240     // If the body was previously defined, this is an error.
3241     if (!CurRec->getValues().empty() ||
3242         !CurRec->getSuperClasses().empty() ||
3243         !CurRec->getTemplateArgs().empty())
3244       return TokError("Class '" + CurRec->getNameInitAsString() +
3245                       "' already defined");
3246   } else {
3247     // If this is the first reference to this class, create and add it.
3248     auto NewRec =
3249         std::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records,
3250                                   /*Class=*/true);
3251     CurRec = NewRec.get();
3252     Records.addClass(std::move(NewRec));
3253   }
3254   Lex.Lex(); // eat the name.
3255 
3256   // If there are template args, parse them.
3257   if (Lex.getCode() == tgtok::less)
3258     if (ParseTemplateArgList(CurRec))
3259       return true;
3260 
3261   return ParseObjectBody(CurRec);
3262 }
3263 
3264 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
3265 /// of LetRecords.
3266 ///
3267 ///   LetList ::= LetItem (',' LetItem)*
3268 ///   LetItem ::= ID OptionalRangeList '=' Value
3269 ///
3270 void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) {
3271   do {
3272     if (Lex.getCode() != tgtok::Id) {
3273       TokError("expected identifier in let definition");
3274       Result.clear();
3275       return;
3276     }
3277 
3278     StringInit *Name = StringInit::get(Lex.getCurStrVal());
3279     SMLoc NameLoc = Lex.getLoc();
3280     Lex.Lex();  // Eat the identifier.
3281 
3282     // Check for an optional RangeList.
3283     SmallVector<unsigned, 16> Bits;
3284     if (ParseOptionalRangeList(Bits)) {
3285       Result.clear();
3286       return;
3287     }
3288     std::reverse(Bits.begin(), Bits.end());
3289 
3290     if (!consume(tgtok::equal)) {
3291       TokError("expected '=' in let expression");
3292       Result.clear();
3293       return;
3294     }
3295 
3296     Init *Val = ParseValue(nullptr);
3297     if (!Val) {
3298       Result.clear();
3299       return;
3300     }
3301 
3302     // Now that we have everything, add the record.
3303     Result.emplace_back(Name, Bits, Val, NameLoc);
3304   } while (consume(tgtok::comma));
3305 }
3306 
3307 /// ParseTopLevelLet - Parse a 'let' at top level.  This can be a couple of
3308 /// different related productions. This works inside multiclasses too.
3309 ///
3310 ///   Object ::= LET LetList IN '{' ObjectList '}'
3311 ///   Object ::= LET LetList IN Object
3312 ///
3313 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
3314   assert(Lex.getCode() == tgtok::Let && "Unexpected token");
3315   Lex.Lex();
3316 
3317   // Add this entry to the let stack.
3318   SmallVector<LetRecord, 8> LetInfo;
3319   ParseLetList(LetInfo);
3320   if (LetInfo.empty()) return true;
3321   LetStack.push_back(std::move(LetInfo));
3322 
3323   if (!consume(tgtok::In))
3324     return TokError("expected 'in' at end of top-level 'let'");
3325 
3326   TGLocalVarScope *LetScope = PushLocalScope();
3327 
3328   // If this is a scalar let, just handle it now
3329   if (Lex.getCode() != tgtok::l_brace) {
3330     // LET LetList IN Object
3331     if (ParseObject(CurMultiClass))
3332       return true;
3333   } else {   // Object ::= LETCommand '{' ObjectList '}'
3334     SMLoc BraceLoc = Lex.getLoc();
3335     // Otherwise, this is a group let.
3336     Lex.Lex();  // eat the '{'.
3337 
3338     // Parse the object list.
3339     if (ParseObjectList(CurMultiClass))
3340       return true;
3341 
3342     if (!consume(tgtok::r_brace)) {
3343       TokError("expected '}' at end of top level let command");
3344       return Error(BraceLoc, "to match this '{'");
3345     }
3346   }
3347 
3348   PopLocalScope(LetScope);
3349 
3350   // Outside this let scope, this let block is not active.
3351   LetStack.pop_back();
3352   return false;
3353 }
3354 
3355 /// ParseMultiClass - Parse a multiclass definition.
3356 ///
3357 ///  MultiClassInst ::= MULTICLASS ID TemplateArgList?
3358 ///                     ':' BaseMultiClassList '{' MultiClassObject+ '}'
3359 ///  MultiClassObject ::= DefInst
3360 ///  MultiClassObject ::= MultiClassInst
3361 ///  MultiClassObject ::= DefMInst
3362 ///  MultiClassObject ::= LETCommand '{' ObjectList '}'
3363 ///  MultiClassObject ::= LETCommand Object
3364 ///
3365 bool TGParser::ParseMultiClass() {
3366   assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
3367   Lex.Lex();  // Eat the multiclass token.
3368 
3369   if (Lex.getCode() != tgtok::Id)
3370     return TokError("expected identifier after multiclass for name");
3371   std::string Name = Lex.getCurStrVal();
3372 
3373   auto Result =
3374     MultiClasses.insert(std::make_pair(Name,
3375                     std::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
3376 
3377   if (!Result.second)
3378     return TokError("multiclass '" + Name + "' already defined");
3379 
3380   CurMultiClass = Result.first->second.get();
3381   Lex.Lex();  // Eat the identifier.
3382 
3383   // If there are template args, parse them.
3384   if (Lex.getCode() == tgtok::less)
3385     if (ParseTemplateArgList(nullptr))
3386       return true;
3387 
3388   bool inherits = false;
3389 
3390   // If there are submulticlasses, parse them.
3391   if (consume(tgtok::colon)) {
3392     inherits = true;
3393 
3394     // Read all of the submulticlasses.
3395     SubMultiClassReference SubMultiClass =
3396       ParseSubMultiClassReference(CurMultiClass);
3397     while (true) {
3398       // Check for error.
3399       if (!SubMultiClass.MC) return true;
3400 
3401       // Add it.
3402       if (AddSubMultiClass(CurMultiClass, SubMultiClass))
3403         return true;
3404 
3405       if (!consume(tgtok::comma))
3406         break;
3407       SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
3408     }
3409   }
3410 
3411   if (Lex.getCode() != tgtok::l_brace) {
3412     if (!inherits)
3413       return TokError("expected '{' in multiclass definition");
3414     if (!consume(tgtok::semi))
3415       return TokError("expected ';' in multiclass definition");
3416   } else {
3417     if (Lex.Lex() == tgtok::r_brace)  // eat the '{'.
3418       return TokError("multiclass must contain at least one def");
3419 
3420     // A multiclass body introduces a new scope for local variables.
3421     TGLocalVarScope *MulticlassScope = PushLocalScope();
3422 
3423     while (Lex.getCode() != tgtok::r_brace) {
3424       switch (Lex.getCode()) {
3425       default:
3426         return TokError("expected 'assert', 'def', 'defm', 'defvar', "
3427                         "'foreach', 'if', or 'let' in multiclass body");
3428       case tgtok::Assert:
3429         return TokError("an assert statement in a multiclass is not yet supported");
3430 
3431       case tgtok::Def:
3432       case tgtok::Defm:
3433       case tgtok::Defvar:
3434       case tgtok::Foreach:
3435       case tgtok::If:
3436       case tgtok::Let:
3437         if (ParseObject(CurMultiClass))
3438           return true;
3439         break;
3440       }
3441     }
3442     Lex.Lex();  // eat the '}'.
3443 
3444     // If we have a semicolon, print a gentle error.
3445     SMLoc SemiLoc = Lex.getLoc();
3446     if (consume(tgtok::semi)) {
3447       PrintError(SemiLoc, "A multiclass body should not end with a semicolon");
3448       PrintNote("Semicolon ignored; remove to eliminate this error");
3449     }
3450 
3451     PopLocalScope(MulticlassScope);
3452   }
3453 
3454   CurMultiClass = nullptr;
3455   return false;
3456 }
3457 
3458 /// ParseDefm - Parse the instantiation of a multiclass.
3459 ///
3460 ///   DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
3461 ///
3462 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
3463   assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
3464   Lex.Lex(); // eat the defm
3465 
3466   Init *DefmName = ParseObjectName(CurMultiClass);
3467   if (!DefmName)
3468     return true;
3469   if (isa<UnsetInit>(DefmName)) {
3470     DefmName = Records.getNewAnonymousName();
3471     if (CurMultiClass)
3472       DefmName = BinOpInit::getStrConcat(
3473           VarInit::get(QualifiedNameOfImplicitName(CurMultiClass),
3474                        StringRecTy::get()),
3475           DefmName);
3476   }
3477 
3478   if (Lex.getCode() != tgtok::colon)
3479     return TokError("expected ':' after defm identifier");
3480 
3481   // Keep track of the new generated record definitions.
3482   std::vector<RecordsEntry> NewEntries;
3483 
3484   // This record also inherits from a regular class (non-multiclass)?
3485   bool InheritFromClass = false;
3486 
3487   // eat the colon.
3488   Lex.Lex();
3489 
3490   SMLoc SubClassLoc = Lex.getLoc();
3491   SubClassReference Ref = ParseSubClassReference(nullptr, true);
3492 
3493   while (true) {
3494     if (!Ref.Rec) return true;
3495 
3496     // To instantiate a multiclass, we need to first get the multiclass, then
3497     // instantiate each def contained in the multiclass with the SubClassRef
3498     // template parameters.
3499     MultiClass *MC = MultiClasses[std::string(Ref.Rec->getName())].get();
3500     assert(MC && "Didn't lookup multiclass correctly?");
3501     ArrayRef<Init*> TemplateVals = Ref.TemplateArgs;
3502 
3503     // Verify that the correct number of template arguments were specified.
3504     ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs();
3505     if (TArgs.size() < TemplateVals.size())
3506       return Error(SubClassLoc,
3507                    "more template args specified than multiclass expects");
3508 
3509     SubstStack Substs;
3510     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
3511       if (i < TemplateVals.size()) {
3512         Substs.emplace_back(TArgs[i], TemplateVals[i]);
3513       } else {
3514         Init *Default = MC->Rec.getValue(TArgs[i])->getValue();
3515         if (!Default->isComplete()) {
3516           return Error(SubClassLoc,
3517                        "value not specified for template argument #" +
3518                            Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
3519                            ") of multiclass '" + MC->Rec.getNameInitAsString() +
3520                            "'");
3521         }
3522         Substs.emplace_back(TArgs[i], Default);
3523       }
3524     }
3525 
3526     Substs.emplace_back(QualifiedNameOfImplicitName(MC), DefmName);
3527 
3528     if (resolve(MC->Entries, Substs, !CurMultiClass && Loops.empty(),
3529                 &NewEntries, &SubClassLoc))
3530       return true;
3531 
3532     if (!consume(tgtok::comma))
3533       break;
3534 
3535     if (Lex.getCode() != tgtok::Id)
3536       return TokError("expected identifier");
3537 
3538     SubClassLoc = Lex.getLoc();
3539 
3540     // A defm can inherit from regular classes (non-multiclass) as
3541     // long as they come in the end of the inheritance list.
3542     InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
3543 
3544     if (InheritFromClass)
3545       break;
3546 
3547     Ref = ParseSubClassReference(nullptr, true);
3548   }
3549 
3550   if (InheritFromClass) {
3551     // Process all the classes to inherit as if they were part of a
3552     // regular 'def' and inherit all record values.
3553     SubClassReference SubClass = ParseSubClassReference(nullptr, false);
3554     while (true) {
3555       // Check for error.
3556       if (!SubClass.Rec) return true;
3557 
3558       // Get the expanded definition prototypes and teach them about
3559       // the record values the current class to inherit has
3560       for (auto &E : NewEntries) {
3561         // Add it.
3562         if (AddSubClass(E, SubClass))
3563           return true;
3564       }
3565 
3566       if (!consume(tgtok::comma))
3567         break;
3568       SubClass = ParseSubClassReference(nullptr, false);
3569     }
3570   }
3571 
3572   for (auto &E : NewEntries) {
3573     if (ApplyLetStack(E))
3574       return true;
3575 
3576     addEntry(std::move(E));
3577   }
3578 
3579   if (!consume(tgtok::semi))
3580     return TokError("expected ';' at end of defm");
3581 
3582   return false;
3583 }
3584 
3585 /// ParseObject
3586 ///   Object ::= ClassInst
3587 ///   Object ::= DefInst
3588 ///   Object ::= MultiClassInst
3589 ///   Object ::= DefMInst
3590 ///   Object ::= LETCommand '{' ObjectList '}'
3591 ///   Object ::= LETCommand Object
3592 ///   Object ::= Defset
3593 ///   Object ::= Defvar
3594 ///   Object ::= Assert
3595 bool TGParser::ParseObject(MultiClass *MC) {
3596   switch (Lex.getCode()) {
3597   default:
3598     return TokError(
3599                "Expected assert, class, def, defm, defset, foreach, if, or let");
3600   case tgtok::Assert:  return ParseAssert(MC, nullptr);
3601   case tgtok::Def:     return ParseDef(MC);
3602   case tgtok::Defm:    return ParseDefm(MC);
3603   case tgtok::Defvar:  return ParseDefvar();
3604   case tgtok::Foreach: return ParseForeach(MC);
3605   case tgtok::If:      return ParseIf(MC);
3606   case tgtok::Let:     return ParseTopLevelLet(MC);
3607   case tgtok::Defset:
3608     if (MC)
3609       return TokError("defset is not allowed inside multiclass");
3610     return ParseDefset();
3611   case tgtok::Class:
3612     if (MC)
3613       return TokError("class is not allowed inside multiclass");
3614     if (!Loops.empty())
3615       return TokError("class is not allowed inside foreach loop");
3616     return ParseClass();
3617   case tgtok::MultiClass:
3618     if (!Loops.empty())
3619       return TokError("multiclass is not allowed inside foreach loop");
3620     return ParseMultiClass();
3621   }
3622 }
3623 
3624 /// ParseObjectList
3625 ///   ObjectList :== Object*
3626 bool TGParser::ParseObjectList(MultiClass *MC) {
3627   while (isObjectStart(Lex.getCode())) {
3628     if (ParseObject(MC))
3629       return true;
3630   }
3631   return false;
3632 }
3633 
3634 bool TGParser::ParseFile() {
3635   Lex.Lex(); // Prime the lexer.
3636   if (ParseObjectList()) return true;
3637 
3638   // If we have unread input at the end of the file, report it.
3639   if (Lex.getCode() == tgtok::Eof)
3640     return false;
3641 
3642   return TokError("Unexpected token at top level");
3643 }
3644 
3645 // Check an assertion: Obtain the condition value and be sure it is true.
3646 // If not, print a nonfatal error along with the message.
3647 void TGParser::CheckAssert(SMLoc Loc, Init *Condition, Init *Message) {
3648   auto *CondValue = dyn_cast_or_null<IntInit>(
3649                         Condition->convertInitializerTo(IntRecTy::get()));
3650   if (CondValue) {
3651     if (!CondValue->getValue()) {
3652       PrintError(Loc, "assertion failed");
3653       if (auto *MessageInit = dyn_cast<StringInit>(Message))
3654         PrintNote(MessageInit->getValue());
3655       else
3656         PrintNote("(assert message is not a string)");
3657     }
3658   } else {
3659     PrintError(Loc, "assert condition must of type bit, bits, or int.");
3660   }
3661 }
3662 
3663 // Check all record assertions: For each one, resolve the condition
3664 // and message, then call CheckAssert().
3665 void TGParser::CheckRecordAsserts(Record &Rec) {
3666   RecordResolver R(Rec);
3667   R.setFinal(true);
3668 
3669   for (auto Assertion : Rec.getAssertions()) {
3670     Init *Condition = std::get<1>(Assertion)->resolveReferences(R);
3671     Init *Message = std::get<2>(Assertion)->resolveReferences(R);
3672     CheckAssert(std::get<0>(Assertion), Condition, Message);
3673   }
3674 }
3675 
3676 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3677 LLVM_DUMP_METHOD void RecordsEntry::dump() const {
3678   if (Loop)
3679     Loop->dump();
3680   if (Rec)
3681     Rec->dump();
3682 }
3683 
3684 LLVM_DUMP_METHOD void ForeachLoop::dump() const {
3685   errs() << "foreach " << IterVar->getAsString() << " = "
3686          << ListValue->getAsString() << " in {\n";
3687 
3688   for (const auto &E : Entries)
3689     E.dump();
3690 
3691   errs() << "}\n";
3692 }
3693 
3694 LLVM_DUMP_METHOD void MultiClass::dump() const {
3695   errs() << "Record:\n";
3696   Rec.dump();
3697 
3698   errs() << "Defs:\n";
3699   for (const auto &E : Entries)
3700     E.dump();
3701 }
3702 #endif
3703