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