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