LLVM  9.0.0svn
TGParser.cpp
Go to the documentation of this file.
1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Implement the Parser for TableGen.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TGParser.h"
14 #include "llvm/ADT/None.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Config/llvm-config.h"
19 #include "llvm/Support/Casting.h"
20 #include "llvm/Support/Compiler.h"
23 #include "llvm/TableGen/Record.h"
24 #include <algorithm>
25 #include <cassert>
26 #include <cstdint>
27 
28 using namespace llvm;
29 
30 //===----------------------------------------------------------------------===//
31 // Support Code for the Semantic Actions.
32 //===----------------------------------------------------------------------===//
33 
34 namespace llvm {
35 
40 
41  SubClassReference() : Rec(nullptr) {}
42 
43  bool isInvalid() const { return Rec == nullptr; }
44 };
45 
50 
51  SubMultiClassReference() : MC(nullptr) {}
52 
53  bool isInvalid() const { return MC == nullptr; }
54  void dump() const;
55 };
56 
57 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
59  errs() << "Multiclass:\n";
60 
61  MC->dump();
62 
63  errs() << "Template args:\n";
64  for (Init *TA : TemplateArgs)
65  TA->dump();
66 }
67 #endif
68 
69 } // end namespace llvm
70 
71 static bool checkBitsConcrete(Record &R, const RecordVal &RV) {
72  BitsInit *BV = cast<BitsInit>(RV.getValue());
73  for (unsigned i = 0, e = BV->getNumBits(); i != e; ++i) {
74  Init *Bit = BV->getBit(i);
75  bool IsReference = false;
76  if (auto VBI = dyn_cast<VarBitInit>(Bit)) {
77  if (auto VI = dyn_cast<VarInit>(VBI->getBitVar())) {
78  if (R.getValue(VI->getName()))
79  IsReference = true;
80  }
81  } else if (isa<VarInit>(Bit)) {
82  IsReference = true;
83  }
84  if (!(IsReference || Bit->isConcrete()))
85  return false;
86  }
87  return true;
88 }
89 
90 static void checkConcrete(Record &R) {
91  for (const RecordVal &RV : R.getValues()) {
92  // HACK: Disable this check for variables declared with 'field'. This is
93  // done merely because existing targets have legitimate cases of
94  // non-concrete variables in helper defs. Ideally, we'd introduce a
95  // 'maybe' or 'optional' modifier instead of this.
96  if (RV.getPrefix())
97  continue;
98 
99  if (Init *V = RV.getValue()) {
100  bool Ok = isa<BitsInit>(V) ? checkBitsConcrete(R, RV) : V->isConcrete();
101  if (!Ok) {
102  PrintError(R.getLoc(),
103  Twine("Initializer of '") + RV.getNameInitAsString() +
104  "' in '" + R.getNameInitAsString() +
105  "' could not be fully resolved: " +
106  RV.getValue()->getAsString());
107  }
108  }
109  }
110 }
111 
112 /// Return an Init with a qualifier prefix referring
113 /// to CurRec's name.
114 static Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass,
115  Init *Name, StringRef Scoper) {
116  Init *NewName =
118  NewName = BinOpInit::getStrConcat(NewName, Name);
119  if (CurMultiClass && Scoper != "::") {
120  Init *Prefix = BinOpInit::getStrConcat(CurMultiClass->Rec.getNameInit(),
121  StringInit::get("::"));
122  NewName = BinOpInit::getStrConcat(Prefix, NewName);
123  }
124 
125  if (BinOpInit *BinOp = dyn_cast<BinOpInit>(NewName))
126  NewName = BinOp->Fold(&CurRec);
127  return NewName;
128 }
129 
130 /// Return the qualified version of the implicit 'NAME' template argument.
132  MultiClass *MC = nullptr) {
133  return QualifyName(Rec, MC, StringInit::get("NAME"), MC ? "::" : ":");
134 }
135 
137  return QualifiedNameOfImplicitName(MC->Rec, MC);
138 }
139 
140 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
141  if (!CurRec)
142  CurRec = &CurMultiClass->Rec;
143 
144  if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
145  // The value already exists in the class, treat this as a set.
146  if (ERV->setValue(RV.getValue()))
147  return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
148  RV.getType()->getAsString() + "' is incompatible with " +
149  "previous definition of type '" +
150  ERV->getType()->getAsString() + "'");
151  } else {
152  CurRec->addValue(RV);
153  }
154  return false;
155 }
156 
157 /// SetValue -
158 /// Return true on error, false on success.
159 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
160  ArrayRef<unsigned> BitList, Init *V,
161  bool AllowSelfAssignment) {
162  if (!V) return false;
163 
164  if (!CurRec) CurRec = &CurMultiClass->Rec;
165 
166  RecordVal *RV = CurRec->getValue(ValName);
167  if (!RV)
168  return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
169  "' unknown!");
170 
171  // Do not allow assignments like 'X = X'. This will just cause infinite loops
172  // in the resolution machinery.
173  if (BitList.empty())
174  if (VarInit *VI = dyn_cast<VarInit>(V))
175  if (VI->getNameInit() == ValName && !AllowSelfAssignment)
176  return Error(Loc, "Recursion / self-assignment forbidden");
177 
178  // If we are assigning to a subset of the bits in the value... then we must be
179  // assigning to a field of BitsRecTy, which must have a BitsInit
180  // initializer.
181  //
182  if (!BitList.empty()) {
183  BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
184  if (!CurVal)
185  return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
186  "' is not a bits type");
187 
188  // Convert the incoming value to a bits type of the appropriate size...
189  Init *BI = V->getCastTo(BitsRecTy::get(BitList.size()));
190  if (!BI)
191  return Error(Loc, "Initializer is not compatible with bit range");
192 
193  SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
194 
195  // Loop over bits, assigning values as appropriate.
196  for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
197  unsigned Bit = BitList[i];
198  if (NewBits[Bit])
199  return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" +
200  ValName->getAsUnquotedString() + "' more than once");
201  NewBits[Bit] = BI->getBit(i);
202  }
203 
204  for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
205  if (!NewBits[i])
206  NewBits[i] = CurVal->getBit(i);
207 
208  V = BitsInit::get(NewBits);
209  }
210 
211  if (RV->setValue(V)) {
212  std::string InitType;
213  if (BitsInit *BI = dyn_cast<BitsInit>(V))
214  InitType = (Twine("' of type bit initializer with length ") +
215  Twine(BI->getNumBits())).str();
216  else if (TypedInit *TI = dyn_cast<TypedInit>(V))
217  InitType = (Twine("' of type '") + TI->getType()->getAsString()).str();
218  return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
219  "' of type '" + RV->getType()->getAsString() +
220  "' is incompatible with initializer '" +
221  V->getAsString() + InitType + "'");
222  }
223  return false;
224 }
225 
226 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
227 /// args as SubClass's template arguments.
228 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
229  Record *SC = SubClass.Rec;
230  // Add all of the values in the subclass into the current class.
231  for (const RecordVal &Val : SC->getValues())
232  if (AddValue(CurRec, SubClass.RefRange.Start, Val))
233  return true;
234 
235  ArrayRef<Init *> TArgs = SC->getTemplateArgs();
236 
237  // Ensure that an appropriate number of template arguments are specified.
238  if (TArgs.size() < SubClass.TemplateArgs.size())
239  return Error(SubClass.RefRange.Start,
240  "More template args specified than expected");
241 
242  // Loop over all of the template arguments, setting them to the specified
243  // value or leaving them as the default if necessary.
244  MapResolver R(CurRec);
245 
246  for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
247  if (i < SubClass.TemplateArgs.size()) {
248  // If a value is specified for this template arg, set it now.
249  if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
250  None, SubClass.TemplateArgs[i]))
251  return true;
252  } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
253  return Error(SubClass.RefRange.Start,
254  "Value not specified for template argument #" +
255  Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
256  ") of subclass '" + SC->getNameInitAsString() + "'!");
257  }
258 
259  R.set(TArgs[i], CurRec->getValue(TArgs[i])->getValue());
260 
261  CurRec->removeValue(TArgs[i]);
262  }
263 
264  Init *Name;
265  if (CurRec->isClass())
266  Name =
268  else
269  Name = CurRec->getNameInit();
270  R.set(QualifiedNameOfImplicitName(*SC), Name);
271 
272  CurRec->resolveReferences(R);
273 
274  // Since everything went well, we can now set the "superclass" list for the
275  // current record.
277  for (const auto &SCPair : SCs) {
278  if (CurRec->isSubClassOf(SCPair.first))
279  return Error(SubClass.RefRange.Start,
280  "Already subclass of '" + SCPair.first->getName() + "'!\n");
281  CurRec->addSuperClass(SCPair.first, SCPair.second);
282  }
283 
284  if (CurRec->isSubClassOf(SC))
285  return Error(SubClass.RefRange.Start,
286  "Already subclass of '" + SC->getName() + "'!\n");
287  CurRec->addSuperClass(SC, SubClass.RefRange);
288  return false;
289 }
290 
291 bool TGParser::AddSubClass(RecordsEntry &Entry, SubClassReference &SubClass) {
292  if (Entry.Rec)
293  return AddSubClass(Entry.Rec.get(), SubClass);
294 
295  for (auto &E : Entry.Loop->Entries) {
296  if (AddSubClass(E, SubClass))
297  return true;
298  }
299 
300  return false;
301 }
302 
303 /// AddSubMultiClass - Add SubMultiClass as a subclass to
304 /// CurMC, resolving its template args as SubMultiClass's
305 /// template arguments.
306 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
307  SubMultiClassReference &SubMultiClass) {
308  MultiClass *SMC = SubMultiClass.MC;
309 
310  ArrayRef<Init *> SMCTArgs = SMC->Rec.getTemplateArgs();
311  if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
312  return Error(SubMultiClass.RefRange.Start,
313  "More template args specified than expected");
314 
315  // Prepare the mapping of template argument name to value, filling in default
316  // values if necessary.
317  SubstStack TemplateArgs;
318  for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
319  if (i < SubMultiClass.TemplateArgs.size()) {
320  TemplateArgs.emplace_back(SMCTArgs[i], SubMultiClass.TemplateArgs[i]);
321  } else {
322  Init *Default = SMC->Rec.getValue(SMCTArgs[i])->getValue();
323  if (!Default->isComplete()) {
324  return Error(SubMultiClass.RefRange.Start,
325  "value not specified for template argument #" + Twine(i) +
326  " (" + SMCTArgs[i]->getAsUnquotedString() +
327  ") of multiclass '" + SMC->Rec.getNameInitAsString() +
328  "'");
329  }
330  TemplateArgs.emplace_back(SMCTArgs[i], Default);
331  }
332  }
333 
334  TemplateArgs.emplace_back(
337 
338  // Add all of the defs in the subclass into the current multiclass.
339  return resolve(SMC->Entries, TemplateArgs, false, &CurMC->Entries);
340 }
341 
342 /// Add a record or foreach loop to the current context (global record keeper,
343 /// current inner-most foreach loop, or multiclass).
344 bool TGParser::addEntry(RecordsEntry E) {
345  assert(!E.Rec || !E.Loop);
346 
347  if (!Loops.empty()) {
348  Loops.back()->Entries.push_back(std::move(E));
349  return false;
350  }
351 
352  if (E.Loop) {
353  SubstStack Stack;
354  return resolve(*E.Loop, Stack, CurMultiClass == nullptr,
355  CurMultiClass ? &CurMultiClass->Entries : nullptr);
356  }
357 
358  if (CurMultiClass) {
359  CurMultiClass->Entries.push_back(std::move(E));
360  return false;
361  }
362 
363  return addDefOne(std::move(E.Rec));
364 }
365 
366 /// Resolve the entries in \p Loop, going over inner loops recursively
367 /// and making the given subsitutions of (name, value) pairs.
368 ///
369 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
370 /// are added to the global record keeper.
371 bool TGParser::resolve(const ForeachLoop &Loop, SubstStack &Substs,
372  bool Final, std::vector<RecordsEntry> *Dest,
373  SMLoc *Loc) {
374  MapResolver R;
375  for (const auto &S : Substs)
376  R.set(S.first, S.second);
377  Init *List = Loop.ListValue->resolveReferences(R);
378  auto LI = dyn_cast<ListInit>(List);
379  if (!LI) {
380  if (!Final) {
381  Dest->emplace_back(make_unique<ForeachLoop>(Loop.Loc, Loop.IterVar,
382  List));
383  return resolve(Loop.Entries, Substs, Final, &Dest->back().Loop->Entries,
384  Loc);
385  }
386 
387  PrintError(Loop.Loc, Twine("attempting to loop over '") +
388  List->getAsString() + "', expected a list");
389  return true;
390  }
391 
392  bool Error = false;
393  for (auto Elt : *LI) {
394  Substs.emplace_back(Loop.IterVar->getNameInit(), Elt);
395  Error = resolve(Loop.Entries, Substs, Final, Dest);
396  Substs.pop_back();
397  if (Error)
398  break;
399  }
400  return Error;
401 }
402 
403 /// Resolve the entries in \p Source, going over loops recursively and
404 /// making the given substitutions of (name, value) pairs.
405 ///
406 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
407 /// are added to the global record keeper.
408 bool TGParser::resolve(const std::vector<RecordsEntry> &Source,
409  SubstStack &Substs, bool Final,
410  std::vector<RecordsEntry> *Dest, SMLoc *Loc) {
411  bool Error = false;
412  for (auto &E : Source) {
413  if (E.Loop) {
414  Error = resolve(*E.Loop, Substs, Final, Dest);
415  } else {
416  auto Rec = make_unique<Record>(*E.Rec);
417  if (Loc)
418  Rec->appendLoc(*Loc);
419 
420  MapResolver R(Rec.get());
421  for (const auto &S : Substs)
422  R.set(S.first, S.second);
424 
425  if (Dest)
426  Dest->push_back(std::move(Rec));
427  else
428  Error = addDefOne(std::move(Rec));
429  }
430  if (Error)
431  break;
432  }
433  return Error;
434 }
435 
436 /// Resolve the record fully and add it to the record keeper.
437 bool TGParser::addDefOne(std::unique_ptr<Record> Rec) {
438  if (Record *Prev = Records.getDef(Rec->getNameInitAsString())) {
439  if (!Rec->isAnonymous()) {
440  PrintError(Rec->getLoc(),
441  "def already exists: " + Rec->getNameInitAsString());
442  PrintNote(Prev->getLoc(), "location of previous definition");
443  return true;
444  }
445  Rec->setName(Records.getNewAnonymousName());
446  }
447 
448  Rec->resolveReferences();
449  checkConcrete(*Rec);
450 
451  if (!isa<StringInit>(Rec->getNameInit())) {
452  PrintError(Rec->getLoc(), Twine("record name '") +
453  Rec->getNameInit()->getAsString() +
454  "' could not be fully resolved");
455  return true;
456  }
457 
458  // If ObjectBody has template arguments, it's an error.
459  assert(Rec->getTemplateArgs().empty() && "How'd this get template args?");
460 
461  for (DefsetRecord *Defset : Defsets) {
462  DefInit *I = Rec->getDefInit();
463  if (!I->getType()->typeIsA(Defset->EltTy)) {
464  PrintError(Rec->getLoc(), Twine("adding record of incompatible type '") +
465  I->getType()->getAsString() +
466  "' to defset");
467  PrintNote(Defset->Loc, "location of defset declaration");
468  return true;
469  }
470  Defset->Elements.push_back(I);
471  }
472 
473  Records.addDef(std::move(Rec));
474  return false;
475 }
476 
477 //===----------------------------------------------------------------------===//
478 // Parser Code
479 //===----------------------------------------------------------------------===//
480 
481 /// isObjectStart - Return true if this is a valid first token for an Object.
483  return K == tgtok::Class || K == tgtok::Def || K == tgtok::Defm ||
484  K == tgtok::Let || K == tgtok::MultiClass || K == tgtok::Foreach ||
485  K == tgtok::Defset;
486 }
487 
488 /// ParseObjectName - If a valid object name is specified, return it. If no
489 /// name is specified, return the unset initializer. Return nullptr on parse
490 /// error.
491 /// ObjectName ::= Value [ '#' Value ]*
492 /// ObjectName ::= /*empty*/
493 ///
494 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
495  switch (Lex.getCode()) {
496  case tgtok::colon:
497  case tgtok::semi:
498  case tgtok::l_brace:
499  // These are all of the tokens that can begin an object body.
500  // Some of these can also begin values but we disallow those cases
501  // because they are unlikely to be useful.
502  return UnsetInit::get();
503  default:
504  break;
505  }
506 
507  Record *CurRec = nullptr;
508  if (CurMultiClass)
509  CurRec = &CurMultiClass->Rec;
510 
511  Init *Name = ParseValue(CurRec, StringRecTy::get(), ParseNameMode);
512  if (!Name)
513  return nullptr;
514 
515  if (CurMultiClass) {
516  Init *NameStr = QualifiedNameOfImplicitName(CurMultiClass);
517  HasReferenceResolver R(NameStr);
518  Name->resolveReferences(R);
519  if (!R.found())
521  Name);
522  }
523 
524  return Name;
525 }
526 
527 /// ParseClassID - Parse and resolve a reference to a class name. This returns
528 /// null on error.
529 ///
530 /// ClassID ::= ID
531 ///
532 Record *TGParser::ParseClassID() {
533  if (Lex.getCode() != tgtok::Id) {
534  TokError("expected name for ClassID");
535  return nullptr;
536  }
537 
538  Record *Result = Records.getClass(Lex.getCurStrVal());
539  if (!Result) {
540  std::string Msg("Couldn't find class '" + Lex.getCurStrVal() + "'");
541  if (MultiClasses[Lex.getCurStrVal()].get())
542  TokError(Msg + ". Use 'defm' if you meant to use multiclass '" +
543  Lex.getCurStrVal() + "'");
544  else
545  TokError(Msg);
546  }
547 
548  Lex.Lex();
549  return Result;
550 }
551 
552 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
553 /// This returns null on error.
554 ///
555 /// MultiClassID ::= ID
556 ///
557 MultiClass *TGParser::ParseMultiClassID() {
558  if (Lex.getCode() != tgtok::Id) {
559  TokError("expected name for MultiClassID");
560  return nullptr;
561  }
562 
563  MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
564  if (!Result)
565  TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
566 
567  Lex.Lex();
568  return Result;
569 }
570 
571 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
572 /// subclass. This returns a SubClassRefTy with a null Record* on error.
573 ///
574 /// SubClassRef ::= ClassID
575 /// SubClassRef ::= ClassID '<' ValueList '>'
576 ///
577 SubClassReference TGParser::
578 ParseSubClassReference(Record *CurRec, bool isDefm) {
579  SubClassReference Result;
580  Result.RefRange.Start = Lex.getLoc();
581 
582  if (isDefm) {
583  if (MultiClass *MC = ParseMultiClassID())
584  Result.Rec = &MC->Rec;
585  } else {
586  Result.Rec = ParseClassID();
587  }
588  if (!Result.Rec) return Result;
589 
590  // If there is no template arg list, we're done.
591  if (Lex.getCode() != tgtok::less) {
592  Result.RefRange.End = Lex.getLoc();
593  return Result;
594  }
595  Lex.Lex(); // Eat the '<'
596 
597  if (Lex.getCode() == tgtok::greater) {
598  TokError("subclass reference requires a non-empty list of template values");
599  Result.Rec = nullptr;
600  return Result;
601  }
602 
603  ParseValueList(Result.TemplateArgs, CurRec, Result.Rec);
604  if (Result.TemplateArgs.empty()) {
605  Result.Rec = nullptr; // Error parsing value list.
606  return Result;
607  }
608 
609  if (Lex.getCode() != tgtok::greater) {
610  TokError("expected '>' in template value list");
611  Result.Rec = nullptr;
612  return Result;
613  }
614  Lex.Lex();
615  Result.RefRange.End = Lex.getLoc();
616 
617  return Result;
618 }
619 
620 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
621 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
622 /// Record* on error.
623 ///
624 /// SubMultiClassRef ::= MultiClassID
625 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
626 ///
627 SubMultiClassReference TGParser::
628 ParseSubMultiClassReference(MultiClass *CurMC) {
629  SubMultiClassReference Result;
630  Result.RefRange.Start = Lex.getLoc();
631 
632  Result.MC = ParseMultiClassID();
633  if (!Result.MC) return Result;
634 
635  // If there is no template arg list, we're done.
636  if (Lex.getCode() != tgtok::less) {
637  Result.RefRange.End = Lex.getLoc();
638  return Result;
639  }
640  Lex.Lex(); // Eat the '<'
641 
642  if (Lex.getCode() == tgtok::greater) {
643  TokError("subclass reference requires a non-empty list of template values");
644  Result.MC = nullptr;
645  return Result;
646  }
647 
648  ParseValueList(Result.TemplateArgs, &CurMC->Rec, &Result.MC->Rec);
649  if (Result.TemplateArgs.empty()) {
650  Result.MC = nullptr; // Error parsing value list.
651  return Result;
652  }
653 
654  if (Lex.getCode() != tgtok::greater) {
655  TokError("expected '>' in template value list");
656  Result.MC = nullptr;
657  return Result;
658  }
659  Lex.Lex();
660  Result.RefRange.End = Lex.getLoc();
661 
662  return Result;
663 }
664 
665 /// ParseRangePiece - Parse a bit/value range.
666 /// RangePiece ::= INTVAL
667 /// RangePiece ::= INTVAL '-' INTVAL
668 /// RangePiece ::= INTVAL INTVAL
669 bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges) {
670  if (Lex.getCode() != tgtok::IntVal) {
671  TokError("expected integer or bitrange");
672  return true;
673  }
674  int64_t Start = Lex.getCurIntVal();
675  int64_t End;
676 
677  if (Start < 0)
678  return TokError("invalid range, cannot be negative");
679 
680  switch (Lex.Lex()) { // eat first character.
681  default:
682  Ranges.push_back(Start);
683  return false;
684  case tgtok::minus:
685  if (Lex.Lex() != tgtok::IntVal) {
686  TokError("expected integer value as end of range");
687  return true;
688  }
689  End = Lex.getCurIntVal();
690  break;
691  case tgtok::IntVal:
692  End = -Lex.getCurIntVal();
693  break;
694  }
695  if (End < 0)
696  return TokError("invalid range, cannot be negative");
697  Lex.Lex();
698 
699  // Add to the range.
700  if (Start < End)
701  for (; Start <= End; ++Start)
702  Ranges.push_back(Start);
703  else
704  for (; Start >= End; --Start)
705  Ranges.push_back(Start);
706  return false;
707 }
708 
709 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
710 ///
711 /// RangeList ::= RangePiece (',' RangePiece)*
712 ///
713 void TGParser::ParseRangeList(SmallVectorImpl<unsigned> &Result) {
714  // Parse the first piece.
715  if (ParseRangePiece(Result)) {
716  Result.clear();
717  return;
718  }
719  while (Lex.getCode() == tgtok::comma) {
720  Lex.Lex(); // Eat the comma.
721 
722  // Parse the next range piece.
723  if (ParseRangePiece(Result)) {
724  Result.clear();
725  return;
726  }
727  }
728 }
729 
730 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
731 /// OptionalRangeList ::= '<' RangeList '>'
732 /// OptionalRangeList ::= /*empty*/
733 bool TGParser::ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges) {
734  if (Lex.getCode() != tgtok::less)
735  return false;
736 
737  SMLoc StartLoc = Lex.getLoc();
738  Lex.Lex(); // eat the '<'
739 
740  // Parse the range list.
741  ParseRangeList(Ranges);
742  if (Ranges.empty()) return true;
743 
744  if (Lex.getCode() != tgtok::greater) {
745  TokError("expected '>' at end of range list");
746  return Error(StartLoc, "to match this '<'");
747  }
748  Lex.Lex(); // eat the '>'.
749  return false;
750 }
751 
752 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
753 /// OptionalBitList ::= '{' RangeList '}'
754 /// OptionalBitList ::= /*empty*/
755 bool TGParser::ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges) {
756  if (Lex.getCode() != tgtok::l_brace)
757  return false;
758 
759  SMLoc StartLoc = Lex.getLoc();
760  Lex.Lex(); // eat the '{'
761 
762  // Parse the range list.
763  ParseRangeList(Ranges);
764  if (Ranges.empty()) return true;
765 
766  if (Lex.getCode() != tgtok::r_brace) {
767  TokError("expected '}' at end of bit list");
768  return Error(StartLoc, "to match this '{'");
769  }
770  Lex.Lex(); // eat the '}'.
771  return false;
772 }
773 
774 /// ParseType - Parse and return a tblgen type. This returns null on error.
775 ///
776 /// Type ::= STRING // string type
777 /// Type ::= CODE // code type
778 /// Type ::= BIT // bit type
779 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
780 /// Type ::= INT // int type
781 /// Type ::= LIST '<' Type '>' // list<x> type
782 /// Type ::= DAG // dag type
783 /// Type ::= ClassID // Record Type
784 ///
785 RecTy *TGParser::ParseType() {
786  switch (Lex.getCode()) {
787  default: TokError("Unknown token when expecting a type"); return nullptr;
788  case tgtok::String: Lex.Lex(); return StringRecTy::get();
789  case tgtok::Code: Lex.Lex(); return CodeRecTy::get();
790  case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
791  case tgtok::Int: Lex.Lex(); return IntRecTy::get();
792  case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
793  case tgtok::Id:
794  if (Record *R = ParseClassID()) return RecordRecTy::get(R);
795  TokError("unknown class name");
796  return nullptr;
797  case tgtok::Bits: {
798  if (Lex.Lex() != tgtok::less) { // Eat 'bits'
799  TokError("expected '<' after bits type");
800  return nullptr;
801  }
802  if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
803  TokError("expected integer in bits<n> type");
804  return nullptr;
805  }
806  uint64_t Val = Lex.getCurIntVal();
807  if (Lex.Lex() != tgtok::greater) { // Eat count.
808  TokError("expected '>' at end of bits<n> type");
809  return nullptr;
810  }
811  Lex.Lex(); // Eat '>'
812  return BitsRecTy::get(Val);
813  }
814  case tgtok::List: {
815  if (Lex.Lex() != tgtok::less) { // Eat 'bits'
816  TokError("expected '<' after list type");
817  return nullptr;
818  }
819  Lex.Lex(); // Eat '<'
820  RecTy *SubType = ParseType();
821  if (!SubType) return nullptr;
822 
823  if (Lex.getCode() != tgtok::greater) {
824  TokError("expected '>' at end of list<ty> type");
825  return nullptr;
826  }
827  Lex.Lex(); // Eat '>'
828  return ListRecTy::get(SubType);
829  }
830  }
831 }
832 
833 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
834 /// has already been read.
835 Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMLoc NameLoc,
836  IDParseMode Mode) {
837  if (CurRec) {
838  if (const RecordVal *RV = CurRec->getValue(Name))
839  return VarInit::get(Name, RV->getType());
840  }
841 
842  if ((CurRec && CurRec->isClass()) || CurMultiClass) {
843  Init *TemplateArgName;
844  if (CurMultiClass) {
845  TemplateArgName =
846  QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
847  } else
848  TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
849 
850  Record *TemplateRec = CurMultiClass ? &CurMultiClass->Rec : CurRec;
851  if (TemplateRec->isTemplateArg(TemplateArgName)) {
852  const RecordVal *RV = TemplateRec->getValue(TemplateArgName);
853  assert(RV && "Template arg doesn't exist??");
854  return VarInit::get(TemplateArgName, RV->getType());
855  } else if (Name->getValue() == "NAME") {
856  return VarInit::get(TemplateArgName, StringRecTy::get());
857  }
858  }
859 
860  // If this is in a foreach loop, make sure it's not a loop iterator
861  for (const auto &L : Loops) {
862  VarInit *IterVar = dyn_cast<VarInit>(L->IterVar);
863  if (IterVar && IterVar->getNameInit() == Name)
864  return IterVar;
865  }
866 
867  if (Mode == ParseNameMode)
868  return Name;
869 
870  if (Init *I = Records.getGlobal(Name->getValue()))
871  return I;
872 
873  // Allow self-references of concrete defs, but delay the lookup so that we
874  // get the correct type.
875  if (CurRec && !CurRec->isClass() && !CurMultiClass &&
876  CurRec->getNameInit() == Name)
877  return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType());
878 
879  Error(NameLoc, "Variable not defined: '" + Name->getValue() + "'");
880  return nullptr;
881 }
882 
883 /// ParseOperation - Parse an operator. This returns null on error.
884 ///
885 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
886 ///
887 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
888  switch (Lex.getCode()) {
889  default:
890  TokError("unknown operation");
891  return nullptr;
892  case tgtok::XHead:
893  case tgtok::XTail:
894  case tgtok::XSize:
895  case tgtok::XEmpty:
896  case tgtok::XCast: { // Value ::= !unop '(' Value ')'
897  UnOpInit::UnaryOp Code;
898  RecTy *Type = nullptr;
899 
900  switch (Lex.getCode()) {
901  default: llvm_unreachable("Unhandled code!");
902  case tgtok::XCast:
903  Lex.Lex(); // eat the operation
904  Code = UnOpInit::CAST;
905 
906  Type = ParseOperatorType();
907 
908  if (!Type) {
909  TokError("did not get type for unary operator");
910  return nullptr;
911  }
912 
913  break;
914  case tgtok::XHead:
915  Lex.Lex(); // eat the operation
916  Code = UnOpInit::HEAD;
917  break;
918  case tgtok::XTail:
919  Lex.Lex(); // eat the operation
920  Code = UnOpInit::TAIL;
921  break;
922  case tgtok::XSize:
923  Lex.Lex();
924  Code = UnOpInit::SIZE;
925  Type = IntRecTy::get();
926  break;
927  case tgtok::XEmpty:
928  Lex.Lex(); // eat the operation
929  Code = UnOpInit::EMPTY;
930  Type = IntRecTy::get();
931  break;
932  }
933  if (Lex.getCode() != tgtok::l_paren) {
934  TokError("expected '(' after unary operator");
935  return nullptr;
936  }
937  Lex.Lex(); // eat the '('
938 
939  Init *LHS = ParseValue(CurRec);
940  if (!LHS) return nullptr;
941 
942  if (Code == UnOpInit::HEAD ||
943  Code == UnOpInit::TAIL ||
944  Code == UnOpInit::EMPTY) {
945  ListInit *LHSl = dyn_cast<ListInit>(LHS);
946  StringInit *LHSs = dyn_cast<StringInit>(LHS);
947  TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
948  if (!LHSl && !LHSs && !LHSt) {
949  TokError("expected list or string type argument in unary operator");
950  return nullptr;
951  }
952  if (LHSt) {
953  ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
954  StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
955  if (!LType && !SType) {
956  TokError("expected list or string type argument in unary operator");
957  return nullptr;
958  }
959  }
960 
961  if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL ||
962  Code == UnOpInit::SIZE) {
963  if (!LHSl && !LHSt) {
964  TokError("expected list type argument in unary operator");
965  return nullptr;
966  }
967  }
968 
969  if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
970  if (LHSl && LHSl->empty()) {
971  TokError("empty list argument in unary operator");
972  return nullptr;
973  }
974  if (LHSl) {
975  Init *Item = LHSl->getElement(0);
976  TypedInit *Itemt = dyn_cast<TypedInit>(Item);
977  if (!Itemt) {
978  TokError("untyped list element in unary operator");
979  return nullptr;
980  }
981  Type = (Code == UnOpInit::HEAD) ? Itemt->getType()
982  : ListRecTy::get(Itemt->getType());
983  } else {
984  assert(LHSt && "expected list type argument in unary operator");
985  ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
986  if (!LType) {
987  TokError("expected list type argument in unary operator");
988  return nullptr;
989  }
990  Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType;
991  }
992  }
993  }
994 
995  if (Lex.getCode() != tgtok::r_paren) {
996  TokError("expected ')' in unary operator");
997  return nullptr;
998  }
999  Lex.Lex(); // eat the ')'
1000  return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec);
1001  }
1002 
1003  case tgtok::XIsA: {
1004  // Value ::= !isa '<' Type '>' '(' Value ')'
1005  Lex.Lex(); // eat the operation
1006 
1007  RecTy *Type = ParseOperatorType();
1008  if (!Type)
1009  return nullptr;
1010 
1011  if (Lex.getCode() != tgtok::l_paren) {
1012  TokError("expected '(' after type of !isa");
1013  return nullptr;
1014  }
1015  Lex.Lex(); // eat the '('
1016 
1017  Init *LHS = ParseValue(CurRec);
1018  if (!LHS)
1019  return nullptr;
1020 
1021  if (Lex.getCode() != tgtok::r_paren) {
1022  TokError("expected ')' in !isa");
1023  return nullptr;
1024  }
1025  Lex.Lex(); // eat the ')'
1026 
1027  return (IsAOpInit::get(Type, LHS))->Fold();
1028  }
1029 
1030  case tgtok::XConcat:
1031  case tgtok::XADD:
1032  case tgtok::XMUL:
1033  case tgtok::XAND:
1034  case tgtok::XOR:
1035  case tgtok::XSRA:
1036  case tgtok::XSRL:
1037  case tgtok::XSHL:
1038  case tgtok::XEq:
1039  case tgtok::XNe:
1040  case tgtok::XLe:
1041  case tgtok::XLt:
1042  case tgtok::XGe:
1043  case tgtok::XGt:
1044  case tgtok::XListConcat:
1045  case tgtok::XListSplat:
1046  case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
1047  tgtok::TokKind OpTok = Lex.getCode();
1048  SMLoc OpLoc = Lex.getLoc();
1049  Lex.Lex(); // eat the operation
1050 
1051  BinOpInit::BinaryOp Code;
1052  switch (OpTok) {
1053  default: llvm_unreachable("Unhandled code!");
1054  case tgtok::XConcat: Code = BinOpInit::CONCAT; break;
1055  case tgtok::XADD: Code = BinOpInit::ADD; break;
1056  case tgtok::XMUL: Code = BinOpInit::MUL; break;
1057  case tgtok::XAND: Code = BinOpInit::AND; break;
1058  case tgtok::XOR: Code = BinOpInit::OR; break;
1059  case tgtok::XSRA: Code = BinOpInit::SRA; break;
1060  case tgtok::XSRL: Code = BinOpInit::SRL; break;
1061  case tgtok::XSHL: Code = BinOpInit::SHL; break;
1062  case tgtok::XEq: Code = BinOpInit::EQ; break;
1063  case tgtok::XNe: Code = BinOpInit::NE; break;
1064  case tgtok::XLe: Code = BinOpInit::LE; break;
1065  case tgtok::XLt: Code = BinOpInit::LT; break;
1066  case tgtok::XGe: Code = BinOpInit::GE; break;
1067  case tgtok::XGt: Code = BinOpInit::GT; break;
1068  case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break;
1069  case tgtok::XListSplat: Code = BinOpInit::LISTSPLAT; break;
1070  case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break;
1071  }
1072 
1073  RecTy *Type = nullptr;
1074  RecTy *ArgType = nullptr;
1075  switch (OpTok) {
1076  default:
1077  llvm_unreachable("Unhandled code!");
1078  case tgtok::XConcat:
1079  Type = DagRecTy::get();
1080  ArgType = DagRecTy::get();
1081  break;
1082  case tgtok::XAND:
1083  case tgtok::XOR:
1084  case tgtok::XSRA:
1085  case tgtok::XSRL:
1086  case tgtok::XSHL:
1087  case tgtok::XADD:
1088  case tgtok::XMUL:
1089  Type = IntRecTy::get();
1090  ArgType = IntRecTy::get();
1091  break;
1092  case tgtok::XEq:
1093  case tgtok::XNe:
1094  Type = BitRecTy::get();
1095  // ArgType for Eq / Ne is not known at this point
1096  break;
1097  case tgtok::XLe:
1098  case tgtok::XLt:
1099  case tgtok::XGe:
1100  case tgtok::XGt:
1101  Type = BitRecTy::get();
1102  ArgType = IntRecTy::get();
1103  break;
1104  case tgtok::XListConcat:
1105  // We don't know the list type until we parse the first argument
1106  ArgType = ItemType;
1107  break;
1108  case tgtok::XListSplat:
1109  // Can't do any typechecking until we parse the first argument.
1110  break;
1111  case tgtok::XStrConcat:
1112  Type = StringRecTy::get();
1113  ArgType = StringRecTy::get();
1114  break;
1115  }
1116 
1117  if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) {
1118  Error(OpLoc, Twine("expected value of type '") +
1119  ItemType->getAsString() + "', got '" +
1120  Type->getAsString() + "'");
1121  return nullptr;
1122  }
1123 
1124  if (Lex.getCode() != tgtok::l_paren) {
1125  TokError("expected '(' after binary operator");
1126  return nullptr;
1127  }
1128  Lex.Lex(); // eat the '('
1129 
1130  SmallVector<Init*, 2> InitList;
1131 
1132  for (;;) {
1133  SMLoc InitLoc = Lex.getLoc();
1134  InitList.push_back(ParseValue(CurRec, ArgType));
1135  if (!InitList.back()) return nullptr;
1136 
1137  // All BinOps require their arguments to be of compatible types.
1138  TypedInit *TI = dyn_cast<TypedInit>(InitList.back());
1139  if (!ArgType) {
1140  ArgType = TI->getType();
1141 
1142  switch (Code) {
1143  case BinOpInit::LISTCONCAT:
1144  if (!isa<ListRecTy>(ArgType)) {
1145  Error(InitLoc, Twine("expected a list, got value of type '") +
1146  ArgType->getAsString() + "'");
1147  return nullptr;
1148  }
1149  break;
1150  case BinOpInit::LISTSPLAT:
1151  if (ItemType && InitList.size() == 1) {
1152  if (!isa<ListRecTy>(ItemType)) {
1153  Error(OpLoc,
1154  Twine("expected output type to be a list, got type '") +
1155  ItemType->getAsString() + "'");
1156  return nullptr;
1157  }
1158  if (!ArgType->getListTy()->typeIsConvertibleTo(ItemType)) {
1159  Error(OpLoc, Twine("expected first arg type to be '") +
1160  ArgType->getAsString() +
1161  "', got value of type '" +
1162  cast<ListRecTy>(ItemType)
1163  ->getElementType()
1164  ->getAsString() +
1165  "'");
1166  return nullptr;
1167  }
1168  }
1169  if (InitList.size() == 2 && !isa<IntRecTy>(ArgType)) {
1170  Error(InitLoc, Twine("expected second parameter to be an int, got "
1171  "value of type '") +
1172  ArgType->getAsString() + "'");
1173  return nullptr;
1174  }
1175  ArgType = nullptr; // Broken invariant: types not identical.
1176  break;
1177  case BinOpInit::EQ:
1178  case BinOpInit::NE:
1179  if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) &&
1180  !ArgType->typeIsConvertibleTo(StringRecTy::get())) {
1181  Error(InitLoc, Twine("expected int, bits, or string; got value of "
1182  "type '") + ArgType->getAsString() + "'");
1183  return nullptr;
1184  }
1185  break;
1186  default: llvm_unreachable("other ops have fixed argument types");
1187  }
1188  } else {
1189  RecTy *Resolved = resolveTypes(ArgType, TI->getType());
1190  if (!Resolved) {
1191  Error(InitLoc, Twine("expected value of type '") +
1192  ArgType->getAsString() + "', got '" +
1193  TI->getType()->getAsString() + "'");
1194  return nullptr;
1195  }
1196  if (Code != BinOpInit::ADD && Code != BinOpInit::AND &&
1197  Code != BinOpInit::OR && Code != BinOpInit::SRA &&
1198  Code != BinOpInit::SRL && Code != BinOpInit::SHL &&
1199  Code != BinOpInit::MUL)
1200  ArgType = Resolved;
1201  }
1202 
1203  if (Lex.getCode() != tgtok::comma)
1204  break;
1205  Lex.Lex(); // eat the ','
1206  }
1207 
1208  if (Lex.getCode() != tgtok::r_paren) {
1209  TokError("expected ')' in operator");
1210  return nullptr;
1211  }
1212  Lex.Lex(); // eat the ')'
1213 
1214  // listconcat returns a list with type of the argument.
1215  if (Code == BinOpInit::LISTCONCAT)
1216  Type = ArgType;
1217  // listsplat returns a list of type of the *first* argument.
1218  if (Code == BinOpInit::LISTSPLAT)
1219  Type = cast<TypedInit>(InitList.front())->getType()->getListTy();
1220 
1221  // We allow multiple operands to associative operators like !strconcat as
1222  // shorthand for nesting them.
1223  if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT ||
1224  Code == BinOpInit::CONCAT || Code == BinOpInit::ADD ||
1225  Code == BinOpInit::AND || Code == BinOpInit::OR ||
1226  Code == BinOpInit::MUL) {
1227  while (InitList.size() > 2) {
1228  Init *RHS = InitList.pop_back_val();
1229  RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec);
1230  InitList.back() = RHS;
1231  }
1232  }
1233 
1234  if (InitList.size() == 2)
1235  return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
1236  ->Fold(CurRec);
1237 
1238  Error(OpLoc, "expected two operands to operator");
1239  return nullptr;
1240  }
1241 
1242  case tgtok::XForEach: { // Value ::= !foreach '(' Id ',' Value ',' Value ')'
1243  SMLoc OpLoc = Lex.getLoc();
1244  Lex.Lex(); // eat the operation
1245  if (Lex.getCode() != tgtok::l_paren) {
1246  TokError("expected '(' after !foreach");
1247  return nullptr;
1248  }
1249 
1250  if (Lex.Lex() != tgtok::Id) { // eat the '('
1251  TokError("first argument of !foreach must be an identifier");
1252  return nullptr;
1253  }
1254 
1255  Init *LHS = StringInit::get(Lex.getCurStrVal());
1256 
1257  if (CurRec && CurRec->getValue(LHS)) {
1258  TokError((Twine("iteration variable '") + LHS->getAsString() +
1259  "' already defined")
1260  .str());
1261  return nullptr;
1262  }
1263 
1264  if (Lex.Lex() != tgtok::comma) { // eat the id
1265  TokError("expected ',' in ternary operator");
1266  return nullptr;
1267  }
1268  Lex.Lex(); // eat the ','
1269 
1270  Init *MHS = ParseValue(CurRec);
1271  if (!MHS)
1272  return nullptr;
1273 
1274  if (Lex.getCode() != tgtok::comma) {
1275  TokError("expected ',' in ternary operator");
1276  return nullptr;
1277  }
1278  Lex.Lex(); // eat the ','
1279 
1280  TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1281  if (!MHSt) {
1282  TokError("could not get type of !foreach input");
1283  return nullptr;
1284  }
1285 
1286  RecTy *InEltType = nullptr;
1287  RecTy *OutEltType = nullptr;
1288  bool IsDAG = false;
1289 
1290  if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) {
1291  InEltType = InListTy->getElementType();
1292  if (ItemType) {
1293  if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) {
1294  OutEltType = OutListTy->getElementType();
1295  } else {
1296  Error(OpLoc,
1297  "expected value of type '" + Twine(ItemType->getAsString()) +
1298  "', but got !foreach of list type");
1299  return nullptr;
1300  }
1301  }
1302  } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) {
1303  InEltType = InDagTy;
1304  if (ItemType && !isa<DagRecTy>(ItemType)) {
1305  Error(OpLoc,
1306  "expected value of type '" + Twine(ItemType->getAsString()) +
1307  "', but got !foreach of dag type");
1308  return nullptr;
1309  }
1310  IsDAG = true;
1311  } else {
1312  TokError("!foreach must have list or dag input");
1313  return nullptr;
1314  }
1315 
1316  // We need to create a temporary record to provide a scope for the iteration
1317  // variable while parsing top-level foreach's.
1318  std::unique_ptr<Record> ParseRecTmp;
1319  Record *ParseRec = CurRec;
1320  if (!ParseRec) {
1321  ParseRecTmp = make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1322  ParseRec = ParseRecTmp.get();
1323  }
1324 
1325  ParseRec->addValue(RecordVal(LHS, InEltType, false));
1326  Init *RHS = ParseValue(ParseRec, OutEltType);
1327  ParseRec->removeValue(LHS);
1328  if (!RHS)
1329  return nullptr;
1330 
1331  if (Lex.getCode() != tgtok::r_paren) {
1332  TokError("expected ')' in binary operator");
1333  return nullptr;
1334  }
1335  Lex.Lex(); // eat the ')'
1336 
1337  RecTy *OutType;
1338  if (IsDAG) {
1339  OutType = InEltType;
1340  } else {
1341  TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1342  if (!RHSt) {
1343  TokError("could not get type of !foreach result");
1344  return nullptr;
1345  }
1346  OutType = RHSt->getType()->getListTy();
1347  }
1348 
1349  return (TernOpInit::get(TernOpInit::FOREACH, LHS, MHS, RHS, OutType))
1350  ->Fold(CurRec);
1351  }
1352 
1353  case tgtok::XDag:
1354  case tgtok::XIf:
1355  case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1356  TernOpInit::TernaryOp Code;
1357  RecTy *Type = nullptr;
1358 
1359  tgtok::TokKind LexCode = Lex.getCode();
1360  Lex.Lex(); // eat the operation
1361  switch (LexCode) {
1362  default: llvm_unreachable("Unhandled code!");
1363  case tgtok::XDag:
1364  Code = TernOpInit::DAG;
1365  Type = DagRecTy::get();
1366  ItemType = nullptr;
1367  break;
1368  case tgtok::XIf:
1369  Code = TernOpInit::IF;
1370  break;
1371  case tgtok::XSubst:
1372  Code = TernOpInit::SUBST;
1373  break;
1374  }
1375  if (Lex.getCode() != tgtok::l_paren) {
1376  TokError("expected '(' after ternary operator");
1377  return nullptr;
1378  }
1379  Lex.Lex(); // eat the '('
1380 
1381  Init *LHS = ParseValue(CurRec);
1382  if (!LHS) return nullptr;
1383 
1384  if (Lex.getCode() != tgtok::comma) {
1385  TokError("expected ',' in ternary operator");
1386  return nullptr;
1387  }
1388  Lex.Lex(); // eat the ','
1389 
1390  SMLoc MHSLoc = Lex.getLoc();
1391  Init *MHS = ParseValue(CurRec, ItemType);
1392  if (!MHS)
1393  return nullptr;
1394 
1395  if (Lex.getCode() != tgtok::comma) {
1396  TokError("expected ',' in ternary operator");
1397  return nullptr;
1398  }
1399  Lex.Lex(); // eat the ','
1400 
1401  SMLoc RHSLoc = Lex.getLoc();
1402  Init *RHS = ParseValue(CurRec, ItemType);
1403  if (!RHS)
1404  return nullptr;
1405 
1406  if (Lex.getCode() != tgtok::r_paren) {
1407  TokError("expected ')' in binary operator");
1408  return nullptr;
1409  }
1410  Lex.Lex(); // eat the ')'
1411 
1412  switch (LexCode) {
1413  default: llvm_unreachable("Unhandled code!");
1414  case tgtok::XDag: {
1415  TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1416  if (!MHSt && !isa<UnsetInit>(MHS)) {
1417  Error(MHSLoc, "could not determine type of the child list in !dag");
1418  return nullptr;
1419  }
1420  if (MHSt && !isa<ListRecTy>(MHSt->getType())) {
1421  Error(MHSLoc, Twine("expected list of children, got type '") +
1422  MHSt->getType()->getAsString() + "'");
1423  return nullptr;
1424  }
1425 
1426  TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1427  if (!RHSt && !isa<UnsetInit>(RHS)) {
1428  Error(RHSLoc, "could not determine type of the name list in !dag");
1429  return nullptr;
1430  }
1431  if (RHSt && StringRecTy::get()->getListTy() != RHSt->getType()) {
1432  Error(RHSLoc, Twine("expected list<string>, got type '") +
1433  RHSt->getType()->getAsString() + "'");
1434  return nullptr;
1435  }
1436 
1437  if (!MHSt && !RHSt) {
1438  Error(MHSLoc,
1439  "cannot have both unset children and unset names in !dag");
1440  return nullptr;
1441  }
1442  break;
1443  }
1444  case tgtok::XIf: {
1445  RecTy *MHSTy = nullptr;
1446  RecTy *RHSTy = nullptr;
1447 
1448  if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1449  MHSTy = MHSt->getType();
1450  if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1451  MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1452  if (isa<BitInit>(MHS))
1453  MHSTy = BitRecTy::get();
1454 
1455  if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1456  RHSTy = RHSt->getType();
1457  if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1458  RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1459  if (isa<BitInit>(RHS))
1460  RHSTy = BitRecTy::get();
1461 
1462  // For UnsetInit, it's typed from the other hand.
1463  if (isa<UnsetInit>(MHS))
1464  MHSTy = RHSTy;
1465  if (isa<UnsetInit>(RHS))
1466  RHSTy = MHSTy;
1467 
1468  if (!MHSTy || !RHSTy) {
1469  TokError("could not get type for !if");
1470  return nullptr;
1471  }
1472 
1473  Type = resolveTypes(MHSTy, RHSTy);
1474  if (!Type) {
1475  TokError(Twine("inconsistent types '") + MHSTy->getAsString() +
1476  "' and '" + RHSTy->getAsString() + "' for !if");
1477  return nullptr;
1478  }
1479  break;
1480  }
1481  case tgtok::XSubst: {
1482  TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1483  if (!RHSt) {
1484  TokError("could not get type for !subst");
1485  return nullptr;
1486  }
1487  Type = RHSt->getType();
1488  break;
1489  }
1490  }
1491  return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
1492  }
1493 
1494  case tgtok::XCond:
1495  return ParseOperationCond(CurRec, ItemType);
1496 
1497  case tgtok::XFoldl: {
1498  // Value ::= !foldl '(' Id ',' Id ',' Value ',' Value ',' Value ')'
1499  Lex.Lex(); // eat the operation
1500  if (Lex.getCode() != tgtok::l_paren) {
1501  TokError("expected '(' after !foldl");
1502  return nullptr;
1503  }
1504  Lex.Lex(); // eat the '('
1505 
1506  Init *StartUntyped = ParseValue(CurRec);
1507  if (!StartUntyped)
1508  return nullptr;
1509 
1510  TypedInit *Start = dyn_cast<TypedInit>(StartUntyped);
1511  if (!Start) {
1512  TokError(Twine("could not get type of !foldl start: '") +
1513  StartUntyped->getAsString() + "'");
1514  return nullptr;
1515  }
1516 
1517  if (Lex.getCode() != tgtok::comma) {
1518  TokError("expected ',' in !foldl");
1519  return nullptr;
1520  }
1521  Lex.Lex(); // eat the ','
1522 
1523  Init *ListUntyped = ParseValue(CurRec);
1524  if (!ListUntyped)
1525  return nullptr;
1526 
1527  TypedInit *List = dyn_cast<TypedInit>(ListUntyped);
1528  if (!List) {
1529  TokError(Twine("could not get type of !foldl list: '") +
1530  ListUntyped->getAsString() + "'");
1531  return nullptr;
1532  }
1533 
1534  ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType());
1535  if (!ListType) {
1536  TokError(Twine("!foldl list must be a list, but is of type '") +
1537  List->getType()->getAsString());
1538  return nullptr;
1539  }
1540 
1541  if (Lex.getCode() != tgtok::comma) {
1542  TokError("expected ',' in !foldl");
1543  return nullptr;
1544  }
1545 
1546  if (Lex.Lex() != tgtok::Id) { // eat the ','
1547  TokError("third argument of !foldl must be an identifier");
1548  return nullptr;
1549  }
1550 
1551  Init *A = StringInit::get(Lex.getCurStrVal());
1552  if (CurRec && CurRec->getValue(A)) {
1553  TokError((Twine("left !foldl variable '") + A->getAsString() +
1554  "' already defined")
1555  .str());
1556  return nullptr;
1557  }
1558 
1559  if (Lex.Lex() != tgtok::comma) { // eat the id
1560  TokError("expected ',' in !foldl");
1561  return nullptr;
1562  }
1563 
1564  if (Lex.Lex() != tgtok::Id) { // eat the ','
1565  TokError("fourth argument of !foldl must be an identifier");
1566  return nullptr;
1567  }
1568 
1569  Init *B = StringInit::get(Lex.getCurStrVal());
1570  if (CurRec && CurRec->getValue(B)) {
1571  TokError((Twine("right !foldl variable '") + B->getAsString() +
1572  "' already defined")
1573  .str());
1574  return nullptr;
1575  }
1576 
1577  if (Lex.Lex() != tgtok::comma) { // eat the id
1578  TokError("expected ',' in !foldl");
1579  return nullptr;
1580  }
1581  Lex.Lex(); // eat the ','
1582 
1583  // We need to create a temporary record to provide a scope for the iteration
1584  // variable while parsing top-level foreach's.
1585  std::unique_ptr<Record> ParseRecTmp;
1586  Record *ParseRec = CurRec;
1587  if (!ParseRec) {
1588  ParseRecTmp = make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1589  ParseRec = ParseRecTmp.get();
1590  }
1591 
1592  ParseRec->addValue(RecordVal(A, Start->getType(), false));
1593  ParseRec->addValue(RecordVal(B, ListType->getElementType(), false));
1594  Init *ExprUntyped = ParseValue(ParseRec);
1595  ParseRec->removeValue(A);
1596  ParseRec->removeValue(B);
1597  if (!ExprUntyped)
1598  return nullptr;
1599 
1600  TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped);
1601  if (!Expr) {
1602  TokError("could not get type of !foldl expression");
1603  return nullptr;
1604  }
1605 
1606  if (Expr->getType() != Start->getType()) {
1607  TokError(Twine("!foldl expression must be of same type as start (") +
1608  Start->getType()->getAsString() + "), but is of type " +
1609  Expr->getType()->getAsString());
1610  return nullptr;
1611  }
1612 
1613  if (Lex.getCode() != tgtok::r_paren) {
1614  TokError("expected ')' in fold operator");
1615  return nullptr;
1616  }
1617  Lex.Lex(); // eat the ')'
1618 
1619  return FoldOpInit::get(Start, List, A, B, Expr, Start->getType())
1620  ->Fold(CurRec);
1621  }
1622  }
1623 }
1624 
1625 /// ParseOperatorType - Parse a type for an operator. This returns
1626 /// null on error.
1627 ///
1628 /// OperatorType ::= '<' Type '>'
1629 ///
1630 RecTy *TGParser::ParseOperatorType() {
1631  RecTy *Type = nullptr;
1632 
1633  if (Lex.getCode() != tgtok::less) {
1634  TokError("expected type name for operator");
1635  return nullptr;
1636  }
1637  Lex.Lex(); // eat the <
1638 
1639  Type = ParseType();
1640 
1641  if (!Type) {
1642  TokError("expected type name for operator");
1643  return nullptr;
1644  }
1645 
1646  if (Lex.getCode() != tgtok::greater) {
1647  TokError("expected type name for operator");
1648  return nullptr;
1649  }
1650  Lex.Lex(); // eat the >
1651 
1652  return Type;
1653 }
1654 
1655 Init *TGParser::ParseOperationCond(Record *CurRec, RecTy *ItemType) {
1656  Lex.Lex(); // eat the operation 'cond'
1657 
1658  if (Lex.getCode() != tgtok::l_paren) {
1659  TokError("expected '(' after !cond operator");
1660  return nullptr;
1661  }
1662  Lex.Lex(); // eat the '('
1663 
1664  // Parse through '[Case: Val,]+'
1667  while (true) {
1668  if (Lex.getCode() == tgtok::r_paren) {
1669  Lex.Lex(); // eat the ')'
1670  break;
1671  }
1672 
1673  Init *V = ParseValue(CurRec);
1674  if (!V)
1675  return nullptr;
1676  Case.push_back(V);
1677 
1678  if (Lex.getCode() != tgtok::colon) {
1679  TokError("expected ':' following a condition in !cond operator");
1680  return nullptr;
1681  }
1682  Lex.Lex(); // eat the ':'
1683 
1684  V = ParseValue(CurRec, ItemType);
1685  if (!V)
1686  return nullptr;
1687  Val.push_back(V);
1688 
1689  if (Lex.getCode() == tgtok::r_paren) {
1690  Lex.Lex(); // eat the ')'
1691  break;
1692  }
1693 
1694  if (Lex.getCode() != tgtok::comma) {
1695  TokError("expected ',' or ')' following a value in !cond operator");
1696  return nullptr;
1697  }
1698  Lex.Lex(); // eat the ','
1699  }
1700 
1701  if (Case.size() < 1) {
1702  TokError("there should be at least 1 'condition : value' in the !cond operator");
1703  return nullptr;
1704  }
1705 
1706  // resolve type
1707  RecTy *Type = nullptr;
1708  for (Init *V : Val) {
1709  RecTy *VTy = nullptr;
1710  if (TypedInit *Vt = dyn_cast<TypedInit>(V))
1711  VTy = Vt->getType();
1712  if (BitsInit *Vbits = dyn_cast<BitsInit>(V))
1713  VTy = BitsRecTy::get(Vbits->getNumBits());
1714  if (isa<BitInit>(V))
1715  VTy = BitRecTy::get();
1716 
1717  if (Type == nullptr) {
1718  if (!isa<UnsetInit>(V))
1719  Type = VTy;
1720  } else {
1721  if (!isa<UnsetInit>(V)) {
1722  RecTy *RType = resolveTypes(Type, VTy);
1723  if (!RType) {
1724  TokError(Twine("inconsistent types '") + Type->getAsString() +
1725  "' and '" + VTy->getAsString() + "' for !cond");
1726  return nullptr;
1727  }
1728  Type = RType;
1729  }
1730  }
1731  }
1732 
1733  if (!Type) {
1734  TokError("could not determine type for !cond from its arguments");
1735  return nullptr;
1736  }
1737  return CondOpInit::get(Case, Val, Type)->Fold(CurRec);
1738 }
1739 
1740 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1741 ///
1742 /// SimpleValue ::= IDValue
1743 /// SimpleValue ::= INTVAL
1744 /// SimpleValue ::= STRVAL+
1745 /// SimpleValue ::= CODEFRAGMENT
1746 /// SimpleValue ::= '?'
1747 /// SimpleValue ::= '{' ValueList '}'
1748 /// SimpleValue ::= ID '<' ValueListNE '>'
1749 /// SimpleValue ::= '[' ValueList ']'
1750 /// SimpleValue ::= '(' IDValue DagArgList ')'
1751 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1752 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1753 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1754 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1755 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1756 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1757 /// SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')'
1758 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1759 /// SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
1760 ///
1761 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1762  IDParseMode Mode) {
1763  Init *R = nullptr;
1764  switch (Lex.getCode()) {
1765  default: TokError("Unknown token when parsing a value"); break;
1766  case tgtok::paste:
1767  // This is a leading paste operation. This is deprecated but
1768  // still exists in some .td files. Ignore it.
1769  Lex.Lex(); // Skip '#'.
1770  return ParseSimpleValue(CurRec, ItemType, Mode);
1771  case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1772  case tgtok::BinaryIntVal: {
1773  auto BinaryVal = Lex.getCurBinaryIntVal();
1774  SmallVector<Init*, 16> Bits(BinaryVal.second);
1775  for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
1776  Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
1777  R = BitsInit::get(Bits);
1778  Lex.Lex();
1779  break;
1780  }
1781  case tgtok::StrVal: {
1782  std::string Val = Lex.getCurStrVal();
1783  Lex.Lex();
1784 
1785  // Handle multiple consecutive concatenated strings.
1786  while (Lex.getCode() == tgtok::StrVal) {
1787  Val += Lex.getCurStrVal();
1788  Lex.Lex();
1789  }
1790 
1791  R = StringInit::get(Val);
1792  break;
1793  }
1794  case tgtok::CodeFragment:
1795  R = CodeInit::get(Lex.getCurStrVal(), Lex.getLoc());
1796  Lex.Lex();
1797  break;
1798  case tgtok::question:
1799  R = UnsetInit::get();
1800  Lex.Lex();
1801  break;
1802  case tgtok::Id: {
1803  SMLoc NameLoc = Lex.getLoc();
1804  StringInit *Name = StringInit::get(Lex.getCurStrVal());
1805  if (Lex.Lex() != tgtok::less) // consume the Id.
1806  return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1807 
1808  // Value ::= ID '<' ValueListNE '>'
1809  if (Lex.Lex() == tgtok::greater) {
1810  TokError("expected non-empty value list");
1811  return nullptr;
1812  }
1813 
1814  // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1815  // a new anonymous definition, deriving from CLASS<initvalslist> with no
1816  // body.
1817  Record *Class = Records.getClass(Name->getValue());
1818  if (!Class) {
1819  Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'");
1820  return nullptr;
1821  }
1822 
1824  ParseValueList(Args, CurRec, Class);
1825  if (Args.empty()) return nullptr;
1826 
1827  if (Lex.getCode() != tgtok::greater) {
1828  TokError("expected '>' at end of value list");
1829  return nullptr;
1830  }
1831  Lex.Lex(); // eat the '>'
1832 
1833  // Typecheck the template arguments list
1834  ArrayRef<Init *> ExpectedArgs = Class->getTemplateArgs();
1835  if (ExpectedArgs.size() < Args.size()) {
1836  Error(NameLoc,
1837  "More template args specified than expected");
1838  return nullptr;
1839  }
1840 
1841  for (unsigned i = 0, e = ExpectedArgs.size(); i != e; ++i) {
1842  RecordVal *ExpectedArg = Class->getValue(ExpectedArgs[i]);
1843  if (i < Args.size()) {
1844  if (TypedInit *TI = dyn_cast<TypedInit>(Args[i])) {
1845  RecTy *ExpectedType = ExpectedArg->getType();
1846  if (!TI->getType()->typeIsConvertibleTo(ExpectedType)) {
1847  Error(NameLoc,
1848  "Value specified for template argument #" + Twine(i) + " (" +
1849  ExpectedArg->getNameInitAsString() + ") is of type '" +
1850  TI->getType()->getAsString() + "', expected '" +
1851  ExpectedType->getAsString() + "': " + TI->getAsString());
1852  return nullptr;
1853  }
1854  continue;
1855  }
1856  } else if (ExpectedArg->getValue()->isComplete())
1857  continue;
1858 
1859  Error(NameLoc,
1860  "Value not specified for template argument #" + Twine(i) + " (" +
1861  ExpectedArgs[i]->getAsUnquotedString() + ")");
1862  return nullptr;
1863  }
1864 
1865  return VarDefInit::get(Class, Args)->Fold();
1866  }
1867  case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1868  SMLoc BraceLoc = Lex.getLoc();
1869  Lex.Lex(); // eat the '{'
1871 
1872  if (Lex.getCode() != tgtok::r_brace) {
1873  ParseValueList(Vals, CurRec);
1874  if (Vals.empty()) return nullptr;
1875  }
1876  if (Lex.getCode() != tgtok::r_brace) {
1877  TokError("expected '}' at end of bit list value");
1878  return nullptr;
1879  }
1880  Lex.Lex(); // eat the '}'
1881 
1882  SmallVector<Init *, 16> NewBits;
1883 
1884  // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1885  // first. We'll first read everything in to a vector, then we can reverse
1886  // it to get the bits in the correct order for the BitsInit value.
1887  for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1888  // FIXME: The following two loops would not be duplicated
1889  // if the API was a little more orthogonal.
1890 
1891  // bits<n> values are allowed to initialize n bits.
1892  if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
1893  for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
1894  NewBits.push_back(BI->getBit((e - i) - 1));
1895  continue;
1896  }
1897  // bits<n> can also come from variable initializers.
1898  if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
1899  if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
1900  for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
1901  NewBits.push_back(VI->getBit((e - i) - 1));
1902  continue;
1903  }
1904  // Fallthrough to try convert this to a bit.
1905  }
1906  // All other values must be convertible to just a single bit.
1907  Init *Bit = Vals[i]->getCastTo(BitRecTy::get());
1908  if (!Bit) {
1909  Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
1910  ") is not convertable to a bit");
1911  return nullptr;
1912  }
1913  NewBits.push_back(Bit);
1914  }
1915  std::reverse(NewBits.begin(), NewBits.end());
1916  return BitsInit::get(NewBits);
1917  }
1918  case tgtok::l_square: { // Value ::= '[' ValueList ']'
1919  Lex.Lex(); // eat the '['
1921 
1922  RecTy *DeducedEltTy = nullptr;
1923  ListRecTy *GivenListTy = nullptr;
1924 
1925  if (ItemType) {
1926  ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1927  if (!ListType) {
1928  TokError(Twine("Type mismatch for list, expected list type, got ") +
1929  ItemType->getAsString());
1930  return nullptr;
1931  }
1932  GivenListTy = ListType;
1933  }
1934 
1935  if (Lex.getCode() != tgtok::r_square) {
1936  ParseValueList(Vals, CurRec, nullptr,
1937  GivenListTy ? GivenListTy->getElementType() : nullptr);
1938  if (Vals.empty()) return nullptr;
1939  }
1940  if (Lex.getCode() != tgtok::r_square) {
1941  TokError("expected ']' at end of list value");
1942  return nullptr;
1943  }
1944  Lex.Lex(); // eat the ']'
1945 
1946  RecTy *GivenEltTy = nullptr;
1947  if (Lex.getCode() == tgtok::less) {
1948  // Optional list element type
1949  Lex.Lex(); // eat the '<'
1950 
1951  GivenEltTy = ParseType();
1952  if (!GivenEltTy) {
1953  // Couldn't parse element type
1954  return nullptr;
1955  }
1956 
1957  if (Lex.getCode() != tgtok::greater) {
1958  TokError("expected '>' at end of list element type");
1959  return nullptr;
1960  }
1961  Lex.Lex(); // eat the '>'
1962  }
1963 
1964  // Check elements
1965  RecTy *EltTy = nullptr;
1966  for (Init *V : Vals) {
1967  TypedInit *TArg = dyn_cast<TypedInit>(V);
1968  if (TArg) {
1969  if (EltTy) {
1970  EltTy = resolveTypes(EltTy, TArg->getType());
1971  if (!EltTy) {
1972  TokError("Incompatible types in list elements");
1973  return nullptr;
1974  }
1975  } else {
1976  EltTy = TArg->getType();
1977  }
1978  }
1979  }
1980 
1981  if (GivenEltTy) {
1982  if (EltTy) {
1983  // Verify consistency
1984  if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1985  TokError("Incompatible types in list elements");
1986  return nullptr;
1987  }
1988  }
1989  EltTy = GivenEltTy;
1990  }
1991 
1992  if (!EltTy) {
1993  if (!ItemType) {
1994  TokError("No type for list");
1995  return nullptr;
1996  }
1997  DeducedEltTy = GivenListTy->getElementType();
1998  } else {
1999  // Make sure the deduced type is compatible with the given type
2000  if (GivenListTy) {
2001  if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
2002  TokError(Twine("Element type mismatch for list: element type '") +
2003  EltTy->getAsString() + "' not convertible to '" +
2004  GivenListTy->getElementType()->getAsString());
2005  return nullptr;
2006  }
2007  }
2008  DeducedEltTy = EltTy;
2009  }
2010 
2011  return ListInit::get(Vals, DeducedEltTy);
2012  }
2013  case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
2014  Lex.Lex(); // eat the '('
2015  if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
2016  TokError("expected identifier in dag init");
2017  return nullptr;
2018  }
2019 
2020  Init *Operator = ParseValue(CurRec);
2021  if (!Operator) return nullptr;
2022 
2023  // If the operator name is present, parse it.
2024  StringInit *OperatorName = nullptr;
2025  if (Lex.getCode() == tgtok::colon) {
2026  if (Lex.Lex() != tgtok::VarName) { // eat the ':'
2027  TokError("expected variable name in dag operator");
2028  return nullptr;
2029  }
2030  OperatorName = StringInit::get(Lex.getCurStrVal());
2031  Lex.Lex(); // eat the VarName.
2032  }
2033 
2035  if (Lex.getCode() != tgtok::r_paren) {
2036  ParseDagArgList(DagArgs, CurRec);
2037  if (DagArgs.empty()) return nullptr;
2038  }
2039 
2040  if (Lex.getCode() != tgtok::r_paren) {
2041  TokError("expected ')' in dag init");
2042  return nullptr;
2043  }
2044  Lex.Lex(); // eat the ')'
2045 
2046  return DagInit::get(Operator, OperatorName, DagArgs);
2047  }
2048 
2049  case tgtok::XHead:
2050  case tgtok::XTail:
2051  case tgtok::XSize:
2052  case tgtok::XEmpty:
2053  case tgtok::XCast: // Value ::= !unop '(' Value ')'
2054  case tgtok::XIsA:
2055  case tgtok::XConcat:
2056  case tgtok::XDag:
2057  case tgtok::XADD:
2058  case tgtok::XMUL:
2059  case tgtok::XAND:
2060  case tgtok::XOR:
2061  case tgtok::XSRA:
2062  case tgtok::XSRL:
2063  case tgtok::XSHL:
2064  case tgtok::XEq:
2065  case tgtok::XNe:
2066  case tgtok::XLe:
2067  case tgtok::XLt:
2068  case tgtok::XGe:
2069  case tgtok::XGt:
2070  case tgtok::XListConcat:
2071  case tgtok::XListSplat:
2072  case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
2073  case tgtok::XIf:
2074  case tgtok::XCond:
2075  case tgtok::XFoldl:
2076  case tgtok::XForEach:
2077  case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
2078  return ParseOperation(CurRec, ItemType);
2079  }
2080  }
2081 
2082  return R;
2083 }
2084 
2085 /// ParseValue - Parse a tblgen value. This returns null on error.
2086 ///
2087 /// Value ::= SimpleValue ValueSuffix*
2088 /// ValueSuffix ::= '{' BitList '}'
2089 /// ValueSuffix ::= '[' BitList ']'
2090 /// ValueSuffix ::= '.' ID
2091 ///
2092 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
2093  Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
2094  if (!Result) return nullptr;
2095 
2096  // Parse the suffixes now if present.
2097  while (true) {
2098  switch (Lex.getCode()) {
2099  default: return Result;
2100  case tgtok::l_brace: {
2101  if (Mode == ParseNameMode)
2102  // This is the beginning of the object body.
2103  return Result;
2104 
2105  SMLoc CurlyLoc = Lex.getLoc();
2106  Lex.Lex(); // eat the '{'
2108  ParseRangeList(Ranges);
2109  if (Ranges.empty()) return nullptr;
2110 
2111  // Reverse the bitlist.
2112  std::reverse(Ranges.begin(), Ranges.end());
2113  Result = Result->convertInitializerBitRange(Ranges);
2114  if (!Result) {
2115  Error(CurlyLoc, "Invalid bit range for value");
2116  return nullptr;
2117  }
2118 
2119  // Eat the '}'.
2120  if (Lex.getCode() != tgtok::r_brace) {
2121  TokError("expected '}' at end of bit range list");
2122  return nullptr;
2123  }
2124  Lex.Lex();
2125  break;
2126  }
2127  case tgtok::l_square: {
2128  SMLoc SquareLoc = Lex.getLoc();
2129  Lex.Lex(); // eat the '['
2131  ParseRangeList(Ranges);
2132  if (Ranges.empty()) return nullptr;
2133 
2134  Result = Result->convertInitListSlice(Ranges);
2135  if (!Result) {
2136  Error(SquareLoc, "Invalid range for list slice");
2137  return nullptr;
2138  }
2139 
2140  // Eat the ']'.
2141  if (Lex.getCode() != tgtok::r_square) {
2142  TokError("expected ']' at end of list slice");
2143  return nullptr;
2144  }
2145  Lex.Lex();
2146  break;
2147  }
2148  case tgtok::period: {
2149  if (Lex.Lex() != tgtok::Id) { // eat the .
2150  TokError("expected field identifier after '.'");
2151  return nullptr;
2152  }
2153  StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2154  if (!Result->getFieldType(FieldName)) {
2155  TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
2156  Result->getAsString() + "'");
2157  return nullptr;
2158  }
2159  Result = FieldInit::get(Result, FieldName)->Fold(CurRec);
2160  Lex.Lex(); // eat field name
2161  break;
2162  }
2163 
2164  case tgtok::paste:
2165  SMLoc PasteLoc = Lex.getLoc();
2166  TypedInit *LHS = dyn_cast<TypedInit>(Result);
2167  if (!LHS) {
2168  Error(PasteLoc, "LHS of paste is not typed!");
2169  return nullptr;
2170  }
2171 
2172  // Check if it's a 'listA # listB'
2173  if (isa<ListRecTy>(LHS->getType())) {
2174  Lex.Lex(); // Eat the '#'.
2175 
2176  switch (Lex.getCode()) {
2177  case tgtok::colon:
2178  case tgtok::semi:
2179  case tgtok::l_brace:
2180  Result = LHS; // trailing paste, ignore.
2181  break;
2182  default:
2183  Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
2184  Result = BinOpInit::getListConcat(LHS, RHSResult);
2185  }
2186  break;
2187  }
2188 
2189  // Create a !strconcat() operation, first casting each operand to
2190  // a string if necessary.
2191  if (LHS->getType() != StringRecTy::get()) {
2192  auto CastLHS = dyn_cast<TypedInit>(
2194  ->Fold(CurRec));
2195  if (!CastLHS) {
2196  Error(PasteLoc,
2197  Twine("can't cast '") + LHS->getAsString() + "' to string");
2198  return nullptr;
2199  }
2200  LHS = CastLHS;
2201  }
2202 
2203  TypedInit *RHS = nullptr;
2204 
2205  Lex.Lex(); // Eat the '#'.
2206  switch (Lex.getCode()) {
2207  case tgtok::colon:
2208  case tgtok::semi:
2209  case tgtok::l_brace:
2210  // These are all of the tokens that can begin an object body.
2211  // Some of these can also begin values but we disallow those cases
2212  // because they are unlikely to be useful.
2213 
2214  // Trailing paste, concat with an empty string.
2215  RHS = StringInit::get("");
2216  break;
2217 
2218  default:
2219  Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode);
2220  RHS = dyn_cast<TypedInit>(RHSResult);
2221  if (!RHS) {
2222  Error(PasteLoc, "RHS of paste is not typed!");
2223  return nullptr;
2224  }
2225 
2226  if (RHS->getType() != StringRecTy::get()) {
2227  auto CastRHS = dyn_cast<TypedInit>(
2229  ->Fold(CurRec));
2230  if (!CastRHS) {
2231  Error(PasteLoc,
2232  Twine("can't cast '") + RHS->getAsString() + "' to string");
2233  return nullptr;
2234  }
2235  RHS = CastRHS;
2236  }
2237 
2238  break;
2239  }
2240 
2241  Result = BinOpInit::getStrConcat(LHS, RHS);
2242  break;
2243  }
2244  }
2245 }
2246 
2247 /// ParseDagArgList - Parse the argument list for a dag literal expression.
2248 ///
2249 /// DagArg ::= Value (':' VARNAME)?
2250 /// DagArg ::= VARNAME
2251 /// DagArgList ::= DagArg
2252 /// DagArgList ::= DagArgList ',' DagArg
2253 void TGParser::ParseDagArgList(
2254  SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result,
2255  Record *CurRec) {
2256 
2257  while (true) {
2258  // DagArg ::= VARNAME
2259  if (Lex.getCode() == tgtok::VarName) {
2260  // A missing value is treated like '?'.
2261  StringInit *VarName = StringInit::get(Lex.getCurStrVal());
2262  Result.emplace_back(UnsetInit::get(), VarName);
2263  Lex.Lex();
2264  } else {
2265  // DagArg ::= Value (':' VARNAME)?
2266  Init *Val = ParseValue(CurRec);
2267  if (!Val) {
2268  Result.clear();
2269  return;
2270  }
2271 
2272  // If the variable name is present, add it.
2273  StringInit *VarName = nullptr;
2274  if (Lex.getCode() == tgtok::colon) {
2275  if (Lex.Lex() != tgtok::VarName) { // eat the ':'
2276  TokError("expected variable name in dag literal");
2277  Result.clear();
2278  return;
2279  }
2280  VarName = StringInit::get(Lex.getCurStrVal());
2281  Lex.Lex(); // eat the VarName.
2282  }
2283 
2284  Result.push_back(std::make_pair(Val, VarName));
2285  }
2286  if (Lex.getCode() != tgtok::comma) break;
2287  Lex.Lex(); // eat the ','
2288  }
2289 }
2290 
2291 /// ParseValueList - Parse a comma separated list of values, returning them as a
2292 /// vector. Note that this always expects to be able to parse at least one
2293 /// value. It returns an empty list if this is not possible.
2294 ///
2295 /// ValueList ::= Value (',' Value)
2296 ///
2297 void TGParser::ParseValueList(SmallVectorImpl<Init*> &Result, Record *CurRec,
2298  Record *ArgsRec, RecTy *EltTy) {
2299  RecTy *ItemType = EltTy;
2300  unsigned int ArgN = 0;
2301  if (ArgsRec && !EltTy) {
2302  ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2303  if (TArgs.empty()) {
2304  TokError("template argument provided to non-template class");
2305  Result.clear();
2306  return;
2307  }
2308  const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2309  if (!RV) {
2310  errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
2311  << ")\n";
2312  }
2313  assert(RV && "Template argument record not found??");
2314  ItemType = RV->getType();
2315  ++ArgN;
2316  }
2317  Result.push_back(ParseValue(CurRec, ItemType));
2318  if (!Result.back()) {
2319  Result.clear();
2320  return;
2321  }
2322 
2323  while (Lex.getCode() == tgtok::comma) {
2324  Lex.Lex(); // Eat the comma
2325 
2326  // ignore trailing comma for lists
2327  if (Lex.getCode() == tgtok::r_square)
2328  return;
2329 
2330  if (ArgsRec && !EltTy) {
2331  ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2332  if (ArgN >= TArgs.size()) {
2333  TokError("too many template arguments");
2334  Result.clear();
2335  return;
2336  }
2337  const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2338  assert(RV && "Template argument record not found??");
2339  ItemType = RV->getType();
2340  ++ArgN;
2341  }
2342  Result.push_back(ParseValue(CurRec, ItemType));
2343  if (!Result.back()) {
2344  Result.clear();
2345  return;
2346  }
2347  }
2348 }
2349 
2350 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
2351 /// empty string on error. This can happen in a number of different context's,
2352 /// including within a def or in the template args for a def (which which case
2353 /// CurRec will be non-null) and within the template args for a multiclass (in
2354 /// which case CurRec will be null, but CurMultiClass will be set). This can
2355 /// also happen within a def that is within a multiclass, which will set both
2356 /// CurRec and CurMultiClass.
2357 ///
2358 /// Declaration ::= FIELD? Type ID ('=' Value)?
2359 ///
2360 Init *TGParser::ParseDeclaration(Record *CurRec,
2361  bool ParsingTemplateArgs) {
2362  // Read the field prefix if present.
2363  bool HasField = Lex.getCode() == tgtok::Field;
2364  if (HasField) Lex.Lex();
2365 
2366  RecTy *Type = ParseType();
2367  if (!Type) return nullptr;
2368 
2369  if (Lex.getCode() != tgtok::Id) {
2370  TokError("Expected identifier in declaration");
2371  return nullptr;
2372  }
2373 
2374  std::string Str = Lex.getCurStrVal();
2375  if (Str == "NAME") {
2376  TokError("'" + Str + "' is a reserved variable name");
2377  return nullptr;
2378  }
2379 
2380  SMLoc IdLoc = Lex.getLoc();
2381  Init *DeclName = StringInit::get(Str);
2382  Lex.Lex();
2383 
2384  if (ParsingTemplateArgs) {
2385  if (CurRec)
2386  DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
2387  else
2388  assert(CurMultiClass);
2389  if (CurMultiClass)
2390  DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
2391  "::");
2392  }
2393 
2394  // Add the value.
2395  if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
2396  return nullptr;
2397 
2398  // If a value is present, parse it.
2399  if (Lex.getCode() == tgtok::equal) {
2400  Lex.Lex();
2401  SMLoc ValLoc = Lex.getLoc();
2402  Init *Val = ParseValue(CurRec, Type);
2403  if (!Val ||
2404  SetValue(CurRec, ValLoc, DeclName, None, Val))
2405  // Return the name, even if an error is thrown. This is so that we can
2406  // continue to make some progress, even without the value having been
2407  // initialized.
2408  return DeclName;
2409  }
2410 
2411  return DeclName;
2412 }
2413 
2414 /// ParseForeachDeclaration - Read a foreach declaration, returning
2415 /// the name of the declared object or a NULL Init on error. Return
2416 /// the name of the parsed initializer list through ForeachListName.
2417 ///
2418 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
2419 /// ForeachDeclaration ::= ID '=' RangePiece
2420 /// ForeachDeclaration ::= ID '=' Value
2421 ///
2422 VarInit *TGParser::ParseForeachDeclaration(Init *&ForeachListValue) {
2423  if (Lex.getCode() != tgtok::Id) {
2424  TokError("Expected identifier in foreach declaration");
2425  return nullptr;
2426  }
2427 
2428  Init *DeclName = StringInit::get(Lex.getCurStrVal());
2429  Lex.Lex();
2430 
2431  // If a value is present, parse it.
2432  if (Lex.getCode() != tgtok::equal) {
2433  TokError("Expected '=' in foreach declaration");
2434  return nullptr;
2435  }
2436  Lex.Lex(); // Eat the '='
2437 
2438  RecTy *IterType = nullptr;
2440 
2441  switch (Lex.getCode()) {
2442  case tgtok::IntVal: { // RangePiece.
2443  if (ParseRangePiece(Ranges))
2444  return nullptr;
2445  break;
2446  }
2447 
2448  case tgtok::l_brace: { // '{' RangeList '}'
2449  Lex.Lex(); // eat the '{'
2450  ParseRangeList(Ranges);
2451  if (Lex.getCode() != tgtok::r_brace) {
2452  TokError("expected '}' at end of bit range list");
2453  return nullptr;
2454  }
2455  Lex.Lex();
2456  break;
2457  }
2458 
2459  default: {
2460  SMLoc ValueLoc = Lex.getLoc();
2461  Init *I = ParseValue(nullptr);
2462  TypedInit *TI = dyn_cast<TypedInit>(I);
2463  if (!TI || !isa<ListRecTy>(TI->getType())) {
2464  std::string Type;
2465  if (TI)
2466  Type = (Twine("' of type '") + TI->getType()->getAsString()).str();
2467  Error(ValueLoc, "expected a list, got '" + I->getAsString() + Type + "'");
2468  if (CurMultiClass)
2469  PrintNote({}, "references to multiclass template arguments cannot be "
2470  "resolved at this time");
2471  return nullptr;
2472  }
2473  ForeachListValue = I;
2474  IterType = cast<ListRecTy>(TI->getType())->getElementType();
2475  break;
2476  }
2477  }
2478 
2479  if (!Ranges.empty()) {
2480  assert(!IterType && "Type already initialized?");
2481  IterType = IntRecTy::get();
2482  std::vector<Init*> Values;
2483  for (unsigned R : Ranges)
2484  Values.push_back(IntInit::get(R));
2485  ForeachListValue = ListInit::get(Values, IterType);
2486  }
2487 
2488  if (!IterType)
2489  return nullptr;
2490 
2491  return VarInit::get(DeclName, IterType);
2492 }
2493 
2494 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
2495 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
2496 /// template args for a def, which may or may not be in a multiclass. If null,
2497 /// these are the template args for a multiclass.
2498 ///
2499 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
2500 ///
2501 bool TGParser::ParseTemplateArgList(Record *CurRec) {
2502  assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
2503  Lex.Lex(); // eat the '<'
2504 
2505  Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
2506 
2507  // Read the first declaration.
2508  Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2509  if (!TemplArg)
2510  return true;
2511 
2512  TheRecToAddTo->addTemplateArg(TemplArg);
2513 
2514  while (Lex.getCode() == tgtok::comma) {
2515  Lex.Lex(); // eat the ','
2516 
2517  // Read the following declarations.
2518  SMLoc Loc = Lex.getLoc();
2519  TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2520  if (!TemplArg)
2521  return true;
2522 
2523  if (TheRecToAddTo->isTemplateArg(TemplArg))
2524  return Error(Loc, "template argument with the same name has already been "
2525  "defined");
2526 
2527  TheRecToAddTo->addTemplateArg(TemplArg);
2528  }
2529 
2530  if (Lex.getCode() != tgtok::greater)
2531  return TokError("expected '>' at end of template argument list");
2532  Lex.Lex(); // eat the '>'.
2533  return false;
2534 }
2535 
2536 /// ParseBodyItem - Parse a single item at within the body of a def or class.
2537 ///
2538 /// BodyItem ::= Declaration ';'
2539 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
2540 bool TGParser::ParseBodyItem(Record *CurRec) {
2541  if (Lex.getCode() != tgtok::Let) {
2542  if (!ParseDeclaration(CurRec, false))
2543  return true;
2544 
2545  if (Lex.getCode() != tgtok::semi)
2546  return TokError("expected ';' after declaration");
2547  Lex.Lex();
2548  return false;
2549  }
2550 
2551  // LET ID OptionalRangeList '=' Value ';'
2552  if (Lex.Lex() != tgtok::Id)
2553  return TokError("expected field identifier after let");
2554 
2555  SMLoc IdLoc = Lex.getLoc();
2556  StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2557  Lex.Lex(); // eat the field name.
2558 
2559  SmallVector<unsigned, 16> BitList;
2560  if (ParseOptionalBitList(BitList))
2561  return true;
2562  std::reverse(BitList.begin(), BitList.end());
2563 
2564  if (Lex.getCode() != tgtok::equal)
2565  return TokError("expected '=' in let expression");
2566  Lex.Lex(); // eat the '='.
2567 
2568  RecordVal *Field = CurRec->getValue(FieldName);
2569  if (!Field)
2570  return TokError("Value '" + FieldName->getValue() + "' unknown!");
2571 
2572  RecTy *Type = Field->getType();
2573 
2574  Init *Val = ParseValue(CurRec, Type);
2575  if (!Val) return true;
2576 
2577  if (Lex.getCode() != tgtok::semi)
2578  return TokError("expected ';' after let expression");
2579  Lex.Lex();
2580 
2581  return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
2582 }
2583 
2584 /// ParseBody - Read the body of a class or def. Return true on error, false on
2585 /// success.
2586 ///
2587 /// Body ::= ';'
2588 /// Body ::= '{' BodyList '}'
2589 /// BodyList BodyItem*
2590 ///
2591 bool TGParser::ParseBody(Record *CurRec) {
2592  // If this is a null definition, just eat the semi and return.
2593  if (Lex.getCode() == tgtok::semi) {
2594  Lex.Lex();
2595  return false;
2596  }
2597 
2598  if (Lex.getCode() != tgtok::l_brace)
2599  return TokError("Expected ';' or '{' to start body");
2600  // Eat the '{'.
2601  Lex.Lex();
2602 
2603  while (Lex.getCode() != tgtok::r_brace)
2604  if (ParseBodyItem(CurRec))
2605  return true;
2606 
2607  // Eat the '}'.
2608  Lex.Lex();
2609  return false;
2610 }
2611 
2612 /// Apply the current let bindings to \a CurRec.
2613 /// \returns true on error, false otherwise.
2614 bool TGParser::ApplyLetStack(Record *CurRec) {
2615  for (SmallVectorImpl<LetRecord> &LetInfo : LetStack)
2616  for (LetRecord &LR : LetInfo)
2617  if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
2618  return true;
2619  return false;
2620 }
2621 
2622 bool TGParser::ApplyLetStack(RecordsEntry &Entry) {
2623  if (Entry.Rec)
2624  return ApplyLetStack(Entry.Rec.get());
2625 
2626  for (auto &E : Entry.Loop->Entries) {
2627  if (ApplyLetStack(E))
2628  return true;
2629  }
2630 
2631  return false;
2632 }
2633 
2634 /// ParseObjectBody - Parse the body of a def or class. This consists of an
2635 /// optional ClassList followed by a Body. CurRec is the current def or class
2636 /// that is being parsed.
2637 ///
2638 /// ObjectBody ::= BaseClassList Body
2639 /// BaseClassList ::= /*empty*/
2640 /// BaseClassList ::= ':' BaseClassListNE
2641 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
2642 ///
2643 bool TGParser::ParseObjectBody(Record *CurRec) {
2644  // If there is a baseclass list, read it.
2645  if (Lex.getCode() == tgtok::colon) {
2646  Lex.Lex();
2647 
2648  // Read all of the subclasses.
2649  SubClassReference SubClass = ParseSubClassReference(CurRec, false);
2650  while (true) {
2651  // Check for error.
2652  if (!SubClass.Rec) return true;
2653 
2654  // Add it.
2655  if (AddSubClass(CurRec, SubClass))
2656  return true;
2657 
2658  if (Lex.getCode() != tgtok::comma) break;
2659  Lex.Lex(); // eat ','.
2660  SubClass = ParseSubClassReference(CurRec, false);
2661  }
2662  }
2663 
2664  if (ApplyLetStack(CurRec))
2665  return true;
2666 
2667  return ParseBody(CurRec);
2668 }
2669 
2670 /// ParseDef - Parse and return a top level or multiclass def, return the record
2671 /// corresponding to it. This returns null on error.
2672 ///
2673 /// DefInst ::= DEF ObjectName ObjectBody
2674 ///
2675 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
2676  SMLoc DefLoc = Lex.getLoc();
2677  assert(Lex.getCode() == tgtok::Def && "Unknown tok");
2678  Lex.Lex(); // Eat the 'def' token.
2679 
2680  // Parse ObjectName and make a record for it.
2681  std::unique_ptr<Record> CurRec;
2682  Init *Name = ParseObjectName(CurMultiClass);
2683  if (!Name)
2684  return true;
2685 
2686  if (isa<UnsetInit>(Name))
2687  CurRec = make_unique<Record>(Records.getNewAnonymousName(), DefLoc, Records,
2688  /*Anonymous=*/true);
2689  else
2690  CurRec = make_unique<Record>(Name, DefLoc, Records);
2691 
2692  if (ParseObjectBody(CurRec.get()))
2693  return true;
2694 
2695  return addEntry(std::move(CurRec));
2696 }
2697 
2698 /// ParseDefset - Parse a defset statement.
2699 ///
2700 /// Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
2701 ///
2702 bool TGParser::ParseDefset() {
2703  assert(Lex.getCode() == tgtok::Defset);
2704  Lex.Lex(); // Eat the 'defset' token
2705 
2707  Defset.Loc = Lex.getLoc();
2708  RecTy *Type = ParseType();
2709  if (!Type)
2710  return true;
2711  if (!isa<ListRecTy>(Type))
2712  return Error(Defset.Loc, "expected list type");
2713  Defset.EltTy = cast<ListRecTy>(Type)->getElementType();
2714 
2715  if (Lex.getCode() != tgtok::Id)
2716  return TokError("expected identifier");
2717  StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
2718  if (Records.getGlobal(DeclName->getValue()))
2719  return TokError("def or global variable of this name already exists");
2720 
2721  if (Lex.Lex() != tgtok::equal) // Eat the identifier
2722  return TokError("expected '='");
2723  if (Lex.Lex() != tgtok::l_brace) // Eat the '='
2724  return TokError("expected '{'");
2725  SMLoc BraceLoc = Lex.getLoc();
2726  Lex.Lex(); // Eat the '{'
2727 
2728  Defsets.push_back(&Defset);
2729  bool Err = ParseObjectList(nullptr);
2730  Defsets.pop_back();
2731  if (Err)
2732  return true;
2733 
2734  if (Lex.getCode() != tgtok::r_brace) {
2735  TokError("expected '}' at end of defset");
2736  return Error(BraceLoc, "to match this '{'");
2737  }
2738  Lex.Lex(); // Eat the '}'
2739 
2740  Records.addExtraGlobal(DeclName->getValue(),
2741  ListInit::get(Defset.Elements, Defset.EltTy));
2742  return false;
2743 }
2744 
2745 /// ParseForeach - Parse a for statement. Return the record corresponding
2746 /// to it. This returns true on error.
2747 ///
2748 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2749 /// Foreach ::= FOREACH Declaration IN Object
2750 ///
2751 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2752  SMLoc Loc = Lex.getLoc();
2753  assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2754  Lex.Lex(); // Eat the 'for' token.
2755 
2756  // Make a temporary object to record items associated with the for
2757  // loop.
2758  Init *ListValue = nullptr;
2759  VarInit *IterName = ParseForeachDeclaration(ListValue);
2760  if (!IterName)
2761  return TokError("expected declaration in for");
2762 
2763  if (Lex.getCode() != tgtok::In)
2764  return TokError("Unknown tok");
2765  Lex.Lex(); // Eat the in
2766 
2767  // Create a loop object and remember it.
2768  Loops.push_back(llvm::make_unique<ForeachLoop>(Loc, IterName, ListValue));
2769 
2770  if (Lex.getCode() != tgtok::l_brace) {
2771  // FOREACH Declaration IN Object
2772  if (ParseObject(CurMultiClass))
2773  return true;
2774  } else {
2775  SMLoc BraceLoc = Lex.getLoc();
2776  // Otherwise, this is a group foreach.
2777  Lex.Lex(); // eat the '{'.
2778 
2779  // Parse the object list.
2780  if (ParseObjectList(CurMultiClass))
2781  return true;
2782 
2783  if (Lex.getCode() != tgtok::r_brace) {
2784  TokError("expected '}' at end of foreach command");
2785  return Error(BraceLoc, "to match this '{'");
2786  }
2787  Lex.Lex(); // Eat the }
2788  }
2789 
2790  // Resolve the loop or store it for later resolution.
2791  std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
2792  Loops.pop_back();
2793 
2794  return addEntry(std::move(Loop));
2795 }
2796 
2797 /// ParseClass - Parse a tblgen class definition.
2798 ///
2799 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2800 ///
2801 bool TGParser::ParseClass() {
2802  assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2803  Lex.Lex();
2804 
2805  if (Lex.getCode() != tgtok::Id)
2806  return TokError("expected class name after 'class' keyword");
2807 
2808  Record *CurRec = Records.getClass(Lex.getCurStrVal());
2809  if (CurRec) {
2810  // If the body was previously defined, this is an error.
2811  if (!CurRec->getValues().empty() ||
2812  !CurRec->getSuperClasses().empty() ||
2813  !CurRec->getTemplateArgs().empty())
2814  return TokError("Class '" + CurRec->getNameInitAsString() +
2815  "' already defined");
2816  } else {
2817  // If this is the first reference to this class, create and add it.
2818  auto NewRec =
2819  llvm::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records,
2820  /*Class=*/true);
2821  CurRec = NewRec.get();
2822  Records.addClass(std::move(NewRec));
2823  }
2824  Lex.Lex(); // eat the name.
2825 
2826  // If there are template args, parse them.
2827  if (Lex.getCode() == tgtok::less)
2828  if (ParseTemplateArgList(CurRec))
2829  return true;
2830 
2831  return ParseObjectBody(CurRec);
2832 }
2833 
2834 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2835 /// of LetRecords.
2836 ///
2837 /// LetList ::= LetItem (',' LetItem)*
2838 /// LetItem ::= ID OptionalRangeList '=' Value
2839 ///
2840 void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) {
2841  while (true) {
2842  if (Lex.getCode() != tgtok::Id) {
2843  TokError("expected identifier in let definition");
2844  Result.clear();
2845  return;
2846  }
2847 
2848  StringInit *Name = StringInit::get(Lex.getCurStrVal());
2849  SMLoc NameLoc = Lex.getLoc();
2850  Lex.Lex(); // Eat the identifier.
2851 
2852  // Check for an optional RangeList.
2854  if (ParseOptionalRangeList(Bits)) {
2855  Result.clear();
2856  return;
2857  }
2858  std::reverse(Bits.begin(), Bits.end());
2859 
2860  if (Lex.getCode() != tgtok::equal) {
2861  TokError("expected '=' in let expression");
2862  Result.clear();
2863  return;
2864  }
2865  Lex.Lex(); // eat the '='.
2866 
2867  Init *Val = ParseValue(nullptr);
2868  if (!Val) {
2869  Result.clear();
2870  return;
2871  }
2872 
2873  // Now that we have everything, add the record.
2874  Result.emplace_back(Name, Bits, Val, NameLoc);
2875 
2876  if (Lex.getCode() != tgtok::comma)
2877  return;
2878  Lex.Lex(); // eat the comma.
2879  }
2880 }
2881 
2882 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2883 /// different related productions. This works inside multiclasses too.
2884 ///
2885 /// Object ::= LET LetList IN '{' ObjectList '}'
2886 /// Object ::= LET LetList IN Object
2887 ///
2888 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2889  assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2890  Lex.Lex();
2891 
2892  // Add this entry to the let stack.
2893  SmallVector<LetRecord, 8> LetInfo;
2894  ParseLetList(LetInfo);
2895  if (LetInfo.empty()) return true;
2896  LetStack.push_back(std::move(LetInfo));
2897 
2898  if (Lex.getCode() != tgtok::In)
2899  return TokError("expected 'in' at end of top-level 'let'");
2900  Lex.Lex();
2901 
2902  // If this is a scalar let, just handle it now
2903  if (Lex.getCode() != tgtok::l_brace) {
2904  // LET LetList IN Object
2905  if (ParseObject(CurMultiClass))
2906  return true;
2907  } else { // Object ::= LETCommand '{' ObjectList '}'
2908  SMLoc BraceLoc = Lex.getLoc();
2909  // Otherwise, this is a group let.
2910  Lex.Lex(); // eat the '{'.
2911 
2912  // Parse the object list.
2913  if (ParseObjectList(CurMultiClass))
2914  return true;
2915 
2916  if (Lex.getCode() != tgtok::r_brace) {
2917  TokError("expected '}' at end of top level let command");
2918  return Error(BraceLoc, "to match this '{'");
2919  }
2920  Lex.Lex();
2921  }
2922 
2923  // Outside this let scope, this let block is not active.
2924  LetStack.pop_back();
2925  return false;
2926 }
2927 
2928 /// ParseMultiClass - Parse a multiclass definition.
2929 ///
2930 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2931 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2932 /// MultiClassObject ::= DefInst
2933 /// MultiClassObject ::= MultiClassInst
2934 /// MultiClassObject ::= DefMInst
2935 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
2936 /// MultiClassObject ::= LETCommand Object
2937 ///
2938 bool TGParser::ParseMultiClass() {
2939  assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2940  Lex.Lex(); // Eat the multiclass token.
2941 
2942  if (Lex.getCode() != tgtok::Id)
2943  return TokError("expected identifier after multiclass for name");
2944  std::string Name = Lex.getCurStrVal();
2945 
2946  auto Result =
2947  MultiClasses.insert(std::make_pair(Name,
2948  llvm::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
2949 
2950  if (!Result.second)
2951  return TokError("multiclass '" + Name + "' already defined");
2952 
2953  CurMultiClass = Result.first->second.get();
2954  Lex.Lex(); // Eat the identifier.
2955 
2956  // If there are template args, parse them.
2957  if (Lex.getCode() == tgtok::less)
2958  if (ParseTemplateArgList(nullptr))
2959  return true;
2960 
2961  bool inherits = false;
2962 
2963  // If there are submulticlasses, parse them.
2964  if (Lex.getCode() == tgtok::colon) {
2965  inherits = true;
2966 
2967  Lex.Lex();
2968 
2969  // Read all of the submulticlasses.
2970  SubMultiClassReference SubMultiClass =
2971  ParseSubMultiClassReference(CurMultiClass);
2972  while (true) {
2973  // Check for error.
2974  if (!SubMultiClass.MC) return true;
2975 
2976  // Add it.
2977  if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2978  return true;
2979 
2980  if (Lex.getCode() != tgtok::comma) break;
2981  Lex.Lex(); // eat ','.
2982  SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2983  }
2984  }
2985 
2986  if (Lex.getCode() != tgtok::l_brace) {
2987  if (!inherits)
2988  return TokError("expected '{' in multiclass definition");
2989  if (Lex.getCode() != tgtok::semi)
2990  return TokError("expected ';' in multiclass definition");
2991  Lex.Lex(); // eat the ';'.
2992  } else {
2993  if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2994  return TokError("multiclass must contain at least one def");
2995 
2996  while (Lex.getCode() != tgtok::r_brace) {
2997  switch (Lex.getCode()) {
2998  default:
2999  return TokError("expected 'let', 'def', 'defm' or 'foreach' in "
3000  "multiclass body");
3001  case tgtok::Let:
3002  case tgtok::Def:
3003  case tgtok::Defm:
3004  case tgtok::Foreach:
3005  if (ParseObject(CurMultiClass))
3006  return true;
3007  break;
3008  }
3009  }
3010  Lex.Lex(); // eat the '}'.
3011  }
3012 
3013  CurMultiClass = nullptr;
3014  return false;
3015 }
3016 
3017 /// ParseDefm - Parse the instantiation of a multiclass.
3018 ///
3019 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
3020 ///
3021 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
3022  assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
3023  Lex.Lex(); // eat the defm
3024 
3025  Init *DefmName = ParseObjectName(CurMultiClass);
3026  if (!DefmName)
3027  return true;
3028  if (isa<UnsetInit>(DefmName)) {
3029  DefmName = Records.getNewAnonymousName();
3030  if (CurMultiClass)
3031  DefmName = BinOpInit::getStrConcat(
3033  StringRecTy::get()),
3034  DefmName);
3035  }
3036 
3037  if (Lex.getCode() != tgtok::colon)
3038  return TokError("expected ':' after defm identifier");
3039 
3040  // Keep track of the new generated record definitions.
3041  std::vector<RecordsEntry> NewEntries;
3042 
3043  // This record also inherits from a regular class (non-multiclass)?
3044  bool InheritFromClass = false;
3045 
3046  // eat the colon.
3047  Lex.Lex();
3048 
3049  SMLoc SubClassLoc = Lex.getLoc();
3050  SubClassReference Ref = ParseSubClassReference(nullptr, true);
3051 
3052  while (true) {
3053  if (!Ref.Rec) return true;
3054 
3055  // To instantiate a multiclass, we need to first get the multiclass, then
3056  // instantiate each def contained in the multiclass with the SubClassRef
3057  // template parameters.
3058  MultiClass *MC = MultiClasses[Ref.Rec->getName()].get();
3059  assert(MC && "Didn't lookup multiclass correctly?");
3060  ArrayRef<Init*> TemplateVals = Ref.TemplateArgs;
3061 
3062  // Verify that the correct number of template arguments were specified.
3063  ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs();
3064  if (TArgs.size() < TemplateVals.size())
3065  return Error(SubClassLoc,
3066  "more template args specified than multiclass expects");
3067 
3068  SubstStack Substs;
3069  for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
3070  if (i < TemplateVals.size()) {
3071  Substs.emplace_back(TArgs[i], TemplateVals[i]);
3072  } else {
3073  Init *Default = MC->Rec.getValue(TArgs[i])->getValue();
3074  if (!Default->isComplete()) {
3075  return Error(SubClassLoc,
3076  "value not specified for template argument #" +
3077  Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
3078  ") of multiclass '" + MC->Rec.getNameInitAsString() +
3079  "'");
3080  }
3081  Substs.emplace_back(TArgs[i], Default);
3082  }
3083  }
3084 
3085  Substs.emplace_back(QualifiedNameOfImplicitName(MC), DefmName);
3086 
3087  if (resolve(MC->Entries, Substs, CurMultiClass == nullptr, &NewEntries,
3088  &SubClassLoc))
3089  return true;
3090 
3091  if (Lex.getCode() != tgtok::comma) break;
3092  Lex.Lex(); // eat ','.
3093 
3094  if (Lex.getCode() != tgtok::Id)
3095  return TokError("expected identifier");
3096 
3097  SubClassLoc = Lex.getLoc();
3098 
3099  // A defm can inherit from regular classes (non-multiclass) as
3100  // long as they come in the end of the inheritance list.
3101  InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
3102 
3103  if (InheritFromClass)
3104  break;
3105 
3106  Ref = ParseSubClassReference(nullptr, true);
3107  }
3108 
3109  if (InheritFromClass) {
3110  // Process all the classes to inherit as if they were part of a
3111  // regular 'def' and inherit all record values.
3112  SubClassReference SubClass = ParseSubClassReference(nullptr, false);
3113  while (true) {
3114  // Check for error.
3115  if (!SubClass.Rec) return true;
3116 
3117  // Get the expanded definition prototypes and teach them about
3118  // the record values the current class to inherit has
3119  for (auto &E : NewEntries) {
3120  // Add it.
3121  if (AddSubClass(E, SubClass))
3122  return true;
3123  }
3124 
3125  if (Lex.getCode() != tgtok::comma) break;
3126  Lex.Lex(); // eat ','.
3127  SubClass = ParseSubClassReference(nullptr, false);
3128  }
3129  }
3130 
3131  for (auto &E : NewEntries) {
3132  if (ApplyLetStack(E))
3133  return true;
3134 
3135  addEntry(std::move(E));
3136  }
3137 
3138  if (Lex.getCode() != tgtok::semi)
3139  return TokError("expected ';' at end of defm");
3140  Lex.Lex();
3141 
3142  return false;
3143 }
3144 
3145 /// ParseObject
3146 /// Object ::= ClassInst
3147 /// Object ::= DefInst
3148 /// Object ::= MultiClassInst
3149 /// Object ::= DefMInst
3150 /// Object ::= LETCommand '{' ObjectList '}'
3151 /// Object ::= LETCommand Object
3152 bool TGParser::ParseObject(MultiClass *MC) {
3153  switch (Lex.getCode()) {
3154  default:
3155  return TokError("Expected class, def, defm, defset, multiclass, let or "
3156  "foreach");
3157  case tgtok::Let: return ParseTopLevelLet(MC);
3158  case tgtok::Def: return ParseDef(MC);
3159  case tgtok::Foreach: return ParseForeach(MC);
3160  case tgtok::Defm: return ParseDefm(MC);
3161  case tgtok::Defset:
3162  if (MC)
3163  return TokError("defset is not allowed inside multiclass");
3164  return ParseDefset();
3165  case tgtok::Class:
3166  if (MC)
3167  return TokError("class is not allowed inside multiclass");
3168  if (!Loops.empty())
3169  return TokError("class is not allowed inside foreach loop");
3170  return ParseClass();
3171  case tgtok::MultiClass:
3172  if (!Loops.empty())
3173  return TokError("multiclass is not allowed inside foreach loop");
3174  return ParseMultiClass();
3175  }
3176 }
3177 
3178 /// ParseObjectList
3179 /// ObjectList :== Object*
3180 bool TGParser::ParseObjectList(MultiClass *MC) {
3181  while (isObjectStart(Lex.getCode())) {
3182  if (ParseObject(MC))
3183  return true;
3184  }
3185  return false;
3186 }
3187 
3188 bool TGParser::ParseFile() {
3189  Lex.Lex(); // Prime the lexer.
3190  if (ParseObjectList()) return true;
3191 
3192  // If we have unread input at the end of the file, report it.
3193  if (Lex.getCode() == tgtok::Eof)
3194  return false;
3195 
3196  return TokError("Unexpected input at top level");
3197 }
3198 
3199 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3200 LLVM_DUMP_METHOD void RecordsEntry::dump() const {
3201  if (Loop)
3202  Loop->dump();
3203  if (Rec)
3204  Rec->dump();
3205 }
3206 
3207 LLVM_DUMP_METHOD void ForeachLoop::dump() const {
3208  errs() << "foreach " << IterVar->getAsString() << " = "
3209  << ListValue->getAsString() << " in {\n";
3210 
3211  for (const auto &E : Entries)
3212  E.dump();
3213 
3214  errs() << "}\n";
3215 }
3216 
3217 LLVM_DUMP_METHOD void MultiClass::dump() const {
3218  errs() << "Record:\n";
3219  Rec.dump();
3220 
3221  errs() << "Defs:\n";
3222  for (const auto &E : Entries)
3223  E.dump();
3224 }
3225 #endif
static BinOpInit * get(BinaryOp opc, Init *lhs, Init *rhs, RecTy *Type)
Definition: Record.cpp:825
unsigned getNumBits() const
Definition: Record.h:535
Represents a range in source code.
Definition: SMLoc.h:48
StringRef getName() const
Definition: Record.cpp:1985
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:645
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Init * getValue() const
Definition: Record.h:1406
SI Whole Quad Mode
This class represents lattice values for constants.
Definition: AllocatorList.h:23
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
Definition: Compiler.h:473
virtual std::string getAsUnquotedString() const
Convert this value to a string form, without adding quote markers.
Definition: Record.h:367
VarInit * IterVar
Definition: TGParser.h:61
static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF)
Definition: Execution.cpp:41
bool empty() const
Definition: Record.h:718
std::unique_ptr< ForeachLoop > Loop
Definition: TGParser.h:47
[AL, AH, CL] - Represent a list of defs
Definition: Record.h:661
virtual RecTy * getFieldType(StringInit *FieldName) const
This method is used to implement the FieldInit class.
Definition: Record.h:402
&#39;list<Ty>&#39; - Represent a list of values, all of which must be of the specified type.
Definition: Record.h:195
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
!op (X, Y) - Combine two inits.
Definition: Record.h:801
void push_back(const T &Elt)
Definition: SmallVector.h:211
AL - Represent a reference to a &#39;def&#39; in the description.
Definition: Record.h:1174
static Init * getListConcat(TypedInit *lhs, Init *rhs)
Definition: Record.cpp:868
static UnOpInit * get(UnaryOp opc, Init *lhs, RecTy *Type)
Definition: Record.cpp:693
std::unique_ptr< Record > Rec
Definition: TGParser.h:46
Init * Fold(Record *CurRec, bool IsFinal=false) const
Definition: Record.cpp:712
static Init * getStrConcat(Init *lhs, Init *rhs)
Definition: Record.cpp:852
static VarInit * get(StringRef VN, RecTy *T)
Definition: Record.cpp:1466
static CodeRecTy * get()
Definition: Record.h:150
virtual Init * getCastTo(RecTy *Ty) const =0
If this initializer is convertible to Ty, return an initializer whose type is-a Ty, generating a !cast operation if required.
&#39;{ a, b, c }&#39; - Represents an initializer for a BitsRecTy value.
Definition: Record.h:513
std::string getNameInitAsString() const
Definition: Record.h:1400
Init * Fold() const
Definition: Record.cpp:1683
static BitRecTy * get()
Definition: Record.h:110
bool isInvalid() const
Definition: TGParser.cpp:43
C::iterator addEntry(C &Container, StringRef InstallName)
static IntInit * get(int64_t V)
Definition: Record.cpp:460
static BitsInit * get(ArrayRef< Init *> Range)
Definition: Record.cpp:342
SMLoc Start
Definition: SMLoc.h:50
ArrayRef< std::pair< Record *, SMRange > > getSuperClasses() const
Definition: Record.h:1501
void addSuperClass(Record *R, SMRange Range)
Definition: Record.h:1574
Hexagon Hardware Loops
static BitsRecTy * get(unsigned Sz)
Definition: Record.cpp:84
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
This is the common super-class of types that have a specific, explicit, type.
Definition: Record.h:425
RecTy * getElementType() const
Definition: Record.h:208
static StringRecTy * get()
Definition: Record.h:186
ArrayRef< Init * > getTemplateArgs() const
Definition: Record.h:1495
virtual bool isComplete() const
This virtual method should be overridden by values that may not be completely specified yet...
Definition: Record.h:352
The access may reference the value stored in memory.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:266
virtual Init * convertInitializerBitRange(ArrayRef< unsigned > Bits) const
This method is used to implement the bitrange selection operator.
Definition: Record.h:387
ArrayRef< SMLoc > getLoc() const
Definition: Record.h:1484
&#39;bits<n>&#39; - Represent a fixed number of bits
Definition: Record.h:118
bool isTemplateArg(Init *Name) const
Definition: Record.h:1508
RecTy * getType() const
Definition: Record.h:1405
bool isSubClassOf(const Record *R) const
Definition: Record.h:1555
static CodeInit * get(StringRef, const SMLoc &Loc)
Definition: Record.cpp:517
virtual Init * convertInitListSlice(ArrayRef< unsigned > Elements) const
This method is used to implement the list slice selection operator.
Definition: Record.h:395
ArrayRef< RecordVal > getValues() const
Definition: Record.h:1499
std::vector< RecordsEntry > Entries
Definition: TGParser.h:79
static Init * QualifyName(Record &CurRec, MultiClass *CurMultiClass, Init *Name, StringRef Scoper)
Return an Init with a qualifier prefix referring to CurRec&#39;s name.
Definition: TGParser.cpp:114
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
RecTy * getType() const
Definition: Record.h:441
Init * getElement(unsigned i) const
Definition: Record.h:686
Resolve arbitrary mappings.
Definition: Record.h:1884
void dump() const
Definition: Record.cpp:2115
Init * getNameInit() const
Definition: Record.h:1398
bool isClass() const
Definition: Record.h:1493
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
virtual bool isConcrete() const
Is this a concrete and fully resolved value without any references or stuck operations? Unset values are concrete.
Definition: Record.h:356
void resolveReferences()
If there are any field references that refer to fields that have been filled in, we can propagate the...
Definition: Record.cpp:2103
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:148
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
void set(Init *Key, Init *Value)
Definition: Record.h:1898
"foo" - Represent an initialization by a string value.
Definition: Record.h:594
RecordsEntry - Can be either a record or a foreach loop.
Definition: TGParser.h:45
const std::string getNameInitAsString() const
Definition: Record.h:1478
static DagInit * get(Init *V, StringInit *VN, ArrayRef< Init *> ArgRange, ArrayRef< StringInit *> NameRange)
Definition: Record.cpp:1894
&#39;string&#39; - Represent an string value
Definition: Record.h:176
static BitInit * get(bool V)
Definition: Record.cpp:311
Init * ListValue
Definition: TGParser.h:62
bool setValue(Init *V)
Definition: Record.cpp:1989
size_t size() const
Definition: SmallVector.h:52
static wasm::ValType getType(const TargetRegisterClass *RC)
static bool isObjectStart(tgtok::TokKind K)
isObjectStart - Return true if this is a valid first token for an Object.
Definition: TGParser.cpp:482
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static bool checkBitsConcrete(Record &R, const RecordVal &RV)
Definition: TGParser.cpp:71
static RecordRecTy * get(ArrayRef< Record *> Classes)
Get the record type with the given non-redundant list of superclasses.
Definition: Record.cpp:157
ForeachLoop - Record the iteration state associated with a for loop.
Definition: TGParser.h:59
static FieldInit * get(Init *R, StringInit *FN)
Definition: Record.cpp:1707
virtual Init * resolveReferences(Resolver &R) const
This method is used by classes that refer to other variables which may not be defined at the time the...
Definition: Record.h:410
void addTemplateArg(Init *Name)
Definition: Record.h:1532
virtual bool typeIsA(const RecTy *RHS) const
Return true if &#39;this&#39; type is equal to or a subtype of RHS.
Definition: Record.cpp:74
static Init * QualifiedNameOfImplicitName(Record &Rec, MultiClass *MC=nullptr)
Return the qualified version of the implicit &#39;NAME&#39; template argument.
Definition: TGParser.cpp:131
const RecordVal * getValue(const Init *Name) const
Definition: Record.h:1514
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
This is a utility class that provides an abstraction for the common functionality between Instruction...
Definition: Operator.h:30
static StringInit * get(StringRef)
Definition: Record.cpp:533
void dump() const
SmallVector< Init *, 4 > TemplateArgs
Definition: TGParser.cpp:39
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:374
CHAIN = SC CHAIN, Imm128 - System call.
SmallVector< Init *, 4 > TemplateArgs
Definition: TGParser.cpp:49
static VarDefInit * get(Record *Class, ArrayRef< Init *> Args)
Definition: Record.cpp:1593
static IsAOpInit * get(RecTy *CheckType, Init *Expr)
Definition: Record.cpp:1338
SMLoc End
Definition: SMLoc.h:50
void dump() const
RecordRecTy * getType()
Definition: Record.cpp:2035
void removeValue(Init *Name)
Definition: Record.h:1542
iterator insert(iterator I, T &&Elt)
Definition: SmallVector.h:471
static FoldOpInit * get(Init *Start, Init *List, Init *A, Init *B, Init *Expr, RecTy *Type)
Definition: Record.cpp:1272
Init * getBit(unsigned Bit) const override
This method is used to return the initializer for the specified bit.
Definition: Record.h:557
void appendLoc(SMLoc Loc)
Definition: Record.h:1485
bool typeIsConvertibleTo(const RecTy *RHS) const override
Return true if all values of &#39;this&#39; type can be converted to the specified type.
Definition: Record.cpp:134
Init * getNameInit() const
Definition: Record.h:1474
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
static UnsetInit * get()
Definition: Record.cpp:298
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:465
SmallVector< Init *, 16 > Elements
Definition: TGParser.h:74
Do not resolve anything, but keep track of whether a given variable was referenced.
Definition: Record.h:1972
static DagRecTy * get()
Definition: Record.h:228
void addValue(const RecordVal &RV)
Definition: Record.h:1537
const NodeList & List
Definition: RDFGraph.cpp:201
static TernOpInit * get(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs, RecTy *Type)
Definition: Record.cpp:1054
#define I(x, y, z)
Definition: MD5.cpp:58
RecTy * resolveTypes(RecTy *T1, RecTy *T2)
Find a common type that T1 and T2 convert to.
Definition: Record.cpp:262
&#39;Opcode&#39; - Represent a reference to an entire variable object.
Definition: Record.h:1068
bool ParseFile()
ParseFile - Main entrypoint for parsing a tblgen file.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
static ListRecTy * get(RecTy *T)
Definition: Record.h:207
Init * Fold(Record *CurRec) const
Definition: Record.cpp:1818
static ListInit * get(ArrayRef< Init *> Range, RecTy *EltTy)
Definition: Record.cpp:570
virtual bool typeIsConvertibleTo(const RecTy *RHS) const
Return true if all values of &#39;this&#39; type can be converted to the specified type.
Definition: Record.cpp:69
StringRef getValue() const
Definition: Record.h:610
&#39;dag&#39; - Represent a dag fragment
Definition: Record.h:218
StringRef getName() const
Definition: Record.h:1472
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
virtual std::string getAsString() const =0
Convert this value to a string form.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
std::vector< RecordsEntry > Entries
Definition: TGParser.h:63
static CondOpInit * get(ArrayRef< Init *> C, ArrayRef< Init *> V, RecTy *Type)
Definition: Record.cpp:1770
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
void dump() const
virtual std::string getAsString() const =0
Represents a location in source code.
Definition: SMLoc.h:23
ListRecTy * getListTy()
Returns the type representing list<this>.
Definition: Record.cpp:63
Init * getNameInit() const
Definition: Record.h:1086
static void checkConcrete(Record &R)
Definition: TGParser.cpp:90
Init * Fold(Record *CurRec) const
Definition: Record.cpp:1731
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:143
static IntRecTy * get()
Definition: Record.h:168
void PrintNote(ArrayRef< SMLoc > NoteLoc, const Twine &Msg)
Definition: Error.cpp:42
void PrintError(ArrayRef< SMLoc > ErrorLoc, const Twine &Msg)
Definition: Error.cpp:56