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 VarInit *IterVar = CurLoop->IterVar;
198 if (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 if (CheckTemplateArgValues(Result.TemplateArgs, ArgLocs, &Result.MC->Rec)) {
867 Result.MC = nullptr; // Error checking value list.
868 return Result;
869 }
870
871 Result.RefRange.End = Lex.getLoc();
872
873 return Result;
874}
875
876/// ParseSliceElement - Parse subscript or range
877///
878/// SliceElement ::= Value<list<int>>
879/// SliceElement ::= Value<int>
880/// SliceElement ::= Value<int> '...' Value<int>
881/// SliceElement ::= Value<int> '-' Value<int> (deprecated)
882/// SliceElement ::= Value<int> INTVAL(Negative; deprecated)
883///
884/// SliceElement is either IntRecTy, ListRecTy, or nullptr
885///
886const TypedInit *TGParser::ParseSliceElement(Record *CurRec) {
887 auto LHSLoc = Lex.getLoc();
888 auto *CurVal = ParseValue(CurRec);
889 if (!CurVal)
890 return nullptr;
891 const auto *LHS = cast<TypedInit>(CurVal);
892
893 const TypedInit *RHS = nullptr;
894 switch (Lex.getCode()) {
895 case tgtok::dotdotdot:
896 case tgtok::minus: { // Deprecated
897 Lex.Lex(); // eat
898 auto RHSLoc = Lex.getLoc();
899 CurVal = ParseValue(CurRec);
900 if (!CurVal)
901 return nullptr;
902 RHS = cast<TypedInit>(CurVal);
903 if (!isa<IntRecTy>(RHS->getType())) {
904 Error(RHSLoc,
905 "expected int...int, got " + Twine(RHS->getType()->getAsString()));
906 return nullptr;
907 }
908 break;
909 }
910 case tgtok::IntVal: { // Deprecated "-num"
911 auto i = -Lex.getCurIntVal();
912 if (i < 0) {
913 TokError("invalid range, cannot be negative");
914 return nullptr;
915 }
916 RHS = IntInit::get(Records, i);
917 Lex.Lex(); // eat IntVal
918 break;
919 }
920 default: // Single value (IntRecTy or ListRecTy)
921 return LHS;
922 }
923
924 assert(RHS);
926
927 // Closed-interval range <LHS:IntRecTy>...<RHS:IntRecTy>
928 if (!isa<IntRecTy>(LHS->getType())) {
929 Error(LHSLoc,
930 "expected int...int, got " + Twine(LHS->getType()->getAsString()));
931 return nullptr;
932 }
933
935 IntRecTy::get(Records)->getListTy())
936 ->Fold(CurRec));
937}
938
939/// ParseSliceElements - Parse subscripts in square brackets.
940///
941/// SliceElements ::= ( SliceElement ',' )* SliceElement ','?
942///
943/// SliceElement is either IntRecTy, ListRecTy, or nullptr
944///
945/// Returns ListRecTy by defaut.
946/// Returns IntRecTy if;
947/// - Single=true
948/// - SliceElements is Value<int> w/o trailing comma
949///
950const TypedInit *TGParser::ParseSliceElements(Record *CurRec, bool Single) {
951 const TypedInit *CurVal;
952 SmallVector<const Init *, 2> Elems; // int
953 SmallVector<const TypedInit *, 2> Slices; // list<int>
954
955 auto FlushElems = [&] {
956 if (!Elems.empty()) {
957 Slices.push_back(ListInit::get(Elems, IntRecTy::get(Records)));
958 Elems.clear();
959 }
960 };
961
962 do {
963 auto LHSLoc = Lex.getLoc();
964 CurVal = ParseSliceElement(CurRec);
965 if (!CurVal)
966 return nullptr;
967 auto *CurValTy = CurVal->getType();
968
969 if (const auto *ListValTy = dyn_cast<ListRecTy>(CurValTy)) {
970 if (!isa<IntRecTy>(ListValTy->getElementType())) {
971 Error(LHSLoc,
972 "expected list<int>, got " + Twine(ListValTy->getAsString()));
973 return nullptr;
974 }
975
976 FlushElems();
977 Slices.push_back(CurVal);
978 Single = false;
979 CurVal = nullptr;
980 } else if (!isa<IntRecTy>(CurValTy)) {
981 Error(LHSLoc,
982 "unhandled type " + Twine(CurValTy->getAsString()) + " in range");
983 return nullptr;
984 }
985
986 if (Lex.getCode() != tgtok::comma)
987 break;
988
989 Lex.Lex(); // eat comma
990
991 // `[i,]` is not LISTELEM but LISTSLICE
992 Single = false;
993 if (CurVal)
994 Elems.push_back(CurVal);
995 CurVal = nullptr;
996 } while (Lex.getCode() != tgtok::r_square);
997
998 if (CurVal) {
999 // LISTELEM
1000 if (Single)
1001 return CurVal;
1002
1003 Elems.push_back(CurVal);
1004 }
1005
1006 FlushElems();
1007
1008 // Concatenate lists in Slices
1009 const TypedInit *Result = nullptr;
1010 for (auto *Slice : Slices) {
1012 : Slice);
1013 }
1014
1015 return Result;
1016}
1017
1018/// ParseRangePiece - Parse a bit/value range.
1019/// RangePiece ::= INTVAL
1020/// RangePiece ::= INTVAL '...' INTVAL
1021/// RangePiece ::= INTVAL '-' INTVAL
1022/// RangePiece ::= INTVAL INTVAL
1023// The last two forms are deprecated.
1024bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
1025 const TypedInit *FirstItem) {
1026 const Init *CurVal = FirstItem;
1027 if (!CurVal)
1028 CurVal = ParseValue(nullptr);
1029
1030 const auto *II = dyn_cast_or_null<IntInit>(CurVal);
1031 if (!II)
1032 return TokError("expected integer or bitrange");
1033
1034 int64_t Start = II->getValue();
1035 int64_t End;
1036
1037 if (Start < 0)
1038 return TokError("invalid range, cannot be negative");
1039
1040 switch (Lex.getCode()) {
1041 default:
1042 Ranges.push_back(Start);
1043 return false;
1044
1045 case tgtok::dotdotdot:
1046 case tgtok::minus: {
1047 Lex.Lex(); // eat
1048
1049 const Init *I_End = ParseValue(nullptr);
1050 const auto *II_End = dyn_cast_or_null<IntInit>(I_End);
1051 if (!II_End) {
1052 TokError("expected integer value as end of range");
1053 return true;
1054 }
1055
1056 End = II_End->getValue();
1057 break;
1058 }
1059 case tgtok::IntVal: {
1060 End = -Lex.getCurIntVal();
1061 Lex.Lex();
1062 break;
1063 }
1064 }
1065 if (End < 0)
1066 return TokError("invalid range, cannot be negative");
1067
1068 // Add to the range.
1069 if (Start < End)
1070 for (; Start <= End; ++Start)
1071 Ranges.push_back(Start);
1072 else
1073 for (; Start >= End; --Start)
1074 Ranges.push_back(Start);
1075 return false;
1076}
1077
1078/// ParseRangeList - Parse a list of scalars and ranges into scalar values.
1079///
1080/// RangeList ::= RangePiece (',' RangePiece)*
1081///
1082void TGParser::ParseRangeList(SmallVectorImpl<unsigned> &Result) {
1083 // Parse the first piece.
1084 if (ParseRangePiece(Result)) {
1085 Result.clear();
1086 return;
1087 }
1088 while (consume(tgtok::comma))
1089 // Parse the next range piece.
1090 if (ParseRangePiece(Result)) {
1091 Result.clear();
1092 return;
1093 }
1094}
1095
1096/// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
1097/// OptionalRangeList ::= '{' RangeList '}'
1098/// OptionalRangeList ::= /*empty*/
1099bool TGParser::ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges) {
1100 SMLoc StartLoc = Lex.getLoc();
1101 if (!consume(tgtok::l_brace))
1102 return false;
1103
1104 // Parse the range list.
1105 ParseRangeList(Ranges);
1106 if (Ranges.empty())
1107 return true;
1108
1109 if (!consume(tgtok::r_brace)) {
1110 TokError("expected '}' at end of bit list");
1111 return Error(StartLoc, "to match this '{'");
1112 }
1113 return false;
1114}
1115
1116/// ParseType - Parse and return a tblgen type. This returns null on error.
1117///
1118/// Type ::= STRING // string type
1119/// Type ::= CODE // code type
1120/// Type ::= BIT // bit type
1121/// Type ::= BITS '<' INTVAL '>' // bits<x> type
1122/// Type ::= INT // int type
1123/// Type ::= LIST '<' Type '>' // list<x> type
1124/// Type ::= DAG // dag type
1125/// Type ::= ClassID // Record Type
1126///
1127const RecTy *TGParser::ParseType() {
1128 switch (Lex.getCode()) {
1129 default:
1130 TokError("Unknown token when expecting a type");
1131 return nullptr;
1132 case tgtok::String:
1133 case tgtok::Code:
1134 Lex.Lex();
1135 return StringRecTy::get(Records);
1136 case tgtok::Bit:
1137 Lex.Lex();
1138 return BitRecTy::get(Records);
1139 case tgtok::Int:
1140 Lex.Lex();
1141 return IntRecTy::get(Records);
1142 case tgtok::Dag:
1143 Lex.Lex();
1144 return DagRecTy::get(Records);
1145 case tgtok::Id: {
1146 auto I = TypeAliases.find(Lex.getCurStrVal());
1147 if (I != TypeAliases.end()) {
1148 Lex.Lex();
1149 return I->second;
1150 }
1151 if (const Record *R = ParseClassID())
1152 return RecordRecTy::get(R);
1153 TokError("unknown class name");
1154 return nullptr;
1155 }
1156 case tgtok::Bits: {
1157 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
1158 TokError("expected '<' after bits type");
1159 return nullptr;
1160 }
1161 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
1162 TokError("expected integer in bits<n> type");
1163 return nullptr;
1164 }
1165 uint64_t Val = Lex.getCurIntVal();
1166 if (Lex.Lex() != tgtok::greater) { // Eat count.
1167 TokError("expected '>' at end of bits<n> type");
1168 return nullptr;
1169 }
1170 Lex.Lex(); // Eat '>'
1171 return BitsRecTy::get(Records, Val);
1172 }
1173 case tgtok::List: {
1174 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
1175 TokError("expected '<' after list type");
1176 return nullptr;
1177 }
1178 Lex.Lex(); // Eat '<'
1179 const RecTy *SubType = ParseType();
1180 if (!SubType)
1181 return nullptr;
1182
1183 if (!consume(tgtok::greater)) {
1184 TokError("expected '>' at end of list<ty> type");
1185 return nullptr;
1186 }
1187 return ListRecTy::get(SubType);
1188 }
1189 }
1190}
1191
1192/// ParseIDValue
1193const Init *TGParser::ParseIDValue(Record *CurRec, const StringInit *Name,
1194 SMRange NameLoc, IDParseMode Mode) {
1195 if (const Init *I = CurScope->getVar(Records, CurMultiClass, Name, NameLoc,
1196 TrackReferenceLocs))
1197 return I;
1198
1199 if (Mode == ParseNameMode)
1200 return Name;
1201
1202 if (const Init *I = Records.getGlobal(Name->getValue())) {
1203 // Add a reference to the global if it's a record.
1204 if (TrackReferenceLocs) {
1205 if (const auto *Def = dyn_cast<DefInit>(I))
1206 Def->getDef()->appendReferenceLoc(NameLoc);
1207 }
1208 return I;
1209 }
1210
1211 // Allow self-references of concrete defs, but delay the lookup so that we
1212 // get the correct type.
1213 if (CurRec && !CurRec->isClass() && !CurMultiClass &&
1214 CurRec->getNameInit() == Name)
1215 return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType());
1216
1217 Error(NameLoc.Start, "Variable not defined: '" + Name->getValue() + "'");
1218 return nullptr;
1219}
1220
1221/// ParseOperation - Parse an operator. This returns null on error.
1222///
1223/// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
1224///
1225const Init *TGParser::ParseOperation(Record *CurRec, const RecTy *ItemType) {
1226 switch (Lex.getCode()) {
1227 default:
1228 TokError("unknown bang operator");
1229 return nullptr;
1230 case tgtok::XNOT:
1231 case tgtok::XToLower:
1232 case tgtok::XToUpper:
1234 case tgtok::XLOG2:
1235 case tgtok::XHead:
1236 case tgtok::XTail:
1237 case tgtok::XSize:
1238 case tgtok::XEmpty:
1239 case tgtok::XCast:
1240 case tgtok::XRepr:
1241 case tgtok::XGetDagOp:
1243 case tgtok::XInitialized: { // Value ::= !unop '(' Value ')'
1245 const RecTy *Type = nullptr;
1246
1247 switch (Lex.getCode()) {
1248 default:
1249 llvm_unreachable("Unhandled code!");
1250 case tgtok::XCast:
1251 Lex.Lex(); // eat the operation
1253
1254 Type = ParseOperatorType();
1255
1256 if (!Type) {
1257 TokError("did not get type for unary operator");
1258 return nullptr;
1259 }
1260
1261 break;
1262 case tgtok::XRepr:
1263 Lex.Lex(); // eat the operation
1265 Type = StringRecTy::get(Records);
1266 break;
1267 case tgtok::XToLower:
1268 Lex.Lex(); // eat the operation
1270 Type = StringRecTy::get(Records);
1271 break;
1272 case tgtok::XToUpper:
1273 Lex.Lex(); // eat the operation
1275 Type = StringRecTy::get(Records);
1276 break;
1277 case tgtok::XNOT:
1278 Lex.Lex(); // eat the operation
1280 Type = IntRecTy::get(Records);
1281 break;
1283 Lex.Lex(); // eat the operation.
1285 Type = IntRecTy::get(Records); // Bogus type used here.
1286 break;
1287 case tgtok::XLOG2:
1288 Lex.Lex(); // eat the operation
1290 Type = IntRecTy::get(Records);
1291 break;
1292 case tgtok::XHead:
1293 Lex.Lex(); // eat the operation
1295 break;
1296 case tgtok::XTail:
1297 Lex.Lex(); // eat the operation
1299 break;
1300 case tgtok::XSize:
1301 Lex.Lex();
1303 Type = IntRecTy::get(Records);
1304 break;
1305 case tgtok::XEmpty:
1306 Lex.Lex(); // eat the operation
1308 Type = IntRecTy::get(Records);
1309 break;
1310 case tgtok::XGetDagOp:
1311 Lex.Lex(); // eat the operation
1312 if (Lex.getCode() == tgtok::less) {
1313 // Parse an optional type suffix, so that you can say
1314 // !getdagop<BaseClass>(someDag) as a shorthand for
1315 // !cast<BaseClass>(!getdagop(someDag)).
1316 Type = ParseOperatorType();
1317
1318 if (!Type) {
1319 TokError("did not get type for unary operator");
1320 return nullptr;
1321 }
1322
1323 if (!isa<RecordRecTy>(Type)) {
1324 TokError("type for !getdagop must be a record type");
1325 // but keep parsing, to consume the operand
1326 }
1327 } else {
1328 Type = RecordRecTy::get(Records, {});
1329 }
1331 break;
1333 Lex.Lex(); // eat the operation
1334 Type = StringRecTy::get(Records);
1336 break;
1338 Lex.Lex(); // eat the operation
1340 Type = IntRecTy::get(Records);
1341 break;
1342 }
1343 if (!consume(tgtok::l_paren)) {
1344 TokError("expected '(' after unary operator");
1345 return nullptr;
1346 }
1347
1348 const Init *LHS = ParseValue(CurRec);
1349 if (!LHS)
1350 return nullptr;
1351
1352 if (Code == UnOpInit::EMPTY || Code == UnOpInit::SIZE) {
1353 const auto *LHSl = dyn_cast<ListInit>(LHS);
1354 const auto *LHSs = dyn_cast<StringInit>(LHS);
1355 const auto *LHSd = dyn_cast<DagInit>(LHS);
1356 const auto *LHSt = dyn_cast<TypedInit>(LHS);
1357 if (!LHSl && !LHSs && !LHSd && !LHSt) {
1358 TokError(
1359 "expected string, list, or dag type argument in unary operator");
1360 return nullptr;
1361 }
1362 if (LHSt) {
1363 if (!isa<ListRecTy, StringRecTy, DagRecTy>(LHSt->getType())) {
1364 TokError(
1365 "expected string, list, or dag type argument in unary operator");
1366 return nullptr;
1367 }
1368 }
1369 }
1370
1371 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL ||
1372 Code == UnOpInit::LISTFLATTEN) {
1373 const auto *LHSl = dyn_cast<ListInit>(LHS);
1374 const auto *LHSt = dyn_cast<TypedInit>(LHS);
1375 if (!LHSl && !LHSt) {
1376 TokError("expected list type argument in unary operator");
1377 return nullptr;
1378 }
1379 if (LHSt) {
1380 if (!isa<ListRecTy>(LHSt->getType())) {
1381 TokError("expected list type argument in unary operator");
1382 return nullptr;
1383 }
1384 }
1385
1386 if (LHSl && LHSl->empty()) {
1387 TokError("empty list argument in unary operator");
1388 return nullptr;
1389 }
1390 bool UseElementType =
1392 if (LHSl) {
1393 const Init *Item = LHSl->getElement(0);
1394 const auto *Itemt = dyn_cast<TypedInit>(Item);
1395 if (!Itemt) {
1396 TokError("untyped list element in unary operator");
1397 return nullptr;
1398 }
1399 Type = UseElementType ? Itemt->getType()
1400 : ListRecTy::get(Itemt->getType());
1401 } else {
1402 assert(LHSt && "expected list type argument in unary operator");
1403 const auto *LType = dyn_cast<ListRecTy>(LHSt->getType());
1404 Type = UseElementType ? LType->getElementType() : LType;
1405 }
1406
1407 // for !listflatten, we expect a list of lists, but also support a list of
1408 // non-lists, where !listflatten will be a NOP.
1409 if (Code == UnOpInit::LISTFLATTEN) {
1410 const auto *InnerListTy = dyn_cast<ListRecTy>(Type);
1411 if (InnerListTy) {
1412 // listflatten will convert list<list<X>> to list<X>.
1413 Type = ListRecTy::get(InnerListTy->getElementType());
1414 } else {
1415 // If its a list of non-lists, !listflatten will be a NOP.
1417 }
1418 }
1419 }
1420
1421 if (!consume(tgtok::r_paren)) {
1422 TokError("expected ')' in unary operator");
1423 return nullptr;
1424 }
1425 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec);
1426 }
1427
1428 case tgtok::XIsA: {
1429 // Value ::= !isa '<' Type '>' '(' Value ')'
1430 Lex.Lex(); // eat the operation
1431
1432 const RecTy *Type = ParseOperatorType();
1433 if (!Type)
1434 return nullptr;
1435
1436 if (!consume(tgtok::l_paren)) {
1437 TokError("expected '(' after type of !isa");
1438 return nullptr;
1439 }
1440
1441 const Init *LHS = ParseValue(CurRec);
1442 if (!LHS)
1443 return nullptr;
1444
1445 if (!consume(tgtok::r_paren)) {
1446 TokError("expected ')' in !isa");
1447 return nullptr;
1448 }
1449
1450 return IsAOpInit::get(Type, LHS)->Fold();
1451 }
1452
1453 case tgtok::XExists: {
1454 // Value ::= !exists '<' Type '>' '(' Value ')'
1455 Lex.Lex(); // eat the operation.
1456
1457 const RecTy *Type = ParseOperatorType();
1458 if (!Type)
1459 return nullptr;
1460
1461 if (!consume(tgtok::l_paren)) {
1462 TokError("expected '(' after type of !exists");
1463 return nullptr;
1464 }
1465
1466 SMLoc ExprLoc = Lex.getLoc();
1467 const Init *Expr = ParseValue(CurRec);
1468 if (!Expr)
1469 return nullptr;
1470
1471 const auto *ExprType = dyn_cast<TypedInit>(Expr);
1472 if (!ExprType) {
1473 Error(ExprLoc, "expected string type argument in !exists operator");
1474 return nullptr;
1475 }
1476
1477 const auto *RecType = dyn_cast<RecordRecTy>(ExprType->getType());
1478 if (RecType) {
1479 Error(ExprLoc,
1480 "expected string type argument in !exists operator, please "
1481 "use !isa instead");
1482 return nullptr;
1483 }
1484
1485 const auto *SType = dyn_cast<StringRecTy>(ExprType->getType());
1486 if (!SType) {
1487 Error(ExprLoc, "expected string type argument in !exists operator");
1488 return nullptr;
1489 }
1490
1491 if (!consume(tgtok::r_paren)) {
1492 TokError("expected ')' in !exists");
1493 return nullptr;
1494 }
1495
1496 return (ExistsOpInit::get(Type, Expr))->Fold(CurRec);
1497 }
1498
1499 case tgtok::XInstances: {
1500 // Value ::= !instances '<' Type '>' '(' Regex? ')'
1501 Lex.Lex(); // eat the operation.
1502
1503 const RecTy *Type = ParseOperatorType();
1504 if (!Type)
1505 return nullptr;
1506
1507 if (!consume(tgtok::l_paren)) {
1508 TokError("expected '(' after type of !instances");
1509 return nullptr;
1510 }
1511
1512 // The Regex can be optional.
1513 const Init *Regex;
1514 if (Lex.getCode() != tgtok::r_paren) {
1515 SMLoc RegexLoc = Lex.getLoc();
1516 Regex = ParseValue(CurRec);
1517
1518 const auto *RegexType = dyn_cast<TypedInit>(Regex);
1519 if (!RegexType) {
1520 Error(RegexLoc, "expected string type argument in !instances operator");
1521 return nullptr;
1522 }
1523
1524 const auto *SType = dyn_cast<StringRecTy>(RegexType->getType());
1525 if (!SType) {
1526 Error(RegexLoc, "expected string type argument in !instances operator");
1527 return nullptr;
1528 }
1529 } else {
1530 // Use wildcard when Regex is not specified.
1531 Regex = StringInit::get(Records, ".*");
1532 }
1533
1534 if (!consume(tgtok::r_paren)) {
1535 TokError("expected ')' in !instances");
1536 return nullptr;
1537 }
1538
1539 return InstancesOpInit::get(Type, Regex)->Fold(CurRec);
1540 }
1541
1542 case tgtok::XConcat:
1543 case tgtok::XMatch:
1544 case tgtok::XADD:
1545 case tgtok::XSUB:
1546 case tgtok::XMUL:
1547 case tgtok::XDIV:
1548 case tgtok::XAND:
1549 case tgtok::XOR:
1550 case tgtok::XXOR:
1551 case tgtok::XSRA:
1552 case tgtok::XSRL:
1553 case tgtok::XSHL:
1554 case tgtok::XEq:
1555 case tgtok::XNe:
1556 case tgtok::XLe:
1557 case tgtok::XLt:
1558 case tgtok::XGe:
1559 case tgtok::XGt:
1560 case tgtok::XListConcat:
1561 case tgtok::XListSplat:
1562 case tgtok::XListRemove:
1563 case tgtok::XStrConcat:
1564 case tgtok::XInterleave:
1565 case tgtok::XGetDagArg:
1566 case tgtok::XGetDagName:
1567 case tgtok::XSetDagOp:
1568 case tgtok::XSetDagOpName: { // Value ::= !binop '(' Value ',' Value ')'
1569 tgtok::TokKind OpTok = Lex.getCode();
1570 SMLoc OpLoc = Lex.getLoc();
1571 Lex.Lex(); // eat the operation
1572
1574 switch (OpTok) {
1575 default:
1576 llvm_unreachable("Unhandled code!");
1577 case tgtok::XConcat:
1579 break;
1580 case tgtok::XMatch:
1582 break;
1583 case tgtok::XADD:
1585 break;
1586 case tgtok::XSUB:
1588 break;
1589 case tgtok::XMUL:
1591 break;
1592 case tgtok::XDIV:
1594 break;
1595 case tgtok::XAND:
1597 break;
1598 case tgtok::XOR:
1600 break;
1601 case tgtok::XXOR:
1603 break;
1604 case tgtok::XSRA:
1606 break;
1607 case tgtok::XSRL:
1609 break;
1610 case tgtok::XSHL:
1612 break;
1613 case tgtok::XEq:
1615 break;
1616 case tgtok::XNe:
1618 break;
1619 case tgtok::XLe:
1621 break;
1622 case tgtok::XLt:
1624 break;
1625 case tgtok::XGe:
1627 break;
1628 case tgtok::XGt:
1630 break;
1631 case tgtok::XListConcat:
1633 break;
1634 case tgtok::XListSplat:
1636 break;
1637 case tgtok::XListRemove:
1639 break;
1640 case tgtok::XStrConcat:
1642 break;
1643 case tgtok::XInterleave:
1645 break;
1646 case tgtok::XSetDagOp:
1648 break;
1651 break;
1652 case tgtok::XGetDagArg:
1654 break;
1655 case tgtok::XGetDagName:
1657 break;
1658 }
1659
1660 const RecTy *Type = nullptr;
1661 const RecTy *ArgType = nullptr;
1662 switch (OpTok) {
1663 default:
1664 llvm_unreachable("Unhandled code!");
1665 case tgtok::XMatch:
1666 Type = BitRecTy::get(Records);
1667 ArgType = StringRecTy::get(Records);
1668 break;
1669 case tgtok::XConcat:
1670 case tgtok::XSetDagOp:
1671 Type = DagRecTy::get(Records);
1672 ArgType = DagRecTy::get(Records);
1673 break;
1674 case tgtok::XGetDagArg:
1675 Type = ParseOperatorType();
1676 if (!Type) {
1677 TokError("did not get type for !getdagarg operator");
1678 return nullptr;
1679 }
1680 ArgType = DagRecTy::get(Records);
1681 break;
1683 Type = DagRecTy::get(Records);
1684 ArgType = DagRecTy::get(Records);
1685 break;
1686 case tgtok::XGetDagName:
1687 Type = StringRecTy::get(Records);
1688 ArgType = DagRecTy::get(Records);
1689 break;
1690 case tgtok::XAND:
1691 case tgtok::XOR:
1692 case tgtok::XXOR:
1693 case tgtok::XSRA:
1694 case tgtok::XSRL:
1695 case tgtok::XSHL:
1696 case tgtok::XADD:
1697 case tgtok::XSUB:
1698 case tgtok::XMUL:
1699 case tgtok::XDIV:
1700 Type = IntRecTy::get(Records);
1701 ArgType = IntRecTy::get(Records);
1702 break;
1703 case tgtok::XEq:
1704 case tgtok::XNe:
1705 case tgtok::XLe:
1706 case tgtok::XLt:
1707 case tgtok::XGe:
1708 case tgtok::XGt:
1709 Type = BitRecTy::get(Records);
1710 // ArgType for the comparison operators is not yet known.
1711 break;
1712 case tgtok::XListConcat:
1713 // We don't know the list type until we parse the first argument.
1714 ArgType = ItemType;
1715 break;
1716 case tgtok::XListSplat:
1717 // Can't do any typechecking until we parse the first argument.
1718 break;
1719 case tgtok::XListRemove:
1720 // We don't know the list type until we parse the first argument.
1721 ArgType = ItemType;
1722 break;
1723 case tgtok::XStrConcat:
1724 Type = StringRecTy::get(Records);
1725 ArgType = StringRecTy::get(Records);
1726 break;
1727 case tgtok::XInterleave:
1728 Type = StringRecTy::get(Records);
1729 // The first argument type is not yet known.
1730 }
1731
1732 if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) {
1733 Error(OpLoc, Twine("expected value of type '") + ItemType->getAsString() +
1734 "', got '" + Type->getAsString() + "'");
1735 return nullptr;
1736 }
1737
1738 if (!consume(tgtok::l_paren)) {
1739 TokError("expected '(' after binary operator");
1740 return nullptr;
1741 }
1742
1744
1745 // Note that this loop consumes an arbitrary number of arguments.
1746 // The actual count is checked later.
1747 for (;;) {
1748 SMLoc InitLoc = Lex.getLoc();
1749 InitList.push_back(ParseValue(CurRec, ArgType));
1750 if (!InitList.back())
1751 return nullptr;
1752
1753 const auto *InitListBack = dyn_cast<TypedInit>(InitList.back());
1754 if (!InitListBack) {
1755 Error(OpLoc, Twine("expected value to be a typed value, got '" +
1756 InitList.back()->getAsString() + "'"));
1757 return nullptr;
1758 }
1759 const RecTy *ListType = InitListBack->getType();
1760
1761 if (!ArgType) {
1762 // Argument type must be determined from the argument itself.
1763 ArgType = ListType;
1764
1765 switch (Code) {
1767 if (!isa<ListRecTy>(ArgType)) {
1768 Error(InitLoc, Twine("expected a list, got value of type '") +
1769 ArgType->getAsString() + "'");
1770 return nullptr;
1771 }
1772 break;
1774 if (ItemType && InitList.size() == 1) {
1775 if (!isa<ListRecTy>(ItemType)) {
1776 Error(OpLoc,
1777 Twine("expected output type to be a list, got type '") +
1778 ItemType->getAsString() + "'");
1779 return nullptr;
1780 }
1781 if (!ArgType->getListTy()->typeIsConvertibleTo(ItemType)) {
1782 Error(OpLoc, Twine("expected first arg type to be '") +
1783 ArgType->getAsString() +
1784 "', got value of type '" +
1785 cast<ListRecTy>(ItemType)
1786 ->getElementType()
1787 ->getAsString() +
1788 "'");
1789 return nullptr;
1790 }
1791 }
1792 if (InitList.size() == 2 && !isa<IntRecTy>(ArgType)) {
1793 Error(InitLoc, Twine("expected second parameter to be an int, got "
1794 "value of type '") +
1795 ArgType->getAsString() + "'");
1796 return nullptr;
1797 }
1798 ArgType = nullptr; // Broken invariant: types not identical.
1799 break;
1801 if (!isa<ListRecTy>(ArgType)) {
1802 Error(InitLoc, Twine("expected a list, got value of type '") +
1803 ArgType->getAsString() + "'");
1804 return nullptr;
1805 }
1806 break;
1807 case BinOpInit::EQ:
1808 case BinOpInit::NE:
1809 if (!ArgType->typeIsConvertibleTo(IntRecTy::get(Records)) &&
1810 !ArgType->typeIsConvertibleTo(StringRecTy::get(Records)) &&
1811 !ArgType->typeIsConvertibleTo(RecordRecTy::get(Records, {}))) {
1812 Error(InitLoc, Twine("expected bit, bits, int, string, or record; "
1813 "got value of type '") +
1814 ArgType->getAsString() + "'");
1815 return nullptr;
1816 }
1817 break;
1818 case BinOpInit::GETDAGARG: // The 2nd argument of !getdagarg could be
1819 // index or name.
1820 case BinOpInit::LE:
1821 case BinOpInit::LT:
1822 case BinOpInit::GE:
1823 case BinOpInit::GT:
1824 if (!ArgType->typeIsConvertibleTo(IntRecTy::get(Records)) &&
1825 !ArgType->typeIsConvertibleTo(StringRecTy::get(Records))) {
1826 Error(InitLoc, Twine("expected bit, bits, int, or string; "
1827 "got value of type '") +
1828 ArgType->getAsString() + "'");
1829 return nullptr;
1830 }
1831 break;
1833 switch (InitList.size()) {
1834 case 1: // First argument must be a list of strings or integers.
1835 if (ArgType != StringRecTy::get(Records)->getListTy() &&
1836 !ArgType->typeIsConvertibleTo(
1837 IntRecTy::get(Records)->getListTy())) {
1838 Error(InitLoc,
1839 Twine("expected list of string, int, bits, or bit; "
1840 "got value of type '") +
1841 ArgType->getAsString() + "'");
1842 return nullptr;
1843 }
1844 break;
1845 case 2: // Second argument must be a string.
1846 if (!isa<StringRecTy>(ArgType)) {
1847 Error(InitLoc, Twine("expected second argument to be a string, "
1848 "got value of type '") +
1849 ArgType->getAsString() + "'");
1850 return nullptr;
1851 }
1852 break;
1853 default:;
1854 }
1855 ArgType = nullptr; // Broken invariant: types not identical.
1856 break;
1857 default:
1858 llvm_unreachable("other ops have fixed argument types");
1859 }
1860
1861 } else {
1862 // Desired argument type is a known and in ArgType.
1863 const RecTy *Resolved = resolveTypes(ArgType, ListType);
1864 if (!Resolved) {
1865 Error(InitLoc, Twine("expected value of type '") +
1866 ArgType->getAsString() + "', got '" +
1867 ListType->getAsString() + "'");
1868 return nullptr;
1869 }
1870 if (Code != BinOpInit::ADD && Code != BinOpInit::SUB &&
1871 Code != BinOpInit::AND && Code != BinOpInit::OR &&
1872 Code != BinOpInit::XOR && Code != BinOpInit::SRA &&
1873 Code != BinOpInit::SRL && Code != BinOpInit::SHL &&
1874 Code != BinOpInit::MUL && Code != BinOpInit::DIV)
1875 ArgType = Resolved;
1876 }
1877
1878 // Deal with BinOps whose arguments have different types, by
1879 // rewriting ArgType in between them.
1880 switch (Code) {
1882 // After parsing the first dag argument, expect a string.
1883 ArgType = StringRecTy::get(Records);
1884 break;
1886 // After parsing the first dag argument, switch to expecting
1887 // a record, with no restriction on its superclasses.
1888 ArgType = RecordRecTy::get(Records, {});
1889 break;
1891 // After parsing the first dag argument, expect an index integer or a
1892 // name string.
1893 ArgType = nullptr;
1894 break;
1896 // After parsing the first dag argument, expect an index integer.
1897 ArgType = IntRecTy::get(Records);
1898 break;
1899 default:
1900 break;
1901 }
1902
1903 if (!consume(tgtok::comma))
1904 break;
1905 }
1906
1907 if (!consume(tgtok::r_paren)) {
1908 TokError("expected ')' in operator");
1909 return nullptr;
1910 }
1911
1912 // listconcat returns a list with type of the argument.
1913 if (Code == BinOpInit::LISTCONCAT)
1914 Type = ArgType;
1915 // listsplat returns a list of type of the *first* argument.
1916 if (Code == BinOpInit::LISTSPLAT)
1917 Type = cast<TypedInit>(InitList.front())->getType()->getListTy();
1918 // listremove returns a list with type of the argument.
1919 if (Code == BinOpInit::LISTREMOVE)
1920 Type = ArgType;
1921
1922 // We allow multiple operands to associative operators like !strconcat as
1923 // shorthand for nesting them.
1924 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT ||
1925 Code == BinOpInit::CONCAT || Code == BinOpInit::ADD ||
1926 Code == BinOpInit::AND || Code == BinOpInit::OR ||
1927 Code == BinOpInit::XOR || Code == BinOpInit::MUL) {
1928 while (InitList.size() > 2) {
1929 const Init *RHS = InitList.pop_back_val();
1930 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec);
1931 InitList.back() = RHS;
1932 }
1933 }
1934
1935 if (InitList.size() == 2)
1936 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
1937 ->Fold(CurRec);
1938
1939 Error(OpLoc, "expected two operands to operator");
1940 return nullptr;
1941 }
1942
1943 case tgtok::XForEach:
1944 case tgtok::XFilter:
1945 case tgtok::XSort: {
1946 return ParseOperationListComprehension(CurRec, ItemType);
1947 }
1948
1949 case tgtok::XRange: {
1950 SMLoc OpLoc = Lex.getLoc();
1951 Lex.Lex(); // eat the operation
1952
1953 if (!consume(tgtok::l_paren)) {
1954 TokError("expected '(' after !range operator");
1955 return nullptr;
1956 }
1957
1959 bool FirstArgIsList = false;
1960 for (;;) {
1961 if (Args.size() >= 3) {
1962 TokError("expected at most three values of integer");
1963 return nullptr;
1964 }
1965
1966 SMLoc InitLoc = Lex.getLoc();
1967 Args.push_back(ParseValue(CurRec));
1968 if (!Args.back())
1969 return nullptr;
1970
1971 const auto *ArgBack = dyn_cast<TypedInit>(Args.back());
1972 if (!ArgBack) {
1973 Error(OpLoc, Twine("expected value to be a typed value, got '" +
1974 Args.back()->getAsString() + "'"));
1975 return nullptr;
1976 }
1977
1978 const RecTy *ArgBackType = ArgBack->getType();
1979 if (!FirstArgIsList || Args.size() == 1) {
1980 if (Args.size() == 1 && isa<ListRecTy>(ArgBackType)) {
1981 FirstArgIsList = true; // Detect error if 2nd arg were present.
1982 } else if (isa<IntRecTy>(ArgBackType)) {
1983 // Assume 2nd arg should be IntRecTy
1984 } else {
1985 if (Args.size() != 1)
1986 Error(InitLoc, Twine("expected value of type 'int', got '" +
1987 ArgBackType->getAsString() + "'"));
1988 else
1989 Error(InitLoc, Twine("expected list or int, got value of type '") +
1990 ArgBackType->getAsString() + "'");
1991 return nullptr;
1992 }
1993 } else {
1994 // Don't come here unless 1st arg is ListRecTy.
1996 Error(InitLoc, Twine("expected one list, got extra value of type '") +
1997 ArgBackType->getAsString() + "'");
1998 return nullptr;
1999 }
2000 if (!consume(tgtok::comma))
2001 break;
2002 }
2003
2004 if (!consume(tgtok::r_paren)) {
2005 TokError("expected ')' in operator");
2006 return nullptr;
2007 }
2008
2009 const Init *LHS, *MHS, *RHS;
2010 auto ArgCount = Args.size();
2011 assert(ArgCount >= 1);
2012 const auto *Arg0 = cast<TypedInit>(Args[0]);
2013 const auto *Arg0Ty = Arg0->getType();
2014 if (ArgCount == 1) {
2015 if (isa<ListRecTy>(Arg0Ty)) {
2016 // (0, !size(arg), 1)
2017 LHS = IntInit::get(Records, 0);
2018 MHS = UnOpInit::get(UnOpInit::SIZE, Arg0, IntRecTy::get(Records))
2019 ->Fold(CurRec);
2020 RHS = IntInit::get(Records, 1);
2021 } else {
2022 assert(isa<IntRecTy>(Arg0Ty));
2023 // (0, arg, 1)
2024 LHS = IntInit::get(Records, 0);
2025 MHS = Arg0;
2026 RHS = IntInit::get(Records, 1);
2027 }
2028 } else {
2029 assert(isa<IntRecTy>(Arg0Ty));
2030 const auto *Arg1 = cast<TypedInit>(Args[1]);
2031 assert(isa<IntRecTy>(Arg1->getType()));
2032 LHS = Arg0;
2033 MHS = Arg1;
2034 if (ArgCount == 3) {
2035 // (start, end, step)
2036 const auto *Arg2 = cast<TypedInit>(Args[2]);
2037 assert(isa<IntRecTy>(Arg2->getType()));
2038 RHS = Arg2;
2039 } else {
2040 // (start, end, 1)
2041 RHS = IntInit::get(Records, 1);
2042 }
2043 }
2045 IntRecTy::get(Records)->getListTy())
2046 ->Fold(CurRec);
2047 }
2048
2049 case tgtok::XSetDagArg:
2050 case tgtok::XSetDagName:
2051 case tgtok::XDag:
2052 case tgtok::XIf:
2053 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
2055 const RecTy *Type = nullptr;
2056
2057 tgtok::TokKind LexCode = Lex.getCode();
2058 Lex.Lex(); // Eat the operation.
2059 switch (LexCode) {
2060 default:
2061 llvm_unreachable("Unhandled code!");
2062 case tgtok::XDag:
2064 Type = DagRecTy::get(Records);
2065 ItemType = nullptr;
2066 break;
2067 case tgtok::XIf:
2069 break;
2070 case tgtok::XSubst:
2072 break;
2073 case tgtok::XSetDagArg:
2075 Type = DagRecTy::get(Records);
2076 ItemType = nullptr;
2077 break;
2078 case tgtok::XSetDagName:
2080 Type = DagRecTy::get(Records);
2081 ItemType = nullptr;
2082 break;
2083 }
2084 if (!consume(tgtok::l_paren)) {
2085 TokError("expected '(' after ternary operator");
2086 return nullptr;
2087 }
2088
2089 const Init *LHS = ParseValue(CurRec);
2090 if (!LHS)
2091 return nullptr;
2092
2093 if (!consume(tgtok::comma)) {
2094 TokError("expected ',' in ternary operator");
2095 return nullptr;
2096 }
2097
2098 SMLoc MHSLoc = Lex.getLoc();
2099 const Init *MHS = ParseValue(CurRec, ItemType);
2100 if (!MHS)
2101 return nullptr;
2102
2103 if (!consume(tgtok::comma)) {
2104 TokError("expected ',' in ternary operator");
2105 return nullptr;
2106 }
2107
2108 SMLoc RHSLoc = Lex.getLoc();
2109 const Init *RHS = ParseValue(CurRec, ItemType);
2110 if (!RHS)
2111 return nullptr;
2112
2113 if (!consume(tgtok::r_paren)) {
2114 TokError("expected ')' in binary operator");
2115 return nullptr;
2116 }
2117
2118 switch (LexCode) {
2119 default:
2120 llvm_unreachable("Unhandled code!");
2121 case tgtok::XDag: {
2122 const auto *MHSt = dyn_cast<TypedInit>(MHS);
2123 if (!MHSt && !isa<UnsetInit>(MHS)) {
2124 Error(MHSLoc, "could not determine type of the child list in !dag");
2125 return nullptr;
2126 }
2127 if (MHSt && !isa<ListRecTy>(MHSt->getType())) {
2128 Error(MHSLoc, Twine("expected list of children, got type '") +
2129 MHSt->getType()->getAsString() + "'");
2130 return nullptr;
2131 }
2132
2133 const auto *RHSt = dyn_cast<TypedInit>(RHS);
2134 if (!RHSt && !isa<UnsetInit>(RHS)) {
2135 Error(RHSLoc, "could not determine type of the name list in !dag");
2136 return nullptr;
2137 }
2138 if (RHSt && StringRecTy::get(Records)->getListTy() != RHSt->getType()) {
2139 Error(RHSLoc, Twine("expected list<string>, got type '") +
2140 RHSt->getType()->getAsString() + "'");
2141 return nullptr;
2142 }
2143
2144 if (!MHSt && !RHSt) {
2145 Error(MHSLoc,
2146 "cannot have both unset children and unset names in !dag");
2147 return nullptr;
2148 }
2149 break;
2150 }
2151 case tgtok::XIf: {
2152 const RecTy *MHSTy = nullptr;
2153 const RecTy *RHSTy = nullptr;
2154
2155 if (const auto *MHSt = dyn_cast<TypedInit>(MHS))
2156 MHSTy = MHSt->getType();
2157 if (const auto *MHSbits = dyn_cast<BitsInit>(MHS))
2158 MHSTy = BitsRecTy::get(Records, MHSbits->getNumBits());
2159 if (isa<BitInit>(MHS))
2160 MHSTy = BitRecTy::get(Records);
2161
2162 if (const auto *RHSt = dyn_cast<TypedInit>(RHS))
2163 RHSTy = RHSt->getType();
2164 if (const auto *RHSbits = dyn_cast<BitsInit>(RHS))
2165 RHSTy = BitsRecTy::get(Records, RHSbits->getNumBits());
2166 if (isa<BitInit>(RHS))
2167 RHSTy = BitRecTy::get(Records);
2168
2169 // For UnsetInit, it's typed from the other hand.
2170 if (isa<UnsetInit>(MHS))
2171 MHSTy = RHSTy;
2172 if (isa<UnsetInit>(RHS))
2173 RHSTy = MHSTy;
2174
2175 if (!MHSTy || !RHSTy) {
2176 TokError("could not get type for !if");
2177 return nullptr;
2178 }
2179
2180 Type = resolveTypes(MHSTy, RHSTy);
2181 if (!Type) {
2182 TokError(Twine("inconsistent types '") + MHSTy->getAsString() +
2183 "' and '" + RHSTy->getAsString() + "' for !if");
2184 return nullptr;
2185 }
2186 break;
2187 }
2188 case tgtok::XSubst: {
2189 const auto *RHSt = dyn_cast<TypedInit>(RHS);
2190 if (!RHSt) {
2191 TokError("could not get type for !subst");
2192 return nullptr;
2193 }
2194 Type = RHSt->getType();
2195 break;
2196 }
2197 case tgtok::XSetDagArg: {
2198 const auto *MHSt = dyn_cast<TypedInit>(MHS);
2199 if (!MHSt || !isa<IntRecTy, StringRecTy>(MHSt->getType())) {
2200 Error(MHSLoc, Twine("expected integer index or string name, got ") +
2201 (MHSt ? ("type '" + MHSt->getType()->getAsString())
2202 : ("'" + MHS->getAsString())) +
2203 "'");
2204 return nullptr;
2205 }
2206 break;
2207 }
2208 case tgtok::XSetDagName: {
2209 const auto *MHSt = dyn_cast<TypedInit>(MHS);
2210 if (!MHSt || !isa<IntRecTy, StringRecTy>(MHSt->getType())) {
2211 Error(MHSLoc, Twine("expected integer index or string name, got ") +
2212 (MHSt ? ("type '" + MHSt->getType()->getAsString())
2213 : ("'" + MHS->getAsString())) +
2214 "'");
2215 return nullptr;
2216 }
2217 const auto *RHSt = dyn_cast<TypedInit>(RHS);
2218 // The name could be a string or unset.
2219 if (RHSt && !isa<StringRecTy>(RHSt->getType())) {
2220 Error(RHSLoc, Twine("expected string or unset name, got type '") +
2221 RHSt->getType()->getAsString() + "'");
2222 return nullptr;
2223 }
2224 break;
2225 }
2226 }
2227 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
2228 }
2229
2230 case tgtok::XSubstr:
2231 return ParseOperationSubstr(CurRec, ItemType);
2232
2233 case tgtok::XFind:
2234 return ParseOperationFind(CurRec, ItemType);
2235
2236 case tgtok::XCond:
2237 return ParseOperationCond(CurRec, ItemType);
2238
2239 case tgtok::XFoldl: {
2240 // Value ::= !foldl '(' Value ',' Value ',' Id ',' Id ',' Expr ')'
2241 Lex.Lex(); // eat the operation
2242 if (!consume(tgtok::l_paren)) {
2243 TokError("expected '(' after !foldl");
2244 return nullptr;
2245 }
2246
2247 const Init *StartUntyped = ParseValue(CurRec);
2248 if (!StartUntyped)
2249 return nullptr;
2250
2251 const auto *Start = dyn_cast<TypedInit>(StartUntyped);
2252 if (!Start) {
2253 TokError(Twine("could not get type of !foldl start: '") +
2254 StartUntyped->getAsString() + "'");
2255 return nullptr;
2256 }
2257
2258 if (!consume(tgtok::comma)) {
2259 TokError("expected ',' in !foldl");
2260 return nullptr;
2261 }
2262
2263 const Init *ListUntyped = ParseValue(CurRec);
2264 if (!ListUntyped)
2265 return nullptr;
2266
2267 const auto *List = dyn_cast<TypedInit>(ListUntyped);
2268 if (!List) {
2269 TokError(Twine("could not get type of !foldl list: '") +
2270 ListUntyped->getAsString() + "'");
2271 return nullptr;
2272 }
2273
2274 const auto *ListType = dyn_cast<ListRecTy>(List->getType());
2275 if (!ListType) {
2276 TokError(Twine("!foldl list must be a list, but is of type '") +
2277 List->getType()->getAsString());
2278 return nullptr;
2279 }
2280
2281 if (Lex.getCode() != tgtok::comma) {
2282 TokError("expected ',' in !foldl");
2283 return nullptr;
2284 }
2285
2286 if (Lex.Lex() != tgtok::Id) { // eat the ','
2287 TokError("third argument of !foldl must be an identifier");
2288 return nullptr;
2289 }
2290
2291 const Init *A = StringInit::get(Records, Lex.getCurStrVal());
2292 if (CurRec && CurRec->getValue(A)) {
2293 TokError((Twine("left !foldl variable '") + A->getAsString() +
2294 "' already defined")
2295 .str());
2296 return nullptr;
2297 }
2298
2299 if (Lex.Lex() != tgtok::comma) { // eat the id
2300 TokError("expected ',' in !foldl");
2301 return nullptr;
2302 }
2303
2304 if (Lex.Lex() != tgtok::Id) { // eat the ','
2305 TokError("fourth argument of !foldl must be an identifier");
2306 return nullptr;
2307 }
2308
2309 const Init *B = StringInit::get(Records, Lex.getCurStrVal());
2310 if (CurRec && CurRec->getValue(B)) {
2311 TokError((Twine("right !foldl variable '") + B->getAsString() +
2312 "' already defined")
2313 .str());
2314 return nullptr;
2315 }
2316
2317 if (Lex.Lex() != tgtok::comma) { // eat the id
2318 TokError("expected ',' in !foldl");
2319 return nullptr;
2320 }
2321 Lex.Lex(); // eat the ','
2322
2323 // We need to create a temporary record to provide a scope for the
2324 // two variables.
2325 std::unique_ptr<Record> ParseRecTmp;
2326 Record *ParseRec = CurRec;
2327 if (!ParseRec) {
2328 ParseRecTmp =
2329 std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
2330 ParseRec = ParseRecTmp.get();
2331 }
2332
2333 TGVarScope *FoldScope = PushScope(ParseRec);
2334 ParseRec->addValue(RecordVal(A, Start->getType(), RecordVal::FK_Normal));
2335 ParseRec->addValue(
2336 RecordVal(B, ListType->getElementType(), RecordVal::FK_Normal));
2337 const Init *ExprUntyped = ParseValue(ParseRec);
2338 ParseRec->removeValue(A);
2339 ParseRec->removeValue(B);
2340 PopScope(FoldScope);
2341 if (!ExprUntyped)
2342 return nullptr;
2343
2344 const auto *Expr = dyn_cast<TypedInit>(ExprUntyped);
2345 if (!Expr) {
2346 TokError("could not get type of !foldl expression");
2347 return nullptr;
2348 }
2349
2350 if (Expr->getType() != Start->getType()) {
2351 TokError(Twine("!foldl expression must be of same type as start (") +
2352 Start->getType()->getAsString() + "), but is of type " +
2353 Expr->getType()->getAsString());
2354 return nullptr;
2355 }
2356
2357 if (!consume(tgtok::r_paren)) {
2358 TokError("expected ')' in fold operator");
2359 return nullptr;
2360 }
2361
2362 return FoldOpInit::get(Start, List, A, B, Expr, Start->getType())
2363 ->Fold(CurRec);
2364 }
2365 }
2366}
2367
2368/// ParseOperatorType - Parse a type for an operator. This returns
2369/// null on error.
2370///
2371/// OperatorType ::= '<' Type '>'
2372///
2373const RecTy *TGParser::ParseOperatorType() {
2374 const RecTy *Type = nullptr;
2375
2376 if (!consume(tgtok::less)) {
2377 TokError("expected type name for operator");
2378 return nullptr;
2379 }
2380
2381 if (Lex.getCode() == tgtok::Code)
2382 TokError("the 'code' type is not allowed in bang operators; use 'string'");
2383
2384 Type = ParseType();
2385
2386 if (!Type) {
2387 TokError("expected type name for operator");
2388 return nullptr;
2389 }
2390
2391 if (!consume(tgtok::greater)) {
2392 TokError("expected type name for operator");
2393 return nullptr;
2394 }
2395
2396 return Type;
2397}
2398
2399/// Parse the !substr operation. Return null on error.
2400///
2401/// Substr ::= !substr(string, start-int [, length-int]) => string
2402const Init *TGParser::ParseOperationSubstr(Record *CurRec,
2403 const RecTy *ItemType) {
2405 const RecTy *Type = StringRecTy::get(Records);
2406
2407 Lex.Lex(); // eat the operation
2408
2409 if (!consume(tgtok::l_paren)) {
2410 TokError("expected '(' after !substr operator");
2411 return nullptr;
2412 }
2413
2414 const Init *LHS = ParseValue(CurRec);
2415 if (!LHS)
2416 return nullptr;
2417
2418 if (!consume(tgtok::comma)) {
2419 TokError("expected ',' in !substr operator");
2420 return nullptr;
2421 }
2422
2423 SMLoc MHSLoc = Lex.getLoc();
2424 const Init *MHS = ParseValue(CurRec);
2425 if (!MHS)
2426 return nullptr;
2427
2428 SMLoc RHSLoc = Lex.getLoc();
2429 const Init *RHS;
2430 if (consume(tgtok::comma)) {
2431 RHSLoc = Lex.getLoc();
2432 RHS = ParseValue(CurRec);
2433 if (!RHS)
2434 return nullptr;
2435 } else {
2436 RHS = IntInit::get(Records, std::numeric_limits<int64_t>::max());
2437 }
2438
2439 if (!consume(tgtok::r_paren)) {
2440 TokError("expected ')' in !substr operator");
2441 return nullptr;
2442 }
2443
2444 if (ItemType && !Type->typeIsConvertibleTo(ItemType)) {
2445 Error(RHSLoc, Twine("expected value of type '") + ItemType->getAsString() +
2446 "', got '" + Type->getAsString() + "'");
2447 }
2448
2449 const auto *LHSt = dyn_cast<TypedInit>(LHS);
2450 if (!LHSt && !isa<UnsetInit>(LHS)) {
2451 TokError("could not determine type of the string in !substr");
2452 return nullptr;
2453 }
2454 if (LHSt && !isa<StringRecTy>(LHSt->getType())) {
2455 TokError(Twine("expected string, got type '") +
2456 LHSt->getType()->getAsString() + "'");
2457 return nullptr;
2458 }
2459
2460 const auto *MHSt = dyn_cast<TypedInit>(MHS);
2461 if (!MHSt && !isa<UnsetInit>(MHS)) {
2462 TokError("could not determine type of the start position in !substr");
2463 return nullptr;
2464 }
2465 if (MHSt && !isa<IntRecTy>(MHSt->getType())) {
2466 Error(MHSLoc, Twine("expected int, got type '") +
2467 MHSt->getType()->getAsString() + "'");
2468 return nullptr;
2469 }
2470
2471 if (RHS) {
2472 const auto *RHSt = dyn_cast<TypedInit>(RHS);
2473 if (!RHSt && !isa<UnsetInit>(RHS)) {
2474 TokError("could not determine type of the length in !substr");
2475 return nullptr;
2476 }
2477 if (RHSt && !isa<IntRecTy>(RHSt->getType())) {
2478 TokError(Twine("expected int, got type '") +
2479 RHSt->getType()->getAsString() + "'");
2480 return nullptr;
2481 }
2482 }
2483
2484 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
2485}
2486
2487/// Parse the !find operation. Return null on error.
2488///
2489/// Substr ::= !find(string, string [, start-int]) => int
2490const Init *TGParser::ParseOperationFind(Record *CurRec,
2491 const RecTy *ItemType) {
2493 const RecTy *Type = IntRecTy::get(Records);
2494
2495 Lex.Lex(); // eat the operation
2496
2497 if (!consume(tgtok::l_paren)) {
2498 TokError("expected '(' after !find operator");
2499 return nullptr;
2500 }
2501
2502 const Init *LHS = ParseValue(CurRec);
2503 if (!LHS)
2504 return nullptr;
2505
2506 if (!consume(tgtok::comma)) {
2507 TokError("expected ',' in !find operator");
2508 return nullptr;
2509 }
2510
2511 SMLoc MHSLoc = Lex.getLoc();
2512 const Init *MHS = ParseValue(CurRec);
2513 if (!MHS)
2514 return nullptr;
2515
2516 SMLoc RHSLoc = Lex.getLoc();
2517 const Init *RHS;
2518 if (consume(tgtok::comma)) {
2519 RHSLoc = Lex.getLoc();
2520 RHS = ParseValue(CurRec);
2521 if (!RHS)
2522 return nullptr;
2523 } else {
2524 RHS = IntInit::get(Records, 0);
2525 }
2526
2527 if (!consume(tgtok::r_paren)) {
2528 TokError("expected ')' in !find operator");
2529 return nullptr;
2530 }
2531
2532 if (ItemType && !Type->typeIsConvertibleTo(ItemType)) {
2533 Error(RHSLoc, Twine("expected value of type '") + ItemType->getAsString() +
2534 "', got '" + Type->getAsString() + "'");
2535 }
2536
2537 const auto *LHSt = dyn_cast<TypedInit>(LHS);
2538 if (!LHSt && !isa<UnsetInit>(LHS)) {
2539 TokError("could not determine type of the source string in !find");
2540 return nullptr;
2541 }
2542 if (LHSt && !isa<StringRecTy>(LHSt->getType())) {
2543 TokError(Twine("expected string, got type '") +
2544 LHSt->getType()->getAsString() + "'");
2545 return nullptr;
2546 }
2547
2548 const auto *MHSt = dyn_cast<TypedInit>(MHS);
2549 if (!MHSt && !isa<UnsetInit>(MHS)) {
2550 TokError("could not determine type of the target string in !find");
2551 return nullptr;
2552 }
2553 if (MHSt && !isa<StringRecTy>(MHSt->getType())) {
2554 Error(MHSLoc, Twine("expected string, got type '") +
2555 MHSt->getType()->getAsString() + "'");
2556 return nullptr;
2557 }
2558
2559 if (RHS) {
2560 const auto *RHSt = dyn_cast<TypedInit>(RHS);
2561 if (!RHSt && !isa<UnsetInit>(RHS)) {
2562 TokError("could not determine type of the start position in !find");
2563 return nullptr;
2564 }
2565 if (RHSt && !isa<IntRecTy>(RHSt->getType())) {
2566 TokError(Twine("expected int, got type '") +
2567 RHSt->getType()->getAsString() + "'");
2568 return nullptr;
2569 }
2570 }
2571
2572 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
2573}
2574
2575/// Parse the !foreach, !filter, and !sort operations. Return null on error.
2576///
2577/// ForEach ::= !foreach(ID, list-or-dag, expr) => list<expr type>
2578/// Filter ::= !filter(ID, list, predicate) ==> list<list type>
2579/// Sort ::= !sort(ID, list, key-expr) ==> list<list type>
2580const Init *TGParser::ParseOperationListComprehension(Record *CurRec,
2581 const RecTy *ItemType) {
2582 SMLoc OpLoc = Lex.getLoc();
2583 tgtok::TokKind Operation = Lex.getCode();
2584 Lex.Lex(); // eat the operation
2585 if (Lex.getCode() != tgtok::l_paren) {
2586 TokError("expected '(' after !foreach/!filter");
2587 return nullptr;
2588 }
2589
2590 if (Lex.Lex() != tgtok::Id) { // eat the '('
2591 TokError("first argument of !foreach/!filter must be an identifier");
2592 return nullptr;
2593 }
2594
2595 const Init *LHS = StringInit::get(Records, Lex.getCurStrVal());
2596 Lex.Lex(); // eat the ID.
2597
2598 if (CurRec && CurRec->getValue(LHS)) {
2599 TokError((Twine("iteration variable '") + LHS->getAsString() +
2600 "' is already defined")
2601 .str());
2602 return nullptr;
2603 }
2604
2605 if (!consume(tgtok::comma)) {
2606 TokError("expected ',' in !foreach/!filter");
2607 return nullptr;
2608 }
2609
2610 const Init *MHS = ParseValue(CurRec);
2611 if (!MHS)
2612 return nullptr;
2613
2614 if (!consume(tgtok::comma)) {
2615 TokError("expected ',' in !foreach/!filter");
2616 return nullptr;
2617 }
2618
2619 const auto *MHSt = dyn_cast<TypedInit>(MHS);
2620 if (!MHSt) {
2621 TokError("could not get type of !foreach/!filter list or dag");
2622 return nullptr;
2623 }
2624
2625 const RecTy *InEltType = nullptr;
2626 const RecTy *ExprEltType = nullptr;
2627 bool IsDAG = false;
2628
2629 if (const auto *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) {
2630 InEltType = InListTy->getElementType();
2631 if (ItemType) {
2632 if (const auto *OutListTy = dyn_cast<ListRecTy>(ItemType)) {
2633 switch (Operation) {
2634 case tgtok::XForEach:
2635 ExprEltType = OutListTy->getElementType();
2636 break;
2637 case tgtok::XFilter:
2638 ExprEltType = IntRecTy::get(Records);
2639 break;
2640 case tgtok::XSort:
2641 ExprEltType = nullptr;
2642 break;
2643 default:
2644 llvm_unreachable("unexpected token");
2645 }
2646 } else {
2647 Error(OpLoc, "expected value of type '" +
2648 Twine(ItemType->getAsString()) +
2649 "', but got list type");
2650 return nullptr;
2651 }
2652 }
2653 } else if (const auto *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) {
2654 switch (Operation) {
2655 case tgtok::XFilter:
2656 TokError("!filter must have a list argument");
2657 return nullptr;
2658 case tgtok::XSort:
2659 TokError("!sort must have a list argument");
2660 return nullptr;
2661 case tgtok::XForEach:
2662 break;
2663 default:
2664 llvm_unreachable("unexpected token");
2665 }
2666 InEltType = InDagTy;
2667 if (ItemType && !isa<DagRecTy>(ItemType)) {
2668 Error(OpLoc, "expected value of type '" + Twine(ItemType->getAsString()) +
2669 "', but got dag type");
2670 return nullptr;
2671 }
2672 IsDAG = true;
2673 } else {
2674 switch (Operation) {
2675 case tgtok::XForEach:
2676 TokError("!foreach must have a list or dag argument");
2677 return nullptr;
2678 case tgtok::XFilter:
2679 TokError("!filter must have a list argument");
2680 return nullptr;
2681 case tgtok::XSort:
2682 TokError("!sort must have a list argument");
2683 return nullptr;
2684 default:
2685 llvm_unreachable("unexpected token");
2686 }
2687 }
2688
2689 // We need to create a temporary record to provide a scope for the
2690 // iteration variable.
2691 std::unique_ptr<Record> ParseRecTmp;
2692 Record *ParseRec = CurRec;
2693 if (!ParseRec) {
2694 ParseRecTmp =
2695 std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
2696 ParseRec = ParseRecTmp.get();
2697 }
2698 TGVarScope *TempScope = PushScope(ParseRec);
2699 ParseRec->addValue(RecordVal(LHS, InEltType, RecordVal::FK_Normal));
2700 const Init *RHS = ParseValue(ParseRec, ExprEltType);
2701 ParseRec->removeValue(LHS);
2702 PopScope(TempScope);
2703 if (!RHS)
2704 return nullptr;
2705
2706 if (!consume(tgtok::r_paren)) {
2707 TokError("expected ')' in !foreach/!filter");
2708 return nullptr;
2709 }
2710
2711 const RecTy *OutType;
2713 switch (Operation) {
2714 case tgtok::XForEach:
2716 if (IsDAG) {
2717 OutType = InEltType;
2718 } else {
2719 const auto *RHSt = dyn_cast<TypedInit>(RHS);
2720 if (!RHSt) {
2721 TokError("could not get type of !foreach result expression");
2722 return nullptr;
2723 }
2724 OutType = RHSt->getType()->getListTy();
2725 }
2726 break;
2727 case tgtok::XFilter:
2729 OutType = InEltType->getListTy();
2730 break;
2731 case tgtok::XSort:
2733 OutType = InEltType->getListTy();
2734 break;
2735 default:
2736 llvm_unreachable("unexpected token");
2737 }
2738 return (TernOpInit::get(Opc, LHS, MHS, RHS, OutType))->Fold(CurRec);
2739}
2740
2741const Init *TGParser::ParseOperationCond(Record *CurRec,
2742 const RecTy *ItemType) {
2743 Lex.Lex(); // eat the operation 'cond'
2744
2745 if (!consume(tgtok::l_paren)) {
2746 TokError("expected '(' after !cond operator");
2747 return nullptr;
2748 }
2749
2750 // Parse through '[Case: Val,]+'
2753 while (true) {
2755 break;
2756
2757 const Init *V = ParseValue(CurRec);
2758 if (!V)
2759 return nullptr;
2760 Case.push_back(V);
2761
2762 if (!consume(tgtok::colon)) {
2763 TokError("expected ':' following a condition in !cond operator");
2764 return nullptr;
2765 }
2766
2767 V = ParseValue(CurRec, ItemType);
2768 if (!V)
2769 return nullptr;
2770 Val.push_back(V);
2771
2773 break;
2774
2775 if (!consume(tgtok::comma)) {
2776 TokError("expected ',' or ')' following a value in !cond operator");
2777 return nullptr;
2778 }
2779 }
2780
2781 if (Case.size() < 1) {
2782 TokError(
2783 "there should be at least 1 'condition : value' in the !cond operator");
2784 return nullptr;
2785 }
2786
2787 // resolve type
2788 const RecTy *Type = nullptr;
2789 for (const Init *V : Val) {
2790 const RecTy *VTy = nullptr;
2791 if (const auto *Vt = dyn_cast<TypedInit>(V))
2792 VTy = Vt->getType();
2793 if (const auto *Vbits = dyn_cast<BitsInit>(V))
2794 VTy = BitsRecTy::get(Records, Vbits->getNumBits());
2795 if (isa<BitInit>(V))
2796 VTy = BitRecTy::get(Records);
2797
2798 if (Type == nullptr) {
2799 if (!isa<UnsetInit>(V))
2800 Type = VTy;
2801 } else {
2802 if (!isa<UnsetInit>(V)) {
2803 const RecTy *RType = resolveTypes(Type, VTy);
2804 if (!RType) {
2805 TokError(Twine("inconsistent types '") + Type->getAsString() +
2806 "' and '" + VTy->getAsString() + "' for !cond");
2807 return nullptr;
2808 }
2809 Type = RType;
2810 }
2811 }
2812 }
2813
2814 if (!Type) {
2815 TokError("could not determine type for !cond from its arguments");
2816 return nullptr;
2817 }
2818 return CondOpInit::get(Case, Val, Type)->Fold(CurRec);
2819}
2820
2821/// ParseSimpleValue - Parse a tblgen value. This returns null on error.
2822///
2823/// SimpleValue ::= IDValue
2824/// SimpleValue ::= INTVAL
2825/// SimpleValue ::= STRVAL+
2826/// SimpleValue ::= CODEFRAGMENT
2827/// SimpleValue ::= '?'
2828/// SimpleValue ::= '{' ValueList '}'
2829/// SimpleValue ::= ID '<' ValueListNE '>'
2830/// SimpleValue ::= '[' ValueList ']'
2831/// SimpleValue ::= '(' IDValue DagArgList ')'
2832/// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
2833/// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
2834/// SimpleValue ::= DIVTOK '(' Value ',' Value ')'
2835/// SimpleValue ::= SUBTOK '(' Value ',' Value ')'
2836/// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
2837/// SimpleValue ::= SRATOK '(' Value ',' Value ')'
2838/// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
2839/// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
2840/// SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')'
2841/// SimpleValue ::= LISTREMOVETOK '(' Value ',' Value ')'
2842/// SimpleValue ::= RANGE '(' Value ')'
2843/// SimpleValue ::= RANGE '(' Value ',' Value ')'
2844/// SimpleValue ::= RANGE '(' Value ',' Value ',' Value ')'
2845/// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
2846/// SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
2847///
2848const Init *TGParser::ParseSimpleValue(Record *CurRec, const RecTy *ItemType,
2849 IDParseMode Mode) {
2850 const Init *R = nullptr;
2851 tgtok::TokKind Code = Lex.getCode();
2852
2853 // Parse bang operators.
2854 if (tgtok::isBangOperator(Code))
2855 return ParseOperation(CurRec, ItemType);
2856
2857 switch (Code) {
2858 default:
2859 TokError("Unknown or reserved token when parsing a value");
2860 break;
2861
2862 case tgtok::TrueVal:
2863 R = IntInit::get(Records, 1);
2864 Lex.Lex();
2865 break;
2866 case tgtok::FalseVal:
2867 R = IntInit::get(Records, 0);
2868 Lex.Lex();
2869 break;
2870 case tgtok::IntVal:
2871 R = IntInit::get(Records, Lex.getCurIntVal());
2872 Lex.Lex();
2873 break;
2874 case tgtok::BinaryIntVal: {
2875 auto BinaryVal = Lex.getCurBinaryIntVal();
2876 SmallVector<Init *, 16> Bits(BinaryVal.second);
2877 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
2878 Bits[i] = BitInit::get(Records, BinaryVal.first & (1LL << i));
2879 R = BitsInit::get(Records, Bits);
2880 Lex.Lex();
2881 break;
2882 }
2883 case tgtok::StrVal: {
2884 std::string Val = Lex.getCurStrVal();
2885 Lex.Lex();
2886
2887 // Handle multiple consecutive concatenated strings.
2888 while (Lex.getCode() == tgtok::StrVal) {
2889 Val += Lex.getCurStrVal();
2890 Lex.Lex();
2891 }
2892
2893 R = StringInit::get(Records, Val);
2894 break;
2895 }
2897 R = StringInit::get(Records, Lex.getCurStrVal(), StringInit::SF_Code);
2898 Lex.Lex();
2899 break;
2900 case tgtok::question:
2901 R = UnsetInit::get(Records);
2902 Lex.Lex();
2903 break;
2904 case tgtok::Id: {
2905 SMRange NameLoc = Lex.getLocRange();
2906 const StringInit *Name = StringInit::get(Records, Lex.getCurStrVal());
2907 tgtok::TokKind Next = Lex.Lex();
2908 if (Next == tgtok::equal) // Named argument.
2909 return Name;
2910 if (Next != tgtok::less) // consume the Id.
2911 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
2912
2913 // Value ::= CLASSID '<' ArgValueList '>' (CLASSID has been consumed)
2914 // This is supposed to synthesize a new anonymous definition, deriving
2915 // from the class with the template arguments, but no body.
2916 const Record *Class = Records.getClass(Name->getValue());
2917 if (!Class) {
2918 Error(NameLoc.Start,
2919 "Expected a class name, got '" + Name->getValue() + "'");
2920 return nullptr;
2921 }
2922
2924 SmallVector<SMLoc> ArgLocs;
2925 Lex.Lex(); // consume the <
2926 if (ParseTemplateArgValueList(Args, ArgLocs, CurRec, Class))
2927 return nullptr; // Error parsing value list.
2928
2929 if (CheckTemplateArgValues(Args, ArgLocs, Class))
2930 return nullptr; // Error checking template argument values.
2931
2932 if (resolveArguments(Class, Args, NameLoc.Start))
2933 return nullptr;
2934
2935 if (TrackReferenceLocs)
2936 Class->appendReferenceLoc(NameLoc);
2937 return VarDefInit::get(NameLoc.Start, Class, Args)->Fold();
2938 }
2939 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
2940 SMLoc BraceLoc = Lex.getLoc();
2941 Lex.Lex(); // eat the '{'
2943
2944 if (Lex.getCode() != tgtok::r_brace) {
2945 ParseValueList(Vals, CurRec);
2946 if (Vals.empty())
2947 return nullptr;
2948 }
2949 if (!consume(tgtok::r_brace)) {
2950 TokError("expected '}' at end of bit list value");
2951 return nullptr;
2952 }
2953
2955
2956 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
2957 // first. We'll first read everything in to a vector, then we can reverse
2958 // it to get the bits in the correct order for the BitsInit value.
2959 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2960 // FIXME: The following two loops would not be duplicated
2961 // if the API was a little more orthogonal.
2962
2963 // bits<n> values are allowed to initialize n bits.
2964 if (const auto *BI = dyn_cast<BitsInit>(Vals[i])) {
2965 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
2966 NewBits.push_back(BI->getBit((e - i) - 1));
2967 continue;
2968 }
2969 // bits<n> can also come from variable initializers.
2970 if (const auto *VI = dyn_cast<VarInit>(Vals[i])) {
2971 if (const auto *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
2972 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
2973 NewBits.push_back(VI->getBit((e - i) - 1));
2974 continue;
2975 }
2976 // Fallthrough to try convert this to a bit.
2977 }
2978 // All other values must be convertible to just a single bit.
2979 const Init *Bit = Vals[i]->getCastTo(BitRecTy::get(Records));
2980 if (!Bit) {
2981 Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
2982 ") is not convertable to a bit");
2983 return nullptr;
2984 }
2985 NewBits.push_back(Bit);
2986 }
2987 std::reverse(NewBits.begin(), NewBits.end());
2988 return BitsInit::get(Records, NewBits);
2989 }
2990 case tgtok::l_square: { // Value ::= '[' ValueList ']'
2991 Lex.Lex(); // eat the '['
2993
2994 const RecTy *DeducedEltTy = nullptr;
2995 const ListRecTy *GivenListTy = nullptr;
2996
2997 if (ItemType) {
2998 const auto *ListType = dyn_cast<ListRecTy>(ItemType);
2999 if (!ListType) {
3000 TokError(Twine("Encountered a list when expecting a ") +
3001 ItemType->getAsString());
3002 return nullptr;
3003 }
3004 GivenListTy = ListType;
3005 }
3006
3007 if (Lex.getCode() != tgtok::r_square) {
3008 ParseValueList(Vals, CurRec,
3009 GivenListTy ? GivenListTy->getElementType() : nullptr);
3010 if (Vals.empty())
3011 return nullptr;
3012 }
3013 if (!consume(tgtok::r_square)) {
3014 TokError("expected ']' at end of list value");
3015 return nullptr;
3016 }
3017
3018 const RecTy *GivenEltTy = nullptr;
3019 if (consume(tgtok::less)) {
3020 // Optional list element type
3021 GivenEltTy = ParseType();
3022 if (!GivenEltTy) {
3023 // Couldn't parse element type
3024 return nullptr;
3025 }
3026
3027 if (!consume(tgtok::greater)) {
3028 TokError("expected '>' at end of list element type");
3029 return nullptr;
3030 }
3031 }
3032
3033 // Check elements
3034 const RecTy *EltTy = nullptr;
3035 for (const Init *V : Vals) {
3036 const auto *TArg = dyn_cast<TypedInit>(V);
3037 if (TArg) {
3038 if (EltTy) {
3039 EltTy = resolveTypes(EltTy, TArg->getType());
3040 if (!EltTy) {
3041 TokError("Incompatible types in list elements");
3042 return nullptr;
3043 }
3044 } else {
3045 EltTy = TArg->getType();
3046 }
3047 }
3048 }
3049
3050 if (GivenEltTy) {
3051 if (EltTy) {
3052 // Verify consistency
3053 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
3054 TokError("Incompatible types in list elements");
3055 return nullptr;
3056 }
3057 }
3058 EltTy = GivenEltTy;
3059 }
3060
3061 if (!EltTy) {
3062 if (!ItemType) {
3063 TokError("No type for list");
3064 return nullptr;
3065 }
3066 DeducedEltTy = GivenListTy->getElementType();
3067 } else {
3068 // Make sure the deduced type is compatible with the given type
3069 if (GivenListTy) {
3070 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
3071 TokError(Twine("Element type mismatch for list: element type '") +
3072 EltTy->getAsString() + "' not convertible to '" +
3073 GivenListTy->getElementType()->getAsString());
3074 return nullptr;
3075 }
3076 }
3077 DeducedEltTy = EltTy;
3078 }
3079
3080 return ListInit::get(Vals, DeducedEltTy);
3081 }
3082 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
3083 // Value ::= '(' '[' ValueList ']' DagArgList ')'
3084 Lex.Lex(); // eat the '('
3085 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast &&
3086 Lex.getCode() != tgtok::question && Lex.getCode() != tgtok::XGetDagOp &&
3087 Lex.getCode() != tgtok::l_square) {
3088 TokError("expected identifier or list of value types in dag init");
3089 return nullptr;
3090 }
3091
3092 const Init *Operator = ParseValue(CurRec);
3093 if (!Operator)
3094 return nullptr;
3095
3096 // If the operator name is present, parse it.
3097 const StringInit *OperatorName = nullptr;
3098 if (consume(tgtok::colon)) {
3099 if (Lex.getCode() != tgtok::VarName) { // eat the ':'
3100 TokError("expected variable name in dag operator");
3101 return nullptr;
3102 }
3103 OperatorName = StringInit::get(Records, Lex.getCurStrVal());
3104 Lex.Lex(); // eat the VarName.
3105 }
3106
3108 if (Lex.getCode() != tgtok::r_paren) {
3109 ParseDagArgList(DagArgs, CurRec);
3110 if (DagArgs.empty())
3111 return nullptr;
3112 }
3113
3114 if (!consume(tgtok::r_paren)) {
3115 TokError("expected ')' in dag init");
3116 return nullptr;
3117 }
3118
3119 return DagInit::get(Operator, OperatorName, DagArgs);
3120 }
3121 }
3122
3123 return R;
3124}
3125
3126/// ParseValue - Parse a TableGen value. This returns null on error.
3127///
3128/// Value ::= SimpleValue ValueSuffix*
3129/// ValueSuffix ::= '{' BitList '}'
3130/// ValueSuffix ::= '[' SliceElements ']'
3131/// ValueSuffix ::= '.' ID
3132///
3133const Init *TGParser::ParseValue(Record *CurRec, const RecTy *ItemType,
3134 IDParseMode Mode) {
3135 SMLoc LHSLoc = Lex.getLoc();
3136 const Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
3137 if (!Result)
3138 return nullptr;
3139
3140 // Parse the suffixes now if present.
3141 while (true) {
3142 switch (Lex.getCode()) {
3143 default:
3144 return Result;
3145 case tgtok::l_brace: {
3146 if (Mode == ParseNameMode)
3147 // This is the beginning of the object body.
3148 return Result;
3149
3150 SMLoc CurlyLoc = Lex.getLoc();
3151 Lex.Lex(); // eat the '{'
3152 SmallVector<unsigned, 16> Ranges;
3153 ParseRangeList(Ranges);
3154 if (Ranges.empty())
3155 return nullptr;
3156
3157 // Reverse the bitlist.
3158 std::reverse(Ranges.begin(), Ranges.end());
3159 Result = Result->convertInitializerBitRange(Ranges);
3160 if (!Result) {
3161 Error(CurlyLoc, "Invalid bit range for value");
3162 return nullptr;
3163 }
3164
3165 // Eat the '}'.
3166 if (!consume(tgtok::r_brace)) {
3167 TokError("expected '}' at end of bit range list");
3168 return nullptr;
3169 }
3170 break;
3171 }
3172 case tgtok::l_square: {
3173 const auto *LHS = dyn_cast<TypedInit>(Result);
3174 if (!LHS) {
3175 Error(LHSLoc, "Invalid value, list expected");
3176 return nullptr;
3177 }
3178
3179 const auto *LHSTy = dyn_cast<ListRecTy>(LHS->getType());
3180 if (!LHSTy) {
3181 Error(LHSLoc, "Type '" + Twine(LHS->getType()->getAsString()) +
3182 "' is invalid, list expected");
3183 return nullptr;
3184 }
3185
3186 Lex.Lex(); // eat the '['
3187 const TypedInit *RHS = ParseSliceElements(CurRec, /*Single=*/true);
3188 if (!RHS)
3189 return nullptr;
3190
3191 if (isa<ListRecTy>(RHS->getType())) {
3192 Result =
3193 BinOpInit::get(BinOpInit::LISTSLICE, LHS, RHS, LHSTy)->Fold(CurRec);
3194 } else {
3196 LHSTy->getElementType())
3197 ->Fold(CurRec);
3198 }
3199
3200 assert(Result);
3201
3202 // Eat the ']'.
3203 if (!consume(tgtok::r_square)) {
3204 TokError("expected ']' at end of list slice");
3205 return nullptr;
3206 }
3207 break;
3208 }
3209 case tgtok::dot: {
3210 if (Lex.Lex() != tgtok::Id) { // eat the .
3211 TokError("expected field identifier after '.'");
3212 return nullptr;
3213 }
3214 SMRange FieldNameLoc = Lex.getLocRange();
3215 const StringInit *FieldName =
3216 StringInit::get(Records, Lex.getCurStrVal());
3217 if (!Result->getFieldType(FieldName)) {
3218 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
3219 Result->getAsString() + "'");
3220 return nullptr;
3221 }
3222
3223 // Add a reference to this field if we know the record class.
3224 if (TrackReferenceLocs) {
3225 if (const auto *DI = dyn_cast<DefInit>(Result)) {
3226 const RecordVal *V = DI->getDef()->getValue(FieldName);
3227 const_cast<RecordVal *>(V)->addReferenceLoc(FieldNameLoc);
3228 } else if (const auto *TI = dyn_cast<TypedInit>(Result)) {
3229 if (const auto *RecTy = dyn_cast<RecordRecTy>(TI->getType())) {
3230 for (const Record *R : RecTy->getClasses())
3231 if (const auto *RV = R->getValue(FieldName))
3232 const_cast<RecordVal *>(RV)->addReferenceLoc(FieldNameLoc);
3233 }
3234 }
3235 }
3236
3237 Result = FieldInit::get(Result, FieldName)->Fold(CurRec);
3238 Lex.Lex(); // eat field name
3239 break;
3240 }
3241
3242 case tgtok::paste:
3243 SMLoc PasteLoc = Lex.getLoc();
3244 const auto *LHS = dyn_cast<TypedInit>(Result);
3245 if (!LHS) {
3246 Error(PasteLoc, "LHS of paste is not typed!");
3247 return nullptr;
3248 }
3249
3250 // Check if it's a 'listA # listB'
3251 if (isa<ListRecTy>(LHS->getType())) {
3252 Lex.Lex(); // Eat the '#'.
3253
3254 assert(Mode == ParseValueMode && "encountered paste of lists in name");
3255
3256 switch (Lex.getCode()) {
3257 case tgtok::colon:
3258 case tgtok::semi:
3259 case tgtok::l_brace:
3260 Result = LHS; // trailing paste, ignore.
3261 break;
3262 default:
3263 const Init *RHSResult = ParseValue(CurRec, ItemType, ParseValueMode);
3264 if (!RHSResult)
3265 return nullptr;
3266 Result = BinOpInit::getListConcat(LHS, RHSResult);
3267 break;
3268 }
3269 break;
3270 }
3271
3272 // Create a !strconcat() operation, first casting each operand to
3273 // a string if necessary.
3274 if (LHS->getType() != StringRecTy::get(Records)) {
3275 auto CastLHS = dyn_cast<TypedInit>(
3277 ->Fold(CurRec));
3278 if (!CastLHS) {
3279 Error(PasteLoc,
3280 Twine("can't cast '") + LHS->getAsString() + "' to string");
3281 return nullptr;
3282 }
3283 LHS = CastLHS;
3284 }
3285
3286 const TypedInit *RHS = nullptr;
3287
3288 Lex.Lex(); // Eat the '#'.
3289 switch (Lex.getCode()) {
3290 case tgtok::colon:
3291 case tgtok::semi:
3292 case tgtok::l_brace:
3293 // These are all of the tokens that can begin an object body.
3294 // Some of these can also begin values but we disallow those cases
3295 // because they are unlikely to be useful.
3296
3297 // Trailing paste, concat with an empty string.
3298 RHS = StringInit::get(Records, "");
3299 break;
3300
3301 default:
3302 const Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode);
3303 if (!RHSResult)
3304 return nullptr;
3305 RHS = dyn_cast<TypedInit>(RHSResult);
3306 if (!RHS) {
3307 Error(PasteLoc, "RHS of paste is not typed!");
3308 return nullptr;
3309 }
3310
3311 if (RHS->getType() != StringRecTy::get(Records)) {
3312 auto CastRHS = dyn_cast<TypedInit>(
3314 ->Fold(CurRec));
3315 if (!CastRHS) {
3316 Error(PasteLoc,
3317 Twine("can't cast '") + RHS->getAsString() + "' to string");
3318 return nullptr;
3319 }
3320 RHS = CastRHS;
3321 }
3322
3323 break;
3324 }
3325
3327 break;
3328 }
3329 }
3330}
3331
3332/// ParseDagArgList - Parse the argument list for a dag literal expression.
3333///
3334/// DagArg ::= Value (':' VARNAME)?
3335/// DagArg ::= VARNAME
3336/// DagArgList ::= DagArg
3337/// DagArgList ::= DagArgList ',' DagArg
3338void TGParser::ParseDagArgList(
3339 SmallVectorImpl<std::pair<const Init *, const StringInit *>> &Result,
3340 Record *CurRec) {
3341
3342 while (true) {
3343 // DagArg ::= VARNAME
3344 if (Lex.getCode() == tgtok::VarName) {
3345 // A missing value is treated like '?'.
3346 const StringInit *VarName = StringInit::get(Records, Lex.getCurStrVal());
3347 Result.emplace_back(UnsetInit::get(Records), VarName);
3348 Lex.Lex();
3349 } else {
3350 // DagArg ::= Value (':' VARNAME)?
3351 const Init *Val = ParseValue(CurRec);
3352 if (!Val) {
3353 Result.clear();
3354 return;
3355 }
3356
3357 // If the variable name is present, add it.
3358 const StringInit *VarName = nullptr;
3359 if (Lex.getCode() == tgtok::colon) {
3360 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
3361 TokError("expected variable name in dag literal");
3362 Result.clear();
3363 return;
3364 }
3365 VarName = StringInit::get(Records, Lex.getCurStrVal());
3366 Lex.Lex(); // eat the VarName.
3367 }
3368
3369 Result.emplace_back(Val, VarName);
3370 }
3371 if (!consume(tgtok::comma))
3372 break;
3373 }
3374}
3375
3376/// ParseValueList - Parse a comma separated list of values, returning them
3377/// in a vector. Note that this always expects to be able to parse at least one
3378/// value. It returns an empty list if this is not possible.
3379///
3380/// ValueList ::= Value (',' Value)
3381///
3382void TGParser::ParseValueList(SmallVectorImpl<const Init *> &Result,
3383 Record *CurRec, const RecTy *ItemType) {
3384 Result.push_back(ParseValue(CurRec, ItemType));
3385 if (!Result.back()) {
3386 Result.clear();
3387 return;
3388 }
3389
3390 while (consume(tgtok::comma)) {
3391 // ignore trailing comma for lists
3392 if (Lex.getCode() == tgtok::r_square)
3393 return;
3394 Result.push_back(ParseValue(CurRec, ItemType));
3395 if (!Result.back()) {
3396 Result.clear();
3397 return;
3398 }
3399 }
3400}
3401
3402// ParseTemplateArgValueList - Parse a template argument list with the syntax
3403// shown, filling in the Result vector. The open angle has been consumed.
3404// An empty argument list is allowed. Return false if okay, true if an
3405// error was detected.
3406//
3407// ArgValueList ::= '<' PostionalArgValueList [','] NamedArgValueList '>'
3408// PostionalArgValueList ::= [Value {',' Value}*]
3409// NamedArgValueList ::= [NameValue '=' Value {',' NameValue '=' Value}*]
3410bool TGParser::ParseTemplateArgValueList(
3412 SmallVectorImpl<SMLoc> &ArgLocs, Record *CurRec, const Record *ArgsRec) {
3413 assert(Result.empty() && "Result vector is not empty");
3414 ArrayRef<const Init *> TArgs = ArgsRec->getTemplateArgs();
3415
3416 if (consume(tgtok::greater)) // empty value list
3417 return false;
3418
3419 bool HasNamedArg = false;
3420 unsigned ArgIndex = 0;
3421 while (true) {
3422 if (ArgIndex >= TArgs.size()) {
3423 TokError("Too many template arguments: " + utostr(ArgIndex + 1));
3424 return true;
3425 }
3426
3427 SMLoc ValueLoc = ArgLocs.emplace_back(Lex.getLoc());
3428 // If we are parsing named argument, we don't need to know the argument name
3429 // and argument type will be resolved after we know the name.
3430 const Init *Value = ParseValue(
3431 CurRec,
3432 HasNamedArg ? nullptr : ArgsRec->getValue(TArgs[ArgIndex])->getType());
3433 if (!Value)
3434 return true;
3435
3436 // If we meet '=', then we are parsing named arguments.
3437 if (Lex.getCode() == tgtok::equal) {
3438 if (!isa<StringInit>(Value))
3439 return Error(ValueLoc,
3440 "The name of named argument should be a valid identifier");
3441
3442 auto *Name = cast<StringInit>(Value);
3443 const Init *QualifiedName = QualifyName(*ArgsRec, Name);
3444 auto *NamedArg = ArgsRec->getValue(QualifiedName);
3445 if (!NamedArg)
3446 return Error(ValueLoc,
3447 "Argument " + Name->getAsString() + " doesn't exist");
3448
3449 Lex.Lex(); // eat the '='.
3450 ValueLoc = Lex.getLoc();
3451 Value = ParseValue(CurRec, NamedArg->getType());
3452 // Named value can't be uninitialized.
3453 if (isa<UnsetInit>(Value))
3454 return Error(ValueLoc,
3455 "The value of named argument should be initialized, "
3456 "but we got '" +
3457 Value->getAsString() + "'");
3458
3459 Result.push_back(ArgumentInit::get(Value, QualifiedName));
3460 HasNamedArg = true;
3461 } else {
3462 // Positional arguments should be put before named arguments.
3463 if (HasNamedArg)
3464 return Error(ValueLoc,
3465 "Positional argument should be put before named argument");
3466
3467 Result.push_back(ArgumentInit::get(Value, ArgIndex));
3468 }
3469
3470 if (consume(tgtok::greater)) // end of argument list?
3471 return false;
3472 if (!consume(tgtok::comma))
3473 return TokError("Expected comma before next argument");
3474 ++ArgIndex;
3475 }
3476}
3477
3478/// ParseDeclaration - Read a declaration, returning the name of field ID, or an
3479/// empty string on error. This can happen in a number of different contexts,
3480/// including within a def or in the template args for a class (in which case
3481/// CurRec will be non-null) and within the template args for a multiclass (in
3482/// which case CurRec will be null, but CurMultiClass will be set). This can
3483/// also happen within a def that is within a multiclass, which will set both
3484/// CurRec and CurMultiClass.
3485///
3486/// Declaration ::= FIELD? Type ID ('=' Value)?
3487///
3488const Init *TGParser::ParseDeclaration(Record *CurRec,
3489 bool ParsingTemplateArgs) {
3490 // Read the field prefix if present.
3491 bool HasField = consume(tgtok::Field);
3492
3493 const RecTy *Type = ParseType();
3494 if (!Type)
3495 return nullptr;
3496
3497 if (Lex.getCode() != tgtok::Id) {
3498 TokError("Expected identifier in declaration");
3499 return nullptr;
3500 }
3501
3502 std::string Str = Lex.getCurStrVal();
3503 if (Str == "NAME") {
3504 TokError("'" + Str + "' is a reserved variable name");
3505 return nullptr;
3506 }
3507
3508 if (!ParsingTemplateArgs && CurScope->varAlreadyDefined(Str)) {
3509 TokError("local variable of this name already exists");
3510 return nullptr;
3511 }
3512
3513 SMLoc IdLoc = Lex.getLoc();
3514 const Init *DeclName = StringInit::get(Records, Str);
3515 Lex.Lex();
3516
3517 bool BadField;
3518 if (!ParsingTemplateArgs) { // def, possibly in a multiclass
3519 BadField = AddValue(CurRec, IdLoc,
3520 RecordVal(DeclName, IdLoc, Type,
3523 } else if (CurRec) { // class template argument
3524 DeclName = QualifyName(*CurRec, DeclName);
3525 BadField =
3526 AddValue(CurRec, IdLoc,
3527 RecordVal(DeclName, IdLoc, Type, RecordVal::FK_TemplateArg));
3528 } else { // multiclass template argument
3529 assert(CurMultiClass && "invalid context for template argument");
3530 DeclName = QualifyName(CurMultiClass, DeclName);
3531 BadField =
3532 AddValue(CurRec, IdLoc,
3533 RecordVal(DeclName, IdLoc, Type, RecordVal::FK_TemplateArg));
3534 }
3535 if (BadField)
3536 return nullptr;
3537
3538 // If a value is present, parse it and set new field's value.
3539 if (consume(tgtok::equal)) {
3540 SMLoc ValLoc = Lex.getLoc();
3541 const Init *Val = ParseValue(CurRec, Type);
3542 if (!Val ||
3543 SetValue(CurRec, ValLoc, DeclName, {}, Val,
3544 /*AllowSelfAssignment=*/false, /*OverrideDefLoc=*/false)) {
3545 // Return the name, even if an error is thrown. This is so that we can
3546 // continue to make some progress, even without the value having been
3547 // initialized.
3548 return DeclName;
3549 }
3550 }
3551
3552 return DeclName;
3553}
3554
3555/// ParseForeachDeclaration - Read a foreach declaration, returning
3556/// the name of the declared object or a NULL Init on error. Return
3557/// the name of the parsed initializer list through ForeachListName.
3558///
3559/// ForeachDeclaration ::= ID '=' '{' RangeList '}'
3560/// ForeachDeclaration ::= ID '=' RangePiece
3561/// ForeachDeclaration ::= ID '=' Value
3562///
3563const VarInit *
3564TGParser::ParseForeachDeclaration(const Init *&ForeachListValue) {
3565 if (Lex.getCode() != tgtok::Id) {
3566 TokError("Expected identifier in foreach declaration");
3567 return nullptr;
3568 }
3569
3570 const Init *DeclName = StringInit::get(Records, Lex.getCurStrVal());
3571 Lex.Lex();
3572
3573 // If a value is present, parse it.
3574 if (!consume(tgtok::equal)) {
3575 TokError("Expected '=' in foreach declaration");
3576 return nullptr;
3577 }
3578
3579 const RecTy *IterType = nullptr;
3580 SmallVector<unsigned, 16> Ranges;
3581
3582 switch (Lex.getCode()) {
3583 case tgtok::l_brace: { // '{' RangeList '}'
3584 Lex.Lex(); // eat the '{'
3585 ParseRangeList(Ranges);
3586 if (!consume(tgtok::r_brace)) {
3587 TokError("expected '}' at end of bit range list");
3588 return nullptr;
3589 }
3590 break;
3591 }
3592
3593 default: {
3594 SMLoc ValueLoc = Lex.getLoc();
3595 const Init *I = ParseValue(nullptr);
3596 if (!I)
3597 return nullptr;
3598
3599 const auto *TI = dyn_cast<TypedInit>(I);
3600 if (TI && isa<ListRecTy>(TI->getType())) {
3601 ForeachListValue = I;
3602 IterType = cast<ListRecTy>(TI->getType())->getElementType();
3603 break;
3604 }
3605
3606 if (TI) {
3607 if (ParseRangePiece(Ranges, TI))
3608 return nullptr;
3609 break;
3610 }
3611
3612 Error(ValueLoc, "expected a list, got '" + I->getAsString() + "'");
3613 if (CurMultiClass) {
3614 PrintNote({}, "references to multiclass template arguments cannot be "
3615 "resolved at this time");
3616 }
3617 return nullptr;
3618 }
3619 }
3620
3621 if (!Ranges.empty()) {
3622 assert(!IterType && "Type already initialized?");
3623 IterType = IntRecTy::get(Records);
3624 std::vector<Init *> Values;
3625 for (unsigned R : Ranges)
3626 Values.push_back(IntInit::get(Records, R));
3627 ForeachListValue = ListInit::get(Values, IterType);
3628 }
3629
3630 if (!IterType)
3631 return nullptr;
3632
3633 return VarInit::get(DeclName, IterType);
3634}
3635
3636/// ParseTemplateArgList - Read a template argument list, which is a non-empty
3637/// sequence of template-declarations in <>'s. If CurRec is non-null, these are
3638/// template args for a class. If null, these are the template args for a
3639/// multiclass.
3640///
3641/// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
3642///
3643bool TGParser::ParseTemplateArgList(Record *CurRec) {
3644 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
3645 Lex.Lex(); // eat the '<'
3646
3647 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
3648
3649 // Read the first declaration.
3650 const Init *TemplArg = ParseDeclaration(CurRec, true /*templateargs*/);
3651 if (!TemplArg)
3652 return true;
3653
3654 TheRecToAddTo->addTemplateArg(TemplArg);
3655
3656 while (consume(tgtok::comma)) {
3657 // Read the following declarations.
3658 SMLoc Loc = Lex.getLoc();
3659 TemplArg = ParseDeclaration(CurRec, true /*templateargs*/);
3660 if (!TemplArg)
3661 return true;
3662
3663 if (TheRecToAddTo->isTemplateArg(TemplArg))
3664 return Error(Loc, "template argument with the same name has already been "
3665 "defined");
3666
3667 TheRecToAddTo->addTemplateArg(TemplArg);
3668 }
3669
3670 if (!consume(tgtok::greater))
3671 return TokError("expected '>' at end of template argument list");
3672 return false;
3673}
3674
3675/// Parse an optional 'append'/'prepend' mode followed by a field name.
3676///
3677/// The current token must be an identifier. If the identifier is 'append' or
3678/// 'prepend' and is followed by another identifier, it is interpreted as a
3679/// mode keyword and the following identifier is parsed as the field name.
3680/// Otherwise the identifier itself is treated as the field name.
3681///
3682/// These keywords are contextual: a field may still be named 'append' or
3683/// 'prepend' (e.g. `let append = ...`). In that case the keyword is not
3684/// interpreted as a mode and the identifier is parsed as the field name.
3685LetModeAndName TGParser::ParseLetModeAndName() {
3686 assert(Lex.getCode() == tgtok::Id && "expected identifier");
3687
3688 SMLoc Loc = Lex.getLoc();
3689 // Copy the identifier before Lex.Lex() invalidates the lexer buffer.
3690 std::string CurStr = Lex.getCurStrVal();
3691
3692 LetMode Mode = llvm::StringSwitch<LetMode>(CurStr)
3693 .Case("append", LetMode::Append)
3694 .Case("prepend", LetMode::Prepend)
3695 .Default(LetMode::Replace);
3696
3697 // Consume the current identifier.
3698 Lex.Lex();
3699
3700 if (Mode != LetMode::Replace && Lex.getCode() == tgtok::Id) {
3701 // 'append'/'prepend' used as a contextual keyword.
3702 LetModeAndName Result = {Mode, Lex.getLoc(), Lex.getCurStrVal()};
3703 Lex.Lex(); // Consume the field name.
3704 return Result;
3705 }
3706
3707 // Otherwise the identifier itself is the field name (including the case
3708 // where the field is literally named 'append' or 'prepend').
3709 return {LetMode::Replace, Loc, std::move(CurStr)};
3710}
3711
3712/// ParseBodyItem - Parse a single item within the body of a def or class.
3713///
3714/// BodyItem ::= Declaration ';'
3715/// BodyItem ::= LET [append|prepend] ID OptionalRangeList '=' Value ';'
3716/// BodyItem ::= Defvar
3717/// BodyItem ::= Dump
3718/// BodyItem ::= Assert
3719///
3720bool TGParser::ParseBodyItem(Record *CurRec) {
3721 if (Lex.getCode() == tgtok::Assert)
3722 return ParseAssert(nullptr, CurRec);
3723
3724 if (Lex.getCode() == tgtok::Defvar)
3725 return ParseDefvar(CurRec);
3726
3727 if (Lex.getCode() == tgtok::Dump)
3728 return ParseDump(nullptr, CurRec);
3729
3730 if (Lex.getCode() != tgtok::Let) {
3731 if (!ParseDeclaration(CurRec, false))
3732 return true;
3733
3734 if (!consume(tgtok::semi))
3735 return TokError("expected ';' after declaration");
3736 return false;
3737 }
3738
3739 // LET [append|prepend] ID OptionalBitList '=' Value ';'
3740 Lex.Lex(); // eat 'let'.
3741
3742 if (Lex.getCode() != tgtok::Id)
3743 return TokError("expected field identifier after let");
3744
3745 auto [Mode, IdLoc, FieldNameStr] = ParseLetModeAndName();
3746 const StringInit *FieldName = StringInit::get(Records, FieldNameStr);
3747
3748 SmallVector<unsigned, 16> BitList;
3749 if (ParseOptionalRangeList(BitList))
3750 return true;
3751 std::reverse(BitList.begin(), BitList.end());
3752
3753 if (!consume(tgtok::equal))
3754 return TokError("expected '=' in let expression");
3755
3756 RecordVal *Field = CurRec->getValue(FieldName);
3757 if (!Field)
3758 return Error(IdLoc, "Value '" + FieldName->getValue() + "' unknown!");
3759
3760 const RecTy *Type = Field->getType();
3761 if (!BitList.empty() && isa<BitsRecTy>(Type)) {
3762 // When assigning to a subset of a 'bits' object, expect the RHS to have
3763 // the type of that subset instead of the type of the whole object.
3764 Type = BitsRecTy::get(Records, BitList.size());
3765 }
3766
3767 const Init *Val = ParseValue(CurRec, Type);
3768 if (!Val)
3769 return true;
3770
3771 if (!consume(tgtok::semi))
3772 return TokError("expected ';' after let expression");
3773
3774 return SetValue(CurRec, IdLoc, FieldName, BitList, Val,
3775 /*AllowSelfAssignment=*/false, /*OverrideDefLoc=*/true, Mode);
3776}
3777
3778/// ParseBody - Read the body of a class or def. Return true on error, false on
3779/// success.
3780///
3781/// Body ::= ';'
3782/// Body ::= '{' BodyList '}'
3783/// BodyList BodyItem*
3784///
3785bool TGParser::ParseBody(Record *CurRec) {
3786 // If this is a null definition, just eat the semi and return.
3787 if (consume(tgtok::semi))
3788 return false;
3789
3790 if (!consume(tgtok::l_brace))
3791 return TokError("Expected '{' to start body or ';' for declaration only");
3792
3793 while (Lex.getCode() != tgtok::r_brace)
3794 if (ParseBodyItem(CurRec))
3795 return true;
3796
3797 // Eat the '}'.
3798 Lex.Lex();
3799
3800 // If we have a semicolon, print a gentle error.
3801 SMLoc SemiLoc = Lex.getLoc();
3802 if (consume(tgtok::semi)) {
3803 PrintError(SemiLoc, "A class or def body should not end with a semicolon");
3804 PrintNote("Semicolon ignored; remove to eliminate this error");
3805 }
3806
3807 return false;
3808}
3809
3810/// Apply the current let bindings to \a CurRec.
3811/// \returns true on error, false otherwise.
3812bool TGParser::ApplyLetStack(Record *CurRec) {
3813 for (SmallVectorImpl<LetRecord> &LetInfo : LetStack)
3814 for (LetRecord &LR : LetInfo)
3815 if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value,
3816 /*AllowSelfAssignment=*/false, /*OverrideDefLoc=*/true,
3817 LR.Mode))
3818 return true;
3819 return false;
3820}
3821
3822/// Apply the current let bindings to the RecordsEntry.
3823bool TGParser::ApplyLetStack(RecordsEntry &Entry) {
3824 if (Entry.Rec)
3825 return ApplyLetStack(Entry.Rec.get());
3826
3827 // Let bindings are not applied to assertions.
3828 if (Entry.Assertion)
3829 return false;
3830
3831 // Let bindings are not applied to dumps.
3832 if (Entry.Dump)
3833 return false;
3834
3835 for (auto &E : Entry.Loop->Entries) {
3836 if (ApplyLetStack(E))
3837 return true;
3838 }
3839
3840 return false;
3841}
3842
3843/// ParseObjectBody - Parse the body of a def or class. This consists of an
3844/// optional ClassList followed by a Body. CurRec is the current def or class
3845/// that is being parsed.
3846///
3847/// ObjectBody ::= BaseClassList Body
3848/// BaseClassList ::= /*empty*/
3849/// BaseClassList ::= ':' BaseClassListNE
3850/// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
3851///
3852bool TGParser::ParseObjectBody(Record *CurRec) {
3853 // An object body introduces a new scope for local variables.
3854 TGVarScope *ObjectScope = PushScope(CurRec);
3855 // If there is a baseclass list, read it.
3856 if (consume(tgtok::colon)) {
3857
3858 // Read all of the subclasses.
3859 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
3860 while (true) {
3861 // Check for error.
3862 if (!SubClass.Rec)
3863 return true;
3864
3865 // Add it.
3866 if (AddSubClass(CurRec, SubClass))
3867 return true;
3868
3869 if (!consume(tgtok::comma))
3870 break;
3871 SubClass = ParseSubClassReference(CurRec, false);
3872 }
3873 }
3874
3875 if (ApplyLetStack(CurRec))
3876 return true;
3877
3878 bool Result = ParseBody(CurRec);
3879 PopScope(ObjectScope);
3880 return Result;
3881}
3882
3883/// ParseDef - Parse and return a top level or multiclass record definition.
3884/// Return false if okay, true if error.
3885///
3886/// DefInst ::= DEF ObjectName ObjectBody
3887///
3888bool TGParser::ParseDef(MultiClass *CurMultiClass) {
3889 SMLoc DefLoc = Lex.getLoc();
3890 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
3891 Lex.Lex(); // Eat the 'def' token.
3892
3893 // If the name of the def is an Id token, use that for the location.
3894 // Otherwise, the name is more complex and we use the location of the 'def'
3895 // token.
3896 SMLoc NameLoc = Lex.getCode() == tgtok::Id ? Lex.getLoc() : DefLoc;
3897
3898 // Parse ObjectName and make a record for it.
3899 std::unique_ptr<Record> CurRec;
3900 const Init *Name = ParseObjectName(CurMultiClass);
3901 if (!Name)
3902 return true;
3903
3904 if (isa<UnsetInit>(Name)) {
3905 CurRec = std::make_unique<Record>(Records.getNewAnonymousName(), DefLoc,
3906 Records, Record::RK_AnonymousDef);
3907 } else {
3908 CurRec = std::make_unique<Record>(Name, NameLoc, Records);
3909 }
3910
3911 if (ParseObjectBody(CurRec.get()))
3912 return true;
3913
3914 return addEntry(std::move(CurRec));
3915}
3916
3917/// ParseDefset - Parse a defset statement.
3918///
3919/// Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
3920///
3921bool TGParser::ParseDefset() {
3922 assert(Lex.getCode() == tgtok::Defset);
3923 Lex.Lex(); // Eat the 'defset' token
3924
3925 DefsetRecord Defset;
3926 Defset.Loc = Lex.getLoc();
3927 const RecTy *Type = ParseType();
3928 if (!Type)
3929 return true;
3930 if (!isa<ListRecTy>(Type))
3931 return Error(Defset.Loc, "expected list type");
3932 Defset.EltTy = cast<ListRecTy>(Type)->getElementType();
3933
3934 if (Lex.getCode() != tgtok::Id)
3935 return TokError("expected identifier");
3936 const StringInit *DeclName = StringInit::get(Records, Lex.getCurStrVal());
3937 if (Records.getGlobal(DeclName->getValue()))
3938 return TokError("def or global variable of this name already exists");
3939
3940 if (Lex.Lex() != tgtok::equal) // Eat the identifier
3941 return TokError("expected '='");
3942 if (Lex.Lex() != tgtok::l_brace) // Eat the '='
3943 return TokError("expected '{'");
3944 SMLoc BraceLoc = Lex.getLoc();
3945 Lex.Lex(); // Eat the '{'
3946
3947 Defsets.push_back(&Defset);
3948 bool Err = ParseObjectList(nullptr);
3949 Defsets.pop_back();
3950 if (Err)
3951 return true;
3952
3953 if (!consume(tgtok::r_brace)) {
3954 TokError("expected '}' at end of defset");
3955 return Error(BraceLoc, "to match this '{'");
3956 }
3957
3958 Records.addExtraGlobal(DeclName->getValue(),
3959 ListInit::get(Defset.Elements, Defset.EltTy));
3960 return false;
3961}
3962
3963/// ParseDeftype - Parse a defvar statement.
3964///
3965/// Deftype ::= DEFTYPE Id '=' Type ';'
3966///
3967bool TGParser::ParseDeftype() {
3968 assert(Lex.getCode() == tgtok::Deftype);
3969 Lex.Lex(); // Eat the 'deftype' token
3970
3971 if (Lex.getCode() != tgtok::Id)
3972 return TokError("expected identifier");
3973
3974 const std::string TypeName = Lex.getCurStrVal();
3975 if (TypeAliases.count(TypeName) || Records.getClass(TypeName))
3976 return TokError("type of this name '" + TypeName + "' already exists");
3977
3978 Lex.Lex();
3979 if (!consume(tgtok::equal))
3980 return TokError("expected '='");
3981
3982 SMLoc Loc = Lex.getLoc();
3983 const RecTy *Type = ParseType();
3984 if (!Type)
3985 return true;
3986
3987 if (Type->getRecTyKind() == RecTy::RecordRecTyKind)
3988 return Error(Loc, "cannot define type alias for class type '" +
3989 Type->getAsString() + "'");
3990
3991 TypeAliases[TypeName] = Type;
3992
3993 if (!consume(tgtok::semi))
3994 return TokError("expected ';'");
3995
3996 return false;
3997}
3998
3999/// ParseDefvar - Parse a defvar statement.
4000///
4001/// Defvar ::= DEFVAR Id '=' Value ';'
4002///
4003bool TGParser::ParseDefvar(Record *CurRec) {
4004 assert(Lex.getCode() == tgtok::Defvar);
4005 Lex.Lex(); // Eat the 'defvar' token
4006
4007 if (Lex.getCode() != tgtok::Id)
4008 return TokError("expected identifier");
4009 const StringInit *DeclName = StringInit::get(Records, Lex.getCurStrVal());
4010 if (CurScope->varAlreadyDefined(DeclName->getValue()))
4011 return TokError("local variable of this name already exists");
4012
4013 // The name should not be conflicted with existed field names.
4014 if (CurRec) {
4015 auto *V = CurRec->getValue(DeclName->getValue());
4016 if (V && !V->isTemplateArg())
4017 return TokError("field of this name already exists");
4018 }
4019
4020 // If this defvar is in the top level, the name should not be conflicted
4021 // with existed global names.
4022 if (CurScope->isOutermost() && Records.getGlobal(DeclName->getValue()))
4023 return TokError("def or global variable of this name already exists");
4024
4025 Lex.Lex();
4026 if (!consume(tgtok::equal))
4027 return TokError("expected '='");
4028
4029 const Init *Value = ParseValue(CurRec);
4030 if (!Value)
4031 return true;
4032
4033 if (!consume(tgtok::semi))
4034 return TokError("expected ';'");
4035
4036 if (!CurScope->isOutermost())
4037 CurScope->addVar(DeclName->getValue(), Value);
4038 else
4039 Records.addExtraGlobal(DeclName->getValue(), Value);
4040
4041 return false;
4042}
4043
4044/// ParseForeach - Parse a for statement. Return the record corresponding
4045/// to it. This returns true on error.
4046///
4047/// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
4048/// Foreach ::= FOREACH Declaration IN Object
4049///
4050bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
4051 SMLoc Loc = Lex.getLoc();
4052 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
4053 Lex.Lex(); // Eat the 'for' token.
4054
4055 // Make a temporary object to record items associated with the for
4056 // loop.
4057 const Init *ListValue = nullptr;
4058 const VarInit *IterName = ParseForeachDeclaration(ListValue);
4059 if (!IterName)
4060 return TokError("expected declaration in for");
4061
4062 if (!consume(tgtok::In))
4063 return TokError("Unknown tok");
4064
4065 // Create a loop object and remember it.
4066 auto TheLoop = std::make_unique<ForeachLoop>(Loc, IterName, ListValue);
4067 // A foreach loop introduces a new scope for local variables.
4068 TGVarScope *ForeachScope = PushScope(TheLoop.get());
4069 Loops.push_back(std::move(TheLoop));
4070
4071 if (Lex.getCode() != tgtok::l_brace) {
4072 // FOREACH Declaration IN Object
4073 if (ParseObject(CurMultiClass))
4074 return true;
4075 } else {
4076 SMLoc BraceLoc = Lex.getLoc();
4077 // Otherwise, this is a group foreach.
4078 Lex.Lex(); // eat the '{'.
4079
4080 // Parse the object list.
4081 if (ParseObjectList(CurMultiClass))
4082 return true;
4083
4084 if (!consume(tgtok::r_brace)) {
4085 TokError("expected '}' at end of foreach command");
4086 return Error(BraceLoc, "to match this '{'");
4087 }
4088 }
4089
4090 PopScope(ForeachScope);
4091
4092 // Resolve the loop or store it for later resolution.
4093 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
4094 Loops.pop_back();
4095
4096 return addEntry(std::move(Loop));
4097}
4098
4099/// ParseIf - Parse an if statement.
4100///
4101/// If ::= IF Value THEN IfBody
4102/// If ::= IF Value THEN IfBody ELSE IfBody
4103///
4104bool TGParser::ParseIf(MultiClass *CurMultiClass) {
4105 SMLoc Loc = Lex.getLoc();
4106 assert(Lex.getCode() == tgtok::If && "Unknown tok");
4107 Lex.Lex(); // Eat the 'if' token.
4108
4109 // Make a temporary object to record items associated with the for
4110 // loop.
4111 const Init *Condition = ParseValue(nullptr);
4112 if (!Condition)
4113 return true;
4114
4115 if (!consume(tgtok::Then))
4116 return TokError("Unknown tok");
4117
4118 // We have to be able to save if statements to execute later, and they have
4119 // to live on the same stack as foreach loops. The simplest implementation
4120 // technique is to convert each 'then' or 'else' clause *into* a foreach
4121 // loop, over a list of length 0 or 1 depending on the condition, and with no
4122 // iteration variable being assigned.
4123
4124 const ListInit *EmptyList = ListInit::get({}, BitRecTy::get(Records));
4125 const ListInit *SingletonList =
4126 ListInit::get({BitInit::get(Records, true)}, BitRecTy::get(Records));
4127 const RecTy *BitListTy = ListRecTy::get(BitRecTy::get(Records));
4128
4129 // The foreach containing the then-clause selects SingletonList if
4130 // the condition is true.
4131 const Init *ThenClauseList =
4132 TernOpInit::get(TernOpInit::IF, Condition, SingletonList, EmptyList,
4133 BitListTy)
4134 ->Fold(nullptr);
4135 Loops.push_back(std::make_unique<ForeachLoop>(Loc, nullptr, ThenClauseList));
4136
4137 if (ParseIfBody(CurMultiClass, "then"))
4138 return true;
4139
4140 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
4141 Loops.pop_back();
4142
4143 if (addEntry(std::move(Loop)))
4144 return true;
4145
4146 // Now look for an optional else clause. The if-else syntax has the usual
4147 // dangling-else ambiguity, and by greedily matching an else here if we can,
4148 // we implement the usual resolution of pairing with the innermost unmatched
4149 // if.
4150 if (consume(tgtok::ElseKW)) {
4151 // The foreach containing the else-clause uses the same pair of lists as
4152 // above, but this time, selects SingletonList if the condition is *false*.
4153 const Init *ElseClauseList =
4154 TernOpInit::get(TernOpInit::IF, Condition, EmptyList, SingletonList,
4155 BitListTy)
4156 ->Fold(nullptr);
4157 Loops.push_back(
4158 std::make_unique<ForeachLoop>(Loc, nullptr, ElseClauseList));
4159
4160 if (ParseIfBody(CurMultiClass, "else"))
4161 return true;
4162
4163 Loop = std::move(Loops.back());
4164 Loops.pop_back();
4165
4166 if (addEntry(std::move(Loop)))
4167 return true;
4168 }
4169
4170 return false;
4171}
4172
4173/// ParseIfBody - Parse the then-clause or else-clause of an if statement.
4174///
4175/// IfBody ::= Object
4176/// IfBody ::= '{' ObjectList '}'
4177///
4178bool TGParser::ParseIfBody(MultiClass *CurMultiClass, StringRef Kind) {
4179 // An if-statement introduces a new scope for local variables.
4180 TGVarScope *BodyScope = PushScope();
4181
4182 if (Lex.getCode() != tgtok::l_brace) {
4183 // A single object.
4184 if (ParseObject(CurMultiClass))
4185 return true;
4186 } else {
4187 SMLoc BraceLoc = Lex.getLoc();
4188 // A braced block.
4189 Lex.Lex(); // eat the '{'.
4190
4191 // Parse the object list.
4192 if (ParseObjectList(CurMultiClass))
4193 return true;
4194
4195 if (!consume(tgtok::r_brace)) {
4196 TokError("expected '}' at end of '" + Kind + "' clause");
4197 return Error(BraceLoc, "to match this '{'");
4198 }
4199 }
4200
4201 PopScope(BodyScope);
4202 return false;
4203}
4204
4205/// ParseAssert - Parse an assert statement.
4206///
4207/// Assert ::= ASSERT condition , message ;
4208bool TGParser::ParseAssert(MultiClass *CurMultiClass, Record *CurRec) {
4209 assert(Lex.getCode() == tgtok::Assert && "Unknown tok");
4210 Lex.Lex(); // Eat the 'assert' token.
4211
4212 SMLoc ConditionLoc = Lex.getLoc();
4213 const Init *Condition = ParseValue(CurRec);
4214 if (!Condition)
4215 return true;
4216
4217 if (!consume(tgtok::comma)) {
4218 TokError("expected ',' in assert statement");
4219 return true;
4220 }
4221
4222 const Init *Message = ParseValue(CurRec);
4223 if (!Message)
4224 return true;
4225
4226 if (!consume(tgtok::semi))
4227 return TokError("expected ';'");
4228
4229 if (CurRec)
4230 CurRec->addAssertion(ConditionLoc, Condition, Message);
4231 else
4232 addEntry(std::make_unique<Record::AssertionInfo>(ConditionLoc, Condition,
4233 Message));
4234 return false;
4235}
4236
4237/// ParseClass - Parse a tblgen class definition.
4238///
4239/// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
4240///
4241bool TGParser::ParseClass() {
4242 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
4243 Lex.Lex();
4244
4245 if (Lex.getCode() != tgtok::Id)
4246 return TokError("expected class name after 'class' keyword");
4247
4248 const std::string &Name = Lex.getCurStrVal();
4249 Record *CurRec = const_cast<Record *>(Records.getClass(Name));
4250 if (CurRec) {
4251 // If the body was previously defined, this is an error.
4252 if (!CurRec->getValues().empty() ||
4253 !CurRec->getDirectSuperClasses().empty() ||
4254 !CurRec->getTemplateArgs().empty())
4255 return TokError("Class '" + CurRec->getNameInitAsString() +
4256 "' already defined");
4257
4258 CurRec->updateClassLoc(Lex.getLoc());
4259 } else {
4260 // If this is the first reference to this class, create and add it.
4261 auto NewRec = std::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(),
4262 Records, Record::RK_Class);
4263 CurRec = NewRec.get();
4264 Records.addClass(std::move(NewRec));
4265 }
4266
4267 if (TypeAliases.count(Name))
4268 return TokError("there is already a defined type alias '" + Name + "'");
4269
4270 Lex.Lex(); // eat the name.
4271
4272 // A class definition introduces a new scope.
4273 TGVarScope *ClassScope = PushScope(CurRec);
4274 // If there are template args, parse them.
4275 if (Lex.getCode() == tgtok::less)
4276 if (ParseTemplateArgList(CurRec))
4277 return true;
4278
4279 if (ParseObjectBody(CurRec))
4280 return true;
4281
4282 if (!NoWarnOnUnusedTemplateArgs)
4283 CurRec->checkUnusedTemplateArgs();
4284
4285 PopScope(ClassScope);
4286 return false;
4287}
4288
4289/// ParseLetList - Parse a non-empty list of assignment expressions into a list
4290/// of LetRecords.
4291///
4292/// LetList ::= LetItem (',' LetItem)*
4293/// LetItem ::= [append|prepend] ID OptionalRangeList '=' Value
4294///
4295void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) {
4296 do {
4297 if (Lex.getCode() != tgtok::Id) {
4298 TokError("expected identifier in let definition");
4299 Result.clear();
4300 return;
4301 }
4302
4303 auto [Mode, NameLoc, NameStr] = ParseLetModeAndName();
4304 const StringInit *Name = StringInit::get(Records, NameStr);
4305
4306 // Check for an optional RangeList.
4307 SmallVector<unsigned, 16> Bits;
4308 if (ParseOptionalRangeList(Bits)) {
4309 Result.clear();
4310 return;
4311 }
4312 std::reverse(Bits.begin(), Bits.end());
4313
4314 if (!consume(tgtok::equal)) {
4315 TokError("expected '=' in let expression");
4316 Result.clear();
4317 return;
4318 }
4319
4320 const Init *Val = ParseValue(nullptr);
4321 if (!Val) {
4322 Result.clear();
4323 return;
4324 }
4325
4326 // Now that we have everything, add the record.
4327 Result.emplace_back(Name, Bits, Val, NameLoc, Mode);
4328 } while (consume(tgtok::comma));
4329}
4330
4331/// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
4332/// different related productions. This works inside multiclasses too.
4333///
4334/// Object ::= LET LetList IN '{' ObjectList '}'
4335/// Object ::= LET LetList IN Object
4336///
4337bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
4338 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
4339 Lex.Lex();
4340
4341 // Add this entry to the let stack.
4343 ParseLetList(LetInfo);
4344 if (LetInfo.empty())
4345 return true;
4346 LetStack.push_back(std::move(LetInfo));
4347
4348 if (!consume(tgtok::In))
4349 return TokError("expected 'in' at end of top-level 'let'");
4350
4351 // If this is a scalar let, just handle it now
4352 if (Lex.getCode() != tgtok::l_brace) {
4353 // LET LetList IN Object
4354 if (ParseObject(CurMultiClass))
4355 return true;
4356 } else { // Object ::= LETCommand '{' ObjectList '}'
4357 SMLoc BraceLoc = Lex.getLoc();
4358 // Otherwise, this is a group let.
4359 Lex.Lex(); // eat the '{'.
4360
4361 // A group let introduces a new scope for local variables.
4362 TGVarScope *LetScope = PushScope();
4363
4364 // Parse the object list.
4365 if (ParseObjectList(CurMultiClass))
4366 return true;
4367
4368 if (!consume(tgtok::r_brace)) {
4369 TokError("expected '}' at end of top level let command");
4370 return Error(BraceLoc, "to match this '{'");
4371 }
4372
4373 PopScope(LetScope);
4374 }
4375
4376 // Outside this let scope, this let block is not active.
4377 LetStack.pop_back();
4378 return false;
4379}
4380
4381/// ParseMultiClass - Parse a multiclass definition.
4382///
4383/// MultiClassInst ::= MULTICLASS ID TemplateArgList?
4384/// ':' BaseMultiClassList '{' MultiClassObject+ '}'
4385/// MultiClassObject ::= Assert
4386/// MultiClassObject ::= DefInst
4387/// MultiClassObject ::= DefMInst
4388/// MultiClassObject ::= Defvar
4389/// MultiClassObject ::= Foreach
4390/// MultiClassObject ::= If
4391/// MultiClassObject ::= LETCommand '{' ObjectList '}'
4392/// MultiClassObject ::= LETCommand Object
4393///
4394bool TGParser::ParseMultiClass() {
4395 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
4396 Lex.Lex(); // Eat the multiclass token.
4397
4398 if (Lex.getCode() != tgtok::Id)
4399 return TokError("expected identifier after multiclass for name");
4400 std::string Name = Lex.getCurStrVal();
4401
4402 auto Result = MultiClasses.try_emplace(
4403 Name, std::make_unique<MultiClass>(Name, Lex.getLoc(), Records));
4404
4405 if (!Result.second)
4406 return TokError("multiclass '" + Name + "' already defined");
4407
4408 CurMultiClass = Result.first->second.get();
4409 Lex.Lex(); // Eat the identifier.
4410
4411 // A multiclass body introduces a new scope for local variables.
4412 TGVarScope *MulticlassScope = PushScope(CurMultiClass);
4413
4414 // If there are template args, parse them.
4415 if (Lex.getCode() == tgtok::less)
4416 if (ParseTemplateArgList(nullptr))
4417 return true;
4418
4419 bool inherits = false;
4420
4421 // If there are submulticlasses, parse them.
4422 if (consume(tgtok::colon)) {
4423 inherits = true;
4424
4425 // Read all of the submulticlasses.
4426 SubMultiClassReference SubMultiClass =
4427 ParseSubMultiClassReference(CurMultiClass);
4428 while (true) {
4429 // Check for error.
4430 if (!SubMultiClass.MC)
4431 return true;
4432
4433 // Add it.
4434 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
4435 return true;
4436
4437 if (!consume(tgtok::comma))
4438 break;
4439 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
4440 }
4441 }
4442
4443 if (Lex.getCode() != tgtok::l_brace) {
4444 if (!inherits)
4445 return TokError("expected '{' in multiclass definition");
4446 if (!consume(tgtok::semi))
4447 return TokError("expected ';' in multiclass definition");
4448 } else {
4449 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
4450 return TokError("multiclass must contain at least one def");
4451
4452 while (Lex.getCode() != tgtok::r_brace) {
4453 switch (Lex.getCode()) {
4454 default:
4455 return TokError("expected 'assert', 'def', 'defm', 'defvar', 'dump', "
4456 "'foreach', 'if', or 'let' in multiclass body");
4457
4458 case tgtok::Assert:
4459 case tgtok::Def:
4460 case tgtok::Defm:
4461 case tgtok::Defvar:
4462 case tgtok::Dump:
4463 case tgtok::Foreach:
4464 case tgtok::If:
4465 case tgtok::Let:
4466 if (ParseObject(CurMultiClass))
4467 return true;
4468 break;
4469 }
4470 }
4471 Lex.Lex(); // eat the '}'.
4472
4473 // If we have a semicolon, print a gentle error.
4474 SMLoc SemiLoc = Lex.getLoc();
4475 if (consume(tgtok::semi)) {
4476 PrintError(SemiLoc, "A multiclass body should not end with a semicolon");
4477 PrintNote("Semicolon ignored; remove to eliminate this error");
4478 }
4479 }
4480
4481 if (!NoWarnOnUnusedTemplateArgs)
4482 CurMultiClass->Rec.checkUnusedTemplateArgs();
4483
4484 PopScope(MulticlassScope);
4485 CurMultiClass = nullptr;
4486 return false;
4487}
4488
4489/// ParseDefm - Parse the instantiation of a multiclass.
4490///
4491/// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
4492///
4493bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
4494 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
4495 Lex.Lex(); // eat the defm
4496
4497 const Init *DefmName = ParseObjectName(CurMultiClass);
4498 if (!DefmName)
4499 return true;
4500 if (isa<UnsetInit>(DefmName)) {
4501 DefmName = Records.getNewAnonymousName();
4502 if (CurMultiClass)
4503 DefmName = BinOpInit::getStrConcat(
4505 StringRecTy::get(Records)),
4506 DefmName);
4507 }
4508
4509 if (Lex.getCode() != tgtok::colon)
4510 return TokError("expected ':' after defm identifier");
4511
4512 // Keep track of the new generated record definitions.
4513 std::vector<RecordsEntry> NewEntries;
4514
4515 // This record also inherits from a regular class (non-multiclass)?
4516 bool InheritFromClass = false;
4517
4518 // eat the colon.
4519 Lex.Lex();
4520
4521 SMLoc SubClassLoc = Lex.getLoc();
4522 SubClassReference Ref = ParseSubClassReference(nullptr, true);
4523
4524 while (true) {
4525 if (!Ref.Rec)
4526 return true;
4527
4528 // To instantiate a multiclass, we get the multiclass and then loop
4529 // through its template argument names. Substs contains a substitution
4530 // value for each argument, either the value specified or the default.
4531 // Then we can resolve the template arguments.
4532 MultiClass *MC = MultiClasses[Ref.Rec->getName().str()].get();
4533 assert(MC && "Didn't lookup multiclass correctly?");
4534
4535 SubstStack Substs;
4536 if (resolveArgumentsOfMultiClass(Substs, MC, Ref.TemplateArgs, DefmName,
4537 SubClassLoc))
4538 return true;
4539
4540 if (resolve(MC->Entries, Substs, !CurMultiClass && Loops.empty(),
4541 &NewEntries, &SubClassLoc))
4542 return true;
4543
4544 if (!consume(tgtok::comma))
4545 break;
4546
4547 if (Lex.getCode() != tgtok::Id)
4548 return TokError("expected identifier");
4549
4550 SubClassLoc = Lex.getLoc();
4551
4552 // A defm can inherit from regular classes (non-multiclasses) as
4553 // long as they come in the end of the inheritance list.
4554 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
4555
4556 if (InheritFromClass)
4557 break;
4558
4559 Ref = ParseSubClassReference(nullptr, true);
4560 }
4561
4562 if (InheritFromClass) {
4563 // Process all the classes to inherit as if they were part of a
4564 // regular 'def' and inherit all record values.
4565 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
4566 while (true) {
4567 // Check for error.
4568 if (!SubClass.Rec)
4569 return true;
4570
4571 // Get the expanded definition prototypes and teach them about
4572 // the record values the current class to inherit has
4573 for (auto &E : NewEntries) {
4574 // Add it.
4575 if (AddSubClass(E, SubClass))
4576 return true;
4577 }
4578
4579 if (!consume(tgtok::comma))
4580 break;
4581 SubClass = ParseSubClassReference(nullptr, false);
4582 }
4583 }
4584
4585 for (auto &E : NewEntries) {
4586 if (ApplyLetStack(E))
4587 return true;
4588
4589 addEntry(std::move(E));
4590 }
4591
4592 if (!consume(tgtok::semi))
4593 return TokError("expected ';' at end of defm");
4594
4595 return false;
4596}
4597
4598/// ParseObject
4599/// Object ::= ClassInst
4600/// Object ::= DefInst
4601/// Object ::= MultiClassInst
4602/// Object ::= DefMInst
4603/// Object ::= LETCommand '{' ObjectList '}'
4604/// Object ::= LETCommand Object
4605/// Object ::= Defset
4606/// Object ::= Deftype
4607/// Object ::= Defvar
4608/// Object ::= Assert
4609/// Object ::= Dump
4610bool TGParser::ParseObject(MultiClass *MC) {
4611 switch (Lex.getCode()) {
4612 default:
4613 return TokError(
4614 "Expected assert, class, def, defm, defset, dump, foreach, if, or let");
4615 case tgtok::Assert:
4616 return ParseAssert(MC);
4617 case tgtok::Def:
4618 return ParseDef(MC);
4619 case tgtok::Defm:
4620 return ParseDefm(MC);
4621 case tgtok::Deftype:
4622 return ParseDeftype();
4623 case tgtok::Defvar:
4624 return ParseDefvar();
4625 case tgtok::Dump:
4626 return ParseDump(MC);
4627 case tgtok::Foreach:
4628 return ParseForeach(MC);
4629 case tgtok::If:
4630 return ParseIf(MC);
4631 case tgtok::Let:
4632 return ParseTopLevelLet(MC);
4633 case tgtok::Defset:
4634 if (MC)
4635 return TokError("defset is not allowed inside multiclass");
4636 return ParseDefset();
4637 case tgtok::Class:
4638 if (MC)
4639 return TokError("class is not allowed inside multiclass");
4640 if (!Loops.empty())
4641 return TokError("class is not allowed inside foreach loop");
4642 return ParseClass();
4643 case tgtok::MultiClass:
4644 if (!Loops.empty())
4645 return TokError("multiclass is not allowed inside foreach loop");
4646 return ParseMultiClass();
4647 }
4648}
4649
4650/// ParseObjectList
4651/// ObjectList :== Object*
4652bool TGParser::ParseObjectList(MultiClass *MC) {
4653 while (tgtok::isObjectStart(Lex.getCode())) {
4654 if (ParseObject(MC))
4655 return true;
4656 }
4657 return false;
4658}
4659
4661 Lex.Lex(); // Prime the lexer.
4662 TGVarScope *GlobalScope = PushScope();
4663 if (ParseObjectList())
4664 return true;
4665 PopScope(GlobalScope);
4666
4667 // If we have unread input at the end of the file, report it.
4668 if (Lex.getCode() == tgtok::Eof)
4669 return false;
4670
4671 return TokError("Unexpected token at top level");
4672}
4673
4674// Check the types of the template argument values for a class
4675// inheritance, multiclass invocation, or anonymous class invocation.
4676// If necessary, replace an argument with a cast to the required type.
4677// The argument count has already been checked.
4678bool TGParser::CheckTemplateArgValues(
4680 const Record *ArgsRec) {
4681 assert(Values.size() == ValuesLocs.size() &&
4682 "expected as many values as locations");
4683
4684 ArrayRef<const Init *> TArgs = ArgsRec->getTemplateArgs();
4685
4686 bool HasError = false;
4687 for (auto [Value, Loc] : llvm::zip_equal(Values, ValuesLocs)) {
4688 const Init *ArgName = nullptr;
4689 if (Value->isPositional())
4690 ArgName = TArgs[Value->getIndex()];
4691 if (Value->isNamed())
4692 ArgName = Value->getName();
4693
4694 const RecordVal *Arg = ArgsRec->getValue(ArgName);
4695 const RecTy *ArgType = Arg->getType();
4696
4697 if (const auto *ArgValue = dyn_cast<TypedInit>(Value->getValue())) {
4698 auto *CastValue = ArgValue->getCastTo(ArgType);
4699 if (CastValue) {
4700 assert((!isa<TypedInit>(CastValue) ||
4701 cast<TypedInit>(CastValue)->getType()->typeIsA(ArgType)) &&
4702 "result of template arg value cast has wrong type");
4703 Value = Value->cloneWithValue(CastValue);
4704 } else {
4705 HasError |= Error(
4706 Loc, "Value specified for template argument '" +
4707 Arg->getNameInitAsString() + "' is of type " +
4708 ArgValue->getType()->getAsString() + "; expected type " +
4709 ArgType->getAsString() + ": " + ArgValue->getAsString());
4710 }
4711 }
4712 }
4713
4714 return HasError;
4715}
4716
4717#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4719 if (Loop)
4720 Loop->dump();
4721 if (Rec)
4722 Rec->dump();
4723}
4724
4726 errs() << "foreach " << IterVar->getAsString() << " = "
4727 << ListValue->getAsString() << " in {\n";
4728
4729 for (const auto &E : Entries)
4730 E.dump();
4731
4732 errs() << "}\n";
4733}
4734
4736 errs() << "Record:\n";
4737 Rec.dump();
4738
4739 errs() << "Defs:\n";
4740 for (const auto &E : Entries)
4741 E.dump();
4742}
4743#endif
4744
4745bool TGParser::ParseDump(MultiClass *CurMultiClass, Record *CurRec) {
4746 // Location of the `dump` statement.
4747 SMLoc Loc = Lex.getLoc();
4748 assert(Lex.getCode() == tgtok::Dump && "Unknown tok");
4749 Lex.Lex(); // eat the operation
4750
4751 const Init *Message = ParseValue(CurRec);
4752 if (!Message)
4753 return true;
4754
4755 // Allow to use dump directly on `defvar` and `def`, by wrapping
4756 // them with a `!repl`.
4757 if (isa<DefInit>(Message))
4758 Message = UnOpInit::get(UnOpInit::REPR, Message, StringRecTy::get(Records))
4759 ->Fold(CurRec);
4760
4761 if (!consume(tgtok::semi))
4762 return TokError("expected ';'");
4763
4764 if (CurRec)
4765 CurRec->addDump(Loc, Message);
4766 else {
4767 HasReferenceResolver resolver{nullptr};
4768 resolver.setFinal(true);
4769 // force a resolution with a dummy resolver
4770 const Init *ResolvedMessage = Message->resolveReferences(resolver);
4771 addEntry(std::make_unique<Record::DumpInfo>(Loc, ResolvedMessage));
4772 }
4773
4774 return false;
4775}
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
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
static const BinOpInit * get(BinaryOp opc, const Init *lhs, const Init *rhs, const RecTy *Type)
Definition Record.cpp:1096
static const Init * getStrConcat(const Init *lhs, const Init *rhs)
Definition Record.cpp:1167
static const Init * getListConcat(const TypedInit *lhs, const Init *rhs)
Definition Record.cpp:1184
const Init * Fold(const Record *CurRec) const
Definition Record.cpp:1304
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:2751
static const CondOpInit * get(ArrayRef< const Init * > Conds, ArrayRef< const Init * > Values, const RecTy *Type)
Definition Record.cpp:2708
static const DagInit * get(const Init *V, const StringInit *VN, ArrayRef< const Init * > Args, ArrayRef< const StringInit * > ArgNames)
Definition Record.cpp:2820
static const DagRecTy * get(RecordKeeper &RK)
Definition Record.cpp:222
static const ExistsOpInit * get(const RecTy *CheckType, const Init *Expr)
Definition Record.cpp:2251
const Init * Fold(const Record *CurRec) const
Definition Record.cpp:2659
static const FieldInit * get(const Init *R, const StringInit *FN)
Definition Record.cpp:2638
const Init * Fold(const Record *CurRec) const
Definition Record.cpp:2139
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:2119
Do not resolve anything, but keep track of whether a given variable was referenced.
Definition Record.h:2308
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:2346
static const InstancesOpInit * get(const RecTy *Type, const Init *Regex)
Definition Record.cpp:2326
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:2187
const Init * Fold() const
Definition Record.cpp:2206
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:2230
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:1544
std::string getNameInitAsString() const
Get the name of the field as a std::string.
Definition Record.h:1578
void setUsed(bool Used)
Whether this value is used.
Definition Record.h:1618
bool setValue(const Init *V)
Set the value of the field from an Init.
Definition Record.cpp:2949
const Init * getValue() const
Get the value of the field as an Init.
Definition Record.h:1602
StringRef getName() const
Get the name of the field as a StringRef.
Definition Record.cpp:2930
void addReferenceLoc(SMRange Loc)
Add a reference to this record value.
Definition Record.h:1611
const Init * getNameInit() const
Get the name of the field as an Init.
Definition Record.h:1575
const RecTy * getType() const
Get the type of the field value as a RecTy.
Definition Record.h:1596
const RecordRecTy * getType() const
Definition Record.cpp:3011
@ RK_AnonymousDef
Definition Record.h:1654
void addDump(SMLoc Loc, const Init *Message)
Definition Record.h:1833
void checkUnusedTemplateArgs()
Definition Record.cpp:3329
std::string getNameInitAsString() const
Definition Record.h:1717
RecordKeeper & getRecords() const
Definition Record.h:1890
const RecordVal * getValue(const Init *Name) const
Definition Record.h:1787
void addTemplateArg(const Init *Name)
Definition Record.h:1807
bool isMultiClass() const
Definition Record.h:1747
void addValue(const RecordVal &RV)
Definition Record.h:1812
void addAssertion(SMLoc Loc, const Init *Condition, const Init *Message)
Definition Record.h:1829
bool isClass() const
Definition Record.h:1745
ArrayRef< std::pair< const Record *, SMRange > > getDirectSuperClasses() const
Return the direct superclasses of this record.
Definition Record.h:1779
StringRef getName() const
Definition Record.h:1713
bool isTemplateArg(const Init *Name) const
Definition Record.h:1783
void appendDumps(const Record *Rec)
Definition Record.h:1841
bool isSubClassOf(const Record *R) const
Definition Record.h:1847
ArrayRef< RecordVal > getValues() const
Definition Record.h:1753
SMLoc getFieldLoc(StringRef FieldName) const
Return the source location for the named field.
Definition Record.cpp:3135
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:3089
ArrayRef< const Init * > getTemplateArgs() const
Definition Record.h:1751
void updateClassLoc(SMLoc Loc)
Definition Record.cpp:2995
void addDirectSuperClass(const Record *R, SMRange Range)
Definition Record.h:1869
void appendAssertions(const Record *Rec)
Definition Record.h:1837
const Init * getNameInit() const
Definition Record.h:1715
void setFinal(bool Final)
Definition Record.h:2226
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
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
tgtok::TokKind Lex()
Definition TGLexer.h:219
tgtok::TokKind getCode() const
Definition TGLexer.h:223
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:1842
static const TernOpInit * get(TernaryOp opc, const Init *lhs, const Init *mhs, const Init *rhs, const RecTy *Type)
Definition Record.cpp:1690
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:825
const Init * Fold(const Record *CurRec, bool IsFinal=false) const
Definition Record.cpp:843
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:255
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
static const VarDefInit * get(SMLoc Loc, const Record *Class, ArrayRef< const ArgumentInit * > Args)
Definition Record.cpp:2519
const Init * Fold() const
Definition Record.cpp:2615
'Opcode' - Represent a reference to an entire variable object.
Definition Record.h:1223
static const VarInit * get(StringRef VN, const RecTy *T)
Definition Record.cpp:2435
const Init * getNameInit() const
Definition Record.h:1241
#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:177
@ 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:182
This is an optimization pass for GlobalISel generic memory operations.
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:840
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:2199
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:1916
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:1946
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 value is 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:874
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