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