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