LLVM API Documentation

TGParser.cpp
Go to the documentation of this file.
00001 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Implement the Parser for TableGen.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "TGParser.h"
00015 #include "llvm/ADT/SmallVector.h"
00016 #include "llvm/ADT/StringExtras.h"
00017 #include "llvm/Support/CommandLine.h"
00018 #include "llvm/TableGen/Record.h"
00019 #include <algorithm>
00020 #include <sstream>
00021 using namespace llvm;
00022 
00023 //===----------------------------------------------------------------------===//
00024 // Support Code for the Semantic Actions.
00025 //===----------------------------------------------------------------------===//
00026 
00027 namespace llvm {
00028 struct SubClassReference {
00029   SMRange RefRange;
00030   Record *Rec;
00031   std::vector<Init*> TemplateArgs;
00032   SubClassReference() : Rec(nullptr) {}
00033 
00034   bool isInvalid() const { return Rec == nullptr; }
00035 };
00036 
00037 struct SubMultiClassReference {
00038   SMRange RefRange;
00039   MultiClass *MC;
00040   std::vector<Init*> TemplateArgs;
00041   SubMultiClassReference() : MC(nullptr) {}
00042 
00043   bool isInvalid() const { return MC == nullptr; }
00044   void dump() const;
00045 };
00046 
00047 void SubMultiClassReference::dump() const {
00048   errs() << "Multiclass:\n";
00049 
00050   MC->dump();
00051 
00052   errs() << "Template args:\n";
00053   for (std::vector<Init *>::const_iterator i = TemplateArgs.begin(),
00054          iend = TemplateArgs.end();
00055        i != iend;
00056        ++i) {
00057     (*i)->dump();
00058   }
00059 }
00060 
00061 } // end namespace llvm
00062 
00063 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
00064   if (!CurRec)
00065     CurRec = &CurMultiClass->Rec;
00066 
00067   if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
00068     // The value already exists in the class, treat this as a set.
00069     if (ERV->setValue(RV.getValue()))
00070       return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
00071                    RV.getType()->getAsString() + "' is incompatible with " +
00072                    "previous definition of type '" +
00073                    ERV->getType()->getAsString() + "'");
00074   } else {
00075     CurRec->addValue(RV);
00076   }
00077   return false;
00078 }
00079 
00080 /// SetValue -
00081 /// Return true on error, false on success.
00082 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
00083                         const std::vector<unsigned> &BitList, Init *V) {
00084   if (!V) return false;
00085 
00086   if (!CurRec) CurRec = &CurMultiClass->Rec;
00087 
00088   RecordVal *RV = CurRec->getValue(ValName);
00089   if (!RV)
00090     return Error(Loc, "Value '" + ValName->getAsUnquotedString()
00091                  + "' unknown!");
00092 
00093   // Do not allow assignments like 'X = X'.  This will just cause infinite loops
00094   // in the resolution machinery.
00095   if (BitList.empty())
00096     if (VarInit *VI = dyn_cast<VarInit>(V))
00097       if (VI->getNameInit() == ValName)
00098         return false;
00099 
00100   // If we are assigning to a subset of the bits in the value... then we must be
00101   // assigning to a field of BitsRecTy, which must have a BitsInit
00102   // initializer.
00103   //
00104   if (!BitList.empty()) {
00105     BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
00106     if (!CurVal)
00107       return Error(Loc, "Value '" + ValName->getAsUnquotedString()
00108                    + "' is not a bits type");
00109 
00110     // Convert the incoming value to a bits type of the appropriate size...
00111     Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size()));
00112     if (!BI) {
00113       return Error(Loc, "Initializer is not compatible with bit range");
00114     }
00115 
00116     // We should have a BitsInit type now.
00117     BitsInit *BInit = dyn_cast<BitsInit>(BI);
00118     assert(BInit != nullptr);
00119 
00120     SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
00121 
00122     // Loop over bits, assigning values as appropriate.
00123     for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
00124       unsigned Bit = BitList[i];
00125       if (NewBits[Bit])
00126         return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
00127                      ValName->getAsUnquotedString() + "' more than once");
00128       NewBits[Bit] = BInit->getBit(i);
00129     }
00130 
00131     for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
00132       if (!NewBits[i])
00133         NewBits[i] = CurVal->getBit(i);
00134 
00135     V = BitsInit::get(NewBits);
00136   }
00137 
00138   if (RV->setValue(V)) {
00139     std::string InitType = "";
00140     if (BitsInit *BI = dyn_cast<BitsInit>(V)) {
00141       InitType = (Twine("' of type bit initializer with length ") +
00142                   Twine(BI->getNumBits())).str();
00143     }
00144     return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of type '"
00145                  + RV->getType()->getAsString() +
00146                  "' is incompatible with initializer '" + V->getAsString()
00147                  + InitType
00148                  + "'");
00149   }
00150   return false;
00151 }
00152 
00153 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
00154 /// args as SubClass's template arguments.
00155 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
00156   Record *SC = SubClass.Rec;
00157   // Add all of the values in the subclass into the current class.
00158   const std::vector<RecordVal> &Vals = SC->getValues();
00159   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
00160     if (AddValue(CurRec, SubClass.RefRange.Start, Vals[i]))
00161       return true;
00162 
00163   const std::vector<Init *> &TArgs = SC->getTemplateArgs();
00164 
00165   // Ensure that an appropriate number of template arguments are specified.
00166   if (TArgs.size() < SubClass.TemplateArgs.size())
00167     return Error(SubClass.RefRange.Start,
00168                  "More template args specified than expected");
00169 
00170   // Loop over all of the template arguments, setting them to the specified
00171   // value or leaving them as the default if necessary.
00172   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
00173     if (i < SubClass.TemplateArgs.size()) {
00174       // If a value is specified for this template arg, set it now.
00175       if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
00176                    std::vector<unsigned>(), SubClass.TemplateArgs[i]))
00177         return true;
00178 
00179       // Resolve it next.
00180       CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
00181 
00182       // Now remove it.
00183       CurRec->removeValue(TArgs[i]);
00184 
00185     } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
00186       return Error(SubClass.RefRange.Start,
00187                    "Value not specified for template argument #"
00188                    + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
00189                    + ") of subclass '" + SC->getNameInitAsString() + "'!");
00190     }
00191   }
00192 
00193   // Since everything went well, we can now set the "superclass" list for the
00194   // current record.
00195   const std::vector<Record*> &SCs = SC->getSuperClasses();
00196   ArrayRef<SMRange> SCRanges = SC->getSuperClassRanges();
00197   for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
00198     if (CurRec->isSubClassOf(SCs[i]))
00199       return Error(SubClass.RefRange.Start,
00200                    "Already subclass of '" + SCs[i]->getName() + "'!\n");
00201     CurRec->addSuperClass(SCs[i], SCRanges[i]);
00202   }
00203 
00204   if (CurRec->isSubClassOf(SC))
00205     return Error(SubClass.RefRange.Start,
00206                  "Already subclass of '" + SC->getName() + "'!\n");
00207   CurRec->addSuperClass(SC, SubClass.RefRange);
00208   return false;
00209 }
00210 
00211 /// AddSubMultiClass - Add SubMultiClass as a subclass to
00212 /// CurMC, resolving its template args as SubMultiClass's
00213 /// template arguments.
00214 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
00215                                 SubMultiClassReference &SubMultiClass) {
00216   MultiClass *SMC = SubMultiClass.MC;
00217   Record *CurRec = &CurMC->Rec;
00218 
00219   const std::vector<RecordVal> &MCVals = CurRec->getValues();
00220 
00221   // Add all of the values in the subclass into the current class.
00222   const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
00223   for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
00224     if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVals[i]))
00225       return true;
00226 
00227   int newDefStart = CurMC->DefPrototypes.size();
00228 
00229   // Add all of the defs in the subclass into the current multiclass.
00230   for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
00231          iend = SMC->DefPrototypes.end();
00232        i != iend;
00233        ++i) {
00234     // Clone the def and add it to the current multiclass
00235     Record *NewDef = new Record(**i);
00236 
00237     // Add all of the values in the superclass into the current def.
00238     for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
00239       if (AddValue(NewDef, SubMultiClass.RefRange.Start, MCVals[i])) {
00240         delete NewDef;
00241         return true;
00242       }
00243 
00244     CurMC->DefPrototypes.push_back(NewDef);
00245   }
00246 
00247   const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
00248 
00249   // Ensure that an appropriate number of template arguments are
00250   // specified.
00251   if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
00252     return Error(SubMultiClass.RefRange.Start,
00253                  "More template args specified than expected");
00254 
00255   // Loop over all of the template arguments, setting them to the specified
00256   // value or leaving them as the default if necessary.
00257   for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
00258     if (i < SubMultiClass.TemplateArgs.size()) {
00259       // If a value is specified for this template arg, set it in the
00260       // superclass now.
00261       if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i],
00262                    std::vector<unsigned>(),
00263                    SubMultiClass.TemplateArgs[i]))
00264         return true;
00265 
00266       // Resolve it next.
00267       CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
00268 
00269       // Now remove it.
00270       CurRec->removeValue(SMCTArgs[i]);
00271 
00272       // If a value is specified for this template arg, set it in the
00273       // new defs now.
00274       for (MultiClass::RecordVector::iterator j =
00275              CurMC->DefPrototypes.begin() + newDefStart,
00276              jend = CurMC->DefPrototypes.end();
00277            j != jend;
00278            ++j) {
00279         Record *Def = *j;
00280 
00281         if (SetValue(Def, SubMultiClass.RefRange.Start, SMCTArgs[i],
00282                      std::vector<unsigned>(),
00283                      SubMultiClass.TemplateArgs[i]))
00284           return true;
00285 
00286         // Resolve it next.
00287         Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
00288 
00289         // Now remove it
00290         Def->removeValue(SMCTArgs[i]);
00291       }
00292     } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
00293       return Error(SubMultiClass.RefRange.Start,
00294                    "Value not specified for template argument #"
00295                    + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
00296                    + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
00297     }
00298   }
00299 
00300   return false;
00301 }
00302 
00303 /// ProcessForeachDefs - Given a record, apply all of the variable
00304 /// values in all surrounding foreach loops, creating new records for
00305 /// each combination of values.
00306 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
00307   if (Loops.empty())
00308     return false;
00309 
00310   // We want to instantiate a new copy of CurRec for each combination
00311   // of nested loop iterator values.  We don't want top instantiate
00312   // any copies until we have values for each loop iterator.
00313   IterSet IterVals;
00314   return ProcessForeachDefs(CurRec, Loc, IterVals);
00315 }
00316 
00317 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
00318 /// apply each of the variable values in this loop and then process
00319 /// subloops.
00320 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
00321   // Recursively build a tuple of iterator values.
00322   if (IterVals.size() != Loops.size()) {
00323     assert(IterVals.size() < Loops.size());
00324     ForeachLoop &CurLoop = Loops[IterVals.size()];
00325     ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
00326     if (!List) {
00327       Error(Loc, "Loop list is not a list");
00328       return true;
00329     }
00330 
00331     // Process each value.
00332     for (int64_t i = 0; i < List->getSize(); ++i) {
00333       Init *ItemVal = List->resolveListElementReference(*CurRec, nullptr, i);
00334       IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
00335       if (ProcessForeachDefs(CurRec, Loc, IterVals))
00336         return true;
00337       IterVals.pop_back();
00338     }
00339     return false;
00340   }
00341 
00342   // This is the bottom of the recursion. We have all of the iterator values
00343   // for this point in the iteration space.  Instantiate a new record to
00344   // reflect this combination of values.
00345   Record *IterRec = new Record(*CurRec);
00346 
00347   // Set the iterator values now.
00348   for (unsigned i = 0, e = IterVals.size(); i != e; ++i) {
00349     VarInit *IterVar = IterVals[i].IterVar;
00350     TypedInit *IVal = dyn_cast<TypedInit>(IterVals[i].IterValue);
00351     if (!IVal) {
00352       Error(Loc, "foreach iterator value is untyped");
00353       delete IterRec;
00354       return true;
00355     }
00356 
00357     IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
00358 
00359     if (SetValue(IterRec, Loc, IterVar->getName(),
00360                  std::vector<unsigned>(), IVal)) {
00361       Error(Loc, "when instantiating this def");
00362       delete IterRec;
00363       return true;
00364     }
00365 
00366     // Resolve it next.
00367     IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
00368 
00369     // Remove it.
00370     IterRec->removeValue(IterVar->getName());
00371   }
00372 
00373   if (Records.getDef(IterRec->getNameInitAsString())) {
00374     // If this record is anonymous, it's no problem, just generate a new name
00375     if (IterRec->isAnonymous())
00376       IterRec->setName(GetNewAnonymousName());
00377     else {
00378       Error(Loc, "def already exists: " + IterRec->getNameInitAsString());
00379       delete IterRec;
00380       return true;
00381     }
00382   }
00383 
00384   Records.addDef(IterRec);
00385   IterRec->resolveReferences();
00386   return false;
00387 }
00388 
00389 //===----------------------------------------------------------------------===//
00390 // Parser Code
00391 //===----------------------------------------------------------------------===//
00392 
00393 /// isObjectStart - Return true if this is a valid first token for an Object.
00394 static bool isObjectStart(tgtok::TokKind K) {
00395   return K == tgtok::Class || K == tgtok::Def ||
00396          K == tgtok::Defm || K == tgtok::Let ||
00397          K == tgtok::MultiClass || K == tgtok::Foreach;
00398 }
00399 
00400 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
00401 /// an identifier.
00402 std::string TGParser::GetNewAnonymousName() {
00403   unsigned Tmp = AnonCounter++; // MSVC2012 ICEs without this.
00404   return "anonymous_" + utostr(Tmp);
00405 }
00406 
00407 /// ParseObjectName - If an object name is specified, return it.  Otherwise,
00408 /// return 0.
00409 ///   ObjectName ::= Value [ '#' Value ]*
00410 ///   ObjectName ::= /*empty*/
00411 ///
00412 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
00413   switch (Lex.getCode()) {
00414   case tgtok::colon:
00415   case tgtok::semi:
00416   case tgtok::l_brace:
00417     // These are all of the tokens that can begin an object body.
00418     // Some of these can also begin values but we disallow those cases
00419     // because they are unlikely to be useful.
00420     return nullptr;
00421   default:
00422     break;
00423   }
00424 
00425   Record *CurRec = nullptr;
00426   if (CurMultiClass)
00427     CurRec = &CurMultiClass->Rec;
00428 
00429   RecTy *Type = nullptr;
00430   if (CurRec) {
00431     const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
00432     if (!CurRecName) {
00433       TokError("Record name is not typed!");
00434       return nullptr;
00435     }
00436     Type = CurRecName->getType();
00437   }
00438 
00439   return ParseValue(CurRec, Type, ParseNameMode);
00440 }
00441 
00442 /// ParseClassID - Parse and resolve a reference to a class name.  This returns
00443 /// null on error.
00444 ///
00445 ///    ClassID ::= ID
00446 ///
00447 Record *TGParser::ParseClassID() {
00448   if (Lex.getCode() != tgtok::Id) {
00449     TokError("expected name for ClassID");
00450     return nullptr;
00451   }
00452 
00453   Record *Result = Records.getClass(Lex.getCurStrVal());
00454   if (!Result)
00455     TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
00456 
00457   Lex.Lex();
00458   return Result;
00459 }
00460 
00461 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
00462 /// This returns null on error.
00463 ///
00464 ///    MultiClassID ::= ID
00465 ///
00466 MultiClass *TGParser::ParseMultiClassID() {
00467   if (Lex.getCode() != tgtok::Id) {
00468     TokError("expected name for MultiClassID");
00469     return nullptr;
00470   }
00471 
00472   MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
00473   if (!Result)
00474     TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
00475 
00476   Lex.Lex();
00477   return Result;
00478 }
00479 
00480 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
00481 /// subclass.  This returns a SubClassRefTy with a null Record* on error.
00482 ///
00483 ///  SubClassRef ::= ClassID
00484 ///  SubClassRef ::= ClassID '<' ValueList '>'
00485 ///
00486 SubClassReference TGParser::
00487 ParseSubClassReference(Record *CurRec, bool isDefm) {
00488   SubClassReference Result;
00489   Result.RefRange.Start = Lex.getLoc();
00490 
00491   if (isDefm) {
00492     if (MultiClass *MC = ParseMultiClassID())
00493       Result.Rec = &MC->Rec;
00494   } else {
00495     Result.Rec = ParseClassID();
00496   }
00497   if (!Result.Rec) return Result;
00498 
00499   // If there is no template arg list, we're done.
00500   if (Lex.getCode() != tgtok::less) {
00501     Result.RefRange.End = Lex.getLoc();
00502     return Result;
00503   }
00504   Lex.Lex();  // Eat the '<'
00505 
00506   if (Lex.getCode() == tgtok::greater) {
00507     TokError("subclass reference requires a non-empty list of template values");
00508     Result.Rec = nullptr;
00509     return Result;
00510   }
00511 
00512   Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
00513   if (Result.TemplateArgs.empty()) {
00514     Result.Rec = nullptr;   // Error parsing value list.
00515     return Result;
00516   }
00517 
00518   if (Lex.getCode() != tgtok::greater) {
00519     TokError("expected '>' in template value list");
00520     Result.Rec = nullptr;
00521     return Result;
00522   }
00523   Lex.Lex();
00524   Result.RefRange.End = Lex.getLoc();
00525 
00526   return Result;
00527 }
00528 
00529 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
00530 /// templated submulticlass.  This returns a SubMultiClassRefTy with a null
00531 /// Record* on error.
00532 ///
00533 ///  SubMultiClassRef ::= MultiClassID
00534 ///  SubMultiClassRef ::= MultiClassID '<' ValueList '>'
00535 ///
00536 SubMultiClassReference TGParser::
00537 ParseSubMultiClassReference(MultiClass *CurMC) {
00538   SubMultiClassReference Result;
00539   Result.RefRange.Start = Lex.getLoc();
00540 
00541   Result.MC = ParseMultiClassID();
00542   if (!Result.MC) return Result;
00543 
00544   // If there is no template arg list, we're done.
00545   if (Lex.getCode() != tgtok::less) {
00546     Result.RefRange.End = Lex.getLoc();
00547     return Result;
00548   }
00549   Lex.Lex();  // Eat the '<'
00550 
00551   if (Lex.getCode() == tgtok::greater) {
00552     TokError("subclass reference requires a non-empty list of template values");
00553     Result.MC = nullptr;
00554     return Result;
00555   }
00556 
00557   Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
00558   if (Result.TemplateArgs.empty()) {
00559     Result.MC = nullptr;   // Error parsing value list.
00560     return Result;
00561   }
00562 
00563   if (Lex.getCode() != tgtok::greater) {
00564     TokError("expected '>' in template value list");
00565     Result.MC = nullptr;
00566     return Result;
00567   }
00568   Lex.Lex();
00569   Result.RefRange.End = Lex.getLoc();
00570 
00571   return Result;
00572 }
00573 
00574 /// ParseRangePiece - Parse a bit/value range.
00575 ///   RangePiece ::= INTVAL
00576 ///   RangePiece ::= INTVAL '-' INTVAL
00577 ///   RangePiece ::= INTVAL INTVAL
00578 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
00579   if (Lex.getCode() != tgtok::IntVal) {
00580     TokError("expected integer or bitrange");
00581     return true;
00582   }
00583   int64_t Start = Lex.getCurIntVal();
00584   int64_t End;
00585 
00586   if (Start < 0)
00587     return TokError("invalid range, cannot be negative");
00588 
00589   switch (Lex.Lex()) {  // eat first character.
00590   default:
00591     Ranges.push_back(Start);
00592     return false;
00593   case tgtok::minus:
00594     if (Lex.Lex() != tgtok::IntVal) {
00595       TokError("expected integer value as end of range");
00596       return true;
00597     }
00598     End = Lex.getCurIntVal();
00599     break;
00600   case tgtok::IntVal:
00601     End = -Lex.getCurIntVal();
00602     break;
00603   }
00604   if (End < 0)
00605     return TokError("invalid range, cannot be negative");
00606   Lex.Lex();
00607 
00608   // Add to the range.
00609   if (Start < End) {
00610     for (; Start <= End; ++Start)
00611       Ranges.push_back(Start);
00612   } else {
00613     for (; Start >= End; --Start)
00614       Ranges.push_back(Start);
00615   }
00616   return false;
00617 }
00618 
00619 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
00620 ///
00621 ///   RangeList ::= RangePiece (',' RangePiece)*
00622 ///
00623 std::vector<unsigned> TGParser::ParseRangeList() {
00624   std::vector<unsigned> Result;
00625 
00626   // Parse the first piece.
00627   if (ParseRangePiece(Result))
00628     return std::vector<unsigned>();
00629   while (Lex.getCode() == tgtok::comma) {
00630     Lex.Lex();  // Eat the comma.
00631 
00632     // Parse the next range piece.
00633     if (ParseRangePiece(Result))
00634       return std::vector<unsigned>();
00635   }
00636   return Result;
00637 }
00638 
00639 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
00640 ///   OptionalRangeList ::= '<' RangeList '>'
00641 ///   OptionalRangeList ::= /*empty*/
00642 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
00643   if (Lex.getCode() != tgtok::less)
00644     return false;
00645 
00646   SMLoc StartLoc = Lex.getLoc();
00647   Lex.Lex(); // eat the '<'
00648 
00649   // Parse the range list.
00650   Ranges = ParseRangeList();
00651   if (Ranges.empty()) return true;
00652 
00653   if (Lex.getCode() != tgtok::greater) {
00654     TokError("expected '>' at end of range list");
00655     return Error(StartLoc, "to match this '<'");
00656   }
00657   Lex.Lex();   // eat the '>'.
00658   return false;
00659 }
00660 
00661 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
00662 ///   OptionalBitList ::= '{' RangeList '}'
00663 ///   OptionalBitList ::= /*empty*/
00664 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
00665   if (Lex.getCode() != tgtok::l_brace)
00666     return false;
00667 
00668   SMLoc StartLoc = Lex.getLoc();
00669   Lex.Lex(); // eat the '{'
00670 
00671   // Parse the range list.
00672   Ranges = ParseRangeList();
00673   if (Ranges.empty()) return true;
00674 
00675   if (Lex.getCode() != tgtok::r_brace) {
00676     TokError("expected '}' at end of bit list");
00677     return Error(StartLoc, "to match this '{'");
00678   }
00679   Lex.Lex();   // eat the '}'.
00680   return false;
00681 }
00682 
00683 
00684 /// ParseType - Parse and return a tblgen type.  This returns null on error.
00685 ///
00686 ///   Type ::= STRING                       // string type
00687 ///   Type ::= CODE                         // code type
00688 ///   Type ::= BIT                          // bit type
00689 ///   Type ::= BITS '<' INTVAL '>'          // bits<x> type
00690 ///   Type ::= INT                          // int type
00691 ///   Type ::= LIST '<' Type '>'            // list<x> type
00692 ///   Type ::= DAG                          // dag type
00693 ///   Type ::= ClassID                      // Record Type
00694 ///
00695 RecTy *TGParser::ParseType() {
00696   switch (Lex.getCode()) {
00697   default: TokError("Unknown token when expecting a type"); return nullptr;
00698   case tgtok::String: Lex.Lex(); return StringRecTy::get();
00699   case tgtok::Code:   Lex.Lex(); return StringRecTy::get();
00700   case tgtok::Bit:    Lex.Lex(); return BitRecTy::get();
00701   case tgtok::Int:    Lex.Lex(); return IntRecTy::get();
00702   case tgtok::Dag:    Lex.Lex(); return DagRecTy::get();
00703   case tgtok::Id:
00704     if (Record *R = ParseClassID()) return RecordRecTy::get(R);
00705     return nullptr;
00706   case tgtok::Bits: {
00707     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
00708       TokError("expected '<' after bits type");
00709       return nullptr;
00710     }
00711     if (Lex.Lex() != tgtok::IntVal) {  // Eat '<'
00712       TokError("expected integer in bits<n> type");
00713       return nullptr;
00714     }
00715     uint64_t Val = Lex.getCurIntVal();
00716     if (Lex.Lex() != tgtok::greater) {  // Eat count.
00717       TokError("expected '>' at end of bits<n> type");
00718       return nullptr;
00719     }
00720     Lex.Lex();  // Eat '>'
00721     return BitsRecTy::get(Val);
00722   }
00723   case tgtok::List: {
00724     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
00725       TokError("expected '<' after list type");
00726       return nullptr;
00727     }
00728     Lex.Lex();  // Eat '<'
00729     RecTy *SubType = ParseType();
00730     if (!SubType) return nullptr;
00731 
00732     if (Lex.getCode() != tgtok::greater) {
00733       TokError("expected '>' at end of list<ty> type");
00734       return nullptr;
00735     }
00736     Lex.Lex();  // Eat '>'
00737     return ListRecTy::get(SubType);
00738   }
00739   }
00740 }
00741 
00742 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
00743 /// has already been read.
00744 Init *TGParser::ParseIDValue(Record *CurRec,
00745                              const std::string &Name, SMLoc NameLoc,
00746                              IDParseMode Mode) {
00747   if (CurRec) {
00748     if (const RecordVal *RV = CurRec->getValue(Name))
00749       return VarInit::get(Name, RV->getType());
00750 
00751     Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
00752 
00753     if (CurMultiClass)
00754       TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
00755                                     "::");
00756 
00757     if (CurRec->isTemplateArg(TemplateArgName)) {
00758       const RecordVal *RV = CurRec->getValue(TemplateArgName);
00759       assert(RV && "Template arg doesn't exist??");
00760       return VarInit::get(TemplateArgName, RV->getType());
00761     }
00762   }
00763 
00764   if (CurMultiClass) {
00765     Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
00766                                "::");
00767 
00768     if (CurMultiClass->Rec.isTemplateArg(MCName)) {
00769       const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
00770       assert(RV && "Template arg doesn't exist??");
00771       return VarInit::get(MCName, RV->getType());
00772     }
00773   }
00774 
00775   // If this is in a foreach loop, make sure it's not a loop iterator
00776   for (LoopVector::iterator i = Loops.begin(), iend = Loops.end();
00777        i != iend;
00778        ++i) {
00779     VarInit *IterVar = dyn_cast<VarInit>(i->IterVar);
00780     if (IterVar && IterVar->getName() == Name)
00781       return IterVar;
00782   }
00783 
00784   if (Mode == ParseNameMode)
00785     return StringInit::get(Name);
00786 
00787   if (Record *D = Records.getDef(Name))
00788     return DefInit::get(D);
00789 
00790   if (Mode == ParseValueMode) {
00791     Error(NameLoc, "Variable not defined: '" + Name + "'");
00792     return nullptr;
00793   }
00794   
00795   return StringInit::get(Name);
00796 }
00797 
00798 /// ParseOperation - Parse an operator.  This returns null on error.
00799 ///
00800 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
00801 ///
00802 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
00803   switch (Lex.getCode()) {
00804   default:
00805     TokError("unknown operation");
00806     return nullptr;
00807   case tgtok::XHead:
00808   case tgtok::XTail:
00809   case tgtok::XEmpty:
00810   case tgtok::XCast: {  // Value ::= !unop '(' Value ')'
00811     UnOpInit::UnaryOp Code;
00812     RecTy *Type = nullptr;
00813 
00814     switch (Lex.getCode()) {
00815     default: llvm_unreachable("Unhandled code!");
00816     case tgtok::XCast:
00817       Lex.Lex();  // eat the operation
00818       Code = UnOpInit::CAST;
00819 
00820       Type = ParseOperatorType();
00821 
00822       if (!Type) {
00823         TokError("did not get type for unary operator");
00824         return nullptr;
00825       }
00826 
00827       break;
00828     case tgtok::XHead:
00829       Lex.Lex();  // eat the operation
00830       Code = UnOpInit::HEAD;
00831       break;
00832     case tgtok::XTail:
00833       Lex.Lex();  // eat the operation
00834       Code = UnOpInit::TAIL;
00835       break;
00836     case tgtok::XEmpty:
00837       Lex.Lex();  // eat the operation
00838       Code = UnOpInit::EMPTY;
00839       Type = IntRecTy::get();
00840       break;
00841     }
00842     if (Lex.getCode() != tgtok::l_paren) {
00843       TokError("expected '(' after unary operator");
00844       return nullptr;
00845     }
00846     Lex.Lex();  // eat the '('
00847 
00848     Init *LHS = ParseValue(CurRec);
00849     if (!LHS) return nullptr;
00850 
00851     if (Code == UnOpInit::HEAD
00852         || Code == UnOpInit::TAIL
00853         || Code == UnOpInit::EMPTY) {
00854       ListInit *LHSl = dyn_cast<ListInit>(LHS);
00855       StringInit *LHSs = dyn_cast<StringInit>(LHS);
00856       TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
00857       if (!LHSl && !LHSs && !LHSt) {
00858         TokError("expected list or string type argument in unary operator");
00859         return nullptr;
00860       }
00861       if (LHSt) {
00862         ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
00863         StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
00864         if (!LType && !SType) {
00865           TokError("expected list or string type argument in unary operator");
00866           return nullptr;
00867         }
00868       }
00869 
00870       if (Code == UnOpInit::HEAD
00871           || Code == UnOpInit::TAIL) {
00872         if (!LHSl && !LHSt) {
00873           TokError("expected list type argument in unary operator");
00874           return nullptr;
00875         }
00876 
00877         if (LHSl && LHSl->getSize() == 0) {
00878           TokError("empty list argument in unary operator");
00879           return nullptr;
00880         }
00881         if (LHSl) {
00882           Init *Item = LHSl->getElement(0);
00883           TypedInit *Itemt = dyn_cast<TypedInit>(Item);
00884           if (!Itemt) {
00885             TokError("untyped list element in unary operator");
00886             return nullptr;
00887           }
00888           if (Code == UnOpInit::HEAD) {
00889             Type = Itemt->getType();
00890           } else {
00891             Type = ListRecTy::get(Itemt->getType());
00892           }
00893         } else {
00894           assert(LHSt && "expected list type argument in unary operator");
00895           ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
00896           if (!LType) {
00897             TokError("expected list type argument in unary operator");
00898             return nullptr;
00899           }
00900           if (Code == UnOpInit::HEAD) {
00901             Type = LType->getElementType();
00902           } else {
00903             Type = LType;
00904           }
00905         }
00906       }
00907     }
00908 
00909     if (Lex.getCode() != tgtok::r_paren) {
00910       TokError("expected ')' in unary operator");
00911       return nullptr;
00912     }
00913     Lex.Lex();  // eat the ')'
00914     return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
00915   }
00916 
00917   case tgtok::XConcat:
00918   case tgtok::XADD:
00919   case tgtok::XAND:
00920   case tgtok::XSRA:
00921   case tgtok::XSRL:
00922   case tgtok::XSHL:
00923   case tgtok::XEq:
00924   case tgtok::XListConcat:
00925   case tgtok::XStrConcat: {  // Value ::= !binop '(' Value ',' Value ')'
00926     tgtok::TokKind OpTok = Lex.getCode();
00927     SMLoc OpLoc = Lex.getLoc();
00928     Lex.Lex();  // eat the operation
00929 
00930     BinOpInit::BinaryOp Code;
00931     RecTy *Type = nullptr;
00932 
00933     switch (OpTok) {
00934     default: llvm_unreachable("Unhandled code!");
00935     case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
00936     case tgtok::XADD:    Code = BinOpInit::ADD;   Type = IntRecTy::get(); break;
00937     case tgtok::XAND:    Code = BinOpInit::AND;   Type = IntRecTy::get(); break;
00938     case tgtok::XSRA:    Code = BinOpInit::SRA;   Type = IntRecTy::get(); break;
00939     case tgtok::XSRL:    Code = BinOpInit::SRL;   Type = IntRecTy::get(); break;
00940     case tgtok::XSHL:    Code = BinOpInit::SHL;   Type = IntRecTy::get(); break;
00941     case tgtok::XEq:     Code = BinOpInit::EQ;    Type = BitRecTy::get(); break;
00942     case tgtok::XListConcat:
00943       Code = BinOpInit::LISTCONCAT;
00944       // We don't know the list type until we parse the first argument
00945       break;
00946     case tgtok::XStrConcat:
00947       Code = BinOpInit::STRCONCAT;
00948       Type = StringRecTy::get();
00949       break;
00950     }
00951 
00952     if (Lex.getCode() != tgtok::l_paren) {
00953       TokError("expected '(' after binary operator");
00954       return nullptr;
00955     }
00956     Lex.Lex();  // eat the '('
00957 
00958     SmallVector<Init*, 2> InitList;
00959 
00960     InitList.push_back(ParseValue(CurRec));
00961     if (!InitList.back()) return nullptr;
00962 
00963     while (Lex.getCode() == tgtok::comma) {
00964       Lex.Lex();  // eat the ','
00965 
00966       InitList.push_back(ParseValue(CurRec));
00967       if (!InitList.back()) return nullptr;
00968     }
00969 
00970     if (Lex.getCode() != tgtok::r_paren) {
00971       TokError("expected ')' in operator");
00972       return nullptr;
00973     }
00974     Lex.Lex();  // eat the ')'
00975 
00976     // If we are doing !listconcat, we should know the type by now
00977     if (OpTok == tgtok::XListConcat) {
00978       if (VarInit *Arg0 = dyn_cast<VarInit>(InitList[0]))
00979         Type = Arg0->getType();
00980       else if (ListInit *Arg0 = dyn_cast<ListInit>(InitList[0]))
00981         Type = Arg0->getType();
00982       else {
00983         InitList[0]->dump();
00984         Error(OpLoc, "expected a list");
00985         return nullptr;
00986       }
00987     }
00988 
00989     // We allow multiple operands to associative operators like !strconcat as
00990     // shorthand for nesting them.
00991     if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT) {
00992       while (InitList.size() > 2) {
00993         Init *RHS = InitList.pop_back_val();
00994         RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
00995                            ->Fold(CurRec, CurMultiClass);
00996         InitList.back() = RHS;
00997       }
00998     }
00999 
01000     if (InitList.size() == 2)
01001       return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
01002         ->Fold(CurRec, CurMultiClass);
01003 
01004     Error(OpLoc, "expected two operands to operator");
01005     return nullptr;
01006   }
01007 
01008   case tgtok::XIf:
01009   case tgtok::XForEach:
01010   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
01011     TernOpInit::TernaryOp Code;
01012     RecTy *Type = nullptr;
01013 
01014     tgtok::TokKind LexCode = Lex.getCode();
01015     Lex.Lex();  // eat the operation
01016     switch (LexCode) {
01017     default: llvm_unreachable("Unhandled code!");
01018     case tgtok::XIf:
01019       Code = TernOpInit::IF;
01020       break;
01021     case tgtok::XForEach:
01022       Code = TernOpInit::FOREACH;
01023       break;
01024     case tgtok::XSubst:
01025       Code = TernOpInit::SUBST;
01026       break;
01027     }
01028     if (Lex.getCode() != tgtok::l_paren) {
01029       TokError("expected '(' after ternary operator");
01030       return nullptr;
01031     }
01032     Lex.Lex();  // eat the '('
01033 
01034     Init *LHS = ParseValue(CurRec);
01035     if (!LHS) return nullptr;
01036 
01037     if (Lex.getCode() != tgtok::comma) {
01038       TokError("expected ',' in ternary operator");
01039       return nullptr;
01040     }
01041     Lex.Lex();  // eat the ','
01042 
01043     Init *MHS = ParseValue(CurRec, ItemType);
01044     if (!MHS)
01045       return nullptr;
01046 
01047     if (Lex.getCode() != tgtok::comma) {
01048       TokError("expected ',' in ternary operator");
01049       return nullptr;
01050     }
01051     Lex.Lex();  // eat the ','
01052 
01053     Init *RHS = ParseValue(CurRec, ItemType);
01054     if (!RHS)
01055       return nullptr;
01056 
01057     if (Lex.getCode() != tgtok::r_paren) {
01058       TokError("expected ')' in binary operator");
01059       return nullptr;
01060     }
01061     Lex.Lex();  // eat the ')'
01062 
01063     switch (LexCode) {
01064     default: llvm_unreachable("Unhandled code!");
01065     case tgtok::XIf: {
01066       RecTy *MHSTy = nullptr;
01067       RecTy *RHSTy = nullptr;
01068 
01069       if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
01070         MHSTy = MHSt->getType();
01071       if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
01072         MHSTy = BitsRecTy::get(MHSbits->getNumBits());
01073       if (isa<BitInit>(MHS))
01074         MHSTy = BitRecTy::get();
01075 
01076       if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
01077         RHSTy = RHSt->getType();
01078       if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
01079         RHSTy = BitsRecTy::get(RHSbits->getNumBits());
01080       if (isa<BitInit>(RHS))
01081         RHSTy = BitRecTy::get();
01082 
01083       // For UnsetInit, it's typed from the other hand.
01084       if (isa<UnsetInit>(MHS))
01085         MHSTy = RHSTy;
01086       if (isa<UnsetInit>(RHS))
01087         RHSTy = MHSTy;
01088 
01089       if (!MHSTy || !RHSTy) {
01090         TokError("could not get type for !if");
01091         return nullptr;
01092       }
01093 
01094       if (MHSTy->typeIsConvertibleTo(RHSTy)) {
01095         Type = RHSTy;
01096       } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
01097         Type = MHSTy;
01098       } else {
01099         TokError("inconsistent types for !if");
01100         return nullptr;
01101       }
01102       break;
01103     }
01104     case tgtok::XForEach: {
01105       TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
01106       if (!MHSt) {
01107         TokError("could not get type for !foreach");
01108         return nullptr;
01109       }
01110       Type = MHSt->getType();
01111       break;
01112     }
01113     case tgtok::XSubst: {
01114       TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
01115       if (!RHSt) {
01116         TokError("could not get type for !subst");
01117         return nullptr;
01118       }
01119       Type = RHSt->getType();
01120       break;
01121     }
01122     }
01123     return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
01124                                                              CurMultiClass);
01125   }
01126   }
01127 }
01128 
01129 /// ParseOperatorType - Parse a type for an operator.  This returns
01130 /// null on error.
01131 ///
01132 /// OperatorType ::= '<' Type '>'
01133 ///
01134 RecTy *TGParser::ParseOperatorType() {
01135   RecTy *Type = nullptr;
01136 
01137   if (Lex.getCode() != tgtok::less) {
01138     TokError("expected type name for operator");
01139     return nullptr;
01140   }
01141   Lex.Lex();  // eat the <
01142 
01143   Type = ParseType();
01144 
01145   if (!Type) {
01146     TokError("expected type name for operator");
01147     return nullptr;
01148   }
01149 
01150   if (Lex.getCode() != tgtok::greater) {
01151     TokError("expected type name for operator");
01152     return nullptr;
01153   }
01154   Lex.Lex();  // eat the >
01155 
01156   return Type;
01157 }
01158 
01159 
01160 /// ParseSimpleValue - Parse a tblgen value.  This returns null on error.
01161 ///
01162 ///   SimpleValue ::= IDValue
01163 ///   SimpleValue ::= INTVAL
01164 ///   SimpleValue ::= STRVAL+
01165 ///   SimpleValue ::= CODEFRAGMENT
01166 ///   SimpleValue ::= '?'
01167 ///   SimpleValue ::= '{' ValueList '}'
01168 ///   SimpleValue ::= ID '<' ValueListNE '>'
01169 ///   SimpleValue ::= '[' ValueList ']'
01170 ///   SimpleValue ::= '(' IDValue DagArgList ')'
01171 ///   SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
01172 ///   SimpleValue ::= ADDTOK '(' Value ',' Value ')'
01173 ///   SimpleValue ::= SHLTOK '(' Value ',' Value ')'
01174 ///   SimpleValue ::= SRATOK '(' Value ',' Value ')'
01175 ///   SimpleValue ::= SRLTOK '(' Value ',' Value ')'
01176 ///   SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
01177 ///   SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
01178 ///
01179 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
01180                                  IDParseMode Mode) {
01181   Init *R = nullptr;
01182   switch (Lex.getCode()) {
01183   default: TokError("Unknown token when parsing a value"); break;
01184   case tgtok::paste:
01185     // This is a leading paste operation.  This is deprecated but
01186     // still exists in some .td files.  Ignore it.
01187     Lex.Lex();  // Skip '#'.
01188     return ParseSimpleValue(CurRec, ItemType, Mode);
01189   case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
01190   case tgtok::BinaryIntVal: {
01191     auto BinaryVal = Lex.getCurBinaryIntVal();
01192     SmallVector<Init*, 16> Bits(BinaryVal.second);
01193     for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
01194       Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
01195     R = BitsInit::get(Bits);
01196     Lex.Lex();
01197     break;
01198   }
01199   case tgtok::StrVal: {
01200     std::string Val = Lex.getCurStrVal();
01201     Lex.Lex();
01202 
01203     // Handle multiple consecutive concatenated strings.
01204     while (Lex.getCode() == tgtok::StrVal) {
01205       Val += Lex.getCurStrVal();
01206       Lex.Lex();
01207     }
01208 
01209     R = StringInit::get(Val);
01210     break;
01211   }
01212   case tgtok::CodeFragment:
01213     R = StringInit::get(Lex.getCurStrVal());
01214     Lex.Lex();
01215     break;
01216   case tgtok::question:
01217     R = UnsetInit::get();
01218     Lex.Lex();
01219     break;
01220   case tgtok::Id: {
01221     SMLoc NameLoc = Lex.getLoc();
01222     std::string Name = Lex.getCurStrVal();
01223     if (Lex.Lex() != tgtok::less)  // consume the Id.
01224       return ParseIDValue(CurRec, Name, NameLoc, Mode);    // Value ::= IDValue
01225 
01226     // Value ::= ID '<' ValueListNE '>'
01227     if (Lex.Lex() == tgtok::greater) {
01228       TokError("expected non-empty value list");
01229       return nullptr;
01230     }
01231 
01232     // This is a CLASS<initvalslist> expression.  This is supposed to synthesize
01233     // a new anonymous definition, deriving from CLASS<initvalslist> with no
01234     // body.
01235     Record *Class = Records.getClass(Name);
01236     if (!Class) {
01237       Error(NameLoc, "Expected a class name, got '" + Name + "'");
01238       return nullptr;
01239     }
01240 
01241     std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
01242     if (ValueList.empty()) return nullptr;
01243 
01244     if (Lex.getCode() != tgtok::greater) {
01245       TokError("expected '>' at end of value list");
01246       return nullptr;
01247     }
01248     Lex.Lex();  // eat the '>'
01249     SMLoc EndLoc = Lex.getLoc();
01250 
01251     // Create the new record, set it as CurRec temporarily.
01252     Record *NewRec = new Record(GetNewAnonymousName(), NameLoc, Records,
01253                                 /*IsAnonymous=*/true);
01254     SubClassReference SCRef;
01255     SCRef.RefRange = SMRange(NameLoc, EndLoc);
01256     SCRef.Rec = Class;
01257     SCRef.TemplateArgs = ValueList;
01258     // Add info about the subclass to NewRec.
01259     if (AddSubClass(NewRec, SCRef)) {
01260       delete NewRec;
01261       return nullptr;
01262     }
01263     if (!CurMultiClass) {
01264       NewRec->resolveReferences();
01265       Records.addDef(NewRec);
01266     } else {
01267       // This needs to get resolved once the multiclass template arguments are
01268       // known before any use.
01269       NewRec->setResolveFirst(true);
01270       // Otherwise, we're inside a multiclass, add it to the multiclass.
01271       CurMultiClass->DefPrototypes.push_back(NewRec);
01272 
01273       // Copy the template arguments for the multiclass into the def.
01274       const std::vector<Init *> &TArgs =
01275                                   CurMultiClass->Rec.getTemplateArgs();
01276 
01277       for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
01278         const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
01279         assert(RV && "Template arg doesn't exist?");
01280         NewRec->addValue(*RV);
01281       }
01282 
01283       // We can't return the prototype def here, instead return:
01284       // !cast<ItemType>(!strconcat(NAME, AnonName)).
01285       const RecordVal *MCNameRV = CurMultiClass->Rec.getValue("NAME");
01286       assert(MCNameRV && "multiclass record must have a NAME");
01287 
01288       return UnOpInit::get(UnOpInit::CAST,
01289                            BinOpInit::get(BinOpInit::STRCONCAT,
01290                                           VarInit::get(MCNameRV->getName(),
01291                                                        MCNameRV->getType()),
01292                                           NewRec->getNameInit(),
01293                                           StringRecTy::get()),
01294                            Class->getDefInit()->getType());
01295     }
01296 
01297     // The result of the expression is a reference to the new record.
01298     return DefInit::get(NewRec);
01299   }
01300   case tgtok::l_brace: {           // Value ::= '{' ValueList '}'
01301     SMLoc BraceLoc = Lex.getLoc();
01302     Lex.Lex(); // eat the '{'
01303     std::vector<Init*> Vals;
01304 
01305     if (Lex.getCode() != tgtok::r_brace) {
01306       Vals = ParseValueList(CurRec);
01307       if (Vals.empty()) return nullptr;
01308     }
01309     if (Lex.getCode() != tgtok::r_brace) {
01310       TokError("expected '}' at end of bit list value");
01311       return nullptr;
01312     }
01313     Lex.Lex();  // eat the '}'
01314 
01315     SmallVector<Init *, 16> NewBits;
01316 
01317     // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
01318     // first.  We'll first read everything in to a vector, then we can reverse
01319     // it to get the bits in the correct order for the BitsInit value.
01320     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
01321       // FIXME: The following two loops would not be duplicated
01322       //        if the API was a little more orthogonal.
01323 
01324       // bits<n> values are allowed to initialize n bits.
01325       if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
01326         for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
01327           NewBits.push_back(BI->getBit((e - i) - 1));
01328         continue;
01329       }
01330       // bits<n> can also come from variable initializers.
01331       if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
01332         if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
01333           for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
01334             NewBits.push_back(VI->getBit((e - i) - 1));
01335           continue;
01336         }
01337         // Fallthrough to try convert this to a bit.
01338       }
01339       // All other values must be convertible to just a single bit.
01340       Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
01341       if (!Bit) {
01342         Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
01343               ") is not convertable to a bit");
01344         return nullptr;
01345       }
01346       NewBits.push_back(Bit);
01347     }
01348     std::reverse(NewBits.begin(), NewBits.end());
01349     return BitsInit::get(NewBits);
01350   }
01351   case tgtok::l_square: {          // Value ::= '[' ValueList ']'
01352     Lex.Lex(); // eat the '['
01353     std::vector<Init*> Vals;
01354 
01355     RecTy *DeducedEltTy = nullptr;
01356     ListRecTy *GivenListTy = nullptr;
01357 
01358     if (ItemType) {
01359       ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
01360       if (!ListType) {
01361         std::string s;
01362         raw_string_ostream ss(s);
01363         ss << "Type mismatch for list, expected list type, got "
01364            << ItemType->getAsString();
01365         TokError(ss.str());
01366         return nullptr;
01367       }
01368       GivenListTy = ListType;
01369     }
01370 
01371     if (Lex.getCode() != tgtok::r_square) {
01372       Vals = ParseValueList(CurRec, nullptr,
01373                             GivenListTy ? GivenListTy->getElementType() : nullptr);
01374       if (Vals.empty()) return nullptr;
01375     }
01376     if (Lex.getCode() != tgtok::r_square) {
01377       TokError("expected ']' at end of list value");
01378       return nullptr;
01379     }
01380     Lex.Lex();  // eat the ']'
01381 
01382     RecTy *GivenEltTy = nullptr;
01383     if (Lex.getCode() == tgtok::less) {
01384       // Optional list element type
01385       Lex.Lex();  // eat the '<'
01386 
01387       GivenEltTy = ParseType();
01388       if (!GivenEltTy) {
01389         // Couldn't parse element type
01390         return nullptr;
01391       }
01392 
01393       if (Lex.getCode() != tgtok::greater) {
01394         TokError("expected '>' at end of list element type");
01395         return nullptr;
01396       }
01397       Lex.Lex();  // eat the '>'
01398     }
01399 
01400     // Check elements
01401     RecTy *EltTy = nullptr;
01402     for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
01403          i != ie;
01404          ++i) {
01405       TypedInit *TArg = dyn_cast<TypedInit>(*i);
01406       if (!TArg) {
01407         TokError("Untyped list element");
01408         return nullptr;
01409       }
01410       if (EltTy) {
01411         EltTy = resolveTypes(EltTy, TArg->getType());
01412         if (!EltTy) {
01413           TokError("Incompatible types in list elements");
01414           return nullptr;
01415         }
01416       } else {
01417         EltTy = TArg->getType();
01418       }
01419     }
01420 
01421     if (GivenEltTy) {
01422       if (EltTy) {
01423         // Verify consistency
01424         if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
01425           TokError("Incompatible types in list elements");
01426           return nullptr;
01427         }
01428       }
01429       EltTy = GivenEltTy;
01430     }
01431 
01432     if (!EltTy) {
01433       if (!ItemType) {
01434         TokError("No type for list");
01435         return nullptr;
01436       }
01437       DeducedEltTy = GivenListTy->getElementType();
01438     } else {
01439       // Make sure the deduced type is compatible with the given type
01440       if (GivenListTy) {
01441         if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
01442           TokError("Element type mismatch for list");
01443           return nullptr;
01444         }
01445       }
01446       DeducedEltTy = EltTy;
01447     }
01448 
01449     return ListInit::get(Vals, DeducedEltTy);
01450   }
01451   case tgtok::l_paren: {         // Value ::= '(' IDValue DagArgList ')'
01452     Lex.Lex();   // eat the '('
01453     if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
01454       TokError("expected identifier in dag init");
01455       return nullptr;
01456     }
01457 
01458     Init *Operator = ParseValue(CurRec);
01459     if (!Operator) return nullptr;
01460 
01461     // If the operator name is present, parse it.
01462     std::string OperatorName;
01463     if (Lex.getCode() == tgtok::colon) {
01464       if (Lex.Lex() != tgtok::VarName) { // eat the ':'
01465         TokError("expected variable name in dag operator");
01466         return nullptr;
01467       }
01468       OperatorName = Lex.getCurStrVal();
01469       Lex.Lex();  // eat the VarName.
01470     }
01471 
01472     std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
01473     if (Lex.getCode() != tgtok::r_paren) {
01474       DagArgs = ParseDagArgList(CurRec);
01475       if (DagArgs.empty()) return nullptr;
01476     }
01477 
01478     if (Lex.getCode() != tgtok::r_paren) {
01479       TokError("expected ')' in dag init");
01480       return nullptr;
01481     }
01482     Lex.Lex();  // eat the ')'
01483 
01484     return DagInit::get(Operator, OperatorName, DagArgs);
01485   }
01486 
01487   case tgtok::XHead:
01488   case tgtok::XTail:
01489   case tgtok::XEmpty:
01490   case tgtok::XCast:  // Value ::= !unop '(' Value ')'
01491   case tgtok::XConcat:
01492   case tgtok::XADD:
01493   case tgtok::XAND:
01494   case tgtok::XSRA:
01495   case tgtok::XSRL:
01496   case tgtok::XSHL:
01497   case tgtok::XEq:
01498   case tgtok::XListConcat:
01499   case tgtok::XStrConcat:   // Value ::= !binop '(' Value ',' Value ')'
01500   case tgtok::XIf:
01501   case tgtok::XForEach:
01502   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
01503     return ParseOperation(CurRec, ItemType);
01504   }
01505   }
01506 
01507   return R;
01508 }
01509 
01510 /// ParseValue - Parse a tblgen value.  This returns null on error.
01511 ///
01512 ///   Value       ::= SimpleValue ValueSuffix*
01513 ///   ValueSuffix ::= '{' BitList '}'
01514 ///   ValueSuffix ::= '[' BitList ']'
01515 ///   ValueSuffix ::= '.' ID
01516 ///
01517 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
01518   Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
01519   if (!Result) return nullptr;
01520 
01521   // Parse the suffixes now if present.
01522   while (1) {
01523     switch (Lex.getCode()) {
01524     default: return Result;
01525     case tgtok::l_brace: {
01526       if (Mode == ParseNameMode || Mode == ParseForeachMode)
01527         // This is the beginning of the object body.
01528         return Result;
01529 
01530       SMLoc CurlyLoc = Lex.getLoc();
01531       Lex.Lex(); // eat the '{'
01532       std::vector<unsigned> Ranges = ParseRangeList();
01533       if (Ranges.empty()) return nullptr;
01534 
01535       // Reverse the bitlist.
01536       std::reverse(Ranges.begin(), Ranges.end());
01537       Result = Result->convertInitializerBitRange(Ranges);
01538       if (!Result) {
01539         Error(CurlyLoc, "Invalid bit range for value");
01540         return nullptr;
01541       }
01542 
01543       // Eat the '}'.
01544       if (Lex.getCode() != tgtok::r_brace) {
01545         TokError("expected '}' at end of bit range list");
01546         return nullptr;
01547       }
01548       Lex.Lex();
01549       break;
01550     }
01551     case tgtok::l_square: {
01552       SMLoc SquareLoc = Lex.getLoc();
01553       Lex.Lex(); // eat the '['
01554       std::vector<unsigned> Ranges = ParseRangeList();
01555       if (Ranges.empty()) return nullptr;
01556 
01557       Result = Result->convertInitListSlice(Ranges);
01558       if (!Result) {
01559         Error(SquareLoc, "Invalid range for list slice");
01560         return nullptr;
01561       }
01562 
01563       // Eat the ']'.
01564       if (Lex.getCode() != tgtok::r_square) {
01565         TokError("expected ']' at end of list slice");
01566         return nullptr;
01567       }
01568       Lex.Lex();
01569       break;
01570     }
01571     case tgtok::period:
01572       if (Lex.Lex() != tgtok::Id) {  // eat the .
01573         TokError("expected field identifier after '.'");
01574         return nullptr;
01575       }
01576       if (!Result->getFieldType(Lex.getCurStrVal())) {
01577         TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
01578                  Result->getAsString() + "'");
01579         return nullptr;
01580       }
01581       Result = FieldInit::get(Result, Lex.getCurStrVal());
01582       Lex.Lex();  // eat field name
01583       break;
01584 
01585     case tgtok::paste:
01586       SMLoc PasteLoc = Lex.getLoc();
01587 
01588       // Create a !strconcat() operation, first casting each operand to
01589       // a string if necessary.
01590 
01591       TypedInit *LHS = dyn_cast<TypedInit>(Result);
01592       if (!LHS) {
01593         Error(PasteLoc, "LHS of paste is not typed!");
01594         return nullptr;
01595       }
01596   
01597       if (LHS->getType() != StringRecTy::get()) {
01598         LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
01599       }
01600 
01601       TypedInit *RHS = nullptr;
01602 
01603       Lex.Lex();  // Eat the '#'.
01604       switch (Lex.getCode()) { 
01605       case tgtok::colon:
01606       case tgtok::semi:
01607       case tgtok::l_brace:
01608         // These are all of the tokens that can begin an object body.
01609         // Some of these can also begin values but we disallow those cases
01610         // because they are unlikely to be useful.
01611        
01612         // Trailing paste, concat with an empty string.
01613         RHS = StringInit::get("");
01614         break;
01615 
01616       default:
01617         Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
01618         RHS = dyn_cast<TypedInit>(RHSResult);
01619         if (!RHS) {
01620           Error(PasteLoc, "RHS of paste is not typed!");
01621           return nullptr;
01622         }
01623 
01624         if (RHS->getType() != StringRecTy::get()) {
01625           RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
01626         }
01627   
01628         break;
01629       }
01630 
01631       Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
01632                               StringRecTy::get())->Fold(CurRec, CurMultiClass);
01633       break;
01634     }
01635   }
01636 }
01637 
01638 /// ParseDagArgList - Parse the argument list for a dag literal expression.
01639 ///
01640 ///    DagArg     ::= Value (':' VARNAME)?
01641 ///    DagArg     ::= VARNAME
01642 ///    DagArgList ::= DagArg
01643 ///    DagArgList ::= DagArgList ',' DagArg
01644 std::vector<std::pair<llvm::Init*, std::string> >
01645 TGParser::ParseDagArgList(Record *CurRec) {
01646   std::vector<std::pair<llvm::Init*, std::string> > Result;
01647 
01648   while (1) {
01649     // DagArg ::= VARNAME
01650     if (Lex.getCode() == tgtok::VarName) {
01651       // A missing value is treated like '?'.
01652       Result.push_back(std::make_pair(UnsetInit::get(), Lex.getCurStrVal()));
01653       Lex.Lex();
01654     } else {
01655       // DagArg ::= Value (':' VARNAME)?
01656       Init *Val = ParseValue(CurRec);
01657       if (!Val)
01658         return std::vector<std::pair<llvm::Init*, std::string> >();
01659 
01660       // If the variable name is present, add it.
01661       std::string VarName;
01662       if (Lex.getCode() == tgtok::colon) {
01663         if (Lex.Lex() != tgtok::VarName) { // eat the ':'
01664           TokError("expected variable name in dag literal");
01665           return std::vector<std::pair<llvm::Init*, std::string> >();
01666         }
01667         VarName = Lex.getCurStrVal();
01668         Lex.Lex();  // eat the VarName.
01669       }
01670 
01671       Result.push_back(std::make_pair(Val, VarName));
01672     }
01673     if (Lex.getCode() != tgtok::comma) break;
01674     Lex.Lex(); // eat the ','
01675   }
01676 
01677   return Result;
01678 }
01679 
01680 
01681 /// ParseValueList - Parse a comma separated list of values, returning them as a
01682 /// vector.  Note that this always expects to be able to parse at least one
01683 /// value.  It returns an empty list if this is not possible.
01684 ///
01685 ///   ValueList ::= Value (',' Value)
01686 ///
01687 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
01688                                             RecTy *EltTy) {
01689   std::vector<Init*> Result;
01690   RecTy *ItemType = EltTy;
01691   unsigned int ArgN = 0;
01692   if (ArgsRec && !EltTy) {
01693     const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
01694     if (!TArgs.size()) {
01695       TokError("template argument provided to non-template class");
01696       return std::vector<Init*>();
01697     }
01698     const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
01699     if (!RV) {
01700       errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
01701         << ")\n";
01702     }
01703     assert(RV && "Template argument record not found??");
01704     ItemType = RV->getType();
01705     ++ArgN;
01706   }
01707   Result.push_back(ParseValue(CurRec, ItemType));
01708   if (!Result.back()) return std::vector<Init*>();
01709 
01710   while (Lex.getCode() == tgtok::comma) {
01711     Lex.Lex();  // Eat the comma
01712 
01713     if (ArgsRec && !EltTy) {
01714       const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
01715       if (ArgN >= TArgs.size()) {
01716         TokError("too many template arguments");
01717         return std::vector<Init*>();
01718       }
01719       const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
01720       assert(RV && "Template argument record not found??");
01721       ItemType = RV->getType();
01722       ++ArgN;
01723     }
01724     Result.push_back(ParseValue(CurRec, ItemType));
01725     if (!Result.back()) return std::vector<Init*>();
01726   }
01727 
01728   return Result;
01729 }
01730 
01731 
01732 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
01733 /// empty string on error.  This can happen in a number of different context's,
01734 /// including within a def or in the template args for a def (which which case
01735 /// CurRec will be non-null) and within the template args for a multiclass (in
01736 /// which case CurRec will be null, but CurMultiClass will be set).  This can
01737 /// also happen within a def that is within a multiclass, which will set both
01738 /// CurRec and CurMultiClass.
01739 ///
01740 ///  Declaration ::= FIELD? Type ID ('=' Value)?
01741 ///
01742 Init *TGParser::ParseDeclaration(Record *CurRec,
01743                                        bool ParsingTemplateArgs) {
01744   // Read the field prefix if present.
01745   bool HasField = Lex.getCode() == tgtok::Field;
01746   if (HasField) Lex.Lex();
01747 
01748   RecTy *Type = ParseType();
01749   if (!Type) return nullptr;
01750 
01751   if (Lex.getCode() != tgtok::Id) {
01752     TokError("Expected identifier in declaration");
01753     return nullptr;
01754   }
01755 
01756   SMLoc IdLoc = Lex.getLoc();
01757   Init *DeclName = StringInit::get(Lex.getCurStrVal());
01758   Lex.Lex();
01759 
01760   if (ParsingTemplateArgs) {
01761     if (CurRec) {
01762       DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
01763     } else {
01764       assert(CurMultiClass);
01765     }
01766     if (CurMultiClass)
01767       DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
01768                              "::");
01769   }
01770 
01771   // Add the value.
01772   if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
01773     return nullptr;
01774 
01775   // If a value is present, parse it.
01776   if (Lex.getCode() == tgtok::equal) {
01777     Lex.Lex();
01778     SMLoc ValLoc = Lex.getLoc();
01779     Init *Val = ParseValue(CurRec, Type);
01780     if (!Val ||
01781         SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
01782       // Return the name, even if an error is thrown.  This is so that we can
01783       // continue to make some progress, even without the value having been
01784       // initialized.
01785       return DeclName;
01786   }
01787 
01788   return DeclName;
01789 }
01790 
01791 /// ParseForeachDeclaration - Read a foreach declaration, returning
01792 /// the name of the declared object or a NULL Init on error.  Return
01793 /// the name of the parsed initializer list through ForeachListName.
01794 ///
01795 ///  ForeachDeclaration ::= ID '=' '[' ValueList ']'
01796 ///  ForeachDeclaration ::= ID '=' '{' RangeList '}'
01797 ///  ForeachDeclaration ::= ID '=' RangePiece
01798 ///
01799 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
01800   if (Lex.getCode() != tgtok::Id) {
01801     TokError("Expected identifier in foreach declaration");
01802     return nullptr;
01803   }
01804 
01805   Init *DeclName = StringInit::get(Lex.getCurStrVal());
01806   Lex.Lex();
01807 
01808   // If a value is present, parse it.
01809   if (Lex.getCode() != tgtok::equal) {
01810     TokError("Expected '=' in foreach declaration");
01811     return nullptr;
01812   }
01813   Lex.Lex();  // Eat the '='
01814 
01815   RecTy *IterType = nullptr;
01816   std::vector<unsigned> Ranges;
01817 
01818   switch (Lex.getCode()) {
01819   default: TokError("Unknown token when expecting a range list"); return nullptr;
01820   case tgtok::l_square: { // '[' ValueList ']'
01821     Init *List = ParseSimpleValue(nullptr, nullptr, ParseForeachMode);
01822     ForeachListValue = dyn_cast<ListInit>(List);
01823     if (!ForeachListValue) {
01824       TokError("Expected a Value list");
01825       return nullptr;
01826     }
01827     RecTy *ValueType = ForeachListValue->getType();
01828     ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
01829     if (!ListType) {
01830       TokError("Value list is not of list type");
01831       return nullptr;
01832     }
01833     IterType = ListType->getElementType();
01834     break;
01835   }
01836 
01837   case tgtok::IntVal: { // RangePiece.
01838     if (ParseRangePiece(Ranges))
01839       return nullptr;
01840     break;
01841   }
01842 
01843   case tgtok::l_brace: { // '{' RangeList '}'
01844     Lex.Lex(); // eat the '{'
01845     Ranges = ParseRangeList();
01846     if (Lex.getCode() != tgtok::r_brace) {
01847       TokError("expected '}' at end of bit range list");
01848       return nullptr;
01849     }
01850     Lex.Lex();
01851     break;
01852   }
01853   }
01854 
01855   if (!Ranges.empty()) {
01856     assert(!IterType && "Type already initialized?");
01857     IterType = IntRecTy::get();
01858     std::vector<Init*> Values;
01859     for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
01860       Values.push_back(IntInit::get(Ranges[i]));
01861     ForeachListValue = ListInit::get(Values, IterType);
01862   }
01863 
01864   if (!IterType)
01865     return nullptr;
01866 
01867   return VarInit::get(DeclName, IterType);
01868 }
01869 
01870 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
01871 /// sequence of template-declarations in <>'s.  If CurRec is non-null, these are
01872 /// template args for a def, which may or may not be in a multiclass.  If null,
01873 /// these are the template args for a multiclass.
01874 ///
01875 ///    TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
01876 ///
01877 bool TGParser::ParseTemplateArgList(Record *CurRec) {
01878   assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
01879   Lex.Lex(); // eat the '<'
01880 
01881   Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
01882 
01883   // Read the first declaration.
01884   Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
01885   if (!TemplArg)
01886     return true;
01887 
01888   TheRecToAddTo->addTemplateArg(TemplArg);
01889 
01890   while (Lex.getCode() == tgtok::comma) {
01891     Lex.Lex(); // eat the ','
01892 
01893     // Read the following declarations.
01894     TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
01895     if (!TemplArg)
01896       return true;
01897     TheRecToAddTo->addTemplateArg(TemplArg);
01898   }
01899 
01900   if (Lex.getCode() != tgtok::greater)
01901     return TokError("expected '>' at end of template argument list");
01902   Lex.Lex(); // eat the '>'.
01903   return false;
01904 }
01905 
01906 
01907 /// ParseBodyItem - Parse a single item at within the body of a def or class.
01908 ///
01909 ///   BodyItem ::= Declaration ';'
01910 ///   BodyItem ::= LET ID OptionalBitList '=' Value ';'
01911 bool TGParser::ParseBodyItem(Record *CurRec) {
01912   if (Lex.getCode() != tgtok::Let) {
01913     if (!ParseDeclaration(CurRec, false))
01914       return true;
01915 
01916     if (Lex.getCode() != tgtok::semi)
01917       return TokError("expected ';' after declaration");
01918     Lex.Lex();
01919     return false;
01920   }
01921 
01922   // LET ID OptionalRangeList '=' Value ';'
01923   if (Lex.Lex() != tgtok::Id)
01924     return TokError("expected field identifier after let");
01925 
01926   SMLoc IdLoc = Lex.getLoc();
01927   std::string FieldName = Lex.getCurStrVal();
01928   Lex.Lex();  // eat the field name.
01929 
01930   std::vector<unsigned> BitList;
01931   if (ParseOptionalBitList(BitList))
01932     return true;
01933   std::reverse(BitList.begin(), BitList.end());
01934 
01935   if (Lex.getCode() != tgtok::equal)
01936     return TokError("expected '=' in let expression");
01937   Lex.Lex();  // eat the '='.
01938 
01939   RecordVal *Field = CurRec->getValue(FieldName);
01940   if (!Field)
01941     return TokError("Value '" + FieldName + "' unknown!");
01942 
01943   RecTy *Type = Field->getType();
01944 
01945   Init *Val = ParseValue(CurRec, Type);
01946   if (!Val) return true;
01947 
01948   if (Lex.getCode() != tgtok::semi)
01949     return TokError("expected ';' after let expression");
01950   Lex.Lex();
01951 
01952   return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
01953 }
01954 
01955 /// ParseBody - Read the body of a class or def.  Return true on error, false on
01956 /// success.
01957 ///
01958 ///   Body     ::= ';'
01959 ///   Body     ::= '{' BodyList '}'
01960 ///   BodyList BodyItem*
01961 ///
01962 bool TGParser::ParseBody(Record *CurRec) {
01963   // If this is a null definition, just eat the semi and return.
01964   if (Lex.getCode() == tgtok::semi) {
01965     Lex.Lex();
01966     return false;
01967   }
01968 
01969   if (Lex.getCode() != tgtok::l_brace)
01970     return TokError("Expected ';' or '{' to start body");
01971   // Eat the '{'.
01972   Lex.Lex();
01973 
01974   while (Lex.getCode() != tgtok::r_brace)
01975     if (ParseBodyItem(CurRec))
01976       return true;
01977 
01978   // Eat the '}'.
01979   Lex.Lex();
01980   return false;
01981 }
01982 
01983 /// \brief Apply the current let bindings to \a CurRec.
01984 /// \returns true on error, false otherwise.
01985 bool TGParser::ApplyLetStack(Record *CurRec) {
01986   for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
01987     for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
01988       if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
01989                    LetStack[i][j].Bits, LetStack[i][j].Value))
01990         return true;
01991   return false;
01992 }
01993 
01994 /// ParseObjectBody - Parse the body of a def or class.  This consists of an
01995 /// optional ClassList followed by a Body.  CurRec is the current def or class
01996 /// that is being parsed.
01997 ///
01998 ///   ObjectBody      ::= BaseClassList Body
01999 ///   BaseClassList   ::= /*empty*/
02000 ///   BaseClassList   ::= ':' BaseClassListNE
02001 ///   BaseClassListNE ::= SubClassRef (',' SubClassRef)*
02002 ///
02003 bool TGParser::ParseObjectBody(Record *CurRec) {
02004   // If there is a baseclass list, read it.
02005   if (Lex.getCode() == tgtok::colon) {
02006     Lex.Lex();
02007 
02008     // Read all of the subclasses.
02009     SubClassReference SubClass = ParseSubClassReference(CurRec, false);
02010     while (1) {
02011       // Check for error.
02012       if (!SubClass.Rec) return true;
02013 
02014       // Add it.
02015       if (AddSubClass(CurRec, SubClass))
02016         return true;
02017 
02018       if (Lex.getCode() != tgtok::comma) break;
02019       Lex.Lex(); // eat ','.
02020       SubClass = ParseSubClassReference(CurRec, false);
02021     }
02022   }
02023 
02024   if (ApplyLetStack(CurRec))
02025     return true;
02026 
02027   return ParseBody(CurRec);
02028 }
02029 
02030 /// ParseDef - Parse and return a top level or multiclass def, return the record
02031 /// corresponding to it.  This returns null on error.
02032 ///
02033 ///   DefInst ::= DEF ObjectName ObjectBody
02034 ///
02035 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
02036   SMLoc DefLoc = Lex.getLoc();
02037   assert(Lex.getCode() == tgtok::Def && "Unknown tok");
02038   Lex.Lex();  // Eat the 'def' token.
02039 
02040   // Parse ObjectName and make a record for it.
02041   Record *CurRec;
02042   bool CurRecOwnershipTransferred = false;
02043   Init *Name = ParseObjectName(CurMultiClass);
02044   if (Name)
02045     CurRec = new Record(Name, DefLoc, Records);
02046   else
02047     CurRec = new Record(GetNewAnonymousName(), DefLoc, Records,
02048                         /*IsAnonymous=*/true);
02049 
02050   if (!CurMultiClass && Loops.empty()) {
02051     // Top-level def definition.
02052 
02053     // Ensure redefinition doesn't happen.
02054     if (Records.getDef(CurRec->getNameInitAsString())) {
02055       Error(DefLoc, "def '" + CurRec->getNameInitAsString()
02056             + "' already defined");
02057       delete CurRec;
02058       return true;
02059     }
02060     Records.addDef(CurRec);
02061     CurRecOwnershipTransferred = true;
02062 
02063     if (ParseObjectBody(CurRec))
02064       return true;
02065   } else if (CurMultiClass) {
02066     // Parse the body before adding this prototype to the DefPrototypes vector.
02067     // That way implicit definitions will be added to the DefPrototypes vector
02068     // before this object, instantiated prior to defs derived from this object,
02069     // and this available for indirect name resolution when defs derived from
02070     // this object are instantiated.
02071     if (ParseObjectBody(CurRec)) {
02072       delete CurRec;
02073       return true;
02074     }
02075 
02076     // Otherwise, a def inside a multiclass, add it to the multiclass.
02077     for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
02078       if (CurMultiClass->DefPrototypes[i]->getNameInit()
02079           == CurRec->getNameInit()) {
02080         Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
02081               "' already defined in this multiclass!");
02082         delete CurRec;
02083         return true;
02084       }
02085     CurMultiClass->DefPrototypes.push_back(CurRec);
02086     CurRecOwnershipTransferred = true;
02087   } else if (ParseObjectBody(CurRec)) {
02088     delete CurRec;
02089     return true;
02090   }
02091 
02092   if (!CurMultiClass)  // Def's in multiclasses aren't really defs.
02093     // See Record::setName().  This resolve step will see any new name
02094     // for the def that might have been created when resolving
02095     // inheritance, values and arguments above.
02096     CurRec->resolveReferences();
02097 
02098   // If ObjectBody has template arguments, it's an error.
02099   assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
02100 
02101   if (CurMultiClass) {
02102     // Copy the template arguments for the multiclass into the def.
02103     const std::vector<Init *> &TArgs =
02104                                 CurMultiClass->Rec.getTemplateArgs();
02105 
02106     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
02107       const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
02108       assert(RV && "Template arg doesn't exist?");
02109       CurRec->addValue(*RV);
02110     }
02111   }
02112 
02113   if (ProcessForeachDefs(CurRec, DefLoc)) {
02114     Error(DefLoc,
02115           "Could not process loops for def" + CurRec->getNameInitAsString());
02116     if (!CurRecOwnershipTransferred)
02117       delete CurRec;
02118     return true;
02119   }
02120 
02121   if (!CurRecOwnershipTransferred)
02122     delete CurRec;
02123   return false;
02124 }
02125 
02126 /// ParseForeach - Parse a for statement.  Return the record corresponding
02127 /// to it.  This returns true on error.
02128 ///
02129 ///   Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
02130 ///   Foreach ::= FOREACH Declaration IN Object
02131 ///
02132 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
02133   assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
02134   Lex.Lex();  // Eat the 'for' token.
02135 
02136   // Make a temporary object to record items associated with the for
02137   // loop.
02138   ListInit *ListValue = nullptr;
02139   VarInit *IterName = ParseForeachDeclaration(ListValue);
02140   if (!IterName)
02141     return TokError("expected declaration in for");
02142 
02143   if (Lex.getCode() != tgtok::In)
02144     return TokError("Unknown tok");
02145   Lex.Lex();  // Eat the in
02146 
02147   // Create a loop object and remember it.
02148   Loops.push_back(ForeachLoop(IterName, ListValue));
02149 
02150   if (Lex.getCode() != tgtok::l_brace) {
02151     // FOREACH Declaration IN Object
02152     if (ParseObject(CurMultiClass))
02153       return true;
02154   }
02155   else {
02156     SMLoc BraceLoc = Lex.getLoc();
02157     // Otherwise, this is a group foreach.
02158     Lex.Lex();  // eat the '{'.
02159 
02160     // Parse the object list.
02161     if (ParseObjectList(CurMultiClass))
02162       return true;
02163 
02164     if (Lex.getCode() != tgtok::r_brace) {
02165       TokError("expected '}' at end of foreach command");
02166       return Error(BraceLoc, "to match this '{'");
02167     }
02168     Lex.Lex();  // Eat the }
02169   }
02170 
02171   // We've processed everything in this loop.
02172   Loops.pop_back();
02173 
02174   return false;
02175 }
02176 
02177 /// ParseClass - Parse a tblgen class definition.
02178 ///
02179 ///   ClassInst ::= CLASS ID TemplateArgList? ObjectBody
02180 ///
02181 bool TGParser::ParseClass() {
02182   assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
02183   Lex.Lex();
02184 
02185   if (Lex.getCode() != tgtok::Id)
02186     return TokError("expected class name after 'class' keyword");
02187 
02188   Record *CurRec = Records.getClass(Lex.getCurStrVal());
02189   if (CurRec) {
02190     // If the body was previously defined, this is an error.
02191     if (CurRec->getValues().size() > 1 ||  // Account for NAME.
02192         !CurRec->getSuperClasses().empty() ||
02193         !CurRec->getTemplateArgs().empty())
02194       return TokError("Class '" + CurRec->getNameInitAsString()
02195                       + "' already defined");
02196   } else {
02197     // If this is the first reference to this class, create and add it.
02198     CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
02199     Records.addClass(CurRec);
02200   }
02201   Lex.Lex(); // eat the name.
02202 
02203   // If there are template args, parse them.
02204   if (Lex.getCode() == tgtok::less)
02205     if (ParseTemplateArgList(CurRec))
02206       return true;
02207 
02208   // Finally, parse the object body.
02209   return ParseObjectBody(CurRec);
02210 }
02211 
02212 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
02213 /// of LetRecords.
02214 ///
02215 ///   LetList ::= LetItem (',' LetItem)*
02216 ///   LetItem ::= ID OptionalRangeList '=' Value
02217 ///
02218 std::vector<LetRecord> TGParser::ParseLetList() {
02219   std::vector<LetRecord> Result;
02220 
02221   while (1) {
02222     if (Lex.getCode() != tgtok::Id) {
02223       TokError("expected identifier in let definition");
02224       return std::vector<LetRecord>();
02225     }
02226     std::string Name = Lex.getCurStrVal();
02227     SMLoc NameLoc = Lex.getLoc();
02228     Lex.Lex();  // Eat the identifier.
02229 
02230     // Check for an optional RangeList.
02231     std::vector<unsigned> Bits;
02232     if (ParseOptionalRangeList(Bits))
02233       return std::vector<LetRecord>();
02234     std::reverse(Bits.begin(), Bits.end());
02235 
02236     if (Lex.getCode() != tgtok::equal) {
02237       TokError("expected '=' in let expression");
02238       return std::vector<LetRecord>();
02239     }
02240     Lex.Lex();  // eat the '='.
02241 
02242     Init *Val = ParseValue(nullptr);
02243     if (!Val) return std::vector<LetRecord>();
02244 
02245     // Now that we have everything, add the record.
02246     Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
02247 
02248     if (Lex.getCode() != tgtok::comma)
02249       return Result;
02250     Lex.Lex();  // eat the comma.
02251   }
02252 }
02253 
02254 /// ParseTopLevelLet - Parse a 'let' at top level.  This can be a couple of
02255 /// different related productions. This works inside multiclasses too.
02256 ///
02257 ///   Object ::= LET LetList IN '{' ObjectList '}'
02258 ///   Object ::= LET LetList IN Object
02259 ///
02260 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
02261   assert(Lex.getCode() == tgtok::Let && "Unexpected token");
02262   Lex.Lex();
02263 
02264   // Add this entry to the let stack.
02265   std::vector<LetRecord> LetInfo = ParseLetList();
02266   if (LetInfo.empty()) return true;
02267   LetStack.push_back(LetInfo);
02268 
02269   if (Lex.getCode() != tgtok::In)
02270     return TokError("expected 'in' at end of top-level 'let'");
02271   Lex.Lex();
02272 
02273   // If this is a scalar let, just handle it now
02274   if (Lex.getCode() != tgtok::l_brace) {
02275     // LET LetList IN Object
02276     if (ParseObject(CurMultiClass))
02277       return true;
02278   } else {   // Object ::= LETCommand '{' ObjectList '}'
02279     SMLoc BraceLoc = Lex.getLoc();
02280     // Otherwise, this is a group let.
02281     Lex.Lex();  // eat the '{'.
02282 
02283     // Parse the object list.
02284     if (ParseObjectList(CurMultiClass))
02285       return true;
02286 
02287     if (Lex.getCode() != tgtok::r_brace) {
02288       TokError("expected '}' at end of top level let command");
02289       return Error(BraceLoc, "to match this '{'");
02290     }
02291     Lex.Lex();
02292   }
02293 
02294   // Outside this let scope, this let block is not active.
02295   LetStack.pop_back();
02296   return false;
02297 }
02298 
02299 /// ParseMultiClass - Parse a multiclass definition.
02300 ///
02301 ///  MultiClassInst ::= MULTICLASS ID TemplateArgList?
02302 ///                     ':' BaseMultiClassList '{' MultiClassObject+ '}'
02303 ///  MultiClassObject ::= DefInst
02304 ///  MultiClassObject ::= MultiClassInst
02305 ///  MultiClassObject ::= DefMInst
02306 ///  MultiClassObject ::= LETCommand '{' ObjectList '}'
02307 ///  MultiClassObject ::= LETCommand Object
02308 ///
02309 bool TGParser::ParseMultiClass() {
02310   assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
02311   Lex.Lex();  // Eat the multiclass token.
02312 
02313   if (Lex.getCode() != tgtok::Id)
02314     return TokError("expected identifier after multiclass for name");
02315   std::string Name = Lex.getCurStrVal();
02316 
02317   if (MultiClasses.count(Name))
02318     return TokError("multiclass '" + Name + "' already defined");
02319 
02320   CurMultiClass = MultiClasses[Name] = new MultiClass(Name, 
02321                                                       Lex.getLoc(), Records);
02322   Lex.Lex();  // Eat the identifier.
02323 
02324   // If there are template args, parse them.
02325   if (Lex.getCode() == tgtok::less)
02326     if (ParseTemplateArgList(nullptr))
02327       return true;
02328 
02329   bool inherits = false;
02330 
02331   // If there are submulticlasses, parse them.
02332   if (Lex.getCode() == tgtok::colon) {
02333     inherits = true;
02334 
02335     Lex.Lex();
02336 
02337     // Read all of the submulticlasses.
02338     SubMultiClassReference SubMultiClass =
02339       ParseSubMultiClassReference(CurMultiClass);
02340     while (1) {
02341       // Check for error.
02342       if (!SubMultiClass.MC) return true;
02343 
02344       // Add it.
02345       if (AddSubMultiClass(CurMultiClass, SubMultiClass))
02346         return true;
02347 
02348       if (Lex.getCode() != tgtok::comma) break;
02349       Lex.Lex(); // eat ','.
02350       SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
02351     }
02352   }
02353 
02354   if (Lex.getCode() != tgtok::l_brace) {
02355     if (!inherits)
02356       return TokError("expected '{' in multiclass definition");
02357     else if (Lex.getCode() != tgtok::semi)
02358       return TokError("expected ';' in multiclass definition");
02359     else
02360       Lex.Lex();  // eat the ';'.
02361   } else {
02362     if (Lex.Lex() == tgtok::r_brace)  // eat the '{'.
02363       return TokError("multiclass must contain at least one def");
02364 
02365     while (Lex.getCode() != tgtok::r_brace) {
02366       switch (Lex.getCode()) {
02367         default:
02368           return TokError("expected 'let', 'def' or 'defm' in multiclass body");
02369         case tgtok::Let:
02370         case tgtok::Def:
02371         case tgtok::Defm:
02372         case tgtok::Foreach:
02373           if (ParseObject(CurMultiClass))
02374             return true;
02375          break;
02376       }
02377     }
02378     Lex.Lex();  // eat the '}'.
02379   }
02380 
02381   CurMultiClass = nullptr;
02382   return false;
02383 }
02384 
02385 Record *TGParser::
02386 InstantiateMulticlassDef(MultiClass &MC,
02387                          Record *DefProto,
02388                          Init *&DefmPrefix,
02389                          SMRange DefmPrefixRange) {
02390   // We need to preserve DefProto so it can be reused for later
02391   // instantiations, so create a new Record to inherit from it.
02392 
02393   // Add in the defm name.  If the defm prefix is empty, give each
02394   // instantiated def a unique name.  Otherwise, if "#NAME#" exists in the
02395   // name, substitute the prefix for #NAME#.  Otherwise, use the defm name
02396   // as a prefix.
02397 
02398   bool IsAnonymous = false;
02399   if (!DefmPrefix) {
02400     DefmPrefix = StringInit::get(GetNewAnonymousName());
02401     IsAnonymous = true;
02402   }
02403 
02404   Init *DefName = DefProto->getNameInit();
02405 
02406   StringInit *DefNameString = dyn_cast<StringInit>(DefName);
02407 
02408   if (DefNameString) {
02409     // We have a fully expanded string so there are no operators to
02410     // resolve.  We should concatenate the given prefix and name.
02411     DefName =
02412       BinOpInit::get(BinOpInit::STRCONCAT,
02413                      UnOpInit::get(UnOpInit::CAST, DefmPrefix,
02414                                    StringRecTy::get())->Fold(DefProto, &MC),
02415                      DefName, StringRecTy::get())->Fold(DefProto, &MC);
02416   }
02417 
02418   // Make a trail of SMLocs from the multiclass instantiations.
02419   SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
02420   Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
02421   Record *CurRec = new Record(DefName, Locs, Records, IsAnonymous);
02422 
02423   SubClassReference Ref;
02424   Ref.RefRange = DefmPrefixRange;
02425   Ref.Rec = DefProto;
02426   AddSubClass(CurRec, Ref);
02427 
02428   // Set the value for NAME. We don't resolve references to it 'til later,
02429   // though, so that uses in nested multiclass names don't get
02430   // confused.
02431   if (SetValue(CurRec, Ref.RefRange.Start, "NAME", std::vector<unsigned>(),
02432                DefmPrefix)) {
02433     Error(DefmPrefixRange.Start, "Could not resolve "
02434           + CurRec->getNameInitAsString() + ":NAME to '"
02435           + DefmPrefix->getAsUnquotedString() + "'");
02436     delete CurRec;
02437     return nullptr;
02438   }
02439 
02440   // If the DefNameString didn't resolve, we probably have a reference to
02441   // NAME and need to replace it. We need to do at least this much greedily,
02442   // otherwise nested multiclasses will end up with incorrect NAME expansions.
02443   if (!DefNameString) {
02444     RecordVal *DefNameRV = CurRec->getValue("NAME");
02445     CurRec->resolveReferencesTo(DefNameRV);
02446   }
02447 
02448   if (!CurMultiClass) {
02449     // Now that we're at the top level, resolve all NAME references
02450     // in the resultant defs that weren't in the def names themselves.
02451     RecordVal *DefNameRV = CurRec->getValue("NAME");
02452     CurRec->resolveReferencesTo(DefNameRV);
02453 
02454     // Now that NAME references are resolved and we're at the top level of
02455     // any multiclass expansions, add the record to the RecordKeeper. If we are
02456     // currently in a multiclass, it means this defm appears inside a
02457     // multiclass and its name won't be fully resolvable until we see
02458     // the top-level defm.  Therefore, we don't add this to the
02459     // RecordKeeper at this point.  If we did we could get duplicate
02460     // defs as more than one probably refers to NAME or some other
02461     // common internal placeholder.
02462 
02463     // Ensure redefinition doesn't happen.
02464     if (Records.getDef(CurRec->getNameInitAsString())) {
02465       Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
02466             "' already defined, instantiating defm with subdef '" + 
02467             DefProto->getNameInitAsString() + "'");
02468       delete CurRec;
02469       return nullptr;
02470     }
02471 
02472     Records.addDef(CurRec);
02473   }
02474 
02475   return CurRec;
02476 }
02477 
02478 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
02479                                         Record *CurRec,
02480                                         SMLoc DefmPrefixLoc,
02481                                         SMLoc SubClassLoc,
02482                                         const std::vector<Init *> &TArgs,
02483                                         std::vector<Init *> &TemplateVals,
02484                                         bool DeleteArgs) {
02485   // Loop over all of the template arguments, setting them to the specified
02486   // value or leaving them as the default if necessary.
02487   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
02488     // Check if a value is specified for this temp-arg.
02489     if (i < TemplateVals.size()) {
02490       // Set it now.
02491       if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
02492                    TemplateVals[i]))
02493         return true;
02494         
02495       // Resolve it next.
02496       CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
02497 
02498       if (DeleteArgs)
02499         // Now remove it.
02500         CurRec->removeValue(TArgs[i]);
02501         
02502     } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
02503       return Error(SubClassLoc, "value not specified for template argument #"+
02504                    utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
02505                    + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
02506                    + "'");
02507     }
02508   }
02509   return false;
02510 }
02511 
02512 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
02513                                     Record *CurRec,
02514                                     Record *DefProto,
02515                                     SMLoc DefmPrefixLoc) {
02516   // If the mdef is inside a 'let' expression, add to each def.
02517   if (ApplyLetStack(CurRec))
02518     return Error(DefmPrefixLoc, "when instantiating this defm");
02519 
02520   // Don't create a top level definition for defm inside multiclasses,
02521   // instead, only update the prototypes and bind the template args
02522   // with the new created definition.
02523   if (!CurMultiClass)
02524     return false;
02525   for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
02526        i != e; ++i)
02527     if (CurMultiClass->DefPrototypes[i]->getNameInit()
02528         == CurRec->getNameInit())
02529       return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
02530                    "' already defined in this multiclass!");
02531   CurMultiClass->DefPrototypes.push_back(CurRec);
02532 
02533   // Copy the template arguments for the multiclass into the new def.
02534   const std::vector<Init *> &TA =
02535     CurMultiClass->Rec.getTemplateArgs();
02536 
02537   for (unsigned i = 0, e = TA.size(); i != e; ++i) {
02538     const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
02539     assert(RV && "Template arg doesn't exist?");
02540     CurRec->addValue(*RV);
02541   }
02542 
02543   return false;
02544 }
02545 
02546 /// ParseDefm - Parse the instantiation of a multiclass.
02547 ///
02548 ///   DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
02549 ///
02550 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
02551   assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
02552   SMLoc DefmLoc = Lex.getLoc();
02553   Init *DefmPrefix = nullptr;
02554 
02555   if (Lex.Lex() == tgtok::Id) {  // eat the defm.
02556     DefmPrefix = ParseObjectName(CurMultiClass);
02557   }
02558 
02559   SMLoc DefmPrefixEndLoc = Lex.getLoc();
02560   if (Lex.getCode() != tgtok::colon)
02561     return TokError("expected ':' after defm identifier");
02562 
02563   // Keep track of the new generated record definitions.
02564   std::vector<Record*> NewRecDefs;
02565 
02566   // This record also inherits from a regular class (non-multiclass)?
02567   bool InheritFromClass = false;
02568 
02569   // eat the colon.
02570   Lex.Lex();
02571 
02572   SMLoc SubClassLoc = Lex.getLoc();
02573   SubClassReference Ref = ParseSubClassReference(nullptr, true);
02574 
02575   while (1) {
02576     if (!Ref.Rec) return true;
02577 
02578     // To instantiate a multiclass, we need to first get the multiclass, then
02579     // instantiate each def contained in the multiclass with the SubClassRef
02580     // template parameters.
02581     MultiClass *MC = MultiClasses[Ref.Rec->getName()];
02582     assert(MC && "Didn't lookup multiclass correctly?");
02583     std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
02584 
02585     // Verify that the correct number of template arguments were specified.
02586     const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
02587     if (TArgs.size() < TemplateVals.size())
02588       return Error(SubClassLoc,
02589                    "more template args specified than multiclass expects");
02590 
02591     // Loop over all the def's in the multiclass, instantiating each one.
02592     for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
02593       Record *DefProto = MC->DefPrototypes[i];
02594 
02595       Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix,
02596                                                 SMRange(DefmLoc,
02597                                                         DefmPrefixEndLoc));
02598       if (!CurRec)
02599         return true;
02600 
02601       if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
02602                                    TArgs, TemplateVals, true/*Delete args*/))
02603         return Error(SubClassLoc, "could not instantiate def");
02604 
02605       if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmLoc))
02606         return Error(SubClassLoc, "could not instantiate def");
02607 
02608       // Defs that can be used by other definitions should be fully resolved
02609       // before any use.
02610       if (DefProto->isResolveFirst() && !CurMultiClass) {
02611         CurRec->resolveReferences();
02612         CurRec->setResolveFirst(false);
02613       }
02614       NewRecDefs.push_back(CurRec);
02615     }
02616 
02617 
02618     if (Lex.getCode() != tgtok::comma) break;
02619     Lex.Lex(); // eat ','.
02620 
02621     if (Lex.getCode() != tgtok::Id)
02622       return TokError("expected identifier");
02623 
02624     SubClassLoc = Lex.getLoc();
02625 
02626     // A defm can inherit from regular classes (non-multiclass) as
02627     // long as they come in the end of the inheritance list.
02628     InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
02629 
02630     if (InheritFromClass)
02631       break;
02632 
02633     Ref = ParseSubClassReference(nullptr, true);
02634   }
02635 
02636   if (InheritFromClass) {
02637     // Process all the classes to inherit as if they were part of a
02638     // regular 'def' and inherit all record values.
02639     SubClassReference SubClass = ParseSubClassReference(nullptr, false);
02640     while (1) {
02641       // Check for error.
02642       if (!SubClass.Rec) return true;
02643 
02644       // Get the expanded definition prototypes and teach them about
02645       // the record values the current class to inherit has
02646       for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
02647         Record *CurRec = NewRecDefs[i];
02648 
02649         // Add it.
02650         if (AddSubClass(CurRec, SubClass))
02651           return true;
02652 
02653         if (ApplyLetStack(CurRec))
02654           return true;
02655       }
02656 
02657       if (Lex.getCode() != tgtok::comma) break;
02658       Lex.Lex(); // eat ','.
02659       SubClass = ParseSubClassReference(nullptr, false);
02660     }
02661   }
02662 
02663   if (!CurMultiClass)
02664     for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
02665       // See Record::setName().  This resolve step will see any new
02666       // name for the def that might have been created when resolving
02667       // inheritance, values and arguments above.
02668       NewRecDefs[i]->resolveReferences();
02669 
02670   if (Lex.getCode() != tgtok::semi)
02671     return TokError("expected ';' at end of defm");
02672   Lex.Lex();
02673 
02674   return false;
02675 }
02676 
02677 /// ParseObject
02678 ///   Object ::= ClassInst
02679 ///   Object ::= DefInst
02680 ///   Object ::= MultiClassInst
02681 ///   Object ::= DefMInst
02682 ///   Object ::= LETCommand '{' ObjectList '}'
02683 ///   Object ::= LETCommand Object
02684 bool TGParser::ParseObject(MultiClass *MC) {
02685   switch (Lex.getCode()) {
02686   default:
02687     return TokError("Expected class, def, defm, multiclass or let definition");
02688   case tgtok::Let:   return ParseTopLevelLet(MC);
02689   case tgtok::Def:   return ParseDef(MC);
02690   case tgtok::Foreach:   return ParseForeach(MC);
02691   case tgtok::Defm:  return ParseDefm(MC);
02692   case tgtok::Class: return ParseClass();
02693   case tgtok::MultiClass: return ParseMultiClass();
02694   }
02695 }
02696 
02697 /// ParseObjectList
02698 ///   ObjectList :== Object*
02699 bool TGParser::ParseObjectList(MultiClass *MC) {
02700   while (isObjectStart(Lex.getCode())) {
02701     if (ParseObject(MC))
02702       return true;
02703   }
02704   return false;
02705 }
02706 
02707 bool TGParser::ParseFile() {
02708   Lex.Lex(); // Prime the lexer.
02709   if (ParseObjectList()) return true;
02710 
02711   // If we have unread input at the end of the file, report it.
02712   if (Lex.getCode() == tgtok::Eof)
02713     return false;
02714 
02715   return TokError("Unexpected input at top level");
02716 }
02717