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