blob: c3b17ac603933342d31cce6842ebd98941df17a4 [file] [log] [blame]
Chris Lattnerf4601652007-11-22 20:49:04 +00001//===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner30609102007-12-29 20:37:13 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerf4601652007-11-22 20:49:04 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Implement the Parser for TableGen.
11//
12//===----------------------------------------------------------------------===//
13
Chuck Rose IIIaa917922007-11-26 23:19:59 +000014#include <algorithm>
15
Chris Lattnerf4601652007-11-22 20:49:04 +000016#include "TGParser.h"
17#include "Record.h"
18#include "llvm/ADT/StringExtras.h"
19using namespace llvm;
20
21//===----------------------------------------------------------------------===//
22// Support Code for the Semantic Actions.
23//===----------------------------------------------------------------------===//
24
25namespace llvm {
Chris Lattnerf4601652007-11-22 20:49:04 +000026struct SubClassReference {
Chris Lattner1c8ae592009-03-13 16:01:53 +000027 TGLoc RefLoc;
Chris Lattnerf4601652007-11-22 20:49:04 +000028 Record *Rec;
29 std::vector<Init*> TemplateArgs;
Chris Lattner1c8ae592009-03-13 16:01:53 +000030 SubClassReference() : Rec(0) {}
Chris Lattnerf4601652007-11-22 20:49:04 +000031
32 bool isInvalid() const { return Rec == 0; }
33};
David Greenede444af2009-04-22 16:42:54 +000034
35struct SubMultiClassReference {
36 TGLoc RefLoc;
37 MultiClass *MC;
38 std::vector<Init*> TemplateArgs;
39 SubMultiClassReference() : MC(0) {}
40
41 bool isInvalid() const { return MC == 0; }
42};
Chris Lattnerf4601652007-11-22 20:49:04 +000043
44} // end namespace llvm
45
Chris Lattner1c8ae592009-03-13 16:01:53 +000046bool TGParser::AddValue(Record *CurRec, TGLoc Loc, const RecordVal &RV) {
Chris Lattnerf4601652007-11-22 20:49:04 +000047 if (CurRec == 0)
48 CurRec = &CurMultiClass->Rec;
49
50 if (RecordVal *ERV = CurRec->getValue(RV.getName())) {
51 // The value already exists in the class, treat this as a set.
52 if (ERV->setValue(RV.getValue()))
53 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
54 RV.getType()->getAsString() + "' is incompatible with " +
55 "previous definition of type '" +
56 ERV->getType()->getAsString() + "'");
57 } else {
58 CurRec->addValue(RV);
59 }
60 return false;
61}
62
63/// SetValue -
64/// Return true on error, false on success.
Chris Lattner1c8ae592009-03-13 16:01:53 +000065bool TGParser::SetValue(Record *CurRec, TGLoc Loc, const std::string &ValName,
Chris Lattnerf4601652007-11-22 20:49:04 +000066 const std::vector<unsigned> &BitList, Init *V) {
67 if (!V) return false;
68
69 if (CurRec == 0) CurRec = &CurMultiClass->Rec;
70
71 RecordVal *RV = CurRec->getValue(ValName);
72 if (RV == 0)
73 return Error(Loc, "Value '" + ValName + "' unknown!");
74
75 // Do not allow assignments like 'X = X'. This will just cause infinite loops
76 // in the resolution machinery.
77 if (BitList.empty())
78 if (VarInit *VI = dynamic_cast<VarInit*>(V))
79 if (VI->getName() == ValName)
80 return false;
81
82 // If we are assigning to a subset of the bits in the value... then we must be
83 // assigning to a field of BitsRecTy, which must have a BitsInit
84 // initializer.
85 //
86 if (!BitList.empty()) {
87 BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
88 if (CurVal == 0)
89 return Error(Loc, "Value '" + ValName + "' is not a bits type");
90
91 // Convert the incoming value to a bits type of the appropriate size...
92 Init *BI = V->convertInitializerTo(new BitsRecTy(BitList.size()));
93 if (BI == 0) {
94 V->convertInitializerTo(new BitsRecTy(BitList.size()));
95 return Error(Loc, "Initializer is not compatible with bit range");
96 }
97
98 // We should have a BitsInit type now.
99 BitsInit *BInit = dynamic_cast<BitsInit*>(BI);
100 assert(BInit != 0);
101
102 BitsInit *NewVal = new BitsInit(CurVal->getNumBits());
103
104 // Loop over bits, assigning values as appropriate.
105 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
106 unsigned Bit = BitList[i];
107 if (NewVal->getBit(Bit))
108 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
109 ValName + "' more than once");
110 NewVal->setBit(Bit, BInit->getBit(i));
111 }
112
113 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
114 if (NewVal->getBit(i) == 0)
115 NewVal->setBit(i, CurVal->getBit(i));
116
117 V = NewVal;
118 }
119
120 if (RV->setValue(V))
121 return Error(Loc, "Value '" + ValName + "' of type '" +
122 RV->getType()->getAsString() +
Chris Lattner5d814862007-11-22 21:06:59 +0000123 "' is incompatible with initializer '" + V->getAsString() +"'");
Chris Lattnerf4601652007-11-22 20:49:04 +0000124 return false;
125}
126
127/// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
128/// args as SubClass's template arguments.
Cedric Venetaff9c272009-02-14 16:06:42 +0000129bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
Chris Lattnerf4601652007-11-22 20:49:04 +0000130 Record *SC = SubClass.Rec;
131 // Add all of the values in the subclass into the current class.
132 const std::vector<RecordVal> &Vals = SC->getValues();
133 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
134 if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
135 return true;
136
137 const std::vector<std::string> &TArgs = SC->getTemplateArgs();
138
139 // Ensure that an appropriate number of template arguments are specified.
140 if (TArgs.size() < SubClass.TemplateArgs.size())
141 return Error(SubClass.RefLoc, "More template args specified than expected");
142
143 // Loop over all of the template arguments, setting them to the specified
144 // value or leaving them as the default if necessary.
145 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
146 if (i < SubClass.TemplateArgs.size()) {
147 // If a value is specified for this template arg, set it now.
148 if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(),
149 SubClass.TemplateArgs[i]))
150 return true;
151
152 // Resolve it next.
153 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
154
155 // Now remove it.
156 CurRec->removeValue(TArgs[i]);
157
158 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
159 return Error(SubClass.RefLoc,"Value not specified for template argument #"
160 + utostr(i) + " (" + TArgs[i] + ") of subclass '" +
161 SC->getName() + "'!");
162 }
163 }
164
165 // Since everything went well, we can now set the "superclass" list for the
166 // current record.
167 const std::vector<Record*> &SCs = SC->getSuperClasses();
168 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
169 if (CurRec->isSubClassOf(SCs[i]))
170 return Error(SubClass.RefLoc,
171 "Already subclass of '" + SCs[i]->getName() + "'!\n");
172 CurRec->addSuperClass(SCs[i]);
173 }
174
175 if (CurRec->isSubClassOf(SC))
176 return Error(SubClass.RefLoc,
177 "Already subclass of '" + SC->getName() + "'!\n");
178 CurRec->addSuperClass(SC);
179 return false;
180}
181
David Greenede444af2009-04-22 16:42:54 +0000182/// AddSubMultiClass - Add SubMultiClass as a subclass to
183/// CurMultiClass, resolving its template args as SubMultiClass's
184/// template arguments.
185bool TGParser::AddSubMultiClass(MultiClass *CurMultiClass, class SubMultiClassReference &SubMultiClass) {
186 MultiClass *SMC = SubMultiClass.MC;
187 Record *CurRec = &CurMultiClass->Rec;
188
189 const std::vector<RecordVal> &MCVals = CurMultiClass->Rec.getValues();
190
191 // Add all of the values in the subclass into the current class.
192 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
193 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
194 if (AddValue(CurRec, SubMultiClass.RefLoc, SMCVals[i]))
195 return true;
196
197 // Add all of the defs in the subclass into the current multiclass.
198 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
199 iend = SMC->DefPrototypes.end();
200 i != iend;
201 ++i) {
202 // Clone the def and add it to the current multiclass
203 Record *NewDef = new Record(**i);
204
205 // Add all of the values in the superclass into the current def.
206 for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
207 if (AddValue(NewDef, SubMultiClass.RefLoc, MCVals[i]))
208 return true;
209
210 CurMultiClass->DefPrototypes.push_back(NewDef);
211 }
212
213 const std::vector<std::string> &SMCTArgs = SMC->Rec.getTemplateArgs();
214
215 // Ensure that an appropriate number of template arguments are specified.
216 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
217 return Error(SubMultiClass.RefLoc, "More template args specified than expected");
218
219 // Loop over all of the template arguments, setting them to the specified
220 // value or leaving them as the default if necessary.
221 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
222 if (i < SubMultiClass.TemplateArgs.size()) {
223 // If a value is specified for this template arg, set it in the superclass now.
224 if (SetValue(CurRec, SubMultiClass.RefLoc, SMCTArgs[i], std::vector<unsigned>(),
225 SubMultiClass.TemplateArgs[i]))
226 return true;
227
228 // Resolve it next.
229 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
230
231 // Now remove it.
232 CurRec->removeValue(SMCTArgs[i]);
233
234 // If a value is specified for this template arg, set it in the defs now.
235 for (MultiClass::RecordVector::iterator j = CurMultiClass->DefPrototypes.begin(),
236 jend = CurMultiClass->DefPrototypes.end();
237 j != jend;
238 ++j) {
239 Record *Def = *j;
240
241 if (SetValue(Def, SubMultiClass.RefLoc, SMCTArgs[i], std::vector<unsigned>(),
242 SubMultiClass.TemplateArgs[i]))
243 return true;
244
245 // Resolve it next.
246 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
247
248 // Now remove it
249 Def->removeValue(SMCTArgs[i]);
250 }
251 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
252 return Error(SubMultiClass.RefLoc,"Value not specified for template argument #"
253 + utostr(i) + " (" + SMCTArgs[i] + ") of subclass '" +
254 SMC->Rec.getName() + "'!");
255 }
256 }
257
258 return false;
259}
260
Chris Lattnerf4601652007-11-22 20:49:04 +0000261//===----------------------------------------------------------------------===//
262// Parser Code
263//===----------------------------------------------------------------------===//
264
265/// isObjectStart - Return true if this is a valid first token for an Object.
266static bool isObjectStart(tgtok::TokKind K) {
267 return K == tgtok::Class || K == tgtok::Def ||
268 K == tgtok::Defm || K == tgtok::Let || K == tgtok::MultiClass;
269}
270
271/// ParseObjectName - If an object name is specified, return it. Otherwise,
272/// return an anonymous name.
273/// ObjectName ::= ID
274/// ObjectName ::= /*empty*/
275///
276std::string TGParser::ParseObjectName() {
277 if (Lex.getCode() == tgtok::Id) {
278 std::string Ret = Lex.getCurStrVal();
279 Lex.Lex();
280 return Ret;
281 }
282
283 static unsigned AnonCounter = 0;
284 return "anonymous."+utostr(AnonCounter++);
285}
286
287
288/// ParseClassID - Parse and resolve a reference to a class name. This returns
289/// null on error.
290///
291/// ClassID ::= ID
292///
293Record *TGParser::ParseClassID() {
294 if (Lex.getCode() != tgtok::Id) {
295 TokError("expected name for ClassID");
296 return 0;
297 }
298
299 Record *Result = Records.getClass(Lex.getCurStrVal());
300 if (Result == 0)
301 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
302
303 Lex.Lex();
304 return Result;
305}
306
David Greenede444af2009-04-22 16:42:54 +0000307/// ParseMultiClassID - Parse and resolve a reference to a multiclass name. This returns
308/// null on error.
309///
310/// MultiClassID ::= ID
311///
312MultiClass *TGParser::ParseMultiClassID() {
313 if (Lex.getCode() != tgtok::Id) {
314 TokError("expected name for ClassID");
315 return 0;
316 }
317
318 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
319 if (Result == 0)
320 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
321
322 Lex.Lex();
323 return Result;
324}
325
Chris Lattnerf4601652007-11-22 20:49:04 +0000326Record *TGParser::ParseDefmID() {
327 if (Lex.getCode() != tgtok::Id) {
328 TokError("expected multiclass name");
329 return 0;
330 }
331
332 MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
333 if (MC == 0) {
334 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
335 return 0;
336 }
337
338 Lex.Lex();
339 return &MC->Rec;
340}
341
342
343
344/// ParseSubClassReference - Parse a reference to a subclass or to a templated
345/// subclass. This returns a SubClassRefTy with a null Record* on error.
346///
347/// SubClassRef ::= ClassID
348/// SubClassRef ::= ClassID '<' ValueList '>'
349///
350SubClassReference TGParser::
351ParseSubClassReference(Record *CurRec, bool isDefm) {
352 SubClassReference Result;
353 Result.RefLoc = Lex.getLoc();
354
355 if (isDefm)
356 Result.Rec = ParseDefmID();
357 else
358 Result.Rec = ParseClassID();
359 if (Result.Rec == 0) return Result;
360
361 // If there is no template arg list, we're done.
362 if (Lex.getCode() != tgtok::less)
363 return Result;
364 Lex.Lex(); // Eat the '<'
365
366 if (Lex.getCode() == tgtok::greater) {
367 TokError("subclass reference requires a non-empty list of template values");
368 Result.Rec = 0;
369 return Result;
370 }
371
372 Result.TemplateArgs = ParseValueList(CurRec);
373 if (Result.TemplateArgs.empty()) {
374 Result.Rec = 0; // Error parsing value list.
375 return Result;
376 }
377
378 if (Lex.getCode() != tgtok::greater) {
379 TokError("expected '>' in template value list");
380 Result.Rec = 0;
381 return Result;
382 }
383 Lex.Lex();
384
385 return Result;
386}
387
David Greenede444af2009-04-22 16:42:54 +0000388/// ParseSubMultiClassReference - Parse a reference to a subclass or to a templated
389/// submulticlass. This returns a SubMultiClassRefTy with a null Record* on error.
390///
391/// SubMultiClassRef ::= MultiClassID
392/// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
393///
394SubMultiClassReference TGParser::
395ParseSubMultiClassReference(MultiClass *CurMC) {
396 SubMultiClassReference Result;
397 Result.RefLoc = Lex.getLoc();
398
399 Result.MC = ParseMultiClassID();
400 if (Result.MC == 0) return Result;
401
402 // If there is no template arg list, we're done.
403 if (Lex.getCode() != tgtok::less)
404 return Result;
405 Lex.Lex(); // Eat the '<'
406
407 if (Lex.getCode() == tgtok::greater) {
408 TokError("subclass reference requires a non-empty list of template values");
409 Result.MC = 0;
410 return Result;
411 }
412
413 Result.TemplateArgs = ParseValueList(&CurMC->Rec);
414 if (Result.TemplateArgs.empty()) {
415 Result.MC = 0; // Error parsing value list.
416 return Result;
417 }
418
419 if (Lex.getCode() != tgtok::greater) {
420 TokError("expected '>' in template value list");
421 Result.MC = 0;
422 return Result;
423 }
424 Lex.Lex();
425
426 return Result;
427}
428
Chris Lattnerf4601652007-11-22 20:49:04 +0000429/// ParseRangePiece - Parse a bit/value range.
430/// RangePiece ::= INTVAL
431/// RangePiece ::= INTVAL '-' INTVAL
432/// RangePiece ::= INTVAL INTVAL
433bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
Chris Lattner811281e2008-01-10 07:01:53 +0000434 if (Lex.getCode() != tgtok::IntVal) {
435 TokError("expected integer or bitrange");
436 return true;
437 }
Dan Gohman63f97202008-10-17 01:33:43 +0000438 int64_t Start = Lex.getCurIntVal();
439 int64_t End;
Chris Lattnerf4601652007-11-22 20:49:04 +0000440
441 if (Start < 0)
442 return TokError("invalid range, cannot be negative");
443
444 switch (Lex.Lex()) { // eat first character.
445 default:
446 Ranges.push_back(Start);
447 return false;
448 case tgtok::minus:
449 if (Lex.Lex() != tgtok::IntVal) {
450 TokError("expected integer value as end of range");
451 return true;
452 }
453 End = Lex.getCurIntVal();
454 break;
455 case tgtok::IntVal:
456 End = -Lex.getCurIntVal();
457 break;
458 }
459 if (End < 0)
460 return TokError("invalid range, cannot be negative");
461 Lex.Lex();
462
463 // Add to the range.
464 if (Start < End) {
465 for (; Start <= End; ++Start)
466 Ranges.push_back(Start);
467 } else {
468 for (; Start >= End; --Start)
469 Ranges.push_back(Start);
470 }
471 return false;
472}
473
474/// ParseRangeList - Parse a list of scalars and ranges into scalar values.
475///
476/// RangeList ::= RangePiece (',' RangePiece)*
477///
478std::vector<unsigned> TGParser::ParseRangeList() {
479 std::vector<unsigned> Result;
480
481 // Parse the first piece.
482 if (ParseRangePiece(Result))
483 return std::vector<unsigned>();
484 while (Lex.getCode() == tgtok::comma) {
485 Lex.Lex(); // Eat the comma.
486
487 // Parse the next range piece.
488 if (ParseRangePiece(Result))
489 return std::vector<unsigned>();
490 }
491 return Result;
492}
493
494/// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
495/// OptionalRangeList ::= '<' RangeList '>'
496/// OptionalRangeList ::= /*empty*/
497bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
498 if (Lex.getCode() != tgtok::less)
499 return false;
500
Chris Lattner1c8ae592009-03-13 16:01:53 +0000501 TGLoc StartLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +0000502 Lex.Lex(); // eat the '<'
503
504 // Parse the range list.
505 Ranges = ParseRangeList();
506 if (Ranges.empty()) return true;
507
508 if (Lex.getCode() != tgtok::greater) {
509 TokError("expected '>' at end of range list");
510 return Error(StartLoc, "to match this '<'");
511 }
512 Lex.Lex(); // eat the '>'.
513 return false;
514}
515
516/// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
517/// OptionalBitList ::= '{' RangeList '}'
518/// OptionalBitList ::= /*empty*/
519bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
520 if (Lex.getCode() != tgtok::l_brace)
521 return false;
522
Chris Lattner1c8ae592009-03-13 16:01:53 +0000523 TGLoc StartLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +0000524 Lex.Lex(); // eat the '{'
525
526 // Parse the range list.
527 Ranges = ParseRangeList();
528 if (Ranges.empty()) return true;
529
530 if (Lex.getCode() != tgtok::r_brace) {
531 TokError("expected '}' at end of bit list");
532 return Error(StartLoc, "to match this '{'");
533 }
534 Lex.Lex(); // eat the '}'.
535 return false;
536}
537
538
539/// ParseType - Parse and return a tblgen type. This returns null on error.
540///
541/// Type ::= STRING // string type
542/// Type ::= BIT // bit type
543/// Type ::= BITS '<' INTVAL '>' // bits<x> type
544/// Type ::= INT // int type
545/// Type ::= LIST '<' Type '>' // list<x> type
546/// Type ::= CODE // code type
547/// Type ::= DAG // dag type
548/// Type ::= ClassID // Record Type
549///
550RecTy *TGParser::ParseType() {
551 switch (Lex.getCode()) {
552 default: TokError("Unknown token when expecting a type"); return 0;
553 case tgtok::String: Lex.Lex(); return new StringRecTy();
554 case tgtok::Bit: Lex.Lex(); return new BitRecTy();
555 case tgtok::Int: Lex.Lex(); return new IntRecTy();
556 case tgtok::Code: Lex.Lex(); return new CodeRecTy();
557 case tgtok::Dag: Lex.Lex(); return new DagRecTy();
558 case tgtok::Id:
559 if (Record *R = ParseClassID()) return new RecordRecTy(R);
560 return 0;
561 case tgtok::Bits: {
562 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
563 TokError("expected '<' after bits type");
564 return 0;
565 }
566 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
567 TokError("expected integer in bits<n> type");
568 return 0;
569 }
Dan Gohman63f97202008-10-17 01:33:43 +0000570 uint64_t Val = Lex.getCurIntVal();
Chris Lattnerf4601652007-11-22 20:49:04 +0000571 if (Lex.Lex() != tgtok::greater) { // Eat count.
572 TokError("expected '>' at end of bits<n> type");
573 return 0;
574 }
575 Lex.Lex(); // Eat '>'
576 return new BitsRecTy(Val);
577 }
578 case tgtok::List: {
579 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
580 TokError("expected '<' after list type");
581 return 0;
582 }
583 Lex.Lex(); // Eat '<'
584 RecTy *SubType = ParseType();
585 if (SubType == 0) return 0;
586
587 if (Lex.getCode() != tgtok::greater) {
588 TokError("expected '>' at end of list<ty> type");
589 return 0;
590 }
591 Lex.Lex(); // Eat '>'
592 return new ListRecTy(SubType);
593 }
594 }
595}
596
597/// ParseIDValue - Parse an ID as a value and decode what it means.
598///
599/// IDValue ::= ID [def local value]
600/// IDValue ::= ID [def template arg]
601/// IDValue ::= ID [multiclass local value]
602/// IDValue ::= ID [multiclass template argument]
603/// IDValue ::= ID [def name]
604///
605Init *TGParser::ParseIDValue(Record *CurRec) {
606 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
607 std::string Name = Lex.getCurStrVal();
Chris Lattner1c8ae592009-03-13 16:01:53 +0000608 TGLoc Loc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +0000609 Lex.Lex();
610 return ParseIDValue(CurRec, Name, Loc);
611}
612
613/// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
614/// has already been read.
615Init *TGParser::ParseIDValue(Record *CurRec,
Chris Lattner1c8ae592009-03-13 16:01:53 +0000616 const std::string &Name, TGLoc NameLoc) {
Chris Lattnerf4601652007-11-22 20:49:04 +0000617 if (CurRec) {
618 if (const RecordVal *RV = CurRec->getValue(Name))
619 return new VarInit(Name, RV->getType());
620
621 std::string TemplateArgName = CurRec->getName()+":"+Name;
622 if (CurRec->isTemplateArg(TemplateArgName)) {
623 const RecordVal *RV = CurRec->getValue(TemplateArgName);
624 assert(RV && "Template arg doesn't exist??");
625 return new VarInit(TemplateArgName, RV->getType());
626 }
627 }
628
629 if (CurMultiClass) {
630 std::string MCName = CurMultiClass->Rec.getName()+"::"+Name;
631 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
632 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
633 assert(RV && "Template arg doesn't exist??");
634 return new VarInit(MCName, RV->getType());
635 }
636 }
637
638 if (Record *D = Records.getDef(Name))
639 return new DefInit(D);
640
641 Error(NameLoc, "Variable not defined: '" + Name + "'");
642 return 0;
643}
644
645/// ParseSimpleValue - Parse a tblgen value. This returns null on error.
646///
647/// SimpleValue ::= IDValue
648/// SimpleValue ::= INTVAL
Chris Lattnerd7a50cf2009-03-11 17:08:13 +0000649/// SimpleValue ::= STRVAL+
Chris Lattnerf4601652007-11-22 20:49:04 +0000650/// SimpleValue ::= CODEFRAGMENT
651/// SimpleValue ::= '?'
652/// SimpleValue ::= '{' ValueList '}'
653/// SimpleValue ::= ID '<' ValueListNE '>'
654/// SimpleValue ::= '[' ValueList ']'
655/// SimpleValue ::= '(' IDValue DagArgList ')'
656/// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
657/// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
658/// SimpleValue ::= SRATOK '(' Value ',' Value ')'
659/// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
660/// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
661///
662Init *TGParser::ParseSimpleValue(Record *CurRec) {
663 Init *R = 0;
664 switch (Lex.getCode()) {
665 default: TokError("Unknown token when parsing a value"); break;
666 case tgtok::IntVal: R = new IntInit(Lex.getCurIntVal()); Lex.Lex(); break;
Chris Lattnerd7a50cf2009-03-11 17:08:13 +0000667 case tgtok::StrVal: {
668 std::string Val = Lex.getCurStrVal();
669 Lex.Lex();
670
Jim Grosbachda4231f2009-03-26 16:17:51 +0000671 // Handle multiple consecutive concatenated strings.
Chris Lattnerd7a50cf2009-03-11 17:08:13 +0000672 while (Lex.getCode() == tgtok::StrVal) {
673 Val += Lex.getCurStrVal();
674 Lex.Lex();
675 }
676
677 R = new StringInit(Val);
678 break;
679 }
Chris Lattnerf4601652007-11-22 20:49:04 +0000680 case tgtok::CodeFragment:
681 R = new CodeInit(Lex.getCurStrVal()); Lex.Lex(); break;
682 case tgtok::question: R = new UnsetInit(); Lex.Lex(); break;
683 case tgtok::Id: {
Chris Lattner1c8ae592009-03-13 16:01:53 +0000684 TGLoc NameLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +0000685 std::string Name = Lex.getCurStrVal();
686 if (Lex.Lex() != tgtok::less) // consume the Id.
687 return ParseIDValue(CurRec, Name, NameLoc); // Value ::= IDValue
688
689 // Value ::= ID '<' ValueListNE '>'
690 if (Lex.Lex() == tgtok::greater) {
691 TokError("expected non-empty value list");
692 return 0;
693 }
694 std::vector<Init*> ValueList = ParseValueList(CurRec);
695 if (ValueList.empty()) return 0;
696
697 if (Lex.getCode() != tgtok::greater) {
698 TokError("expected '>' at end of value list");
699 return 0;
700 }
701 Lex.Lex(); // eat the '>'
702
703 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
704 // a new anonymous definition, deriving from CLASS<initvalslist> with no
705 // body.
706 Record *Class = Records.getClass(Name);
707 if (!Class) {
708 Error(NameLoc, "Expected a class name, got '" + Name + "'");
709 return 0;
710 }
711
712 // Create the new record, set it as CurRec temporarily.
713 static unsigned AnonCounter = 0;
Chris Lattner7b9ffe42009-03-13 16:09:24 +0000714 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),NameLoc);
Chris Lattnerf4601652007-11-22 20:49:04 +0000715 SubClassReference SCRef;
716 SCRef.RefLoc = NameLoc;
717 SCRef.Rec = Class;
718 SCRef.TemplateArgs = ValueList;
719 // Add info about the subclass to NewRec.
720 if (AddSubClass(NewRec, SCRef))
721 return 0;
722 NewRec->resolveReferences();
723 Records.addDef(NewRec);
724
725 // The result of the expression is a reference to the new record.
726 return new DefInit(NewRec);
727 }
728 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
Chris Lattner1c8ae592009-03-13 16:01:53 +0000729 TGLoc BraceLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +0000730 Lex.Lex(); // eat the '{'
731 std::vector<Init*> Vals;
732
733 if (Lex.getCode() != tgtok::r_brace) {
734 Vals = ParseValueList(CurRec);
735 if (Vals.empty()) return 0;
736 }
737 if (Lex.getCode() != tgtok::r_brace) {
738 TokError("expected '}' at end of bit list value");
739 return 0;
740 }
741 Lex.Lex(); // eat the '}'
742
743 BitsInit *Result = new BitsInit(Vals.size());
744 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
745 Init *Bit = Vals[i]->convertInitializerTo(new BitRecTy());
746 if (Bit == 0) {
Chris Lattner5d814862007-11-22 21:06:59 +0000747 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
748 ") is not convertable to a bit");
Chris Lattnerf4601652007-11-22 20:49:04 +0000749 return 0;
750 }
751 Result->setBit(Vals.size()-i-1, Bit);
752 }
753 return Result;
754 }
755 case tgtok::l_square: { // Value ::= '[' ValueList ']'
756 Lex.Lex(); // eat the '['
757 std::vector<Init*> Vals;
758
759 if (Lex.getCode() != tgtok::r_square) {
760 Vals = ParseValueList(CurRec);
761 if (Vals.empty()) return 0;
762 }
763 if (Lex.getCode() != tgtok::r_square) {
764 TokError("expected ']' at end of list value");
765 return 0;
766 }
767 Lex.Lex(); // eat the ']'
768 return new ListInit(Vals);
769 }
770 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
771 Lex.Lex(); // eat the '('
David Greenec7cafcd2009-04-22 20:18:10 +0000772 if (Lex.getCode() != tgtok::Id
773 && Lex.getCode() != tgtok::XNameConcat) {
Chris Lattner3dc2e962008-04-10 04:48:34 +0000774 TokError("expected identifier in dag init");
775 return 0;
776 }
777
David Greenec7cafcd2009-04-22 20:18:10 +0000778 Init *Operator = 0;
779 if (Lex.getCode() == tgtok::Id) {
780 Operator = ParseIDValue(CurRec);
781 if (Operator == 0) return 0;
782 }
783 else {
784 BinOpInit::BinaryOp Code = BinOpInit::NAMECONCAT;
785
786 Lex.Lex(); // eat the operation
David Greenee8cf21e2009-04-23 21:25:15 +0000787
788 if (Lex.getCode() != tgtok::less) {
789 TokError("expected type name for nameconcat");
790 return 0;
791 }
792 Lex.Lex(); // eat the <
793
794 RecTy *Type = ParseType();
795
796 if (Type == 0) {
797 TokError("expected type name for nameconcat");
798 return 0;
799 }
800
801 if (Lex.getCode() != tgtok::greater) {
802 TokError("expected type name for nameconcat");
803 return 0;
804 }
805 Lex.Lex(); // eat the >
806
David Greenec7cafcd2009-04-22 20:18:10 +0000807 if (Lex.getCode() != tgtok::l_paren) {
808 TokError("expected '(' after binary operator");
809 return 0;
810 }
811 Lex.Lex(); // eat the '('
812
813 Init *LHS = ParseValue(CurRec);
814 if (LHS == 0) return 0;
815
816 if (Lex.getCode() != tgtok::comma) {
817 TokError("expected ',' in binary operator");
818 return 0;
819 }
820 Lex.Lex(); // eat the ','
821
822 Init *RHS = ParseValue(CurRec);
823 if (RHS == 0) return 0;
824
825 if (Lex.getCode() != tgtok::r_paren) {
826 TokError("expected ')' in binary operator");
827 return 0;
828 }
829 Lex.Lex(); // eat the ')'
David Greenee8cf21e2009-04-23 21:25:15 +0000830 Operator = (new BinOpInit(Code, LHS, RHS, Type))->Fold(CurRec, CurMultiClass);
David Greenec7cafcd2009-04-22 20:18:10 +0000831 }
832
Nate Begeman7cee8172009-03-19 05:21:56 +0000833 // If the operator name is present, parse it.
834 std::string OperatorName;
835 if (Lex.getCode() == tgtok::colon) {
836 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
837 TokError("expected variable name in dag operator");
838 return 0;
839 }
840 OperatorName = Lex.getCurStrVal();
841 Lex.Lex(); // eat the VarName.
842 }
843
Chris Lattnerf4601652007-11-22 20:49:04 +0000844 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
845 if (Lex.getCode() != tgtok::r_paren) {
846 DagArgs = ParseDagArgList(CurRec);
847 if (DagArgs.empty()) return 0;
848 }
849
850 if (Lex.getCode() != tgtok::r_paren) {
851 TokError("expected ')' in dag init");
852 return 0;
853 }
854 Lex.Lex(); // eat the ')'
855
Nate Begeman7cee8172009-03-19 05:21:56 +0000856 return new DagInit(Operator, OperatorName, DagArgs);
Chris Lattnerf4601652007-11-22 20:49:04 +0000857 }
858 case tgtok::XConcat:
859 case tgtok::XSRA:
860 case tgtok::XSRL:
861 case tgtok::XSHL:
David Greenec7cafcd2009-04-22 20:18:10 +0000862 case tgtok::XStrConcat:
863 case tgtok::XNameConcat: { // Value ::= !binop '(' Value ',' Value ')'
Chris Lattnerf4601652007-11-22 20:49:04 +0000864 BinOpInit::BinaryOp Code;
David Greenee8cf21e2009-04-23 21:25:15 +0000865 RecTy *Type = 0;
866
867
Chris Lattnerf4601652007-11-22 20:49:04 +0000868 switch (Lex.getCode()) {
869 default: assert(0 && "Unhandled code!");
David Greenee8cf21e2009-04-23 21:25:15 +0000870 case tgtok::XConcat:
871 Lex.Lex(); // eat the operation
872 Code = BinOpInit::CONCAT;
873 Type = new DagRecTy();
874 break;
875 case tgtok::XSRA:
876 Lex.Lex(); // eat the operation
877 Code = BinOpInit::SRA;
878 Type = new IntRecTy();
879 break;
880 case tgtok::XSRL:
881 Lex.Lex(); // eat the operation
882 Code = BinOpInit::SRL;
883 Type = new IntRecTy();
884 break;
885 case tgtok::XSHL:
886 Lex.Lex(); // eat the operation
887 Code = BinOpInit::SHL;
888 Type = new IntRecTy();
889 break;
890 case tgtok::XStrConcat:
891 Lex.Lex(); // eat the operation
892 Code = BinOpInit::STRCONCAT;
893 Type = new StringRecTy();
894 break;
895 case tgtok::XNameConcat:
896 Lex.Lex(); // eat the operation
897 Code = BinOpInit::NAMECONCAT;
898 if (Lex.getCode() != tgtok::less) {
899 TokError("expected type name for nameconcat");
900 return 0;
901 }
902 Lex.Lex(); // eat the <
903
904 Type = ParseType();
905
906 if (Type == 0) {
907 TokError("expected type name for nameconcat");
908 return 0;
909 }
910
911 if (Lex.getCode() != tgtok::greater) {
912 TokError("expected type name for nameconcat");
913 return 0;
914 }
915 Lex.Lex(); // eat the >
916 break;
Chris Lattnerf4601652007-11-22 20:49:04 +0000917 }
Chris Lattnerf4601652007-11-22 20:49:04 +0000918 if (Lex.getCode() != tgtok::l_paren) {
919 TokError("expected '(' after binary operator");
920 return 0;
921 }
922 Lex.Lex(); // eat the '('
David Greenec7cafcd2009-04-22 20:18:10 +0000923
Chris Lattnerf4601652007-11-22 20:49:04 +0000924 Init *LHS = ParseValue(CurRec);
925 if (LHS == 0) return 0;
926
927 if (Lex.getCode() != tgtok::comma) {
928 TokError("expected ',' in binary operator");
929 return 0;
930 }
931 Lex.Lex(); // eat the ','
932
933 Init *RHS = ParseValue(CurRec);
934 if (RHS == 0) return 0;
935
936 if (Lex.getCode() != tgtok::r_paren) {
937 TokError("expected ')' in binary operator");
938 return 0;
939 }
940 Lex.Lex(); // eat the ')'
David Greenee8cf21e2009-04-23 21:25:15 +0000941 return (new BinOpInit(Code, LHS, RHS, Type))->Fold(CurRec, CurMultiClass);
Chris Lattnerf4601652007-11-22 20:49:04 +0000942 }
943 }
944
945 return R;
946}
947
948/// ParseValue - Parse a tblgen value. This returns null on error.
949///
950/// Value ::= SimpleValue ValueSuffix*
951/// ValueSuffix ::= '{' BitList '}'
952/// ValueSuffix ::= '[' BitList ']'
953/// ValueSuffix ::= '.' ID
954///
955Init *TGParser::ParseValue(Record *CurRec) {
956 Init *Result = ParseSimpleValue(CurRec);
957 if (Result == 0) return 0;
958
959 // Parse the suffixes now if present.
960 while (1) {
961 switch (Lex.getCode()) {
962 default: return Result;
963 case tgtok::l_brace: {
Chris Lattner1c8ae592009-03-13 16:01:53 +0000964 TGLoc CurlyLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +0000965 Lex.Lex(); // eat the '{'
966 std::vector<unsigned> Ranges = ParseRangeList();
967 if (Ranges.empty()) return 0;
968
969 // Reverse the bitlist.
970 std::reverse(Ranges.begin(), Ranges.end());
971 Result = Result->convertInitializerBitRange(Ranges);
972 if (Result == 0) {
973 Error(CurlyLoc, "Invalid bit range for value");
974 return 0;
975 }
976
977 // Eat the '}'.
978 if (Lex.getCode() != tgtok::r_brace) {
979 TokError("expected '}' at end of bit range list");
980 return 0;
981 }
982 Lex.Lex();
983 break;
984 }
985 case tgtok::l_square: {
Chris Lattner1c8ae592009-03-13 16:01:53 +0000986 TGLoc SquareLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +0000987 Lex.Lex(); // eat the '['
988 std::vector<unsigned> Ranges = ParseRangeList();
989 if (Ranges.empty()) return 0;
990
991 Result = Result->convertInitListSlice(Ranges);
992 if (Result == 0) {
993 Error(SquareLoc, "Invalid range for list slice");
994 return 0;
995 }
996
997 // Eat the ']'.
998 if (Lex.getCode() != tgtok::r_square) {
999 TokError("expected ']' at end of list slice");
1000 return 0;
1001 }
1002 Lex.Lex();
1003 break;
1004 }
1005 case tgtok::period:
1006 if (Lex.Lex() != tgtok::Id) { // eat the .
1007 TokError("expected field identifier after '.'");
1008 return 0;
1009 }
1010 if (!Result->getFieldType(Lex.getCurStrVal())) {
Chris Lattnerf4601652007-11-22 20:49:04 +00001011 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
Chris Lattner5d814862007-11-22 21:06:59 +00001012 Result->getAsString() + "'");
Chris Lattnerf4601652007-11-22 20:49:04 +00001013 return 0;
1014 }
1015 Result = new FieldInit(Result, Lex.getCurStrVal());
1016 Lex.Lex(); // eat field name
1017 break;
1018 }
1019 }
1020}
1021
1022/// ParseDagArgList - Parse the argument list for a dag literal expression.
1023///
1024/// ParseDagArgList ::= Value (':' VARNAME)?
1025/// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1026std::vector<std::pair<llvm::Init*, std::string> >
1027TGParser::ParseDagArgList(Record *CurRec) {
1028 std::vector<std::pair<llvm::Init*, std::string> > Result;
1029
1030 while (1) {
1031 Init *Val = ParseValue(CurRec);
1032 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1033
1034 // If the variable name is present, add it.
1035 std::string VarName;
1036 if (Lex.getCode() == tgtok::colon) {
1037 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1038 TokError("expected variable name in dag literal");
1039 return std::vector<std::pair<llvm::Init*, std::string> >();
1040 }
1041 VarName = Lex.getCurStrVal();
1042 Lex.Lex(); // eat the VarName.
1043 }
1044
1045 Result.push_back(std::make_pair(Val, VarName));
1046
1047 if (Lex.getCode() != tgtok::comma) break;
1048 Lex.Lex(); // eat the ','
1049 }
1050
1051 return Result;
1052}
1053
1054
1055/// ParseValueList - Parse a comma separated list of values, returning them as a
1056/// vector. Note that this always expects to be able to parse at least one
1057/// value. It returns an empty list if this is not possible.
1058///
1059/// ValueList ::= Value (',' Value)
1060///
1061std::vector<Init*> TGParser::ParseValueList(Record *CurRec) {
1062 std::vector<Init*> Result;
1063 Result.push_back(ParseValue(CurRec));
1064 if (Result.back() == 0) return std::vector<Init*>();
1065
1066 while (Lex.getCode() == tgtok::comma) {
1067 Lex.Lex(); // Eat the comma
1068
1069 Result.push_back(ParseValue(CurRec));
1070 if (Result.back() == 0) return std::vector<Init*>();
1071 }
1072
1073 return Result;
1074}
1075
1076
1077
1078/// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1079/// empty string on error. This can happen in a number of different context's,
1080/// including within a def or in the template args for a def (which which case
1081/// CurRec will be non-null) and within the template args for a multiclass (in
1082/// which case CurRec will be null, but CurMultiClass will be set). This can
1083/// also happen within a def that is within a multiclass, which will set both
1084/// CurRec and CurMultiClass.
1085///
1086/// Declaration ::= FIELD? Type ID ('=' Value)?
1087///
1088std::string TGParser::ParseDeclaration(Record *CurRec,
1089 bool ParsingTemplateArgs) {
1090 // Read the field prefix if present.
1091 bool HasField = Lex.getCode() == tgtok::Field;
1092 if (HasField) Lex.Lex();
1093
1094 RecTy *Type = ParseType();
1095 if (Type == 0) return "";
1096
1097 if (Lex.getCode() != tgtok::Id) {
1098 TokError("Expected identifier in declaration");
1099 return "";
1100 }
1101
Chris Lattner1c8ae592009-03-13 16:01:53 +00001102 TGLoc IdLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +00001103 std::string DeclName = Lex.getCurStrVal();
1104 Lex.Lex();
1105
1106 if (ParsingTemplateArgs) {
1107 if (CurRec) {
1108 DeclName = CurRec->getName() + ":" + DeclName;
1109 } else {
1110 assert(CurMultiClass);
1111 }
1112 if (CurMultiClass)
1113 DeclName = CurMultiClass->Rec.getName() + "::" + DeclName;
1114 }
1115
1116 // Add the value.
1117 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1118 return "";
1119
1120 // If a value is present, parse it.
1121 if (Lex.getCode() == tgtok::equal) {
1122 Lex.Lex();
Chris Lattner1c8ae592009-03-13 16:01:53 +00001123 TGLoc ValLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +00001124 Init *Val = ParseValue(CurRec);
1125 if (Val == 0 ||
1126 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1127 return "";
1128 }
1129
1130 return DeclName;
1131}
1132
1133/// ParseTemplateArgList - Read a template argument list, which is a non-empty
1134/// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1135/// template args for a def, which may or may not be in a multiclass. If null,
1136/// these are the template args for a multiclass.
1137///
1138/// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1139///
1140bool TGParser::ParseTemplateArgList(Record *CurRec) {
1141 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1142 Lex.Lex(); // eat the '<'
1143
1144 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1145
1146 // Read the first declaration.
1147 std::string TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1148 if (TemplArg.empty())
1149 return true;
1150
1151 TheRecToAddTo->addTemplateArg(TemplArg);
1152
1153 while (Lex.getCode() == tgtok::comma) {
1154 Lex.Lex(); // eat the ','
1155
1156 // Read the following declarations.
1157 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1158 if (TemplArg.empty())
1159 return true;
1160 TheRecToAddTo->addTemplateArg(TemplArg);
1161 }
1162
1163 if (Lex.getCode() != tgtok::greater)
1164 return TokError("expected '>' at end of template argument list");
1165 Lex.Lex(); // eat the '>'.
1166 return false;
1167}
1168
1169
1170/// ParseBodyItem - Parse a single item at within the body of a def or class.
1171///
1172/// BodyItem ::= Declaration ';'
1173/// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1174bool TGParser::ParseBodyItem(Record *CurRec) {
1175 if (Lex.getCode() != tgtok::Let) {
1176 if (ParseDeclaration(CurRec, false).empty())
1177 return true;
1178
1179 if (Lex.getCode() != tgtok::semi)
1180 return TokError("expected ';' after declaration");
1181 Lex.Lex();
1182 return false;
1183 }
1184
1185 // LET ID OptionalRangeList '=' Value ';'
1186 if (Lex.Lex() != tgtok::Id)
1187 return TokError("expected field identifier after let");
1188
Chris Lattner1c8ae592009-03-13 16:01:53 +00001189 TGLoc IdLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +00001190 std::string FieldName = Lex.getCurStrVal();
1191 Lex.Lex(); // eat the field name.
1192
1193 std::vector<unsigned> BitList;
1194 if (ParseOptionalBitList(BitList))
1195 return true;
1196 std::reverse(BitList.begin(), BitList.end());
1197
1198 if (Lex.getCode() != tgtok::equal)
1199 return TokError("expected '=' in let expression");
1200 Lex.Lex(); // eat the '='.
1201
1202 Init *Val = ParseValue(CurRec);
1203 if (Val == 0) return true;
1204
1205 if (Lex.getCode() != tgtok::semi)
1206 return TokError("expected ';' after let expression");
1207 Lex.Lex();
1208
1209 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1210}
1211
1212/// ParseBody - Read the body of a class or def. Return true on error, false on
1213/// success.
1214///
1215/// Body ::= ';'
1216/// Body ::= '{' BodyList '}'
1217/// BodyList BodyItem*
1218///
1219bool TGParser::ParseBody(Record *CurRec) {
1220 // If this is a null definition, just eat the semi and return.
1221 if (Lex.getCode() == tgtok::semi) {
1222 Lex.Lex();
1223 return false;
1224 }
1225
1226 if (Lex.getCode() != tgtok::l_brace)
1227 return TokError("Expected ';' or '{' to start body");
1228 // Eat the '{'.
1229 Lex.Lex();
1230
1231 while (Lex.getCode() != tgtok::r_brace)
1232 if (ParseBodyItem(CurRec))
1233 return true;
1234
1235 // Eat the '}'.
1236 Lex.Lex();
1237 return false;
1238}
1239
1240/// ParseObjectBody - Parse the body of a def or class. This consists of an
1241/// optional ClassList followed by a Body. CurRec is the current def or class
1242/// that is being parsed.
1243///
1244/// ObjectBody ::= BaseClassList Body
1245/// BaseClassList ::= /*empty*/
1246/// BaseClassList ::= ':' BaseClassListNE
1247/// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1248///
1249bool TGParser::ParseObjectBody(Record *CurRec) {
1250 // If there is a baseclass list, read it.
1251 if (Lex.getCode() == tgtok::colon) {
1252 Lex.Lex();
1253
1254 // Read all of the subclasses.
1255 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1256 while (1) {
1257 // Check for error.
1258 if (SubClass.Rec == 0) return true;
1259
1260 // Add it.
1261 if (AddSubClass(CurRec, SubClass))
1262 return true;
1263
1264 if (Lex.getCode() != tgtok::comma) break;
1265 Lex.Lex(); // eat ','.
1266 SubClass = ParseSubClassReference(CurRec, false);
1267 }
1268 }
1269
1270 // Process any variables on the let stack.
1271 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1272 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1273 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1274 LetStack[i][j].Bits, LetStack[i][j].Value))
1275 return true;
1276
1277 return ParseBody(CurRec);
1278}
1279
1280
1281/// ParseDef - Parse and return a top level or multiclass def, return the record
1282/// corresponding to it. This returns null on error.
1283///
1284/// DefInst ::= DEF ObjectName ObjectBody
1285///
1286llvm::Record *TGParser::ParseDef(MultiClass *CurMultiClass) {
Chris Lattner1c8ae592009-03-13 16:01:53 +00001287 TGLoc DefLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +00001288 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1289 Lex.Lex(); // Eat the 'def' token.
1290
1291 // Parse ObjectName and make a record for it.
Chris Lattner7b9ffe42009-03-13 16:09:24 +00001292 Record *CurRec = new Record(ParseObjectName(), DefLoc);
Chris Lattnerf4601652007-11-22 20:49:04 +00001293
1294 if (!CurMultiClass) {
1295 // Top-level def definition.
1296
1297 // Ensure redefinition doesn't happen.
1298 if (Records.getDef(CurRec->getName())) {
1299 Error(DefLoc, "def '" + CurRec->getName() + "' already defined");
1300 return 0;
1301 }
1302 Records.addDef(CurRec);
1303 } else {
1304 // Otherwise, a def inside a multiclass, add it to the multiclass.
1305 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1306 if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
1307 Error(DefLoc, "def '" + CurRec->getName() +
1308 "' already defined in this multiclass!");
1309 return 0;
1310 }
1311 CurMultiClass->DefPrototypes.push_back(CurRec);
1312 }
1313
1314 if (ParseObjectBody(CurRec))
1315 return 0;
1316
1317 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1318 CurRec->resolveReferences();
1319
1320 // If ObjectBody has template arguments, it's an error.
1321 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1322 return CurRec;
1323}
1324
1325
1326/// ParseClass - Parse a tblgen class definition.
1327///
1328/// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1329///
1330bool TGParser::ParseClass() {
1331 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1332 Lex.Lex();
1333
1334 if (Lex.getCode() != tgtok::Id)
1335 return TokError("expected class name after 'class' keyword");
1336
1337 Record *CurRec = Records.getClass(Lex.getCurStrVal());
1338 if (CurRec) {
1339 // If the body was previously defined, this is an error.
1340 if (!CurRec->getValues().empty() ||
1341 !CurRec->getSuperClasses().empty() ||
1342 !CurRec->getTemplateArgs().empty())
1343 return TokError("Class '" + CurRec->getName() + "' already defined");
1344 } else {
1345 // If this is the first reference to this class, create and add it.
Chris Lattner7b9ffe42009-03-13 16:09:24 +00001346 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc());
Chris Lattnerf4601652007-11-22 20:49:04 +00001347 Records.addClass(CurRec);
1348 }
1349 Lex.Lex(); // eat the name.
1350
1351 // If there are template args, parse them.
1352 if (Lex.getCode() == tgtok::less)
1353 if (ParseTemplateArgList(CurRec))
1354 return true;
1355
1356 // Finally, parse the object body.
1357 return ParseObjectBody(CurRec);
1358}
1359
1360/// ParseLetList - Parse a non-empty list of assignment expressions into a list
1361/// of LetRecords.
1362///
1363/// LetList ::= LetItem (',' LetItem)*
1364/// LetItem ::= ID OptionalRangeList '=' Value
1365///
1366std::vector<LetRecord> TGParser::ParseLetList() {
1367 std::vector<LetRecord> Result;
1368
1369 while (1) {
1370 if (Lex.getCode() != tgtok::Id) {
1371 TokError("expected identifier in let definition");
1372 return std::vector<LetRecord>();
1373 }
1374 std::string Name = Lex.getCurStrVal();
Chris Lattner1c8ae592009-03-13 16:01:53 +00001375 TGLoc NameLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +00001376 Lex.Lex(); // Eat the identifier.
1377
1378 // Check for an optional RangeList.
1379 std::vector<unsigned> Bits;
1380 if (ParseOptionalRangeList(Bits))
1381 return std::vector<LetRecord>();
1382 std::reverse(Bits.begin(), Bits.end());
1383
1384 if (Lex.getCode() != tgtok::equal) {
1385 TokError("expected '=' in let expression");
1386 return std::vector<LetRecord>();
1387 }
1388 Lex.Lex(); // eat the '='.
1389
1390 Init *Val = ParseValue(0);
1391 if (Val == 0) return std::vector<LetRecord>();
1392
1393 // Now that we have everything, add the record.
1394 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1395
1396 if (Lex.getCode() != tgtok::comma)
1397 return Result;
1398 Lex.Lex(); // eat the comma.
1399 }
1400}
1401
1402/// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
1403/// different related productions.
1404///
1405/// Object ::= LET LetList IN '{' ObjectList '}'
1406/// Object ::= LET LetList IN Object
1407///
1408bool TGParser::ParseTopLevelLet() {
1409 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1410 Lex.Lex();
1411
1412 // Add this entry to the let stack.
1413 std::vector<LetRecord> LetInfo = ParseLetList();
1414 if (LetInfo.empty()) return true;
1415 LetStack.push_back(LetInfo);
1416
1417 if (Lex.getCode() != tgtok::In)
1418 return TokError("expected 'in' at end of top-level 'let'");
1419 Lex.Lex();
1420
1421 // If this is a scalar let, just handle it now
1422 if (Lex.getCode() != tgtok::l_brace) {
1423 // LET LetList IN Object
1424 if (ParseObject())
1425 return true;
1426 } else { // Object ::= LETCommand '{' ObjectList '}'
Chris Lattner1c8ae592009-03-13 16:01:53 +00001427 TGLoc BraceLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +00001428 // Otherwise, this is a group let.
1429 Lex.Lex(); // eat the '{'.
1430
1431 // Parse the object list.
1432 if (ParseObjectList())
1433 return true;
1434
1435 if (Lex.getCode() != tgtok::r_brace) {
1436 TokError("expected '}' at end of top level let command");
1437 return Error(BraceLoc, "to match this '{'");
1438 }
1439 Lex.Lex();
1440 }
1441
1442 // Outside this let scope, this let block is not active.
1443 LetStack.pop_back();
1444 return false;
1445}
1446
1447/// ParseMultiClassDef - Parse a def in a multiclass context.
1448///
1449/// MultiClassDef ::= DefInst
1450///
1451bool TGParser::ParseMultiClassDef(MultiClass *CurMC) {
1452 if (Lex.getCode() != tgtok::Def)
1453 return TokError("expected 'def' in multiclass body");
1454
1455 Record *D = ParseDef(CurMC);
1456 if (D == 0) return true;
1457
1458 // Copy the template arguments for the multiclass into the def.
1459 const std::vector<std::string> &TArgs = CurMC->Rec.getTemplateArgs();
1460
1461 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1462 const RecordVal *RV = CurMC->Rec.getValue(TArgs[i]);
1463 assert(RV && "Template arg doesn't exist?");
1464 D->addValue(*RV);
1465 }
1466
1467 return false;
1468}
1469
1470/// ParseMultiClass - Parse a multiclass definition.
1471///
David Greenede444af2009-04-22 16:42:54 +00001472/// MultiClassInst ::= MULTICLASS ID TemplateArgList? ':' BaseMultiClassList '{' MultiClassDef+ '}'
Chris Lattnerf4601652007-11-22 20:49:04 +00001473///
1474bool TGParser::ParseMultiClass() {
1475 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1476 Lex.Lex(); // Eat the multiclass token.
1477
1478 if (Lex.getCode() != tgtok::Id)
1479 return TokError("expected identifier after multiclass for name");
1480 std::string Name = Lex.getCurStrVal();
1481
1482 if (MultiClasses.count(Name))
1483 return TokError("multiclass '" + Name + "' already defined");
1484
Chris Lattner7b9ffe42009-03-13 16:09:24 +00001485 CurMultiClass = MultiClasses[Name] = new MultiClass(Name, Lex.getLoc());
Chris Lattnerf4601652007-11-22 20:49:04 +00001486 Lex.Lex(); // Eat the identifier.
1487
1488 // If there are template args, parse them.
1489 if (Lex.getCode() == tgtok::less)
1490 if (ParseTemplateArgList(0))
1491 return true;
1492
David Greenede444af2009-04-22 16:42:54 +00001493 // If there are submulticlasses, parse them.
1494 if (Lex.getCode() == tgtok::colon) {
1495 Lex.Lex();
1496
1497 // Read all of the submulticlasses.
1498 SubMultiClassReference SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
1499 while (1) {
1500 // Check for error.
1501 if (SubMultiClass.MC == 0) return true;
1502
1503 // Add it.
1504 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
1505 return true;
1506
1507 if (Lex.getCode() != tgtok::comma) break;
1508 Lex.Lex(); // eat ','.
1509 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
1510 }
1511 }
1512
Chris Lattnerf4601652007-11-22 20:49:04 +00001513 if (Lex.getCode() != tgtok::l_brace)
1514 return TokError("expected '{' in multiclass definition");
1515
1516 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
1517 return TokError("multiclass must contain at least one def");
1518
1519 while (Lex.getCode() != tgtok::r_brace)
1520 if (ParseMultiClassDef(CurMultiClass))
1521 return true;
1522
1523 Lex.Lex(); // eat the '}'.
1524
1525 CurMultiClass = 0;
1526 return false;
1527}
1528
1529/// ParseDefm - Parse the instantiation of a multiclass.
1530///
1531/// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
1532///
1533bool TGParser::ParseDefm() {
1534 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
1535 if (Lex.Lex() != tgtok::Id) // eat the defm.
1536 return TokError("expected identifier after defm");
1537
Chris Lattner1c8ae592009-03-13 16:01:53 +00001538 TGLoc DefmPrefixLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +00001539 std::string DefmPrefix = Lex.getCurStrVal();
1540 if (Lex.Lex() != tgtok::colon)
1541 return TokError("expected ':' after defm identifier");
1542
1543 // eat the colon.
1544 Lex.Lex();
1545
Chris Lattner1c8ae592009-03-13 16:01:53 +00001546 TGLoc SubClassLoc = Lex.getLoc();
Chris Lattnerf4601652007-11-22 20:49:04 +00001547 SubClassReference Ref = ParseSubClassReference(0, true);
David Greene56546132009-04-22 22:17:51 +00001548
1549 while (1) {
1550 if (Ref.Rec == 0) return true;
1551
1552 // To instantiate a multiclass, we need to first get the multiclass, then
1553 // instantiate each def contained in the multiclass with the SubClassRef
1554 // template parameters.
1555 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
1556 assert(MC && "Didn't lookup multiclass correctly?");
1557 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
1558
1559 // Verify that the correct number of template arguments were specified.
1560 const std::vector<std::string> &TArgs = MC->Rec.getTemplateArgs();
1561 if (TArgs.size() < TemplateVals.size())
1562 return Error(SubClassLoc,
1563 "more template args specified than multiclass expects");
1564
1565 // Loop over all the def's in the multiclass, instantiating each one.
1566 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
1567 Record *DefProto = MC->DefPrototypes[i];
1568
1569 // Add the suffix to the defm name to get the new name.
1570 Record *CurRec = new Record(DefmPrefix + DefProto->getName(), DefmPrefixLoc);
1571
1572 SubClassReference Ref;
1573 Ref.RefLoc = DefmPrefixLoc;
1574 Ref.Rec = DefProto;
1575 AddSubClass(CurRec, Ref);
1576
1577 // Loop over all of the template arguments, setting them to the specified
1578 // value or leaving them as the default if necessary.
1579 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1580 if (i < TemplateVals.size()) { // A value is specified for this temp-arg?
1581 // Set it now.
1582 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
1583 TemplateVals[i]))
1584 return true;
1585
1586 // Resolve it next.
1587 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
1588
1589 // Now remove it.
1590 CurRec->removeValue(TArgs[i]);
1591
1592 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
1593 return Error(SubClassLoc, "value not specified for template argument #"+
1594 utostr(i) + " (" + TArgs[i] + ") of multiclassclass '" +
1595 MC->Rec.getName() + "'");
1596 }
1597 }
1598
1599 // If the mdef is inside a 'let' expression, add to each def.
1600 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1601 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1602 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1603 LetStack[i][j].Bits, LetStack[i][j].Value)) {
1604 Error(DefmPrefixLoc, "when instantiating this defm");
1605 return true;
1606 }
1607
1608 // Ensure redefinition doesn't happen.
1609 if (Records.getDef(CurRec->getName()))
1610 return Error(DefmPrefixLoc, "def '" + CurRec->getName() +
1611 "' already defined, instantiating defm with subdef '" +
1612 DefProto->getName() + "'");
1613 Records.addDef(CurRec);
1614 CurRec->resolveReferences();
1615 }
1616
1617 if (Lex.getCode() != tgtok::comma) break;
1618 Lex.Lex(); // eat ','.
1619
1620 SubClassLoc = Lex.getLoc();
1621 Ref = ParseSubClassReference(0, true);
1622 }
1623
Chris Lattnerf4601652007-11-22 20:49:04 +00001624 if (Lex.getCode() != tgtok::semi)
1625 return TokError("expected ';' at end of defm");
1626 Lex.Lex();
1627
Chris Lattnerf4601652007-11-22 20:49:04 +00001628 return false;
1629}
1630
1631/// ParseObject
1632/// Object ::= ClassInst
1633/// Object ::= DefInst
1634/// Object ::= MultiClassInst
1635/// Object ::= DefMInst
1636/// Object ::= LETCommand '{' ObjectList '}'
1637/// Object ::= LETCommand Object
1638bool TGParser::ParseObject() {
1639 switch (Lex.getCode()) {
1640 default: assert(0 && "This is not an object");
1641 case tgtok::Let: return ParseTopLevelLet();
1642 case tgtok::Def: return ParseDef(0) == 0;
1643 case tgtok::Defm: return ParseDefm();
1644 case tgtok::Class: return ParseClass();
1645 case tgtok::MultiClass: return ParseMultiClass();
1646 }
1647}
1648
1649/// ParseObjectList
1650/// ObjectList :== Object*
1651bool TGParser::ParseObjectList() {
1652 while (isObjectStart(Lex.getCode())) {
1653 if (ParseObject())
1654 return true;
1655 }
1656 return false;
1657}
1658
1659
1660bool TGParser::ParseFile() {
1661 Lex.Lex(); // Prime the lexer.
1662 if (ParseObjectList()) return true;
1663
1664 // If we have unread input at the end of the file, report it.
1665 if (Lex.getCode() == tgtok::Eof)
1666 return false;
1667
1668 return TokError("Unexpected input at top level");
1669}
1670