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