Bug Summary

File:llvm/lib/Target/AArch64/AArch64StackTagging.cpp
Warning:line 637, column 11
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name AArch64StackTagging.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/Target/AArch64 -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/AArch64 -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.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++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/Target/AArch64 -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility hidden -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/AArch64/AArch64StackTagging.cpp

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/AArch64/AArch64StackTagging.cpp

1//===- AArch64StackTagging.cpp - Stack tagging in IR --===//
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
11#include "AArch64.h"
12#include "AArch64InstrInfo.h"
13#include "AArch64Subtarget.h"
14#include "AArch64TargetMachine.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/DepthFirstIterator.h"
17#include "llvm/ADT/MapVector.h"
18#include "llvm/ADT/None.h"
19#include "llvm/ADT/Optional.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/Analysis/CFG.h"
23#include "llvm/Analysis/LoopInfo.h"
24#include "llvm/Analysis/ScalarEvolution.h"
25#include "llvm/Analysis/ScalarEvolutionExpressions.h"
26#include "llvm/Analysis/ValueTracking.h"
27#include "llvm/CodeGen/LiveRegUnits.h"
28#include "llvm/CodeGen/MachineBasicBlock.h"
29#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFunctionPass.h"
31#include "llvm/CodeGen/MachineInstr.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
33#include "llvm/CodeGen/MachineLoopInfo.h"
34#include "llvm/CodeGen/MachineOperand.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
36#include "llvm/CodeGen/TargetPassConfig.h"
37#include "llvm/CodeGen/TargetRegisterInfo.h"
38#include "llvm/IR/DebugLoc.h"
39#include "llvm/IR/Dominators.h"
40#include "llvm/IR/Function.h"
41#include "llvm/IR/GetElementPtrTypeIterator.h"
42#include "llvm/IR/Instruction.h"
43#include "llvm/IR/Instructions.h"
44#include "llvm/IR/IntrinsicInst.h"
45#include "llvm/IR/IntrinsicsAArch64.h"
46#include "llvm/IR/Metadata.h"
47#include "llvm/Pass.h"
48#include "llvm/Support/Casting.h"
49#include "llvm/Support/Debug.h"
50#include "llvm/Support/raw_ostream.h"
51#include "llvm/Transforms/Utils/Local.h"
52#include <cassert>
53#include <iterator>
54#include <utility>
55
56using namespace llvm;
57
58#define DEBUG_TYPE"stack-tagging" "stack-tagging"
59
60static cl::opt<bool> ClMergeInit(
61 "stack-tagging-merge-init", cl::Hidden, cl::init(true), cl::ZeroOrMore,
62 cl::desc("merge stack variable initializers with tagging when possible"));
63
64static cl::opt<unsigned> ClScanLimit("stack-tagging-merge-init-scan-limit",
65 cl::init(40), cl::Hidden);
66
67static const Align kTagGranuleSize = Align(16);
68
69namespace {
70
71class InitializerBuilder {
72 uint64_t Size;
73 const DataLayout *DL;
74 Value *BasePtr;
75 Function *SetTagFn;
76 Function *SetTagZeroFn;
77 Function *StgpFn;
78
79 // List of initializers sorted by start offset.
80 struct Range {
81 uint64_t Start, End;
82 Instruction *Inst;
83 };
84 SmallVector<Range, 4> Ranges;
85 // 8-aligned offset => 8-byte initializer
86 // Missing keys are zero initialized.
87 std::map<uint64_t, Value *> Out;
88
89public:
90 InitializerBuilder(uint64_t Size, const DataLayout *DL, Value *BasePtr,
91 Function *SetTagFn, Function *SetTagZeroFn,
92 Function *StgpFn)
93 : Size(Size), DL(DL), BasePtr(BasePtr), SetTagFn(SetTagFn),
94 SetTagZeroFn(SetTagZeroFn), StgpFn(StgpFn) {}
95
96 bool addRange(uint64_t Start, uint64_t End, Instruction *Inst) {
97 auto I = std::lower_bound(
98 Ranges.begin(), Ranges.end(), Start,
99 [](const Range &LHS, uint64_t RHS) { return LHS.End <= RHS; });
100 if (I != Ranges.end() && End > I->Start) {
101 // Overlap - bail.
102 return false;
103 }
104 Ranges.insert(I, {Start, End, Inst});
105 return true;
106 }
107
108 bool addStore(uint64_t Offset, StoreInst *SI, const DataLayout *DL) {
109 int64_t StoreSize = DL->getTypeStoreSize(SI->getOperand(0)->getType());
110 if (!addRange(Offset, Offset + StoreSize, SI))
111 return false;
112 IRBuilder<> IRB(SI);
113 applyStore(IRB, Offset, Offset + StoreSize, SI->getOperand(0));
114 return true;
115 }
116
117 bool addMemSet(uint64_t Offset, MemSetInst *MSI) {
118 uint64_t StoreSize = cast<ConstantInt>(MSI->getLength())->getZExtValue();
119 if (!addRange(Offset, Offset + StoreSize, MSI))
120 return false;
121 IRBuilder<> IRB(MSI);
122 applyMemSet(IRB, Offset, Offset + StoreSize,
123 cast<ConstantInt>(MSI->getValue()));
124 return true;
125 }
126
127 void applyMemSet(IRBuilder<> &IRB, int64_t Start, int64_t End,
128 ConstantInt *V) {
129 // Out[] does not distinguish between zero and undef, and we already know
130 // that this memset does not overlap with any other initializer. Nothing to
131 // do for memset(0).
132 if (V->isZero())
133 return;
134 for (int64_t Offset = Start - Start % 8; Offset < End; Offset += 8) {
135 uint64_t Cst = 0x0101010101010101UL;
136 int LowBits = Offset < Start ? (Start - Offset) * 8 : 0;
137 if (LowBits)
138 Cst = (Cst >> LowBits) << LowBits;
139 int HighBits = End - Offset < 8 ? (8 - (End - Offset)) * 8 : 0;
140 if (HighBits)
141 Cst = (Cst << HighBits) >> HighBits;
142 ConstantInt *C =
143 ConstantInt::get(IRB.getInt64Ty(), Cst * V->getZExtValue());
144
145 Value *&CurrentV = Out[Offset];
146 if (!CurrentV) {
147 CurrentV = C;
148 } else {
149 CurrentV = IRB.CreateOr(CurrentV, C);
150 }
151 }
152 }
153
154 // Take a 64-bit slice of the value starting at the given offset (in bytes).
155 // Offset can be negative. Pad with zeroes on both sides when necessary.
156 Value *sliceValue(IRBuilder<> &IRB, Value *V, int64_t Offset) {
157 if (Offset > 0) {
158 V = IRB.CreateLShr(V, Offset * 8);
159 V = IRB.CreateZExtOrTrunc(V, IRB.getInt64Ty());
160 } else if (Offset < 0) {
161 V = IRB.CreateZExtOrTrunc(V, IRB.getInt64Ty());
162 V = IRB.CreateShl(V, -Offset * 8);
163 } else {
164 V = IRB.CreateZExtOrTrunc(V, IRB.getInt64Ty());
165 }
166 return V;
167 }
168
169 void applyStore(IRBuilder<> &IRB, int64_t Start, int64_t End,
170 Value *StoredValue) {
171 StoredValue = flatten(IRB, StoredValue);
172 for (int64_t Offset = Start - Start % 8; Offset < End; Offset += 8) {
173 Value *V = sliceValue(IRB, StoredValue, Offset - Start);
174 Value *&CurrentV = Out[Offset];
175 if (!CurrentV) {
176 CurrentV = V;
177 } else {
178 CurrentV = IRB.CreateOr(CurrentV, V);
179 }
180 }
181 }
182
183 void generate(IRBuilder<> &IRB) {
184 LLVM_DEBUG(dbgs() << "Combined initializer\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("stack-tagging")) { dbgs() << "Combined initializer\n"
; } } while (false)
;
185 // No initializers => the entire allocation is undef.
186 if (Ranges.empty()) {
187 emitUndef(IRB, 0, Size);
188 return;
189 }
190
191 // Look through 8-byte initializer list 16 bytes at a time;
192 // If one of the two 8-byte halfs is non-zero non-undef, emit STGP.
193 // Otherwise, emit zeroes up to next available item.
194 uint64_t LastOffset = 0;
195 for (uint64_t Offset = 0; Offset < Size; Offset += 16) {
196 auto I1 = Out.find(Offset);
197 auto I2 = Out.find(Offset + 8);
198 if (I1 == Out.end() && I2 == Out.end())
199 continue;
200
201 if (Offset > LastOffset)
202 emitZeroes(IRB, LastOffset, Offset - LastOffset);
203
204 Value *Store1 = I1 == Out.end() ? Constant::getNullValue(IRB.getInt64Ty())
205 : I1->second;
206 Value *Store2 = I2 == Out.end() ? Constant::getNullValue(IRB.getInt64Ty())
207 : I2->second;
208 emitPair(IRB, Offset, Store1, Store2);
209 LastOffset = Offset + 16;
210 }
211
212 // memset(0) does not update Out[], therefore the tail can be either undef
213 // or zero.
214 if (LastOffset < Size)
215 emitZeroes(IRB, LastOffset, Size - LastOffset);
216
217 for (const auto &R : Ranges) {
218 R.Inst->eraseFromParent();
219 }
220 }
221
222 void emitZeroes(IRBuilder<> &IRB, uint64_t Offset, uint64_t Size) {
223 LLVM_DEBUG(dbgs() << " [" << Offset << ", " << Offset + Sizedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("stack-tagging")) { dbgs() << " [" << Offset <<
", " << Offset + Size << ") zero\n"; } } while (
false)
224 << ") zero\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("stack-tagging")) { dbgs() << " [" << Offset <<
", " << Offset + Size << ") zero\n"; } } while (
false)
;
225 Value *Ptr = BasePtr;
226 if (Offset)
227 Ptr = IRB.CreateConstGEP1_32(Ptr, Offset);
228 IRB.CreateCall(SetTagZeroFn,
229 {Ptr, ConstantInt::get(IRB.getInt64Ty(), Size)});
230 }
231
232 void emitUndef(IRBuilder<> &IRB, uint64_t Offset, uint64_t Size) {
233 LLVM_DEBUG(dbgs() << " [" << Offset << ", " << Offset + Sizedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("stack-tagging")) { dbgs() << " [" << Offset <<
", " << Offset + Size << ") undef\n"; } } while (
false)
234 << ") undef\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("stack-tagging")) { dbgs() << " [" << Offset <<
", " << Offset + Size << ") undef\n"; } } while (
false)
;
235 Value *Ptr = BasePtr;
236 if (Offset)
237 Ptr = IRB.CreateConstGEP1_32(Ptr, Offset);
238 IRB.CreateCall(SetTagFn, {Ptr, ConstantInt::get(IRB.getInt64Ty(), Size)});
239 }
240
241 void emitPair(IRBuilder<> &IRB, uint64_t Offset, Value *A, Value *B) {
242 LLVM_DEBUG(dbgs() << " [" << Offset << ", " << Offset + 16 << "):\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("stack-tagging")) { dbgs() << " [" << Offset <<
", " << Offset + 16 << "):\n"; } } while (false)
;
243 LLVM_DEBUG(dbgs() << " " << *A << "\n " << *B << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("stack-tagging")) { dbgs() << " " << *A <<
"\n " << *B << "\n"; } } while (false)
;
244 Value *Ptr = BasePtr;
245 if (Offset)
246 Ptr = IRB.CreateConstGEP1_32(Ptr, Offset);
247 IRB.CreateCall(StgpFn, {Ptr, A, B});
248 }
249
250 Value *flatten(IRBuilder<> &IRB, Value *V) {
251 if (V->getType()->isIntegerTy())
252 return V;
253 // vector of pointers -> vector of ints
254 if (VectorType *VecTy = dyn_cast<VectorType>(V->getType())) {
255 LLVMContext &Ctx = IRB.getContext();
256 Type *EltTy = VecTy->getElementType();
257 if (EltTy->isPointerTy()) {
258 uint32_t EltSize = DL->getTypeSizeInBits(EltTy);
259 Type *NewTy = VectorType::get(IntegerType::get(Ctx, EltSize),
260 VecTy->getNumElements());
261 V = IRB.CreatePointerCast(V, NewTy);
262 }
263 }
264 return IRB.CreateBitOrPointerCast(
265 V, IRB.getIntNTy(DL->getTypeStoreSize(V->getType()) * 8));
266 }
267};
268
269class AArch64StackTagging : public FunctionPass {
270 struct AllocaInfo {
271 AllocaInst *AI;
272 SmallVector<IntrinsicInst *, 2> LifetimeStart;
273 SmallVector<IntrinsicInst *, 2> LifetimeEnd;
274 SmallVector<DbgVariableIntrinsic *, 2> DbgVariableIntrinsics;
275 int Tag; // -1 for non-tagged allocations
276 };
277
278 bool MergeInit;
279
280public:
281 static char ID; // Pass ID, replacement for typeid
282
283 AArch64StackTagging(bool MergeInit = true)
284 : FunctionPass(ID),
285 MergeInit(ClMergeInit.getNumOccurrences() > 0 ? ClMergeInit
286 : MergeInit) {
287 initializeAArch64StackTaggingPass(*PassRegistry::getPassRegistry());
288 }
289
290 bool isInterestingAlloca(const AllocaInst &AI);
291 void alignAndPadAlloca(AllocaInfo &Info);
292
293 void tagAlloca(AllocaInst *AI, Instruction *InsertBefore, Value *Ptr,
294 uint64_t Size);
295 void untagAlloca(AllocaInst *AI, Instruction *InsertBefore, uint64_t Size);
296
297 Instruction *collectInitializers(Instruction *StartInst, Value *StartPtr,
298 uint64_t Size, InitializerBuilder &IB);
299
300 Instruction *
301 insertBaseTaggedPointer(const MapVector<AllocaInst *, AllocaInfo> &Allocas,
302 const DominatorTree *DT);
303 bool runOnFunction(Function &F) override;
304
305 StringRef getPassName() const override { return "AArch64 Stack Tagging"; }
306
307private:
308 Function *F;
309 Function *SetTagFunc;
310 const DataLayout *DL;
311 AAResults *AA;
312
313 void getAnalysisUsage(AnalysisUsage &AU) const override {
314 AU.setPreservesCFG();
315 if (MergeInit)
316 AU.addRequired<AAResultsWrapperPass>();
317 }
318};
319
320} // end anonymous namespace
321
322char AArch64StackTagging::ID = 0;
323
324INITIALIZE_PASS_BEGIN(AArch64StackTagging, DEBUG_TYPE, "AArch64 Stack Tagging",static void *initializeAArch64StackTaggingPassOnce(PassRegistry
&Registry) {
325 false, false)static void *initializeAArch64StackTaggingPassOnce(PassRegistry
&Registry) {
326INITIALIZE_PASS_END(AArch64StackTagging, DEBUG_TYPE, "AArch64 Stack Tagging",PassInfo *PI = new PassInfo( "AArch64 Stack Tagging", "stack-tagging"
, &AArch64StackTagging::ID, PassInfo::NormalCtor_t(callDefaultCtor
<AArch64StackTagging>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeAArch64StackTaggingPassFlag
; void llvm::initializeAArch64StackTaggingPass(PassRegistry &
Registry) { llvm::call_once(InitializeAArch64StackTaggingPassFlag
, initializeAArch64StackTaggingPassOnce, std::ref(Registry));
}
327 false, false)PassInfo *PI = new PassInfo( "AArch64 Stack Tagging", "stack-tagging"
, &AArch64StackTagging::ID, PassInfo::NormalCtor_t(callDefaultCtor
<AArch64StackTagging>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeAArch64StackTaggingPassFlag
; void llvm::initializeAArch64StackTaggingPass(PassRegistry &
Registry) { llvm::call_once(InitializeAArch64StackTaggingPassFlag
, initializeAArch64StackTaggingPassOnce, std::ref(Registry));
}
328
329FunctionPass *llvm::createAArch64StackTaggingPass(bool MergeInit) {
330 return new AArch64StackTagging(MergeInit);
331}
332
333Instruction *AArch64StackTagging::collectInitializers(Instruction *StartInst,
334 Value *StartPtr,
335 uint64_t Size,
336 InitializerBuilder &IB) {
337 MemoryLocation AllocaLoc{StartPtr, Size};
338 Instruction *LastInst = StartInst;
339 BasicBlock::iterator BI(StartInst);
340
341 unsigned Count = 0;
342 for (; Count < ClScanLimit && !BI->isTerminator(); ++BI) {
343 if (!isa<DbgInfoIntrinsic>(*BI))
344 ++Count;
345
346 if (isNoModRef(AA->getModRefInfo(&*BI, AllocaLoc)))
347 continue;
348
349 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
350 // If the instruction is readnone, ignore it, otherwise bail out. We
351 // don't even allow readonly here because we don't want something like:
352 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
353 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
354 break;
355 continue;
356 }
357
358 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
359 if (!NextStore->isSimple())
360 break;
361
362 // Check to see if this store is to a constant offset from the start ptr.
363 Optional<int64_t> Offset =
364 isPointerOffset(StartPtr, NextStore->getPointerOperand(), *DL);
365 if (!Offset)
366 break;
367
368 if (!IB.addStore(*Offset, NextStore, DL))
369 break;
370 LastInst = NextStore;
371 } else {
372 MemSetInst *MSI = cast<MemSetInst>(BI);
373
374 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
375 break;
376
377 if (!isa<ConstantInt>(MSI->getValue()))
378 break;
379
380 // Check to see if this store is to a constant offset from the start ptr.
381 Optional<int64_t> Offset = isPointerOffset(StartPtr, MSI->getDest(), *DL);
382 if (!Offset)
383 break;
384
385 if (!IB.addMemSet(*Offset, MSI))
386 break;
387 LastInst = MSI;
388 }
389 }
390 return LastInst;
391}
392
393bool AArch64StackTagging::isInterestingAlloca(const AllocaInst &AI) {
394 // FIXME: support dynamic allocas
395 bool IsInteresting =
396 AI.getAllocatedType()->isSized() && AI.isStaticAlloca() &&
397 // alloca() may be called with 0 size, ignore it.
398 AI.getAllocationSizeInBits(*DL).getValue() > 0 &&
399 // inalloca allocas are not treated as static, and we don't want
400 // dynamic alloca instrumentation for them as well.
401 !AI.isUsedWithInAlloca() &&
402 // swifterror allocas are register promoted by ISel
403 !AI.isSwiftError();
404 return IsInteresting;
405}
406
407void AArch64StackTagging::tagAlloca(AllocaInst *AI, Instruction *InsertBefore,
408 Value *Ptr, uint64_t Size) {
409 auto SetTagZeroFunc =
410 Intrinsic::getDeclaration(F->getParent(), Intrinsic::aarch64_settag_zero);
411 auto StgpFunc =
412 Intrinsic::getDeclaration(F->getParent(), Intrinsic::aarch64_stgp);
413
414 InitializerBuilder IB(Size, DL, Ptr, SetTagFunc, SetTagZeroFunc, StgpFunc);
415 bool LittleEndian =
416 Triple(AI->getModule()->getTargetTriple()).isLittleEndian();
417 // Current implementation of initializer merging assumes little endianness.
418 if (MergeInit && !F->hasOptNone() && LittleEndian) {
419 LLVM_DEBUG(dbgs() << "collecting initializers for " << *AIdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("stack-tagging")) { dbgs() << "collecting initializers for "
<< *AI << ", size = " << Size << "\n"
; } } while (false)
420 << ", size = " << Size << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("stack-tagging")) { dbgs() << "collecting initializers for "
<< *AI << ", size = " << Size << "\n"
; } } while (false)
;
421 InsertBefore = collectInitializers(InsertBefore, Ptr, Size, IB);
422 }
423
424 IRBuilder<> IRB(InsertBefore);
425 IB.generate(IRB);
426}
427
428void AArch64StackTagging::untagAlloca(AllocaInst *AI, Instruction *InsertBefore,
429 uint64_t Size) {
430 IRBuilder<> IRB(InsertBefore);
431 IRB.CreateCall(SetTagFunc, {IRB.CreatePointerCast(AI, IRB.getInt8PtrTy()),
432 ConstantInt::get(IRB.getInt64Ty(), Size)});
433}
434
435Instruction *AArch64StackTagging::insertBaseTaggedPointer(
436 const MapVector<AllocaInst *, AllocaInfo> &Allocas,
437 const DominatorTree *DT) {
438 BasicBlock *PrologueBB = nullptr;
439 // Try sinking IRG as deep as possible to avoid hurting shrink wrap.
440 for (auto &I : Allocas) {
441 const AllocaInfo &Info = I.second;
442 AllocaInst *AI = Info.AI;
443 if (Info.Tag < 0)
444 continue;
445 if (!PrologueBB) {
446 PrologueBB = AI->getParent();
447 continue;
448 }
449 PrologueBB = DT->findNearestCommonDominator(PrologueBB, AI->getParent());
450 }
451 assert(PrologueBB)((PrologueBB) ? static_cast<void> (0) : __assert_fail (
"PrologueBB", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/AArch64/AArch64StackTagging.cpp"
, 451, __PRETTY_FUNCTION__))
;
452
453 IRBuilder<> IRB(&PrologueBB->front());
454 Function *IRG_SP =
455 Intrinsic::getDeclaration(F->getParent(), Intrinsic::aarch64_irg_sp);
456 Instruction *Base =
457 IRB.CreateCall(IRG_SP, {Constant::getNullValue(IRB.getInt64Ty())});
458 Base->setName("basetag");
459 return Base;
460}
461
462void AArch64StackTagging::alignAndPadAlloca(AllocaInfo &Info) {
463 const Align NewAlignment =
464 max(MaybeAlign(Info.AI->getAlignment()), kTagGranuleSize);
465 Info.AI->setAlignment(NewAlignment);
466
467 uint64_t Size = Info.AI->getAllocationSizeInBits(*DL).getValue() / 8;
468 uint64_t AlignedSize = alignTo(Size, kTagGranuleSize);
469 if (Size == AlignedSize)
470 return;
471
472 // Add padding to the alloca.
473 Type *AllocatedType =
474 Info.AI->isArrayAllocation()
475 ? ArrayType::get(
476 Info.AI->getAllocatedType(),
477 cast<ConstantInt>(Info.AI->getArraySize())->getZExtValue())
478 : Info.AI->getAllocatedType();
479 Type *PaddingType =
480 ArrayType::get(Type::getInt8Ty(F->getContext()), AlignedSize - Size);
481 Type *TypeWithPadding = StructType::get(AllocatedType, PaddingType);
482 auto *NewAI = new AllocaInst(
483 TypeWithPadding, Info.AI->getType()->getAddressSpace(), nullptr, "", Info.AI);
484 NewAI->takeName(Info.AI);
485 NewAI->setAlignment(MaybeAlign(Info.AI->getAlignment()));
486 NewAI->setUsedWithInAlloca(Info.AI->isUsedWithInAlloca());
487 NewAI->setSwiftError(Info.AI->isSwiftError());
488 NewAI->copyMetadata(*Info.AI);
489
490 auto *NewPtr = new BitCastInst(NewAI, Info.AI->getType(), "", Info.AI);
491 Info.AI->replaceAllUsesWith(NewPtr);
492 Info.AI->eraseFromParent();
493 Info.AI = NewAI;
494}
495
496// Helper function to check for post-dominance.
497static bool postDominates(const PostDominatorTree *PDT, const IntrinsicInst *A,
498 const IntrinsicInst *B) {
499 const BasicBlock *ABB = A->getParent();
500 const BasicBlock *BBB = B->getParent();
501
502 if (ABB != BBB)
503 return PDT->dominates(ABB, BBB);
504
505 for (const Instruction &I : *ABB) {
506 if (&I == B)
507 return true;
508 if (&I == A)
509 return false;
510 }
511 llvm_unreachable("Corrupt instruction list")::llvm::llvm_unreachable_internal("Corrupt instruction list",
"/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/AArch64/AArch64StackTagging.cpp"
, 511)
;
512}
513
514// FIXME: check for MTE extension
515bool AArch64StackTagging::runOnFunction(Function &Fn) {
516 if (!Fn.hasFnAttribute(Attribute::SanitizeMemTag))
1
Assuming the condition is false
2
Taking false branch
517 return false;
518
519 F = &Fn;
520 DL = &Fn.getParent()->getDataLayout();
521 if (MergeInit)
3
Assuming field 'MergeInit' is false
4
Taking false branch
522 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
523
524 MapVector<AllocaInst *, AllocaInfo> Allocas; // need stable iteration order
525 SmallVector<Instruction *, 8> RetVec;
526 DenseMap<Value *, AllocaInst *> AllocaForValue;
527 SmallVector<Instruction *, 4> UnrecognizedLifetimes;
528
529 for (auto &BB : *F) {
530 for (BasicBlock::iterator IT = BB.begin(); IT != BB.end(); ++IT) {
531 Instruction *I = &*IT;
532 if (auto *AI = dyn_cast<AllocaInst>(I)) {
533 Allocas[AI].AI = AI;
534 continue;
535 }
536
537 if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(I)) {
538 if (auto *AI =
539 dyn_cast_or_null<AllocaInst>(DVI->getVariableLocation())) {
540 Allocas[AI].DbgVariableIntrinsics.push_back(DVI);
541 }
542 continue;
543 }
544
545 auto *II = dyn_cast<IntrinsicInst>(I);
546 if (II && (II->getIntrinsicID() == Intrinsic::lifetime_start ||
547 II->getIntrinsicID() == Intrinsic::lifetime_end)) {
548 AllocaInst *AI =
549 llvm::findAllocaForValue(II->getArgOperand(1), AllocaForValue);
550 if (!AI) {
551 UnrecognizedLifetimes.push_back(I);
552 continue;
553 }
554 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
555 Allocas[AI].LifetimeStart.push_back(II);
556 else
557 Allocas[AI].LifetimeEnd.push_back(II);
558 }
559
560 if (isa<ReturnInst>(I) || isa<ResumeInst>(I) || isa<CleanupReturnInst>(I))
561 RetVec.push_back(I);
562 }
563 }
564
565 if (Allocas.empty())
5
Assuming the condition is false
6
Taking false branch
566 return false;
567
568 int NextTag = 0;
569 int NumInterestingAllocas = 0;
570 for (auto &I : Allocas) {
571 AllocaInfo &Info = I.second;
572 assert(Info.AI)((Info.AI) ? static_cast<void> (0) : __assert_fail ("Info.AI"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/AArch64/AArch64StackTagging.cpp"
, 572, __PRETTY_FUNCTION__))
;
7
Assuming field 'AI' is non-null
8
'?' condition is true
11
Assuming field 'AI' is non-null
12
'?' condition is true
15
Assuming field 'AI' is non-null
16
'?' condition is true
573
574 if (!isInterestingAlloca(*Info.AI)) {
9
Taking true branch
13
Taking true branch
17
Taking false branch
575 Info.Tag = -1;
576 continue;
10
Execution continues on line 570
14
Execution continues on line 570
577 }
578
579 alignAndPadAlloca(Info);
580 NumInterestingAllocas++;
581 Info.Tag = NextTag;
582 NextTag = (NextTag + 1) % 16;
583 }
584
585 if (NumInterestingAllocas
17.1
'NumInterestingAllocas' is not equal to 0
17.1
'NumInterestingAllocas' is not equal to 0
== 0)
18
Taking false branch
586 return true;
587
588 std::unique_ptr<DominatorTree> DeleteDT;
589 DominatorTree *DT = nullptr;
590 if (auto *P
18.1
'P' is null
18.1
'P' is null
= getAnalysisIfAvailable<DominatorTreeWrapperPass>())
19
Taking false branch
591 DT = &P->getDomTree();
592
593 if (DT == nullptr && (NumInterestingAllocas
19.1
'NumInterestingAllocas' is <= 1
19.1
'NumInterestingAllocas' is <= 1
> 1 ||
21
Taking false branch
594 !F->hasFnAttribute(Attribute::OptimizeNone))) {
20
Assuming the condition is false
595 DeleteDT = std::make_unique<DominatorTree>(*F);
596 DT = DeleteDT.get();
597 }
598
599 std::unique_ptr<PostDominatorTree> DeletePDT;
600 PostDominatorTree *PDT = nullptr;
601 if (auto *P
21.1
'P' is null
21.1
'P' is null
= getAnalysisIfAvailable<PostDominatorTreeWrapperPass>())
22
Taking false branch
602 PDT = &P->getPostDomTree();
603
604 if (PDT == nullptr && !F->hasFnAttribute(Attribute::OptimizeNone)) {
23
Assuming the condition is false
24
Taking false branch
605 DeletePDT = std::make_unique<PostDominatorTree>(*F);
606 PDT = DeletePDT.get();
607 }
608
609 SetTagFunc =
610 Intrinsic::getDeclaration(F->getParent(), Intrinsic::aarch64_settag);
611
612 Instruction *Base = insertBaseTaggedPointer(Allocas, DT);
613
614 for (auto &I : Allocas) {
615 const AllocaInfo &Info = I.second;
616 AllocaInst *AI = Info.AI;
617 if (Info.Tag < 0)
25
Assuming field 'Tag' is >= 0
26
Taking false branch
618 continue;
619
620 // Replace alloca with tagp(alloca).
621 IRBuilder<> IRB(Info.AI->getNextNode());
622 Function *TagP = Intrinsic::getDeclaration(
623 F->getParent(), Intrinsic::aarch64_tagp, {Info.AI->getType()});
624 Instruction *TagPCall =
625 IRB.CreateCall(TagP, {Constant::getNullValue(Info.AI->getType()), Base,
626 ConstantInt::get(IRB.getInt64Ty(), Info.Tag)});
627 if (Info.AI->hasName())
27
Assuming the condition is false
28
Taking false branch
628 TagPCall->setName(Info.AI->getName() + ".tag");
629 Info.AI->replaceAllUsesWith(TagPCall);
630 TagPCall->setOperand(0, Info.AI);
631
632 if (UnrecognizedLifetimes.empty() && Info.LifetimeStart.size() == 1 &&
29
Calling 'SmallVectorBase::empty'
32
Returning from 'SmallVectorBase::empty'
33
Assuming the condition is true
35
Taking true branch
633 Info.LifetimeEnd.size() == 1) {
34
Assuming the condition is true
634 IntrinsicInst *Start = Info.LifetimeStart[0];
635 IntrinsicInst *End = Info.LifetimeEnd[0];
636 uint64_t Size =
637 dyn_cast<ConstantInt>(Start->getArgOperand(0))->getZExtValue();
36
Assuming the object is not a 'ConstantInt'
37
Called C++ object pointer is null
638 Size = alignTo(Size, kTagGranuleSize);
639 tagAlloca(AI, Start->getNextNode(), Start->getArgOperand(1), Size);
640 // We need to ensure that if we tag some object, we certainly untag it
641 // before the function exits.
642 if (PDT != nullptr && postDominates(PDT, End, Start)) {
643 untagAlloca(AI, End, Size);
644 } else {
645 SmallVector<Instruction *, 8> ReachableRetVec;
646 unsigned NumCoveredExits = 0;
647 for (auto &RI : RetVec) {
648 if (!isPotentiallyReachable(Start, RI, nullptr, DT))
649 continue;
650 ReachableRetVec.push_back(RI);
651 if (DT != nullptr && DT->dominates(End, RI))
652 ++NumCoveredExits;
653 }
654 // If there's a mix of covered and non-covered exits, just put the untag
655 // on exits, so we avoid the redundancy of untagging twice.
656 if (NumCoveredExits == ReachableRetVec.size()) {
657 untagAlloca(AI, End, Size);
658 } else {
659 for (auto &RI : ReachableRetVec)
660 untagAlloca(AI, RI, Size);
661 // We may have inserted untag outside of the lifetime interval.
662 // Remove the lifetime end call for this alloca.
663 End->eraseFromParent();
664 }
665 }
666 } else {
667 uint64_t Size = Info.AI->getAllocationSizeInBits(*DL).getValue() / 8;
668 Value *Ptr = IRB.CreatePointerCast(TagPCall, IRB.getInt8PtrTy());
669 tagAlloca(AI, &*IRB.GetInsertPoint(), Ptr, Size);
670 for (auto &RI : RetVec) {
671 untagAlloca(AI, RI, Size);
672 }
673 // We may have inserted tag/untag outside of any lifetime interval.
674 // Remove all lifetime intrinsics for this alloca.
675 for (auto &II : Info.LifetimeStart)
676 II->eraseFromParent();
677 for (auto &II : Info.LifetimeEnd)
678 II->eraseFromParent();
679 }
680
681 // Fixup debug intrinsics to point to the new alloca.
682 for (auto DVI : Info.DbgVariableIntrinsics)
683 DVI->setArgOperand(
684 0,
685 MetadataAsValue::get(F->getContext(), LocalAsMetadata::get(Info.AI)));
686 }
687
688 // If we have instrumented at least one alloca, all unrecognized lifetime
689 // instrinsics have to go.
690 for (auto &I : UnrecognizedLifetimes)
691 I->eraseFromParent();
692
693 return true;
694}

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h

1//===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the SmallVector class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ADT_SMALLVECTOR_H
14#define LLVM_ADT_SMALLVECTOR_H
15
16#include "llvm/ADT/iterator_range.h"
17#include "llvm/Support/AlignOf.h"
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/MathExtras.h"
20#include "llvm/Support/MemAlloc.h"
21#include "llvm/Support/type_traits.h"
22#include "llvm/Support/ErrorHandling.h"
23#include <algorithm>
24#include <cassert>
25#include <cstddef>
26#include <cstdlib>
27#include <cstring>
28#include <initializer_list>
29#include <iterator>
30#include <memory>
31#include <new>
32#include <type_traits>
33#include <utility>
34
35namespace llvm {
36
37/// This is all the non-templated stuff common to all SmallVectors.
38class SmallVectorBase {
39protected:
40 void *BeginX;
41 unsigned Size = 0, Capacity;
42
43 SmallVectorBase() = delete;
44 SmallVectorBase(void *FirstEl, size_t TotalCapacity)
45 : BeginX(FirstEl), Capacity(TotalCapacity) {}
46
47 /// This is an implementation of the grow() method which only works
48 /// on POD-like data types and is out of line to reduce code duplication.
49 void grow_pod(void *FirstEl, size_t MinCapacity, size_t TSize);
50
51public:
52 size_t size() const { return Size; }
53 size_t capacity() const { return Capacity; }
54
55 LLVM_NODISCARD[[clang::warn_unused_result]] bool empty() const { return !Size; }
30
Assuming field 'Size' is 0, which participates in a condition later
31
Returning the value 1, which participates in a condition later
56
57 /// Set the array size to \p N, which the current array must have enough
58 /// capacity for.
59 ///
60 /// This does not construct or destroy any elements in the vector.
61 ///
62 /// Clients can use this in conjunction with capacity() to write past the end
63 /// of the buffer when they know that more elements are available, and only
64 /// update the size later. This avoids the cost of value initializing elements
65 /// which will only be overwritten.
66 void set_size(size_t N) {
67 assert(N <= capacity())((N <= capacity()) ? static_cast<void> (0) : __assert_fail
("N <= capacity()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h"
, 67, __PRETTY_FUNCTION__))
;
68 Size = N;
69 }
70};
71
72/// Figure out the offset of the first element.
73template <class T, typename = void> struct SmallVectorAlignmentAndSize {
74 AlignedCharArrayUnion<SmallVectorBase> Base;
75 AlignedCharArrayUnion<T> FirstEl;
76};
77
78/// This is the part of SmallVectorTemplateBase which does not depend on whether
79/// the type T is a POD. The extra dummy template argument is used by ArrayRef
80/// to avoid unnecessarily requiring T to be complete.
81template <typename T, typename = void>
82class SmallVectorTemplateCommon : public SmallVectorBase {
83 /// Find the address of the first element. For this pointer math to be valid
84 /// with small-size of 0 for T with lots of alignment, it's important that
85 /// SmallVectorStorage is properly-aligned even for small-size of 0.
86 void *getFirstEl() const {
87 return const_cast<void *>(reinterpret_cast<const void *>(
88 reinterpret_cast<const char *>(this) +
89 offsetof(SmallVectorAlignmentAndSize<T>, FirstEl)__builtin_offsetof(SmallVectorAlignmentAndSize<T>, FirstEl
)
));
90 }
91 // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
92
93protected:
94 SmallVectorTemplateCommon(size_t Size)
95 : SmallVectorBase(getFirstEl(), Size) {}
96
97 void grow_pod(size_t MinCapacity, size_t TSize) {
98 SmallVectorBase::grow_pod(getFirstEl(), MinCapacity, TSize);
99 }
100
101 /// Return true if this is a smallvector which has not had dynamic
102 /// memory allocated for it.
103 bool isSmall() const { return BeginX == getFirstEl(); }
104
105 /// Put this vector in a state of being small.
106 void resetToSmall() {
107 BeginX = getFirstEl();
108 Size = Capacity = 0; // FIXME: Setting Capacity to 0 is suspect.
109 }
110
111public:
112 using size_type = size_t;
113 using difference_type = ptrdiff_t;
114 using value_type = T;
115 using iterator = T *;
116 using const_iterator = const T *;
117
118 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
119 using reverse_iterator = std::reverse_iterator<iterator>;
120
121 using reference = T &;
122 using const_reference = const T &;
123 using pointer = T *;
124 using const_pointer = const T *;
125
126 // forward iterator creation methods.
127 iterator begin() { return (iterator)this->BeginX; }
128 const_iterator begin() const { return (const_iterator)this->BeginX; }
129 iterator end() { return begin() + size(); }
130 const_iterator end() const { return begin() + size(); }
131
132 // reverse iterator creation methods.
133 reverse_iterator rbegin() { return reverse_iterator(end()); }
134 const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
135 reverse_iterator rend() { return reverse_iterator(begin()); }
136 const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
137
138 size_type size_in_bytes() const { return size() * sizeof(T); }
139 size_type max_size() const { return size_type(-1) / sizeof(T); }
140
141 size_t capacity_in_bytes() const { return capacity() * sizeof(T); }
142
143 /// Return a pointer to the vector's buffer, even if empty().
144 pointer data() { return pointer(begin()); }
145 /// Return a pointer to the vector's buffer, even if empty().
146 const_pointer data() const { return const_pointer(begin()); }
147
148 reference operator[](size_type idx) {
149 assert(idx < size())((idx < size()) ? static_cast<void> (0) : __assert_fail
("idx < size()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h"
, 149, __PRETTY_FUNCTION__))
;
150 return begin()[idx];
151 }
152 const_reference operator[](size_type idx) const {
153 assert(idx < size())((idx < size()) ? static_cast<void> (0) : __assert_fail
("idx < size()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h"
, 153, __PRETTY_FUNCTION__))
;
154 return begin()[idx];
155 }
156
157 reference front() {
158 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h"
, 158, __PRETTY_FUNCTION__))
;
159 return begin()[0];
160 }
161 const_reference front() const {
162 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h"
, 162, __PRETTY_FUNCTION__))
;
163 return begin()[0];
164 }
165
166 reference back() {
167 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h"
, 167, __PRETTY_FUNCTION__))
;
168 return end()[-1];
169 }
170 const_reference back() const {
171 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h"
, 171, __PRETTY_FUNCTION__))
;
172 return end()[-1];
173 }
174};
175
176/// SmallVectorTemplateBase<TriviallyCopyable = false> - This is where we put method
177/// implementations that are designed to work with non-POD-like T's.
178template <typename T, bool = is_trivially_copyable<T>::value>
179class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
180protected:
181 SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
182
183 static void destroy_range(T *S, T *E) {
184 while (S != E) {
185 --E;
186 E->~T();
187 }
188 }
189
190 /// Move the range [I, E) into the uninitialized memory starting with "Dest",
191 /// constructing elements as needed.
192 template<typename It1, typename It2>
193 static void uninitialized_move(It1 I, It1 E, It2 Dest) {
194 std::uninitialized_copy(std::make_move_iterator(I),
195 std::make_move_iterator(E), Dest);
196 }
197
198 /// Copy the range [I, E) onto the uninitialized memory starting with "Dest",
199 /// constructing elements as needed.
200 template<typename It1, typename It2>
201 static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
202 std::uninitialized_copy(I, E, Dest);
203 }
204
205 /// Grow the allocated memory (without initializing new elements), doubling
206 /// the size of the allocated memory. Guarantees space for at least one more
207 /// element, or MinSize more elements if specified.
208 void grow(size_t MinSize = 0);
209
210public:
211 void push_back(const T &Elt) {
212 if (LLVM_UNLIKELY(this->size() >= this->capacity())__builtin_expect((bool)(this->size() >= this->capacity
()), false)
)
213 this->grow();
214 ::new ((void*) this->end()) T(Elt);
215 this->set_size(this->size() + 1);
216 }
217
218 void push_back(T &&Elt) {
219 if (LLVM_UNLIKELY(this->size() >= this->capacity())__builtin_expect((bool)(this->size() >= this->capacity
()), false)
)
220 this->grow();
221 ::new ((void*) this->end()) T(::std::move(Elt));
222 this->set_size(this->size() + 1);
223 }
224
225 void pop_back() {
226 this->set_size(this->size() - 1);
227 this->end()->~T();
228 }
229};
230
231// Define this out-of-line to dissuade the C++ compiler from inlining it.
232template <typename T, bool TriviallyCopyable>
233void SmallVectorTemplateBase<T, TriviallyCopyable>::grow(size_t MinSize) {
234 if (MinSize > UINT32_MAX(4294967295U))
235 report_bad_alloc_error("SmallVector capacity overflow during allocation");
236
237 // Always grow, even from zero.
238 size_t NewCapacity = size_t(NextPowerOf2(this->capacity() + 2));
239 NewCapacity = std::min(std::max(NewCapacity, MinSize), size_t(UINT32_MAX(4294967295U)));
240 T *NewElts = static_cast<T*>(llvm::safe_malloc(NewCapacity*sizeof(T)));
241
242 // Move the elements over.
243 this->uninitialized_move(this->begin(), this->end(), NewElts);
244
245 // Destroy the original elements.
246 destroy_range(this->begin(), this->end());
247
248 // If this wasn't grown from the inline copy, deallocate the old space.
249 if (!this->isSmall())
250 free(this->begin());
251
252 this->BeginX = NewElts;
253 this->Capacity = NewCapacity;
254}
255
256/// SmallVectorTemplateBase<TriviallyCopyable = true> - This is where we put
257/// method implementations that are designed to work with POD-like T's.
258template <typename T>
259class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> {
260protected:
261 SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
262
263 // No need to do a destroy loop for POD's.
264 static void destroy_range(T *, T *) {}
265
266 /// Move the range [I, E) onto the uninitialized memory
267 /// starting with "Dest", constructing elements into it as needed.
268 template<typename It1, typename It2>
269 static void uninitialized_move(It1 I, It1 E, It2 Dest) {
270 // Just do a copy.
271 uninitialized_copy(I, E, Dest);
272 }
273
274 /// Copy the range [I, E) onto the uninitialized memory
275 /// starting with "Dest", constructing elements into it as needed.
276 template<typename It1, typename It2>
277 static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
278 // Arbitrary iterator types; just use the basic implementation.
279 std::uninitialized_copy(I, E, Dest);
280 }
281
282 /// Copy the range [I, E) onto the uninitialized memory
283 /// starting with "Dest", constructing elements into it as needed.
284 template <typename T1, typename T2>
285 static void uninitialized_copy(
286 T1 *I, T1 *E, T2 *Dest,
287 std::enable_if_t<std::is_same<typename std::remove_const<T1>::type,
288 T2>::value> * = nullptr) {
289 // Use memcpy for PODs iterated by pointers (which includes SmallVector
290 // iterators): std::uninitialized_copy optimizes to memmove, but we can
291 // use memcpy here. Note that I and E are iterators and thus might be
292 // invalid for memcpy if they are equal.
293 if (I != E)
294 memcpy(reinterpret_cast<void *>(Dest), I, (E - I) * sizeof(T));
295 }
296
297 /// Double the size of the allocated memory, guaranteeing space for at
298 /// least one more element or MinSize if specified.
299 void grow(size_t MinSize = 0) { this->grow_pod(MinSize, sizeof(T)); }
300
301public:
302 void push_back(const T &Elt) {
303 if (LLVM_UNLIKELY(this->size() >= this->capacity())__builtin_expect((bool)(this->size() >= this->capacity
()), false)
)
304 this->grow();
305 memcpy(reinterpret_cast<void *>(this->end()), &Elt, sizeof(T));
306 this->set_size(this->size() + 1);
307 }
308
309 void pop_back() { this->set_size(this->size() - 1); }
310};
311
312/// This class consists of common code factored out of the SmallVector class to
313/// reduce code duplication based on the SmallVector 'N' template parameter.
314template <typename T>
315class SmallVectorImpl : public SmallVectorTemplateBase<T> {
316 using SuperClass = SmallVectorTemplateBase<T>;
317
318public:
319 using iterator = typename SuperClass::iterator;
320 using const_iterator = typename SuperClass::const_iterator;
321 using reference = typename SuperClass::reference;
322 using size_type = typename SuperClass::size_type;
323
324protected:
325 // Default ctor - Initialize to empty.
326 explicit SmallVectorImpl(unsigned N)
327 : SmallVectorTemplateBase<T>(N) {}
328
329public:
330 SmallVectorImpl(const SmallVectorImpl &) = delete;
331
332 ~SmallVectorImpl() {
333 // Subclass has already destructed this vector's elements.
334 // If this wasn't grown from the inline copy, deallocate the old space.
335 if (!this->isSmall())
336 free(this->begin());
337 }
338
339 void clear() {
340 this->destroy_range(this->begin(), this->end());
341 this->Size = 0;
342 }
343
344 void resize(size_type N) {
345 if (N < this->size()) {
346 this->destroy_range(this->begin()+N, this->end());
347 this->set_size(N);
348 } else if (N > this->size()) {
349 if (this->capacity() < N)
350 this->grow(N);
351 for (auto I = this->end(), E = this->begin() + N; I != E; ++I)
352 new (&*I) T();
353 this->set_size(N);
354 }
355 }
356
357 void resize(size_type N, const T &NV) {
358 if (N < this->size()) {
359 this->destroy_range(this->begin()+N, this->end());
360 this->set_size(N);
361 } else if (N > this->size()) {
362 if (this->capacity() < N)
363 this->grow(N);
364 std::uninitialized_fill(this->end(), this->begin()+N, NV);
365 this->set_size(N);
366 }
367 }
368
369 void reserve(size_type N) {
370 if (this->capacity() < N)
371 this->grow(N);
372 }
373
374 LLVM_NODISCARD[[clang::warn_unused_result]] T pop_back_val() {
375 T Result = ::std::move(this->back());
376 this->pop_back();
377 return Result;
378 }
379
380 void swap(SmallVectorImpl &RHS);
381
382 /// Add the specified range to the end of the SmallVector.
383 template <typename in_iter,
384 typename = std::enable_if_t<std::is_convertible<
385 typename std::iterator_traits<in_iter>::iterator_category,
386 std::input_iterator_tag>::value>>
387 void append(in_iter in_start, in_iter in_end) {
388 size_type NumInputs = std::distance(in_start, in_end);
389 if (NumInputs > this->capacity() - this->size())
390 this->grow(this->size()+NumInputs);
391
392 this->uninitialized_copy(in_start, in_end, this->end());
393 this->set_size(this->size() + NumInputs);
394 }
395
396 /// Append \p NumInputs copies of \p Elt to the end.
397 void append(size_type NumInputs, const T &Elt) {
398 if (NumInputs > this->capacity() - this->size())
399 this->grow(this->size()+NumInputs);
400
401 std::uninitialized_fill_n(this->end(), NumInputs, Elt);
402 this->set_size(this->size() + NumInputs);
403 }
404
405 void append(std::initializer_list<T> IL) {
406 append(IL.begin(), IL.end());
407 }
408
409 // FIXME: Consider assigning over existing elements, rather than clearing &
410 // re-initializing them - for all assign(...) variants.
411
412 void assign(size_type NumElts, const T &Elt) {
413 clear();
414 if (this->capacity() < NumElts)
415 this->grow(NumElts);
416 this->set_size(NumElts);
417 std::uninitialized_fill(this->begin(), this->end(), Elt);
418 }
419
420 template <typename in_iter,
421 typename = std::enable_if_t<std::is_convertible<
422 typename std::iterator_traits<in_iter>::iterator_category,
423 std::input_iterator_tag>::value>>
424 void assign(in_iter in_start, in_iter in_end) {
425 clear();
426 append(in_start, in_end);
427 }
428
429 void assign(std::initializer_list<T> IL) {
430 clear();
431 append(IL);
432 }
433
434 iterator erase(const_iterator CI) {
435 // Just cast away constness because this is a non-const member function.
436 iterator I = const_cast<iterator>(CI);
437
438 assert(I >= this->begin() && "Iterator to erase is out of bounds.")((I >= this->begin() && "Iterator to erase is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("I >= this->begin() && \"Iterator to erase is out of bounds.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h"
, 438, __PRETTY_FUNCTION__))
;
439 assert(I < this->end() && "Erasing at past-the-end iterator.")((I < this->end() && "Erasing at past-the-end iterator."
) ? static_cast<void> (0) : __assert_fail ("I < this->end() && \"Erasing at past-the-end iterator.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h"
, 439, __PRETTY_FUNCTION__))
;
440
441 iterator N = I;
442 // Shift all elts down one.
443 std::move(I+1, this->end(), I);
444 // Drop the last elt.
445 this->pop_back();
446 return(N);
447 }
448
449 iterator erase(const_iterator CS, const_iterator CE) {
450 // Just cast away constness because this is a non-const member function.
451 iterator S = const_cast<iterator>(CS);
452 iterator E = const_cast<iterator>(CE);
453
454 assert(S >= this->begin() && "Range to erase is out of bounds.")((S >= this->begin() && "Range to erase is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("S >= this->begin() && \"Range to erase is out of bounds.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h"
, 454, __PRETTY_FUNCTION__))
;
455 assert(S <= E && "Trying to erase invalid range.")((S <= E && "Trying to erase invalid range.") ? static_cast
<void> (0) : __assert_fail ("S <= E && \"Trying to erase invalid range.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h"
, 455, __PRETTY_FUNCTION__))
;
456 assert(E <= this->end() && "Trying to erase past the end.")((E <= this->end() && "Trying to erase past the end."
) ? static_cast<void> (0) : __assert_fail ("E <= this->end() && \"Trying to erase past the end.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h"
, 456, __PRETTY_FUNCTION__))
;
457
458 iterator N = S;
459 // Shift all elts down.
460 iterator I = std::move(E, this->end(), S);
461 // Drop the last elts.
462 this->destroy_range(I, this->end());
463 this->set_size(I - this->begin());
464 return(N);
465 }
466
467 iterator insert(iterator I, T &&Elt) {
468 if (I == this->end()) { // Important special case for empty vector.
469 this->push_back(::std::move(Elt));
470 return this->end()-1;
471 }
472
473 assert(I >= this->begin() && "Insertion iterator is out of bounds.")((I >= this->begin() && "Insertion iterator is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("I >= this->begin() && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h"
, 473, __PRETTY_FUNCTION__))
;
474 assert(I <= this->end() && "Inserting past the end of the vector.")((I <= this->end() && "Inserting past the end of the vector."
) ? static_cast<void> (0) : __assert_fail ("I <= this->end() && \"Inserting past the end of the vector.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h"
, 474, __PRETTY_FUNCTION__))
;
475
476 if (this->size() >= this->capacity()) {
477 size_t EltNo = I-this->begin();
478 this->grow();
479 I = this->begin()+EltNo;
480 }
481
482 ::new ((void*) this->end()) T(::std::move(this->back()));
483 // Push everything else over.
484 std::move_backward(I, this->end()-1, this->end());
485 this->set_size(this->size() + 1);
486
487 // If we just moved the element we're inserting, be sure to update
488 // the reference.
489 T *EltPtr = &Elt;
490 if (I <= EltPtr && EltPtr < this->end())
491 ++EltPtr;
492
493 *I = ::std::move(*EltPtr);
494 return I;
495 }
496
497 iterator insert(iterator I, const T &Elt) {
498 if (I == this->end()) { // Important special case for empty vector.
499 this->push_back(Elt);
500 return this->end()-1;
501 }
502
503 assert(I >= this->begin() && "Insertion iterator is out of bounds.")((I >= this->begin() && "Insertion iterator is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("I >= this->begin() && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h"
, 503, __PRETTY_FUNCTION__))
;
504 assert(I <= this->end() && "Inserting past the end of the vector.")((I <= this->end() && "Inserting past the end of the vector."
) ? static_cast<void> (0) : __assert_fail ("I <= this->end() && \"Inserting past the end of the vector.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h"
, 504, __PRETTY_FUNCTION__))
;
505
506 if (this->size() >= this->capacity()) {
507 size_t EltNo = I-this->begin();
508 this->grow();
509 I = this->begin()+EltNo;
510 }
511 ::new ((void*) this->end()) T(std::move(this->back()));
512 // Push everything else over.
513 std::move_backward(I, this->end()-1, this->end());
514 this->set_size(this->size() + 1);
515
516 // If we just moved the element we're inserting, be sure to update
517 // the reference.
518 const T *EltPtr = &Elt;
519 if (I <= EltPtr && EltPtr < this->end())
520 ++EltPtr;
521
522 *I = *EltPtr;
523 return I;
524 }
525
526 iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
527 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
528 size_t InsertElt = I - this->begin();
529
530 if (I == this->end()) { // Important special case for empty vector.
531 append(NumToInsert, Elt);
532 return this->begin()+InsertElt;
533 }
534
535 assert(I >= this->begin() && "Insertion iterator is out of bounds.")((I >= this->begin() && "Insertion iterator is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("I >= this->begin() && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h"
, 535, __PRETTY_FUNCTION__))
;
536 assert(I <= this->end() && "Inserting past the end of the vector.")((I <= this->end() && "Inserting past the end of the vector."
) ? static_cast<void> (0) : __assert_fail ("I <= this->end() && \"Inserting past the end of the vector.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h"
, 536, __PRETTY_FUNCTION__))
;
537
538 // Ensure there is enough space.
539 reserve(this->size() + NumToInsert);
540
541 // Uninvalidate the iterator.
542 I = this->begin()+InsertElt;
543
544 // If there are more elements between the insertion point and the end of the
545 // range than there are being inserted, we can use a simple approach to
546 // insertion. Since we already reserved space, we know that this won't
547 // reallocate the vector.
548 if (size_t(this->end()-I) >= NumToInsert) {
549 T *OldEnd = this->end();
550 append(std::move_iterator<iterator>(this->end() - NumToInsert),
551 std::move_iterator<iterator>(this->end()));
552
553 // Copy the existing elements that get replaced.
554 std::move_backward(I, OldEnd-NumToInsert, OldEnd);
555
556 std::fill_n(I, NumToInsert, Elt);
557 return I;
558 }
559
560 // Otherwise, we're inserting more elements than exist already, and we're
561 // not inserting at the end.
562
563 // Move over the elements that we're about to overwrite.
564 T *OldEnd = this->end();
565 this->set_size(this->size() + NumToInsert);
566 size_t NumOverwritten = OldEnd-I;
567 this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
568
569 // Replace the overwritten part.
570 std::fill_n(I, NumOverwritten, Elt);
571
572 // Insert the non-overwritten middle part.
573 std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
574 return I;
575 }
576
577 template <typename ItTy,
578 typename = std::enable_if_t<std::is_convertible<
579 typename std::iterator_traits<ItTy>::iterator_category,
580 std::input_iterator_tag>::value>>
581 iterator insert(iterator I, ItTy From, ItTy To) {
582 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
583 size_t InsertElt = I - this->begin();
584
585 if (I == this->end()) { // Important special case for empty vector.
586 append(From, To);
587 return this->begin()+InsertElt;
588 }
589
590 assert(I >= this->begin() && "Insertion iterator is out of bounds.")((I >= this->begin() && "Insertion iterator is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("I >= this->begin() && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h"
, 590, __PRETTY_FUNCTION__))
;
591 assert(I <= this->end() && "Inserting past the end of the vector.")((I <= this->end() && "Inserting past the end of the vector."
) ? static_cast<void> (0) : __assert_fail ("I <= this->end() && \"Inserting past the end of the vector.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/SmallVector.h"
, 591, __PRETTY_FUNCTION__))
;
592
593 size_t NumToInsert = std::distance(From, To);
594
595 // Ensure there is enough space.
596 reserve(this->size() + NumToInsert);
597
598 // Uninvalidate the iterator.
599 I = this->begin()+InsertElt;
600
601 // If there are more elements between the insertion point and the end of the
602 // range than there are being inserted, we can use a simple approach to
603 // insertion. Since we already reserved space, we know that this won't
604 // reallocate the vector.
605 if (size_t(this->end()-I) >= NumToInsert) {
606 T *OldEnd = this->end();
607 append(std::move_iterator<iterator>(this->end() - NumToInsert),
608 std::move_iterator<iterator>(this->end()));
609
610 // Copy the existing elements that get replaced.
611 std::move_backward(I, OldEnd-NumToInsert, OldEnd);
612
613 std::copy(From, To, I);
614 return I;
615 }
616
617 // Otherwise, we're inserting more elements than exist already, and we're
618 // not inserting at the end.
619
620 // Move over the elements that we're about to overwrite.
621 T *OldEnd = this->end();
622 this->set_size(this->size() + NumToInsert);
623 size_t NumOverwritten = OldEnd-I;
624 this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
625
626 // Replace the overwritten part.
627 for (T *J = I; NumOverwritten > 0; --NumOverwritten) {
628 *J = *From;
629 ++J; ++From;
630 }
631
632 // Insert the non-overwritten middle part.
633 this->uninitialized_copy(From, To, OldEnd);
634 return I;
635 }
636
637 void insert(iterator I, std::initializer_list<T> IL) {
638 insert(I, IL.begin(), IL.end());
639 }
640
641 template <typename... ArgTypes> reference emplace_back(ArgTypes &&... Args) {
642 if (LLVM_UNLIKELY(this->size() >= this->capacity())__builtin_expect((bool)(this->size() >= this->capacity
()), false)
)
643 this->grow();
644 ::new ((void *)this->end()) T(std::forward<ArgTypes>(Args)...);
645 this->set_size(this->size() + 1);
646 return this->back();
647 }
648
649 SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
650
651 SmallVectorImpl &operator=(SmallVectorImpl &&RHS);
652
653 bool operator==(const SmallVectorImpl &RHS) const {
654 if (this->size() != RHS.size()) return false;
655 return std::equal(this->begin(), this->end(), RHS.begin());
656 }
657 bool operator!=(const SmallVectorImpl &RHS) const {
658 return !(*this == RHS);
659 }
660
661 bool operator<(const SmallVectorImpl &RHS) const {
662 return std::lexicographical_compare(this->begin(), this->end(),
663 RHS.begin(), RHS.end());
664 }
665};
666
667template <typename T>
668void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
669 if (this == &RHS) return;
670
671 // We can only avoid copying elements if neither vector is small.
672 if (!this->isSmall() && !RHS.isSmall()) {
673 std::swap(this->BeginX, RHS.BeginX);
674 std::swap(this->Size, RHS.Size);
675 std::swap(this->Capacity, RHS.Capacity);
676 return;
677 }
678 if (RHS.size() > this->capacity())
679 this->grow(RHS.size());
680 if (this->size() > RHS.capacity())
681 RHS.grow(this->size());
682
683 // Swap the shared elements.
684 size_t NumShared = this->size();
685 if (NumShared > RHS.size()) NumShared = RHS.size();
686 for (size_type i = 0; i != NumShared; ++i)
687 std::swap((*this)[i], RHS[i]);
688
689 // Copy over the extra elts.
690 if (this->size() > RHS.size()) {
691 size_t EltDiff = this->size() - RHS.size();
692 this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end());
693 RHS.set_size(RHS.size() + EltDiff);
694 this->destroy_range(this->begin()+NumShared, this->end());
695 this->set_size(NumShared);
696 } else if (RHS.size() > this->size()) {
697 size_t EltDiff = RHS.size() - this->size();
698 this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end());
699 this->set_size(this->size() + EltDiff);
700 this->destroy_range(RHS.begin()+NumShared, RHS.end());
701 RHS.set_size(NumShared);
702 }
703}
704
705template <typename T>
706SmallVectorImpl<T> &SmallVectorImpl<T>::
707 operator=(const SmallVectorImpl<T> &RHS) {
708 // Avoid self-assignment.
709 if (this == &RHS) return *this;
710
711 // If we already have sufficient space, assign the common elements, then
712 // destroy any excess.
713 size_t RHSSize = RHS.size();
714 size_t CurSize = this->size();
715 if (CurSize >= RHSSize) {
716 // Assign common elements.
717 iterator NewEnd;
718 if (RHSSize)
719 NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin());
720 else
721 NewEnd = this->begin();
722
723 // Destroy excess elements.
724 this->destroy_range(NewEnd, this->end());
725
726 // Trim.
727 this->set_size(RHSSize);
728 return *this;
729 }
730
731 // If we have to grow to have enough elements, destroy the current elements.
732 // This allows us to avoid copying them during the grow.
733 // FIXME: don't do this if they're efficiently moveable.
734 if (this->capacity() < RHSSize) {
735 // Destroy current elements.
736 this->destroy_range(this->begin(), this->end());
737 this->set_size(0);
738 CurSize = 0;
739 this->grow(RHSSize);
740 } else if (CurSize) {
741 // Otherwise, use assignment for the already-constructed elements.
742 std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin());
743 }
744
745 // Copy construct the new elements in place.
746 this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(),
747 this->begin()+CurSize);
748
749 // Set end.
750 this->set_size(RHSSize);
751 return *this;
752}
753
754template <typename T>
755SmallVectorImpl<T> &SmallVectorImpl<T>::operator=(SmallVectorImpl<T> &&RHS) {
756 // Avoid self-assignment.
757 if (this == &RHS) return *this;
758
759 // If the RHS isn't small, clear this vector and then steal its buffer.
760 if (!RHS.isSmall()) {
761 this->destroy_range(this->begin(), this->end());
762 if (!this->isSmall()) free(this->begin());
763 this->BeginX = RHS.BeginX;
764 this->Size = RHS.Size;
765 this->Capacity = RHS.Capacity;
766 RHS.resetToSmall();
767 return *this;
768 }
769
770 // If we already have sufficient space, assign the common elements, then
771 // destroy any excess.
772 size_t RHSSize = RHS.size();
773 size_t CurSize = this->size();
774 if (CurSize >= RHSSize) {
775 // Assign common elements.
776 iterator NewEnd = this->begin();
777 if (RHSSize)
778 NewEnd = std::move(RHS.begin(), RHS.end(), NewEnd);
779
780 // Destroy excess elements and trim the bounds.
781 this->destroy_range(NewEnd, this->end());
782 this->set_size(RHSSize);
783
784 // Clear the RHS.
785 RHS.clear();
786
787 return *this;
788 }
789
790 // If we have to grow to have enough elements, destroy the current elements.
791 // This allows us to avoid copying them during the grow.
792 // FIXME: this may not actually make any sense if we can efficiently move
793 // elements.
794 if (this->capacity() < RHSSize) {
795 // Destroy current elements.
796 this->destroy_range(this->begin(), this->end());
797 this->set_size(0);
798 CurSize = 0;
799 this->grow(RHSSize);
800 } else if (CurSize) {
801 // Otherwise, use assignment for the already-constructed elements.
802 std::move(RHS.begin(), RHS.begin()+CurSize, this->begin());
803 }
804
805 // Move-construct the new elements in place.
806 this->uninitialized_move(RHS.begin()+CurSize, RHS.end(),
807 this->begin()+CurSize);
808
809 // Set end.
810 this->set_size(RHSSize);
811
812 RHS.clear();
813 return *this;
814}
815
816/// Storage for the SmallVector elements. This is specialized for the N=0 case
817/// to avoid allocating unnecessary storage.
818template <typename T, unsigned N>
819struct SmallVectorStorage {
820 AlignedCharArrayUnion<T> InlineElts[N];
821};
822
823/// We need the storage to be properly aligned even for small-size of 0 so that
824/// the pointer math in \a SmallVectorTemplateCommon::getFirstEl() is
825/// well-defined.
826template <typename T> struct alignas(alignof(T)) SmallVectorStorage<T, 0> {};
827
828/// This is a 'vector' (really, a variable-sized array), optimized
829/// for the case when the array is small. It contains some number of elements
830/// in-place, which allows it to avoid heap allocation when the actual number of
831/// elements is below that threshold. This allows normal "small" cases to be
832/// fast without losing generality for large inputs.
833///
834/// Note that this does not attempt to be exception safe.
835///
836template <typename T, unsigned N>
837class SmallVector : public SmallVectorImpl<T>, SmallVectorStorage<T, N> {
838public:
839 SmallVector() : SmallVectorImpl<T>(N) {}
840
841 ~SmallVector() {
842 // Destroy the constructed elements in the vector.
843 this->destroy_range(this->begin(), this->end());
844 }
845
846 explicit SmallVector(size_t Size, const T &Value = T())
847 : SmallVectorImpl<T>(N) {
848 this->assign(Size, Value);
849 }
850
851 template <typename ItTy,
852 typename = std::enable_if_t<std::is_convertible<
853 typename std::iterator_traits<ItTy>::iterator_category,
854 std::input_iterator_tag>::value>>
855 SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(N) {
856 this->append(S, E);
857 }
858
859 template <typename RangeTy>
860 explicit SmallVector(const iterator_range<RangeTy> &R)
861 : SmallVectorImpl<T>(N) {
862 this->append(R.begin(), R.end());
863 }
864
865 SmallVector(std::initializer_list<T> IL) : SmallVectorImpl<T>(N) {
866 this->assign(IL);
867 }
868
869 SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(N) {
870 if (!RHS.empty())
871 SmallVectorImpl<T>::operator=(RHS);
872 }
873
874 const SmallVector &operator=(const SmallVector &RHS) {
875 SmallVectorImpl<T>::operator=(RHS);
876 return *this;
877 }
878
879 SmallVector(SmallVector &&RHS) : SmallVectorImpl<T>(N) {
880 if (!RHS.empty())
881 SmallVectorImpl<T>::operator=(::std::move(RHS));
882 }
883
884 SmallVector(SmallVectorImpl<T> &&RHS) : SmallVectorImpl<T>(N) {
885 if (!RHS.empty())
886 SmallVectorImpl<T>::operator=(::std::move(RHS));
887 }
888
889 const SmallVector &operator=(SmallVector &&RHS) {
890 SmallVectorImpl<T>::operator=(::std::move(RHS));
891 return *this;
892 }
893
894 const SmallVector &operator=(SmallVectorImpl<T> &&RHS) {
895 SmallVectorImpl<T>::operator=(::std::move(RHS));
896 return *this;
897 }
898
899 const SmallVector &operator=(std::initializer_list<T> IL) {
900 this->assign(IL);
901 return *this;
902 }
903};
904
905template <typename T, unsigned N>
906inline size_t capacity_in_bytes(const SmallVector<T, N> &X) {
907 return X.capacity_in_bytes();
908}
909
910/// Given a range of type R, iterate the entire range and return a
911/// SmallVector with elements of the vector. This is useful, for example,
912/// when you want to iterate a range and then sort the results.
913template <unsigned Size, typename R>
914SmallVector<typename std::remove_const<typename std::remove_reference<
915 decltype(*std::begin(std::declval<R &>()))>::type>::type,
916 Size>
917to_vector(R &&Range) {
918 return {std::begin(Range), std::end(Range)};
919}
920
921} // end namespace llvm
922
923namespace std {
924
925 /// Implement std::swap in terms of SmallVector swap.
926 template<typename T>
927 inline void
928 swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
929 LHS.swap(RHS);
930 }
931
932 /// Implement std::swap in terms of SmallVector swap.
933 template<typename T, unsigned N>
934 inline void
935 swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
936 LHS.swap(RHS);
937 }
938
939} // end namespace std
940
941#endif // LLVM_ADT_SMALLVECTOR_H