Bug Summary

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