Bug Summary

File:llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp
Warning:line 1478, column 28
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name MemCpyOptimizer.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 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/lib/Transforms/Scalar -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/lib/Transforms/Scalar -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-06-13-111025-38230-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp

/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp

1//===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
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 pass performs various transformations related to eliminating memcpy
10// calls, or transforming sets of stores into memset's.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
15#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/ADT/iterator_range.h"
21#include "llvm/Analysis/AliasAnalysis.h"
22#include "llvm/Analysis/AssumptionCache.h"
23#include "llvm/Analysis/GlobalsModRef.h"
24#include "llvm/Analysis/Loads.h"
25#include "llvm/Analysis/MemoryDependenceAnalysis.h"
26#include "llvm/Analysis/MemoryLocation.h"
27#include "llvm/Analysis/MemorySSA.h"
28#include "llvm/Analysis/MemorySSAUpdater.h"
29#include "llvm/Analysis/TargetLibraryInfo.h"
30#include "llvm/Analysis/ValueTracking.h"
31#include "llvm/IR/Argument.h"
32#include "llvm/IR/BasicBlock.h"
33#include "llvm/IR/Constants.h"
34#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/DerivedTypes.h"
36#include "llvm/IR/Dominators.h"
37#include "llvm/IR/Function.h"
38#include "llvm/IR/GetElementPtrTypeIterator.h"
39#include "llvm/IR/GlobalVariable.h"
40#include "llvm/IR/IRBuilder.h"
41#include "llvm/IR/InstrTypes.h"
42#include "llvm/IR/Instruction.h"
43#include "llvm/IR/Instructions.h"
44#include "llvm/IR/IntrinsicInst.h"
45#include "llvm/IR/Intrinsics.h"
46#include "llvm/IR/LLVMContext.h"
47#include "llvm/IR/Module.h"
48#include "llvm/IR/Operator.h"
49#include "llvm/IR/PassManager.h"
50#include "llvm/IR/Type.h"
51#include "llvm/IR/User.h"
52#include "llvm/IR/Value.h"
53#include "llvm/InitializePasses.h"
54#include "llvm/Pass.h"
55#include "llvm/Support/Casting.h"
56#include "llvm/Support/Debug.h"
57#include "llvm/Support/MathExtras.h"
58#include "llvm/Support/raw_ostream.h"
59#include "llvm/Transforms/Scalar.h"
60#include "llvm/Transforms/Utils/Local.h"
61#include <algorithm>
62#include <cassert>
63#include <cstdint>
64#include <utility>
65
66using namespace llvm;
67
68#define DEBUG_TYPE"memcpyopt" "memcpyopt"
69
70static cl::opt<bool>
71 EnableMemorySSA("enable-memcpyopt-memoryssa", cl::init(true), cl::Hidden,
72 cl::desc("Use MemorySSA-backed MemCpyOpt."));
73
74STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted")static llvm::Statistic NumMemCpyInstr = {"memcpyopt", "NumMemCpyInstr"
, "Number of memcpy instructions deleted"}
;
75STATISTIC(NumMemSetInfer, "Number of memsets inferred")static llvm::Statistic NumMemSetInfer = {"memcpyopt", "NumMemSetInfer"
, "Number of memsets inferred"}
;
76STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy")static llvm::Statistic NumMoveToCpy = {"memcpyopt", "NumMoveToCpy"
, "Number of memmoves converted to memcpy"}
;
77STATISTIC(NumCpyToSet, "Number of memcpys converted to memset")static llvm::Statistic NumCpyToSet = {"memcpyopt", "NumCpyToSet"
, "Number of memcpys converted to memset"}
;
78STATISTIC(NumCallSlot, "Number of call slot optimizations performed")static llvm::Statistic NumCallSlot = {"memcpyopt", "NumCallSlot"
, "Number of call slot optimizations performed"}
;
79
80namespace {
81
82/// Represents a range of memset'd bytes with the ByteVal value.
83/// This allows us to analyze stores like:
84/// store 0 -> P+1
85/// store 0 -> P+0
86/// store 0 -> P+3
87/// store 0 -> P+2
88/// which sometimes happens with stores to arrays of structs etc. When we see
89/// the first store, we make a range [1, 2). The second store extends the range
90/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
91/// two ranges into [0, 3) which is memset'able.
92struct MemsetRange {
93 // Start/End - A semi range that describes the span that this range covers.
94 // The range is closed at the start and open at the end: [Start, End).
95 int64_t Start, End;
96
97 /// StartPtr - The getelementptr instruction that points to the start of the
98 /// range.
99 Value *StartPtr;
100
101 /// Alignment - The known alignment of the first store.
102 unsigned Alignment;
103
104 /// TheStores - The actual stores that make up this range.
105 SmallVector<Instruction*, 16> TheStores;
106
107 bool isProfitableToUseMemset(const DataLayout &DL) const;
108};
109
110} // end anonymous namespace
111
112bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const {
113 // If we found more than 4 stores to merge or 16 bytes, use memset.
114 if (TheStores.size() >= 4 || End-Start >= 16) return true;
115
116 // If there is nothing to merge, don't do anything.
117 if (TheStores.size() < 2) return false;
118
119 // If any of the stores are a memset, then it is always good to extend the
120 // memset.
121 for (Instruction *SI : TheStores)
122 if (!isa<StoreInst>(SI))
123 return true;
124
125 // Assume that the code generator is capable of merging pairs of stores
126 // together if it wants to.
127 if (TheStores.size() == 2) return false;
128
129 // If we have fewer than 8 stores, it can still be worthwhile to do this.
130 // For example, merging 4 i8 stores into an i32 store is useful almost always.
131 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
132 // memset will be split into 2 32-bit stores anyway) and doing so can
133 // pessimize the llvm optimizer.
134 //
135 // Since we don't have perfect knowledge here, make some assumptions: assume
136 // the maximum GPR width is the same size as the largest legal integer
137 // size. If so, check to see whether we will end up actually reducing the
138 // number of stores used.
139 unsigned Bytes = unsigned(End-Start);
140 unsigned MaxIntSize = DL.getLargestLegalIntTypeSizeInBits() / 8;
141 if (MaxIntSize == 0)
142 MaxIntSize = 1;
143 unsigned NumPointerStores = Bytes / MaxIntSize;
144
145 // Assume the remaining bytes if any are done a byte at a time.
146 unsigned NumByteStores = Bytes % MaxIntSize;
147
148 // If we will reduce the # stores (according to this heuristic), do the
149 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
150 // etc.
151 return TheStores.size() > NumPointerStores+NumByteStores;
152}
153
154namespace {
155
156class MemsetRanges {
157 using range_iterator = SmallVectorImpl<MemsetRange>::iterator;
158
159 /// A sorted list of the memset ranges.
160 SmallVector<MemsetRange, 8> Ranges;
161
162 const DataLayout &DL;
163
164public:
165 MemsetRanges(const DataLayout &DL) : DL(DL) {}
166
167 using const_iterator = SmallVectorImpl<MemsetRange>::const_iterator;
168
169 const_iterator begin() const { return Ranges.begin(); }
170 const_iterator end() const { return Ranges.end(); }
171 bool empty() const { return Ranges.empty(); }
172
173 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
174 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
175 addStore(OffsetFromFirst, SI);
176 else
177 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
178 }
179
180 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
181 int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
182
183 addRange(OffsetFromFirst, StoreSize, SI->getPointerOperand(),
184 SI->getAlign().value(), SI);
185 }
186
187 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
188 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
189 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getDestAlignment(), MSI);
190 }
191
192 void addRange(int64_t Start, int64_t Size, Value *Ptr,
193 unsigned Alignment, Instruction *Inst);
194};
195
196} // end anonymous namespace
197
198/// Add a new store to the MemsetRanges data structure. This adds a
199/// new range for the specified store at the specified offset, merging into
200/// existing ranges as appropriate.
201void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
202 unsigned Alignment, Instruction *Inst) {
203 int64_t End = Start+Size;
204
205 range_iterator I = partition_point(
206 Ranges, [=](const MemsetRange &O) { return O.End < Start; });
207
208 // We now know that I == E, in which case we didn't find anything to merge
209 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
210 // to insert a new range. Handle this now.
211 if (I == Ranges.end() || End < I->Start) {
212 MemsetRange &R = *Ranges.insert(I, MemsetRange());
213 R.Start = Start;
214 R.End = End;
215 R.StartPtr = Ptr;
216 R.Alignment = Alignment;
217 R.TheStores.push_back(Inst);
218 return;
219 }
220
221 // This store overlaps with I, add it.
222 I->TheStores.push_back(Inst);
223
224 // At this point, we may have an interval that completely contains our store.
225 // If so, just add it to the interval and return.
226 if (I->Start <= Start && I->End >= End)
227 return;
228
229 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
230 // but is not entirely contained within the range.
231
232 // See if the range extends the start of the range. In this case, it couldn't
233 // possibly cause it to join the prior range, because otherwise we would have
234 // stopped on *it*.
235 if (Start < I->Start) {
236 I->Start = Start;
237 I->StartPtr = Ptr;
238 I->Alignment = Alignment;
239 }
240
241 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
242 // is in or right at the end of I), and that End >= I->Start. Extend I out to
243 // End.
244 if (End > I->End) {
245 I->End = End;
246 range_iterator NextI = I;
247 while (++NextI != Ranges.end() && End >= NextI->Start) {
248 // Merge the range in.
249 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
250 if (NextI->End > I->End)
251 I->End = NextI->End;
252 Ranges.erase(NextI);
253 NextI = I;
254 }
255 }
256}
257
258//===----------------------------------------------------------------------===//
259// MemCpyOptLegacyPass Pass
260//===----------------------------------------------------------------------===//
261
262namespace {
263
264class MemCpyOptLegacyPass : public FunctionPass {
265 MemCpyOptPass Impl;
266
267public:
268 static char ID; // Pass identification, replacement for typeid
269
270 MemCpyOptLegacyPass() : FunctionPass(ID) {
271 initializeMemCpyOptLegacyPassPass(*PassRegistry::getPassRegistry());
272 }
273
274 bool runOnFunction(Function &F) override;
275
276private:
277 // This transformation requires dominator postdominator info
278 void getAnalysisUsage(AnalysisUsage &AU) const override {
279 AU.setPreservesCFG();
280 AU.addRequired<AssumptionCacheTracker>();
281 AU.addRequired<DominatorTreeWrapperPass>();
282 AU.addPreserved<DominatorTreeWrapperPass>();
283 AU.addPreserved<GlobalsAAWrapperPass>();
284 AU.addRequired<TargetLibraryInfoWrapperPass>();
285 if (!EnableMemorySSA)
286 AU.addRequired<MemoryDependenceWrapperPass>();
287 AU.addPreserved<MemoryDependenceWrapperPass>();
288 AU.addRequired<AAResultsWrapperPass>();
289 AU.addPreserved<AAResultsWrapperPass>();
290 if (EnableMemorySSA)
291 AU.addRequired<MemorySSAWrapperPass>();
292 AU.addPreserved<MemorySSAWrapperPass>();
293 }
294};
295
296} // end anonymous namespace
297
298char MemCpyOptLegacyPass::ID = 0;
299
300/// The public interface to this file...
301FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOptLegacyPass(); }
302
303INITIALIZE_PASS_BEGIN(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",static void *initializeMemCpyOptLegacyPassPassOnce(PassRegistry
&Registry) {
304 false, false)static void *initializeMemCpyOptLegacyPassPassOnce(PassRegistry
&Registry) {
305INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry);
306INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)initializeDominatorTreeWrapperPassPass(Registry);
307INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)initializeMemoryDependenceWrapperPassPass(Registry);
308INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
309INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)initializeAAResultsWrapperPassPass(Registry);
310INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)initializeGlobalsAAWrapperPassPass(Registry);
311INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)initializeMemorySSAWrapperPassPass(Registry);
312INITIALIZE_PASS_END(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",PassInfo *PI = new PassInfo( "MemCpy Optimization", "memcpyopt"
, &MemCpyOptLegacyPass::ID, PassInfo::NormalCtor_t(callDefaultCtor
<MemCpyOptLegacyPass>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeMemCpyOptLegacyPassPassFlag
; void llvm::initializeMemCpyOptLegacyPassPass(PassRegistry &
Registry) { llvm::call_once(InitializeMemCpyOptLegacyPassPassFlag
, initializeMemCpyOptLegacyPassPassOnce, std::ref(Registry));
}
313 false, false)PassInfo *PI = new PassInfo( "MemCpy Optimization", "memcpyopt"
, &MemCpyOptLegacyPass::ID, PassInfo::NormalCtor_t(callDefaultCtor
<MemCpyOptLegacyPass>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeMemCpyOptLegacyPassPassFlag
; void llvm::initializeMemCpyOptLegacyPassPass(PassRegistry &
Registry) { llvm::call_once(InitializeMemCpyOptLegacyPassPassFlag
, initializeMemCpyOptLegacyPassPassOnce, std::ref(Registry));
}
314
315// Check that V is either not accessible by the caller, or unwinding cannot
316// occur between Start and End.
317static bool mayBeVisibleThroughUnwinding(Value *V, Instruction *Start,
318 Instruction *End) {
319 assert(Start->getParent() == End->getParent() && "Must be in same block")(static_cast <bool> (Start->getParent() == End->getParent
() && "Must be in same block") ? void (0) : __assert_fail
("Start->getParent() == End->getParent() && \"Must be in same block\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp"
, 319, __extension__ __PRETTY_FUNCTION__))
;
320 if (!Start->getFunction()->doesNotThrow() &&
321 !isa<AllocaInst>(getUnderlyingObject(V))) {
322 for (const Instruction &I :
323 make_range(Start->getIterator(), End->getIterator())) {
324 if (I.mayThrow())
325 return true;
326 }
327 }
328 return false;
329}
330
331void MemCpyOptPass::eraseInstruction(Instruction *I) {
332 if (MSSAU)
333 MSSAU->removeMemoryAccess(I);
334 if (MD)
335 MD->removeInstruction(I);
336 I->eraseFromParent();
337}
338
339// Check for mod or ref of Loc between Start and End, excluding both boundaries.
340// Start and End must be in the same block
341static bool accessedBetween(AliasAnalysis &AA, MemoryLocation Loc,
342 const MemoryUseOrDef *Start,
343 const MemoryUseOrDef *End) {
344 assert(Start->getBlock() == End->getBlock() && "Only local supported")(static_cast <bool> (Start->getBlock() == End->getBlock
() && "Only local supported") ? void (0) : __assert_fail
("Start->getBlock() == End->getBlock() && \"Only local supported\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp"
, 344, __extension__ __PRETTY_FUNCTION__))
;
345 for (const MemoryAccess &MA :
346 make_range(++Start->getIterator(), End->getIterator())) {
347 if (isModOrRefSet(AA.getModRefInfo(cast<MemoryUseOrDef>(MA).getMemoryInst(),
348 Loc)))
349 return true;
350 }
351 return false;
352}
353
354// Check for mod of Loc between Start and End, excluding both boundaries.
355// Start and End can be in different blocks.
356static bool writtenBetween(MemorySSA *MSSA, MemoryLocation Loc,
357 const MemoryUseOrDef *Start,
358 const MemoryUseOrDef *End) {
359 // TODO: Only walk until we hit Start.
360 MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
361 End->getDefiningAccess(), Loc);
362 return !MSSA->dominates(Clobber, Start);
363}
364
365/// When scanning forward over instructions, we look for some other patterns to
366/// fold away. In particular, this looks for stores to neighboring locations of
367/// memory. If it sees enough consecutive ones, it attempts to merge them
368/// together into a memcpy/memset.
369Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst,
370 Value *StartPtr,
371 Value *ByteVal) {
372 const DataLayout &DL = StartInst->getModule()->getDataLayout();
373
374 // Okay, so we now have a single store that can be splatable. Scan to find
375 // all subsequent stores of the same value to offset from the same pointer.
376 // Join these together into ranges, so we can decide whether contiguous blocks
377 // are stored.
378 MemsetRanges Ranges(DL);
379
380 BasicBlock::iterator BI(StartInst);
381
382 // Keeps track of the last memory use or def before the insertion point for
383 // the new memset. The new MemoryDef for the inserted memsets will be inserted
384 // after MemInsertPoint. It points to either LastMemDef or to the last user
385 // before the insertion point of the memset, if there are any such users.
386 MemoryUseOrDef *MemInsertPoint = nullptr;
387 // Keeps track of the last MemoryDef between StartInst and the insertion point
388 // for the new memset. This will become the defining access of the inserted
389 // memsets.
390 MemoryDef *LastMemDef = nullptr;
391 for (++BI; !BI->isTerminator(); ++BI) {
392 if (MSSAU) {
393 auto *CurrentAcc = cast_or_null<MemoryUseOrDef>(
394 MSSAU->getMemorySSA()->getMemoryAccess(&*BI));
395 if (CurrentAcc) {
396 MemInsertPoint = CurrentAcc;
397 if (auto *CurrentDef = dyn_cast<MemoryDef>(CurrentAcc))
398 LastMemDef = CurrentDef;
399 }
400 }
401
402 // Calls that only access inaccessible memory do not block merging
403 // accessible stores.
404 if (auto *CB = dyn_cast<CallBase>(BI)) {
405 if (CB->onlyAccessesInaccessibleMemory())
406 continue;
407 }
408
409 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
410 // If the instruction is readnone, ignore it, otherwise bail out. We
411 // don't even allow readonly here because we don't want something like:
412 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
413 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
414 break;
415 continue;
416 }
417
418 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
419 // If this is a store, see if we can merge it in.
420 if (!NextStore->isSimple()) break;
421
422 Value *StoredVal = NextStore->getValueOperand();
423
424 // Don't convert stores of non-integral pointer types to memsets (which
425 // stores integers).
426 if (DL.isNonIntegralPointerType(StoredVal->getType()->getScalarType()))
427 break;
428
429 // Check to see if this stored value is of the same byte-splattable value.
430 Value *StoredByte = isBytewiseValue(StoredVal, DL);
431 if (isa<UndefValue>(ByteVal) && StoredByte)
432 ByteVal = StoredByte;
433 if (ByteVal != StoredByte)
434 break;
435
436 // Check to see if this store is to a constant offset from the start ptr.
437 Optional<int64_t> Offset =
438 isPointerOffset(StartPtr, NextStore->getPointerOperand(), DL);
439 if (!Offset)
440 break;
441
442 Ranges.addStore(*Offset, NextStore);
443 } else {
444 MemSetInst *MSI = cast<MemSetInst>(BI);
445
446 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
447 !isa<ConstantInt>(MSI->getLength()))
448 break;
449
450 // Check to see if this store is to a constant offset from the start ptr.
451 Optional<int64_t> Offset = isPointerOffset(StartPtr, MSI->getDest(), DL);
452 if (!Offset)
453 break;
454
455 Ranges.addMemSet(*Offset, MSI);
456 }
457 }
458
459 // If we have no ranges, then we just had a single store with nothing that
460 // could be merged in. This is a very common case of course.
461 if (Ranges.empty())
462 return nullptr;
463
464 // If we had at least one store that could be merged in, add the starting
465 // store as well. We try to avoid this unless there is at least something
466 // interesting as a small compile-time optimization.
467 Ranges.addInst(0, StartInst);
468
469 // If we create any memsets, we put it right before the first instruction that
470 // isn't part of the memset block. This ensure that the memset is dominated
471 // by any addressing instruction needed by the start of the block.
472 IRBuilder<> Builder(&*BI);
473
474 // Now that we have full information about ranges, loop over the ranges and
475 // emit memset's for anything big enough to be worthwhile.
476 Instruction *AMemSet = nullptr;
477 for (const MemsetRange &Range : Ranges) {
478 if (Range.TheStores.size() == 1) continue;
479
480 // If it is profitable to lower this range to memset, do so now.
481 if (!Range.isProfitableToUseMemset(DL))
482 continue;
483
484 // Otherwise, we do want to transform this! Create a new memset.
485 // Get the starting pointer of the block.
486 StartPtr = Range.StartPtr;
487
488 AMemSet = Builder.CreateMemSet(StartPtr, ByteVal, Range.End - Range.Start,
489 MaybeAlign(Range.Alignment));
490 LLVM_DEBUG(dbgs() << "Replace stores:\n"; for (Instruction *SIdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Replace stores:\n"; for (Instruction
*SI : Range.TheStores) dbgs() << *SI << '\n'; dbgs
() << "With: " << *AMemSet << '\n'; } } while
(false)
491 : Range.TheStores) dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Replace stores:\n"; for (Instruction
*SI : Range.TheStores) dbgs() << *SI << '\n'; dbgs
() << "With: " << *AMemSet << '\n'; } } while
(false)
492 << *SI << '\n';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Replace stores:\n"; for (Instruction
*SI : Range.TheStores) dbgs() << *SI << '\n'; dbgs
() << "With: " << *AMemSet << '\n'; } } while
(false)
493 dbgs() << "With: " << *AMemSet << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Replace stores:\n"; for (Instruction
*SI : Range.TheStores) dbgs() << *SI << '\n'; dbgs
() << "With: " << *AMemSet << '\n'; } } while
(false)
;
494 if (!Range.TheStores.empty())
495 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
496
497 if (MSSAU) {
498 assert(LastMemDef && MemInsertPoint &&(static_cast <bool> (LastMemDef && MemInsertPoint
&& "Both LastMemDef and MemInsertPoint need to be set"
) ? void (0) : __assert_fail ("LastMemDef && MemInsertPoint && \"Both LastMemDef and MemInsertPoint need to be set\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp"
, 499, __extension__ __PRETTY_FUNCTION__))
499 "Both LastMemDef and MemInsertPoint need to be set")(static_cast <bool> (LastMemDef && MemInsertPoint
&& "Both LastMemDef and MemInsertPoint need to be set"
) ? void (0) : __assert_fail ("LastMemDef && MemInsertPoint && \"Both LastMemDef and MemInsertPoint need to be set\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp"
, 499, __extension__ __PRETTY_FUNCTION__))
;
500 auto *NewDef =
501 cast<MemoryDef>(MemInsertPoint->getMemoryInst() == &*BI
502 ? MSSAU->createMemoryAccessBefore(
503 AMemSet, LastMemDef, MemInsertPoint)
504 : MSSAU->createMemoryAccessAfter(
505 AMemSet, LastMemDef, MemInsertPoint));
506 MSSAU->insertDef(NewDef, /*RenameUses=*/true);
507 LastMemDef = NewDef;
508 MemInsertPoint = NewDef;
509 }
510
511 // Zap all the stores.
512 for (Instruction *SI : Range.TheStores)
513 eraseInstruction(SI);
514
515 ++NumMemSetInfer;
516 }
517
518 return AMemSet;
519}
520
521// This method try to lift a store instruction before position P.
522// It will lift the store and its argument + that anything that
523// may alias with these.
524// The method returns true if it was successful.
525bool MemCpyOptPass::moveUp(StoreInst *SI, Instruction *P, const LoadInst *LI) {
526 // If the store alias this position, early bail out.
527 MemoryLocation StoreLoc = MemoryLocation::get(SI);
528 if (isModOrRefSet(AA->getModRefInfo(P, StoreLoc)))
529 return false;
530
531 // Keep track of the arguments of all instruction we plan to lift
532 // so we can make sure to lift them as well if appropriate.
533 DenseSet<Instruction*> Args;
534 if (auto *Ptr = dyn_cast<Instruction>(SI->getPointerOperand()))
535 if (Ptr->getParent() == SI->getParent())
536 Args.insert(Ptr);
537
538 // Instruction to lift before P.
539 SmallVector<Instruction *, 8> ToLift{SI};
540
541 // Memory locations of lifted instructions.
542 SmallVector<MemoryLocation, 8> MemLocs{StoreLoc};
543
544 // Lifted calls.
545 SmallVector<const CallBase *, 8> Calls;
546
547 const MemoryLocation LoadLoc = MemoryLocation::get(LI);
548
549 for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) {
550 auto *C = &*I;
551
552 // Make sure hoisting does not perform a store that was not guaranteed to
553 // happen.
554 if (!isGuaranteedToTransferExecutionToSuccessor(C))
555 return false;
556
557 bool MayAlias = isModOrRefSet(AA->getModRefInfo(C, None));
558
559 bool NeedLift = false;
560 if (Args.erase(C))
561 NeedLift = true;
562 else if (MayAlias) {
563 NeedLift = llvm::any_of(MemLocs, [C, this](const MemoryLocation &ML) {
564 return isModOrRefSet(AA->getModRefInfo(C, ML));
565 });
566
567 if (!NeedLift)
568 NeedLift = llvm::any_of(Calls, [C, this](const CallBase *Call) {
569 return isModOrRefSet(AA->getModRefInfo(C, Call));
570 });
571 }
572
573 if (!NeedLift)
574 continue;
575
576 if (MayAlias) {
577 // Since LI is implicitly moved downwards past the lifted instructions,
578 // none of them may modify its source.
579 if (isModSet(AA->getModRefInfo(C, LoadLoc)))
580 return false;
581 else if (const auto *Call = dyn_cast<CallBase>(C)) {
582 // If we can't lift this before P, it's game over.
583 if (isModOrRefSet(AA->getModRefInfo(P, Call)))
584 return false;
585
586 Calls.push_back(Call);
587 } else if (isa<LoadInst>(C) || isa<StoreInst>(C) || isa<VAArgInst>(C)) {
588 // If we can't lift this before P, it's game over.
589 auto ML = MemoryLocation::get(C);
590 if (isModOrRefSet(AA->getModRefInfo(P, ML)))
591 return false;
592
593 MemLocs.push_back(ML);
594 } else
595 // We don't know how to lift this instruction.
596 return false;
597 }
598
599 ToLift.push_back(C);
600 for (unsigned k = 0, e = C->getNumOperands(); k != e; ++k)
601 if (auto *A = dyn_cast<Instruction>(C->getOperand(k))) {
602 if (A->getParent() == SI->getParent()) {
603 // Cannot hoist user of P above P
604 if(A == P) return false;
605 Args.insert(A);
606 }
607 }
608 }
609
610 // Find MSSA insertion point. Normally P will always have a corresponding
611 // memory access before which we can insert. However, with non-standard AA
612 // pipelines, there may be a mismatch between AA and MSSA, in which case we
613 // will scan for a memory access before P. In either case, we know for sure
614 // that at least the load will have a memory access.
615 // TODO: Simplify this once P will be determined by MSSA, in which case the
616 // discrepancy can no longer occur.
617 MemoryUseOrDef *MemInsertPoint = nullptr;
618 if (MSSAU) {
619 if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(P)) {
620 MemInsertPoint = cast<MemoryUseOrDef>(--MA->getIterator());
621 } else {
622 const Instruction *ConstP = P;
623 for (const Instruction &I : make_range(++ConstP->getReverseIterator(),
624 ++LI->getReverseIterator())) {
625 if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(&I)) {
626 MemInsertPoint = MA;
627 break;
628 }
629 }
630 }
631 }
632
633 // We made it, we need to lift.
634 for (auto *I : llvm::reverse(ToLift)) {
635 LLVM_DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Lifting " << *I <<
" before " << *P << "\n"; } } while (false)
;
636 I->moveBefore(P);
637 if (MSSAU) {
638 assert(MemInsertPoint && "Must have found insert point")(static_cast <bool> (MemInsertPoint && "Must have found insert point"
) ? void (0) : __assert_fail ("MemInsertPoint && \"Must have found insert point\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp"
, 638, __extension__ __PRETTY_FUNCTION__))
;
639 if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(I)) {
640 MSSAU->moveAfter(MA, MemInsertPoint);
641 MemInsertPoint = MA;
642 }
643 }
644 }
645
646 return true;
647}
648
649bool MemCpyOptPass::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
650 if (!SI->isSimple()) return false;
651
652 // Avoid merging nontemporal stores since the resulting
653 // memcpy/memset would not be able to preserve the nontemporal hint.
654 // In theory we could teach how to propagate the !nontemporal metadata to
655 // memset calls. However, that change would force the backend to
656 // conservatively expand !nontemporal memset calls back to sequences of
657 // store instructions (effectively undoing the merging).
658 if (SI->getMetadata(LLVMContext::MD_nontemporal))
659 return false;
660
661 const DataLayout &DL = SI->getModule()->getDataLayout();
662
663 Value *StoredVal = SI->getValueOperand();
664
665 // Not all the transforms below are correct for non-integral pointers, bail
666 // until we've audited the individual pieces.
667 if (DL.isNonIntegralPointerType(StoredVal->getType()->getScalarType()))
668 return false;
669
670 // Load to store forwarding can be interpreted as memcpy.
671 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
672 if (LI->isSimple() && LI->hasOneUse() &&
673 LI->getParent() == SI->getParent()) {
674
675 auto *T = LI->getType();
676 if (T->isAggregateType()) {
677 MemoryLocation LoadLoc = MemoryLocation::get(LI);
678
679 // We use alias analysis to check if an instruction may store to
680 // the memory we load from in between the load and the store. If
681 // such an instruction is found, we try to promote there instead
682 // of at the store position.
683 // TODO: Can use MSSA for this.
684 Instruction *P = SI;
685 for (auto &I : make_range(++LI->getIterator(), SI->getIterator())) {
686 if (isModSet(AA->getModRefInfo(&I, LoadLoc))) {
687 P = &I;
688 break;
689 }
690 }
691
692 // We found an instruction that may write to the loaded memory.
693 // We can try to promote at this position instead of the store
694 // position if nothing alias the store memory after this and the store
695 // destination is not in the range.
696 if (P && P != SI) {
697 if (!moveUp(SI, P, LI))
698 P = nullptr;
699 }
700
701 // If a valid insertion position is found, then we can promote
702 // the load/store pair to a memcpy.
703 if (P) {
704 // If we load from memory that may alias the memory we store to,
705 // memmove must be used to preserve semantic. If not, memcpy can
706 // be used.
707 bool UseMemMove = false;
708 if (!AA->isNoAlias(MemoryLocation::get(SI), LoadLoc))
709 UseMemMove = true;
710
711 uint64_t Size = DL.getTypeStoreSize(T);
712
713 IRBuilder<> Builder(P);
714 Instruction *M;
715 if (UseMemMove)
716 M = Builder.CreateMemMove(
717 SI->getPointerOperand(), SI->getAlign(),
718 LI->getPointerOperand(), LI->getAlign(), Size);
719 else
720 M = Builder.CreateMemCpy(
721 SI->getPointerOperand(), SI->getAlign(),
722 LI->getPointerOperand(), LI->getAlign(), Size);
723
724 LLVM_DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI << " => "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Promoting " << *LI <<
" to " << *SI << " => " << *M << "\n"
; } } while (false)
725 << *M << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Promoting " << *LI <<
" to " << *SI << " => " << *M << "\n"
; } } while (false)
;
726
727 if (MSSAU) {
728 auto *LastDef =
729 cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI));
730 auto *NewAccess =
731 MSSAU->createMemoryAccessAfter(M, LastDef, LastDef);
732 MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
733 }
734
735 eraseInstruction(SI);
736 eraseInstruction(LI);
737 ++NumMemCpyInstr;
738
739 // Make sure we do not invalidate the iterator.
740 BBI = M->getIterator();
741 return true;
742 }
743 }
744
745 // Detect cases where we're performing call slot forwarding, but
746 // happen to be using a load-store pair to implement it, rather than
747 // a memcpy.
748 CallInst *C = nullptr;
749 if (EnableMemorySSA) {
750 if (auto *LoadClobber = dyn_cast<MemoryUseOrDef>(
751 MSSA->getWalker()->getClobberingMemoryAccess(LI))) {
752 // The load most post-dom the call. Limit to the same block for now.
753 // TODO: Support non-local call-slot optimization?
754 if (LoadClobber->getBlock() == SI->getParent())
755 C = dyn_cast_or_null<CallInst>(LoadClobber->getMemoryInst());
756 }
757 } else {
758 MemDepResult ldep = MD->getDependency(LI);
759 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
760 C = dyn_cast<CallInst>(ldep.getInst());
761 }
762
763 if (C) {
764 // Check that nothing touches the dest of the "copy" between
765 // the call and the store.
766 MemoryLocation StoreLoc = MemoryLocation::get(SI);
767 if (EnableMemorySSA) {
768 if (accessedBetween(*AA, StoreLoc, MSSA->getMemoryAccess(C),
769 MSSA->getMemoryAccess(SI)))
770 C = nullptr;
771 } else {
772 for (BasicBlock::iterator I = --SI->getIterator(),
773 E = C->getIterator();
774 I != E; --I) {
775 if (isModOrRefSet(AA->getModRefInfo(&*I, StoreLoc))) {
776 C = nullptr;
777 break;
778 }
779 }
780 }
781 }
782
783 if (C) {
784 bool changed = performCallSlotOptzn(
785 LI, SI, SI->getPointerOperand()->stripPointerCasts(),
786 LI->getPointerOperand()->stripPointerCasts(),
787 DL.getTypeStoreSize(SI->getOperand(0)->getType()),
788 commonAlignment(SI->getAlign(), LI->getAlign()), C);
789 if (changed) {
790 eraseInstruction(SI);
791 eraseInstruction(LI);
792 ++NumMemCpyInstr;
793 return true;
794 }
795 }
796 }
797 }
798
799 // There are two cases that are interesting for this code to handle: memcpy
800 // and memset. Right now we only handle memset.
801
802 // Ensure that the value being stored is something that can be memset'able a
803 // byte at a time like "0" or "-1" or any width, as well as things like
804 // 0xA0A0A0A0 and 0.0.
805 auto *V = SI->getOperand(0);
806 if (Value *ByteVal = isBytewiseValue(V, DL)) {
807 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
808 ByteVal)) {
809 BBI = I->getIterator(); // Don't invalidate iterator.
810 return true;
811 }
812
813 // If we have an aggregate, we try to promote it to memset regardless
814 // of opportunity for merging as it can expose optimization opportunities
815 // in subsequent passes.
816 auto *T = V->getType();
817 if (T->isAggregateType()) {
818 uint64_t Size = DL.getTypeStoreSize(T);
819 IRBuilder<> Builder(SI);
820 auto *M = Builder.CreateMemSet(SI->getPointerOperand(), ByteVal, Size,
821 SI->getAlign());
822
823 LLVM_DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Promoting " << *SI <<
" to " << *M << "\n"; } } while (false)
;
824
825 if (MSSAU) {
826 assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI)))(static_cast <bool> (isa<MemoryDef>(MSSAU->getMemorySSA
()->getMemoryAccess(SI))) ? void (0) : __assert_fail ("isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI))"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp"
, 826, __extension__ __PRETTY_FUNCTION__))
;
827 auto *LastDef =
828 cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI));
829 auto *NewAccess = MSSAU->createMemoryAccessAfter(M, LastDef, LastDef);
830 MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
831 }
832
833 eraseInstruction(SI);
834 NumMemSetInfer++;
835
836 // Make sure we do not invalidate the iterator.
837 BBI = M->getIterator();
838 return true;
839 }
840 }
841
842 return false;
843}
844
845bool MemCpyOptPass::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
846 // See if there is another memset or store neighboring this memset which
847 // allows us to widen out the memset to do a single larger store.
848 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
849 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
850 MSI->getValue())) {
851 BBI = I->getIterator(); // Don't invalidate iterator.
852 return true;
853 }
854 return false;
855}
856
857/// Takes a memcpy and a call that it depends on,
858/// and checks for the possibility of a call slot optimization by having
859/// the call write its result directly into the destination of the memcpy.
860bool MemCpyOptPass::performCallSlotOptzn(Instruction *cpyLoad,
861 Instruction *cpyStore, Value *cpyDest,
862 Value *cpySrc, uint64_t cpyLen,
863 Align cpyAlign, CallInst *C) {
864 // The general transformation to keep in mind is
865 //
866 // call @func(..., src, ...)
867 // memcpy(dest, src, ...)
868 //
869 // ->
870 //
871 // memcpy(dest, src, ...)
872 // call @func(..., dest, ...)
873 //
874 // Since moving the memcpy is technically awkward, we additionally check that
875 // src only holds uninitialized values at the moment of the call, meaning that
876 // the memcpy can be discarded rather than moved.
877
878 // Lifetime marks shouldn't be operated on.
879 if (Function *F = C->getCalledFunction())
880 if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::lifetime_start)
881 return false;
882
883 // Require that src be an alloca. This simplifies the reasoning considerably.
884 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
885 if (!srcAlloca)
886 return false;
887
888 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
889 if (!srcArraySize)
890 return false;
891
892 const DataLayout &DL = cpyLoad->getModule()->getDataLayout();
893 uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
894 srcArraySize->getZExtValue();
895
896 if (cpyLen < srcSize)
897 return false;
898
899 // Check that accessing the first srcSize bytes of dest will not cause a
900 // trap. Otherwise the transform is invalid since it might cause a trap
901 // to occur earlier than it otherwise would.
902 if (!isDereferenceableAndAlignedPointer(cpyDest, Align(1), APInt(64, cpyLen),
903 DL, C, DT))
904 return false;
905
906 // Make sure that nothing can observe cpyDest being written early. There are
907 // a number of cases to consider:
908 // 1. cpyDest cannot be accessed between C and cpyStore as a precondition of
909 // the transform.
910 // 2. C itself may not access cpyDest (prior to the transform). This is
911 // checked further below.
912 // 3. If cpyDest is accessible to the caller of this function (potentially
913 // captured and not based on an alloca), we need to ensure that we cannot
914 // unwind between C and cpyStore. This is checked here.
915 // 4. If cpyDest is potentially captured, there may be accesses to it from
916 // another thread. In this case, we need to check that cpyStore is
917 // guaranteed to be executed if C is. As it is a non-atomic access, it
918 // renders accesses from other threads undefined.
919 // TODO: This is currently not checked.
920 if (mayBeVisibleThroughUnwinding(cpyDest, C, cpyStore))
921 return false;
922
923 // Check that dest points to memory that is at least as aligned as src.
924 Align srcAlign = srcAlloca->getAlign();
925 bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
926 // If dest is not aligned enough and we can't increase its alignment then
927 // bail out.
928 if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
929 return false;
930
931 // Check that src is not accessed except via the call and the memcpy. This
932 // guarantees that it holds only undefined values when passed in (so the final
933 // memcpy can be dropped), that it is not read or written between the call and
934 // the memcpy, and that writing beyond the end of it is undefined.
935 SmallVector<User *, 8> srcUseList(srcAlloca->users());
936 while (!srcUseList.empty()) {
937 User *U = srcUseList.pop_back_val();
938
939 if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
940 append_range(srcUseList, U->users());
941 continue;
942 }
943 if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
944 if (!G->hasAllZeroIndices())
945 return false;
946
947 append_range(srcUseList, U->users());
948 continue;
949 }
950 if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
951 if (IT->isLifetimeStartOrEnd())
952 continue;
953
954 if (U != C && U != cpyLoad)
955 return false;
956 }
957
958 // Check that src isn't captured by the called function since the
959 // transformation can cause aliasing issues in that case.
960 for (unsigned ArgI = 0, E = C->arg_size(); ArgI != E; ++ArgI)
961 if (C->getArgOperand(ArgI) == cpySrc && !C->doesNotCapture(ArgI))
962 return false;
963
964 // Since we're changing the parameter to the callsite, we need to make sure
965 // that what would be the new parameter dominates the callsite.
966 if (!DT->dominates(cpyDest, C)) {
967 // Support moving a constant index GEP before the call.
968 auto *GEP = dyn_cast<GetElementPtrInst>(cpyDest);
969 if (GEP && GEP->hasAllConstantIndices() &&
970 DT->dominates(GEP->getPointerOperand(), C))
971 GEP->moveBefore(C);
972 else
973 return false;
974 }
975
976 // In addition to knowing that the call does not access src in some
977 // unexpected manner, for example via a global, which we deduce from
978 // the use analysis, we also need to know that it does not sneakily
979 // access dest. We rely on AA to figure this out for us.
980 ModRefInfo MR = AA->getModRefInfo(C, cpyDest, LocationSize::precise(srcSize));
981 // If necessary, perform additional analysis.
982 if (isModOrRefSet(MR))
983 MR = AA->callCapturesBefore(C, cpyDest, LocationSize::precise(srcSize), DT);
984 if (isModOrRefSet(MR))
985 return false;
986
987 // We can't create address space casts here because we don't know if they're
988 // safe for the target.
989 if (cpySrc->getType()->getPointerAddressSpace() !=
990 cpyDest->getType()->getPointerAddressSpace())
991 return false;
992 for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI)
993 if (C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc &&
994 cpySrc->getType()->getPointerAddressSpace() !=
995 C->getArgOperand(ArgI)->getType()->getPointerAddressSpace())
996 return false;
997
998 // All the checks have passed, so do the transformation.
999 bool changedArgument = false;
1000 for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI)
1001 if (C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc) {
1002 Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
1003 : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
1004 cpyDest->getName(), C);
1005 changedArgument = true;
1006 if (C->getArgOperand(ArgI)->getType() == Dest->getType())
1007 C->setArgOperand(ArgI, Dest);
1008 else
1009 C->setArgOperand(ArgI, CastInst::CreatePointerCast(
1010 Dest, C->getArgOperand(ArgI)->getType(),
1011 Dest->getName(), C));
1012 }
1013
1014 if (!changedArgument)
1015 return false;
1016
1017 // If the destination wasn't sufficiently aligned then increase its alignment.
1018 if (!isDestSufficientlyAligned) {
1019 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!")(static_cast <bool> (isa<AllocaInst>(cpyDest) &&
"Can only increase alloca alignment!") ? void (0) : __assert_fail
("isa<AllocaInst>(cpyDest) && \"Can only increase alloca alignment!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp"
, 1019, __extension__ __PRETTY_FUNCTION__))
;
1020 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
1021 }
1022
1023 // Drop any cached information about the call, because we may have changed
1024 // its dependence information by changing its parameter.
1025 if (MD)
1026 MD->removeInstruction(C);
1027
1028 // Update AA metadata
1029 // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
1030 // handled here, but combineMetadata doesn't support them yet
1031 unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
1032 LLVMContext::MD_noalias,
1033 LLVMContext::MD_invariant_group,
1034 LLVMContext::MD_access_group};
1035 combineMetadata(C, cpyLoad, KnownIDs, true);
1036
1037 ++NumCallSlot;
1038 return true;
1039}
1040
1041/// We've found that the (upward scanning) memory dependence of memcpy 'M' is
1042/// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can.
1043bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M,
1044 MemCpyInst *MDep) {
1045 // We can only transforms memcpy's where the dest of one is the source of the
1046 // other.
1047 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
1048 return false;
1049
1050 // If dep instruction is reading from our current input, then it is a noop
1051 // transfer and substituting the input won't change this instruction. Just
1052 // ignore the input and let someone else zap MDep. This handles cases like:
1053 // memcpy(a <- a)
1054 // memcpy(b <- a)
1055 if (M->getSource() == MDep->getSource())
1056 return false;
1057
1058 // Second, the length of the memcpy's must be the same, or the preceding one
1059 // must be larger than the following one.
1060 if (MDep->getLength() != M->getLength()) {
1061 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
1062 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
1063 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
1064 return false;
1065 }
1066
1067 // Verify that the copied-from memory doesn't change in between the two
1068 // transfers. For example, in:
1069 // memcpy(a <- b)
1070 // *b = 42;
1071 // memcpy(c <- a)
1072 // It would be invalid to transform the second memcpy into memcpy(c <- b).
1073 //
1074 // TODO: If the code between M and MDep is transparent to the destination "c",
1075 // then we could still perform the xform by moving M up to the first memcpy.
1076 if (EnableMemorySSA) {
1077 // TODO: It would be sufficient to check the MDep source up to the memcpy
1078 // size of M, rather than MDep.
1079 if (writtenBetween(MSSA, MemoryLocation::getForSource(MDep),
1080 MSSA->getMemoryAccess(MDep), MSSA->getMemoryAccess(M)))
1081 return false;
1082 } else {
1083 // NOTE: This is conservative, it will stop on any read from the source loc,
1084 // not just the defining memcpy.
1085 MemDepResult SourceDep =
1086 MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false,
1087 M->getIterator(), M->getParent());
1088 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1089 return false;
1090 }
1091
1092 // If the dest of the second might alias the source of the first, then the
1093 // source and dest might overlap. We still want to eliminate the intermediate
1094 // value, but we have to generate a memmove instead of memcpy.
1095 bool UseMemMove = false;
1096 if (!AA->isNoAlias(MemoryLocation::getForDest(M),
1097 MemoryLocation::getForSource(MDep)))
1098 UseMemMove = true;
1099
1100 // If all checks passed, then we can transform M.
1101 LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy->memcpy src:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "MemCpyOptPass: Forwarding memcpy->memcpy src:\n"
<< *MDep << '\n' << *M << '\n'; } } while
(false)
1102 << *MDep << '\n' << *M << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "MemCpyOptPass: Forwarding memcpy->memcpy src:\n"
<< *MDep << '\n' << *M << '\n'; } } while
(false)
;
1103
1104 // TODO: Is this worth it if we're creating a less aligned memcpy? For
1105 // example we could be moving from movaps -> movq on x86.
1106 IRBuilder<> Builder(M);
1107 Instruction *NewM;
1108 if (UseMemMove)
1109 NewM = Builder.CreateMemMove(M->getRawDest(), M->getDestAlign(),
1110 MDep->getRawSource(), MDep->getSourceAlign(),
1111 M->getLength(), M->isVolatile());
1112 else
1113 NewM = Builder.CreateMemCpy(M->getRawDest(), M->getDestAlign(),
1114 MDep->getRawSource(), MDep->getSourceAlign(),
1115 M->getLength(), M->isVolatile());
1116
1117 if (MSSAU) {
1118 assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M)))(static_cast <bool> (isa<MemoryDef>(MSSAU->getMemorySSA
()->getMemoryAccess(M))) ? void (0) : __assert_fail ("isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M))"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp"
, 1118, __extension__ __PRETTY_FUNCTION__))
;
1119 auto *LastDef = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M));
1120 auto *NewAccess = MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
1121 MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
1122 }
1123
1124 // Remove the instruction we're replacing.
1125 eraseInstruction(M);
1126 ++NumMemCpyInstr;
1127 return true;
1128}
1129
1130/// We've found that the (upward scanning) memory dependence of \p MemCpy is
1131/// \p MemSet. Try to simplify \p MemSet to only set the trailing bytes that
1132/// weren't copied over by \p MemCpy.
1133///
1134/// In other words, transform:
1135/// \code
1136/// memset(dst, c, dst_size);
1137/// memcpy(dst, src, src_size);
1138/// \endcode
1139/// into:
1140/// \code
1141/// memcpy(dst, src, src_size);
1142/// memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
1143/// \endcode
1144bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
1145 MemSetInst *MemSet) {
1146 // We can only transform memset/memcpy with the same destination.
1147 if (!AA->isMustAlias(MemSet->getDest(), MemCpy->getDest()))
1148 return false;
1149
1150 // Check that src and dst of the memcpy aren't the same. While memcpy
1151 // operands cannot partially overlap, exact equality is allowed.
1152 if (!AA->isNoAlias(MemoryLocation(MemCpy->getSource(),
1153 LocationSize::precise(1)),
1154 MemoryLocation(MemCpy->getDest(),
1155 LocationSize::precise(1))))
1156 return false;
1157
1158 if (EnableMemorySSA) {
1159 // We know that dst up to src_size is not written. We now need to make sure
1160 // that dst up to dst_size is not accessed. (If we did not move the memset,
1161 // checking for reads would be sufficient.)
1162 if (accessedBetween(*AA, MemoryLocation::getForDest(MemSet),
1163 MSSA->getMemoryAccess(MemSet),
1164 MSSA->getMemoryAccess(MemCpy))) {
1165 return false;
1166 }
1167 } else {
1168 // We have already checked that dst up to src_size is not accessed. We
1169 // need to make sure that there are no accesses up to dst_size either.
1170 MemDepResult DstDepInfo = MD->getPointerDependencyFrom(
1171 MemoryLocation::getForDest(MemSet), false, MemCpy->getIterator(),
1172 MemCpy->getParent());
1173 if (DstDepInfo.getInst() != MemSet)
1174 return false;
1175 }
1176
1177 // Use the same i8* dest as the memcpy, killing the memset dest if different.
1178 Value *Dest = MemCpy->getRawDest();
1179 Value *DestSize = MemSet->getLength();
1180 Value *SrcSize = MemCpy->getLength();
1181
1182 if (mayBeVisibleThroughUnwinding(Dest, MemSet, MemCpy))
1183 return false;
1184
1185 // If the sizes are the same, simply drop the memset instead of generating
1186 // a replacement with zero size.
1187 if (DestSize == SrcSize) {
1188 eraseInstruction(MemSet);
1189 return true;
1190 }
1191
1192 // By default, create an unaligned memset.
1193 unsigned Align = 1;
1194 // If Dest is aligned, and SrcSize is constant, use the minimum alignment
1195 // of the sum.
1196 const unsigned DestAlign =
1197 std::max(MemSet->getDestAlignment(), MemCpy->getDestAlignment());
1198 if (DestAlign > 1)
1199 if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
1200 Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign);
1201
1202 IRBuilder<> Builder(MemCpy);
1203
1204 // If the sizes have different types, zext the smaller one.
1205 if (DestSize->getType() != SrcSize->getType()) {
1206 if (DestSize->getType()->getIntegerBitWidth() >
1207 SrcSize->getType()->getIntegerBitWidth())
1208 SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
1209 else
1210 DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
1211 }
1212
1213 Value *Ule = Builder.CreateICmpULE(DestSize, SrcSize);
1214 Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize);
1215 Value *MemsetLen = Builder.CreateSelect(
1216 Ule, ConstantInt::getNullValue(DestSize->getType()), SizeDiff);
1217 Instruction *NewMemSet = Builder.CreateMemSet(
1218 Builder.CreateGEP(Dest->getType()->getPointerElementType(), Dest,
1219 SrcSize),
1220 MemSet->getOperand(1), MemsetLen, MaybeAlign(Align));
1221
1222 if (MSSAU) {
1223 assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy)) &&(static_cast <bool> (isa<MemoryDef>(MSSAU->getMemorySSA
()->getMemoryAccess(MemCpy)) && "MemCpy must be a MemoryDef"
) ? void (0) : __assert_fail ("isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy)) && \"MemCpy must be a MemoryDef\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp"
, 1224, __extension__ __PRETTY_FUNCTION__))
1224 "MemCpy must be a MemoryDef")(static_cast <bool> (isa<MemoryDef>(MSSAU->getMemorySSA
()->getMemoryAccess(MemCpy)) && "MemCpy must be a MemoryDef"
) ? void (0) : __assert_fail ("isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy)) && \"MemCpy must be a MemoryDef\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp"
, 1224, __extension__ __PRETTY_FUNCTION__))
;
1225 // The new memset is inserted after the memcpy, but it is known that its
1226 // defining access is the memset about to be removed which immediately
1227 // precedes the memcpy.
1228 auto *LastDef =
1229 cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy));
1230 auto *NewAccess = MSSAU->createMemoryAccessBefore(
1231 NewMemSet, LastDef->getDefiningAccess(), LastDef);
1232 MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
1233 }
1234
1235 eraseInstruction(MemSet);
1236 return true;
1237}
1238
1239/// Determine whether the instruction has undefined content for the given Size,
1240/// either because it was freshly alloca'd or started its lifetime.
1241static bool hasUndefContents(Instruction *I, Value *Size) {
1242 if (isa<AllocaInst>(I))
1243 return true;
1244
1245 if (ConstantInt *CSize = dyn_cast<ConstantInt>(Size)) {
1246 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1247 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1248 if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
1249 if (LTSize->getZExtValue() >= CSize->getZExtValue())
1250 return true;
1251 }
1252
1253 return false;
1254}
1255
1256static bool hasUndefContentsMSSA(MemorySSA *MSSA, AliasAnalysis *AA, Value *V,
1257 MemoryDef *Def, Value *Size) {
1258 if (MSSA->isLiveOnEntryDef(Def))
1259 return isa<AllocaInst>(getUnderlyingObject(V));
1260
1261 if (IntrinsicInst *II =
1262 dyn_cast_or_null<IntrinsicInst>(Def->getMemoryInst())) {
1263 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
1264 ConstantInt *LTSize = cast<ConstantInt>(II->getArgOperand(0));
1265
1266 if (ConstantInt *CSize = dyn_cast<ConstantInt>(Size)) {
1267 if (AA->isMustAlias(V, II->getArgOperand(1)) &&
1268 LTSize->getZExtValue() >= CSize->getZExtValue())
1269 return true;
1270 }
1271
1272 // If the lifetime.start covers a whole alloca (as it almost always
1273 // does) and we're querying a pointer based on that alloca, then we know
1274 // the memory is definitely undef, regardless of how exactly we alias.
1275 // The size also doesn't matter, as an out-of-bounds access would be UB.
1276 AllocaInst *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(V));
1277 if (getUnderlyingObject(II->getArgOperand(1)) == Alloca) {
1278 const DataLayout &DL = Alloca->getModule()->getDataLayout();
1279 if (Optional<TypeSize> AllocaSize = Alloca->getAllocationSizeInBits(DL))
1280 if (*AllocaSize == LTSize->getValue() * 8)
1281 return true;
1282 }
1283 }
1284 }
1285
1286 return false;
1287}
1288
1289/// Transform memcpy to memset when its source was just memset.
1290/// In other words, turn:
1291/// \code
1292/// memset(dst1, c, dst1_size);
1293/// memcpy(dst2, dst1, dst2_size);
1294/// \endcode
1295/// into:
1296/// \code
1297/// memset(dst1, c, dst1_size);
1298/// memset(dst2, c, dst2_size);
1299/// \endcode
1300/// When dst2_size <= dst1_size.
1301bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
1302 MemSetInst *MemSet) {
1303 // Make sure that memcpy(..., memset(...), ...), that is we are memsetting and
1304 // memcpying from the same address. Otherwise it is hard to reason about.
1305 if (!AA->isMustAlias(MemSet->getRawDest(), MemCpy->getRawSource()))
1306 return false;
1307
1308 Value *MemSetSize = MemSet->getLength();
1309 Value *CopySize = MemCpy->getLength();
1310
1311 if (MemSetSize != CopySize) {
1312 // Make sure the memcpy doesn't read any more than what the memset wrote.
1313 // Don't worry about sizes larger than i64.
1314
1315 // A known memset size is required.
1316 ConstantInt *CMemSetSize = dyn_cast<ConstantInt>(MemSetSize);
1317 if (!CMemSetSize)
1318 return false;
1319
1320 // A known memcpy size is also required.
1321 ConstantInt *CCopySize = dyn_cast<ConstantInt>(CopySize);
1322 if (!CCopySize)
1323 return false;
1324 if (CCopySize->getZExtValue() > CMemSetSize->getZExtValue()) {
1325 // If the memcpy is larger than the memset, but the memory was undef prior
1326 // to the memset, we can just ignore the tail. Technically we're only
1327 // interested in the bytes from MemSetSize..CopySize here, but as we can't
1328 // easily represent this location, we use the full 0..CopySize range.
1329 MemoryLocation MemCpyLoc = MemoryLocation::getForSource(MemCpy);
1330 bool CanReduceSize = false;
1331 if (EnableMemorySSA) {
1332 MemoryUseOrDef *MemSetAccess = MSSA->getMemoryAccess(MemSet);
1333 MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
1334 MemSetAccess->getDefiningAccess(), MemCpyLoc);
1335 if (auto *MD = dyn_cast<MemoryDef>(Clobber))
1336 if (hasUndefContentsMSSA(MSSA, AA, MemCpy->getSource(), MD, CopySize))
1337 CanReduceSize = true;
1338 } else {
1339 MemDepResult DepInfo = MD->getPointerDependencyFrom(
1340 MemCpyLoc, true, MemSet->getIterator(), MemSet->getParent());
1341 if (DepInfo.isDef() && hasUndefContents(DepInfo.getInst(), CopySize))
1342 CanReduceSize = true;
1343 }
1344
1345 if (!CanReduceSize)
1346 return false;
1347 CopySize = MemSetSize;
1348 }
1349 }
1350
1351 IRBuilder<> Builder(MemCpy);
1352 Instruction *NewM =
1353 Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1),
1354 CopySize, MaybeAlign(MemCpy->getDestAlignment()));
1355 if (MSSAU) {
1356 auto *LastDef =
1357 cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy));
1358 auto *NewAccess = MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
1359 MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
1360 }
1361
1362 return true;
1363}
1364
1365/// Perform simplification of memcpy's. If we have memcpy A
1366/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
1367/// B to be a memcpy from X to Z (or potentially a memmove, depending on
1368/// circumstances). This allows later passes to remove the first memcpy
1369/// altogether.
1370bool MemCpyOptPass::processMemCpy(MemCpyInst *M, BasicBlock::iterator &BBI) {
1371 // We can only optimize non-volatile memcpy's.
1372 if (M->isVolatile()) return false;
27
Calling 'MemIntrinsic::isVolatile'
44
Returning from 'MemIntrinsic::isVolatile'
45
Taking false branch
1373
1374 // If the source and destination of the memcpy are the same, then zap it.
1375 if (M->getSource() == M->getDest()) {
46
Assuming the condition is false
47
Taking false branch
1376 ++BBI;
1377 eraseInstruction(M);
1378 return true;
1379 }
1380
1381 // If copying from a constant, try to turn the memcpy into a memset.
1382 if (GlobalVariable *GV
48.1
'GV' is null
48.1
'GV' is null
48.1
'GV' is null
48.1
'GV' is null
= dyn_cast<GlobalVariable>(M->getSource()))
48
Assuming the object is not a 'GlobalVariable'
49
Taking false branch
1383 if (GV->isConstant() && GV->hasDefinitiveInitializer())
1384 if (Value *ByteVal = isBytewiseValue(GV->getInitializer(),
1385 M->getModule()->getDataLayout())) {
1386 IRBuilder<> Builder(M);
1387 Instruction *NewM =
1388 Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
1389 MaybeAlign(M->getDestAlignment()), false);
1390 if (MSSAU) {
1391 auto *LastDef =
1392 cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M));
1393 auto *NewAccess =
1394 MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
1395 MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
1396 }
1397
1398 eraseInstruction(M);
1399 ++NumCpyToSet;
1400 return true;
1401 }
1402
1403 if (EnableMemorySSA) {
50
Assuming the condition is false
51
Taking false branch
1404 MemoryUseOrDef *MA = MSSA->getMemoryAccess(M);
1405 MemoryAccess *AnyClobber = MSSA->getWalker()->getClobberingMemoryAccess(MA);
1406 MemoryLocation DestLoc = MemoryLocation::getForDest(M);
1407 const MemoryAccess *DestClobber =
1408 MSSA->getWalker()->getClobberingMemoryAccess(AnyClobber, DestLoc);
1409
1410 // Try to turn a partially redundant memset + memcpy into
1411 // memcpy + smaller memset. We don't need the memcpy size for this.
1412 // The memcpy most post-dom the memset, so limit this to the same basic
1413 // block. A non-local generalization is likely not worthwhile.
1414 if (auto *MD = dyn_cast<MemoryDef>(DestClobber))
1415 if (auto *MDep = dyn_cast_or_null<MemSetInst>(MD->getMemoryInst()))
1416 if (DestClobber->getBlock() == M->getParent())
1417 if (processMemSetMemCpyDependence(M, MDep))
1418 return true;
1419
1420 MemoryAccess *SrcClobber = MSSA->getWalker()->getClobberingMemoryAccess(
1421 AnyClobber, MemoryLocation::getForSource(M));
1422
1423 // There are four possible optimizations we can do for memcpy:
1424 // a) memcpy-memcpy xform which exposes redundance for DSE.
1425 // b) call-memcpy xform for return slot optimization.
1426 // c) memcpy from freshly alloca'd space or space that has just started
1427 // its lifetime copies undefined data, and we can therefore eliminate
1428 // the memcpy in favor of the data that was already at the destination.
1429 // d) memcpy from a just-memset'd source can be turned into memset.
1430 if (auto *MD = dyn_cast<MemoryDef>(SrcClobber)) {
1431 if (Instruction *MI = MD->getMemoryInst()) {
1432 if (ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength())) {
1433 if (auto *C = dyn_cast<CallInst>(MI)) {
1434 // The memcpy must post-dom the call. Limit to the same block for
1435 // now. Additionally, we need to ensure that there are no accesses
1436 // to dest between the call and the memcpy. Accesses to src will be
1437 // checked by performCallSlotOptzn().
1438 // TODO: Support non-local call-slot optimization?
1439 if (C->getParent() == M->getParent() &&
1440 !accessedBetween(*AA, DestLoc, MD, MA)) {
1441 // FIXME: Can we pass in either of dest/src alignment here instead
1442 // of conservatively taking the minimum?
1443 Align Alignment = std::min(M->getDestAlign().valueOrOne(),
1444 M->getSourceAlign().valueOrOne());
1445 if (performCallSlotOptzn(M, M, M->getDest(), M->getSource(),
1446 CopySize->getZExtValue(), Alignment,
1447 C)) {
1448 LLVM_DEBUG(dbgs() << "Performed call slot optimization:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Performed call slot optimization:\n"
<< " call: " << *C << "\n" << " memcpy: "
<< *M << "\n"; } } while (false)
1449 << " call: " << *C << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Performed call slot optimization:\n"
<< " call: " << *C << "\n" << " memcpy: "
<< *M << "\n"; } } while (false)
1450 << " memcpy: " << *M << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Performed call slot optimization:\n"
<< " call: " << *C << "\n" << " memcpy: "
<< *M << "\n"; } } while (false)
;
1451 eraseInstruction(M);
1452 ++NumMemCpyInstr;
1453 return true;
1454 }
1455 }
1456 }
1457 }
1458 if (auto *MDep = dyn_cast<MemCpyInst>(MI))
1459 return processMemCpyMemCpyDependence(M, MDep);
1460 if (auto *MDep = dyn_cast<MemSetInst>(MI)) {
1461 if (performMemCpyToMemSetOptzn(M, MDep)) {
1462 LLVM_DEBUG(dbgs() << "Converted memcpy to memset\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Converted memcpy to memset\n"
; } } while (false)
;
1463 eraseInstruction(M);
1464 ++NumCpyToSet;
1465 return true;
1466 }
1467 }
1468 }
1469
1470 if (hasUndefContentsMSSA(MSSA, AA, M->getSource(), MD, M->getLength())) {
1471 LLVM_DEBUG(dbgs() << "Removed memcpy from undef\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Removed memcpy from undef\n"
; } } while (false)
;
1472 eraseInstruction(M);
1473 ++NumMemCpyInstr;
1474 return true;
1475 }
1476 }
1477 } else {
1478 MemDepResult DepInfo = MD->getDependency(M);
52
Called C++ object pointer is null
1479
1480 // Try to turn a partially redundant memset + memcpy into
1481 // memcpy + smaller memset. We don't need the memcpy size for this.
1482 if (DepInfo.isClobber())
1483 if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst()))
1484 if (processMemSetMemCpyDependence(M, MDep))
1485 return true;
1486
1487 // There are four possible optimizations we can do for memcpy:
1488 // a) memcpy-memcpy xform which exposes redundance for DSE.
1489 // b) call-memcpy xform for return slot optimization.
1490 // c) memcpy from freshly alloca'd space or space that has just started
1491 // its lifetime copies undefined data, and we can therefore eliminate
1492 // the memcpy in favor of the data that was already at the destination.
1493 // d) memcpy from a just-memset'd source can be turned into memset.
1494 if (ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength())) {
1495 if (DepInfo.isClobber()) {
1496 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
1497 // FIXME: Can we pass in either of dest/src alignment here instead
1498 // of conservatively taking the minimum?
1499 Align Alignment = std::min(M->getDestAlign().valueOrOne(),
1500 M->getSourceAlign().valueOrOne());
1501 if (performCallSlotOptzn(M, M, M->getDest(), M->getSource(),
1502 CopySize->getZExtValue(), Alignment, C)) {
1503 eraseInstruction(M);
1504 ++NumMemCpyInstr;
1505 return true;
1506 }
1507 }
1508 }
1509 }
1510
1511 MemoryLocation SrcLoc = MemoryLocation::getForSource(M);
1512 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(
1513 SrcLoc, true, M->getIterator(), M->getParent());
1514
1515 if (SrcDepInfo.isClobber()) {
1516 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
1517 return processMemCpyMemCpyDependence(M, MDep);
1518 } else if (SrcDepInfo.isDef()) {
1519 if (hasUndefContents(SrcDepInfo.getInst(), M->getLength())) {
1520 eraseInstruction(M);
1521 ++NumMemCpyInstr;
1522 return true;
1523 }
1524 }
1525
1526 if (SrcDepInfo.isClobber())
1527 if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst()))
1528 if (performMemCpyToMemSetOptzn(M, MDep)) {
1529 eraseInstruction(M);
1530 ++NumCpyToSet;
1531 return true;
1532 }
1533 }
1534
1535 return false;
1536}
1537
1538/// Transforms memmove calls to memcpy calls when the src/dst are guaranteed
1539/// not to alias.
1540bool MemCpyOptPass::processMemMove(MemMoveInst *M) {
1541 if (!TLI->has(LibFunc_memmove))
1542 return false;
1543
1544 // See if the pointers alias.
1545 if (!AA->isNoAlias(MemoryLocation::getForDest(M),
1546 MemoryLocation::getForSource(M)))
1547 return false;
1548
1549 LLVM_DEBUG(dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *Mdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: "
<< *M << "\n"; } } while (false)
1550 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: "
<< *M << "\n"; } } while (false)
;
1551
1552 // If not, then we know we can transform this.
1553 Type *ArgTys[3] = { M->getRawDest()->getType(),
1554 M->getRawSource()->getType(),
1555 M->getLength()->getType() };
1556 M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(),
1557 Intrinsic::memcpy, ArgTys));
1558
1559 // For MemorySSA nothing really changes (except that memcpy may imply stricter
1560 // aliasing guarantees).
1561
1562 // MemDep may have over conservative information about this instruction, just
1563 // conservatively flush it from the cache.
1564 if (MD)
1565 MD->removeInstruction(M);
1566
1567 ++NumMoveToCpy;
1568 return true;
1569}
1570
1571/// This is called on every byval argument in call sites.
1572bool MemCpyOptPass::processByValArgument(CallBase &CB, unsigned ArgNo) {
1573 const DataLayout &DL = CB.getCaller()->getParent()->getDataLayout();
1574 // Find out what feeds this byval argument.
1575 Value *ByValArg = CB.getArgOperand(ArgNo);
1576 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
1577 uint64_t ByValSize = DL.getTypeAllocSize(ByValTy);
1578 MemoryLocation Loc(ByValArg, LocationSize::precise(ByValSize));
1579 MemCpyInst *MDep = nullptr;
1580 if (EnableMemorySSA) {
1581 MemoryUseOrDef *CallAccess = MSSA->getMemoryAccess(&CB);
1582 if (!CallAccess)
1583 return false;
1584 MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
1585 CallAccess->getDefiningAccess(), Loc);
1586 if (auto *MD = dyn_cast<MemoryDef>(Clobber))
1587 MDep = dyn_cast_or_null<MemCpyInst>(MD->getMemoryInst());
1588 } else {
1589 MemDepResult DepInfo = MD->getPointerDependencyFrom(
1590 Loc, true, CB.getIterator(), CB.getParent());
1591 if (!DepInfo.isClobber())
1592 return false;
1593 MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
1594 }
1595
1596 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
1597 // a memcpy, see if we can byval from the source of the memcpy instead of the
1598 // result.
1599 if (!MDep || MDep->isVolatile() ||
1600 ByValArg->stripPointerCasts() != MDep->getDest())
1601 return false;
1602
1603 // The length of the memcpy must be larger or equal to the size of the byval.
1604 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
1605 if (!C1 || C1->getValue().getZExtValue() < ByValSize)
1606 return false;
1607
1608 // Get the alignment of the byval. If the call doesn't specify the alignment,
1609 // then it is some target specific value that we can't know.
1610 MaybeAlign ByValAlign = CB.getParamAlign(ArgNo);
1611 if (!ByValAlign) return false;
1612
1613 // If it is greater than the memcpy, then we check to see if we can force the
1614 // source of the memcpy to the alignment we need. If we fail, we bail out.
1615 MaybeAlign MemDepAlign = MDep->getSourceAlign();
1616 if ((!MemDepAlign || *MemDepAlign < *ByValAlign) &&
1617 getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL, &CB, AC,
1618 DT) < *ByValAlign)
1619 return false;
1620
1621 // The address space of the memcpy source must match the byval argument
1622 if (MDep->getSource()->getType()->getPointerAddressSpace() !=
1623 ByValArg->getType()->getPointerAddressSpace())
1624 return false;
1625
1626 // Verify that the copied-from memory doesn't change in between the memcpy and
1627 // the byval call.
1628 // memcpy(a <- b)
1629 // *b = 42;
1630 // foo(*a)
1631 // It would be invalid to transform the second memcpy into foo(*b).
1632 if (EnableMemorySSA) {
1633 if (writtenBetween(MSSA, MemoryLocation::getForSource(MDep),
1634 MSSA->getMemoryAccess(MDep), MSSA->getMemoryAccess(&CB)))
1635 return false;
1636 } else {
1637 // NOTE: This is conservative, it will stop on any read from the source loc,
1638 // not just the defining memcpy.
1639 MemDepResult SourceDep = MD->getPointerDependencyFrom(
1640 MemoryLocation::getForSource(MDep), false,
1641 CB.getIterator(), MDep->getParent());
1642 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1643 return false;
1644 }
1645
1646 Value *TmpCast = MDep->getSource();
1647 if (MDep->getSource()->getType() != ByValArg->getType()) {
1648 BitCastInst *TmpBitCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
1649 "tmpcast", &CB);
1650 // Set the tmpcast's DebugLoc to MDep's
1651 TmpBitCast->setDebugLoc(MDep->getDebugLoc());
1652 TmpCast = TmpBitCast;
1653 }
1654
1655 LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"
<< " " << *MDep << "\n" << " " <<
CB << "\n"; } } while (false)
1656 << " " << *MDep << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"
<< " " << *MDep << "\n" << " " <<
CB << "\n"; } } while (false)
1657 << " " << CB << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"
<< " " << *MDep << "\n" << " " <<
CB << "\n"; } } while (false)
;
1658
1659 // Otherwise we're good! Update the byval argument.
1660 CB.setArgOperand(ArgNo, TmpCast);
1661 ++NumMemCpyInstr;
1662 return true;
1663}
1664
1665/// Executes one iteration of MemCpyOptPass.
1666bool MemCpyOptPass::iterateOnFunction(Function &F) {
1667 bool MadeChange = false;
1668
1669 // Walk all instruction in the function.
1670 for (BasicBlock &BB : F) {
1671 // Skip unreachable blocks. For example processStore assumes that an
1672 // instruction in a BB can't be dominated by a later instruction in the
1673 // same BB (which is a scenario that can happen for an unreachable BB that
1674 // has itself as a predecessor).
1675 if (!DT->isReachableFromEntry(&BB))
17
Assuming the condition is false
18
Taking false branch
1676 continue;
1677
1678 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
19
Loop condition is true. Entering loop body
1679 // Avoid invalidating the iterator.
1680 Instruction *I = &*BI++;
1681
1682 bool RepeatInstruction = false;
1683
1684 if (StoreInst *SI
20.1
'SI' is null
20.1
'SI' is null
20.1
'SI' is null
20.1
'SI' is null
= dyn_cast<StoreInst>(I))
20
Assuming 'I' is not a 'StoreInst'
21
Taking false branch
1685 MadeChange |= processStore(SI, BI);
1686 else if (MemSetInst *M
22.1
'M' is null
22.1
'M' is null
22.1
'M' is null
22.1
'M' is null
= dyn_cast<MemSetInst>(I))
22
Assuming 'I' is not a 'MemSetInst'
23
Taking false branch
1687 RepeatInstruction = processMemSet(M, BI);
1688 else if (MemCpyInst *M
24.1
'M' is non-null
24.1
'M' is non-null
24.1
'M' is non-null
24.1
'M' is non-null
= dyn_cast<MemCpyInst>(I))
24
Assuming 'I' is a 'MemCpyInst'
25
Taking true branch
1689 RepeatInstruction = processMemCpy(M, BI);
26
Calling 'MemCpyOptPass::processMemCpy'
1690 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
1691 RepeatInstruction = processMemMove(M);
1692 else if (auto *CB = dyn_cast<CallBase>(I)) {
1693 for (unsigned i = 0, e = CB->arg_size(); i != e; ++i)
1694 if (CB->isByValArgument(i))
1695 MadeChange |= processByValArgument(*CB, i);
1696 }
1697
1698 // Reprocess the instruction if desired.
1699 if (RepeatInstruction) {
1700 if (BI != BB.begin())
1701 --BI;
1702 MadeChange = true;
1703 }
1704 }
1705 }
1706
1707 return MadeChange;
1708}
1709
1710PreservedAnalyses MemCpyOptPass::run(Function &F, FunctionAnalysisManager &AM) {
1711 auto *MD = !EnableMemorySSA ? &AM.getResult<MemoryDependenceAnalysis>(F)
1712 : AM.getCachedResult<MemoryDependenceAnalysis>(F);
1713 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1714 auto *AA = &AM.getResult<AAManager>(F);
1715 auto *AC = &AM.getResult<AssumptionAnalysis>(F);
1716 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
1717 auto *MSSA = EnableMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F)
1718 : AM.getCachedResult<MemorySSAAnalysis>(F);
1719
1720 bool MadeChange =
1721 runImpl(F, MD, &TLI, AA, AC, DT, MSSA ? &MSSA->getMSSA() : nullptr);
1722 if (!MadeChange)
1723 return PreservedAnalyses::all();
1724
1725 PreservedAnalyses PA;
1726 PA.preserveSet<CFGAnalyses>();
1727 if (MD)
1728 PA.preserve<MemoryDependenceAnalysis>();
1729 if (MSSA)
1730 PA.preserve<MemorySSAAnalysis>();
1731 return PA;
1732}
1733
1734bool MemCpyOptPass::runImpl(Function &F, MemoryDependenceResults *MD_,
1735 TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
1736 AssumptionCache *AC_, DominatorTree *DT_,
1737 MemorySSA *MSSA_) {
1738 bool MadeChange = false;
1739 MD = MD_;
12
Null pointer value stored to field 'MD'
1740 TLI = TLI_;
1741 AA = AA_;
1742 AC = AC_;
1743 DT = DT_;
1744 MSSA = MSSA_;
1745 MemorySSAUpdater MSSAU_(MSSA_);
1746 MSSAU = MSSA_
12.1
'MSSA_' is null
12.1
'MSSA_' is null
12.1
'MSSA_' is null
12.1
'MSSA_' is null
? &MSSAU_ : nullptr;
13
'?' condition is false
1747 // If we don't have at least memset and memcpy, there is little point of doing
1748 // anything here. These are required by a freestanding implementation, so if
1749 // even they are disabled, there is no point in trying hard.
1750 if (!TLI->has(LibFunc_memset) || !TLI->has(LibFunc_memcpy))
14
Taking false branch
1751 return false;
1752
1753 while (true) {
15
Loop condition is true. Entering loop body
1754 if (!iterateOnFunction(F))
16
Calling 'MemCpyOptPass::iterateOnFunction'
1755 break;
1756 MadeChange = true;
1757 }
1758
1759 if (MSSA_ && VerifyMemorySSA)
1760 MSSA_->verifyMemorySSA();
1761
1762 MD = nullptr;
1763 return MadeChange;
1764}
1765
1766/// This is the main transformation entry point for a function.
1767bool MemCpyOptLegacyPass::runOnFunction(Function &F) {
1768 if (skipFunction(F))
1
Assuming the condition is false
2
Taking false branch
1769 return false;
1770
1771 auto *MDWP = !EnableMemorySSA
3
Assuming the condition is false
4
'?' condition is false
1772 ? &getAnalysis<MemoryDependenceWrapperPass>()
1773 : getAnalysisIfAvailable<MemoryDependenceWrapperPass>();
1774 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1775 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1776 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1777 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1778 auto *MSSAWP = EnableMemorySSA
5
Assuming the condition is false
6
'?' condition is false
1779 ? &getAnalysis<MemorySSAWrapperPass>()
1780 : getAnalysisIfAvailable<MemorySSAWrapperPass>();
1781
1782 return Impl.runImpl(F, MDWP ? & MDWP->getMemDep() : nullptr, TLI, AA, AC, DT,
7
Assuming 'MDWP' is null
8
'?' condition is false
10
Passing null pointer value via 2nd parameter 'MD_'
11
Calling 'MemCpyOptPass::runImpl'
1783 MSSAWP
8.1
'MSSAWP' is null
8.1
'MSSAWP' is null
8.1
'MSSAWP' is null
8.1
'MSSAWP' is null
? &MSSAWP->getMSSA() : nullptr)
;
9
'?' condition is false
1784}

/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/IntrinsicInst.h

1//===-- llvm/IntrinsicInst.h - Intrinsic Instruction Wrappers ---*- 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 classes that make it really easy to deal with intrinsic
10// functions with the isa/dyncast family of functions. In particular, this
11// allows you to do things like:
12//
13// if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(Inst))
14// ... MCI->getDest() ... MCI->getSource() ...
15//
16// All intrinsic function calls are instances of the call instruction, so these
17// are all subclasses of the CallInst class. Note that none of these classes
18// has state or virtual methods, which is an important part of this gross/neat
19// hack working.
20//
21//===----------------------------------------------------------------------===//
22
23#ifndef LLVM_IR_INTRINSICINST_H
24#define LLVM_IR_INTRINSICINST_H
25
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DebugInfoMetadata.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/FPEnv.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/GlobalVariable.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/Metadata.h"
35#include "llvm/IR/Value.h"
36#include "llvm/Support/Casting.h"
37#include <cassert>
38#include <cstdint>
39
40namespace llvm {
41
42/// A wrapper class for inspecting calls to intrinsic functions.
43/// This allows the standard isa/dyncast/cast functionality to work with calls
44/// to intrinsic functions.
45class IntrinsicInst : public CallInst {
46public:
47 IntrinsicInst() = delete;
48 IntrinsicInst(const IntrinsicInst &) = delete;
49 IntrinsicInst &operator=(const IntrinsicInst &) = delete;
50
51 /// Return the intrinsic ID of this intrinsic.
52 Intrinsic::ID getIntrinsicID() const {
53 return getCalledFunction()->getIntrinsicID();
54 }
55
56 /// Return true if swapping the first two arguments to the intrinsic produces
57 /// the same result.
58 bool isCommutative() const {
59 switch (getIntrinsicID()) {
60 case Intrinsic::maxnum:
61 case Intrinsic::minnum:
62 case Intrinsic::maximum:
63 case Intrinsic::minimum:
64 case Intrinsic::smax:
65 case Intrinsic::smin:
66 case Intrinsic::umax:
67 case Intrinsic::umin:
68 case Intrinsic::sadd_sat:
69 case Intrinsic::uadd_sat:
70 case Intrinsic::sadd_with_overflow:
71 case Intrinsic::uadd_with_overflow:
72 case Intrinsic::smul_with_overflow:
73 case Intrinsic::umul_with_overflow:
74 case Intrinsic::smul_fix:
75 case Intrinsic::umul_fix:
76 case Intrinsic::smul_fix_sat:
77 case Intrinsic::umul_fix_sat:
78 case Intrinsic::fma:
79 case Intrinsic::fmuladd:
80 return true;
81 default:
82 return false;
83 }
84 }
85
86 // Checks if the intrinsic is an annotation.
87 bool isAssumeLikeIntrinsic() const {
88 switch (getIntrinsicID()) {
89 default: break;
90 case Intrinsic::assume:
91 case Intrinsic::sideeffect:
92 case Intrinsic::pseudoprobe:
93 case Intrinsic::dbg_declare:
94 case Intrinsic::dbg_value:
95 case Intrinsic::dbg_label:
96 case Intrinsic::invariant_start:
97 case Intrinsic::invariant_end:
98 case Intrinsic::lifetime_start:
99 case Intrinsic::lifetime_end:
100 case Intrinsic::experimental_noalias_scope_decl:
101 case Intrinsic::objectsize:
102 case Intrinsic::ptr_annotation:
103 case Intrinsic::var_annotation:
104 return true;
105 }
106 return false;
107 }
108
109 // Methods for support type inquiry through isa, cast, and dyn_cast:
110 static bool classof(const CallInst *I) {
111 if (const Function *CF = I->getCalledFunction())
112 return CF->isIntrinsic();
113 return false;
114 }
115 static bool classof(const Value *V) {
116 return isa<CallInst>(V) && classof(cast<CallInst>(V));
117 }
118};
119
120/// Check if \p ID corresponds to a debug info intrinsic.
121static inline bool isDbgInfoIntrinsic(Intrinsic::ID ID) {
122 switch (ID) {
123 case Intrinsic::dbg_declare:
124 case Intrinsic::dbg_value:
125 case Intrinsic::dbg_addr:
126 case Intrinsic::dbg_label:
127 return true;
128 default:
129 return false;
130 }
131}
132
133/// This is the common base class for debug info intrinsics.
134class DbgInfoIntrinsic : public IntrinsicInst {
135public:
136 /// \name Casting methods
137 /// @{
138 static bool classof(const IntrinsicInst *I) {
139 return isDbgInfoIntrinsic(I->getIntrinsicID());
140 }
141 static bool classof(const Value *V) {
142 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
143 }
144 /// @}
145};
146
147/// This is the common base class for debug info intrinsics for variables.
148class DbgVariableIntrinsic : public DbgInfoIntrinsic {
149public:
150 // Iterator for ValueAsMetadata that internally uses direct pointer iteration
151 // over either a ValueAsMetadata* or a ValueAsMetadata**, dereferencing to the
152 // ValueAsMetadata .
153 class location_op_iterator
154 : public iterator_facade_base<location_op_iterator,
155 std::bidirectional_iterator_tag, Value *> {
156 PointerUnion<ValueAsMetadata *, ValueAsMetadata **> I;
157
158 public:
159 location_op_iterator(ValueAsMetadata *SingleIter) : I(SingleIter) {}
160 location_op_iterator(ValueAsMetadata **MultiIter) : I(MultiIter) {}
161
162 location_op_iterator(const location_op_iterator &R) : I(R.I) {}
163 location_op_iterator &operator=(const location_op_iterator &R) {
164 I = R.I;
165 return *this;
166 }
167 bool operator==(const location_op_iterator &RHS) const {
168 return I == RHS.I;
169 }
170 const Value *operator*() const {
171 ValueAsMetadata *VAM = I.is<ValueAsMetadata *>()
172 ? I.get<ValueAsMetadata *>()
173 : *I.get<ValueAsMetadata **>();
174 return VAM->getValue();
175 };
176 Value *operator*() {
177 ValueAsMetadata *VAM = I.is<ValueAsMetadata *>()
178 ? I.get<ValueAsMetadata *>()
179 : *I.get<ValueAsMetadata **>();
180 return VAM->getValue();
181 }
182 location_op_iterator &operator++() {
183 if (I.is<ValueAsMetadata *>())
184 I = I.get<ValueAsMetadata *>() + 1;
185 else
186 I = I.get<ValueAsMetadata **>() + 1;
187 return *this;
188 }
189 location_op_iterator &operator--() {
190 if (I.is<ValueAsMetadata *>())
191 I = I.get<ValueAsMetadata *>() - 1;
192 else
193 I = I.get<ValueAsMetadata **>() - 1;
194 return *this;
195 }
196 };
197
198 /// Get the locations corresponding to the variable referenced by the debug
199 /// info intrinsic. Depending on the intrinsic, this could be the
200 /// variable's value or its address.
201 iterator_range<location_op_iterator> location_ops() const;
202
203 Value *getVariableLocationOp(unsigned OpIdx) const;
204
205 void replaceVariableLocationOp(Value *OldValue, Value *NewValue);
206 void replaceVariableLocationOp(unsigned OpIdx, Value *NewValue);
207
208 void setVariable(DILocalVariable *NewVar) {
209 setArgOperand(1, MetadataAsValue::get(NewVar->getContext(), NewVar));
210 }
211
212 void setExpression(DIExpression *NewExpr) {
213 setArgOperand(2, MetadataAsValue::get(NewExpr->getContext(), NewExpr));
214 }
215
216 unsigned getNumVariableLocationOps() const {
217 if (hasArgList())
218 return cast<DIArgList>(getRawLocation())->getArgs().size();
219 return 1;
220 }
221
222 bool hasArgList() const { return isa<DIArgList>(getRawLocation()); }
223
224 /// Does this describe the address of a local variable. True for dbg.addr
225 /// and dbg.declare, but not dbg.value, which describes its value.
226 bool isAddressOfVariable() const {
227 return getIntrinsicID() != Intrinsic::dbg_value;
228 }
229
230 void setUndef() {
231 // TODO: When/if we remove duplicate values from DIArgLists, we don't need
232 // this set anymore.
233 SmallPtrSet<Value *, 4> RemovedValues;
234 for (Value *OldValue : location_ops()) {
235 if (!RemovedValues.insert(OldValue).second)
236 continue;
237 Value *Undef = UndefValue::get(OldValue->getType());
238 replaceVariableLocationOp(OldValue, Undef);
239 }
240 }
241
242 bool isUndef() const {
243 return (getNumVariableLocationOps() == 0 &&
244 !getExpression()->isComplex()) ||
245 any_of(location_ops(), [](Value *V) { return isa<UndefValue>(V); });
246 }
247
248 DILocalVariable *getVariable() const {
249 return cast<DILocalVariable>(getRawVariable());
250 }
251
252 DIExpression *getExpression() const {
253 return cast<DIExpression>(getRawExpression());
254 }
255
256 Metadata *getRawLocation() const {
257 return cast<MetadataAsValue>(getArgOperand(0))->getMetadata();
258 }
259
260 Metadata *getRawVariable() const {
261 return cast<MetadataAsValue>(getArgOperand(1))->getMetadata();
262 }
263
264 Metadata *getRawExpression() const {
265 return cast<MetadataAsValue>(getArgOperand(2))->getMetadata();
266 }
267
268 /// Use of this should generally be avoided; instead,
269 /// replaceVariableLocationOp and addVariableLocationOps should be used where
270 /// possible to avoid creating invalid state.
271 void setRawLocation(Metadata *Location) {
272 return setArgOperand(0, MetadataAsValue::get(getContext(), Location));
273 }
274
275 /// Get the size (in bits) of the variable, or fragment of the variable that
276 /// is described.
277 Optional<uint64_t> getFragmentSizeInBits() const;
278
279 /// \name Casting methods
280 /// @{
281 static bool classof(const IntrinsicInst *I) {
282 switch (I->getIntrinsicID()) {
283 case Intrinsic::dbg_declare:
284 case Intrinsic::dbg_value:
285 case Intrinsic::dbg_addr:
286 return true;
287 default:
288 return false;
289 }
290 }
291 static bool classof(const Value *V) {
292 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
293 }
294 /// @}
295private:
296 void setArgOperand(unsigned i, Value *v) {
297 DbgInfoIntrinsic::setArgOperand(i, v);
298 }
299 void setOperand(unsigned i, Value *v) { DbgInfoIntrinsic::setOperand(i, v); }
300};
301
302/// This represents the llvm.dbg.declare instruction.
303class DbgDeclareInst : public DbgVariableIntrinsic {
304public:
305 Value *getAddress() const {
306 assert(getNumVariableLocationOps() == 1 &&(static_cast <bool> (getNumVariableLocationOps() == 1 &&
"dbg.declare must have exactly 1 location operand.") ? void (
0) : __assert_fail ("getNumVariableLocationOps() == 1 && \"dbg.declare must have exactly 1 location operand.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/IntrinsicInst.h"
, 307, __extension__ __PRETTY_FUNCTION__))
307 "dbg.declare must have exactly 1 location operand.")(static_cast <bool> (getNumVariableLocationOps() == 1 &&
"dbg.declare must have exactly 1 location operand.") ? void (
0) : __assert_fail ("getNumVariableLocationOps() == 1 && \"dbg.declare must have exactly 1 location operand.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/IntrinsicInst.h"
, 307, __extension__ __PRETTY_FUNCTION__))
;
308 return getVariableLocationOp(0);
309 }
310
311 /// \name Casting methods
312 /// @{
313 static bool classof(const IntrinsicInst *I) {
314 return I->getIntrinsicID() == Intrinsic::dbg_declare;
315 }
316 static bool classof(const Value *V) {
317 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
318 }
319 /// @}
320};
321
322/// This represents the llvm.dbg.addr instruction.
323class DbgAddrIntrinsic : public DbgVariableIntrinsic {
324public:
325 Value *getAddress() const {
326 assert(getNumVariableLocationOps() == 1 &&(static_cast <bool> (getNumVariableLocationOps() == 1 &&
"dbg.addr must have exactly 1 location operand.") ? void (0)
: __assert_fail ("getNumVariableLocationOps() == 1 && \"dbg.addr must have exactly 1 location operand.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/IntrinsicInst.h"
, 327, __extension__ __PRETTY_FUNCTION__))
327 "dbg.addr must have exactly 1 location operand.")(static_cast <bool> (getNumVariableLocationOps() == 1 &&
"dbg.addr must have exactly 1 location operand.") ? void (0)
: __assert_fail ("getNumVariableLocationOps() == 1 && \"dbg.addr must have exactly 1 location operand.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/IntrinsicInst.h"
, 327, __extension__ __PRETTY_FUNCTION__))
;
328 return getVariableLocationOp(0);
329 }
330
331 /// \name Casting methods
332 /// @{
333 static bool classof(const IntrinsicInst *I) {
334 return I->getIntrinsicID() == Intrinsic::dbg_addr;
335 }
336 static bool classof(const Value *V) {
337 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
338 }
339};
340
341/// This represents the llvm.dbg.value instruction.
342class DbgValueInst : public DbgVariableIntrinsic {
343public:
344 // The default argument should only be used in ISel, and the default option
345 // should be removed once ISel support for multiple location ops is complete.
346 Value *getValue(unsigned OpIdx = 0) const {
347 return getVariableLocationOp(OpIdx);
348 }
349 iterator_range<location_op_iterator> getValues() const {
350 return location_ops();
351 }
352
353 /// \name Casting methods
354 /// @{
355 static bool classof(const IntrinsicInst *I) {
356 return I->getIntrinsicID() == Intrinsic::dbg_value;
357 }
358 static bool classof(const Value *V) {
359 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
360 }
361 /// @}
362};
363
364/// This represents the llvm.dbg.label instruction.
365class DbgLabelInst : public DbgInfoIntrinsic {
366public:
367 DILabel *getLabel() const { return cast<DILabel>(getRawLabel()); }
368
369 Metadata *getRawLabel() const {
370 return cast<MetadataAsValue>(getArgOperand(0))->getMetadata();
371 }
372
373 /// Methods for support type inquiry through isa, cast, and dyn_cast:
374 /// @{
375 static bool classof(const IntrinsicInst *I) {
376 return I->getIntrinsicID() == Intrinsic::dbg_label;
377 }
378 static bool classof(const Value *V) {
379 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
380 }
381 /// @}
382};
383
384/// This is the common base class for vector predication intrinsics.
385class VPIntrinsic : public IntrinsicInst {
386public:
387 /// \brief Declares a llvm.vp.* intrinsic in \p M that matches the parameters
388 /// \p Params.
389 static Function *getDeclarationForParams(Module *M, Intrinsic::ID,
390 ArrayRef<Value *> Params);
391
392 static Optional<unsigned> getMaskParamPos(Intrinsic::ID IntrinsicID);
393 static Optional<unsigned> getVectorLengthParamPos(Intrinsic::ID IntrinsicID);
394
395 /// The llvm.vp.* intrinsics for this instruction Opcode
396 static Intrinsic::ID getForOpcode(unsigned OC);
397
398 // Whether \p ID is a VP intrinsic ID.
399 static bool isVPIntrinsic(Intrinsic::ID);
400
401 /// \return the mask parameter or nullptr.
402 Value *getMaskParam() const;
403 void setMaskParam(Value *);
404
405 /// \return the vector length parameter or nullptr.
406 Value *getVectorLengthParam() const;
407 void setVectorLengthParam(Value *);
408
409 /// \return whether the vector length param can be ignored.
410 bool canIgnoreVectorLengthParam() const;
411
412 /// \return the static element count (vector number of elements) the vector
413 /// length parameter applies to.
414 ElementCount getStaticVectorLength() const;
415
416 // Methods for support type inquiry through isa, cast, and dyn_cast:
417 static bool classof(const IntrinsicInst *I) {
418 return isVPIntrinsic(I->getIntrinsicID());
419 }
420 static bool classof(const Value *V) {
421 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
422 }
423
424 // Equivalent non-predicated opcode
425 Optional<unsigned> getFunctionalOpcode() const {
426 return getFunctionalOpcodeForVP(getIntrinsicID());
427 }
428
429 // Equivalent non-predicated opcode
430 static Optional<unsigned> getFunctionalOpcodeForVP(Intrinsic::ID ID);
431};
432
433/// This is the common base class for constrained floating point intrinsics.
434class ConstrainedFPIntrinsic : public IntrinsicInst {
435public:
436 bool isUnaryOp() const;
437 bool isTernaryOp() const;
438 Optional<RoundingMode> getRoundingMode() const;
439 Optional<fp::ExceptionBehavior> getExceptionBehavior() const;
440 bool isDefaultFPEnvironment() const;
441
442 // Methods for support type inquiry through isa, cast, and dyn_cast:
443 static bool classof(const IntrinsicInst *I);
444 static bool classof(const Value *V) {
445 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
446 }
447};
448
449/// Constrained floating point compare intrinsics.
450class ConstrainedFPCmpIntrinsic : public ConstrainedFPIntrinsic {
451public:
452 FCmpInst::Predicate getPredicate() const;
453
454 // Methods for support type inquiry through isa, cast, and dyn_cast:
455 static bool classof(const IntrinsicInst *I) {
456 switch (I->getIntrinsicID()) {
457 case Intrinsic::experimental_constrained_fcmp:
458 case Intrinsic::experimental_constrained_fcmps:
459 return true;
460 default:
461 return false;
462 }
463 }
464 static bool classof(const Value *V) {
465 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
466 }
467};
468
469/// This class represents min/max intrinsics.
470class MinMaxIntrinsic : public IntrinsicInst {
471public:
472 static bool classof(const IntrinsicInst *I) {
473 switch (I->getIntrinsicID()) {
474 case Intrinsic::umin:
475 case Intrinsic::umax:
476 case Intrinsic::smin:
477 case Intrinsic::smax:
478 return true;
479 default:
480 return false;
481 }
482 }
483 static bool classof(const Value *V) {
484 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
485 }
486
487 Value *getLHS() const { return const_cast<Value *>(getArgOperand(0)); }
488 Value *getRHS() const { return const_cast<Value *>(getArgOperand(1)); }
489
490 /// Returns the comparison predicate underlying the intrinsic.
491 ICmpInst::Predicate getPredicate() const {
492 switch (getIntrinsicID()) {
493 case Intrinsic::umin:
494 return ICmpInst::Predicate::ICMP_ULT;
495 case Intrinsic::umax:
496 return ICmpInst::Predicate::ICMP_UGT;
497 case Intrinsic::smin:
498 return ICmpInst::Predicate::ICMP_SLT;
499 case Intrinsic::smax:
500 return ICmpInst::Predicate::ICMP_SGT;
501 default:
502 llvm_unreachable("Invalid intrinsic")::llvm::llvm_unreachable_internal("Invalid intrinsic", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/IntrinsicInst.h"
, 502)
;
503 }
504 }
505
506 /// Whether the intrinsic is signed or unsigned.
507 bool isSigned() const { return ICmpInst::isSigned(getPredicate()); };
508};
509
510/// This class represents an intrinsic that is based on a binary operation.
511/// This includes op.with.overflow and saturating add/sub intrinsics.
512class BinaryOpIntrinsic : public IntrinsicInst {
513public:
514 static bool classof(const IntrinsicInst *I) {
515 switch (I->getIntrinsicID()) {
516 case Intrinsic::uadd_with_overflow:
517 case Intrinsic::sadd_with_overflow:
518 case Intrinsic::usub_with_overflow:
519 case Intrinsic::ssub_with_overflow:
520 case Intrinsic::umul_with_overflow:
521 case Intrinsic::smul_with_overflow:
522 case Intrinsic::uadd_sat:
523 case Intrinsic::sadd_sat:
524 case Intrinsic::usub_sat:
525 case Intrinsic::ssub_sat:
526 return true;
527 default:
528 return false;
529 }
530 }
531 static bool classof(const Value *V) {
532 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
533 }
534
535 Value *getLHS() const { return const_cast<Value *>(getArgOperand(0)); }
536 Value *getRHS() const { return const_cast<Value *>(getArgOperand(1)); }
537
538 /// Returns the binary operation underlying the intrinsic.
539 Instruction::BinaryOps getBinaryOp() const;
540
541 /// Whether the intrinsic is signed or unsigned.
542 bool isSigned() const;
543
544 /// Returns one of OBO::NoSignedWrap or OBO::NoUnsignedWrap.
545 unsigned getNoWrapKind() const;
546};
547
548/// Represents an op.with.overflow intrinsic.
549class WithOverflowInst : public BinaryOpIntrinsic {
550public:
551 static bool classof(const IntrinsicInst *I) {
552 switch (I->getIntrinsicID()) {
553 case Intrinsic::uadd_with_overflow:
554 case Intrinsic::sadd_with_overflow:
555 case Intrinsic::usub_with_overflow:
556 case Intrinsic::ssub_with_overflow:
557 case Intrinsic::umul_with_overflow:
558 case Intrinsic::smul_with_overflow:
559 return true;
560 default:
561 return false;
562 }
563 }
564 static bool classof(const Value *V) {
565 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
566 }
567};
568
569/// Represents a saturating add/sub intrinsic.
570class SaturatingInst : public BinaryOpIntrinsic {
571public:
572 static bool classof(const IntrinsicInst *I) {
573 switch (I->getIntrinsicID()) {
574 case Intrinsic::uadd_sat:
575 case Intrinsic::sadd_sat:
576 case Intrinsic::usub_sat:
577 case Intrinsic::ssub_sat:
578 return true;
579 default:
580 return false;
581 }
582 }
583 static bool classof(const Value *V) {
584 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
585 }
586};
587
588/// Common base class for all memory intrinsics. Simply provides
589/// common methods.
590/// Written as CRTP to avoid a common base class amongst the
591/// three atomicity hierarchies.
592template <typename Derived> class MemIntrinsicBase : public IntrinsicInst {
593private:
594 enum { ARG_DEST = 0, ARG_LENGTH = 2 };
595
596public:
597 Value *getRawDest() const {
598 return const_cast<Value *>(getArgOperand(ARG_DEST));
599 }
600 const Use &getRawDestUse() const { return getArgOperandUse(ARG_DEST); }
601 Use &getRawDestUse() { return getArgOperandUse(ARG_DEST); }
602
603 Value *getLength() const {
604 return const_cast<Value *>(getArgOperand(ARG_LENGTH));
605 }
606 const Use &getLengthUse() const { return getArgOperandUse(ARG_LENGTH); }
607 Use &getLengthUse() { return getArgOperandUse(ARG_LENGTH); }
608
609 /// This is just like getRawDest, but it strips off any cast
610 /// instructions (including addrspacecast) that feed it, giving the
611 /// original input. The returned value is guaranteed to be a pointer.
612 Value *getDest() const { return getRawDest()->stripPointerCasts(); }
613
614 unsigned getDestAddressSpace() const {
615 return cast<PointerType>(getRawDest()->getType())->getAddressSpace();
616 }
617
618 /// FIXME: Remove this function once transition to Align is over.
619 /// Use getDestAlign() instead.
620 unsigned getDestAlignment() const {
621 if (auto MA = getParamAlign(ARG_DEST))
622 return MA->value();
623 return 0;
624 }
625 MaybeAlign getDestAlign() const { return getParamAlign(ARG_DEST); }
626
627 /// Set the specified arguments of the instruction.
628 void setDest(Value *Ptr) {
629 assert(getRawDest()->getType() == Ptr->getType() &&(static_cast <bool> (getRawDest()->getType() == Ptr->
getType() && "setDest called with pointer of wrong type!"
) ? void (0) : __assert_fail ("getRawDest()->getType() == Ptr->getType() && \"setDest called with pointer of wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/IntrinsicInst.h"
, 630, __extension__ __PRETTY_FUNCTION__))
630 "setDest called with pointer of wrong type!")(static_cast <bool> (getRawDest()->getType() == Ptr->
getType() && "setDest called with pointer of wrong type!"
) ? void (0) : __assert_fail ("getRawDest()->getType() == Ptr->getType() && \"setDest called with pointer of wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/IntrinsicInst.h"
, 630, __extension__ __PRETTY_FUNCTION__))
;
631 setArgOperand(ARG_DEST, Ptr);
632 }
633
634 /// FIXME: Remove this function once transition to Align is over.
635 /// Use the version that takes MaybeAlign instead of this one.
636 void setDestAlignment(unsigned Alignment) {
637 setDestAlignment(MaybeAlign(Alignment));
638 }
639 void setDestAlignment(MaybeAlign Alignment) {
640 removeParamAttr(ARG_DEST, Attribute::Alignment);
641 if (Alignment)
642 addParamAttr(ARG_DEST,
643 Attribute::getWithAlignment(getContext(), *Alignment));
644 }
645 void setDestAlignment(Align Alignment) {
646 removeParamAttr(ARG_DEST, Attribute::Alignment);
647 addParamAttr(ARG_DEST,
648 Attribute::getWithAlignment(getContext(), Alignment));
649 }
650
651 void setLength(Value *L) {
652 assert(getLength()->getType() == L->getType() &&(static_cast <bool> (getLength()->getType() == L->
getType() && "setLength called with value of wrong type!"
) ? void (0) : __assert_fail ("getLength()->getType() == L->getType() && \"setLength called with value of wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/IntrinsicInst.h"
, 653, __extension__ __PRETTY_FUNCTION__))
653 "setLength called with value of wrong type!")(static_cast <bool> (getLength()->getType() == L->
getType() && "setLength called with value of wrong type!"
) ? void (0) : __assert_fail ("getLength()->getType() == L->getType() && \"setLength called with value of wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/IntrinsicInst.h"
, 653, __extension__ __PRETTY_FUNCTION__))
;
654 setArgOperand(ARG_LENGTH, L);
655 }
656};
657
658/// Common base class for all memory transfer intrinsics. Simply provides
659/// common methods.
660template <class BaseCL> class MemTransferBase : public BaseCL {
661private:
662 enum { ARG_SOURCE = 1 };
663
664public:
665 /// Return the arguments to the instruction.
666 Value *getRawSource() const {
667 return const_cast<Value *>(BaseCL::getArgOperand(ARG_SOURCE));
668 }
669 const Use &getRawSourceUse() const {
670 return BaseCL::getArgOperandUse(ARG_SOURCE);
671 }
672 Use &getRawSourceUse() { return BaseCL::getArgOperandUse(ARG_SOURCE); }
673
674 /// This is just like getRawSource, but it strips off any cast
675 /// instructions that feed it, giving the original input. The returned
676 /// value is guaranteed to be a pointer.
677 Value *getSource() const { return getRawSource()->stripPointerCasts(); }
678
679 unsigned getSourceAddressSpace() const {
680 return cast<PointerType>(getRawSource()->getType())->getAddressSpace();
681 }
682
683 /// FIXME: Remove this function once transition to Align is over.
684 /// Use getSourceAlign() instead.
685 unsigned getSourceAlignment() const {
686 if (auto MA = BaseCL::getParamAlign(ARG_SOURCE))
687 return MA->value();
688 return 0;
689 }
690
691 MaybeAlign getSourceAlign() const {
692 return BaseCL::getParamAlign(ARG_SOURCE);
693 }
694
695 void setSource(Value *Ptr) {
696 assert(getRawSource()->getType() == Ptr->getType() &&(static_cast <bool> (getRawSource()->getType() == Ptr
->getType() && "setSource called with pointer of wrong type!"
) ? void (0) : __assert_fail ("getRawSource()->getType() == Ptr->getType() && \"setSource called with pointer of wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/IntrinsicInst.h"
, 697, __extension__ __PRETTY_FUNCTION__))
697 "setSource called with pointer of wrong type!")(static_cast <bool> (getRawSource()->getType() == Ptr
->getType() && "setSource called with pointer of wrong type!"
) ? void (0) : __assert_fail ("getRawSource()->getType() == Ptr->getType() && \"setSource called with pointer of wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/IntrinsicInst.h"
, 697, __extension__ __PRETTY_FUNCTION__))
;
698 BaseCL::setArgOperand(ARG_SOURCE, Ptr);
699 }
700
701 /// FIXME: Remove this function once transition to Align is over.
702 /// Use the version that takes MaybeAlign instead of this one.
703 void setSourceAlignment(unsigned Alignment) {
704 setSourceAlignment(MaybeAlign(Alignment));
705 }
706 void setSourceAlignment(MaybeAlign Alignment) {
707 BaseCL::removeParamAttr(ARG_SOURCE, Attribute::Alignment);
708 if (Alignment)
709 BaseCL::addParamAttr(ARG_SOURCE, Attribute::getWithAlignment(
710 BaseCL::getContext(), *Alignment));
711 }
712 void setSourceAlignment(Align Alignment) {
713 BaseCL::removeParamAttr(ARG_SOURCE, Attribute::Alignment);
714 BaseCL::addParamAttr(ARG_SOURCE, Attribute::getWithAlignment(
715 BaseCL::getContext(), Alignment));
716 }
717};
718
719/// Common base class for all memset intrinsics. Simply provides
720/// common methods.
721template <class BaseCL> class MemSetBase : public BaseCL {
722private:
723 enum { ARG_VALUE = 1 };
724
725public:
726 Value *getValue() const {
727 return const_cast<Value *>(BaseCL::getArgOperand(ARG_VALUE));
728 }
729 const Use &getValueUse() const { return BaseCL::getArgOperandUse(ARG_VALUE); }
730 Use &getValueUse() { return BaseCL::getArgOperandUse(ARG_VALUE); }
731
732 void setValue(Value *Val) {
733 assert(getValue()->getType() == Val->getType() &&(static_cast <bool> (getValue()->getType() == Val->
getType() && "setValue called with value of wrong type!"
) ? void (0) : __assert_fail ("getValue()->getType() == Val->getType() && \"setValue called with value of wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/IntrinsicInst.h"
, 734, __extension__ __PRETTY_FUNCTION__))
734 "setValue called with value of wrong type!")(static_cast <bool> (getValue()->getType() == Val->
getType() && "setValue called with value of wrong type!"
) ? void (0) : __assert_fail ("getValue()->getType() == Val->getType() && \"setValue called with value of wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/IntrinsicInst.h"
, 734, __extension__ __PRETTY_FUNCTION__))
;
735 BaseCL::setArgOperand(ARG_VALUE, Val);
736 }
737};
738
739// The common base class for the atomic memset/memmove/memcpy intrinsics
740// i.e. llvm.element.unordered.atomic.memset/memcpy/memmove
741class AtomicMemIntrinsic : public MemIntrinsicBase<AtomicMemIntrinsic> {
742private:
743 enum { ARG_ELEMENTSIZE = 3 };
744
745public:
746 Value *getRawElementSizeInBytes() const {
747 return const_cast<Value *>(getArgOperand(ARG_ELEMENTSIZE));
748 }
749
750 ConstantInt *getElementSizeInBytesCst() const {
751 return cast<ConstantInt>(getRawElementSizeInBytes());
752 }
753
754 uint32_t getElementSizeInBytes() const {
755 return getElementSizeInBytesCst()->getZExtValue();
756 }
757
758 void setElementSizeInBytes(Constant *V) {
759 assert(V->getType() == Type::getInt8Ty(getContext()) &&(static_cast <bool> (V->getType() == Type::getInt8Ty
(getContext()) && "setElementSizeInBytes called with value of wrong type!"
) ? void (0) : __assert_fail ("V->getType() == Type::getInt8Ty(getContext()) && \"setElementSizeInBytes called with value of wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/IntrinsicInst.h"
, 760, __extension__ __PRETTY_FUNCTION__))
760 "setElementSizeInBytes called with value of wrong type!")(static_cast <bool> (V->getType() == Type::getInt8Ty
(getContext()) && "setElementSizeInBytes called with value of wrong type!"
) ? void (0) : __assert_fail ("V->getType() == Type::getInt8Ty(getContext()) && \"setElementSizeInBytes called with value of wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/IntrinsicInst.h"
, 760, __extension__ __PRETTY_FUNCTION__))
;
761 setArgOperand(ARG_ELEMENTSIZE, V);
762 }
763
764 static bool classof(const IntrinsicInst *I) {
765 switch (I->getIntrinsicID()) {
766 case Intrinsic::memcpy_element_unordered_atomic:
767 case Intrinsic::memmove_element_unordered_atomic:
768 case Intrinsic::memset_element_unordered_atomic:
769 return true;
770 default:
771 return false;
772 }
773 }
774 static bool classof(const Value *V) {
775 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
776 }
777};
778
779/// This class represents atomic memset intrinsic
780// i.e. llvm.element.unordered.atomic.memset
781class AtomicMemSetInst : public MemSetBase<AtomicMemIntrinsic> {
782public:
783 static bool classof(const IntrinsicInst *I) {
784 return I->getIntrinsicID() == Intrinsic::memset_element_unordered_atomic;
785 }
786 static bool classof(const Value *V) {
787 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
788 }
789};
790
791// This class wraps the atomic memcpy/memmove intrinsics
792// i.e. llvm.element.unordered.atomic.memcpy/memmove
793class AtomicMemTransferInst : public MemTransferBase<AtomicMemIntrinsic> {
794public:
795 static bool classof(const IntrinsicInst *I) {
796 switch (I->getIntrinsicID()) {
797 case Intrinsic::memcpy_element_unordered_atomic:
798 case Intrinsic::memmove_element_unordered_atomic:
799 return true;
800 default:
801 return false;
802 }
803 }
804 static bool classof(const Value *V) {
805 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
806 }
807};
808
809/// This class represents the atomic memcpy intrinsic
810/// i.e. llvm.element.unordered.atomic.memcpy
811class AtomicMemCpyInst : public AtomicMemTransferInst {
812public:
813 static bool classof(const IntrinsicInst *I) {
814 return I->getIntrinsicID() == Intrinsic::memcpy_element_unordered_atomic;
815 }
816 static bool classof(const Value *V) {
817 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
818 }
819};
820
821/// This class represents the atomic memmove intrinsic
822/// i.e. llvm.element.unordered.atomic.memmove
823class AtomicMemMoveInst : public AtomicMemTransferInst {
824public:
825 static bool classof(const IntrinsicInst *I) {
826 return I->getIntrinsicID() == Intrinsic::memmove_element_unordered_atomic;
827 }
828 static bool classof(const Value *V) {
829 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
830 }
831};
832
833/// This is the common base class for memset/memcpy/memmove.
834class MemIntrinsic : public MemIntrinsicBase<MemIntrinsic> {
835private:
836 enum { ARG_VOLATILE = 3 };
837
838public:
839 ConstantInt *getVolatileCst() const {
840 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(ARG_VOLATILE)));
841 }
842
843 bool isVolatile() const { return !getVolatileCst()->isZero(); }
28
Calling 'ConstantInt::isZero'
42
Returning from 'ConstantInt::isZero'
43
Returning zero, which participates in a condition later
844
845 void setVolatile(Constant *V) { setArgOperand(ARG_VOLATILE, V); }
846
847 // Methods for support type inquiry through isa, cast, and dyn_cast:
848 static bool classof(const IntrinsicInst *I) {
849 switch (I->getIntrinsicID()) {
850 case Intrinsic::memcpy:
851 case Intrinsic::memmove:
852 case Intrinsic::memset:
853 case Intrinsic::memcpy_inline:
854 return true;
855 default:
856 return false;
857 }
858 }
859 static bool classof(const Value *V) {
860 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
861 }
862};
863
864/// This class wraps the llvm.memset intrinsic.
865class MemSetInst : public MemSetBase<MemIntrinsic> {
866public:
867 // Methods for support type inquiry through isa, cast, and dyn_cast:
868 static bool classof(const IntrinsicInst *I) {
869 return I->getIntrinsicID() == Intrinsic::memset;
870 }
871 static bool classof(const Value *V) {
872 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
873 }
874};
875
876/// This class wraps the llvm.memcpy/memmove intrinsics.
877class MemTransferInst : public MemTransferBase<MemIntrinsic> {
878public:
879 // Methods for support type inquiry through isa, cast, and dyn_cast:
880 static bool classof(const IntrinsicInst *I) {
881 switch (I->getIntrinsicID()) {
882 case Intrinsic::memcpy:
883 case Intrinsic::memmove:
884 case Intrinsic::memcpy_inline:
885 return true;
886 default:
887 return false;
888 }
889 }
890 static bool classof(const Value *V) {
891 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
892 }
893};
894
895/// This class wraps the llvm.memcpy intrinsic.
896class MemCpyInst : public MemTransferInst {
897public:
898 // Methods for support type inquiry through isa, cast, and dyn_cast:
899 static bool classof(const IntrinsicInst *I) {
900 return I->getIntrinsicID() == Intrinsic::memcpy;
901 }
902 static bool classof(const Value *V) {
903 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
904 }
905};
906
907/// This class wraps the llvm.memmove intrinsic.
908class MemMoveInst : public MemTransferInst {
909public:
910 // Methods for support type inquiry through isa, cast, and dyn_cast:
911 static bool classof(const IntrinsicInst *I) {
912 return I->getIntrinsicID() == Intrinsic::memmove;
913 }
914 static bool classof(const Value *V) {
915 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
916 }
917};
918
919/// This class wraps the llvm.memcpy.inline intrinsic.
920class MemCpyInlineInst : public MemTransferInst {
921public:
922 ConstantInt *getLength() const {
923 return cast<ConstantInt>(MemTransferInst::getLength());
924 }
925 // Methods for support type inquiry through isa, cast, and dyn_cast:
926 static bool classof(const IntrinsicInst *I) {
927 return I->getIntrinsicID() == Intrinsic::memcpy_inline;
928 }
929 static bool classof(const Value *V) {
930 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
931 }
932};
933
934// The common base class for any memset/memmove/memcpy intrinsics;
935// whether they be atomic or non-atomic.
936// i.e. llvm.element.unordered.atomic.memset/memcpy/memmove
937// and llvm.memset/memcpy/memmove
938class AnyMemIntrinsic : public MemIntrinsicBase<AnyMemIntrinsic> {
939public:
940 bool isVolatile() const {
941 // Only the non-atomic intrinsics can be volatile
942 if (auto *MI = dyn_cast<MemIntrinsic>(this))
943 return MI->isVolatile();
944 return false;
945 }
946
947 static bool classof(const IntrinsicInst *I) {
948 switch (I->getIntrinsicID()) {
949 case Intrinsic::memcpy:
950 case Intrinsic::memcpy_inline:
951 case Intrinsic::memmove:
952 case Intrinsic::memset:
953 case Intrinsic::memcpy_element_unordered_atomic:
954 case Intrinsic::memmove_element_unordered_atomic:
955 case Intrinsic::memset_element_unordered_atomic:
956 return true;
957 default:
958 return false;
959 }
960 }
961 static bool classof(const Value *V) {
962 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
963 }
964};
965
966/// This class represents any memset intrinsic
967// i.e. llvm.element.unordered.atomic.memset
968// and llvm.memset
969class AnyMemSetInst : public MemSetBase<AnyMemIntrinsic> {
970public:
971 static bool classof(const IntrinsicInst *I) {
972 switch (I->getIntrinsicID()) {
973 case Intrinsic::memset:
974 case Intrinsic::memset_element_unordered_atomic:
975 return true;
976 default:
977 return false;
978 }
979 }
980 static bool classof(const Value *V) {
981 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
982 }
983};
984
985// This class wraps any memcpy/memmove intrinsics
986// i.e. llvm.element.unordered.atomic.memcpy/memmove
987// and llvm.memcpy/memmove
988class AnyMemTransferInst : public MemTransferBase<AnyMemIntrinsic> {
989public:
990 static bool classof(const IntrinsicInst *I) {
991 switch (I->getIntrinsicID()) {
992 case Intrinsic::memcpy:
993 case Intrinsic::memcpy_inline:
994 case Intrinsic::memmove:
995 case Intrinsic::memcpy_element_unordered_atomic:
996 case Intrinsic::memmove_element_unordered_atomic:
997 return true;
998 default:
999 return false;
1000 }
1001 }
1002 static bool classof(const Value *V) {
1003 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1004 }
1005};
1006
1007/// This class represents any memcpy intrinsic
1008/// i.e. llvm.element.unordered.atomic.memcpy
1009/// and llvm.memcpy
1010class AnyMemCpyInst : public AnyMemTransferInst {
1011public:
1012 static bool classof(const IntrinsicInst *I) {
1013 switch (I->getIntrinsicID()) {
1014 case Intrinsic::memcpy:
1015 case Intrinsic::memcpy_inline:
1016 case Intrinsic::memcpy_element_unordered_atomic:
1017 return true;
1018 default:
1019 return false;
1020 }
1021 }
1022 static bool classof(const Value *V) {
1023 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1024 }
1025};
1026
1027/// This class represents any memmove intrinsic
1028/// i.e. llvm.element.unordered.atomic.memmove
1029/// and llvm.memmove
1030class AnyMemMoveInst : public AnyMemTransferInst {
1031public:
1032 static bool classof(const IntrinsicInst *I) {
1033 switch (I->getIntrinsicID()) {
1034 case Intrinsic::memmove:
1035 case Intrinsic::memmove_element_unordered_atomic:
1036 return true;
1037 default:
1038 return false;
1039 }
1040 }
1041 static bool classof(const Value *V) {
1042 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1043 }
1044};
1045
1046/// This represents the llvm.va_start intrinsic.
1047class VAStartInst : public IntrinsicInst {
1048public:
1049 static bool classof(const IntrinsicInst *I) {
1050 return I->getIntrinsicID() == Intrinsic::vastart;
1051 }
1052 static bool classof(const Value *V) {
1053 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1054 }
1055
1056 Value *getArgList() const { return const_cast<Value *>(getArgOperand(0)); }
1057};
1058
1059/// This represents the llvm.va_end intrinsic.
1060class VAEndInst : public IntrinsicInst {
1061public:
1062 static bool classof(const IntrinsicInst *I) {
1063 return I->getIntrinsicID() == Intrinsic::vaend;
1064 }
1065 static bool classof(const Value *V) {
1066 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1067 }
1068
1069 Value *getArgList() const { return const_cast<Value *>(getArgOperand(0)); }
1070};
1071
1072/// This represents the llvm.va_copy intrinsic.
1073class VACopyInst : public IntrinsicInst {
1074public:
1075 static bool classof(const IntrinsicInst *I) {
1076 return I->getIntrinsicID() == Intrinsic::vacopy;
1077 }
1078 static bool classof(const Value *V) {
1079 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1080 }
1081
1082 Value *getDest() const { return const_cast<Value *>(getArgOperand(0)); }
1083 Value *getSrc() const { return const_cast<Value *>(getArgOperand(1)); }
1084};
1085
1086/// This represents the llvm.instrprof_increment intrinsic.
1087class InstrProfIncrementInst : public IntrinsicInst {
1088public:
1089 static bool classof(const IntrinsicInst *I) {
1090 return I->getIntrinsicID() == Intrinsic::instrprof_increment;
1091 }
1092 static bool classof(const Value *V) {
1093 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1094 }
1095
1096 GlobalVariable *getName() const {
1097 return cast<GlobalVariable>(
1098 const_cast<Value *>(getArgOperand(0))->stripPointerCasts());
1099 }
1100
1101 ConstantInt *getHash() const {
1102 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(1)));
1103 }
1104
1105 ConstantInt *getNumCounters() const {
1106 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(2)));
1107 }
1108
1109 ConstantInt *getIndex() const {
1110 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(3)));
1111 }
1112
1113 Value *getStep() const;
1114};
1115
1116class InstrProfIncrementInstStep : public InstrProfIncrementInst {
1117public:
1118 static bool classof(const IntrinsicInst *I) {
1119 return I->getIntrinsicID() == Intrinsic::instrprof_increment_step;
1120 }
1121 static bool classof(const Value *V) {
1122 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1123 }
1124};
1125
1126/// This represents the llvm.instrprof_value_profile intrinsic.
1127class InstrProfValueProfileInst : public IntrinsicInst {
1128public:
1129 static bool classof(const IntrinsicInst *I) {
1130 return I->getIntrinsicID() == Intrinsic::instrprof_value_profile;
1131 }
1132 static bool classof(const Value *V) {
1133 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1134 }
1135
1136 GlobalVariable *getName() const {
1137 return cast<GlobalVariable>(
1138 const_cast<Value *>(getArgOperand(0))->stripPointerCasts());
1139 }
1140
1141 ConstantInt *getHash() const {
1142 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(1)));
1143 }
1144
1145 Value *getTargetValue() const {
1146 return cast<Value>(const_cast<Value *>(getArgOperand(2)));
1147 }
1148
1149 ConstantInt *getValueKind() const {
1150 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(3)));
1151 }
1152
1153 // Returns the value site index.
1154 ConstantInt *getIndex() const {
1155 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(4)));
1156 }
1157};
1158
1159class PseudoProbeInst : public IntrinsicInst {
1160public:
1161 static bool classof(const IntrinsicInst *I) {
1162 return I->getIntrinsicID() == Intrinsic::pseudoprobe;
1163 }
1164
1165 static bool classof(const Value *V) {
1166 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1167 }
1168
1169 ConstantInt *getFuncGuid() const {
1170 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(0)));
1171 }
1172
1173 ConstantInt *getIndex() const {
1174 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(1)));
1175 }
1176
1177 ConstantInt *getAttributes() const {
1178 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(2)));
1179 }
1180
1181 ConstantInt *getFactor() const {
1182 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(3)));
1183 }
1184};
1185
1186class NoAliasScopeDeclInst : public IntrinsicInst {
1187public:
1188 static bool classof(const IntrinsicInst *I) {
1189 return I->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl;
1190 }
1191
1192 static bool classof(const Value *V) {
1193 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1194 }
1195
1196 MDNode *getScopeList() const {
1197 auto *MV =
1198 cast<MetadataAsValue>(getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
1199 return cast<MDNode>(MV->getMetadata());
1200 }
1201
1202 void setScopeList(MDNode *ScopeList) {
1203 setOperand(Intrinsic::NoAliasScopeDeclScopeArg,
1204 MetadataAsValue::get(getContext(), ScopeList));
1205 }
1206};
1207
1208// Defined in Statepoint.h -- NOT a subclass of IntrinsicInst
1209class GCStatepointInst;
1210
1211/// Common base class for representing values projected from a statepoint.
1212/// Currently, the only projections available are gc.result and gc.relocate.
1213class GCProjectionInst : public IntrinsicInst {
1214public:
1215 static bool classof(const IntrinsicInst *I) {
1216 return I->getIntrinsicID() == Intrinsic::experimental_gc_relocate ||
1217 I->getIntrinsicID() == Intrinsic::experimental_gc_result;
1218 }
1219
1220 static bool classof(const Value *V) {
1221 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1222 }
1223
1224 /// Return true if this relocate is tied to the invoke statepoint.
1225 /// This includes relocates which are on the unwinding path.
1226 bool isTiedToInvoke() const {
1227 const Value *Token = getArgOperand(0);
1228
1229 return isa<LandingPadInst>(Token) || isa<InvokeInst>(Token);
1230 }
1231
1232 /// The statepoint with which this gc.relocate is associated.
1233 const GCStatepointInst *getStatepoint() const;
1234};
1235
1236/// Represents calls to the gc.relocate intrinsic.
1237class GCRelocateInst : public GCProjectionInst {
1238public:
1239 static bool classof(const IntrinsicInst *I) {
1240 return I->getIntrinsicID() == Intrinsic::experimental_gc_relocate;
1241 }
1242
1243 static bool classof(const Value *V) {
1244 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1245 }
1246
1247 /// The index into the associate statepoint's argument list
1248 /// which contains the base pointer of the pointer whose
1249 /// relocation this gc.relocate describes.
1250 unsigned getBasePtrIndex() const {
1251 return cast<ConstantInt>(getArgOperand(1))->getZExtValue();
1252 }
1253
1254 /// The index into the associate statepoint's argument list which
1255 /// contains the pointer whose relocation this gc.relocate describes.
1256 unsigned getDerivedPtrIndex() const {
1257 return cast<ConstantInt>(getArgOperand(2))->getZExtValue();
1258 }
1259
1260 Value *getBasePtr() const;
1261 Value *getDerivedPtr() const;
1262};
1263
1264/// Represents calls to the gc.result intrinsic.
1265class GCResultInst : public GCProjectionInst {
1266public:
1267 static bool classof(const IntrinsicInst *I) {
1268 return I->getIntrinsicID() == Intrinsic::experimental_gc_result;
1269 }
1270
1271 static bool classof(const Value *V) {
1272 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1273 }
1274};
1275
1276
1277/// This represents the llvm.assume intrinsic.
1278class AssumeInst : public IntrinsicInst {
1279public:
1280 static bool classof(const IntrinsicInst *I) {
1281 return I->getIntrinsicID() == Intrinsic::assume;
1282 }
1283 static bool classof(const Value *V) {
1284 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1285 }
1286};
1287
1288} // end namespace llvm
1289
1290#endif // LLVM_IR_INTRINSICINST_H

/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/Constants.h

1//===-- llvm/Constants.h - Constant class subclass definitions --*- 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/// @file
10/// This file contains the declarations for the subclasses of Constant,
11/// which represent the different flavors of constant values that live in LLVM.
12/// Note that Constants are immutable (once created they never change) and are
13/// fully shared by structural equivalence. This means that two structurally
14/// equivalent constants will always have the same address. Constants are
15/// created on demand as needed and never deleted: thus clients don't have to
16/// worry about the lifetime of the objects.
17//
18//===----------------------------------------------------------------------===//
19
20#ifndef LLVM_IR_CONSTANTS_H
21#define LLVM_IR_CONSTANTS_H
22
23#include "llvm/ADT/APFloat.h"
24#include "llvm/ADT/APInt.h"
25#include "llvm/ADT/ArrayRef.h"
26#include "llvm/ADT/None.h"
27#include "llvm/ADT/Optional.h"
28#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/StringRef.h"
30#include "llvm/IR/Constant.h"
31#include "llvm/IR/DerivedTypes.h"
32#include "llvm/IR/OperandTraits.h"
33#include "llvm/IR/User.h"
34#include "llvm/IR/Value.h"
35#include "llvm/Support/Casting.h"
36#include "llvm/Support/Compiler.h"
37#include "llvm/Support/ErrorHandling.h"
38#include <cassert>
39#include <cstddef>
40#include <cstdint>
41
42namespace llvm {
43
44template <class ConstantClass> struct ConstantAggrKeyType;
45
46/// Base class for constants with no operands.
47///
48/// These constants have no operands; they represent their data directly.
49/// Since they can be in use by unrelated modules (and are never based on
50/// GlobalValues), it never makes sense to RAUW them.
51class ConstantData : public Constant {
52 friend class Constant;
53
54 Value *handleOperandChangeImpl(Value *From, Value *To) {
55 llvm_unreachable("Constant data does not have operands!")::llvm::llvm_unreachable_internal("Constant data does not have operands!"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/Constants.h"
, 55)
;
56 }
57
58protected:
59 explicit ConstantData(Type *Ty, ValueTy VT) : Constant(Ty, VT, nullptr, 0) {}
60
61 void *operator new(size_t s) { return User::operator new(s, 0); }
62
63public:
64 ConstantData(const ConstantData &) = delete;
65
66 /// Methods to support type inquiry through isa, cast, and dyn_cast.
67 static bool classof(const Value *V) {
68 return V->getValueID() >= ConstantDataFirstVal &&
69 V->getValueID() <= ConstantDataLastVal;
70 }
71};
72
73//===----------------------------------------------------------------------===//
74/// This is the shared class of boolean and integer constants. This class
75/// represents both boolean and integral constants.
76/// Class for constant integers.
77class ConstantInt final : public ConstantData {
78 friend class Constant;
79
80 APInt Val;
81
82 ConstantInt(IntegerType *Ty, const APInt &V);
83
84 void destroyConstantImpl();
85
86public:
87 ConstantInt(const ConstantInt &) = delete;
88
89 static ConstantInt *getTrue(LLVMContext &Context);
90 static ConstantInt *getFalse(LLVMContext &Context);
91 static ConstantInt *getBool(LLVMContext &Context, bool V);
92 static Constant *getTrue(Type *Ty);
93 static Constant *getFalse(Type *Ty);
94 static Constant *getBool(Type *Ty, bool V);
95
96 /// If Ty is a vector type, return a Constant with a splat of the given
97 /// value. Otherwise return a ConstantInt for the given value.
98 static Constant *get(Type *Ty, uint64_t V, bool IsSigned = false);
99
100 /// Return a ConstantInt with the specified integer value for the specified
101 /// type. If the type is wider than 64 bits, the value will be zero-extended
102 /// to fit the type, unless IsSigned is true, in which case the value will
103 /// be interpreted as a 64-bit signed integer and sign-extended to fit
104 /// the type.
105 /// Get a ConstantInt for a specific value.
106 static ConstantInt *get(IntegerType *Ty, uint64_t V, bool IsSigned = false);
107
108 /// Return a ConstantInt with the specified value for the specified type. The
109 /// value V will be canonicalized to a an unsigned APInt. Accessing it with
110 /// either getSExtValue() or getZExtValue() will yield a correctly sized and
111 /// signed value for the type Ty.
112 /// Get a ConstantInt for a specific signed value.
113 static ConstantInt *getSigned(IntegerType *Ty, int64_t V);
114 static Constant *getSigned(Type *Ty, int64_t V);
115
116 /// Return a ConstantInt with the specified value and an implied Type. The
117 /// type is the integer type that corresponds to the bit width of the value.
118 static ConstantInt *get(LLVMContext &Context, const APInt &V);
119
120 /// Return a ConstantInt constructed from the string strStart with the given
121 /// radix.
122 static ConstantInt *get(IntegerType *Ty, StringRef Str, uint8_t Radix);
123
124 /// If Ty is a vector type, return a Constant with a splat of the given
125 /// value. Otherwise return a ConstantInt for the given value.
126 static Constant *get(Type *Ty, const APInt &V);
127
128 /// Return the constant as an APInt value reference. This allows clients to
129 /// obtain a full-precision copy of the value.
130 /// Return the constant's value.
131 inline const APInt &getValue() const { return Val; }
132
133 /// getBitWidth - Return the bitwidth of this constant.
134 unsigned getBitWidth() const { return Val.getBitWidth(); }
135
136 /// Return the constant as a 64-bit unsigned integer value after it
137 /// has been zero extended as appropriate for the type of this constant. Note
138 /// that this method can assert if the value does not fit in 64 bits.
139 /// Return the zero extended value.
140 inline uint64_t getZExtValue() const { return Val.getZExtValue(); }
141
142 /// Return the constant as a 64-bit integer value after it has been sign
143 /// extended as appropriate for the type of this constant. Note that
144 /// this method can assert if the value does not fit in 64 bits.
145 /// Return the sign extended value.
146 inline int64_t getSExtValue() const { return Val.getSExtValue(); }
147
148 /// Return the constant as an llvm::MaybeAlign.
149 /// Note that this method can assert if the value does not fit in 64 bits or
150 /// is not a power of two.
151 inline MaybeAlign getMaybeAlignValue() const {
152 return MaybeAlign(getZExtValue());
153 }
154
155 /// Return the constant as an llvm::Align, interpreting `0` as `Align(1)`.
156 /// Note that this method can assert if the value does not fit in 64 bits or
157 /// is not a power of two.
158 inline Align getAlignValue() const {
159 return getMaybeAlignValue().valueOrOne();
160 }
161
162 /// A helper method that can be used to determine if the constant contained
163 /// within is equal to a constant. This only works for very small values,
164 /// because this is all that can be represented with all types.
165 /// Determine if this constant's value is same as an unsigned char.
166 bool equalsInt(uint64_t V) const { return Val == V; }
167
168 /// getType - Specialize the getType() method to always return an IntegerType,
169 /// which reduces the amount of casting needed in parts of the compiler.
170 ///
171 inline IntegerType *getType() const {
172 return cast<IntegerType>(Value::getType());
173 }
174
175 /// This static method returns true if the type Ty is big enough to
176 /// represent the value V. This can be used to avoid having the get method
177 /// assert when V is larger than Ty can represent. Note that there are two
178 /// versions of this method, one for unsigned and one for signed integers.
179 /// Although ConstantInt canonicalizes everything to an unsigned integer,
180 /// the signed version avoids callers having to convert a signed quantity
181 /// to the appropriate unsigned type before calling the method.
182 /// @returns true if V is a valid value for type Ty
183 /// Determine if the value is in range for the given type.
184 static bool isValueValidForType(Type *Ty, uint64_t V);
185 static bool isValueValidForType(Type *Ty, int64_t V);
186
187 bool isNegative() const { return Val.isNegative(); }
188
189 /// This is just a convenience method to make client code smaller for a
190 /// common code. It also correctly performs the comparison without the
191 /// potential for an assertion from getZExtValue().
192 bool isZero() const { return Val.isNullValue(); }
29
Calling 'APInt::isNullValue'
40
Returning from 'APInt::isNullValue'
41
Returning the value 1, which participates in a condition later
193
194 /// This is just a convenience method to make client code smaller for a
195 /// common case. It also correctly performs the comparison without the
196 /// potential for an assertion from getZExtValue().
197 /// Determine if the value is one.
198 bool isOne() const { return Val.isOneValue(); }
199
200 /// This function will return true iff every bit in this constant is set
201 /// to true.
202 /// @returns true iff this constant's bits are all set to true.
203 /// Determine if the value is all ones.
204 bool isMinusOne() const { return Val.isAllOnesValue(); }
205
206 /// This function will return true iff this constant represents the largest
207 /// value that may be represented by the constant's type.
208 /// @returns true iff this is the largest value that may be represented
209 /// by this type.
210 /// Determine if the value is maximal.
211 bool isMaxValue(bool IsSigned) const {
212 if (IsSigned)
213 return Val.isMaxSignedValue();
214 else
215 return Val.isMaxValue();
216 }
217
218 /// This function will return true iff this constant represents the smallest
219 /// value that may be represented by this constant's type.
220 /// @returns true if this is the smallest value that may be represented by
221 /// this type.
222 /// Determine if the value is minimal.
223 bool isMinValue(bool IsSigned) const {
224 if (IsSigned)
225 return Val.isMinSignedValue();
226 else
227 return Val.isMinValue();
228 }
229
230 /// This function will return true iff this constant represents a value with
231 /// active bits bigger than 64 bits or a value greater than the given uint64_t
232 /// value.
233 /// @returns true iff this constant is greater or equal to the given number.
234 /// Determine if the value is greater or equal to the given number.
235 bool uge(uint64_t Num) const { return Val.uge(Num); }
236
237 /// getLimitedValue - If the value is smaller than the specified limit,
238 /// return it, otherwise return the limit value. This causes the value
239 /// to saturate to the limit.
240 /// @returns the min of the value of the constant and the specified value
241 /// Get the constant's value with a saturation limit
242 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
243 return Val.getLimitedValue(Limit);
244 }
245
246 /// Methods to support type inquiry through isa, cast, and dyn_cast.
247 static bool classof(const Value *V) {
248 return V->getValueID() == ConstantIntVal;
249 }
250};
251
252//===----------------------------------------------------------------------===//
253/// ConstantFP - Floating Point Values [float, double]
254///
255class ConstantFP final : public ConstantData {
256 friend class Constant;
257
258 APFloat Val;
259
260 ConstantFP(Type *Ty, const APFloat &V);
261
262 void destroyConstantImpl();
263
264public:
265 ConstantFP(const ConstantFP &) = delete;
266
267 /// Floating point negation must be implemented with f(x) = -0.0 - x. This
268 /// method returns the negative zero constant for floating point or vector
269 /// floating point types; for all other types, it returns the null value.
270 static Constant *getZeroValueForNegation(Type *Ty);
271
272 /// This returns a ConstantFP, or a vector containing a splat of a ConstantFP,
273 /// for the specified value in the specified type. This should only be used
274 /// for simple constant values like 2.0/1.0 etc, that are known-valid both as
275 /// host double and as the target format.
276 static Constant *get(Type *Ty, double V);
277
278 /// If Ty is a vector type, return a Constant with a splat of the given
279 /// value. Otherwise return a ConstantFP for the given value.
280 static Constant *get(Type *Ty, const APFloat &V);
281
282 static Constant *get(Type *Ty, StringRef Str);
283 static ConstantFP *get(LLVMContext &Context, const APFloat &V);
284 static Constant *getNaN(Type *Ty, bool Negative = false,
285 uint64_t Payload = 0);
286 static Constant *getQNaN(Type *Ty, bool Negative = false,
287 APInt *Payload = nullptr);
288 static Constant *getSNaN(Type *Ty, bool Negative = false,
289 APInt *Payload = nullptr);
290 static Constant *getNegativeZero(Type *Ty);
291 static Constant *getInfinity(Type *Ty, bool Negative = false);
292
293 /// Return true if Ty is big enough to represent V.
294 static bool isValueValidForType(Type *Ty, const APFloat &V);
295 inline const APFloat &getValueAPF() const { return Val; }
296 inline const APFloat &getValue() const { return Val; }
297
298 /// Return true if the value is positive or negative zero.
299 bool isZero() const { return Val.isZero(); }
300
301 /// Return true if the sign bit is set.
302 bool isNegative() const { return Val.isNegative(); }
303
304 /// Return true if the value is infinity
305 bool isInfinity() const { return Val.isInfinity(); }
306
307 /// Return true if the value is a NaN.
308 bool isNaN() const { return Val.isNaN(); }
309
310 /// We don't rely on operator== working on double values, as it returns true
311 /// for things that are clearly not equal, like -0.0 and 0.0.
312 /// As such, this method can be used to do an exact bit-for-bit comparison of
313 /// two floating point values. The version with a double operand is retained
314 /// because it's so convenient to write isExactlyValue(2.0), but please use
315 /// it only for simple constants.
316 bool isExactlyValue(const APFloat &V) const;
317
318 bool isExactlyValue(double V) const {
319 bool ignored;
320 APFloat FV(V);
321 FV.convert(Val.getSemantics(), APFloat::rmNearestTiesToEven, &ignored);
322 return isExactlyValue(FV);
323 }
324
325 /// Methods for support type inquiry through isa, cast, and dyn_cast:
326 static bool classof(const Value *V) {
327 return V->getValueID() == ConstantFPVal;
328 }
329};
330
331//===----------------------------------------------------------------------===//
332/// All zero aggregate value
333///
334class ConstantAggregateZero final : public ConstantData {
335 friend class Constant;
336
337 explicit ConstantAggregateZero(Type *Ty)
338 : ConstantData(Ty, ConstantAggregateZeroVal) {}
339
340 void destroyConstantImpl();
341
342public:
343 ConstantAggregateZero(const ConstantAggregateZero &) = delete;
344
345 static ConstantAggregateZero *get(Type *Ty);
346
347 /// If this CAZ has array or vector type, return a zero with the right element
348 /// type.
349 Constant *getSequentialElement() const;
350
351 /// If this CAZ has struct type, return a zero with the right element type for
352 /// the specified element.
353 Constant *getStructElement(unsigned Elt) const;
354
355 /// Return a zero of the right value for the specified GEP index if we can,
356 /// otherwise return null (e.g. if C is a ConstantExpr).
357 Constant *getElementValue(Constant *C) const;
358
359 /// Return a zero of the right value for the specified GEP index.
360 Constant *getElementValue(unsigned Idx) const;
361
362 /// Return the number of elements in the array, vector, or struct.
363 ElementCount getElementCount() const;
364
365 /// Methods for support type inquiry through isa, cast, and dyn_cast:
366 ///
367 static bool classof(const Value *V) {
368 return V->getValueID() == ConstantAggregateZeroVal;
369 }
370};
371
372/// Base class for aggregate constants (with operands).
373///
374/// These constants are aggregates of other constants, which are stored as
375/// operands.
376///
377/// Subclasses are \a ConstantStruct, \a ConstantArray, and \a
378/// ConstantVector.
379///
380/// \note Some subclasses of \a ConstantData are semantically aggregates --
381/// such as \a ConstantDataArray -- but are not subclasses of this because they
382/// use operands.
383class ConstantAggregate : public Constant {
384protected:
385 ConstantAggregate(Type *T, ValueTy VT, ArrayRef<Constant *> V);
386
387public:
388 /// Transparently provide more efficient getOperand methods.
389 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant)public: inline Constant *getOperand(unsigned) const; inline void
setOperand(unsigned, Constant*); inline op_iterator op_begin
(); inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
390
391 /// Methods for support type inquiry through isa, cast, and dyn_cast:
392 static bool classof(const Value *V) {
393 return V->getValueID() >= ConstantAggregateFirstVal &&
394 V->getValueID() <= ConstantAggregateLastVal;
395 }
396};
397
398template <>
399struct OperandTraits<ConstantAggregate>
400 : public VariadicOperandTraits<ConstantAggregate> {};
401
402DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantAggregate, Constant)ConstantAggregate::op_iterator ConstantAggregate::op_begin() {
return OperandTraits<ConstantAggregate>::op_begin(this
); } ConstantAggregate::const_op_iterator ConstantAggregate::
op_begin() const { return OperandTraits<ConstantAggregate>
::op_begin(const_cast<ConstantAggregate*>(this)); } ConstantAggregate
::op_iterator ConstantAggregate::op_end() { return OperandTraits
<ConstantAggregate>::op_end(this); } ConstantAggregate::
const_op_iterator ConstantAggregate::op_end() const { return OperandTraits
<ConstantAggregate>::op_end(const_cast<ConstantAggregate
*>(this)); } Constant *ConstantAggregate::getOperand(unsigned
i_nocapture) const { (static_cast <bool> (i_nocapture <
OperandTraits<ConstantAggregate>::operands(this) &&
"getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<ConstantAggregate>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/Constants.h"
, 402, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Constant>( OperandTraits<ConstantAggregate>::op_begin
(const_cast<ConstantAggregate*>(this))[i_nocapture].get
()); } void ConstantAggregate::setOperand(unsigned i_nocapture
, Constant *Val_nocapture) { (static_cast <bool> (i_nocapture
< OperandTraits<ConstantAggregate>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<ConstantAggregate>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/Constants.h"
, 402, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
ConstantAggregate>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned ConstantAggregate::getNumOperands() const { return
OperandTraits<ConstantAggregate>::operands(this); } template
<int Idx_nocapture> Use &ConstantAggregate::Op() {
return this->OpFrom<Idx_nocapture>(this); } template
<int Idx_nocapture> const Use &ConstantAggregate::
Op() const { return this->OpFrom<Idx_nocapture>(this
); }
403
404//===----------------------------------------------------------------------===//
405/// ConstantArray - Constant Array Declarations
406///
407class ConstantArray final : public ConstantAggregate {
408 friend struct ConstantAggrKeyType<ConstantArray>;
409 friend class Constant;
410
411 ConstantArray(ArrayType *T, ArrayRef<Constant *> Val);
412
413 void destroyConstantImpl();
414 Value *handleOperandChangeImpl(Value *From, Value *To);
415
416public:
417 // ConstantArray accessors
418 static Constant *get(ArrayType *T, ArrayRef<Constant *> V);
419
420private:
421 static Constant *getImpl(ArrayType *T, ArrayRef<Constant *> V);
422
423public:
424 /// Specialize the getType() method to always return an ArrayType,
425 /// which reduces the amount of casting needed in parts of the compiler.
426 inline ArrayType *getType() const {
427 return cast<ArrayType>(Value::getType());
428 }
429
430 /// Methods for support type inquiry through isa, cast, and dyn_cast:
431 static bool classof(const Value *V) {
432 return V->getValueID() == ConstantArrayVal;
433 }
434};
435
436//===----------------------------------------------------------------------===//
437// Constant Struct Declarations
438//
439class ConstantStruct final : public ConstantAggregate {
440 friend struct ConstantAggrKeyType<ConstantStruct>;
441 friend class Constant;
442
443 ConstantStruct(StructType *T, ArrayRef<Constant *> Val);
444
445 void destroyConstantImpl();
446 Value *handleOperandChangeImpl(Value *From, Value *To);
447
448public:
449 // ConstantStruct accessors
450 static Constant *get(StructType *T, ArrayRef<Constant *> V);
451
452 template <typename... Csts>
453 static std::enable_if_t<are_base_of<Constant, Csts...>::value, Constant *>
454 get(StructType *T, Csts *...Vs) {
455 SmallVector<Constant *, 8> Values({Vs...});
456 return get(T, Values);
457 }
458
459 /// Return an anonymous struct that has the specified elements.
460 /// If the struct is possibly empty, then you must specify a context.
461 static Constant *getAnon(ArrayRef<Constant *> V, bool Packed = false) {
462 return get(getTypeForElements(V, Packed), V);
463 }
464 static Constant *getAnon(LLVMContext &Ctx, ArrayRef<Constant *> V,
465 bool Packed = false) {
466 return get(getTypeForElements(Ctx, V, Packed), V);
467 }
468
469 /// Return an anonymous struct type to use for a constant with the specified
470 /// set of elements. The list must not be empty.
471 static StructType *getTypeForElements(ArrayRef<Constant *> V,
472 bool Packed = false);
473 /// This version of the method allows an empty list.
474 static StructType *getTypeForElements(LLVMContext &Ctx,
475 ArrayRef<Constant *> V,
476 bool Packed = false);
477
478 /// Specialization - reduce amount of casting.
479 inline StructType *getType() const {
480 return cast<StructType>(Value::getType());
481 }
482
483 /// Methods for support type inquiry through isa, cast, and dyn_cast:
484 static bool classof(const Value *V) {
485 return V->getValueID() == ConstantStructVal;
486 }
487};
488
489//===----------------------------------------------------------------------===//
490/// Constant Vector Declarations
491///
492class ConstantVector final : public ConstantAggregate {
493 friend struct ConstantAggrKeyType<ConstantVector>;
494 friend class Constant;
495
496 ConstantVector(VectorType *T, ArrayRef<Constant *> Val);
497
498 void destroyConstantImpl();
499 Value *handleOperandChangeImpl(Value *From, Value *To);
500
501public:
502 // ConstantVector accessors
503 static Constant *get(ArrayRef<Constant *> V);
504
505private:
506 static Constant *getImpl(ArrayRef<Constant *> V);
507
508public:
509 /// Return a ConstantVector with the specified constant in each element.
510 /// Note that this might not return an instance of ConstantVector
511 static Constant *getSplat(ElementCount EC, Constant *Elt);
512
513 /// Specialize the getType() method to always return a FixedVectorType,
514 /// which reduces the amount of casting needed in parts of the compiler.
515 inline FixedVectorType *getType() const {
516 return cast<FixedVectorType>(Value::getType());
517 }
518
519 /// If all elements of the vector constant have the same value, return that
520 /// value. Otherwise, return nullptr. Ignore undefined elements by setting
521 /// AllowUndefs to true.
522 Constant *getSplatValue(bool AllowUndefs = false) const;
523
524 /// Methods for support type inquiry through isa, cast, and dyn_cast:
525 static bool classof(const Value *V) {
526 return V->getValueID() == ConstantVectorVal;
527 }
528};
529
530//===----------------------------------------------------------------------===//
531/// A constant pointer value that points to null
532///
533class ConstantPointerNull final : public ConstantData {
534 friend class Constant;
535
536 explicit ConstantPointerNull(PointerType *T)
537 : ConstantData(T, Value::ConstantPointerNullVal) {}
538
539 void destroyConstantImpl();
540
541public:
542 ConstantPointerNull(const ConstantPointerNull &) = delete;
543
544 /// Static factory methods - Return objects of the specified value
545 static ConstantPointerNull *get(PointerType *T);
546
547 /// Specialize the getType() method to always return an PointerType,
548 /// which reduces the amount of casting needed in parts of the compiler.
549 inline PointerType *getType() const {
550 return cast<PointerType>(Value::getType());
551 }
552
553 /// Methods for support type inquiry through isa, cast, and dyn_cast:
554 static bool classof(const Value *V) {
555 return V->getValueID() == ConstantPointerNullVal;
556 }
557};
558
559//===----------------------------------------------------------------------===//
560/// ConstantDataSequential - A vector or array constant whose element type is a
561/// simple 1/2/4/8-byte integer or half/bfloat/float/double, and whose elements
562/// are just simple data values (i.e. ConstantInt/ConstantFP). This Constant
563/// node has no operands because it stores all of the elements of the constant
564/// as densely packed data, instead of as Value*'s.
565///
566/// This is the common base class of ConstantDataArray and ConstantDataVector.
567///
568class ConstantDataSequential : public ConstantData {
569 friend class LLVMContextImpl;
570 friend class Constant;
571
572 /// A pointer to the bytes underlying this constant (which is owned by the
573 /// uniquing StringMap).
574 const char *DataElements;
575
576 /// This forms a link list of ConstantDataSequential nodes that have
577 /// the same value but different type. For example, 0,0,0,1 could be a 4
578 /// element array of i8, or a 1-element array of i32. They'll both end up in
579 /// the same StringMap bucket, linked up.
580 std::unique_ptr<ConstantDataSequential> Next;
581
582 void destroyConstantImpl();
583
584protected:
585 explicit ConstantDataSequential(Type *ty, ValueTy VT, const char *Data)
586 : ConstantData(ty, VT), DataElements(Data) {}
587
588 static Constant *getImpl(StringRef Bytes, Type *Ty);
589
590public:
591 ConstantDataSequential(const ConstantDataSequential &) = delete;
592
593 /// Return true if a ConstantDataSequential can be formed with a vector or
594 /// array of the specified element type.
595 /// ConstantDataArray only works with normal float and int types that are
596 /// stored densely in memory, not with things like i42 or x86_f80.
597 static bool isElementTypeCompatible(Type *Ty);
598
599 /// If this is a sequential container of integers (of any size), return the
600 /// specified element in the low bits of a uint64_t.
601 uint64_t getElementAsInteger(unsigned i) const;
602
603 /// If this is a sequential container of integers (of any size), return the
604 /// specified element as an APInt.
605 APInt getElementAsAPInt(unsigned i) const;
606
607 /// If this is a sequential container of floating point type, return the
608 /// specified element as an APFloat.
609 APFloat getElementAsAPFloat(unsigned i) const;
610
611 /// If this is an sequential container of floats, return the specified element
612 /// as a float.
613 float getElementAsFloat(unsigned i) const;
614
615 /// If this is an sequential container of doubles, return the specified
616 /// element as a double.
617 double getElementAsDouble(unsigned i) const;
618
619 /// Return a Constant for a specified index's element.
620 /// Note that this has to compute a new constant to return, so it isn't as
621 /// efficient as getElementAsInteger/Float/Double.
622 Constant *getElementAsConstant(unsigned i) const;
623
624 /// Return the element type of the array/vector.
625 Type *getElementType() const;
626
627 /// Return the number of elements in the array or vector.
628 unsigned getNumElements() const;
629
630 /// Return the size (in bytes) of each element in the array/vector.
631 /// The size of the elements is known to be a multiple of one byte.
632 uint64_t getElementByteSize() const;
633
634 /// This method returns true if this is an array of \p CharSize integers.
635 bool isString(unsigned CharSize = 8) const;
636
637 /// This method returns true if the array "isString", ends with a null byte,
638 /// and does not contains any other null bytes.
639 bool isCString() const;
640
641 /// If this array is isString(), then this method returns the array as a
642 /// StringRef. Otherwise, it asserts out.
643 StringRef getAsString() const {
644 assert(isString() && "Not a string")(static_cast <bool> (isString() && "Not a string"
) ? void (0) : __assert_fail ("isString() && \"Not a string\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/Constants.h"
, 644, __extension__ __PRETTY_FUNCTION__))
;
645 return getRawDataValues();
646 }
647
648 /// If this array is isCString(), then this method returns the array (without
649 /// the trailing null byte) as a StringRef. Otherwise, it asserts out.
650 StringRef getAsCString() const {
651 assert(isCString() && "Isn't a C string")(static_cast <bool> (isCString() && "Isn't a C string"
) ? void (0) : __assert_fail ("isCString() && \"Isn't a C string\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/Constants.h"
, 651, __extension__ __PRETTY_FUNCTION__))
;
652 StringRef Str = getAsString();
653 return Str.substr(0, Str.size() - 1);
654 }
655
656 /// Return the raw, underlying, bytes of this data. Note that this is an
657 /// extremely tricky thing to work with, as it exposes the host endianness of
658 /// the data elements.
659 StringRef getRawDataValues() const;
660
661 /// Methods for support type inquiry through isa, cast, and dyn_cast:
662 static bool classof(const Value *V) {
663 return V->getValueID() == ConstantDataArrayVal ||
664 V->getValueID() == ConstantDataVectorVal;
665 }
666
667private:
668 const char *getElementPointer(unsigned Elt) const;
669};
670
671//===----------------------------------------------------------------------===//
672/// An array constant whose element type is a simple 1/2/4/8-byte integer or
673/// float/double, and whose elements are just simple data values
674/// (i.e. ConstantInt/ConstantFP). This Constant node has no operands because it
675/// stores all of the elements of the constant as densely packed data, instead
676/// of as Value*'s.
677class ConstantDataArray final : public ConstantDataSequential {
678 friend class ConstantDataSequential;
679
680 explicit ConstantDataArray(Type *ty, const char *Data)
681 : ConstantDataSequential(ty, ConstantDataArrayVal, Data) {}
682
683public:
684 ConstantDataArray(const ConstantDataArray &) = delete;
685
686 /// get() constructor - Return a constant with array type with an element
687 /// count and element type matching the ArrayRef passed in. Note that this
688 /// can return a ConstantAggregateZero object.
689 template <typename ElementTy>
690 static Constant *get(LLVMContext &Context, ArrayRef<ElementTy> Elts) {
691 const char *Data = reinterpret_cast<const char *>(Elts.data());
692 return getRaw(StringRef(Data, Elts.size() * sizeof(ElementTy)), Elts.size(),
693 Type::getScalarTy<ElementTy>(Context));
694 }
695
696 /// get() constructor - ArrayTy needs to be compatible with
697 /// ArrayRef<ElementTy>. Calls get(LLVMContext, ArrayRef<ElementTy>).
698 template <typename ArrayTy>
699 static Constant *get(LLVMContext &Context, ArrayTy &Elts) {
700 return ConstantDataArray::get(Context, makeArrayRef(Elts));
701 }
702
703 /// getRaw() constructor - Return a constant with array type with an element
704 /// count and element type matching the NumElements and ElementTy parameters
705 /// passed in. Note that this can return a ConstantAggregateZero object.
706 /// ElementTy must be one of i8/i16/i32/i64/half/bfloat/float/double. Data is
707 /// the buffer containing the elements. Be careful to make sure Data uses the
708 /// right endianness, the buffer will be used as-is.
709 static Constant *getRaw(StringRef Data, uint64_t NumElements,
710 Type *ElementTy) {
711 Type *Ty = ArrayType::get(ElementTy, NumElements);
712 return getImpl(Data, Ty);
713 }
714
715 /// getFP() constructors - Return a constant of array type with a float
716 /// element type taken from argument `ElementType', and count taken from
717 /// argument `Elts'. The amount of bits of the contained type must match the
718 /// number of bits of the type contained in the passed in ArrayRef.
719 /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
720 /// that this can return a ConstantAggregateZero object.
721 static Constant *getFP(Type *ElementType, ArrayRef<uint16_t> Elts);
722 static Constant *getFP(Type *ElementType, ArrayRef<uint32_t> Elts);
723 static Constant *getFP(Type *ElementType, ArrayRef<uint64_t> Elts);
724
725 /// This method constructs a CDS and initializes it with a text string.
726 /// The default behavior (AddNull==true) causes a null terminator to
727 /// be placed at the end of the array (increasing the length of the string by
728 /// one more than the StringRef would normally indicate. Pass AddNull=false
729 /// to disable this behavior.
730 static Constant *getString(LLVMContext &Context, StringRef Initializer,
731 bool AddNull = true);
732
733 /// Specialize the getType() method to always return an ArrayType,
734 /// which reduces the amount of casting needed in parts of the compiler.
735 inline ArrayType *getType() const {
736 return cast<ArrayType>(Value::getType());
737 }
738
739 /// Methods for support type inquiry through isa, cast, and dyn_cast:
740 static bool classof(const Value *V) {
741 return V->getValueID() == ConstantDataArrayVal;
742 }
743};
744
745//===----------------------------------------------------------------------===//
746/// A vector constant whose element type is a simple 1/2/4/8-byte integer or
747/// float/double, and whose elements are just simple data values
748/// (i.e. ConstantInt/ConstantFP). This Constant node has no operands because it
749/// stores all of the elements of the constant as densely packed data, instead
750/// of as Value*'s.
751class ConstantDataVector final : public ConstantDataSequential {
752 friend class ConstantDataSequential;
753
754 explicit ConstantDataVector(Type *ty, const char *Data)
755 : ConstantDataSequential(ty, ConstantDataVectorVal, Data),
756 IsSplatSet(false) {}
757 // Cache whether or not the constant is a splat.
758 mutable bool IsSplatSet : 1;
759 mutable bool IsSplat : 1;
760 bool isSplatData() const;
761
762public:
763 ConstantDataVector(const ConstantDataVector &) = delete;
764
765 /// get() constructors - Return a constant with vector type with an element
766 /// count and element type matching the ArrayRef passed in. Note that this
767 /// can return a ConstantAggregateZero object.
768 static Constant *get(LLVMContext &Context, ArrayRef<uint8_t> Elts);
769 static Constant *get(LLVMContext &Context, ArrayRef<uint16_t> Elts);
770 static Constant *get(LLVMContext &Context, ArrayRef<uint32_t> Elts);
771 static Constant *get(LLVMContext &Context, ArrayRef<uint64_t> Elts);
772 static Constant *get(LLVMContext &Context, ArrayRef<float> Elts);
773 static Constant *get(LLVMContext &Context, ArrayRef<double> Elts);
774
775 /// getRaw() constructor - Return a constant with vector type with an element
776 /// count and element type matching the NumElements and ElementTy parameters
777 /// passed in. Note that this can return a ConstantAggregateZero object.
778 /// ElementTy must be one of i8/i16/i32/i64/half/bfloat/float/double. Data is
779 /// the buffer containing the elements. Be careful to make sure Data uses the
780 /// right endianness, the buffer will be used as-is.
781 static Constant *getRaw(StringRef Data, uint64_t NumElements,
782 Type *ElementTy) {
783 Type *Ty = VectorType::get(ElementTy, ElementCount::getFixed(NumElements));
784 return getImpl(Data, Ty);
785 }
786
787 /// getFP() constructors - Return a constant of vector type with a float
788 /// element type taken from argument `ElementType', and count taken from
789 /// argument `Elts'. The amount of bits of the contained type must match the
790 /// number of bits of the type contained in the passed in ArrayRef.
791 /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
792 /// that this can return a ConstantAggregateZero object.
793 static Constant *getFP(Type *ElementType, ArrayRef<uint16_t> Elts);
794 static Constant *getFP(Type *ElementType, ArrayRef<uint32_t> Elts);
795 static Constant *getFP(Type *ElementType, ArrayRef<uint64_t> Elts);
796
797 /// Return a ConstantVector with the specified constant in each element.
798 /// The specified constant has to be a of a compatible type (i8/i16/
799 /// i32/i64/half/bfloat/float/double) and must be a ConstantFP or ConstantInt.
800 static Constant *getSplat(unsigned NumElts, Constant *Elt);
801
802 /// Returns true if this is a splat constant, meaning that all elements have
803 /// the same value.
804 bool isSplat() const;
805
806 /// If this is a splat constant, meaning that all of the elements have the
807 /// same value, return that value. Otherwise return NULL.
808 Constant *getSplatValue() const;
809
810 /// Specialize the getType() method to always return a FixedVectorType,
811 /// which reduces the amount of casting needed in parts of the compiler.
812 inline FixedVectorType *getType() const {
813 return cast<FixedVectorType>(Value::getType());
814 }
815
816 /// Methods for support type inquiry through isa, cast, and dyn_cast:
817 static bool classof(const Value *V) {
818 return V->getValueID() == ConstantDataVectorVal;
819 }
820};
821
822//===----------------------------------------------------------------------===//
823/// A constant token which is empty
824///
825class ConstantTokenNone final : public ConstantData {
826 friend class Constant;
827
828 explicit ConstantTokenNone(LLVMContext &Context)
829 : ConstantData(Type::getTokenTy(Context), ConstantTokenNoneVal) {}
830
831 void destroyConstantImpl();
832
833public:
834 ConstantTokenNone(const ConstantTokenNone &) = delete;
835
836 /// Return the ConstantTokenNone.
837 static ConstantTokenNone *get(LLVMContext &Context);
838
839 /// Methods to support type inquiry through isa, cast, and dyn_cast.
840 static bool classof(const Value *V) {
841 return V->getValueID() == ConstantTokenNoneVal;
842 }
843};
844
845/// The address of a basic block.
846///
847class BlockAddress final : public Constant {
848 friend class Constant;
849
850 BlockAddress(Function *F, BasicBlock *BB);
851
852 void *operator new(size_t s) { return User::operator new(s, 2); }
853
854 void destroyConstantImpl();
855 Value *handleOperandChangeImpl(Value *From, Value *To);
856
857public:
858 /// Return a BlockAddress for the specified function and basic block.
859 static BlockAddress *get(Function *F, BasicBlock *BB);
860
861 /// Return a BlockAddress for the specified basic block. The basic
862 /// block must be embedded into a function.
863 static BlockAddress *get(BasicBlock *BB);
864
865 /// Lookup an existing \c BlockAddress constant for the given BasicBlock.
866 ///
867 /// \returns 0 if \c !BB->hasAddressTaken(), otherwise the \c BlockAddress.
868 static BlockAddress *lookup(const BasicBlock *BB);
869
870 /// Transparently provide more efficient getOperand methods.
871 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
872
873 Function *getFunction() const { return (Function *)Op<0>().get(); }
874 BasicBlock *getBasicBlock() const { return (BasicBlock *)Op<1>().get(); }
875
876 /// Methods for support type inquiry through isa, cast, and dyn_cast:
877 static bool classof(const Value *V) {
878 return V->getValueID() == BlockAddressVal;
879 }
880};
881
882template <>
883struct OperandTraits<BlockAddress>
884 : public FixedNumOperandTraits<BlockAddress, 2> {};
885
886DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BlockAddress, Value)BlockAddress::op_iterator BlockAddress::op_begin() { return OperandTraits
<BlockAddress>::op_begin(this); } BlockAddress::const_op_iterator
BlockAddress::op_begin() const { return OperandTraits<BlockAddress
>::op_begin(const_cast<BlockAddress*>(this)); } BlockAddress
::op_iterator BlockAddress::op_end() { return OperandTraits<
BlockAddress>::op_end(this); } BlockAddress::const_op_iterator
BlockAddress::op_end() const { return OperandTraits<BlockAddress
>::op_end(const_cast<BlockAddress*>(this)); } Value *
BlockAddress::getOperand(unsigned i_nocapture) const { (static_cast
<bool> (i_nocapture < OperandTraits<BlockAddress
>::operands(this) && "getOperand() out of range!")
? void (0) : __assert_fail ("i_nocapture < OperandTraits<BlockAddress>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/Constants.h"
, 886, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<BlockAddress>::op_begin(const_cast
<BlockAddress*>(this))[i_nocapture].get()); } void BlockAddress
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast
<bool> (i_nocapture < OperandTraits<BlockAddress
>::operands(this) && "setOperand() out of range!")
? void (0) : __assert_fail ("i_nocapture < OperandTraits<BlockAddress>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/Constants.h"
, 886, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
BlockAddress>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned BlockAddress::getNumOperands() const { return OperandTraits
<BlockAddress>::operands(this); } template <int Idx_nocapture
> Use &BlockAddress::Op() { return this->OpFrom<
Idx_nocapture>(this); } template <int Idx_nocapture>
const Use &BlockAddress::Op() const { return this->OpFrom
<Idx_nocapture>(this); }
887
888/// Wrapper for a function that represents a value that
889/// functionally represents the original function. This can be a function,
890/// global alias to a function, or an ifunc.
891class DSOLocalEquivalent final : public Constant {
892 friend class Constant;
893
894 DSOLocalEquivalent(GlobalValue *GV);
895
896 void *operator new(size_t s) { return User::operator new(s, 1); }
897
898 void destroyConstantImpl();
899 Value *handleOperandChangeImpl(Value *From, Value *To);
900
901public:
902 /// Return a DSOLocalEquivalent for the specified global value.
903 static DSOLocalEquivalent *get(GlobalValue *GV);
904
905 /// Transparently provide more efficient getOperand methods.
906 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
907
908 GlobalValue *getGlobalValue() const {
909 return cast<GlobalValue>(Op<0>().get());
910 }
911
912 /// Methods for support type inquiry through isa, cast, and dyn_cast:
913 static bool classof(const Value *V) {
914 return V->getValueID() == DSOLocalEquivalentVal;
915 }
916};
917
918template <>
919struct OperandTraits<DSOLocalEquivalent>
920 : public FixedNumOperandTraits<DSOLocalEquivalent, 1> {};
921
922DEFINE_TRANSPARENT_OPERAND_ACCESSORS(DSOLocalEquivalent, Value)DSOLocalEquivalent::op_iterator DSOLocalEquivalent::op_begin(
) { return OperandTraits<DSOLocalEquivalent>::op_begin(
this); } DSOLocalEquivalent::const_op_iterator DSOLocalEquivalent
::op_begin() const { return OperandTraits<DSOLocalEquivalent
>::op_begin(const_cast<DSOLocalEquivalent*>(this)); }
DSOLocalEquivalent::op_iterator DSOLocalEquivalent::op_end()
{ return OperandTraits<DSOLocalEquivalent>::op_end(this
); } DSOLocalEquivalent::const_op_iterator DSOLocalEquivalent
::op_end() const { return OperandTraits<DSOLocalEquivalent
>::op_end(const_cast<DSOLocalEquivalent*>(this)); } Value
*DSOLocalEquivalent::getOperand(unsigned i_nocapture) const {
(static_cast <bool> (i_nocapture < OperandTraits<
DSOLocalEquivalent>::operands(this) && "getOperand() out of range!"
) ? void (0) : __assert_fail ("i_nocapture < OperandTraits<DSOLocalEquivalent>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/Constants.h"
, 922, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<DSOLocalEquivalent>::op_begin
(const_cast<DSOLocalEquivalent*>(this))[i_nocapture].get
()); } void DSOLocalEquivalent::setOperand(unsigned i_nocapture
, Value *Val_nocapture) { (static_cast <bool> (i_nocapture
< OperandTraits<DSOLocalEquivalent>::operands(this)
&& "setOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<DSOLocalEquivalent>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/Constants.h"
, 922, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
DSOLocalEquivalent>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned DSOLocalEquivalent::getNumOperands() const { return
OperandTraits<DSOLocalEquivalent>::operands(this); } template
<int Idx_nocapture> Use &DSOLocalEquivalent::Op() {
return this->OpFrom<Idx_nocapture>(this); } template
<int Idx_nocapture> const Use &DSOLocalEquivalent::
Op() const { return this->OpFrom<Idx_nocapture>(this
); }
923
924//===----------------------------------------------------------------------===//
925/// A constant value that is initialized with an expression using
926/// other constant values.
927///
928/// This class uses the standard Instruction opcodes to define the various
929/// constant expressions. The Opcode field for the ConstantExpr class is
930/// maintained in the Value::SubclassData field.
931class ConstantExpr : public Constant {
932 friend struct ConstantExprKeyType;
933 friend class Constant;
934
935 void destroyConstantImpl();
936 Value *handleOperandChangeImpl(Value *From, Value *To);
937
938protected:
939 ConstantExpr(Type *ty, unsigned Opcode, Use *Ops, unsigned NumOps)
940 : Constant(ty, ConstantExprVal, Ops, NumOps) {
941 // Operation type (an Instruction opcode) is stored as the SubclassData.
942 setValueSubclassData(Opcode);
943 }
944
945 ~ConstantExpr() = default;
946
947public:
948 // Static methods to construct a ConstantExpr of different kinds. Note that
949 // these methods may return a object that is not an instance of the
950 // ConstantExpr class, because they will attempt to fold the constant
951 // expression into something simpler if possible.
952
953 /// getAlignOf constant expr - computes the alignment of a type in a target
954 /// independent way (Note: the return type is an i64).
955 static Constant *getAlignOf(Type *Ty);
956
957 /// getSizeOf constant expr - computes the (alloc) size of a type (in
958 /// address-units, not bits) in a target independent way (Note: the return
959 /// type is an i64).
960 ///
961 static Constant *getSizeOf(Type *Ty);
962
963 /// getOffsetOf constant expr - computes the offset of a struct field in a
964 /// target independent way (Note: the return type is an i64).
965 ///
966 static Constant *getOffsetOf(StructType *STy, unsigned FieldNo);
967
968 /// getOffsetOf constant expr - This is a generalized form of getOffsetOf,
969 /// which supports any aggregate type, and any Constant index.
970 ///
971 static Constant *getOffsetOf(Type *Ty, Constant *FieldNo);
972
973 static Constant *getNeg(Constant *C, bool HasNUW = false,
974 bool HasNSW = false);
975 static Constant *getFNeg(Constant *C);
976 static Constant *getNot(Constant *C);
977 static Constant *getAdd(Constant *C1, Constant *C2, bool HasNUW = false,
978 bool HasNSW = false);
979 static Constant *getFAdd(Constant *C1, Constant *C2);
980 static Constant *getSub(Constant *C1, Constant *C2, bool HasNUW = false,
981 bool HasNSW = false);
982 static Constant *getFSub(Constant *C1, Constant *C2);
983 static Constant *getMul(Constant *C1, Constant *C2, bool HasNUW = false,
984 bool HasNSW = false);
985 static Constant *getFMul(Constant *C1, Constant *C2);
986 static Constant *getUDiv(Constant *C1, Constant *C2, bool isExact = false);
987 static Constant *getSDiv(Constant *C1, Constant *C2, bool isExact = false);
988 static Constant *getFDiv(Constant *C1, Constant *C2);
989 static Constant *getURem(Constant *C1, Constant *C2);
990 static Constant *getSRem(Constant *C1, Constant *C2);
991 static Constant *getFRem(Constant *C1, Constant *C2);
992 static Constant *getAnd(Constant *C1, Constant *C2);
993 static Constant *getOr(Constant *C1, Constant *C2);
994 static Constant *getXor(Constant *C1, Constant *C2);
995 static Constant *getUMin(Constant *C1, Constant *C2);
996 static Constant *getShl(Constant *C1, Constant *C2, bool HasNUW = false,
997 bool HasNSW = false);
998 static Constant *getLShr(Constant *C1, Constant *C2, bool isExact = false);
999 static Constant *getAShr(Constant *C1, Constant *C2, bool isExact = false);
1000 static Constant *getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced = false);
1001 static Constant *getSExt(Constant *C, Type *Ty, bool OnlyIfReduced = false);
1002 static Constant *getZExt(Constant *C, Type *Ty, bool OnlyIfReduced = false);
1003 static Constant *getFPTrunc(Constant *C, Type *Ty,
1004 bool OnlyIfReduced = false);
1005 static Constant *getFPExtend(Constant *C, Type *Ty,
1006 bool OnlyIfReduced = false);
1007 static Constant *getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced = false);
1008 static Constant *getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced = false);
1009 static Constant *getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced = false);
1010 static Constant *getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced = false);
1011 static Constant *getPtrToInt(Constant *C, Type *Ty,
1012 bool OnlyIfReduced = false);
1013 static Constant *getIntToPtr(Constant *C, Type *Ty,
1014 bool OnlyIfReduced = false);
1015 static Constant *getBitCast(Constant *C, Type *Ty,
1016 bool OnlyIfReduced = false);
1017 static Constant *getAddrSpaceCast(Constant *C, Type *Ty,
1018 bool OnlyIfReduced = false);
1019
1020 static Constant *getNSWNeg(Constant *C) { return getNeg(C, false, true); }
1021 static Constant *getNUWNeg(Constant *C) { return getNeg(C, true, false); }
1022
1023 static Constant *getNSWAdd(Constant *C1, Constant *C2) {
1024 return getAdd(C1, C2, false, true);
1025 }
1026
1027 static Constant *getNUWAdd(Constant *C1, Constant *C2) {
1028 return getAdd(C1, C2, true, false);
1029 }
1030
1031 static Constant *getNSWSub(Constant *C1, Constant *C2) {
1032 return getSub(C1, C2, false, true);
1033 }
1034
1035 static Constant *getNUWSub(Constant *C1, Constant *C2) {
1036 return getSub(C1, C2, true, false);
1037 }
1038
1039 static Constant *getNSWMul(Constant *C1, Constant *C2) {
1040 return getMul(C1, C2, false, true);
1041 }
1042
1043 static Constant *getNUWMul(Constant *C1, Constant *C2) {
1044 return getMul(C1, C2, true, false);
1045 }
1046
1047 static Constant *getNSWShl(Constant *C1, Constant *C2) {
1048 return getShl(C1, C2, false, true);
1049 }
1050
1051 static Constant *getNUWShl(Constant *C1, Constant *C2) {
1052 return getShl(C1, C2, true, false);
1053 }
1054
1055 static Constant *getExactSDiv(Constant *C1, Constant *C2) {
1056 return getSDiv(C1, C2, true);
1057 }
1058
1059 static Constant *getExactUDiv(Constant *C1, Constant *C2) {
1060 return getUDiv(C1, C2, true);
1061 }
1062
1063 static Constant *getExactAShr(Constant *C1, Constant *C2) {
1064 return getAShr(C1, C2, true);
1065 }
1066
1067 static Constant *getExactLShr(Constant *C1, Constant *C2) {
1068 return getLShr(C1, C2, true);
1069 }
1070
1071 /// If C is a scalar/fixed width vector of known powers of 2, then this
1072 /// function returns a new scalar/fixed width vector obtained from logBase2
1073 /// of C. Undef vector elements are set to zero.
1074 /// Return a null pointer otherwise.
1075 static Constant *getExactLogBase2(Constant *C);
1076
1077 /// Return the identity constant for a binary opcode.
1078 /// The identity constant C is defined as X op C = X and C op X = X for every
1079 /// X when the binary operation is commutative. If the binop is not
1080 /// commutative, callers can acquire the operand 1 identity constant by
1081 /// setting AllowRHSConstant to true. For example, any shift has a zero
1082 /// identity constant for operand 1: X shift 0 = X.
1083 /// Return nullptr if the operator does not have an identity constant.
1084 static Constant *getBinOpIdentity(unsigned Opcode, Type *Ty,
1085 bool AllowRHSConstant = false);
1086
1087 /// Return the absorbing element for the given binary
1088 /// operation, i.e. a constant C such that X op C = C and C op X = C for
1089 /// every X. For example, this returns zero for integer multiplication.
1090 /// It returns null if the operator doesn't have an absorbing element.
1091 static Constant *getBinOpAbsorber(unsigned Opcode, Type *Ty);
1092
1093 /// Transparently provide more efficient getOperand methods.
1094 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant)public: inline Constant *getOperand(unsigned) const; inline void
setOperand(unsigned, Constant*); inline op_iterator op_begin
(); inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
1095
1096 /// Convenience function for getting a Cast operation.
1097 ///
1098 /// \param ops The opcode for the conversion
1099 /// \param C The constant to be converted
1100 /// \param Ty The type to which the constant is converted
1101 /// \param OnlyIfReduced see \a getWithOperands() docs.
1102 static Constant *getCast(unsigned ops, Constant *C, Type *Ty,
1103 bool OnlyIfReduced = false);
1104
1105 // Create a ZExt or BitCast cast constant expression
1106 static Constant *
1107 getZExtOrBitCast(Constant *C, ///< The constant to zext or bitcast
1108 Type *Ty ///< The type to zext or bitcast C to
1109 );
1110
1111 // Create a SExt or BitCast cast constant expression
1112 static Constant *
1113 getSExtOrBitCast(Constant *C, ///< The constant to sext or bitcast
1114 Type *Ty ///< The type to sext or bitcast C to
1115 );
1116
1117 // Create a Trunc or BitCast cast constant expression
1118 static Constant *
1119 getTruncOrBitCast(Constant *C, ///< The constant to trunc or bitcast
1120 Type *Ty ///< The type to trunc or bitcast C to
1121 );
1122
1123 /// Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant
1124 /// expression.
1125 static Constant *
1126 getPointerCast(Constant *C, ///< The pointer value to be casted (operand 0)
1127 Type *Ty ///< The type to which cast should be made
1128 );
1129
1130 /// Create a BitCast or AddrSpaceCast for a pointer type depending on
1131 /// the address space.
1132 static Constant *getPointerBitCastOrAddrSpaceCast(
1133 Constant *C, ///< The constant to addrspacecast or bitcast
1134 Type *Ty ///< The type to bitcast or addrspacecast C to
1135 );
1136
1137 /// Create a ZExt, Bitcast or Trunc for integer -> integer casts
1138 static Constant *
1139 getIntegerCast(Constant *C, ///< The integer constant to be casted
1140 Type *Ty, ///< The integer type to cast to
1141 bool IsSigned ///< Whether C should be treated as signed or not
1142 );
1143
1144 /// Create a FPExt, Bitcast or FPTrunc for fp -> fp casts
1145 static Constant *getFPCast(Constant *C, ///< The integer constant to be casted
1146 Type *Ty ///< The integer type to cast to
1147 );
1148
1149 /// Return true if this is a convert constant expression
1150 bool isCast() const;
1151
1152 /// Return true if this is a compare constant expression
1153 bool isCompare() const;
1154
1155 /// Return true if this is an insertvalue or extractvalue expression,
1156 /// and the getIndices() method may be used.
1157 bool hasIndices() const;
1158
1159 /// Return true if this is a getelementptr expression and all
1160 /// the index operands are compile-time known integers within the
1161 /// corresponding notional static array extents. Note that this is
1162 /// not equivalant to, a subset of, or a superset of the "inbounds"
1163 /// property.
1164 bool isGEPWithNoNotionalOverIndexing() const;
1165
1166 /// Select constant expr
1167 ///
1168 /// \param OnlyIfReducedTy see \a getWithOperands() docs.
1169 static Constant *getSelect(Constant *C, Constant *V1, Constant *V2,
1170 Type *OnlyIfReducedTy = nullptr);
1171
1172 /// get - Return a unary operator constant expression,
1173 /// folding if possible.
1174 ///
1175 /// \param OnlyIfReducedTy see \a getWithOperands() docs.
1176 static Constant *get(unsigned Opcode, Constant *C1, unsigned Flags = 0,
1177 Type *OnlyIfReducedTy = nullptr);
1178
1179 /// get - Return a binary or shift operator constant expression,
1180 /// folding if possible.
1181 ///
1182 /// \param OnlyIfReducedTy see \a getWithOperands() docs.
1183 static Constant *get(unsigned Opcode, Constant *C1, Constant *C2,
1184 unsigned Flags = 0, Type *OnlyIfReducedTy = nullptr);
1185
1186 /// Return an ICmp or FCmp comparison operator constant expression.
1187 ///
1188 /// \param OnlyIfReduced see \a getWithOperands() docs.
1189 static Constant *getCompare(unsigned short pred, Constant *C1, Constant *C2,
1190 bool OnlyIfReduced = false);
1191
1192 /// get* - Return some common constants without having to
1193 /// specify the full Instruction::OPCODE identifier.
1194 ///
1195 static Constant *getICmp(unsigned short pred, Constant *LHS, Constant *RHS,
1196 bool OnlyIfReduced = false);
1197 static Constant *getFCmp(unsigned short pred, Constant *LHS, Constant *RHS,
1198 bool OnlyIfReduced = false);
1199
1200 /// Getelementptr form. Value* is only accepted for convenience;
1201 /// all elements must be Constants.
1202 ///
1203 /// \param InRangeIndex the inrange index if present or None.
1204 /// \param OnlyIfReducedTy see \a getWithOperands() docs.
1205 static Constant *getGetElementPtr(Type *Ty, Constant *C,
1206 ArrayRef<Constant *> IdxList,
1207 bool InBounds = false,
1208 Optional<unsigned> InRangeIndex = None,
1209 Type *OnlyIfReducedTy = nullptr) {
1210 return getGetElementPtr(
1211 Ty, C, makeArrayRef((Value *const *)IdxList.data(), IdxList.size()),
1212 InBounds, InRangeIndex, OnlyIfReducedTy);
1213 }
1214 static Constant *getGetElementPtr(Type *Ty, Constant *C, Constant *Idx,
1215 bool InBounds = false,
1216 Optional<unsigned> InRangeIndex = None,
1217 Type *OnlyIfReducedTy = nullptr) {
1218 // This form of the function only exists to avoid ambiguous overload
1219 // warnings about whether to convert Idx to ArrayRef<Constant *> or
1220 // ArrayRef<Value *>.
1221 return getGetElementPtr(Ty, C, cast<Value>(Idx), InBounds, InRangeIndex,
1222 OnlyIfReducedTy);
1223 }
1224 static Constant *getGetElementPtr(Type *Ty, Constant *C,
1225 ArrayRef<Value *> IdxList,
1226 bool InBounds = false,
1227 Optional<unsigned> InRangeIndex = None,
1228 Type *OnlyIfReducedTy = nullptr);
1229
1230 /// Create an "inbounds" getelementptr. See the documentation for the
1231 /// "inbounds" flag in LangRef.html for details.
1232 static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
1233 ArrayRef<Constant *> IdxList) {
1234 return getGetElementPtr(Ty, C, IdxList, true);
1235 }
1236 static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
1237 Constant *Idx) {
1238 // This form of the function only exists to avoid ambiguous overload
1239 // warnings about whether to convert Idx to ArrayRef<Constant *> or
1240 // ArrayRef<Value *>.
1241 return getGetElementPtr(Ty, C, Idx, true);
1242 }
1243 static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
1244 ArrayRef<Value *> IdxList) {
1245 return getGetElementPtr(Ty, C, IdxList, true);
1246 }
1247
1248 static Constant *getExtractElement(Constant *Vec, Constant *Idx,
1249 Type *OnlyIfReducedTy = nullptr);
1250 static Constant *getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx,
1251 Type *OnlyIfReducedTy = nullptr);
1252 static Constant *getShuffleVector(Constant *V1, Constant *V2,
1253 ArrayRef<int> Mask,
1254 Type *OnlyIfReducedTy = nullptr);
1255 static Constant *getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
1256 Type *OnlyIfReducedTy = nullptr);
1257 static Constant *getInsertValue(Constant *Agg, Constant *Val,
1258 ArrayRef<unsigned> Idxs,
1259 Type *OnlyIfReducedTy = nullptr);
1260
1261 /// Return the opcode at the root of this constant expression
1262 unsigned getOpcode() const { return getSubclassDataFromValue(); }
1263
1264 /// Return the ICMP or FCMP predicate value. Assert if this is not an ICMP or
1265 /// FCMP constant expression.
1266 unsigned getPredicate() const;
1267
1268 /// Assert that this is an insertvalue or exactvalue
1269 /// expression and return the list of indices.
1270 ArrayRef<unsigned> getIndices() const;
1271
1272 /// Assert that this is a shufflevector and return the mask. See class
1273 /// ShuffleVectorInst for a description of the mask representation.
1274 ArrayRef<int> getShuffleMask() const;
1275
1276 /// Assert that this is a shufflevector and return the mask.
1277 ///
1278 /// TODO: This is a temporary hack until we update the bitcode format for
1279 /// shufflevector.
1280 Constant *getShuffleMaskForBitcode() const;
1281
1282 /// Return a string representation for an opcode.
1283 const char *getOpcodeName() const;
1284
1285 /// Return a constant expression identical to this one, but with the specified
1286 /// operand set to the specified value.
1287 Constant *getWithOperandReplaced(unsigned OpNo, Constant *Op) const;
1288
1289 /// This returns the current constant expression with the operands replaced
1290 /// with the specified values. The specified array must have the same number
1291 /// of operands as our current one.
1292 Constant *getWithOperands(ArrayRef<Constant *> Ops) const {
1293 return getWithOperands(Ops, getType());
1294 }
1295
1296 /// Get the current expression with the operands replaced.
1297 ///
1298 /// Return the current constant expression with the operands replaced with \c
1299 /// Ops and the type with \c Ty. The new operands must have the same number
1300 /// as the current ones.
1301 ///
1302 /// If \c OnlyIfReduced is \c true, nullptr will be returned unless something
1303 /// gets constant-folded, the type changes, or the expression is otherwise
1304 /// canonicalized. This parameter should almost always be \c false.
1305 Constant *getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
1306 bool OnlyIfReduced = false,
1307 Type *SrcTy = nullptr) const;
1308
1309 /// Returns an Instruction which implements the same operation as this
1310 /// ConstantExpr. The instruction is not linked to any basic block.
1311 ///
1312 /// A better approach to this could be to have a constructor for Instruction
1313 /// which would take a ConstantExpr parameter, but that would have spread
1314 /// implementation details of ConstantExpr outside of Constants.cpp, which
1315 /// would make it harder to remove ConstantExprs altogether.
1316 Instruction *getAsInstruction() const;
1317
1318 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1319 static bool classof(const Value *V) {
1320 return V->getValueID() == ConstantExprVal;
1321 }
1322
1323private:
1324 // Shadow Value::setValueSubclassData with a private forwarding method so that
1325 // subclasses cannot accidentally use it.
1326 void setValueSubclassData(unsigned short D) {
1327 Value::setValueSubclassData(D);
1328 }
1329};
1330
1331template <>
1332struct OperandTraits<ConstantExpr>
1333 : public VariadicOperandTraits<ConstantExpr, 1> {};
1334
1335DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantExpr, Constant)ConstantExpr::op_iterator ConstantExpr::op_begin() { return OperandTraits
<ConstantExpr>::op_begin(this); } ConstantExpr::const_op_iterator
ConstantExpr::op_begin() const { return OperandTraits<ConstantExpr
>::op_begin(const_cast<ConstantExpr*>(this)); } ConstantExpr
::op_iterator ConstantExpr::op_end() { return OperandTraits<
ConstantExpr>::op_end(this); } ConstantExpr::const_op_iterator
ConstantExpr::op_end() const { return OperandTraits<ConstantExpr
>::op_end(const_cast<ConstantExpr*>(this)); } Constant
*ConstantExpr::getOperand(unsigned i_nocapture) const { (static_cast
<bool> (i_nocapture < OperandTraits<ConstantExpr
>::operands(this) && "getOperand() out of range!")
? void (0) : __assert_fail ("i_nocapture < OperandTraits<ConstantExpr>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/Constants.h"
, 1335, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Constant>( OperandTraits<ConstantExpr>::op_begin
(const_cast<ConstantExpr*>(this))[i_nocapture].get()); }
void ConstantExpr::setOperand(unsigned i_nocapture, Constant
*Val_nocapture) { (static_cast <bool> (i_nocapture <
OperandTraits<ConstantExpr>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<ConstantExpr>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/IR/Constants.h"
, 1335, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
ConstantExpr>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned ConstantExpr::getNumOperands() const { return OperandTraits
<ConstantExpr>::operands(this); } template <int Idx_nocapture
> Use &ConstantExpr::Op() { return this->OpFrom<
Idx_nocapture>(this); } template <int Idx_nocapture>
const Use &ConstantExpr::Op() const { return this->OpFrom
<Idx_nocapture>(this); }
1336
1337//===----------------------------------------------------------------------===//
1338/// 'undef' values are things that do not have specified contents.
1339/// These are used for a variety of purposes, including global variable
1340/// initializers and operands to instructions. 'undef' values can occur with
1341/// any first-class type.
1342///
1343/// Undef values aren't exactly constants; if they have multiple uses, they
1344/// can appear to have different bit patterns at each use. See
1345/// LangRef.html#undefvalues for details.
1346///
1347class UndefValue : public ConstantData {
1348 friend class Constant;
1349
1350 explicit UndefValue(Type *T) : ConstantData(T, UndefValueVal) {}
1351
1352 void destroyConstantImpl();
1353
1354protected:
1355 explicit UndefValue(Type *T, ValueTy vty) : ConstantData(T, vty) {}
1356
1357public:
1358 UndefValue(const UndefValue &) = delete;
1359
1360 /// Static factory methods - Return an 'undef' object of the specified type.
1361 static UndefValue *get(Type *T);
1362
1363 /// If this Undef has array or vector type, return a undef with the right
1364 /// element type.
1365 UndefValue *getSequentialElement() const;
1366
1367 /// If this undef has struct type, return a undef with the right element type
1368 /// for the specified element.
1369 UndefValue *getStructElement(unsigned Elt) const;
1370
1371 /// Return an undef of the right value for the specified GEP index if we can,
1372 /// otherwise return null (e.g. if C is a ConstantExpr).
1373 UndefValue *getElementValue(Constant *C) const;
1374
1375 /// Return an undef of the right value for the specified GEP index.
1376 UndefValue *getElementValue(unsigned Idx) const;
1377
1378 /// Return the number of elements in the array, vector, or struct.
1379 unsigned getNumElements() const;
1380
1381 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1382 static bool classof(const Value *V) {
1383 return V->getValueID() == UndefValueVal ||
1384 V->getValueID() == PoisonValueVal;
1385 }
1386};
1387
1388//===----------------------------------------------------------------------===//
1389/// In order to facilitate speculative execution, many instructions do not
1390/// invoke immediate undefined behavior when provided with illegal operands,
1391/// and return a poison value instead.
1392///
1393/// see LangRef.html#poisonvalues for details.
1394///
1395class PoisonValue final : public UndefValue {
1396 friend class Constant;
1397
1398 explicit PoisonValue(Type *T) : UndefValue(T, PoisonValueVal) {}
1399
1400 void destroyConstantImpl();
1401
1402public:
1403 PoisonValue(const PoisonValue &) = delete;
1404
1405 /// Static factory methods - Return an 'poison' object of the specified type.
1406 static PoisonValue *get(Type *T);
1407
1408 /// If this poison has array or vector type, return a poison with the right
1409 /// element type.
1410 PoisonValue *getSequentialElement() const;
1411
1412 /// If this poison has struct type, return a poison with the right element
1413 /// type for the specified element.
1414 PoisonValue *getStructElement(unsigned Elt) const;
1415
1416 /// Return an poison of the right value for the specified GEP index if we can,
1417 /// otherwise return null (e.g. if C is a ConstantExpr).
1418 PoisonValue *getElementValue(Constant *C) const;
1419
1420 /// Return an poison of the right value for the specified GEP index.
1421 PoisonValue *getElementValue(unsigned Idx) const;
1422
1423 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1424 static bool classof(const Value *V) {
1425 return V->getValueID() == PoisonValueVal;
1426 }
1427};
1428
1429} // end namespace llvm
1430
1431#endif // LLVM_IR_CONSTANTS_H

/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/ADT/APInt.h

1//===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- 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/// \file
10/// This file implements a class to represent arbitrary precision
11/// integral constant values and operations on them.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ADT_APINT_H
16#define LLVM_ADT_APINT_H
17
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/MathExtras.h"
20#include <cassert>
21#include <climits>
22#include <cstring>
23#include <utility>
24
25namespace llvm {
26class FoldingSetNodeID;
27class StringRef;
28class hash_code;
29class raw_ostream;
30
31template <typename T> class SmallVectorImpl;
32template <typename T> class ArrayRef;
33template <typename T> class Optional;
34template <typename T> struct DenseMapInfo;
35
36class APInt;
37
38inline APInt operator-(APInt);
39
40//===----------------------------------------------------------------------===//
41// APInt Class
42//===----------------------------------------------------------------------===//
43
44/// Class for arbitrary precision integers.
45///
46/// APInt is a functional replacement for common case unsigned integer type like
47/// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
48/// integer sizes and large integer value types such as 3-bits, 15-bits, or more
49/// than 64-bits of precision. APInt provides a variety of arithmetic operators
50/// and methods to manipulate integer values of any bit-width. It supports both
51/// the typical integer arithmetic and comparison operations as well as bitwise
52/// manipulation.
53///
54/// The class has several invariants worth noting:
55/// * All bit, byte, and word positions are zero-based.
56/// * Once the bit width is set, it doesn't change except by the Truncate,
57/// SignExtend, or ZeroExtend operations.
58/// * All binary operators must be on APInt instances of the same bit width.
59/// Attempting to use these operators on instances with different bit
60/// widths will yield an assertion.
61/// * The value is stored canonically as an unsigned value. For operations
62/// where it makes a difference, there are both signed and unsigned variants
63/// of the operation. For example, sdiv and udiv. However, because the bit
64/// widths must be the same, operations such as Mul and Add produce the same
65/// results regardless of whether the values are interpreted as signed or
66/// not.
67/// * In general, the class tries to follow the style of computation that LLVM
68/// uses in its IR. This simplifies its use for LLVM.
69///
70class LLVM_NODISCARD[[clang::warn_unused_result]] APInt {
71public:
72 typedef uint64_t WordType;
73
74 /// This enum is used to hold the constants we needed for APInt.
75 enum : unsigned {
76 /// Byte size of a word.
77 APINT_WORD_SIZE = sizeof(WordType),
78 /// Bits in a word.
79 APINT_BITS_PER_WORD = APINT_WORD_SIZE * CHAR_BIT8
80 };
81
82 enum class Rounding {
83 DOWN,
84 TOWARD_ZERO,
85 UP,
86 };
87
88 static constexpr WordType WORDTYPE_MAX = ~WordType(0);
89
90private:
91 /// This union is used to store the integer value. When the
92 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
93 union {
94 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
95 uint64_t *pVal; ///< Used to store the >64 bits integer value.
96 } U;
97
98 unsigned BitWidth; ///< The number of bits in this APInt.
99
100 friend struct DenseMapInfo<APInt>;
101
102 friend class APSInt;
103
104 /// Fast internal constructor
105 ///
106 /// This constructor is used only internally for speed of construction of
107 /// temporaries. It is unsafe for general use so it is not public.
108 APInt(uint64_t *val, unsigned bits) : BitWidth(bits) {
109 U.pVal = val;
110 }
111
112 /// Determine if this APInt just has one word to store value.
113 ///
114 /// \returns true if the number of bits <= 64, false otherwise.
115 bool isSingleWord() const { return BitWidth <= APINT_BITS_PER_WORD; }
32
Assuming field 'BitWidth' is > APINT_BITS_PER_WORD
33
Returning zero, which participates in a condition later
116
117 /// Determine which word a bit is in.
118 ///
119 /// \returns the word position for the specified bit position.
120 static unsigned whichWord(unsigned bitPosition) {
121 return bitPosition / APINT_BITS_PER_WORD;
122 }
123
124 /// Determine which bit in a word a bit is in.
125 ///
126 /// \returns the bit position in a word for the specified bit position
127 /// in the APInt.
128 static unsigned whichBit(unsigned bitPosition) {
129 return bitPosition % APINT_BITS_PER_WORD;
130 }
131
132 /// Get a single bit mask.
133 ///
134 /// \returns a uint64_t with only bit at "whichBit(bitPosition)" set
135 /// This method generates and returns a uint64_t (word) mask for a single
136 /// bit at a specific bit position. This is used to mask the bit in the
137 /// corresponding word.
138 static uint64_t maskBit(unsigned bitPosition) {
139 return 1ULL << whichBit(bitPosition);
140 }
141
142 /// Clear unused high order bits
143 ///
144 /// This method is used internally to clear the top "N" bits in the high order
145 /// word that are not used by the APInt. This is needed after the most
146 /// significant word is assigned a value to ensure that those bits are
147 /// zero'd out.
148 APInt &clearUnusedBits() {
149 // Compute how many bits are used in the final word
150 unsigned WordBits = ((BitWidth-1) % APINT_BITS_PER_WORD) + 1;
151
152 // Mask out the high bits.
153 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - WordBits);
154 if (isSingleWord())
155 U.VAL &= mask;
156 else
157 U.pVal[getNumWords() - 1] &= mask;
158 return *this;
159 }
160
161 /// Get the word corresponding to a bit position
162 /// \returns the corresponding word for the specified bit position.
163 uint64_t getWord(unsigned bitPosition) const {
164 return isSingleWord() ? U.VAL : U.pVal[whichWord(bitPosition)];
165 }
166
167 /// Utility method to change the bit width of this APInt to new bit width,
168 /// allocating and/or deallocating as necessary. There is no guarantee on the
169 /// value of any bits upon return. Caller should populate the bits after.
170 void reallocate(unsigned NewBitWidth);
171
172 /// Convert a char array into an APInt
173 ///
174 /// \param radix 2, 8, 10, 16, or 36
175 /// Converts a string into a number. The string must be non-empty
176 /// and well-formed as a number of the given base. The bit-width
177 /// must be sufficient to hold the result.
178 ///
179 /// This is used by the constructors that take string arguments.
180 ///
181 /// StringRef::getAsInteger is superficially similar but (1) does
182 /// not assume that the string is well-formed and (2) grows the
183 /// result to hold the input.
184 void fromString(unsigned numBits, StringRef str, uint8_t radix);
185
186 /// An internal division function for dividing APInts.
187 ///
188 /// This is used by the toString method to divide by the radix. It simply
189 /// provides a more convenient form of divide for internal use since KnuthDiv
190 /// has specific constraints on its inputs. If those constraints are not met
191 /// then it provides a simpler form of divide.
192 static void divide(const WordType *LHS, unsigned lhsWords,
193 const WordType *RHS, unsigned rhsWords, WordType *Quotient,
194 WordType *Remainder);
195
196 /// out-of-line slow case for inline constructor
197 void initSlowCase(uint64_t val, bool isSigned);
198
199 /// shared code between two array constructors
200 void initFromArray(ArrayRef<uint64_t> array);
201
202 /// out-of-line slow case for inline copy constructor
203 void initSlowCase(const APInt &that);
204
205 /// out-of-line slow case for shl
206 void shlSlowCase(unsigned ShiftAmt);
207
208 /// out-of-line slow case for lshr.
209 void lshrSlowCase(unsigned ShiftAmt);
210
211 /// out-of-line slow case for ashr.
212 void ashrSlowCase(unsigned ShiftAmt);
213
214 /// out-of-line slow case for operator=
215 void AssignSlowCase(const APInt &RHS);
216
217 /// out-of-line slow case for operator==
218 bool EqualSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
219
220 /// out-of-line slow case for countLeadingZeros
221 unsigned countLeadingZerosSlowCase() const LLVM_READONLY__attribute__((__pure__));
222
223 /// out-of-line slow case for countLeadingOnes.
224 unsigned countLeadingOnesSlowCase() const LLVM_READONLY__attribute__((__pure__));
225
226 /// out-of-line slow case for countTrailingZeros.
227 unsigned countTrailingZerosSlowCase() const LLVM_READONLY__attribute__((__pure__));
228
229 /// out-of-line slow case for countTrailingOnes
230 unsigned countTrailingOnesSlowCase() const LLVM_READONLY__attribute__((__pure__));
231
232 /// out-of-line slow case for countPopulation
233 unsigned countPopulationSlowCase() const LLVM_READONLY__attribute__((__pure__));
234
235 /// out-of-line slow case for intersects.
236 bool intersectsSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
237
238 /// out-of-line slow case for isSubsetOf.
239 bool isSubsetOfSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
240
241 /// out-of-line slow case for setBits.
242 void setBitsSlowCase(unsigned loBit, unsigned hiBit);
243
244 /// out-of-line slow case for flipAllBits.
245 void flipAllBitsSlowCase();
246
247 /// out-of-line slow case for operator&=.
248 void AndAssignSlowCase(const APInt& RHS);
249
250 /// out-of-line slow case for operator|=.
251 void OrAssignSlowCase(const APInt& RHS);
252
253 /// out-of-line slow case for operator^=.
254 void XorAssignSlowCase(const APInt& RHS);
255
256 /// Unsigned comparison. Returns -1, 0, or 1 if this APInt is less than, equal
257 /// to, or greater than RHS.
258 int compare(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
259
260 /// Signed comparison. Returns -1, 0, or 1 if this APInt is less than, equal
261 /// to, or greater than RHS.
262 int compareSigned(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
263
264public:
265 /// \name Constructors
266 /// @{
267
268 /// Create a new APInt of numBits width, initialized as val.
269 ///
270 /// If isSigned is true then val is treated as if it were a signed value
271 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
272 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
273 /// the range of val are zero filled).
274 ///
275 /// \param numBits the bit width of the constructed APInt
276 /// \param val the initial value of the APInt
277 /// \param isSigned how to treat signedness of val
278 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
279 : BitWidth(numBits) {
280 assert(BitWidth && "bitwidth too small")(static_cast <bool> (BitWidth && "bitwidth too small"
) ? void (0) : __assert_fail ("BitWidth && \"bitwidth too small\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/ADT/APInt.h"
, 280, __extension__ __PRETTY_FUNCTION__))
;
281 if (isSingleWord()) {
282 U.VAL = val;
283 clearUnusedBits();
284 } else {
285 initSlowCase(val, isSigned);
286 }
287 }
288
289 /// Construct an APInt of numBits width, initialized as bigVal[].
290 ///
291 /// Note that bigVal.size() can be smaller or larger than the corresponding
292 /// bit width but any extraneous bits will be dropped.
293 ///
294 /// \param numBits the bit width of the constructed APInt
295 /// \param bigVal a sequence of words to form the initial value of the APInt
296 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
297
298 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
299 /// deprecated because this constructor is prone to ambiguity with the
300 /// APInt(unsigned, uint64_t, bool) constructor.
301 ///
302 /// If this overload is ever deleted, care should be taken to prevent calls
303 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
304 /// constructor.
305 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
306
307 /// Construct an APInt from a string representation.
308 ///
309 /// This constructor interprets the string \p str in the given radix. The
310 /// interpretation stops when the first character that is not suitable for the
311 /// radix is encountered, or the end of the string. Acceptable radix values
312 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
313 /// string to require more bits than numBits.
314 ///
315 /// \param numBits the bit width of the constructed APInt
316 /// \param str the string to be interpreted
317 /// \param radix the radix to use for the conversion
318 APInt(unsigned numBits, StringRef str, uint8_t radix);
319
320 /// Simply makes *this a copy of that.
321 /// Copy Constructor.
322 APInt(const APInt &that) : BitWidth(that.BitWidth) {
323 if (isSingleWord())
324 U.VAL = that.U.VAL;
325 else
326 initSlowCase(that);
327 }
328
329 /// Move Constructor.
330 APInt(APInt &&that) : BitWidth(that.BitWidth) {
331 memcpy(&U, &that.U, sizeof(U));
332 that.BitWidth = 0;
333 }
334
335 /// Destructor.
336 ~APInt() {
337 if (needsCleanup())
338 delete[] U.pVal;
339 }
340
341 /// Default constructor that creates an uninteresting APInt
342 /// representing a 1-bit zero value.
343 ///
344 /// This is useful for object deserialization (pair this with the static
345 /// method Read).
346 explicit APInt() : BitWidth(1) { U.VAL = 0; }
347
348 /// Returns whether this instance allocated memory.
349 bool needsCleanup() const { return !isSingleWord(); }
350
351 /// Used to insert APInt objects, or objects that contain APInt objects, into
352 /// FoldingSets.
353 void Profile(FoldingSetNodeID &id) const;
354
355 /// @}
356 /// \name Value Tests
357 /// @{
358
359 /// Determine sign of this APInt.
360 ///
361 /// This tests the high bit of this APInt to determine if it is set.
362 ///
363 /// \returns true if this APInt is negative, false otherwise
364 bool isNegative() const { return (*this)[BitWidth - 1]; }
365
366 /// Determine if this APInt Value is non-negative (>= 0)
367 ///
368 /// This tests the high bit of the APInt to determine if it is unset.
369 bool isNonNegative() const { return !isNegative(); }
370
371 /// Determine if sign bit of this APInt is set.
372 ///
373 /// This tests the high bit of this APInt to determine if it is set.
374 ///
375 /// \returns true if this APInt has its sign bit set, false otherwise.
376 bool isSignBitSet() const { return (*this)[BitWidth-1]; }
377
378 /// Determine if sign bit of this APInt is clear.
379 ///
380 /// This tests the high bit of this APInt to determine if it is clear.
381 ///
382 /// \returns true if this APInt has its sign bit clear, false otherwise.
383 bool isSignBitClear() const { return !isSignBitSet(); }
384
385 /// Determine if this APInt Value is positive.
386 ///
387 /// This tests if the value of this APInt is positive (> 0). Note
388 /// that 0 is not a positive value.
389 ///
390 /// \returns true if this APInt is positive.
391 bool isStrictlyPositive() const { return isNonNegative() && !isNullValue(); }
392
393 /// Determine if this APInt Value is non-positive (<= 0).
394 ///
395 /// \returns true if this APInt is non-positive.
396 bool isNonPositive() const { return !isStrictlyPositive(); }
397
398 /// Determine if all bits are set
399 ///
400 /// This checks to see if the value has all bits of the APInt are set or not.
401 bool isAllOnesValue() const {
402 if (isSingleWord())
403 return U.VAL == WORDTYPE_MAX >> (APINT_BITS_PER_WORD - BitWidth);
404 return countTrailingOnesSlowCase() == BitWidth;
405 }
406
407 /// Determine if all bits are clear
408 ///
409 /// This checks to see if the value has all bits of the APInt are clear or
410 /// not.
411 bool isNullValue() const { return !*this; }
30
Calling 'APInt::operator!'
38
Returning from 'APInt::operator!'
39
Returning the value 1, which participates in a condition later
412
413 /// Determine if this is a value of 1.
414 ///
415 /// This checks to see if the value of this APInt is one.
416 bool isOneValue() const {
417 if (isSingleWord())
418 return U.VAL == 1;
419 return countLeadingZerosSlowCase() == BitWidth - 1;
420 }
421
422 /// Determine if this is the largest unsigned value.
423 ///
424 /// This checks to see if the value of this APInt is the maximum unsigned
425 /// value for the APInt's bit width.
426 bool isMaxValue() const { return isAllOnesValue(); }
427
428 /// Determine if this is the largest signed value.
429 ///
430 /// This checks to see if the value of this APInt is the maximum signed
431 /// value for the APInt's bit width.
432 bool isMaxSignedValue() const {
433 if (isSingleWord())
434 return U.VAL == ((WordType(1) << (BitWidth - 1)) - 1);
435 return !isNegative() && countTrailingOnesSlowCase() == BitWidth - 1;
436 }
437
438 /// Determine if this is the smallest unsigned value.
439 ///
440 /// This checks to see if the value of this APInt is the minimum unsigned
441 /// value for the APInt's bit width.
442 bool isMinValue() const { return isNullValue(); }
443
444 /// Determine if this is the smallest signed value.
445 ///
446 /// This checks to see if the value of this APInt is the minimum signed
447 /// value for the APInt's bit width.
448 bool isMinSignedValue() const {
449 if (isSingleWord())
450 return U.VAL == (WordType(1) << (BitWidth - 1));
451 return isNegative() && countTrailingZerosSlowCase() == BitWidth - 1;
452 }
453
454 /// Check if this APInt has an N-bits unsigned integer value.
455 bool isIntN(unsigned N) const {
456 assert(N && "N == 0 ???")(static_cast <bool> (N && "N == 0 ???") ? void (
0) : __assert_fail ("N && \"N == 0 ???\"", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/ADT/APInt.h"
, 456, __extension__ __PRETTY_FUNCTION__))
;
457 return getActiveBits() <= N;
458 }
459
460 /// Check if this APInt has an N-bits signed integer value.
461 bool isSignedIntN(unsigned N) const {
462 assert(N && "N == 0 ???")(static_cast <bool> (N && "N == 0 ???") ? void (
0) : __assert_fail ("N && \"N == 0 ???\"", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/ADT/APInt.h"
, 462, __extension__ __PRETTY_FUNCTION__))
;
463 return getMinSignedBits() <= N;
464 }
465
466 /// Check if this APInt's value is a power of two greater than zero.
467 ///
468 /// \returns true if the argument APInt value is a power of two > 0.
469 bool isPowerOf2() const {
470 if (isSingleWord())
471 return isPowerOf2_64(U.VAL);
472 return countPopulationSlowCase() == 1;
473 }
474
475 /// Check if the APInt's value is returned by getSignMask.
476 ///
477 /// \returns true if this is the value returned by getSignMask.
478 bool isSignMask() const { return isMinSignedValue(); }
479
480 /// Convert APInt to a boolean value.
481 ///
482 /// This converts the APInt to a boolean value as a test against zero.
483 bool getBoolValue() const { return !!*this; }
484
485 /// If this value is smaller than the specified limit, return it, otherwise
486 /// return the limit value. This causes the value to saturate to the limit.
487 uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX(18446744073709551615UL)) const {
488 return ugt(Limit) ? Limit : getZExtValue();
489 }
490
491 /// Check if the APInt consists of a repeated bit pattern.
492 ///
493 /// e.g. 0x01010101 satisfies isSplat(8).
494 /// \param SplatSizeInBits The size of the pattern in bits. Must divide bit
495 /// width without remainder.
496 bool isSplat(unsigned SplatSizeInBits) const;
497
498 /// \returns true if this APInt value is a sequence of \param numBits ones
499 /// starting at the least significant bit with the remainder zero.
500 bool isMask(unsigned numBits) const {
501 assert(numBits != 0 && "numBits must be non-zero")(static_cast <bool> (numBits != 0 && "numBits must be non-zero"
) ? void (0) : __assert_fail ("numBits != 0 && \"numBits must be non-zero\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/ADT/APInt.h"
, 501, __extension__ __PRETTY_FUNCTION__))
;
502 assert(numBits <= BitWidth && "numBits out of range")(static_cast <bool> (numBits <= BitWidth && "numBits out of range"
) ? void (0) : __assert_fail ("numBits <= BitWidth && \"numBits out of range\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/ADT/APInt.h"
, 502, __extension__ __PRETTY_FUNCTION__))
;
503 if (isSingleWord())
504 return U.VAL == (WORDTYPE_MAX >> (APINT_BITS_PER_WORD - numBits));
505 unsigned Ones = countTrailingOnesSlowCase();
506 return (numBits == Ones) &&
507 ((Ones + countLeadingZerosSlowCase()) == BitWidth);
508 }
509
510 /// \returns true if this APInt is a non-empty sequence of ones starting at
511 /// the least significant bit with the remainder zero.
512 /// Ex. isMask(0x0000FFFFU) == true.
513 bool isMask() const {
514 if (isSingleWord())
515 return isMask_64(U.VAL);
516 unsigned Ones = countTrailingOnesSlowCase();
517 return (Ones > 0) && ((Ones + countLeadingZerosSlowCase()) == BitWidth);
518 }
519
520 /// Return true if this APInt value contains a sequence of ones with
521 /// the remainder zero.
522 bool isShiftedMask() const {
523 if (isSingleWord())
524 return isShiftedMask_64(U.VAL);
525 unsigned Ones = countPopulationSlowCase();
526 unsigned LeadZ = countLeadingZerosSlowCase();
527 return (Ones + LeadZ + countTrailingZeros()) == BitWidth;
528 }
529
530 /// @}
531 /// \name Value Generators
532 /// @{
533
534 /// Gets maximum unsigned value of APInt for specific bit width.
535 static APInt getMaxValue(unsigned numBits) {
536 return getAllOnesValue(numBits);
537 }
538
539 /// Gets maximum signed value of APInt for a specific bit width.
540 static APInt getSignedMaxValue(unsigned numBits) {
541 APInt API = getAllOnesValue(numBits);
542 API.clearBit(numBits - 1);
543 return API;
544 }
545
546 /// Gets minimum unsigned value of APInt for a specific bit width.
547 static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); }
548
549 /// Gets minimum signed value of APInt for a specific bit width.
550 static APInt getSignedMinValue(unsigned numBits) {
551 APInt API(numBits, 0);
552 API.setBit(numBits - 1);
553 return API;
554 }
555
556 /// Get the SignMask for a specific bit width.
557 ///
558 /// This is just a wrapper function of getSignedMinValue(), and it helps code
559 /// readability when we want to get a SignMask.
560 static APInt getSignMask(unsigned BitWidth) {
561 return getSignedMinValue(BitWidth);
562 }
563
564 /// Get the all-ones value.
565 ///
566 /// \returns the all-ones value for an APInt of the specified bit-width.
567 static APInt getAllOnesValue(unsigned numBits) {
568 return APInt(numBits, WORDTYPE_MAX, true);
569 }
570
571 /// Get the '0' value.
572 ///
573 /// \returns the '0' value for an APInt of the specified bit-width.
574 static APInt getNullValue(unsigned numBits) { return APInt(numBits, 0); }
575
576 /// Compute an APInt containing numBits highbits from this APInt.
577 ///
578 /// Get an APInt with the same BitWidth as this APInt, just zero mask
579 /// the low bits and right shift to the least significant bit.
580 ///
581 /// \returns the high "numBits" bits of this APInt.
582 APInt getHiBits(unsigned numBits) const;
583
584 /// Compute an APInt containing numBits lowbits from this APInt.
585 ///
586 /// Get an APInt with the same BitWidth as this APInt, just zero mask
587 /// the high bits.
588 ///
589 /// \returns the low "numBits" bits of this APInt.
590 APInt getLoBits(unsigned numBits) const;
591
592 /// Return an APInt with exactly one bit set in the result.
593 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
594 APInt Res(numBits, 0);
595 Res.setBit(BitNo);
596 return Res;
597 }
598
599 /// Get a value with a block of bits set.
600 ///
601 /// Constructs an APInt value that has a contiguous range of bits set. The
602 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
603 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
604 /// 0x0000FFFF. Please call getBitsSetWithWrap if \p loBit may be greater than
605 /// \p hiBit.
606 ///
607 /// \param numBits the intended bit width of the result
608 /// \param loBit the index of the lowest bit set.
609 /// \param hiBit the index of the highest bit set.
610 ///
611 /// \returns An APInt value with the requested bits set.
612 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
613 assert(loBit <= hiBit && "loBit greater than hiBit")(static_cast <bool> (loBit <= hiBit && "loBit greater than hiBit"
) ? void (0) : __assert_fail ("loBit <= hiBit && \"loBit greater than hiBit\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/ADT/APInt.h"
, 613, __extension__ __PRETTY_FUNCTION__))
;
614 APInt Res(numBits, 0);
615 Res.setBits(loBit, hiBit);
616 return Res;
617 }
618
619 /// Wrap version of getBitsSet.
620 /// If \p hiBit is bigger than \p loBit, this is same with getBitsSet.
621 /// If \p hiBit is not bigger than \p loBit, the set bits "wrap". For example,
622 /// with parameters (32, 28, 4), you would get 0xF000000F.
623 /// If \p hiBit is equal to \p loBit, you would get a result with all bits
624 /// set.
625 static APInt getBitsSetWithWrap(unsigned numBits, unsigned loBit,
626 unsigned hiBit) {
627 APInt Res(numBits, 0);
628 Res.setBitsWithWrap(loBit, hiBit);
629 return Res;
630 }
631
632 /// Get a value with upper bits starting at loBit set.
633 ///
634 /// Constructs an APInt value that has a contiguous range of bits set. The
635 /// bits from loBit (inclusive) to numBits (exclusive) will be set. All other
636 /// bits will be zero. For example, with parameters(32, 12) you would get
637 /// 0xFFFFF000.
638 ///
639 /// \param numBits the intended bit width of the result
640 /// \param loBit the index of the lowest bit to set.
641 ///
642 /// \returns An APInt value with the requested bits set.
643 static APInt getBitsSetFrom(unsigned numBits, unsigned loBit) {
644 APInt Res(numBits, 0);
645 Res.setBitsFrom(loBit);
646 return Res;
647 }
648
649 /// Get a value with high bits set
650 ///
651 /// Constructs an APInt value that has the top hiBitsSet bits set.
652 ///
653 /// \param numBits the bitwidth of the result
654 /// \param hiBitsSet the number of high-order bits set in the result.
655 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
656 APInt Res(numBits, 0);
657 Res.setHighBits(hiBitsSet);
658 return Res;
659 }
660
661 /// Get a value with low bits set
662 ///
663 /// Constructs an APInt value that has the bottom loBitsSet bits set.
664 ///
665 /// \param numBits the bitwidth of the result
666 /// \param loBitsSet the number of low-order bits set in the result.
667 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
668 APInt Res(numBits, 0);
669 Res.setLowBits(loBitsSet);
670 return Res;
671 }
672
673 /// Return a value containing V broadcasted over NewLen bits.
674 static APInt getSplat(unsigned NewLen, const APInt &V);
675
676 /// Determine if two APInts have the same value, after zero-extending
677 /// one of them (if needed!) to ensure that the bit-widths match.
678 static bool isSameValue(const APInt &I1, const APInt &I2) {
679 if (I1.getBitWidth() == I2.getBitWidth())
680 return I1 == I2;
681
682 if (I1.getBitWidth() > I2.getBitWidth())
683 return I1 == I2.zext(I1.getBitWidth());
684
685 return I1.zext(I2.getBitWidth()) == I2;
686 }
687
688 /// Overload to compute a hash_code for an APInt value.
689 friend hash_code hash_value(const APInt &Arg);
690
691 /// This function returns a pointer to the internal storage of the APInt.
692 /// This is useful for writing out the APInt in binary form without any
693 /// conversions.
694 const uint64_t *getRawData() const {
695 if (isSingleWord())
696 return &U.VAL;
697 return &U.pVal[0];
698 }
699
700 /// @}
701 /// \name Unary Operators
702 /// @{
703
704 /// Postfix increment operator.
705 ///
706 /// Increments *this by 1.
707 ///
708 /// \returns a new APInt value representing the original value of *this.
709 const APInt operator++(int) {
710 APInt API(*this);
711 ++(*this);
712 return API;
713 }
714
715 /// Prefix increment operator.
716 ///
717 /// \returns *this incremented by one
718 APInt &operator++();
719
720 /// Postfix decrement operator.
721 ///
722 /// Decrements *this by 1.
723 ///
724 /// \returns a new APInt value representing the original value of *this.
725 const APInt operator--(int) {
726 APInt API(*this);
727 --(*this);
728 return API;
729 }
730
731 /// Prefix decrement operator.
732 ///
733 /// \returns *this decremented by one.
734 APInt &operator--();
735
736 /// Logical negation operator.
737 ///
738 /// Performs logical negation operation on this APInt.
739 ///
740 /// \returns true if *this is zero, false otherwise.
741 bool operator!() const {
742 if (isSingleWord())
31
Calling 'APInt::isSingleWord'
34
Returning from 'APInt::isSingleWord'
35
Taking false branch
743 return U.VAL == 0;
744 return countLeadingZerosSlowCase() == BitWidth;
36
Assuming the condition is true
37
Returning the value 1, which participates in a condition later
745 }
746
747 /// @}
748 /// \name Assignment Operators
749 /// @{
750
751 /// Copy assignment operator.
752 ///
753 /// \returns *this after assignment of RHS.
754 APInt &operator=(const APInt &RHS) {
755 // If the bitwidths are the same, we can avoid mucking with memory
756 if (isSingleWord() && RHS.isSingleWord()) {
757 U.VAL = RHS.U.VAL;
758 BitWidth = RHS.BitWidth;
759 return clearUnusedBits();
760 }
761
762 AssignSlowCase(RHS);
763 return *this;
764 }
765
766 /// Move assignment operator.
767 APInt &operator=(APInt &&that) {
768#ifdef EXPENSIVE_CHECKS
769 // Some std::shuffle implementations still do self-assignment.
770 if (this == &that)
771 return *this;
772#endif
773 assert(this != &that && "Self-move not supported")(static_cast <bool> (this != &that && "Self-move not supported"
) ? void (0) : __assert_fail ("this != &that && \"Self-move not supported\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/ADT/APInt.h"
, 773, __extension__ __PRETTY_FUNCTION__))
;
774 if (!isSingleWord())
775 delete[] U.pVal;
776
777 // Use memcpy so that type based alias analysis sees both VAL and pVal
778 // as modified.
779 memcpy(&U, &that.U, sizeof(U));
780
781 BitWidth = that.BitWidth;
782 that.BitWidth = 0;
783
784 return *this;
785 }
786
787 /// Assignment operator.
788 ///
789 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
790 /// the bit width, the excess bits are truncated. If the bit width is larger
791 /// than 64, the value is zero filled in the unspecified high order bits.
792 ///
793 /// \returns *this after assignment of RHS value.
794 APInt &operator=(uint64_t RHS) {
795 if (isSingleWord()) {
796 U.VAL = RHS;
797 return clearUnusedBits();
798 }
799 U.pVal[0] = RHS;
800 memset(U.pVal + 1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
801 return *this;
802 }
803
804 /// Bitwise AND assignment operator.
805 ///
806 /// Performs a bitwise AND operation on this APInt and RHS. The result is
807 /// assigned to *this.
808 ///
809 /// \returns *this after ANDing with RHS.
810 APInt &operator&=(const APInt &RHS) {
811 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Bit widths must be the same") ? void (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/ADT/APInt.h"
, 811, __extension__ __PRETTY_FUNCTION__))
;
812 if (isSingleWord())
813 U.VAL &= RHS.U.VAL;
814 else
815 AndAssignSlowCase(RHS);
816 return *this;
817 }
818
819 /// Bitwise AND assignment operator.
820 ///
821 /// Performs a bitwise AND operation on this APInt and RHS. RHS is
822 /// logically zero-extended or truncated to match the bit-width of
823 /// the LHS.
824 APInt &operator&=(uint64_t RHS) {
825 if (isSingleWord()) {
826 U.VAL &= RHS;
827 return *this;
828 }
829 U.pVal[0] &= RHS;
830 memset(U.pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
831 return *this;
832 }
833
834 /// Bitwise OR assignment operator.
835 ///
836 /// Performs a bitwise OR operation on this APInt and RHS. The result is
837 /// assigned *this;
838 ///
839 /// \returns *this after ORing with RHS.
840 APInt &operator|=(const APInt &RHS) {
841 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Bit widths must be the same") ? void (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/ADT/APInt.h"
, 841, __extension__ __PRETTY_FUNCTION__))
;
842 if (isSingleWord())
843 U.VAL |= RHS.U.VAL;
844 else
845 OrAssignSlowCase(RHS);
846 return *this;
847 }
848
849 /// Bitwise OR assignment operator.
850 ///
851 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
852 /// logically zero-extended or truncated to match the bit-width of
853 /// the LHS.
854 APInt &operator|=(uint64_t RHS) {
855 if (isSingleWord()) {
856 U.VAL |= RHS;
857 return clearUnusedBits();
858 }
859 U.pVal[0] |= RHS;
860 return *this;
861 }
862
863 /// Bitwise XOR assignment operator.
864 ///
865 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
866 /// assigned to *this.
867 ///
868 /// \returns *this after XORing with RHS.
869 APInt &operator^=(const APInt &RHS) {
870 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Bit widths must be the same") ? void (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/ADT/APInt.h"
, 870, __extension__ __PRETTY_FUNCTION__))
;
871 if (isSingleWord())
872 U.VAL ^= RHS.U.VAL;
873 else
874 XorAssignSlowCase(RHS);
875 return *this;
876 }
877
878 /// Bitwise XOR assignment operator.
879 ///
880 /// Performs a bitwise XOR operation on this APInt and RHS. RHS is
881 /// logically zero-extended or truncated to match the bit-width of
882 /// the LHS.
883 APInt &operator^=(uint64_t RHS) {
884 if (isSingleWord()) {
885 U.VAL ^= RHS;
886 return clearUnusedBits();
887 }
888 U.pVal[0] ^= RHS;
889 return *this;
890 }
891
892 /// Multiplication assignment operator.
893 ///
894 /// Multiplies this APInt by RHS and assigns the result to *this.
895 ///
896 /// \returns *this
897 APInt &operator*=(const APInt &RHS);
898 APInt &operator*=(uint64_t RHS);
899
900 /// Addition assignment operator.
901 ///
902 /// Adds RHS to *this and assigns the result to *this.
903 ///
904 /// \returns *this
905 APInt &operator+=(const APInt &RHS);
906 APInt &operator+=(uint64_t RHS);
907
908 /// Subtraction assignment operator.
909 ///
910 /// Subtracts RHS from *this and assigns the result to *this.
911 ///
912 /// \returns *this
913 APInt &operator-=(const APInt &RHS);
914 APInt &operator-=(uint64_t RHS);
915
916 /// Left-shift assignment function.
917 ///
918 /// Shifts *this left by shiftAmt and assigns the result to *this.
919 ///
920 /// \returns *this after shifting left by ShiftAmt
921 APInt &operator<<=(unsigned ShiftAmt) {
922 assert(ShiftAmt <= BitWidth && "Invalid shift amount")(static_cast <bool> (ShiftAmt <= BitWidth &&
"Invalid shift amount") ? void (0) : __assert_fail ("ShiftAmt <= BitWidth && \"Invalid shift amount\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/ADT/APInt.h"
, 922, __extension__ __PRETTY_FUNCTION__))
;
923 if (isSingleWord()) {
924 if (ShiftAmt == BitWidth)
925 U.VAL = 0;
926 else
927 U.VAL <<= ShiftAmt;
928 return clearUnusedBits();
929 }
930 shlSlowCase(ShiftAmt);
931 return *this;
932 }
933
934 /// Left-shift assignment function.
935 ///
936 /// Shifts *this left by shiftAmt and assigns the result to *this.
937 ///
938 /// \returns *this after shifting left by ShiftAmt
939 APInt &operator<<=(const APInt &ShiftAmt);
940
941 /// @}
942 /// \name Binary Operators
943 /// @{
944
945 /// Multiplication operator.
946 ///
947 /// Multiplies this APInt by RHS and returns the result.
948 APInt operator*(const APInt &RHS) const;
949
950 /// Left logical shift operator.
951 ///
952 /// Shifts this APInt left by \p Bits and returns the result.
953 APInt operator<<(unsigned Bits) const { return shl(Bits); }
954
955 /// Left logical shift operator.
956 ///
957 /// Shifts this APInt left by \p Bits and returns the result.
958 APInt operator<<(const APInt &Bits) const { return shl(Bits); }
959
960 /// Arithmetic right-shift function.
961 ///
962 /// Arithmetic right-shift this APInt by shiftAmt.
963 APInt ashr(unsigned ShiftAmt) const {
964 APInt R(*this);
965 R.ashrInPlace(ShiftAmt);
966 return R;
967 }
968
969 /// Arithmetic right-shift this APInt by ShiftAmt in place.
970 void ashrInPlace(unsigned ShiftAmt) {
971 assert(ShiftAmt <= BitWidth && "Invalid shift amount")(static_cast <bool> (ShiftAmt <= BitWidth &&
"Invalid shift amount") ? void (0) : __assert_fail ("ShiftAmt <= BitWidth && \"Invalid shift amount\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/ADT/APInt.h"
, 971, __extension__ __PRETTY_FUNCTION__))
;
972 if (isSingleWord()) {
973 int64_t SExtVAL = SignExtend64(U.VAL, BitWidth);
974 if (ShiftAmt == BitWidth)
975 U.VAL = SExtVAL >> (APINT_BITS_PER_WORD - 1); // Fill with sign bit.
976 else
977 U.VAL = SExtVAL >> ShiftAmt;
978 clearUnusedBits();
979 return;
980 }
981 ashrSlowCase(ShiftAmt);
982 }
983
984 /// Logical right-shift function.
985 ///
986 /// Logical right-shift this APInt by shiftAmt.
987 APInt lshr(unsigned shiftAmt) const {
988 APInt R(*this);
989 R.lshrInPlace(shiftAmt);
990 return R;
991 }
992
993 /// Logical right-shift this APInt by ShiftAmt in place.
994 void lshrInPlace(unsigned ShiftAmt) {
995 assert(ShiftAmt <= BitWidth && "Invalid shift amount")(static_cast <bool> (ShiftAmt <= BitWidth &&
"Invalid shift amount") ? void (0) : __assert_fail ("ShiftAmt <= BitWidth && \"Invalid shift amount\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/ADT/APInt.h"
, 995, __extension__ __PRETTY_FUNCTION__))
;
996 if (isSingleWord()) {
997 if (ShiftAmt == BitWidth)
998 U.VAL = 0;
999 else
1000 U.VAL >>= ShiftAmt;
1001 return;
1002 }
1003 lshrSlowCase(ShiftAmt);
1004 }
1005
1006 /// Left-shift function.
1007 ///
1008 /// Left-shift this APInt by shiftAmt.
1009 APInt shl(unsigned shiftAmt) const {
1010 APInt R(*this);
1011 R <<= shiftAmt;
1012 return R;
1013 }
1014
1015 /// Rotate left by rotateAmt.
1016 APInt rotl(unsigned rotateAmt) const;
1017
1018 /// Rotate right by rotateAmt.
1019 APInt rotr(unsigned rotateAmt) const;
1020
1021 /// Arithmetic right-shift function.
1022 ///
1023 /// Arithmetic right-shift this APInt by shiftAmt.
1024 APInt ashr(const APInt &ShiftAmt) const {
1025 APInt R(*this);
1026 R.ashrInPlace(ShiftAmt);
1027 return R;
1028 }
1029
1030 /// Arithmetic right-shift this APInt by shiftAmt in place.
1031 void ashrInPlace(const APInt &shiftAmt);
1032
1033 /// Logical right-shift function.
1034 ///
1035 /// Logical right-shift this APInt by shiftAmt.
1036 APInt lshr(const APInt &ShiftAmt) const {
1037 APInt R(*this);
1038 R.lshrInPlace(ShiftAmt);
1039 return R;
1040 }
1041
1042 /// Logical right-shift this APInt by ShiftAmt in place.
1043 void lshrInPlace(const APInt &ShiftAmt);
1044
1045 /// Left-shift function.
1046 ///
1047 /// Left-shift this APInt by shiftAmt.
1048 APInt shl(const APInt &ShiftAmt) const {
1049 APInt R(*this);
1050 R <<= ShiftAmt;
1051 return R;
1052 }
1053
1054 /// Rotate left by rotateAmt.
1055 APInt rotl(const APInt &rotateAmt) const;
1056
1057 /// Rotate right by rotateAmt.
1058 APInt rotr(const APInt &rotateAmt) const;
1059
1060 /// Unsigned division operation.
1061 ///
1062 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
1063 /// RHS are treated as unsigned quantities for purposes of this division.
1064 ///
1065 /// \returns a new APInt value containing the division result, rounded towards
1066 /// zero.
1067 APInt udiv(const APInt &RHS) const;
1068 APInt udiv(uint64_t RHS) const;
1069
1070 /// Signed division function for APInt.
1071 ///
1072 /// Signed divide this APInt by APInt RHS.
1073 ///
1074 /// The result is rounded towards zero.
1075 APInt sdiv(const APInt &RHS) const;
1076 APInt sdiv(int64_t RHS) const;
1077
1078 /// Unsigned remainder operation.
1079 ///
1080 /// Perform an unsigned remainder operation on this APInt with RHS being the
1081 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
1082 /// of this operation. Note that this is a true remainder operation and not a
1083 /// modulo operation because the sign follows the sign of the dividend which
1084 /// is *this.
1085 ///
1086 /// \returns a new APInt value containing the remainder result
1087 APInt urem(const APInt &RHS) const;
1088 uint64_t urem(uint64_t RHS) const;
1089
1090 /// Function for signed remainder operation.
1091 ///
1092 /// Signed remainder operation on APInt.
1093 APInt srem(const APInt &RHS) const;
1094 int64_t srem(int64_t RHS) const;
1095
1096 /// Dual division/remainder interface.
1097 ///
1098 /// Sometimes it is convenient to divide two APInt values and obtain both the
1099 /// quotient and remainder. This function does both operations in the same
1100 /// computation making it a little more efficient. The pair of input arguments
1101 /// may overlap with the pair of output arguments. It is safe to call
1102 /// udivrem(X, Y, X, Y), for example.
1103 static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
1104 APInt &Remainder);
1105 static void udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient,
1106 uint64_t &Remainder);
1107
1108 static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
1109 APInt &Remainder);
1110 static void sdivrem(const APInt &LHS, int64_t RHS, APInt &Quotient,
1111 int64_t &Remainder);
1112
1113 // Operations that return overflow indicators.
1114 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
1115 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
1116 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
1117 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
1118 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
1119 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
1120 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
1121 APInt sshl_ov(const APInt &Amt, bool &Overflow) const;
1122 APInt ushl_ov(const APInt &Amt, bool &Overflow) const;
1123
1124 // Operations that saturate
1125 APInt sadd_sat(const APInt &RHS) const;
1126 APInt uadd_sat(const APInt &RHS) const;
1127 APInt ssub_sat(const APInt &RHS) const;
1128 APInt usub_sat(const APInt &RHS) const;
1129 APInt smul_sat(const APInt &RHS) const;
1130 APInt umul_sat(const APInt &RHS) const;
1131 APInt sshl_sat(const APInt &RHS) const;
1132 APInt ushl_sat(const APInt &RHS) const;
1133
1134 /// Array-indexing support.
1135 ///
1136 /// \returns the bit value at bitPosition
1137 bool operator[](unsigned bitPosition) const {
1138 assert(bitPosition < getBitWidth() && "Bit position out of bounds!")(static_cast <bool> (bitPosition < getBitWidth() &&
"Bit position out of bounds!") ? void (0) : __assert_fail ("bitPosition < getBitWidth() && \"Bit position out of bounds!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/ADT/APInt.h"
, 1138, __extension__ __PRETTY_FUNCTION__))
;
1139 return (maskBit(bitPosition) & getWord(bitPosition)) != 0;
1140 }
1141
1142 /// @}
1143 /// \name Comparison Operators
1144 /// @{
1145
1146 /// Equality operator.
1147 ///
1148 /// Compares this APInt with RHS for the validity of the equality
1149 /// relationship.
1150 bool operator==(const APInt &RHS) const {
1151 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Comparison requires equal bit widths") ? void (0) : __assert_fail
("BitWidth == RHS.BitWidth && \"Comparison requires equal bit widths\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include/llvm/ADT/APInt.h"
, 1151, __extension__ __PRETTY_FUNCTION__))
;
1152 if (isSingleWord())
1153 return U.VAL == RHS.U.VAL;
1154 return EqualSlowCase(RHS);
1155 }
1156
1157 /// Equality operator.
1158 ///
1159 /// Compares this APInt with a uint64_t for the validity of the equality
1160 /// relationship.
1161 ///
1162 /// \returns true if *this == Val
1163 bool operator==(uint64_t Val) const {
1164 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() == Val;
1165 }
1166
1167 /// Equality comparison.
1168 ///
1169 /// Compares this APInt with RHS for the validity of the equality
1170 /// relationship.
1171 ///
1172 /// \returns true if *this == Val
1173 bool eq(const APInt &RHS) const { return (*this) == RHS; }
1174
1175 /// Inequality operator.
1176 ///
1177 /// Compares this APInt with RHS for the validity of the inequality
1178 /// relationship.
1179 ///
1180 /// \returns true if *this != Val
1181 bool operator!=(const APInt &RHS) const { return !((*this) == RHS); }
1182
1183 /// Inequality operator.
1184 ///
1185 /// Compares this APInt with a uint64_t for the validity of the inequality
1186 /// relationship.
1187 ///
1188 /// \returns true if *this != Val
1189 bool operator!=(uint64_t Val) const { return !((*this) == Val); }
1190
1191 /// Inequality comparison
1192 ///
1193 /// Compares this APInt with RHS for the validity of the inequality
1194 /// relationship.
1195 ///
1196 /// \returns true if *this != Val
1197 bool ne(const APInt &RHS) const { return !((*this) == RHS); }
1198
1199 /// Unsigned less than comparison
1200 ///
1201 /// Regards both *this and RHS as unsigned quantities and compares them for