Bug Summary

File:lib/TableGen/Record.cpp
Warning:line 1605, column 11
Use of memory after it is freed

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name Record.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -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 -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/lib/TableGen -I /build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/lib/TableGen -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp

/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp

1//===- Record.cpp - Record implementation ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Implement the tablegen record classes.
11//
12//===----------------------------------------------------------------------===//
13
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/Support/Allocator.h"
23#include "llvm/Support/Casting.h"
24#include "llvm/Support/Compiler.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/SMLoc.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/TableGen/Error.h"
29#include "llvm/TableGen/Record.h"
30#include <cassert>
31#include <cstdint>
32#include <memory>
33#include <string>
34#include <utility>
35#include <vector>
36
37using namespace llvm;
38
39static BumpPtrAllocator Allocator;
40
41//===----------------------------------------------------------------------===//
42// Type implementations
43//===----------------------------------------------------------------------===//
44
45BitRecTy BitRecTy::Shared;
46CodeRecTy CodeRecTy::Shared;
47IntRecTy IntRecTy::Shared;
48StringRecTy StringRecTy::Shared;
49DagRecTy DagRecTy::Shared;
50
51#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
52LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void RecTy::dump() const { print(errs()); }
53#endif
54
55ListRecTy *RecTy::getListTy() {
56 if (!ListTy)
57 ListTy = new(Allocator) ListRecTy(this);
58 return ListTy;
59}
60
61bool RecTy::typeIsConvertibleTo(const RecTy *RHS) const {
62 assert(RHS && "NULL pointer")(static_cast <bool> (RHS && "NULL pointer") ? void
(0) : __assert_fail ("RHS && \"NULL pointer\"", "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp"
, 62, __extension__ __PRETTY_FUNCTION__))
;
63 return Kind == RHS->getRecTyKind();
64}
65
66bool RecTy::typeIsA(const RecTy *RHS) const { return this == RHS; }
67
68bool BitRecTy::typeIsConvertibleTo(const RecTy *RHS) const{
69 if (RecTy::typeIsConvertibleTo(RHS) || RHS->getRecTyKind() == IntRecTyKind)
70 return true;
71 if (const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
72 return BitsTy->getNumBits() == 1;
73 return false;
74}
75
76BitsRecTy *BitsRecTy::get(unsigned Sz) {
77 static std::vector<BitsRecTy*> Shared;
78 if (Sz >= Shared.size())
79 Shared.resize(Sz + 1);
80 BitsRecTy *&Ty = Shared[Sz];
81 if (!Ty)
82 Ty = new(Allocator) BitsRecTy(Sz);
83 return Ty;
84}
85
86std::string BitsRecTy::getAsString() const {
87 return "bits<" + utostr(Size) + ">";
88}
89
90bool BitsRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
91 if (RecTy::typeIsConvertibleTo(RHS)) //argument and the sender are same type
92 return cast<BitsRecTy>(RHS)->Size == Size;
93 RecTyKind kind = RHS->getRecTyKind();
94 return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
95}
96
97bool BitsRecTy::typeIsA(const RecTy *RHS) const {
98 if (const BitsRecTy *RHSb = dyn_cast<BitsRecTy>(RHS))
99 return RHSb->Size == Size;
100 return false;
101}
102
103bool IntRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
104 RecTyKind kind = RHS->getRecTyKind();
105 return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
106}
107
108bool CodeRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
109 RecTyKind Kind = RHS->getRecTyKind();
110 return Kind == CodeRecTyKind || Kind == StringRecTyKind;
111}
112
113std::string StringRecTy::getAsString() const {
114 return "string";
115}
116
117bool StringRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
118 RecTyKind Kind = RHS->getRecTyKind();
119 return Kind == StringRecTyKind || Kind == CodeRecTyKind;
120}
121
122std::string ListRecTy::getAsString() const {
123 return "list<" + Ty->getAsString() + ">";
124}
125
126bool ListRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
127 if (const auto *ListTy = dyn_cast<ListRecTy>(RHS))
128 return Ty->typeIsConvertibleTo(ListTy->getElementType());
129 return false;
130}
131
132bool ListRecTy::typeIsA(const RecTy *RHS) const {
133 if (const ListRecTy *RHSl = dyn_cast<ListRecTy>(RHS))
134 return getElementType()->typeIsA(RHSl->getElementType());
135 return false;
136}
137
138std::string DagRecTy::getAsString() const {
139 return "dag";
140}
141
142static void ProfileRecordRecTy(FoldingSetNodeID &ID,
143 ArrayRef<Record *> Classes) {
144 ID.AddInteger(Classes.size());
145 for (Record *R : Classes)
146 ID.AddPointer(R);
147}
148
149RecordRecTy *RecordRecTy::get(ArrayRef<Record *> UnsortedClasses) {
150 if (UnsortedClasses.empty()) {
151 static RecordRecTy AnyRecord(0);
152 return &AnyRecord;
153 }
154
155 FoldingSet<RecordRecTy> &ThePool =
156 UnsortedClasses[0]->getRecords().RecordTypePool;
157
158 SmallVector<Record *, 4> Classes(UnsortedClasses.begin(),
159 UnsortedClasses.end());
160 llvm::sort(Classes.begin(), Classes.end(),
161 [](Record *LHS, Record *RHS) {
162 return LHS->getNameInitAsString() < RHS->getNameInitAsString();
163 });
164
165 FoldingSetNodeID ID;
166 ProfileRecordRecTy(ID, Classes);
167
168 void *IP = nullptr;
169 if (RecordRecTy *Ty = ThePool.FindNodeOrInsertPos(ID, IP))
170 return Ty;
171
172#ifndef NDEBUG
173 // Check for redundancy.
174 for (unsigned i = 0; i < Classes.size(); ++i) {
175 for (unsigned j = 0; j < Classes.size(); ++j) {
176 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])"
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp"
, 176, __extension__ __PRETTY_FUNCTION__))
;
177 }
178 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()"
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp"
, 178, __extension__ __PRETTY_FUNCTION__))
;
179 }
180#endif
181
182 void *Mem = Allocator.Allocate(totalSizeToAlloc<Record *>(Classes.size()),
183 alignof(RecordRecTy));
184 RecordRecTy *Ty = new(Mem) RecordRecTy(Classes.size());
185 std::uninitialized_copy(Classes.begin(), Classes.end(),
186 Ty->getTrailingObjects<Record *>());
187 ThePool.InsertNode(Ty, IP);
188 return Ty;
189}
190
191void RecordRecTy::Profile(FoldingSetNodeID &ID) const {
192 ProfileRecordRecTy(ID, getClasses());
193}
194
195std::string RecordRecTy::getAsString() const {
196 if (NumClasses == 1)
197 return getClasses()[0]->getNameInitAsString();
198
199 std::string Str = "{";
200 bool First = true;
201 for (Record *R : getClasses()) {
202 if (!First)
203 Str += ", ";
204 First = false;
205 Str += R->getNameInitAsString();
206 }
207 Str += "}";
208 return Str;
209}
210
211bool RecordRecTy::isSubClassOf(Record *Class) const {
212 return llvm::any_of(getClasses(), [Class](Record *MySuperClass) {
213 return MySuperClass == Class ||
214 MySuperClass->isSubClassOf(Class);
215 });
216}
217
218bool RecordRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
219 if (this == RHS)
220 return true;
221
222 const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
223 if (!RTy)
224 return false;
225
226 return llvm::all_of(RTy->getClasses(), [this](Record *TargetClass) {
227 return isSubClassOf(TargetClass);
228 });
229}
230
231bool RecordRecTy::typeIsA(const RecTy *RHS) const {
232 return typeIsConvertibleTo(RHS);
233}
234
235static RecordRecTy *resolveRecordTypes(RecordRecTy *T1, RecordRecTy *T2) {
236 SmallVector<Record *, 4> CommonSuperClasses;
237 SmallVector<Record *, 4> Stack;
238
239 Stack.insert(Stack.end(), T1->classes_begin(), T1->classes_end());
240
241 while (!Stack.empty()) {
242 Record *R = Stack.back();
243 Stack.pop_back();
244
245 if (T2->isSubClassOf(R)) {
246 CommonSuperClasses.push_back(R);
247 } else {
248 R->getDirectSuperClasses(Stack);
249 }
250 }
251
252 return RecordRecTy::get(CommonSuperClasses);
253}
254
255RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
256 if (T1 == T2)
257 return T1;
258
259 if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
260 if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2))
261 return resolveRecordTypes(RecTy1, RecTy2);
262 }
263
264 if (T1->typeIsConvertibleTo(T2))
265 return T2;
266 if (T2->typeIsConvertibleTo(T1))
267 return T1;
268
269 if (ListRecTy *ListTy1 = dyn_cast<ListRecTy>(T1)) {
270 if (ListRecTy *ListTy2 = dyn_cast<ListRecTy>(T2)) {
271 RecTy* NewType = resolveTypes(ListTy1->getElementType(),
272 ListTy2->getElementType());
273 if (NewType)
274 return NewType->getListTy();
275 }
276 }
277
278 return nullptr;
279}
280
281//===----------------------------------------------------------------------===//
282// Initializer implementations
283//===----------------------------------------------------------------------===//
284
285void Init::anchor() {}
286
287#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
288LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void Init::dump() const { return print(errs()); }
289#endif
290
291UnsetInit *UnsetInit::get() {
292 static UnsetInit TheInit;
293 return &TheInit;
294}
295
296Init *UnsetInit::getCastTo(RecTy *Ty) const {
297 return const_cast<UnsetInit *>(this);
298}
299
300Init *UnsetInit::convertInitializerTo(RecTy *Ty) const {
301 return const_cast<UnsetInit *>(this);
302}
303
304BitInit *BitInit::get(bool V) {
305 static BitInit True(true);
306 static BitInit False(false);
307
308 return V ? &True : &False;
309}
310
311Init *BitInit::convertInitializerTo(RecTy *Ty) const {
312 if (isa<BitRecTy>(Ty))
313 return const_cast<BitInit *>(this);
314
315 if (isa<IntRecTy>(Ty))
316 return IntInit::get(getValue());
317
318 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
319 // Can only convert single bit.
320 if (BRT->getNumBits() == 1)
321 return BitsInit::get(const_cast<BitInit *>(this));
322 }
323
324 return nullptr;
325}
326
327static void
328ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
329 ID.AddInteger(Range.size());
330
331 for (Init *I : Range)
332 ID.AddPointer(I);
333}
334
335BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
336 static FoldingSet<BitsInit> ThePool;
337
338 FoldingSetNodeID ID;
339 ProfileBitsInit(ID, Range);
340
341 void *IP = nullptr;
342 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
343 return I;
344
345 void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()),
346 alignof(BitsInit));
347 BitsInit *I = new(Mem) BitsInit(Range.size());
348 std::uninitialized_copy(Range.begin(), Range.end(),
349 I->getTrailingObjects<Init *>());
350 ThePool.InsertNode(I, IP);
351 return I;
352}
353
354void BitsInit::Profile(FoldingSetNodeID &ID) const {
355 ProfileBitsInit(ID, makeArrayRef(getTrailingObjects<Init *>(), NumBits));
356}
357
358Init *BitsInit::convertInitializerTo(RecTy *Ty) const {
359 if (isa<BitRecTy>(Ty)) {
360 if (getNumBits() != 1) return nullptr; // Only accept if just one bit!
361 return getBit(0);
362 }
363
364 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
365 // If the number of bits is right, return it. Otherwise we need to expand
366 // or truncate.
367 if (getNumBits() != BRT->getNumBits()) return nullptr;
368 return const_cast<BitsInit *>(this);
369 }
370
371 if (isa<IntRecTy>(Ty)) {
372 int64_t Result = 0;
373 for (unsigned i = 0, e = getNumBits(); i != e; ++i)
374 if (auto *Bit = dyn_cast<BitInit>(getBit(i)))
375 Result |= static_cast<int64_t>(Bit->getValue()) << i;
376 else
377 return nullptr;
378 return IntInit::get(Result);
379 }
380
381 return nullptr;
382}
383
384Init *
385BitsInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
386 SmallVector<Init *, 16> NewBits(Bits.size());
387
388 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
389 if (Bits[i] >= getNumBits())
390 return nullptr;
391 NewBits[i] = getBit(Bits[i]);
392 }
393 return BitsInit::get(NewBits);
394}
395
396bool BitsInit::isConcrete() const {
397 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
398 if (!getBit(i)->isConcrete())
399 return false;
400 }
401 return true;
402}
403
404std::string BitsInit::getAsString() const {
405 std::string Result = "{ ";
406 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
407 if (i) Result += ", ";
408 if (Init *Bit = getBit(e-i-1))
409 Result += Bit->getAsString();
410 else
411 Result += "*";
412 }
413 return Result + " }";
414}
415
416// resolveReferences - If there are any field references that refer to fields
417// that have been filled in, we can propagate the values now.
418Init *BitsInit::resolveReferences(Resolver &R) const {
419 bool Changed = false;
420 SmallVector<Init *, 16> NewBits(getNumBits());
421
422 Init *CachedBitVarRef = nullptr;
423 Init *CachedBitVarResolved = nullptr;
424
425 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
426 Init *CurBit = getBit(i);
427 Init *NewBit = CurBit;
428
429 if (VarBitInit *CurBitVar = dyn_cast<VarBitInit>(CurBit)) {
430 if (CurBitVar->getBitVar() != CachedBitVarRef) {
431 CachedBitVarRef = CurBitVar->getBitVar();
432 CachedBitVarResolved = CachedBitVarRef->resolveReferences(R);
433 }
434
435 NewBit = CachedBitVarResolved->getBit(CurBitVar->getBitNum());
436 } else {
437 // getBit(0) implicitly converts int and bits<1> values to bit.
438 NewBit = CurBit->resolveReferences(R)->getBit(0);
439 }
440
441 if (isa<UnsetInit>(NewBit) && R.keepUnsetBits())
442 NewBit = CurBit;
443 NewBits[i] = NewBit;
444 Changed |= CurBit != NewBit;
445 }
446
447 if (Changed)
448 return BitsInit::get(NewBits);
449
450 return const_cast<BitsInit *>(this);
451}
452
453IntInit *IntInit::get(int64_t V) {
454 static DenseMap<int64_t, IntInit*> ThePool;
455
456 IntInit *&I = ThePool[V];
457 if (!I) I = new(Allocator) IntInit(V);
458 return I;
459}
460
461std::string IntInit::getAsString() const {
462 return itostr(Value);
463}
464
465static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
466 // For example, with NumBits == 4, we permit Values from [-7 .. 15].
467 return (NumBits >= sizeof(Value) * 8) ||
468 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
469}
470
471Init *IntInit::convertInitializerTo(RecTy *Ty) const {
472 if (isa<IntRecTy>(Ty))
473 return const_cast<IntInit *>(this);
474
475 if (isa<BitRecTy>(Ty)) {
476 int64_t Val = getValue();
477 if (Val != 0 && Val != 1) return nullptr; // Only accept 0 or 1 for a bit!
478 return BitInit::get(Val != 0);
479 }
480
481 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
482 int64_t Value = getValue();
483 // Make sure this bitfield is large enough to hold the integer value.
484 if (!canFitInBitfield(Value, BRT->getNumBits()))
485 return nullptr;
486
487 SmallVector<Init *, 16> NewBits(BRT->getNumBits());
488 for (unsigned i = 0; i != BRT->getNumBits(); ++i)
489 NewBits[i] = BitInit::get(Value & (1LL << i));
490
491 return BitsInit::get(NewBits);
492 }
493
494 return nullptr;
495}
496
497Init *
498IntInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
499 SmallVector<Init *, 16> NewBits(Bits.size());
500
501 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
502 if (Bits[i] >= 64)
503 return nullptr;
504
505 NewBits[i] = BitInit::get(Value & (INT64_C(1)1L << Bits[i]));
506 }
507 return BitsInit::get(NewBits);
508}
509
510CodeInit *CodeInit::get(StringRef V) {
511 static StringMap<CodeInit*, BumpPtrAllocator &> ThePool(Allocator);
512
513 auto &Entry = *ThePool.insert(std::make_pair(V, nullptr)).first;
514 if (!Entry.second)
515 Entry.second = new(Allocator) CodeInit(Entry.getKey());
516 return Entry.second;
517}
518
519StringInit *StringInit::get(StringRef V) {
520 static StringMap<StringInit*, BumpPtrAllocator &> ThePool(Allocator);
521
522 auto &Entry = *ThePool.insert(std::make_pair(V, nullptr)).first;
523 if (!Entry.second)
524 Entry.second = new(Allocator) StringInit(Entry.getKey());
525 return Entry.second;
526}
527
528Init *StringInit::convertInitializerTo(RecTy *Ty) const {
529 if (isa<StringRecTy>(Ty))
530 return const_cast<StringInit *>(this);
531 if (isa<CodeRecTy>(Ty))
532 return CodeInit::get(getValue());
533
534 return nullptr;
535}
536
537Init *CodeInit::convertInitializerTo(RecTy *Ty) const {
538 if (isa<CodeRecTy>(Ty))
539 return const_cast<CodeInit *>(this);
540 if (isa<StringRecTy>(Ty))
541 return StringInit::get(getValue());
542
543 return nullptr;
544}
545
546static void ProfileListInit(FoldingSetNodeID &ID,
547 ArrayRef<Init *> Range,
548 RecTy *EltTy) {
549 ID.AddInteger(Range.size());
550 ID.AddPointer(EltTy);
551
552 for (Init *I : Range)
553 ID.AddPointer(I);
554}
555
556ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
557 static FoldingSet<ListInit> ThePool;
558
559 FoldingSetNodeID ID;
560 ProfileListInit(ID, Range, EltTy);
561
562 void *IP = nullptr;
563 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
564 return I;
565
566 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)"
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp"
, 567, __extension__ __PRETTY_FUNCTION__))
567 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)"
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp"
, 567, __extension__ __PRETTY_FUNCTION__))
;
568
569 void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()),
570 alignof(ListInit));
571 ListInit *I = new(Mem) ListInit(Range.size(), EltTy);
572 std::uninitialized_copy(Range.begin(), Range.end(),
573 I->getTrailingObjects<Init *>());
574 ThePool.InsertNode(I, IP);
575 return I;
576}
577
578void ListInit::Profile(FoldingSetNodeID &ID) const {
579 RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();
580
581 ProfileListInit(ID, getValues(), EltTy);
582}
583
584Init *ListInit::convertInitializerTo(RecTy *Ty) const {
585 if (getType() == Ty)
586 return const_cast<ListInit*>(this);
587
588 if (auto *LRT = dyn_cast<ListRecTy>(Ty)) {
589 SmallVector<Init*, 8> Elements;
590 Elements.reserve(getValues().size());
591
592 // Verify that all of the elements of the list are subclasses of the
593 // appropriate class!
594 bool Changed = false;
595 RecTy *ElementType = LRT->getElementType();
596 for (Init *I : getValues())
597 if (Init *CI = I->convertInitializerTo(ElementType)) {
598 Elements.push_back(CI);
599 if (CI != I)
600 Changed = true;
601 } else
602 return nullptr;
603
604 if (!Changed)
605 return const_cast<ListInit*>(this);
606 return ListInit::get(Elements, ElementType);
607 }
608
609 return nullptr;
610}
611
612Init *ListInit::convertInitListSlice(ArrayRef<unsigned> Elements) const {
613 SmallVector<Init*, 8> Vals;
614 Vals.reserve(Elements.size());
615 for (unsigned Element : Elements) {
616 if (Element >= size())
617 return nullptr;
618 Vals.push_back(getElement(Element));
619 }
620 return ListInit::get(Vals, getElementType());
621}
622
623Record *ListInit::getElementAsRecord(unsigned i) const {
624 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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp"
, 624, __extension__ __PRETTY_FUNCTION__))
;
625 DefInit *DI = dyn_cast<DefInit>(getElement(i));
626 if (!DI)
627 PrintFatalError("Expected record in list!");
628 return DI->getDef();
629}
630
631Init *ListInit::resolveReferences(Resolver &R) const {
632 SmallVector<Init*, 8> Resolved;
633 Resolved.reserve(size());
634 bool Changed = false;
635
636 for (Init *CurElt : getValues()) {
637 Init *E = CurElt->resolveReferences(R);
638 Changed |= E != CurElt;
639 Resolved.push_back(E);
640 }
641
642 if (Changed)
643 return ListInit::get(Resolved, getElementType());
644 return const_cast<ListInit *>(this);
645}
646
647bool ListInit::isConcrete() const {
648 for (Init *Element : *this) {
649 if (!Element->isConcrete())
650 return false;
651 }
652 return true;
653}
654
655std::string ListInit::getAsString() const {
656 std::string Result = "[";
657 const char *sep = "";
658 for (Init *Element : *this) {
659 Result += sep;
660 sep = ", ";
661 Result += Element->getAsString();
662 }
663 return Result + "]";
664}
665
666Init *OpInit::getBit(unsigned Bit) const {
667 if (getType() == BitRecTy::get())
668 return const_cast<OpInit*>(this);
669 return VarBitInit::get(const_cast<OpInit*>(this), Bit);
670}
671
672static void
673ProfileUnOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *Op, RecTy *Type) {
674 ID.AddInteger(Opcode);
675 ID.AddPointer(Op);
676 ID.AddPointer(Type);
677}
678
679UnOpInit *UnOpInit::get(UnaryOp Opc, Init *LHS, RecTy *Type) {
680 static FoldingSet<UnOpInit> ThePool;
681
682 FoldingSetNodeID ID;
683 ProfileUnOpInit(ID, Opc, LHS, Type);
684
685 void *IP = nullptr;
686 if (UnOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
687 return I;
688
689 UnOpInit *I = new(Allocator) UnOpInit(Opc, LHS, Type);
690 ThePool.InsertNode(I, IP);
691 return I;
692}
693
694void UnOpInit::Profile(FoldingSetNodeID &ID) const {
695 ProfileUnOpInit(ID, getOpcode(), getOperand(), getType());
696}
697
698Init *UnOpInit::Fold(Record *CurRec, bool IsFinal) const {
699 switch (getOpcode()) {
700 case CAST:
701 if (isa<StringRecTy>(getType())) {
702 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
703 return LHSs;
704
705 if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
706 return StringInit::get(LHSd->getAsString());
707
708 if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
709 return StringInit::get(LHSi->getAsString());
710 } else if (isa<RecordRecTy>(getType())) {
711 if (StringInit *Name = dyn_cast<StringInit>(LHS)) {
712 assert(CurRec && "NULL pointer")(static_cast <bool> (CurRec && "NULL pointer") ?
void (0) : __assert_fail ("CurRec && \"NULL pointer\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp"
, 712, __extension__ __PRETTY_FUNCTION__))
;
713 Record *D;
714
715 // Self-references are allowed, but their resolution is delayed until
716 // the final resolve to ensure that we get the correct type for them.
717 if (Name == CurRec->getNameInit()) {
718 if (!IsFinal)
719 break;
720 D = CurRec;
721 } else {
722 D = CurRec->getRecords().getDef(Name->getValue());
723 if (!D) {
724 if (IsFinal)
725 PrintFatalError(CurRec->getLoc(),
726 Twine("Undefined reference to record: '") +
727 Name->getValue() + "'\n");
728 break;
729 }
730 }
731
732 DefInit *DI = DefInit::get(D);
733 if (!DI->getType()->typeIsA(getType())) {
734 PrintFatalError(CurRec->getLoc(),
735 Twine("Expected type '") +
736 getType()->getAsString() + "', got '" +
737 DI->getType()->getAsString() + "' in: " +
738 getAsString() + "\n");
739 }
740 return DI;
741 }
742 }
743
744 if (Init *NewInit = LHS->convertInitializerTo(getType()))
745 return NewInit;
746 break;
747
748 case HEAD:
749 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
750 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp"
, 750, __extension__ __PRETTY_FUNCTION__))
;
751 return LHSl->getElement(0);
752 }
753 break;
754
755 case TAIL:
756 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
757 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp"
, 757, __extension__ __PRETTY_FUNCTION__))
;
758 // Note the +1. We can't just pass the result of getValues()
759 // directly.
760 return ListInit::get(LHSl->getValues().slice(1), LHSl->getElementType());
761 }
762 break;
763
764 case SIZE:
765 if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
766 return IntInit::get(LHSl->size());
767 break;
768
769 case EMPTY:
770 if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
771 return IntInit::get(LHSl->empty());
772 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
773 return IntInit::get(LHSs->getValue().empty());
774 break;
775 }
776 return const_cast<UnOpInit *>(this);
777}
778
779Init *UnOpInit::resolveReferences(Resolver &R) const {
780 Init *lhs = LHS->resolveReferences(R);
781
782 if (LHS != lhs || (R.isFinal() && getOpcode() == CAST))
783 return (UnOpInit::get(getOpcode(), lhs, getType()))
784 ->Fold(R.getCurrentRecord(), R.isFinal());
785 return const_cast<UnOpInit *>(this);
786}
787
788std::string UnOpInit::getAsString() const {
789 std::string Result;
790 switch (getOpcode()) {
791 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
792 case HEAD: Result = "!head"; break;
793 case TAIL: Result = "!tail"; break;
794 case SIZE: Result = "!size"; break;
795 case EMPTY: Result = "!empty"; break;
796 }
797 return Result + "(" + LHS->getAsString() + ")";
798}
799
800static void
801ProfileBinOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *RHS,
802 RecTy *Type) {
803 ID.AddInteger(Opcode);
804 ID.AddPointer(LHS);
805 ID.AddPointer(RHS);
806 ID.AddPointer(Type);
807}
808
809BinOpInit *BinOpInit::get(BinaryOp Opc, Init *LHS,
810 Init *RHS, RecTy *Type) {
811 static FoldingSet<BinOpInit> ThePool;
812
813 FoldingSetNodeID ID;
814 ProfileBinOpInit(ID, Opc, LHS, RHS, Type);
815
816 void *IP = nullptr;
817 if (BinOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
818 return I;
819
820 BinOpInit *I = new(Allocator) BinOpInit(Opc, LHS, RHS, Type);
821 ThePool.InsertNode(I, IP);
822 return I;
823}
824
825void BinOpInit::Profile(FoldingSetNodeID &ID) const {
826 ProfileBinOpInit(ID, getOpcode(), getLHS(), getRHS(), getType());
827}
828
829static StringInit *ConcatStringInits(const StringInit *I0,
830 const StringInit *I1) {
831 SmallString<80> Concat(I0->getValue());
832 Concat.append(I1->getValue());
833 return StringInit::get(Concat);
834}
835
836Init *BinOpInit::getStrConcat(Init *I0, Init *I1) {
837 // Shortcut for the common case of concatenating two strings.
838 if (const StringInit *I0s = dyn_cast<StringInit>(I0))
839 if (const StringInit *I1s = dyn_cast<StringInit>(I1))
840 return ConcatStringInits(I0s, I1s);
841 return BinOpInit::get(BinOpInit::STRCONCAT, I0, I1, StringRecTy::get());
842}
843
844Init *BinOpInit::Fold(Record *CurRec) const {
845 switch (getOpcode()) {
846 case CONCAT: {
847 DagInit *LHSs = dyn_cast<DagInit>(LHS);
848 DagInit *RHSs = dyn_cast<DagInit>(RHS);
849 if (LHSs && RHSs) {
850 DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
851 DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
852 if (!LOp || !ROp)
853 break;
854 if (LOp->getDef() != ROp->getDef()) {
855 PrintFatalError(Twine("Concatenated Dag operators do not match: '") +
856 LHSs->getAsString() + "' vs. '" + RHSs->getAsString() +
857 "'");
858 }
859 SmallVector<Init*, 8> Args;
860 SmallVector<StringInit*, 8> ArgNames;
861 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
862 Args.push_back(LHSs->getArg(i));
863 ArgNames.push_back(LHSs->getArgName(i));
864 }
865 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
866 Args.push_back(RHSs->getArg(i));
867 ArgNames.push_back(RHSs->getArgName(i));
868 }
869 return DagInit::get(LHSs->getOperator(), nullptr, Args, ArgNames);
870 }
871 break;
872 }
873 case LISTCONCAT: {
874 ListInit *LHSs = dyn_cast<ListInit>(LHS);
875 ListInit *RHSs = dyn_cast<ListInit>(RHS);
876 if (LHSs && RHSs) {
877 SmallVector<Init *, 8> Args;
878 Args.insert(Args.end(), LHSs->begin(), LHSs->end());
879 Args.insert(Args.end(), RHSs->begin(), RHSs->end());
880 return ListInit::get(Args, LHSs->getElementType());
881 }
882 break;
883 }
884 case STRCONCAT: {
885 StringInit *LHSs = dyn_cast<StringInit>(LHS);
886 StringInit *RHSs = dyn_cast<StringInit>(RHS);
887 if (LHSs && RHSs)
888 return ConcatStringInits(LHSs, RHSs);
889 break;
890 }
891 case EQ:
892 case NE:
893 case LE:
894 case LT:
895 case GE:
896 case GT: {
897 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
898 // to string objects.
899 IntInit *L =
900 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
901 IntInit *R =
902 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
903
904 if (L && R) {
905 bool Result;
906 switch (getOpcode()) {
907 case EQ: Result = L->getValue() == R->getValue(); break;
908 case NE: Result = L->getValue() != R->getValue(); break;
909 case LE: Result = L->getValue() <= R->getValue(); break;
910 case LT: Result = L->getValue() < R->getValue(); break;
911 case GE: Result = L->getValue() >= R->getValue(); break;
912 case GT: Result = L->getValue() > R->getValue(); break;
913 default: llvm_unreachable("unhandled comparison")::llvm::llvm_unreachable_internal("unhandled comparison", "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp"
, 913)
;
914 }
915 return BitInit::get(Result);
916 }
917
918 if (getOpcode() == EQ || getOpcode() == NE) {
919 StringInit *LHSs = dyn_cast<StringInit>(LHS);
920 StringInit *RHSs = dyn_cast<StringInit>(RHS);
921
922 // Make sure we've resolved
923 if (LHSs && RHSs) {
924 bool Equal = LHSs->getValue() == RHSs->getValue();
925 return BitInit::get(getOpcode() == EQ ? Equal : !Equal);
926 }
927 }
928
929 break;
930 }
931 case ADD:
932 case AND:
933 case OR:
934 case SHL:
935 case SRA:
936 case SRL: {
937 IntInit *LHSi =
938 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
939 IntInit *RHSi =
940 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
941 if (LHSi && RHSi) {
942 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
943 int64_t Result;
944 switch (getOpcode()) {
945 default: llvm_unreachable("Bad opcode!")::llvm::llvm_unreachable_internal("Bad opcode!", "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp"
, 945)
;
946 case ADD: Result = LHSv + RHSv; break;
947 case AND: Result = LHSv & RHSv; break;
948 case OR: Result = LHSv | RHSv; break;
949 case SHL: Result = LHSv << RHSv; break;
950 case SRA: Result = LHSv >> RHSv; break;
951 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
952 }
953 return IntInit::get(Result);
954 }
955 break;
956 }
957 }
958 return const_cast<BinOpInit *>(this);
959}
960
961Init *BinOpInit::resolveReferences(Resolver &R) const {
962 Init *lhs = LHS->resolveReferences(R);
963 Init *rhs = RHS->resolveReferences(R);
964
965 if (LHS != lhs || RHS != rhs)
966 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))
967 ->Fold(R.getCurrentRecord());
968 return const_cast<BinOpInit *>(this);
969}
970
971std::string BinOpInit::getAsString() const {
972 std::string Result;
973 switch (getOpcode()) {
974 case CONCAT: Result = "!con"; break;
975 case ADD: Result = "!add"; break;
976 case AND: Result = "!and"; break;
977 case OR: Result = "!or"; break;
978 case SHL: Result = "!shl"; break;
979 case SRA: Result = "!sra"; break;
980 case SRL: Result = "!srl"; break;
981 case EQ: Result = "!eq"; break;
982 case NE: Result = "!ne"; break;
983 case LE: Result = "!le"; break;
984 case LT: Result = "!lt"; break;
985 case GE: Result = "!ge"; break;
986 case GT: Result = "!gt"; break;
987 case LISTCONCAT: Result = "!listconcat"; break;
988 case STRCONCAT: Result = "!strconcat"; break;
989 }
990 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
991}
992
993static void
994ProfileTernOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *MHS,
995 Init *RHS, RecTy *Type) {
996 ID.AddInteger(Opcode);
997 ID.AddPointer(LHS);
998 ID.AddPointer(MHS);
999 ID.AddPointer(RHS);
1000 ID.AddPointer(Type);
1001}
1002
1003TernOpInit *TernOpInit::get(TernaryOp Opc, Init *LHS, Init *MHS, Init *RHS,
1004 RecTy *Type) {
1005 static FoldingSet<TernOpInit> ThePool;
1006
1007 FoldingSetNodeID ID;
1008 ProfileTernOpInit(ID, Opc, LHS, MHS, RHS, Type);
1009
1010 void *IP = nullptr;
1011 if (TernOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1012 return I;
1013
1014 TernOpInit *I = new(Allocator) TernOpInit(Opc, LHS, MHS, RHS, Type);
1015 ThePool.InsertNode(I, IP);
1016 return I;
1017}
1018
1019void TernOpInit::Profile(FoldingSetNodeID &ID) const {
1020 ProfileTernOpInit(ID, getOpcode(), getLHS(), getMHS(), getRHS(), getType());
1021}
1022
1023static Init *ForeachApply(Init *LHS, Init *MHSe, Init *RHS, Record *CurRec) {
1024 MapResolver R(CurRec);
1025 R.set(LHS, MHSe);
1026 return RHS->resolveReferences(R);
1027}
1028
1029static Init *ForeachDagApply(Init *LHS, DagInit *MHSd, Init *RHS,
1030 Record *CurRec) {
1031 bool Change = false;
1032 Init *Val = ForeachApply(LHS, MHSd->getOperator(), RHS, CurRec);
1033 if (Val != MHSd->getOperator())
1034 Change = true;
1035
1036 SmallVector<std::pair<Init *, StringInit *>, 8> NewArgs;
1037 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1038 Init *Arg = MHSd->getArg(i);
1039 Init *NewArg;
1040 StringInit *ArgName = MHSd->getArgName(i);
1041
1042 if (DagInit *Argd = dyn_cast<DagInit>(Arg))
1043 NewArg = ForeachDagApply(LHS, Argd, RHS, CurRec);
1044 else
1045 NewArg = ForeachApply(LHS, Arg, RHS, CurRec);
1046
1047 NewArgs.push_back(std::make_pair(NewArg, ArgName));
1048 if (Arg != NewArg)
1049 Change = true;
1050 }
1051
1052 if (Change)
1053 return DagInit::get(Val, nullptr, NewArgs);
1054 return MHSd;
1055}
1056
1057// Applies RHS to all elements of MHS, using LHS as a temp variable.
1058static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1059 Record *CurRec) {
1060 if (DagInit *MHSd = dyn_cast<DagInit>(MHS))
1061 return ForeachDagApply(LHS, MHSd, RHS, CurRec);
1062
1063 if (ListInit *MHSl = dyn_cast<ListInit>(MHS)) {
1064 SmallVector<Init *, 8> NewList(MHSl->begin(), MHSl->end());
1065
1066 for (Init *&Item : NewList) {
1067 Init *NewItem = ForeachApply(LHS, Item, RHS, CurRec);
1068 if (NewItem != Item)
1069 Item = NewItem;
1070 }
1071 return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());
1072 }
1073
1074 return nullptr;
1075}
1076
1077Init *TernOpInit::Fold(Record *CurRec) const {
1078 switch (getOpcode()) {
1079 case SUBST: {
1080 DefInit *LHSd = dyn_cast<DefInit>(LHS);
1081 VarInit *LHSv = dyn_cast<VarInit>(LHS);
1082 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1083
1084 DefInit *MHSd = dyn_cast<DefInit>(MHS);
1085 VarInit *MHSv = dyn_cast<VarInit>(MHS);
1086 StringInit *MHSs = dyn_cast<StringInit>(MHS);
1087
1088 DefInit *RHSd = dyn_cast<DefInit>(RHS);
1089 VarInit *RHSv = dyn_cast<VarInit>(RHS);
1090 StringInit *RHSs = dyn_cast<StringInit>(RHS);
1091
1092 if (LHSd && MHSd && RHSd) {
1093 Record *Val = RHSd->getDef();
1094 if (LHSd->getAsString() == RHSd->getAsString())
1095 Val = MHSd->getDef();
1096 return DefInit::get(Val);
1097 }
1098 if (LHSv && MHSv && RHSv) {
1099 std::string Val = RHSv->getName();
1100 if (LHSv->getAsString() == RHSv->getAsString())
1101 Val = MHSv->getName();
1102 return VarInit::get(Val, getType());
1103 }
1104 if (LHSs && MHSs && RHSs) {
1105 std::string Val = RHSs->getValue();
1106
1107 std::string::size_type found;
1108 std::string::size_type idx = 0;
1109 while (true) {
1110 found = Val.find(LHSs->getValue(), idx);
1111 if (found == std::string::npos)
1112 break;
1113 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1114 idx = found + MHSs->getValue().size();
1115 }
1116
1117 return StringInit::get(Val);
1118 }
1119 break;
1120 }
1121
1122 case FOREACH: {
1123 if (Init *Result = ForeachHelper(LHS, MHS, RHS, getType(), CurRec))
1124 return Result;
1125 break;
1126 }
1127
1128 case IF: {
1129 if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
1130 LHS->convertInitializerTo(IntRecTy::get()))) {
1131 if (LHSi->getValue())
1132 return MHS;
1133 return RHS;
1134 }
1135 break;
1136 }
1137
1138 case DAG: {
1139 ListInit *MHSl = dyn_cast<ListInit>(MHS);
1140 ListInit *RHSl = dyn_cast<ListInit>(RHS);
1141 bool MHSok = MHSl || isa<UnsetInit>(MHS);
1142 bool RHSok = RHSl || isa<UnsetInit>(RHS);
1143
1144 if (isa<UnsetInit>(MHS) && isa<UnsetInit>(RHS))
1145 break; // Typically prevented by the parser, but might happen with template args
1146
1147 if (MHSok && RHSok && (!MHSl || !RHSl || MHSl->size() == RHSl->size())) {
1148 SmallVector<std::pair<Init *, StringInit *>, 8> Children;
1149 unsigned Size = MHSl ? MHSl->size() : RHSl->size();
1150 for (unsigned i = 0; i != Size; ++i) {
1151 Init *Node = MHSl ? MHSl->getElement(i) : UnsetInit::get();
1152 Init *Name = RHSl ? RHSl->getElement(i) : UnsetInit::get();
1153 if (!isa<StringInit>(Name) && !isa<UnsetInit>(Name))
1154 return const_cast<TernOpInit *>(this);
1155 Children.emplace_back(Node, dyn_cast<StringInit>(Name));
1156 }
1157 return DagInit::get(LHS, nullptr, Children);
1158 }
1159 break;
1160 }
1161 }
1162
1163 return const_cast<TernOpInit *>(this);
1164}
1165
1166Init *TernOpInit::resolveReferences(Resolver &R) const {
1167 Init *lhs = LHS->resolveReferences(R);
1168
1169 if (getOpcode() == IF && lhs != LHS) {
1170 if (IntInit *Value = dyn_cast_or_null<IntInit>(
1171 lhs->convertInitializerTo(IntRecTy::get()))) {
1172 // Short-circuit
1173 if (Value->getValue())
1174 return MHS->resolveReferences(R);
1175 return RHS->resolveReferences(R);
1176 }
1177 }
1178
1179 Init *mhs = MHS->resolveReferences(R);
1180 Init *rhs;
1181
1182 if (getOpcode() == FOREACH) {
1183 ShadowResolver SR(R);
1184 SR.addShadow(lhs);
1185 rhs = RHS->resolveReferences(SR);
1186 } else {
1187 rhs = RHS->resolveReferences(R);
1188 }
1189
1190 if (LHS != lhs || MHS != mhs || RHS != rhs)
1191 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs, getType()))
1192 ->Fold(R.getCurrentRecord());
1193 return const_cast<TernOpInit *>(this);
1194}
1195
1196std::string TernOpInit::getAsString() const {
1197 std::string Result;
1198 switch (getOpcode()) {
1199 case SUBST: Result = "!subst"; break;
1200 case FOREACH: Result = "!foreach"; break;
1201 case IF: Result = "!if"; break;
1202 case DAG: Result = "!dag"; break;
1203 }
1204 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", " +
1205 RHS->getAsString() + ")";
1206}
1207
1208static void ProfileFoldOpInit(FoldingSetNodeID &ID, Init *A, Init *B,
1209 Init *Start, Init *List, Init *Expr,
1210 RecTy *Type) {
1211 ID.AddPointer(Start);
1212 ID.AddPointer(List);
1213 ID.AddPointer(A);
1214 ID.AddPointer(B);
1215 ID.AddPointer(Expr);
1216 ID.AddPointer(Type);
1217}
1218
1219FoldOpInit *FoldOpInit::get(Init *Start, Init *List, Init *A, Init *B,
1220 Init *Expr, RecTy *Type) {
1221 static FoldingSet<FoldOpInit> ThePool;
1222
1223 FoldingSetNodeID ID;
1224 ProfileFoldOpInit(ID, Start, List, A, B, Expr, Type);
1225
1226 void *IP = nullptr;
1227 if (FoldOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1228 return I;
1229
1230 FoldOpInit *I = new (Allocator) FoldOpInit(Start, List, A, B, Expr, Type);
1231 ThePool.InsertNode(I, IP);
1232 return I;
1233}
1234
1235void FoldOpInit::Profile(FoldingSetNodeID &ID) const {
1236 ProfileFoldOpInit(ID, Start, List, A, B, Expr, getType());
1237}
1238
1239Init *FoldOpInit::Fold(Record *CurRec) const {
1240 if (ListInit *LI = dyn_cast<ListInit>(List)) {
1241 Init *Accum = Start;
1242 for (Init *Elt : *LI) {
1243 MapResolver R(CurRec);
1244 R.set(A, Accum);
1245 R.set(B, Elt);
1246 Accum = Expr->resolveReferences(R);
1247 }
1248 return Accum;
1249 }
1250 return const_cast<FoldOpInit *>(this);
1251}
1252
1253Init *FoldOpInit::resolveReferences(Resolver &R) const {
1254 Init *NewStart = Start->resolveReferences(R);
1255 Init *NewList = List->resolveReferences(R);
1256 ShadowResolver SR(R);
1257 SR.addShadow(A);
1258 SR.addShadow(B);
1259 Init *NewExpr = Expr->resolveReferences(SR);
1260
1261 if (Start == NewStart && List == NewList && Expr == NewExpr)
1262 return const_cast<FoldOpInit *>(this);
1263
1264 return get(NewStart, NewList, A, B, NewExpr, getType())
1265 ->Fold(R.getCurrentRecord());
1266}
1267
1268Init *FoldOpInit::getBit(unsigned Bit) const {
1269 return VarBitInit::get(const_cast<FoldOpInit *>(this), Bit);
1270}
1271
1272std::string FoldOpInit::getAsString() const {
1273 return (Twine("!foldl(") + Start->getAsString() + ", " + List->getAsString() +
1274 ", " + A->getAsUnquotedString() + ", " + B->getAsUnquotedString() +
1275 ", " + Expr->getAsString() + ")")
1276 .str();
1277}
1278
1279static void ProfileIsAOpInit(FoldingSetNodeID &ID, RecTy *CheckType,
1280 Init *Expr) {
1281 ID.AddPointer(CheckType);
1282 ID.AddPointer(Expr);
1283}
1284
1285IsAOpInit *IsAOpInit::get(RecTy *CheckType, Init *Expr) {
1286 static FoldingSet<IsAOpInit> ThePool;
1287
1288 FoldingSetNodeID ID;
1289 ProfileIsAOpInit(ID, CheckType, Expr);
1290
1291 void *IP = nullptr;
1292 if (IsAOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1293 return I;
1294
1295 IsAOpInit *I = new (Allocator) IsAOpInit(CheckType, Expr);
1296 ThePool.InsertNode(I, IP);
1297 return I;
1298}
1299
1300void IsAOpInit::Profile(FoldingSetNodeID &ID) const {
1301 ProfileIsAOpInit(ID, CheckType, Expr);
1302}
1303
1304Init *IsAOpInit::Fold() const {
1305 if (TypedInit *TI = dyn_cast<TypedInit>(Expr)) {
1306 // Is the expression type known to be (a subclass of) the desired type?
1307 if (TI->getType()->typeIsConvertibleTo(CheckType))
1308 return IntInit::get(1);
1309
1310 if (isa<RecordRecTy>(CheckType)) {
1311 // If the target type is not a subclass of the expression type, or if
1312 // the expression has fully resolved to a record, we know that it can't
1313 // be of the required type.
1314 if (!CheckType->typeIsConvertibleTo(TI->getType()) || isa<DefInit>(Expr))
1315 return IntInit::get(0);
1316 } else {
1317 // We treat non-record types as not castable.
1318 return IntInit::get(0);
1319 }
1320 }
1321 return const_cast<IsAOpInit *>(this);
1322}
1323
1324Init *IsAOpInit::resolveReferences(Resolver &R) const {
1325 Init *NewExpr = Expr->resolveReferences(R);
1326 if (Expr != NewExpr)
1327 return get(CheckType, NewExpr)->Fold();
1328 return const_cast<IsAOpInit *>(this);
1329}
1330
1331Init *IsAOpInit::getBit(unsigned Bit) const {
1332 return VarBitInit::get(const_cast<IsAOpInit *>(this), Bit);
1333}
1334
1335std::string IsAOpInit::getAsString() const {
1336 return (Twine("!isa<") + CheckType->getAsString() + ">(" +
1337 Expr->getAsString() + ")")
1338 .str();
1339}
1340
1341RecTy *TypedInit::getFieldType(StringInit *FieldName) const {
1342 if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType())) {
1343 for (Record *Rec : RecordType->getClasses()) {
1344 if (RecordVal *Field = Rec->getValue(FieldName))
1345 return Field->getType();
1346 }
1347 }
1348 return nullptr;
1349}
1350
1351Init *
1352TypedInit::convertInitializerTo(RecTy *Ty) const {
1353 if (getType() == Ty || getType()->typeIsA(Ty))
1354 return const_cast<TypedInit *>(this);
1355
1356 if (isa<BitRecTy>(getType()) && isa<BitsRecTy>(Ty) &&
1357 cast<BitsRecTy>(Ty)->getNumBits() == 1)
1358 return BitsInit::get({const_cast<TypedInit *>(this)});
1359
1360 return nullptr;
1361}
1362
1363Init *TypedInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
1364 BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1365 if (!T) return nullptr; // Cannot subscript a non-bits variable.
1366 unsigned NumBits = T->getNumBits();
1367
1368 SmallVector<Init *, 16> NewBits;
1369 NewBits.reserve(Bits.size());
1370 for (unsigned Bit : Bits) {
1371 if (Bit >= NumBits)
1372 return nullptr;
1373
1374 NewBits.push_back(VarBitInit::get(const_cast<TypedInit *>(this), Bit));
1375 }
1376 return BitsInit::get(NewBits);
1377}
1378
1379Init *TypedInit::getCastTo(RecTy *Ty) const {
1380 // Handle the common case quickly
1381 if (getType() == Ty || getType()->typeIsA(Ty))
1382 return const_cast<TypedInit *>(this);
1383
1384 if (Init *Converted = convertInitializerTo(Ty)) {
1385 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)"
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp"
, 1386, __extension__ __PRETTY_FUNCTION__))
1386 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)"
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp"
, 1386, __extension__ __PRETTY_FUNCTION__))
;
1387 return Converted;
1388 }
1389
1390 if (!getType()->typeIsConvertibleTo(Ty))
1391 return nullptr;
1392
1393 return UnOpInit::get(UnOpInit::CAST, const_cast<TypedInit *>(this), Ty)
1394 ->Fold(nullptr);
1395}
1396
1397Init *TypedInit::convertInitListSlice(ArrayRef<unsigned> Elements) const {
1398 ListRecTy *T = dyn_cast<ListRecTy>(getType());
1399 if (!T) return nullptr; // Cannot subscript a non-list variable.
1400
1401 if (Elements.size() == 1)
1402 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1403
1404 SmallVector<Init*, 8> ListInits;
1405 ListInits.reserve(Elements.size());
1406 for (unsigned Element : Elements)
1407 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1408 Element));
1409 return ListInit::get(ListInits, T->getElementType());
1410}
1411
1412
1413VarInit *VarInit::get(StringRef VN, RecTy *T) {
1414 Init *Value = StringInit::get(VN);
1415 return VarInit::get(Value, T);
1416}
1417
1418VarInit *VarInit::get(Init *VN, RecTy *T) {
1419 using Key = std::pair<RecTy *, Init *>;
1420 static DenseMap<Key, VarInit*> ThePool;
1421
1422 Key TheKey(std::make_pair(T, VN));
1423
1424 VarInit *&I = ThePool[TheKey];
1425 if (!I)
1426 I = new(Allocator) VarInit(VN, T);
1427 return I;
1428}
1429
1430StringRef VarInit::getName() const {
1431 StringInit *NameString = cast<StringInit>(getNameInit());
1432 return NameString->getValue();
1433}
1434
1435Init *VarInit::getBit(unsigned Bit) const {
1436 if (getType() == BitRecTy::get())
1437 return const_cast<VarInit*>(this);
1438 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1439}
1440
1441Init *VarInit::resolveReferences(Resolver &R) const {
1442 if (Init *Val = R.resolve(VarName))
1443 return Val;
1444 return const_cast<VarInit *>(this);
1445}
1446
1447VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1448 using Key = std::pair<TypedInit *, unsigned>;
1449 static DenseMap<Key, VarBitInit*> ThePool;
1450
1451 Key TheKey(std::make_pair(T, B));
1452
1453 VarBitInit *&I = ThePool[TheKey];
1454 if (!I)
1455 I = new(Allocator) VarBitInit(T, B);
1456 return I;
1457}
1458
1459std::string VarBitInit::getAsString() const {
1460 return TI->getAsString() + "{" + utostr(Bit) + "}";
1461}
1462
1463Init *VarBitInit::resolveReferences(Resolver &R) const {
1464 Init *I = TI->resolveReferences(R);
1465 if (TI != I)
1466 return I->getBit(getBitNum());
1467
1468 return const_cast<VarBitInit*>(this);
1469}
1470
1471VarListElementInit *VarListElementInit::get(TypedInit *T,
1472 unsigned E) {
1473 using Key = std::pair<TypedInit *, unsigned>;
1474 static DenseMap<Key, VarListElementInit*> ThePool;
1475
1476 Key TheKey(std::make_pair(T, E));
1477
1478 VarListElementInit *&I = ThePool[TheKey];
1479 if (!I) I = new(Allocator) VarListElementInit(T, E);
1480 return I;
1481}
1482
1483std::string VarListElementInit::getAsString() const {
1484 return TI->getAsString() + "[" + utostr(Element) + "]";
1485}
1486
1487Init *VarListElementInit::resolveReferences(Resolver &R) const {
1488 Init *NewTI = TI->resolveReferences(R);
1489 if (ListInit *List = dyn_cast<ListInit>(NewTI)) {
1490 // Leave out-of-bounds array references as-is. This can happen without
1491 // being an error, e.g. in the untaken "branch" of an !if expression.
1492 if (getElementNum() < List->size())
1493 return List->getElement(getElementNum());
1494 }
1495 if (NewTI != TI && isa<TypedInit>(NewTI))
1496 return VarListElementInit::get(cast<TypedInit>(NewTI), getElementNum());
1497 return const_cast<VarListElementInit *>(this);
1498}
1499
1500Init *VarListElementInit::getBit(unsigned Bit) const {
1501 if (getType() == BitRecTy::get())
1502 return const_cast<VarListElementInit*>(this);
1503 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1504}
1505
1506DefInit::DefInit(Record *D)
1507 : TypedInit(IK_DefInit, D->getType()), Def(D) {}
1508
1509DefInit *DefInit::get(Record *R) {
1510 return R->getDefInit();
1511}
1512
1513Init *DefInit::convertInitializerTo(RecTy *Ty) const {
1514 if (auto *RRT = dyn_cast<RecordRecTy>(Ty))
1515 if (getType()->typeIsConvertibleTo(RRT))
1516 return const_cast<DefInit *>(this);
1517 return nullptr;
1518}
1519
1520RecTy *DefInit::getFieldType(StringInit *FieldName) const {
1521 if (const RecordVal *RV = Def->getValue(FieldName))
1522 return RV->getType();
1523 return nullptr;
1524}
1525
1526std::string DefInit::getAsString() const {
1527 return Def->getName();
1528}
1529
1530static void ProfileVarDefInit(FoldingSetNodeID &ID,
1531 Record *Class,
1532 ArrayRef<Init *> Args) {
1533 ID.AddInteger(Args.size());
1534 ID.AddPointer(Class);
1535
1536 for (Init *I : Args)
1537 ID.AddPointer(I);
1538}
1539
1540VarDefInit *VarDefInit::get(Record *Class, ArrayRef<Init *> Args) {
1541 static FoldingSet<VarDefInit> ThePool;
1542
1543 FoldingSetNodeID ID;
1544 ProfileVarDefInit(ID, Class, Args);
1545
1546 void *IP = nullptr;
1547 if (VarDefInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1548 return I;
1549
1550 void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Args.size()),
1551 alignof(VarDefInit));
1552 VarDefInit *I = new(Mem) VarDefInit(Class, Args.size());
1553 std::uninitialized_copy(Args.begin(), Args.end(),
1554 I->getTrailingObjects<Init *>());
1555 ThePool.InsertNode(I, IP);
1556 return I;
1557}
1558
1559void VarDefInit::Profile(FoldingSetNodeID &ID) const {
1560 ProfileVarDefInit(ID, Class, args());
1561}
1562
1563DefInit *VarDefInit::instantiate() {
1564 if (!Def) {
6
Assuming the condition is true
7
Taking true branch
1565 RecordKeeper &Records = Class->getRecords();
1566 auto NewRecOwner = make_unique<Record>(Records.getNewAnonymousName(),
8
Calling 'make_unique'
10
Returned allocated memory
1567 Class->getLoc(), Records,
1568 /*IsAnonymous=*/true);
1569 Record *NewRec = NewRecOwner.get();
1570
1571 // Copy values from class to instance
1572 for (const RecordVal &Val : Class->getValues()) {
11
Assuming '__begin2' is equal to '__end2'
1573 if (Val.getName() != "NAME")
1574 NewRec->addValue(Val);
1575 }
1576
1577 // Substitute and resolve template arguments
1578 ArrayRef<Init *> TArgs = Class->getTemplateArgs();
1579 MapResolver R(NewRec);
1580
1581 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
12
Assuming 'i' is equal to 'e'
13
Loop condition is false. Execution continues on line 1590
1582 if (i < args_size())
1583 R.set(TArgs[i], getArg(i));
1584 else
1585 R.set(TArgs[i], NewRec->getValue(TArgs[i])->getValue());
1586
1587 NewRec->removeValue(TArgs[i]);
1588 }
1589
1590 NewRec->resolveReferences(R);
1591
1592 // Add superclasses.
1593 ArrayRef<std::pair<Record *, SMRange>> SCs = Class->getSuperClasses();
1594 for (const auto &SCPair : SCs)
14
Assuming '__begin2' is equal to '__end2'
1595 NewRec->addSuperClass(SCPair.first, SCPair.second);
1596
1597 NewRec->addSuperClass(Class,
1598 SMRange(Class->getLoc().back(),
1599 Class->getLoc().back()));
1600
1601 // Resolve internal references and store in record keeper
1602 NewRec->resolveReferences();
1603 Records.addDef(std::move(NewRecOwner));
15
Calling '~unique_ptr'
20
Returning from '~unique_ptr'
1604
1605 Def = DefInit::get(NewRec);
21
Use of memory after it is freed
1606 }
1607
1608 return Def;
1609}
1610
1611Init *VarDefInit::resolveReferences(Resolver &R) const {
1612 TrackUnresolvedResolver UR(&R);
1613 bool Changed = false;
1614 SmallVector<Init *, 8> NewArgs;
1615 NewArgs.reserve(args_size());
1616
1617 for (Init *Arg : args()) {
1618 Init *NewArg = Arg->resolveReferences(UR);
1619 NewArgs.push_back(NewArg);
1620 Changed |= NewArg != Arg;
1621 }
1622
1623 if (Changed) {
1624 auto New = VarDefInit::get(Class, NewArgs);
1625 if (!UR.foundUnresolved())
1626 return New->instantiate();
1627 return New;
1628 }
1629 return const_cast<VarDefInit *>(this);
1630}
1631
1632Init *VarDefInit::Fold() const {
1633 if (Def)
1
Assuming the condition is false
2
Taking false branch
1634 return Def;
1635
1636 TrackUnresolvedResolver R;
1637 for (Init *Arg : args())
3
Assuming '__begin1' is equal to '__end1'
1638 Arg->resolveReferences(R);
1639
1640 if (!R.foundUnresolved())
4
Taking true branch
1641 return const_cast<VarDefInit *>(this)->instantiate();
5
Calling 'VarDefInit::instantiate'
1642 return const_cast<VarDefInit *>(this);
1643}
1644
1645std::string VarDefInit::getAsString() const {
1646 std::string Result = Class->getNameInitAsString() + "<";
1647 const char *sep = "";
1648 for (Init *Arg : args()) {
1649 Result += sep;
1650 sep = ", ";
1651 Result += Arg->getAsString();
1652 }
1653 return Result + ">";
1654}
1655
1656FieldInit *FieldInit::get(Init *R, StringInit *FN) {
1657 using Key = std::pair<Init *, StringInit *>;
1658 static DenseMap<Key, FieldInit*> ThePool;
1659
1660 Key TheKey(std::make_pair(R, FN));
1661
1662 FieldInit *&I = ThePool[TheKey];
1663 if (!I) I = new(Allocator) FieldInit(R, FN);
1664 return I;
1665}
1666
1667Init *FieldInit::getBit(unsigned Bit) const {
1668 if (getType() == BitRecTy::get())
1669 return const_cast<FieldInit*>(this);
1670 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1671}
1672
1673Init *FieldInit::resolveReferences(Resolver &R) const {
1674 Init *NewRec = Rec->resolveReferences(R);
1675 if (NewRec != Rec)
1676 return FieldInit::get(NewRec, FieldName)->Fold(R.getCurrentRecord());
1677 return const_cast<FieldInit *>(this);
1678}
1679
1680Init *FieldInit::Fold(Record *CurRec) const {
1681 if (DefInit *DI = dyn_cast<DefInit>(Rec)) {
1682 Record *Def = DI->getDef();
1683 if (Def == CurRec)
1684 PrintFatalError(CurRec->getLoc(),
1685 Twine("Attempting to access field '") +
1686 FieldName->getAsUnquotedString() + "' of '" +
1687 Rec->getAsString() + "' is a forbidden self-reference");
1688 Init *FieldVal = Def->getValue(FieldName)->getValue();
1689 if (FieldVal->isComplete())
1690 return FieldVal;
1691 }
1692 return const_cast<FieldInit *>(this);
1693}
1694
1695static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, StringInit *VN,
1696 ArrayRef<Init *> ArgRange,
1697 ArrayRef<StringInit *> NameRange) {
1698 ID.AddPointer(V);
1699 ID.AddPointer(VN);
1700
1701 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1702 ArrayRef<StringInit *>::iterator Name = NameRange.begin();
1703 while (Arg != ArgRange.end()) {
1704 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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp"
, 1704, __extension__ __PRETTY_FUNCTION__))
;
1705 ID.AddPointer(*Arg++);
1706 ID.AddPointer(*Name++);
1707 }
1708 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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp"
, 1708, __extension__ __PRETTY_FUNCTION__))
;
1709}
1710
1711DagInit *
1712DagInit::get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
1713 ArrayRef<StringInit *> NameRange) {
1714 static FoldingSet<DagInit> ThePool;
1715
1716 FoldingSetNodeID ID;
1717 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1718
1719 void *IP = nullptr;
1720 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1721 return I;
1722
1723 void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *, StringInit *>(ArgRange.size(), NameRange.size()), alignof(BitsInit));
1724 DagInit *I = new(Mem) DagInit(V, VN, ArgRange.size(), NameRange.size());
1725 std::uninitialized_copy(ArgRange.begin(), ArgRange.end(),
1726 I->getTrailingObjects<Init *>());
1727 std::uninitialized_copy(NameRange.begin(), NameRange.end(),
1728 I->getTrailingObjects<StringInit *>());
1729 ThePool.InsertNode(I, IP);
1730 return I;
1731}
1732
1733DagInit *
1734DagInit::get(Init *V, StringInit *VN,
1735 ArrayRef<std::pair<Init*, StringInit*>> args) {
1736 SmallVector<Init *, 8> Args;
1737 SmallVector<StringInit *, 8> Names;
1738
1739 for (const auto &Arg : args) {
1740 Args.push_back(Arg.first);
1741 Names.push_back(Arg.second);
1742 }
1743
1744 return DagInit::get(V, VN, Args, Names);
1745}
1746
1747void DagInit::Profile(FoldingSetNodeID &ID) const {
1748 ProfileDagInit(ID, Val, ValName, makeArrayRef(getTrailingObjects<Init *>(), NumArgs), makeArrayRef(getTrailingObjects<StringInit *>(), NumArgNames));
1749}
1750
1751Init *DagInit::resolveReferences(Resolver &R) const {
1752 SmallVector<Init*, 8> NewArgs;
1753 NewArgs.reserve(arg_size());
1754 bool ArgsChanged = false;
1755 for (const Init *Arg : getArgs()) {
1756 Init *NewArg = Arg->resolveReferences(R);
1757 NewArgs.push_back(NewArg);
1758 ArgsChanged |= NewArg != Arg;
1759 }
1760
1761 Init *Op = Val->resolveReferences(R);
1762 if (Op != Val || ArgsChanged)
1763 return DagInit::get(Op, ValName, NewArgs, getArgNames());
1764
1765 return const_cast<DagInit *>(this);
1766}
1767
1768bool DagInit::isConcrete() const {
1769 if (!Val->isConcrete())
1770 return false;
1771 for (const Init *Elt : getArgs()) {
1772 if (!Elt->isConcrete())
1773 return false;
1774 }
1775 return true;
1776}
1777
1778std::string DagInit::getAsString() const {
1779 std::string Result = "(" + Val->getAsString();
1780 if (ValName)
1781 Result += ":" + ValName->getAsUnquotedString();
1782 if (!arg_empty()) {
1783 Result += " " + getArg(0)->getAsString();
1784 if (getArgName(0)) Result += ":$" + getArgName(0)->getAsUnquotedString();
1785 for (unsigned i = 1, e = getNumArgs(); i != e; ++i) {
1786 Result += ", " + getArg(i)->getAsString();
1787 if (getArgName(i)) Result += ":$" + getArgName(i)->getAsUnquotedString();
1788 }
1789 }
1790 return Result + ")";
1791}
1792
1793//===----------------------------------------------------------------------===//
1794// Other implementations
1795//===----------------------------------------------------------------------===//
1796
1797RecordVal::RecordVal(Init *N, RecTy *T, bool P)
1798 : Name(N), TyAndPrefix(T, P) {
1799 setValue(UnsetInit::get());
1800 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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp"
, 1800, __extension__ __PRETTY_FUNCTION__))
;
1801}
1802
1803StringRef RecordVal::getName() const {
1804 return cast<StringInit>(getNameInit())->getValue();
1805}
1806
1807bool RecordVal::setValue(Init *V) {
1808 if (V) {
1809 Value = V->getCastTo(getType());
1810 if (Value) {
1811 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())"
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp"
, 1812, __extension__ __PRETTY_FUNCTION__))
1812 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())"
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp"
, 1812, __extension__ __PRETTY_FUNCTION__))
;
1813 if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) {
1814 if (!isa<BitsInit>(Value)) {
1815 SmallVector<Init *, 64> Bits;
1816 Bits.reserve(BTy->getNumBits());
1817 for (unsigned i = 0, e = BTy->getNumBits(); i < e; ++i)
1818 Bits.push_back(Value->getBit(i));
1819 Value = BitsInit::get(Bits);
1820 }
1821 }
1822 }
1823 return Value == nullptr;
1824 }
1825 Value = nullptr;
1826 return false;
1827}
1828
1829#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1830LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void RecordVal::dump() const { errs() << *this; }
1831#endif
1832
1833void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1834 if (getPrefix()) OS << "field ";
1835 OS << *getType() << " " << getNameInitAsString();
1836
1837 if (getValue())
1838 OS << " = " << *getValue();
1839
1840 if (PrintSem) OS << ";\n";
1841}
1842
1843unsigned Record::LastID = 0;
1844
1845void Record::init() {
1846 checkName();
1847
1848 // Every record potentially has a def at the top. This value is
1849 // replaced with the top-level def name at instantiation time.
1850 addValue(RecordVal(StringInit::get("NAME"), StringRecTy::get(), false));
1851}
1852
1853void Record::checkName() {
1854 // Ensure the record name has string type.
1855 const TypedInit *TypedName = cast<const TypedInit>(Name);
1856 if (!isa<StringRecTy>(TypedName->getType()))
1857 PrintFatalError(getLoc(), Twine("Record name '") + Name->getAsString() +
1858 "' is not a string!");
1859}
1860
1861RecordRecTy *Record::getType() {
1862 SmallVector<Record *, 4> DirectSCs;
1863 getDirectSuperClasses(DirectSCs);
1864 return RecordRecTy::get(DirectSCs);
1865}
1866
1867DefInit *Record::getDefInit() {
1868 if (!TheInit)
1869 TheInit = new(Allocator) DefInit(this);
1870 return TheInit;
1871}
1872
1873void Record::setName(Init *NewName) {
1874 Name = NewName;
1875 checkName();
1876 // DO NOT resolve record values to the name at this point because
1877 // there might be default values for arguments of this def. Those
1878 // arguments might not have been resolved yet so we don't want to
1879 // prematurely assume values for those arguments were not passed to
1880 // this def.
1881 //
1882 // Nonetheless, it may be that some of this Record's values
1883 // reference the record name. Indeed, the reason for having the
1884 // record name be an Init is to provide this flexibility. The extra
1885 // resolve steps after completely instantiating defs takes care of
1886 // this. See TGParser::ParseDef and TGParser::ParseDefm.
1887}
1888
1889void Record::getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const {
1890 ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses();
1891 while (!SCs.empty()) {
1892 // Superclasses are in reverse preorder, so 'back' is a direct superclass,
1893 // and its transitive superclasses are directly preceding it.
1894 Record *SC = SCs.back().first;
1895 SCs = SCs.drop_back(1 + SC->getSuperClasses().size());
1896 Classes.push_back(SC);
1897 }
1898}
1899
1900void Record::resolveReferences(Resolver &R, const RecordVal *SkipVal) {
1901 for (RecordVal &Value : Values) {
1902 if (SkipVal == &Value) // Skip resolve the same field as the given one
1903 continue;
1904 if (Init *V = Value.getValue()) {
1905 Init *VR = V->resolveReferences(R);
1906 if (Value.setValue(VR)) {
1907 std::string Type;
1908 if (TypedInit *VRT = dyn_cast<TypedInit>(VR))
1909 Type =
1910 (Twine("of type '") + VRT->getType()->getAsString() + "' ").str();
1911 PrintFatalError(getLoc(), Twine("Invalid value ") + Type +
1912 "is found when setting '" +
1913 Value.getNameInitAsString() +
1914 "' of type '" +
1915 Value.getType()->getAsString() +
1916 "' after resolving references: " +
1917 VR->getAsUnquotedString() + "\n");
1918 }
1919 }
1920 }
1921 Init *OldName = getNameInit();
1922 Init *NewName = Name->resolveReferences(R);
1923 if (NewName != OldName) {
1924 // Re-register with RecordKeeper.
1925 setName(NewName);
1926 }
1927}
1928
1929void Record::resolveReferences() {
1930 RecordResolver R(*this);
1931 R.setFinal(true);
1932 resolveReferences(R);
1933}
1934
1935void Record::resolveReferencesTo(const RecordVal *RV) {
1936 RecordValResolver R(*this, RV);
1937 resolveReferences(R, RV);
1938}
1939
1940#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1941LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void Record::dump() const { errs() << *this; }
1942#endif
1943
1944raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1945 OS << R.getNameInitAsString();
1946
1947 ArrayRef<Init *> TArgs = R.getTemplateArgs();
1948 if (!TArgs.empty()) {
1949 OS << "<";
1950 bool NeedComma = false;
1951 for (const Init *TA : TArgs) {
1952 if (NeedComma) OS << ", ";
1953 NeedComma = true;
1954 const RecordVal *RV = R.getValue(TA);
1955 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??\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/Record.cpp"
, 1955, __extension__ __PRETTY_FUNCTION__))
;
1956 RV->print(OS, false);
1957 }
1958 OS << ">";
1959 }
1960
1961 OS << " {";
1962 ArrayRef<std::pair<Record *, SMRange>> SC = R.getSuperClasses();
1963 if (!SC.empty()) {
1964 OS << "\t//";
1965 for (const auto &SuperPair : SC)
1966 OS << " " << SuperPair.first->getNameInitAsString();
1967 }
1968 OS << "\n";
1969
1970 for (const RecordVal &Val : R.getValues())
1971 if (Val.getPrefix() && !R.isTemplateArg(Val.getNameInit()))
1972 OS << Val;
1973 for (const RecordVal &Val : R.getValues())
1974 if (!Val.getPrefix() && !R.isTemplateArg(Val.getNameInit()))
1975 OS << Val;
1976
1977 return OS << "}\n";
1978}
1979
1980Init *Record::getValueInit(StringRef FieldName) const {
1981 const RecordVal *R = getValue(FieldName);
1982 if (!R || !R->getValue())
1983 PrintFatalError(getLoc(), "Record `" + getName() +
1984 "' does not have a field named `" + FieldName + "'!\n");
1985 return R->getValue();
1986}
1987
1988StringRef Record::getValueAsString(StringRef FieldName) const {
1989 const RecordVal *R = getValue(FieldName);
1990 if (!R || !R->getValue())
1991 PrintFatalError(getLoc(), "Record `" + getName() +
1992 "' does not have a field named `" + FieldName + "'!\n");
1993
1994 if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
1995 return SI->getValue();
1996 if (CodeInit *CI = dyn_cast<CodeInit>(R->getValue()))
1997 return CI->getValue();
1998
1999 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2000 FieldName + "' does not have a string initializer!");
2001}
2002
2003BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
2004 const RecordVal *R = getValue(FieldName);
2005 if (!R || !R->getValue())
2006 PrintFatalError(getLoc(), "Record `" + getName() +
2007 "' does not have a field named `" + FieldName + "'!\n");
2008
2009 if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
2010 return BI;
2011 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2012 FieldName + "' does not have a BitsInit initializer!");
2013}
2014
2015ListInit *Record::getValueAsListInit(StringRef FieldName) const {
2016 const RecordVal *R = getValue(FieldName);
2017 if (!R || !R->getValue())
2018 PrintFatalError(getLoc(), "Record `" + getName() +
2019 "' does not have a field named `" + FieldName + "'!\n");
2020
2021 if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
2022 return LI;
2023 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2024 FieldName + "' does not have a list initializer!");
2025}
2026
2027std::vector<Record*>
2028Record::getValueAsListOfDefs(StringRef FieldName) const {
2029 ListInit *List = getValueAsListInit(FieldName);
2030 std::vector<Record*> Defs;
2031 for (Init *I : List->getValues()) {
2032 if (DefInit *DI = dyn_cast<DefInit>(I))
2033 Defs.push_back(DI->getDef());
2034 else
2035 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2036 FieldName + "' list is not entirely DefInit!");
2037 }
2038 return Defs;
2039}
2040
2041int64_t Record::getValueAsInt(StringRef FieldName) const {
2042 const RecordVal *R = getValue(FieldName);
2043 if (!R || !R->getValue())
2044 PrintFatalError(getLoc(), "Record `" + getName() +
2045 "' does not have a field named `" + FieldName + "'!\n");
2046
2047 if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
2048 return II->getValue();
2049 PrintFatalError(getLoc(), Twine("Record `") + getName() + "', field `" +
2050 FieldName +
2051 "' does not have an int initializer: " +
2052 R->getValue()->getAsString());
2053}
2054
2055std::vector<int64_t>
2056Record::getValueAsListOfInts(StringRef FieldName) const {
2057 ListInit *List = getValueAsListInit(FieldName);
2058 std::vector<int64_t> Ints;
2059 for (Init *I : List->getValues()) {
2060 if (IntInit *II = dyn_cast<IntInit>(I))
2061 Ints.push_back(II->getValue());
2062 else
2063 PrintFatalError(getLoc(),
2064 Twine("Record `") + getName() + "', field `" + FieldName +
2065 "' does not have a list of ints initializer: " +
2066 I->getAsString());
2067 }
2068 return Ints;
2069}
2070
2071std::vector<StringRef>
2072Record::getValueAsListOfStrings(StringRef FieldName) const {
2073 ListInit *List = getValueAsListInit(FieldName);
2074 std::vector<StringRef> Strings;
2075 for (Init *I : List->getValues()) {
2076 if (StringInit *SI = dyn_cast<StringInit>(I))
2077 Strings.push_back(SI->getValue());
2078 else
2079 PrintFatalError(getLoc(),
2080 Twine("Record `") + getName() + "', field `" + FieldName +
2081 "' does not have a list of strings initializer: " +
2082 I->getAsString());
2083 }
2084 return Strings;
2085}
2086
2087Record *Record::getValueAsDef(StringRef FieldName) const {
2088 const RecordVal *R = getValue(FieldName);
2089 if (!R || !R->getValue())
2090 PrintFatalError(getLoc(), "Record `" + getName() +
2091 "' does not have a field named `" + FieldName + "'!\n");
2092
2093 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
2094 return DI->getDef();
2095 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2096 FieldName + "' does not have a def initializer!");
2097}
2098
2099bool Record::getValueAsBit(StringRef FieldName) const {
2100 const RecordVal *R = getValue(FieldName);
2101 if (!R || !R->getValue())
2102 PrintFatalError(getLoc(), "Record `" + getName() +
2103 "' does not have a field named `" + FieldName + "'!\n");
2104
2105 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
2106 return BI->getValue();
2107 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2108 FieldName + "' does not have a bit initializer!");
2109}
2110
2111bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
2112 const RecordVal *R = getValue(FieldName);
2113 if (!R || !R->getValue())
2114 PrintFatalError(getLoc(), "Record `" + getName() +
2115 "' does not have a field named `" + FieldName.str() + "'!\n");
2116
2117 if (isa<UnsetInit>(R->getValue())) {
2118 Unset = true;
2119 return false;
2120 }
2121 Unset = false;
2122 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
2123 return BI->getValue();
2124 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2125 FieldName + "' does not have a bit initializer!");
2126}
2127
2128DagInit *Record::getValueAsDag(StringRef FieldName) const {
2129 const RecordVal *R = getValue(FieldName);
2130 if (!R || !R->getValue())
2131 PrintFatalError(getLoc(), "Record `" + getName() +
2132 "' does not have a field named `" + FieldName + "'!\n");
2133
2134 if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
2135 return DI;
2136 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2137 FieldName + "' does not have a dag initializer!");
2138}
2139
2140#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2141LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void MultiClass::dump() const {
2142 errs() << "Record:\n";
2143 Rec.dump();
2144
2145 errs() << "Defs:\n";
2146 for (const auto &Proto : DefPrototypes)
2147 Proto->dump();
2148}
2149
2150LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void RecordKeeper::dump() const { errs() << *this; }
2151#endif
2152
2153raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
2154 OS << "------------- Classes -----------------\n";
2155 for (const auto &C : RK.getClasses())
2156 OS << "class " << *C.second;
2157
2158 OS << "------------- Defs -----------------\n";
2159 for (const auto &D : RK.getDefs())
2160 OS << "def " << *D.second;
2161 return OS;
2162}
2163
2164/// GetNewAnonymousName - Generate a unique anonymous name that can be used as
2165/// an identifier.
2166Init *RecordKeeper::getNewAnonymousName() {
2167 return StringInit::get("anonymous_" + utostr(AnonCounter++));
2168}
2169
2170std::vector<Record *>
2171RecordKeeper::getAllDerivedDefinitions(StringRef ClassName) const {
2172 Record *Class = getClass(ClassName);
2173 if (!Class)
2174 PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
2175
2176 std::vector<Record*> Defs;
2177 for (const auto &D : getDefs())
2178 if (D.second->isSubClassOf(Class))
2179 Defs.push_back(D.second.get());
2180
2181 return Defs;
2182}
2183
2184Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2185 Init *Name, StringRef Scoper) {
2186 Init *NewName =
2187 BinOpInit::getStrConcat(CurRec.getNameInit(), StringInit::get(Scoper));
2188 NewName = BinOpInit::getStrConcat(NewName, Name);
2189 if (CurMultiClass && Scoper != "::") {
2190 Init *Prefix = BinOpInit::getStrConcat(CurMultiClass->Rec.getNameInit(),
2191 StringInit::get("::"));
2192 NewName = BinOpInit::getStrConcat(Prefix, NewName);
2193 }
2194
2195 if (BinOpInit *BinOp = dyn_cast<BinOpInit>(NewName))
2196 NewName = BinOp->Fold(&CurRec);
2197 return NewName;
2198}
2199
2200Init *MapResolver::resolve(Init *VarName) {
2201 auto It = Map.find(VarName);
2202 if (It == Map.end())
2203 return nullptr;
2204
2205 Init *I = It->second.V;
2206
2207 if (!It->second.Resolved && Map.size() > 1) {
2208 // Resolve mutual references among the mapped variables, but prevent
2209 // infinite recursion.
2210 Map.erase(It);
2211 I = I->resolveReferences(*this);
2212 Map[VarName] = {I, true};
2213 }
2214
2215 return I;
2216}
2217
2218Init *RecordResolver::resolve(Init *VarName) {
2219 Init *Val = Cache.lookup(VarName);
2220 if (Val)
2221 return Val;
2222
2223 for (Init *S : Stack) {
2224 if (S == VarName)
2225 return nullptr; // prevent infinite recursion
2226 }
2227
2228 if (RecordVal *RV = getCurrentRecord()->getValue(VarName)) {
2229 if (!isa<UnsetInit>(RV->getValue())) {
2230 Val = RV->getValue();
2231 Stack.push_back(VarName);
2232 Val = Val->resolveReferences(*this);
2233 Stack.pop_back();
2234 }
2235 }
2236
2237 Cache[VarName] = Val;
2238 return Val;
2239}
2240
2241Init *TrackUnresolvedResolver::resolve(Init *VarName) {
2242 Init *I = nullptr;
2243
2244 if (R) {
2245 I = R->resolve(VarName);
2246 if (I && !FoundUnresolved) {
2247 // Do not recurse into the resolved initializer, as that would change
2248 // the behavior of the resolver we're delegating, but do check to see
2249 // if there are unresolved variables remaining.
2250 TrackUnresolvedResolver Sub;
2251 I->resolveReferences(Sub);
2252 FoundUnresolved |= Sub.FoundUnresolved;
2253 }
2254 }
2255
2256 if (!I)
2257 FoundUnresolved = true;
2258 return I;
2259}

/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h

1//===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains some templates that are useful if you are working with the
11// STL at all.
12//
13// No library is required when using these functions.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_ADT_STLEXTRAS_H
18#define LLVM_ADT_STLEXTRAS_H
19
20#include "llvm/ADT/Optional.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/iterator.h"
23#include "llvm/ADT/iterator_range.h"
24#include "llvm/Support/ErrorHandling.h"
25#include <algorithm>
26#include <cassert>
27#include <cstddef>
28#include <cstdint>
29#include <cstdlib>
30#include <functional>
31#include <initializer_list>
32#include <iterator>
33#include <limits>
34#include <memory>
35#include <tuple>
36#include <type_traits>
37#include <utility>
38
39#ifdef EXPENSIVE_CHECKS
40#include <random> // for std::mt19937
41#endif
42
43namespace llvm {
44
45// Only used by compiler if both template types are the same. Useful when
46// using SFINAE to test for the existence of member functions.
47template <typename T, T> struct SameType;
48
49namespace detail {
50
51template <typename RangeT>
52using IterOfRange = decltype(std::begin(std::declval<RangeT &>()));
53
54template <typename RangeT>
55using ValueOfRange = typename std::remove_reference<decltype(
56 *std::begin(std::declval<RangeT &>()))>::type;
57
58} // end namespace detail
59
60//===----------------------------------------------------------------------===//
61// Extra additions to <functional>
62//===----------------------------------------------------------------------===//
63
64template <class Ty> struct identity {
65 using argument_type = Ty;
66
67 Ty &operator()(Ty &self) const {
68 return self;
69 }
70 const Ty &operator()(const Ty &self) const {
71 return self;
72 }
73};
74
75template <class Ty> struct less_ptr {
76 bool operator()(const Ty* left, const Ty* right) const {
77 return *left < *right;
78 }
79};
80
81template <class Ty> struct greater_ptr {
82 bool operator()(const Ty* left, const Ty* right) const {
83 return *right < *left;
84 }
85};
86
87/// An efficient, type-erasing, non-owning reference to a callable. This is
88/// intended for use as the type of a function parameter that is not used
89/// after the function in question returns.
90///
91/// This class does not own the callable, so it is not in general safe to store
92/// a function_ref.
93template<typename Fn> class function_ref;
94
95template<typename Ret, typename ...Params>
96class function_ref<Ret(Params...)> {
97 Ret (*callback)(intptr_t callable, Params ...params) = nullptr;
98 intptr_t callable;
99
100 template<typename Callable>
101 static Ret callback_fn(intptr_t callable, Params ...params) {
102 return (*reinterpret_cast<Callable*>(callable))(
103 std::forward<Params>(params)...);
104 }
105
106public:
107 function_ref() = default;
108 function_ref(std::nullptr_t) {}
109
110 template <typename Callable>
111 function_ref(Callable &&callable,
112 typename std::enable_if<
113 !std::is_same<typename std::remove_reference<Callable>::type,
114 function_ref>::value>::type * = nullptr)
115 : callback(callback_fn<typename std::remove_reference<Callable>::type>),
116 callable(reinterpret_cast<intptr_t>(&callable)) {}
117
118 Ret operator()(Params ...params) const {
119 return callback(callable, std::forward<Params>(params)...);
120 }
121
122 operator bool() const { return callback; }
123};
124
125// deleter - Very very very simple method that is used to invoke operator
126// delete on something. It is used like this:
127//
128// for_each(V.begin(), B.end(), deleter<Interval>);
129template <class T>
130inline void deleter(T *Ptr) {
131 delete Ptr;
132}
133
134//===----------------------------------------------------------------------===//
135// Extra additions to <iterator>
136//===----------------------------------------------------------------------===//
137
138namespace adl_detail {
139
140using std::begin;
141
142template <typename ContainerTy>
143auto adl_begin(ContainerTy &&container)
144 -> decltype(begin(std::forward<ContainerTy>(container))) {
145 return begin(std::forward<ContainerTy>(container));
146}
147
148using std::end;
149
150template <typename ContainerTy>
151auto adl_end(ContainerTy &&container)
152 -> decltype(end(std::forward<ContainerTy>(container))) {
153 return end(std::forward<ContainerTy>(container));
154}
155
156using std::swap;
157
158template <typename T>
159void adl_swap(T &&lhs, T &&rhs) noexcept(noexcept(swap(std::declval<T>(),
160 std::declval<T>()))) {
161 swap(std::forward<T>(lhs), std::forward<T>(rhs));
162}
163
164} // end namespace adl_detail
165
166template <typename ContainerTy>
167auto adl_begin(ContainerTy &&container)
168 -> decltype(adl_detail::adl_begin(std::forward<ContainerTy>(container))) {
169 return adl_detail::adl_begin(std::forward<ContainerTy>(container));
170}
171
172template <typename ContainerTy>
173auto adl_end(ContainerTy &&container)
174 -> decltype(adl_detail::adl_end(std::forward<ContainerTy>(container))) {
175 return adl_detail::adl_end(std::forward<ContainerTy>(container));
176}
177
178template <typename T>
179void adl_swap(T &&lhs, T &&rhs) noexcept(
180 noexcept(adl_detail::adl_swap(std::declval<T>(), std::declval<T>()))) {
181 adl_detail::adl_swap(std::forward<T>(lhs), std::forward<T>(rhs));
182}
183
184// mapped_iterator - This is a simple iterator adapter that causes a function to
185// be applied whenever operator* is invoked on the iterator.
186
187template <typename ItTy, typename FuncTy,
188 typename FuncReturnTy =
189 decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))>
190class mapped_iterator
191 : public iterator_adaptor_base<
192 mapped_iterator<ItTy, FuncTy>, ItTy,
193 typename std::iterator_traits<ItTy>::iterator_category,
194 typename std::remove_reference<FuncReturnTy>::type> {
195public:
196 mapped_iterator(ItTy U, FuncTy F)
197 : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {}
198
199 ItTy getCurrent() { return this->I; }
200
201 FuncReturnTy operator*() { return F(*this->I); }
202
203private:
204 FuncTy F;
205};
206
207// map_iterator - Provide a convenient way to create mapped_iterators, just like
208// make_pair is useful for creating pairs...
209template <class ItTy, class FuncTy>
210inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) {
211 return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F));
212}
213
214/// Helper to determine if type T has a member called rbegin().
215template <typename Ty> class has_rbegin_impl {
216 using yes = char[1];
217 using no = char[2];
218
219 template <typename Inner>
220 static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr);
221
222 template <typename>
223 static no& test(...);
224
225public:
226 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
227};
228
229/// Metafunction to determine if T& or T has a member called rbegin().
230template <typename Ty>
231struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> {
232};
233
234// Returns an iterator_range over the given container which iterates in reverse.
235// Note that the container must have rbegin()/rend() methods for this to work.
236template <typename ContainerTy>
237auto reverse(ContainerTy &&C,
238 typename std::enable_if<has_rbegin<ContainerTy>::value>::type * =
239 nullptr) -> decltype(make_range(C.rbegin(), C.rend())) {
240 return make_range(C.rbegin(), C.rend());
241}
242
243// Returns a std::reverse_iterator wrapped around the given iterator.
244template <typename IteratorTy>
245std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) {
246 return std::reverse_iterator<IteratorTy>(It);
247}
248
249// Returns an iterator_range over the given container which iterates in reverse.
250// Note that the container must have begin()/end() methods which return
251// bidirectional iterators for this to work.
252template <typename ContainerTy>
253auto reverse(
254 ContainerTy &&C,
255 typename std::enable_if<!has_rbegin<ContainerTy>::value>::type * = nullptr)
256 -> decltype(make_range(llvm::make_reverse_iterator(std::end(C)),
257 llvm::make_reverse_iterator(std::begin(C)))) {
258 return make_range(llvm::make_reverse_iterator(std::end(C)),
259 llvm::make_reverse_iterator(std::begin(C)));
260}
261
262/// An iterator adaptor that filters the elements of given inner iterators.
263///
264/// The predicate parameter should be a callable object that accepts the wrapped
265/// iterator's reference type and returns a bool. When incrementing or
266/// decrementing the iterator, it will call the predicate on each element and
267/// skip any where it returns false.
268///
269/// \code
270/// int A[] = { 1, 2, 3, 4 };
271/// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
272/// // R contains { 1, 3 }.
273/// \endcode
274template <typename WrappedIteratorT, typename PredicateT>
275class filter_iterator
276 : public iterator_adaptor_base<
277 filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT,
278 typename std::common_type<
279 std::forward_iterator_tag,
280 typename std::iterator_traits<
281 WrappedIteratorT>::iterator_category>::type> {
282 using BaseT = iterator_adaptor_base<
283 filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT,
284 typename std::common_type<
285 std::forward_iterator_tag,
286 typename std::iterator_traits<WrappedIteratorT>::iterator_category>::
287 type>;
288
289 struct PayloadType {
290 WrappedIteratorT End;
291 PredicateT Pred;
292 };
293
294 Optional<PayloadType> Payload;
295
296 void findNextValid() {
297 assert(Payload && "Payload should be engaged when findNextValid is called")(static_cast <bool> (Payload && "Payload should be engaged when findNextValid is called"
) ? void (0) : __assert_fail ("Payload && \"Payload should be engaged when findNextValid is called\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 297, __extension__ __PRETTY_FUNCTION__))
;
298 while (this->I != Payload->End && !Payload->Pred(*this->I))
299 BaseT::operator++();
300 }
301
302 // Construct the begin iterator. The begin iterator requires to know where end
303 // is, so that it can properly stop when it hits end.
304 filter_iterator(WrappedIteratorT Begin, WrappedIteratorT End, PredicateT Pred)
305 : BaseT(std::move(Begin)),
306 Payload(PayloadType{std::move(End), std::move(Pred)}) {
307 findNextValid();
308 }
309
310 // Construct the end iterator. It's not incrementable, so Payload doesn't
311 // have to be engaged.
312 filter_iterator(WrappedIteratorT End) : BaseT(End) {}
313
314public:
315 using BaseT::operator++;
316
317 filter_iterator &operator++() {
318 BaseT::operator++();
319 findNextValid();
320 return *this;
321 }
322
323 template <typename RT, typename PT>
324 friend iterator_range<filter_iterator<detail::IterOfRange<RT>, PT>>
325 make_filter_range(RT &&, PT);
326};
327
328/// Convenience function that takes a range of elements and a predicate,
329/// and return a new filter_iterator range.
330///
331/// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
332/// lifetime of that temporary is not kept by the returned range object, and the
333/// temporary is going to be dropped on the floor after the make_iterator_range
334/// full expression that contains this function call.
335template <typename RangeT, typename PredicateT>
336iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>>
337make_filter_range(RangeT &&Range, PredicateT Pred) {
338 using FilterIteratorT =
339 filter_iterator<detail::IterOfRange<RangeT>, PredicateT>;
340 return make_range(FilterIteratorT(std::begin(std::forward<RangeT>(Range)),
341 std::end(std::forward<RangeT>(Range)),
342 std::move(Pred)),
343 FilterIteratorT(std::end(std::forward<RangeT>(Range))));
344}
345
346// forward declarations required by zip_shortest/zip_first
347template <typename R, typename UnaryPredicate>
348bool all_of(R &&range, UnaryPredicate P);
349
350template <size_t... I> struct index_sequence;
351
352template <class... Ts> struct index_sequence_for;
353
354namespace detail {
355
356using std::declval;
357
358// We have to alias this since inlining the actual type at the usage site
359// in the parameter list of iterator_facade_base<> below ICEs MSVC 2017.
360template<typename... Iters> struct ZipTupleType {
361 using type = std::tuple<decltype(*declval<Iters>())...>;
362};
363
364template <typename ZipType, typename... Iters>
365using zip_traits = iterator_facade_base<
366 ZipType, typename std::common_type<std::bidirectional_iterator_tag,
367 typename std::iterator_traits<
368 Iters>::iterator_category...>::type,
369 // ^ TODO: Implement random access methods.
370 typename ZipTupleType<Iters...>::type,
371 typename std::iterator_traits<typename std::tuple_element<
372 0, std::tuple<Iters...>>::type>::difference_type,
373 // ^ FIXME: This follows boost::make_zip_iterator's assumption that all
374 // inner iterators have the same difference_type. It would fail if, for
375 // instance, the second field's difference_type were non-numeric while the
376 // first is.
377 typename ZipTupleType<Iters...>::type *,
378 typename ZipTupleType<Iters...>::type>;
379
380template <typename ZipType, typename... Iters>
381struct zip_common : public zip_traits<ZipType, Iters...> {
382 using Base = zip_traits<ZipType, Iters...>;
383 using value_type = typename Base::value_type;
384
385 std::tuple<Iters...> iterators;
386
387protected:
388 template <size_t... Ns> value_type deref(index_sequence<Ns...>) const {
389 return value_type(*std::get<Ns>(iterators)...);
390 }
391
392 template <size_t... Ns>
393 decltype(iterators) tup_inc(index_sequence<Ns...>) const {
394 return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...);
395 }
396
397 template <size_t... Ns>
398 decltype(iterators) tup_dec(index_sequence<Ns...>) const {
399 return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...);
400 }
401
402public:
403 zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
404
405 value_type operator*() { return deref(index_sequence_for<Iters...>{}); }
406
407 const value_type operator*() const {
408 return deref(index_sequence_for<Iters...>{});
409 }
410
411 ZipType &operator++() {
412 iterators = tup_inc(index_sequence_for<Iters...>{});
413 return *reinterpret_cast<ZipType *>(this);
414 }
415
416 ZipType &operator--() {
417 static_assert(Base::IsBidirectional,
418 "All inner iterators must be at least bidirectional.");
419 iterators = tup_dec(index_sequence_for<Iters...>{});
420 return *reinterpret_cast<ZipType *>(this);
421 }
422};
423
424template <typename... Iters>
425struct zip_first : public zip_common<zip_first<Iters...>, Iters...> {
426 using Base = zip_common<zip_first<Iters...>, Iters...>;
427
428 bool operator==(const zip_first<Iters...> &other) const {
429 return std::get<0>(this->iterators) == std::get<0>(other.iterators);
430 }
431
432 zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
433};
434
435template <typename... Iters>
436class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> {
437 template <size_t... Ns>
438 bool test(const zip_shortest<Iters...> &other, index_sequence<Ns...>) const {
439 return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
440 std::get<Ns>(other.iterators)...},
441 identity<bool>{});
442 }
443
444public:
445 using Base = zip_common<zip_shortest<Iters...>, Iters...>;
446
447 zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
448
449 bool operator==(const zip_shortest<Iters...> &other) const {
450 return !test(other, index_sequence_for<Iters...>{});
451 }
452};
453
454template <template <typename...> class ItType, typename... Args> class zippy {
455public:
456 using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>;
457 using iterator_category = typename iterator::iterator_category;
458 using value_type = typename iterator::value_type;
459 using difference_type = typename iterator::difference_type;
460 using pointer = typename iterator::pointer;
461 using reference = typename iterator::reference;
462
463private:
464 std::tuple<Args...> ts;
465
466 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) const {
467 return iterator(std::begin(std::get<Ns>(ts))...);
468 }
469 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) const {
470 return iterator(std::end(std::get<Ns>(ts))...);
471 }
472
473public:
474 zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
475
476 iterator begin() const { return begin_impl(index_sequence_for<Args...>{}); }
477 iterator end() const { return end_impl(index_sequence_for<Args...>{}); }
478};
479
480} // end namespace detail
481
482/// zip iterator for two or more iteratable types.
483template <typename T, typename U, typename... Args>
484detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u,
485 Args &&... args) {
486 return detail::zippy<detail::zip_shortest, T, U, Args...>(
487 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
488}
489
490/// zip iterator that, for the sake of efficiency, assumes the first iteratee to
491/// be the shortest.
492template <typename T, typename U, typename... Args>
493detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u,
494 Args &&... args) {
495 return detail::zippy<detail::zip_first, T, U, Args...>(
496 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
497}
498
499/// Iterator wrapper that concatenates sequences together.
500///
501/// This can concatenate different iterators, even with different types, into
502/// a single iterator provided the value types of all the concatenated
503/// iterators expose `reference` and `pointer` types that can be converted to
504/// `ValueT &` and `ValueT *` respectively. It doesn't support more
505/// interesting/customized pointer or reference types.
506///
507/// Currently this only supports forward or higher iterator categories as
508/// inputs and always exposes a forward iterator interface.
509template <typename ValueT, typename... IterTs>
510class concat_iterator
511 : public iterator_facade_base<concat_iterator<ValueT, IterTs...>,
512 std::forward_iterator_tag, ValueT> {
513 using BaseT = typename concat_iterator::iterator_facade_base;
514
515 /// We store both the current and end iterators for each concatenated
516 /// sequence in a tuple of pairs.
517 ///
518 /// Note that something like iterator_range seems nice at first here, but the
519 /// range properties are of little benefit and end up getting in the way
520 /// because we need to do mutation on the current iterators.
521 std::tuple<std::pair<IterTs, IterTs>...> IterPairs;
522
523 /// Attempts to increment a specific iterator.
524 ///
525 /// Returns true if it was able to increment the iterator. Returns false if
526 /// the iterator is already at the end iterator.
527 template <size_t Index> bool incrementHelper() {
528 auto &IterPair = std::get<Index>(IterPairs);
529 if (IterPair.first == IterPair.second)
530 return false;
531
532 ++IterPair.first;
533 return true;
534 }
535
536 /// Increments the first non-end iterator.
537 ///
538 /// It is an error to call this with all iterators at the end.
539 template <size_t... Ns> void increment(index_sequence<Ns...>) {
540 // Build a sequence of functions to increment each iterator if possible.
541 bool (concat_iterator::*IncrementHelperFns[])() = {
542 &concat_iterator::incrementHelper<Ns>...};
543
544 // Loop over them, and stop as soon as we succeed at incrementing one.
545 for (auto &IncrementHelperFn : IncrementHelperFns)
546 if ((this->*IncrementHelperFn)())
547 return;
548
549 llvm_unreachable("Attempted to increment an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to increment an end concat iterator!"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 549)
;
550 }
551
552 /// Returns null if the specified iterator is at the end. Otherwise,
553 /// dereferences the iterator and returns the address of the resulting
554 /// reference.
555 template <size_t Index> ValueT *getHelper() const {
556 auto &IterPair = std::get<Index>(IterPairs);
557 if (IterPair.first == IterPair.second)
558 return nullptr;
559
560 return &*IterPair.first;
561 }
562
563 /// Finds the first non-end iterator, dereferences, and returns the resulting
564 /// reference.
565 ///
566 /// It is an error to call this with all iterators at the end.
567 template <size_t... Ns> ValueT &get(index_sequence<Ns...>) const {
568 // Build a sequence of functions to get from iterator if possible.
569 ValueT *(concat_iterator::*GetHelperFns[])() const = {
570 &concat_iterator::getHelper<Ns>...};
571
572 // Loop over them, and return the first result we find.
573 for (auto &GetHelperFn : GetHelperFns)
574 if (ValueT *P = (this->*GetHelperFn)())
575 return *P;
576
577 llvm_unreachable("Attempted to get a pointer from an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to get a pointer from an end concat iterator!"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 577)
;
578 }
579
580public:
581 /// Constructs an iterator from a squence of ranges.
582 ///
583 /// We need the full range to know how to switch between each of the
584 /// iterators.
585 template <typename... RangeTs>
586 explicit concat_iterator(RangeTs &&... Ranges)
587 : IterPairs({std::begin(Ranges), std::end(Ranges)}...) {}
588
589 using BaseT::operator++;
590
591 concat_iterator &operator++() {
592 increment(index_sequence_for<IterTs...>());
593 return *this;
594 }
595
596 ValueT &operator*() const { return get(index_sequence_for<IterTs...>()); }
597
598 bool operator==(const concat_iterator &RHS) const {
599 return IterPairs == RHS.IterPairs;
600 }
601};
602
603namespace detail {
604
605/// Helper to store a sequence of ranges being concatenated and access them.
606///
607/// This is designed to facilitate providing actual storage when temporaries
608/// are passed into the constructor such that we can use it as part of range
609/// based for loops.
610template <typename ValueT, typename... RangeTs> class concat_range {
611public:
612 using iterator =
613 concat_iterator<ValueT,
614 decltype(std::begin(std::declval<RangeTs &>()))...>;
615
616private:
617 std::tuple<RangeTs...> Ranges;
618
619 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) {
620 return iterator(std::get<Ns>(Ranges)...);
621 }
622 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) {
623 return iterator(make_range(std::end(std::get<Ns>(Ranges)),
624 std::end(std::get<Ns>(Ranges)))...);
625 }
626
627public:
628 concat_range(RangeTs &&... Ranges)
629 : Ranges(std::forward<RangeTs>(Ranges)...) {}
630
631 iterator begin() { return begin_impl(index_sequence_for<RangeTs...>{}); }
632 iterator end() { return end_impl(index_sequence_for<RangeTs...>{}); }
633};
634
635} // end namespace detail
636
637/// Concatenated range across two or more ranges.
638///
639/// The desired value type must be explicitly specified.
640template <typename ValueT, typename... RangeTs>
641detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) {
642 static_assert(sizeof...(RangeTs) > 1,
643 "Need more than one range to concatenate!");
644 return detail::concat_range<ValueT, RangeTs...>(
645 std::forward<RangeTs>(Ranges)...);
646}
647
648//===----------------------------------------------------------------------===//
649// Extra additions to <utility>
650//===----------------------------------------------------------------------===//
651
652/// \brief Function object to check whether the first component of a std::pair
653/// compares less than the first component of another std::pair.
654struct less_first {
655 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
656 return lhs.first < rhs.first;
657 }
658};
659
660/// \brief Function object to check whether the second component of a std::pair
661/// compares less than the second component of another std::pair.
662struct less_second {
663 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
664 return lhs.second < rhs.second;
665 }
666};
667
668// A subset of N3658. More stuff can be added as-needed.
669
670/// \brief Represents a compile-time sequence of integers.
671template <class T, T... I> struct integer_sequence {
672 using value_type = T;
673
674 static constexpr size_t size() { return sizeof...(I); }
675};
676
677/// \brief Alias for the common case of a sequence of size_ts.
678template <size_t... I>
679struct index_sequence : integer_sequence<std::size_t, I...> {};
680
681template <std::size_t N, std::size_t... I>
682struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {};
683template <std::size_t... I>
684struct build_index_impl<0, I...> : index_sequence<I...> {};
685
686/// \brief Creates a compile-time integer sequence for a parameter pack.
687template <class... Ts>
688struct index_sequence_for : build_index_impl<sizeof...(Ts)> {};
689
690/// Utility type to build an inheritance chain that makes it easy to rank
691/// overload candidates.
692template <int N> struct rank : rank<N - 1> {};
693template <> struct rank<0> {};
694
695/// \brief traits class for checking whether type T is one of any of the given
696/// types in the variadic list.
697template <typename T, typename... Ts> struct is_one_of {
698 static const bool value = false;
699};
700
701template <typename T, typename U, typename... Ts>
702struct is_one_of<T, U, Ts...> {
703 static const bool value =
704 std::is_same<T, U>::value || is_one_of<T, Ts...>::value;
705};
706
707/// \brief traits class for checking whether type T is a base class for all
708/// the given types in the variadic list.
709template <typename T, typename... Ts> struct are_base_of {
710 static const bool value = true;
711};
712
713template <typename T, typename U, typename... Ts>
714struct are_base_of<T, U, Ts...> {
715 static const bool value =
716 std::is_base_of<T, U>::value && are_base_of<T, Ts...>::value;
717};
718
719//===----------------------------------------------------------------------===//
720// Extra additions for arrays
721//===----------------------------------------------------------------------===//
722
723/// Find the length of an array.
724template <class T, std::size_t N>
725constexpr inline size_t array_lengthof(T (&)[N]) {
726 return N;
727}
728
729/// Adapt std::less<T> for array_pod_sort.
730template<typename T>
731inline int array_pod_sort_comparator(const void *P1, const void *P2) {
732 if (std::less<T>()(*reinterpret_cast<const T*>(P1),
733 *reinterpret_cast<const T*>(P2)))
734 return -1;
735 if (std::less<T>()(*reinterpret_cast<const T*>(P2),
736 *reinterpret_cast<const T*>(P1)))
737 return 1;
738 return 0;
739}
740
741/// get_array_pod_sort_comparator - This is an internal helper function used to
742/// get type deduction of T right.
743template<typename T>
744inline int (*get_array_pod_sort_comparator(const T &))
745 (const void*, const void*) {
746 return array_pod_sort_comparator<T>;
747}
748
749/// array_pod_sort - This sorts an array with the specified start and end
750/// extent. This is just like std::sort, except that it calls qsort instead of
751/// using an inlined template. qsort is slightly slower than std::sort, but
752/// most sorts are not performance critical in LLVM and std::sort has to be
753/// template instantiated for each type, leading to significant measured code
754/// bloat. This function should generally be used instead of std::sort where
755/// possible.
756///
757/// This function assumes that you have simple POD-like types that can be
758/// compared with std::less and can be moved with memcpy. If this isn't true,
759/// you should use std::sort.
760///
761/// NOTE: If qsort_r were portable, we could allow a custom comparator and
762/// default to std::less.
763template<class IteratorTy>
764inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
765 // Don't inefficiently call qsort with one element or trigger undefined
766 // behavior with an empty sequence.
767 auto NElts = End - Start;
768 if (NElts <= 1) return;
769#ifdef EXPENSIVE_CHECKS
770 std::mt19937 Generator(std::random_device{}());
771 std::shuffle(Start, End, Generator);
772#endif
773 qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
774}
775
776template <class IteratorTy>
777inline void array_pod_sort(
778 IteratorTy Start, IteratorTy End,
779 int (*Compare)(
780 const typename std::iterator_traits<IteratorTy>::value_type *,
781 const typename std::iterator_traits<IteratorTy>::value_type *)) {
782 // Don't inefficiently call qsort with one element or trigger undefined
783 // behavior with an empty sequence.
784 auto NElts = End - Start;
785 if (NElts <= 1) return;
786#ifdef EXPENSIVE_CHECKS
787 std::mt19937 Generator(std::random_device{}());
788 std::shuffle(Start, End, Generator);
789#endif
790 qsort(&*Start, NElts, sizeof(*Start),
791 reinterpret_cast<int (*)(const void *, const void *)>(Compare));
792}
793
794// Provide wrappers to std::sort which shuffle the elements before sorting
795// to help uncover non-deterministic behavior (PR35135).
796template <typename IteratorTy>
797inline void sort(IteratorTy Start, IteratorTy End) {
798#ifdef EXPENSIVE_CHECKS
799 std::mt19937 Generator(std::random_device{}());
800 std::shuffle(Start, End, Generator);
801#endif
802 std::sort(Start, End);
803}
804
805template <typename IteratorTy, typename Compare>
806inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) {
807#ifdef EXPENSIVE_CHECKS
808 std::mt19937 Generator(std::random_device{}());
809 std::shuffle(Start, End, Generator);
810#endif
811 std::sort(Start, End, Comp);
812}
813
814//===----------------------------------------------------------------------===//
815// Extra additions to <algorithm>
816//===----------------------------------------------------------------------===//
817
818/// For a container of pointers, deletes the pointers and then clears the
819/// container.
820template<typename Container>
821void DeleteContainerPointers(Container &C) {
822 for (auto V : C)
823 delete V;
824 C.clear();
825}
826
827/// In a container of pairs (usually a map) whose second element is a pointer,
828/// deletes the second elements and then clears the container.
829template<typename Container>
830void DeleteContainerSeconds(Container &C) {
831 for (auto &V : C)
832 delete V.second;
833 C.clear();
834}
835
836/// Provide wrappers to std::for_each which take ranges instead of having to
837/// pass begin/end explicitly.
838template <typename R, typename UnaryPredicate>
839UnaryPredicate for_each(R &&Range, UnaryPredicate P) {
840 return std::for_each(adl_begin(Range), adl_end(Range), P);
841}
842
843/// Provide wrappers to std::all_of which take ranges instead of having to pass
844/// begin/end explicitly.
845template <typename R, typename UnaryPredicate>
846bool all_of(R &&Range, UnaryPredicate P) {
847 return std::all_of(adl_begin(Range), adl_end(Range), P);
848}
849
850/// Provide wrappers to std::any_of which take ranges instead of having to pass
851/// begin/end explicitly.
852template <typename R, typename UnaryPredicate>
853bool any_of(R &&Range, UnaryPredicate P) {
854 return std::any_of(adl_begin(Range), adl_end(Range), P);
855}
856
857/// Provide wrappers to std::none_of which take ranges instead of having to pass
858/// begin/end explicitly.
859template <typename R, typename UnaryPredicate>
860bool none_of(R &&Range, UnaryPredicate P) {
861 return std::none_of(adl_begin(Range), adl_end(Range), P);
862}
863
864/// Provide wrappers to std::find which take ranges instead of having to pass
865/// begin/end explicitly.
866template <typename R, typename T>
867auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range)) {
868 return std::find(adl_begin(Range), adl_end(Range), Val);
869}
870
871/// Provide wrappers to std::find_if which take ranges instead of having to pass
872/// begin/end explicitly.
873template <typename R, typename UnaryPredicate>
874auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
875 return std::find_if(adl_begin(Range), adl_end(Range), P);
876}
877
878template <typename R, typename UnaryPredicate>
879auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
880 return std::find_if_not(adl_begin(Range), adl_end(Range), P);
881}
882
883/// Provide wrappers to std::remove_if which take ranges instead of having to
884/// pass begin/end explicitly.
885template <typename R, typename UnaryPredicate>
886auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
887 return std::remove_if(adl_begin(Range), adl_end(Range), P);
888}
889
890/// Provide wrappers to std::copy_if which take ranges instead of having to
891/// pass begin/end explicitly.
892template <typename R, typename OutputIt, typename UnaryPredicate>
893OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) {
894 return std::copy_if(adl_begin(Range), adl_end(Range), Out, P);
895}
896
897template <typename R, typename OutputIt>
898OutputIt copy(R &&Range, OutputIt Out) {
899 return std::copy(adl_begin(Range), adl_end(Range), Out);
900}
901
902/// Wrapper function around std::find to detect if an element exists
903/// in a container.
904template <typename R, typename E>
905bool is_contained(R &&Range, const E &Element) {
906 return std::find(adl_begin(Range), adl_end(Range), Element) != adl_end(Range);
907}
908
909/// Wrapper function around std::count to count the number of times an element
910/// \p Element occurs in the given range \p Range.
911template <typename R, typename E>
912auto count(R &&Range, const E &Element) ->
913 typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
914 return std::count(adl_begin(Range), adl_end(Range), Element);
915}
916
917/// Wrapper function around std::count_if to count the number of times an
918/// element satisfying a given predicate occurs in a range.
919template <typename R, typename UnaryPredicate>
920auto count_if(R &&Range, UnaryPredicate P) ->
921 typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
922 return std::count_if(adl_begin(Range), adl_end(Range), P);
923}
924
925/// Wrapper function around std::transform to apply a function to a range and
926/// store the result elsewhere.
927template <typename R, typename OutputIt, typename UnaryPredicate>
928OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P) {
929 return std::transform(adl_begin(Range), adl_end(Range), d_first, P);
930}
931
932/// Provide wrappers to std::partition which take ranges instead of having to
933/// pass begin/end explicitly.
934template <typename R, typename UnaryPredicate>
935auto partition(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
936 return std::partition(adl_begin(Range), adl_end(Range), P);
937}
938
939/// Provide wrappers to std::lower_bound which take ranges instead of having to
940/// pass begin/end explicitly.
941template <typename R, typename ForwardIt>
942auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range)) {
943 return std::lower_bound(adl_begin(Range), adl_end(Range), I);
944}
945
946/// \brief Given a range of type R, iterate the entire range and return a
947/// SmallVector with elements of the vector. This is useful, for example,
948/// when you want to iterate a range and then sort the results.
949template <unsigned Size, typename R>
950SmallVector<typename std::remove_const<detail::ValueOfRange<R>>::type, Size>
951to_vector(R &&Range) {
952 return {adl_begin(Range), adl_end(Range)};
953}
954
955/// Provide a container algorithm similar to C++ Library Fundamentals v2's
956/// `erase_if` which is equivalent to:
957///
958/// C.erase(remove_if(C, pred), C.end());
959///
960/// This version works for any container with an erase method call accepting
961/// two iterators.
962template <typename Container, typename UnaryPredicate>
963void erase_if(Container &C, UnaryPredicate P) {
964 C.erase(remove_if(C, P), C.end());
965}
966
967//===----------------------------------------------------------------------===//
968// Extra additions to <memory>
969//===----------------------------------------------------------------------===//
970
971// Implement make_unique according to N3656.
972
973/// \brief Constructs a `new T()` with the given args and returns a
974/// `unique_ptr<T>` which owns the object.
975///
976/// Example:
977///
978/// auto p = make_unique<int>();
979/// auto p = make_unique<std::tuple<int, int>>(0, 1);
980template <class T, class... Args>
981typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
982make_unique(Args &&... args) {
983 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
9
Memory is allocated
984}
985
986/// \brief Constructs a `new T[n]` with the given args and returns a
987/// `unique_ptr<T[]>` which owns the object.
988///
989/// \param n size of the new array.
990///
991/// Example:
992///
993/// auto p = make_unique<int[]>(2); // value-initializes the array with 0's.
994template <class T>
995typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0,
996 std::unique_ptr<T>>::type
997make_unique(size_t n) {
998 return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
999}
1000
1001/// This function isn't used and is only here to provide better compile errors.
1002template <class T, class... Args>
1003typename std::enable_if<std::extent<T>::value != 0>::type
1004make_unique(Args &&...) = delete;
1005
1006struct FreeDeleter {
1007 void operator()(void* v) {
1008 ::free(v);
1009 }
1010};
1011
1012template<typename First, typename Second>
1013struct pair_hash {
1014 size_t operator()(const std::pair<First, Second> &P) const {
1015 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
1016 }
1017};
1018
1019/// A functor like C++14's std::less<void> in its absence.
1020struct less {
1021 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
1022 return std::forward<A>(a) < std::forward<B>(b);
1023 }
1024};
1025
1026/// A functor like C++14's std::equal<void> in its absence.
1027struct equal {
1028 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
1029 return std::forward<A>(a) == std::forward<B>(b);
1030 }
1031};
1032
1033/// Binary functor that adapts to any other binary functor after dereferencing
1034/// operands.
1035template <typename T> struct deref {
1036 T func;
1037
1038 // Could be further improved to cope with non-derivable functors and
1039 // non-binary functors (should be a variadic template member function
1040 // operator()).
1041 template <typename A, typename B>
1042 auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
1043 assert(lhs)(static_cast <bool> (lhs) ? void (0) : __assert_fail ("lhs"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 1043, __extension__ __PRETTY_FUNCTION__))
;
1044 assert(rhs)(static_cast <bool> (rhs) ? void (0) : __assert_fail ("rhs"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 1044, __extension__ __PRETTY_FUNCTION__))
;
1045 return func(*lhs, *rhs);
1046 }
1047};
1048
1049namespace detail {
1050
1051template <typename R> class enumerator_iter;
1052
1053template <typename R> struct result_pair {
1054 friend class enumerator_iter<R>;
1055
1056 result_pair() = default;
1057 result_pair(std::size_t Index, IterOfRange<R> Iter)
1058 : Index(Index), Iter(Iter) {}
1059
1060 result_pair<R> &operator=(const result_pair<R> &Other) {
1061 Index = Other.Index;
1062 Iter = Other.Iter;
1063 return *this;
1064 }
1065
1066 std::size_t index() const { return Index; }
1067 const ValueOfRange<R> &value() const { return *Iter; }
1068 ValueOfRange<R> &value() { return *Iter; }
1069
1070private:
1071 std::size_t Index = std::numeric_limits<std::size_t>::max();
1072 IterOfRange<R> Iter;
1073};
1074
1075template <typename R>
1076class enumerator_iter
1077 : public iterator_facade_base<
1078 enumerator_iter<R>, std::forward_iterator_tag, result_pair<R>,
1079 typename std::iterator_traits<IterOfRange<R>>::difference_type,
1080 typename std::iterator_traits<IterOfRange<R>>::pointer,
1081 typename std::iterator_traits<IterOfRange<R>>::reference> {
1082 using result_type = result_pair<R>;
1083
1084public:
1085 explicit enumerator_iter(IterOfRange<R> EndIter)
1086 : Result(std::numeric_limits<size_t>::max(), EndIter) {}
1087
1088 enumerator_iter(std::size_t Index, IterOfRange<R> Iter)
1089 : Result(Index, Iter) {}
1090
1091 result_type &operator*() { return Result; }
1092 const result_type &operator*() const { return Result; }
1093
1094 enumerator_iter<R> &operator++() {
1095 assert(Result.Index != std::numeric_limits<size_t>::max())(static_cast <bool> (Result.Index != std::numeric_limits
<size_t>::max()) ? void (0) : __assert_fail ("Result.Index != std::numeric_limits<size_t>::max()"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 1095, __extension__ __PRETTY_FUNCTION__))
;
1096 ++Result.Iter;
1097 ++Result.Index;
1098 return *this;
1099 }
1100
1101 bool operator==(const enumerator_iter<R> &RHS) const {
1102 // Don't compare indices here, only iterators. It's possible for an end
1103 // iterator to have different indices depending on whether it was created
1104 // by calling std::end() versus incrementing a valid iterator.
1105 return Result.Iter == RHS.Result.Iter;
1106 }
1107
1108 enumerator_iter<R> &operator=(const enumerator_iter<R> &Other) {
1109 Result = Other.Result;
1110 return *this;
1111 }
1112
1113private:
1114 result_type Result;
1115};
1116
1117template <typename R> class enumerator {
1118public:
1119 explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {}
1120
1121 enumerator_iter<R> begin() {
1122 return enumerator_iter<R>(0, std::begin(TheRange));
1123 }
1124
1125 enumerator_iter<R> end() {
1126 return enumerator_iter<R>(std::end(TheRange));
1127 }
1128
1129private:
1130 R TheRange;
1131};
1132
1133} // end namespace detail
1134
1135/// Given an input range, returns a new range whose values are are pair (A,B)
1136/// such that A is the 0-based index of the item in the sequence, and B is
1137/// the value from the original sequence. Example:
1138///
1139/// std::vector<char> Items = {'A', 'B', 'C', 'D'};
1140/// for (auto X : enumerate(Items)) {
1141/// printf("Item %d - %c\n", X.index(), X.value());
1142/// }
1143///
1144/// Output:
1145/// Item 0 - A
1146/// Item 1 - B
1147/// Item 2 - C
1148/// Item 3 - D
1149///
1150template <typename R> detail::enumerator<R> enumerate(R &&TheRange) {
1151 return detail::enumerator<R>(std::forward<R>(TheRange));
1152}
1153
1154namespace detail {
1155
1156template <typename F, typename Tuple, std::size_t... I>
1157auto apply_tuple_impl(F &&f, Tuple &&t, index_sequence<I...>)
1158 -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...)) {
1159 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
1160}
1161
1162} // end namespace detail
1163
1164/// Given an input tuple (a1, a2, ..., an), pass the arguments of the
1165/// tuple variadically to f as if by calling f(a1, a2, ..., an) and
1166/// return the result.
1167template <typename F, typename Tuple>
1168auto apply_tuple(F &&f, Tuple &&t) -> decltype(detail::apply_tuple_impl(
1169 std::forward<F>(f), std::forward<Tuple>(t),
1170 build_index_impl<
1171 std::tuple_size<typename std::decay<Tuple>::type>::value>{})) {
1172 using Indices = build_index_impl<
1173 std::tuple_size<typename std::decay<Tuple>::type>::value>;
1174
1175 return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t),
1176 Indices{});
1177}
1178
1179} // end namespace llvm
1180
1181#endif // LLVM_ADT_STLEXTRAS_H

/usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/bits/unique_ptr.h

1// unique_ptr implementation -*- C++ -*-
2
3// Copyright (C) 2008-2017 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/** @file bits/unique_ptr.h
26 * This is an internal header file, included by other library headers.
27 * Do not attempt to use it directly. @headername{memory}
28 */
29
30#ifndef _UNIQUE_PTR_H1
31#define _UNIQUE_PTR_H1 1
32
33#include <bits/c++config.h>
34#include <debug/assertions.h>
35#include <type_traits>
36#include <utility>
37#include <tuple>
38#include <bits/stl_function.h>
39#include <bits/functional_hash.h>
40
41namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
42{
43_GLIBCXX_BEGIN_NAMESPACE_VERSION
44
45 /**
46 * @addtogroup pointer_abstractions
47 * @{
48 */
49
50#if _GLIBCXX_USE_DEPRECATED1
51 template<typename> class auto_ptr;
52#endif
53
54 /// Primary template of default_delete, used by unique_ptr
55 template<typename _Tp>
56 struct default_delete
57 {
58 /// Default constructor
59 constexpr default_delete() noexcept = default;
60
61 /** @brief Converting constructor.
62 *
63 * Allows conversion from a deleter for arrays of another type, @p _Up,
64 * only if @p _Up* is convertible to @p _Tp*.
65 */
66 template<typename _Up, typename = typename
67 enable_if<is_convertible<_Up*, _Tp*>::value>::type>
68 default_delete(const default_delete<_Up>&) noexcept { }
69
70 /// Calls @c delete @p __ptr
71 void
72 operator()(_Tp* __ptr) const
73 {
74 static_assert(!is_void<_Tp>::value,
75 "can't delete pointer to incomplete type");
76 static_assert(sizeof(_Tp)>0,
77 "can't delete pointer to incomplete type");
78 delete __ptr;
18
Memory is released
79 }
80 };
81
82 // _GLIBCXX_RESOLVE_LIB_DEFECTS
83 // DR 740 - omit specialization for array objects with a compile time length
84 /// Specialization for arrays, default_delete.
85 template<typename _Tp>
86 struct default_delete<_Tp[]>
87 {
88 public:
89 /// Default constructor
90 constexpr default_delete() noexcept = default;
91
92 /** @brief Converting constructor.
93 *
94 * Allows conversion from a deleter for arrays of another type, such as
95 * a const-qualified version of @p _Tp.
96 *
97 * Conversions from types derived from @c _Tp are not allowed because
98 * it is unsafe to @c delete[] an array of derived types through a
99 * pointer to the base type.
100 */
101 template<typename _Up, typename = typename
102 enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value>::type>
103 default_delete(const default_delete<_Up[]>&) noexcept { }
104
105 /// Calls @c delete[] @p __ptr
106 template<typename _Up>
107 typename enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value>::type
108 operator()(_Up* __ptr) const
109 {
110 static_assert(sizeof(_Tp)>0,
111 "can't delete pointer to incomplete type");
112 delete [] __ptr;
113 }
114 };
115
116 template <typename _Tp, typename _Dp>
117 class __uniq_ptr_impl
118 {
119 template <typename _Up, typename _Ep, typename = void>
120 struct _Ptr
121 {
122 using type = _Up*;
123 };
124
125 template <typename _Up, typename _Ep>
126 struct
127 _Ptr<_Up, _Ep, __void_t<typename remove_reference<_Ep>::type::pointer>>
128 {
129 using type = typename remove_reference<_Ep>::type::pointer;
130 };
131
132 public:
133 using _DeleterConstraint = enable_if<
134 __and_<__not_<is_pointer<_Dp>>,
135 is_default_constructible<_Dp>>::value>;
136
137 using pointer = typename _Ptr<_Tp, _Dp>::type;
138
139 __uniq_ptr_impl() = default;
140 __uniq_ptr_impl(pointer __p) : _M_t() { _M_ptr() = __p; }
141
142 template<typename _Del>
143 __uniq_ptr_impl(pointer __p, _Del&& __d)
144 : _M_t(__p, std::forward<_Del>(__d)) { }
145
146 pointer& _M_ptr() { return std::get<0>(_M_t); }
147 pointer _M_ptr() const { return std::get<0>(_M_t); }
148 _Dp& _M_deleter() { return std::get<1>(_M_t); }
149 const _Dp& _M_deleter() const { return std::get<1>(_M_t); }
150
151 private:
152 tuple<pointer, _Dp> _M_t;
153 };
154
155 /// 20.7.1.2 unique_ptr for single objects.
156 template <typename _Tp, typename _Dp = default_delete<_Tp>>
157 class unique_ptr
158 {
159 template <class _Up>
160 using _DeleterConstraint =
161 typename __uniq_ptr_impl<_Tp, _Up>::_DeleterConstraint::type;
162
163 __uniq_ptr_impl<_Tp, _Dp> _M_t;
164
165 public:
166 using pointer = typename __uniq_ptr_impl<_Tp, _Dp>::pointer;
167 using element_type = _Tp;
168 using deleter_type = _Dp;
169
170 // helper template for detecting a safe conversion from another
171 // unique_ptr
172 template<typename _Up, typename _Ep>
173 using __safe_conversion_up = __and_<
174 is_convertible<typename unique_ptr<_Up, _Ep>::pointer, pointer>,
175 __not_<is_array<_Up>>,
176 __or_<__and_<is_reference<deleter_type>,
177 is_same<deleter_type, _Ep>>,
178 __and_<__not_<is_reference<deleter_type>>,
179 is_convertible<_Ep, deleter_type>>
180 >
181 >;
182
183 // Constructors.
184
185 /// Default constructor, creates a unique_ptr that owns nothing.
186 template <typename _Up = _Dp,
187 typename = _DeleterConstraint<_Up>>
188 constexpr unique_ptr() noexcept
189 : _M_t()
190 { }
191
192 /** Takes ownership of a pointer.
193 *
194 * @param __p A pointer to an object of @c element_type
195 *
196 * The deleter will be value-initialized.
197 */
198 template <typename _Up = _Dp,
199 typename = _DeleterConstraint<_Up>>
200 explicit
201 unique_ptr(pointer __p) noexcept
202 : _M_t(__p)
203 { }
204
205 /** Takes ownership of a pointer.
206 *
207 * @param __p A pointer to an object of @c element_type
208 * @param __d A reference to a deleter.
209 *
210 * The deleter will be initialized with @p __d
211 */
212 unique_ptr(pointer __p,
213 typename conditional<is_reference<deleter_type>::value,
214 deleter_type, const deleter_type&>::type __d) noexcept
215 : _M_t(__p, __d) { }
216
217 /** Takes ownership of a pointer.
218 *
219 * @param __p A pointer to an object of @c element_type
220 * @param __d An rvalue reference to a deleter.
221 *
222 * The deleter will be initialized with @p std::move(__d)
223 */
224 unique_ptr(pointer __p,
225 typename remove_reference<deleter_type>::type&& __d) noexcept
226 : _M_t(std::move(__p), std::move(__d))
227 { static_assert(!std::is_reference<deleter_type>::value,
228 "rvalue deleter bound to reference"); }
229
230 /// Creates a unique_ptr that owns nothing.
231 template <typename _Up = _Dp,
232 typename = _DeleterConstraint<_Up>>
233 constexpr unique_ptr(nullptr_t) noexcept : unique_ptr() { }
234
235 // Move constructors.
236
237 /// Move constructor.
238 unique_ptr(unique_ptr&& __u) noexcept
239 : _M_t(__u.release(), std::forward<deleter_type>(__u.get_deleter())) { }
240
241 /** @brief Converting constructor from another type
242 *
243 * Requires that the pointer owned by @p __u is convertible to the
244 * type of pointer owned by this object, @p __u does not own an array,
245 * and @p __u has a compatible deleter type.
246 */
247 template<typename _Up, typename _Ep, typename = _Require<
248 __safe_conversion_up<_Up, _Ep>,
249 typename conditional<is_reference<_Dp>::value,
250 is_same<_Ep, _Dp>,
251 is_convertible<_Ep, _Dp>>::type>>
252 unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept
253 : _M_t(__u.release(), std::forward<_Ep>(__u.get_deleter()))
254 { }
255
256#if _GLIBCXX_USE_DEPRECATED1
257 /// Converting constructor from @c auto_ptr
258 template<typename _Up, typename = _Require<
259 is_convertible<_Up*, _Tp*>, is_same<_Dp, default_delete<_Tp>>>>
260 unique_ptr(auto_ptr<_Up>&& __u) noexcept;
261#endif
262
263 /// Destructor, invokes the deleter if the stored pointer is not null.
264 ~unique_ptr() noexcept
265 {
266 auto& __ptr = _M_t._M_ptr();
267 if (__ptr != nullptr)
16
Taking true branch
268 get_deleter()(__ptr);
17
Calling 'default_delete::operator()'
19
Returning; memory was released via 2nd parameter
269 __ptr = pointer();
270 }
271
272 // Assignment.
273
274 /** @brief Move assignment operator.
275 *
276 * @param __u The object to transfer ownership from.
277 *
278 * Invokes the deleter first if this object owns a pointer.
279 */
280 unique_ptr&
281 operator=(unique_ptr&& __u) noexcept
282 {
283 reset(__u.release());
284 get_deleter() = std::forward<deleter_type>(__u.get_deleter());
285 return *this;
286 }
287
288 /** @brief Assignment from another type.
289 *
290 * @param __u The object to transfer ownership from, which owns a
291 * convertible pointer to a non-array object.
292 *
293 * Invokes the deleter first if this object owns a pointer.
294 */
295 template<typename _Up, typename _Ep>
296 typename enable_if< __and_<
297 __safe_conversion_up<_Up, _Ep>,
298 is_assignable<deleter_type&, _Ep&&>
299 >::value,
300 unique_ptr&>::type
301 operator=(unique_ptr<_Up, _Ep>&& __u) noexcept
302 {
303 reset(__u.release());
304 get_deleter() = std::forward<_Ep>(__u.get_deleter());
305 return *this;
306 }
307
308 /// Reset the %unique_ptr to empty, invoking the deleter if necessary.
309 unique_ptr&
310 operator=(nullptr_t) noexcept
311 {
312 reset();
313 return *this;
314 }
315
316 // Observers.
317
318 /// Dereference the stored pointer.
319 typename add_lvalue_reference<element_type>::type
320 operator*() const
321 {
322 __glibcxx_assert(get() != pointer());
323 return *get();
324 }
325
326 /// Return the stored pointer.
327 pointer
328 operator->() const noexcept
329 {
330 _GLIBCXX_DEBUG_PEDASSERT(get() != pointer());
331 return get();
332 }
333
334 /// Return the stored pointer.
335 pointer
336 get() const noexcept
337 { return _M_t._M_ptr(); }
338
339 /// Return a reference to the stored deleter.
340 deleter_type&
341 get_deleter() noexcept
342 { return _M_t._M_deleter(); }
343
344 /// Return a reference to the stored deleter.
345 const deleter_type&
346 get_deleter() const noexcept
347 { return _M_t._M_deleter(); }
348
349 /// Return @c true if the stored pointer is not null.
350 explicit operator bool() const noexcept
351 { return get() == pointer() ? false : true; }
352
353 // Modifiers.
354
355 /// Release ownership of any stored pointer.
356 pointer
357 release() noexcept
358 {
359 pointer __p = get();
360 _M_t._M_ptr() = pointer();
361 return __p;
362 }
363
364 /** @brief Replace the stored pointer.
365 *
366 * @param __p The new pointer to store.
367 *
368 * The deleter will be invoked if a pointer is already owned.
369 */
370 void
371 reset(pointer __p = pointer()) noexcept
372 {
373 using std::swap;
374 swap(_M_t._M_ptr(), __p);
375 if (__p != pointer())
376 get_deleter()(__p);
377 }
378
379 /// Exchange the pointer and deleter with another object.
380 void
381 swap(unique_ptr& __u) noexcept
382 {
383 using std::swap;
384 swap(_M_t, __u._M_t);
385 }
386
387 // Disable copy from lvalue.
388 unique_ptr(const unique_ptr&) = delete;
389 unique_ptr& operator=(const unique_ptr&) = delete;
390 };
391
392 /// 20.7.1.3 unique_ptr for array objects with a runtime length
393 // [unique.ptr.runtime]
394 // _GLIBCXX_RESOLVE_LIB_DEFECTS
395 // DR 740 - omit specialization for array objects with a compile time length
396 template<typename _Tp, typename _Dp>
397 class unique_ptr<_Tp[], _Dp>
398 {
399 template <typename _Up>
400 using _DeleterConstraint =
401 typename __uniq_ptr_impl<_Tp, _Up>::_DeleterConstraint::type;
402
403 __uniq_ptr_impl<_Tp, _Dp> _M_t;
404
405 template<typename _Up>
406 using __remove_cv = typename remove_cv<_Up>::type;
407
408 // like is_base_of<_Tp, _Up> but false if unqualified types are the same
409 template<typename _Up>
410 using __is_derived_Tp
411 = __and_< is_base_of<_Tp, _Up>,
412 __not_<is_same<__remove_cv<_Tp>, __remove_cv<_Up>>> >;
413
414 public:
415 using pointer = typename __uniq_ptr_impl<_Tp, _Dp>::pointer;
416 using element_type = _Tp;
417 using deleter_type = _Dp;
418
419 // helper template for detecting a safe conversion from another
420 // unique_ptr
421 template<typename _Up, typename _Ep,
422 typename _Up_up = unique_ptr<_Up, _Ep>,
423 typename _Up_element_type = typename _Up_up::element_type>
424 using __safe_conversion_up = __and_<
425 is_array<_Up>,
426 is_same<pointer, element_type*>,
427 is_same<typename _Up_up::pointer, _Up_element_type*>,
428 is_convertible<_Up_element_type(*)[], element_type(*)[]>,
429 __or_<__and_<is_reference<deleter_type>, is_same<deleter_type, _Ep>>,
430 __and_<__not_<is_reference<deleter_type>>,
431 is_convertible<_Ep, deleter_type>>>
432 >;
433
434 // helper template for detecting a safe conversion from a raw pointer
435 template<typename _Up>
436 using __safe_conversion_raw = __and_<
437 __or_<__or_<is_same<_Up, pointer>,
438 is_same<_Up, nullptr_t>>,
439 __and_<is_pointer<_Up>,
440 is_same<pointer, element_type*>,
441 is_convertible<
442 typename remove_pointer<_Up>::type(*)[],
443 element_type(*)[]>
444 >
445 >
446 >;
447
448 // Constructors.
449
450 /// Default constructor, creates a unique_ptr that owns nothing.
451 template <typename _Up = _Dp,
452 typename = _DeleterConstraint<_Up>>
453 constexpr unique_ptr() noexcept
454 : _M_t()
455 { }
456
457 /** Takes ownership of a pointer.
458 *
459 * @param __p A pointer to an array of a type safely convertible
460 * to an array of @c element_type
461 *
462 * The deleter will be value-initialized.
463 */
464 template<typename _Up,
465 typename _Vp = _Dp,
466 typename = _DeleterConstraint<_Vp>,
467 typename = typename enable_if<
468 __safe_conversion_raw<_Up>::value, bool>::type>
469 explicit
470 unique_ptr(_Up __p) noexcept
471 : _M_t(__p)
472 { }
473
474 /** Takes ownership of a pointer.
475 *
476 * @param __p A pointer to an array of a type safely convertible
477 * to an array of @c element_type
478 * @param __d A reference to a deleter.
479 *
480 * The deleter will be initialized with @p __d
481 */
482 template<typename _Up,
483 typename = typename enable_if<
484 __safe_conversion_raw<_Up>::value, bool>::type>
485 unique_ptr(_Up __p,
486 typename conditional<is_reference<deleter_type>::value,
487 deleter_type, const deleter_type&>::type __d) noexcept
488 : _M_t(__p, __d) { }
489
490 /** Takes ownership of a pointer.
491 *
492 * @param __p A pointer to an array of a type safely convertible
493 * to an array of @c element_type
494 * @param __d A reference to a deleter.
495 *
496 * The deleter will be initialized with @p std::move(__d)
497 */
498 template<typename _Up,
499 typename = typename enable_if<
500 __safe_conversion_raw<_Up>::value, bool>::type>
501 unique_ptr(_Up __p, typename
502 remove_reference<deleter_type>::type&& __d) noexcept
503 : _M_t(std::move(__p), std::move(__d))
504 { static_assert(!is_reference<deleter_type>::value,
505 "rvalue deleter bound to reference"); }
506
507 /// Move constructor.
508 unique_ptr(unique_ptr&& __u) noexcept
509 : _M_t(__u.release(), std::forward<deleter_type>(__u.get_deleter())) { }
510
511 /// Creates a unique_ptr that owns nothing.
512 template <typename _Up = _Dp,
513 typename = _DeleterConstraint<_Up>>
514 constexpr unique_ptr(nullptr_t) noexcept : unique_ptr() { }
515
516 template<typename _Up, typename _Ep,
517 typename = _Require<__safe_conversion_up<_Up, _Ep>>>
518 unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept
519 : _M_t(__u.release(), std::forward<_Ep>(__u.get_deleter()))
520 { }
521
522 /// Destructor, invokes the deleter if the stored pointer is not null.
523 ~unique_ptr()
524 {
525 auto& __ptr = _M_t._M_ptr();
526 if (__ptr != nullptr)
527 get_deleter()(__ptr);
528 __ptr = pointer();
529 }
530
531 // Assignment.
532
533 /** @brief Move assignment operator.
534 *
535 * @param __u The object to transfer ownership from.
536 *
537 * Invokes the deleter first if this object owns a pointer.
538 */
539 unique_ptr&
540 operator=(unique_ptr&& __u) noexcept
541 {
542 reset(__u.release());
543 get_deleter() = std::forward<deleter_type>(__u.get_deleter());
544 return *this;
545 }
546
547 /** @brief Assignment from another type.
548 *
549 * @param __u The object to transfer ownership from, which owns a
550 * convertible pointer to an array object.
551 *
552 * Invokes the deleter first if this object owns a pointer.
553 */
554 template<typename _Up, typename _Ep>
555 typename
556 enable_if<__and_<__safe_conversion_up<_Up, _Ep>,
557 is_assignable<deleter_type&, _Ep&&>
558 >::value,
559 unique_ptr&>::type
560 operator=(unique_ptr<_Up, _Ep>&& __u) noexcept
561 {
562 reset(__u.release());
563 get_deleter() = std::forward<_Ep>(__u.get_deleter());
564 return *this;
565 }
566
567 /// Reset the %unique_ptr to empty, invoking the deleter if necessary.
568 unique_ptr&
569 operator=(nullptr_t) noexcept
570 {
571 reset();
572 return *this;
573 }
574
575 // Observers.
576
577 /// Access an element of owned array.
578 typename std::add_lvalue_reference<element_type>::type
579 operator[](size_t __i) const
580 {
581 __glibcxx_assert(get() != pointer());
582 return get()[__i];
583 }
584
585 /// Return the stored pointer.
586 pointer
587 get() const noexcept
588 { return _M_t._M_ptr(); }
589
590 /// Return a reference to the stored deleter.
591 deleter_type&
592 get_deleter() noexcept
593 { return _M_t._M_deleter(); }
594
595 /// Return a reference to the stored deleter.
596 const deleter_type&
597 get_deleter() const noexcept
598 { return _M_t._M_deleter(); }
599
600 /// Return @c true if the stored pointer is not null.
601 explicit operator bool() const noexcept
602 { return get() == pointer() ? false : true; }
603
604 // Modifiers.
605
606 /// Release ownership of any stored pointer.
607 pointer
608 release() noexcept
609 {
610 pointer __p = get();
611 _M_t._M_ptr() = pointer();
612 return __p;
613 }
614
615 /** @brief Replace the stored pointer.
616 *
617 * @param __p The new pointer to store.
618 *
619 * The deleter will be invoked if a pointer is already owned.
620 */
621 template <typename _Up,
622 typename = _Require<
623 __or_<is_same<_Up, pointer>,
624 __and_<is_same<pointer, element_type*>,
625 is_pointer<_Up>,
626 is_convertible<
627 typename remove_pointer<_Up>::type(*)[],
628 element_type(*)[]
629 >
630 >
631 >
632 >>
633 void
634 reset(_Up __p) noexcept
635 {
636 pointer __ptr = __p;
637 using std::swap;
638 swap(_M_t._M_ptr(), __ptr);
639 if (__ptr != nullptr)
640 get_deleter()(__ptr);
641 }
642
643 void reset(nullptr_t = nullptr) noexcept
644 {
645 reset(pointer());
646 }
647
648 /// Exchange the pointer and deleter with another object.
649 void
650 swap(unique_ptr& __u) noexcept
651 {
652 using std::swap;
653 swap(_M_t, __u._M_t);
654 }
655
656 // Disable copy from lvalue.
657 unique_ptr(const unique_ptr&) = delete;
658 unique_ptr& operator=(const unique_ptr&) = delete;
659 };
660
661 template<typename _Tp, typename _Dp>
662 inline
663#if __cplusplus201103L > 201402L || !defined(__STRICT_ANSI__1) // c++1z or gnu++11
664 // Constrained free swap overload, see p0185r1
665 typename enable_if<__is_swappable<_Dp>::value>::type
666#else
667 void
668#endif
669 swap(unique_ptr<_Tp, _Dp>& __x,
670 unique_ptr<_Tp, _Dp>& __y) noexcept
671 { __x.swap(__y); }
672
673#if __cplusplus201103L > 201402L || !defined(__STRICT_ANSI__1) // c++1z or gnu++11
674 template<typename _Tp, typename _Dp>
675 typename enable_if<!__is_swappable<_Dp>::value>::type
676 swap(unique_ptr<_Tp, _Dp>&,
677 unique_ptr<_Tp, _Dp>&) = delete;
678#endif
679
680 template<typename _Tp, typename _Dp,
681 typename _Up, typename _Ep>
682 inline bool
683 operator==(const unique_ptr<_Tp, _Dp>& __x,
684 const unique_ptr<_Up, _Ep>& __y)
685 { return __x.get() == __y.get(); }
686
687 template<typename _Tp, typename _Dp>
688 inline bool
689 operator==(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) noexcept
690 { return !__x; }
691
692 template<typename _Tp, typename _Dp>
693 inline bool
694 operator==(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) noexcept
695 { return !__x; }
696
697 template<typename _Tp, typename _Dp,
698 typename _Up, typename _Ep>
699 inline bool
700 operator!=(const unique_ptr<_Tp, _Dp>& __x,
701 const unique_ptr<_Up, _Ep>& __y)
702 { return __x.get() != __y.get(); }
703
704 template<typename _Tp, typename _Dp>
705 inline bool
706 operator!=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) noexcept
707 { return (bool)__x; }
708
709 template<typename _Tp, typename _Dp>
710 inline bool
711 operator!=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) noexcept
712 { return (bool)__x; }
713
714 template<typename _Tp, typename _Dp,
715 typename _Up, typename _Ep>
716 inline bool
717 operator<(const unique_ptr<_Tp, _Dp>& __x,
718 const unique_ptr<_Up, _Ep>& __y)
719 {
720 typedef typename
721 std::common_type<typename unique_ptr<_Tp, _Dp>::pointer,
722 typename unique_ptr<_Up, _Ep>::pointer>::type _CT;
723 return std::less<_CT>()(__x.get(), __y.get());
724 }
725
726 template<typename _Tp, typename _Dp>
727 inline bool
728 operator<(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
729 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(__x.get(),
730 nullptr); }
731
732 template<typename _Tp, typename _Dp>
733 inline bool
734 operator<(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
735 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(nullptr,
736 __x.get()); }
737
738 template<typename _Tp, typename _Dp,
739 typename _Up, typename _Ep>
740 inline bool
741 operator<=(const unique_ptr<_Tp, _Dp>& __x,
742 const unique_ptr<_Up, _Ep>& __y)
743 { return !(__y < __x); }
744
745 template<typename _Tp, typename _Dp>
746 inline bool
747 operator<=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
748 { return !(nullptr < __x); }
749
750 template<typename _Tp, typename _Dp>
751 inline bool
752 operator<=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
753 { return !(__x < nullptr); }
754
755 template<typename _Tp, typename _Dp,
756 typename _Up, typename _Ep>
757 inline bool
758 operator>(const unique_ptr<_Tp, _Dp>& __x,
759 const unique_ptr<_Up, _Ep>& __y)
760 { return (__y < __x); }
761
762 template<typename _Tp, typename _Dp>
763 inline bool
764 operator>(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
765 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(nullptr,
766 __x.get()); }
767
768 template<typename _Tp, typename _Dp>
769 inline bool
770 operator>(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
771 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(__x.get(),
772 nullptr); }
773
774 template<typename _Tp, typename _Dp,
775 typename _Up, typename _Ep>
776 inline bool
777 operator>=(const unique_ptr<_Tp, _Dp>& __x,
778 const unique_ptr<_Up, _Ep>& __y)
779 { return !(__x < __y); }
780
781 template<typename _Tp, typename _Dp>
782 inline bool
783 operator>=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
784 { return !(__x < nullptr); }
785
786 template<typename _Tp, typename _Dp>
787 inline bool
788 operator>=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
789 { return !(nullptr < __x); }
790
791 /// std::hash specialization for unique_ptr.
792 template<typename _Tp, typename _Dp>
793 struct hash<unique_ptr<_Tp, _Dp>>
794 : public __hash_base<size_t, unique_ptr<_Tp, _Dp>>,
795 private __poison_hash<typename unique_ptr<_Tp, _Dp>::pointer>
796 {
797 size_t
798 operator()(const unique_ptr<_Tp, _Dp>& __u) const noexcept
799 {
800 typedef unique_ptr<_Tp, _Dp> _UP;
801 return std::hash<typename _UP::pointer>()(__u.get());
802 }
803 };
804
805#if __cplusplus201103L > 201103L
806
807#define __cpp_lib_make_unique 201304
808
809 template<typename _Tp>
810 struct _MakeUniq
811 { typedef unique_ptr<_Tp> __single_object; };
812
813 template<typename _Tp>
814 struct _MakeUniq<_Tp[]>
815 { typedef unique_ptr<_Tp[]> __array; };
816
817 template<typename _Tp, size_t _Bound>
818 struct _MakeUniq<_Tp[_Bound]>
819 { struct __invalid_type { }; };
820
821 /// std::make_unique for single objects
822 template<typename _Tp, typename... _Args>
823 inline typename _MakeUniq<_Tp>::__single_object
824 make_unique(_Args&&... __args)
825 { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
826
827 /// std::make_unique for arrays of unknown bound
828 template<typename _Tp>
829 inline typename _MakeUniq<_Tp>::__array
830 make_unique(size_t __num)
831 { return unique_ptr<_Tp>(new remove_extent_t<_Tp>[__num]()); }
832
833 /// Disable std::make_unique for arrays of known bound
834 template<typename _Tp, typename... _Args>
835 inline typename _MakeUniq<_Tp>::__invalid_type
836 make_unique(_Args&&...) = delete;
837#endif
838
839 // @} group pointer_abstractions
840
841_GLIBCXX_END_NAMESPACE_VERSION
842} // namespace
843
844#endif /* _UNIQUE_PTR_H */