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