Bug Summary

File:build/source/llvm/lib/TableGen/Record.cpp
Warning:line 895, column 25
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name Record.cpp -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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16 -I lib/TableGen -I /build/source/llvm/lib/TableGen -I include -I /build/source/llvm/include -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -source-date-epoch 1670191760 -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-12-05-012027-15999-1 -x c++ /build/source/llvm/lib/TableGen/Record.cpp
1//===- Record.cpp - Record implementation ---------------------------------===//
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 tablegen record classes.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/TableGen/Record.h"
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/FoldingSet.h"
17#include "llvm/ADT/SmallString.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/StringMap.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/Config/llvm-config.h"
23#include "llvm/Support/Allocator.h"
24#include "llvm/Support/Casting.h"
25#include "llvm/Support/Compiler.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/MathExtras.h"
28#include "llvm/Support/SMLoc.h"
29#include "llvm/Support/raw_ostream.h"
30#include "llvm/TableGen/Error.h"
31#include <cassert>
32#include <cstdint>
33#include <map>
34#include <memory>
35#include <string>
36#include <utility>
37#include <vector>
38
39using namespace llvm;
40
41#define DEBUG_TYPE"tblgen-records" "tblgen-records"
42
43//===----------------------------------------------------------------------===//
44// Context
45//===----------------------------------------------------------------------===//
46
47namespace llvm {
48namespace detail {
49/// This class represents the internal implementation of the RecordKeeper.
50/// It contains all of the contextual static state of the Record classes. It is
51/// kept out-of-line to simplify dependencies, and also make it easier for
52/// internal classes to access the uniquer state of the keeper.
53struct RecordKeeperImpl {
54 RecordKeeperImpl(RecordKeeper &RK)
55 : SharedBitRecTy(RK), SharedIntRecTy(RK), SharedStringRecTy(RK),
56 SharedDagRecTy(RK), AnyRecord(RK, 0), TheUnsetInit(RK),
57 TrueBitInit(true, &SharedBitRecTy),
58 FalseBitInit(false, &SharedBitRecTy), StringInitStringPool(Allocator),
59 StringInitCodePool(Allocator), AnonCounter(0), LastRecordID(0) {}
60
61 BumpPtrAllocator Allocator;
62 std::vector<BitsRecTy *> SharedBitsRecTys;
63 BitRecTy SharedBitRecTy;
64 IntRecTy SharedIntRecTy;
65 StringRecTy SharedStringRecTy;
66 DagRecTy SharedDagRecTy;
67
68 RecordRecTy AnyRecord;
69 UnsetInit TheUnsetInit;
70 BitInit TrueBitInit;
71 BitInit FalseBitInit;
72
73 FoldingSet<BitsInit> TheBitsInitPool;
74 std::map<int64_t, IntInit *> TheIntInitPool;
75 StringMap<StringInit *, BumpPtrAllocator &> StringInitStringPool;
76 StringMap<StringInit *, BumpPtrAllocator &> StringInitCodePool;
77 FoldingSet<ListInit> TheListInitPool;
78 FoldingSet<UnOpInit> TheUnOpInitPool;
79 FoldingSet<BinOpInit> TheBinOpInitPool;
80 FoldingSet<TernOpInit> TheTernOpInitPool;
81 FoldingSet<FoldOpInit> TheFoldOpInitPool;
82 FoldingSet<IsAOpInit> TheIsAOpInitPool;
83 FoldingSet<ExistsOpInit> TheExistsOpInitPool;
84 DenseMap<std::pair<RecTy *, Init *>, VarInit *> TheVarInitPool;
85 DenseMap<std::pair<TypedInit *, unsigned>, VarBitInit *> TheVarBitInitPool;
86 DenseMap<std::pair<TypedInit *, unsigned>, VarListElementInit *>
87 TheVarListElementInitPool;
88 FoldingSet<VarDefInit> TheVarDefInitPool;
89 DenseMap<std::pair<Init *, StringInit *>, FieldInit *> TheFieldInitPool;
90 FoldingSet<CondOpInit> TheCondOpInitPool;
91 FoldingSet<DagInit> TheDagInitPool;
92 FoldingSet<RecordRecTy> RecordTypePool;
93
94 unsigned AnonCounter;
95 unsigned LastRecordID;
96};
97} // namespace detail
98} // namespace llvm
99
100//===----------------------------------------------------------------------===//
101// Type implementations
102//===----------------------------------------------------------------------===//
103
104#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
105LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void RecTy::dump() const { print(errs()); }
106#endif
107
108ListRecTy *RecTy::getListTy() {
109 if (!ListTy)
110 ListTy = new (RK.getImpl().Allocator) ListRecTy(this);
111 return ListTy;
112}
113
114bool RecTy::typeIsConvertibleTo(const RecTy *RHS) const {
115 assert(RHS && "NULL pointer")(static_cast <bool> (RHS && "NULL pointer") ? void
(0) : __assert_fail ("RHS && \"NULL pointer\"", "llvm/lib/TableGen/Record.cpp"
, 115, __extension__ __PRETTY_FUNCTION__))
;
116 return Kind == RHS->getRecTyKind();
117}
118
119bool RecTy::typeIsA(const RecTy *RHS) const { return this == RHS; }
120
121BitRecTy *BitRecTy::get(RecordKeeper &RK) {
122 return &RK.getImpl().SharedBitRecTy;
123}
124
125bool BitRecTy::typeIsConvertibleTo(const RecTy *RHS) const{
126 if (RecTy::typeIsConvertibleTo(RHS) || RHS->getRecTyKind() == IntRecTyKind)
127 return true;
128 if (const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
129 return BitsTy->getNumBits() == 1;
130 return false;
131}
132
133BitsRecTy *BitsRecTy::get(RecordKeeper &RK, unsigned Sz) {
134 detail::RecordKeeperImpl &RKImpl = RK.getImpl();
135 if (Sz >= RKImpl.SharedBitsRecTys.size())
136 RKImpl.SharedBitsRecTys.resize(Sz + 1);
137 BitsRecTy *&Ty = RKImpl.SharedBitsRecTys[Sz];
138 if (!Ty)
139 Ty = new (RKImpl.Allocator) BitsRecTy(RK, Sz);
140 return Ty;
141}
142
143std::string BitsRecTy::getAsString() const {
144 return "bits<" + utostr(Size) + ">";
145}
146
147bool BitsRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
148 if (RecTy::typeIsConvertibleTo(RHS)) //argument and the sender are same type
149 return cast<BitsRecTy>(RHS)->Size == Size;
150 RecTyKind kind = RHS->getRecTyKind();
151 return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
152}
153
154bool BitsRecTy::typeIsA(const RecTy *RHS) const {
155 if (const BitsRecTy *RHSb = dyn_cast<BitsRecTy>(RHS))
156 return RHSb->Size == Size;
157 return false;
158}
159
160IntRecTy *IntRecTy::get(RecordKeeper &RK) {
161 return &RK.getImpl().SharedIntRecTy;
162}
163
164bool IntRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
165 RecTyKind kind = RHS->getRecTyKind();
166 return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
167}
168
169StringRecTy *StringRecTy::get(RecordKeeper &RK) {
170 return &RK.getImpl().SharedStringRecTy;
171}
172
173std::string StringRecTy::getAsString() const {
174 return "string";
175}
176
177bool StringRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
178 RecTyKind Kind = RHS->getRecTyKind();
179 return Kind == StringRecTyKind;
180}
181
182std::string ListRecTy::getAsString() const {
183 return "list<" + ElementTy->getAsString() + ">";
184}
185
186bool ListRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
187 if (const auto *ListTy = dyn_cast<ListRecTy>(RHS))
188 return ElementTy->typeIsConvertibleTo(ListTy->getElementType());
189 return false;
190}
191
192bool ListRecTy::typeIsA(const RecTy *RHS) const {
193 if (const ListRecTy *RHSl = dyn_cast<ListRecTy>(RHS))
194 return getElementType()->typeIsA(RHSl->getElementType());
195 return false;
196}
197
198DagRecTy *DagRecTy::get(RecordKeeper &RK) {
199 return &RK.getImpl().SharedDagRecTy;
200}
201
202std::string DagRecTy::getAsString() const {
203 return "dag";
204}
205
206static void ProfileRecordRecTy(FoldingSetNodeID &ID,
207 ArrayRef<Record *> Classes) {
208 ID.AddInteger(Classes.size());
209 for (Record *R : Classes)
210 ID.AddPointer(R);
211}
212
213RecordRecTy *RecordRecTy::get(RecordKeeper &RK,
214 ArrayRef<Record *> UnsortedClasses) {
215 detail::RecordKeeperImpl &RKImpl = RK.getImpl();
216 if (UnsortedClasses.empty())
217 return &RKImpl.AnyRecord;
218
219 FoldingSet<RecordRecTy> &ThePool = RKImpl.RecordTypePool;
220
221 SmallVector<Record *, 4> Classes(UnsortedClasses.begin(),
222 UnsortedClasses.end());
223 llvm::sort(Classes, [](Record *LHS, Record *RHS) {
224 return LHS->getNameInitAsString() < RHS->getNameInitAsString();
225 });
226
227 FoldingSetNodeID ID;
228 ProfileRecordRecTy(ID, Classes);
229
230 void *IP = nullptr;
231 if (RecordRecTy *Ty = ThePool.FindNodeOrInsertPos(ID, IP))
232 return Ty;
233
234#ifndef NDEBUG
235 // Check for redundancy.
236 for (unsigned i = 0; i < Classes.size(); ++i) {
237 for (unsigned j = 0; j < Classes.size(); ++j) {
238 assert(i == j || !Classes[i]->isSubClassOf(Classes[j]))(static_cast <bool> (i == j || !Classes[i]->isSubClassOf
(Classes[j])) ? void (0) : __assert_fail ("i == j || !Classes[i]->isSubClassOf(Classes[j])"
, "llvm/lib/TableGen/Record.cpp", 238, __extension__ __PRETTY_FUNCTION__
))
;
239 }
240 assert(&Classes[0]->getRecords() == &Classes[i]->getRecords())(static_cast <bool> (&Classes[0]->getRecords() ==
&Classes[i]->getRecords()) ? void (0) : __assert_fail
("&Classes[0]->getRecords() == &Classes[i]->getRecords()"
, "llvm/lib/TableGen/Record.cpp", 240, __extension__ __PRETTY_FUNCTION__
))
;
241 }
242#endif
243
244 void *Mem = RKImpl.Allocator.Allocate(
245 totalSizeToAlloc<Record *>(Classes.size()), alignof(RecordRecTy));
246 RecordRecTy *Ty = new (Mem) RecordRecTy(RK, Classes.size());
247 std::uninitialized_copy(Classes.begin(), Classes.end(),
248 Ty->getTrailingObjects<Record *>());
249 ThePool.InsertNode(Ty, IP);
250 return Ty;
251}
252RecordRecTy *RecordRecTy::get(Record *Class) {
253 assert(Class && "unexpected null class")(static_cast <bool> (Class && "unexpected null class"
) ? void (0) : __assert_fail ("Class && \"unexpected null class\""
, "llvm/lib/TableGen/Record.cpp", 253, __extension__ __PRETTY_FUNCTION__
))
;
254 return get(Class->getRecords(), Class);
255}
256
257void RecordRecTy::Profile(FoldingSetNodeID &ID) const {
258 ProfileRecordRecTy(ID, getClasses());
259}
260
261std::string RecordRecTy::getAsString() const {
262 if (NumClasses == 1)
263 return getClasses()[0]->getNameInitAsString();
264
265 std::string Str = "{";
266 bool First = true;
267 for (Record *R : getClasses()) {
268 if (!First)
269 Str += ", ";
270 First = false;
271 Str += R->getNameInitAsString();
272 }
273 Str += "}";
274 return Str;
275}
276
277bool RecordRecTy::isSubClassOf(Record *Class) const {
278 return llvm::any_of(getClasses(), [Class](Record *MySuperClass) {
279 return MySuperClass == Class ||
280 MySuperClass->isSubClassOf(Class);
281 });
282}
283
284bool RecordRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
285 if (this == RHS)
286 return true;
287
288 const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
289 if (!RTy)
290 return false;
291
292 return llvm::all_of(RTy->getClasses(), [this](Record *TargetClass) {
293 return isSubClassOf(TargetClass);
294 });
295}
296
297bool RecordRecTy::typeIsA(const RecTy *RHS) const {
298 return typeIsConvertibleTo(RHS);
299}
300
301static RecordRecTy *resolveRecordTypes(RecordRecTy *T1, RecordRecTy *T2) {
302 SmallVector<Record *, 4> CommonSuperClasses;
303 SmallVector<Record *, 4> Stack(T1->classes_begin(), T1->classes_end());
304
305 while (!Stack.empty()) {
306 Record *R = Stack.pop_back_val();
307
308 if (T2->isSubClassOf(R)) {
309 CommonSuperClasses.push_back(R);
310 } else {
311 R->getDirectSuperClasses(Stack);
312 }
313 }
314
315 return RecordRecTy::get(T1->getRecordKeeper(), CommonSuperClasses);
316}
317
318RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
319 if (T1 == T2)
320 return T1;
321
322 if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
323 if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2))
324 return resolveRecordTypes(RecTy1, RecTy2);
325 }
326
327 if (T1->typeIsConvertibleTo(T2))
328 return T2;
329 if (T2->typeIsConvertibleTo(T1))
330 return T1;
331
332 if (ListRecTy *ListTy1 = dyn_cast<ListRecTy>(T1)) {
333 if (ListRecTy *ListTy2 = dyn_cast<ListRecTy>(T2)) {
334 RecTy* NewType = resolveTypes(ListTy1->getElementType(),
335 ListTy2->getElementType());
336 if (NewType)
337 return NewType->getListTy();
338 }
339 }
340
341 return nullptr;
342}
343
344//===----------------------------------------------------------------------===//
345// Initializer implementations
346//===----------------------------------------------------------------------===//
347
348void Init::anchor() {}
349
350#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
351LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void Init::dump() const { return print(errs()); }
352#endif
353
354RecordKeeper &Init::getRecordKeeper() const {
355 if (auto *TyInit = dyn_cast<TypedInit>(this))
356 return TyInit->getType()->getRecordKeeper();
357 return cast<UnsetInit>(this)->getRecordKeeper();
358}
359
360UnsetInit *UnsetInit::get(RecordKeeper &RK) {
361 return &RK.getImpl().TheUnsetInit;
362}
363
364Init *UnsetInit::getCastTo(RecTy *Ty) const {
365 return const_cast<UnsetInit *>(this);
366}
367
368Init *UnsetInit::convertInitializerTo(RecTy *Ty) const {
369 return const_cast<UnsetInit *>(this);
370}
371
372BitInit *BitInit::get(RecordKeeper &RK, bool V) {
373 return V ? &RK.getImpl().TrueBitInit : &RK.getImpl().FalseBitInit;
374}
375
376Init *BitInit::convertInitializerTo(RecTy *Ty) const {
377 if (isa<BitRecTy>(Ty))
378 return const_cast<BitInit *>(this);
379
380 if (isa<IntRecTy>(Ty))
381 return IntInit::get(getRecordKeeper(), getValue());
382
383 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
384 // Can only convert single bit.
385 if (BRT->getNumBits() == 1)
386 return BitsInit::get(getRecordKeeper(), const_cast<BitInit *>(this));
387 }
388
389 return nullptr;
390}
391
392static void
393ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
394 ID.AddInteger(Range.size());
395
396 for (Init *I : Range)
397 ID.AddPointer(I);
398}
399
400BitsInit *BitsInit::get(RecordKeeper &RK, ArrayRef<Init *> Range) {
401 FoldingSetNodeID ID;
402 ProfileBitsInit(ID, Range);
403
404 detail::RecordKeeperImpl &RKImpl = RK.getImpl();
405 void *IP = nullptr;
406 if (BitsInit *I = RKImpl.TheBitsInitPool.FindNodeOrInsertPos(ID, IP))
407 return I;
408
409 void *Mem = RKImpl.Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()),
410 alignof(BitsInit));
411 BitsInit *I = new (Mem) BitsInit(RK, Range.size());
412 std::uninitialized_copy(Range.begin(), Range.end(),
413 I->getTrailingObjects<Init *>());
414 RKImpl.TheBitsInitPool.InsertNode(I, IP);
415 return I;
416}
417
418void BitsInit::Profile(FoldingSetNodeID &ID) const {
419 ProfileBitsInit(ID, makeArrayRef(getTrailingObjects<Init *>(), NumBits));
420}
421
422Init *BitsInit::convertInitializerTo(RecTy *Ty) const {
423 if (isa<BitRecTy>(Ty)) {
424 if (getNumBits() != 1) return nullptr; // Only accept if just one bit!
425 return getBit(0);
426 }
427
428 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
429 // If the number of bits is right, return it. Otherwise we need to expand
430 // or truncate.
431 if (getNumBits() != BRT->getNumBits()) return nullptr;
432 return const_cast<BitsInit *>(this);
433 }
434
435 if (isa<IntRecTy>(Ty)) {
436 int64_t Result = 0;
437 for (unsigned i = 0, e = getNumBits(); i != e; ++i)
438 if (auto *Bit = dyn_cast<BitInit>(getBit(i)))
439 Result |= static_cast<int64_t>(Bit->getValue()) << i;
440 else
441 return nullptr;
442 return IntInit::get(getRecordKeeper(), Result);
443 }
444
445 return nullptr;
446}
447
448Init *
449BitsInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
450 SmallVector<Init *, 16> NewBits(Bits.size());
451
452 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
453 if (Bits[i] >= getNumBits())
454 return nullptr;
455 NewBits[i] = getBit(Bits[i]);
456 }
457 return BitsInit::get(getRecordKeeper(), NewBits);
458}
459
460bool BitsInit::isConcrete() const {
461 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
462 if (!getBit(i)->isConcrete())
463 return false;
464 }
465 return true;
466}
467
468std::string BitsInit::getAsString() const {
469 std::string Result = "{ ";
470 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
471 if (i) Result += ", ";
472 if (Init *Bit = getBit(e-i-1))
473 Result += Bit->getAsString();
474 else
475 Result += "*";
476 }
477 return Result + " }";
478}
479
480// resolveReferences - If there are any field references that refer to fields
481// that have been filled in, we can propagate the values now.
482Init *BitsInit::resolveReferences(Resolver &R) const {
483 bool Changed = false;
484 SmallVector<Init *, 16> NewBits(getNumBits());
485
486 Init *CachedBitVarRef = nullptr;
487 Init *CachedBitVarResolved = nullptr;
488
489 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
490 Init *CurBit = getBit(i);
491 Init *NewBit = CurBit;
492
493 if (VarBitInit *CurBitVar = dyn_cast<VarBitInit>(CurBit)) {
494 if (CurBitVar->getBitVar() != CachedBitVarRef) {
495 CachedBitVarRef = CurBitVar->getBitVar();
496 CachedBitVarResolved = CachedBitVarRef->resolveReferences(R);
497 }
498 assert(CachedBitVarResolved && "Unresolved bitvar reference")(static_cast <bool> (CachedBitVarResolved && "Unresolved bitvar reference"
) ? void (0) : __assert_fail ("CachedBitVarResolved && \"Unresolved bitvar reference\""
, "llvm/lib/TableGen/Record.cpp", 498, __extension__ __PRETTY_FUNCTION__
))
;
499 NewBit = CachedBitVarResolved->getBit(CurBitVar->getBitNum());
500 } else {
501 // getBit(0) implicitly converts int and bits<1> values to bit.
502 NewBit = CurBit->resolveReferences(R)->getBit(0);
503 }
504
505 if (isa<UnsetInit>(NewBit) && R.keepUnsetBits())
506 NewBit = CurBit;
507 NewBits[i] = NewBit;
508 Changed |= CurBit != NewBit;
509 }
510
511 if (Changed)
512 return BitsInit::get(getRecordKeeper(), NewBits);
513
514 return const_cast<BitsInit *>(this);
515}
516
517IntInit *IntInit::get(RecordKeeper &RK, int64_t V) {
518 IntInit *&I = RK.getImpl().TheIntInitPool[V];
519 if (!I)
520 I = new (RK.getImpl().Allocator) IntInit(RK, V);
521 return I;
522}
523
524std::string IntInit::getAsString() const {
525 return itostr(Value);
526}
527
528static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
529 // For example, with NumBits == 4, we permit Values from [-7 .. 15].
530 return (NumBits >= sizeof(Value) * 8) ||
531 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
532}
533
534Init *IntInit::convertInitializerTo(RecTy *Ty) const {
535 if (isa<IntRecTy>(Ty))
536 return const_cast<IntInit *>(this);
537
538 if (isa<BitRecTy>(Ty)) {
539 int64_t Val = getValue();
540 if (Val != 0 && Val != 1) return nullptr; // Only accept 0 or 1 for a bit!
541 return BitInit::get(getRecordKeeper(), Val != 0);
542 }
543
544 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
545 int64_t Value = getValue();
546 // Make sure this bitfield is large enough to hold the integer value.
547 if (!canFitInBitfield(Value, BRT->getNumBits()))
548 return nullptr;
549
550 SmallVector<Init *, 16> NewBits(BRT->getNumBits());
551 for (unsigned i = 0; i != BRT->getNumBits(); ++i)
552 NewBits[i] =
553 BitInit::get(getRecordKeeper(), Value & ((i < 64) ? (1LL << i) : 0));
554
555 return BitsInit::get(getRecordKeeper(), NewBits);
556 }
557
558 return nullptr;
559}
560
561Init *
562IntInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
563 SmallVector<Init *, 16> NewBits(Bits.size());
564
565 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
566 if (Bits[i] >= 64)
567 return nullptr;
568
569 NewBits[i] =
570 BitInit::get(getRecordKeeper(), Value & (INT64_C(1)1L << Bits[i]));
571 }
572 return BitsInit::get(getRecordKeeper(), NewBits);
573}
574
575AnonymousNameInit *AnonymousNameInit::get(RecordKeeper &RK, unsigned V) {
576 return new (RK.getImpl().Allocator) AnonymousNameInit(RK, V);
577}
578
579StringInit *AnonymousNameInit::getNameInit() const {
580 return StringInit::get(getRecordKeeper(), getAsString());
581}
582
583std::string AnonymousNameInit::getAsString() const {
584 return "anonymous_" + utostr(Value);
585}
586
587Init *AnonymousNameInit::resolveReferences(Resolver &R) const {
588 auto *Old = const_cast<Init *>(static_cast<const Init *>(this));
589 auto *New = R.resolve(Old);
590 New = New ? New : Old;
591 if (R.isFinal())
592 if (auto *Anonymous = dyn_cast<AnonymousNameInit>(New))
593 return Anonymous->getNameInit();
594 return New;
595}
596
597StringInit *StringInit::get(RecordKeeper &RK, StringRef V, StringFormat Fmt) {
598 detail::RecordKeeperImpl &RKImpl = RK.getImpl();
599 auto &InitMap = Fmt == SF_String ? RKImpl.StringInitStringPool
600 : RKImpl.StringInitCodePool;
601 auto &Entry = *InitMap.insert(std::make_pair(V, nullptr)).first;
602 if (!Entry.second)
603 Entry.second = new (RKImpl.Allocator) StringInit(RK, Entry.getKey(), Fmt);
604 return Entry.second;
605}
606
607Init *StringInit::convertInitializerTo(RecTy *Ty) const {
608 if (isa<StringRecTy>(Ty))
609 return const_cast<StringInit *>(this);
610
611 return nullptr;
612}
613
614static void ProfileListInit(FoldingSetNodeID &ID,
615 ArrayRef<Init *> Range,
616 RecTy *EltTy) {
617 ID.AddInteger(Range.size());
618 ID.AddPointer(EltTy);
619
620 for (Init *I : Range)
621 ID.AddPointer(I);
622}
623
624ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
625 FoldingSetNodeID ID;
626 ProfileListInit(ID, Range, EltTy);
627
628 detail::RecordKeeperImpl &RK = EltTy->getRecordKeeper().getImpl();
629 void *IP = nullptr;
630 if (ListInit *I = RK.TheListInitPool.FindNodeOrInsertPos(ID, IP))
631 return I;
632
633 assert(Range.empty() || !isa<TypedInit>(Range[0]) ||(static_cast <bool> (Range.empty() || !isa<TypedInit
>(Range[0]) || cast<TypedInit>(Range[0])->getType
()->typeIsConvertibleTo(EltTy)) ? void (0) : __assert_fail
("Range.empty() || !isa<TypedInit>(Range[0]) || cast<TypedInit>(Range[0])->getType()->typeIsConvertibleTo(EltTy)"
, "llvm/lib/TableGen/Record.cpp", 634, __extension__ __PRETTY_FUNCTION__
))
634 cast<TypedInit>(Range[0])->getType()->typeIsConvertibleTo(EltTy))(static_cast <bool> (Range.empty() || !isa<TypedInit
>(Range[0]) || cast<TypedInit>(Range[0])->getType
()->typeIsConvertibleTo(EltTy)) ? void (0) : __assert_fail
("Range.empty() || !isa<TypedInit>(Range[0]) || cast<TypedInit>(Range[0])->getType()->typeIsConvertibleTo(EltTy)"
, "llvm/lib/TableGen/Record.cpp", 634, __extension__ __PRETTY_FUNCTION__
))
;
635
636 void *Mem = RK.Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()),
637 alignof(ListInit));
638 ListInit *I = new (Mem) ListInit(Range.size(), EltTy);
639 std::uninitialized_copy(Range.begin(), Range.end(),
640 I->getTrailingObjects<Init *>());
641 RK.TheListInitPool.InsertNode(I, IP);
642 return I;
643}
644
645void ListInit::Profile(FoldingSetNodeID &ID) const {
646 RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();
647
648 ProfileListInit(ID, getValues(), EltTy);
649}
650
651Init *ListInit::convertInitializerTo(RecTy *Ty) const {
652 if (getType() == Ty)
653 return const_cast<ListInit*>(this);
654
655 if (auto *LRT = dyn_cast<ListRecTy>(Ty)) {
656 SmallVector<Init*, 8> Elements;
657 Elements.reserve(getValues().size());
658
659 // Verify that all of the elements of the list are subclasses of the
660 // appropriate class!
661 bool Changed = false;
662 RecTy *ElementType = LRT->getElementType();
663 for (Init *I : getValues())
664 if (Init *CI = I->convertInitializerTo(ElementType)) {
665 Elements.push_back(CI);
666 if (CI != I)
667 Changed = true;
668 } else
669 return nullptr;
670
671 if (!Changed)
672 return const_cast<ListInit*>(this);
673 return ListInit::get(Elements, ElementType);
674 }
675
676 return nullptr;
677}
678
679Init *ListInit::convertInitListSlice(ArrayRef<unsigned> Elements) const {
680 if (Elements.size() == 1) {
681 if (Elements[0] >= size())
682 return nullptr;
683 return getElement(Elements[0]);
684 }
685
686 SmallVector<Init*, 8> Vals;
687 Vals.reserve(Elements.size());
688 for (unsigned Element : Elements) {
689 if (Element >= size())
690 return nullptr;
691 Vals.push_back(getElement(Element));
692 }
693 return ListInit::get(Vals, getElementType());
694}
695
696Record *ListInit::getElementAsRecord(unsigned i) const {
697 assert(i < NumValues && "List element index out of range!")(static_cast <bool> (i < NumValues && "List element index out of range!"
) ? void (0) : __assert_fail ("i < NumValues && \"List element index out of range!\""
, "llvm/lib/TableGen/Record.cpp", 697, __extension__ __PRETTY_FUNCTION__
))
;
698 DefInit *DI = dyn_cast<DefInit>(getElement(i));
699 if (!DI)
700 PrintFatalError("Expected record in list!");
701 return DI->getDef();
702}
703
704Init *ListInit::resolveReferences(Resolver &R) const {
705 SmallVector<Init*, 8> Resolved;
706 Resolved.reserve(size());
707 bool Changed = false;
708
709 for (Init *CurElt : getValues()) {
710 Init *E = CurElt->resolveReferences(R);
711 Changed |= E != CurElt;
712 Resolved.push_back(E);
713 }
714
715 if (Changed)
716 return ListInit::get(Resolved, getElementType());
717 return const_cast<ListInit *>(this);
718}
719
720bool ListInit::isComplete() const {
721 for (Init *Element : *this) {
722 if (!Element->isComplete())
723 return false;
724 }
725 return true;
726}
727
728bool ListInit::isConcrete() const {
729 for (Init *Element : *this) {
730 if (!Element->isConcrete())
731 return false;
732 }
733 return true;
734}
735
736std::string ListInit::getAsString() const {
737 std::string Result = "[";
738 const char *sep = "";
739 for (Init *Element : *this) {
740 Result += sep;
741 sep = ", ";
742 Result += Element->getAsString();
743 }
744 return Result + "]";
745}
746
747Init *OpInit::getBit(unsigned Bit) const {
748 if (getType() == BitRecTy::get(getRecordKeeper()))
749 return const_cast<OpInit*>(this);
750 return VarBitInit::get(const_cast<OpInit*>(this), Bit);
751}
752
753static void
754ProfileUnOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *Op, RecTy *Type) {
755 ID.AddInteger(Opcode);
756 ID.AddPointer(Op);
757 ID.AddPointer(Type);
758}
759
760UnOpInit *UnOpInit::get(UnaryOp Opc, Init *LHS, RecTy *Type) {
761 FoldingSetNodeID ID;
762 ProfileUnOpInit(ID, Opc, LHS, Type);
763
764 detail::RecordKeeperImpl &RK = Type->getRecordKeeper().getImpl();
765 void *IP = nullptr;
766 if (UnOpInit *I = RK.TheUnOpInitPool.FindNodeOrInsertPos(ID, IP))
767 return I;
768
769 UnOpInit *I = new (RK.Allocator) UnOpInit(Opc, LHS, Type);
770 RK.TheUnOpInitPool.InsertNode(I, IP);
771 return I;
772}
773
774void UnOpInit::Profile(FoldingSetNodeID &ID) const {
775 ProfileUnOpInit(ID, getOpcode(), getOperand(), getType());
776}
777
778Init *UnOpInit::Fold(Record *CurRec, bool IsFinal) const {
779 RecordKeeper &RK = getRecordKeeper();
780 switch (getOpcode()) {
10
Control jumps to 'case LOG2:' at line 890
781 case CAST:
782 if (isa<StringRecTy>(getType())) {
783 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
784 return LHSs;
785
786 if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
787 return StringInit::get(RK, LHSd->getAsString());
788
789 if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
790 LHS->convertInitializerTo(IntRecTy::get(RK))))
791 return StringInit::get(RK, LHSi->getAsString());
792
793 } else if (isa<RecordRecTy>(getType())) {
794 if (StringInit *Name = dyn_cast<StringInit>(LHS)) {
795 if (!CurRec && !IsFinal)
796 break;
797 assert(CurRec && "NULL pointer")(static_cast <bool> (CurRec && "NULL pointer") ?
void (0) : __assert_fail ("CurRec && \"NULL pointer\""
, "llvm/lib/TableGen/Record.cpp", 797, __extension__ __PRETTY_FUNCTION__
))
;
798 Record *D;
799
800 // Self-references are allowed, but their resolution is delayed until
801 // the final resolve to ensure that we get the correct type for them.
802 auto *Anonymous = dyn_cast<AnonymousNameInit>(CurRec->getNameInit());
803 if (Name == CurRec->getNameInit() ||
804 (Anonymous && Name == Anonymous->getNameInit())) {
805 if (!IsFinal)
806 break;
807 D = CurRec;
808 } else {
809 D = CurRec->getRecords().getDef(Name->getValue());
810 if (!D) {
811 if (IsFinal)
812 PrintFatalError(CurRec->getLoc(),
813 Twine("Undefined reference to record: '") +
814 Name->getValue() + "'\n");
815 break;
816 }
817 }
818
819 DefInit *DI = DefInit::get(D);
820 if (!DI->getType()->typeIsA(getType())) {
821 PrintFatalError(CurRec->getLoc(),
822 Twine("Expected type '") +
823 getType()->getAsString() + "', got '" +
824 DI->getType()->getAsString() + "' in: " +
825 getAsString() + "\n");
826 }
827 return DI;
828 }
829 }
830
831 if (Init *NewInit = LHS->convertInitializerTo(getType()))
832 return NewInit;
833 break;
834
835 case NOT:
836 if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
837 LHS->convertInitializerTo(IntRecTy::get(RK))))
838 return IntInit::get(RK, LHSi->getValue() ? 0 : 1);
839 break;
840
841 case HEAD:
842 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
843 assert(!LHSl->empty() && "Empty list in head")(static_cast <bool> (!LHSl->empty() && "Empty list in head"
) ? void (0) : __assert_fail ("!LHSl->empty() && \"Empty list in head\""
, "llvm/lib/TableGen/Record.cpp", 843, __extension__ __PRETTY_FUNCTION__
))
;
844 return LHSl->getElement(0);
845 }
846 break;
847
848 case TAIL:
849 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
850 assert(!LHSl->empty() && "Empty list in tail")(static_cast <bool> (!LHSl->empty() && "Empty list in tail"
) ? void (0) : __assert_fail ("!LHSl->empty() && \"Empty list in tail\""
, "llvm/lib/TableGen/Record.cpp", 850, __extension__ __PRETTY_FUNCTION__
))
;
851 // Note the +1. We can't just pass the result of getValues()
852 // directly.
853 return ListInit::get(LHSl->getValues().slice(1), LHSl->getElementType());
854 }
855 break;
856
857 case SIZE:
858 if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
859 return IntInit::get(RK, LHSl->size());
860 if (DagInit *LHSd = dyn_cast<DagInit>(LHS))
861 return IntInit::get(RK, LHSd->arg_size());
862 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
863 return IntInit::get(RK, LHSs->getValue().size());
864 break;
865
866 case EMPTY:
867 if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
868 return IntInit::get(RK, LHSl->empty());
869 if (DagInit *LHSd = dyn_cast<DagInit>(LHS))
870 return IntInit::get(RK, LHSd->arg_empty());
871 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
872 return IntInit::get(RK, LHSs->getValue().empty());
873 break;
874
875 case GETDAGOP:
876 if (DagInit *Dag = dyn_cast<DagInit>(LHS)) {
877 DefInit *DI = DefInit::get(Dag->getOperatorAsDef({}));
878 if (!DI->getType()->typeIsA(getType())) {
879 PrintFatalError(CurRec->getLoc(),
880 Twine("Expected type '") +
881 getType()->getAsString() + "', got '" +
882 DI->getType()->getAsString() + "' in: " +
883 getAsString() + "\n");
884 } else {
885 return DI;
886 }
887 }
888 break;
889
890 case LOG2:
891 if (IntInit *LHSi
11.1
'LHSi' is non-null
= dyn_cast_or_null<IntInit>(
11
Assuming the object is a 'CastReturnType'
12
Taking true branch
892 LHS->convertInitializerTo(IntRecTy::get(RK)))) {
893 int64_t LHSv = LHSi->getValue();
894 if (LHSv <= 0) {
13
Assuming 'LHSv' is <= 0
14
Taking true branch
895 PrintFatalError(CurRec->getLoc(),
15
Called C++ object pointer is null
896 "Illegal operation: logtwo is undefined "
897 "on arguments less than or equal to 0");
898 } else {
899 uint64_t Log = Log2_64(LHSv);
900 assert(Log <= INT64_MAX &&(static_cast <bool> (Log <= (9223372036854775807L) &&
"Log of an int64_t must be smaller than INT64_MAX") ? void (
0) : __assert_fail ("Log <= INT64_MAX && \"Log of an int64_t must be smaller than INT64_MAX\""
, "llvm/lib/TableGen/Record.cpp", 901, __extension__ __PRETTY_FUNCTION__
))
901 "Log of an int64_t must be smaller than INT64_MAX")(static_cast <bool> (Log <= (9223372036854775807L) &&
"Log of an int64_t must be smaller than INT64_MAX") ? void (
0) : __assert_fail ("Log <= INT64_MAX && \"Log of an int64_t must be smaller than INT64_MAX\""
, "llvm/lib/TableGen/Record.cpp", 901, __extension__ __PRETTY_FUNCTION__
))
;
902 return IntInit::get(RK, static_cast<int64_t>(Log));
903 }
904 }
905 break;
906 }
907 return const_cast<UnOpInit *>(this);
908}
909
910Init *UnOpInit::resolveReferences(Resolver &R) const {
911 Init *lhs = LHS->resolveReferences(R);
912
913 if (LHS != lhs || (R.isFinal() && getOpcode() == CAST))
914 return (UnOpInit::get(getOpcode(), lhs, getType()))
915 ->Fold(R.getCurrentRecord(), R.isFinal());
916 return const_cast<UnOpInit *>(this);
917}
918
919std::string UnOpInit::getAsString() const {
920 std::string Result;
921 switch (getOpcode()) {
922 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
923 case NOT: Result = "!not"; break;
924 case HEAD: Result = "!head"; break;
925 case TAIL: Result = "!tail"; break;
926 case SIZE: Result = "!size"; break;
927 case EMPTY: Result = "!empty"; break;
928 case GETDAGOP: Result = "!getdagop"; break;
929 case LOG2 : Result = "!logtwo"; break;
930 }
931 return Result + "(" + LHS->getAsString() + ")";
932}
933
934static void
935ProfileBinOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *RHS,
936 RecTy *Type) {
937 ID.AddInteger(Opcode);
938 ID.AddPointer(LHS);
939 ID.AddPointer(RHS);
940 ID.AddPointer(Type);
941}
942
943BinOpInit *BinOpInit::get(BinaryOp Opc, Init *LHS, Init *RHS, RecTy *Type) {
944 FoldingSetNodeID ID;
945 ProfileBinOpInit(ID, Opc, LHS, RHS, Type);
946
947 detail::RecordKeeperImpl &RK = LHS->getRecordKeeper().getImpl();
948 void *IP = nullptr;
949 if (BinOpInit *I = RK.TheBinOpInitPool.FindNodeOrInsertPos(ID, IP))
950 return I;
951
952 BinOpInit *I = new (RK.Allocator) BinOpInit(Opc, LHS, RHS, Type);
953 RK.TheBinOpInitPool.InsertNode(I, IP);
954 return I;
955}
956
957void BinOpInit::Profile(FoldingSetNodeID &ID) const {
958 ProfileBinOpInit(ID, getOpcode(), getLHS(), getRHS(), getType());
959}
960
961static StringInit *ConcatStringInits(const StringInit *I0,
962 const StringInit *I1) {
963 SmallString<80> Concat(I0->getValue());
964 Concat.append(I1->getValue());
965 return StringInit::get(
966 I0->getRecordKeeper(), Concat,
967 StringInit::determineFormat(I0->getFormat(), I1->getFormat()));
968}
969
970static StringInit *interleaveStringList(const ListInit *List,
971 const StringInit *Delim) {
972 if (List->size() == 0)
973 return StringInit::get(List->getRecordKeeper(), "");
974 StringInit *Element = dyn_cast<StringInit>(List->getElement(0));
975 if (!Element)
976 return nullptr;
977 SmallString<80> Result(Element->getValue());
978 StringInit::StringFormat Fmt = StringInit::SF_String;
979
980 for (unsigned I = 1, E = List->size(); I < E; ++I) {
981 Result.append(Delim->getValue());
982 StringInit *Element = dyn_cast<StringInit>(List->getElement(I));
983 if (!Element)
984 return nullptr;
985 Result.append(Element->getValue());
986 Fmt = StringInit::determineFormat(Fmt, Element->getFormat());
987 }
988 return StringInit::get(List->getRecordKeeper(), Result, Fmt);
989}
990
991static StringInit *interleaveIntList(const ListInit *List,
992 const StringInit *Delim) {
993 RecordKeeper &RK = List->getRecordKeeper();
994 if (List->size() == 0)
995 return StringInit::get(RK, "");
996 IntInit *Element = dyn_cast_or_null<IntInit>(
997 List->getElement(0)->convertInitializerTo(IntRecTy::get(RK)));
998 if (!Element)
999 return nullptr;
1000 SmallString<80> Result(Element->getAsString());
1001
1002 for (unsigned I = 1, E = List->size(); I < E; ++I) {
1003 Result.append(Delim->getValue());
1004 IntInit *Element = dyn_cast_or_null<IntInit>(
1005 List->getElement(I)->convertInitializerTo(IntRecTy::get(RK)));
1006 if (!Element)
1007 return nullptr;
1008 Result.append(Element->getAsString());
1009 }
1010 return StringInit::get(RK, Result);
1011}
1012
1013Init *BinOpInit::getStrConcat(Init *I0, Init *I1) {
1014 // Shortcut for the common case of concatenating two strings.
1015 if (const StringInit *I0s = dyn_cast<StringInit>(I0))
1016 if (const StringInit *I1s = dyn_cast<StringInit>(I1))
1017 return ConcatStringInits(I0s, I1s);
1018 return BinOpInit::get(BinOpInit::STRCONCAT, I0, I1,
1019 StringRecTy::get(I0->getRecordKeeper()));
1020}
1021
1022static ListInit *ConcatListInits(const ListInit *LHS,
1023 const ListInit *RHS) {
1024 SmallVector<Init *, 8> Args;
1025 llvm::append_range(Args, *LHS);
1026 llvm::append_range(Args, *RHS);
1027 return ListInit::get(Args, LHS->getElementType());
1028}
1029
1030Init *BinOpInit::getListConcat(TypedInit *LHS, Init *RHS) {
1031 assert(isa<ListRecTy>(LHS->getType()) && "First arg must be a list")(static_cast <bool> (isa<ListRecTy>(LHS->getType
()) && "First arg must be a list") ? void (0) : __assert_fail
("isa<ListRecTy>(LHS->getType()) && \"First arg must be a list\""
, "llvm/lib/TableGen/Record.cpp", 1031, __extension__ __PRETTY_FUNCTION__
))
;
1032
1033 // Shortcut for the common case of concatenating two lists.
1034 if (const ListInit *LHSList = dyn_cast<ListInit>(LHS))
1035 if (const ListInit *RHSList = dyn_cast<ListInit>(RHS))
1036 return ConcatListInits(LHSList, RHSList);
1037 return BinOpInit::get(BinOpInit::LISTCONCAT, LHS, RHS, LHS->getType());
1038}
1039
1040Init *BinOpInit::Fold(Record *CurRec) const {
1041 switch (getOpcode()) {
1042 case CONCAT: {
1043 DagInit *LHSs = dyn_cast<DagInit>(LHS);
1044 DagInit *RHSs = dyn_cast<DagInit>(RHS);
1045 if (LHSs && RHSs) {
1046 DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
1047 DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
1048 if ((!LOp && !isa<UnsetInit>(LHSs->getOperator())) ||
1049 (!ROp && !isa<UnsetInit>(RHSs->getOperator())))
1050 break;
1051 if (LOp && ROp && LOp->getDef() != ROp->getDef()) {
1052 PrintFatalError(Twine("Concatenated Dag operators do not match: '") +
1053 LHSs->getAsString() + "' vs. '" + RHSs->getAsString() +
1054 "'");
1055 }
1056 Init *Op = LOp ? LOp : ROp;
1057 if (!Op)
1058 Op = UnsetInit::get(getRecordKeeper());
1059
1060 SmallVector<Init*, 8> Args;
1061 SmallVector<StringInit*, 8> ArgNames;
1062 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
1063 Args.push_back(LHSs->getArg(i));
1064 ArgNames.push_back(LHSs->getArgName(i));
1065 }
1066 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
1067 Args.push_back(RHSs->getArg(i));
1068 ArgNames.push_back(RHSs->getArgName(i));
1069 }
1070 return DagInit::get(Op, nullptr, Args, ArgNames);
1071 }
1072 break;
1073 }
1074 case LISTCONCAT: {
1075 ListInit *LHSs = dyn_cast<ListInit>(LHS);
1076 ListInit *RHSs = dyn_cast<ListInit>(RHS);
1077 if (LHSs && RHSs) {
1078 SmallVector<Init *, 8> Args;
1079 llvm::append_range(Args, *LHSs);
1080 llvm::append_range(Args, *RHSs);
1081 return ListInit::get(Args, LHSs->getElementType());
1082 }
1083 break;
1084 }
1085 case LISTSPLAT: {
1086 TypedInit *Value = dyn_cast<TypedInit>(LHS);
1087 IntInit *Size = dyn_cast<IntInit>(RHS);
1088 if (Value && Size) {
1089 SmallVector<Init *, 8> Args(Size->getValue(), Value);
1090 return ListInit::get(Args, Value->getType());
1091 }
1092 break;
1093 }
1094 case STRCONCAT: {
1095 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1096 StringInit *RHSs = dyn_cast<StringInit>(RHS);
1097 if (LHSs && RHSs)
1098 return ConcatStringInits(LHSs, RHSs);
1099 break;
1100 }
1101 case INTERLEAVE: {
1102 ListInit *List = dyn_cast<ListInit>(LHS);
1103 StringInit *Delim = dyn_cast<StringInit>(RHS);
1104 if (List && Delim) {
1105 StringInit *Result;
1106 if (isa<StringRecTy>(List->getElementType()))
1107 Result = interleaveStringList(List, Delim);
1108 else
1109 Result = interleaveIntList(List, Delim);
1110 if (Result)
1111 return Result;
1112 }
1113 break;
1114 }
1115 case EQ:
1116 case NE:
1117 case LE:
1118 case LT:
1119 case GE:
1120 case GT: {
1121 // First see if we have two bit, bits, or int.
1122 IntInit *LHSi = dyn_cast_or_null<IntInit>(
1123 LHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
1124 IntInit *RHSi = dyn_cast_or_null<IntInit>(
1125 RHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
1126
1127 if (LHSi && RHSi) {
1128 bool Result;
1129 switch (getOpcode()) {
1130 case EQ: Result = LHSi->getValue() == RHSi->getValue(); break;
1131 case NE: Result = LHSi->getValue() != RHSi->getValue(); break;
1132 case LE: Result = LHSi->getValue() <= RHSi->getValue(); break;
1133 case LT: Result = LHSi->getValue() < RHSi->getValue(); break;
1134 case GE: Result = LHSi->getValue() >= RHSi->getValue(); break;
1135 case GT: Result = LHSi->getValue() > RHSi->getValue(); break;
1136 default: llvm_unreachable("unhandled comparison")::llvm::llvm_unreachable_internal("unhandled comparison", "llvm/lib/TableGen/Record.cpp"
, 1136)
;
1137 }
1138 return BitInit::get(getRecordKeeper(), Result);
1139 }
1140
1141 // Next try strings.
1142 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1143 StringInit *RHSs = dyn_cast<StringInit>(RHS);
1144
1145 if (LHSs && RHSs) {
1146 bool Result;
1147 switch (getOpcode()) {
1148 case EQ: Result = LHSs->getValue() == RHSs->getValue(); break;
1149 case NE: Result = LHSs->getValue() != RHSs->getValue(); break;
1150 case LE: Result = LHSs->getValue() <= RHSs->getValue(); break;
1151 case LT: Result = LHSs->getValue() < RHSs->getValue(); break;
1152 case GE: Result = LHSs->getValue() >= RHSs->getValue(); break;
1153 case GT: Result = LHSs->getValue() > RHSs->getValue(); break;
1154 default: llvm_unreachable("unhandled comparison")::llvm::llvm_unreachable_internal("unhandled comparison", "llvm/lib/TableGen/Record.cpp"
, 1154)
;
1155 }
1156 return BitInit::get(getRecordKeeper(), Result);
1157 }
1158
1159 // Finally, !eq and !ne can be used with records.
1160 if (getOpcode() == EQ || getOpcode() == NE) {
1161 DefInit *LHSd = dyn_cast<DefInit>(LHS);
1162 DefInit *RHSd = dyn_cast<DefInit>(RHS);
1163 if (LHSd && RHSd)
1164 return BitInit::get(getRecordKeeper(),
1165 (getOpcode() == EQ) ? LHSd == RHSd : LHSd != RHSd);
1166 }
1167
1168 break;
1169 }
1170 case SETDAGOP: {
1171 DagInit *Dag = dyn_cast<DagInit>(LHS);
1172 DefInit *Op = dyn_cast<DefInit>(RHS);
1173 if (Dag && Op) {
1174 SmallVector<Init*, 8> Args;
1175 SmallVector<StringInit*, 8> ArgNames;
1176 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1177 Args.push_back(Dag->getArg(i));
1178 ArgNames.push_back(Dag->getArgName(i));
1179 }
1180 return DagInit::get(Op, nullptr, Args, ArgNames);
1181 }
1182 break;
1183 }
1184 case ADD:
1185 case SUB:
1186 case MUL:
1187 case DIV:
1188 case AND:
1189 case OR:
1190 case XOR:
1191 case SHL:
1192 case SRA:
1193 case SRL: {
1194 IntInit *LHSi = dyn_cast_or_null<IntInit>(
1195 LHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
1196 IntInit *RHSi = dyn_cast_or_null<IntInit>(
1197 RHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
1198 if (LHSi && RHSi) {
1199 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
1200 int64_t Result;
1201 switch (getOpcode()) {
1202 default: llvm_unreachable("Bad opcode!")::llvm::llvm_unreachable_internal("Bad opcode!", "llvm/lib/TableGen/Record.cpp"
, 1202)
;
1203 case ADD: Result = LHSv + RHSv; break;
1204 case SUB: Result = LHSv - RHSv; break;
1205 case MUL: Result = LHSv * RHSv; break;
1206 case DIV:
1207 if (RHSv == 0)
1208 PrintFatalError(CurRec->getLoc(),
1209 "Illegal operation: division by zero");
1210 else if (LHSv == INT64_MIN(-9223372036854775807L -1) && RHSv == -1)
1211 PrintFatalError(CurRec->getLoc(),
1212 "Illegal operation: INT64_MIN / -1");
1213 else
1214 Result = LHSv / RHSv;
1215 break;
1216 case AND: Result = LHSv & RHSv; break;
1217 case OR: Result = LHSv | RHSv; break;
1218 case XOR: Result = LHSv ^ RHSv; break;
1219 case SHL: Result = (uint64_t)LHSv << (uint64_t)RHSv; break;
1220 case SRA: Result = LHSv >> RHSv; break;
1221 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
1222 }
1223 return IntInit::get(getRecordKeeper(), Result);
1224 }
1225 break;
1226 }
1227 }
1228 return const_cast<BinOpInit *>(this);
1229}
1230
1231Init *BinOpInit::resolveReferences(Resolver &R) const {
1232 Init *lhs = LHS->resolveReferences(R);
1233 Init *rhs = RHS->resolveReferences(R);
1234
1235 if (LHS != lhs || RHS != rhs)
1236 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))
1237 ->Fold(R.getCurrentRecord());
1238 return const_cast<BinOpInit *>(this);
1239}
1240
1241std::string BinOpInit::getAsString() const {
1242 std::string Result;
1243 switch (getOpcode()) {
1244 case CONCAT: Result = "!con"; break;
1245 case ADD: Result = "!add"; break;
1246 case SUB: Result = "!sub"; break;
1247 case MUL: Result = "!mul"; break;
1248 case DIV: Result = "!div"; break;
1249 case AND: Result = "!and"; break;
1250 case OR: Result = "!or"; break;
1251 case XOR: Result = "!xor"; break;
1252 case SHL: Result = "!shl"; break;
1253 case SRA: Result = "!sra"; break;
1254 case SRL: Result = "!srl"; break;
1255 case EQ: Result = "!eq"; break;
1256 case NE: Result = "!ne"; break;
1257 case LE: Result = "!le"; break;
1258 case LT: Result = "!lt"; break;
1259 case GE: Result = "!ge"; break;
1260 case GT: Result = "!gt"; break;
1261 case LISTCONCAT: Result = "!listconcat"; break;
1262 case LISTSPLAT: Result = "!listsplat"; break;
1263 case STRCONCAT: Result = "!strconcat"; break;
1264 case INTERLEAVE: Result = "!interleave"; break;
1265 case SETDAGOP: Result = "!setdagop"; break;
1266 }
1267 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
1268}
1269
1270static void
1271ProfileTernOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *MHS,
1272 Init *RHS, RecTy *Type) {
1273 ID.AddInteger(Opcode);
1274 ID.AddPointer(LHS);
1275 ID.AddPointer(MHS);
1276 ID.AddPointer(RHS);
1277 ID.AddPointer(Type);
1278}
1279
1280TernOpInit *TernOpInit::get(TernaryOp Opc, Init *LHS, Init *MHS, Init *RHS,
1281 RecTy *Type) {
1282 FoldingSetNodeID ID;
1283 ProfileTernOpInit(ID, Opc, LHS, MHS, RHS, Type);
1284
1285 detail::RecordKeeperImpl &RK = LHS->getRecordKeeper().getImpl();
1286 void *IP = nullptr;
1287 if (TernOpInit *I = RK.TheTernOpInitPool.FindNodeOrInsertPos(ID, IP))
1288 return I;
1289
1290 TernOpInit *I = new (RK.Allocator) TernOpInit(Opc, LHS, MHS, RHS, Type);
1291 RK.TheTernOpInitPool.InsertNode(I, IP);
1292 return I;
1293}
1294
1295void TernOpInit::Profile(FoldingSetNodeID &ID) const {
1296 ProfileTernOpInit(ID, getOpcode(), getLHS(), getMHS(), getRHS(), getType());
1297}
1298
1299static Init *ItemApply(Init *LHS, Init *MHSe, Init *RHS, Record *CurRec) {
1300 MapResolver R(CurRec);
1301 R.set(LHS, MHSe);
1302 return RHS->resolveReferences(R);
1303}
1304
1305static Init *ForeachDagApply(Init *LHS, DagInit *MHSd, Init *RHS,
1306 Record *CurRec) {
1307 bool Change = false;
1308 Init *Val = ItemApply(LHS, MHSd->getOperator(), RHS, CurRec);
1309 if (Val != MHSd->getOperator())
1310 Change = true;
1311
1312 SmallVector<std::pair<Init *, StringInit *>, 8> NewArgs;
1313 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1314 Init *Arg = MHSd->getArg(i);
1315 Init *NewArg;
1316 StringInit *ArgName = MHSd->getArgName(i);
1317
1318 if (DagInit *Argd = dyn_cast<DagInit>(Arg))
1319 NewArg = ForeachDagApply(LHS, Argd, RHS, CurRec);
1320 else
1321 NewArg = ItemApply(LHS, Arg, RHS, CurRec);
1322
1323 NewArgs.push_back(std::make_pair(NewArg, ArgName));
1324 if (Arg != NewArg)
1325 Change = true;
1326 }
1327
1328 if (Change)
1329 return DagInit::get(Val, nullptr, NewArgs);
1330 return MHSd;
1331}
1332
1333// Applies RHS to all elements of MHS, using LHS as a temp variable.
1334static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1335 Record *CurRec) {
1336 if (DagInit *MHSd = dyn_cast<DagInit>(MHS))
1337 return ForeachDagApply(LHS, MHSd, RHS, CurRec);
1338
1339 if (ListInit *MHSl = dyn_cast<ListInit>(MHS)) {
1340 SmallVector<Init *, 8> NewList(MHSl->begin(), MHSl->end());
1341
1342 for (Init *&Item : NewList) {
1343 Init *NewItem = ItemApply(LHS, Item, RHS, CurRec);
1344 if (NewItem != Item)
1345 Item = NewItem;
1346 }
1347 return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());
1348 }
1349
1350 return nullptr;
1351}
1352
1353// Evaluates RHS for all elements of MHS, using LHS as a temp variable.
1354// Creates a new list with the elements that evaluated to true.
1355static Init *FilterHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1356 Record *CurRec) {
1357 if (ListInit *MHSl = dyn_cast<ListInit>(MHS)) {
1358 SmallVector<Init *, 8> NewList;
1359
1360 for (Init *Item : MHSl->getValues()) {
1361 Init *Include = ItemApply(LHS, Item, RHS, CurRec);
1362 if (!Include)
1363 return nullptr;
1364 if (IntInit *IncludeInt =
1365 dyn_cast_or_null<IntInit>(Include->convertInitializerTo(
1366 IntRecTy::get(LHS->getRecordKeeper())))) {
1367 if (IncludeInt->getValue())
1368 NewList.push_back(Item);
1369 } else {
1370 return nullptr;
1371 }
1372 }
1373 return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());
1374 }
1375
1376 return nullptr;
1377}
1378
1379Init *TernOpInit::Fold(Record *CurRec) const {
1380 RecordKeeper &RK = getRecordKeeper();
1381 switch (getOpcode()) {
1382 case SUBST: {
1383 DefInit *LHSd = dyn_cast<DefInit>(LHS);
1384 VarInit *LHSv = dyn_cast<VarInit>(LHS);
1385 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1386
1387 DefInit *MHSd = dyn_cast<DefInit>(MHS);
1388 VarInit *MHSv = dyn_cast<VarInit>(MHS);
1389 StringInit *MHSs = dyn_cast<StringInit>(MHS);
1390
1391 DefInit *RHSd = dyn_cast<DefInit>(RHS);
1392 VarInit *RHSv = dyn_cast<VarInit>(RHS);
1393 StringInit *RHSs = dyn_cast<StringInit>(RHS);
1394
1395 if (LHSd && MHSd && RHSd) {
1396 Record *Val = RHSd->getDef();
1397 if (LHSd->getAsString() == RHSd->getAsString())
1398 Val = MHSd->getDef();
1399 return DefInit::get(Val);
1400 }
1401 if (LHSv && MHSv && RHSv) {
1402 std::string Val = std::string(RHSv->getName());
1403 if (LHSv->getAsString() == RHSv->getAsString())
1404 Val = std::string(MHSv->getName());
1405 return VarInit::get(Val, getType());
1406 }
1407 if (LHSs && MHSs && RHSs) {
1408 std::string Val = std::string(RHSs->getValue());
1409
1410 std::string::size_type found;
1411 std::string::size_type idx = 0;
1412 while (true) {
1413 found = Val.find(std::string(LHSs->getValue()), idx);
1414 if (found == std::string::npos)
1415 break;
1416 Val.replace(found, LHSs->getValue().size(),
1417 std::string(MHSs->getValue()));
1418 idx = found + MHSs->getValue().size();
1419 }
1420
1421 return StringInit::get(RK, Val);
1422 }
1423 break;
1424 }
1425
1426 case FOREACH: {
1427 if (Init *Result = ForeachHelper(LHS, MHS, RHS, getType(), CurRec))
1428 return Result;
1429 break;
1430 }
1431
1432 case FILTER: {
1433 if (Init *Result = FilterHelper(LHS, MHS, RHS, getType(), CurRec))
1434 return Result;
1435 break;
1436 }
1437
1438 case IF: {
1439 if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
1440 LHS->convertInitializerTo(IntRecTy::get(RK)))) {
1441 if (LHSi->getValue())
1442 return MHS;
1443 return RHS;
1444 }
1445 break;
1446 }
1447
1448 case DAG: {
1449 ListInit *MHSl = dyn_cast<ListInit>(MHS);
1450 ListInit *RHSl = dyn_cast<ListInit>(RHS);
1451 bool MHSok = MHSl || isa<UnsetInit>(MHS);
1452 bool RHSok = RHSl || isa<UnsetInit>(RHS);
1453
1454 if (isa<UnsetInit>(MHS) && isa<UnsetInit>(RHS))
1455 break; // Typically prevented by the parser, but might happen with template args
1456
1457 if (MHSok && RHSok && (!MHSl || !RHSl || MHSl->size() == RHSl->size())) {
1458 SmallVector<std::pair<Init *, StringInit *>, 8> Children;
1459 unsigned Size = MHSl ? MHSl->size() : RHSl->size();
1460 for (unsigned i = 0; i != Size; ++i) {
1461 Init *Node = MHSl ? MHSl->getElement(i) : UnsetInit::get(RK);
1462 Init *Name = RHSl ? RHSl->getElement(i) : UnsetInit::get(RK);
1463 if (!isa<StringInit>(Name) && !isa<UnsetInit>(Name))
1464 return const_cast<TernOpInit *>(this);
1465 Children.emplace_back(Node, dyn_cast<StringInit>(Name));
1466 }
1467 return DagInit::get(LHS, nullptr, Children);
1468 }
1469 break;
1470 }
1471
1472 case SUBSTR: {
1473 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1474 IntInit *MHSi = dyn_cast<IntInit>(MHS);
1475 IntInit *RHSi = dyn_cast<IntInit>(RHS);
1476 if (LHSs && MHSi && RHSi) {
1477 int64_t StringSize = LHSs->getValue().size();
1478 int64_t Start = MHSi->getValue();
1479 int64_t Length = RHSi->getValue();
1480 if (Start < 0 || Start > StringSize)
1481 PrintError(CurRec->getLoc(),
1482 Twine("!substr start position is out of range 0...") +
1483 std::to_string(StringSize) + ": " +
1484 std::to_string(Start));
1485 if (Length < 0)
1486 PrintError(CurRec->getLoc(), "!substr length must be nonnegative");
1487 return StringInit::get(RK, LHSs->getValue().substr(Start, Length),
1488 LHSs->getFormat());
1489 }
1490 break;
1491 }
1492
1493 case FIND: {
1494 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1495 StringInit *MHSs = dyn_cast<StringInit>(MHS);
1496 IntInit *RHSi = dyn_cast<IntInit>(RHS);
1497 if (LHSs && MHSs && RHSi) {
1498 int64_t SourceSize = LHSs->getValue().size();
1499 int64_t Start = RHSi->getValue();
1500 if (Start < 0 || Start > SourceSize)
1501 PrintError(CurRec->getLoc(),
1502 Twine("!find start position is out of range 0...") +
1503 std::to_string(SourceSize) + ": " +
1504 std::to_string(Start));
1505 auto I = LHSs->getValue().find(MHSs->getValue(), Start);
1506 if (I == std::string::npos)
1507 return IntInit::get(RK, -1);
1508 return IntInit::get(RK, I);
1509 }
1510 break;
1511 }
1512 }
1513
1514 return const_cast<TernOpInit *>(this);
1515}
1516
1517Init *TernOpInit::resolveReferences(Resolver &R) const {
1518 Init *lhs = LHS->resolveReferences(R);
1519
1520 if (getOpcode() == IF && lhs != LHS) {
1521 if (IntInit *Value = dyn_cast_or_null<IntInit>(
1522 lhs->convertInitializerTo(IntRecTy::get(getRecordKeeper())))) {
1523 // Short-circuit
1524 if (Value->getValue())
1525 return MHS->resolveReferences(R);
1526 return RHS->resolveReferences(R);
1527 }
1528 }
1529
1530 Init *mhs = MHS->resolveReferences(R);
1531 Init *rhs;
1532
1533 if (getOpcode() == FOREACH || getOpcode() == FILTER) {
1534 ShadowResolver SR(R);
1535 SR.addShadow(lhs);
1536 rhs = RHS->resolveReferences(SR);
1537 } else {
1538 rhs = RHS->resolveReferences(R);
1539 }
1540
1541 if (LHS != lhs || MHS != mhs || RHS != rhs)
1542 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs, getType()))
1543 ->Fold(R.getCurrentRecord());
1544 return const_cast<TernOpInit *>(this);
1545}
1546
1547std::string TernOpInit::getAsString() const {
1548 std::string Result;
1549 bool UnquotedLHS = false;
1550 switch (getOpcode()) {
1551 case DAG: Result = "!dag"; break;
1552 case FILTER: Result = "!filter"; UnquotedLHS = true; break;
1553 case FOREACH: Result = "!foreach"; UnquotedLHS = true; break;
1554 case IF: Result = "!if"; break;
1555 case SUBST: Result = "!subst"; break;
1556 case SUBSTR: Result = "!substr"; break;
1557 case FIND: Result = "!find"; break;
1558 }
1559 return (Result + "(" +
1560 (UnquotedLHS ? LHS->getAsUnquotedString() : LHS->getAsString()) +
1561 ", " + MHS->getAsString() + ", " + RHS->getAsString() + ")");
1562}
1563
1564static void ProfileFoldOpInit(FoldingSetNodeID &ID, Init *Start, Init *List,
1565 Init *A, Init *B, Init *Expr, RecTy *Type) {
1566 ID.AddPointer(Start);
1567 ID.AddPointer(List);
1568 ID.AddPointer(A);
1569 ID.AddPointer(B);
1570 ID.AddPointer(Expr);
1571 ID.AddPointer(Type);
1572}
1573
1574FoldOpInit *FoldOpInit::get(Init *Start, Init *List, Init *A, Init *B,
1575 Init *Expr, RecTy *Type) {
1576 FoldingSetNodeID ID;
1577 ProfileFoldOpInit(ID, Start, List, A, B, Expr, Type);
1578
1579 detail::RecordKeeperImpl &RK = Start->getRecordKeeper().getImpl();
1580 void *IP = nullptr;
1581 if (FoldOpInit *I = RK.TheFoldOpInitPool.FindNodeOrInsertPos(ID, IP))
1582 return I;
1583
1584 FoldOpInit *I = new (RK.Allocator) FoldOpInit(Start, List, A, B, Expr, Type);
1585 RK.TheFoldOpInitPool.InsertNode(I, IP);
1586 return I;
1587}
1588
1589void FoldOpInit::Profile(FoldingSetNodeID &ID) const {
1590 ProfileFoldOpInit(ID, Start, List, A, B, Expr, getType());
1591}
1592
1593Init *FoldOpInit::Fold(Record *CurRec) const {
1594 if (ListInit *LI = dyn_cast<ListInit>(List)) {
1595 Init *Accum = Start;
1596 for (Init *Elt : *LI) {
1597 MapResolver R(CurRec);
1598 R.set(A, Accum);
1599 R.set(B, Elt);
1600 Accum = Expr->resolveReferences(R);
1601 }
1602 return Accum;
1603 }
1604 return const_cast<FoldOpInit *>(this);
1605}
1606
1607Init *FoldOpInit::resolveReferences(Resolver &R) const {
1608 Init *NewStart = Start->resolveReferences(R);
1609 Init *NewList = List->resolveReferences(R);
1610 ShadowResolver SR(R);
1611 SR.addShadow(A);
1612 SR.addShadow(B);
1613 Init *NewExpr = Expr->resolveReferences(SR);
1614
1615 if (Start == NewStart && List == NewList && Expr == NewExpr)
1616 return const_cast<FoldOpInit *>(this);
1617
1618 return get(NewStart, NewList, A, B, NewExpr, getType())
1619 ->Fold(R.getCurrentRecord());
1620}
1621
1622Init *FoldOpInit::getBit(unsigned Bit) const {
1623 return VarBitInit::get(const_cast<FoldOpInit *>(this), Bit);
1624}
1625
1626std::string FoldOpInit::getAsString() const {
1627 return (Twine("!foldl(") + Start->getAsString() + ", " + List->getAsString() +
1628 ", " + A->getAsUnquotedString() + ", " + B->getAsUnquotedString() +
1629 ", " + Expr->getAsString() + ")")
1630 .str();
1631}
1632
1633static void ProfileIsAOpInit(FoldingSetNodeID &ID, RecTy *CheckType,
1634 Init *Expr) {
1635 ID.AddPointer(CheckType);
1636 ID.AddPointer(Expr);
1637}
1638
1639IsAOpInit *IsAOpInit::get(RecTy *CheckType, Init *Expr) {
1640
1641 FoldingSetNodeID ID;
1642 ProfileIsAOpInit(ID, CheckType, Expr);
1643
1644 detail::RecordKeeperImpl &RK = Expr->getRecordKeeper().getImpl();
1645 void *IP = nullptr;
1646 if (IsAOpInit *I = RK.TheIsAOpInitPool.FindNodeOrInsertPos(ID, IP))
1647 return I;
1648
1649 IsAOpInit *I = new (RK.Allocator) IsAOpInit(CheckType, Expr);
1650 RK.TheIsAOpInitPool.InsertNode(I, IP);
1651 return I;
1652}
1653
1654void IsAOpInit::Profile(FoldingSetNodeID &ID) const {
1655 ProfileIsAOpInit(ID, CheckType, Expr);
1656}
1657
1658Init *IsAOpInit::Fold() const {
1659 if (TypedInit *TI = dyn_cast<TypedInit>(Expr)) {
1660 // Is the expression type known to be (a subclass of) the desired type?
1661 if (TI->getType()->typeIsConvertibleTo(CheckType))
1662 return IntInit::get(getRecordKeeper(), 1);
1663
1664 if (isa<RecordRecTy>(CheckType)) {
1665 // If the target type is not a subclass of the expression type, or if
1666 // the expression has fully resolved to a record, we know that it can't
1667 // be of the required type.
1668 if (!CheckType->typeIsConvertibleTo(TI->getType()) || isa<DefInit>(Expr))
1669 return IntInit::get(getRecordKeeper(), 0);
1670 } else {
1671 // We treat non-record types as not castable.
1672 return IntInit::get(getRecordKeeper(), 0);
1673 }
1674 }
1675 return const_cast<IsAOpInit *>(this);
1676}
1677
1678Init *IsAOpInit::resolveReferences(Resolver &R) const {
1679 Init *NewExpr = Expr->resolveReferences(R);
1680 if (Expr != NewExpr)
1681 return get(CheckType, NewExpr)->Fold();
1682 return const_cast<IsAOpInit *>(this);
1683}
1684
1685Init *IsAOpInit::getBit(unsigned Bit) const {
1686 return VarBitInit::get(const_cast<IsAOpInit *>(this), Bit);
1687}
1688
1689std::string IsAOpInit::getAsString() const {
1690 return (Twine("!isa<") + CheckType->getAsString() + ">(" +
1691 Expr->getAsString() + ")")
1692 .str();
1693}
1694
1695static void ProfileExistsOpInit(FoldingSetNodeID &ID, RecTy *CheckType,
1696 Init *Expr) {
1697 ID.AddPointer(CheckType);
1698 ID.AddPointer(Expr);
1699}
1700
1701ExistsOpInit *ExistsOpInit::get(RecTy *CheckType, Init *Expr) {
1702 FoldingSetNodeID ID;
1703 ProfileExistsOpInit(ID, CheckType, Expr);
1704
1705 detail::RecordKeeperImpl &RK = Expr->getRecordKeeper().getImpl();
1706 void *IP = nullptr;
1707 if (ExistsOpInit *I = RK.TheExistsOpInitPool.FindNodeOrInsertPos(ID, IP))
1708 return I;
1709
1710 ExistsOpInit *I = new (RK.Allocator) ExistsOpInit(CheckType, Expr);
1711 RK.TheExistsOpInitPool.InsertNode(I, IP);
1712 return I;
1713}
1714
1715void ExistsOpInit::Profile(FoldingSetNodeID &ID) const {
1716 ProfileExistsOpInit(ID, CheckType, Expr);
1717}
1718
1719Init *ExistsOpInit::Fold(Record *CurRec, bool IsFinal) const {
1720 if (StringInit *Name = dyn_cast<StringInit>(Expr)) {
1721 if (!CurRec && !IsFinal)
1722 return const_cast<ExistsOpInit *>(this);
1723
1724 // Self-references are allowed, but their resolution is delayed until
1725 // the final resolve to ensure that we get the correct type for them.
1726 auto *Anonymous = dyn_cast<AnonymousNameInit>(CurRec->getNameInit());
1727 if (Name == CurRec->getNameInit() ||
1728 (Anonymous && Name == Anonymous->getNameInit())) {
1729 if (!IsFinal)
1730 return const_cast<ExistsOpInit *>(this);
1731
1732 // No doubt that there exists a record, so we should check if types are
1733 // compatiable.
1734 return IntInit::get(getRecordKeeper(),
1735 CurRec->getType()->typeIsA(CheckType));
1736 }
1737
1738 // Look up all defined records to see if we can find one.
1739 Record *D = CheckType->getRecordKeeper().getDef(Name->getValue());
1740 if (!D) {
1741 if (IsFinal)
1742 return IntInit::get(getRecordKeeper(), 0);
1743 return const_cast<ExistsOpInit *>(this);
1744 }
1745
1746 // Check if types are compatiable.
1747 return IntInit::get(getRecordKeeper(),
1748 DefInit::get(D)->getType()->typeIsA(CheckType));
1749 }
1750 return const_cast<ExistsOpInit *>(this);
1751}
1752
1753Init *ExistsOpInit::resolveReferences(Resolver &R) const {
1754 Init *NewExpr = Expr->resolveReferences(R);
1755 if (Expr != NewExpr || R.isFinal())
1756 return get(CheckType, NewExpr)->Fold(R.getCurrentRecord(), R.isFinal());
1757 return const_cast<ExistsOpInit *>(this);
1758}
1759
1760Init *ExistsOpInit::getBit(unsigned Bit) const {
1761 return VarBitInit::get(const_cast<ExistsOpInit *>(this), Bit);
1762}
1763
1764std::string ExistsOpInit::getAsString() const {
1765 return (Twine("!exists<") + CheckType->getAsString() + ">(" +
1766 Expr->getAsString() + ")")
1767 .str();
1768}
1769
1770RecTy *TypedInit::getFieldType(StringInit *FieldName) const {
1771 if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType())) {
1772 for (Record *Rec : RecordType->getClasses()) {
1773 if (RecordVal *Field = Rec->getValue(FieldName))
1774 return Field->getType();
1775 }
1776 }
1777 return nullptr;
1778}
1779
1780Init *
1781TypedInit::convertInitializerTo(RecTy *Ty) const {
1782 if (getType() == Ty || getType()->typeIsA(Ty))
1783 return const_cast<TypedInit *>(this);
1784
1785 if (isa<BitRecTy>(getType()) && isa<BitsRecTy>(Ty) &&
1786 cast<BitsRecTy>(Ty)->getNumBits() == 1)
1787 return BitsInit::get(getRecordKeeper(), {const_cast<TypedInit *>(this)});
1788
1789 return nullptr;
1790}
1791
1792Init *TypedInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
1793 BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1794 if (!T) return nullptr; // Cannot subscript a non-bits variable.
1795 unsigned NumBits = T->getNumBits();
1796
1797 SmallVector<Init *, 16> NewBits;
1798 NewBits.reserve(Bits.size());
1799 for (unsigned Bit : Bits) {
1800 if (Bit >= NumBits)
1801 return nullptr;
1802
1803 NewBits.push_back(VarBitInit::get(const_cast<TypedInit *>(this), Bit));
1804 }
1805 return BitsInit::get(getRecordKeeper(), NewBits);
1806}
1807
1808Init *TypedInit::getCastTo(RecTy *Ty) const {
1809 // Handle the common case quickly
1810 if (getType() == Ty || getType()->typeIsA(Ty))
1
Assuming the condition is false
2
Assuming the condition is false
3
Taking false branch
1811 return const_cast<TypedInit *>(this);
1812
1813 if (Init *Converted = convertInitializerTo(Ty)) {
4
Assuming 'Converted' is null
5
Taking false branch
1814 assert(!isa<TypedInit>(Converted) ||(static_cast <bool> (!isa<TypedInit>(Converted) ||
cast<TypedInit>(Converted)->getType()->typeIsA(Ty
)) ? void (0) : __assert_fail ("!isa<TypedInit>(Converted) || cast<TypedInit>(Converted)->getType()->typeIsA(Ty)"
, "llvm/lib/TableGen/Record.cpp", 1815, __extension__ __PRETTY_FUNCTION__
))
1815 cast<TypedInit>(Converted)->getType()->typeIsA(Ty))(static_cast <bool> (!isa<TypedInit>(Converted) ||
cast<TypedInit>(Converted)->getType()->typeIsA(Ty
)) ? void (0) : __assert_fail ("!isa<TypedInit>(Converted) || cast<TypedInit>(Converted)->getType()->typeIsA(Ty)"
, "llvm/lib/TableGen/Record.cpp", 1815, __extension__ __PRETTY_FUNCTION__
))
;
1816 return Converted;
1817 }
1818
1819 if (!getType()->typeIsConvertibleTo(Ty))
6
Assuming the condition is false
7
Taking false branch
1820 return nullptr;
1821
1822 return UnOpInit::get(UnOpInit::CAST, const_cast<TypedInit *>(this), Ty)
9
Calling 'UnOpInit::Fold'
1823 ->Fold(nullptr);
8
Passing null pointer value via 1st parameter 'CurRec'
1824}
1825
1826Init *TypedInit::convertInitListSlice(ArrayRef<unsigned> Elements) const {
1827 ListRecTy *T = dyn_cast<ListRecTy>(getType());
1828 if (!T) return nullptr; // Cannot subscript a non-list variable.
1829
1830 if (Elements.size() == 1)
1831 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1832
1833 SmallVector<Init*, 8> ListInits;
1834 ListInits.reserve(Elements.size());
1835 for (unsigned Element : Elements)
1836 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1837 Element));
1838 return ListInit::get(ListInits, T->getElementType());
1839}
1840
1841
1842VarInit *VarInit::get(StringRef VN, RecTy *T) {
1843 Init *Value = StringInit::get(T->getRecordKeeper(), VN);
1844 return VarInit::get(Value, T);
1845}
1846
1847VarInit *VarInit::get(Init *VN, RecTy *T) {
1848 detail::RecordKeeperImpl &RK = T->getRecordKeeper().getImpl();
1849 VarInit *&I = RK.TheVarInitPool[std::make_pair(T, VN)];
1850 if (!I)
1851 I = new (RK.Allocator) VarInit(VN, T);
1852 return I;
1853}
1854
1855StringRef VarInit::getName() const {
1856 StringInit *NameString = cast<StringInit>(getNameInit());
1857 return NameString->getValue();
1858}
1859
1860Init *VarInit::getBit(unsigned Bit) const {
1861 if (getType() == BitRecTy::get(getRecordKeeper()))
1862 return const_cast<VarInit*>(this);
1863 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1864}
1865
1866Init *VarInit::resolveReferences(Resolver &R) const {
1867 if (Init *Val = R.resolve(VarName))
1868 return Val;
1869 return const_cast<VarInit *>(this);
1870}
1871
1872VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1873 detail::RecordKeeperImpl &RK = T->getRecordKeeper().getImpl();
1874 VarBitInit *&I = RK.TheVarBitInitPool[std::make_pair(T, B)];
1875 if (!I)
1876 I = new (RK.Allocator) VarBitInit(T, B);
1877 return I;
1878}
1879
1880std::string VarBitInit::getAsString() const {
1881 return TI->getAsString() + "{" + utostr(Bit) + "}";
1882}
1883
1884Init *VarBitInit::resolveReferences(Resolver &R) const {
1885 Init *I = TI->resolveReferences(R);
1886 if (TI != I)
1887 return I->getBit(getBitNum());
1888
1889 return const_cast<VarBitInit*>(this);
1890}
1891
1892VarListElementInit *VarListElementInit::get(TypedInit *T, unsigned E) {
1893 detail::RecordKeeperImpl &RK = T->getRecordKeeper().getImpl();
1894 VarListElementInit *&I = RK.TheVarListElementInitPool[std::make_pair(T, E)];
1895 if (!I)
1896 I = new (RK.Allocator) VarListElementInit(T, E);
1897 return I;
1898}
1899
1900std::string VarListElementInit::getAsString() const {
1901 return TI->getAsString() + "[" + utostr(Element) + "]";
1902}
1903
1904Init *VarListElementInit::resolveReferences(Resolver &R) const {
1905 Init *NewTI = TI->resolveReferences(R);
1906 if (ListInit *List = dyn_cast<ListInit>(NewTI)) {
1907 // Leave out-of-bounds array references as-is. This can happen without
1908 // being an error, e.g. in the untaken "branch" of an !if expression.
1909 if (getElementNum() < List->size())
1910 return List->getElement(getElementNum());
1911 }
1912 if (NewTI != TI && isa<TypedInit>(NewTI))
1913 return VarListElementInit::get(cast<TypedInit>(NewTI), getElementNum());
1914 return const_cast<VarListElementInit *>(this);
1915}
1916
1917Init *VarListElementInit::getBit(unsigned Bit) const {
1918 if (getType() == BitRecTy::get(getRecordKeeper()))
1919 return const_cast<VarListElementInit*>(this);
1920 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1921}
1922
1923DefInit::DefInit(Record *D)
1924 : TypedInit(IK_DefInit, D->getType()), Def(D) {}
1925
1926DefInit *DefInit::get(Record *R) {
1927 return R->getDefInit();
1928}
1929
1930Init *DefInit::convertInitializerTo(RecTy *Ty) const {
1931 if (auto *RRT = dyn_cast<RecordRecTy>(Ty))
1932 if (getType()->typeIsConvertibleTo(RRT))
1933 return const_cast<DefInit *>(this);
1934 return nullptr;
1935}
1936
1937RecTy *DefInit::getFieldType(StringInit *FieldName) const {
1938 if (const RecordVal *RV = Def->getValue(FieldName))
1939 return RV->getType();
1940 return nullptr;
1941}
1942
1943std::string DefInit::getAsString() const { return std::string(Def->getName()); }
1944
1945static void ProfileVarDefInit(FoldingSetNodeID &ID,
1946 Record *Class,
1947 ArrayRef<Init *> Args) {
1948 ID.AddInteger(Args.size());
1949 ID.AddPointer(Class);
1950
1951 for (Init *I : Args)
1952 ID.AddPointer(I);
1953}
1954
1955VarDefInit::VarDefInit(Record *Class, unsigned N)
1956 : TypedInit(IK_VarDefInit, RecordRecTy::get(Class)), Class(Class),
1957 NumArgs(N) {}
1958
1959VarDefInit *VarDefInit::get(Record *Class, ArrayRef<Init *> Args) {
1960 FoldingSetNodeID ID;
1961 ProfileVarDefInit(ID, Class, Args);
1962
1963 detail::RecordKeeperImpl &RK = Class->getRecords().getImpl();
1964 void *IP = nullptr;
1965 if (VarDefInit *I = RK.TheVarDefInitPool.FindNodeOrInsertPos(ID, IP))
1966 return I;
1967
1968 void *Mem = RK.Allocator.Allocate(totalSizeToAlloc<Init *>(Args.size()),
1969 alignof(VarDefInit));
1970 VarDefInit *I = new (Mem) VarDefInit(Class, Args.size());
1971 std::uninitialized_copy(Args.begin(), Args.end(),
1972 I->getTrailingObjects<Init *>());
1973 RK.TheVarDefInitPool.InsertNode(I, IP);
1974 return I;
1975}
1976
1977void VarDefInit::Profile(FoldingSetNodeID &ID) const {
1978 ProfileVarDefInit(ID, Class, args());
1979}
1980
1981DefInit *VarDefInit::instantiate() {
1982 if (!Def) {
1983 RecordKeeper &Records = Class->getRecords();
1984 auto NewRecOwner = std::make_unique<Record>(Records.getNewAnonymousName(),
1985 Class->getLoc(), Records,
1986 /*IsAnonymous=*/true);
1987 Record *NewRec = NewRecOwner.get();
1988
1989 // Copy values from class to instance
1990 for (const RecordVal &Val : Class->getValues())
1991 NewRec->addValue(Val);
1992
1993 // Copy assertions from class to instance.
1994 NewRec->appendAssertions(Class);
1995
1996 // Substitute and resolve template arguments
1997 ArrayRef<Init *> TArgs = Class->getTemplateArgs();
1998 MapResolver R(NewRec);
1999
2000 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2001 if (i < args_size())
2002 R.set(TArgs[i], getArg(i));
2003 else
2004 R.set(TArgs[i], NewRec->getValue(TArgs[i])->getValue());
2005
2006 NewRec->removeValue(TArgs[i]);
2007 }
2008
2009 NewRec->resolveReferences(R);
2010
2011 // Add superclasses.
2012 ArrayRef<std::pair<Record *, SMRange>> SCs = Class->getSuperClasses();
2013 for (const auto &SCPair : SCs)
2014 NewRec->addSuperClass(SCPair.first, SCPair.second);
2015
2016 NewRec->addSuperClass(Class,
2017 SMRange(Class->getLoc().back(),
2018 Class->getLoc().back()));
2019
2020 // Resolve internal references and store in record keeper
2021 NewRec->resolveReferences();
2022 Records.addDef(std::move(NewRecOwner));
2023
2024 // Check the assertions.
2025 NewRec->checkRecordAssertions();
2026
2027 Def = DefInit::get(NewRec);
2028 }
2029
2030 return Def;
2031}
2032
2033Init *VarDefInit::resolveReferences(Resolver &R) const {
2034 TrackUnresolvedResolver UR(&R);
2035 bool Changed = false;
2036 SmallVector<Init *, 8> NewArgs;
2037 NewArgs.reserve(args_size());
2038
2039 for (Init *Arg : args()) {
2040 Init *NewArg = Arg->resolveReferences(UR);
2041 NewArgs.push_back(NewArg);
2042 Changed |= NewArg != Arg;
2043 }
2044
2045 if (Changed) {
2046 auto New = VarDefInit::get(Class, NewArgs);
2047 if (!UR.foundUnresolved())
2048 return New->instantiate();
2049 return New;
2050 }
2051 return const_cast<VarDefInit *>(this);
2052}
2053
2054Init *VarDefInit::Fold() const {
2055 if (Def)
2056 return Def;
2057
2058 TrackUnresolvedResolver R;
2059 for (Init *Arg : args())
2060 Arg->resolveReferences(R);
2061
2062 if (!R.foundUnresolved())
2063 return const_cast<VarDefInit *>(this)->instantiate();
2064 return const_cast<VarDefInit *>(this);
2065}
2066
2067std::string VarDefInit::getAsString() const {
2068 std::string Result = Class->getNameInitAsString() + "<";
2069 const char *sep = "";
2070 for (Init *Arg : args()) {
2071 Result += sep;
2072 sep = ", ";
2073 Result += Arg->getAsString();
2074 }
2075 return Result + ">";
2076}
2077
2078FieldInit *FieldInit::get(Init *R, StringInit *FN) {
2079 detail::RecordKeeperImpl &RK = R->getRecordKeeper().getImpl();
2080 FieldInit *&I = RK.TheFieldInitPool[std::make_pair(R, FN)];
2081 if (!I)
2082 I = new (RK.Allocator) FieldInit(R, FN);
2083 return I;
2084}
2085
2086Init *FieldInit::getBit(unsigned Bit) const {
2087 if (getType() == BitRecTy::get(getRecordKeeper()))
2088 return const_cast<FieldInit*>(this);
2089 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
2090}
2091
2092Init *FieldInit::resolveReferences(Resolver &R) const {
2093 Init *NewRec = Rec->resolveReferences(R);
2094 if (NewRec != Rec)
2095 return FieldInit::get(NewRec, FieldName)->Fold(R.getCurrentRecord());
2096 return const_cast<FieldInit *>(this);
2097}
2098
2099Init *FieldInit::Fold(Record *CurRec) const {
2100 if (DefInit *DI = dyn_cast<DefInit>(Rec)) {
2101 Record *Def = DI->getDef();
2102 if (Def == CurRec)
2103 PrintFatalError(CurRec->getLoc(),
2104 Twine("Attempting to access field '") +
2105 FieldName->getAsUnquotedString() + "' of '" +
2106 Rec->getAsString() + "' is a forbidden self-reference");
2107 Init *FieldVal = Def->getValue(FieldName)->getValue();
2108 if (FieldVal->isConcrete())
2109 return FieldVal;
2110 }
2111 return const_cast<FieldInit *>(this);
2112}
2113
2114bool FieldInit::isConcrete() const {
2115 if (DefInit *DI = dyn_cast<DefInit>(Rec)) {
2116 Init *FieldVal = DI->getDef()->getValue(FieldName)->getValue();
2117 return FieldVal->isConcrete();
2118 }
2119 return false;
2120}
2121
2122static void ProfileCondOpInit(FoldingSetNodeID &ID,
2123 ArrayRef<Init *> CondRange,
2124 ArrayRef<Init *> ValRange,
2125 const RecTy *ValType) {
2126 assert(CondRange.size() == ValRange.size() &&(static_cast <bool> (CondRange.size() == ValRange.size(
) && "Number of conditions and values must match!") ?
void (0) : __assert_fail ("CondRange.size() == ValRange.size() && \"Number of conditions and values must match!\""
, "llvm/lib/TableGen/Record.cpp", 2127, __extension__ __PRETTY_FUNCTION__
))
2127 "Number of conditions and values must match!")(static_cast <bool> (CondRange.size() == ValRange.size(
) && "Number of conditions and values must match!") ?
void (0) : __assert_fail ("CondRange.size() == ValRange.size() && \"Number of conditions and values must match!\""
, "llvm/lib/TableGen/Record.cpp", 2127, __extension__ __PRETTY_FUNCTION__
))
;
2128 ID.AddPointer(ValType);
2129 ArrayRef<Init *>::iterator Case = CondRange.begin();
2130 ArrayRef<Init *>::iterator Val = ValRange.begin();
2131
2132 while (Case != CondRange.end()) {
2133 ID.AddPointer(*Case++);
2134 ID.AddPointer(*Val++);
2135 }
2136}
2137
2138void CondOpInit::Profile(FoldingSetNodeID &ID) const {
2139 ProfileCondOpInit(ID,
2140 makeArrayRef(getTrailingObjects<Init *>(), NumConds),
2141 makeArrayRef(getTrailingObjects<Init *>() + NumConds, NumConds),
2142 ValType);
2143}
2144
2145CondOpInit *CondOpInit::get(ArrayRef<Init *> CondRange,
2146 ArrayRef<Init *> ValRange, RecTy *Ty) {
2147 assert(CondRange.size() == ValRange.size() &&(static_cast <bool> (CondRange.size() == ValRange.size(
) && "Number of conditions and values must match!") ?
void (0) : __assert_fail ("CondRange.size() == ValRange.size() && \"Number of conditions and values must match!\""
, "llvm/lib/TableGen/Record.cpp", 2148, __extension__ __PRETTY_FUNCTION__
))
2148 "Number of conditions and values must match!")(static_cast <bool> (CondRange.size() == ValRange.size(
) && "Number of conditions and values must match!") ?
void (0) : __assert_fail ("CondRange.size() == ValRange.size() && \"Number of conditions and values must match!\""
, "llvm/lib/TableGen/Record.cpp", 2148, __extension__ __PRETTY_FUNCTION__
))
;
2149
2150 FoldingSetNodeID ID;
2151 ProfileCondOpInit(ID, CondRange, ValRange, Ty);
2152
2153 detail::RecordKeeperImpl &RK = Ty->getRecordKeeper().getImpl();
2154 void *IP = nullptr;
2155 if (CondOpInit *I = RK.TheCondOpInitPool.FindNodeOrInsertPos(ID, IP))
2156 return I;
2157
2158 void *Mem = RK.Allocator.Allocate(
2159 totalSizeToAlloc<Init *>(2 * CondRange.size()), alignof(BitsInit));
2160 CondOpInit *I = new(Mem) CondOpInit(CondRange.size(), Ty);
2161
2162 std::uninitialized_copy(CondRange.begin(), CondRange.end(),
2163 I->getTrailingObjects<Init *>());
2164 std::uninitialized_copy(ValRange.begin(), ValRange.end(),
2165 I->getTrailingObjects<Init *>()+CondRange.size());
2166 RK.TheCondOpInitPool.InsertNode(I, IP);
2167 return I;
2168}
2169
2170Init *CondOpInit::resolveReferences(Resolver &R) const {
2171 SmallVector<Init*, 4> NewConds;
2172 bool Changed = false;
2173 for (const Init *Case : getConds()) {
2174 Init *NewCase = Case->resolveReferences(R);
2175 NewConds.push_back(NewCase);
2176 Changed |= NewCase != Case;
2177 }
2178
2179 SmallVector<Init*, 4> NewVals;
2180 for (const Init *Val : getVals()) {
2181 Init *NewVal = Val->resolveReferences(R);
2182 NewVals.push_back(NewVal);
2183 Changed |= NewVal != Val;
2184 }
2185
2186 if (Changed)
2187 return (CondOpInit::get(NewConds, NewVals,
2188 getValType()))->Fold(R.getCurrentRecord());
2189
2190 return const_cast<CondOpInit *>(this);
2191}
2192
2193Init *CondOpInit::Fold(Record *CurRec) const {
2194 RecordKeeper &RK = getRecordKeeper();
2195 for ( unsigned i = 0; i < NumConds; ++i) {
2196 Init *Cond = getCond(i);
2197 Init *Val = getVal(i);
2198
2199 if (IntInit *CondI = dyn_cast_or_null<IntInit>(
2200 Cond->convertInitializerTo(IntRecTy::get(RK)))) {
2201 if (CondI->getValue())
2202 return Val->convertInitializerTo(getValType());
2203 } else {
2204 return const_cast<CondOpInit *>(this);
2205 }
2206 }
2207
2208 PrintFatalError(CurRec->getLoc(),
2209 CurRec->getName() +
2210 " does not have any true condition in:" +
2211 this->getAsString());
2212 return nullptr;
2213}
2214
2215bool CondOpInit::isConcrete() const {
2216 for (const Init *Case : getConds())
2217 if (!Case->isConcrete())
2218 return false;
2219
2220 for (const Init *Val : getVals())
2221 if (!Val->isConcrete())
2222 return false;
2223
2224 return true;
2225}
2226
2227bool CondOpInit::isComplete() const {
2228 for (const Init *Case : getConds())
2229 if (!Case->isComplete())
2230 return false;
2231
2232 for (const Init *Val : getVals())
2233 if (!Val->isConcrete())
2234 return false;
2235
2236 return true;
2237}
2238
2239std::string CondOpInit::getAsString() const {
2240 std::string Result = "!cond(";
2241 for (unsigned i = 0; i < getNumConds(); i++) {
2242 Result += getCond(i)->getAsString() + ": ";
2243 Result += getVal(i)->getAsString();
2244 if (i != getNumConds()-1)
2245 Result += ", ";
2246 }
2247 return Result + ")";
2248}
2249
2250Init *CondOpInit::getBit(unsigned Bit) const {
2251 return VarBitInit::get(const_cast<CondOpInit *>(this), Bit);
2252}
2253
2254static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, StringInit *VN,
2255 ArrayRef<Init *> ArgRange,
2256 ArrayRef<StringInit *> NameRange) {
2257 ID.AddPointer(V);
2258 ID.AddPointer(VN);
2259
2260 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
2261 ArrayRef<StringInit *>::iterator Name = NameRange.begin();
2262 while (Arg != ArgRange.end()) {
2263 assert(Name != NameRange.end() && "Arg name underflow!")(static_cast <bool> (Name != NameRange.end() &&
"Arg name underflow!") ? void (0) : __assert_fail ("Name != NameRange.end() && \"Arg name underflow!\""
, "llvm/lib/TableGen/Record.cpp", 2263, __extension__ __PRETTY_FUNCTION__
))
;
2264 ID.AddPointer(*Arg++);
2265 ID.AddPointer(*Name++);
2266 }
2267 assert(Name == NameRange.end() && "Arg name overflow!")(static_cast <bool> (Name == NameRange.end() &&
"Arg name overflow!") ? void (0) : __assert_fail ("Name == NameRange.end() && \"Arg name overflow!\""
, "llvm/lib/TableGen/Record.cpp", 2267, __extension__ __PRETTY_FUNCTION__
))
;
2268}
2269
2270DagInit *DagInit::get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
2271 ArrayRef<StringInit *> NameRange) {
2272 assert(ArgRange.size() == NameRange.size())(static_cast <bool> (ArgRange.size() == NameRange.size(
)) ? void (0) : __assert_fail ("ArgRange.size() == NameRange.size()"
, "llvm/lib/TableGen/Record.cpp", 2272, __extension__ __PRETTY_FUNCTION__
))
;
2273 FoldingSetNodeID ID;
2274 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
2275
2276 detail::RecordKeeperImpl &RK = V->getRecordKeeper().getImpl();
2277 void *IP = nullptr;
2278 if (DagInit *I = RK.TheDagInitPool.FindNodeOrInsertPos(ID, IP))
2279 return I;
2280
2281 void *Mem = RK.Allocator.Allocate(
2282 totalSizeToAlloc<Init *, StringInit *>(ArgRange.size(), NameRange.size()),
2283 alignof(BitsInit));
2284 DagInit *I = new (Mem) DagInit(V, VN, ArgRange.size(), NameRange.size());
2285 std::uninitialized_copy(ArgRange.begin(), ArgRange.end(),
2286 I->getTrailingObjects<Init *>());
2287 std::uninitialized_copy(NameRange.begin(), NameRange.end(),
2288 I->getTrailingObjects<StringInit *>());
2289 RK.TheDagInitPool.InsertNode(I, IP);
2290 return I;
2291}
2292
2293DagInit *
2294DagInit::get(Init *V, StringInit *VN,
2295 ArrayRef<std::pair<Init*, StringInit*>> args) {
2296 SmallVector<Init *, 8> Args;
2297 SmallVector<StringInit *, 8> Names;
2298
2299 for (const auto &Arg : args) {
2300 Args.push_back(Arg.first);
2301 Names.push_back(Arg.second);
2302 }
2303
2304 return DagInit::get(V, VN, Args, Names);
2305}
2306
2307void DagInit::Profile(FoldingSetNodeID &ID) const {
2308 ProfileDagInit(ID, Val, ValName, makeArrayRef(getTrailingObjects<Init *>(), NumArgs), makeArrayRef(getTrailingObjects<StringInit *>(), NumArgNames));
2309}
2310
2311Record *DagInit::getOperatorAsDef(ArrayRef<SMLoc> Loc) const {
2312 if (DefInit *DefI = dyn_cast<DefInit>(Val))
2313 return DefI->getDef();
2314 PrintFatalError(Loc, "Expected record as operator");
2315 return nullptr;
2316}
2317
2318Init *DagInit::resolveReferences(Resolver &R) const {
2319 SmallVector<Init*, 8> NewArgs;
2320 NewArgs.reserve(arg_size());
2321 bool ArgsChanged = false;
2322 for (const Init *Arg : getArgs()) {
2323 Init *NewArg = Arg->resolveReferences(R);
2324 NewArgs.push_back(NewArg);
2325 ArgsChanged |= NewArg != Arg;
2326 }
2327
2328 Init *Op = Val->resolveReferences(R);
2329 if (Op != Val || ArgsChanged)
2330 return DagInit::get(Op, ValName, NewArgs, getArgNames());
2331
2332 return const_cast<DagInit *>(this);
2333}
2334
2335bool DagInit::isConcrete() const {
2336 if (!Val->isConcrete())
2337 return false;
2338 for (const Init *Elt : getArgs()) {
2339 if (!Elt->isConcrete())
2340 return false;
2341 }
2342 return true;
2343}
2344
2345std::string DagInit::getAsString() const {
2346 std::string Result = "(" + Val->getAsString();
2347 if (ValName)
2348 Result += ":" + ValName->getAsUnquotedString();
2349 if (!arg_empty()) {
2350 Result += " " + getArg(0)->getAsString();
2351 if (getArgName(0)) Result += ":$" + getArgName(0)->getAsUnquotedString();
2352 for (unsigned i = 1, e = getNumArgs(); i != e; ++i) {
2353 Result += ", " + getArg(i)->getAsString();
2354 if (getArgName(i)) Result += ":$" + getArgName(i)->getAsUnquotedString();
2355 }
2356 }
2357 return Result + ")";
2358}
2359
2360//===----------------------------------------------------------------------===//
2361// Other implementations
2362//===----------------------------------------------------------------------===//
2363
2364RecordVal::RecordVal(Init *N, RecTy *T, FieldKind K)
2365 : Name(N), TyAndKind(T, K) {
2366 setValue(UnsetInit::get(N->getRecordKeeper()));
2367 assert(Value && "Cannot create unset value for current type!")(static_cast <bool> (Value && "Cannot create unset value for current type!"
) ? void (0) : __assert_fail ("Value && \"Cannot create unset value for current type!\""
, "llvm/lib/TableGen/Record.cpp", 2367, __extension__ __PRETTY_FUNCTION__
))
;
2368}
2369
2370// This constructor accepts the same arguments as the above, but also
2371// a source location.
2372RecordVal::RecordVal(Init *N, SMLoc Loc, RecTy *T, FieldKind K)
2373 : Name(N), Loc(Loc), TyAndKind(T, K) {
2374 setValue(UnsetInit::get(N->getRecordKeeper()));
2375 assert(Value && "Cannot create unset value for current type!")(static_cast <bool> (Value && "Cannot create unset value for current type!"
) ? void (0) : __assert_fail ("Value && \"Cannot create unset value for current type!\""
, "llvm/lib/TableGen/Record.cpp", 2375, __extension__ __PRETTY_FUNCTION__
))
;
2376}
2377
2378StringRef RecordVal::getName() const {
2379 return cast<StringInit>(getNameInit())->getValue();
2380}
2381
2382std::string RecordVal::getPrintType() const {
2383 if (getType() == StringRecTy::get(getRecordKeeper())) {
2384 if (auto *StrInit = dyn_cast<StringInit>(Value)) {
2385 if (StrInit->hasCodeFormat())
2386 return "code";
2387 else
2388 return "string";
2389 } else {
2390 return "string";
2391 }
2392 } else {
2393 return TyAndKind.getPointer()->getAsString();
2394 }
2395}
2396
2397bool RecordVal::setValue(Init *V) {
2398 if (V) {
2399 Value = V->getCastTo(getType());
2400 if (Value) {
2401 assert(!isa<TypedInit>(Value) ||(static_cast <bool> (!isa<TypedInit>(Value) || cast
<TypedInit>(Value)->getType()->typeIsA(getType())
) ? void (0) : __assert_fail ("!isa<TypedInit>(Value) || cast<TypedInit>(Value)->getType()->typeIsA(getType())"
, "llvm/lib/TableGen/Record.cpp", 2402, __extension__ __PRETTY_FUNCTION__
))
2402 cast<TypedInit>(Value)->getType()->typeIsA(getType()))(static_cast <bool> (!isa<TypedInit>(Value) || cast
<TypedInit>(Value)->getType()->typeIsA(getType())
) ? void (0) : __assert_fail ("!isa<TypedInit>(Value) || cast<TypedInit>(Value)->getType()->typeIsA(getType())"
, "llvm/lib/TableGen/Record.cpp", 2402, __extension__ __PRETTY_FUNCTION__
))
;
2403 if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) {
2404 if (!isa<BitsInit>(Value)) {
2405 SmallVector<Init *, 64> Bits;
2406 Bits.reserve(BTy->getNumBits());
2407 for (unsigned I = 0, E = BTy->getNumBits(); I < E; ++I)
2408 Bits.push_back(Value->getBit(I));
2409 Value = BitsInit::get(V->getRecordKeeper(), Bits);
2410 }
2411 }
2412 }
2413 return Value == nullptr;
2414 }
2415 Value = nullptr;
2416 return false;
2417}
2418
2419// This version of setValue takes a source location and resets the
2420// location in the RecordVal.
2421bool RecordVal::setValue(Init *V, SMLoc NewLoc) {
2422 Loc = NewLoc;
2423 if (V) {
2424 Value = V->getCastTo(getType());
2425 if (Value) {
2426 assert(!isa<TypedInit>(Value) ||(static_cast <bool> (!isa<TypedInit>(Value) || cast
<TypedInit>(Value)->getType()->typeIsA(getType())
) ? void (0) : __assert_fail ("!isa<TypedInit>(Value) || cast<TypedInit>(Value)->getType()->typeIsA(getType())"
, "llvm/lib/TableGen/Record.cpp", 2427, __extension__ __PRETTY_FUNCTION__
))
2427 cast<TypedInit>(Value)->getType()->typeIsA(getType()))(static_cast <bool> (!isa<TypedInit>(Value) || cast
<TypedInit>(Value)->getType()->typeIsA(getType())
) ? void (0) : __assert_fail ("!isa<TypedInit>(Value) || cast<TypedInit>(Value)->getType()->typeIsA(getType())"
, "llvm/lib/TableGen/Record.cpp", 2427, __extension__ __PRETTY_FUNCTION__
))
;
2428 if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) {
2429 if (!isa<BitsInit>(Value)) {
2430 SmallVector<Init *, 64> Bits;
2431 Bits.reserve(BTy->getNumBits());
2432 for (unsigned I = 0, E = BTy->getNumBits(); I < E; ++I)
2433 Bits.push_back(Value->getBit(I));
2434 Value = BitsInit::get(getRecordKeeper(), Bits);
2435 }
2436 }
2437 }
2438 return Value == nullptr;
2439 }
2440 Value = nullptr;
2441 return false;
2442}
2443
2444#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2445#include "llvm/TableGen/Record.h"
2446LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void RecordVal::dump() const { errs() << *this; }
2447#endif
2448
2449void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
2450 if (isNonconcreteOK()) OS << "field ";
2451 OS << getPrintType() << " " << getNameInitAsString();
2452
2453 if (getValue())
2454 OS << " = " << *getValue();
2455
2456 if (PrintSem) OS << ";\n";
2457}
2458
2459void Record::updateClassLoc(SMLoc Loc) {
2460 assert(Locs.size() == 1)(static_cast <bool> (Locs.size() == 1) ? void (0) : __assert_fail
("Locs.size() == 1", "llvm/lib/TableGen/Record.cpp", 2460, __extension__
__PRETTY_FUNCTION__))
;
2461 ForwardDeclarationLocs.push_back(Locs.front());
2462
2463 Locs.clear();
2464 Locs.push_back(Loc);
2465}
2466
2467void Record::checkName() {
2468 // Ensure the record name has string type.
2469 const TypedInit *TypedName = cast<const TypedInit>(Name);
2470 if (!isa<StringRecTy>(TypedName->getType()))
2471 PrintFatalError(getLoc(), Twine("Record name '") + Name->getAsString() +
2472 "' is not a string!");
2473}
2474
2475RecordRecTy *Record::getType() {
2476 SmallVector<Record *, 4> DirectSCs;
2477 getDirectSuperClasses(DirectSCs);
2478 return RecordRecTy::get(TrackedRecords, DirectSCs);
2479}
2480
2481DefInit *Record::getDefInit() {
2482 if (!CorrespondingDefInit) {
2483 CorrespondingDefInit =
2484 new (TrackedRecords.getImpl().Allocator) DefInit(this);
2485 }
2486 return CorrespondingDefInit;
2487}
2488
2489unsigned Record::getNewUID(RecordKeeper &RK) {
2490 return RK.getImpl().LastRecordID++;
2491}
2492
2493void Record::setName(Init *NewName) {
2494 Name = NewName;
2495 checkName();
2496 // DO NOT resolve record values to the name at this point because
2497 // there might be default values for arguments of this def. Those
2498 // arguments might not have been resolved yet so we don't want to
2499 // prematurely assume values for those arguments were not passed to
2500 // this def.
2501 //
2502 // Nonetheless, it may be that some of this Record's values
2503 // reference the record name. Indeed, the reason for having the
2504 // record name be an Init is to provide this flexibility. The extra
2505 // resolve steps after completely instantiating defs takes care of
2506 // this. See TGParser::ParseDef and TGParser::ParseDefm.
2507}
2508
2509// NOTE for the next two functions:
2510// Superclasses are in post-order, so the final one is a direct
2511// superclass. All of its transitive superclases immediately precede it,
2512// so we can step through the direct superclasses in reverse order.
2513
2514bool Record::hasDirectSuperClass(const Record *Superclass) const {
2515 ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses();
2516
2517 for (int I = SCs.size() - 1; I >= 0; --I) {
2518 const Record *SC = SCs[I].first;
2519 if (SC == Superclass)
2520 return true;
2521 I -= SC->getSuperClasses().size();
2522 }
2523
2524 return false;
2525}
2526
2527void Record::getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const {
2528 ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses();
2529
2530 while (!SCs.empty()) {
2531 Record *SC = SCs.back().first;
2532 SCs = SCs.drop_back(1 + SC->getSuperClasses().size());
2533 Classes.push_back(SC);
2534 }
2535}
2536
2537void Record::resolveReferences(Resolver &R, const RecordVal *SkipVal) {
2538 Init *OldName = getNameInit();
2539 Init *NewName = Name->resolveReferences(R);
2540 if (NewName != OldName) {
2541 // Re-register with RecordKeeper.
2542 setName(NewName);
2543 }
2544
2545 // Resolve the field values.
2546 for (RecordVal &Value : Values) {
2547 if (SkipVal == &Value) // Skip resolve the same field as the given one
2548 continue;
2549 if (Init *V = Value.getValue()) {
2550 Init *VR = V->resolveReferences(R);
2551 if (Value.setValue(VR)) {
2552 std::string Type;
2553 if (TypedInit *VRT = dyn_cast<TypedInit>(VR))
2554 Type =
2555 (Twine("of type '") + VRT->getType()->getAsString() + "' ").str();
2556 PrintFatalError(
2557 getLoc(),
2558 Twine("Invalid value ") + Type + "found when setting field '" +
2559 Value.getNameInitAsString() + "' of type '" +
2560 Value.getType()->getAsString() +
2561 "' after resolving references: " + VR->getAsUnquotedString() +
2562 "\n");
2563 }
2564 }
2565 }
2566
2567 // Resolve the assertion expressions.
2568 for (auto &Assertion : Assertions) {
2569 Init *Value = Assertion.Condition->resolveReferences(R);
2570 Assertion.Condition = Value;
2571 Value = Assertion.Message->resolveReferences(R);
2572 Assertion.Message = Value;
2573 }
2574}
2575
2576void Record::resolveReferences(Init *NewName) {
2577 RecordResolver R(*this);
2578 R.setName(NewName);
2579 R.setFinal(true);
2580 resolveReferences(R);
2581}
2582
2583#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2584LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void Record::dump() const { errs() << *this; }
2585#endif
2586
2587raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
2588 OS << R.getNameInitAsString();
2589
2590 ArrayRef<Init *> TArgs = R.getTemplateArgs();
2591 if (!TArgs.empty()) {
2592 OS << "<";
2593 bool NeedComma = false;
2594 for (const Init *TA : TArgs) {
2595 if (NeedComma) OS << ", ";
2596 NeedComma = true;
2597 const RecordVal *RV = R.getValue(TA);
2598 assert(RV && "Template argument record not found??")(static_cast <bool> (RV && "Template argument record not found??"
) ? void (0) : __assert_fail ("RV && \"Template argument record not found??\""
, "llvm/lib/TableGen/Record.cpp", 2598, __extension__ __PRETTY_FUNCTION__
))
;
2599 RV->print(OS, false);
2600 }
2601 OS << ">";
2602 }
2603
2604 OS << " {";
2605 ArrayRef<std::pair<Record *, SMRange>> SC = R.getSuperClasses();
2606 if (!SC.empty()) {
2607 OS << "\t//";
2608 for (const auto &SuperPair : SC)
2609 OS << " " << SuperPair.first->getNameInitAsString();
2610 }
2611 OS << "\n";
2612
2613 for (const RecordVal &Val : R.getValues())
2614 if (Val.isNonconcreteOK() && !R.isTemplateArg(Val.getNameInit()))
2615 OS << Val;
2616 for (const RecordVal &Val : R.getValues())
2617 if (!Val.isNonconcreteOK() && !R.isTemplateArg(Val.getNameInit()))
2618 OS << Val;
2619
2620 return OS << "}\n";
2621}
2622
2623SMLoc Record::getFieldLoc(StringRef FieldName) const {
2624 const RecordVal *R = getValue(FieldName);
2625 if (!R)
2626 PrintFatalError(getLoc(), "Record `" + getName() +
2627 "' does not have a field named `" + FieldName + "'!\n");
2628 return R->getLoc();
2629}
2630
2631Init *Record::getValueInit(StringRef FieldName) const {
2632 const RecordVal *R = getValue(FieldName);
2633 if (!R || !R->getValue())
2634 PrintFatalError(getLoc(), "Record `" + getName() +
2635 "' does not have a field named `" + FieldName + "'!\n");
2636 return R->getValue();
2637}
2638
2639StringRef Record::getValueAsString(StringRef FieldName) const {
2640 llvm::Optional<StringRef> S = getValueAsOptionalString(FieldName);
2641 if (!S)
2642 PrintFatalError(getLoc(), "Record `" + getName() +
2643 "' does not have a field named `" + FieldName + "'!\n");
2644 return S.value();
2645}
2646
2647llvm::Optional<StringRef>
2648Record::getValueAsOptionalString(StringRef FieldName) const {
2649 const RecordVal *R = getValue(FieldName);
2650 if (!R || !R->getValue())
2651 return std::nullopt;
2652 if (isa<UnsetInit>(R->getValue()))
2653 return std::nullopt;
2654
2655 if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
2656 return SI->getValue();
2657
2658 PrintFatalError(getLoc(),
2659 "Record `" + getName() + "', ` field `" + FieldName +
2660 "' exists but does not have a string initializer!");
2661}
2662
2663BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
2664 const RecordVal *R = getValue(FieldName);
2665 if (!R || !R->getValue())
2666 PrintFatalError(getLoc(), "Record `" + getName() +
2667 "' does not have a field named `" + FieldName + "'!\n");
2668
2669 if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
2670 return BI;
2671 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName +
2672 "' exists but does not have a bits value");
2673}
2674
2675ListInit *Record::getValueAsListInit(StringRef FieldName) const {
2676 const RecordVal *R = getValue(FieldName);
2677 if (!R || !R->getValue())
2678 PrintFatalError(getLoc(), "Record `" + getName() +
2679 "' does not have a field named `" + FieldName + "'!\n");
2680
2681 if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
2682 return LI;
2683 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName +
2684 "' exists but does not have a list value");
2685}
2686
2687std::vector<Record*>
2688Record::getValueAsListOfDefs(StringRef FieldName) const {
2689 ListInit *List = getValueAsListInit(FieldName);
2690 std::vector<Record*> Defs;
2691 for (Init *I : List->getValues()) {
2692 if (DefInit *DI = dyn_cast<DefInit>(I))
2693 Defs.push_back(DI->getDef());
2694 else
2695 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2696 FieldName + "' list is not entirely DefInit!");
2697 }
2698 return Defs;
2699}
2700
2701int64_t Record::getValueAsInt(StringRef FieldName) const {
2702 const RecordVal *R = getValue(FieldName);
2703 if (!R || !R->getValue())
2704 PrintFatalError(getLoc(), "Record `" + getName() +
2705 "' does not have a field named `" + FieldName + "'!\n");
2706
2707 if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
2708 return II->getValue();
2709 PrintFatalError(getLoc(), Twine("Record `") + getName() + "', field `" +
2710 FieldName +
2711 "' exists but does not have an int value: " +
2712 R->getValue()->getAsString());
2713}
2714
2715std::vector<int64_t>
2716Record::getValueAsListOfInts(StringRef FieldName) const {
2717 ListInit *List = getValueAsListInit(FieldName);
2718 std::vector<int64_t> Ints;
2719 for (Init *I : List->getValues()) {
2720 if (IntInit *II = dyn_cast<IntInit>(I))
2721 Ints.push_back(II->getValue());
2722 else
2723 PrintFatalError(getLoc(),
2724 Twine("Record `") + getName() + "', field `" + FieldName +
2725 "' exists but does not have a list of ints value: " +
2726 I->getAsString());
2727 }
2728 return Ints;
2729}
2730
2731std::vector<StringRef>
2732Record::getValueAsListOfStrings(StringRef FieldName) const {
2733 ListInit *List = getValueAsListInit(FieldName);
2734 std::vector<StringRef> Strings;
2735 for (Init *I : List->getValues()) {
2736 if (StringInit *SI = dyn_cast<StringInit>(I))
2737 Strings.push_back(SI->getValue());
2738 else
2739 PrintFatalError(getLoc(),
2740 Twine("Record `") + getName() + "', field `" + FieldName +
2741 "' exists but does not have a list of strings value: " +
2742 I->getAsString());
2743 }
2744 return Strings;
2745}
2746
2747Record *Record::getValueAsDef(StringRef FieldName) const {
2748 const RecordVal *R = getValue(FieldName);
2749 if (!R || !R->getValue())
2750 PrintFatalError(getLoc(), "Record `" + getName() +
2751 "' does not have a field named `" + FieldName + "'!\n");
2752
2753 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
2754 return DI->getDef();
2755 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2756 FieldName + "' does not have a def initializer!");
2757}
2758
2759Record *Record::getValueAsOptionalDef(StringRef FieldName) const {
2760 const RecordVal *R = getValue(FieldName);
2761 if (!R || !R->getValue())
2762 PrintFatalError(getLoc(), "Record `" + getName() +
2763 "' does not have a field named `" + FieldName + "'!\n");
2764
2765 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
2766 return DI->getDef();
2767 if (isa<UnsetInit>(R->getValue()))
2768 return nullptr;
2769 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2770 FieldName + "' does not have either a def initializer or '?'!");
2771}
2772
2773
2774bool Record::getValueAsBit(StringRef FieldName) const {
2775 const RecordVal *R = getValue(FieldName);
2776 if (!R || !R->getValue())
2777 PrintFatalError(getLoc(), "Record `" + getName() +
2778 "' does not have a field named `" + FieldName + "'!\n");
2779
2780 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
2781 return BI->getValue();
2782 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2783 FieldName + "' does not have a bit initializer!");
2784}
2785
2786bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
2787 const RecordVal *R = getValue(FieldName);
2788 if (!R || !R->getValue())
2789 PrintFatalError(getLoc(), "Record `" + getName() +
2790 "' does not have a field named `" + FieldName.str() + "'!\n");
2791
2792 if (isa<UnsetInit>(R->getValue())) {
2793 Unset = true;
2794 return false;
2795 }
2796 Unset = false;
2797 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
2798 return BI->getValue();
2799 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2800 FieldName + "' does not have a bit initializer!");
2801}
2802
2803DagInit *Record::getValueAsDag(StringRef FieldName) const {
2804 const RecordVal *R = getValue(FieldName);
2805 if (!R || !R->getValue())
2806 PrintFatalError(getLoc(), "Record `" + getName() +
2807 "' does not have a field named `" + FieldName + "'!\n");
2808
2809 if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
2810 return DI;
2811 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2812 FieldName + "' does not have a dag initializer!");
2813}
2814
2815// Check all record assertions: For each one, resolve the condition
2816// and message, then call CheckAssert().
2817// Note: The condition and message are probably already resolved,
2818// but resolving again allows calls before records are resolved.
2819void Record::checkRecordAssertions() {
2820 RecordResolver R(*this);
2821 R.setFinal(true);
2822
2823 for (const auto &Assertion : getAssertions()) {
2824 Init *Condition = Assertion.Condition->resolveReferences(R);
2825 Init *Message = Assertion.Message->resolveReferences(R);
2826 CheckAssert(Assertion.Loc, Condition, Message);
2827 }
2828}
2829
2830// Report a warning if the record has unused template arguments.
2831void Record::checkUnusedTemplateArgs() {
2832 for (const Init *TA : getTemplateArgs()) {
2833 const RecordVal *Arg = getValue(TA);
2834 if (!Arg->isUsed())
2835 PrintWarning(Arg->getLoc(),
2836 "unused template argument: " + Twine(Arg->getName()));
2837 }
2838}
2839
2840RecordKeeper::RecordKeeper()
2841 : Impl(std::make_unique<detail::RecordKeeperImpl>(*this)) {}
2842RecordKeeper::~RecordKeeper() = default;
2843
2844#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2845LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void RecordKeeper::dump() const { errs() << *this; }
2846#endif
2847
2848raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
2849 OS << "------------- Classes -----------------\n";
2850 for (const auto &C : RK.getClasses())
2851 OS << "class " << *C.second;
2852
2853 OS << "------------- Defs -----------------\n";
2854 for (const auto &D : RK.getDefs())
2855 OS << "def " << *D.second;
2856 return OS;
2857}
2858
2859/// GetNewAnonymousName - Generate a unique anonymous name that can be used as
2860/// an identifier.
2861Init *RecordKeeper::getNewAnonymousName() {
2862 return AnonymousNameInit::get(*this, getImpl().AnonCounter++);
2863}
2864
2865// These functions implement the phase timing facility. Starting a timer
2866// when one is already running stops the running one.
2867
2868void RecordKeeper::startTimer(StringRef Name) {
2869 if (TimingGroup) {
2870 if (LastTimer && LastTimer->isRunning()) {
2871 LastTimer->stopTimer();
2872 if (BackendTimer) {
2873 LastTimer->clear();
2874 BackendTimer = false;
2875 }
2876 }
2877
2878 LastTimer = new Timer("", Name, *TimingGroup);
2879 LastTimer->startTimer();
2880 }
2881}
2882
2883void RecordKeeper::stopTimer() {
2884 if (TimingGroup) {
2885 assert(LastTimer && "No phase timer was started")(static_cast <bool> (LastTimer && "No phase timer was started"
) ? void (0) : __assert_fail ("LastTimer && \"No phase timer was started\""
, "llvm/lib/TableGen/Record.cpp", 2885, __extension__ __PRETTY_FUNCTION__
))
;
2886 LastTimer->stopTimer();
2887 }
2888}
2889
2890void RecordKeeper::startBackendTimer(StringRef Name) {
2891 if (TimingGroup) {
2892 startTimer(Name);
2893 BackendTimer = true;
2894 }
2895}
2896
2897void RecordKeeper::stopBackendTimer() {
2898 if (TimingGroup) {
2899 if (BackendTimer) {
2900 stopTimer();
2901 BackendTimer = false;
2902 }
2903 }
2904}
2905
2906std::vector<Record *>
2907RecordKeeper::getAllDerivedDefinitions(StringRef ClassName) const {
2908 // We cache the record vectors for single classes. Many backends request
2909 // the same vectors multiple times.
2910 auto Pair = ClassRecordsMap.try_emplace(ClassName);
2911 if (Pair.second)
2912 Pair.first->second = getAllDerivedDefinitions(makeArrayRef(ClassName));
2913
2914 return Pair.first->second;
2915}
2916
2917std::vector<Record *> RecordKeeper::getAllDerivedDefinitions(
2918 ArrayRef<StringRef> ClassNames) const {
2919 SmallVector<Record *, 2> ClassRecs;
2920 std::vector<Record *> Defs;
2921
2922 assert(ClassNames.size() > 0 && "At least one class must be passed.")(static_cast <bool> (ClassNames.size() > 0 &&
"At least one class must be passed.") ? void (0) : __assert_fail
("ClassNames.size() > 0 && \"At least one class must be passed.\""
, "llvm/lib/TableGen/Record.cpp", 2922, __extension__ __PRETTY_FUNCTION__
))
;
2923 for (const auto &ClassName : ClassNames) {
2924 Record *Class = getClass(ClassName);
2925 if (!Class)
2926 PrintFatalError("The class '" + ClassName + "' is not defined\n");
2927 ClassRecs.push_back(Class);
2928 }
2929
2930 for (const auto &OneDef : getDefs()) {
2931 if (all_of(ClassRecs, [&OneDef](const Record *Class) {
2932 return OneDef.second->isSubClassOf(Class);
2933 }))
2934 Defs.push_back(OneDef.second.get());
2935 }
2936
2937 return Defs;
2938}
2939
2940std::vector<Record *>
2941RecordKeeper::getAllDerivedDefinitionsIfDefined(StringRef ClassName) const {
2942 return getClass(ClassName) ? getAllDerivedDefinitions(ClassName)
2943 : std::vector<Record *>();
2944}
2945
2946Init *MapResolver::resolve(Init *VarName) {
2947 auto It = Map.find(VarName);
2948 if (It == Map.end())
2949 return nullptr;
2950
2951 Init *I = It->second.V;
2952
2953 if (!It->second.Resolved && Map.size() > 1) {
2954 // Resolve mutual references among the mapped variables, but prevent
2955 // infinite recursion.
2956 Map.erase(It);
2957 I = I->resolveReferences(*this);
2958 Map[VarName] = {I, true};
2959 }
2960
2961 return I;
2962}
2963
2964Init *RecordResolver::resolve(Init *VarName) {
2965 Init *Val = Cache.lookup(VarName);
2966 if (Val)
2967 return Val;
2968
2969 if (llvm::is_contained(Stack, VarName))
2970 return nullptr; // prevent infinite recursion
2971
2972 if (RecordVal *RV = getCurrentRecord()->getValue(VarName)) {
2973 if (!isa<UnsetInit>(RV->getValue())) {
2974 Val = RV->getValue();
2975 Stack.push_back(VarName);
2976 Val = Val->resolveReferences(*this);
2977 Stack.pop_back();
2978 }
2979 } else if (Name && VarName == getCurrentRecord()->getNameInit()) {
2980 Stack.push_back(VarName);
2981 Val = Name->resolveReferences(*this);
2982 Stack.pop_back();
2983 }
2984
2985 Cache[VarName] = Val;
2986 return Val;
2987}
2988
2989Init *TrackUnresolvedResolver::resolve(Init *VarName) {
2990 Init *I = nullptr;
2991
2992 if (R) {
2993 I = R->resolve(VarName);
2994 if (I && !FoundUnresolved) {
2995 // Do not recurse into the resolved initializer, as that would change
2996 // the behavior of the resolver we're delegating, but do check to see
2997 // if there are unresolved variables remaining.
2998 TrackUnresolvedResolver Sub;
2999 I->resolveReferences(Sub);
3000 FoundUnresolved |= Sub.FoundUnresolved;
3001 }
3002 }
3003
3004 if (!I)
3005 FoundUnresolved = true;
3006 return I;
3007}
3008
3009Init *HasReferenceResolver::resolve(Init *VarName)
3010{
3011 if (VarName == VarNameToTrack)
3012 Found = true;
3013 return nullptr;
3014}