TGParser.cpp revision 261991
1226584Sdim//===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
2226584Sdim//
3226584Sdim//                     The LLVM Compiler Infrastructure
4226584Sdim//
5226584Sdim// This file is distributed under the University of Illinois Open Source
6226584Sdim// License. See LICENSE.TXT for details.
7226584Sdim//
8226584Sdim//===----------------------------------------------------------------------===//
9226584Sdim//
10226584Sdim// Implement the Parser for TableGen.
11226584Sdim//
12226584Sdim//===----------------------------------------------------------------------===//
13226584Sdim
14226584Sdim#include "TGParser.h"
15249423Sdim#include "llvm/ADT/SmallVector.h"
16249423Sdim#include "llvm/ADT/StringExtras.h"
17249423Sdim#include "llvm/Support/CommandLine.h"
18226584Sdim#include "llvm/TableGen/Record.h"
19226584Sdim#include <algorithm>
20226584Sdim#include <sstream>
21226584Sdimusing namespace llvm;
22226584Sdim
23226584Sdim//===----------------------------------------------------------------------===//
24226584Sdim// Support Code for the Semantic Actions.
25226584Sdim//===----------------------------------------------------------------------===//
26226584Sdim
27226584Sdimnamespace llvm {
28226584Sdimstruct SubClassReference {
29249423Sdim  SMRange RefRange;
30226584Sdim  Record *Rec;
31226584Sdim  std::vector<Init*> TemplateArgs;
32226584Sdim  SubClassReference() : Rec(0) {}
33226584Sdim
34226584Sdim  bool isInvalid() const { return Rec == 0; }
35226584Sdim};
36226584Sdim
37226584Sdimstruct SubMultiClassReference {
38249423Sdim  SMRange RefRange;
39226584Sdim  MultiClass *MC;
40226584Sdim  std::vector<Init*> TemplateArgs;
41226584Sdim  SubMultiClassReference() : MC(0) {}
42226584Sdim
43226584Sdim  bool isInvalid() const { return MC == 0; }
44226584Sdim  void dump() const;
45226584Sdim};
46226584Sdim
47226584Sdimvoid SubMultiClassReference::dump() const {
48226584Sdim  errs() << "Multiclass:\n";
49226584Sdim
50226584Sdim  MC->dump();
51226584Sdim
52226584Sdim  errs() << "Template args:\n";
53226584Sdim  for (std::vector<Init *>::const_iterator i = TemplateArgs.begin(),
54226584Sdim         iend = TemplateArgs.end();
55226584Sdim       i != iend;
56226584Sdim       ++i) {
57226584Sdim    (*i)->dump();
58226584Sdim  }
59226584Sdim}
60226584Sdim
61226584Sdim} // end namespace llvm
62226584Sdim
63226584Sdimbool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
64226584Sdim  if (CurRec == 0)
65226584Sdim    CurRec = &CurMultiClass->Rec;
66226584Sdim
67234353Sdim  if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
68226584Sdim    // The value already exists in the class, treat this as a set.
69226584Sdim    if (ERV->setValue(RV.getValue()))
70226584Sdim      return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
71226584Sdim                   RV.getType()->getAsString() + "' is incompatible with " +
72226584Sdim                   "previous definition of type '" +
73226584Sdim                   ERV->getType()->getAsString() + "'");
74226584Sdim  } else {
75226584Sdim    CurRec->addValue(RV);
76226584Sdim  }
77226584Sdim  return false;
78226584Sdim}
79226584Sdim
80226584Sdim/// SetValue -
81226584Sdim/// Return true on error, false on success.
82234353Sdimbool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
83226584Sdim                        const std::vector<unsigned> &BitList, Init *V) {
84226584Sdim  if (!V) return false;
85226584Sdim
86226584Sdim  if (CurRec == 0) CurRec = &CurMultiClass->Rec;
87226584Sdim
88226584Sdim  RecordVal *RV = CurRec->getValue(ValName);
89226584Sdim  if (RV == 0)
90234353Sdim    return Error(Loc, "Value '" + ValName->getAsUnquotedString()
91234353Sdim                 + "' unknown!");
92226584Sdim
93226584Sdim  // Do not allow assignments like 'X = X'.  This will just cause infinite loops
94226584Sdim  // in the resolution machinery.
95226584Sdim  if (BitList.empty())
96243830Sdim    if (VarInit *VI = dyn_cast<VarInit>(V))
97234353Sdim      if (VI->getNameInit() == ValName)
98226584Sdim        return false;
99226584Sdim
100226584Sdim  // If we are assigning to a subset of the bits in the value... then we must be
101226584Sdim  // assigning to a field of BitsRecTy, which must have a BitsInit
102226584Sdim  // initializer.
103226584Sdim  //
104226584Sdim  if (!BitList.empty()) {
105243830Sdim    BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
106226584Sdim    if (CurVal == 0)
107234353Sdim      return Error(Loc, "Value '" + ValName->getAsUnquotedString()
108234353Sdim                   + "' is not a bits type");
109226584Sdim
110226584Sdim    // Convert the incoming value to a bits type of the appropriate size...
111226584Sdim    Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size()));
112226584Sdim    if (BI == 0) {
113226584Sdim      return Error(Loc, "Initializer is not compatible with bit range");
114226584Sdim    }
115226584Sdim
116226584Sdim    // We should have a BitsInit type now.
117243830Sdim    BitsInit *BInit = dyn_cast<BitsInit>(BI);
118226584Sdim    assert(BInit != 0);
119226584Sdim
120226584Sdim    SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
121226584Sdim
122226584Sdim    // Loop over bits, assigning values as appropriate.
123226584Sdim    for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
124226584Sdim      unsigned Bit = BitList[i];
125226584Sdim      if (NewBits[Bit])
126226584Sdim        return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
127234353Sdim                     ValName->getAsUnquotedString() + "' more than once");
128226584Sdim      NewBits[Bit] = BInit->getBit(i);
129226584Sdim    }
130226584Sdim
131226584Sdim    for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
132226584Sdim      if (NewBits[i] == 0)
133226584Sdim        NewBits[i] = CurVal->getBit(i);
134226584Sdim
135226584Sdim    V = BitsInit::get(NewBits);
136226584Sdim  }
137226584Sdim
138226584Sdim  if (RV->setValue(V))
139234353Sdim    return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of type '"
140234353Sdim                 + RV->getType()->getAsString() +
141234353Sdim                 "' is incompatible with initializer '" + V->getAsString()
142234353Sdim                 + "'");
143226584Sdim  return false;
144226584Sdim}
145226584Sdim
146226584Sdim/// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
147226584Sdim/// args as SubClass's template arguments.
148226584Sdimbool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
149226584Sdim  Record *SC = SubClass.Rec;
150226584Sdim  // Add all of the values in the subclass into the current class.
151226584Sdim  const std::vector<RecordVal> &Vals = SC->getValues();
152226584Sdim  for (unsigned i = 0, e = Vals.size(); i != e; ++i)
153249423Sdim    if (AddValue(CurRec, SubClass.RefRange.Start, Vals[i]))
154226584Sdim      return true;
155226584Sdim
156234353Sdim  const std::vector<Init *> &TArgs = SC->getTemplateArgs();
157226584Sdim
158226584Sdim  // Ensure that an appropriate number of template arguments are specified.
159226584Sdim  if (TArgs.size() < SubClass.TemplateArgs.size())
160249423Sdim    return Error(SubClass.RefRange.Start,
161249423Sdim                 "More template args specified than expected");
162226584Sdim
163226584Sdim  // Loop over all of the template arguments, setting them to the specified
164226584Sdim  // value or leaving them as the default if necessary.
165226584Sdim  for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
166226584Sdim    if (i < SubClass.TemplateArgs.size()) {
167226584Sdim      // If a value is specified for this template arg, set it now.
168249423Sdim      if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
169249423Sdim                   std::vector<unsigned>(), SubClass.TemplateArgs[i]))
170226584Sdim        return true;
171226584Sdim
172226584Sdim      // Resolve it next.
173226584Sdim      CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
174226584Sdim
175226584Sdim      // Now remove it.
176226584Sdim      CurRec->removeValue(TArgs[i]);
177226584Sdim
178226584Sdim    } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
179249423Sdim      return Error(SubClass.RefRange.Start,
180249423Sdim                   "Value not specified for template argument #"
181234353Sdim                   + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
182234353Sdim                   + ") of subclass '" + SC->getNameInitAsString() + "'!");
183226584Sdim    }
184226584Sdim  }
185226584Sdim
186226584Sdim  // Since everything went well, we can now set the "superclass" list for the
187226584Sdim  // current record.
188226584Sdim  const std::vector<Record*> &SCs = SC->getSuperClasses();
189249423Sdim  ArrayRef<SMRange> SCRanges = SC->getSuperClassRanges();
190226584Sdim  for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
191226584Sdim    if (CurRec->isSubClassOf(SCs[i]))
192249423Sdim      return Error(SubClass.RefRange.Start,
193226584Sdim                   "Already subclass of '" + SCs[i]->getName() + "'!\n");
194249423Sdim    CurRec->addSuperClass(SCs[i], SCRanges[i]);
195226584Sdim  }
196226584Sdim
197226584Sdim  if (CurRec->isSubClassOf(SC))
198249423Sdim    return Error(SubClass.RefRange.Start,
199226584Sdim                 "Already subclass of '" + SC->getName() + "'!\n");
200249423Sdim  CurRec->addSuperClass(SC, SubClass.RefRange);
201226584Sdim  return false;
202226584Sdim}
203226584Sdim
204226584Sdim/// AddSubMultiClass - Add SubMultiClass as a subclass to
205226584Sdim/// CurMC, resolving its template args as SubMultiClass's
206226584Sdim/// template arguments.
207226584Sdimbool TGParser::AddSubMultiClass(MultiClass *CurMC,
208226584Sdim                                SubMultiClassReference &SubMultiClass) {
209226584Sdim  MultiClass *SMC = SubMultiClass.MC;
210226584Sdim  Record *CurRec = &CurMC->Rec;
211226584Sdim
212226584Sdim  const std::vector<RecordVal> &MCVals = CurRec->getValues();
213226584Sdim
214226584Sdim  // Add all of the values in the subclass into the current class.
215226584Sdim  const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
216226584Sdim  for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
217249423Sdim    if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVals[i]))
218226584Sdim      return true;
219226584Sdim
220226584Sdim  int newDefStart = CurMC->DefPrototypes.size();
221226584Sdim
222226584Sdim  // Add all of the defs in the subclass into the current multiclass.
223226584Sdim  for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
224226584Sdim         iend = SMC->DefPrototypes.end();
225226584Sdim       i != iend;
226226584Sdim       ++i) {
227226584Sdim    // Clone the def and add it to the current multiclass
228226584Sdim    Record *NewDef = new Record(**i);
229226584Sdim
230226584Sdim    // Add all of the values in the superclass into the current def.
231226584Sdim    for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
232249423Sdim      if (AddValue(NewDef, SubMultiClass.RefRange.Start, MCVals[i]))
233226584Sdim        return true;
234226584Sdim
235226584Sdim    CurMC->DefPrototypes.push_back(NewDef);
236226584Sdim  }
237226584Sdim
238234353Sdim  const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
239226584Sdim
240226584Sdim  // Ensure that an appropriate number of template arguments are
241226584Sdim  // specified.
242226584Sdim  if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
243249423Sdim    return Error(SubMultiClass.RefRange.Start,
244226584Sdim                 "More template args specified than expected");
245226584Sdim
246226584Sdim  // Loop over all of the template arguments, setting them to the specified
247226584Sdim  // value or leaving them as the default if necessary.
248226584Sdim  for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
249226584Sdim    if (i < SubMultiClass.TemplateArgs.size()) {
250226584Sdim      // If a value is specified for this template arg, set it in the
251226584Sdim      // superclass now.
252249423Sdim      if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i],
253226584Sdim                   std::vector<unsigned>(),
254226584Sdim                   SubMultiClass.TemplateArgs[i]))
255226584Sdim        return true;
256226584Sdim
257226584Sdim      // Resolve it next.
258226584Sdim      CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
259226584Sdim
260226584Sdim      // Now remove it.
261226584Sdim      CurRec->removeValue(SMCTArgs[i]);
262226584Sdim
263226584Sdim      // If a value is specified for this template arg, set it in the
264226584Sdim      // new defs now.
265226584Sdim      for (MultiClass::RecordVector::iterator j =
266226584Sdim             CurMC->DefPrototypes.begin() + newDefStart,
267226584Sdim             jend = CurMC->DefPrototypes.end();
268226584Sdim           j != jend;
269226584Sdim           ++j) {
270226584Sdim        Record *Def = *j;
271226584Sdim
272249423Sdim        if (SetValue(Def, SubMultiClass.RefRange.Start, SMCTArgs[i],
273226584Sdim                     std::vector<unsigned>(),
274226584Sdim                     SubMultiClass.TemplateArgs[i]))
275226584Sdim          return true;
276226584Sdim
277226584Sdim        // Resolve it next.
278226584Sdim        Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
279226584Sdim
280226584Sdim        // Now remove it
281226584Sdim        Def->removeValue(SMCTArgs[i]);
282226584Sdim      }
283226584Sdim    } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
284249423Sdim      return Error(SubMultiClass.RefRange.Start,
285226584Sdim                   "Value not specified for template argument #"
286234353Sdim                   + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
287234353Sdim                   + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
288226584Sdim    }
289226584Sdim  }
290226584Sdim
291226584Sdim  return false;
292226584Sdim}
293226584Sdim
294234353Sdim/// ProcessForeachDefs - Given a record, apply all of the variable
295234353Sdim/// values in all surrounding foreach loops, creating new records for
296234353Sdim/// each combination of values.
297239462Sdimbool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
298239462Sdim  if (Loops.empty())
299239462Sdim    return false;
300239462Sdim
301234353Sdim  // We want to instantiate a new copy of CurRec for each combination
302234353Sdim  // of nested loop iterator values.  We don't want top instantiate
303234353Sdim  // any copies until we have values for each loop iterator.
304234353Sdim  IterSet IterVals;
305239462Sdim  return ProcessForeachDefs(CurRec, Loc, IterVals);
306234353Sdim}
307234353Sdim
308234353Sdim/// ProcessForeachDefs - Given a record, a loop and a loop iterator,
309234353Sdim/// apply each of the variable values in this loop and then process
310234353Sdim/// subloops.
311239462Sdimbool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
312239462Sdim  // Recursively build a tuple of iterator values.
313239462Sdim  if (IterVals.size() != Loops.size()) {
314239462Sdim    assert(IterVals.size() < Loops.size());
315239462Sdim    ForeachLoop &CurLoop = Loops[IterVals.size()];
316243830Sdim    ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
317239462Sdim    if (List == 0) {
318239462Sdim      Error(Loc, "Loop list is not a list");
319239462Sdim      return true;
320239462Sdim    }
321234353Sdim
322239462Sdim    // Process each value.
323239462Sdim    for (int64_t i = 0; i < List->getSize(); ++i) {
324239462Sdim      Init *ItemVal = List->resolveListElementReference(*CurRec, 0, i);
325239462Sdim      IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
326239462Sdim      if (ProcessForeachDefs(CurRec, Loc, IterVals))
327239462Sdim        return true;
328239462Sdim      IterVals.pop_back();
329239462Sdim    }
330239462Sdim    return false;
331234353Sdim  }
332234353Sdim
333239462Sdim  // This is the bottom of the recursion. We have all of the iterator values
334239462Sdim  // for this point in the iteration space.  Instantiate a new record to
335239462Sdim  // reflect this combination of values.
336239462Sdim  Record *IterRec = new Record(*CurRec);
337234353Sdim
338239462Sdim  // Set the iterator values now.
339239462Sdim  for (unsigned i = 0, e = IterVals.size(); i != e; ++i) {
340239462Sdim    VarInit *IterVar = IterVals[i].IterVar;
341243830Sdim    TypedInit *IVal = dyn_cast<TypedInit>(IterVals[i].IterValue);
342239462Sdim    if (IVal == 0) {
343239462Sdim      Error(Loc, "foreach iterator value is untyped");
344239462Sdim      return true;
345239462Sdim    }
346234353Sdim
347239462Sdim    IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
348234353Sdim
349239462Sdim    if (SetValue(IterRec, Loc, IterVar->getName(),
350239462Sdim                 std::vector<unsigned>(), IVal)) {
351239462Sdim      Error(Loc, "when instantiating this def");
352239462Sdim      return true;
353239462Sdim    }
354234353Sdim
355239462Sdim    // Resolve it next.
356239462Sdim    IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
357234353Sdim
358239462Sdim    // Remove it.
359239462Sdim    IterRec->removeValue(IterVar->getName());
360239462Sdim  }
361234353Sdim
362239462Sdim  if (Records.getDef(IterRec->getNameInitAsString())) {
363239462Sdim    Error(Loc, "def already exists: " + IterRec->getNameInitAsString());
364239462Sdim    return true;
365239462Sdim  }
366234353Sdim
367239462Sdim  Records.addDef(IterRec);
368239462Sdim  IterRec->resolveReferences();
369234353Sdim  return false;
370234353Sdim}
371234353Sdim
372226584Sdim//===----------------------------------------------------------------------===//
373226584Sdim// Parser Code
374226584Sdim//===----------------------------------------------------------------------===//
375226584Sdim
376226584Sdim/// isObjectStart - Return true if this is a valid first token for an Object.
377226584Sdimstatic bool isObjectStart(tgtok::TokKind K) {
378226584Sdim  return K == tgtok::Class || K == tgtok::Def ||
379234353Sdim         K == tgtok::Defm || K == tgtok::Let ||
380234353Sdim         K == tgtok::MultiClass || K == tgtok::Foreach;
381226584Sdim}
382226584Sdim
383226584Sdimstatic std::string GetNewAnonymousName() {
384226584Sdim  static unsigned AnonCounter = 0;
385249423Sdim  unsigned Tmp = AnonCounter++; // MSVC2012 ICEs without this.
386249423Sdim  return "anonymous." + utostr(Tmp);
387226584Sdim}
388226584Sdim
389226584Sdim/// ParseObjectName - If an object name is specified, return it.  Otherwise,
390249423Sdim/// return 0.
391234353Sdim///   ObjectName ::= Value [ '#' Value ]*
392226584Sdim///   ObjectName ::= /*empty*/
393226584Sdim///
394234353SdimInit *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
395234353Sdim  switch (Lex.getCode()) {
396234353Sdim  case tgtok::colon:
397234353Sdim  case tgtok::semi:
398234353Sdim  case tgtok::l_brace:
399234353Sdim    // These are all of the tokens that can begin an object body.
400234353Sdim    // Some of these can also begin values but we disallow those cases
401234353Sdim    // because they are unlikely to be useful.
402249423Sdim    return 0;
403234353Sdim  default:
404234353Sdim    break;
405234353Sdim  }
406226584Sdim
407234353Sdim  Record *CurRec = 0;
408234353Sdim  if (CurMultiClass)
409234353Sdim    CurRec = &CurMultiClass->Rec;
410234353Sdim
411234353Sdim  RecTy *Type = 0;
412234353Sdim  if (CurRec) {
413243830Sdim    const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
414234353Sdim    if (!CurRecName) {
415234353Sdim      TokError("Record name is not typed!");
416234353Sdim      return 0;
417234353Sdim    }
418234353Sdim    Type = CurRecName->getType();
419234353Sdim  }
420234353Sdim
421234353Sdim  return ParseValue(CurRec, Type, ParseNameMode);
422226584Sdim}
423226584Sdim
424226584Sdim/// ParseClassID - Parse and resolve a reference to a class name.  This returns
425226584Sdim/// null on error.
426226584Sdim///
427226584Sdim///    ClassID ::= ID
428226584Sdim///
429226584SdimRecord *TGParser::ParseClassID() {
430226584Sdim  if (Lex.getCode() != tgtok::Id) {
431226584Sdim    TokError("expected name for ClassID");
432226584Sdim    return 0;
433226584Sdim  }
434226584Sdim
435226584Sdim  Record *Result = Records.getClass(Lex.getCurStrVal());
436226584Sdim  if (Result == 0)
437226584Sdim    TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
438226584Sdim
439226584Sdim  Lex.Lex();
440226584Sdim  return Result;
441226584Sdim}
442226584Sdim
443226584Sdim/// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
444226584Sdim/// This returns null on error.
445226584Sdim///
446226584Sdim///    MultiClassID ::= ID
447226584Sdim///
448226584SdimMultiClass *TGParser::ParseMultiClassID() {
449226584Sdim  if (Lex.getCode() != tgtok::Id) {
450249423Sdim    TokError("expected name for MultiClassID");
451226584Sdim    return 0;
452226584Sdim  }
453226584Sdim
454226584Sdim  MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
455226584Sdim  if (Result == 0)
456249423Sdim    TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
457226584Sdim
458226584Sdim  Lex.Lex();
459226584Sdim  return Result;
460226584Sdim}
461226584Sdim
462226584Sdim/// ParseSubClassReference - Parse a reference to a subclass or to a templated
463226584Sdim/// subclass.  This returns a SubClassRefTy with a null Record* on error.
464226584Sdim///
465226584Sdim///  SubClassRef ::= ClassID
466226584Sdim///  SubClassRef ::= ClassID '<' ValueList '>'
467226584Sdim///
468226584SdimSubClassReference TGParser::
469226584SdimParseSubClassReference(Record *CurRec, bool isDefm) {
470226584Sdim  SubClassReference Result;
471249423Sdim  Result.RefRange.Start = Lex.getLoc();
472226584Sdim
473249423Sdim  if (isDefm) {
474249423Sdim    if (MultiClass *MC = ParseMultiClassID())
475249423Sdim      Result.Rec = &MC->Rec;
476249423Sdim  } else {
477226584Sdim    Result.Rec = ParseClassID();
478249423Sdim  }
479226584Sdim  if (Result.Rec == 0) return Result;
480226584Sdim
481226584Sdim  // If there is no template arg list, we're done.
482249423Sdim  if (Lex.getCode() != tgtok::less) {
483249423Sdim    Result.RefRange.End = Lex.getLoc();
484226584Sdim    return Result;
485249423Sdim  }
486226584Sdim  Lex.Lex();  // Eat the '<'
487226584Sdim
488226584Sdim  if (Lex.getCode() == tgtok::greater) {
489226584Sdim    TokError("subclass reference requires a non-empty list of template values");
490226584Sdim    Result.Rec = 0;
491226584Sdim    return Result;
492226584Sdim  }
493226584Sdim
494226584Sdim  Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
495226584Sdim  if (Result.TemplateArgs.empty()) {
496226584Sdim    Result.Rec = 0;   // Error parsing value list.
497226584Sdim    return Result;
498226584Sdim  }
499226584Sdim
500226584Sdim  if (Lex.getCode() != tgtok::greater) {
501226584Sdim    TokError("expected '>' in template value list");
502226584Sdim    Result.Rec = 0;
503226584Sdim    return Result;
504226584Sdim  }
505226584Sdim  Lex.Lex();
506249423Sdim  Result.RefRange.End = Lex.getLoc();
507226584Sdim
508226584Sdim  return Result;
509226584Sdim}
510226584Sdim
511226584Sdim/// ParseSubMultiClassReference - Parse a reference to a subclass or to a
512226584Sdim/// templated submulticlass.  This returns a SubMultiClassRefTy with a null
513226584Sdim/// Record* on error.
514226584Sdim///
515226584Sdim///  SubMultiClassRef ::= MultiClassID
516226584Sdim///  SubMultiClassRef ::= MultiClassID '<' ValueList '>'
517226584Sdim///
518226584SdimSubMultiClassReference TGParser::
519226584SdimParseSubMultiClassReference(MultiClass *CurMC) {
520226584Sdim  SubMultiClassReference Result;
521249423Sdim  Result.RefRange.Start = Lex.getLoc();
522226584Sdim
523226584Sdim  Result.MC = ParseMultiClassID();
524226584Sdim  if (Result.MC == 0) return Result;
525226584Sdim
526226584Sdim  // If there is no template arg list, we're done.
527249423Sdim  if (Lex.getCode() != tgtok::less) {
528249423Sdim    Result.RefRange.End = Lex.getLoc();
529226584Sdim    return Result;
530249423Sdim  }
531226584Sdim  Lex.Lex();  // Eat the '<'
532226584Sdim
533226584Sdim  if (Lex.getCode() == tgtok::greater) {
534226584Sdim    TokError("subclass reference requires a non-empty list of template values");
535226584Sdim    Result.MC = 0;
536226584Sdim    return Result;
537226584Sdim  }
538226584Sdim
539226584Sdim  Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
540226584Sdim  if (Result.TemplateArgs.empty()) {
541226584Sdim    Result.MC = 0;   // Error parsing value list.
542226584Sdim    return Result;
543226584Sdim  }
544226584Sdim
545226584Sdim  if (Lex.getCode() != tgtok::greater) {
546226584Sdim    TokError("expected '>' in template value list");
547226584Sdim    Result.MC = 0;
548226584Sdim    return Result;
549226584Sdim  }
550226584Sdim  Lex.Lex();
551249423Sdim  Result.RefRange.End = Lex.getLoc();
552226584Sdim
553226584Sdim  return Result;
554226584Sdim}
555226584Sdim
556226584Sdim/// ParseRangePiece - Parse a bit/value range.
557226584Sdim///   RangePiece ::= INTVAL
558226584Sdim///   RangePiece ::= INTVAL '-' INTVAL
559226584Sdim///   RangePiece ::= INTVAL INTVAL
560226584Sdimbool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
561226584Sdim  if (Lex.getCode() != tgtok::IntVal) {
562226584Sdim    TokError("expected integer or bitrange");
563226584Sdim    return true;
564226584Sdim  }
565226584Sdim  int64_t Start = Lex.getCurIntVal();
566226584Sdim  int64_t End;
567226584Sdim
568226584Sdim  if (Start < 0)
569226584Sdim    return TokError("invalid range, cannot be negative");
570226584Sdim
571226584Sdim  switch (Lex.Lex()) {  // eat first character.
572226584Sdim  default:
573226584Sdim    Ranges.push_back(Start);
574226584Sdim    return false;
575226584Sdim  case tgtok::minus:
576226584Sdim    if (Lex.Lex() != tgtok::IntVal) {
577226584Sdim      TokError("expected integer value as end of range");
578226584Sdim      return true;
579226584Sdim    }
580226584Sdim    End = Lex.getCurIntVal();
581226584Sdim    break;
582226584Sdim  case tgtok::IntVal:
583226584Sdim    End = -Lex.getCurIntVal();
584226584Sdim    break;
585226584Sdim  }
586226584Sdim  if (End < 0)
587226584Sdim    return TokError("invalid range, cannot be negative");
588226584Sdim  Lex.Lex();
589226584Sdim
590226584Sdim  // Add to the range.
591226584Sdim  if (Start < End) {
592226584Sdim    for (; Start <= End; ++Start)
593226584Sdim      Ranges.push_back(Start);
594226584Sdim  } else {
595226584Sdim    for (; Start >= End; --Start)
596226584Sdim      Ranges.push_back(Start);
597226584Sdim  }
598226584Sdim  return false;
599226584Sdim}
600226584Sdim
601226584Sdim/// ParseRangeList - Parse a list of scalars and ranges into scalar values.
602226584Sdim///
603226584Sdim///   RangeList ::= RangePiece (',' RangePiece)*
604226584Sdim///
605226584Sdimstd::vector<unsigned> TGParser::ParseRangeList() {
606226584Sdim  std::vector<unsigned> Result;
607226584Sdim
608226584Sdim  // Parse the first piece.
609226584Sdim  if (ParseRangePiece(Result))
610226584Sdim    return std::vector<unsigned>();
611226584Sdim  while (Lex.getCode() == tgtok::comma) {
612226584Sdim    Lex.Lex();  // Eat the comma.
613226584Sdim
614226584Sdim    // Parse the next range piece.
615226584Sdim    if (ParseRangePiece(Result))
616226584Sdim      return std::vector<unsigned>();
617226584Sdim  }
618226584Sdim  return Result;
619226584Sdim}
620226584Sdim
621226584Sdim/// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
622226584Sdim///   OptionalRangeList ::= '<' RangeList '>'
623226584Sdim///   OptionalRangeList ::= /*empty*/
624226584Sdimbool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
625226584Sdim  if (Lex.getCode() != tgtok::less)
626226584Sdim    return false;
627226584Sdim
628226584Sdim  SMLoc StartLoc = Lex.getLoc();
629226584Sdim  Lex.Lex(); // eat the '<'
630226584Sdim
631226584Sdim  // Parse the range list.
632226584Sdim  Ranges = ParseRangeList();
633226584Sdim  if (Ranges.empty()) return true;
634226584Sdim
635226584Sdim  if (Lex.getCode() != tgtok::greater) {
636226584Sdim    TokError("expected '>' at end of range list");
637226584Sdim    return Error(StartLoc, "to match this '<'");
638226584Sdim  }
639226584Sdim  Lex.Lex();   // eat the '>'.
640226584Sdim  return false;
641226584Sdim}
642226584Sdim
643226584Sdim/// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
644226584Sdim///   OptionalBitList ::= '{' RangeList '}'
645226584Sdim///   OptionalBitList ::= /*empty*/
646226584Sdimbool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
647226584Sdim  if (Lex.getCode() != tgtok::l_brace)
648226584Sdim    return false;
649226584Sdim
650226584Sdim  SMLoc StartLoc = Lex.getLoc();
651226584Sdim  Lex.Lex(); // eat the '{'
652226584Sdim
653226584Sdim  // Parse the range list.
654226584Sdim  Ranges = ParseRangeList();
655226584Sdim  if (Ranges.empty()) return true;
656226584Sdim
657226584Sdim  if (Lex.getCode() != tgtok::r_brace) {
658226584Sdim    TokError("expected '}' at end of bit list");
659226584Sdim    return Error(StartLoc, "to match this '{'");
660226584Sdim  }
661226584Sdim  Lex.Lex();   // eat the '}'.
662226584Sdim  return false;
663226584Sdim}
664226584Sdim
665226584Sdim
666226584Sdim/// ParseType - Parse and return a tblgen type.  This returns null on error.
667226584Sdim///
668226584Sdim///   Type ::= STRING                       // string type
669234353Sdim///   Type ::= CODE                         // code type
670226584Sdim///   Type ::= BIT                          // bit type
671226584Sdim///   Type ::= BITS '<' INTVAL '>'          // bits<x> type
672226584Sdim///   Type ::= INT                          // int type
673226584Sdim///   Type ::= LIST '<' Type '>'            // list<x> type
674226584Sdim///   Type ::= DAG                          // dag type
675226584Sdim///   Type ::= ClassID                      // Record Type
676226584Sdim///
677226584SdimRecTy *TGParser::ParseType() {
678226584Sdim  switch (Lex.getCode()) {
679226584Sdim  default: TokError("Unknown token when expecting a type"); return 0;
680226584Sdim  case tgtok::String: Lex.Lex(); return StringRecTy::get();
681234353Sdim  case tgtok::Code:   Lex.Lex(); return StringRecTy::get();
682226584Sdim  case tgtok::Bit:    Lex.Lex(); return BitRecTy::get();
683226584Sdim  case tgtok::Int:    Lex.Lex(); return IntRecTy::get();
684226584Sdim  case tgtok::Dag:    Lex.Lex(); return DagRecTy::get();
685226584Sdim  case tgtok::Id:
686226584Sdim    if (Record *R = ParseClassID()) return RecordRecTy::get(R);
687226584Sdim    return 0;
688226584Sdim  case tgtok::Bits: {
689226584Sdim    if (Lex.Lex() != tgtok::less) { // Eat 'bits'
690226584Sdim      TokError("expected '<' after bits type");
691226584Sdim      return 0;
692226584Sdim    }
693226584Sdim    if (Lex.Lex() != tgtok::IntVal) {  // Eat '<'
694226584Sdim      TokError("expected integer in bits<n> type");
695226584Sdim      return 0;
696226584Sdim    }
697226584Sdim    uint64_t Val = Lex.getCurIntVal();
698226584Sdim    if (Lex.Lex() != tgtok::greater) {  // Eat count.
699226584Sdim      TokError("expected '>' at end of bits<n> type");
700226584Sdim      return 0;
701226584Sdim    }
702226584Sdim    Lex.Lex();  // Eat '>'
703226584Sdim    return BitsRecTy::get(Val);
704226584Sdim  }
705226584Sdim  case tgtok::List: {
706226584Sdim    if (Lex.Lex() != tgtok::less) { // Eat 'bits'
707226584Sdim      TokError("expected '<' after list type");
708226584Sdim      return 0;
709226584Sdim    }
710226584Sdim    Lex.Lex();  // Eat '<'
711226584Sdim    RecTy *SubType = ParseType();
712226584Sdim    if (SubType == 0) return 0;
713226584Sdim
714226584Sdim    if (Lex.getCode() != tgtok::greater) {
715226584Sdim      TokError("expected '>' at end of list<ty> type");
716226584Sdim      return 0;
717226584Sdim    }
718226584Sdim    Lex.Lex();  // Eat '>'
719226584Sdim    return ListRecTy::get(SubType);
720226584Sdim  }
721226584Sdim  }
722226584Sdim}
723226584Sdim
724226584Sdim/// ParseIDValue - Parse an ID as a value and decode what it means.
725226584Sdim///
726226584Sdim///  IDValue ::= ID [def local value]
727226584Sdim///  IDValue ::= ID [def template arg]
728226584Sdim///  IDValue ::= ID [multiclass local value]
729226584Sdim///  IDValue ::= ID [multiclass template argument]
730226584Sdim///  IDValue ::= ID [def name]
731226584Sdim///
732234353SdimInit *TGParser::ParseIDValue(Record *CurRec, IDParseMode Mode) {
733226584Sdim  assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
734226584Sdim  std::string Name = Lex.getCurStrVal();
735226584Sdim  SMLoc Loc = Lex.getLoc();
736226584Sdim  Lex.Lex();
737226584Sdim  return ParseIDValue(CurRec, Name, Loc);
738226584Sdim}
739226584Sdim
740226584Sdim/// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
741226584Sdim/// has already been read.
742226584SdimInit *TGParser::ParseIDValue(Record *CurRec,
743234353Sdim                             const std::string &Name, SMLoc NameLoc,
744234353Sdim                             IDParseMode Mode) {
745226584Sdim  if (CurRec) {
746226584Sdim    if (const RecordVal *RV = CurRec->getValue(Name))
747226584Sdim      return VarInit::get(Name, RV->getType());
748226584Sdim
749234353Sdim    Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
750234353Sdim
751226584Sdim    if (CurMultiClass)
752234353Sdim      TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
753234353Sdim                                    "::");
754226584Sdim
755226584Sdim    if (CurRec->isTemplateArg(TemplateArgName)) {
756226584Sdim      const RecordVal *RV = CurRec->getValue(TemplateArgName);
757226584Sdim      assert(RV && "Template arg doesn't exist??");
758226584Sdim      return VarInit::get(TemplateArgName, RV->getType());
759226584Sdim    }
760226584Sdim  }
761226584Sdim
762226584Sdim  if (CurMultiClass) {
763234353Sdim    Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
764234353Sdim                               "::");
765234353Sdim
766226584Sdim    if (CurMultiClass->Rec.isTemplateArg(MCName)) {
767226584Sdim      const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
768226584Sdim      assert(RV && "Template arg doesn't exist??");
769226584Sdim      return VarInit::get(MCName, RV->getType());
770226584Sdim    }
771226584Sdim  }
772226584Sdim
773234353Sdim  // If this is in a foreach loop, make sure it's not a loop iterator
774234353Sdim  for (LoopVector::iterator i = Loops.begin(), iend = Loops.end();
775234353Sdim       i != iend;
776234353Sdim       ++i) {
777243830Sdim    VarInit *IterVar = dyn_cast<VarInit>(i->IterVar);
778234353Sdim    if (IterVar && IterVar->getName() == Name)
779234353Sdim      return IterVar;
780234353Sdim  }
781234353Sdim
782234353Sdim  if (Mode == ParseNameMode)
783234353Sdim    return StringInit::get(Name);
784234353Sdim
785226584Sdim  if (Record *D = Records.getDef(Name))
786226584Sdim    return DefInit::get(D);
787226584Sdim
788234353Sdim  if (Mode == ParseValueMode) {
789234353Sdim    Error(NameLoc, "Variable not defined: '" + Name + "'");
790234353Sdim    return 0;
791234353Sdim  }
792234353Sdim
793234353Sdim  return StringInit::get(Name);
794226584Sdim}
795226584Sdim
796226584Sdim/// ParseOperation - Parse an operator.  This returns null on error.
797226584Sdim///
798226584Sdim/// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
799226584Sdim///
800226584SdimInit *TGParser::ParseOperation(Record *CurRec) {
801226584Sdim  switch (Lex.getCode()) {
802226584Sdim  default:
803226584Sdim    TokError("unknown operation");
804226584Sdim    return 0;
805226584Sdim  case tgtok::XHead:
806226584Sdim  case tgtok::XTail:
807226584Sdim  case tgtok::XEmpty:
808226584Sdim  case tgtok::XCast: {  // Value ::= !unop '(' Value ')'
809226584Sdim    UnOpInit::UnaryOp Code;
810226584Sdim    RecTy *Type = 0;
811226584Sdim
812226584Sdim    switch (Lex.getCode()) {
813234353Sdim    default: llvm_unreachable("Unhandled code!");
814226584Sdim    case tgtok::XCast:
815226584Sdim      Lex.Lex();  // eat the operation
816226584Sdim      Code = UnOpInit::CAST;
817226584Sdim
818226584Sdim      Type = ParseOperatorType();
819226584Sdim
820226584Sdim      if (Type == 0) {
821226584Sdim        TokError("did not get type for unary operator");
822226584Sdim        return 0;
823226584Sdim      }
824226584Sdim
825226584Sdim      break;
826226584Sdim    case tgtok::XHead:
827226584Sdim      Lex.Lex();  // eat the operation
828226584Sdim      Code = UnOpInit::HEAD;
829226584Sdim      break;
830226584Sdim    case tgtok::XTail:
831226584Sdim      Lex.Lex();  // eat the operation
832226584Sdim      Code = UnOpInit::TAIL;
833226584Sdim      break;
834226584Sdim    case tgtok::XEmpty:
835226584Sdim      Lex.Lex();  // eat the operation
836226584Sdim      Code = UnOpInit::EMPTY;
837226584Sdim      Type = IntRecTy::get();
838226584Sdim      break;
839226584Sdim    }
840226584Sdim    if (Lex.getCode() != tgtok::l_paren) {
841226584Sdim      TokError("expected '(' after unary operator");
842226584Sdim      return 0;
843226584Sdim    }
844226584Sdim    Lex.Lex();  // eat the '('
845226584Sdim
846226584Sdim    Init *LHS = ParseValue(CurRec);
847226584Sdim    if (LHS == 0) return 0;
848226584Sdim
849226584Sdim    if (Code == UnOpInit::HEAD
850226584Sdim        || Code == UnOpInit::TAIL
851226584Sdim        || Code == UnOpInit::EMPTY) {
852243830Sdim      ListInit *LHSl = dyn_cast<ListInit>(LHS);
853243830Sdim      StringInit *LHSs = dyn_cast<StringInit>(LHS);
854243830Sdim      TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
855226584Sdim      if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
856226584Sdim        TokError("expected list or string type argument in unary operator");
857226584Sdim        return 0;
858226584Sdim      }
859226584Sdim      if (LHSt) {
860243830Sdim        ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
861243830Sdim        StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
862226584Sdim        if (LType == 0 && SType == 0) {
863226584Sdim          TokError("expected list or string type argumnet in unary operator");
864226584Sdim          return 0;
865226584Sdim        }
866226584Sdim      }
867226584Sdim
868226584Sdim      if (Code == UnOpInit::HEAD
869226584Sdim          || Code == UnOpInit::TAIL) {
870226584Sdim        if (LHSl == 0 && LHSt == 0) {
871226584Sdim          TokError("expected list type argumnet in unary operator");
872226584Sdim          return 0;
873226584Sdim        }
874226584Sdim
875226584Sdim        if (LHSl && LHSl->getSize() == 0) {
876226584Sdim          TokError("empty list argument in unary operator");
877226584Sdim          return 0;
878226584Sdim        }
879226584Sdim        if (LHSl) {
880226584Sdim          Init *Item = LHSl->getElement(0);
881243830Sdim          TypedInit *Itemt = dyn_cast<TypedInit>(Item);
882226584Sdim          if (Itemt == 0) {
883226584Sdim            TokError("untyped list element in unary operator");
884226584Sdim            return 0;
885226584Sdim          }
886226584Sdim          if (Code == UnOpInit::HEAD) {
887226584Sdim            Type = Itemt->getType();
888226584Sdim          } else {
889226584Sdim            Type = ListRecTy::get(Itemt->getType());
890226584Sdim          }
891226584Sdim        } else {
892226584Sdim          assert(LHSt && "expected list type argument in unary operator");
893243830Sdim          ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
894226584Sdim          if (LType == 0) {
895226584Sdim            TokError("expected list type argumnet in unary operator");
896226584Sdim            return 0;
897226584Sdim          }
898226584Sdim          if (Code == UnOpInit::HEAD) {
899226584Sdim            Type = LType->getElementType();
900226584Sdim          } else {
901226584Sdim            Type = LType;
902226584Sdim          }
903226584Sdim        }
904226584Sdim      }
905226584Sdim    }
906226584Sdim
907226584Sdim    if (Lex.getCode() != tgtok::r_paren) {
908226584Sdim      TokError("expected ')' in unary operator");
909226584Sdim      return 0;
910226584Sdim    }
911226584Sdim    Lex.Lex();  // eat the ')'
912226584Sdim    return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
913226584Sdim  }
914226584Sdim
915226584Sdim  case tgtok::XConcat:
916249423Sdim  case tgtok::XADD:
917226584Sdim  case tgtok::XSRA:
918226584Sdim  case tgtok::XSRL:
919226584Sdim  case tgtok::XSHL:
920226584Sdim  case tgtok::XEq:
921226584Sdim  case tgtok::XStrConcat: {  // Value ::= !binop '(' Value ',' Value ')'
922226584Sdim    tgtok::TokKind OpTok = Lex.getCode();
923226584Sdim    SMLoc OpLoc = Lex.getLoc();
924226584Sdim    Lex.Lex();  // eat the operation
925226584Sdim
926226584Sdim    BinOpInit::BinaryOp Code;
927226584Sdim    RecTy *Type = 0;
928226584Sdim
929226584Sdim    switch (OpTok) {
930234353Sdim    default: llvm_unreachable("Unhandled code!");
931226584Sdim    case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
932249423Sdim    case tgtok::XADD:    Code = BinOpInit::ADD;   Type = IntRecTy::get(); break;
933226584Sdim    case tgtok::XSRA:    Code = BinOpInit::SRA;   Type = IntRecTy::get(); break;
934226584Sdim    case tgtok::XSRL:    Code = BinOpInit::SRL;   Type = IntRecTy::get(); break;
935226584Sdim    case tgtok::XSHL:    Code = BinOpInit::SHL;   Type = IntRecTy::get(); break;
936226584Sdim    case tgtok::XEq:     Code = BinOpInit::EQ;    Type = BitRecTy::get(); break;
937226584Sdim    case tgtok::XStrConcat:
938226584Sdim      Code = BinOpInit::STRCONCAT;
939226584Sdim      Type = StringRecTy::get();
940226584Sdim      break;
941226584Sdim    }
942226584Sdim
943226584Sdim    if (Lex.getCode() != tgtok::l_paren) {
944226584Sdim      TokError("expected '(' after binary operator");
945226584Sdim      return 0;
946226584Sdim    }
947226584Sdim    Lex.Lex();  // eat the '('
948226584Sdim
949226584Sdim    SmallVector<Init*, 2> InitList;
950226584Sdim
951226584Sdim    InitList.push_back(ParseValue(CurRec));
952226584Sdim    if (InitList.back() == 0) return 0;
953226584Sdim
954226584Sdim    while (Lex.getCode() == tgtok::comma) {
955226584Sdim      Lex.Lex();  // eat the ','
956226584Sdim
957226584Sdim      InitList.push_back(ParseValue(CurRec));
958226584Sdim      if (InitList.back() == 0) return 0;
959226584Sdim    }
960226584Sdim
961226584Sdim    if (Lex.getCode() != tgtok::r_paren) {
962226584Sdim      TokError("expected ')' in operator");
963226584Sdim      return 0;
964226584Sdim    }
965226584Sdim    Lex.Lex();  // eat the ')'
966226584Sdim
967226584Sdim    // We allow multiple operands to associative operators like !strconcat as
968226584Sdim    // shorthand for nesting them.
969226584Sdim    if (Code == BinOpInit::STRCONCAT) {
970226584Sdim      while (InitList.size() > 2) {
971226584Sdim        Init *RHS = InitList.pop_back_val();
972226584Sdim        RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
973226584Sdim                           ->Fold(CurRec, CurMultiClass);
974226584Sdim        InitList.back() = RHS;
975226584Sdim      }
976226584Sdim    }
977226584Sdim
978226584Sdim    if (InitList.size() == 2)
979226584Sdim      return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
980226584Sdim        ->Fold(CurRec, CurMultiClass);
981226584Sdim
982226584Sdim    Error(OpLoc, "expected two operands to operator");
983226584Sdim    return 0;
984226584Sdim  }
985226584Sdim
986226584Sdim  case tgtok::XIf:
987226584Sdim  case tgtok::XForEach:
988226584Sdim  case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
989226584Sdim    TernOpInit::TernaryOp Code;
990226584Sdim    RecTy *Type = 0;
991226584Sdim
992226584Sdim    tgtok::TokKind LexCode = Lex.getCode();
993226584Sdim    Lex.Lex();  // eat the operation
994226584Sdim    switch (LexCode) {
995234353Sdim    default: llvm_unreachable("Unhandled code!");
996226584Sdim    case tgtok::XIf:
997226584Sdim      Code = TernOpInit::IF;
998226584Sdim      break;
999226584Sdim    case tgtok::XForEach:
1000226584Sdim      Code = TernOpInit::FOREACH;
1001226584Sdim      break;
1002226584Sdim    case tgtok::XSubst:
1003226584Sdim      Code = TernOpInit::SUBST;
1004226584Sdim      break;
1005226584Sdim    }
1006226584Sdim    if (Lex.getCode() != tgtok::l_paren) {
1007226584Sdim      TokError("expected '(' after ternary operator");
1008226584Sdim      return 0;
1009226584Sdim    }
1010226584Sdim    Lex.Lex();  // eat the '('
1011226584Sdim
1012226584Sdim    Init *LHS = ParseValue(CurRec);
1013226584Sdim    if (LHS == 0) return 0;
1014226584Sdim
1015226584Sdim    if (Lex.getCode() != tgtok::comma) {
1016226584Sdim      TokError("expected ',' in ternary operator");
1017226584Sdim      return 0;
1018226584Sdim    }
1019226584Sdim    Lex.Lex();  // eat the ','
1020226584Sdim
1021226584Sdim    Init *MHS = ParseValue(CurRec);
1022226584Sdim    if (MHS == 0) return 0;
1023226584Sdim
1024226584Sdim    if (Lex.getCode() != tgtok::comma) {
1025226584Sdim      TokError("expected ',' in ternary operator");
1026226584Sdim      return 0;
1027226584Sdim    }
1028226584Sdim    Lex.Lex();  // eat the ','
1029226584Sdim
1030226584Sdim    Init *RHS = ParseValue(CurRec);
1031226584Sdim    if (RHS == 0) return 0;
1032226584Sdim
1033226584Sdim    if (Lex.getCode() != tgtok::r_paren) {
1034226584Sdim      TokError("expected ')' in binary operator");
1035226584Sdim      return 0;
1036226584Sdim    }
1037226584Sdim    Lex.Lex();  // eat the ')'
1038226584Sdim
1039226584Sdim    switch (LexCode) {
1040234353Sdim    default: llvm_unreachable("Unhandled code!");
1041226584Sdim    case tgtok::XIf: {
1042226584Sdim      RecTy *MHSTy = 0;
1043226584Sdim      RecTy *RHSTy = 0;
1044226584Sdim
1045243830Sdim      if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1046243830Sdim        MHSTy = MHSt->getType();
1047243830Sdim      if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1048243830Sdim        MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1049243830Sdim      if (isa<BitInit>(MHS))
1050243830Sdim        MHSTy = BitRecTy::get();
1051226584Sdim
1052243830Sdim      if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1053226584Sdim        RHSTy = RHSt->getType();
1054243830Sdim      if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1055243830Sdim        RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1056243830Sdim      if (isa<BitInit>(RHS))
1057243830Sdim        RHSTy = BitRecTy::get();
1058226584Sdim
1059243830Sdim      // For UnsetInit, it's typed from the other hand.
1060243830Sdim      if (isa<UnsetInit>(MHS))
1061243830Sdim        MHSTy = RHSTy;
1062243830Sdim      if (isa<UnsetInit>(RHS))
1063243830Sdim        RHSTy = MHSTy;
1064243830Sdim
1065226584Sdim      if (!MHSTy || !RHSTy) {
1066226584Sdim        TokError("could not get type for !if");
1067226584Sdim        return 0;
1068226584Sdim      }
1069226584Sdim
1070226584Sdim      if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1071226584Sdim        Type = RHSTy;
1072226584Sdim      } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1073226584Sdim        Type = MHSTy;
1074226584Sdim      } else {
1075226584Sdim        TokError("inconsistent types for !if");
1076226584Sdim        return 0;
1077226584Sdim      }
1078226584Sdim      break;
1079226584Sdim    }
1080226584Sdim    case tgtok::XForEach: {
1081243830Sdim      TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1082226584Sdim      if (MHSt == 0) {
1083226584Sdim        TokError("could not get type for !foreach");
1084226584Sdim        return 0;
1085226584Sdim      }
1086226584Sdim      Type = MHSt->getType();
1087226584Sdim      break;
1088226584Sdim    }
1089226584Sdim    case tgtok::XSubst: {
1090243830Sdim      TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1091226584Sdim      if (RHSt == 0) {
1092226584Sdim        TokError("could not get type for !subst");
1093226584Sdim        return 0;
1094226584Sdim      }
1095226584Sdim      Type = RHSt->getType();
1096226584Sdim      break;
1097226584Sdim    }
1098226584Sdim    }
1099226584Sdim    return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1100226584Sdim                                                             CurMultiClass);
1101226584Sdim  }
1102226584Sdim  }
1103226584Sdim}
1104226584Sdim
1105226584Sdim/// ParseOperatorType - Parse a type for an operator.  This returns
1106226584Sdim/// null on error.
1107226584Sdim///
1108226584Sdim/// OperatorType ::= '<' Type '>'
1109226584Sdim///
1110226584SdimRecTy *TGParser::ParseOperatorType() {
1111226584Sdim  RecTy *Type = 0;
1112226584Sdim
1113226584Sdim  if (Lex.getCode() != tgtok::less) {
1114226584Sdim    TokError("expected type name for operator");
1115226584Sdim    return 0;
1116226584Sdim  }
1117226584Sdim  Lex.Lex();  // eat the <
1118226584Sdim
1119226584Sdim  Type = ParseType();
1120226584Sdim
1121226584Sdim  if (Type == 0) {
1122226584Sdim    TokError("expected type name for operator");
1123226584Sdim    return 0;
1124226584Sdim  }
1125226584Sdim
1126226584Sdim  if (Lex.getCode() != tgtok::greater) {
1127226584Sdim    TokError("expected type name for operator");
1128226584Sdim    return 0;
1129226584Sdim  }
1130226584Sdim  Lex.Lex();  // eat the >
1131226584Sdim
1132226584Sdim  return Type;
1133226584Sdim}
1134226584Sdim
1135226584Sdim
1136226584Sdim/// ParseSimpleValue - Parse a tblgen value.  This returns null on error.
1137226584Sdim///
1138226584Sdim///   SimpleValue ::= IDValue
1139226584Sdim///   SimpleValue ::= INTVAL
1140226584Sdim///   SimpleValue ::= STRVAL+
1141226584Sdim///   SimpleValue ::= CODEFRAGMENT
1142226584Sdim///   SimpleValue ::= '?'
1143226584Sdim///   SimpleValue ::= '{' ValueList '}'
1144226584Sdim///   SimpleValue ::= ID '<' ValueListNE '>'
1145226584Sdim///   SimpleValue ::= '[' ValueList ']'
1146226584Sdim///   SimpleValue ::= '(' IDValue DagArgList ')'
1147226584Sdim///   SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1148249423Sdim///   SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1149226584Sdim///   SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1150226584Sdim///   SimpleValue ::= SRATOK '(' Value ',' Value ')'
1151226584Sdim///   SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1152226584Sdim///   SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1153226584Sdim///
1154234353SdimInit *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1155234353Sdim                                 IDParseMode Mode) {
1156226584Sdim  Init *R = 0;
1157226584Sdim  switch (Lex.getCode()) {
1158226584Sdim  default: TokError("Unknown token when parsing a value"); break;
1159234353Sdim  case tgtok::paste:
1160234353Sdim    // This is a leading paste operation.  This is deprecated but
1161234353Sdim    // still exists in some .td files.  Ignore it.
1162234353Sdim    Lex.Lex();  // Skip '#'.
1163234353Sdim    return ParseSimpleValue(CurRec, ItemType, Mode);
1164226584Sdim  case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1165226584Sdim  case tgtok::StrVal: {
1166226584Sdim    std::string Val = Lex.getCurStrVal();
1167226584Sdim    Lex.Lex();
1168226584Sdim
1169226584Sdim    // Handle multiple consecutive concatenated strings.
1170226584Sdim    while (Lex.getCode() == tgtok::StrVal) {
1171226584Sdim      Val += Lex.getCurStrVal();
1172226584Sdim      Lex.Lex();
1173226584Sdim    }
1174226584Sdim
1175226584Sdim    R = StringInit::get(Val);
1176226584Sdim    break;
1177226584Sdim  }
1178226584Sdim  case tgtok::CodeFragment:
1179234353Sdim    R = StringInit::get(Lex.getCurStrVal());
1180226584Sdim    Lex.Lex();
1181226584Sdim    break;
1182226584Sdim  case tgtok::question:
1183226584Sdim    R = UnsetInit::get();
1184226584Sdim    Lex.Lex();
1185226584Sdim    break;
1186226584Sdim  case tgtok::Id: {
1187226584Sdim    SMLoc NameLoc = Lex.getLoc();
1188226584Sdim    std::string Name = Lex.getCurStrVal();
1189226584Sdim    if (Lex.Lex() != tgtok::less)  // consume the Id.
1190234353Sdim      return ParseIDValue(CurRec, Name, NameLoc, Mode);    // Value ::= IDValue
1191226584Sdim
1192226584Sdim    // Value ::= ID '<' ValueListNE '>'
1193226584Sdim    if (Lex.Lex() == tgtok::greater) {
1194226584Sdim      TokError("expected non-empty value list");
1195226584Sdim      return 0;
1196226584Sdim    }
1197226584Sdim
1198226584Sdim    // This is a CLASS<initvalslist> expression.  This is supposed to synthesize
1199226584Sdim    // a new anonymous definition, deriving from CLASS<initvalslist> with no
1200226584Sdim    // body.
1201226584Sdim    Record *Class = Records.getClass(Name);
1202226584Sdim    if (!Class) {
1203226584Sdim      Error(NameLoc, "Expected a class name, got '" + Name + "'");
1204226584Sdim      return 0;
1205226584Sdim    }
1206226584Sdim
1207226584Sdim    std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1208226584Sdim    if (ValueList.empty()) return 0;
1209226584Sdim
1210226584Sdim    if (Lex.getCode() != tgtok::greater) {
1211226584Sdim      TokError("expected '>' at end of value list");
1212226584Sdim      return 0;
1213226584Sdim    }
1214226584Sdim    Lex.Lex();  // eat the '>'
1215249423Sdim    SMLoc EndLoc = Lex.getLoc();
1216226584Sdim
1217226584Sdim    // Create the new record, set it as CurRec temporarily.
1218226584Sdim    static unsigned AnonCounter = 0;
1219226584Sdim    Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),
1220226584Sdim                                NameLoc,
1221249423Sdim                                Records,
1222249423Sdim                                /*IsAnonymous=*/true);
1223226584Sdim    SubClassReference SCRef;
1224249423Sdim    SCRef.RefRange = SMRange(NameLoc, EndLoc);
1225226584Sdim    SCRef.Rec = Class;
1226226584Sdim    SCRef.TemplateArgs = ValueList;
1227226584Sdim    // Add info about the subclass to NewRec.
1228226584Sdim    if (AddSubClass(NewRec, SCRef))
1229226584Sdim      return 0;
1230226584Sdim    NewRec->resolveReferences();
1231226584Sdim    Records.addDef(NewRec);
1232226584Sdim
1233226584Sdim    // The result of the expression is a reference to the new record.
1234226584Sdim    return DefInit::get(NewRec);
1235226584Sdim  }
1236226584Sdim  case tgtok::l_brace: {           // Value ::= '{' ValueList '}'
1237226584Sdim    SMLoc BraceLoc = Lex.getLoc();
1238226584Sdim    Lex.Lex(); // eat the '{'
1239226584Sdim    std::vector<Init*> Vals;
1240226584Sdim
1241226584Sdim    if (Lex.getCode() != tgtok::r_brace) {
1242226584Sdim      Vals = ParseValueList(CurRec);
1243226584Sdim      if (Vals.empty()) return 0;
1244226584Sdim    }
1245226584Sdim    if (Lex.getCode() != tgtok::r_brace) {
1246226584Sdim      TokError("expected '}' at end of bit list value");
1247226584Sdim      return 0;
1248226584Sdim    }
1249226584Sdim    Lex.Lex();  // eat the '}'
1250226584Sdim
1251226584Sdim    SmallVector<Init *, 16> NewBits(Vals.size());
1252226584Sdim
1253226584Sdim    for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1254226584Sdim      Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1255226584Sdim      if (Bit == 0) {
1256226584Sdim        Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1257226584Sdim              ") is not convertable to a bit");
1258226584Sdim        return 0;
1259226584Sdim      }
1260226584Sdim      NewBits[Vals.size()-i-1] = Bit;
1261226584Sdim    }
1262226584Sdim    return BitsInit::get(NewBits);
1263226584Sdim  }
1264226584Sdim  case tgtok::l_square: {          // Value ::= '[' ValueList ']'
1265226584Sdim    Lex.Lex(); // eat the '['
1266226584Sdim    std::vector<Init*> Vals;
1267226584Sdim
1268226584Sdim    RecTy *DeducedEltTy = 0;
1269226584Sdim    ListRecTy *GivenListTy = 0;
1270226584Sdim
1271226584Sdim    if (ItemType != 0) {
1272243830Sdim      ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1273226584Sdim      if (ListType == 0) {
1274261991Sdim        std::string s;
1275261991Sdim        raw_string_ostream ss(s);
1276261991Sdim        ss << "Type mismatch for list, expected list type, got "
1277261991Sdim           << ItemType->getAsString();
1278261991Sdim        TokError(ss.str());
1279226584Sdim        return 0;
1280226584Sdim      }
1281226584Sdim      GivenListTy = ListType;
1282226584Sdim    }
1283226584Sdim
1284226584Sdim    if (Lex.getCode() != tgtok::r_square) {
1285226584Sdim      Vals = ParseValueList(CurRec, 0,
1286226584Sdim                            GivenListTy ? GivenListTy->getElementType() : 0);
1287226584Sdim      if (Vals.empty()) return 0;
1288226584Sdim    }
1289226584Sdim    if (Lex.getCode() != tgtok::r_square) {
1290226584Sdim      TokError("expected ']' at end of list value");
1291226584Sdim      return 0;
1292226584Sdim    }
1293226584Sdim    Lex.Lex();  // eat the ']'
1294226584Sdim
1295226584Sdim    RecTy *GivenEltTy = 0;
1296226584Sdim    if (Lex.getCode() == tgtok::less) {
1297226584Sdim      // Optional list element type
1298226584Sdim      Lex.Lex();  // eat the '<'
1299226584Sdim
1300226584Sdim      GivenEltTy = ParseType();
1301226584Sdim      if (GivenEltTy == 0) {
1302226584Sdim        // Couldn't parse element type
1303226584Sdim        return 0;
1304226584Sdim      }
1305226584Sdim
1306226584Sdim      if (Lex.getCode() != tgtok::greater) {
1307226584Sdim        TokError("expected '>' at end of list element type");
1308226584Sdim        return 0;
1309226584Sdim      }
1310226584Sdim      Lex.Lex();  // eat the '>'
1311226584Sdim    }
1312226584Sdim
1313226584Sdim    // Check elements
1314226584Sdim    RecTy *EltTy = 0;
1315226584Sdim    for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1316226584Sdim         i != ie;
1317226584Sdim         ++i) {
1318243830Sdim      TypedInit *TArg = dyn_cast<TypedInit>(*i);
1319226584Sdim      if (TArg == 0) {
1320226584Sdim        TokError("Untyped list element");
1321226584Sdim        return 0;
1322226584Sdim      }
1323226584Sdim      if (EltTy != 0) {
1324226584Sdim        EltTy = resolveTypes(EltTy, TArg->getType());
1325226584Sdim        if (EltTy == 0) {
1326226584Sdim          TokError("Incompatible types in list elements");
1327226584Sdim          return 0;
1328226584Sdim        }
1329226584Sdim      } else {
1330226584Sdim        EltTy = TArg->getType();
1331226584Sdim      }
1332226584Sdim    }
1333226584Sdim
1334226584Sdim    if (GivenEltTy != 0) {
1335226584Sdim      if (EltTy != 0) {
1336226584Sdim        // Verify consistency
1337226584Sdim        if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1338226584Sdim          TokError("Incompatible types in list elements");
1339226584Sdim          return 0;
1340226584Sdim        }
1341226584Sdim      }
1342226584Sdim      EltTy = GivenEltTy;
1343226584Sdim    }
1344226584Sdim
1345226584Sdim    if (EltTy == 0) {
1346226584Sdim      if (ItemType == 0) {
1347226584Sdim        TokError("No type for list");
1348226584Sdim        return 0;
1349226584Sdim      }
1350226584Sdim      DeducedEltTy = GivenListTy->getElementType();
1351226584Sdim    } else {
1352226584Sdim      // Make sure the deduced type is compatible with the given type
1353226584Sdim      if (GivenListTy) {
1354226584Sdim        if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1355226584Sdim          TokError("Element type mismatch for list");
1356226584Sdim          return 0;
1357226584Sdim        }
1358226584Sdim      }
1359226584Sdim      DeducedEltTy = EltTy;
1360226584Sdim    }
1361226584Sdim
1362226584Sdim    return ListInit::get(Vals, DeducedEltTy);
1363226584Sdim  }
1364226584Sdim  case tgtok::l_paren: {         // Value ::= '(' IDValue DagArgList ')'
1365226584Sdim    Lex.Lex();   // eat the '('
1366226584Sdim    if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1367226584Sdim      TokError("expected identifier in dag init");
1368226584Sdim      return 0;
1369226584Sdim    }
1370226584Sdim
1371226584Sdim    Init *Operator = ParseValue(CurRec);
1372226584Sdim    if (Operator == 0) return 0;
1373226584Sdim
1374226584Sdim    // If the operator name is present, parse it.
1375226584Sdim    std::string OperatorName;
1376226584Sdim    if (Lex.getCode() == tgtok::colon) {
1377226584Sdim      if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1378226584Sdim        TokError("expected variable name in dag operator");
1379226584Sdim        return 0;
1380226584Sdim      }
1381226584Sdim      OperatorName = Lex.getCurStrVal();
1382226584Sdim      Lex.Lex();  // eat the VarName.
1383226584Sdim    }
1384226584Sdim
1385226584Sdim    std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1386226584Sdim    if (Lex.getCode() != tgtok::r_paren) {
1387226584Sdim      DagArgs = ParseDagArgList(CurRec);
1388226584Sdim      if (DagArgs.empty()) return 0;
1389226584Sdim    }
1390226584Sdim
1391226584Sdim    if (Lex.getCode() != tgtok::r_paren) {
1392226584Sdim      TokError("expected ')' in dag init");
1393226584Sdim      return 0;
1394226584Sdim    }
1395226584Sdim    Lex.Lex();  // eat the ')'
1396226584Sdim
1397226584Sdim    return DagInit::get(Operator, OperatorName, DagArgs);
1398226584Sdim  }
1399226584Sdim
1400226584Sdim  case tgtok::XHead:
1401226584Sdim  case tgtok::XTail:
1402226584Sdim  case tgtok::XEmpty:
1403226584Sdim  case tgtok::XCast:  // Value ::= !unop '(' Value ')'
1404226584Sdim  case tgtok::XConcat:
1405249423Sdim  case tgtok::XADD:
1406226584Sdim  case tgtok::XSRA:
1407226584Sdim  case tgtok::XSRL:
1408226584Sdim  case tgtok::XSHL:
1409226584Sdim  case tgtok::XEq:
1410226584Sdim  case tgtok::XStrConcat:   // Value ::= !binop '(' Value ',' Value ')'
1411226584Sdim  case tgtok::XIf:
1412226584Sdim  case tgtok::XForEach:
1413226584Sdim  case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1414226584Sdim    return ParseOperation(CurRec);
1415226584Sdim  }
1416226584Sdim  }
1417226584Sdim
1418226584Sdim  return R;
1419226584Sdim}
1420226584Sdim
1421226584Sdim/// ParseValue - Parse a tblgen value.  This returns null on error.
1422226584Sdim///
1423226584Sdim///   Value       ::= SimpleValue ValueSuffix*
1424226584Sdim///   ValueSuffix ::= '{' BitList '}'
1425226584Sdim///   ValueSuffix ::= '[' BitList ']'
1426226584Sdim///   ValueSuffix ::= '.' ID
1427226584Sdim///
1428234353SdimInit *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1429234353Sdim  Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1430226584Sdim  if (Result == 0) return 0;
1431226584Sdim
1432226584Sdim  // Parse the suffixes now if present.
1433226584Sdim  while (1) {
1434226584Sdim    switch (Lex.getCode()) {
1435226584Sdim    default: return Result;
1436226584Sdim    case tgtok::l_brace: {
1437234353Sdim      if (Mode == ParseNameMode || Mode == ParseForeachMode)
1438234353Sdim        // This is the beginning of the object body.
1439234353Sdim        return Result;
1440234353Sdim
1441226584Sdim      SMLoc CurlyLoc = Lex.getLoc();
1442226584Sdim      Lex.Lex(); // eat the '{'
1443226584Sdim      std::vector<unsigned> Ranges = ParseRangeList();
1444226584Sdim      if (Ranges.empty()) return 0;
1445226584Sdim
1446226584Sdim      // Reverse the bitlist.
1447226584Sdim      std::reverse(Ranges.begin(), Ranges.end());
1448226584Sdim      Result = Result->convertInitializerBitRange(Ranges);
1449226584Sdim      if (Result == 0) {
1450226584Sdim        Error(CurlyLoc, "Invalid bit range for value");
1451226584Sdim        return 0;
1452226584Sdim      }
1453226584Sdim
1454226584Sdim      // Eat the '}'.
1455226584Sdim      if (Lex.getCode() != tgtok::r_brace) {
1456226584Sdim        TokError("expected '}' at end of bit range list");
1457226584Sdim        return 0;
1458226584Sdim      }
1459226584Sdim      Lex.Lex();
1460226584Sdim      break;
1461226584Sdim    }
1462226584Sdim    case tgtok::l_square: {
1463226584Sdim      SMLoc SquareLoc = Lex.getLoc();
1464226584Sdim      Lex.Lex(); // eat the '['
1465226584Sdim      std::vector<unsigned> Ranges = ParseRangeList();
1466226584Sdim      if (Ranges.empty()) return 0;
1467226584Sdim
1468226584Sdim      Result = Result->convertInitListSlice(Ranges);
1469226584Sdim      if (Result == 0) {
1470226584Sdim        Error(SquareLoc, "Invalid range for list slice");
1471226584Sdim        return 0;
1472226584Sdim      }
1473226584Sdim
1474226584Sdim      // Eat the ']'.
1475226584Sdim      if (Lex.getCode() != tgtok::r_square) {
1476226584Sdim        TokError("expected ']' at end of list slice");
1477226584Sdim        return 0;
1478226584Sdim      }
1479226584Sdim      Lex.Lex();
1480226584Sdim      break;
1481226584Sdim    }
1482226584Sdim    case tgtok::period:
1483226584Sdim      if (Lex.Lex() != tgtok::Id) {  // eat the .
1484226584Sdim        TokError("expected field identifier after '.'");
1485226584Sdim        return 0;
1486226584Sdim      }
1487226584Sdim      if (!Result->getFieldType(Lex.getCurStrVal())) {
1488226584Sdim        TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1489226584Sdim                 Result->getAsString() + "'");
1490226584Sdim        return 0;
1491226584Sdim      }
1492226584Sdim      Result = FieldInit::get(Result, Lex.getCurStrVal());
1493226584Sdim      Lex.Lex();  // eat field name
1494226584Sdim      break;
1495234353Sdim
1496234353Sdim    case tgtok::paste:
1497234353Sdim      SMLoc PasteLoc = Lex.getLoc();
1498234353Sdim
1499234353Sdim      // Create a !strconcat() operation, first casting each operand to
1500234353Sdim      // a string if necessary.
1501234353Sdim
1502243830Sdim      TypedInit *LHS = dyn_cast<TypedInit>(Result);
1503234353Sdim      if (!LHS) {
1504234353Sdim        Error(PasteLoc, "LHS of paste is not typed!");
1505234353Sdim        return 0;
1506234353Sdim      }
1507234353Sdim
1508234353Sdim      if (LHS->getType() != StringRecTy::get()) {
1509234353Sdim        LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1510234353Sdim      }
1511234353Sdim
1512234353Sdim      TypedInit *RHS = 0;
1513234353Sdim
1514234353Sdim      Lex.Lex();  // Eat the '#'.
1515234353Sdim      switch (Lex.getCode()) {
1516234353Sdim      case tgtok::colon:
1517234353Sdim      case tgtok::semi:
1518234353Sdim      case tgtok::l_brace:
1519234353Sdim        // These are all of the tokens that can begin an object body.
1520234353Sdim        // Some of these can also begin values but we disallow those cases
1521234353Sdim        // because they are unlikely to be useful.
1522234353Sdim
1523234353Sdim        // Trailing paste, concat with an empty string.
1524234353Sdim        RHS = StringInit::get("");
1525234353Sdim        break;
1526234353Sdim
1527234353Sdim      default:
1528234353Sdim        Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1529243830Sdim        RHS = dyn_cast<TypedInit>(RHSResult);
1530234353Sdim        if (!RHS) {
1531234353Sdim          Error(PasteLoc, "RHS of paste is not typed!");
1532234353Sdim          return 0;
1533234353Sdim        }
1534234353Sdim
1535234353Sdim        if (RHS->getType() != StringRecTy::get()) {
1536234353Sdim          RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1537234353Sdim        }
1538234353Sdim
1539234353Sdim        break;
1540234353Sdim      }
1541234353Sdim
1542234353Sdim      Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1543234353Sdim                              StringRecTy::get())->Fold(CurRec, CurMultiClass);
1544234353Sdim      break;
1545226584Sdim    }
1546226584Sdim  }
1547226584Sdim}
1548226584Sdim
1549226584Sdim/// ParseDagArgList - Parse the argument list for a dag literal expression.
1550226584Sdim///
1551249423Sdim///    DagArg     ::= Value (':' VARNAME)?
1552249423Sdim///    DagArg     ::= VARNAME
1553249423Sdim///    DagArgList ::= DagArg
1554249423Sdim///    DagArgList ::= DagArgList ',' DagArg
1555226584Sdimstd::vector<std::pair<llvm::Init*, std::string> >
1556226584SdimTGParser::ParseDagArgList(Record *CurRec) {
1557226584Sdim  std::vector<std::pair<llvm::Init*, std::string> > Result;
1558226584Sdim
1559226584Sdim  while (1) {
1560249423Sdim    // DagArg ::= VARNAME
1561249423Sdim    if (Lex.getCode() == tgtok::VarName) {
1562249423Sdim      // A missing value is treated like '?'.
1563249423Sdim      Result.push_back(std::make_pair(UnsetInit::get(), Lex.getCurStrVal()));
1564249423Sdim      Lex.Lex();
1565249423Sdim    } else {
1566249423Sdim      // DagArg ::= Value (':' VARNAME)?
1567249423Sdim      Init *Val = ParseValue(CurRec);
1568249423Sdim      if (Val == 0)
1569249423Sdim        return std::vector<std::pair<llvm::Init*, std::string> >();
1570226584Sdim
1571249423Sdim      // If the variable name is present, add it.
1572249423Sdim      std::string VarName;
1573249423Sdim      if (Lex.getCode() == tgtok::colon) {
1574249423Sdim        if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1575249423Sdim          TokError("expected variable name in dag literal");
1576249423Sdim          return std::vector<std::pair<llvm::Init*, std::string> >();
1577249423Sdim        }
1578249423Sdim        VarName = Lex.getCurStrVal();
1579249423Sdim        Lex.Lex();  // eat the VarName.
1580226584Sdim      }
1581249423Sdim
1582249423Sdim      Result.push_back(std::make_pair(Val, VarName));
1583226584Sdim    }
1584226584Sdim    if (Lex.getCode() != tgtok::comma) break;
1585226584Sdim    Lex.Lex(); // eat the ','
1586226584Sdim  }
1587226584Sdim
1588226584Sdim  return Result;
1589226584Sdim}
1590226584Sdim
1591226584Sdim
1592226584Sdim/// ParseValueList - Parse a comma separated list of values, returning them as a
1593226584Sdim/// vector.  Note that this always expects to be able to parse at least one
1594226584Sdim/// value.  It returns an empty list if this is not possible.
1595226584Sdim///
1596226584Sdim///   ValueList ::= Value (',' Value)
1597226584Sdim///
1598226584Sdimstd::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1599226584Sdim                                            RecTy *EltTy) {
1600226584Sdim  std::vector<Init*> Result;
1601226584Sdim  RecTy *ItemType = EltTy;
1602226584Sdim  unsigned int ArgN = 0;
1603226584Sdim  if (ArgsRec != 0 && EltTy == 0) {
1604234353Sdim    const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1605234353Sdim    if (!TArgs.size()) {
1606234353Sdim      TokError("template argument provided to non-template class");
1607234353Sdim      return std::vector<Init*>();
1608234353Sdim    }
1609226584Sdim    const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1610226584Sdim    if (!RV) {
1611226584Sdim      errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1612226584Sdim        << ")\n";
1613226584Sdim    }
1614226584Sdim    assert(RV && "Template argument record not found??");
1615226584Sdim    ItemType = RV->getType();
1616226584Sdim    ++ArgN;
1617226584Sdim  }
1618226584Sdim  Result.push_back(ParseValue(CurRec, ItemType));
1619226584Sdim  if (Result.back() == 0) return std::vector<Init*>();
1620226584Sdim
1621226584Sdim  while (Lex.getCode() == tgtok::comma) {
1622226584Sdim    Lex.Lex();  // Eat the comma
1623226584Sdim
1624226584Sdim    if (ArgsRec != 0 && EltTy == 0) {
1625234353Sdim      const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1626226584Sdim      if (ArgN >= TArgs.size()) {
1627226584Sdim        TokError("too many template arguments");
1628226584Sdim        return std::vector<Init*>();
1629226584Sdim      }
1630226584Sdim      const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1631226584Sdim      assert(RV && "Template argument record not found??");
1632226584Sdim      ItemType = RV->getType();
1633226584Sdim      ++ArgN;
1634226584Sdim    }
1635226584Sdim    Result.push_back(ParseValue(CurRec, ItemType));
1636226584Sdim    if (Result.back() == 0) return std::vector<Init*>();
1637226584Sdim  }
1638226584Sdim
1639226584Sdim  return Result;
1640226584Sdim}
1641226584Sdim
1642226584Sdim
1643226584Sdim/// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1644226584Sdim/// empty string on error.  This can happen in a number of different context's,
1645226584Sdim/// including within a def or in the template args for a def (which which case
1646226584Sdim/// CurRec will be non-null) and within the template args for a multiclass (in
1647226584Sdim/// which case CurRec will be null, but CurMultiClass will be set).  This can
1648226584Sdim/// also happen within a def that is within a multiclass, which will set both
1649226584Sdim/// CurRec and CurMultiClass.
1650226584Sdim///
1651226584Sdim///  Declaration ::= FIELD? Type ID ('=' Value)?
1652226584Sdim///
1653234353SdimInit *TGParser::ParseDeclaration(Record *CurRec,
1654226584Sdim                                       bool ParsingTemplateArgs) {
1655226584Sdim  // Read the field prefix if present.
1656226584Sdim  bool HasField = Lex.getCode() == tgtok::Field;
1657226584Sdim  if (HasField) Lex.Lex();
1658226584Sdim
1659226584Sdim  RecTy *Type = ParseType();
1660234353Sdim  if (Type == 0) return 0;
1661226584Sdim
1662226584Sdim  if (Lex.getCode() != tgtok::Id) {
1663226584Sdim    TokError("Expected identifier in declaration");
1664234353Sdim    return 0;
1665226584Sdim  }
1666226584Sdim
1667226584Sdim  SMLoc IdLoc = Lex.getLoc();
1668234353Sdim  Init *DeclName = StringInit::get(Lex.getCurStrVal());
1669226584Sdim  Lex.Lex();
1670226584Sdim
1671226584Sdim  if (ParsingTemplateArgs) {
1672226584Sdim    if (CurRec) {
1673234353Sdim      DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1674226584Sdim    } else {
1675226584Sdim      assert(CurMultiClass);
1676226584Sdim    }
1677226584Sdim    if (CurMultiClass)
1678234353Sdim      DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1679234353Sdim                             "::");
1680226584Sdim  }
1681226584Sdim
1682226584Sdim  // Add the value.
1683226584Sdim  if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1684234353Sdim    return 0;
1685226584Sdim
1686226584Sdim  // If a value is present, parse it.
1687226584Sdim  if (Lex.getCode() == tgtok::equal) {
1688226584Sdim    Lex.Lex();
1689226584Sdim    SMLoc ValLoc = Lex.getLoc();
1690226584Sdim    Init *Val = ParseValue(CurRec, Type);
1691226584Sdim    if (Val == 0 ||
1692226584Sdim        SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1693234353Sdim      return 0;
1694226584Sdim  }
1695226584Sdim
1696226584Sdim  return DeclName;
1697226584Sdim}
1698226584Sdim
1699234353Sdim/// ParseForeachDeclaration - Read a foreach declaration, returning
1700234353Sdim/// the name of the declared object or a NULL Init on error.  Return
1701234353Sdim/// the name of the parsed initializer list through ForeachListName.
1702234353Sdim///
1703239462Sdim///  ForeachDeclaration ::= ID '=' '[' ValueList ']'
1704239462Sdim///  ForeachDeclaration ::= ID '=' '{' RangeList '}'
1705239462Sdim///  ForeachDeclaration ::= ID '=' RangePiece
1706234353Sdim///
1707239462SdimVarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1708234353Sdim  if (Lex.getCode() != tgtok::Id) {
1709234353Sdim    TokError("Expected identifier in foreach declaration");
1710234353Sdim    return 0;
1711234353Sdim  }
1712234353Sdim
1713234353Sdim  Init *DeclName = StringInit::get(Lex.getCurStrVal());
1714234353Sdim  Lex.Lex();
1715234353Sdim
1716234353Sdim  // If a value is present, parse it.
1717234353Sdim  if (Lex.getCode() != tgtok::equal) {
1718234353Sdim    TokError("Expected '=' in foreach declaration");
1719234353Sdim    return 0;
1720234353Sdim  }
1721234353Sdim  Lex.Lex();  // Eat the '='
1722234353Sdim
1723239462Sdim  RecTy *IterType = 0;
1724239462Sdim  std::vector<unsigned> Ranges;
1725234353Sdim
1726239462Sdim  switch (Lex.getCode()) {
1727239462Sdim  default: TokError("Unknown token when expecting a range list"); return 0;
1728239462Sdim  case tgtok::l_square: { // '[' ValueList ']'
1729239462Sdim    Init *List = ParseSimpleValue(0, 0, ParseForeachMode);
1730243830Sdim    ForeachListValue = dyn_cast<ListInit>(List);
1731239462Sdim    if (ForeachListValue == 0) {
1732239462Sdim      TokError("Expected a Value list");
1733239462Sdim      return 0;
1734239462Sdim    }
1735239462Sdim    RecTy *ValueType = ForeachListValue->getType();
1736243830Sdim    ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1737239462Sdim    if (ListType == 0) {
1738239462Sdim      TokError("Value list is not of list type");
1739239462Sdim      return 0;
1740239462Sdim    }
1741239462Sdim    IterType = ListType->getElementType();
1742239462Sdim    break;
1743234353Sdim  }
1744234353Sdim
1745239462Sdim  case tgtok::IntVal: { // RangePiece.
1746239462Sdim    if (ParseRangePiece(Ranges))
1747239462Sdim      return 0;
1748239462Sdim    break;
1749234353Sdim  }
1750234353Sdim
1751239462Sdim  case tgtok::l_brace: { // '{' RangeList '}'
1752239462Sdim    Lex.Lex(); // eat the '{'
1753239462Sdim    Ranges = ParseRangeList();
1754239462Sdim    if (Lex.getCode() != tgtok::r_brace) {
1755239462Sdim      TokError("expected '}' at end of bit range list");
1756239462Sdim      return 0;
1757239462Sdim    }
1758239462Sdim    Lex.Lex();
1759239462Sdim    break;
1760239462Sdim  }
1761239462Sdim  }
1762234353Sdim
1763239462Sdim  if (!Ranges.empty()) {
1764239462Sdim    assert(!IterType && "Type already initialized?");
1765239462Sdim    IterType = IntRecTy::get();
1766239462Sdim    std::vector<Init*> Values;
1767239462Sdim    for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
1768239462Sdim      Values.push_back(IntInit::get(Ranges[i]));
1769239462Sdim    ForeachListValue = ListInit::get(Values, IterType);
1770239462Sdim  }
1771239462Sdim
1772239462Sdim  if (!IterType)
1773239462Sdim    return 0;
1774239462Sdim
1775239462Sdim  return VarInit::get(DeclName, IterType);
1776234353Sdim}
1777234353Sdim
1778226584Sdim/// ParseTemplateArgList - Read a template argument list, which is a non-empty
1779226584Sdim/// sequence of template-declarations in <>'s.  If CurRec is non-null, these are
1780226584Sdim/// template args for a def, which may or may not be in a multiclass.  If null,
1781226584Sdim/// these are the template args for a multiclass.
1782226584Sdim///
1783226584Sdim///    TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1784226584Sdim///
1785226584Sdimbool TGParser::ParseTemplateArgList(Record *CurRec) {
1786226584Sdim  assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1787226584Sdim  Lex.Lex(); // eat the '<'
1788226584Sdim
1789226584Sdim  Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1790226584Sdim
1791226584Sdim  // Read the first declaration.
1792234353Sdim  Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1793234353Sdim  if (TemplArg == 0)
1794226584Sdim    return true;
1795226584Sdim
1796226584Sdim  TheRecToAddTo->addTemplateArg(TemplArg);
1797226584Sdim
1798226584Sdim  while (Lex.getCode() == tgtok::comma) {
1799226584Sdim    Lex.Lex(); // eat the ','
1800226584Sdim
1801226584Sdim    // Read the following declarations.
1802226584Sdim    TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1803234353Sdim    if (TemplArg == 0)
1804226584Sdim      return true;
1805226584Sdim    TheRecToAddTo->addTemplateArg(TemplArg);
1806226584Sdim  }
1807226584Sdim
1808226584Sdim  if (Lex.getCode() != tgtok::greater)
1809226584Sdim    return TokError("expected '>' at end of template argument list");
1810226584Sdim  Lex.Lex(); // eat the '>'.
1811226584Sdim  return false;
1812226584Sdim}
1813226584Sdim
1814226584Sdim
1815226584Sdim/// ParseBodyItem - Parse a single item at within the body of a def or class.
1816226584Sdim///
1817226584Sdim///   BodyItem ::= Declaration ';'
1818226584Sdim///   BodyItem ::= LET ID OptionalBitList '=' Value ';'
1819226584Sdimbool TGParser::ParseBodyItem(Record *CurRec) {
1820226584Sdim  if (Lex.getCode() != tgtok::Let) {
1821234353Sdim    if (ParseDeclaration(CurRec, false) == 0)
1822226584Sdim      return true;
1823226584Sdim
1824226584Sdim    if (Lex.getCode() != tgtok::semi)
1825226584Sdim      return TokError("expected ';' after declaration");
1826226584Sdim    Lex.Lex();
1827226584Sdim    return false;
1828226584Sdim  }
1829226584Sdim
1830226584Sdim  // LET ID OptionalRangeList '=' Value ';'
1831226584Sdim  if (Lex.Lex() != tgtok::Id)
1832226584Sdim    return TokError("expected field identifier after let");
1833226584Sdim
1834226584Sdim  SMLoc IdLoc = Lex.getLoc();
1835226584Sdim  std::string FieldName = Lex.getCurStrVal();
1836226584Sdim  Lex.Lex();  // eat the field name.
1837226584Sdim
1838226584Sdim  std::vector<unsigned> BitList;
1839226584Sdim  if (ParseOptionalBitList(BitList))
1840226584Sdim    return true;
1841226584Sdim  std::reverse(BitList.begin(), BitList.end());
1842226584Sdim
1843226584Sdim  if (Lex.getCode() != tgtok::equal)
1844226584Sdim    return TokError("expected '=' in let expression");
1845226584Sdim  Lex.Lex();  // eat the '='.
1846226584Sdim
1847226584Sdim  RecordVal *Field = CurRec->getValue(FieldName);
1848226584Sdim  if (Field == 0)
1849226584Sdim    return TokError("Value '" + FieldName + "' unknown!");
1850226584Sdim
1851226584Sdim  RecTy *Type = Field->getType();
1852226584Sdim
1853226584Sdim  Init *Val = ParseValue(CurRec, Type);
1854226584Sdim  if (Val == 0) return true;
1855226584Sdim
1856226584Sdim  if (Lex.getCode() != tgtok::semi)
1857226584Sdim    return TokError("expected ';' after let expression");
1858226584Sdim  Lex.Lex();
1859226584Sdim
1860226584Sdim  return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1861226584Sdim}
1862226584Sdim
1863226584Sdim/// ParseBody - Read the body of a class or def.  Return true on error, false on
1864226584Sdim/// success.
1865226584Sdim///
1866226584Sdim///   Body     ::= ';'
1867226584Sdim///   Body     ::= '{' BodyList '}'
1868226584Sdim///   BodyList BodyItem*
1869226584Sdim///
1870226584Sdimbool TGParser::ParseBody(Record *CurRec) {
1871226584Sdim  // If this is a null definition, just eat the semi and return.
1872226584Sdim  if (Lex.getCode() == tgtok::semi) {
1873226584Sdim    Lex.Lex();
1874226584Sdim    return false;
1875226584Sdim  }
1876226584Sdim
1877226584Sdim  if (Lex.getCode() != tgtok::l_brace)
1878226584Sdim    return TokError("Expected ';' or '{' to start body");
1879226584Sdim  // Eat the '{'.
1880226584Sdim  Lex.Lex();
1881226584Sdim
1882226584Sdim  while (Lex.getCode() != tgtok::r_brace)
1883226584Sdim    if (ParseBodyItem(CurRec))
1884226584Sdim      return true;
1885226584Sdim
1886226584Sdim  // Eat the '}'.
1887226584Sdim  Lex.Lex();
1888226584Sdim  return false;
1889226584Sdim}
1890226584Sdim
1891249423Sdim/// \brief Apply the current let bindings to \a CurRec.
1892249423Sdim/// \returns true on error, false otherwise.
1893249423Sdimbool TGParser::ApplyLetStack(Record *CurRec) {
1894249423Sdim  for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1895249423Sdim    for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1896249423Sdim      if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1897249423Sdim                   LetStack[i][j].Bits, LetStack[i][j].Value))
1898249423Sdim        return true;
1899249423Sdim  return false;
1900249423Sdim}
1901249423Sdim
1902226584Sdim/// ParseObjectBody - Parse the body of a def or class.  This consists of an
1903226584Sdim/// optional ClassList followed by a Body.  CurRec is the current def or class
1904226584Sdim/// that is being parsed.
1905226584Sdim///
1906226584Sdim///   ObjectBody      ::= BaseClassList Body
1907226584Sdim///   BaseClassList   ::= /*empty*/
1908226584Sdim///   BaseClassList   ::= ':' BaseClassListNE
1909226584Sdim///   BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1910226584Sdim///
1911226584Sdimbool TGParser::ParseObjectBody(Record *CurRec) {
1912226584Sdim  // If there is a baseclass list, read it.
1913226584Sdim  if (Lex.getCode() == tgtok::colon) {
1914226584Sdim    Lex.Lex();
1915226584Sdim
1916226584Sdim    // Read all of the subclasses.
1917226584Sdim    SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1918226584Sdim    while (1) {
1919226584Sdim      // Check for error.
1920226584Sdim      if (SubClass.Rec == 0) return true;
1921226584Sdim
1922226584Sdim      // Add it.
1923226584Sdim      if (AddSubClass(CurRec, SubClass))
1924226584Sdim        return true;
1925226584Sdim
1926226584Sdim      if (Lex.getCode() != tgtok::comma) break;
1927226584Sdim      Lex.Lex(); // eat ','.
1928226584Sdim      SubClass = ParseSubClassReference(CurRec, false);
1929226584Sdim    }
1930226584Sdim  }
1931226584Sdim
1932249423Sdim  if (ApplyLetStack(CurRec))
1933249423Sdim    return true;
1934226584Sdim
1935226584Sdim  return ParseBody(CurRec);
1936226584Sdim}
1937226584Sdim
1938226584Sdim/// ParseDef - Parse and return a top level or multiclass def, return the record
1939226584Sdim/// corresponding to it.  This returns null on error.
1940226584Sdim///
1941226584Sdim///   DefInst ::= DEF ObjectName ObjectBody
1942226584Sdim///
1943226584Sdimbool TGParser::ParseDef(MultiClass *CurMultiClass) {
1944226584Sdim  SMLoc DefLoc = Lex.getLoc();
1945226584Sdim  assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1946226584Sdim  Lex.Lex();  // Eat the 'def' token.
1947226584Sdim
1948226584Sdim  // Parse ObjectName and make a record for it.
1949249423Sdim  Record *CurRec;
1950249423Sdim  Init *Name = ParseObjectName(CurMultiClass);
1951249423Sdim  if (Name)
1952249423Sdim    CurRec = new Record(Name, DefLoc, Records);
1953249423Sdim  else
1954249423Sdim    CurRec = new Record(GetNewAnonymousName(), DefLoc, Records,
1955249423Sdim                        /*IsAnonymous=*/true);
1956226584Sdim
1957239462Sdim  if (!CurMultiClass && Loops.empty()) {
1958226584Sdim    // Top-level def definition.
1959226584Sdim
1960226584Sdim    // Ensure redefinition doesn't happen.
1961234353Sdim    if (Records.getDef(CurRec->getNameInitAsString())) {
1962234353Sdim      Error(DefLoc, "def '" + CurRec->getNameInitAsString()
1963234353Sdim            + "' already defined");
1964226584Sdim      return true;
1965226584Sdim    }
1966226584Sdim    Records.addDef(CurRec);
1967239462Sdim  } else if (CurMultiClass) {
1968226584Sdim    // Otherwise, a def inside a multiclass, add it to the multiclass.
1969226584Sdim    for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1970234353Sdim      if (CurMultiClass->DefPrototypes[i]->getNameInit()
1971234353Sdim          == CurRec->getNameInit()) {
1972234353Sdim        Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
1973226584Sdim              "' already defined in this multiclass!");
1974226584Sdim        return true;
1975226584Sdim      }
1976226584Sdim    CurMultiClass->DefPrototypes.push_back(CurRec);
1977226584Sdim  }
1978226584Sdim
1979226584Sdim  if (ParseObjectBody(CurRec))
1980226584Sdim    return true;
1981226584Sdim
1982226584Sdim  if (CurMultiClass == 0)  // Def's in multiclasses aren't really defs.
1983226584Sdim    // See Record::setName().  This resolve step will see any new name
1984226584Sdim    // for the def that might have been created when resolving
1985226584Sdim    // inheritance, values and arguments above.
1986226584Sdim    CurRec->resolveReferences();
1987226584Sdim
1988226584Sdim  // If ObjectBody has template arguments, it's an error.
1989226584Sdim  assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1990226584Sdim
1991226584Sdim  if (CurMultiClass) {
1992226584Sdim    // Copy the template arguments for the multiclass into the def.
1993234353Sdim    const std::vector<Init *> &TArgs =
1994226584Sdim                                CurMultiClass->Rec.getTemplateArgs();
1995226584Sdim
1996226584Sdim    for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1997226584Sdim      const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1998226584Sdim      assert(RV && "Template arg doesn't exist?");
1999226584Sdim      CurRec->addValue(*RV);
2000226584Sdim    }
2001226584Sdim  }
2002226584Sdim
2003239462Sdim  if (ProcessForeachDefs(CurRec, DefLoc)) {
2004234353Sdim    Error(DefLoc,
2005234353Sdim          "Could not process loops for def" + CurRec->getNameInitAsString());
2006234353Sdim    return true;
2007234353Sdim  }
2008234353Sdim
2009226584Sdim  return false;
2010226584Sdim}
2011226584Sdim
2012234353Sdim/// ParseForeach - Parse a for statement.  Return the record corresponding
2013234353Sdim/// to it.  This returns true on error.
2014234353Sdim///
2015234353Sdim///   Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2016234353Sdim///   Foreach ::= FOREACH Declaration IN Object
2017234353Sdim///
2018234353Sdimbool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2019234353Sdim  assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2020234353Sdim  Lex.Lex();  // Eat the 'for' token.
2021234353Sdim
2022234353Sdim  // Make a temporary object to record items associated with the for
2023234353Sdim  // loop.
2024239462Sdim  ListInit *ListValue = 0;
2025239462Sdim  VarInit *IterName = ParseForeachDeclaration(ListValue);
2026234353Sdim  if (IterName == 0)
2027234353Sdim    return TokError("expected declaration in for");
2028234353Sdim
2029234353Sdim  if (Lex.getCode() != tgtok::In)
2030234353Sdim    return TokError("Unknown tok");
2031234353Sdim  Lex.Lex();  // Eat the in
2032234353Sdim
2033234353Sdim  // Create a loop object and remember it.
2034234353Sdim  Loops.push_back(ForeachLoop(IterName, ListValue));
2035234353Sdim
2036234353Sdim  if (Lex.getCode() != tgtok::l_brace) {
2037234353Sdim    // FOREACH Declaration IN Object
2038234353Sdim    if (ParseObject(CurMultiClass))
2039234353Sdim      return true;
2040234353Sdim  }
2041234353Sdim  else {
2042234353Sdim    SMLoc BraceLoc = Lex.getLoc();
2043234353Sdim    // Otherwise, this is a group foreach.
2044234353Sdim    Lex.Lex();  // eat the '{'.
2045234353Sdim
2046234353Sdim    // Parse the object list.
2047234353Sdim    if (ParseObjectList(CurMultiClass))
2048234353Sdim      return true;
2049234353Sdim
2050234353Sdim    if (Lex.getCode() != tgtok::r_brace) {
2051234353Sdim      TokError("expected '}' at end of foreach command");
2052234353Sdim      return Error(BraceLoc, "to match this '{'");
2053234353Sdim    }
2054234353Sdim    Lex.Lex();  // Eat the }
2055234353Sdim  }
2056234353Sdim
2057234353Sdim  // We've processed everything in this loop.
2058234353Sdim  Loops.pop_back();
2059234353Sdim
2060234353Sdim  return false;
2061234353Sdim}
2062234353Sdim
2063226584Sdim/// ParseClass - Parse a tblgen class definition.
2064226584Sdim///
2065226584Sdim///   ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2066226584Sdim///
2067226584Sdimbool TGParser::ParseClass() {
2068226584Sdim  assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2069226584Sdim  Lex.Lex();
2070226584Sdim
2071226584Sdim  if (Lex.getCode() != tgtok::Id)
2072226584Sdim    return TokError("expected class name after 'class' keyword");
2073226584Sdim
2074226584Sdim  Record *CurRec = Records.getClass(Lex.getCurStrVal());
2075226584Sdim  if (CurRec) {
2076226584Sdim    // If the body was previously defined, this is an error.
2077234353Sdim    if (CurRec->getValues().size() > 1 ||  // Account for NAME.
2078226584Sdim        !CurRec->getSuperClasses().empty() ||
2079226584Sdim        !CurRec->getTemplateArgs().empty())
2080234353Sdim      return TokError("Class '" + CurRec->getNameInitAsString()
2081234353Sdim                      + "' already defined");
2082226584Sdim  } else {
2083226584Sdim    // If this is the first reference to this class, create and add it.
2084226584Sdim    CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
2085226584Sdim    Records.addClass(CurRec);
2086226584Sdim  }
2087226584Sdim  Lex.Lex(); // eat the name.
2088226584Sdim
2089226584Sdim  // If there are template args, parse them.
2090226584Sdim  if (Lex.getCode() == tgtok::less)
2091226584Sdim    if (ParseTemplateArgList(CurRec))
2092226584Sdim      return true;
2093226584Sdim
2094226584Sdim  // Finally, parse the object body.
2095226584Sdim  return ParseObjectBody(CurRec);
2096226584Sdim}
2097226584Sdim
2098226584Sdim/// ParseLetList - Parse a non-empty list of assignment expressions into a list
2099226584Sdim/// of LetRecords.
2100226584Sdim///
2101226584Sdim///   LetList ::= LetItem (',' LetItem)*
2102226584Sdim///   LetItem ::= ID OptionalRangeList '=' Value
2103226584Sdim///
2104226584Sdimstd::vector<LetRecord> TGParser::ParseLetList() {
2105226584Sdim  std::vector<LetRecord> Result;
2106226584Sdim
2107226584Sdim  while (1) {
2108226584Sdim    if (Lex.getCode() != tgtok::Id) {
2109226584Sdim      TokError("expected identifier in let definition");
2110226584Sdim      return std::vector<LetRecord>();
2111226584Sdim    }
2112226584Sdim    std::string Name = Lex.getCurStrVal();
2113226584Sdim    SMLoc NameLoc = Lex.getLoc();
2114226584Sdim    Lex.Lex();  // Eat the identifier.
2115226584Sdim
2116226584Sdim    // Check for an optional RangeList.
2117226584Sdim    std::vector<unsigned> Bits;
2118226584Sdim    if (ParseOptionalRangeList(Bits))
2119226584Sdim      return std::vector<LetRecord>();
2120226584Sdim    std::reverse(Bits.begin(), Bits.end());
2121226584Sdim
2122226584Sdim    if (Lex.getCode() != tgtok::equal) {
2123226584Sdim      TokError("expected '=' in let expression");
2124226584Sdim      return std::vector<LetRecord>();
2125226584Sdim    }
2126226584Sdim    Lex.Lex();  // eat the '='.
2127226584Sdim
2128226584Sdim    Init *Val = ParseValue(0);
2129226584Sdim    if (Val == 0) return std::vector<LetRecord>();
2130226584Sdim
2131226584Sdim    // Now that we have everything, add the record.
2132226584Sdim    Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2133226584Sdim
2134226584Sdim    if (Lex.getCode() != tgtok::comma)
2135226584Sdim      return Result;
2136226584Sdim    Lex.Lex();  // eat the comma.
2137226584Sdim  }
2138226584Sdim}
2139226584Sdim
2140226584Sdim/// ParseTopLevelLet - Parse a 'let' at top level.  This can be a couple of
2141226584Sdim/// different related productions. This works inside multiclasses too.
2142226584Sdim///
2143226584Sdim///   Object ::= LET LetList IN '{' ObjectList '}'
2144226584Sdim///   Object ::= LET LetList IN Object
2145226584Sdim///
2146226584Sdimbool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2147226584Sdim  assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2148226584Sdim  Lex.Lex();
2149226584Sdim
2150226584Sdim  // Add this entry to the let stack.
2151226584Sdim  std::vector<LetRecord> LetInfo = ParseLetList();
2152226584Sdim  if (LetInfo.empty()) return true;
2153226584Sdim  LetStack.push_back(LetInfo);
2154226584Sdim
2155226584Sdim  if (Lex.getCode() != tgtok::In)
2156226584Sdim    return TokError("expected 'in' at end of top-level 'let'");
2157226584Sdim  Lex.Lex();
2158226584Sdim
2159226584Sdim  // If this is a scalar let, just handle it now
2160226584Sdim  if (Lex.getCode() != tgtok::l_brace) {
2161226584Sdim    // LET LetList IN Object
2162226584Sdim    if (ParseObject(CurMultiClass))
2163226584Sdim      return true;
2164226584Sdim  } else {   // Object ::= LETCommand '{' ObjectList '}'
2165226584Sdim    SMLoc BraceLoc = Lex.getLoc();
2166226584Sdim    // Otherwise, this is a group let.
2167226584Sdim    Lex.Lex();  // eat the '{'.
2168226584Sdim
2169226584Sdim    // Parse the object list.
2170226584Sdim    if (ParseObjectList(CurMultiClass))
2171226584Sdim      return true;
2172226584Sdim
2173226584Sdim    if (Lex.getCode() != tgtok::r_brace) {
2174226584Sdim      TokError("expected '}' at end of top level let command");
2175226584Sdim      return Error(BraceLoc, "to match this '{'");
2176226584Sdim    }
2177226584Sdim    Lex.Lex();
2178226584Sdim  }
2179226584Sdim
2180226584Sdim  // Outside this let scope, this let block is not active.
2181226584Sdim  LetStack.pop_back();
2182226584Sdim  return false;
2183226584Sdim}
2184226584Sdim
2185226584Sdim/// ParseMultiClass - Parse a multiclass definition.
2186226584Sdim///
2187226584Sdim///  MultiClassInst ::= MULTICLASS ID TemplateArgList?
2188249423Sdim///                     ':' BaseMultiClassList '{' MultiClassObject+ '}'
2189249423Sdim///  MultiClassObject ::= DefInst
2190249423Sdim///  MultiClassObject ::= MultiClassInst
2191249423Sdim///  MultiClassObject ::= DefMInst
2192249423Sdim///  MultiClassObject ::= LETCommand '{' ObjectList '}'
2193249423Sdim///  MultiClassObject ::= LETCommand Object
2194226584Sdim///
2195226584Sdimbool TGParser::ParseMultiClass() {
2196226584Sdim  assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2197226584Sdim  Lex.Lex();  // Eat the multiclass token.
2198226584Sdim
2199226584Sdim  if (Lex.getCode() != tgtok::Id)
2200226584Sdim    return TokError("expected identifier after multiclass for name");
2201226584Sdim  std::string Name = Lex.getCurStrVal();
2202226584Sdim
2203226584Sdim  if (MultiClasses.count(Name))
2204226584Sdim    return TokError("multiclass '" + Name + "' already defined");
2205226584Sdim
2206226584Sdim  CurMultiClass = MultiClasses[Name] = new MultiClass(Name,
2207226584Sdim                                                      Lex.getLoc(), Records);
2208226584Sdim  Lex.Lex();  // Eat the identifier.
2209226584Sdim
2210226584Sdim  // If there are template args, parse them.
2211226584Sdim  if (Lex.getCode() == tgtok::less)
2212226584Sdim    if (ParseTemplateArgList(0))
2213226584Sdim      return true;
2214226584Sdim
2215226584Sdim  bool inherits = false;
2216226584Sdim
2217226584Sdim  // If there are submulticlasses, parse them.
2218226584Sdim  if (Lex.getCode() == tgtok::colon) {
2219226584Sdim    inherits = true;
2220226584Sdim
2221226584Sdim    Lex.Lex();
2222226584Sdim
2223226584Sdim    // Read all of the submulticlasses.
2224226584Sdim    SubMultiClassReference SubMultiClass =
2225226584Sdim      ParseSubMultiClassReference(CurMultiClass);
2226226584Sdim    while (1) {
2227226584Sdim      // Check for error.
2228226584Sdim      if (SubMultiClass.MC == 0) return true;
2229226584Sdim
2230226584Sdim      // Add it.
2231226584Sdim      if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2232226584Sdim        return true;
2233226584Sdim
2234226584Sdim      if (Lex.getCode() != tgtok::comma) break;
2235226584Sdim      Lex.Lex(); // eat ','.
2236226584Sdim      SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2237226584Sdim    }
2238226584Sdim  }
2239226584Sdim
2240226584Sdim  if (Lex.getCode() != tgtok::l_brace) {
2241226584Sdim    if (!inherits)
2242226584Sdim      return TokError("expected '{' in multiclass definition");
2243226584Sdim    else if (Lex.getCode() != tgtok::semi)
2244226584Sdim      return TokError("expected ';' in multiclass definition");
2245226584Sdim    else
2246226584Sdim      Lex.Lex();  // eat the ';'.
2247226584Sdim  } else {
2248226584Sdim    if (Lex.Lex() == tgtok::r_brace)  // eat the '{'.
2249226584Sdim      return TokError("multiclass must contain at least one def");
2250226584Sdim
2251226584Sdim    while (Lex.getCode() != tgtok::r_brace) {
2252226584Sdim      switch (Lex.getCode()) {
2253226584Sdim        default:
2254226584Sdim          return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2255226584Sdim        case tgtok::Let:
2256226584Sdim        case tgtok::Def:
2257226584Sdim        case tgtok::Defm:
2258234353Sdim        case tgtok::Foreach:
2259226584Sdim          if (ParseObject(CurMultiClass))
2260226584Sdim            return true;
2261226584Sdim         break;
2262226584Sdim      }
2263226584Sdim    }
2264226584Sdim    Lex.Lex();  // eat the '}'.
2265226584Sdim  }
2266226584Sdim
2267226584Sdim  CurMultiClass = 0;
2268226584Sdim  return false;
2269226584Sdim}
2270226584Sdim
2271226584SdimRecord *TGParser::
2272226584SdimInstantiateMulticlassDef(MultiClass &MC,
2273226584Sdim                         Record *DefProto,
2274234353Sdim                         Init *DefmPrefix,
2275249423Sdim                         SMRange DefmPrefixRange) {
2276234353Sdim  // We need to preserve DefProto so it can be reused for later
2277234353Sdim  // instantiations, so create a new Record to inherit from it.
2278234353Sdim
2279226584Sdim  // Add in the defm name.  If the defm prefix is empty, give each
2280226584Sdim  // instantiated def a unique name.  Otherwise, if "#NAME#" exists in the
2281226584Sdim  // name, substitute the prefix for #NAME#.  Otherwise, use the defm name
2282226584Sdim  // as a prefix.
2283234353Sdim
2284249423Sdim  bool IsAnonymous = false;
2285249423Sdim  if (DefmPrefix == 0) {
2286234353Sdim    DefmPrefix = StringInit::get(GetNewAnonymousName());
2287249423Sdim    IsAnonymous = true;
2288249423Sdim  }
2289234353Sdim
2290234353Sdim  Init *DefName = DefProto->getNameInit();
2291234353Sdim
2292243830Sdim  StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2293234353Sdim
2294234353Sdim  if (DefNameString != 0) {
2295234353Sdim    // We have a fully expanded string so there are no operators to
2296234353Sdim    // resolve.  We should concatenate the given prefix and name.
2297234353Sdim    DefName =
2298234353Sdim      BinOpInit::get(BinOpInit::STRCONCAT,
2299234353Sdim                     UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2300234353Sdim                                   StringRecTy::get())->Fold(DefProto, &MC),
2301234353Sdim                     DefName, StringRecTy::get())->Fold(DefProto, &MC);
2302226584Sdim  }
2303226584Sdim
2304243830Sdim  // Make a trail of SMLocs from the multiclass instantiations.
2305249423Sdim  SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
2306243830Sdim  Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2307249423Sdim  Record *CurRec = new Record(DefName, Locs, Records, IsAnonymous);
2308226584Sdim
2309226584Sdim  SubClassReference Ref;
2310249423Sdim  Ref.RefRange = DefmPrefixRange;
2311226584Sdim  Ref.Rec = DefProto;
2312226584Sdim  AddSubClass(CurRec, Ref);
2313226584Sdim
2314239462Sdim  // Set the value for NAME. We don't resolve references to it 'til later,
2315239462Sdim  // though, so that uses in nested multiclass names don't get
2316239462Sdim  // confused.
2317249423Sdim  if (SetValue(CurRec, Ref.RefRange.Start, "NAME", std::vector<unsigned>(),
2318239462Sdim               DefmPrefix)) {
2319249423Sdim    Error(DefmPrefixRange.Start, "Could not resolve "
2320239462Sdim          + CurRec->getNameInitAsString() + ":NAME to '"
2321239462Sdim          + DefmPrefix->getAsUnquotedString() + "'");
2322239462Sdim    return 0;
2323239462Sdim  }
2324239462Sdim
2325239462Sdim  // If the DefNameString didn't resolve, we probably have a reference to
2326239462Sdim  // NAME and need to replace it. We need to do at least this much greedily,
2327239462Sdim  // otherwise nested multiclasses will end up with incorrect NAME expansions.
2328234353Sdim  if (DefNameString == 0) {
2329234353Sdim    RecordVal *DefNameRV = CurRec->getValue("NAME");
2330234353Sdim    CurRec->resolveReferencesTo(DefNameRV);
2331234353Sdim  }
2332234353Sdim
2333234353Sdim  if (!CurMultiClass) {
2334239462Sdim    // Now that we're at the top level, resolve all NAME references
2335239462Sdim    // in the resultant defs that weren't in the def names themselves.
2336239462Sdim    RecordVal *DefNameRV = CurRec->getValue("NAME");
2337239462Sdim    CurRec->resolveReferencesTo(DefNameRV);
2338239462Sdim
2339239462Sdim    // Now that NAME references are resolved and we're at the top level of
2340239462Sdim    // any multiclass expansions, add the record to the RecordKeeper. If we are
2341234353Sdim    // currently in a multiclass, it means this defm appears inside a
2342234353Sdim    // multiclass and its name won't be fully resolvable until we see
2343234353Sdim    // the top-level defm.  Therefore, we don't add this to the
2344234353Sdim    // RecordKeeper at this point.  If we did we could get duplicate
2345234353Sdim    // defs as more than one probably refers to NAME or some other
2346234353Sdim    // common internal placeholder.
2347234353Sdim
2348234353Sdim    // Ensure redefinition doesn't happen.
2349234353Sdim    if (Records.getDef(CurRec->getNameInitAsString())) {
2350249423Sdim      Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
2351234353Sdim            "' already defined, instantiating defm with subdef '" +
2352234353Sdim            DefProto->getNameInitAsString() + "'");
2353234353Sdim      return 0;
2354234353Sdim    }
2355234353Sdim
2356234353Sdim    Records.addDef(CurRec);
2357234353Sdim  }
2358234353Sdim
2359226584Sdim  return CurRec;
2360226584Sdim}
2361226584Sdim
2362226584Sdimbool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2363226584Sdim                                        Record *CurRec,
2364226584Sdim                                        SMLoc DefmPrefixLoc,
2365226584Sdim                                        SMLoc SubClassLoc,
2366234353Sdim                                        const std::vector<Init *> &TArgs,
2367226584Sdim                                        std::vector<Init *> &TemplateVals,
2368226584Sdim                                        bool DeleteArgs) {
2369226584Sdim  // Loop over all of the template arguments, setting them to the specified
2370226584Sdim  // value or leaving them as the default if necessary.
2371226584Sdim  for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2372226584Sdim    // Check if a value is specified for this temp-arg.
2373226584Sdim    if (i < TemplateVals.size()) {
2374226584Sdim      // Set it now.
2375226584Sdim      if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2376226584Sdim                   TemplateVals[i]))
2377226584Sdim        return true;
2378226584Sdim
2379226584Sdim      // Resolve it next.
2380226584Sdim      CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2381226584Sdim
2382226584Sdim      if (DeleteArgs)
2383226584Sdim        // Now remove it.
2384226584Sdim        CurRec->removeValue(TArgs[i]);
2385226584Sdim
2386226584Sdim    } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2387226584Sdim      return Error(SubClassLoc, "value not specified for template argument #"+
2388234353Sdim                   utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2389234353Sdim                   + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2390234353Sdim                   + "'");
2391226584Sdim    }
2392226584Sdim  }
2393226584Sdim  return false;
2394226584Sdim}
2395226584Sdim
2396226584Sdimbool TGParser::ResolveMulticlassDef(MultiClass &MC,
2397226584Sdim                                    Record *CurRec,
2398226584Sdim                                    Record *DefProto,
2399226584Sdim                                    SMLoc DefmPrefixLoc) {
2400226584Sdim  // If the mdef is inside a 'let' expression, add to each def.
2401249423Sdim  if (ApplyLetStack(CurRec))
2402249423Sdim    return Error(DefmPrefixLoc, "when instantiating this defm");
2403226584Sdim
2404226584Sdim  // Don't create a top level definition for defm inside multiclasses,
2405226584Sdim  // instead, only update the prototypes and bind the template args
2406226584Sdim  // with the new created definition.
2407249423Sdim  if (!CurMultiClass)
2408249423Sdim    return false;
2409249423Sdim  for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2410249423Sdim       i != e; ++i)
2411249423Sdim    if (CurMultiClass->DefPrototypes[i]->getNameInit()
2412249423Sdim        == CurRec->getNameInit())
2413249423Sdim      return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2414249423Sdim                   "' already defined in this multiclass!");
2415249423Sdim  CurMultiClass->DefPrototypes.push_back(CurRec);
2416226584Sdim
2417249423Sdim  // Copy the template arguments for the multiclass into the new def.
2418249423Sdim  const std::vector<Init *> &TA =
2419249423Sdim    CurMultiClass->Rec.getTemplateArgs();
2420226584Sdim
2421249423Sdim  for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2422249423Sdim    const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2423249423Sdim    assert(RV && "Template arg doesn't exist?");
2424249423Sdim    CurRec->addValue(*RV);
2425226584Sdim  }
2426226584Sdim
2427226584Sdim  return false;
2428226584Sdim}
2429226584Sdim
2430226584Sdim/// ParseDefm - Parse the instantiation of a multiclass.
2431226584Sdim///
2432226584Sdim///   DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2433226584Sdim///
2434226584Sdimbool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2435226584Sdim  assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2436249423Sdim  SMLoc DefmLoc = Lex.getLoc();
2437234353Sdim  Init *DefmPrefix = 0;
2438234353Sdim
2439226584Sdim  if (Lex.Lex() == tgtok::Id) {  // eat the defm.
2440234353Sdim    DefmPrefix = ParseObjectName(CurMultiClass);
2441226584Sdim  }
2442226584Sdim
2443249423Sdim  SMLoc DefmPrefixEndLoc = Lex.getLoc();
2444226584Sdim  if (Lex.getCode() != tgtok::colon)
2445226584Sdim    return TokError("expected ':' after defm identifier");
2446226584Sdim
2447226584Sdim  // Keep track of the new generated record definitions.
2448226584Sdim  std::vector<Record*> NewRecDefs;
2449226584Sdim
2450226584Sdim  // This record also inherits from a regular class (non-multiclass)?
2451226584Sdim  bool InheritFromClass = false;
2452226584Sdim
2453226584Sdim  // eat the colon.
2454226584Sdim  Lex.Lex();
2455226584Sdim
2456226584Sdim  SMLoc SubClassLoc = Lex.getLoc();
2457226584Sdim  SubClassReference Ref = ParseSubClassReference(0, true);
2458226584Sdim
2459226584Sdim  while (1) {
2460226584Sdim    if (Ref.Rec == 0) return true;
2461226584Sdim
2462226584Sdim    // To instantiate a multiclass, we need to first get the multiclass, then
2463226584Sdim    // instantiate each def contained in the multiclass with the SubClassRef
2464226584Sdim    // template parameters.
2465226584Sdim    MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2466226584Sdim    assert(MC && "Didn't lookup multiclass correctly?");
2467226584Sdim    std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2468226584Sdim
2469226584Sdim    // Verify that the correct number of template arguments were specified.
2470234353Sdim    const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2471226584Sdim    if (TArgs.size() < TemplateVals.size())
2472226584Sdim      return Error(SubClassLoc,
2473226584Sdim                   "more template args specified than multiclass expects");
2474226584Sdim
2475226584Sdim    // Loop over all the def's in the multiclass, instantiating each one.
2476226584Sdim    for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2477226584Sdim      Record *DefProto = MC->DefPrototypes[i];
2478226584Sdim
2479249423Sdim      Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix,
2480249423Sdim                                                SMRange(DefmLoc,
2481249423Sdim                                                        DefmPrefixEndLoc));
2482234353Sdim      if (!CurRec)
2483234353Sdim        return true;
2484226584Sdim
2485249423Sdim      if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
2486226584Sdim                                   TArgs, TemplateVals, true/*Delete args*/))
2487226584Sdim        return Error(SubClassLoc, "could not instantiate def");
2488226584Sdim
2489249423Sdim      if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmLoc))
2490226584Sdim        return Error(SubClassLoc, "could not instantiate def");
2491226584Sdim
2492226584Sdim      NewRecDefs.push_back(CurRec);
2493226584Sdim    }
2494226584Sdim
2495226584Sdim
2496226584Sdim    if (Lex.getCode() != tgtok::comma) break;
2497226584Sdim    Lex.Lex(); // eat ','.
2498226584Sdim
2499261991Sdim    if (Lex.getCode() != tgtok::Id)
2500261991Sdim      return TokError("expected identifier");
2501261991Sdim
2502226584Sdim    SubClassLoc = Lex.getLoc();
2503226584Sdim
2504226584Sdim    // A defm can inherit from regular classes (non-multiclass) as
2505226584Sdim    // long as they come in the end of the inheritance list.
2506226584Sdim    InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != 0);
2507226584Sdim
2508226584Sdim    if (InheritFromClass)
2509226584Sdim      break;
2510226584Sdim
2511226584Sdim    Ref = ParseSubClassReference(0, true);
2512226584Sdim  }
2513226584Sdim
2514226584Sdim  if (InheritFromClass) {
2515226584Sdim    // Process all the classes to inherit as if they were part of a
2516226584Sdim    // regular 'def' and inherit all record values.
2517226584Sdim    SubClassReference SubClass = ParseSubClassReference(0, false);
2518226584Sdim    while (1) {
2519226584Sdim      // Check for error.
2520226584Sdim      if (SubClass.Rec == 0) return true;
2521226584Sdim
2522226584Sdim      // Get the expanded definition prototypes and teach them about
2523226584Sdim      // the record values the current class to inherit has
2524226584Sdim      for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2525226584Sdim        Record *CurRec = NewRecDefs[i];
2526226584Sdim
2527226584Sdim        // Add it.
2528226584Sdim        if (AddSubClass(CurRec, SubClass))
2529226584Sdim          return true;
2530226584Sdim
2531249423Sdim        if (ApplyLetStack(CurRec))
2532249423Sdim          return true;
2533226584Sdim      }
2534226584Sdim
2535226584Sdim      if (Lex.getCode() != tgtok::comma) break;
2536226584Sdim      Lex.Lex(); // eat ','.
2537226584Sdim      SubClass = ParseSubClassReference(0, false);
2538226584Sdim    }
2539226584Sdim  }
2540226584Sdim
2541226584Sdim  if (!CurMultiClass)
2542226584Sdim    for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2543226584Sdim      // See Record::setName().  This resolve step will see any new
2544226584Sdim      // name for the def that might have been created when resolving
2545226584Sdim      // inheritance, values and arguments above.
2546226584Sdim      NewRecDefs[i]->resolveReferences();
2547226584Sdim
2548226584Sdim  if (Lex.getCode() != tgtok::semi)
2549226584Sdim    return TokError("expected ';' at end of defm");
2550226584Sdim  Lex.Lex();
2551226584Sdim
2552226584Sdim  return false;
2553226584Sdim}
2554226584Sdim
2555226584Sdim/// ParseObject
2556226584Sdim///   Object ::= ClassInst
2557226584Sdim///   Object ::= DefInst
2558226584Sdim///   Object ::= MultiClassInst
2559226584Sdim///   Object ::= DefMInst
2560226584Sdim///   Object ::= LETCommand '{' ObjectList '}'
2561226584Sdim///   Object ::= LETCommand Object
2562226584Sdimbool TGParser::ParseObject(MultiClass *MC) {
2563226584Sdim  switch (Lex.getCode()) {
2564226584Sdim  default:
2565226584Sdim    return TokError("Expected class, def, defm, multiclass or let definition");
2566226584Sdim  case tgtok::Let:   return ParseTopLevelLet(MC);
2567226584Sdim  case tgtok::Def:   return ParseDef(MC);
2568234353Sdim  case tgtok::Foreach:   return ParseForeach(MC);
2569226584Sdim  case tgtok::Defm:  return ParseDefm(MC);
2570226584Sdim  case tgtok::Class: return ParseClass();
2571226584Sdim  case tgtok::MultiClass: return ParseMultiClass();
2572226584Sdim  }
2573226584Sdim}
2574226584Sdim
2575226584Sdim/// ParseObjectList
2576226584Sdim///   ObjectList :== Object*
2577226584Sdimbool TGParser::ParseObjectList(MultiClass *MC) {
2578226584Sdim  while (isObjectStart(Lex.getCode())) {
2579226584Sdim    if (ParseObject(MC))
2580226584Sdim      return true;
2581226584Sdim  }
2582226584Sdim  return false;
2583226584Sdim}
2584226584Sdim
2585226584Sdimbool TGParser::ParseFile() {
2586226584Sdim  Lex.Lex(); // Prime the lexer.
2587226584Sdim  if (ParseObjectList()) return true;
2588226584Sdim
2589226584Sdim  // If we have unread input at the end of the file, report it.
2590226584Sdim  if (Lex.getCode() == tgtok::Eof)
2591226584Sdim    return false;
2592226584Sdim
2593226584Sdim  return TokError("Unexpected input at top level");
2594226584Sdim}
2595226584Sdim
2596