1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implement the Parser for TableGen.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TGParser.h"
15 #include "llvm/ADT/None.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Support/Casting.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/TableGen/Record.h"
24 #include <algorithm>
25 #include <cassert>
26 #include <cstdint>
27 
28 using namespace llvm;
29 
30 //===----------------------------------------------------------------------===//
31 // Support Code for the Semantic Actions.
32 //===----------------------------------------------------------------------===//
33 
34 namespace llvm {
35 
36 struct SubClassReference {
37   SMRange RefRange;
38   Record *Rec;
39   SmallVector<Init*, 4> TemplateArgs;
40 
41   SubClassReference() : Rec(nullptr) {}
42 
43   bool isInvalid() const { return Rec == nullptr; }
44 };
45 
46 struct SubMultiClassReference {
47   SMRange RefRange;
48   MultiClass *MC;
49   SmallVector<Init*, 4> TemplateArgs;
50 
51   SubMultiClassReference() : MC(nullptr) {}
52 
53   bool isInvalid() const { return MC == nullptr; }
54   void dump() const;
55 };
56 
57 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
58 LLVM_DUMP_METHOD void SubMultiClassReference::dump() const {
59   errs() << "Multiclass:\n";
60 
61   MC->dump();
62 
63   errs() << "Template args:\n";
64   for (Init *TA : TemplateArgs)
65     TA->dump();
66 }
67 #endif
68 
69 } // end namespace llvm
70 
71 static bool checkBitsConcrete(Record &R, const RecordVal &RV) {
72   BitsInit *BV = cast<BitsInit>(RV.getValue());
73   for (unsigned i = 0, e = BV->getNumBits(); i != e; ++i) {
74     Init *Bit = BV->getBit(i);
75     bool IsReference = false;
76     if (auto VBI = dyn_cast<VarBitInit>(Bit)) {
77       if (auto VI = dyn_cast<VarInit>(VBI->getBitVar())) {
78         if (R.getValue(VI->getName()))
79           IsReference = true;
80       }
81     } else if (isa<VarInit>(Bit)) {
82       IsReference = true;
83     }
84     if (!(IsReference || Bit->isConcrete()))
85       return false;
86   }
87   return true;
88 }
89 
90 static void checkConcrete(Record &R) {
91   for (const RecordVal &RV : R.getValues()) {
92     // HACK: Disable this check for variables declared with 'field'. This is
93     // done merely because existing targets have legitimate cases of
94     // non-concrete variables in helper defs. Ideally, we'd introduce a
95     // 'maybe' or 'optional' modifier instead of this.
96     if (RV.getPrefix())
97       continue;
98 
99     if (Init *V = RV.getValue()) {
100       bool Ok = isa<BitsInit>(V) ? checkBitsConcrete(R, RV) : V->isConcrete();
101       if (!Ok) {
102         PrintError(R.getLoc(),
103                    Twine("Initializer of '") + RV.getNameInitAsString() +
104                    "' in '" + R.getNameInitAsString() +
105                    "' could not be fully resolved: " +
106                    RV.getValue()->getAsString());
107       }
108     }
109   }
110 }
111 
112 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
113   if (!CurRec)
114     CurRec = &CurMultiClass->Rec;
115 
116   if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
117     // The value already exists in the class, treat this as a set.
118     if (ERV->setValue(RV.getValue()))
119       return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
120                    RV.getType()->getAsString() + "' is incompatible with " +
121                    "previous definition of type '" +
122                    ERV->getType()->getAsString() + "'");
123   } else {
124     CurRec->addValue(RV);
125   }
126   return false;
127 }
128 
129 /// SetValue -
130 /// Return true on error, false on success.
131 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
132                         ArrayRef<unsigned> BitList, Init *V,
133                         bool AllowSelfAssignment) {
134   if (!V) return false;
135 
136   if (!CurRec) CurRec = &CurMultiClass->Rec;
137 
138   RecordVal *RV = CurRec->getValue(ValName);
139   if (!RV)
140     return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
141                  "' unknown!");
142 
143   // Do not allow assignments like 'X = X'.  This will just cause infinite loops
144   // in the resolution machinery.
145   if (BitList.empty())
146     if (VarInit *VI = dyn_cast<VarInit>(V))
147       if (VI->getNameInit() == ValName && !AllowSelfAssignment)
148         return Error(Loc, "Recursion / self-assignment forbidden");
149 
150   // If we are assigning to a subset of the bits in the value... then we must be
151   // assigning to a field of BitsRecTy, which must have a BitsInit
152   // initializer.
153   //
154   if (!BitList.empty()) {
155     BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
156     if (!CurVal)
157       return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
158                    "' is not a bits type");
159 
160     // Convert the incoming value to a bits type of the appropriate size...
161     Init *BI = V->getCastTo(BitsRecTy::get(BitList.size()));
162     if (!BI)
163       return Error(Loc, "Initializer is not compatible with bit range");
164 
165     SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
166 
167     // Loop over bits, assigning values as appropriate.
168     for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
169       unsigned Bit = BitList[i];
170       if (NewBits[Bit])
171         return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" +
172                      ValName->getAsUnquotedString() + "' more than once");
173       NewBits[Bit] = BI->getBit(i);
174     }
175 
176     for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
177       if (!NewBits[i])
178         NewBits[i] = CurVal->getBit(i);
179 
180     V = BitsInit::get(NewBits);
181   }
182 
183   if (RV->setValue(V)) {
184     std::string InitType;
185     if (BitsInit *BI = dyn_cast<BitsInit>(V))
186       InitType = (Twine("' of type bit initializer with length ") +
187                   Twine(BI->getNumBits())).str();
188     else if (TypedInit *TI = dyn_cast<TypedInit>(V))
189       InitType = (Twine("' of type '") + TI->getType()->getAsString()).str();
190     return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
191                           "' of type '" + RV->getType()->getAsString() +
192                           "' is incompatible with initializer '" +
193                           V->getAsString() + InitType + "'");
194   }
195   return false;
196 }
197 
198 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
199 /// args as SubClass's template arguments.
200 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
201   Record *SC = SubClass.Rec;
202   // Add all of the values in the subclass into the current class.
203   for (const RecordVal &Val : SC->getValues())
204     if (AddValue(CurRec, SubClass.RefRange.Start, Val))
205       return true;
206 
207   ArrayRef<Init *> TArgs = SC->getTemplateArgs();
208 
209   // Ensure that an appropriate number of template arguments are specified.
210   if (TArgs.size() < SubClass.TemplateArgs.size())
211     return Error(SubClass.RefRange.Start,
212                  "More template args specified than expected");
213 
214   // Loop over all of the template arguments, setting them to the specified
215   // value or leaving them as the default if necessary.
216   MapResolver R(CurRec);
217 
218   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
219     if (i < SubClass.TemplateArgs.size()) {
220       // If a value is specified for this template arg, set it now.
221       if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
222                    None, SubClass.TemplateArgs[i]))
223         return true;
224     } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
225       return Error(SubClass.RefRange.Start,
226                    "Value not specified for template argument #" +
227                    Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
228                    ") of subclass '" + SC->getNameInitAsString() + "'!");
229     }
230 
231     R.set(TArgs[i], CurRec->getValue(TArgs[i])->getValue());
232 
233     CurRec->removeValue(TArgs[i]);
234   }
235 
236   CurRec->resolveReferences(R);
237 
238   // Since everything went well, we can now set the "superclass" list for the
239   // current record.
240   ArrayRef<std::pair<Record *, SMRange>> SCs = SC->getSuperClasses();
241   for (const auto &SCPair : SCs) {
242     if (CurRec->isSubClassOf(SCPair.first))
243       return Error(SubClass.RefRange.Start,
244                    "Already subclass of '" + SCPair.first->getName() + "'!\n");
245     CurRec->addSuperClass(SCPair.first, SCPair.second);
246   }
247 
248   if (CurRec->isSubClassOf(SC))
249     return Error(SubClass.RefRange.Start,
250                  "Already subclass of '" + SC->getName() + "'!\n");
251   CurRec->addSuperClass(SC, SubClass.RefRange);
252   return false;
253 }
254 
255 /// AddSubMultiClass - Add SubMultiClass as a subclass to
256 /// CurMC, resolving its template args as SubMultiClass's
257 /// template arguments.
258 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
259                                 SubMultiClassReference &SubMultiClass) {
260   MultiClass *SMC = SubMultiClass.MC;
261   Record *CurRec = &CurMC->Rec;
262 
263   // Add all of the values in the subclass into the current class.
264   for (const auto &SMCVal : SMC->Rec.getValues())
265     if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVal))
266       return true;
267 
268   unsigned newDefStart = CurMC->DefPrototypes.size();
269 
270   // Add all of the defs in the subclass into the current multiclass.
271   for (const std::unique_ptr<Record> &R : SMC->DefPrototypes) {
272     // Clone the def and add it to the current multiclass
273     auto NewDef = make_unique<Record>(*R);
274 
275     // Add all of the values in the superclass into the current def.
276     for (const auto &MCVal : CurRec->getValues())
277       if (AddValue(NewDef.get(), SubMultiClass.RefRange.Start, MCVal))
278         return true;
279 
280     CurMC->DefPrototypes.push_back(std::move(NewDef));
281   }
282 
283   ArrayRef<Init *> SMCTArgs = SMC->Rec.getTemplateArgs();
284 
285   // Ensure that an appropriate number of template arguments are
286   // specified.
287   if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
288     return Error(SubMultiClass.RefRange.Start,
289                  "More template args specified than expected");
290 
291   // Loop over all of the template arguments, setting them to the specified
292   // value or leaving them as the default if necessary.
293   MapResolver CurRecResolver(CurRec);
294 
295   for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
296     if (i < SubMultiClass.TemplateArgs.size()) {
297       // If a value is specified for this template arg, set it in the
298       // superclass now.
299       if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i],
300                    None, SubMultiClass.TemplateArgs[i]))
301         return true;
302 
303       // If a value is specified for this template arg, set it in the
304       // new defs now.
305       for (const auto &Def :
306              makeArrayRef(CurMC->DefPrototypes).slice(newDefStart)) {
307         if (SetValue(Def.get(), SubMultiClass.RefRange.Start, SMCTArgs[i],
308                      None, SubMultiClass.TemplateArgs[i]))
309           return true;
310       }
311     } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
312       return Error(SubMultiClass.RefRange.Start,
313                    "Value not specified for template argument #" +
314                    Twine(i) + " (" + SMCTArgs[i]->getAsUnquotedString() +
315                    ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
316     }
317 
318     CurRecResolver.set(SMCTArgs[i], CurRec->getValue(SMCTArgs[i])->getValue());
319 
320     CurRec->removeValue(SMCTArgs[i]);
321   }
322 
323   CurRec->resolveReferences(CurRecResolver);
324 
325   for (const auto &Def :
326        makeArrayRef(CurMC->DefPrototypes).slice(newDefStart)) {
327     MapResolver R(Def.get());
328 
329     for (Init *SMCTArg : SMCTArgs) {
330       R.set(SMCTArg, Def->getValue(SMCTArg)->getValue());
331       Def->removeValue(SMCTArg);
332     }
333 
334     Def->resolveReferences(R);
335   }
336 
337   return false;
338 }
339 
340 /// Add a record that results from 'def' or 'defm', after template arguments
341 /// and the external let stack have been resolved.
342 ///
343 /// Apply foreach loops, resolve internal variable references, and add to the
344 /// current multi class or the global record keeper as appropriate.
345 bool TGParser::addDef(std::unique_ptr<Record> Rec, Init *DefmName) {
346   IterSet IterVals;
347 
348   if (Loops.empty())
349     return addDefOne(std::move(Rec), DefmName, IterVals);
350 
351   return addDefForeach(Rec.get(), DefmName, IterVals);
352 }
353 
354 /// Recursive helper function for addDef/addDefOne to resolve references to
355 /// foreach variables.
356 bool TGParser::addDefForeach(Record *Rec, Init *DefmName, IterSet &IterVals) {
357   if (IterVals.size() != Loops.size()) {
358     assert(IterVals.size() < Loops.size());
359     ForeachLoop &CurLoop = Loops[IterVals.size()];
360     ListInit *List = CurLoop.ListValue;
361 
362     // Process each value.
363     for (unsigned i = 0; i < List->size(); ++i) {
364       IterVals.push_back(IterRecord(CurLoop.IterVar, List->getElement(i)));
365       if (addDefForeach(Rec, DefmName, IterVals))
366         return true;
367       IterVals.pop_back();
368     }
369     return false;
370   }
371 
372   // This is the bottom of the recursion. We have all of the iterator values
373   // for this point in the iteration space.  Instantiate a new record to
374   // reflect this combination of values.
375   auto IterRec = make_unique<Record>(*Rec);
376   return addDefOne(std::move(IterRec), DefmName, IterVals);
377 }
378 
379 /// After resolving foreach loops, add the record as a prototype to the
380 /// current multiclass, or resolve fully and add to the record keeper.
381 bool TGParser::addDefOne(std::unique_ptr<Record> Rec, Init *DefmName,
382                          IterSet &IterVals) {
383   MapResolver R(Rec.get());
384 
385   for (IterRecord &IR : IterVals)
386     R.set(IR.IterVar->getNameInit(), IR.IterValue);
387 
388   Rec->resolveReferences(R);
389 
390   if (CurMultiClass) {
391     for (const auto &Proto : CurMultiClass->DefPrototypes) {
392       if (Proto->getNameInit() == Rec->getNameInit()) {
393         if (!Rec->isAnonymous()) {
394           PrintError(Rec->getLoc(),
395                     Twine("def '") + Rec->getNameInitAsString() +
396                         "' already defined in this multiclass!");
397           PrintNote(Proto->getLoc(), "location of previous definition");
398           return true;
399         }
400         Rec->setName(Records.getNewAnonymousName());
401         break;
402       }
403     }
404     CurMultiClass->DefPrototypes.emplace_back(std::move(Rec));
405     return false;
406   }
407 
408   // Name construction is an incoherent mess. Unfortunately, existing .td
409   // files rely on pretty much all the quirks and implementation details of
410   // this.
411   if (DefmName) {
412     MapResolver R(Rec.get());
413     R.set(StringInit::get("NAME"), DefmName);
414     Rec->resolveReferences(R);
415   }
416 
417   if (Record *Prev = Records.getDef(Rec->getNameInitAsString())) {
418     if (!Rec->isAnonymous()) {
419       PrintError(Rec->getLoc(),
420                  "def already exists: " + Rec->getNameInitAsString());
421       PrintNote(Prev->getLoc(), "location of previous definition");
422       return true;
423     }
424     Rec->setName(Records.getNewAnonymousName());
425   }
426 
427   Rec->resolveReferences();
428   checkConcrete(*Rec);
429 
430   // If ObjectBody has template arguments, it's an error.
431   assert(Rec->getTemplateArgs().empty() && "How'd this get template args?");
432 
433   for (DefsetRecord *Defset : Defsets) {
434     DefInit *I = Rec->getDefInit();
435     if (!I->getType()->typeIsA(Defset->EltTy)) {
436       PrintError(Rec->getLoc(), Twine("adding record of incompatible type '") +
437                                     I->getType()->getAsString() +
438                                      "' to defset");
439       PrintNote(Defset->Loc, "location of defset declaration");
440       return true;
441     }
442     Defset->Elements.push_back(I);
443   }
444 
445   Records.addDef(std::move(Rec));
446   return false;
447 }
448 
449 //===----------------------------------------------------------------------===//
450 // Parser Code
451 //===----------------------------------------------------------------------===//
452 
453 /// isObjectStart - Return true if this is a valid first token for an Object.
454 static bool isObjectStart(tgtok::TokKind K) {
455   return K == tgtok::Class || K == tgtok::Def || K == tgtok::Defm ||
456          K == tgtok::Let || K == tgtok::MultiClass || K == tgtok::Foreach ||
457          K == tgtok::Defset;
458 }
459 
460 /// ParseObjectName - If a valid object name is specified, return it. If no
461 /// name is specified, return the unset initializer. Return nullptr on parse
462 /// error.
463 ///   ObjectName ::= Value [ '#' Value ]*
464 ///   ObjectName ::= /*empty*/
465 ///
466 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
467   switch (Lex.getCode()) {
468   case tgtok::colon:
469   case tgtok::semi:
470   case tgtok::l_brace:
471     // These are all of the tokens that can begin an object body.
472     // Some of these can also begin values but we disallow those cases
473     // because they are unlikely to be useful.
474     return UnsetInit::get();
475   default:
476     break;
477   }
478 
479   Record *CurRec = nullptr;
480   if (CurMultiClass)
481     CurRec = &CurMultiClass->Rec;
482 
483   return ParseValue(CurRec, StringRecTy::get(), ParseNameMode);
484 }
485 
486 /// ParseClassID - Parse and resolve a reference to a class name.  This returns
487 /// null on error.
488 ///
489 ///    ClassID ::= ID
490 ///
491 Record *TGParser::ParseClassID() {
492   if (Lex.getCode() != tgtok::Id) {
493     TokError("expected name for ClassID");
494     return nullptr;
495   }
496 
497   Record *Result = Records.getClass(Lex.getCurStrVal());
498   if (!Result)
499     TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
500 
501   Lex.Lex();
502   return Result;
503 }
504 
505 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
506 /// This returns null on error.
507 ///
508 ///    MultiClassID ::= ID
509 ///
510 MultiClass *TGParser::ParseMultiClassID() {
511   if (Lex.getCode() != tgtok::Id) {
512     TokError("expected name for MultiClassID");
513     return nullptr;
514   }
515 
516   MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
517   if (!Result)
518     TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
519 
520   Lex.Lex();
521   return Result;
522 }
523 
524 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
525 /// subclass.  This returns a SubClassRefTy with a null Record* on error.
526 ///
527 ///  SubClassRef ::= ClassID
528 ///  SubClassRef ::= ClassID '<' ValueList '>'
529 ///
530 SubClassReference TGParser::
531 ParseSubClassReference(Record *CurRec, bool isDefm) {
532   SubClassReference Result;
533   Result.RefRange.Start = Lex.getLoc();
534 
535   if (isDefm) {
536     if (MultiClass *MC = ParseMultiClassID())
537       Result.Rec = &MC->Rec;
538   } else {
539     Result.Rec = ParseClassID();
540   }
541   if (!Result.Rec) return Result;
542 
543   // If there is no template arg list, we're done.
544   if (Lex.getCode() != tgtok::less) {
545     Result.RefRange.End = Lex.getLoc();
546     return Result;
547   }
548   Lex.Lex();  // Eat the '<'
549 
550   if (Lex.getCode() == tgtok::greater) {
551     TokError("subclass reference requires a non-empty list of template values");
552     Result.Rec = nullptr;
553     return Result;
554   }
555 
556   ParseValueList(Result.TemplateArgs, CurRec, Result.Rec);
557   if (Result.TemplateArgs.empty()) {
558     Result.Rec = nullptr;   // Error parsing value list.
559     return Result;
560   }
561 
562   if (Lex.getCode() != tgtok::greater) {
563     TokError("expected '>' in template value list");
564     Result.Rec = nullptr;
565     return Result;
566   }
567   Lex.Lex();
568   Result.RefRange.End = Lex.getLoc();
569 
570   return Result;
571 }
572 
573 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
574 /// templated submulticlass.  This returns a SubMultiClassRefTy with a null
575 /// Record* on error.
576 ///
577 ///  SubMultiClassRef ::= MultiClassID
578 ///  SubMultiClassRef ::= MultiClassID '<' ValueList '>'
579 ///
580 SubMultiClassReference TGParser::
581 ParseSubMultiClassReference(MultiClass *CurMC) {
582   SubMultiClassReference Result;
583   Result.RefRange.Start = Lex.getLoc();
584 
585   Result.MC = ParseMultiClassID();
586   if (!Result.MC) return Result;
587 
588   // If there is no template arg list, we're done.
589   if (Lex.getCode() != tgtok::less) {
590     Result.RefRange.End = Lex.getLoc();
591     return Result;
592   }
593   Lex.Lex();  // Eat the '<'
594 
595   if (Lex.getCode() == tgtok::greater) {
596     TokError("subclass reference requires a non-empty list of template values");
597     Result.MC = nullptr;
598     return Result;
599   }
600 
601   ParseValueList(Result.TemplateArgs, &CurMC->Rec, &Result.MC->Rec);
602   if (Result.TemplateArgs.empty()) {
603     Result.MC = nullptr;   // Error parsing value list.
604     return Result;
605   }
606 
607   if (Lex.getCode() != tgtok::greater) {
608     TokError("expected '>' in template value list");
609     Result.MC = nullptr;
610     return Result;
611   }
612   Lex.Lex();
613   Result.RefRange.End = Lex.getLoc();
614 
615   return Result;
616 }
617 
618 /// ParseRangePiece - Parse a bit/value range.
619 ///   RangePiece ::= INTVAL
620 ///   RangePiece ::= INTVAL '-' INTVAL
621 ///   RangePiece ::= INTVAL INTVAL
622 bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges) {
623   if (Lex.getCode() != tgtok::IntVal) {
624     TokError("expected integer or bitrange");
625     return true;
626   }
627   int64_t Start = Lex.getCurIntVal();
628   int64_t End;
629 
630   if (Start < 0)
631     return TokError("invalid range, cannot be negative");
632 
633   switch (Lex.Lex()) {  // eat first character.
634   default:
635     Ranges.push_back(Start);
636     return false;
637   case tgtok::minus:
638     if (Lex.Lex() != tgtok::IntVal) {
639       TokError("expected integer value as end of range");
640       return true;
641     }
642     End = Lex.getCurIntVal();
643     break;
644   case tgtok::IntVal:
645     End = -Lex.getCurIntVal();
646     break;
647   }
648   if (End < 0)
649     return TokError("invalid range, cannot be negative");
650   Lex.Lex();
651 
652   // Add to the range.
653   if (Start < End)
654     for (; Start <= End; ++Start)
655       Ranges.push_back(Start);
656   else
657     for (; Start >= End; --Start)
658       Ranges.push_back(Start);
659   return false;
660 }
661 
662 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
663 ///
664 ///   RangeList ::= RangePiece (',' RangePiece)*
665 ///
666 void TGParser::ParseRangeList(SmallVectorImpl<unsigned> &Result) {
667   // Parse the first piece.
668   if (ParseRangePiece(Result)) {
669     Result.clear();
670     return;
671   }
672   while (Lex.getCode() == tgtok::comma) {
673     Lex.Lex();  // Eat the comma.
674 
675     // Parse the next range piece.
676     if (ParseRangePiece(Result)) {
677       Result.clear();
678       return;
679     }
680   }
681 }
682 
683 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
684 ///   OptionalRangeList ::= '<' RangeList '>'
685 ///   OptionalRangeList ::= /*empty*/
686 bool TGParser::ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges) {
687   if (Lex.getCode() != tgtok::less)
688     return false;
689 
690   SMLoc StartLoc = Lex.getLoc();
691   Lex.Lex(); // eat the '<'
692 
693   // Parse the range list.
694   ParseRangeList(Ranges);
695   if (Ranges.empty()) return true;
696 
697   if (Lex.getCode() != tgtok::greater) {
698     TokError("expected '>' at end of range list");
699     return Error(StartLoc, "to match this '<'");
700   }
701   Lex.Lex();   // eat the '>'.
702   return false;
703 }
704 
705 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
706 ///   OptionalBitList ::= '{' RangeList '}'
707 ///   OptionalBitList ::= /*empty*/
708 bool TGParser::ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges) {
709   if (Lex.getCode() != tgtok::l_brace)
710     return false;
711 
712   SMLoc StartLoc = Lex.getLoc();
713   Lex.Lex(); // eat the '{'
714 
715   // Parse the range list.
716   ParseRangeList(Ranges);
717   if (Ranges.empty()) return true;
718 
719   if (Lex.getCode() != tgtok::r_brace) {
720     TokError("expected '}' at end of bit list");
721     return Error(StartLoc, "to match this '{'");
722   }
723   Lex.Lex();   // eat the '}'.
724   return false;
725 }
726 
727 /// ParseType - Parse and return a tblgen type.  This returns null on error.
728 ///
729 ///   Type ::= STRING                       // string type
730 ///   Type ::= CODE                         // code type
731 ///   Type ::= BIT                          // bit type
732 ///   Type ::= BITS '<' INTVAL '>'          // bits<x> type
733 ///   Type ::= INT                          // int type
734 ///   Type ::= LIST '<' Type '>'            // list<x> type
735 ///   Type ::= DAG                          // dag type
736 ///   Type ::= ClassID                      // Record Type
737 ///
738 RecTy *TGParser::ParseType() {
739   switch (Lex.getCode()) {
740   default: TokError("Unknown token when expecting a type"); return nullptr;
741   case tgtok::String: Lex.Lex(); return StringRecTy::get();
742   case tgtok::Code:   Lex.Lex(); return CodeRecTy::get();
743   case tgtok::Bit:    Lex.Lex(); return BitRecTy::get();
744   case tgtok::Int:    Lex.Lex(); return IntRecTy::get();
745   case tgtok::Dag:    Lex.Lex(); return DagRecTy::get();
746   case tgtok::Id:
747     if (Record *R = ParseClassID()) return RecordRecTy::get(R);
748     TokError("unknown class name");
749     return nullptr;
750   case tgtok::Bits: {
751     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
752       TokError("expected '<' after bits type");
753       return nullptr;
754     }
755     if (Lex.Lex() != tgtok::IntVal) {  // Eat '<'
756       TokError("expected integer in bits<n> type");
757       return nullptr;
758     }
759     uint64_t Val = Lex.getCurIntVal();
760     if (Lex.Lex() != tgtok::greater) {  // Eat count.
761       TokError("expected '>' at end of bits<n> type");
762       return nullptr;
763     }
764     Lex.Lex();  // Eat '>'
765     return BitsRecTy::get(Val);
766   }
767   case tgtok::List: {
768     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
769       TokError("expected '<' after list type");
770       return nullptr;
771     }
772     Lex.Lex();  // Eat '<'
773     RecTy *SubType = ParseType();
774     if (!SubType) return nullptr;
775 
776     if (Lex.getCode() != tgtok::greater) {
777       TokError("expected '>' at end of list<ty> type");
778       return nullptr;
779     }
780     Lex.Lex();  // Eat '>'
781     return ListRecTy::get(SubType);
782   }
783   }
784 }
785 
786 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
787 /// has already been read.
788 Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMLoc NameLoc,
789                              IDParseMode Mode) {
790   if (CurRec) {
791     if (const RecordVal *RV = CurRec->getValue(Name))
792       return VarInit::get(Name, RV->getType());
793 
794     Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
795 
796     if (CurMultiClass)
797       TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
798                                     "::");
799 
800     if (CurRec->isTemplateArg(TemplateArgName)) {
801       const RecordVal *RV = CurRec->getValue(TemplateArgName);
802       assert(RV && "Template arg doesn't exist??");
803       return VarInit::get(TemplateArgName, RV->getType());
804     }
805   }
806 
807   if (CurMultiClass) {
808     if (Name->getValue() == "NAME")
809       return VarInit::get(Name, StringRecTy::get());
810 
811     Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
812 
813     if (CurMultiClass->Rec.isTemplateArg(MCName)) {
814       const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
815       assert(RV && "Template arg doesn't exist??");
816       return VarInit::get(MCName, RV->getType());
817     }
818   }
819 
820   // If this is in a foreach loop, make sure it's not a loop iterator
821   for (const auto &L : Loops) {
822     VarInit *IterVar = dyn_cast<VarInit>(L.IterVar);
823     if (IterVar && IterVar->getNameInit() == Name)
824       return IterVar;
825   }
826 
827   if (Mode == ParseNameMode)
828     return Name;
829 
830   if (Init *I = Records.getGlobal(Name->getValue()))
831     return I;
832 
833   // Allow self-references of concrete defs, but delay the lookup so that we
834   // get the correct type.
835   if (CurRec && !CurMultiClass && CurRec->getNameInit() == Name)
836     return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType());
837 
838   if (Mode == ParseValueMode) {
839     Error(NameLoc, "Variable not defined: '" + Name->getValue() + "'");
840     return nullptr;
841   }
842 
843   return Name;
844 }
845 
846 /// ParseOperation - Parse an operator.  This returns null on error.
847 ///
848 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
849 ///
850 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
851   switch (Lex.getCode()) {
852   default:
853     TokError("unknown operation");
854     return nullptr;
855   case tgtok::XHead:
856   case tgtok::XTail:
857   case tgtok::XSize:
858   case tgtok::XEmpty:
859   case tgtok::XCast: {  // Value ::= !unop '(' Value ')'
860     UnOpInit::UnaryOp Code;
861     RecTy *Type = nullptr;
862 
863     switch (Lex.getCode()) {
864     default: llvm_unreachable("Unhandled code!");
865     case tgtok::XCast:
866       Lex.Lex();  // eat the operation
867       Code = UnOpInit::CAST;
868 
869       Type = ParseOperatorType();
870 
871       if (!Type) {
872         TokError("did not get type for unary operator");
873         return nullptr;
874       }
875 
876       break;
877     case tgtok::XHead:
878       Lex.Lex();  // eat the operation
879       Code = UnOpInit::HEAD;
880       break;
881     case tgtok::XTail:
882       Lex.Lex();  // eat the operation
883       Code = UnOpInit::TAIL;
884       break;
885     case tgtok::XSize:
886       Lex.Lex();
887       Code = UnOpInit::SIZE;
888       Type = IntRecTy::get();
889       break;
890     case tgtok::XEmpty:
891       Lex.Lex();  // eat the operation
892       Code = UnOpInit::EMPTY;
893       Type = IntRecTy::get();
894       break;
895     }
896     if (Lex.getCode() != tgtok::l_paren) {
897       TokError("expected '(' after unary operator");
898       return nullptr;
899     }
900     Lex.Lex();  // eat the '('
901 
902     Init *LHS = ParseValue(CurRec);
903     if (!LHS) return nullptr;
904 
905     if (Code == UnOpInit::HEAD ||
906         Code == UnOpInit::TAIL ||
907         Code == UnOpInit::EMPTY) {
908       ListInit *LHSl = dyn_cast<ListInit>(LHS);
909       StringInit *LHSs = dyn_cast<StringInit>(LHS);
910       TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
911       if (!LHSl && !LHSs && !LHSt) {
912         TokError("expected list or string type argument in unary operator");
913         return nullptr;
914       }
915       if (LHSt) {
916         ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
917         StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
918         if (!LType && !SType) {
919           TokError("expected list or string type argument in unary operator");
920           return nullptr;
921         }
922       }
923 
924       if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL ||
925           Code == UnOpInit::SIZE) {
926         if (!LHSl && !LHSt) {
927           TokError("expected list type argument in unary operator");
928           return nullptr;
929         }
930       }
931 
932       if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
933         if (LHSl && LHSl->empty()) {
934           TokError("empty list argument in unary operator");
935           return nullptr;
936         }
937         if (LHSl) {
938           Init *Item = LHSl->getElement(0);
939           TypedInit *Itemt = dyn_cast<TypedInit>(Item);
940           if (!Itemt) {
941             TokError("untyped list element in unary operator");
942             return nullptr;
943           }
944           Type = (Code == UnOpInit::HEAD) ? Itemt->getType()
945                                           : ListRecTy::get(Itemt->getType());
946         } else {
947           assert(LHSt && "expected list type argument in unary operator");
948           ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
949           if (!LType) {
950             TokError("expected list type argument in unary operator");
951             return nullptr;
952           }
953           Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType;
954         }
955       }
956     }
957 
958     if (Lex.getCode() != tgtok::r_paren) {
959       TokError("expected ')' in unary operator");
960       return nullptr;
961     }
962     Lex.Lex();  // eat the ')'
963     return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec);
964   }
965 
966   case tgtok::XIsA: {
967     // Value ::= !isa '<' Type '>' '(' Value ')'
968     Lex.Lex(); // eat the operation
969 
970     RecTy *Type = ParseOperatorType();
971     if (!Type)
972       return nullptr;
973 
974     if (Lex.getCode() != tgtok::l_paren) {
975       TokError("expected '(' after type of !isa");
976       return nullptr;
977     }
978     Lex.Lex(); // eat the '('
979 
980     Init *LHS = ParseValue(CurRec);
981     if (!LHS)
982       return nullptr;
983 
984     if (Lex.getCode() != tgtok::r_paren) {
985       TokError("expected ')' in !isa");
986       return nullptr;
987     }
988     Lex.Lex(); // eat the ')'
989 
990     return (IsAOpInit::get(Type, LHS))->Fold();
991   }
992 
993   case tgtok::XConcat:
994   case tgtok::XADD:
995   case tgtok::XAND:
996   case tgtok::XOR:
997   case tgtok::XSRA:
998   case tgtok::XSRL:
999   case tgtok::XSHL:
1000   case tgtok::XEq:
1001   case tgtok::XNe:
1002   case tgtok::XLe:
1003   case tgtok::XLt:
1004   case tgtok::XGe:
1005   case tgtok::XGt:
1006   case tgtok::XListConcat:
1007   case tgtok::XStrConcat: {  // Value ::= !binop '(' Value ',' Value ')'
1008     tgtok::TokKind OpTok = Lex.getCode();
1009     SMLoc OpLoc = Lex.getLoc();
1010     Lex.Lex();  // eat the operation
1011 
1012     BinOpInit::BinaryOp Code;
1013     switch (OpTok) {
1014     default: llvm_unreachable("Unhandled code!");
1015     case tgtok::XConcat: Code = BinOpInit::CONCAT; break;
1016     case tgtok::XADD:    Code = BinOpInit::ADD; break;
1017     case tgtok::XAND:    Code = BinOpInit::AND; break;
1018     case tgtok::XOR:     Code = BinOpInit::OR; break;
1019     case tgtok::XSRA:    Code = BinOpInit::SRA; break;
1020     case tgtok::XSRL:    Code = BinOpInit::SRL; break;
1021     case tgtok::XSHL:    Code = BinOpInit::SHL; break;
1022     case tgtok::XEq:     Code = BinOpInit::EQ; break;
1023     case tgtok::XNe:     Code = BinOpInit::NE; break;
1024     case tgtok::XLe:     Code = BinOpInit::LE; break;
1025     case tgtok::XLt:     Code = BinOpInit::LT; break;
1026     case tgtok::XGe:     Code = BinOpInit::GE; break;
1027     case tgtok::XGt:     Code = BinOpInit::GT; break;
1028     case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break;
1029     case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break;
1030     }
1031 
1032     RecTy *Type = nullptr;
1033     RecTy *ArgType = nullptr;
1034     switch (OpTok) {
1035     default:
1036       llvm_unreachable("Unhandled code!");
1037     case tgtok::XConcat:
1038       Type = DagRecTy::get();
1039       ArgType = DagRecTy::get();
1040       break;
1041     case tgtok::XAND:
1042     case tgtok::XOR:
1043     case tgtok::XSRA:
1044     case tgtok::XSRL:
1045     case tgtok::XSHL:
1046     case tgtok::XADD:
1047       Type = IntRecTy::get();
1048       ArgType = IntRecTy::get();
1049       break;
1050     case tgtok::XEq:
1051     case tgtok::XNe:
1052       Type = BitRecTy::get();
1053       // ArgType for Eq / Ne is not known at this point
1054       break;
1055     case tgtok::XLe:
1056     case tgtok::XLt:
1057     case tgtok::XGe:
1058     case tgtok::XGt:
1059       Type = BitRecTy::get();
1060       ArgType = IntRecTy::get();
1061       break;
1062     case tgtok::XListConcat:
1063       // We don't know the list type until we parse the first argument
1064       ArgType = ItemType;
1065       break;
1066     case tgtok::XStrConcat:
1067       Type = StringRecTy::get();
1068       ArgType = StringRecTy::get();
1069       break;
1070     }
1071 
1072     if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) {
1073       Error(OpLoc, Twine("expected value of type '") +
1074                    ItemType->getAsString() + "', got '" +
1075                    Type->getAsString() + "'");
1076       return nullptr;
1077     }
1078 
1079     if (Lex.getCode() != tgtok::l_paren) {
1080       TokError("expected '(' after binary operator");
1081       return nullptr;
1082     }
1083     Lex.Lex();  // eat the '('
1084 
1085     SmallVector<Init*, 2> InitList;
1086 
1087     for (;;) {
1088       SMLoc InitLoc = Lex.getLoc();
1089       InitList.push_back(ParseValue(CurRec, ArgType));
1090       if (!InitList.back()) return nullptr;
1091 
1092       // All BinOps require their arguments to be of compatible types.
1093       TypedInit *TI = dyn_cast<TypedInit>(InitList.back());
1094       if (!ArgType) {
1095         ArgType = TI->getType();
1096 
1097         switch (Code) {
1098         case BinOpInit::LISTCONCAT:
1099           if (!isa<ListRecTy>(ArgType)) {
1100             Error(InitLoc, Twine("expected a list, got value of type '") +
1101                            ArgType->getAsString() + "'");
1102             return nullptr;
1103           }
1104           break;
1105         case BinOpInit::EQ:
1106         case BinOpInit::NE:
1107           if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) &&
1108               !ArgType->typeIsConvertibleTo(StringRecTy::get())) {
1109             Error(InitLoc, Twine("expected int, bits, or string; got value of "
1110                                  "type '") + ArgType->getAsString() + "'");
1111             return nullptr;
1112           }
1113           break;
1114         default: llvm_unreachable("other ops have fixed argument types");
1115         }
1116       } else {
1117         RecTy *Resolved = resolveTypes(ArgType, TI->getType());
1118         if (!Resolved) {
1119           Error(InitLoc, Twine("expected value of type '") +
1120                          ArgType->getAsString() + "', got '" +
1121                          TI->getType()->getAsString() + "'");
1122           return nullptr;
1123         }
1124         if (Code != BinOpInit::ADD && Code != BinOpInit::AND &&
1125             Code != BinOpInit::OR && Code != BinOpInit::SRA &&
1126             Code != BinOpInit::SRL && Code != BinOpInit::SHL)
1127           ArgType = Resolved;
1128       }
1129 
1130       if (Lex.getCode() != tgtok::comma)
1131         break;
1132       Lex.Lex();  // eat the ','
1133     }
1134 
1135     if (Lex.getCode() != tgtok::r_paren) {
1136       TokError("expected ')' in operator");
1137       return nullptr;
1138     }
1139     Lex.Lex();  // eat the ')'
1140 
1141     if (Code == BinOpInit::LISTCONCAT)
1142       Type = ArgType;
1143 
1144     // We allow multiple operands to associative operators like !strconcat as
1145     // shorthand for nesting them.
1146     if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT ||
1147         Code == BinOpInit::CONCAT || Code == BinOpInit::ADD ||
1148         Code == BinOpInit::AND || Code == BinOpInit::OR) {
1149       while (InitList.size() > 2) {
1150         Init *RHS = InitList.pop_back_val();
1151         RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec);
1152         InitList.back() = RHS;
1153       }
1154     }
1155 
1156     if (InitList.size() == 2)
1157       return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
1158           ->Fold(CurRec);
1159 
1160     Error(OpLoc, "expected two operands to operator");
1161     return nullptr;
1162   }
1163 
1164   case tgtok::XForEach: { // Value ::= !foreach '(' Id ',' Value ',' Value ')'
1165     SMLoc OpLoc = Lex.getLoc();
1166     Lex.Lex(); // eat the operation
1167     if (Lex.getCode() != tgtok::l_paren) {
1168       TokError("expected '(' after !foreach");
1169       return nullptr;
1170     }
1171 
1172     if (Lex.Lex() != tgtok::Id) { // eat the '('
1173       TokError("first argument of !foreach must be an identifier");
1174       return nullptr;
1175     }
1176 
1177     Init *LHS = StringInit::get(Lex.getCurStrVal());
1178 
1179     if (CurRec->getValue(LHS)) {
1180       TokError((Twine("iteration variable '") + LHS->getAsString() +
1181                 "' already defined")
1182                    .str());
1183       return nullptr;
1184     }
1185 
1186     if (Lex.Lex() != tgtok::comma) { // eat the id
1187       TokError("expected ',' in ternary operator");
1188       return nullptr;
1189     }
1190     Lex.Lex();  // eat the ','
1191 
1192     Init *MHS = ParseValue(CurRec);
1193     if (!MHS)
1194       return nullptr;
1195 
1196     if (Lex.getCode() != tgtok::comma) {
1197       TokError("expected ',' in ternary operator");
1198       return nullptr;
1199     }
1200     Lex.Lex();  // eat the ','
1201 
1202     TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1203     if (!MHSt) {
1204       TokError("could not get type of !foreach input");
1205       return nullptr;
1206     }
1207 
1208     RecTy *InEltType = nullptr;
1209     RecTy *OutEltType = nullptr;
1210     bool IsDAG = false;
1211 
1212     if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) {
1213       InEltType = InListTy->getElementType();
1214       if (ItemType) {
1215         if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) {
1216           OutEltType = OutListTy->getElementType();
1217         } else {
1218           Error(OpLoc,
1219                 "expected value of type '" + Twine(ItemType->getAsString()) +
1220                 "', but got !foreach of list type");
1221           return nullptr;
1222         }
1223       }
1224     } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) {
1225       InEltType = InDagTy;
1226       if (ItemType && !isa<DagRecTy>(ItemType)) {
1227         Error(OpLoc,
1228               "expected value of type '" + Twine(ItemType->getAsString()) +
1229               "', but got !foreach of dag type");
1230         return nullptr;
1231       }
1232       IsDAG = true;
1233     } else {
1234       TokError("!foreach must have list or dag input");
1235       return nullptr;
1236     }
1237 
1238     CurRec->addValue(RecordVal(LHS, InEltType, false));
1239     Init *RHS = ParseValue(CurRec, OutEltType);
1240     CurRec->removeValue(LHS);
1241     if (!RHS)
1242       return nullptr;
1243 
1244     if (Lex.getCode() != tgtok::r_paren) {
1245       TokError("expected ')' in binary operator");
1246       return nullptr;
1247     }
1248     Lex.Lex();  // eat the ')'
1249 
1250     RecTy *OutType;
1251     if (IsDAG) {
1252       OutType = InEltType;
1253     } else {
1254       TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1255       if (!RHSt) {
1256         TokError("could not get type of !foreach result");
1257         return nullptr;
1258       }
1259       OutType = RHSt->getType()->getListTy();
1260     }
1261 
1262     return (TernOpInit::get(TernOpInit::FOREACH, LHS, MHS, RHS, OutType))
1263         ->Fold(CurRec);
1264   }
1265 
1266   case tgtok::XDag:
1267   case tgtok::XIf:
1268   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1269     TernOpInit::TernaryOp Code;
1270     RecTy *Type = nullptr;
1271 
1272     tgtok::TokKind LexCode = Lex.getCode();
1273     Lex.Lex();  // eat the operation
1274     switch (LexCode) {
1275     default: llvm_unreachable("Unhandled code!");
1276     case tgtok::XDag:
1277       Code = TernOpInit::DAG;
1278       Type = DagRecTy::get();
1279       ItemType = nullptr;
1280       break;
1281     case tgtok::XIf:
1282       Code = TernOpInit::IF;
1283       break;
1284     case tgtok::XSubst:
1285       Code = TernOpInit::SUBST;
1286       break;
1287     }
1288     if (Lex.getCode() != tgtok::l_paren) {
1289       TokError("expected '(' after ternary operator");
1290       return nullptr;
1291     }
1292     Lex.Lex();  // eat the '('
1293 
1294     Init *LHS = ParseValue(CurRec);
1295     if (!LHS) return nullptr;
1296 
1297     if (Lex.getCode() != tgtok::comma) {
1298       TokError("expected ',' in ternary operator");
1299       return nullptr;
1300     }
1301     Lex.Lex();  // eat the ','
1302 
1303     SMLoc MHSLoc = Lex.getLoc();
1304     Init *MHS = ParseValue(CurRec, ItemType);
1305     if (!MHS)
1306       return nullptr;
1307 
1308     if (Lex.getCode() != tgtok::comma) {
1309       TokError("expected ',' in ternary operator");
1310       return nullptr;
1311     }
1312     Lex.Lex();  // eat the ','
1313 
1314     SMLoc RHSLoc = Lex.getLoc();
1315     Init *RHS = ParseValue(CurRec, ItemType);
1316     if (!RHS)
1317       return nullptr;
1318 
1319     if (Lex.getCode() != tgtok::r_paren) {
1320       TokError("expected ')' in binary operator");
1321       return nullptr;
1322     }
1323     Lex.Lex();  // eat the ')'
1324 
1325     switch (LexCode) {
1326     default: llvm_unreachable("Unhandled code!");
1327     case tgtok::XDag: {
1328       TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1329       if (!MHSt && !isa<UnsetInit>(MHS)) {
1330         Error(MHSLoc, "could not determine type of the child list in !dag");
1331         return nullptr;
1332       }
1333       if (MHSt && !isa<ListRecTy>(MHSt->getType())) {
1334         Error(MHSLoc, Twine("expected list of children, got type '") +
1335                           MHSt->getType()->getAsString() + "'");
1336         return nullptr;
1337       }
1338 
1339       TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1340       if (!RHSt && !isa<UnsetInit>(RHS)) {
1341         Error(RHSLoc, "could not determine type of the name list in !dag");
1342         return nullptr;
1343       }
1344       if (RHSt && StringRecTy::get()->getListTy() != RHSt->getType()) {
1345         Error(RHSLoc, Twine("expected list<string>, got type '") +
1346                           RHSt->getType()->getAsString() + "'");
1347         return nullptr;
1348       }
1349 
1350       if (!MHSt && !RHSt) {
1351         Error(MHSLoc,
1352               "cannot have both unset children and unset names in !dag");
1353         return nullptr;
1354       }
1355       break;
1356     }
1357     case tgtok::XIf: {
1358       RecTy *MHSTy = nullptr;
1359       RecTy *RHSTy = nullptr;
1360 
1361       if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1362         MHSTy = MHSt->getType();
1363       if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1364         MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1365       if (isa<BitInit>(MHS))
1366         MHSTy = BitRecTy::get();
1367 
1368       if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1369         RHSTy = RHSt->getType();
1370       if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1371         RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1372       if (isa<BitInit>(RHS))
1373         RHSTy = BitRecTy::get();
1374 
1375       // For UnsetInit, it's typed from the other hand.
1376       if (isa<UnsetInit>(MHS))
1377         MHSTy = RHSTy;
1378       if (isa<UnsetInit>(RHS))
1379         RHSTy = MHSTy;
1380 
1381       if (!MHSTy || !RHSTy) {
1382         TokError("could not get type for !if");
1383         return nullptr;
1384       }
1385 
1386       Type = resolveTypes(MHSTy, RHSTy);
1387       if (!Type) {
1388         TokError(Twine("inconsistent types '") + MHSTy->getAsString() +
1389                  "' and '" + RHSTy->getAsString() + "' for !if");
1390         return nullptr;
1391       }
1392       break;
1393     }
1394     case tgtok::XSubst: {
1395       TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1396       if (!RHSt) {
1397         TokError("could not get type for !subst");
1398         return nullptr;
1399       }
1400       Type = RHSt->getType();
1401       break;
1402     }
1403     }
1404     return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
1405   }
1406 
1407   case tgtok::XFoldl: {
1408     // Value ::= !foldl '(' Id ',' Id ',' Value ',' Value ',' Value ')'
1409     Lex.Lex(); // eat the operation
1410     if (Lex.getCode() != tgtok::l_paren) {
1411       TokError("expected '(' after !foldl");
1412       return nullptr;
1413     }
1414     Lex.Lex(); // eat the '('
1415 
1416     Init *StartUntyped = ParseValue(CurRec);
1417     if (!StartUntyped)
1418       return nullptr;
1419 
1420     TypedInit *Start = dyn_cast<TypedInit>(StartUntyped);
1421     if (!Start) {
1422       TokError(Twine("could not get type of !foldl start: '") +
1423                StartUntyped->getAsString() + "'");
1424       return nullptr;
1425     }
1426 
1427     if (Lex.getCode() != tgtok::comma) {
1428       TokError("expected ',' in !foldl");
1429       return nullptr;
1430     }
1431     Lex.Lex(); // eat the ','
1432 
1433     Init *ListUntyped = ParseValue(CurRec);
1434     if (!ListUntyped)
1435       return nullptr;
1436 
1437     TypedInit *List = dyn_cast<TypedInit>(ListUntyped);
1438     if (!List) {
1439       TokError(Twine("could not get type of !foldl list: '") +
1440                ListUntyped->getAsString() + "'");
1441       return nullptr;
1442     }
1443 
1444     ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType());
1445     if (!ListType) {
1446       TokError(Twine("!foldl list must be a list, but is of type '") +
1447                List->getType()->getAsString());
1448       return nullptr;
1449     }
1450 
1451     if (Lex.getCode() != tgtok::comma) {
1452       TokError("expected ',' in !foldl");
1453       return nullptr;
1454     }
1455 
1456     if (Lex.Lex() != tgtok::Id) { // eat the ','
1457       TokError("third argument of !foldl must be an identifier");
1458       return nullptr;
1459     }
1460 
1461     Init *A = StringInit::get(Lex.getCurStrVal());
1462     if (CurRec->getValue(A)) {
1463       TokError((Twine("left !foldl variable '") + A->getAsString() +
1464                 "' already defined")
1465                    .str());
1466       return nullptr;
1467     }
1468 
1469     if (Lex.Lex() != tgtok::comma) { // eat the id
1470       TokError("expected ',' in !foldl");
1471       return nullptr;
1472     }
1473 
1474     if (Lex.Lex() != tgtok::Id) { // eat the ','
1475       TokError("fourth argument of !foldl must be an identifier");
1476       return nullptr;
1477     }
1478 
1479     Init *B = StringInit::get(Lex.getCurStrVal());
1480     if (CurRec->getValue(B)) {
1481       TokError((Twine("right !foldl variable '") + B->getAsString() +
1482                 "' already defined")
1483                    .str());
1484       return nullptr;
1485     }
1486 
1487     if (Lex.Lex() != tgtok::comma) { // eat the id
1488       TokError("expected ',' in !foldl");
1489       return nullptr;
1490     }
1491     Lex.Lex(); // eat the ','
1492 
1493     CurRec->addValue(RecordVal(A, Start->getType(), false));
1494     CurRec->addValue(RecordVal(B, ListType->getElementType(), false));
1495     Init *ExprUntyped = ParseValue(CurRec);
1496     CurRec->removeValue(A);
1497     CurRec->removeValue(B);
1498     if (!ExprUntyped)
1499       return nullptr;
1500 
1501     TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped);
1502     if (!Expr) {
1503       TokError("could not get type of !foldl expression");
1504       return nullptr;
1505     }
1506 
1507     if (Expr->getType() != Start->getType()) {
1508       TokError(Twine("!foldl expression must be of same type as start (") +
1509                Start->getType()->getAsString() + "), but is of type " +
1510                Expr->getType()->getAsString());
1511       return nullptr;
1512     }
1513 
1514     if (Lex.getCode() != tgtok::r_paren) {
1515       TokError("expected ')' in fold operator");
1516       return nullptr;
1517     }
1518     Lex.Lex(); // eat the ')'
1519 
1520     return FoldOpInit::get(Start, List, A, B, Expr, Start->getType())
1521         ->Fold(CurRec);
1522   }
1523   }
1524 }
1525 
1526 /// ParseOperatorType - Parse a type for an operator.  This returns
1527 /// null on error.
1528 ///
1529 /// OperatorType ::= '<' Type '>'
1530 ///
1531 RecTy *TGParser::ParseOperatorType() {
1532   RecTy *Type = nullptr;
1533 
1534   if (Lex.getCode() != tgtok::less) {
1535     TokError("expected type name for operator");
1536     return nullptr;
1537   }
1538   Lex.Lex();  // eat the <
1539 
1540   Type = ParseType();
1541 
1542   if (!Type) {
1543     TokError("expected type name for operator");
1544     return nullptr;
1545   }
1546 
1547   if (Lex.getCode() != tgtok::greater) {
1548     TokError("expected type name for operator");
1549     return nullptr;
1550   }
1551   Lex.Lex();  // eat the >
1552 
1553   return Type;
1554 }
1555 
1556 /// ParseSimpleValue - Parse a tblgen value.  This returns null on error.
1557 ///
1558 ///   SimpleValue ::= IDValue
1559 ///   SimpleValue ::= INTVAL
1560 ///   SimpleValue ::= STRVAL+
1561 ///   SimpleValue ::= CODEFRAGMENT
1562 ///   SimpleValue ::= '?'
1563 ///   SimpleValue ::= '{' ValueList '}'
1564 ///   SimpleValue ::= ID '<' ValueListNE '>'
1565 ///   SimpleValue ::= '[' ValueList ']'
1566 ///   SimpleValue ::= '(' IDValue DagArgList ')'
1567 ///   SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1568 ///   SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1569 ///   SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1570 ///   SimpleValue ::= SRATOK '(' Value ',' Value ')'
1571 ///   SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1572 ///   SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1573 ///   SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1574 ///
1575 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1576                                  IDParseMode Mode) {
1577   Init *R = nullptr;
1578   switch (Lex.getCode()) {
1579   default: TokError("Unknown token when parsing a value"); break;
1580   case tgtok::paste:
1581     // This is a leading paste operation.  This is deprecated but
1582     // still exists in some .td files.  Ignore it.
1583     Lex.Lex();  // Skip '#'.
1584     return ParseSimpleValue(CurRec, ItemType, Mode);
1585   case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1586   case tgtok::BinaryIntVal: {
1587     auto BinaryVal = Lex.getCurBinaryIntVal();
1588     SmallVector<Init*, 16> Bits(BinaryVal.second);
1589     for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
1590       Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
1591     R = BitsInit::get(Bits);
1592     Lex.Lex();
1593     break;
1594   }
1595   case tgtok::StrVal: {
1596     std::string Val = Lex.getCurStrVal();
1597     Lex.Lex();
1598 
1599     // Handle multiple consecutive concatenated strings.
1600     while (Lex.getCode() == tgtok::StrVal) {
1601       Val += Lex.getCurStrVal();
1602       Lex.Lex();
1603     }
1604 
1605     R = StringInit::get(Val);
1606     break;
1607   }
1608   case tgtok::CodeFragment:
1609     R = CodeInit::get(Lex.getCurStrVal());
1610     Lex.Lex();
1611     break;
1612   case tgtok::question:
1613     R = UnsetInit::get();
1614     Lex.Lex();
1615     break;
1616   case tgtok::Id: {
1617     SMLoc NameLoc = Lex.getLoc();
1618     StringInit *Name = StringInit::get(Lex.getCurStrVal());
1619     if (Lex.Lex() != tgtok::less)  // consume the Id.
1620       return ParseIDValue(CurRec, Name, NameLoc, Mode);    // Value ::= IDValue
1621 
1622     // Value ::= ID '<' ValueListNE '>'
1623     if (Lex.Lex() == tgtok::greater) {
1624       TokError("expected non-empty value list");
1625       return nullptr;
1626     }
1627 
1628     // This is a CLASS<initvalslist> expression.  This is supposed to synthesize
1629     // a new anonymous definition, deriving from CLASS<initvalslist> with no
1630     // body.
1631     Record *Class = Records.getClass(Name->getValue());
1632     if (!Class) {
1633       Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'");
1634       return nullptr;
1635     }
1636 
1637     SmallVector<Init *, 8> Args;
1638     ParseValueList(Args, CurRec, Class);
1639     if (Args.empty()) return nullptr;
1640 
1641     if (Lex.getCode() != tgtok::greater) {
1642       TokError("expected '>' at end of value list");
1643       return nullptr;
1644     }
1645     Lex.Lex();  // eat the '>'
1646 
1647     // Typecheck the template arguments list
1648     ArrayRef<Init *> ExpectedArgs = Class->getTemplateArgs();
1649     if (ExpectedArgs.size() < Args.size()) {
1650       Error(NameLoc,
1651             "More template args specified than expected");
1652       return nullptr;
1653     }
1654 
1655     for (unsigned i = 0, e = ExpectedArgs.size(); i != e; ++i) {
1656       RecordVal *ExpectedArg = Class->getValue(ExpectedArgs[i]);
1657       if (i < Args.size()) {
1658         if (TypedInit *TI = dyn_cast<TypedInit>(Args[i])) {
1659           RecTy *ExpectedType = ExpectedArg->getType();
1660           if (!TI->getType()->typeIsConvertibleTo(ExpectedType)) {
1661             Error(NameLoc,
1662                   "Value specified for template argument #" + Twine(i) + " (" +
1663                   ExpectedArg->getNameInitAsString() + ") is of type '" +
1664                   TI->getType()->getAsString() + "', expected '" +
1665                   ExpectedType->getAsString() + "': " + TI->getAsString());
1666             return nullptr;
1667           }
1668           continue;
1669         }
1670       } else if (ExpectedArg->getValue()->isComplete())
1671         continue;
1672 
1673       Error(NameLoc,
1674             "Value not specified for template argument #" + Twine(i) + " (" +
1675             ExpectedArgs[i]->getAsUnquotedString() + ")");
1676       return nullptr;
1677     }
1678 
1679     return VarDefInit::get(Class, Args)->Fold();
1680   }
1681   case tgtok::l_brace: {           // Value ::= '{' ValueList '}'
1682     SMLoc BraceLoc = Lex.getLoc();
1683     Lex.Lex(); // eat the '{'
1684     SmallVector<Init*, 16> Vals;
1685 
1686     if (Lex.getCode() != tgtok::r_brace) {
1687       ParseValueList(Vals, CurRec);
1688       if (Vals.empty()) return nullptr;
1689     }
1690     if (Lex.getCode() != tgtok::r_brace) {
1691       TokError("expected '}' at end of bit list value");
1692       return nullptr;
1693     }
1694     Lex.Lex();  // eat the '}'
1695 
1696     SmallVector<Init *, 16> NewBits;
1697 
1698     // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1699     // first.  We'll first read everything in to a vector, then we can reverse
1700     // it to get the bits in the correct order for the BitsInit value.
1701     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1702       // FIXME: The following two loops would not be duplicated
1703       //        if the API was a little more orthogonal.
1704 
1705       // bits<n> values are allowed to initialize n bits.
1706       if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
1707         for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
1708           NewBits.push_back(BI->getBit((e - i) - 1));
1709         continue;
1710       }
1711       // bits<n> can also come from variable initializers.
1712       if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
1713         if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
1714           for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
1715             NewBits.push_back(VI->getBit((e - i) - 1));
1716           continue;
1717         }
1718         // Fallthrough to try convert this to a bit.
1719       }
1720       // All other values must be convertible to just a single bit.
1721       Init *Bit = Vals[i]->getCastTo(BitRecTy::get());
1722       if (!Bit) {
1723         Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
1724               ") is not convertable to a bit");
1725         return nullptr;
1726       }
1727       NewBits.push_back(Bit);
1728     }
1729     std::reverse(NewBits.begin(), NewBits.end());
1730     return BitsInit::get(NewBits);
1731   }
1732   case tgtok::l_square: {          // Value ::= '[' ValueList ']'
1733     Lex.Lex(); // eat the '['
1734     SmallVector<Init*, 16> Vals;
1735 
1736     RecTy *DeducedEltTy = nullptr;
1737     ListRecTy *GivenListTy = nullptr;
1738 
1739     if (ItemType) {
1740       ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1741       if (!ListType) {
1742         TokError(Twine("Type mismatch for list, expected list type, got ") +
1743                  ItemType->getAsString());
1744         return nullptr;
1745       }
1746       GivenListTy = ListType;
1747     }
1748 
1749     if (Lex.getCode() != tgtok::r_square) {
1750       ParseValueList(Vals, CurRec, nullptr,
1751                      GivenListTy ? GivenListTy->getElementType() : nullptr);
1752       if (Vals.empty()) return nullptr;
1753     }
1754     if (Lex.getCode() != tgtok::r_square) {
1755       TokError("expected ']' at end of list value");
1756       return nullptr;
1757     }
1758     Lex.Lex();  // eat the ']'
1759 
1760     RecTy *GivenEltTy = nullptr;
1761     if (Lex.getCode() == tgtok::less) {
1762       // Optional list element type
1763       Lex.Lex();  // eat the '<'
1764 
1765       GivenEltTy = ParseType();
1766       if (!GivenEltTy) {
1767         // Couldn't parse element type
1768         return nullptr;
1769       }
1770 
1771       if (Lex.getCode() != tgtok::greater) {
1772         TokError("expected '>' at end of list element type");
1773         return nullptr;
1774       }
1775       Lex.Lex();  // eat the '>'
1776     }
1777 
1778     // Check elements
1779     RecTy *EltTy = nullptr;
1780     for (Init *V : Vals) {
1781       TypedInit *TArg = dyn_cast<TypedInit>(V);
1782       if (TArg) {
1783         if (EltTy) {
1784           EltTy = resolveTypes(EltTy, TArg->getType());
1785           if (!EltTy) {
1786             TokError("Incompatible types in list elements");
1787             return nullptr;
1788           }
1789         } else {
1790           EltTy = TArg->getType();
1791         }
1792       }
1793     }
1794 
1795     if (GivenEltTy) {
1796       if (EltTy) {
1797         // Verify consistency
1798         if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1799           TokError("Incompatible types in list elements");
1800           return nullptr;
1801         }
1802       }
1803       EltTy = GivenEltTy;
1804     }
1805 
1806     if (!EltTy) {
1807       if (!ItemType) {
1808         TokError("No type for list");
1809         return nullptr;
1810       }
1811       DeducedEltTy = GivenListTy->getElementType();
1812     } else {
1813       // Make sure the deduced type is compatible with the given type
1814       if (GivenListTy) {
1815         if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1816           TokError(Twine("Element type mismatch for list: element type '") +
1817                    EltTy->getAsString() + "' not convertible to '" +
1818                    GivenListTy->getElementType()->getAsString());
1819           return nullptr;
1820         }
1821       }
1822       DeducedEltTy = EltTy;
1823     }
1824 
1825     return ListInit::get(Vals, DeducedEltTy);
1826   }
1827   case tgtok::l_paren: {         // Value ::= '(' IDValue DagArgList ')'
1828     Lex.Lex();   // eat the '('
1829     if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1830       TokError("expected identifier in dag init");
1831       return nullptr;
1832     }
1833 
1834     Init *Operator = ParseValue(CurRec);
1835     if (!Operator) return nullptr;
1836 
1837     // If the operator name is present, parse it.
1838     StringInit *OperatorName = nullptr;
1839     if (Lex.getCode() == tgtok::colon) {
1840       if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1841         TokError("expected variable name in dag operator");
1842         return nullptr;
1843       }
1844       OperatorName = StringInit::get(Lex.getCurStrVal());
1845       Lex.Lex();  // eat the VarName.
1846     }
1847 
1848     SmallVector<std::pair<llvm::Init*, StringInit*>, 8> DagArgs;
1849     if (Lex.getCode() != tgtok::r_paren) {
1850       ParseDagArgList(DagArgs, CurRec);
1851       if (DagArgs.empty()) return nullptr;
1852     }
1853 
1854     if (Lex.getCode() != tgtok::r_paren) {
1855       TokError("expected ')' in dag init");
1856       return nullptr;
1857     }
1858     Lex.Lex();  // eat the ')'
1859 
1860     return DagInit::get(Operator, OperatorName, DagArgs);
1861   }
1862 
1863   case tgtok::XHead:
1864   case tgtok::XTail:
1865   case tgtok::XSize:
1866   case tgtok::XEmpty:
1867   case tgtok::XCast:  // Value ::= !unop '(' Value ')'
1868   case tgtok::XIsA:
1869   case tgtok::XConcat:
1870   case tgtok::XDag:
1871   case tgtok::XADD:
1872   case tgtok::XAND:
1873   case tgtok::XOR:
1874   case tgtok::XSRA:
1875   case tgtok::XSRL:
1876   case tgtok::XSHL:
1877   case tgtok::XEq:
1878   case tgtok::XNe:
1879   case tgtok::XLe:
1880   case tgtok::XLt:
1881   case tgtok::XGe:
1882   case tgtok::XGt:
1883   case tgtok::XListConcat:
1884   case tgtok::XStrConcat:   // Value ::= !binop '(' Value ',' Value ')'
1885   case tgtok::XIf:
1886   case tgtok::XFoldl:
1887   case tgtok::XForEach:
1888   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1889     return ParseOperation(CurRec, ItemType);
1890   }
1891   }
1892 
1893   return R;
1894 }
1895 
1896 /// ParseValue - Parse a tblgen value.  This returns null on error.
1897 ///
1898 ///   Value       ::= SimpleValue ValueSuffix*
1899 ///   ValueSuffix ::= '{' BitList '}'
1900 ///   ValueSuffix ::= '[' BitList ']'
1901 ///   ValueSuffix ::= '.' ID
1902 ///
1903 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1904   Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1905   if (!Result) return nullptr;
1906 
1907   // Parse the suffixes now if present.
1908   while (true) {
1909     switch (Lex.getCode()) {
1910     default: return Result;
1911     case tgtok::l_brace: {
1912       if (Mode == ParseNameMode)
1913         // This is the beginning of the object body.
1914         return Result;
1915 
1916       SMLoc CurlyLoc = Lex.getLoc();
1917       Lex.Lex(); // eat the '{'
1918       SmallVector<unsigned, 16> Ranges;
1919       ParseRangeList(Ranges);
1920       if (Ranges.empty()) return nullptr;
1921 
1922       // Reverse the bitlist.
1923       std::reverse(Ranges.begin(), Ranges.end());
1924       Result = Result->convertInitializerBitRange(Ranges);
1925       if (!Result) {
1926         Error(CurlyLoc, "Invalid bit range for value");
1927         return nullptr;
1928       }
1929 
1930       // Eat the '}'.
1931       if (Lex.getCode() != tgtok::r_brace) {
1932         TokError("expected '}' at end of bit range list");
1933         return nullptr;
1934       }
1935       Lex.Lex();
1936       break;
1937     }
1938     case tgtok::l_square: {
1939       SMLoc SquareLoc = Lex.getLoc();
1940       Lex.Lex(); // eat the '['
1941       SmallVector<unsigned, 16> Ranges;
1942       ParseRangeList(Ranges);
1943       if (Ranges.empty()) return nullptr;
1944 
1945       Result = Result->convertInitListSlice(Ranges);
1946       if (!Result) {
1947         Error(SquareLoc, "Invalid range for list slice");
1948         return nullptr;
1949       }
1950 
1951       // Eat the ']'.
1952       if (Lex.getCode() != tgtok::r_square) {
1953         TokError("expected ']' at end of list slice");
1954         return nullptr;
1955       }
1956       Lex.Lex();
1957       break;
1958     }
1959     case tgtok::period: {
1960       if (Lex.Lex() != tgtok::Id) {  // eat the .
1961         TokError("expected field identifier after '.'");
1962         return nullptr;
1963       }
1964       StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
1965       if (!Result->getFieldType(FieldName)) {
1966         TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1967                  Result->getAsString() + "'");
1968         return nullptr;
1969       }
1970       Result = FieldInit::get(Result, FieldName)->Fold(CurRec);
1971       Lex.Lex();  // eat field name
1972       break;
1973     }
1974 
1975     case tgtok::paste:
1976       SMLoc PasteLoc = Lex.getLoc();
1977 
1978       // Create a !strconcat() operation, first casting each operand to
1979       // a string if necessary.
1980 
1981       TypedInit *LHS = dyn_cast<TypedInit>(Result);
1982       if (!LHS) {
1983         Error(PasteLoc, "LHS of paste is not typed!");
1984         return nullptr;
1985       }
1986 
1987       if (LHS->getType() != StringRecTy::get()) {
1988         LHS = dyn_cast<TypedInit>(
1989             UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get())
1990                 ->Fold(CurRec));
1991         if (!LHS) {
1992           Error(PasteLoc, Twine("can't cast '") + LHS->getAsString() +
1993                               "' to string");
1994           return nullptr;
1995         }
1996       }
1997 
1998       TypedInit *RHS = nullptr;
1999 
2000       Lex.Lex();  // Eat the '#'.
2001       switch (Lex.getCode()) {
2002       case tgtok::colon:
2003       case tgtok::semi:
2004       case tgtok::l_brace:
2005         // These are all of the tokens that can begin an object body.
2006         // Some of these can also begin values but we disallow those cases
2007         // because they are unlikely to be useful.
2008 
2009         // Trailing paste, concat with an empty string.
2010         RHS = StringInit::get("");
2011         break;
2012 
2013       default:
2014         Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode);
2015         RHS = dyn_cast<TypedInit>(RHSResult);
2016         if (!RHS) {
2017           Error(PasteLoc, "RHS of paste is not typed!");
2018           return nullptr;
2019         }
2020 
2021         if (RHS->getType() != StringRecTy::get()) {
2022           RHS = dyn_cast<TypedInit>(
2023               UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get())
2024                   ->Fold(CurRec));
2025           if (!RHS) {
2026             Error(PasteLoc, Twine("can't cast '") + RHS->getAsString() +
2027                                 "' to string");
2028             return nullptr;
2029           }
2030         }
2031 
2032         break;
2033       }
2034 
2035       Result = BinOpInit::getStrConcat(LHS, RHS);
2036       break;
2037     }
2038   }
2039 }
2040 
2041 /// ParseDagArgList - Parse the argument list for a dag literal expression.
2042 ///
2043 ///    DagArg     ::= Value (':' VARNAME)?
2044 ///    DagArg     ::= VARNAME
2045 ///    DagArgList ::= DagArg
2046 ///    DagArgList ::= DagArgList ',' DagArg
2047 void TGParser::ParseDagArgList(
2048     SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result,
2049     Record *CurRec) {
2050 
2051   while (true) {
2052     // DagArg ::= VARNAME
2053     if (Lex.getCode() == tgtok::VarName) {
2054       // A missing value is treated like '?'.
2055       StringInit *VarName = StringInit::get(Lex.getCurStrVal());
2056       Result.emplace_back(UnsetInit::get(), VarName);
2057       Lex.Lex();
2058     } else {
2059       // DagArg ::= Value (':' VARNAME)?
2060       Init *Val = ParseValue(CurRec);
2061       if (!Val) {
2062         Result.clear();
2063         return;
2064       }
2065 
2066       // If the variable name is present, add it.
2067       StringInit *VarName = nullptr;
2068       if (Lex.getCode() == tgtok::colon) {
2069         if (Lex.Lex() != tgtok::VarName) { // eat the ':'
2070           TokError("expected variable name in dag literal");
2071           Result.clear();
2072           return;
2073         }
2074         VarName = StringInit::get(Lex.getCurStrVal());
2075         Lex.Lex();  // eat the VarName.
2076       }
2077 
2078       Result.push_back(std::make_pair(Val, VarName));
2079     }
2080     if (Lex.getCode() != tgtok::comma) break;
2081     Lex.Lex(); // eat the ','
2082   }
2083 }
2084 
2085 /// ParseValueList - Parse a comma separated list of values, returning them as a
2086 /// vector.  Note that this always expects to be able to parse at least one
2087 /// value.  It returns an empty list if this is not possible.
2088 ///
2089 ///   ValueList ::= Value (',' Value)
2090 ///
2091 void TGParser::ParseValueList(SmallVectorImpl<Init*> &Result, Record *CurRec,
2092                               Record *ArgsRec, RecTy *EltTy) {
2093   RecTy *ItemType = EltTy;
2094   unsigned int ArgN = 0;
2095   if (ArgsRec && !EltTy) {
2096     ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2097     if (TArgs.empty()) {
2098       TokError("template argument provided to non-template class");
2099       Result.clear();
2100       return;
2101     }
2102     const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2103     if (!RV) {
2104       errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
2105         << ")\n";
2106     }
2107     assert(RV && "Template argument record not found??");
2108     ItemType = RV->getType();
2109     ++ArgN;
2110   }
2111   Result.push_back(ParseValue(CurRec, ItemType));
2112   if (!Result.back()) {
2113     Result.clear();
2114     return;
2115   }
2116 
2117   while (Lex.getCode() == tgtok::comma) {
2118     Lex.Lex();  // Eat the comma
2119 
2120     if (ArgsRec && !EltTy) {
2121       ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2122       if (ArgN >= TArgs.size()) {
2123         TokError("too many template arguments");
2124         Result.clear();
2125         return;
2126       }
2127       const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2128       assert(RV && "Template argument record not found??");
2129       ItemType = RV->getType();
2130       ++ArgN;
2131     }
2132     Result.push_back(ParseValue(CurRec, ItemType));
2133     if (!Result.back()) {
2134       Result.clear();
2135       return;
2136     }
2137   }
2138 }
2139 
2140 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
2141 /// empty string on error.  This can happen in a number of different context's,
2142 /// including within a def or in the template args for a def (which which case
2143 /// CurRec will be non-null) and within the template args for a multiclass (in
2144 /// which case CurRec will be null, but CurMultiClass will be set).  This can
2145 /// also happen within a def that is within a multiclass, which will set both
2146 /// CurRec and CurMultiClass.
2147 ///
2148 ///  Declaration ::= FIELD? Type ID ('=' Value)?
2149 ///
2150 Init *TGParser::ParseDeclaration(Record *CurRec,
2151                                        bool ParsingTemplateArgs) {
2152   // Read the field prefix if present.
2153   bool HasField = Lex.getCode() == tgtok::Field;
2154   if (HasField) Lex.Lex();
2155 
2156   RecTy *Type = ParseType();
2157   if (!Type) return nullptr;
2158 
2159   if (Lex.getCode() != tgtok::Id) {
2160     TokError("Expected identifier in declaration");
2161     return nullptr;
2162   }
2163 
2164   SMLoc IdLoc = Lex.getLoc();
2165   Init *DeclName = StringInit::get(Lex.getCurStrVal());
2166   Lex.Lex();
2167 
2168   if (ParsingTemplateArgs) {
2169     if (CurRec)
2170       DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
2171     else
2172       assert(CurMultiClass);
2173     if (CurMultiClass)
2174       DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
2175                              "::");
2176   }
2177 
2178   // Add the value.
2179   if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
2180     return nullptr;
2181 
2182   // If a value is present, parse it.
2183   if (Lex.getCode() == tgtok::equal) {
2184     Lex.Lex();
2185     SMLoc ValLoc = Lex.getLoc();
2186     Init *Val = ParseValue(CurRec, Type);
2187     if (!Val ||
2188         SetValue(CurRec, ValLoc, DeclName, None, Val))
2189       // Return the name, even if an error is thrown.  This is so that we can
2190       // continue to make some progress, even without the value having been
2191       // initialized.
2192       return DeclName;
2193   }
2194 
2195   return DeclName;
2196 }
2197 
2198 /// ParseForeachDeclaration - Read a foreach declaration, returning
2199 /// the name of the declared object or a NULL Init on error.  Return
2200 /// the name of the parsed initializer list through ForeachListName.
2201 ///
2202 ///  ForeachDeclaration ::= ID '=' '{' RangeList '}'
2203 ///  ForeachDeclaration ::= ID '=' RangePiece
2204 ///  ForeachDeclaration ::= ID '=' Value
2205 ///
2206 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
2207   if (Lex.getCode() != tgtok::Id) {
2208     TokError("Expected identifier in foreach declaration");
2209     return nullptr;
2210   }
2211 
2212   Init *DeclName = StringInit::get(Lex.getCurStrVal());
2213   Lex.Lex();
2214 
2215   // If a value is present, parse it.
2216   if (Lex.getCode() != tgtok::equal) {
2217     TokError("Expected '=' in foreach declaration");
2218     return nullptr;
2219   }
2220   Lex.Lex();  // Eat the '='
2221 
2222   RecTy *IterType = nullptr;
2223   SmallVector<unsigned, 16> Ranges;
2224 
2225   switch (Lex.getCode()) {
2226   case tgtok::IntVal: { // RangePiece.
2227     if (ParseRangePiece(Ranges))
2228       return nullptr;
2229     break;
2230   }
2231 
2232   case tgtok::l_brace: { // '{' RangeList '}'
2233     Lex.Lex(); // eat the '{'
2234     ParseRangeList(Ranges);
2235     if (Lex.getCode() != tgtok::r_brace) {
2236       TokError("expected '}' at end of bit range list");
2237       return nullptr;
2238     }
2239     Lex.Lex();
2240     break;
2241   }
2242 
2243   default: {
2244     SMLoc ValueLoc = Lex.getLoc();
2245     Init *I = ParseValue(nullptr);
2246     if (!isa<ListInit>(I)) {
2247       std::string Type;
2248       if (TypedInit *TI = dyn_cast<TypedInit>(I))
2249         Type = (Twine("' of type '") + TI->getType()->getAsString()).str();
2250       Error(ValueLoc, "expected a list, got '" + I->getAsString() + Type + "'");
2251       if (CurMultiClass)
2252         PrintNote({}, "references to multiclass template arguments cannot be "
2253                       "resolved at this time");
2254       return nullptr;
2255     }
2256     ForeachListValue = dyn_cast<ListInit>(I);
2257     IterType = ForeachListValue->getElementType();
2258     break;
2259   }
2260   }
2261 
2262   if (!Ranges.empty()) {
2263     assert(!IterType && "Type already initialized?");
2264     IterType = IntRecTy::get();
2265     std::vector<Init*> Values;
2266     for (unsigned R : Ranges)
2267       Values.push_back(IntInit::get(R));
2268     ForeachListValue = ListInit::get(Values, IterType);
2269   }
2270 
2271   if (!IterType)
2272     return nullptr;
2273 
2274   return VarInit::get(DeclName, IterType);
2275 }
2276 
2277 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
2278 /// sequence of template-declarations in <>'s.  If CurRec is non-null, these are
2279 /// template args for a def, which may or may not be in a multiclass.  If null,
2280 /// these are the template args for a multiclass.
2281 ///
2282 ///    TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
2283 ///
2284 bool TGParser::ParseTemplateArgList(Record *CurRec) {
2285   assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
2286   Lex.Lex(); // eat the '<'
2287 
2288   Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
2289 
2290   // Read the first declaration.
2291   Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2292   if (!TemplArg)
2293     return true;
2294 
2295   TheRecToAddTo->addTemplateArg(TemplArg);
2296 
2297   while (Lex.getCode() == tgtok::comma) {
2298     Lex.Lex(); // eat the ','
2299 
2300     // Read the following declarations.
2301     TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2302     if (!TemplArg)
2303       return true;
2304     TheRecToAddTo->addTemplateArg(TemplArg);
2305   }
2306 
2307   if (Lex.getCode() != tgtok::greater)
2308     return TokError("expected '>' at end of template argument list");
2309   Lex.Lex(); // eat the '>'.
2310   return false;
2311 }
2312 
2313 /// ParseBodyItem - Parse a single item at within the body of a def or class.
2314 ///
2315 ///   BodyItem ::= Declaration ';'
2316 ///   BodyItem ::= LET ID OptionalBitList '=' Value ';'
2317 bool TGParser::ParseBodyItem(Record *CurRec) {
2318   if (Lex.getCode() != tgtok::Let) {
2319     if (!ParseDeclaration(CurRec, false))
2320       return true;
2321 
2322     if (Lex.getCode() != tgtok::semi)
2323       return TokError("expected ';' after declaration");
2324     Lex.Lex();
2325     return false;
2326   }
2327 
2328   // LET ID OptionalRangeList '=' Value ';'
2329   if (Lex.Lex() != tgtok::Id)
2330     return TokError("expected field identifier after let");
2331 
2332   SMLoc IdLoc = Lex.getLoc();
2333   StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2334   Lex.Lex();  // eat the field name.
2335 
2336   SmallVector<unsigned, 16> BitList;
2337   if (ParseOptionalBitList(BitList))
2338     return true;
2339   std::reverse(BitList.begin(), BitList.end());
2340 
2341   if (Lex.getCode() != tgtok::equal)
2342     return TokError("expected '=' in let expression");
2343   Lex.Lex();  // eat the '='.
2344 
2345   RecordVal *Field = CurRec->getValue(FieldName);
2346   if (!Field)
2347     return TokError("Value '" + FieldName->getValue() + "' unknown!");
2348 
2349   RecTy *Type = Field->getType();
2350 
2351   Init *Val = ParseValue(CurRec, Type);
2352   if (!Val) return true;
2353 
2354   if (Lex.getCode() != tgtok::semi)
2355     return TokError("expected ';' after let expression");
2356   Lex.Lex();
2357 
2358   return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
2359 }
2360 
2361 /// ParseBody - Read the body of a class or def.  Return true on error, false on
2362 /// success.
2363 ///
2364 ///   Body     ::= ';'
2365 ///   Body     ::= '{' BodyList '}'
2366 ///   BodyList BodyItem*
2367 ///
2368 bool TGParser::ParseBody(Record *CurRec) {
2369   // If this is a null definition, just eat the semi and return.
2370   if (Lex.getCode() == tgtok::semi) {
2371     Lex.Lex();
2372     return false;
2373   }
2374 
2375   if (Lex.getCode() != tgtok::l_brace)
2376     return TokError("Expected ';' or '{' to start body");
2377   // Eat the '{'.
2378   Lex.Lex();
2379 
2380   while (Lex.getCode() != tgtok::r_brace)
2381     if (ParseBodyItem(CurRec))
2382       return true;
2383 
2384   // Eat the '}'.
2385   Lex.Lex();
2386   return false;
2387 }
2388 
2389 /// \brief Apply the current let bindings to \a CurRec.
2390 /// \returns true on error, false otherwise.
2391 bool TGParser::ApplyLetStack(Record *CurRec) {
2392   for (SmallVectorImpl<LetRecord> &LetInfo : LetStack)
2393     for (LetRecord &LR : LetInfo)
2394       if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
2395         return true;
2396   return false;
2397 }
2398 
2399 /// ParseObjectBody - Parse the body of a def or class.  This consists of an
2400 /// optional ClassList followed by a Body.  CurRec is the current def or class
2401 /// that is being parsed.
2402 ///
2403 ///   ObjectBody      ::= BaseClassList Body
2404 ///   BaseClassList   ::= /*empty*/
2405 ///   BaseClassList   ::= ':' BaseClassListNE
2406 ///   BaseClassListNE ::= SubClassRef (',' SubClassRef)*
2407 ///
2408 bool TGParser::ParseObjectBody(Record *CurRec) {
2409   // If there is a baseclass list, read it.
2410   if (Lex.getCode() == tgtok::colon) {
2411     Lex.Lex();
2412 
2413     // Read all of the subclasses.
2414     SubClassReference SubClass = ParseSubClassReference(CurRec, false);
2415     while (true) {
2416       // Check for error.
2417       if (!SubClass.Rec) return true;
2418 
2419       // Add it.
2420       if (AddSubClass(CurRec, SubClass))
2421         return true;
2422 
2423       if (Lex.getCode() != tgtok::comma) break;
2424       Lex.Lex(); // eat ','.
2425       SubClass = ParseSubClassReference(CurRec, false);
2426     }
2427   }
2428 
2429   if (ApplyLetStack(CurRec))
2430     return true;
2431 
2432   return ParseBody(CurRec);
2433 }
2434 
2435 /// ParseDef - Parse and return a top level or multiclass def, return the record
2436 /// corresponding to it.  This returns null on error.
2437 ///
2438 ///   DefInst ::= DEF ObjectName ObjectBody
2439 ///
2440 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
2441   SMLoc DefLoc = Lex.getLoc();
2442   assert(Lex.getCode() == tgtok::Def && "Unknown tok");
2443   Lex.Lex();  // Eat the 'def' token.
2444 
2445   // Parse ObjectName and make a record for it.
2446   std::unique_ptr<Record> CurRec;
2447   Init *Name = ParseObjectName(CurMultiClass);
2448   if (!Name)
2449     return true;
2450 
2451   if (isa<UnsetInit>(Name))
2452     CurRec = make_unique<Record>(Records.getNewAnonymousName(), DefLoc, Records,
2453                                  /*Anonymous=*/true);
2454   else
2455     CurRec = make_unique<Record>(Name, DefLoc, Records);
2456 
2457   if (ParseObjectBody(CurRec.get()))
2458     return true;
2459 
2460   return addDef(std::move(CurRec), nullptr);
2461 }
2462 
2463 /// ParseDefset - Parse a defset statement.
2464 ///
2465 ///   Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
2466 ///
2467 bool TGParser::ParseDefset() {
2468   assert(Lex.getCode() == tgtok::Defset);
2469   Lex.Lex(); // Eat the 'defset' token
2470 
2471   DefsetRecord Defset;
2472   Defset.Loc = Lex.getLoc();
2473   RecTy *Type = ParseType();
2474   if (!Type)
2475     return true;
2476   if (!isa<ListRecTy>(Type))
2477     return Error(Defset.Loc, "expected list type");
2478   Defset.EltTy = cast<ListRecTy>(Type)->getElementType();
2479 
2480   if (Lex.getCode() != tgtok::Id)
2481     return TokError("expected identifier");
2482   StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
2483   if (Records.getGlobal(DeclName->getValue()))
2484     return TokError("def or global variable of this name already exists");
2485 
2486   if (Lex.Lex() != tgtok::equal) // Eat the identifier
2487     return TokError("expected '='");
2488   if (Lex.Lex() != tgtok::l_brace) // Eat the '='
2489     return TokError("expected '{'");
2490   SMLoc BraceLoc = Lex.getLoc();
2491   Lex.Lex(); // Eat the '{'
2492 
2493   Defsets.push_back(&Defset);
2494   bool Err = ParseObjectList(nullptr);
2495   Defsets.pop_back();
2496   if (Err)
2497     return true;
2498 
2499   if (Lex.getCode() != tgtok::r_brace) {
2500     TokError("expected '}' at end of defset");
2501     return Error(BraceLoc, "to match this '{'");
2502   }
2503   Lex.Lex();  // Eat the '}'
2504 
2505   Records.addExtraGlobal(DeclName->getValue(),
2506                          ListInit::get(Defset.Elements, Defset.EltTy));
2507   return false;
2508 }
2509 
2510 /// ParseForeach - Parse a for statement.  Return the record corresponding
2511 /// to it.  This returns true on error.
2512 ///
2513 ///   Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2514 ///   Foreach ::= FOREACH Declaration IN Object
2515 ///
2516 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2517   assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2518   Lex.Lex();  // Eat the 'for' token.
2519 
2520   // Make a temporary object to record items associated with the for
2521   // loop.
2522   ListInit *ListValue = nullptr;
2523   VarInit *IterName = ParseForeachDeclaration(ListValue);
2524   if (!IterName)
2525     return TokError("expected declaration in for");
2526 
2527   if (Lex.getCode() != tgtok::In)
2528     return TokError("Unknown tok");
2529   Lex.Lex();  // Eat the in
2530 
2531   // Create a loop object and remember it.
2532   Loops.push_back(ForeachLoop(IterName, ListValue));
2533 
2534   if (Lex.getCode() != tgtok::l_brace) {
2535     // FOREACH Declaration IN Object
2536     if (ParseObject(CurMultiClass))
2537       return true;
2538   } else {
2539     SMLoc BraceLoc = Lex.getLoc();
2540     // Otherwise, this is a group foreach.
2541     Lex.Lex();  // eat the '{'.
2542 
2543     // Parse the object list.
2544     if (ParseObjectList(CurMultiClass))
2545       return true;
2546 
2547     if (Lex.getCode() != tgtok::r_brace) {
2548       TokError("expected '}' at end of foreach command");
2549       return Error(BraceLoc, "to match this '{'");
2550     }
2551     Lex.Lex();  // Eat the }
2552   }
2553 
2554   // We've processed everything in this loop.
2555   Loops.pop_back();
2556 
2557   return false;
2558 }
2559 
2560 /// ParseClass - Parse a tblgen class definition.
2561 ///
2562 ///   ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2563 ///
2564 bool TGParser::ParseClass() {
2565   assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2566   Lex.Lex();
2567 
2568   if (Lex.getCode() != tgtok::Id)
2569     return TokError("expected class name after 'class' keyword");
2570 
2571   Record *CurRec = Records.getClass(Lex.getCurStrVal());
2572   if (CurRec) {
2573     // If the body was previously defined, this is an error.
2574     if (CurRec->getValues().size() > 1 ||  // Account for NAME.
2575         !CurRec->getSuperClasses().empty() ||
2576         !CurRec->getTemplateArgs().empty())
2577       return TokError("Class '" + CurRec->getNameInitAsString() +
2578                       "' already defined");
2579   } else {
2580     // If this is the first reference to this class, create and add it.
2581     auto NewRec =
2582         llvm::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records);
2583     CurRec = NewRec.get();
2584     Records.addClass(std::move(NewRec));
2585   }
2586   Lex.Lex(); // eat the name.
2587 
2588   // If there are template args, parse them.
2589   if (Lex.getCode() == tgtok::less)
2590     if (ParseTemplateArgList(CurRec))
2591       return true;
2592 
2593   // Finally, parse the object body.
2594   return ParseObjectBody(CurRec);
2595 }
2596 
2597 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2598 /// of LetRecords.
2599 ///
2600 ///   LetList ::= LetItem (',' LetItem)*
2601 ///   LetItem ::= ID OptionalRangeList '=' Value
2602 ///
2603 void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) {
2604   while (true) {
2605     if (Lex.getCode() != tgtok::Id) {
2606       TokError("expected identifier in let definition");
2607       Result.clear();
2608       return;
2609     }
2610 
2611     StringInit *Name = StringInit::get(Lex.getCurStrVal());
2612     SMLoc NameLoc = Lex.getLoc();
2613     Lex.Lex();  // Eat the identifier.
2614 
2615     // Check for an optional RangeList.
2616     SmallVector<unsigned, 16> Bits;
2617     if (ParseOptionalRangeList(Bits)) {
2618       Result.clear();
2619       return;
2620     }
2621     std::reverse(Bits.begin(), Bits.end());
2622 
2623     if (Lex.getCode() != tgtok::equal) {
2624       TokError("expected '=' in let expression");
2625       Result.clear();
2626       return;
2627     }
2628     Lex.Lex();  // eat the '='.
2629 
2630     Init *Val = ParseValue(nullptr);
2631     if (!Val) {
2632       Result.clear();
2633       return;
2634     }
2635 
2636     // Now that we have everything, add the record.
2637     Result.emplace_back(Name, Bits, Val, NameLoc);
2638 
2639     if (Lex.getCode() != tgtok::comma)
2640       return;
2641     Lex.Lex();  // eat the comma.
2642   }
2643 }
2644 
2645 /// ParseTopLevelLet - Parse a 'let' at top level.  This can be a couple of
2646 /// different related productions. This works inside multiclasses too.
2647 ///
2648 ///   Object ::= LET LetList IN '{' ObjectList '}'
2649 ///   Object ::= LET LetList IN Object
2650 ///
2651 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2652   assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2653   Lex.Lex();
2654 
2655   // Add this entry to the let stack.
2656   SmallVector<LetRecord, 8> LetInfo;
2657   ParseLetList(LetInfo);
2658   if (LetInfo.empty()) return true;
2659   LetStack.push_back(std::move(LetInfo));
2660 
2661   if (Lex.getCode() != tgtok::In)
2662     return TokError("expected 'in' at end of top-level 'let'");
2663   Lex.Lex();
2664 
2665   // If this is a scalar let, just handle it now
2666   if (Lex.getCode() != tgtok::l_brace) {
2667     // LET LetList IN Object
2668     if (ParseObject(CurMultiClass))
2669       return true;
2670   } else {   // Object ::= LETCommand '{' ObjectList '}'
2671     SMLoc BraceLoc = Lex.getLoc();
2672     // Otherwise, this is a group let.
2673     Lex.Lex();  // eat the '{'.
2674 
2675     // Parse the object list.
2676     if (ParseObjectList(CurMultiClass))
2677       return true;
2678 
2679     if (Lex.getCode() != tgtok::r_brace) {
2680       TokError("expected '}' at end of top level let command");
2681       return Error(BraceLoc, "to match this '{'");
2682     }
2683     Lex.Lex();
2684   }
2685 
2686   // Outside this let scope, this let block is not active.
2687   LetStack.pop_back();
2688   return false;
2689 }
2690 
2691 /// ParseMultiClass - Parse a multiclass definition.
2692 ///
2693 ///  MultiClassInst ::= MULTICLASS ID TemplateArgList?
2694 ///                     ':' BaseMultiClassList '{' MultiClassObject+ '}'
2695 ///  MultiClassObject ::= DefInst
2696 ///  MultiClassObject ::= MultiClassInst
2697 ///  MultiClassObject ::= DefMInst
2698 ///  MultiClassObject ::= LETCommand '{' ObjectList '}'
2699 ///  MultiClassObject ::= LETCommand Object
2700 ///
2701 bool TGParser::ParseMultiClass() {
2702   assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2703   Lex.Lex();  // Eat the multiclass token.
2704 
2705   if (Lex.getCode() != tgtok::Id)
2706     return TokError("expected identifier after multiclass for name");
2707   std::string Name = Lex.getCurStrVal();
2708 
2709   auto Result =
2710     MultiClasses.insert(std::make_pair(Name,
2711                     llvm::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
2712 
2713   if (!Result.second)
2714     return TokError("multiclass '" + Name + "' already defined");
2715 
2716   CurMultiClass = Result.first->second.get();
2717   Lex.Lex();  // Eat the identifier.
2718 
2719   // If there are template args, parse them.
2720   if (Lex.getCode() == tgtok::less)
2721     if (ParseTemplateArgList(nullptr))
2722       return true;
2723 
2724   bool inherits = false;
2725 
2726   // If there are submulticlasses, parse them.
2727   if (Lex.getCode() == tgtok::colon) {
2728     inherits = true;
2729 
2730     Lex.Lex();
2731 
2732     // Read all of the submulticlasses.
2733     SubMultiClassReference SubMultiClass =
2734       ParseSubMultiClassReference(CurMultiClass);
2735     while (true) {
2736       // Check for error.
2737       if (!SubMultiClass.MC) return true;
2738 
2739       // Add it.
2740       if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2741         return true;
2742 
2743       if (Lex.getCode() != tgtok::comma) break;
2744       Lex.Lex(); // eat ','.
2745       SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2746     }
2747   }
2748 
2749   if (Lex.getCode() != tgtok::l_brace) {
2750     if (!inherits)
2751       return TokError("expected '{' in multiclass definition");
2752     if (Lex.getCode() != tgtok::semi)
2753       return TokError("expected ';' in multiclass definition");
2754     Lex.Lex();  // eat the ';'.
2755   } else {
2756     if (Lex.Lex() == tgtok::r_brace)  // eat the '{'.
2757       return TokError("multiclass must contain at least one def");
2758 
2759     while (Lex.getCode() != tgtok::r_brace) {
2760       switch (Lex.getCode()) {
2761       default:
2762         return TokError("expected 'let', 'def', 'defm' or 'foreach' in "
2763                         "multiclass body");
2764       case tgtok::Let:
2765       case tgtok::Def:
2766       case tgtok::Defm:
2767       case tgtok::Foreach:
2768         if (ParseObject(CurMultiClass))
2769           return true;
2770         break;
2771       }
2772     }
2773     Lex.Lex();  // eat the '}'.
2774   }
2775 
2776   CurMultiClass = nullptr;
2777   return false;
2778 }
2779 
2780 /// ParseDefm - Parse the instantiation of a multiclass.
2781 ///
2782 ///   DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2783 ///
2784 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2785   assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2786   Lex.Lex(); // eat the defm
2787 
2788   Init *DefmName = ParseObjectName(CurMultiClass);
2789   if (!DefmName)
2790     return true;
2791   if (isa<UnsetInit>(DefmName))
2792     DefmName = Records.getNewAnonymousName();
2793 
2794   if (Lex.getCode() != tgtok::colon)
2795     return TokError("expected ':' after defm identifier");
2796 
2797   // Keep track of the new generated record definitions.
2798   SmallVector<std::unique_ptr<Record>, 8> NewRecDefs;
2799 
2800   // This record also inherits from a regular class (non-multiclass)?
2801   bool InheritFromClass = false;
2802 
2803   // eat the colon.
2804   Lex.Lex();
2805 
2806   SMLoc SubClassLoc = Lex.getLoc();
2807   SubClassReference Ref = ParseSubClassReference(nullptr, true);
2808 
2809   while (true) {
2810     if (!Ref.Rec) return true;
2811 
2812     // To instantiate a multiclass, we need to first get the multiclass, then
2813     // instantiate each def contained in the multiclass with the SubClassRef
2814     // template parameters.
2815     MultiClass *MC = MultiClasses[Ref.Rec->getName()].get();
2816     assert(MC && "Didn't lookup multiclass correctly?");
2817     ArrayRef<Init*> TemplateVals = Ref.TemplateArgs;
2818 
2819     // Verify that the correct number of template arguments were specified.
2820     ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs();
2821     if (TArgs.size() < TemplateVals.size())
2822       return Error(SubClassLoc,
2823                    "more template args specified than multiclass expects");
2824 
2825     DenseMap<Init *, Init *> TemplateArgs;
2826     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2827       if (i < TemplateVals.size()) {
2828         TemplateArgs.insert({TArgs[i], TemplateVals[i]});
2829       } else {
2830         Init *Default = MC->Rec.getValue(TArgs[i])->getValue();
2831         if (!Default->isComplete()) {
2832           return Error(SubClassLoc,
2833                        "value not specified for template argument #" +
2834                            Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
2835                            ") of multiclass '" + MC->Rec.getNameInitAsString() +
2836                            "'");
2837         }
2838         TemplateArgs.insert({TArgs[i], Default});
2839       }
2840     }
2841 
2842     // Loop over all the def's in the multiclass, instantiating each one.
2843     for (const std::unique_ptr<Record> &DefProto : MC->DefPrototypes) {
2844       bool ResolveName = true;
2845       auto CurRec = make_unique<Record>(*DefProto);
2846       CurRec->appendLoc(SubClassLoc);
2847 
2848       if (StringInit *NameString =
2849               dyn_cast<StringInit>(CurRec->getNameInit())) {
2850         // We have a fully expanded string so there are no operators to
2851         // resolve.  We should concatenate the given prefix and name.
2852         //
2853         // TODO: This MUST happen before template argument resolution. This
2854         //       does not make sense and should be changed, but at the time of
2855         //       writing, there are existing .td files which rely on this
2856         //       implementation detail. It's a bad idea and should be fixed.
2857         //       See test/TableGen/name-resolution-consistency.td for some
2858         //       examples.
2859         CurRec->setName(BinOpInit::getStrConcat(DefmName, NameString));
2860         ResolveName = false;
2861       }
2862 
2863       MapResolver R(CurRec.get());
2864 
2865       if (ResolveName) {
2866         // If the proto's name wasn't resolved, we probably have a reference to
2867         // NAME and need to replace it.
2868         //
2869         // TODO: Whether the name is resolved is basically determined by magic.
2870         //       Unfortunately, existing .td files depend on it.
2871         R.set(StringInit::get("NAME"), DefmName);
2872       }
2873 
2874       for (const auto &TArg : TemplateArgs)
2875         R.set(TArg.first, TArg.second);
2876 
2877       CurRec->resolveReferences(R);
2878 
2879       NewRecDefs.emplace_back(std::move(CurRec));
2880     }
2881 
2882     if (Lex.getCode() != tgtok::comma) break;
2883     Lex.Lex(); // eat ','.
2884 
2885     if (Lex.getCode() != tgtok::Id)
2886       return TokError("expected identifier");
2887 
2888     SubClassLoc = Lex.getLoc();
2889 
2890     // A defm can inherit from regular classes (non-multiclass) as
2891     // long as they come in the end of the inheritance list.
2892     InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
2893 
2894     if (InheritFromClass)
2895       break;
2896 
2897     Ref = ParseSubClassReference(nullptr, true);
2898   }
2899 
2900   if (InheritFromClass) {
2901     // Process all the classes to inherit as if they were part of a
2902     // regular 'def' and inherit all record values.
2903     SubClassReference SubClass = ParseSubClassReference(nullptr, false);
2904     while (true) {
2905       // Check for error.
2906       if (!SubClass.Rec) return true;
2907 
2908       // Get the expanded definition prototypes and teach them about
2909       // the record values the current class to inherit has
2910       for (const auto &CurRec : NewRecDefs) {
2911         // Add it.
2912         if (AddSubClass(CurRec.get(), SubClass))
2913           return true;
2914       }
2915 
2916       if (Lex.getCode() != tgtok::comma) break;
2917       Lex.Lex(); // eat ','.
2918       SubClass = ParseSubClassReference(nullptr, false);
2919     }
2920   }
2921 
2922   for (auto &CurRec : NewRecDefs) {
2923     if (ApplyLetStack(CurRec.get()))
2924       return true;
2925 
2926     addDef(std::move(CurRec), DefmName);
2927   }
2928 
2929   if (Lex.getCode() != tgtok::semi)
2930     return TokError("expected ';' at end of defm");
2931   Lex.Lex();
2932 
2933   return false;
2934 }
2935 
2936 /// ParseObject
2937 ///   Object ::= ClassInst
2938 ///   Object ::= DefInst
2939 ///   Object ::= MultiClassInst
2940 ///   Object ::= DefMInst
2941 ///   Object ::= LETCommand '{' ObjectList '}'
2942 ///   Object ::= LETCommand Object
2943 bool TGParser::ParseObject(MultiClass *MC) {
2944   switch (Lex.getCode()) {
2945   default:
2946     return TokError("Expected class, def, defm, defset, multiclass, let or "
2947                     "foreach");
2948   case tgtok::Let:   return ParseTopLevelLet(MC);
2949   case tgtok::Def:   return ParseDef(MC);
2950   case tgtok::Foreach:   return ParseForeach(MC);
2951   case tgtok::Defm:  return ParseDefm(MC);
2952   case tgtok::Defset:
2953     if (MC)
2954       return TokError("defset is not allowed inside multiclass");
2955     return ParseDefset();
2956   case tgtok::Class:
2957     if (MC)
2958       return TokError("class is not allowed inside multiclass");
2959     if (!Loops.empty())
2960       return TokError("class is not allowed inside foreach loop");
2961     return ParseClass();
2962   case tgtok::MultiClass:
2963     if (!Loops.empty())
2964       return TokError("multiclass is not allowed inside foreach loop");
2965     return ParseMultiClass();
2966   }
2967 }
2968 
2969 /// ParseObjectList
2970 ///   ObjectList :== Object*
2971 bool TGParser::ParseObjectList(MultiClass *MC) {
2972   while (isObjectStart(Lex.getCode())) {
2973     if (ParseObject(MC))
2974       return true;
2975   }
2976   return false;
2977 }
2978 
2979 bool TGParser::ParseFile() {
2980   Lex.Lex(); // Prime the lexer.
2981   if (ParseObjectList()) return true;
2982 
2983   // If we have unread input at the end of the file, report it.
2984   if (Lex.getCode() == tgtok::Eof)
2985     return false;
2986 
2987   return TokError("Unexpected input at top level");
2988 }
2989