1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Implement the Parser for TableGen.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "TGParser.h"
14 #include "llvm/ADT/None.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Config/llvm-config.h"
20 #include "llvm/Support/Casting.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include <algorithm>
26 #include <cassert>
27 #include <cstdint>
28
29 using namespace llvm;
30
31 //===----------------------------------------------------------------------===//
32 // Support Code for the Semantic Actions.
33 //===----------------------------------------------------------------------===//
34
35 namespace llvm {
36
37 struct SubClassReference {
38 SMRange RefRange;
39 Record *Rec;
40 SmallVector<Init*, 4> TemplateArgs;
41
SubClassReferencellvm::SubClassReference42 SubClassReference() : Rec(nullptr) {}
43
isInvalidllvm::SubClassReference44 bool isInvalid() const { return Rec == nullptr; }
45 };
46
47 struct SubMultiClassReference {
48 SMRange RefRange;
49 MultiClass *MC;
50 SmallVector<Init*, 4> TemplateArgs;
51
SubMultiClassReferencellvm::SubMultiClassReference52 SubMultiClassReference() : MC(nullptr) {}
53
isInvalidllvm::SubMultiClassReference54 bool isInvalid() const { return MC == nullptr; }
55 void dump() const;
56 };
57
58 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const59 LLVM_DUMP_METHOD void SubMultiClassReference::dump() const {
60 errs() << "Multiclass:\n";
61
62 MC->dump();
63
64 errs() << "Template args:\n";
65 for (Init *TA : TemplateArgs)
66 TA->dump();
67 }
68 #endif
69
70 } // end namespace llvm
71
checkBitsConcrete(Record & R,const RecordVal & RV)72 static bool checkBitsConcrete(Record &R, const RecordVal &RV) {
73 BitsInit *BV = cast<BitsInit>(RV.getValue());
74 for (unsigned i = 0, e = BV->getNumBits(); i != e; ++i) {
75 Init *Bit = BV->getBit(i);
76 bool IsReference = false;
77 if (auto VBI = dyn_cast<VarBitInit>(Bit)) {
78 if (auto VI = dyn_cast<VarInit>(VBI->getBitVar())) {
79 if (R.getValue(VI->getName()))
80 IsReference = true;
81 }
82 } else if (isa<VarInit>(Bit)) {
83 IsReference = true;
84 }
85 if (!(IsReference || Bit->isConcrete()))
86 return false;
87 }
88 return true;
89 }
90
checkConcrete(Record & R)91 static void checkConcrete(Record &R) {
92 for (const RecordVal &RV : R.getValues()) {
93 // HACK: Disable this check for variables declared with 'field'. This is
94 // done merely because existing targets have legitimate cases of
95 // non-concrete variables in helper defs. Ideally, we'd introduce a
96 // 'maybe' or 'optional' modifier instead of this.
97 if (RV.getPrefix())
98 continue;
99
100 if (Init *V = RV.getValue()) {
101 bool Ok = isa<BitsInit>(V) ? checkBitsConcrete(R, RV) : V->isConcrete();
102 if (!Ok) {
103 PrintError(R.getLoc(),
104 Twine("Initializer of '") + RV.getNameInitAsString() +
105 "' in '" + R.getNameInitAsString() +
106 "' could not be fully resolved: " +
107 RV.getValue()->getAsString());
108 }
109 }
110 }
111 }
112
113 /// Return an Init with a qualifier prefix referring
114 /// to CurRec's name.
QualifyName(Record & CurRec,MultiClass * CurMultiClass,Init * Name,StringRef Scoper)115 static Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass,
116 Init *Name, StringRef Scoper) {
117 Init *NewName =
118 BinOpInit::getStrConcat(CurRec.getNameInit(), StringInit::get(Scoper));
119 NewName = BinOpInit::getStrConcat(NewName, Name);
120 if (CurMultiClass && Scoper != "::") {
121 Init *Prefix = BinOpInit::getStrConcat(CurMultiClass->Rec.getNameInit(),
122 StringInit::get("::"));
123 NewName = BinOpInit::getStrConcat(Prefix, NewName);
124 }
125
126 if (BinOpInit *BinOp = dyn_cast<BinOpInit>(NewName))
127 NewName = BinOp->Fold(&CurRec);
128 return NewName;
129 }
130
131 /// Return the qualified version of the implicit 'NAME' template argument.
QualifiedNameOfImplicitName(Record & Rec,MultiClass * MC=nullptr)132 static Init *QualifiedNameOfImplicitName(Record &Rec,
133 MultiClass *MC = nullptr) {
134 return QualifyName(Rec, MC, StringInit::get("NAME"), MC ? "::" : ":");
135 }
136
QualifiedNameOfImplicitName(MultiClass * MC)137 static Init *QualifiedNameOfImplicitName(MultiClass *MC) {
138 return QualifiedNameOfImplicitName(MC->Rec, MC);
139 }
140
AddValue(Record * CurRec,SMLoc Loc,const RecordVal & RV)141 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
142 if (!CurRec)
143 CurRec = &CurMultiClass->Rec;
144
145 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
146 // The value already exists in the class, treat this as a set.
147 if (ERV->setValue(RV.getValue()))
148 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
149 RV.getType()->getAsString() + "' is incompatible with " +
150 "previous definition of type '" +
151 ERV->getType()->getAsString() + "'");
152 } else {
153 CurRec->addValue(RV);
154 }
155 return false;
156 }
157
158 /// SetValue -
159 /// Return true on error, false on success.
SetValue(Record * CurRec,SMLoc Loc,Init * ValName,ArrayRef<unsigned> BitList,Init * V,bool AllowSelfAssignment)160 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
161 ArrayRef<unsigned> BitList, Init *V,
162 bool AllowSelfAssignment) {
163 if (!V) return false;
164
165 if (!CurRec) CurRec = &CurMultiClass->Rec;
166
167 RecordVal *RV = CurRec->getValue(ValName);
168 if (!RV)
169 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
170 "' unknown!");
171
172 // Do not allow assignments like 'X = X'. This will just cause infinite loops
173 // in the resolution machinery.
174 if (BitList.empty())
175 if (VarInit *VI = dyn_cast<VarInit>(V))
176 if (VI->getNameInit() == ValName && !AllowSelfAssignment)
177 return Error(Loc, "Recursion / self-assignment forbidden");
178
179 // If we are assigning to a subset of the bits in the value... then we must be
180 // assigning to a field of BitsRecTy, which must have a BitsInit
181 // initializer.
182 //
183 if (!BitList.empty()) {
184 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
185 if (!CurVal)
186 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
187 "' is not a bits type");
188
189 // Convert the incoming value to a bits type of the appropriate size...
190 Init *BI = V->getCastTo(BitsRecTy::get(BitList.size()));
191 if (!BI)
192 return Error(Loc, "Initializer is not compatible with bit range");
193
194 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
195
196 // Loop over bits, assigning values as appropriate.
197 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
198 unsigned Bit = BitList[i];
199 if (NewBits[Bit])
200 return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" +
201 ValName->getAsUnquotedString() + "' more than once");
202 NewBits[Bit] = BI->getBit(i);
203 }
204
205 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
206 if (!NewBits[i])
207 NewBits[i] = CurVal->getBit(i);
208
209 V = BitsInit::get(NewBits);
210 }
211
212 if (RV->setValue(V, Loc)) {
213 std::string InitType;
214 if (BitsInit *BI = dyn_cast<BitsInit>(V))
215 InitType = (Twine("' of type bit initializer with length ") +
216 Twine(BI->getNumBits())).str();
217 else if (TypedInit *TI = dyn_cast<TypedInit>(V))
218 InitType = (Twine("' of type '") + TI->getType()->getAsString()).str();
219 return Error(Loc, "Field '" + ValName->getAsUnquotedString() +
220 "' of type '" + RV->getType()->getAsString() +
221 "' is incompatible with value '" +
222 V->getAsString() + InitType + "'");
223 }
224 return false;
225 }
226
227 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
228 /// args as SubClass's template arguments.
AddSubClass(Record * CurRec,SubClassReference & SubClass)229 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
230 Record *SC = SubClass.Rec;
231 // Add all of the values in the subclass into the current class.
232 for (const RecordVal &Val : SC->getValues())
233 if (AddValue(CurRec, SubClass.RefRange.Start, Val))
234 return true;
235
236 ArrayRef<Init *> TArgs = SC->getTemplateArgs();
237
238 // Ensure that an appropriate number of template arguments are specified.
239 if (TArgs.size() < SubClass.TemplateArgs.size())
240 return Error(SubClass.RefRange.Start,
241 "More template args specified than expected");
242
243 // Loop over all of the template arguments, setting them to the specified
244 // value or leaving them as the default if necessary.
245 MapResolver R(CurRec);
246
247 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
248 if (i < SubClass.TemplateArgs.size()) {
249 // If a value is specified for this template arg, set it now.
250 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
251 None, SubClass.TemplateArgs[i]))
252 return true;
253 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
254 return Error(SubClass.RefRange.Start,
255 "Value not specified for template argument #" +
256 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
257 ") of subclass '" + SC->getNameInitAsString() + "'!");
258 }
259
260 R.set(TArgs[i], CurRec->getValue(TArgs[i])->getValue());
261
262 CurRec->removeValue(TArgs[i]);
263 }
264
265 Init *Name;
266 if (CurRec->isClass())
267 Name =
268 VarInit::get(QualifiedNameOfImplicitName(*CurRec), StringRecTy::get());
269 else
270 Name = CurRec->getNameInit();
271 R.set(QualifiedNameOfImplicitName(*SC), Name);
272
273 CurRec->resolveReferences(R);
274
275 // Since everything went well, we can now set the "superclass" list for the
276 // current record.
277 ArrayRef<std::pair<Record *, SMRange>> SCs = SC->getSuperClasses();
278 for (const auto &SCPair : SCs) {
279 if (CurRec->isSubClassOf(SCPair.first))
280 return Error(SubClass.RefRange.Start,
281 "Already subclass of '" + SCPair.first->getName() + "'!\n");
282 CurRec->addSuperClass(SCPair.first, SCPair.second);
283 }
284
285 if (CurRec->isSubClassOf(SC))
286 return Error(SubClass.RefRange.Start,
287 "Already subclass of '" + SC->getName() + "'!\n");
288 CurRec->addSuperClass(SC, SubClass.RefRange);
289 return false;
290 }
291
AddSubClass(RecordsEntry & Entry,SubClassReference & SubClass)292 bool TGParser::AddSubClass(RecordsEntry &Entry, SubClassReference &SubClass) {
293 if (Entry.Rec)
294 return AddSubClass(Entry.Rec.get(), SubClass);
295
296 for (auto &E : Entry.Loop->Entries) {
297 if (AddSubClass(E, SubClass))
298 return true;
299 }
300
301 return false;
302 }
303
304 /// AddSubMultiClass - Add SubMultiClass as a subclass to
305 /// CurMC, resolving its template args as SubMultiClass's
306 /// template arguments.
AddSubMultiClass(MultiClass * CurMC,SubMultiClassReference & SubMultiClass)307 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
308 SubMultiClassReference &SubMultiClass) {
309 MultiClass *SMC = SubMultiClass.MC;
310
311 ArrayRef<Init *> SMCTArgs = SMC->Rec.getTemplateArgs();
312 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
313 return Error(SubMultiClass.RefRange.Start,
314 "More template args specified than expected");
315
316 // Prepare the mapping of template argument name to value, filling in default
317 // values if necessary.
318 SubstStack TemplateArgs;
319 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
320 if (i < SubMultiClass.TemplateArgs.size()) {
321 TemplateArgs.emplace_back(SMCTArgs[i], SubMultiClass.TemplateArgs[i]);
322 } else {
323 Init *Default = SMC->Rec.getValue(SMCTArgs[i])->getValue();
324 if (!Default->isComplete()) {
325 return Error(SubMultiClass.RefRange.Start,
326 "value not specified for template argument #" + Twine(i) +
327 " (" + SMCTArgs[i]->getAsUnquotedString() +
328 ") of multiclass '" + SMC->Rec.getNameInitAsString() +
329 "'");
330 }
331 TemplateArgs.emplace_back(SMCTArgs[i], Default);
332 }
333 }
334
335 TemplateArgs.emplace_back(
336 QualifiedNameOfImplicitName(SMC),
337 VarInit::get(QualifiedNameOfImplicitName(CurMC), StringRecTy::get()));
338
339 // Add all of the defs in the subclass into the current multiclass.
340 return resolve(SMC->Entries, TemplateArgs, false, &CurMC->Entries);
341 }
342
343 /// Add a record or foreach loop to the current context (global record keeper,
344 /// current inner-most foreach loop, or multiclass).
addEntry(RecordsEntry E)345 bool TGParser::addEntry(RecordsEntry E) {
346 assert(!E.Rec || !E.Loop);
347
348 if (!Loops.empty()) {
349 Loops.back()->Entries.push_back(std::move(E));
350 return false;
351 }
352
353 if (E.Loop) {
354 SubstStack Stack;
355 return resolve(*E.Loop, Stack, CurMultiClass == nullptr,
356 CurMultiClass ? &CurMultiClass->Entries : nullptr);
357 }
358
359 if (CurMultiClass) {
360 CurMultiClass->Entries.push_back(std::move(E));
361 return false;
362 }
363
364 return addDefOne(std::move(E.Rec));
365 }
366
367 /// Resolve the entries in \p Loop, going over inner loops recursively
368 /// and making the given subsitutions of (name, value) pairs.
369 ///
370 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
371 /// are added to the global record keeper.
resolve(const ForeachLoop & Loop,SubstStack & Substs,bool Final,std::vector<RecordsEntry> * Dest,SMLoc * Loc)372 bool TGParser::resolve(const ForeachLoop &Loop, SubstStack &Substs,
373 bool Final, std::vector<RecordsEntry> *Dest,
374 SMLoc *Loc) {
375 MapResolver R;
376 for (const auto &S : Substs)
377 R.set(S.first, S.second);
378 Init *List = Loop.ListValue->resolveReferences(R);
379 auto LI = dyn_cast<ListInit>(List);
380 if (!LI) {
381 if (!Final) {
382 Dest->emplace_back(std::make_unique<ForeachLoop>(Loop.Loc, Loop.IterVar,
383 List));
384 return resolve(Loop.Entries, Substs, Final, &Dest->back().Loop->Entries,
385 Loc);
386 }
387
388 PrintError(Loop.Loc, Twine("attempting to loop over '") +
389 List->getAsString() + "', expected a list");
390 return true;
391 }
392
393 bool Error = false;
394 for (auto Elt : *LI) {
395 if (Loop.IterVar)
396 Substs.emplace_back(Loop.IterVar->getNameInit(), Elt);
397 Error = resolve(Loop.Entries, Substs, Final, Dest);
398 if (Loop.IterVar)
399 Substs.pop_back();
400 if (Error)
401 break;
402 }
403 return Error;
404 }
405
406 /// Resolve the entries in \p Source, going over loops recursively and
407 /// making the given substitutions of (name, value) pairs.
408 ///
409 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
410 /// are added to the global record keeper.
resolve(const std::vector<RecordsEntry> & Source,SubstStack & Substs,bool Final,std::vector<RecordsEntry> * Dest,SMLoc * Loc)411 bool TGParser::resolve(const std::vector<RecordsEntry> &Source,
412 SubstStack &Substs, bool Final,
413 std::vector<RecordsEntry> *Dest, SMLoc *Loc) {
414 bool Error = false;
415 for (auto &E : Source) {
416 if (E.Loop) {
417 Error = resolve(*E.Loop, Substs, Final, Dest);
418 } else {
419 auto Rec = std::make_unique<Record>(*E.Rec);
420 if (Loc)
421 Rec->appendLoc(*Loc);
422
423 MapResolver R(Rec.get());
424 for (const auto &S : Substs)
425 R.set(S.first, S.second);
426 Rec->resolveReferences(R);
427
428 if (Dest)
429 Dest->push_back(std::move(Rec));
430 else
431 Error = addDefOne(std::move(Rec));
432 }
433 if (Error)
434 break;
435 }
436 return Error;
437 }
438
439 /// Resolve the record fully and add it to the record keeper.
addDefOne(std::unique_ptr<Record> Rec)440 bool TGParser::addDefOne(std::unique_ptr<Record> Rec) {
441 if (Record *Prev = Records.getDef(Rec->getNameInitAsString())) {
442 if (!Rec->isAnonymous()) {
443 PrintError(Rec->getLoc(),
444 "def already exists: " + Rec->getNameInitAsString());
445 PrintNote(Prev->getLoc(), "location of previous definition");
446 return true;
447 }
448 Rec->setName(Records.getNewAnonymousName());
449 }
450
451 Rec->resolveReferences();
452 checkConcrete(*Rec);
453
454 if (!isa<StringInit>(Rec->getNameInit())) {
455 PrintError(Rec->getLoc(), Twine("record name '") +
456 Rec->getNameInit()->getAsString() +
457 "' could not be fully resolved");
458 return true;
459 }
460
461 // If ObjectBody has template arguments, it's an error.
462 assert(Rec->getTemplateArgs().empty() && "How'd this get template args?");
463
464 for (DefsetRecord *Defset : Defsets) {
465 DefInit *I = Rec->getDefInit();
466 if (!I->getType()->typeIsA(Defset->EltTy)) {
467 PrintError(Rec->getLoc(), Twine("adding record of incompatible type '") +
468 I->getType()->getAsString() +
469 "' to defset");
470 PrintNote(Defset->Loc, "location of defset declaration");
471 return true;
472 }
473 Defset->Elements.push_back(I);
474 }
475
476 Records.addDef(std::move(Rec));
477 return false;
478 }
479
480 //===----------------------------------------------------------------------===//
481 // Parser Code
482 //===----------------------------------------------------------------------===//
483
484 /// isObjectStart - Return true if this is a valid first token for an Object.
isObjectStart(tgtok::TokKind K)485 static bool isObjectStart(tgtok::TokKind K) {
486 return K == tgtok::Class || K == tgtok::Def || K == tgtok::Defm ||
487 K == tgtok::Let || K == tgtok::MultiClass || K == tgtok::Foreach ||
488 K == tgtok::Defset || K == tgtok::Defvar || K == tgtok::If;
489 }
490
consume(tgtok::TokKind K)491 bool TGParser::consume(tgtok::TokKind K) {
492 if (Lex.getCode() == K) {
493 Lex.Lex();
494 return true;
495 }
496 return false;
497 }
498
499 /// ParseObjectName - If a valid object name is specified, return it. If no
500 /// name is specified, return the unset initializer. Return nullptr on parse
501 /// error.
502 /// ObjectName ::= Value [ '#' Value ]*
503 /// ObjectName ::= /*empty*/
504 ///
ParseObjectName(MultiClass * CurMultiClass)505 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
506 switch (Lex.getCode()) {
507 case tgtok::colon:
508 case tgtok::semi:
509 case tgtok::l_brace:
510 // These are all of the tokens that can begin an object body.
511 // Some of these can also begin values but we disallow those cases
512 // because they are unlikely to be useful.
513 return UnsetInit::get();
514 default:
515 break;
516 }
517
518 Record *CurRec = nullptr;
519 if (CurMultiClass)
520 CurRec = &CurMultiClass->Rec;
521
522 Init *Name = ParseValue(CurRec, StringRecTy::get(), ParseNameMode);
523 if (!Name)
524 return nullptr;
525
526 if (CurMultiClass) {
527 Init *NameStr = QualifiedNameOfImplicitName(CurMultiClass);
528 HasReferenceResolver R(NameStr);
529 Name->resolveReferences(R);
530 if (!R.found())
531 Name = BinOpInit::getStrConcat(VarInit::get(NameStr, StringRecTy::get()),
532 Name);
533 }
534
535 return Name;
536 }
537
538 /// ParseClassID - Parse and resolve a reference to a class name. This returns
539 /// null on error.
540 ///
541 /// ClassID ::= ID
542 ///
ParseClassID()543 Record *TGParser::ParseClassID() {
544 if (Lex.getCode() != tgtok::Id) {
545 TokError("expected name for ClassID");
546 return nullptr;
547 }
548
549 Record *Result = Records.getClass(Lex.getCurStrVal());
550 if (!Result) {
551 std::string Msg("Couldn't find class '" + Lex.getCurStrVal() + "'");
552 if (MultiClasses[Lex.getCurStrVal()].get())
553 TokError(Msg + ". Use 'defm' if you meant to use multiclass '" +
554 Lex.getCurStrVal() + "'");
555 else
556 TokError(Msg);
557 }
558
559 Lex.Lex();
560 return Result;
561 }
562
563 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
564 /// This returns null on error.
565 ///
566 /// MultiClassID ::= ID
567 ///
ParseMultiClassID()568 MultiClass *TGParser::ParseMultiClassID() {
569 if (Lex.getCode() != tgtok::Id) {
570 TokError("expected name for MultiClassID");
571 return nullptr;
572 }
573
574 MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
575 if (!Result)
576 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
577
578 Lex.Lex();
579 return Result;
580 }
581
582 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
583 /// subclass. This returns a SubClassRefTy with a null Record* on error.
584 ///
585 /// SubClassRef ::= ClassID
586 /// SubClassRef ::= ClassID '<' ValueList '>'
587 ///
588 SubClassReference TGParser::
ParseSubClassReference(Record * CurRec,bool isDefm)589 ParseSubClassReference(Record *CurRec, bool isDefm) {
590 SubClassReference Result;
591 Result.RefRange.Start = Lex.getLoc();
592
593 if (isDefm) {
594 if (MultiClass *MC = ParseMultiClassID())
595 Result.Rec = &MC->Rec;
596 } else {
597 Result.Rec = ParseClassID();
598 }
599 if (!Result.Rec) return Result;
600
601 // If there is no template arg list, we're done.
602 if (!consume(tgtok::less)) {
603 Result.RefRange.End = Lex.getLoc();
604 return Result;
605 }
606
607 if (Lex.getCode() == tgtok::greater) {
608 TokError("subclass reference requires a non-empty list of template values");
609 Result.Rec = nullptr;
610 return Result;
611 }
612
613 ParseValueList(Result.TemplateArgs, CurRec, Result.Rec);
614 if (Result.TemplateArgs.empty()) {
615 Result.Rec = nullptr; // Error parsing value list.
616 return Result;
617 }
618
619 if (!consume(tgtok::greater)) {
620 TokError("expected '>' in template value list");
621 Result.Rec = nullptr;
622 return Result;
623 }
624 Result.RefRange.End = Lex.getLoc();
625
626 return Result;
627 }
628
629 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
630 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
631 /// Record* on error.
632 ///
633 /// SubMultiClassRef ::= MultiClassID
634 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
635 ///
636 SubMultiClassReference TGParser::
ParseSubMultiClassReference(MultiClass * CurMC)637 ParseSubMultiClassReference(MultiClass *CurMC) {
638 SubMultiClassReference Result;
639 Result.RefRange.Start = Lex.getLoc();
640
641 Result.MC = ParseMultiClassID();
642 if (!Result.MC) return Result;
643
644 // If there is no template arg list, we're done.
645 if (!consume(tgtok::less)) {
646 Result.RefRange.End = Lex.getLoc();
647 return Result;
648 }
649
650 if (Lex.getCode() == tgtok::greater) {
651 TokError("subclass reference requires a non-empty list of template values");
652 Result.MC = nullptr;
653 return Result;
654 }
655
656 ParseValueList(Result.TemplateArgs, &CurMC->Rec, &Result.MC->Rec);
657 if (Result.TemplateArgs.empty()) {
658 Result.MC = nullptr; // Error parsing value list.
659 return Result;
660 }
661
662 if (!consume(tgtok::greater)) {
663 TokError("expected '>' in template value list");
664 Result.MC = nullptr;
665 return Result;
666 }
667 Result.RefRange.End = Lex.getLoc();
668
669 return Result;
670 }
671
672 /// ParseRangePiece - Parse a bit/value range.
673 /// RangePiece ::= INTVAL
674 /// RangePiece ::= INTVAL '...' INTVAL
675 /// RangePiece ::= INTVAL '-' INTVAL
676 /// RangePiece ::= INTVAL INTVAL
677 // The last two forms are deprecated.
ParseRangePiece(SmallVectorImpl<unsigned> & Ranges,TypedInit * FirstItem)678 bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
679 TypedInit *FirstItem) {
680 Init *CurVal = FirstItem;
681 if (!CurVal)
682 CurVal = ParseValue(nullptr);
683
684 IntInit *II = dyn_cast_or_null<IntInit>(CurVal);
685 if (!II)
686 return TokError("expected integer or bitrange");
687
688 int64_t Start = II->getValue();
689 int64_t End;
690
691 if (Start < 0)
692 return TokError("invalid range, cannot be negative");
693
694 switch (Lex.getCode()) {
695 default:
696 Ranges.push_back(Start);
697 return false;
698
699 case tgtok::dotdotdot:
700 case tgtok::minus: {
701 Lex.Lex(); // eat
702
703 Init *I_End = ParseValue(nullptr);
704 IntInit *II_End = dyn_cast_or_null<IntInit>(I_End);
705 if (!II_End) {
706 TokError("expected integer value as end of range");
707 return true;
708 }
709
710 End = II_End->getValue();
711 break;
712 }
713 case tgtok::IntVal: {
714 End = -Lex.getCurIntVal();
715 Lex.Lex();
716 break;
717 }
718 }
719 if (End < 0)
720 return TokError("invalid range, cannot be negative");
721
722 // Add to the range.
723 if (Start < End)
724 for (; Start <= End; ++Start)
725 Ranges.push_back(Start);
726 else
727 for (; Start >= End; --Start)
728 Ranges.push_back(Start);
729 return false;
730 }
731
732 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
733 ///
734 /// RangeList ::= RangePiece (',' RangePiece)*
735 ///
ParseRangeList(SmallVectorImpl<unsigned> & Result)736 void TGParser::ParseRangeList(SmallVectorImpl<unsigned> &Result) {
737 // Parse the first piece.
738 if (ParseRangePiece(Result)) {
739 Result.clear();
740 return;
741 }
742 while (consume(tgtok::comma))
743 // Parse the next range piece.
744 if (ParseRangePiece(Result)) {
745 Result.clear();
746 return;
747 }
748 }
749
750 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
751 /// OptionalRangeList ::= '<' RangeList '>'
752 /// OptionalRangeList ::= /*empty*/
ParseOptionalRangeList(SmallVectorImpl<unsigned> & Ranges)753 bool TGParser::ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges) {
754 SMLoc StartLoc = Lex.getLoc();
755 if (!consume(tgtok::less))
756 return false;
757
758 // Parse the range list.
759 ParseRangeList(Ranges);
760 if (Ranges.empty()) return true;
761
762 if (!consume(tgtok::greater)) {
763 TokError("expected '>' at end of range list");
764 return Error(StartLoc, "to match this '<'");
765 }
766 return false;
767 }
768
769 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
770 /// OptionalBitList ::= '{' RangeList '}'
771 /// OptionalBitList ::= /*empty*/
ParseOptionalBitList(SmallVectorImpl<unsigned> & Ranges)772 bool TGParser::ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges) {
773 SMLoc StartLoc = Lex.getLoc();
774 if (!consume(tgtok::l_brace))
775 return false;
776
777 // Parse the range list.
778 ParseRangeList(Ranges);
779 if (Ranges.empty()) return true;
780
781 if (!consume(tgtok::r_brace)) {
782 TokError("expected '}' at end of bit list");
783 return Error(StartLoc, "to match this '{'");
784 }
785 return false;
786 }
787
788 /// ParseType - Parse and return a tblgen type. This returns null on error.
789 ///
790 /// Type ::= STRING // string type
791 /// Type ::= CODE // code type
792 /// Type ::= BIT // bit type
793 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
794 /// Type ::= INT // int type
795 /// Type ::= LIST '<' Type '>' // list<x> type
796 /// Type ::= DAG // dag type
797 /// Type ::= ClassID // Record Type
798 ///
ParseType()799 RecTy *TGParser::ParseType() {
800 switch (Lex.getCode()) {
801 default: TokError("Unknown token when expecting a type"); return nullptr;
802 case tgtok::String:
803 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
804 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
805 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
806 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
807 case tgtok::Id:
808 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
809 TokError("unknown class name");
810 return nullptr;
811 case tgtok::Bits: {
812 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
813 TokError("expected '<' after bits type");
814 return nullptr;
815 }
816 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
817 TokError("expected integer in bits<n> type");
818 return nullptr;
819 }
820 uint64_t Val = Lex.getCurIntVal();
821 if (Lex.Lex() != tgtok::greater) { // Eat count.
822 TokError("expected '>' at end of bits<n> type");
823 return nullptr;
824 }
825 Lex.Lex(); // Eat '>'
826 return BitsRecTy::get(Val);
827 }
828 case tgtok::List: {
829 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
830 TokError("expected '<' after list type");
831 return nullptr;
832 }
833 Lex.Lex(); // Eat '<'
834 RecTy *SubType = ParseType();
835 if (!SubType) return nullptr;
836
837 if (!consume(tgtok::greater)) {
838 TokError("expected '>' at end of list<ty> type");
839 return nullptr;
840 }
841 return ListRecTy::get(SubType);
842 }
843 }
844 }
845
846 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
847 /// has already been read.
ParseIDValue(Record * CurRec,StringInit * Name,SMLoc NameLoc,IDParseMode Mode)848 Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMLoc NameLoc,
849 IDParseMode Mode) {
850 if (CurRec) {
851 if (const RecordVal *RV = CurRec->getValue(Name))
852 return VarInit::get(Name, RV->getType());
853 }
854
855 if ((CurRec && CurRec->isClass()) || CurMultiClass) {
856 Init *TemplateArgName;
857 if (CurMultiClass) {
858 TemplateArgName =
859 QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
860 } else
861 TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
862
863 Record *TemplateRec = CurMultiClass ? &CurMultiClass->Rec : CurRec;
864 if (TemplateRec->isTemplateArg(TemplateArgName)) {
865 const RecordVal *RV = TemplateRec->getValue(TemplateArgName);
866 assert(RV && "Template arg doesn't exist??");
867 return VarInit::get(TemplateArgName, RV->getType());
868 } else if (Name->getValue() == "NAME") {
869 return VarInit::get(TemplateArgName, StringRecTy::get());
870 }
871 }
872
873 if (CurLocalScope)
874 if (Init *I = CurLocalScope->getVar(Name->getValue()))
875 return I;
876
877 // If this is in a foreach loop, make sure it's not a loop iterator
878 for (const auto &L : Loops) {
879 if (L->IterVar) {
880 VarInit *IterVar = dyn_cast<VarInit>(L->IterVar);
881 if (IterVar && IterVar->getNameInit() == Name)
882 return IterVar;
883 }
884 }
885
886 if (Mode == ParseNameMode)
887 return Name;
888
889 if (Init *I = Records.getGlobal(Name->getValue()))
890 return I;
891
892 // Allow self-references of concrete defs, but delay the lookup so that we
893 // get the correct type.
894 if (CurRec && !CurRec->isClass() && !CurMultiClass &&
895 CurRec->getNameInit() == Name)
896 return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType());
897
898 Error(NameLoc, "Variable not defined: '" + Name->getValue() + "'");
899 return nullptr;
900 }
901
902 /// ParseOperation - Parse an operator. This returns null on error.
903 ///
904 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
905 ///
ParseOperation(Record * CurRec,RecTy * ItemType)906 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
907 switch (Lex.getCode()) {
908 default:
909 TokError("unknown bang operator");
910 return nullptr;
911 case tgtok::XNOT:
912 case tgtok::XHead:
913 case tgtok::XTail:
914 case tgtok::XSize:
915 case tgtok::XEmpty:
916 case tgtok::XCast:
917 case tgtok::XGetDagOp: { // Value ::= !unop '(' Value ')'
918 UnOpInit::UnaryOp Code;
919 RecTy *Type = nullptr;
920
921 switch (Lex.getCode()) {
922 default: llvm_unreachable("Unhandled code!");
923 case tgtok::XCast:
924 Lex.Lex(); // eat the operation
925 Code = UnOpInit::CAST;
926
927 Type = ParseOperatorType();
928
929 if (!Type) {
930 TokError("did not get type for unary operator");
931 return nullptr;
932 }
933
934 break;
935 case tgtok::XNOT:
936 Lex.Lex(); // eat the operation
937 Code = UnOpInit::NOT;
938 Type = IntRecTy::get();
939 break;
940 case tgtok::XHead:
941 Lex.Lex(); // eat the operation
942 Code = UnOpInit::HEAD;
943 break;
944 case tgtok::XTail:
945 Lex.Lex(); // eat the operation
946 Code = UnOpInit::TAIL;
947 break;
948 case tgtok::XSize:
949 Lex.Lex();
950 Code = UnOpInit::SIZE;
951 Type = IntRecTy::get();
952 break;
953 case tgtok::XEmpty:
954 Lex.Lex(); // eat the operation
955 Code = UnOpInit::EMPTY;
956 Type = IntRecTy::get();
957 break;
958 case tgtok::XGetDagOp:
959 Lex.Lex(); // eat the operation
960 if (Lex.getCode() == tgtok::less) {
961 // Parse an optional type suffix, so that you can say
962 // !getdagop<BaseClass>(someDag) as a shorthand for
963 // !cast<BaseClass>(!getdagop(someDag)).
964 Type = ParseOperatorType();
965
966 if (!Type) {
967 TokError("did not get type for unary operator");
968 return nullptr;
969 }
970
971 if (!isa<RecordRecTy>(Type)) {
972 TokError("type for !getdagop must be a record type");
973 // but keep parsing, to consume the operand
974 }
975 } else {
976 Type = RecordRecTy::get({});
977 }
978 Code = UnOpInit::GETDAGOP;
979 break;
980 }
981 if (!consume(tgtok::l_paren)) {
982 TokError("expected '(' after unary operator");
983 return nullptr;
984 }
985
986 Init *LHS = ParseValue(CurRec);
987 if (!LHS) return nullptr;
988
989 if (Code == UnOpInit::EMPTY || Code == UnOpInit::SIZE) {
990 ListInit *LHSl = dyn_cast<ListInit>(LHS);
991 StringInit *LHSs = dyn_cast<StringInit>(LHS);
992 DagInit *LHSd = dyn_cast<DagInit>(LHS);
993 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
994 if (!LHSl && !LHSs && !LHSd && !LHSt) {
995 TokError("expected string, list, or dag type argument in unary operator");
996 return nullptr;
997 }
998 if (LHSt) {
999 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1000 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
1001 DagRecTy *DType = dyn_cast<DagRecTy>(LHSt->getType());
1002 if (!LType && !SType && !DType) {
1003 TokError("expected string, list, or dag type argument in unary operator");
1004 return nullptr;
1005 }
1006 }
1007 }
1008
1009 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
1010 ListInit *LHSl = dyn_cast<ListInit>(LHS);
1011 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1012 if (!LHSl && !LHSt) {
1013 TokError("expected list type argument in unary operator");
1014 return nullptr;
1015 }
1016 if (LHSt) {
1017 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1018 if (!LType) {
1019 TokError("expected list type argument in unary operator");
1020 return nullptr;
1021 }
1022 }
1023
1024 if (LHSl && LHSl->empty()) {
1025 TokError("empty list argument in unary operator");
1026 return nullptr;
1027 }
1028 if (LHSl) {
1029 Init *Item = LHSl->getElement(0);
1030 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
1031 if (!Itemt) {
1032 TokError("untyped list element in unary operator");
1033 return nullptr;
1034 }
1035 Type = (Code == UnOpInit::HEAD) ? Itemt->getType()
1036 : ListRecTy::get(Itemt->getType());
1037 } else {
1038 assert(LHSt && "expected list type argument in unary operator");
1039 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1040 Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType;
1041 }
1042 }
1043
1044 if (!consume(tgtok::r_paren)) {
1045 TokError("expected ')' in unary operator");
1046 return nullptr;
1047 }
1048 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec);
1049 }
1050
1051 case tgtok::XIsA: {
1052 // Value ::= !isa '<' Type '>' '(' Value ')'
1053 Lex.Lex(); // eat the operation
1054
1055 RecTy *Type = ParseOperatorType();
1056 if (!Type)
1057 return nullptr;
1058
1059 if (!consume(tgtok::l_paren)) {
1060 TokError("expected '(' after type of !isa");
1061 return nullptr;
1062 }
1063
1064 Init *LHS = ParseValue(CurRec);
1065 if (!LHS)
1066 return nullptr;
1067
1068 if (!consume(tgtok::r_paren)) {
1069 TokError("expected ')' in !isa");
1070 return nullptr;
1071 }
1072
1073 return (IsAOpInit::get(Type, LHS))->Fold();
1074 }
1075
1076 case tgtok::XConcat:
1077 case tgtok::XADD:
1078 case tgtok::XSUB:
1079 case tgtok::XMUL:
1080 case tgtok::XAND:
1081 case tgtok::XOR:
1082 case tgtok::XXOR:
1083 case tgtok::XSRA:
1084 case tgtok::XSRL:
1085 case tgtok::XSHL:
1086 case tgtok::XEq:
1087 case tgtok::XNe:
1088 case tgtok::XLe:
1089 case tgtok::XLt:
1090 case tgtok::XGe:
1091 case tgtok::XGt:
1092 case tgtok::XListConcat:
1093 case tgtok::XListSplat:
1094 case tgtok::XStrConcat:
1095 case tgtok::XInterleave:
1096 case tgtok::XSetDagOp: { // Value ::= !binop '(' Value ',' Value ')'
1097 tgtok::TokKind OpTok = Lex.getCode();
1098 SMLoc OpLoc = Lex.getLoc();
1099 Lex.Lex(); // eat the operation
1100
1101 BinOpInit::BinaryOp Code;
1102 switch (OpTok) {
1103 default: llvm_unreachable("Unhandled code!");
1104 case tgtok::XConcat: Code = BinOpInit::CONCAT; break;
1105 case tgtok::XADD: Code = BinOpInit::ADD; break;
1106 case tgtok::XSUB: Code = BinOpInit::SUB; break;
1107 case tgtok::XMUL: Code = BinOpInit::MUL; break;
1108 case tgtok::XAND: Code = BinOpInit::AND; break;
1109 case tgtok::XOR: Code = BinOpInit::OR; break;
1110 case tgtok::XXOR: Code = BinOpInit::XOR; break;
1111 case tgtok::XSRA: Code = BinOpInit::SRA; break;
1112 case tgtok::XSRL: Code = BinOpInit::SRL; break;
1113 case tgtok::XSHL: Code = BinOpInit::SHL; break;
1114 case tgtok::XEq: Code = BinOpInit::EQ; break;
1115 case tgtok::XNe: Code = BinOpInit::NE; break;
1116 case tgtok::XLe: Code = BinOpInit::LE; break;
1117 case tgtok::XLt: Code = BinOpInit::LT; break;
1118 case tgtok::XGe: Code = BinOpInit::GE; break;
1119 case tgtok::XGt: Code = BinOpInit::GT; break;
1120 case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break;
1121 case tgtok::XListSplat: Code = BinOpInit::LISTSPLAT; break;
1122 case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break;
1123 case tgtok::XInterleave: Code = BinOpInit::INTERLEAVE; break;
1124 case tgtok::XSetDagOp: Code = BinOpInit::SETDAGOP; break;
1125 }
1126
1127 RecTy *Type = nullptr;
1128 RecTy *ArgType = nullptr;
1129 switch (OpTok) {
1130 default:
1131 llvm_unreachable("Unhandled code!");
1132 case tgtok::XConcat:
1133 case tgtok::XSetDagOp:
1134 Type = DagRecTy::get();
1135 ArgType = DagRecTy::get();
1136 break;
1137 case tgtok::XAND:
1138 case tgtok::XOR:
1139 case tgtok::XXOR:
1140 case tgtok::XSRA:
1141 case tgtok::XSRL:
1142 case tgtok::XSHL:
1143 case tgtok::XADD:
1144 case tgtok::XSUB:
1145 case tgtok::XMUL:
1146 Type = IntRecTy::get();
1147 ArgType = IntRecTy::get();
1148 break;
1149 case tgtok::XEq:
1150 case tgtok::XNe:
1151 case tgtok::XLe:
1152 case tgtok::XLt:
1153 case tgtok::XGe:
1154 case tgtok::XGt:
1155 Type = BitRecTy::get();
1156 // ArgType for the comparison operators is not yet known.
1157 break;
1158 case tgtok::XListConcat:
1159 // We don't know the list type until we parse the first argument
1160 ArgType = ItemType;
1161 break;
1162 case tgtok::XListSplat:
1163 // Can't do any typechecking until we parse the first argument.
1164 break;
1165 case tgtok::XStrConcat:
1166 Type = StringRecTy::get();
1167 ArgType = StringRecTy::get();
1168 break;
1169 case tgtok::XInterleave:
1170 Type = StringRecTy::get();
1171 // The first argument type is not yet known.
1172 }
1173
1174 if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) {
1175 Error(OpLoc, Twine("expected value of type '") +
1176 ItemType->getAsString() + "', got '" +
1177 Type->getAsString() + "'");
1178 return nullptr;
1179 }
1180
1181 if (!consume(tgtok::l_paren)) {
1182 TokError("expected '(' after binary operator");
1183 return nullptr;
1184 }
1185
1186 SmallVector<Init*, 2> InitList;
1187
1188 // Note that this loop consumes an arbitrary number of arguments.
1189 // The actual count is checked later.
1190 for (;;) {
1191 SMLoc InitLoc = Lex.getLoc();
1192 InitList.push_back(ParseValue(CurRec, ArgType));
1193 if (!InitList.back()) return nullptr;
1194
1195 TypedInit *InitListBack = dyn_cast<TypedInit>(InitList.back());
1196 if (!InitListBack) {
1197 Error(OpLoc, Twine("expected value to be a typed value, got '" +
1198 InitList.back()->getAsString() + "'"));
1199 return nullptr;
1200 }
1201 RecTy *ListType = InitListBack->getType();
1202
1203 if (!ArgType) {
1204 // Argument type must be determined from the argument itself.
1205 ArgType = ListType;
1206
1207 switch (Code) {
1208 case BinOpInit::LISTCONCAT:
1209 if (!isa<ListRecTy>(ArgType)) {
1210 Error(InitLoc, Twine("expected a list, got value of type '") +
1211 ArgType->getAsString() + "'");
1212 return nullptr;
1213 }
1214 break;
1215 case BinOpInit::LISTSPLAT:
1216 if (ItemType && InitList.size() == 1) {
1217 if (!isa<ListRecTy>(ItemType)) {
1218 Error(OpLoc,
1219 Twine("expected output type to be a list, got type '") +
1220 ItemType->getAsString() + "'");
1221 return nullptr;
1222 }
1223 if (!ArgType->getListTy()->typeIsConvertibleTo(ItemType)) {
1224 Error(OpLoc, Twine("expected first arg type to be '") +
1225 ArgType->getAsString() +
1226 "', got value of type '" +
1227 cast<ListRecTy>(ItemType)
1228 ->getElementType()
1229 ->getAsString() +
1230 "'");
1231 return nullptr;
1232 }
1233 }
1234 if (InitList.size() == 2 && !isa<IntRecTy>(ArgType)) {
1235 Error(InitLoc, Twine("expected second parameter to be an int, got "
1236 "value of type '") +
1237 ArgType->getAsString() + "'");
1238 return nullptr;
1239 }
1240 ArgType = nullptr; // Broken invariant: types not identical.
1241 break;
1242 case BinOpInit::EQ:
1243 case BinOpInit::NE:
1244 if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) &&
1245 !ArgType->typeIsConvertibleTo(StringRecTy::get()) &&
1246 !ArgType->typeIsConvertibleTo(RecordRecTy::get({}))) {
1247 Error(InitLoc, Twine("expected bit, bits, int, string, or record; "
1248 "got value of type '") + ArgType->getAsString() +
1249 "'");
1250 return nullptr;
1251 }
1252 break;
1253 case BinOpInit::LE:
1254 case BinOpInit::LT:
1255 case BinOpInit::GE:
1256 case BinOpInit::GT:
1257 if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) &&
1258 !ArgType->typeIsConvertibleTo(StringRecTy::get())) {
1259 Error(InitLoc, Twine("expected bit, bits, int, or string; "
1260 "got value of type '") + ArgType->getAsString() +
1261 "'");
1262 return nullptr;
1263 }
1264 break;
1265 case BinOpInit::INTERLEAVE:
1266 switch (InitList.size()) {
1267 case 1: // First argument must be a list of strings or integers.
1268 if (ArgType != StringRecTy::get()->getListTy() &&
1269 !ArgType->typeIsConvertibleTo(IntRecTy::get()->getListTy())) {
1270 Error(InitLoc, Twine("expected list of string, int, bits, or bit; "
1271 "got value of type '") +
1272 ArgType->getAsString() + "'");
1273 return nullptr;
1274 }
1275 break;
1276 case 2: // Second argument must be a string.
1277 if (!isa<StringRecTy>(ArgType)) {
1278 Error(InitLoc, Twine("expected second argument to be a string, "
1279 "got value of type '") +
1280 ArgType->getAsString() + "'");
1281 return nullptr;
1282 }
1283 break;
1284 default: ;
1285 }
1286 ArgType = nullptr; // Broken invariant: types not identical.
1287 break;
1288 default: llvm_unreachable("other ops have fixed argument types");
1289 }
1290
1291 } else {
1292 // Desired argument type is a known and in ArgType.
1293 RecTy *Resolved = resolveTypes(ArgType, ListType);
1294 if (!Resolved) {
1295 Error(InitLoc, Twine("expected value of type '") +
1296 ArgType->getAsString() + "', got '" +
1297 ListType->getAsString() + "'");
1298 return nullptr;
1299 }
1300 if (Code != BinOpInit::ADD && Code != BinOpInit::SUB &&
1301 Code != BinOpInit::AND && Code != BinOpInit::OR &&
1302 Code != BinOpInit::XOR && Code != BinOpInit::SRA &&
1303 Code != BinOpInit::SRL && Code != BinOpInit::SHL &&
1304 Code != BinOpInit::MUL)
1305 ArgType = Resolved;
1306 }
1307
1308 // Deal with BinOps whose arguments have different types, by
1309 // rewriting ArgType in between them.
1310 switch (Code) {
1311 case BinOpInit::SETDAGOP:
1312 // After parsing the first dag argument, switch to expecting
1313 // a record, with no restriction on its superclasses.
1314 ArgType = RecordRecTy::get({});
1315 break;
1316 default:
1317 break;
1318 }
1319
1320 if (!consume(tgtok::comma))
1321 break;
1322 }
1323
1324 if (!consume(tgtok::r_paren)) {
1325 TokError("expected ')' in operator");
1326 return nullptr;
1327 }
1328
1329 // listconcat returns a list with type of the argument.
1330 if (Code == BinOpInit::LISTCONCAT)
1331 Type = ArgType;
1332 // listsplat returns a list of type of the *first* argument.
1333 if (Code == BinOpInit::LISTSPLAT)
1334 Type = cast<TypedInit>(InitList.front())->getType()->getListTy();
1335
1336 // We allow multiple operands to associative operators like !strconcat as
1337 // shorthand for nesting them.
1338 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT ||
1339 Code == BinOpInit::CONCAT || Code == BinOpInit::ADD ||
1340 Code == BinOpInit::AND || Code == BinOpInit::OR ||
1341 Code == BinOpInit::XOR || Code == BinOpInit::MUL) {
1342 while (InitList.size() > 2) {
1343 Init *RHS = InitList.pop_back_val();
1344 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec);
1345 InitList.back() = RHS;
1346 }
1347 }
1348
1349 if (InitList.size() == 2)
1350 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
1351 ->Fold(CurRec);
1352
1353 Error(OpLoc, "expected two operands to operator");
1354 return nullptr;
1355 }
1356
1357 case tgtok::XForEach:
1358 case tgtok::XFilter: {
1359 return ParseOperationForEachFilter(CurRec, ItemType);
1360 }
1361
1362 case tgtok::XDag:
1363 case tgtok::XIf:
1364 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1365 TernOpInit::TernaryOp Code;
1366 RecTy *Type = nullptr;
1367
1368 tgtok::TokKind LexCode = Lex.getCode();
1369 Lex.Lex(); // eat the operation
1370 switch (LexCode) {
1371 default: llvm_unreachable("Unhandled code!");
1372 case tgtok::XDag:
1373 Code = TernOpInit::DAG;
1374 Type = DagRecTy::get();
1375 ItemType = nullptr;
1376 break;
1377 case tgtok::XIf:
1378 Code = TernOpInit::IF;
1379 break;
1380 case tgtok::XSubst:
1381 Code = TernOpInit::SUBST;
1382 break;
1383 }
1384 if (!consume(tgtok::l_paren)) {
1385 TokError("expected '(' after ternary operator");
1386 return nullptr;
1387 }
1388
1389 Init *LHS = ParseValue(CurRec);
1390 if (!LHS) return nullptr;
1391
1392 if (!consume(tgtok::comma)) {
1393 TokError("expected ',' in ternary operator");
1394 return nullptr;
1395 }
1396
1397 SMLoc MHSLoc = Lex.getLoc();
1398 Init *MHS = ParseValue(CurRec, ItemType);
1399 if (!MHS)
1400 return nullptr;
1401
1402 if (!consume(tgtok::comma)) {
1403 TokError("expected ',' in ternary operator");
1404 return nullptr;
1405 }
1406
1407 SMLoc RHSLoc = Lex.getLoc();
1408 Init *RHS = ParseValue(CurRec, ItemType);
1409 if (!RHS)
1410 return nullptr;
1411
1412 if (!consume(tgtok::r_paren)) {
1413 TokError("expected ')' in binary operator");
1414 return nullptr;
1415 }
1416
1417 switch (LexCode) {
1418 default: llvm_unreachable("Unhandled code!");
1419 case tgtok::XDag: {
1420 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1421 if (!MHSt && !isa<UnsetInit>(MHS)) {
1422 Error(MHSLoc, "could not determine type of the child list in !dag");
1423 return nullptr;
1424 }
1425 if (MHSt && !isa<ListRecTy>(MHSt->getType())) {
1426 Error(MHSLoc, Twine("expected list of children, got type '") +
1427 MHSt->getType()->getAsString() + "'");
1428 return nullptr;
1429 }
1430
1431 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1432 if (!RHSt && !isa<UnsetInit>(RHS)) {
1433 Error(RHSLoc, "could not determine type of the name list in !dag");
1434 return nullptr;
1435 }
1436 if (RHSt && StringRecTy::get()->getListTy() != RHSt->getType()) {
1437 Error(RHSLoc, Twine("expected list<string>, got type '") +
1438 RHSt->getType()->getAsString() + "'");
1439 return nullptr;
1440 }
1441
1442 if (!MHSt && !RHSt) {
1443 Error(MHSLoc,
1444 "cannot have both unset children and unset names in !dag");
1445 return nullptr;
1446 }
1447 break;
1448 }
1449 case tgtok::XIf: {
1450 RecTy *MHSTy = nullptr;
1451 RecTy *RHSTy = nullptr;
1452
1453 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1454 MHSTy = MHSt->getType();
1455 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1456 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1457 if (isa<BitInit>(MHS))
1458 MHSTy = BitRecTy::get();
1459
1460 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1461 RHSTy = RHSt->getType();
1462 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1463 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1464 if (isa<BitInit>(RHS))
1465 RHSTy = BitRecTy::get();
1466
1467 // For UnsetInit, it's typed from the other hand.
1468 if (isa<UnsetInit>(MHS))
1469 MHSTy = RHSTy;
1470 if (isa<UnsetInit>(RHS))
1471 RHSTy = MHSTy;
1472
1473 if (!MHSTy || !RHSTy) {
1474 TokError("could not get type for !if");
1475 return nullptr;
1476 }
1477
1478 Type = resolveTypes(MHSTy, RHSTy);
1479 if (!Type) {
1480 TokError(Twine("inconsistent types '") + MHSTy->getAsString() +
1481 "' and '" + RHSTy->getAsString() + "' for !if");
1482 return nullptr;
1483 }
1484 break;
1485 }
1486 case tgtok::XSubst: {
1487 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1488 if (!RHSt) {
1489 TokError("could not get type for !subst");
1490 return nullptr;
1491 }
1492 Type = RHSt->getType();
1493 break;
1494 }
1495 }
1496 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
1497 }
1498
1499 case tgtok::XCond:
1500 return ParseOperationCond(CurRec, ItemType);
1501
1502 case tgtok::XFoldl: {
1503 // Value ::= !foldl '(' Value ',' Value ',' Id ',' Id ',' Expr ')'
1504 Lex.Lex(); // eat the operation
1505 if (!consume(tgtok::l_paren)) {
1506 TokError("expected '(' after !foldl");
1507 return nullptr;
1508 }
1509
1510 Init *StartUntyped = ParseValue(CurRec);
1511 if (!StartUntyped)
1512 return nullptr;
1513
1514 TypedInit *Start = dyn_cast<TypedInit>(StartUntyped);
1515 if (!Start) {
1516 TokError(Twine("could not get type of !foldl start: '") +
1517 StartUntyped->getAsString() + "'");
1518 return nullptr;
1519 }
1520
1521 if (!consume(tgtok::comma)) {
1522 TokError("expected ',' in !foldl");
1523 return nullptr;
1524 }
1525
1526 Init *ListUntyped = ParseValue(CurRec);
1527 if (!ListUntyped)
1528 return nullptr;
1529
1530 TypedInit *List = dyn_cast<TypedInit>(ListUntyped);
1531 if (!List) {
1532 TokError(Twine("could not get type of !foldl list: '") +
1533 ListUntyped->getAsString() + "'");
1534 return nullptr;
1535 }
1536
1537 ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType());
1538 if (!ListType) {
1539 TokError(Twine("!foldl list must be a list, but is of type '") +
1540 List->getType()->getAsString());
1541 return nullptr;
1542 }
1543
1544 if (Lex.getCode() != tgtok::comma) {
1545 TokError("expected ',' in !foldl");
1546 return nullptr;
1547 }
1548
1549 if (Lex.Lex() != tgtok::Id) { // eat the ','
1550 TokError("third argument of !foldl must be an identifier");
1551 return nullptr;
1552 }
1553
1554 Init *A = StringInit::get(Lex.getCurStrVal());
1555 if (CurRec && CurRec->getValue(A)) {
1556 TokError((Twine("left !foldl variable '") + A->getAsString() +
1557 "' already defined")
1558 .str());
1559 return nullptr;
1560 }
1561
1562 if (Lex.Lex() != tgtok::comma) { // eat the id
1563 TokError("expected ',' in !foldl");
1564 return nullptr;
1565 }
1566
1567 if (Lex.Lex() != tgtok::Id) { // eat the ','
1568 TokError("fourth argument of !foldl must be an identifier");
1569 return nullptr;
1570 }
1571
1572 Init *B = StringInit::get(Lex.getCurStrVal());
1573 if (CurRec && CurRec->getValue(B)) {
1574 TokError((Twine("right !foldl variable '") + B->getAsString() +
1575 "' already defined")
1576 .str());
1577 return nullptr;
1578 }
1579
1580 if (Lex.Lex() != tgtok::comma) { // eat the id
1581 TokError("expected ',' in !foldl");
1582 return nullptr;
1583 }
1584 Lex.Lex(); // eat the ','
1585
1586 // We need to create a temporary record to provide a scope for the
1587 // two variables.
1588 std::unique_ptr<Record> ParseRecTmp;
1589 Record *ParseRec = CurRec;
1590 if (!ParseRec) {
1591 ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1592 ParseRec = ParseRecTmp.get();
1593 }
1594
1595 ParseRec->addValue(RecordVal(A, Start->getType(), false));
1596 ParseRec->addValue(RecordVal(B, ListType->getElementType(), false));
1597 Init *ExprUntyped = ParseValue(ParseRec);
1598 ParseRec->removeValue(A);
1599 ParseRec->removeValue(B);
1600 if (!ExprUntyped)
1601 return nullptr;
1602
1603 TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped);
1604 if (!Expr) {
1605 TokError("could not get type of !foldl expression");
1606 return nullptr;
1607 }
1608
1609 if (Expr->getType() != Start->getType()) {
1610 TokError(Twine("!foldl expression must be of same type as start (") +
1611 Start->getType()->getAsString() + "), but is of type " +
1612 Expr->getType()->getAsString());
1613 return nullptr;
1614 }
1615
1616 if (!consume(tgtok::r_paren)) {
1617 TokError("expected ')' in fold operator");
1618 return nullptr;
1619 }
1620
1621 return FoldOpInit::get(Start, List, A, B, Expr, Start->getType())
1622 ->Fold(CurRec);
1623 }
1624 }
1625 }
1626
1627 /// ParseOperatorType - Parse a type for an operator. This returns
1628 /// null on error.
1629 ///
1630 /// OperatorType ::= '<' Type '>'
1631 ///
ParseOperatorType()1632 RecTy *TGParser::ParseOperatorType() {
1633 RecTy *Type = nullptr;
1634
1635 if (!consume(tgtok::less)) {
1636 TokError("expected type name for operator");
1637 return nullptr;
1638 }
1639
1640 if (Lex.getCode() == tgtok::Code)
1641 TokError("the 'code' type is not allowed in bang operators; use 'string'");
1642
1643 Type = ParseType();
1644
1645 if (!Type) {
1646 TokError("expected type name for operator");
1647 return nullptr;
1648 }
1649
1650 if (!consume(tgtok::greater)) {
1651 TokError("expected type name for operator");
1652 return nullptr;
1653 }
1654
1655 return Type;
1656 }
1657
1658 /// Parse the !foreach and !filter operations. Return null on error.
1659 ///
1660 /// ForEach ::= !foreach(ID, list-or-dag, expr) => list<expr type>
1661 /// Filter ::= !foreach(ID, list, predicate) ==> list<list type>
ParseOperationForEachFilter(Record * CurRec,RecTy * ItemType)1662 Init *TGParser::ParseOperationForEachFilter(Record *CurRec, RecTy *ItemType) {
1663 SMLoc OpLoc = Lex.getLoc();
1664 tgtok::TokKind Operation = Lex.getCode();
1665 Lex.Lex(); // eat the operation
1666 if (Lex.getCode() != tgtok::l_paren) {
1667 TokError("expected '(' after !foreach/!filter");
1668 return nullptr;
1669 }
1670
1671 if (Lex.Lex() != tgtok::Id) { // eat the '('
1672 TokError("first argument of !foreach/!filter must be an identifier");
1673 return nullptr;
1674 }
1675
1676 Init *LHS = StringInit::get(Lex.getCurStrVal());
1677 Lex.Lex(); // eat the ID.
1678
1679 if (CurRec && CurRec->getValue(LHS)) {
1680 TokError((Twine("iteration variable '") + LHS->getAsString() +
1681 "' is already defined")
1682 .str());
1683 return nullptr;
1684 }
1685
1686 if (!consume(tgtok::comma)) {
1687 TokError("expected ',' in !foreach/!filter");
1688 return nullptr;
1689 }
1690
1691 Init *MHS = ParseValue(CurRec);
1692 if (!MHS)
1693 return nullptr;
1694
1695 if (!consume(tgtok::comma)) {
1696 TokError("expected ',' in !foreach/!filter");
1697 return nullptr;
1698 }
1699
1700 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1701 if (!MHSt) {
1702 TokError("could not get type of !foreach/!filter list or dag");
1703 return nullptr;
1704 }
1705
1706 RecTy *InEltType = nullptr;
1707 RecTy *ExprEltType = nullptr;
1708 bool IsDAG = false;
1709
1710 if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) {
1711 InEltType = InListTy->getElementType();
1712 if (ItemType) {
1713 if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) {
1714 ExprEltType = (Operation == tgtok::XForEach)
1715 ? OutListTy->getElementType()
1716 : IntRecTy::get();
1717 } else {
1718 Error(OpLoc,
1719 "expected value of type '" +
1720 Twine(ItemType->getAsString()) +
1721 "', but got list type");
1722 return nullptr;
1723 }
1724 }
1725 } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) {
1726 if (Operation == tgtok::XFilter) {
1727 TokError("!filter must have a list argument");
1728 return nullptr;
1729 }
1730 InEltType = InDagTy;
1731 if (ItemType && !isa<DagRecTy>(ItemType)) {
1732 Error(OpLoc,
1733 "expected value of type '" + Twine(ItemType->getAsString()) +
1734 "', but got dag type");
1735 return nullptr;
1736 }
1737 IsDAG = true;
1738 } else {
1739 if (Operation == tgtok::XForEach)
1740 TokError("!foreach must have a list or dag argument");
1741 else
1742 TokError("!filter must have a list argument");
1743 return nullptr;
1744 }
1745
1746 // We need to create a temporary record to provide a scope for the
1747 // iteration variable.
1748 std::unique_ptr<Record> ParseRecTmp;
1749 Record *ParseRec = CurRec;
1750 if (!ParseRec) {
1751 ParseRecTmp =
1752 std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1753 ParseRec = ParseRecTmp.get();
1754 }
1755
1756 ParseRec->addValue(RecordVal(LHS, InEltType, false));
1757 Init *RHS = ParseValue(ParseRec, ExprEltType);
1758 ParseRec->removeValue(LHS);
1759 if (!RHS)
1760 return nullptr;
1761
1762 if (!consume(tgtok::r_paren)) {
1763 TokError("expected ')' in !foreach/!filter");
1764 return nullptr;
1765 }
1766
1767 RecTy *OutType = InEltType;
1768 if (Operation == tgtok::XForEach && !IsDAG) {
1769 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1770 if (!RHSt) {
1771 TokError("could not get type of !foreach result expression");
1772 return nullptr;
1773 }
1774 OutType = RHSt->getType()->getListTy();
1775 } else if (Operation == tgtok::XFilter) {
1776 OutType = InEltType->getListTy();
1777 }
1778
1779 return (TernOpInit::get((Operation == tgtok::XForEach) ? TernOpInit::FOREACH
1780 : TernOpInit::FILTER,
1781 LHS, MHS, RHS, OutType))
1782 ->Fold(CurRec);
1783 }
1784
ParseOperationCond(Record * CurRec,RecTy * ItemType)1785 Init *TGParser::ParseOperationCond(Record *CurRec, RecTy *ItemType) {
1786 Lex.Lex(); // eat the operation 'cond'
1787
1788 if (!consume(tgtok::l_paren)) {
1789 TokError("expected '(' after !cond operator");
1790 return nullptr;
1791 }
1792
1793 // Parse through '[Case: Val,]+'
1794 SmallVector<Init *, 4> Case;
1795 SmallVector<Init *, 4> Val;
1796 while (true) {
1797 if (consume(tgtok::r_paren))
1798 break;
1799
1800 Init *V = ParseValue(CurRec);
1801 if (!V)
1802 return nullptr;
1803 Case.push_back(V);
1804
1805 if (!consume(tgtok::colon)) {
1806 TokError("expected ':' following a condition in !cond operator");
1807 return nullptr;
1808 }
1809
1810 V = ParseValue(CurRec, ItemType);
1811 if (!V)
1812 return nullptr;
1813 Val.push_back(V);
1814
1815 if (consume(tgtok::r_paren))
1816 break;
1817
1818 if (!consume(tgtok::comma)) {
1819 TokError("expected ',' or ')' following a value in !cond operator");
1820 return nullptr;
1821 }
1822 }
1823
1824 if (Case.size() < 1) {
1825 TokError("there should be at least 1 'condition : value' in the !cond operator");
1826 return nullptr;
1827 }
1828
1829 // resolve type
1830 RecTy *Type = nullptr;
1831 for (Init *V : Val) {
1832 RecTy *VTy = nullptr;
1833 if (TypedInit *Vt = dyn_cast<TypedInit>(V))
1834 VTy = Vt->getType();
1835 if (BitsInit *Vbits = dyn_cast<BitsInit>(V))
1836 VTy = BitsRecTy::get(Vbits->getNumBits());
1837 if (isa<BitInit>(V))
1838 VTy = BitRecTy::get();
1839
1840 if (Type == nullptr) {
1841 if (!isa<UnsetInit>(V))
1842 Type = VTy;
1843 } else {
1844 if (!isa<UnsetInit>(V)) {
1845 RecTy *RType = resolveTypes(Type, VTy);
1846 if (!RType) {
1847 TokError(Twine("inconsistent types '") + Type->getAsString() +
1848 "' and '" + VTy->getAsString() + "' for !cond");
1849 return nullptr;
1850 }
1851 Type = RType;
1852 }
1853 }
1854 }
1855
1856 if (!Type) {
1857 TokError("could not determine type for !cond from its arguments");
1858 return nullptr;
1859 }
1860 return CondOpInit::get(Case, Val, Type)->Fold(CurRec);
1861 }
1862
1863 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1864 ///
1865 /// SimpleValue ::= IDValue
1866 /// SimpleValue ::= INTVAL
1867 /// SimpleValue ::= STRVAL+
1868 /// SimpleValue ::= CODEFRAGMENT
1869 /// SimpleValue ::= '?'
1870 /// SimpleValue ::= '{' ValueList '}'
1871 /// SimpleValue ::= ID '<' ValueListNE '>'
1872 /// SimpleValue ::= '[' ValueList ']'
1873 /// SimpleValue ::= '(' IDValue DagArgList ')'
1874 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1875 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1876 /// SimpleValue ::= SUBTOK '(' Value ',' Value ')'
1877 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1878 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1879 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1880 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1881 /// SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')'
1882 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1883 /// SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
1884 ///
ParseSimpleValue(Record * CurRec,RecTy * ItemType,IDParseMode Mode)1885 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1886 IDParseMode Mode) {
1887 Init *R = nullptr;
1888 switch (Lex.getCode()) {
1889 default: TokError("Unknown or reserved token when parsing a value"); break;
1890
1891 case tgtok::TrueVal:
1892 R = IntInit::get(1);
1893 Lex.Lex();
1894 break;
1895 case tgtok::FalseVal:
1896 R = IntInit::get(0);
1897 Lex.Lex();
1898 break;
1899 case tgtok::IntVal:
1900 R = IntInit::get(Lex.getCurIntVal());
1901 Lex.Lex();
1902 break;
1903 case tgtok::BinaryIntVal: {
1904 auto BinaryVal = Lex.getCurBinaryIntVal();
1905 SmallVector<Init*, 16> Bits(BinaryVal.second);
1906 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
1907 Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
1908 R = BitsInit::get(Bits);
1909 Lex.Lex();
1910 break;
1911 }
1912 case tgtok::StrVal: {
1913 std::string Val = Lex.getCurStrVal();
1914 Lex.Lex();
1915
1916 // Handle multiple consecutive concatenated strings.
1917 while (Lex.getCode() == tgtok::StrVal) {
1918 Val += Lex.getCurStrVal();
1919 Lex.Lex();
1920 }
1921
1922 R = StringInit::get(Val);
1923 break;
1924 }
1925 case tgtok::CodeFragment:
1926 R = StringInit::get(Lex.getCurStrVal(), StringInit::SF_Code);
1927 Lex.Lex();
1928 break;
1929 case tgtok::question:
1930 R = UnsetInit::get();
1931 Lex.Lex();
1932 break;
1933 case tgtok::Id: {
1934 SMLoc NameLoc = Lex.getLoc();
1935 StringInit *Name = StringInit::get(Lex.getCurStrVal());
1936 if (Lex.Lex() != tgtok::less) // consume the Id.
1937 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1938
1939 // Value ::= ID '<' ValueListNE '>'
1940 if (Lex.Lex() == tgtok::greater) {
1941 TokError("expected non-empty value list");
1942 return nullptr;
1943 }
1944
1945 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1946 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1947 // body.
1948 Record *Class = Records.getClass(Name->getValue());
1949 if (!Class) {
1950 Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'");
1951 return nullptr;
1952 }
1953
1954 SmallVector<Init *, 8> Args;
1955 ParseValueList(Args, CurRec, Class);
1956 if (Args.empty()) return nullptr;
1957
1958 if (!consume(tgtok::greater)) {
1959 TokError("expected '>' at end of value list");
1960 return nullptr;
1961 }
1962
1963 // Typecheck the template arguments list
1964 ArrayRef<Init *> ExpectedArgs = Class->getTemplateArgs();
1965 if (ExpectedArgs.size() < Args.size()) {
1966 Error(NameLoc,
1967 "More template args specified than expected");
1968 return nullptr;
1969 }
1970
1971 for (unsigned i = 0, e = ExpectedArgs.size(); i != e; ++i) {
1972 RecordVal *ExpectedArg = Class->getValue(ExpectedArgs[i]);
1973 if (i < Args.size()) {
1974 if (TypedInit *TI = dyn_cast<TypedInit>(Args[i])) {
1975 RecTy *ExpectedType = ExpectedArg->getType();
1976 if (!TI->getType()->typeIsConvertibleTo(ExpectedType)) {
1977 Error(NameLoc,
1978 "Value specified for template argument #" + Twine(i) + " (" +
1979 ExpectedArg->getNameInitAsString() + ") is of type '" +
1980 TI->getType()->getAsString() + "', expected '" +
1981 ExpectedType->getAsString() + "': " + TI->getAsString());
1982 return nullptr;
1983 }
1984 continue;
1985 }
1986 } else if (ExpectedArg->getValue()->isComplete())
1987 continue;
1988
1989 Error(NameLoc,
1990 "Value not specified for template argument #" + Twine(i) + " (" +
1991 ExpectedArgs[i]->getAsUnquotedString() + ")");
1992 return nullptr;
1993 }
1994
1995 return VarDefInit::get(Class, Args)->Fold();
1996 }
1997 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1998 SMLoc BraceLoc = Lex.getLoc();
1999 Lex.Lex(); // eat the '{'
2000 SmallVector<Init*, 16> Vals;
2001
2002 if (Lex.getCode() != tgtok::r_brace) {
2003 ParseValueList(Vals, CurRec);
2004 if (Vals.empty()) return nullptr;
2005 }
2006 if (!consume(tgtok::r_brace)) {
2007 TokError("expected '}' at end of bit list value");
2008 return nullptr;
2009 }
2010
2011 SmallVector<Init *, 16> NewBits;
2012
2013 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
2014 // first. We'll first read everything in to a vector, then we can reverse
2015 // it to get the bits in the correct order for the BitsInit value.
2016 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2017 // FIXME: The following two loops would not be duplicated
2018 // if the API was a little more orthogonal.
2019
2020 // bits<n> values are allowed to initialize n bits.
2021 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
2022 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
2023 NewBits.push_back(BI->getBit((e - i) - 1));
2024 continue;
2025 }
2026 // bits<n> can also come from variable initializers.
2027 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
2028 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
2029 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
2030 NewBits.push_back(VI->getBit((e - i) - 1));
2031 continue;
2032 }
2033 // Fallthrough to try convert this to a bit.
2034 }
2035 // All other values must be convertible to just a single bit.
2036 Init *Bit = Vals[i]->getCastTo(BitRecTy::get());
2037 if (!Bit) {
2038 Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
2039 ") is not convertable to a bit");
2040 return nullptr;
2041 }
2042 NewBits.push_back(Bit);
2043 }
2044 std::reverse(NewBits.begin(), NewBits.end());
2045 return BitsInit::get(NewBits);
2046 }
2047 case tgtok::l_square: { // Value ::= '[' ValueList ']'
2048 Lex.Lex(); // eat the '['
2049 SmallVector<Init*, 16> Vals;
2050
2051 RecTy *DeducedEltTy = nullptr;
2052 ListRecTy *GivenListTy = nullptr;
2053
2054 if (ItemType) {
2055 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
2056 if (!ListType) {
2057 TokError(Twine("Encountered a list when expecting a ") +
2058 ItemType->getAsString());
2059 return nullptr;
2060 }
2061 GivenListTy = ListType;
2062 }
2063
2064 if (Lex.getCode() != tgtok::r_square) {
2065 ParseValueList(Vals, CurRec, nullptr,
2066 GivenListTy ? GivenListTy->getElementType() : nullptr);
2067 if (Vals.empty()) return nullptr;
2068 }
2069 if (!consume(tgtok::r_square)) {
2070 TokError("expected ']' at end of list value");
2071 return nullptr;
2072 }
2073
2074 RecTy *GivenEltTy = nullptr;
2075 if (consume(tgtok::less)) {
2076 // Optional list element type
2077 GivenEltTy = ParseType();
2078 if (!GivenEltTy) {
2079 // Couldn't parse element type
2080 return nullptr;
2081 }
2082
2083 if (!consume(tgtok::greater)) {
2084 TokError("expected '>' at end of list element type");
2085 return nullptr;
2086 }
2087 }
2088
2089 // Check elements
2090 RecTy *EltTy = nullptr;
2091 for (Init *V : Vals) {
2092 TypedInit *TArg = dyn_cast<TypedInit>(V);
2093 if (TArg) {
2094 if (EltTy) {
2095 EltTy = resolveTypes(EltTy, TArg->getType());
2096 if (!EltTy) {
2097 TokError("Incompatible types in list elements");
2098 return nullptr;
2099 }
2100 } else {
2101 EltTy = TArg->getType();
2102 }
2103 }
2104 }
2105
2106 if (GivenEltTy) {
2107 if (EltTy) {
2108 // Verify consistency
2109 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
2110 TokError("Incompatible types in list elements");
2111 return nullptr;
2112 }
2113 }
2114 EltTy = GivenEltTy;
2115 }
2116
2117 if (!EltTy) {
2118 if (!ItemType) {
2119 TokError("No type for list");
2120 return nullptr;
2121 }
2122 DeducedEltTy = GivenListTy->getElementType();
2123 } else {
2124 // Make sure the deduced type is compatible with the given type
2125 if (GivenListTy) {
2126 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
2127 TokError(Twine("Element type mismatch for list: element type '") +
2128 EltTy->getAsString() + "' not convertible to '" +
2129 GivenListTy->getElementType()->getAsString());
2130 return nullptr;
2131 }
2132 }
2133 DeducedEltTy = EltTy;
2134 }
2135
2136 return ListInit::get(Vals, DeducedEltTy);
2137 }
2138 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
2139 Lex.Lex(); // eat the '('
2140 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast &&
2141 Lex.getCode() != tgtok::question && Lex.getCode() != tgtok::XGetDagOp) {
2142 TokError("expected identifier in dag init");
2143 return nullptr;
2144 }
2145
2146 Init *Operator = ParseValue(CurRec);
2147 if (!Operator) return nullptr;
2148
2149 // If the operator name is present, parse it.
2150 StringInit *OperatorName = nullptr;
2151 if (consume(tgtok::colon)) {
2152 if (Lex.getCode() != tgtok::VarName) { // eat the ':'
2153 TokError("expected variable name in dag operator");
2154 return nullptr;
2155 }
2156 OperatorName = StringInit::get(Lex.getCurStrVal());
2157 Lex.Lex(); // eat the VarName.
2158 }
2159
2160 SmallVector<std::pair<llvm::Init*, StringInit*>, 8> DagArgs;
2161 if (Lex.getCode() != tgtok::r_paren) {
2162 ParseDagArgList(DagArgs, CurRec);
2163 if (DagArgs.empty()) return nullptr;
2164 }
2165
2166 if (!consume(tgtok::r_paren)) {
2167 TokError("expected ')' in dag init");
2168 return nullptr;
2169 }
2170
2171 return DagInit::get(Operator, OperatorName, DagArgs);
2172 }
2173
2174 case tgtok::XHead:
2175 case tgtok::XTail:
2176 case tgtok::XSize:
2177 case tgtok::XEmpty:
2178 case tgtok::XCast:
2179 case tgtok::XGetDagOp: // Value ::= !unop '(' Value ')'
2180 case tgtok::XIsA:
2181 case tgtok::XConcat:
2182 case tgtok::XDag:
2183 case tgtok::XADD:
2184 case tgtok::XSUB:
2185 case tgtok::XMUL:
2186 case tgtok::XNOT:
2187 case tgtok::XAND:
2188 case tgtok::XOR:
2189 case tgtok::XXOR:
2190 case tgtok::XSRA:
2191 case tgtok::XSRL:
2192 case tgtok::XSHL:
2193 case tgtok::XEq:
2194 case tgtok::XNe:
2195 case tgtok::XLe:
2196 case tgtok::XLt:
2197 case tgtok::XGe:
2198 case tgtok::XGt:
2199 case tgtok::XListConcat:
2200 case tgtok::XListSplat:
2201 case tgtok::XStrConcat:
2202 case tgtok::XInterleave:
2203 case tgtok::XSetDagOp: // Value ::= !binop '(' Value ',' Value ')'
2204 case tgtok::XIf:
2205 case tgtok::XCond:
2206 case tgtok::XFoldl:
2207 case tgtok::XForEach:
2208 case tgtok::XFilter:
2209 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
2210 return ParseOperation(CurRec, ItemType);
2211 }
2212 }
2213
2214 return R;
2215 }
2216
2217 /// ParseValue - Parse a tblgen value. This returns null on error.
2218 ///
2219 /// Value ::= SimpleValue ValueSuffix*
2220 /// ValueSuffix ::= '{' BitList '}'
2221 /// ValueSuffix ::= '[' BitList ']'
2222 /// ValueSuffix ::= '.' ID
2223 ///
ParseValue(Record * CurRec,RecTy * ItemType,IDParseMode Mode)2224 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
2225 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
2226 if (!Result) return nullptr;
2227
2228 // Parse the suffixes now if present.
2229 while (true) {
2230 switch (Lex.getCode()) {
2231 default: return Result;
2232 case tgtok::l_brace: {
2233 if (Mode == ParseNameMode)
2234 // This is the beginning of the object body.
2235 return Result;
2236
2237 SMLoc CurlyLoc = Lex.getLoc();
2238 Lex.Lex(); // eat the '{'
2239 SmallVector<unsigned, 16> Ranges;
2240 ParseRangeList(Ranges);
2241 if (Ranges.empty()) return nullptr;
2242
2243 // Reverse the bitlist.
2244 std::reverse(Ranges.begin(), Ranges.end());
2245 Result = Result->convertInitializerBitRange(Ranges);
2246 if (!Result) {
2247 Error(CurlyLoc, "Invalid bit range for value");
2248 return nullptr;
2249 }
2250
2251 // Eat the '}'.
2252 if (!consume(tgtok::r_brace)) {
2253 TokError("expected '}' at end of bit range list");
2254 return nullptr;
2255 }
2256 break;
2257 }
2258 case tgtok::l_square: {
2259 SMLoc SquareLoc = Lex.getLoc();
2260 Lex.Lex(); // eat the '['
2261 SmallVector<unsigned, 16> Ranges;
2262 ParseRangeList(Ranges);
2263 if (Ranges.empty()) return nullptr;
2264
2265 Result = Result->convertInitListSlice(Ranges);
2266 if (!Result) {
2267 Error(SquareLoc, "Invalid range for list slice");
2268 return nullptr;
2269 }
2270
2271 // Eat the ']'.
2272 if (!consume(tgtok::r_square)) {
2273 TokError("expected ']' at end of list slice");
2274 return nullptr;
2275 }
2276 break;
2277 }
2278 case tgtok::dot: {
2279 if (Lex.Lex() != tgtok::Id) { // eat the .
2280 TokError("expected field identifier after '.'");
2281 return nullptr;
2282 }
2283 StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2284 if (!Result->getFieldType(FieldName)) {
2285 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
2286 Result->getAsString() + "'");
2287 return nullptr;
2288 }
2289 Result = FieldInit::get(Result, FieldName)->Fold(CurRec);
2290 Lex.Lex(); // eat field name
2291 break;
2292 }
2293
2294 case tgtok::paste:
2295 SMLoc PasteLoc = Lex.getLoc();
2296 TypedInit *LHS = dyn_cast<TypedInit>(Result);
2297 if (!LHS) {
2298 Error(PasteLoc, "LHS of paste is not typed!");
2299 return nullptr;
2300 }
2301
2302 // Check if it's a 'listA # listB'
2303 if (isa<ListRecTy>(LHS->getType())) {
2304 Lex.Lex(); // Eat the '#'.
2305
2306 assert(Mode == ParseValueMode && "encountered paste of lists in name");
2307
2308 switch (Lex.getCode()) {
2309 case tgtok::colon:
2310 case tgtok::semi:
2311 case tgtok::l_brace:
2312 Result = LHS; // trailing paste, ignore.
2313 break;
2314 default:
2315 Init *RHSResult = ParseValue(CurRec, ItemType, ParseValueMode);
2316 if (!RHSResult)
2317 return nullptr;
2318 Result = BinOpInit::getListConcat(LHS, RHSResult);
2319 break;
2320 }
2321 break;
2322 }
2323
2324 // Create a !strconcat() operation, first casting each operand to
2325 // a string if necessary.
2326 if (LHS->getType() != StringRecTy::get()) {
2327 auto CastLHS = dyn_cast<TypedInit>(
2328 UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get())
2329 ->Fold(CurRec));
2330 if (!CastLHS) {
2331 Error(PasteLoc,
2332 Twine("can't cast '") + LHS->getAsString() + "' to string");
2333 return nullptr;
2334 }
2335 LHS = CastLHS;
2336 }
2337
2338 TypedInit *RHS = nullptr;
2339
2340 Lex.Lex(); // Eat the '#'.
2341 switch (Lex.getCode()) {
2342 case tgtok::colon:
2343 case tgtok::semi:
2344 case tgtok::l_brace:
2345 // These are all of the tokens that can begin an object body.
2346 // Some of these can also begin values but we disallow those cases
2347 // because they are unlikely to be useful.
2348
2349 // Trailing paste, concat with an empty string.
2350 RHS = StringInit::get("");
2351 break;
2352
2353 default:
2354 Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode);
2355 if (!RHSResult)
2356 return nullptr;
2357 RHS = dyn_cast<TypedInit>(RHSResult);
2358 if (!RHS) {
2359 Error(PasteLoc, "RHS of paste is not typed!");
2360 return nullptr;
2361 }
2362
2363 if (RHS->getType() != StringRecTy::get()) {
2364 auto CastRHS = dyn_cast<TypedInit>(
2365 UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get())
2366 ->Fold(CurRec));
2367 if (!CastRHS) {
2368 Error(PasteLoc,
2369 Twine("can't cast '") + RHS->getAsString() + "' to string");
2370 return nullptr;
2371 }
2372 RHS = CastRHS;
2373 }
2374
2375 break;
2376 }
2377
2378 Result = BinOpInit::getStrConcat(LHS, RHS);
2379 break;
2380 }
2381 }
2382 }
2383
2384 /// ParseDagArgList - Parse the argument list for a dag literal expression.
2385 ///
2386 /// DagArg ::= Value (':' VARNAME)?
2387 /// DagArg ::= VARNAME
2388 /// DagArgList ::= DagArg
2389 /// DagArgList ::= DagArgList ',' DagArg
ParseDagArgList(SmallVectorImpl<std::pair<llvm::Init *,StringInit * >> & Result,Record * CurRec)2390 void TGParser::ParseDagArgList(
2391 SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result,
2392 Record *CurRec) {
2393
2394 while (true) {
2395 // DagArg ::= VARNAME
2396 if (Lex.getCode() == tgtok::VarName) {
2397 // A missing value is treated like '?'.
2398 StringInit *VarName = StringInit::get(Lex.getCurStrVal());
2399 Result.emplace_back(UnsetInit::get(), VarName);
2400 Lex.Lex();
2401 } else {
2402 // DagArg ::= Value (':' VARNAME)?
2403 Init *Val = ParseValue(CurRec);
2404 if (!Val) {
2405 Result.clear();
2406 return;
2407 }
2408
2409 // If the variable name is present, add it.
2410 StringInit *VarName = nullptr;
2411 if (Lex.getCode() == tgtok::colon) {
2412 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
2413 TokError("expected variable name in dag literal");
2414 Result.clear();
2415 return;
2416 }
2417 VarName = StringInit::get(Lex.getCurStrVal());
2418 Lex.Lex(); // eat the VarName.
2419 }
2420
2421 Result.push_back(std::make_pair(Val, VarName));
2422 }
2423 if (!consume(tgtok::comma))
2424 break;
2425 }
2426 }
2427
2428 /// ParseValueList - Parse a comma separated list of values, returning them as a
2429 /// vector. Note that this always expects to be able to parse at least one
2430 /// value. It returns an empty list if this is not possible.
2431 ///
2432 /// ValueList ::= Value (',' Value)
2433 ///
ParseValueList(SmallVectorImpl<Init * > & Result,Record * CurRec,Record * ArgsRec,RecTy * EltTy)2434 void TGParser::ParseValueList(SmallVectorImpl<Init*> &Result, Record *CurRec,
2435 Record *ArgsRec, RecTy *EltTy) {
2436 RecTy *ItemType = EltTy;
2437 unsigned int ArgN = 0;
2438 if (ArgsRec && !EltTy) {
2439 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2440 if (TArgs.empty()) {
2441 TokError("template argument provided to non-template class");
2442 Result.clear();
2443 return;
2444 }
2445 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2446 if (!RV) {
2447 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
2448 << ")\n";
2449 }
2450 assert(RV && "Template argument record not found??");
2451 ItemType = RV->getType();
2452 ++ArgN;
2453 }
2454 Result.push_back(ParseValue(CurRec, ItemType));
2455 if (!Result.back()) {
2456 Result.clear();
2457 return;
2458 }
2459
2460 while (consume(tgtok::comma)) {
2461 // ignore trailing comma for lists
2462 if (Lex.getCode() == tgtok::r_square)
2463 return;
2464
2465 if (ArgsRec && !EltTy) {
2466 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2467 if (ArgN >= TArgs.size()) {
2468 TokError("too many template arguments");
2469 Result.clear();
2470 return;
2471 }
2472 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2473 assert(RV && "Template argument record not found??");
2474 ItemType = RV->getType();
2475 ++ArgN;
2476 }
2477 Result.push_back(ParseValue(CurRec, ItemType));
2478 if (!Result.back()) {
2479 Result.clear();
2480 return;
2481 }
2482 }
2483 }
2484
2485 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
2486 /// empty string on error. This can happen in a number of different context's,
2487 /// including within a def or in the template args for a def (which which case
2488 /// CurRec will be non-null) and within the template args for a multiclass (in
2489 /// which case CurRec will be null, but CurMultiClass will be set). This can
2490 /// also happen within a def that is within a multiclass, which will set both
2491 /// CurRec and CurMultiClass.
2492 ///
2493 /// Declaration ::= FIELD? Type ID ('=' Value)?
2494 ///
ParseDeclaration(Record * CurRec,bool ParsingTemplateArgs)2495 Init *TGParser::ParseDeclaration(Record *CurRec,
2496 bool ParsingTemplateArgs) {
2497 // Read the field prefix if present.
2498 bool HasField = consume(tgtok::Field);
2499
2500 RecTy *Type = ParseType();
2501 if (!Type) return nullptr;
2502
2503 if (Lex.getCode() != tgtok::Id) {
2504 TokError("Expected identifier in declaration");
2505 return nullptr;
2506 }
2507
2508 std::string Str = Lex.getCurStrVal();
2509 if (Str == "NAME") {
2510 TokError("'" + Str + "' is a reserved variable name");
2511 return nullptr;
2512 }
2513
2514 SMLoc IdLoc = Lex.getLoc();
2515 Init *DeclName = StringInit::get(Str);
2516 Lex.Lex();
2517
2518 if (ParsingTemplateArgs) {
2519 if (CurRec)
2520 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
2521 else
2522 assert(CurMultiClass);
2523 if (CurMultiClass)
2524 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
2525 "::");
2526 }
2527
2528 // Add the value.
2529 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, IdLoc, Type, HasField)))
2530 return nullptr;
2531
2532 // If a value is present, parse it.
2533 if (consume(tgtok::equal)) {
2534 SMLoc ValLoc = Lex.getLoc();
2535 Init *Val = ParseValue(CurRec, Type);
2536 if (!Val ||
2537 SetValue(CurRec, ValLoc, DeclName, None, Val))
2538 // Return the name, even if an error is thrown. This is so that we can
2539 // continue to make some progress, even without the value having been
2540 // initialized.
2541 return DeclName;
2542 }
2543
2544 return DeclName;
2545 }
2546
2547 /// ParseForeachDeclaration - Read a foreach declaration, returning
2548 /// the name of the declared object or a NULL Init on error. Return
2549 /// the name of the parsed initializer list through ForeachListName.
2550 ///
2551 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
2552 /// ForeachDeclaration ::= ID '=' RangePiece
2553 /// ForeachDeclaration ::= ID '=' Value
2554 ///
ParseForeachDeclaration(Init * & ForeachListValue)2555 VarInit *TGParser::ParseForeachDeclaration(Init *&ForeachListValue) {
2556 if (Lex.getCode() != tgtok::Id) {
2557 TokError("Expected identifier in foreach declaration");
2558 return nullptr;
2559 }
2560
2561 Init *DeclName = StringInit::get(Lex.getCurStrVal());
2562 Lex.Lex();
2563
2564 // If a value is present, parse it.
2565 if (!consume(tgtok::equal)) {
2566 TokError("Expected '=' in foreach declaration");
2567 return nullptr;
2568 }
2569
2570 RecTy *IterType = nullptr;
2571 SmallVector<unsigned, 16> Ranges;
2572
2573 switch (Lex.getCode()) {
2574 case tgtok::l_brace: { // '{' RangeList '}'
2575 Lex.Lex(); // eat the '{'
2576 ParseRangeList(Ranges);
2577 if (!consume(tgtok::r_brace)) {
2578 TokError("expected '}' at end of bit range list");
2579 return nullptr;
2580 }
2581 break;
2582 }
2583
2584 default: {
2585 SMLoc ValueLoc = Lex.getLoc();
2586 Init *I = ParseValue(nullptr);
2587 if (!I)
2588 return nullptr;
2589
2590 TypedInit *TI = dyn_cast<TypedInit>(I);
2591 if (TI && isa<ListRecTy>(TI->getType())) {
2592 ForeachListValue = I;
2593 IterType = cast<ListRecTy>(TI->getType())->getElementType();
2594 break;
2595 }
2596
2597 if (TI) {
2598 if (ParseRangePiece(Ranges, TI))
2599 return nullptr;
2600 break;
2601 }
2602
2603 std::string Type;
2604 if (TI)
2605 Type = (Twine("' of type '") + TI->getType()->getAsString()).str();
2606 Error(ValueLoc, "expected a list, got '" + I->getAsString() + Type + "'");
2607 if (CurMultiClass) {
2608 PrintNote({}, "references to multiclass template arguments cannot be "
2609 "resolved at this time");
2610 }
2611 return nullptr;
2612 }
2613 }
2614
2615
2616 if (!Ranges.empty()) {
2617 assert(!IterType && "Type already initialized?");
2618 IterType = IntRecTy::get();
2619 std::vector<Init*> Values;
2620 for (unsigned R : Ranges)
2621 Values.push_back(IntInit::get(R));
2622 ForeachListValue = ListInit::get(Values, IterType);
2623 }
2624
2625 if (!IterType)
2626 return nullptr;
2627
2628 return VarInit::get(DeclName, IterType);
2629 }
2630
2631 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
2632 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
2633 /// template args for a def, which may or may not be in a multiclass. If null,
2634 /// these are the template args for a multiclass.
2635 ///
2636 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
2637 ///
ParseTemplateArgList(Record * CurRec)2638 bool TGParser::ParseTemplateArgList(Record *CurRec) {
2639 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
2640 Lex.Lex(); // eat the '<'
2641
2642 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
2643
2644 // Read the first declaration.
2645 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2646 if (!TemplArg)
2647 return true;
2648
2649 TheRecToAddTo->addTemplateArg(TemplArg);
2650
2651 while (consume(tgtok::comma)) {
2652 // Read the following declarations.
2653 SMLoc Loc = Lex.getLoc();
2654 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2655 if (!TemplArg)
2656 return true;
2657
2658 if (TheRecToAddTo->isTemplateArg(TemplArg))
2659 return Error(Loc, "template argument with the same name has already been "
2660 "defined");
2661
2662 TheRecToAddTo->addTemplateArg(TemplArg);
2663 }
2664
2665 if (!consume(tgtok::greater))
2666 return TokError("expected '>' at end of template argument list");
2667 return false;
2668 }
2669
2670 /// ParseBodyItem - Parse a single item at within the body of a def or class.
2671 ///
2672 /// BodyItem ::= Declaration ';'
2673 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
2674 /// BodyItem ::= Defvar
ParseBodyItem(Record * CurRec)2675 bool TGParser::ParseBodyItem(Record *CurRec) {
2676 if (Lex.getCode() == tgtok::Defvar)
2677 return ParseDefvar();
2678
2679 if (Lex.getCode() != tgtok::Let) {
2680 if (!ParseDeclaration(CurRec, false))
2681 return true;
2682
2683 if (!consume(tgtok::semi))
2684 return TokError("expected ';' after declaration");
2685 return false;
2686 }
2687
2688 // LET ID OptionalRangeList '=' Value ';'
2689 if (Lex.Lex() != tgtok::Id)
2690 return TokError("expected field identifier after let");
2691
2692 SMLoc IdLoc = Lex.getLoc();
2693 StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2694 Lex.Lex(); // eat the field name.
2695
2696 SmallVector<unsigned, 16> BitList;
2697 if (ParseOptionalBitList(BitList))
2698 return true;
2699 std::reverse(BitList.begin(), BitList.end());
2700
2701 if (!consume(tgtok::equal))
2702 return TokError("expected '=' in let expression");
2703
2704 RecordVal *Field = CurRec->getValue(FieldName);
2705 if (!Field)
2706 return TokError("Value '" + FieldName->getValue() + "' unknown!");
2707
2708 RecTy *Type = Field->getType();
2709 if (!BitList.empty() && isa<BitsRecTy>(Type)) {
2710 // When assigning to a subset of a 'bits' object, expect the RHS to have
2711 // the type of that subset instead of the type of the whole object.
2712 Type = BitsRecTy::get(BitList.size());
2713 }
2714
2715 Init *Val = ParseValue(CurRec, Type);
2716 if (!Val) return true;
2717
2718 if (!consume(tgtok::semi))
2719 return TokError("expected ';' after let expression");
2720
2721 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
2722 }
2723
2724 /// ParseBody - Read the body of a class or def. Return true on error, false on
2725 /// success.
2726 ///
2727 /// Body ::= ';'
2728 /// Body ::= '{' BodyList '}'
2729 /// BodyList BodyItem*
2730 ///
ParseBody(Record * CurRec)2731 bool TGParser::ParseBody(Record *CurRec) {
2732 // If this is a null definition, just eat the semi and return.
2733 if (consume(tgtok::semi))
2734 return false;
2735
2736 if (!consume(tgtok::l_brace))
2737 return TokError("Expected ';' or '{' to start body");
2738
2739 // An object body introduces a new scope for local variables.
2740 TGLocalVarScope *BodyScope = PushLocalScope();
2741
2742 while (Lex.getCode() != tgtok::r_brace)
2743 if (ParseBodyItem(CurRec))
2744 return true;
2745
2746 PopLocalScope(BodyScope);
2747
2748 // Eat the '}'.
2749 Lex.Lex();
2750 return false;
2751 }
2752
2753 /// Apply the current let bindings to \a CurRec.
2754 /// \returns true on error, false otherwise.
ApplyLetStack(Record * CurRec)2755 bool TGParser::ApplyLetStack(Record *CurRec) {
2756 for (SmallVectorImpl<LetRecord> &LetInfo : LetStack)
2757 for (LetRecord &LR : LetInfo)
2758 if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
2759 return true;
2760 return false;
2761 }
2762
ApplyLetStack(RecordsEntry & Entry)2763 bool TGParser::ApplyLetStack(RecordsEntry &Entry) {
2764 if (Entry.Rec)
2765 return ApplyLetStack(Entry.Rec.get());
2766
2767 for (auto &E : Entry.Loop->Entries) {
2768 if (ApplyLetStack(E))
2769 return true;
2770 }
2771
2772 return false;
2773 }
2774
2775 /// ParseObjectBody - Parse the body of a def or class. This consists of an
2776 /// optional ClassList followed by a Body. CurRec is the current def or class
2777 /// that is being parsed.
2778 ///
2779 /// ObjectBody ::= BaseClassList Body
2780 /// BaseClassList ::= /*empty*/
2781 /// BaseClassList ::= ':' BaseClassListNE
2782 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
2783 ///
ParseObjectBody(Record * CurRec)2784 bool TGParser::ParseObjectBody(Record *CurRec) {
2785 // If there is a baseclass list, read it.
2786 if (consume(tgtok::colon)) {
2787
2788 // Read all of the subclasses.
2789 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
2790 while (true) {
2791 // Check for error.
2792 if (!SubClass.Rec) return true;
2793
2794 // Add it.
2795 if (AddSubClass(CurRec, SubClass))
2796 return true;
2797
2798 if (!consume(tgtok::comma))
2799 break;
2800 SubClass = ParseSubClassReference(CurRec, false);
2801 }
2802 }
2803
2804 if (ApplyLetStack(CurRec))
2805 return true;
2806
2807 return ParseBody(CurRec);
2808 }
2809
2810 /// ParseDef - Parse and return a top level or multiclass def, return the record
2811 /// corresponding to it. This returns null on error.
2812 ///
2813 /// DefInst ::= DEF ObjectName ObjectBody
2814 ///
ParseDef(MultiClass * CurMultiClass)2815 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
2816 SMLoc DefLoc = Lex.getLoc();
2817 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
2818 Lex.Lex(); // Eat the 'def' token.
2819
2820 // Parse ObjectName and make a record for it.
2821 std::unique_ptr<Record> CurRec;
2822 Init *Name = ParseObjectName(CurMultiClass);
2823 if (!Name)
2824 return true;
2825
2826 if (isa<UnsetInit>(Name))
2827 CurRec = std::make_unique<Record>(Records.getNewAnonymousName(), DefLoc, Records,
2828 /*Anonymous=*/true);
2829 else
2830 CurRec = std::make_unique<Record>(Name, DefLoc, Records);
2831
2832 if (ParseObjectBody(CurRec.get()))
2833 return true;
2834
2835 return addEntry(std::move(CurRec));
2836 }
2837
2838 /// ParseDefset - Parse a defset statement.
2839 ///
2840 /// Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
2841 ///
ParseDefset()2842 bool TGParser::ParseDefset() {
2843 assert(Lex.getCode() == tgtok::Defset);
2844 Lex.Lex(); // Eat the 'defset' token
2845
2846 DefsetRecord Defset;
2847 Defset.Loc = Lex.getLoc();
2848 RecTy *Type = ParseType();
2849 if (!Type)
2850 return true;
2851 if (!isa<ListRecTy>(Type))
2852 return Error(Defset.Loc, "expected list type");
2853 Defset.EltTy = cast<ListRecTy>(Type)->getElementType();
2854
2855 if (Lex.getCode() != tgtok::Id)
2856 return TokError("expected identifier");
2857 StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
2858 if (Records.getGlobal(DeclName->getValue()))
2859 return TokError("def or global variable of this name already exists");
2860
2861 if (Lex.Lex() != tgtok::equal) // Eat the identifier
2862 return TokError("expected '='");
2863 if (Lex.Lex() != tgtok::l_brace) // Eat the '='
2864 return TokError("expected '{'");
2865 SMLoc BraceLoc = Lex.getLoc();
2866 Lex.Lex(); // Eat the '{'
2867
2868 Defsets.push_back(&Defset);
2869 bool Err = ParseObjectList(nullptr);
2870 Defsets.pop_back();
2871 if (Err)
2872 return true;
2873
2874 if (!consume(tgtok::r_brace)) {
2875 TokError("expected '}' at end of defset");
2876 return Error(BraceLoc, "to match this '{'");
2877 }
2878
2879 Records.addExtraGlobal(DeclName->getValue(),
2880 ListInit::get(Defset.Elements, Defset.EltTy));
2881 return false;
2882 }
2883
2884 /// ParseDefvar - Parse a defvar statement.
2885 ///
2886 /// Defvar ::= DEFVAR Id '=' Value ';'
2887 ///
ParseDefvar()2888 bool TGParser::ParseDefvar() {
2889 assert(Lex.getCode() == tgtok::Defvar);
2890 Lex.Lex(); // Eat the 'defvar' token
2891
2892 if (Lex.getCode() != tgtok::Id)
2893 return TokError("expected identifier");
2894 StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
2895 if (CurLocalScope) {
2896 if (CurLocalScope->varAlreadyDefined(DeclName->getValue()))
2897 return TokError("local variable of this name already exists");
2898 } else {
2899 if (Records.getGlobal(DeclName->getValue()))
2900 return TokError("def or global variable of this name already exists");
2901 }
2902
2903 Lex.Lex();
2904 if (!consume(tgtok::equal))
2905 return TokError("expected '='");
2906
2907 Init *Value = ParseValue(nullptr);
2908 if (!Value)
2909 return true;
2910
2911 if (!consume(tgtok::semi))
2912 return TokError("expected ';'");
2913
2914 if (CurLocalScope)
2915 CurLocalScope->addVar(DeclName->getValue(), Value);
2916 else
2917 Records.addExtraGlobal(DeclName->getValue(), Value);
2918
2919 return false;
2920 }
2921
2922 /// ParseForeach - Parse a for statement. Return the record corresponding
2923 /// to it. This returns true on error.
2924 ///
2925 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2926 /// Foreach ::= FOREACH Declaration IN Object
2927 ///
ParseForeach(MultiClass * CurMultiClass)2928 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2929 SMLoc Loc = Lex.getLoc();
2930 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2931 Lex.Lex(); // Eat the 'for' token.
2932
2933 // Make a temporary object to record items associated with the for
2934 // loop.
2935 Init *ListValue = nullptr;
2936 VarInit *IterName = ParseForeachDeclaration(ListValue);
2937 if (!IterName)
2938 return TokError("expected declaration in for");
2939
2940 if (!consume(tgtok::In))
2941 return TokError("Unknown tok");
2942
2943 // Create a loop object and remember it.
2944 Loops.push_back(std::make_unique<ForeachLoop>(Loc, IterName, ListValue));
2945
2946 // A foreach loop introduces a new scope for local variables.
2947 TGLocalVarScope *ForeachScope = PushLocalScope();
2948
2949 if (Lex.getCode() != tgtok::l_brace) {
2950 // FOREACH Declaration IN Object
2951 if (ParseObject(CurMultiClass))
2952 return true;
2953 } else {
2954 SMLoc BraceLoc = Lex.getLoc();
2955 // Otherwise, this is a group foreach.
2956 Lex.Lex(); // eat the '{'.
2957
2958 // Parse the object list.
2959 if (ParseObjectList(CurMultiClass))
2960 return true;
2961
2962 if (!consume(tgtok::r_brace)) {
2963 TokError("expected '}' at end of foreach command");
2964 return Error(BraceLoc, "to match this '{'");
2965 }
2966 }
2967
2968 PopLocalScope(ForeachScope);
2969
2970 // Resolve the loop or store it for later resolution.
2971 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
2972 Loops.pop_back();
2973
2974 return addEntry(std::move(Loop));
2975 }
2976
2977 /// ParseIf - Parse an if statement.
2978 ///
2979 /// If ::= IF Value THEN IfBody
2980 /// If ::= IF Value THEN IfBody ELSE IfBody
2981 ///
ParseIf(MultiClass * CurMultiClass)2982 bool TGParser::ParseIf(MultiClass *CurMultiClass) {
2983 SMLoc Loc = Lex.getLoc();
2984 assert(Lex.getCode() == tgtok::If && "Unknown tok");
2985 Lex.Lex(); // Eat the 'if' token.
2986
2987 // Make a temporary object to record items associated with the for
2988 // loop.
2989 Init *Condition = ParseValue(nullptr);
2990 if (!Condition)
2991 return true;
2992
2993 if (!consume(tgtok::Then))
2994 return TokError("Unknown tok");
2995
2996 // We have to be able to save if statements to execute later, and they have
2997 // to live on the same stack as foreach loops. The simplest implementation
2998 // technique is to convert each 'then' or 'else' clause *into* a foreach
2999 // loop, over a list of length 0 or 1 depending on the condition, and with no
3000 // iteration variable being assigned.
3001
3002 ListInit *EmptyList = ListInit::get({}, BitRecTy::get());
3003 ListInit *SingletonList = ListInit::get({BitInit::get(1)}, BitRecTy::get());
3004 RecTy *BitListTy = ListRecTy::get(BitRecTy::get());
3005
3006 // The foreach containing the then-clause selects SingletonList if
3007 // the condition is true.
3008 Init *ThenClauseList =
3009 TernOpInit::get(TernOpInit::IF, Condition, SingletonList, EmptyList,
3010 BitListTy)
3011 ->Fold(nullptr);
3012 Loops.push_back(std::make_unique<ForeachLoop>(Loc, nullptr, ThenClauseList));
3013
3014 if (ParseIfBody(CurMultiClass, "then"))
3015 return true;
3016
3017 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
3018 Loops.pop_back();
3019
3020 if (addEntry(std::move(Loop)))
3021 return true;
3022
3023 // Now look for an optional else clause. The if-else syntax has the usual
3024 // dangling-else ambiguity, and by greedily matching an else here if we can,
3025 // we implement the usual resolution of pairing with the innermost unmatched
3026 // if.
3027 if (consume(tgtok::ElseKW)) {
3028 // The foreach containing the else-clause uses the same pair of lists as
3029 // above, but this time, selects SingletonList if the condition is *false*.
3030 Init *ElseClauseList =
3031 TernOpInit::get(TernOpInit::IF, Condition, EmptyList, SingletonList,
3032 BitListTy)
3033 ->Fold(nullptr);
3034 Loops.push_back(
3035 std::make_unique<ForeachLoop>(Loc, nullptr, ElseClauseList));
3036
3037 if (ParseIfBody(CurMultiClass, "else"))
3038 return true;
3039
3040 Loop = std::move(Loops.back());
3041 Loops.pop_back();
3042
3043 if (addEntry(std::move(Loop)))
3044 return true;
3045 }
3046
3047 return false;
3048 }
3049
3050 /// ParseIfBody - Parse the then-clause or else-clause of an if statement.
3051 ///
3052 /// IfBody ::= Object
3053 /// IfBody ::= '{' ObjectList '}'
3054 ///
ParseIfBody(MultiClass * CurMultiClass,StringRef Kind)3055 bool TGParser::ParseIfBody(MultiClass *CurMultiClass, StringRef Kind) {
3056 TGLocalVarScope *BodyScope = PushLocalScope();
3057
3058 if (Lex.getCode() != tgtok::l_brace) {
3059 // A single object.
3060 if (ParseObject(CurMultiClass))
3061 return true;
3062 } else {
3063 SMLoc BraceLoc = Lex.getLoc();
3064 // A braced block.
3065 Lex.Lex(); // eat the '{'.
3066
3067 // Parse the object list.
3068 if (ParseObjectList(CurMultiClass))
3069 return true;
3070
3071 if (!consume(tgtok::r_brace)) {
3072 TokError("expected '}' at end of '" + Kind + "' clause");
3073 return Error(BraceLoc, "to match this '{'");
3074 }
3075 }
3076
3077 PopLocalScope(BodyScope);
3078 return false;
3079 }
3080
3081 /// ParseClass - Parse a tblgen class definition.
3082 ///
3083 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
3084 ///
ParseClass()3085 bool TGParser::ParseClass() {
3086 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
3087 Lex.Lex();
3088
3089 if (Lex.getCode() != tgtok::Id)
3090 return TokError("expected class name after 'class' keyword");
3091
3092 Record *CurRec = Records.getClass(Lex.getCurStrVal());
3093 if (CurRec) {
3094 // If the body was previously defined, this is an error.
3095 if (!CurRec->getValues().empty() ||
3096 !CurRec->getSuperClasses().empty() ||
3097 !CurRec->getTemplateArgs().empty())
3098 return TokError("Class '" + CurRec->getNameInitAsString() +
3099 "' already defined");
3100 } else {
3101 // If this is the first reference to this class, create and add it.
3102 auto NewRec =
3103 std::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records,
3104 /*Class=*/true);
3105 CurRec = NewRec.get();
3106 Records.addClass(std::move(NewRec));
3107 }
3108 Lex.Lex(); // eat the name.
3109
3110 // If there are template args, parse them.
3111 if (Lex.getCode() == tgtok::less)
3112 if (ParseTemplateArgList(CurRec))
3113 return true;
3114
3115 return ParseObjectBody(CurRec);
3116 }
3117
3118 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
3119 /// of LetRecords.
3120 ///
3121 /// LetList ::= LetItem (',' LetItem)*
3122 /// LetItem ::= ID OptionalRangeList '=' Value
3123 ///
ParseLetList(SmallVectorImpl<LetRecord> & Result)3124 void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) {
3125 do {
3126 if (Lex.getCode() != tgtok::Id) {
3127 TokError("expected identifier in let definition");
3128 Result.clear();
3129 return;
3130 }
3131
3132 StringInit *Name = StringInit::get(Lex.getCurStrVal());
3133 SMLoc NameLoc = Lex.getLoc();
3134 Lex.Lex(); // Eat the identifier.
3135
3136 // Check for an optional RangeList.
3137 SmallVector<unsigned, 16> Bits;
3138 if (ParseOptionalRangeList(Bits)) {
3139 Result.clear();
3140 return;
3141 }
3142 std::reverse(Bits.begin(), Bits.end());
3143
3144 if (!consume(tgtok::equal)) {
3145 TokError("expected '=' in let expression");
3146 Result.clear();
3147 return;
3148 }
3149
3150 Init *Val = ParseValue(nullptr);
3151 if (!Val) {
3152 Result.clear();
3153 return;
3154 }
3155
3156 // Now that we have everything, add the record.
3157 Result.emplace_back(Name, Bits, Val, NameLoc);
3158 } while (consume(tgtok::comma));
3159 }
3160
3161 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
3162 /// different related productions. This works inside multiclasses too.
3163 ///
3164 /// Object ::= LET LetList IN '{' ObjectList '}'
3165 /// Object ::= LET LetList IN Object
3166 ///
ParseTopLevelLet(MultiClass * CurMultiClass)3167 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
3168 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
3169 Lex.Lex();
3170
3171 // Add this entry to the let stack.
3172 SmallVector<LetRecord, 8> LetInfo;
3173 ParseLetList(LetInfo);
3174 if (LetInfo.empty()) return true;
3175 LetStack.push_back(std::move(LetInfo));
3176
3177 if (!consume(tgtok::In))
3178 return TokError("expected 'in' at end of top-level 'let'");
3179
3180 TGLocalVarScope *LetScope = PushLocalScope();
3181
3182 // If this is a scalar let, just handle it now
3183 if (Lex.getCode() != tgtok::l_brace) {
3184 // LET LetList IN Object
3185 if (ParseObject(CurMultiClass))
3186 return true;
3187 } else { // Object ::= LETCommand '{' ObjectList '}'
3188 SMLoc BraceLoc = Lex.getLoc();
3189 // Otherwise, this is a group let.
3190 Lex.Lex(); // eat the '{'.
3191
3192 // Parse the object list.
3193 if (ParseObjectList(CurMultiClass))
3194 return true;
3195
3196 if (!consume(tgtok::r_brace)) {
3197 TokError("expected '}' at end of top level let command");
3198 return Error(BraceLoc, "to match this '{'");
3199 }
3200 }
3201
3202 PopLocalScope(LetScope);
3203
3204 // Outside this let scope, this let block is not active.
3205 LetStack.pop_back();
3206 return false;
3207 }
3208
3209 /// ParseMultiClass - Parse a multiclass definition.
3210 ///
3211 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
3212 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
3213 /// MultiClassObject ::= DefInst
3214 /// MultiClassObject ::= MultiClassInst
3215 /// MultiClassObject ::= DefMInst
3216 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
3217 /// MultiClassObject ::= LETCommand Object
3218 ///
ParseMultiClass()3219 bool TGParser::ParseMultiClass() {
3220 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
3221 Lex.Lex(); // Eat the multiclass token.
3222
3223 if (Lex.getCode() != tgtok::Id)
3224 return TokError("expected identifier after multiclass for name");
3225 std::string Name = Lex.getCurStrVal();
3226
3227 auto Result =
3228 MultiClasses.insert(std::make_pair(Name,
3229 std::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
3230
3231 if (!Result.second)
3232 return TokError("multiclass '" + Name + "' already defined");
3233
3234 CurMultiClass = Result.first->second.get();
3235 Lex.Lex(); // Eat the identifier.
3236
3237 // If there are template args, parse them.
3238 if (Lex.getCode() == tgtok::less)
3239 if (ParseTemplateArgList(nullptr))
3240 return true;
3241
3242 bool inherits = false;
3243
3244 // If there are submulticlasses, parse them.
3245 if (consume(tgtok::colon)) {
3246 inherits = true;
3247
3248 // Read all of the submulticlasses.
3249 SubMultiClassReference SubMultiClass =
3250 ParseSubMultiClassReference(CurMultiClass);
3251 while (true) {
3252 // Check for error.
3253 if (!SubMultiClass.MC) return true;
3254
3255 // Add it.
3256 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
3257 return true;
3258
3259 if (!consume(tgtok::comma))
3260 break;
3261 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
3262 }
3263 }
3264
3265 if (Lex.getCode() != tgtok::l_brace) {
3266 if (!inherits)
3267 return TokError("expected '{' in multiclass definition");
3268 if (!consume(tgtok::semi))
3269 return TokError("expected ';' in multiclass definition");
3270 } else {
3271 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
3272 return TokError("multiclass must contain at least one def");
3273
3274 // A multiclass body introduces a new scope for local variables.
3275 TGLocalVarScope *MulticlassScope = PushLocalScope();
3276
3277 while (Lex.getCode() != tgtok::r_brace) {
3278 switch (Lex.getCode()) {
3279 default:
3280 return TokError("expected 'let', 'def', 'defm', 'defvar', 'foreach' "
3281 "or 'if' in multiclass body");
3282 case tgtok::Let:
3283 case tgtok::Def:
3284 case tgtok::Defm:
3285 case tgtok::Defvar:
3286 case tgtok::Foreach:
3287 case tgtok::If:
3288 if (ParseObject(CurMultiClass))
3289 return true;
3290 break;
3291 }
3292 }
3293 Lex.Lex(); // eat the '}'.
3294
3295 PopLocalScope(MulticlassScope);
3296 }
3297
3298 CurMultiClass = nullptr;
3299 return false;
3300 }
3301
3302 /// ParseDefm - Parse the instantiation of a multiclass.
3303 ///
3304 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
3305 ///
ParseDefm(MultiClass * CurMultiClass)3306 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
3307 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
3308 Lex.Lex(); // eat the defm
3309
3310 Init *DefmName = ParseObjectName(CurMultiClass);
3311 if (!DefmName)
3312 return true;
3313 if (isa<UnsetInit>(DefmName)) {
3314 DefmName = Records.getNewAnonymousName();
3315 if (CurMultiClass)
3316 DefmName = BinOpInit::getStrConcat(
3317 VarInit::get(QualifiedNameOfImplicitName(CurMultiClass),
3318 StringRecTy::get()),
3319 DefmName);
3320 }
3321
3322 if (Lex.getCode() != tgtok::colon)
3323 return TokError("expected ':' after defm identifier");
3324
3325 // Keep track of the new generated record definitions.
3326 std::vector<RecordsEntry> NewEntries;
3327
3328 // This record also inherits from a regular class (non-multiclass)?
3329 bool InheritFromClass = false;
3330
3331 // eat the colon.
3332 Lex.Lex();
3333
3334 SMLoc SubClassLoc = Lex.getLoc();
3335 SubClassReference Ref = ParseSubClassReference(nullptr, true);
3336
3337 while (true) {
3338 if (!Ref.Rec) return true;
3339
3340 // To instantiate a multiclass, we need to first get the multiclass, then
3341 // instantiate each def contained in the multiclass with the SubClassRef
3342 // template parameters.
3343 MultiClass *MC = MultiClasses[std::string(Ref.Rec->getName())].get();
3344 assert(MC && "Didn't lookup multiclass correctly?");
3345 ArrayRef<Init*> TemplateVals = Ref.TemplateArgs;
3346
3347 // Verify that the correct number of template arguments were specified.
3348 ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs();
3349 if (TArgs.size() < TemplateVals.size())
3350 return Error(SubClassLoc,
3351 "more template args specified than multiclass expects");
3352
3353 SubstStack Substs;
3354 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
3355 if (i < TemplateVals.size()) {
3356 Substs.emplace_back(TArgs[i], TemplateVals[i]);
3357 } else {
3358 Init *Default = MC->Rec.getValue(TArgs[i])->getValue();
3359 if (!Default->isComplete()) {
3360 return Error(SubClassLoc,
3361 "value not specified for template argument #" +
3362 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
3363 ") of multiclass '" + MC->Rec.getNameInitAsString() +
3364 "'");
3365 }
3366 Substs.emplace_back(TArgs[i], Default);
3367 }
3368 }
3369
3370 Substs.emplace_back(QualifiedNameOfImplicitName(MC), DefmName);
3371
3372 if (resolve(MC->Entries, Substs, CurMultiClass == nullptr, &NewEntries,
3373 &SubClassLoc))
3374 return true;
3375
3376 if (!consume(tgtok::comma))
3377 break;
3378
3379 if (Lex.getCode() != tgtok::Id)
3380 return TokError("expected identifier");
3381
3382 SubClassLoc = Lex.getLoc();
3383
3384 // A defm can inherit from regular classes (non-multiclass) as
3385 // long as they come in the end of the inheritance list.
3386 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
3387
3388 if (InheritFromClass)
3389 break;
3390
3391 Ref = ParseSubClassReference(nullptr, true);
3392 }
3393
3394 if (InheritFromClass) {
3395 // Process all the classes to inherit as if they were part of a
3396 // regular 'def' and inherit all record values.
3397 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
3398 while (true) {
3399 // Check for error.
3400 if (!SubClass.Rec) return true;
3401
3402 // Get the expanded definition prototypes and teach them about
3403 // the record values the current class to inherit has
3404 for (auto &E : NewEntries) {
3405 // Add it.
3406 if (AddSubClass(E, SubClass))
3407 return true;
3408 }
3409
3410 if (!consume(tgtok::comma))
3411 break;
3412 SubClass = ParseSubClassReference(nullptr, false);
3413 }
3414 }
3415
3416 for (auto &E : NewEntries) {
3417 if (ApplyLetStack(E))
3418 return true;
3419
3420 addEntry(std::move(E));
3421 }
3422
3423 if (!consume(tgtok::semi))
3424 return TokError("expected ';' at end of defm");
3425
3426 return false;
3427 }
3428
3429 /// ParseObject
3430 /// Object ::= ClassInst
3431 /// Object ::= DefInst
3432 /// Object ::= MultiClassInst
3433 /// Object ::= DefMInst
3434 /// Object ::= LETCommand '{' ObjectList '}'
3435 /// Object ::= LETCommand Object
3436 /// Object ::= Defset
3437 /// Object ::= Defvar
ParseObject(MultiClass * MC)3438 bool TGParser::ParseObject(MultiClass *MC) {
3439 switch (Lex.getCode()) {
3440 default:
3441 return TokError("Expected class, def, defm, defset, multiclass, let, "
3442 "foreach or if");
3443 case tgtok::Let: return ParseTopLevelLet(MC);
3444 case tgtok::Def: return ParseDef(MC);
3445 case tgtok::Foreach: return ParseForeach(MC);
3446 case tgtok::If: return ParseIf(MC);
3447 case tgtok::Defm: return ParseDefm(MC);
3448 case tgtok::Defset:
3449 if (MC)
3450 return TokError("defset is not allowed inside multiclass");
3451 return ParseDefset();
3452 case tgtok::Defvar:
3453 return ParseDefvar();
3454 case tgtok::Class:
3455 if (MC)
3456 return TokError("class is not allowed inside multiclass");
3457 if (!Loops.empty())
3458 return TokError("class is not allowed inside foreach loop");
3459 return ParseClass();
3460 case tgtok::MultiClass:
3461 if (!Loops.empty())
3462 return TokError("multiclass is not allowed inside foreach loop");
3463 return ParseMultiClass();
3464 }
3465 }
3466
3467 /// ParseObjectList
3468 /// ObjectList :== Object*
ParseObjectList(MultiClass * MC)3469 bool TGParser::ParseObjectList(MultiClass *MC) {
3470 while (isObjectStart(Lex.getCode())) {
3471 if (ParseObject(MC))
3472 return true;
3473 }
3474 return false;
3475 }
3476
ParseFile()3477 bool TGParser::ParseFile() {
3478 Lex.Lex(); // Prime the lexer.
3479 if (ParseObjectList()) return true;
3480
3481 // If we have unread input at the end of the file, report it.
3482 if (Lex.getCode() == tgtok::Eof)
3483 return false;
3484
3485 return TokError("Unexpected input at top level");
3486 }
3487
3488 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const3489 LLVM_DUMP_METHOD void RecordsEntry::dump() const {
3490 if (Loop)
3491 Loop->dump();
3492 if (Rec)
3493 Rec->dump();
3494 }
3495
dump() const3496 LLVM_DUMP_METHOD void ForeachLoop::dump() const {
3497 errs() << "foreach " << IterVar->getAsString() << " = "
3498 << ListValue->getAsString() << " in {\n";
3499
3500 for (const auto &E : Entries)
3501 E.dump();
3502
3503 errs() << "}\n";
3504 }
3505
dump() const3506 LLVM_DUMP_METHOD void MultiClass::dump() const {
3507 errs() << "Record:\n";
3508 Rec.dump();
3509
3510 errs() << "Defs:\n";
3511 for (const auto &E : Entries)
3512 E.dump();
3513 }
3514 #endif
3515