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