Bug Summary

File:lib/TableGen/TGParser.cpp
Warning:line 1737, column 38
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name TGParser.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/lib/TableGen -I /build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn362543/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/lib/TableGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn362543=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-06-05-060531-1271-1 -x c++ /build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp -faddrsig
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"
21#include "llvm/Support/ErrorHandling.h"
22#include "llvm/Support/raw_ostream.h"
23#include "llvm/TableGen/Record.h"
24#include <algorithm>
25#include <cassert>
26#include <cstdint>
27
28using namespace llvm;
29
30//===----------------------------------------------------------------------===//
31// Support Code for the Semantic Actions.
32//===----------------------------------------------------------------------===//
33
34namespace llvm {
35
36struct SubClassReference {
37 SMRange RefRange;
38 Record *Rec;
39 SmallVector<Init*, 4> TemplateArgs;
40
41 SubClassReference() : Rec(nullptr) {}
42
43 bool isInvalid() const { return Rec == nullptr; }
44};
45
46struct SubMultiClassReference {
47 SMRange RefRange;
48 MultiClass *MC;
49 SmallVector<Init*, 4> TemplateArgs;
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)
58LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void SubMultiClassReference::dump() const {
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
71static 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
90static 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.
114static Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass,
115 Init *Name, StringRef Scoper) {
116 Init *NewName =
117 BinOpInit::getStrConcat(CurRec.getNameInit(), StringInit::get(Scoper));
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.
131static Init *QualifiedNameOfImplicitName(Record &Rec,
132 MultiClass *MC = nullptr) {
133 return QualifyName(Rec, MC, StringInit::get("NAME"), MC ? "::" : ":");
134}
135
136static Init *QualifiedNameOfImplicitName(MultiClass *MC) {
137 return QualifiedNameOfImplicitName(MC->Rec, MC);
138}
139
140bool 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.
159bool 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.
228bool 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 =
267 VarInit::get(QualifiedNameOfImplicitName(*CurRec), StringRecTy::get());
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.
276 ArrayRef<std::pair<Record *, SMRange>> SCs = SC->getSuperClasses();
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
291bool 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.
306bool 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(
335 QualifiedNameOfImplicitName(SMC),
336 VarInit::get(QualifiedNameOfImplicitName(CurMC), StringRecTy::get()));
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).
344bool TGParser::addEntry(RecordsEntry E) {
345 assert(!E.Rec || !E.Loop)((!E.Rec || !E.Loop) ? static_cast<void> (0) : __assert_fail
("!E.Rec || !E.Loop", "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 345, __PRETTY_FUNCTION__))
;
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.
371bool 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.
408bool 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);
423 Rec->resolveReferences(R);
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.
437bool 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?")((Rec->getTemplateArgs().empty() && "How'd this get template args?"
) ? static_cast<void> (0) : __assert_fail ("Rec->getTemplateArgs().empty() && \"How'd this get template args?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 459, __PRETTY_FUNCTION__))
;
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.
482static bool isObjectStart(tgtok::TokKind K) {
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///
494Init *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())
520 Name = BinOpInit::getStrConcat(VarInit::get(NameStr, StringRecTy::get()),
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///
532Record *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///
557MultiClass *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///
577SubClassReference TGParser::
578ParseSubClassReference(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///
627SubMultiClassReference TGParser::
628ParseSubMultiClassReference(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
669bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
670 TypedInit *FirstItem) {
671 Init *CurVal = FirstItem;
672 if (!CurVal)
673 CurVal = ParseValue(nullptr);
674
675 IntInit *II = dyn_cast_or_null<IntInit>(CurVal);
676 if (!II)
677 return TokError("expected integer or bitrange");
678
679 int64_t Start = II->getValue();
680 int64_t End;
681
682 if (Start < 0)
683 return TokError("invalid range, cannot be negative");
684
685 switch (Lex.getCode()) {
686 default:
687 Ranges.push_back(Start);
688 return false;
689 case tgtok::minus: {
690 Lex.Lex(); // eat
691
692 Init *I_End = ParseValue(nullptr);
693 IntInit *II_End = dyn_cast_or_null<IntInit>(I_End);
694 if (!II_End) {
695 TokError("expected integer value as end of range");
696 return true;
697 }
698
699 End = II_End->getValue();
700 break;
701 }
702 case tgtok::IntVal: {
703 End = -Lex.getCurIntVal();
704 Lex.Lex();
705 break;
706 }
707 }
708 if (End < 0)
709 return TokError("invalid range, cannot be negative");
710
711 // Add to the range.
712 if (Start < End)
713 for (; Start <= End; ++Start)
714 Ranges.push_back(Start);
715 else
716 for (; Start >= End; --Start)
717 Ranges.push_back(Start);
718 return false;
719}
720
721/// ParseRangeList - Parse a list of scalars and ranges into scalar values.
722///
723/// RangeList ::= RangePiece (',' RangePiece)*
724///
725void TGParser::ParseRangeList(SmallVectorImpl<unsigned> &Result) {
726 // Parse the first piece.
727 if (ParseRangePiece(Result)) {
728 Result.clear();
729 return;
730 }
731 while (Lex.getCode() == tgtok::comma) {
732 Lex.Lex(); // Eat the comma.
733
734 // Parse the next range piece.
735 if (ParseRangePiece(Result)) {
736 Result.clear();
737 return;
738 }
739 }
740}
741
742/// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
743/// OptionalRangeList ::= '<' RangeList '>'
744/// OptionalRangeList ::= /*empty*/
745bool TGParser::ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges) {
746 if (Lex.getCode() != tgtok::less)
747 return false;
748
749 SMLoc StartLoc = Lex.getLoc();
750 Lex.Lex(); // eat the '<'
751
752 // Parse the range list.
753 ParseRangeList(Ranges);
754 if (Ranges.empty()) return true;
755
756 if (Lex.getCode() != tgtok::greater) {
757 TokError("expected '>' at end of range list");
758 return Error(StartLoc, "to match this '<'");
759 }
760 Lex.Lex(); // eat the '>'.
761 return false;
762}
763
764/// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
765/// OptionalBitList ::= '{' RangeList '}'
766/// OptionalBitList ::= /*empty*/
767bool TGParser::ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges) {
768 if (Lex.getCode() != tgtok::l_brace)
769 return false;
770
771 SMLoc StartLoc = Lex.getLoc();
772 Lex.Lex(); // eat the '{'
773
774 // Parse the range list.
775 ParseRangeList(Ranges);
776 if (Ranges.empty()) return true;
777
778 if (Lex.getCode() != tgtok::r_brace) {
779 TokError("expected '}' at end of bit list");
780 return Error(StartLoc, "to match this '{'");
781 }
782 Lex.Lex(); // eat the '}'.
783 return false;
784}
785
786/// ParseType - Parse and return a tblgen type. This returns null on error.
787///
788/// Type ::= STRING // string type
789/// Type ::= CODE // code type
790/// Type ::= BIT // bit type
791/// Type ::= BITS '<' INTVAL '>' // bits<x> type
792/// Type ::= INT // int type
793/// Type ::= LIST '<' Type '>' // list<x> type
794/// Type ::= DAG // dag type
795/// Type ::= ClassID // Record Type
796///
797RecTy *TGParser::ParseType() {
798 switch (Lex.getCode()) {
799 default: TokError("Unknown token when expecting a type"); return nullptr;
800 case tgtok::String: Lex.Lex(); return StringRecTy::get();
801 case tgtok::Code: Lex.Lex(); return CodeRecTy::get();
802 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
803 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
804 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
805 case tgtok::Id:
806 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
807 TokError("unknown class name");
808 return nullptr;
809 case tgtok::Bits: {
810 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
811 TokError("expected '<' after bits type");
812 return nullptr;
813 }
814 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
815 TokError("expected integer in bits<n> type");
816 return nullptr;
817 }
818 uint64_t Val = Lex.getCurIntVal();
819 if (Lex.Lex() != tgtok::greater) { // Eat count.
820 TokError("expected '>' at end of bits<n> type");
821 return nullptr;
822 }
823 Lex.Lex(); // Eat '>'
824 return BitsRecTy::get(Val);
825 }
826 case tgtok::List: {
827 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
828 TokError("expected '<' after list type");
829 return nullptr;
830 }
831 Lex.Lex(); // Eat '<'
832 RecTy *SubType = ParseType();
833 if (!SubType) return nullptr;
834
835 if (Lex.getCode() != tgtok::greater) {
836 TokError("expected '>' at end of list<ty> type");
837 return nullptr;
838 }
839 Lex.Lex(); // Eat '>'
840 return ListRecTy::get(SubType);
841 }
842 }
843}
844
845/// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
846/// has already been read.
847Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMLoc NameLoc,
848 IDParseMode Mode) {
849 if (CurRec) {
850 if (const RecordVal *RV = CurRec->getValue(Name))
851 return VarInit::get(Name, RV->getType());
852 }
853
854 if ((CurRec && CurRec->isClass()) || CurMultiClass) {
855 Init *TemplateArgName;
856 if (CurMultiClass) {
857 TemplateArgName =
858 QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
859 } else
860 TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
861
862 Record *TemplateRec = CurMultiClass ? &CurMultiClass->Rec : CurRec;
863 if (TemplateRec->isTemplateArg(TemplateArgName)) {
864 const RecordVal *RV = TemplateRec->getValue(TemplateArgName);
865 assert(RV && "Template arg doesn't exist??")((RV && "Template arg doesn't exist??") ? static_cast
<void> (0) : __assert_fail ("RV && \"Template arg doesn't exist??\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 865, __PRETTY_FUNCTION__))
;
866 return VarInit::get(TemplateArgName, RV->getType());
867 } else if (Name->getValue() == "NAME") {
868 return VarInit::get(TemplateArgName, StringRecTy::get());
869 }
870 }
871
872 // If this is in a foreach loop, make sure it's not a loop iterator
873 for (const auto &L : Loops) {
874 VarInit *IterVar = dyn_cast<VarInit>(L->IterVar);
875 if (IterVar && IterVar->getNameInit() == Name)
876 return IterVar;
877 }
878
879 if (Mode == ParseNameMode)
880 return Name;
881
882 if (Init *I = Records.getGlobal(Name->getValue()))
883 return I;
884
885 // Allow self-references of concrete defs, but delay the lookup so that we
886 // get the correct type.
887 if (CurRec && !CurRec->isClass() && !CurMultiClass &&
888 CurRec->getNameInit() == Name)
889 return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType());
890
891 Error(NameLoc, "Variable not defined: '" + Name->getValue() + "'");
892 return nullptr;
893}
894
895/// ParseOperation - Parse an operator. This returns null on error.
896///
897/// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
898///
899Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
900 switch (Lex.getCode()) {
1
Control jumps to 'case XCond:' at line 1506
901 default:
902 TokError("unknown operation");
903 return nullptr;
904 case tgtok::XHead:
905 case tgtok::XTail:
906 case tgtok::XSize:
907 case tgtok::XEmpty:
908 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
909 UnOpInit::UnaryOp Code;
910 RecTy *Type = nullptr;
911
912 switch (Lex.getCode()) {
913 default: llvm_unreachable("Unhandled code!")::llvm::llvm_unreachable_internal("Unhandled code!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 913)
;
914 case tgtok::XCast:
915 Lex.Lex(); // eat the operation
916 Code = UnOpInit::CAST;
917
918 Type = ParseOperatorType();
919
920 if (!Type) {
921 TokError("did not get type for unary operator");
922 return nullptr;
923 }
924
925 break;
926 case tgtok::XHead:
927 Lex.Lex(); // eat the operation
928 Code = UnOpInit::HEAD;
929 break;
930 case tgtok::XTail:
931 Lex.Lex(); // eat the operation
932 Code = UnOpInit::TAIL;
933 break;
934 case tgtok::XSize:
935 Lex.Lex();
936 Code = UnOpInit::SIZE;
937 Type = IntRecTy::get();
938 break;
939 case tgtok::XEmpty:
940 Lex.Lex(); // eat the operation
941 Code = UnOpInit::EMPTY;
942 Type = IntRecTy::get();
943 break;
944 }
945 if (Lex.getCode() != tgtok::l_paren) {
946 TokError("expected '(' after unary operator");
947 return nullptr;
948 }
949 Lex.Lex(); // eat the '('
950
951 Init *LHS = ParseValue(CurRec);
952 if (!LHS) return nullptr;
953
954 if (Code == UnOpInit::HEAD ||
955 Code == UnOpInit::TAIL ||
956 Code == UnOpInit::EMPTY) {
957 ListInit *LHSl = dyn_cast<ListInit>(LHS);
958 StringInit *LHSs = dyn_cast<StringInit>(LHS);
959 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
960 if (!LHSl && !LHSs && !LHSt) {
961 TokError("expected list or string type argument in unary operator");
962 return nullptr;
963 }
964 if (LHSt) {
965 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
966 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
967 if (!LType && !SType) {
968 TokError("expected list or string type argument in unary operator");
969 return nullptr;
970 }
971 }
972
973 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL ||
974 Code == UnOpInit::SIZE) {
975 if (!LHSl && !LHSt) {
976 TokError("expected list type argument in unary operator");
977 return nullptr;
978 }
979 }
980
981 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
982 if (LHSl && LHSl->empty()) {
983 TokError("empty list argument in unary operator");
984 return nullptr;
985 }
986 if (LHSl) {
987 Init *Item = LHSl->getElement(0);
988 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
989 if (!Itemt) {
990 TokError("untyped list element in unary operator");
991 return nullptr;
992 }
993 Type = (Code == UnOpInit::HEAD) ? Itemt->getType()
994 : ListRecTy::get(Itemt->getType());
995 } else {
996 assert(LHSt && "expected list type argument in unary operator")((LHSt && "expected list type argument in unary operator"
) ? static_cast<void> (0) : __assert_fail ("LHSt && \"expected list type argument in unary operator\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 996, __PRETTY_FUNCTION__))
;
997 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
998 if (!LType) {
999 TokError("expected list type argument in unary operator");
1000 return nullptr;
1001 }
1002 Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType;
1003 }
1004 }
1005 }
1006
1007 if (Lex.getCode() != tgtok::r_paren) {
1008 TokError("expected ')' in unary operator");
1009 return nullptr;
1010 }
1011 Lex.Lex(); // eat the ')'
1012 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec);
1013 }
1014
1015 case tgtok::XIsA: {
1016 // Value ::= !isa '<' Type '>' '(' Value ')'
1017 Lex.Lex(); // eat the operation
1018
1019 RecTy *Type = ParseOperatorType();
1020 if (!Type)
1021 return nullptr;
1022
1023 if (Lex.getCode() != tgtok::l_paren) {
1024 TokError("expected '(' after type of !isa");
1025 return nullptr;
1026 }
1027 Lex.Lex(); // eat the '('
1028
1029 Init *LHS = ParseValue(CurRec);
1030 if (!LHS)
1031 return nullptr;
1032
1033 if (Lex.getCode() != tgtok::r_paren) {
1034 TokError("expected ')' in !isa");
1035 return nullptr;
1036 }
1037 Lex.Lex(); // eat the ')'
1038
1039 return (IsAOpInit::get(Type, LHS))->Fold();
1040 }
1041
1042 case tgtok::XConcat:
1043 case tgtok::XADD:
1044 case tgtok::XMUL:
1045 case tgtok::XAND:
1046 case tgtok::XOR:
1047 case tgtok::XSRA:
1048 case tgtok::XSRL:
1049 case tgtok::XSHL:
1050 case tgtok::XEq:
1051 case tgtok::XNe:
1052 case tgtok::XLe:
1053 case tgtok::XLt:
1054 case tgtok::XGe:
1055 case tgtok::XGt:
1056 case tgtok::XListConcat:
1057 case tgtok::XListSplat:
1058 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
1059 tgtok::TokKind OpTok = Lex.getCode();
1060 SMLoc OpLoc = Lex.getLoc();
1061 Lex.Lex(); // eat the operation
1062
1063 BinOpInit::BinaryOp Code;
1064 switch (OpTok) {
1065 default: llvm_unreachable("Unhandled code!")::llvm::llvm_unreachable_internal("Unhandled code!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 1065)
;
1066 case tgtok::XConcat: Code = BinOpInit::CONCAT; break;
1067 case tgtok::XADD: Code = BinOpInit::ADD; break;
1068 case tgtok::XMUL: Code = BinOpInit::MUL; break;
1069 case tgtok::XAND: Code = BinOpInit::AND; break;
1070 case tgtok::XOR: Code = BinOpInit::OR; break;
1071 case tgtok::XSRA: Code = BinOpInit::SRA; break;
1072 case tgtok::XSRL: Code = BinOpInit::SRL; break;
1073 case tgtok::XSHL: Code = BinOpInit::SHL; break;
1074 case tgtok::XEq: Code = BinOpInit::EQ; break;
1075 case tgtok::XNe: Code = BinOpInit::NE; break;
1076 case tgtok::XLe: Code = BinOpInit::LE; break;
1077 case tgtok::XLt: Code = BinOpInit::LT; break;
1078 case tgtok::XGe: Code = BinOpInit::GE; break;
1079 case tgtok::XGt: Code = BinOpInit::GT; break;
1080 case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break;
1081 case tgtok::XListSplat: Code = BinOpInit::LISTSPLAT; break;
1082 case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break;
1083 }
1084
1085 RecTy *Type = nullptr;
1086 RecTy *ArgType = nullptr;
1087 switch (OpTok) {
1088 default:
1089 llvm_unreachable("Unhandled code!")::llvm::llvm_unreachable_internal("Unhandled code!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 1089)
;
1090 case tgtok::XConcat:
1091 Type = DagRecTy::get();
1092 ArgType = DagRecTy::get();
1093 break;
1094 case tgtok::XAND:
1095 case tgtok::XOR:
1096 case tgtok::XSRA:
1097 case tgtok::XSRL:
1098 case tgtok::XSHL:
1099 case tgtok::XADD:
1100 case tgtok::XMUL:
1101 Type = IntRecTy::get();
1102 ArgType = IntRecTy::get();
1103 break;
1104 case tgtok::XEq:
1105 case tgtok::XNe:
1106 Type = BitRecTy::get();
1107 // ArgType for Eq / Ne is not known at this point
1108 break;
1109 case tgtok::XLe:
1110 case tgtok::XLt:
1111 case tgtok::XGe:
1112 case tgtok::XGt:
1113 Type = BitRecTy::get();
1114 ArgType = IntRecTy::get();
1115 break;
1116 case tgtok::XListConcat:
1117 // We don't know the list type until we parse the first argument
1118 ArgType = ItemType;
1119 break;
1120 case tgtok::XListSplat:
1121 // Can't do any typechecking until we parse the first argument.
1122 break;
1123 case tgtok::XStrConcat:
1124 Type = StringRecTy::get();
1125 ArgType = StringRecTy::get();
1126 break;
1127 }
1128
1129 if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) {
1130 Error(OpLoc, Twine("expected value of type '") +
1131 ItemType->getAsString() + "', got '" +
1132 Type->getAsString() + "'");
1133 return nullptr;
1134 }
1135
1136 if (Lex.getCode() != tgtok::l_paren) {
1137 TokError("expected '(' after binary operator");
1138 return nullptr;
1139 }
1140 Lex.Lex(); // eat the '('
1141
1142 SmallVector<Init*, 2> InitList;
1143
1144 for (;;) {
1145 SMLoc InitLoc = Lex.getLoc();
1146 InitList.push_back(ParseValue(CurRec, ArgType));
1147 if (!InitList.back()) return nullptr;
1148
1149 // All BinOps require their arguments to be of compatible types.
1150 TypedInit *TI = dyn_cast<TypedInit>(InitList.back());
1151 if (!ArgType) {
1152 ArgType = TI->getType();
1153
1154 switch (Code) {
1155 case BinOpInit::LISTCONCAT:
1156 if (!isa<ListRecTy>(ArgType)) {
1157 Error(InitLoc, Twine("expected a list, got value of type '") +
1158 ArgType->getAsString() + "'");
1159 return nullptr;
1160 }
1161 break;
1162 case BinOpInit::LISTSPLAT:
1163 if (ItemType && InitList.size() == 1) {
1164 if (!isa<ListRecTy>(ItemType)) {
1165 Error(OpLoc,
1166 Twine("expected output type to be a list, got type '") +
1167 ItemType->getAsString() + "'");
1168 return nullptr;
1169 }
1170 if (!ArgType->getListTy()->typeIsConvertibleTo(ItemType)) {
1171 Error(OpLoc, Twine("expected first arg type to be '") +
1172 ArgType->getAsString() +
1173 "', got value of type '" +
1174 cast<ListRecTy>(ItemType)
1175 ->getElementType()
1176 ->getAsString() +
1177 "'");
1178 return nullptr;
1179 }
1180 }
1181 if (InitList.size() == 2 && !isa<IntRecTy>(ArgType)) {
1182 Error(InitLoc, Twine("expected second parameter to be an int, got "
1183 "value of type '") +
1184 ArgType->getAsString() + "'");
1185 return nullptr;
1186 }
1187 ArgType = nullptr; // Broken invariant: types not identical.
1188 break;
1189 case BinOpInit::EQ:
1190 case BinOpInit::NE:
1191 if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) &&
1192 !ArgType->typeIsConvertibleTo(StringRecTy::get())) {
1193 Error(InitLoc, Twine("expected int, bits, or string; got value of "
1194 "type '") + ArgType->getAsString() + "'");
1195 return nullptr;
1196 }
1197 break;
1198 default: llvm_unreachable("other ops have fixed argument types")::llvm::llvm_unreachable_internal("other ops have fixed argument types"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 1198)
;
1199 }
1200 } else {
1201 RecTy *Resolved = resolveTypes(ArgType, TI->getType());
1202 if (!Resolved) {
1203 Error(InitLoc, Twine("expected value of type '") +
1204 ArgType->getAsString() + "', got '" +
1205 TI->getType()->getAsString() + "'");
1206 return nullptr;
1207 }
1208 if (Code != BinOpInit::ADD && Code != BinOpInit::AND &&
1209 Code != BinOpInit::OR && Code != BinOpInit::SRA &&
1210 Code != BinOpInit::SRL && Code != BinOpInit::SHL &&
1211 Code != BinOpInit::MUL)
1212 ArgType = Resolved;
1213 }
1214
1215 if (Lex.getCode() != tgtok::comma)
1216 break;
1217 Lex.Lex(); // eat the ','
1218 }
1219
1220 if (Lex.getCode() != tgtok::r_paren) {
1221 TokError("expected ')' in operator");
1222 return nullptr;
1223 }
1224 Lex.Lex(); // eat the ')'
1225
1226 // listconcat returns a list with type of the argument.
1227 if (Code == BinOpInit::LISTCONCAT)
1228 Type = ArgType;
1229 // listsplat returns a list of type of the *first* argument.
1230 if (Code == BinOpInit::LISTSPLAT)
1231 Type = cast<TypedInit>(InitList.front())->getType()->getListTy();
1232
1233 // We allow multiple operands to associative operators like !strconcat as
1234 // shorthand for nesting them.
1235 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT ||
1236 Code == BinOpInit::CONCAT || Code == BinOpInit::ADD ||
1237 Code == BinOpInit::AND || Code == BinOpInit::OR ||
1238 Code == BinOpInit::MUL) {
1239 while (InitList.size() > 2) {
1240 Init *RHS = InitList.pop_back_val();
1241 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec);
1242 InitList.back() = RHS;
1243 }
1244 }
1245
1246 if (InitList.size() == 2)
1247 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
1248 ->Fold(CurRec);
1249
1250 Error(OpLoc, "expected two operands to operator");
1251 return nullptr;
1252 }
1253
1254 case tgtok::XForEach: { // Value ::= !foreach '(' Id ',' Value ',' Value ')'
1255 SMLoc OpLoc = Lex.getLoc();
1256 Lex.Lex(); // eat the operation
1257 if (Lex.getCode() != tgtok::l_paren) {
1258 TokError("expected '(' after !foreach");
1259 return nullptr;
1260 }
1261
1262 if (Lex.Lex() != tgtok::Id) { // eat the '('
1263 TokError("first argument of !foreach must be an identifier");
1264 return nullptr;
1265 }
1266
1267 Init *LHS = StringInit::get(Lex.getCurStrVal());
1268
1269 if (CurRec && CurRec->getValue(LHS)) {
1270 TokError((Twine("iteration variable '") + LHS->getAsString() +
1271 "' already defined")
1272 .str());
1273 return nullptr;
1274 }
1275
1276 if (Lex.Lex() != tgtok::comma) { // eat the id
1277 TokError("expected ',' in ternary operator");
1278 return nullptr;
1279 }
1280 Lex.Lex(); // eat the ','
1281
1282 Init *MHS = ParseValue(CurRec);
1283 if (!MHS)
1284 return nullptr;
1285
1286 if (Lex.getCode() != tgtok::comma) {
1287 TokError("expected ',' in ternary operator");
1288 return nullptr;
1289 }
1290 Lex.Lex(); // eat the ','
1291
1292 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1293 if (!MHSt) {
1294 TokError("could not get type of !foreach input");
1295 return nullptr;
1296 }
1297
1298 RecTy *InEltType = nullptr;
1299 RecTy *OutEltType = nullptr;
1300 bool IsDAG = false;
1301
1302 if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) {
1303 InEltType = InListTy->getElementType();
1304 if (ItemType) {
1305 if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) {
1306 OutEltType = OutListTy->getElementType();
1307 } else {
1308 Error(OpLoc,
1309 "expected value of type '" + Twine(ItemType->getAsString()) +
1310 "', but got !foreach of list type");
1311 return nullptr;
1312 }
1313 }
1314 } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) {
1315 InEltType = InDagTy;
1316 if (ItemType && !isa<DagRecTy>(ItemType)) {
1317 Error(OpLoc,
1318 "expected value of type '" + Twine(ItemType->getAsString()) +
1319 "', but got !foreach of dag type");
1320 return nullptr;
1321 }
1322 IsDAG = true;
1323 } else {
1324 TokError("!foreach must have list or dag input");
1325 return nullptr;
1326 }
1327
1328 // We need to create a temporary record to provide a scope for the iteration
1329 // variable while parsing top-level foreach's.
1330 std::unique_ptr<Record> ParseRecTmp;
1331 Record *ParseRec = CurRec;
1332 if (!ParseRec) {
1333 ParseRecTmp = make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1334 ParseRec = ParseRecTmp.get();
1335 }
1336
1337 ParseRec->addValue(RecordVal(LHS, InEltType, false));
1338 Init *RHS = ParseValue(ParseRec, OutEltType);
1339 ParseRec->removeValue(LHS);
1340 if (!RHS)
1341 return nullptr;
1342
1343 if (Lex.getCode() != tgtok::r_paren) {
1344 TokError("expected ')' in binary operator");
1345 return nullptr;
1346 }
1347 Lex.Lex(); // eat the ')'
1348
1349 RecTy *OutType;
1350 if (IsDAG) {
1351 OutType = InEltType;
1352 } else {
1353 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1354 if (!RHSt) {
1355 TokError("could not get type of !foreach result");
1356 return nullptr;
1357 }
1358 OutType = RHSt->getType()->getListTy();
1359 }
1360
1361 return (TernOpInit::get(TernOpInit::FOREACH, LHS, MHS, RHS, OutType))
1362 ->Fold(CurRec);
1363 }
1364
1365 case tgtok::XDag:
1366 case tgtok::XIf:
1367 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1368 TernOpInit::TernaryOp Code;
1369 RecTy *Type = nullptr;
1370
1371 tgtok::TokKind LexCode = Lex.getCode();
1372 Lex.Lex(); // eat the operation
1373 switch (LexCode) {
1374 default: llvm_unreachable("Unhandled code!")::llvm::llvm_unreachable_internal("Unhandled code!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 1374)
;
1375 case tgtok::XDag:
1376 Code = TernOpInit::DAG;
1377 Type = DagRecTy::get();
1378 ItemType = nullptr;
1379 break;
1380 case tgtok::XIf:
1381 Code = TernOpInit::IF;
1382 break;
1383 case tgtok::XSubst:
1384 Code = TernOpInit::SUBST;
1385 break;
1386 }
1387 if (Lex.getCode() != tgtok::l_paren) {
1388 TokError("expected '(' after ternary operator");
1389 return nullptr;
1390 }
1391 Lex.Lex(); // eat the '('
1392
1393 Init *LHS = ParseValue(CurRec);
1394 if (!LHS) return nullptr;
1395
1396 if (Lex.getCode() != tgtok::comma) {
1397 TokError("expected ',' in ternary operator");
1398 return nullptr;
1399 }
1400 Lex.Lex(); // eat the ','
1401
1402 SMLoc MHSLoc = Lex.getLoc();
1403 Init *MHS = ParseValue(CurRec, ItemType);
1404 if (!MHS)
1405 return nullptr;
1406
1407 if (Lex.getCode() != tgtok::comma) {
1408 TokError("expected ',' in ternary operator");
1409 return nullptr;
1410 }
1411 Lex.Lex(); // eat the ','
1412
1413 SMLoc RHSLoc = Lex.getLoc();
1414 Init *RHS = ParseValue(CurRec, ItemType);
1415 if (!RHS)
1416 return nullptr;
1417
1418 if (Lex.getCode() != tgtok::r_paren) {
1419 TokError("expected ')' in binary operator");
1420 return nullptr;
1421 }
1422 Lex.Lex(); // eat the ')'
1423
1424 switch (LexCode) {
1425 default: llvm_unreachable("Unhandled code!")::llvm::llvm_unreachable_internal("Unhandled code!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 1425)
;
1426 case tgtok::XDag: {
1427 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1428 if (!MHSt && !isa<UnsetInit>(MHS)) {
1429 Error(MHSLoc, "could not determine type of the child list in !dag");
1430 return nullptr;
1431 }
1432 if (MHSt && !isa<ListRecTy>(MHSt->getType())) {
1433 Error(MHSLoc, Twine("expected list of children, got type '") +
1434 MHSt->getType()->getAsString() + "'");
1435 return nullptr;
1436 }
1437
1438 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1439 if (!RHSt && !isa<UnsetInit>(RHS)) {
1440 Error(RHSLoc, "could not determine type of the name list in !dag");
1441 return nullptr;
1442 }
1443 if (RHSt && StringRecTy::get()->getListTy() != RHSt->getType()) {
1444 Error(RHSLoc, Twine("expected list<string>, got type '") +
1445 RHSt->getType()->getAsString() + "'");
1446 return nullptr;
1447 }
1448
1449 if (!MHSt && !RHSt) {
1450 Error(MHSLoc,
1451 "cannot have both unset children and unset names in !dag");
1452 return nullptr;
1453 }
1454 break;
1455 }
1456 case tgtok::XIf: {
1457 RecTy *MHSTy = nullptr;
1458 RecTy *RHSTy = nullptr;
1459
1460 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1461 MHSTy = MHSt->getType();
1462 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1463 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1464 if (isa<BitInit>(MHS))
1465 MHSTy = BitRecTy::get();
1466
1467 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1468 RHSTy = RHSt->getType();
1469 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1470 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1471 if (isa<BitInit>(RHS))
1472 RHSTy = BitRecTy::get();
1473
1474 // For UnsetInit, it's typed from the other hand.
1475 if (isa<UnsetInit>(MHS))
1476 MHSTy = RHSTy;
1477 if (isa<UnsetInit>(RHS))
1478 RHSTy = MHSTy;
1479
1480 if (!MHSTy || !RHSTy) {
1481 TokError("could not get type for !if");
1482 return nullptr;
1483 }
1484
1485 Type = resolveTypes(MHSTy, RHSTy);
1486 if (!Type) {
1487 TokError(Twine("inconsistent types '") + MHSTy->getAsString() +
1488 "' and '" + RHSTy->getAsString() + "' for !if");
1489 return nullptr;
1490 }
1491 break;
1492 }
1493 case tgtok::XSubst: {
1494 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1495 if (!RHSt) {
1496 TokError("could not get type for !subst");
1497 return nullptr;
1498 }
1499 Type = RHSt->getType();
1500 break;
1501 }
1502 }
1503 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
1504 }
1505
1506 case tgtok::XCond:
1507 return ParseOperationCond(CurRec, ItemType);
2
Calling 'TGParser::ParseOperationCond'
1508
1509 case tgtok::XFoldl: {
1510 // Value ::= !foldl '(' Id ',' Id ',' Value ',' Value ',' Value ')'
1511 Lex.Lex(); // eat the operation
1512 if (Lex.getCode() != tgtok::l_paren) {
1513 TokError("expected '(' after !foldl");
1514 return nullptr;
1515 }
1516 Lex.Lex(); // eat the '('
1517
1518 Init *StartUntyped = ParseValue(CurRec);
1519 if (!StartUntyped)
1520 return nullptr;
1521
1522 TypedInit *Start = dyn_cast<TypedInit>(StartUntyped);
1523 if (!Start) {
1524 TokError(Twine("could not get type of !foldl start: '") +
1525 StartUntyped->getAsString() + "'");
1526 return nullptr;
1527 }
1528
1529 if (Lex.getCode() != tgtok::comma) {
1530 TokError("expected ',' in !foldl");
1531 return nullptr;
1532 }
1533 Lex.Lex(); // eat the ','
1534
1535 Init *ListUntyped = ParseValue(CurRec);
1536 if (!ListUntyped)
1537 return nullptr;
1538
1539 TypedInit *List = dyn_cast<TypedInit>(ListUntyped);
1540 if (!List) {
1541 TokError(Twine("could not get type of !foldl list: '") +
1542 ListUntyped->getAsString() + "'");
1543 return nullptr;
1544 }
1545
1546 ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType());
1547 if (!ListType) {
1548 TokError(Twine("!foldl list must be a list, but is of type '") +
1549 List->getType()->getAsString());
1550 return nullptr;
1551 }
1552
1553 if (Lex.getCode() != tgtok::comma) {
1554 TokError("expected ',' in !foldl");
1555 return nullptr;
1556 }
1557
1558 if (Lex.Lex() != tgtok::Id) { // eat the ','
1559 TokError("third argument of !foldl must be an identifier");
1560 return nullptr;
1561 }
1562
1563 Init *A = StringInit::get(Lex.getCurStrVal());
1564 if (CurRec && CurRec->getValue(A)) {
1565 TokError((Twine("left !foldl variable '") + A->getAsString() +
1566 "' already defined")
1567 .str());
1568 return nullptr;
1569 }
1570
1571 if (Lex.Lex() != tgtok::comma) { // eat the id
1572 TokError("expected ',' in !foldl");
1573 return nullptr;
1574 }
1575
1576 if (Lex.Lex() != tgtok::Id) { // eat the ','
1577 TokError("fourth argument of !foldl must be an identifier");
1578 return nullptr;
1579 }
1580
1581 Init *B = StringInit::get(Lex.getCurStrVal());
1582 if (CurRec && CurRec->getValue(B)) {
1583 TokError((Twine("right !foldl variable '") + B->getAsString() +
1584 "' already defined")
1585 .str());
1586 return nullptr;
1587 }
1588
1589 if (Lex.Lex() != tgtok::comma) { // eat the id
1590 TokError("expected ',' in !foldl");
1591 return nullptr;
1592 }
1593 Lex.Lex(); // eat the ','
1594
1595 // We need to create a temporary record to provide a scope for the iteration
1596 // variable while parsing top-level foreach's.
1597 std::unique_ptr<Record> ParseRecTmp;
1598 Record *ParseRec = CurRec;
1599 if (!ParseRec) {
1600 ParseRecTmp = make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1601 ParseRec = ParseRecTmp.get();
1602 }
1603
1604 ParseRec->addValue(RecordVal(A, Start->getType(), false));
1605 ParseRec->addValue(RecordVal(B, ListType->getElementType(), false));
1606 Init *ExprUntyped = ParseValue(ParseRec);
1607 ParseRec->removeValue(A);
1608 ParseRec->removeValue(B);
1609 if (!ExprUntyped)
1610 return nullptr;
1611
1612 TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped);
1613 if (!Expr) {
1614 TokError("could not get type of !foldl expression");
1615 return nullptr;
1616 }
1617
1618 if (Expr->getType() != Start->getType()) {
1619 TokError(Twine("!foldl expression must be of same type as start (") +
1620 Start->getType()->getAsString() + "), but is of type " +
1621 Expr->getType()->getAsString());
1622 return nullptr;
1623 }
1624
1625 if (Lex.getCode() != tgtok::r_paren) {
1626 TokError("expected ')' in fold operator");
1627 return nullptr;
1628 }
1629 Lex.Lex(); // eat the ')'
1630
1631 return FoldOpInit::get(Start, List, A, B, Expr, Start->getType())
1632 ->Fold(CurRec);
1633 }
1634 }
1635}
1636
1637/// ParseOperatorType - Parse a type for an operator. This returns
1638/// null on error.
1639///
1640/// OperatorType ::= '<' Type '>'
1641///
1642RecTy *TGParser::ParseOperatorType() {
1643 RecTy *Type = nullptr;
1644
1645 if (Lex.getCode() != tgtok::less) {
1646 TokError("expected type name for operator");
1647 return nullptr;
1648 }
1649 Lex.Lex(); // eat the <
1650
1651 Type = ParseType();
1652
1653 if (!Type) {
1654 TokError("expected type name for operator");
1655 return nullptr;
1656 }
1657
1658 if (Lex.getCode() != tgtok::greater) {
1659 TokError("expected type name for operator");
1660 return nullptr;
1661 }
1662 Lex.Lex(); // eat the >
1663
1664 return Type;
1665}
1666
1667Init *TGParser::ParseOperationCond(Record *CurRec, RecTy *ItemType) {
1668 Lex.Lex(); // eat the operation 'cond'
1669
1670 if (Lex.getCode() != tgtok::l_paren) {
3
Assuming the condition is false
4
Taking false branch
1671 TokError("expected '(' after !cond operator");
1672 return nullptr;
1673 }
1674 Lex.Lex(); // eat the '('
1675
1676 // Parse through '[Case: Val,]+'
1677 SmallVector<Init *, 4> Case;
1678 SmallVector<Init *, 4> Val;
1679 while (true) {
5
Loop condition is true. Entering loop body
1680 if (Lex.getCode() == tgtok::r_paren) {
6
Assuming the condition is false
7
Taking false branch
1681 Lex.Lex(); // eat the ')'
1682 break;
1683 }
1684
1685 Init *V = ParseValue(CurRec);
1686 if (!V)
8
Assuming 'V' is non-null
9
Taking false branch
1687 return nullptr;
1688 Case.push_back(V);
1689
1690 if (Lex.getCode() != tgtok::colon) {
10
Assuming the condition is false
11
Taking false branch
1691 TokError("expected ':' following a condition in !cond operator");
1692 return nullptr;
1693 }
1694 Lex.Lex(); // eat the ':'
1695
1696 V = ParseValue(CurRec, ItemType);
1697 if (!V)
12
Assuming 'V' is non-null
13
Taking false branch
1698 return nullptr;
1699 Val.push_back(V);
1700
1701 if (Lex.getCode() == tgtok::r_paren) {
14
Assuming the condition is true
15
Taking true branch
1702 Lex.Lex(); // eat the ')'
1703 break;
16
Execution continues on line 1713
1704 }
1705
1706 if (Lex.getCode() != tgtok::comma) {
1707 TokError("expected ',' or ')' following a value in !cond operator");
1708 return nullptr;
1709 }
1710 Lex.Lex(); // eat the ','
1711 }
1712
1713 if (Case.size() < 1) {
17
Assuming the condition is false
18
Taking false branch
1714 TokError("there should be at least 1 'condition : value' in the !cond operator");
1715 return nullptr;
1716 }
1717
1718 // resolve type
1719 RecTy *Type = nullptr;
1720 for (Init *V : Val) {
19
Assuming '__begin1' is not equal to '__end1'
1721 RecTy *VTy = nullptr;
25
'VTy' initialized to a null pointer value
1722 if (TypedInit *Vt = dyn_cast<TypedInit>(V))
20
Taking true branch
26
Taking false branch
1723 VTy = Vt->getType();
1724 if (BitsInit *Vbits = dyn_cast<BitsInit>(V))
21
Taking false branch
27
Taking false branch
1725 VTy = BitsRecTy::get(Vbits->getNumBits());
1726 if (isa<BitInit>(V))
22
Taking false branch
28
Taking false branch
1727 VTy = BitRecTy::get();
1728
1729 if (Type == nullptr) {
23
Taking true branch
29
Assuming the condition is false
30
Taking false branch
1730 if (!isa<UnsetInit>(V))
24
Taking true branch
1731 Type = VTy;
1732 } else {
1733 if (!isa<UnsetInit>(V)) {
31
Taking true branch
1734 RecTy *RType = resolveTypes(Type, VTy);
1735 if (!RType) {
32
Assuming 'RType' is null
33
Taking true branch
1736 TokError(Twine("inconsistent types '") + Type->getAsString() +
1737 "' and '" + VTy->getAsString() + "' for !cond");
34
Called C++ object pointer is null
1738 return nullptr;
1739 }
1740 Type = RType;
1741 }
1742 }
1743 }
1744
1745 if (!Type) {
1746 TokError("could not determine type for !cond from its arguments");
1747 return nullptr;
1748 }
1749 return CondOpInit::get(Case, Val, Type)->Fold(CurRec);
1750}
1751
1752/// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1753///
1754/// SimpleValue ::= IDValue
1755/// SimpleValue ::= INTVAL
1756/// SimpleValue ::= STRVAL+
1757/// SimpleValue ::= CODEFRAGMENT
1758/// SimpleValue ::= '?'
1759/// SimpleValue ::= '{' ValueList '}'
1760/// SimpleValue ::= ID '<' ValueListNE '>'
1761/// SimpleValue ::= '[' ValueList ']'
1762/// SimpleValue ::= '(' IDValue DagArgList ')'
1763/// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1764/// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1765/// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1766/// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1767/// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1768/// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1769/// SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')'
1770/// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1771/// SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
1772///
1773Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1774 IDParseMode Mode) {
1775 Init *R = nullptr;
1776 switch (Lex.getCode()) {
1777 default: TokError("Unknown token when parsing a value"); break;
1778 case tgtok::paste:
1779 // This is a leading paste operation. This is deprecated but
1780 // still exists in some .td files. Ignore it.
1781 Lex.Lex(); // Skip '#'.
1782 return ParseSimpleValue(CurRec, ItemType, Mode);
1783 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1784 case tgtok::BinaryIntVal: {
1785 auto BinaryVal = Lex.getCurBinaryIntVal();
1786 SmallVector<Init*, 16> Bits(BinaryVal.second);
1787 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
1788 Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
1789 R = BitsInit::get(Bits);
1790 Lex.Lex();
1791 break;
1792 }
1793 case tgtok::StrVal: {
1794 std::string Val = Lex.getCurStrVal();
1795 Lex.Lex();
1796
1797 // Handle multiple consecutive concatenated strings.
1798 while (Lex.getCode() == tgtok::StrVal) {
1799 Val += Lex.getCurStrVal();
1800 Lex.Lex();
1801 }
1802
1803 R = StringInit::get(Val);
1804 break;
1805 }
1806 case tgtok::CodeFragment:
1807 R = CodeInit::get(Lex.getCurStrVal(), Lex.getLoc());
1808 Lex.Lex();
1809 break;
1810 case tgtok::question:
1811 R = UnsetInit::get();
1812 Lex.Lex();
1813 break;
1814 case tgtok::Id: {
1815 SMLoc NameLoc = Lex.getLoc();
1816 StringInit *Name = StringInit::get(Lex.getCurStrVal());
1817 if (Lex.Lex() != tgtok::less) // consume the Id.
1818 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1819
1820 // Value ::= ID '<' ValueListNE '>'
1821 if (Lex.Lex() == tgtok::greater) {
1822 TokError("expected non-empty value list");
1823 return nullptr;
1824 }
1825
1826 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1827 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1828 // body.
1829 Record *Class = Records.getClass(Name->getValue());
1830 if (!Class) {
1831 Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'");
1832 return nullptr;
1833 }
1834
1835 SmallVector<Init *, 8> Args;
1836 ParseValueList(Args, CurRec, Class);
1837 if (Args.empty()) return nullptr;
1838
1839 if (Lex.getCode() != tgtok::greater) {
1840 TokError("expected '>' at end of value list");
1841 return nullptr;
1842 }
1843 Lex.Lex(); // eat the '>'
1844
1845 // Typecheck the template arguments list
1846 ArrayRef<Init *> ExpectedArgs = Class->getTemplateArgs();
1847 if (ExpectedArgs.size() < Args.size()) {
1848 Error(NameLoc,
1849 "More template args specified than expected");
1850 return nullptr;
1851 }
1852
1853 for (unsigned i = 0, e = ExpectedArgs.size(); i != e; ++i) {
1854 RecordVal *ExpectedArg = Class->getValue(ExpectedArgs[i]);
1855 if (i < Args.size()) {
1856 if (TypedInit *TI = dyn_cast<TypedInit>(Args[i])) {
1857 RecTy *ExpectedType = ExpectedArg->getType();
1858 if (!TI->getType()->typeIsConvertibleTo(ExpectedType)) {
1859 Error(NameLoc,
1860 "Value specified for template argument #" + Twine(i) + " (" +
1861 ExpectedArg->getNameInitAsString() + ") is of type '" +
1862 TI->getType()->getAsString() + "', expected '" +
1863 ExpectedType->getAsString() + "': " + TI->getAsString());
1864 return nullptr;
1865 }
1866 continue;
1867 }
1868 } else if (ExpectedArg->getValue()->isComplete())
1869 continue;
1870
1871 Error(NameLoc,
1872 "Value not specified for template argument #" + Twine(i) + " (" +
1873 ExpectedArgs[i]->getAsUnquotedString() + ")");
1874 return nullptr;
1875 }
1876
1877 return VarDefInit::get(Class, Args)->Fold();
1878 }
1879 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1880 SMLoc BraceLoc = Lex.getLoc();
1881 Lex.Lex(); // eat the '{'
1882 SmallVector<Init*, 16> Vals;
1883
1884 if (Lex.getCode() != tgtok::r_brace) {
1885 ParseValueList(Vals, CurRec);
1886 if (Vals.empty()) return nullptr;
1887 }
1888 if (Lex.getCode() != tgtok::r_brace) {
1889 TokError("expected '}' at end of bit list value");
1890 return nullptr;
1891 }
1892 Lex.Lex(); // eat the '}'
1893
1894 SmallVector<Init *, 16> NewBits;
1895
1896 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1897 // first. We'll first read everything in to a vector, then we can reverse
1898 // it to get the bits in the correct order for the BitsInit value.
1899 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1900 // FIXME: The following two loops would not be duplicated
1901 // if the API was a little more orthogonal.
1902
1903 // bits<n> values are allowed to initialize n bits.
1904 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
1905 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
1906 NewBits.push_back(BI->getBit((e - i) - 1));
1907 continue;
1908 }
1909 // bits<n> can also come from variable initializers.
1910 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
1911 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
1912 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
1913 NewBits.push_back(VI->getBit((e - i) - 1));
1914 continue;
1915 }
1916 // Fallthrough to try convert this to a bit.
1917 }
1918 // All other values must be convertible to just a single bit.
1919 Init *Bit = Vals[i]->getCastTo(BitRecTy::get());
1920 if (!Bit) {
1921 Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
1922 ") is not convertable to a bit");
1923 return nullptr;
1924 }
1925 NewBits.push_back(Bit);
1926 }
1927 std::reverse(NewBits.begin(), NewBits.end());
1928 return BitsInit::get(NewBits);
1929 }
1930 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1931 Lex.Lex(); // eat the '['
1932 SmallVector<Init*, 16> Vals;
1933
1934 RecTy *DeducedEltTy = nullptr;
1935 ListRecTy *GivenListTy = nullptr;
1936
1937 if (ItemType) {
1938 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1939 if (!ListType) {
1940 TokError(Twine("Type mismatch for list, expected list type, got ") +
1941 ItemType->getAsString());
1942 return nullptr;
1943 }
1944 GivenListTy = ListType;
1945 }
1946
1947 if (Lex.getCode() != tgtok::r_square) {
1948 ParseValueList(Vals, CurRec, nullptr,
1949 GivenListTy ? GivenListTy->getElementType() : nullptr);
1950 if (Vals.empty()) return nullptr;
1951 }
1952 if (Lex.getCode() != tgtok::r_square) {
1953 TokError("expected ']' at end of list value");
1954 return nullptr;
1955 }
1956 Lex.Lex(); // eat the ']'
1957
1958 RecTy *GivenEltTy = nullptr;
1959 if (Lex.getCode() == tgtok::less) {
1960 // Optional list element type
1961 Lex.Lex(); // eat the '<'
1962
1963 GivenEltTy = ParseType();
1964 if (!GivenEltTy) {
1965 // Couldn't parse element type
1966 return nullptr;
1967 }
1968
1969 if (Lex.getCode() != tgtok::greater) {
1970 TokError("expected '>' at end of list element type");
1971 return nullptr;
1972 }
1973 Lex.Lex(); // eat the '>'
1974 }
1975
1976 // Check elements
1977 RecTy *EltTy = nullptr;
1978 for (Init *V : Vals) {
1979 TypedInit *TArg = dyn_cast<TypedInit>(V);
1980 if (TArg) {
1981 if (EltTy) {
1982 EltTy = resolveTypes(EltTy, TArg->getType());
1983 if (!EltTy) {
1984 TokError("Incompatible types in list elements");
1985 return nullptr;
1986 }
1987 } else {
1988 EltTy = TArg->getType();
1989 }
1990 }
1991 }
1992
1993 if (GivenEltTy) {
1994 if (EltTy) {
1995 // Verify consistency
1996 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1997 TokError("Incompatible types in list elements");
1998 return nullptr;
1999 }
2000 }
2001 EltTy = GivenEltTy;
2002 }
2003
2004 if (!EltTy) {
2005 if (!ItemType) {
2006 TokError("No type for list");
2007 return nullptr;
2008 }
2009 DeducedEltTy = GivenListTy->getElementType();
2010 } else {
2011 // Make sure the deduced type is compatible with the given type
2012 if (GivenListTy) {
2013 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
2014 TokError(Twine("Element type mismatch for list: element type '") +
2015 EltTy->getAsString() + "' not convertible to '" +
2016 GivenListTy->getElementType()->getAsString());
2017 return nullptr;
2018 }
2019 }
2020 DeducedEltTy = EltTy;
2021 }
2022
2023 return ListInit::get(Vals, DeducedEltTy);
2024 }
2025 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
2026 Lex.Lex(); // eat the '('
2027 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
2028 TokError("expected identifier in dag init");
2029 return nullptr;
2030 }
2031
2032 Init *Operator = ParseValue(CurRec);
2033 if (!Operator) return nullptr;
2034
2035 // If the operator name is present, parse it.
2036 StringInit *OperatorName = nullptr;
2037 if (Lex.getCode() == tgtok::colon) {
2038 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
2039 TokError("expected variable name in dag operator");
2040 return nullptr;
2041 }
2042 OperatorName = StringInit::get(Lex.getCurStrVal());
2043 Lex.Lex(); // eat the VarName.
2044 }
2045
2046 SmallVector<std::pair<llvm::Init*, StringInit*>, 8> DagArgs;
2047 if (Lex.getCode() != tgtok::r_paren) {
2048 ParseDagArgList(DagArgs, CurRec);
2049 if (DagArgs.empty()) return nullptr;
2050 }
2051
2052 if (Lex.getCode() != tgtok::r_paren) {
2053 TokError("expected ')' in dag init");
2054 return nullptr;
2055 }
2056 Lex.Lex(); // eat the ')'
2057
2058 return DagInit::get(Operator, OperatorName, DagArgs);
2059 }
2060
2061 case tgtok::XHead:
2062 case tgtok::XTail:
2063 case tgtok::XSize:
2064 case tgtok::XEmpty:
2065 case tgtok::XCast: // Value ::= !unop '(' Value ')'
2066 case tgtok::XIsA:
2067 case tgtok::XConcat:
2068 case tgtok::XDag:
2069 case tgtok::XADD:
2070 case tgtok::XMUL:
2071 case tgtok::XAND:
2072 case tgtok::XOR:
2073 case tgtok::XSRA:
2074 case tgtok::XSRL:
2075 case tgtok::XSHL:
2076 case tgtok::XEq:
2077 case tgtok::XNe:
2078 case tgtok::XLe:
2079 case tgtok::XLt:
2080 case tgtok::XGe:
2081 case tgtok::XGt:
2082 case tgtok::XListConcat:
2083 case tgtok::XListSplat:
2084 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
2085 case tgtok::XIf:
2086 case tgtok::XCond:
2087 case tgtok::XFoldl:
2088 case tgtok::XForEach:
2089 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
2090 return ParseOperation(CurRec, ItemType);
2091 }
2092 }
2093
2094 return R;
2095}
2096
2097/// ParseValue - Parse a tblgen value. This returns null on error.
2098///
2099/// Value ::= SimpleValue ValueSuffix*
2100/// ValueSuffix ::= '{' BitList '}'
2101/// ValueSuffix ::= '[' BitList ']'
2102/// ValueSuffix ::= '.' ID
2103///
2104Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
2105 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
2106 if (!Result) return nullptr;
2107
2108 // Parse the suffixes now if present.
2109 while (true) {
2110 switch (Lex.getCode()) {
2111 default: return Result;
2112 case tgtok::l_brace: {
2113 if (Mode == ParseNameMode)
2114 // This is the beginning of the object body.
2115 return Result;
2116
2117 SMLoc CurlyLoc = Lex.getLoc();
2118 Lex.Lex(); // eat the '{'
2119 SmallVector<unsigned, 16> Ranges;
2120 ParseRangeList(Ranges);
2121 if (Ranges.empty()) return nullptr;
2122
2123 // Reverse the bitlist.
2124 std::reverse(Ranges.begin(), Ranges.end());
2125 Result = Result->convertInitializerBitRange(Ranges);
2126 if (!Result) {
2127 Error(CurlyLoc, "Invalid bit range for value");
2128 return nullptr;
2129 }
2130
2131 // Eat the '}'.
2132 if (Lex.getCode() != tgtok::r_brace) {
2133 TokError("expected '}' at end of bit range list");
2134 return nullptr;
2135 }
2136 Lex.Lex();
2137 break;
2138 }
2139 case tgtok::l_square: {
2140 SMLoc SquareLoc = Lex.getLoc();
2141 Lex.Lex(); // eat the '['
2142 SmallVector<unsigned, 16> Ranges;
2143 ParseRangeList(Ranges);
2144 if (Ranges.empty()) return nullptr;
2145
2146 Result = Result->convertInitListSlice(Ranges);
2147 if (!Result) {
2148 Error(SquareLoc, "Invalid range for list slice");
2149 return nullptr;
2150 }
2151
2152 // Eat the ']'.
2153 if (Lex.getCode() != tgtok::r_square) {
2154 TokError("expected ']' at end of list slice");
2155 return nullptr;
2156 }
2157 Lex.Lex();
2158 break;
2159 }
2160 case tgtok::period: {
2161 if (Lex.Lex() != tgtok::Id) { // eat the .
2162 TokError("expected field identifier after '.'");
2163 return nullptr;
2164 }
2165 StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2166 if (!Result->getFieldType(FieldName)) {
2167 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
2168 Result->getAsString() + "'");
2169 return nullptr;
2170 }
2171 Result = FieldInit::get(Result, FieldName)->Fold(CurRec);
2172 Lex.Lex(); // eat field name
2173 break;
2174 }
2175
2176 case tgtok::paste:
2177 SMLoc PasteLoc = Lex.getLoc();
2178 TypedInit *LHS = dyn_cast<TypedInit>(Result);
2179 if (!LHS) {
2180 Error(PasteLoc, "LHS of paste is not typed!");
2181 return nullptr;
2182 }
2183
2184 // Check if it's a 'listA # listB'
2185 if (isa<ListRecTy>(LHS->getType())) {
2186 Lex.Lex(); // Eat the '#'.
2187
2188 switch (Lex.getCode()) {
2189 case tgtok::colon:
2190 case tgtok::semi:
2191 case tgtok::l_brace:
2192 Result = LHS; // trailing paste, ignore.
2193 break;
2194 default:
2195 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
2196 Result = BinOpInit::getListConcat(LHS, RHSResult);
2197 }
2198 break;
2199 }
2200
2201 // Create a !strconcat() operation, first casting each operand to
2202 // a string if necessary.
2203 if (LHS->getType() != StringRecTy::get()) {
2204 auto CastLHS = dyn_cast<TypedInit>(
2205 UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get())
2206 ->Fold(CurRec));
2207 if (!CastLHS) {
2208 Error(PasteLoc,
2209 Twine("can't cast '") + LHS->getAsString() + "' to string");
2210 return nullptr;
2211 }
2212 LHS = CastLHS;
2213 }
2214
2215 TypedInit *RHS = nullptr;
2216
2217 Lex.Lex(); // Eat the '#'.
2218 switch (Lex.getCode()) {
2219 case tgtok::colon:
2220 case tgtok::semi:
2221 case tgtok::l_brace:
2222 // These are all of the tokens that can begin an object body.
2223 // Some of these can also begin values but we disallow those cases
2224 // because they are unlikely to be useful.
2225
2226 // Trailing paste, concat with an empty string.
2227 RHS = StringInit::get("");
2228 break;
2229
2230 default:
2231 Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode);
2232 RHS = dyn_cast<TypedInit>(RHSResult);
2233 if (!RHS) {
2234 Error(PasteLoc, "RHS of paste is not typed!");
2235 return nullptr;
2236 }
2237
2238 if (RHS->getType() != StringRecTy::get()) {
2239 auto CastRHS = dyn_cast<TypedInit>(
2240 UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get())
2241 ->Fold(CurRec));
2242 if (!CastRHS) {
2243 Error(PasteLoc,
2244 Twine("can't cast '") + RHS->getAsString() + "' to string");
2245 return nullptr;
2246 }
2247 RHS = CastRHS;
2248 }
2249
2250 break;
2251 }
2252
2253 Result = BinOpInit::getStrConcat(LHS, RHS);
2254 break;
2255 }
2256 }
2257}
2258
2259/// ParseDagArgList - Parse the argument list for a dag literal expression.
2260///
2261/// DagArg ::= Value (':' VARNAME)?
2262/// DagArg ::= VARNAME
2263/// DagArgList ::= DagArg
2264/// DagArgList ::= DagArgList ',' DagArg
2265void TGParser::ParseDagArgList(
2266 SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result,
2267 Record *CurRec) {
2268
2269 while (true) {
2270 // DagArg ::= VARNAME
2271 if (Lex.getCode() == tgtok::VarName) {
2272 // A missing value is treated like '?'.
2273 StringInit *VarName = StringInit::get(Lex.getCurStrVal());
2274 Result.emplace_back(UnsetInit::get(), VarName);
2275 Lex.Lex();
2276 } else {
2277 // DagArg ::= Value (':' VARNAME)?
2278 Init *Val = ParseValue(CurRec);
2279 if (!Val) {
2280 Result.clear();
2281 return;
2282 }
2283
2284 // If the variable name is present, add it.
2285 StringInit *VarName = nullptr;
2286 if (Lex.getCode() == tgtok::colon) {
2287 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
2288 TokError("expected variable name in dag literal");
2289 Result.clear();
2290 return;
2291 }
2292 VarName = StringInit::get(Lex.getCurStrVal());
2293 Lex.Lex(); // eat the VarName.
2294 }
2295
2296 Result.push_back(std::make_pair(Val, VarName));
2297 }
2298 if (Lex.getCode() != tgtok::comma) break;
2299 Lex.Lex(); // eat the ','
2300 }
2301}
2302
2303/// ParseValueList - Parse a comma separated list of values, returning them as a
2304/// vector. Note that this always expects to be able to parse at least one
2305/// value. It returns an empty list if this is not possible.
2306///
2307/// ValueList ::= Value (',' Value)
2308///
2309void TGParser::ParseValueList(SmallVectorImpl<Init*> &Result, Record *CurRec,
2310 Record *ArgsRec, RecTy *EltTy) {
2311 RecTy *ItemType = EltTy;
2312 unsigned int ArgN = 0;
2313 if (ArgsRec && !EltTy) {
2314 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2315 if (TArgs.empty()) {
2316 TokError("template argument provided to non-template class");
2317 Result.clear();
2318 return;
2319 }
2320 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2321 if (!RV) {
2322 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
2323 << ")\n";
2324 }
2325 assert(RV && "Template argument record not found??")((RV && "Template argument record not found??") ? static_cast
<void> (0) : __assert_fail ("RV && \"Template argument record not found??\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 2325, __PRETTY_FUNCTION__))
;
2326 ItemType = RV->getType();
2327 ++ArgN;
2328 }
2329 Result.push_back(ParseValue(CurRec, ItemType));
2330 if (!Result.back()) {
2331 Result.clear();
2332 return;
2333 }
2334
2335 while (Lex.getCode() == tgtok::comma) {
2336 Lex.Lex(); // Eat the comma
2337
2338 // ignore trailing comma for lists
2339 if (Lex.getCode() == tgtok::r_square)
2340 return;
2341
2342 if (ArgsRec && !EltTy) {
2343 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2344 if (ArgN >= TArgs.size()) {
2345 TokError("too many template arguments");
2346 Result.clear();
2347 return;
2348 }
2349 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2350 assert(RV && "Template argument record not found??")((RV && "Template argument record not found??") ? static_cast
<void> (0) : __assert_fail ("RV && \"Template argument record not found??\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 2350, __PRETTY_FUNCTION__))
;
2351 ItemType = RV->getType();
2352 ++ArgN;
2353 }
2354 Result.push_back(ParseValue(CurRec, ItemType));
2355 if (!Result.back()) {
2356 Result.clear();
2357 return;
2358 }
2359 }
2360}
2361
2362/// ParseDeclaration - Read a declaration, returning the name of field ID, or an
2363/// empty string on error. This can happen in a number of different context's,
2364/// including within a def or in the template args for a def (which which case
2365/// CurRec will be non-null) and within the template args for a multiclass (in
2366/// which case CurRec will be null, but CurMultiClass will be set). This can
2367/// also happen within a def that is within a multiclass, which will set both
2368/// CurRec and CurMultiClass.
2369///
2370/// Declaration ::= FIELD? Type ID ('=' Value)?
2371///
2372Init *TGParser::ParseDeclaration(Record *CurRec,
2373 bool ParsingTemplateArgs) {
2374 // Read the field prefix if present.
2375 bool HasField = Lex.getCode() == tgtok::Field;
2376 if (HasField) Lex.Lex();
2377
2378 RecTy *Type = ParseType();
2379 if (!Type) return nullptr;
2380
2381 if (Lex.getCode() != tgtok::Id) {
2382 TokError("Expected identifier in declaration");
2383 return nullptr;
2384 }
2385
2386 std::string Str = Lex.getCurStrVal();
2387 if (Str == "NAME") {
2388 TokError("'" + Str + "' is a reserved variable name");
2389 return nullptr;
2390 }
2391
2392 SMLoc IdLoc = Lex.getLoc();
2393 Init *DeclName = StringInit::get(Str);
2394 Lex.Lex();
2395
2396 if (ParsingTemplateArgs) {
2397 if (CurRec)
2398 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
2399 else
2400 assert(CurMultiClass)((CurMultiClass) ? static_cast<void> (0) : __assert_fail
("CurMultiClass", "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 2400, __PRETTY_FUNCTION__))
;
2401 if (CurMultiClass)
2402 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
2403 "::");
2404 }
2405
2406 // Add the value.
2407 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
2408 return nullptr;
2409
2410 // If a value is present, parse it.
2411 if (Lex.getCode() == tgtok::equal) {
2412 Lex.Lex();
2413 SMLoc ValLoc = Lex.getLoc();
2414 Init *Val = ParseValue(CurRec, Type);
2415 if (!Val ||
2416 SetValue(CurRec, ValLoc, DeclName, None, Val))
2417 // Return the name, even if an error is thrown. This is so that we can
2418 // continue to make some progress, even without the value having been
2419 // initialized.
2420 return DeclName;
2421 }
2422
2423 return DeclName;
2424}
2425
2426/// ParseForeachDeclaration - Read a foreach declaration, returning
2427/// the name of the declared object or a NULL Init on error. Return
2428/// the name of the parsed initializer list through ForeachListName.
2429///
2430/// ForeachDeclaration ::= ID '=' '{' RangeList '}'
2431/// ForeachDeclaration ::= ID '=' RangePiece
2432/// ForeachDeclaration ::= ID '=' Value
2433///
2434VarInit *TGParser::ParseForeachDeclaration(Init *&ForeachListValue) {
2435 if (Lex.getCode() != tgtok::Id) {
2436 TokError("Expected identifier in foreach declaration");
2437 return nullptr;
2438 }
2439
2440 Init *DeclName = StringInit::get(Lex.getCurStrVal());
2441 Lex.Lex();
2442
2443 // If a value is present, parse it.
2444 if (Lex.getCode() != tgtok::equal) {
2445 TokError("Expected '=' in foreach declaration");
2446 return nullptr;
2447 }
2448 Lex.Lex(); // Eat the '='
2449
2450 RecTy *IterType = nullptr;
2451 SmallVector<unsigned, 16> Ranges;
2452
2453 switch (Lex.getCode()) {
2454 case tgtok::l_brace: { // '{' RangeList '}'
2455 Lex.Lex(); // eat the '{'
2456 ParseRangeList(Ranges);
2457 if (Lex.getCode() != tgtok::r_brace) {
2458 TokError("expected '}' at end of bit range list");
2459 return nullptr;
2460 }
2461 Lex.Lex();
2462 break;
2463 }
2464
2465 default: {
2466 SMLoc ValueLoc = Lex.getLoc();
2467 Init *I = ParseValue(nullptr);
2468 if (!I)
2469 return nullptr;
2470
2471 TypedInit *TI = dyn_cast<TypedInit>(I);
2472 if (TI && isa<ListRecTy>(TI->getType())) {
2473 ForeachListValue = I;
2474 IterType = cast<ListRecTy>(TI->getType())->getElementType();
2475 break;
2476 }
2477
2478 if (TI) {
2479 if (ParseRangePiece(Ranges, TI))
2480 return nullptr;
2481 break;
2482 }
2483
2484 std::string Type;
2485 if (TI)
2486 Type = (Twine("' of type '") + TI->getType()->getAsString()).str();
2487 Error(ValueLoc, "expected a list, got '" + I->getAsString() + Type + "'");
2488 if (CurMultiClass) {
2489 PrintNote({}, "references to multiclass template arguments cannot be "
2490 "resolved at this time");
2491 }
2492 return nullptr;
2493 }
2494 }
2495
2496
2497 if (!Ranges.empty()) {
2498 assert(!IterType && "Type already initialized?")((!IterType && "Type already initialized?") ? static_cast
<void> (0) : __assert_fail ("!IterType && \"Type already initialized?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 2498, __PRETTY_FUNCTION__))
;
2499 IterType = IntRecTy::get();
2500 std::vector<Init*> Values;
2501 for (unsigned R : Ranges)
2502 Values.push_back(IntInit::get(R));
2503 ForeachListValue = ListInit::get(Values, IterType);
2504 }
2505
2506 if (!IterType)
2507 return nullptr;
2508
2509 return VarInit::get(DeclName, IterType);
2510}
2511
2512/// ParseTemplateArgList - Read a template argument list, which is a non-empty
2513/// sequence of template-declarations in <>'s. If CurRec is non-null, these are
2514/// template args for a def, which may or may not be in a multiclass. If null,
2515/// these are the template args for a multiclass.
2516///
2517/// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
2518///
2519bool TGParser::ParseTemplateArgList(Record *CurRec) {
2520 assert(Lex.getCode() == tgtok::less && "Not a template arg list!")((Lex.getCode() == tgtok::less && "Not a template arg list!"
) ? static_cast<void> (0) : __assert_fail ("Lex.getCode() == tgtok::less && \"Not a template arg list!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 2520, __PRETTY_FUNCTION__))
;
2521 Lex.Lex(); // eat the '<'
2522
2523 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
2524
2525 // Read the first declaration.
2526 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2527 if (!TemplArg)
2528 return true;
2529
2530 TheRecToAddTo->addTemplateArg(TemplArg);
2531
2532 while (Lex.getCode() == tgtok::comma) {
2533 Lex.Lex(); // eat the ','
2534
2535 // Read the following declarations.
2536 SMLoc Loc = Lex.getLoc();
2537 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2538 if (!TemplArg)
2539 return true;
2540
2541 if (TheRecToAddTo->isTemplateArg(TemplArg))
2542 return Error(Loc, "template argument with the same name has already been "
2543 "defined");
2544
2545 TheRecToAddTo->addTemplateArg(TemplArg);
2546 }
2547
2548 if (Lex.getCode() != tgtok::greater)
2549 return TokError("expected '>' at end of template argument list");
2550 Lex.Lex(); // eat the '>'.
2551 return false;
2552}
2553
2554/// ParseBodyItem - Parse a single item at within the body of a def or class.
2555///
2556/// BodyItem ::= Declaration ';'
2557/// BodyItem ::= LET ID OptionalBitList '=' Value ';'
2558bool TGParser::ParseBodyItem(Record *CurRec) {
2559 if (Lex.getCode() != tgtok::Let) {
2560 if (!ParseDeclaration(CurRec, false))
2561 return true;
2562
2563 if (Lex.getCode() != tgtok::semi)
2564 return TokError("expected ';' after declaration");
2565 Lex.Lex();
2566 return false;
2567 }
2568
2569 // LET ID OptionalRangeList '=' Value ';'
2570 if (Lex.Lex() != tgtok::Id)
2571 return TokError("expected field identifier after let");
2572
2573 SMLoc IdLoc = Lex.getLoc();
2574 StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2575 Lex.Lex(); // eat the field name.
2576
2577 SmallVector<unsigned, 16> BitList;
2578 if (ParseOptionalBitList(BitList))
2579 return true;
2580 std::reverse(BitList.begin(), BitList.end());
2581
2582 if (Lex.getCode() != tgtok::equal)
2583 return TokError("expected '=' in let expression");
2584 Lex.Lex(); // eat the '='.
2585
2586 RecordVal *Field = CurRec->getValue(FieldName);
2587 if (!Field)
2588 return TokError("Value '" + FieldName->getValue() + "' unknown!");
2589
2590 RecTy *Type = Field->getType();
2591
2592 Init *Val = ParseValue(CurRec, Type);
2593 if (!Val) return true;
2594
2595 if (Lex.getCode() != tgtok::semi)
2596 return TokError("expected ';' after let expression");
2597 Lex.Lex();
2598
2599 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
2600}
2601
2602/// ParseBody - Read the body of a class or def. Return true on error, false on
2603/// success.
2604///
2605/// Body ::= ';'
2606/// Body ::= '{' BodyList '}'
2607/// BodyList BodyItem*
2608///
2609bool TGParser::ParseBody(Record *CurRec) {
2610 // If this is a null definition, just eat the semi and return.
2611 if (Lex.getCode() == tgtok::semi) {
2612 Lex.Lex();
2613 return false;
2614 }
2615
2616 if (Lex.getCode() != tgtok::l_brace)
2617 return TokError("Expected ';' or '{' to start body");
2618 // Eat the '{'.
2619 Lex.Lex();
2620
2621 while (Lex.getCode() != tgtok::r_brace)
2622 if (ParseBodyItem(CurRec))
2623 return true;
2624
2625 // Eat the '}'.
2626 Lex.Lex();
2627 return false;
2628}
2629
2630/// Apply the current let bindings to \a CurRec.
2631/// \returns true on error, false otherwise.
2632bool TGParser::ApplyLetStack(Record *CurRec) {
2633 for (SmallVectorImpl<LetRecord> &LetInfo : LetStack)
2634 for (LetRecord &LR : LetInfo)
2635 if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
2636 return true;
2637 return false;
2638}
2639
2640bool TGParser::ApplyLetStack(RecordsEntry &Entry) {
2641 if (Entry.Rec)
2642 return ApplyLetStack(Entry.Rec.get());
2643
2644 for (auto &E : Entry.Loop->Entries) {
2645 if (ApplyLetStack(E))
2646 return true;
2647 }
2648
2649 return false;
2650}
2651
2652/// ParseObjectBody - Parse the body of a def or class. This consists of an
2653/// optional ClassList followed by a Body. CurRec is the current def or class
2654/// that is being parsed.
2655///
2656/// ObjectBody ::= BaseClassList Body
2657/// BaseClassList ::= /*empty*/
2658/// BaseClassList ::= ':' BaseClassListNE
2659/// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
2660///
2661bool TGParser::ParseObjectBody(Record *CurRec) {
2662 // If there is a baseclass list, read it.
2663 if (Lex.getCode() == tgtok::colon) {
2664 Lex.Lex();
2665
2666 // Read all of the subclasses.
2667 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
2668 while (true) {
2669 // Check for error.
2670 if (!SubClass.Rec) return true;
2671
2672 // Add it.
2673 if (AddSubClass(CurRec, SubClass))
2674 return true;
2675
2676 if (Lex.getCode() != tgtok::comma) break;
2677 Lex.Lex(); // eat ','.
2678 SubClass = ParseSubClassReference(CurRec, false);
2679 }
2680 }
2681
2682 if (ApplyLetStack(CurRec))
2683 return true;
2684
2685 return ParseBody(CurRec);
2686}
2687
2688/// ParseDef - Parse and return a top level or multiclass def, return the record
2689/// corresponding to it. This returns null on error.
2690///
2691/// DefInst ::= DEF ObjectName ObjectBody
2692///
2693bool TGParser::ParseDef(MultiClass *CurMultiClass) {
2694 SMLoc DefLoc = Lex.getLoc();
2695 assert(Lex.getCode() == tgtok::Def && "Unknown tok")((Lex.getCode() == tgtok::Def && "Unknown tok") ? static_cast
<void> (0) : __assert_fail ("Lex.getCode() == tgtok::Def && \"Unknown tok\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 2695, __PRETTY_FUNCTION__))
;
2696 Lex.Lex(); // Eat the 'def' token.
2697
2698 // Parse ObjectName and make a record for it.
2699 std::unique_ptr<Record> CurRec;
2700 Init *Name = ParseObjectName(CurMultiClass);
2701 if (!Name)
2702 return true;
2703
2704 if (isa<UnsetInit>(Name))
2705 CurRec = make_unique<Record>(Records.getNewAnonymousName(), DefLoc, Records,
2706 /*Anonymous=*/true);
2707 else
2708 CurRec = make_unique<Record>(Name, DefLoc, Records);
2709
2710 if (ParseObjectBody(CurRec.get()))
2711 return true;
2712
2713 return addEntry(std::move(CurRec));
2714}
2715
2716/// ParseDefset - Parse a defset statement.
2717///
2718/// Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
2719///
2720bool TGParser::ParseDefset() {
2721 assert(Lex.getCode() == tgtok::Defset)((Lex.getCode() == tgtok::Defset) ? static_cast<void> (
0) : __assert_fail ("Lex.getCode() == tgtok::Defset", "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 2721, __PRETTY_FUNCTION__))
;
2722 Lex.Lex(); // Eat the 'defset' token
2723
2724 DefsetRecord Defset;
2725 Defset.Loc = Lex.getLoc();
2726 RecTy *Type = ParseType();
2727 if (!Type)
2728 return true;
2729 if (!isa<ListRecTy>(Type))
2730 return Error(Defset.Loc, "expected list type");
2731 Defset.EltTy = cast<ListRecTy>(Type)->getElementType();
2732
2733 if (Lex.getCode() != tgtok::Id)
2734 return TokError("expected identifier");
2735 StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
2736 if (Records.getGlobal(DeclName->getValue()))
2737 return TokError("def or global variable of this name already exists");
2738
2739 if (Lex.Lex() != tgtok::equal) // Eat the identifier
2740 return TokError("expected '='");
2741 if (Lex.Lex() != tgtok::l_brace) // Eat the '='
2742 return TokError("expected '{'");
2743 SMLoc BraceLoc = Lex.getLoc();
2744 Lex.Lex(); // Eat the '{'
2745
2746 Defsets.push_back(&Defset);
2747 bool Err = ParseObjectList(nullptr);
2748 Defsets.pop_back();
2749 if (Err)
2750 return true;
2751
2752 if (Lex.getCode() != tgtok::r_brace) {
2753 TokError("expected '}' at end of defset");
2754 return Error(BraceLoc, "to match this '{'");
2755 }
2756 Lex.Lex(); // Eat the '}'
2757
2758 Records.addExtraGlobal(DeclName->getValue(),
2759 ListInit::get(Defset.Elements, Defset.EltTy));
2760 return false;
2761}
2762
2763/// ParseForeach - Parse a for statement. Return the record corresponding
2764/// to it. This returns true on error.
2765///
2766/// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2767/// Foreach ::= FOREACH Declaration IN Object
2768///
2769bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2770 SMLoc Loc = Lex.getLoc();
2771 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok")((Lex.getCode() == tgtok::Foreach && "Unknown tok") ?
static_cast<void> (0) : __assert_fail ("Lex.getCode() == tgtok::Foreach && \"Unknown tok\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 2771, __PRETTY_FUNCTION__))
;
2772 Lex.Lex(); // Eat the 'for' token.
2773
2774 // Make a temporary object to record items associated with the for
2775 // loop.
2776 Init *ListValue = nullptr;
2777 VarInit *IterName = ParseForeachDeclaration(ListValue);
2778 if (!IterName)
2779 return TokError("expected declaration in for");
2780
2781 if (Lex.getCode() != tgtok::In)
2782 return TokError("Unknown tok");
2783 Lex.Lex(); // Eat the in
2784
2785 // Create a loop object and remember it.
2786 Loops.push_back(llvm::make_unique<ForeachLoop>(Loc, IterName, ListValue));
2787
2788 if (Lex.getCode() != tgtok::l_brace) {
2789 // FOREACH Declaration IN Object
2790 if (ParseObject(CurMultiClass))
2791 return true;
2792 } else {
2793 SMLoc BraceLoc = Lex.getLoc();
2794 // Otherwise, this is a group foreach.
2795 Lex.Lex(); // eat the '{'.
2796
2797 // Parse the object list.
2798 if (ParseObjectList(CurMultiClass))
2799 return true;
2800
2801 if (Lex.getCode() != tgtok::r_brace) {
2802 TokError("expected '}' at end of foreach command");
2803 return Error(BraceLoc, "to match this '{'");
2804 }
2805 Lex.Lex(); // Eat the }
2806 }
2807
2808 // Resolve the loop or store it for later resolution.
2809 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
2810 Loops.pop_back();
2811
2812 return addEntry(std::move(Loop));
2813}
2814
2815/// ParseClass - Parse a tblgen class definition.
2816///
2817/// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2818///
2819bool TGParser::ParseClass() {
2820 assert(Lex.getCode() == tgtok::Class && "Unexpected token!")((Lex.getCode() == tgtok::Class && "Unexpected token!"
) ? static_cast<void> (0) : __assert_fail ("Lex.getCode() == tgtok::Class && \"Unexpected token!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 2820, __PRETTY_FUNCTION__))
;
2821 Lex.Lex();
2822
2823 if (Lex.getCode() != tgtok::Id)
2824 return TokError("expected class name after 'class' keyword");
2825
2826 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2827 if (CurRec) {
2828 // If the body was previously defined, this is an error.
2829 if (!CurRec->getValues().empty() ||
2830 !CurRec->getSuperClasses().empty() ||
2831 !CurRec->getTemplateArgs().empty())
2832 return TokError("Class '" + CurRec->getNameInitAsString() +
2833 "' already defined");
2834 } else {
2835 // If this is the first reference to this class, create and add it.
2836 auto NewRec =
2837 llvm::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records,
2838 /*Class=*/true);
2839 CurRec = NewRec.get();
2840 Records.addClass(std::move(NewRec));
2841 }
2842 Lex.Lex(); // eat the name.
2843
2844 // If there are template args, parse them.
2845 if (Lex.getCode() == tgtok::less)
2846 if (ParseTemplateArgList(CurRec))
2847 return true;
2848
2849 return ParseObjectBody(CurRec);
2850}
2851
2852/// ParseLetList - Parse a non-empty list of assignment expressions into a list
2853/// of LetRecords.
2854///
2855/// LetList ::= LetItem (',' LetItem)*
2856/// LetItem ::= ID OptionalRangeList '=' Value
2857///
2858void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) {
2859 while (true) {
2860 if (Lex.getCode() != tgtok::Id) {
2861 TokError("expected identifier in let definition");
2862 Result.clear();
2863 return;
2864 }
2865
2866 StringInit *Name = StringInit::get(Lex.getCurStrVal());
2867 SMLoc NameLoc = Lex.getLoc();
2868 Lex.Lex(); // Eat the identifier.
2869
2870 // Check for an optional RangeList.
2871 SmallVector<unsigned, 16> Bits;
2872 if (ParseOptionalRangeList(Bits)) {
2873 Result.clear();
2874 return;
2875 }
2876 std::reverse(Bits.begin(), Bits.end());
2877
2878 if (Lex.getCode() != tgtok::equal) {
2879 TokError("expected '=' in let expression");
2880 Result.clear();
2881 return;
2882 }
2883 Lex.Lex(); // eat the '='.
2884
2885 Init *Val = ParseValue(nullptr);
2886 if (!Val) {
2887 Result.clear();
2888 return;
2889 }
2890
2891 // Now that we have everything, add the record.
2892 Result.emplace_back(Name, Bits, Val, NameLoc);
2893
2894 if (Lex.getCode() != tgtok::comma)
2895 return;
2896 Lex.Lex(); // eat the comma.
2897 }
2898}
2899
2900/// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2901/// different related productions. This works inside multiclasses too.
2902///
2903/// Object ::= LET LetList IN '{' ObjectList '}'
2904/// Object ::= LET LetList IN Object
2905///
2906bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2907 assert(Lex.getCode() == tgtok::Let && "Unexpected token")((Lex.getCode() == tgtok::Let && "Unexpected token") ?
static_cast<void> (0) : __assert_fail ("Lex.getCode() == tgtok::Let && \"Unexpected token\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 2907, __PRETTY_FUNCTION__))
;
2908 Lex.Lex();
2909
2910 // Add this entry to the let stack.
2911 SmallVector<LetRecord, 8> LetInfo;
2912 ParseLetList(LetInfo);
2913 if (LetInfo.empty()) return true;
2914 LetStack.push_back(std::move(LetInfo));
2915
2916 if (Lex.getCode() != tgtok::In)
2917 return TokError("expected 'in' at end of top-level 'let'");
2918 Lex.Lex();
2919
2920 // If this is a scalar let, just handle it now
2921 if (Lex.getCode() != tgtok::l_brace) {
2922 // LET LetList IN Object
2923 if (ParseObject(CurMultiClass))
2924 return true;
2925 } else { // Object ::= LETCommand '{' ObjectList '}'
2926 SMLoc BraceLoc = Lex.getLoc();
2927 // Otherwise, this is a group let.
2928 Lex.Lex(); // eat the '{'.
2929
2930 // Parse the object list.
2931 if (ParseObjectList(CurMultiClass))
2932 return true;
2933
2934 if (Lex.getCode() != tgtok::r_brace) {
2935 TokError("expected '}' at end of top level let command");
2936 return Error(BraceLoc, "to match this '{'");
2937 }
2938 Lex.Lex();
2939 }
2940
2941 // Outside this let scope, this let block is not active.
2942 LetStack.pop_back();
2943 return false;
2944}
2945
2946/// ParseMultiClass - Parse a multiclass definition.
2947///
2948/// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2949/// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2950/// MultiClassObject ::= DefInst
2951/// MultiClassObject ::= MultiClassInst
2952/// MultiClassObject ::= DefMInst
2953/// MultiClassObject ::= LETCommand '{' ObjectList '}'
2954/// MultiClassObject ::= LETCommand Object
2955///
2956bool TGParser::ParseMultiClass() {
2957 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token")((Lex.getCode() == tgtok::MultiClass && "Unexpected token"
) ? static_cast<void> (0) : __assert_fail ("Lex.getCode() == tgtok::MultiClass && \"Unexpected token\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 2957, __PRETTY_FUNCTION__))
;
2958 Lex.Lex(); // Eat the multiclass token.
2959
2960 if (Lex.getCode() != tgtok::Id)
2961 return TokError("expected identifier after multiclass for name");
2962 std::string Name = Lex.getCurStrVal();
2963
2964 auto Result =
2965 MultiClasses.insert(std::make_pair(Name,
2966 llvm::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
2967
2968 if (!Result.second)
2969 return TokError("multiclass '" + Name + "' already defined");
2970
2971 CurMultiClass = Result.first->second.get();
2972 Lex.Lex(); // Eat the identifier.
2973
2974 // If there are template args, parse them.
2975 if (Lex.getCode() == tgtok::less)
2976 if (ParseTemplateArgList(nullptr))
2977 return true;
2978
2979 bool inherits = false;
2980
2981 // If there are submulticlasses, parse them.
2982 if (Lex.getCode() == tgtok::colon) {
2983 inherits = true;
2984
2985 Lex.Lex();
2986
2987 // Read all of the submulticlasses.
2988 SubMultiClassReference SubMultiClass =
2989 ParseSubMultiClassReference(CurMultiClass);
2990 while (true) {
2991 // Check for error.
2992 if (!SubMultiClass.MC) return true;
2993
2994 // Add it.
2995 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2996 return true;
2997
2998 if (Lex.getCode() != tgtok::comma) break;
2999 Lex.Lex(); // eat ','.
3000 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
3001 }
3002 }
3003
3004 if (Lex.getCode() != tgtok::l_brace) {
3005 if (!inherits)
3006 return TokError("expected '{' in multiclass definition");
3007 if (Lex.getCode() != tgtok::semi)
3008 return TokError("expected ';' in multiclass definition");
3009 Lex.Lex(); // eat the ';'.
3010 } else {
3011 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
3012 return TokError("multiclass must contain at least one def");
3013
3014 while (Lex.getCode() != tgtok::r_brace) {
3015 switch (Lex.getCode()) {
3016 default:
3017 return TokError("expected 'let', 'def', 'defm' or 'foreach' in "
3018 "multiclass body");
3019 case tgtok::Let:
3020 case tgtok::Def:
3021 case tgtok::Defm:
3022 case tgtok::Foreach:
3023 if (ParseObject(CurMultiClass))
3024 return true;
3025 break;
3026 }
3027 }
3028 Lex.Lex(); // eat the '}'.
3029 }
3030
3031 CurMultiClass = nullptr;
3032 return false;
3033}
3034
3035/// ParseDefm - Parse the instantiation of a multiclass.
3036///
3037/// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
3038///
3039bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
3040 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!")((Lex.getCode() == tgtok::Defm && "Unexpected token!"
) ? static_cast<void> (0) : __assert_fail ("Lex.getCode() == tgtok::Defm && \"Unexpected token!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 3040, __PRETTY_FUNCTION__))
;
3041 Lex.Lex(); // eat the defm
3042
3043 Init *DefmName = ParseObjectName(CurMultiClass);
3044 if (!DefmName)
3045 return true;
3046 if (isa<UnsetInit>(DefmName)) {
3047 DefmName = Records.getNewAnonymousName();
3048 if (CurMultiClass)
3049 DefmName = BinOpInit::getStrConcat(
3050 VarInit::get(QualifiedNameOfImplicitName(CurMultiClass),
3051 StringRecTy::get()),
3052 DefmName);
3053 }
3054
3055 if (Lex.getCode() != tgtok::colon)
3056 return TokError("expected ':' after defm identifier");
3057
3058 // Keep track of the new generated record definitions.
3059 std::vector<RecordsEntry> NewEntries;
3060
3061 // This record also inherits from a regular class (non-multiclass)?
3062 bool InheritFromClass = false;
3063
3064 // eat the colon.
3065 Lex.Lex();
3066
3067 SMLoc SubClassLoc = Lex.getLoc();
3068 SubClassReference Ref = ParseSubClassReference(nullptr, true);
3069
3070 while (true) {
3071 if (!Ref.Rec) return true;
3072
3073 // To instantiate a multiclass, we need to first get the multiclass, then
3074 // instantiate each def contained in the multiclass with the SubClassRef
3075 // template parameters.
3076 MultiClass *MC = MultiClasses[Ref.Rec->getName()].get();
3077 assert(MC && "Didn't lookup multiclass correctly?")((MC && "Didn't lookup multiclass correctly?") ? static_cast
<void> (0) : __assert_fail ("MC && \"Didn't lookup multiclass correctly?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/TableGen/TGParser.cpp"
, 3077, __PRETTY_FUNCTION__))
;
3078 ArrayRef<Init*> TemplateVals = Ref.TemplateArgs;
3079
3080 // Verify that the correct number of template arguments were specified.
3081 ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs();
3082 if (TArgs.size() < TemplateVals.size())
3083 return Error(SubClassLoc,
3084 "more template args specified than multiclass expects");
3085
3086 SubstStack Substs;
3087 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
3088 if (i < TemplateVals.size()) {
3089 Substs.emplace_back(TArgs[i], TemplateVals[i]);
3090 } else {
3091 Init *Default = MC->Rec.getValue(TArgs[i])->getValue();
3092 if (!Default->isComplete()) {
3093 return Error(SubClassLoc,
3094 "value not specified for template argument #" +
3095 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
3096 ") of multiclass '" + MC->Rec.getNameInitAsString() +
3097 "'");
3098 }
3099 Substs.emplace_back(TArgs[i], Default);
3100 }
3101 }
3102
3103 Substs.emplace_back(QualifiedNameOfImplicitName(MC), DefmName);
3104
3105 if (resolve(MC->Entries, Substs, CurMultiClass == nullptr, &NewEntries,
3106 &SubClassLoc))
3107 return true;
3108
3109 if (Lex.getCode() != tgtok::comma) break;
3110 Lex.Lex(); // eat ','.
3111
3112 if (Lex.getCode() != tgtok::Id)
3113 return TokError("expected identifier");
3114
3115 SubClassLoc = Lex.getLoc();
3116
3117 // A defm can inherit from regular classes (non-multiclass) as
3118 // long as they come in the end of the inheritance list.
3119 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
3120
3121 if (InheritFromClass)
3122 break;
3123
3124 Ref = ParseSubClassReference(nullptr, true);
3125 }
3126
3127 if (InheritFromClass) {
3128 // Process all the classes to inherit as if they were part of a
3129 // regular 'def' and inherit all record values.
3130 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
3131 while (true) {
3132 // Check for error.
3133 if (!SubClass.Rec) return true;
3134
3135 // Get the expanded definition prototypes and teach them about
3136 // the record values the current class to inherit has
3137 for (auto &E : NewEntries) {
3138 // Add it.
3139 if (AddSubClass(E, SubClass))
3140 return true;
3141 }
3142
3143 if (Lex.getCode() != tgtok::comma) break;
3144 Lex.Lex(); // eat ','.
3145 SubClass = ParseSubClassReference(nullptr, false);
3146 }
3147 }
3148
3149 for (auto &E : NewEntries) {
3150 if (ApplyLetStack(E))
3151 return true;
3152
3153 addEntry(std::move(E));
3154 }
3155
3156 if (Lex.getCode() != tgtok::semi)
3157 return TokError("expected ';' at end of defm");
3158 Lex.Lex();
3159
3160 return false;
3161}
3162
3163/// ParseObject
3164/// Object ::= ClassInst
3165/// Object ::= DefInst
3166/// Object ::= MultiClassInst
3167/// Object ::= DefMInst
3168/// Object ::= LETCommand '{' ObjectList '}'
3169/// Object ::= LETCommand Object
3170bool TGParser::ParseObject(MultiClass *MC) {
3171 switch (Lex.getCode()) {
3172 default:
3173 return TokError("Expected class, def, defm, defset, multiclass, let or "
3174 "foreach");
3175 case tgtok::Let: return ParseTopLevelLet(MC);
3176 case tgtok::Def: return ParseDef(MC);
3177 case tgtok::Foreach: return ParseForeach(MC);
3178 case tgtok::Defm: return ParseDefm(MC);
3179 case tgtok::Defset:
3180 if (MC)
3181 return TokError("defset is not allowed inside multiclass");
3182 return ParseDefset();
3183 case tgtok::Class:
3184 if (MC)
3185 return TokError("class is not allowed inside multiclass");
3186 if (!Loops.empty())
3187 return TokError("class is not allowed inside foreach loop");
3188 return ParseClass();
3189 case tgtok::MultiClass:
3190 if (!Loops.empty())
3191 return TokError("multiclass is not allowed inside foreach loop");
3192 return ParseMultiClass();
3193 }
3194}
3195
3196/// ParseObjectList
3197/// ObjectList :== Object*
3198bool TGParser::ParseObjectList(MultiClass *MC) {
3199 while (isObjectStart(Lex.getCode())) {
3200 if (ParseObject(MC))
3201 return true;
3202 }
3203 return false;
3204}
3205
3206bool TGParser::ParseFile() {
3207 Lex.Lex(); // Prime the lexer.
3208 if (ParseObjectList()) return true;
3209
3210 // If we have unread input at the end of the file, report it.
3211 if (Lex.getCode() == tgtok::Eof)
3212 return false;
3213
3214 return TokError("Unexpected input at top level");
3215}
3216
3217#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3218LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void RecordsEntry::dump() const {
3219 if (Loop)
3220 Loop->dump();
3221 if (Rec)
3222 Rec->dump();
3223}
3224
3225LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void ForeachLoop::dump() const {
3226 errs() << "foreach " << IterVar->getAsString() << " = "
3227 << ListValue->getAsString() << " in {\n";
3228
3229 for (const auto &E : Entries)
3230 E.dump();
3231
3232 errs() << "}\n";
3233}
3234
3235LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void MultiClass::dump() const {
3236 errs() << "Record:\n";
3237 Rec.dump();
3238
3239 errs() << "Defs:\n";
3240 for (const auto &E : Entries)
3241 E.dump();
3242}
3243#endif