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