TGParser.cpp revision 8592b2b2a3dde4e5c8f00e855497f760ae94272f
1//===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Implement the Parser for TableGen.
11//
12//===----------------------------------------------------------------------===//
13
14#include "TGParser.h"
15#include "llvm/TableGen/Record.h"
16#include "llvm/ADT/StringExtras.h"
17#include <algorithm>
18#include <sstream>
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/Support/CommandLine.h"
21using namespace llvm;
22
23//===----------------------------------------------------------------------===//
24// Support Code for the Semantic Actions.
25//===----------------------------------------------------------------------===//
26
27namespace llvm {
28struct SubClassReference {
29  SMLoc RefLoc;
30  Record *Rec;
31  std::vector<Init*> TemplateArgs;
32  SubClassReference() : Rec(0) {}
33
34  bool isInvalid() const { return Rec == 0; }
35};
36
37struct SubMultiClassReference {
38  SMLoc RefLoc;
39  MultiClass *MC;
40  std::vector<Init*> TemplateArgs;
41  SubMultiClassReference() : MC(0) {}
42
43  bool isInvalid() const { return MC == 0; }
44  void dump() const;
45};
46
47void SubMultiClassReference::dump() const {
48  errs() << "Multiclass:\n";
49
50  MC->dump();
51
52  errs() << "Template args:\n";
53  for (std::vector<Init *>::const_iterator i = TemplateArgs.begin(),
54         iend = TemplateArgs.end();
55       i != iend;
56       ++i) {
57    (*i)->dump();
58  }
59}
60
61} // end namespace llvm
62
63bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
64  if (CurRec == 0)
65    CurRec = &CurMultiClass->Rec;
66
67  if (RecordVal *ERV = CurRec->getValue(RV.getName())) {
68    // The value already exists in the class, treat this as a set.
69    if (ERV->setValue(RV.getValue()))
70      return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
71                   RV.getType()->getAsString() + "' is incompatible with " +
72                   "previous definition of type '" +
73                   ERV->getType()->getAsString() + "'");
74  } else {
75    CurRec->addValue(RV);
76  }
77  return false;
78}
79
80/// SetValue -
81/// Return true on error, false on success.
82bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
83                        const std::vector<unsigned> &BitList, Init *V) {
84  if (!V) return false;
85
86  if (CurRec == 0) CurRec = &CurMultiClass->Rec;
87
88  RecordVal *RV = CurRec->getValue(ValName);
89  if (RV == 0)
90    return Error(Loc, "Value '" + ValName->getAsUnquotedString()
91                 + "' unknown!");
92
93  // Do not allow assignments like 'X = X'.  This will just cause infinite loops
94  // in the resolution machinery.
95  if (BitList.empty())
96    if (VarInit *VI = dynamic_cast<VarInit*>(V))
97      if (VI->getNameInit() == ValName)
98        return false;
99
100  // If we are assigning to a subset of the bits in the value... then we must be
101  // assigning to a field of BitsRecTy, which must have a BitsInit
102  // initializer.
103  //
104  if (!BitList.empty()) {
105    BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
106    if (CurVal == 0)
107      return Error(Loc, "Value '" + ValName->getAsUnquotedString()
108                   + "' is not a bits type");
109
110    // Convert the incoming value to a bits type of the appropriate size...
111    Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size()));
112    if (BI == 0) {
113      V->convertInitializerTo(BitsRecTy::get(BitList.size()));
114      return Error(Loc, "Initializer is not compatible with bit range");
115    }
116
117    // We should have a BitsInit type now.
118    BitsInit *BInit = dynamic_cast<BitsInit*>(BI);
119    assert(BInit != 0);
120
121    SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
122
123    // Loop over bits, assigning values as appropriate.
124    for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
125      unsigned Bit = BitList[i];
126      if (NewBits[Bit])
127        return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
128                     ValName->getAsUnquotedString() + "' more than once");
129      NewBits[Bit] = BInit->getBit(i);
130    }
131
132    for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
133      if (NewBits[i] == 0)
134        NewBits[i] = CurVal->getBit(i);
135
136    V = BitsInit::get(NewBits);
137  }
138
139  if (RV->setValue(V))
140    return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of type '"
141                 + RV->getType()->getAsString() +
142                 "' is incompatible with initializer '" + V->getAsString()
143                 + "'");
144  return false;
145}
146
147/// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
148/// args as SubClass's template arguments.
149bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
150  Record *SC = SubClass.Rec;
151  // Add all of the values in the subclass into the current class.
152  const std::vector<RecordVal> &Vals = SC->getValues();
153  for (unsigned i = 0, e = Vals.size(); i != e; ++i)
154    if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
155      return true;
156
157  const std::vector<Init *> &TArgs = SC->getTemplateArgs();
158
159  // Ensure that an appropriate number of template arguments are specified.
160  if (TArgs.size() < SubClass.TemplateArgs.size())
161    return Error(SubClass.RefLoc, "More template args specified than expected");
162
163  // Loop over all of the template arguments, setting them to the specified
164  // value or leaving them as the default if necessary.
165  for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
166    if (i < SubClass.TemplateArgs.size()) {
167      // If a value is specified for this template arg, set it now.
168      if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(),
169                   SubClass.TemplateArgs[i]))
170        return true;
171
172      // Resolve it next.
173      CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
174
175      // Now remove it.
176      CurRec->removeValue(TArgs[i]);
177
178    } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
179      return Error(SubClass.RefLoc,"Value not specified for template argument #"
180                   + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
181                   + ") of subclass '" + SC->getNameInitAsString() + "'!");
182    }
183  }
184
185  // Since everything went well, we can now set the "superclass" list for the
186  // current record.
187  const std::vector<Record*> &SCs = SC->getSuperClasses();
188  for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
189    if (CurRec->isSubClassOf(SCs[i]))
190      return Error(SubClass.RefLoc,
191                   "Already subclass of '" + SCs[i]->getName() + "'!\n");
192    CurRec->addSuperClass(SCs[i]);
193  }
194
195  if (CurRec->isSubClassOf(SC))
196    return Error(SubClass.RefLoc,
197                 "Already subclass of '" + SC->getName() + "'!\n");
198  CurRec->addSuperClass(SC);
199  return false;
200}
201
202/// AddSubMultiClass - Add SubMultiClass as a subclass to
203/// CurMC, resolving its template args as SubMultiClass's
204/// template arguments.
205bool TGParser::AddSubMultiClass(MultiClass *CurMC,
206                                SubMultiClassReference &SubMultiClass) {
207  MultiClass *SMC = SubMultiClass.MC;
208  Record *CurRec = &CurMC->Rec;
209
210  const std::vector<RecordVal> &MCVals = CurRec->getValues();
211
212  // Add all of the values in the subclass into the current class.
213  const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
214  for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
215    if (AddValue(CurRec, SubMultiClass.RefLoc, SMCVals[i]))
216      return true;
217
218  int newDefStart = CurMC->DefPrototypes.size();
219
220  // Add all of the defs in the subclass into the current multiclass.
221  for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
222         iend = SMC->DefPrototypes.end();
223       i != iend;
224       ++i) {
225    // Clone the def and add it to the current multiclass
226    Record *NewDef = new Record(**i);
227
228    // Add all of the values in the superclass into the current def.
229    for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
230      if (AddValue(NewDef, SubMultiClass.RefLoc, MCVals[i]))
231        return true;
232
233    CurMC->DefPrototypes.push_back(NewDef);
234  }
235
236  const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
237
238  // Ensure that an appropriate number of template arguments are
239  // specified.
240  if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
241    return Error(SubMultiClass.RefLoc,
242                 "More template args specified than expected");
243
244  // Loop over all of the template arguments, setting them to the specified
245  // value or leaving them as the default if necessary.
246  for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
247    if (i < SubMultiClass.TemplateArgs.size()) {
248      // If a value is specified for this template arg, set it in the
249      // superclass now.
250      if (SetValue(CurRec, SubMultiClass.RefLoc, SMCTArgs[i],
251                   std::vector<unsigned>(),
252                   SubMultiClass.TemplateArgs[i]))
253        return true;
254
255      // Resolve it next.
256      CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
257
258      // Now remove it.
259      CurRec->removeValue(SMCTArgs[i]);
260
261      // If a value is specified for this template arg, set it in the
262      // new defs now.
263      for (MultiClass::RecordVector::iterator j =
264             CurMC->DefPrototypes.begin() + newDefStart,
265             jend = CurMC->DefPrototypes.end();
266           j != jend;
267           ++j) {
268        Record *Def = *j;
269
270        if (SetValue(Def, SubMultiClass.RefLoc, SMCTArgs[i],
271                     std::vector<unsigned>(),
272                     SubMultiClass.TemplateArgs[i]))
273          return true;
274
275        // Resolve it next.
276        Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
277
278        // Now remove it
279        Def->removeValue(SMCTArgs[i]);
280      }
281    } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
282      return Error(SubMultiClass.RefLoc,
283                   "Value not specified for template argument #"
284                   + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
285                   + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
286    }
287  }
288
289  return false;
290}
291
292//===----------------------------------------------------------------------===//
293// Parser Code
294//===----------------------------------------------------------------------===//
295
296/// isObjectStart - Return true if this is a valid first token for an Object.
297static bool isObjectStart(tgtok::TokKind K) {
298  return K == tgtok::Class || K == tgtok::Def ||
299         K == tgtok::Defm || K == tgtok::Let || K == tgtok::MultiClass;
300}
301
302static std::string GetNewAnonymousName() {
303  static unsigned AnonCounter = 0;
304  return "anonymous."+utostr(AnonCounter++);
305}
306
307/// ParseObjectName - If an object name is specified, return it.  Otherwise,
308/// return an anonymous name.
309///   ObjectName ::= ID
310///   ObjectName ::= /*empty*/
311///
312std::string TGParser::ParseObjectName() {
313  if (Lex.getCode() != tgtok::Id)
314    return GetNewAnonymousName();
315
316  std::string Ret = Lex.getCurStrVal();
317  Lex.Lex();
318  return Ret;
319}
320
321
322/// ParseClassID - Parse and resolve a reference to a class name.  This returns
323/// null on error.
324///
325///    ClassID ::= ID
326///
327Record *TGParser::ParseClassID() {
328  if (Lex.getCode() != tgtok::Id) {
329    TokError("expected name for ClassID");
330    return 0;
331  }
332
333  Record *Result = Records.getClass(Lex.getCurStrVal());
334  if (Result == 0)
335    TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
336
337  Lex.Lex();
338  return Result;
339}
340
341/// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
342/// This returns null on error.
343///
344///    MultiClassID ::= ID
345///
346MultiClass *TGParser::ParseMultiClassID() {
347  if (Lex.getCode() != tgtok::Id) {
348    TokError("expected name for ClassID");
349    return 0;
350  }
351
352  MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
353  if (Result == 0)
354    TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
355
356  Lex.Lex();
357  return Result;
358}
359
360Record *TGParser::ParseDefmID() {
361  if (Lex.getCode() != tgtok::Id) {
362    TokError("expected multiclass name");
363    return 0;
364  }
365
366  MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
367  if (MC == 0) {
368    TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
369    return 0;
370  }
371
372  Lex.Lex();
373  return &MC->Rec;
374}
375
376
377/// ParseSubClassReference - Parse a reference to a subclass or to a templated
378/// subclass.  This returns a SubClassRefTy with a null Record* on error.
379///
380///  SubClassRef ::= ClassID
381///  SubClassRef ::= ClassID '<' ValueList '>'
382///
383SubClassReference TGParser::
384ParseSubClassReference(Record *CurRec, bool isDefm) {
385  SubClassReference Result;
386  Result.RefLoc = Lex.getLoc();
387
388  if (isDefm)
389    Result.Rec = ParseDefmID();
390  else
391    Result.Rec = ParseClassID();
392  if (Result.Rec == 0) return Result;
393
394  // If there is no template arg list, we're done.
395  if (Lex.getCode() != tgtok::less)
396    return Result;
397  Lex.Lex();  // Eat the '<'
398
399  if (Lex.getCode() == tgtok::greater) {
400    TokError("subclass reference requires a non-empty list of template values");
401    Result.Rec = 0;
402    return Result;
403  }
404
405  Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
406  if (Result.TemplateArgs.empty()) {
407    Result.Rec = 0;   // Error parsing value list.
408    return Result;
409  }
410
411  if (Lex.getCode() != tgtok::greater) {
412    TokError("expected '>' in template value list");
413    Result.Rec = 0;
414    return Result;
415  }
416  Lex.Lex();
417
418  return Result;
419}
420
421/// ParseSubMultiClassReference - Parse a reference to a subclass or to a
422/// templated submulticlass.  This returns a SubMultiClassRefTy with a null
423/// Record* on error.
424///
425///  SubMultiClassRef ::= MultiClassID
426///  SubMultiClassRef ::= MultiClassID '<' ValueList '>'
427///
428SubMultiClassReference TGParser::
429ParseSubMultiClassReference(MultiClass *CurMC) {
430  SubMultiClassReference Result;
431  Result.RefLoc = Lex.getLoc();
432
433  Result.MC = ParseMultiClassID();
434  if (Result.MC == 0) return Result;
435
436  // If there is no template arg list, we're done.
437  if (Lex.getCode() != tgtok::less)
438    return Result;
439  Lex.Lex();  // Eat the '<'
440
441  if (Lex.getCode() == tgtok::greater) {
442    TokError("subclass reference requires a non-empty list of template values");
443    Result.MC = 0;
444    return Result;
445  }
446
447  Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
448  if (Result.TemplateArgs.empty()) {
449    Result.MC = 0;   // Error parsing value list.
450    return Result;
451  }
452
453  if (Lex.getCode() != tgtok::greater) {
454    TokError("expected '>' in template value list");
455    Result.MC = 0;
456    return Result;
457  }
458  Lex.Lex();
459
460  return Result;
461}
462
463/// ParseRangePiece - Parse a bit/value range.
464///   RangePiece ::= INTVAL
465///   RangePiece ::= INTVAL '-' INTVAL
466///   RangePiece ::= INTVAL INTVAL
467bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
468  if (Lex.getCode() != tgtok::IntVal) {
469    TokError("expected integer or bitrange");
470    return true;
471  }
472  int64_t Start = Lex.getCurIntVal();
473  int64_t End;
474
475  if (Start < 0)
476    return TokError("invalid range, cannot be negative");
477
478  switch (Lex.Lex()) {  // eat first character.
479  default:
480    Ranges.push_back(Start);
481    return false;
482  case tgtok::minus:
483    if (Lex.Lex() != tgtok::IntVal) {
484      TokError("expected integer value as end of range");
485      return true;
486    }
487    End = Lex.getCurIntVal();
488    break;
489  case tgtok::IntVal:
490    End = -Lex.getCurIntVal();
491    break;
492  }
493  if (End < 0)
494    return TokError("invalid range, cannot be negative");
495  Lex.Lex();
496
497  // Add to the range.
498  if (Start < End) {
499    for (; Start <= End; ++Start)
500      Ranges.push_back(Start);
501  } else {
502    for (; Start >= End; --Start)
503      Ranges.push_back(Start);
504  }
505  return false;
506}
507
508/// ParseRangeList - Parse a list of scalars and ranges into scalar values.
509///
510///   RangeList ::= RangePiece (',' RangePiece)*
511///
512std::vector<unsigned> TGParser::ParseRangeList() {
513  std::vector<unsigned> Result;
514
515  // Parse the first piece.
516  if (ParseRangePiece(Result))
517    return std::vector<unsigned>();
518  while (Lex.getCode() == tgtok::comma) {
519    Lex.Lex();  // Eat the comma.
520
521    // Parse the next range piece.
522    if (ParseRangePiece(Result))
523      return std::vector<unsigned>();
524  }
525  return Result;
526}
527
528/// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
529///   OptionalRangeList ::= '<' RangeList '>'
530///   OptionalRangeList ::= /*empty*/
531bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
532  if (Lex.getCode() != tgtok::less)
533    return false;
534
535  SMLoc StartLoc = Lex.getLoc();
536  Lex.Lex(); // eat the '<'
537
538  // Parse the range list.
539  Ranges = ParseRangeList();
540  if (Ranges.empty()) return true;
541
542  if (Lex.getCode() != tgtok::greater) {
543    TokError("expected '>' at end of range list");
544    return Error(StartLoc, "to match this '<'");
545  }
546  Lex.Lex();   // eat the '>'.
547  return false;
548}
549
550/// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
551///   OptionalBitList ::= '{' RangeList '}'
552///   OptionalBitList ::= /*empty*/
553bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
554  if (Lex.getCode() != tgtok::l_brace)
555    return false;
556
557  SMLoc StartLoc = Lex.getLoc();
558  Lex.Lex(); // eat the '{'
559
560  // Parse the range list.
561  Ranges = ParseRangeList();
562  if (Ranges.empty()) return true;
563
564  if (Lex.getCode() != tgtok::r_brace) {
565    TokError("expected '}' at end of bit list");
566    return Error(StartLoc, "to match this '{'");
567  }
568  Lex.Lex();   // eat the '}'.
569  return false;
570}
571
572
573/// ParseType - Parse and return a tblgen type.  This returns null on error.
574///
575///   Type ::= STRING                       // string type
576///   Type ::= BIT                          // bit type
577///   Type ::= BITS '<' INTVAL '>'          // bits<x> type
578///   Type ::= INT                          // int type
579///   Type ::= LIST '<' Type '>'            // list<x> type
580///   Type ::= CODE                         // code type
581///   Type ::= DAG                          // dag type
582///   Type ::= ClassID                      // Record Type
583///
584RecTy *TGParser::ParseType() {
585  switch (Lex.getCode()) {
586  default: TokError("Unknown token when expecting a type"); return 0;
587  case tgtok::String: Lex.Lex(); return StringRecTy::get();
588  case tgtok::Bit:    Lex.Lex(); return BitRecTy::get();
589  case tgtok::Int:    Lex.Lex(); return IntRecTy::get();
590  case tgtok::Code:   Lex.Lex(); return CodeRecTy::get();
591  case tgtok::Dag:    Lex.Lex(); return DagRecTy::get();
592  case tgtok::Id:
593    if (Record *R = ParseClassID()) return RecordRecTy::get(R);
594    return 0;
595  case tgtok::Bits: {
596    if (Lex.Lex() != tgtok::less) { // Eat 'bits'
597      TokError("expected '<' after bits type");
598      return 0;
599    }
600    if (Lex.Lex() != tgtok::IntVal) {  // Eat '<'
601      TokError("expected integer in bits<n> type");
602      return 0;
603    }
604    uint64_t Val = Lex.getCurIntVal();
605    if (Lex.Lex() != tgtok::greater) {  // Eat count.
606      TokError("expected '>' at end of bits<n> type");
607      return 0;
608    }
609    Lex.Lex();  // Eat '>'
610    return BitsRecTy::get(Val);
611  }
612  case tgtok::List: {
613    if (Lex.Lex() != tgtok::less) { // Eat 'bits'
614      TokError("expected '<' after list type");
615      return 0;
616    }
617    Lex.Lex();  // Eat '<'
618    RecTy *SubType = ParseType();
619    if (SubType == 0) return 0;
620
621    if (Lex.getCode() != tgtok::greater) {
622      TokError("expected '>' at end of list<ty> type");
623      return 0;
624    }
625    Lex.Lex();  // Eat '>'
626    return ListRecTy::get(SubType);
627  }
628  }
629}
630
631/// ParseIDValue - Parse an ID as a value and decode what it means.
632///
633///  IDValue ::= ID [def local value]
634///  IDValue ::= ID [def template arg]
635///  IDValue ::= ID [multiclass local value]
636///  IDValue ::= ID [multiclass template argument]
637///  IDValue ::= ID [def name]
638///
639Init *TGParser::ParseIDValue(Record *CurRec, IDParseMode Mode) {
640  assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
641  std::string Name = Lex.getCurStrVal();
642  SMLoc Loc = Lex.getLoc();
643  Lex.Lex();
644  return ParseIDValue(CurRec, Name, Loc);
645}
646
647/// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
648/// has already been read.
649Init *TGParser::ParseIDValue(Record *CurRec,
650                             const std::string &Name, SMLoc NameLoc,
651                             IDParseMode Mode) {
652  if (CurRec) {
653    if (const RecordVal *RV = CurRec->getValue(Name))
654      return VarInit::get(Name, RV->getType());
655
656    Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
657
658    if (CurMultiClass)
659      TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
660                                    "::");
661
662    if (CurRec->isTemplateArg(TemplateArgName)) {
663      const RecordVal *RV = CurRec->getValue(TemplateArgName);
664      assert(RV && "Template arg doesn't exist??");
665      return VarInit::get(TemplateArgName, RV->getType());
666    }
667  }
668
669  if (CurMultiClass) {
670    Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
671                               "::");
672
673    if (CurMultiClass->Rec.isTemplateArg(MCName)) {
674      const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
675      assert(RV && "Template arg doesn't exist??");
676      return VarInit::get(MCName, RV->getType());
677    }
678  }
679
680  if (Mode == ParseNameMode)
681    return StringInit::get(Name);
682
683  if (Record *D = Records.getDef(Name))
684    return DefInit::get(D);
685
686  if (Mode == ParseValueMode) {
687    Error(NameLoc, "Variable not defined: '" + Name + "'");
688    return 0;
689  }
690
691  return StringInit::get(Name);
692}
693
694/// ParseOperation - Parse an operator.  This returns null on error.
695///
696/// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
697///
698Init *TGParser::ParseOperation(Record *CurRec) {
699  switch (Lex.getCode()) {
700  default:
701    TokError("unknown operation");
702    return 0;
703    break;
704  case tgtok::XHead:
705  case tgtok::XTail:
706  case tgtok::XEmpty:
707  case tgtok::XCast: {  // Value ::= !unop '(' Value ')'
708    UnOpInit::UnaryOp Code;
709    RecTy *Type = 0;
710
711    switch (Lex.getCode()) {
712    default: assert(0 && "Unhandled code!");
713    case tgtok::XCast:
714      Lex.Lex();  // eat the operation
715      Code = UnOpInit::CAST;
716
717      Type = ParseOperatorType();
718
719      if (Type == 0) {
720        TokError("did not get type for unary operator");
721        return 0;
722      }
723
724      break;
725    case tgtok::XHead:
726      Lex.Lex();  // eat the operation
727      Code = UnOpInit::HEAD;
728      break;
729    case tgtok::XTail:
730      Lex.Lex();  // eat the operation
731      Code = UnOpInit::TAIL;
732      break;
733    case tgtok::XEmpty:
734      Lex.Lex();  // eat the operation
735      Code = UnOpInit::EMPTY;
736      Type = IntRecTy::get();
737      break;
738    }
739    if (Lex.getCode() != tgtok::l_paren) {
740      TokError("expected '(' after unary operator");
741      return 0;
742    }
743    Lex.Lex();  // eat the '('
744
745    Init *LHS = ParseValue(CurRec);
746    if (LHS == 0) return 0;
747
748    if (Code == UnOpInit::HEAD
749        || Code == UnOpInit::TAIL
750        || Code == UnOpInit::EMPTY) {
751      ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
752      StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
753      TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
754      if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
755        TokError("expected list or string type argument in unary operator");
756        return 0;
757      }
758      if (LHSt) {
759        ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
760        StringRecTy *SType = dynamic_cast<StringRecTy*>(LHSt->getType());
761        if (LType == 0 && SType == 0) {
762          TokError("expected list or string type argumnet in unary operator");
763          return 0;
764        }
765      }
766
767      if (Code == UnOpInit::HEAD
768          || Code == UnOpInit::TAIL) {
769        if (LHSl == 0 && LHSt == 0) {
770          TokError("expected list type argumnet in unary operator");
771          return 0;
772        }
773
774        if (LHSl && LHSl->getSize() == 0) {
775          TokError("empty list argument in unary operator");
776          return 0;
777        }
778        if (LHSl) {
779          Init *Item = LHSl->getElement(0);
780          TypedInit *Itemt = dynamic_cast<TypedInit*>(Item);
781          if (Itemt == 0) {
782            TokError("untyped list element in unary operator");
783            return 0;
784          }
785          if (Code == UnOpInit::HEAD) {
786            Type = Itemt->getType();
787          } else {
788            Type = ListRecTy::get(Itemt->getType());
789          }
790        } else {
791          assert(LHSt && "expected list type argument in unary operator");
792          ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
793          if (LType == 0) {
794            TokError("expected list type argumnet in unary operator");
795            return 0;
796          }
797          if (Code == UnOpInit::HEAD) {
798            Type = LType->getElementType();
799          } else {
800            Type = LType;
801          }
802        }
803      }
804    }
805
806    if (Lex.getCode() != tgtok::r_paren) {
807      TokError("expected ')' in unary operator");
808      return 0;
809    }
810    Lex.Lex();  // eat the ')'
811    return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
812  }
813
814  case tgtok::XConcat:
815  case tgtok::XSRA:
816  case tgtok::XSRL:
817  case tgtok::XSHL:
818  case tgtok::XEq:
819  case tgtok::XStrConcat: {  // Value ::= !binop '(' Value ',' Value ')'
820    tgtok::TokKind OpTok = Lex.getCode();
821    SMLoc OpLoc = Lex.getLoc();
822    Lex.Lex();  // eat the operation
823
824    BinOpInit::BinaryOp Code;
825    RecTy *Type = 0;
826
827    switch (OpTok) {
828    default: assert(0 && "Unhandled code!");
829    case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
830    case tgtok::XSRA:    Code = BinOpInit::SRA;   Type = IntRecTy::get(); break;
831    case tgtok::XSRL:    Code = BinOpInit::SRL;   Type = IntRecTy::get(); break;
832    case tgtok::XSHL:    Code = BinOpInit::SHL;   Type = IntRecTy::get(); break;
833    case tgtok::XEq:     Code = BinOpInit::EQ;    Type = BitRecTy::get(); break;
834    case tgtok::XStrConcat:
835      Code = BinOpInit::STRCONCAT;
836      Type = StringRecTy::get();
837      break;
838    }
839
840    if (Lex.getCode() != tgtok::l_paren) {
841      TokError("expected '(' after binary operator");
842      return 0;
843    }
844    Lex.Lex();  // eat the '('
845
846    SmallVector<Init*, 2> InitList;
847
848    InitList.push_back(ParseValue(CurRec));
849    if (InitList.back() == 0) return 0;
850
851    while (Lex.getCode() == tgtok::comma) {
852      Lex.Lex();  // eat the ','
853
854      InitList.push_back(ParseValue(CurRec));
855      if (InitList.back() == 0) return 0;
856    }
857
858    if (Lex.getCode() != tgtok::r_paren) {
859      TokError("expected ')' in operator");
860      return 0;
861    }
862    Lex.Lex();  // eat the ')'
863
864    // We allow multiple operands to associative operators like !strconcat as
865    // shorthand for nesting them.
866    if (Code == BinOpInit::STRCONCAT) {
867      while (InitList.size() > 2) {
868        Init *RHS = InitList.pop_back_val();
869        RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
870                           ->Fold(CurRec, CurMultiClass);
871        InitList.back() = RHS;
872      }
873    }
874
875    if (InitList.size() == 2)
876      return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
877        ->Fold(CurRec, CurMultiClass);
878
879    Error(OpLoc, "expected two operands to operator");
880    return 0;
881  }
882
883  case tgtok::XIf:
884  case tgtok::XForEach:
885  case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
886    TernOpInit::TernaryOp Code;
887    RecTy *Type = 0;
888
889    tgtok::TokKind LexCode = Lex.getCode();
890    Lex.Lex();  // eat the operation
891    switch (LexCode) {
892    default: assert(0 && "Unhandled code!");
893    case tgtok::XIf:
894      Code = TernOpInit::IF;
895      break;
896    case tgtok::XForEach:
897      Code = TernOpInit::FOREACH;
898      break;
899    case tgtok::XSubst:
900      Code = TernOpInit::SUBST;
901      break;
902    }
903    if (Lex.getCode() != tgtok::l_paren) {
904      TokError("expected '(' after ternary operator");
905      return 0;
906    }
907    Lex.Lex();  // eat the '('
908
909    Init *LHS = ParseValue(CurRec);
910    if (LHS == 0) return 0;
911
912    if (Lex.getCode() != tgtok::comma) {
913      TokError("expected ',' in ternary operator");
914      return 0;
915    }
916    Lex.Lex();  // eat the ','
917
918    Init *MHS = ParseValue(CurRec);
919    if (MHS == 0) return 0;
920
921    if (Lex.getCode() != tgtok::comma) {
922      TokError("expected ',' in ternary operator");
923      return 0;
924    }
925    Lex.Lex();  // eat the ','
926
927    Init *RHS = ParseValue(CurRec);
928    if (RHS == 0) return 0;
929
930    if (Lex.getCode() != tgtok::r_paren) {
931      TokError("expected ')' in binary operator");
932      return 0;
933    }
934    Lex.Lex();  // eat the ')'
935
936    switch (LexCode) {
937    default: assert(0 && "Unhandled code!");
938    case tgtok::XIf: {
939      // FIXME: The `!if' operator doesn't handle non-TypedInit well at
940      // all. This can be made much more robust.
941      TypedInit *MHSt = dynamic_cast<TypedInit*>(MHS);
942      TypedInit *RHSt = dynamic_cast<TypedInit*>(RHS);
943
944      RecTy *MHSTy = 0;
945      RecTy *RHSTy = 0;
946
947      if (MHSt == 0 && RHSt == 0) {
948        BitsInit *MHSbits = dynamic_cast<BitsInit*>(MHS);
949        BitsInit *RHSbits = dynamic_cast<BitsInit*>(RHS);
950
951        if (MHSbits && RHSbits &&
952            MHSbits->getNumBits() == RHSbits->getNumBits()) {
953          Type = BitRecTy::get();
954          break;
955        } else {
956          BitInit *MHSbit = dynamic_cast<BitInit*>(MHS);
957          BitInit *RHSbit = dynamic_cast<BitInit*>(RHS);
958
959          if (MHSbit && RHSbit) {
960            Type = BitRecTy::get();
961            break;
962          }
963        }
964      } else if (MHSt != 0 && RHSt != 0) {
965        MHSTy = MHSt->getType();
966        RHSTy = RHSt->getType();
967      }
968
969      if (!MHSTy || !RHSTy) {
970        TokError("could not get type for !if");
971        return 0;
972      }
973
974      if (MHSTy->typeIsConvertibleTo(RHSTy)) {
975        Type = RHSTy;
976      } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
977        Type = MHSTy;
978      } else {
979        TokError("inconsistent types for !if");
980        return 0;
981      }
982      break;
983    }
984    case tgtok::XForEach: {
985      TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
986      if (MHSt == 0) {
987        TokError("could not get type for !foreach");
988        return 0;
989      }
990      Type = MHSt->getType();
991      break;
992    }
993    case tgtok::XSubst: {
994      TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
995      if (RHSt == 0) {
996        TokError("could not get type for !subst");
997        return 0;
998      }
999      Type = RHSt->getType();
1000      break;
1001    }
1002    }
1003    return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1004                                                             CurMultiClass);
1005  }
1006  }
1007  TokError("could not parse operation");
1008  return 0;
1009}
1010
1011/// ParseOperatorType - Parse a type for an operator.  This returns
1012/// null on error.
1013///
1014/// OperatorType ::= '<' Type '>'
1015///
1016RecTy *TGParser::ParseOperatorType() {
1017  RecTy *Type = 0;
1018
1019  if (Lex.getCode() != tgtok::less) {
1020    TokError("expected type name for operator");
1021    return 0;
1022  }
1023  Lex.Lex();  // eat the <
1024
1025  Type = ParseType();
1026
1027  if (Type == 0) {
1028    TokError("expected type name for operator");
1029    return 0;
1030  }
1031
1032  if (Lex.getCode() != tgtok::greater) {
1033    TokError("expected type name for operator");
1034    return 0;
1035  }
1036  Lex.Lex();  // eat the >
1037
1038  return Type;
1039}
1040
1041
1042/// ParseSimpleValue - Parse a tblgen value.  This returns null on error.
1043///
1044///   SimpleValue ::= IDValue
1045///   SimpleValue ::= INTVAL
1046///   SimpleValue ::= STRVAL+
1047///   SimpleValue ::= CODEFRAGMENT
1048///   SimpleValue ::= '?'
1049///   SimpleValue ::= '{' ValueList '}'
1050///   SimpleValue ::= ID '<' ValueListNE '>'
1051///   SimpleValue ::= '[' ValueList ']'
1052///   SimpleValue ::= '(' IDValue DagArgList ')'
1053///   SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1054///   SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1055///   SimpleValue ::= SRATOK '(' Value ',' Value ')'
1056///   SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1057///   SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1058///
1059Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1060                                 IDParseMode Mode) {
1061  Init *R = 0;
1062  switch (Lex.getCode()) {
1063  default: TokError("Unknown token when parsing a value"); break;
1064  case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1065  case tgtok::StrVal: {
1066    std::string Val = Lex.getCurStrVal();
1067    Lex.Lex();
1068
1069    // Handle multiple consecutive concatenated strings.
1070    while (Lex.getCode() == tgtok::StrVal) {
1071      Val += Lex.getCurStrVal();
1072      Lex.Lex();
1073    }
1074
1075    R = StringInit::get(Val);
1076    break;
1077  }
1078  case tgtok::CodeFragment:
1079    R = CodeInit::get(Lex.getCurStrVal());
1080    Lex.Lex();
1081    break;
1082  case tgtok::question:
1083    R = UnsetInit::get();
1084    Lex.Lex();
1085    break;
1086  case tgtok::Id: {
1087    SMLoc NameLoc = Lex.getLoc();
1088    std::string Name = Lex.getCurStrVal();
1089    if (Lex.Lex() != tgtok::less)  // consume the Id.
1090      return ParseIDValue(CurRec, Name, NameLoc, Mode);    // Value ::= IDValue
1091
1092    // Value ::= ID '<' ValueListNE '>'
1093    if (Lex.Lex() == tgtok::greater) {
1094      TokError("expected non-empty value list");
1095      return 0;
1096    }
1097
1098    // This is a CLASS<initvalslist> expression.  This is supposed to synthesize
1099    // a new anonymous definition, deriving from CLASS<initvalslist> with no
1100    // body.
1101    Record *Class = Records.getClass(Name);
1102    if (!Class) {
1103      Error(NameLoc, "Expected a class name, got '" + Name + "'");
1104      return 0;
1105    }
1106
1107    std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1108    if (ValueList.empty()) return 0;
1109
1110    if (Lex.getCode() != tgtok::greater) {
1111      TokError("expected '>' at end of value list");
1112      return 0;
1113    }
1114    Lex.Lex();  // eat the '>'
1115
1116    // Create the new record, set it as CurRec temporarily.
1117    static unsigned AnonCounter = 0;
1118    Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),
1119                                NameLoc,
1120                                Records);
1121    SubClassReference SCRef;
1122    SCRef.RefLoc = NameLoc;
1123    SCRef.Rec = Class;
1124    SCRef.TemplateArgs = ValueList;
1125    // Add info about the subclass to NewRec.
1126    if (AddSubClass(NewRec, SCRef))
1127      return 0;
1128    NewRec->resolveReferences();
1129    Records.addDef(NewRec);
1130
1131    // The result of the expression is a reference to the new record.
1132    return DefInit::get(NewRec);
1133  }
1134  case tgtok::l_brace: {           // Value ::= '{' ValueList '}'
1135    SMLoc BraceLoc = Lex.getLoc();
1136    Lex.Lex(); // eat the '{'
1137    std::vector<Init*> Vals;
1138
1139    if (Lex.getCode() != tgtok::r_brace) {
1140      Vals = ParseValueList(CurRec);
1141      if (Vals.empty()) return 0;
1142    }
1143    if (Lex.getCode() != tgtok::r_brace) {
1144      TokError("expected '}' at end of bit list value");
1145      return 0;
1146    }
1147    Lex.Lex();  // eat the '}'
1148
1149    SmallVector<Init *, 16> NewBits(Vals.size());
1150
1151    for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1152      Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1153      if (Bit == 0) {
1154        Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1155              ") is not convertable to a bit");
1156        return 0;
1157      }
1158      NewBits[Vals.size()-i-1] = Bit;
1159    }
1160    return BitsInit::get(NewBits);
1161  }
1162  case tgtok::l_square: {          // Value ::= '[' ValueList ']'
1163    Lex.Lex(); // eat the '['
1164    std::vector<Init*> Vals;
1165
1166    RecTy *DeducedEltTy = 0;
1167    ListRecTy *GivenListTy = 0;
1168
1169    if (ItemType != 0) {
1170      ListRecTy *ListType = dynamic_cast<ListRecTy*>(ItemType);
1171      if (ListType == 0) {
1172        std::stringstream s;
1173        s << "Type mismatch for list, expected list type, got "
1174          << ItemType->getAsString();
1175        TokError(s.str());
1176        return 0;
1177      }
1178      GivenListTy = ListType;
1179    }
1180
1181    if (Lex.getCode() != tgtok::r_square) {
1182      Vals = ParseValueList(CurRec, 0,
1183                            GivenListTy ? GivenListTy->getElementType() : 0);
1184      if (Vals.empty()) return 0;
1185    }
1186    if (Lex.getCode() != tgtok::r_square) {
1187      TokError("expected ']' at end of list value");
1188      return 0;
1189    }
1190    Lex.Lex();  // eat the ']'
1191
1192    RecTy *GivenEltTy = 0;
1193    if (Lex.getCode() == tgtok::less) {
1194      // Optional list element type
1195      Lex.Lex();  // eat the '<'
1196
1197      GivenEltTy = ParseType();
1198      if (GivenEltTy == 0) {
1199        // Couldn't parse element type
1200        return 0;
1201      }
1202
1203      if (Lex.getCode() != tgtok::greater) {
1204        TokError("expected '>' at end of list element type");
1205        return 0;
1206      }
1207      Lex.Lex();  // eat the '>'
1208    }
1209
1210    // Check elements
1211    RecTy *EltTy = 0;
1212    for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1213         i != ie;
1214         ++i) {
1215      TypedInit *TArg = dynamic_cast<TypedInit*>(*i);
1216      if (TArg == 0) {
1217        TokError("Untyped list element");
1218        return 0;
1219      }
1220      if (EltTy != 0) {
1221        EltTy = resolveTypes(EltTy, TArg->getType());
1222        if (EltTy == 0) {
1223          TokError("Incompatible types in list elements");
1224          return 0;
1225        }
1226      } else {
1227        EltTy = TArg->getType();
1228      }
1229    }
1230
1231    if (GivenEltTy != 0) {
1232      if (EltTy != 0) {
1233        // Verify consistency
1234        if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1235          TokError("Incompatible types in list elements");
1236          return 0;
1237        }
1238      }
1239      EltTy = GivenEltTy;
1240    }
1241
1242    if (EltTy == 0) {
1243      if (ItemType == 0) {
1244        TokError("No type for list");
1245        return 0;
1246      }
1247      DeducedEltTy = GivenListTy->getElementType();
1248    } else {
1249      // Make sure the deduced type is compatible with the given type
1250      if (GivenListTy) {
1251        if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1252          TokError("Element type mismatch for list");
1253          return 0;
1254        }
1255      }
1256      DeducedEltTy = EltTy;
1257    }
1258
1259    return ListInit::get(Vals, DeducedEltTy);
1260  }
1261  case tgtok::l_paren: {         // Value ::= '(' IDValue DagArgList ')'
1262    Lex.Lex();   // eat the '('
1263    if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1264      TokError("expected identifier in dag init");
1265      return 0;
1266    }
1267
1268    Init *Operator = ParseValue(CurRec);
1269    if (Operator == 0) return 0;
1270
1271    // If the operator name is present, parse it.
1272    std::string OperatorName;
1273    if (Lex.getCode() == tgtok::colon) {
1274      if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1275        TokError("expected variable name in dag operator");
1276        return 0;
1277      }
1278      OperatorName = Lex.getCurStrVal();
1279      Lex.Lex();  // eat the VarName.
1280    }
1281
1282    std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1283    if (Lex.getCode() != tgtok::r_paren) {
1284      DagArgs = ParseDagArgList(CurRec);
1285      if (DagArgs.empty()) return 0;
1286    }
1287
1288    if (Lex.getCode() != tgtok::r_paren) {
1289      TokError("expected ')' in dag init");
1290      return 0;
1291    }
1292    Lex.Lex();  // eat the ')'
1293
1294    return DagInit::get(Operator, OperatorName, DagArgs);
1295  }
1296
1297  case tgtok::XHead:
1298  case tgtok::XTail:
1299  case tgtok::XEmpty:
1300  case tgtok::XCast:  // Value ::= !unop '(' Value ')'
1301  case tgtok::XConcat:
1302  case tgtok::XSRA:
1303  case tgtok::XSRL:
1304  case tgtok::XSHL:
1305  case tgtok::XEq:
1306  case tgtok::XStrConcat:   // Value ::= !binop '(' Value ',' Value ')'
1307  case tgtok::XIf:
1308  case tgtok::XForEach:
1309  case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1310    return ParseOperation(CurRec);
1311  }
1312  }
1313
1314  return R;
1315}
1316
1317/// ParseValue - Parse a tblgen value.  This returns null on error.
1318///
1319///   Value       ::= SimpleValue ValueSuffix*
1320///   ValueSuffix ::= '{' BitList '}'
1321///   ValueSuffix ::= '[' BitList ']'
1322///   ValueSuffix ::= '.' ID
1323///
1324Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1325  Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1326  if (Result == 0) return 0;
1327
1328  // Parse the suffixes now if present.
1329  while (1) {
1330    switch (Lex.getCode()) {
1331    default: return Result;
1332    case tgtok::l_brace: {
1333      if (Mode == ParseNameMode)
1334        // This is the beginning of the object body.
1335        return Result;
1336
1337      SMLoc CurlyLoc = Lex.getLoc();
1338      Lex.Lex(); // eat the '{'
1339      std::vector<unsigned> Ranges = ParseRangeList();
1340      if (Ranges.empty()) return 0;
1341
1342      // Reverse the bitlist.
1343      std::reverse(Ranges.begin(), Ranges.end());
1344      Result = Result->convertInitializerBitRange(Ranges);
1345      if (Result == 0) {
1346        Error(CurlyLoc, "Invalid bit range for value");
1347        return 0;
1348      }
1349
1350      // Eat the '}'.
1351      if (Lex.getCode() != tgtok::r_brace) {
1352        TokError("expected '}' at end of bit range list");
1353        return 0;
1354      }
1355      Lex.Lex();
1356      break;
1357    }
1358    case tgtok::l_square: {
1359      SMLoc SquareLoc = Lex.getLoc();
1360      Lex.Lex(); // eat the '['
1361      std::vector<unsigned> Ranges = ParseRangeList();
1362      if (Ranges.empty()) return 0;
1363
1364      Result = Result->convertInitListSlice(Ranges);
1365      if (Result == 0) {
1366        Error(SquareLoc, "Invalid range for list slice");
1367        return 0;
1368      }
1369
1370      // Eat the ']'.
1371      if (Lex.getCode() != tgtok::r_square) {
1372        TokError("expected ']' at end of list slice");
1373        return 0;
1374      }
1375      Lex.Lex();
1376      break;
1377    }
1378    case tgtok::period:
1379      if (Lex.Lex() != tgtok::Id) {  // eat the .
1380        TokError("expected field identifier after '.'");
1381        return 0;
1382      }
1383      if (!Result->getFieldType(Lex.getCurStrVal())) {
1384        TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1385                 Result->getAsString() + "'");
1386        return 0;
1387      }
1388      Result = FieldInit::get(Result, Lex.getCurStrVal());
1389      Lex.Lex();  // eat field name
1390      break;
1391    }
1392  }
1393}
1394
1395/// ParseDagArgList - Parse the argument list for a dag literal expression.
1396///
1397///    ParseDagArgList ::= Value (':' VARNAME)?
1398///    ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1399std::vector<std::pair<llvm::Init*, std::string> >
1400TGParser::ParseDagArgList(Record *CurRec) {
1401  std::vector<std::pair<llvm::Init*, std::string> > Result;
1402
1403  while (1) {
1404    Init *Val = ParseValue(CurRec);
1405    if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1406
1407    // If the variable name is present, add it.
1408    std::string VarName;
1409    if (Lex.getCode() == tgtok::colon) {
1410      if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1411        TokError("expected variable name in dag literal");
1412        return std::vector<std::pair<llvm::Init*, std::string> >();
1413      }
1414      VarName = Lex.getCurStrVal();
1415      Lex.Lex();  // eat the VarName.
1416    }
1417
1418    Result.push_back(std::make_pair(Val, VarName));
1419
1420    if (Lex.getCode() != tgtok::comma) break;
1421    Lex.Lex(); // eat the ','
1422  }
1423
1424  return Result;
1425}
1426
1427
1428/// ParseValueList - Parse a comma separated list of values, returning them as a
1429/// vector.  Note that this always expects to be able to parse at least one
1430/// value.  It returns an empty list if this is not possible.
1431///
1432///   ValueList ::= Value (',' Value)
1433///
1434std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1435                                            RecTy *EltTy) {
1436  std::vector<Init*> Result;
1437  RecTy *ItemType = EltTy;
1438  unsigned int ArgN = 0;
1439  if (ArgsRec != 0 && EltTy == 0) {
1440    const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1441    const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1442    if (!RV) {
1443      errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1444        << ")\n";
1445    }
1446    assert(RV && "Template argument record not found??");
1447    ItemType = RV->getType();
1448    ++ArgN;
1449  }
1450  Result.push_back(ParseValue(CurRec, ItemType));
1451  if (Result.back() == 0) return std::vector<Init*>();
1452
1453  while (Lex.getCode() == tgtok::comma) {
1454    Lex.Lex();  // Eat the comma
1455
1456    if (ArgsRec != 0 && EltTy == 0) {
1457      const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1458      if (ArgN >= TArgs.size()) {
1459        TokError("too many template arguments");
1460        return std::vector<Init*>();
1461      }
1462      const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1463      assert(RV && "Template argument record not found??");
1464      ItemType = RV->getType();
1465      ++ArgN;
1466    }
1467    Result.push_back(ParseValue(CurRec, ItemType));
1468    if (Result.back() == 0) return std::vector<Init*>();
1469  }
1470
1471  return Result;
1472}
1473
1474
1475/// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1476/// empty string on error.  This can happen in a number of different context's,
1477/// including within a def or in the template args for a def (which which case
1478/// CurRec will be non-null) and within the template args for a multiclass (in
1479/// which case CurRec will be null, but CurMultiClass will be set).  This can
1480/// also happen within a def that is within a multiclass, which will set both
1481/// CurRec and CurMultiClass.
1482///
1483///  Declaration ::= FIELD? Type ID ('=' Value)?
1484///
1485Init *TGParser::ParseDeclaration(Record *CurRec,
1486                                       bool ParsingTemplateArgs) {
1487  // Read the field prefix if present.
1488  bool HasField = Lex.getCode() == tgtok::Field;
1489  if (HasField) Lex.Lex();
1490
1491  RecTy *Type = ParseType();
1492  if (Type == 0) return 0;
1493
1494  if (Lex.getCode() != tgtok::Id) {
1495    TokError("Expected identifier in declaration");
1496    return 0;
1497  }
1498
1499  SMLoc IdLoc = Lex.getLoc();
1500  Init *DeclName = StringInit::get(Lex.getCurStrVal());
1501  Lex.Lex();
1502
1503  if (ParsingTemplateArgs) {
1504    if (CurRec) {
1505      DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1506    } else {
1507      assert(CurMultiClass);
1508    }
1509    if (CurMultiClass)
1510      DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1511                             "::");
1512  }
1513
1514  // Add the value.
1515  if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1516    return 0;
1517
1518  // If a value is present, parse it.
1519  if (Lex.getCode() == tgtok::equal) {
1520    Lex.Lex();
1521    SMLoc ValLoc = Lex.getLoc();
1522    Init *Val = ParseValue(CurRec, Type);
1523    if (Val == 0 ||
1524        SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1525      return 0;
1526  }
1527
1528  return DeclName;
1529}
1530
1531/// ParseTemplateArgList - Read a template argument list, which is a non-empty
1532/// sequence of template-declarations in <>'s.  If CurRec is non-null, these are
1533/// template args for a def, which may or may not be in a multiclass.  If null,
1534/// these are the template args for a multiclass.
1535///
1536///    TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1537///
1538bool TGParser::ParseTemplateArgList(Record *CurRec) {
1539  assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1540  Lex.Lex(); // eat the '<'
1541
1542  Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1543
1544  // Read the first declaration.
1545  Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1546  if (TemplArg == 0)
1547    return true;
1548
1549  TheRecToAddTo->addTemplateArg(TemplArg);
1550
1551  while (Lex.getCode() == tgtok::comma) {
1552    Lex.Lex(); // eat the ','
1553
1554    // Read the following declarations.
1555    TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1556    if (TemplArg == 0)
1557      return true;
1558    TheRecToAddTo->addTemplateArg(TemplArg);
1559  }
1560
1561  if (Lex.getCode() != tgtok::greater)
1562    return TokError("expected '>' at end of template argument list");
1563  Lex.Lex(); // eat the '>'.
1564  return false;
1565}
1566
1567
1568/// ParseBodyItem - Parse a single item at within the body of a def or class.
1569///
1570///   BodyItem ::= Declaration ';'
1571///   BodyItem ::= LET ID OptionalBitList '=' Value ';'
1572bool TGParser::ParseBodyItem(Record *CurRec) {
1573  if (Lex.getCode() != tgtok::Let) {
1574    if (ParseDeclaration(CurRec, false) == 0)
1575      return true;
1576
1577    if (Lex.getCode() != tgtok::semi)
1578      return TokError("expected ';' after declaration");
1579    Lex.Lex();
1580    return false;
1581  }
1582
1583  // LET ID OptionalRangeList '=' Value ';'
1584  if (Lex.Lex() != tgtok::Id)
1585    return TokError("expected field identifier after let");
1586
1587  SMLoc IdLoc = Lex.getLoc();
1588  std::string FieldName = Lex.getCurStrVal();
1589  Lex.Lex();  // eat the field name.
1590
1591  std::vector<unsigned> BitList;
1592  if (ParseOptionalBitList(BitList))
1593    return true;
1594  std::reverse(BitList.begin(), BitList.end());
1595
1596  if (Lex.getCode() != tgtok::equal)
1597    return TokError("expected '=' in let expression");
1598  Lex.Lex();  // eat the '='.
1599
1600  RecordVal *Field = CurRec->getValue(FieldName);
1601  if (Field == 0)
1602    return TokError("Value '" + FieldName + "' unknown!");
1603
1604  RecTy *Type = Field->getType();
1605
1606  Init *Val = ParseValue(CurRec, Type);
1607  if (Val == 0) return true;
1608
1609  if (Lex.getCode() != tgtok::semi)
1610    return TokError("expected ';' after let expression");
1611  Lex.Lex();
1612
1613  return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1614}
1615
1616/// ParseBody - Read the body of a class or def.  Return true on error, false on
1617/// success.
1618///
1619///   Body     ::= ';'
1620///   Body     ::= '{' BodyList '}'
1621///   BodyList BodyItem*
1622///
1623bool TGParser::ParseBody(Record *CurRec) {
1624  // If this is a null definition, just eat the semi and return.
1625  if (Lex.getCode() == tgtok::semi) {
1626    Lex.Lex();
1627    return false;
1628  }
1629
1630  if (Lex.getCode() != tgtok::l_brace)
1631    return TokError("Expected ';' or '{' to start body");
1632  // Eat the '{'.
1633  Lex.Lex();
1634
1635  while (Lex.getCode() != tgtok::r_brace)
1636    if (ParseBodyItem(CurRec))
1637      return true;
1638
1639  // Eat the '}'.
1640  Lex.Lex();
1641  return false;
1642}
1643
1644/// ParseObjectBody - Parse the body of a def or class.  This consists of an
1645/// optional ClassList followed by a Body.  CurRec is the current def or class
1646/// that is being parsed.
1647///
1648///   ObjectBody      ::= BaseClassList Body
1649///   BaseClassList   ::= /*empty*/
1650///   BaseClassList   ::= ':' BaseClassListNE
1651///   BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1652///
1653bool TGParser::ParseObjectBody(Record *CurRec) {
1654  // If there is a baseclass list, read it.
1655  if (Lex.getCode() == tgtok::colon) {
1656    Lex.Lex();
1657
1658    // Read all of the subclasses.
1659    SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1660    while (1) {
1661      // Check for error.
1662      if (SubClass.Rec == 0) return true;
1663
1664      // Add it.
1665      if (AddSubClass(CurRec, SubClass))
1666        return true;
1667
1668      if (Lex.getCode() != tgtok::comma) break;
1669      Lex.Lex(); // eat ','.
1670      SubClass = ParseSubClassReference(CurRec, false);
1671    }
1672  }
1673
1674  // Process any variables on the let stack.
1675  for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1676    for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1677      if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1678                   LetStack[i][j].Bits, LetStack[i][j].Value))
1679        return true;
1680
1681  return ParseBody(CurRec);
1682}
1683
1684/// ParseDef - Parse and return a top level or multiclass def, return the record
1685/// corresponding to it.  This returns null on error.
1686///
1687///   DefInst ::= DEF ObjectName ObjectBody
1688///
1689bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1690  SMLoc DefLoc = Lex.getLoc();
1691  assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1692  Lex.Lex();  // Eat the 'def' token.
1693
1694  // Parse ObjectName and make a record for it.
1695  Record *CurRec = new Record(ParseObjectName(), DefLoc, Records);
1696
1697  if (!CurMultiClass) {
1698    // Top-level def definition.
1699
1700    // Ensure redefinition doesn't happen.
1701    if (Records.getDef(CurRec->getName())) {
1702      Error(DefLoc, "def '" + CurRec->getNameInitAsString()
1703            + "' already defined");
1704      return true;
1705    }
1706    Records.addDef(CurRec);
1707  } else {
1708    // Otherwise, a def inside a multiclass, add it to the multiclass.
1709    for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1710      if (CurMultiClass->DefPrototypes[i]->getNameInit()
1711          == CurRec->getNameInit()) {
1712        Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
1713              "' already defined in this multiclass!");
1714        return true;
1715      }
1716    CurMultiClass->DefPrototypes.push_back(CurRec);
1717  }
1718
1719  if (ParseObjectBody(CurRec))
1720    return true;
1721
1722  if (CurMultiClass == 0)  // Def's in multiclasses aren't really defs.
1723    // See Record::setName().  This resolve step will see any new name
1724    // for the def that might have been created when resolving
1725    // inheritance, values and arguments above.
1726    CurRec->resolveReferences();
1727
1728  // If ObjectBody has template arguments, it's an error.
1729  assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1730
1731  if (CurMultiClass) {
1732    // Copy the template arguments for the multiclass into the def.
1733    const std::vector<Init *> &TArgs =
1734                                CurMultiClass->Rec.getTemplateArgs();
1735
1736    for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1737      const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1738      assert(RV && "Template arg doesn't exist?");
1739      CurRec->addValue(*RV);
1740    }
1741  }
1742
1743  return false;
1744}
1745
1746/// ParseClass - Parse a tblgen class definition.
1747///
1748///   ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1749///
1750bool TGParser::ParseClass() {
1751  assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1752  Lex.Lex();
1753
1754  if (Lex.getCode() != tgtok::Id)
1755    return TokError("expected class name after 'class' keyword");
1756
1757  Record *CurRec = Records.getClass(Lex.getCurStrVal());
1758  if (CurRec) {
1759    // If the body was previously defined, this is an error.
1760    if (CurRec->getValues().size() > 1 ||  // Account for NAME.
1761        !CurRec->getSuperClasses().empty() ||
1762        !CurRec->getTemplateArgs().empty())
1763      return TokError("Class '" + CurRec->getNameInitAsString()
1764                      + "' already defined");
1765  } else {
1766    // If this is the first reference to this class, create and add it.
1767    CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
1768    Records.addClass(CurRec);
1769  }
1770  Lex.Lex(); // eat the name.
1771
1772  // If there are template args, parse them.
1773  if (Lex.getCode() == tgtok::less)
1774    if (ParseTemplateArgList(CurRec))
1775      return true;
1776
1777  // Finally, parse the object body.
1778  return ParseObjectBody(CurRec);
1779}
1780
1781/// ParseLetList - Parse a non-empty list of assignment expressions into a list
1782/// of LetRecords.
1783///
1784///   LetList ::= LetItem (',' LetItem)*
1785///   LetItem ::= ID OptionalRangeList '=' Value
1786///
1787std::vector<LetRecord> TGParser::ParseLetList() {
1788  std::vector<LetRecord> Result;
1789
1790  while (1) {
1791    if (Lex.getCode() != tgtok::Id) {
1792      TokError("expected identifier in let definition");
1793      return std::vector<LetRecord>();
1794    }
1795    std::string Name = Lex.getCurStrVal();
1796    SMLoc NameLoc = Lex.getLoc();
1797    Lex.Lex();  // Eat the identifier.
1798
1799    // Check for an optional RangeList.
1800    std::vector<unsigned> Bits;
1801    if (ParseOptionalRangeList(Bits))
1802      return std::vector<LetRecord>();
1803    std::reverse(Bits.begin(), Bits.end());
1804
1805    if (Lex.getCode() != tgtok::equal) {
1806      TokError("expected '=' in let expression");
1807      return std::vector<LetRecord>();
1808    }
1809    Lex.Lex();  // eat the '='.
1810
1811    Init *Val = ParseValue(0);
1812    if (Val == 0) return std::vector<LetRecord>();
1813
1814    // Now that we have everything, add the record.
1815    Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1816
1817    if (Lex.getCode() != tgtok::comma)
1818      return Result;
1819    Lex.Lex();  // eat the comma.
1820  }
1821}
1822
1823/// ParseTopLevelLet - Parse a 'let' at top level.  This can be a couple of
1824/// different related productions. This works inside multiclasses too.
1825///
1826///   Object ::= LET LetList IN '{' ObjectList '}'
1827///   Object ::= LET LetList IN Object
1828///
1829bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
1830  assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1831  Lex.Lex();
1832
1833  // Add this entry to the let stack.
1834  std::vector<LetRecord> LetInfo = ParseLetList();
1835  if (LetInfo.empty()) return true;
1836  LetStack.push_back(LetInfo);
1837
1838  if (Lex.getCode() != tgtok::In)
1839    return TokError("expected 'in' at end of top-level 'let'");
1840  Lex.Lex();
1841
1842  // If this is a scalar let, just handle it now
1843  if (Lex.getCode() != tgtok::l_brace) {
1844    // LET LetList IN Object
1845    if (ParseObject(CurMultiClass))
1846      return true;
1847  } else {   // Object ::= LETCommand '{' ObjectList '}'
1848    SMLoc BraceLoc = Lex.getLoc();
1849    // Otherwise, this is a group let.
1850    Lex.Lex();  // eat the '{'.
1851
1852    // Parse the object list.
1853    if (ParseObjectList(CurMultiClass))
1854      return true;
1855
1856    if (Lex.getCode() != tgtok::r_brace) {
1857      TokError("expected '}' at end of top level let command");
1858      return Error(BraceLoc, "to match this '{'");
1859    }
1860    Lex.Lex();
1861  }
1862
1863  // Outside this let scope, this let block is not active.
1864  LetStack.pop_back();
1865  return false;
1866}
1867
1868/// ParseMultiClass - Parse a multiclass definition.
1869///
1870///  MultiClassInst ::= MULTICLASS ID TemplateArgList?
1871///                     ':' BaseMultiClassList '{' MultiClassDef+ '}'
1872///
1873bool TGParser::ParseMultiClass() {
1874  assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1875  Lex.Lex();  // Eat the multiclass token.
1876
1877  if (Lex.getCode() != tgtok::Id)
1878    return TokError("expected identifier after multiclass for name");
1879  std::string Name = Lex.getCurStrVal();
1880
1881  if (MultiClasses.count(Name))
1882    return TokError("multiclass '" + Name + "' already defined");
1883
1884  CurMultiClass = MultiClasses[Name] = new MultiClass(Name,
1885                                                      Lex.getLoc(), Records);
1886  Lex.Lex();  // Eat the identifier.
1887
1888  // If there are template args, parse them.
1889  if (Lex.getCode() == tgtok::less)
1890    if (ParseTemplateArgList(0))
1891      return true;
1892
1893  bool inherits = false;
1894
1895  // If there are submulticlasses, parse them.
1896  if (Lex.getCode() == tgtok::colon) {
1897    inherits = true;
1898
1899    Lex.Lex();
1900
1901    // Read all of the submulticlasses.
1902    SubMultiClassReference SubMultiClass =
1903      ParseSubMultiClassReference(CurMultiClass);
1904    while (1) {
1905      // Check for error.
1906      if (SubMultiClass.MC == 0) return true;
1907
1908      // Add it.
1909      if (AddSubMultiClass(CurMultiClass, SubMultiClass))
1910        return true;
1911
1912      if (Lex.getCode() != tgtok::comma) break;
1913      Lex.Lex(); // eat ','.
1914      SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
1915    }
1916  }
1917
1918  if (Lex.getCode() != tgtok::l_brace) {
1919    if (!inherits)
1920      return TokError("expected '{' in multiclass definition");
1921    else if (Lex.getCode() != tgtok::semi)
1922      return TokError("expected ';' in multiclass definition");
1923    else
1924      Lex.Lex();  // eat the ';'.
1925  } else {
1926    if (Lex.Lex() == tgtok::r_brace)  // eat the '{'.
1927      return TokError("multiclass must contain at least one def");
1928
1929    while (Lex.getCode() != tgtok::r_brace) {
1930      switch (Lex.getCode()) {
1931        default:
1932          return TokError("expected 'let', 'def' or 'defm' in multiclass body");
1933        case tgtok::Let:
1934        case tgtok::Def:
1935        case tgtok::Defm:
1936          if (ParseObject(CurMultiClass))
1937            return true;
1938         break;
1939      }
1940    }
1941    Lex.Lex();  // eat the '}'.
1942  }
1943
1944  CurMultiClass = 0;
1945  return false;
1946}
1947
1948Record *TGParser::
1949InstantiateMulticlassDef(MultiClass &MC,
1950                         Record *DefProto,
1951                         const std::string &DefmPrefix,
1952                         SMLoc DefmPrefixLoc) {
1953  // Add in the defm name.  If the defm prefix is empty, give each
1954  // instantiated def a unique name.  Otherwise, if "#NAME#" exists in the
1955  // name, substitute the prefix for #NAME#.  Otherwise, use the defm name
1956  // as a prefix.
1957  std::string DefName = DefProto->getName();
1958  if (DefmPrefix.empty()) {
1959    DefName = GetNewAnonymousName();
1960  } else {
1961    std::string::size_type idx = DefName.find("#NAME#");
1962    if (idx != std::string::npos) {
1963      DefName.replace(idx, 6, DefmPrefix);
1964    } else {
1965      // Add the suffix to the defm name to get the new name.
1966      DefName = DefmPrefix + DefName;
1967    }
1968  }
1969
1970  Record *CurRec = new Record(DefName, DefmPrefixLoc, Records);
1971
1972  SubClassReference Ref;
1973  Ref.RefLoc = DefmPrefixLoc;
1974  Ref.Rec = DefProto;
1975  AddSubClass(CurRec, Ref);
1976
1977  return CurRec;
1978}
1979
1980bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
1981                                        Record *CurRec,
1982                                        SMLoc DefmPrefixLoc,
1983                                        SMLoc SubClassLoc,
1984                                        const std::vector<Init *> &TArgs,
1985                                        std::vector<Init *> &TemplateVals,
1986                                        bool DeleteArgs) {
1987  // Loop over all of the template arguments, setting them to the specified
1988  // value or leaving them as the default if necessary.
1989  for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1990    // Check if a value is specified for this temp-arg.
1991    if (i < TemplateVals.size()) {
1992      // Set it now.
1993      if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
1994                   TemplateVals[i]))
1995        return true;
1996
1997      // Resolve it next.
1998      CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
1999
2000      if (DeleteArgs)
2001        // Now remove it.
2002        CurRec->removeValue(TArgs[i]);
2003
2004    } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2005      return Error(SubClassLoc, "value not specified for template argument #"+
2006                   utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2007                   + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2008                   + "'");
2009    }
2010  }
2011  return false;
2012}
2013
2014bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2015                                    Record *CurRec,
2016                                    Record *DefProto,
2017                                    SMLoc DefmPrefixLoc) {
2018  // If the mdef is inside a 'let' expression, add to each def.
2019  for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2020    for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2021      if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2022                   LetStack[i][j].Bits, LetStack[i][j].Value))
2023        return Error(DefmPrefixLoc, "when instantiating this defm");
2024
2025  // Ensure redefinition doesn't happen.
2026  if (Records.getDef(CurRec->getName()))
2027    return Error(DefmPrefixLoc, "def '" + CurRec->getName() +
2028                 "' already defined, instantiating defm with subdef '" +
2029                 DefProto->getName() + "'");
2030
2031  // Don't create a top level definition for defm inside multiclasses,
2032  // instead, only update the prototypes and bind the template args
2033  // with the new created definition.
2034  if (CurMultiClass) {
2035    for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2036         i != e; ++i)
2037      if (CurMultiClass->DefPrototypes[i]->getNameInit()
2038          == CurRec->getNameInit())
2039        return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2040                     "' already defined in this multiclass!");
2041    CurMultiClass->DefPrototypes.push_back(CurRec);
2042
2043    // Copy the template arguments for the multiclass into the new def.
2044    const std::vector<Init *> &TA =
2045      CurMultiClass->Rec.getTemplateArgs();
2046
2047    for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2048      const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2049      assert(RV && "Template arg doesn't exist?");
2050      CurRec->addValue(*RV);
2051    }
2052  } else {
2053    Records.addDef(CurRec);
2054  }
2055
2056  return false;
2057}
2058
2059/// ParseDefm - Parse the instantiation of a multiclass.
2060///
2061///   DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2062///
2063bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2064  assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2065
2066  std::string DefmPrefix;
2067  if (Lex.Lex() == tgtok::Id) {  // eat the defm.
2068    DefmPrefix = Lex.getCurStrVal();
2069    Lex.Lex();  // Eat the defm prefix.
2070  }
2071
2072  SMLoc DefmPrefixLoc = Lex.getLoc();
2073  if (Lex.getCode() != tgtok::colon)
2074    return TokError("expected ':' after defm identifier");
2075
2076  // Keep track of the new generated record definitions.
2077  std::vector<Record*> NewRecDefs;
2078
2079  // This record also inherits from a regular class (non-multiclass)?
2080  bool InheritFromClass = false;
2081
2082  // eat the colon.
2083  Lex.Lex();
2084
2085  SMLoc SubClassLoc = Lex.getLoc();
2086  SubClassReference Ref = ParseSubClassReference(0, true);
2087
2088  while (1) {
2089    if (Ref.Rec == 0) return true;
2090
2091    // To instantiate a multiclass, we need to first get the multiclass, then
2092    // instantiate each def contained in the multiclass with the SubClassRef
2093    // template parameters.
2094    MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2095    assert(MC && "Didn't lookup multiclass correctly?");
2096    std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2097
2098    // Verify that the correct number of template arguments were specified.
2099    const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2100    if (TArgs.size() < TemplateVals.size())
2101      return Error(SubClassLoc,
2102                   "more template args specified than multiclass expects");
2103
2104    // Loop over all the def's in the multiclass, instantiating each one.
2105    for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2106      Record *DefProto = MC->DefPrototypes[i];
2107
2108      Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix, DefmPrefixLoc);
2109
2110      if (ResolveMulticlassDefArgs(*MC, CurRec, DefmPrefixLoc, SubClassLoc,
2111                                   TArgs, TemplateVals, true/*Delete args*/))
2112        return Error(SubClassLoc, "could not instantiate def");
2113
2114      if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmPrefixLoc))
2115        return Error(SubClassLoc, "could not instantiate def");
2116
2117      NewRecDefs.push_back(CurRec);
2118    }
2119
2120
2121    if (Lex.getCode() != tgtok::comma) break;
2122    Lex.Lex(); // eat ','.
2123
2124    SubClassLoc = Lex.getLoc();
2125
2126    // A defm can inherit from regular classes (non-multiclass) as
2127    // long as they come in the end of the inheritance list.
2128    InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != 0);
2129
2130    if (InheritFromClass)
2131      break;
2132
2133    Ref = ParseSubClassReference(0, true);
2134  }
2135
2136  if (InheritFromClass) {
2137    // Process all the classes to inherit as if they were part of a
2138    // regular 'def' and inherit all record values.
2139    SubClassReference SubClass = ParseSubClassReference(0, false);
2140    while (1) {
2141      // Check for error.
2142      if (SubClass.Rec == 0) return true;
2143
2144      // Get the expanded definition prototypes and teach them about
2145      // the record values the current class to inherit has
2146      for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2147        Record *CurRec = NewRecDefs[i];
2148
2149        // Add it.
2150        if (AddSubClass(CurRec, SubClass))
2151          return true;
2152
2153        // Process any variables on the let stack.
2154        for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2155          for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2156            if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2157                         LetStack[i][j].Bits, LetStack[i][j].Value))
2158              return true;
2159      }
2160
2161      if (Lex.getCode() != tgtok::comma) break;
2162      Lex.Lex(); // eat ','.
2163      SubClass = ParseSubClassReference(0, false);
2164    }
2165  }
2166
2167  if (!CurMultiClass)
2168    for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2169      // See Record::setName().  This resolve step will see any new
2170      // name for the def that might have been created when resolving
2171      // inheritance, values and arguments above.
2172      NewRecDefs[i]->resolveReferences();
2173
2174  if (Lex.getCode() != tgtok::semi)
2175    return TokError("expected ';' at end of defm");
2176  Lex.Lex();
2177
2178  return false;
2179}
2180
2181/// ParseObject
2182///   Object ::= ClassInst
2183///   Object ::= DefInst
2184///   Object ::= MultiClassInst
2185///   Object ::= DefMInst
2186///   Object ::= LETCommand '{' ObjectList '}'
2187///   Object ::= LETCommand Object
2188bool TGParser::ParseObject(MultiClass *MC) {
2189  switch (Lex.getCode()) {
2190  default:
2191    return TokError("Expected class, def, defm, multiclass or let definition");
2192  case tgtok::Let:   return ParseTopLevelLet(MC);
2193  case tgtok::Def:   return ParseDef(MC);
2194  case tgtok::Defm:  return ParseDefm(MC);
2195  case tgtok::Class: return ParseClass();
2196  case tgtok::MultiClass: return ParseMultiClass();
2197  }
2198}
2199
2200/// ParseObjectList
2201///   ObjectList :== Object*
2202bool TGParser::ParseObjectList(MultiClass *MC) {
2203  while (isObjectStart(Lex.getCode())) {
2204    if (ParseObject(MC))
2205      return true;
2206  }
2207  return false;
2208}
2209
2210bool TGParser::ParseFile() {
2211  Lex.Lex(); // Prime the lexer.
2212  if (ParseObjectList()) return true;
2213
2214  // If we have unread input at the end of the file, report it.
2215  if (Lex.getCode() == tgtok::Eof)
2216    return false;
2217
2218  return TokError("Unexpected input at top level");
2219}
2220
2221