LCOV - code coverage report
Current view: top level - lib/TableGen - TGParser.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 906 1291 70.2 %
Date: 2018-06-17 00:07:59 Functions: 45 45 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13