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