Bug Summary

File:lib/Analysis/BasicAliasAnalysis.cpp
Warning:line 899, column 15
Assigned value is garbage or undefined

Annotated Source Code

Press '?' to see keyboard shortcuts

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

/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp

1//===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the primary stateless implementation of the
11// Alias Analysis interface that implements identities (two different
12// globals cannot alias, etc), but does no stateful analysis.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Analysis/BasicAliasAnalysis.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/Analysis/AliasAnalysis.h"
22#include "llvm/Analysis/AssumptionCache.h"
23#include "llvm/Analysis/CFG.h"
24#include "llvm/Analysis/CaptureTracking.h"
25#include "llvm/Analysis/InstructionSimplify.h"
26#include "llvm/Analysis/LoopInfo.h"
27#include "llvm/Analysis/MemoryBuiltins.h"
28#include "llvm/Analysis/MemoryLocation.h"
29#include "llvm/Analysis/TargetLibraryInfo.h"
30#include "llvm/Analysis/ValueTracking.h"
31#include "llvm/IR/Argument.h"
32#include "llvm/IR/Attributes.h"
33#include "llvm/IR/CallSite.h"
34#include "llvm/IR/Constant.h"
35#include "llvm/IR/Constants.h"
36#include "llvm/IR/DataLayout.h"
37#include "llvm/IR/DerivedTypes.h"
38#include "llvm/IR/Dominators.h"
39#include "llvm/IR/Function.h"
40#include "llvm/IR/GetElementPtrTypeIterator.h"
41#include "llvm/IR/GlobalAlias.h"
42#include "llvm/IR/GlobalVariable.h"
43#include "llvm/IR/InstrTypes.h"
44#include "llvm/IR/Instruction.h"
45#include "llvm/IR/Instructions.h"
46#include "llvm/IR/IntrinsicInst.h"
47#include "llvm/IR/Intrinsics.h"
48#include "llvm/IR/Metadata.h"
49#include "llvm/IR/Operator.h"
50#include "llvm/IR/Type.h"
51#include "llvm/IR/User.h"
52#include "llvm/IR/Value.h"
53#include "llvm/Pass.h"
54#include "llvm/Support/Casting.h"
55#include "llvm/Support/CommandLine.h"
56#include "llvm/Support/Compiler.h"
57#include "llvm/Support/KnownBits.h"
58#include <cassert>
59#include <cstdint>
60#include <cstdlib>
61#include <utility>
62
63#define DEBUG_TYPE"basicaa" "basicaa"
64
65using namespace llvm;
66
67/// Enable analysis of recursive PHI nodes.
68static cl::opt<bool> EnableRecPhiAnalysis("basicaa-recphi", cl::Hidden,
69 cl::init(false));
70/// SearchLimitReached / SearchTimes shows how often the limit of
71/// to decompose GEPs is reached. It will affect the precision
72/// of basic alias analysis.
73STATISTIC(SearchLimitReached, "Number of times the limit to "static llvm::Statistic SearchLimitReached = {"basicaa", "SearchLimitReached"
, "Number of times the limit to " "decompose GEPs is reached"
, {0}, {false}}
74 "decompose GEPs is reached")static llvm::Statistic SearchLimitReached = {"basicaa", "SearchLimitReached"
, "Number of times the limit to " "decompose GEPs is reached"
, {0}, {false}}
;
75STATISTIC(SearchTimes, "Number of times a GEP is decomposed")static llvm::Statistic SearchTimes = {"basicaa", "SearchTimes"
, "Number of times a GEP is decomposed", {0}, {false}}
;
76
77/// Cutoff after which to stop analysing a set of phi nodes potentially involved
78/// in a cycle. Because we are analysing 'through' phi nodes, we need to be
79/// careful with value equivalence. We use reachability to make sure a value
80/// cannot be involved in a cycle.
81const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
82
83// The max limit of the search depth in DecomposeGEPExpression() and
84// GetUnderlyingObject(), both functions need to use the same search
85// depth otherwise the algorithm in aliasGEP will assert.
86static const unsigned MaxLookupSearchDepth = 6;
87
88bool BasicAAResult::invalidate(Function &F, const PreservedAnalyses &PA,
89 FunctionAnalysisManager::Invalidator &Inv) {
90 // We don't care if this analysis itself is preserved, it has no state. But
91 // we need to check that the analyses it depends on have been. Note that we
92 // may be created without handles to some analyses and in that case don't
93 // depend on them.
94 if (Inv.invalidate<AssumptionAnalysis>(F, PA) ||
95 (DT && Inv.invalidate<DominatorTreeAnalysis>(F, PA)) ||
96 (LI && Inv.invalidate<LoopAnalysis>(F, PA)))
97 return true;
98
99 // Otherwise this analysis result remains valid.
100 return false;
101}
102
103//===----------------------------------------------------------------------===//
104// Useful predicates
105//===----------------------------------------------------------------------===//
106
107/// Returns true if the pointer is to a function-local object that never
108/// escapes from the function.
109static bool isNonEscapingLocalObject(const Value *V) {
110 // If this is a local allocation, check to see if it escapes.
111 if (isa<AllocaInst>(V) || isNoAliasCall(V))
112 // Set StoreCaptures to True so that we can assume in our callers that the
113 // pointer is not the result of a load instruction. Currently
114 // PointerMayBeCaptured doesn't have any special analysis for the
115 // StoreCaptures=false case; if it did, our callers could be refined to be
116 // more precise.
117 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
118
119 // If this is an argument that corresponds to a byval or noalias argument,
120 // then it has not escaped before entering the function. Check if it escapes
121 // inside the function.
122 if (const Argument *A = dyn_cast<Argument>(V))
123 if (A->hasByValAttr() || A->hasNoAliasAttr())
124 // Note even if the argument is marked nocapture, we still need to check
125 // for copies made inside the function. The nocapture attribute only
126 // specifies that there are no copies made that outlive the function.
127 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
128
129 return false;
130}
131
132/// Returns true if the pointer is one which would have been considered an
133/// escape by isNonEscapingLocalObject.
134static bool isEscapeSource(const Value *V) {
135 if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
136 return true;
137
138 // The load case works because isNonEscapingLocalObject considers all
139 // stores to be escapes (it passes true for the StoreCaptures argument
140 // to PointerMayBeCaptured).
141 if (isa<LoadInst>(V))
142 return true;
143
144 return false;
145}
146
147/// Returns the size of the object specified by V or UnknownSize if unknown.
148static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
149 const TargetLibraryInfo &TLI,
150 bool RoundToAlign = false) {
151 uint64_t Size;
152 ObjectSizeOpts Opts;
153 Opts.RoundToAlign = RoundToAlign;
154 if (getObjectSize(V, Size, DL, &TLI, Opts))
155 return Size;
156 return MemoryLocation::UnknownSize;
157}
158
159/// Returns true if we can prove that the object specified by V is smaller than
160/// Size.
161static bool isObjectSmallerThan(const Value *V, uint64_t Size,
162 const DataLayout &DL,
163 const TargetLibraryInfo &TLI) {
164 // Note that the meanings of the "object" are slightly different in the
165 // following contexts:
166 // c1: llvm::getObjectSize()
167 // c2: llvm.objectsize() intrinsic
168 // c3: isObjectSmallerThan()
169 // c1 and c2 share the same meaning; however, the meaning of "object" in c3
170 // refers to the "entire object".
171 //
172 // Consider this example:
173 // char *p = (char*)malloc(100)
174 // char *q = p+80;
175 //
176 // In the context of c1 and c2, the "object" pointed by q refers to the
177 // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
178 //
179 // However, in the context of c3, the "object" refers to the chunk of memory
180 // being allocated. So, the "object" has 100 bytes, and q points to the middle
181 // the "object". In case q is passed to isObjectSmallerThan() as the 1st
182 // parameter, before the llvm::getObjectSize() is called to get the size of
183 // entire object, we should:
184 // - either rewind the pointer q to the base-address of the object in
185 // question (in this case rewind to p), or
186 // - just give up. It is up to caller to make sure the pointer is pointing
187 // to the base address the object.
188 //
189 // We go for 2nd option for simplicity.
190 if (!isIdentifiedObject(V))
191 return false;
192
193 // This function needs to use the aligned object size because we allow
194 // reads a bit past the end given sufficient alignment.
195 uint64_t ObjectSize = getObjectSize(V, DL, TLI, /*RoundToAlign*/ true);
196
197 return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size;
198}
199
200/// Returns true if we can prove that the object specified by V has size Size.
201static bool isObjectSize(const Value *V, uint64_t Size, const DataLayout &DL,
202 const TargetLibraryInfo &TLI) {
203 uint64_t ObjectSize = getObjectSize(V, DL, TLI);
204 return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size;
205}
206
207//===----------------------------------------------------------------------===//
208// GetElementPtr Instruction Decomposition and Analysis
209//===----------------------------------------------------------------------===//
210
211/// Analyzes the specified value as a linear expression: "A*V + B", where A and
212/// B are constant integers.
213///
214/// Returns the scale and offset values as APInts and return V as a Value*, and
215/// return whether we looked through any sign or zero extends. The incoming
216/// Value is known to have IntegerType, and it may already be sign or zero
217/// extended.
218///
219/// Note that this looks through extends, so the high bits may not be
220/// represented in the result.
221/*static*/ const Value *BasicAAResult::GetLinearExpression(
222 const Value *V, APInt &Scale, APInt &Offset, unsigned &ZExtBits,
223 unsigned &SExtBits, const DataLayout &DL, unsigned Depth,
224 AssumptionCache *AC, DominatorTree *DT, bool &NSW, bool &NUW) {
225 assert(V->getType()->isIntegerTy() && "Not an integer value")(static_cast <bool> (V->getType()->isIntegerTy() &&
"Not an integer value") ? void (0) : __assert_fail ("V->getType()->isIntegerTy() && \"Not an integer value\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp"
, 225, __extension__ __PRETTY_FUNCTION__))
;
226
227 // Limit our recursion depth.
228 if (Depth == 6) {
7
Taking false branch
229 Scale = 1;
230 Offset = 0;
231 return V;
232 }
233
234 if (const ConstantInt *Const = dyn_cast<ConstantInt>(V)) {
8
Taking false branch
235 // If it's a constant, just convert it to an offset and remove the variable.
236 // If we've been called recursively, the Offset bit width will be greater
237 // than the constant's (the Offset's always as wide as the outermost call),
238 // so we'll zext here and process any extension in the isa<SExtInst> &
239 // isa<ZExtInst> cases below.
240 Offset += Const->getValue().zextOrSelf(Offset.getBitWidth());
241 assert(Scale == 0 && "Constant values don't have a scale")(static_cast <bool> (Scale == 0 && "Constant values don't have a scale"
) ? void (0) : __assert_fail ("Scale == 0 && \"Constant values don't have a scale\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp"
, 241, __extension__ __PRETTY_FUNCTION__))
;
242 return V;
243 }
244
245 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
9
Assuming 'BOp' is non-null
10
Taking true branch
246 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
11
Assuming 'RHSC' is non-null
12
Taking true branch
247 // If we've been called recursively, then Offset and Scale will be wider
248 // than the BOp operands. We'll always zext it here as we'll process sign
249 // extensions below (see the isa<SExtInst> / isa<ZExtInst> cases).
250 APInt RHS = RHSC->getValue().zextOrSelf(Offset.getBitWidth());
251
252 switch (BOp->getOpcode()) {
13
Control jumps to 'case Shl:' at line 285
253 default:
254 // We don't understand this instruction, so we can't decompose it any
255 // further.
256 Scale = 1;
257 Offset = 0;
258 return V;
259 case Instruction::Or:
260 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't
261 // analyze it.
262 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC,
263 BOp, DT)) {
264 Scale = 1;
265 Offset = 0;
266 return V;
267 }
268 LLVM_FALLTHROUGH[[clang::fallthrough]];
269 case Instruction::Add:
270 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
271 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
272 Offset += RHS;
273 break;
274 case Instruction::Sub:
275 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
276 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
277 Offset -= RHS;
278 break;
279 case Instruction::Mul:
280 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
281 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
282 Offset *= RHS;
283 Scale *= RHS;
284 break;
285 case Instruction::Shl:
286 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
287 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
288
289 // We're trying to linearize an expression of the kind:
290 // shl i8 -128, 36
291 // where the shift count exceeds the bitwidth of the type.
292 // We can't decompose this further (the expression would return
293 // a poison value).
294 if (Offset.getBitWidth() < RHS.getLimitedValue() ||
14
Taking false branch
295 Scale.getBitWidth() < RHS.getLimitedValue()) {
296 Scale = 1;
297 Offset = 0;
298 return V;
299 }
300
301 Offset <<= RHS.getLimitedValue();
15
Calling 'APInt::getLimitedValue'
17
Returning from 'APInt::getLimitedValue'
18
Passing the value 4294967295 via 1st parameter 'ShiftAmt'
19
Calling 'APInt::operator<<='
302 Scale <<= RHS.getLimitedValue();
303 // the semantics of nsw and nuw for left shifts don't match those of
304 // multiplications, so we won't propagate them.
305 NSW = NUW = false;
306 return V;
307 }
308
309 if (isa<OverflowingBinaryOperator>(BOp)) {
310 NUW &= BOp->hasNoUnsignedWrap();
311 NSW &= BOp->hasNoSignedWrap();
312 }
313 return V;
314 }
315 }
316
317 // Since GEP indices are sign extended anyway, we don't care about the high
318 // bits of a sign or zero extended value - just scales and offsets. The
319 // extensions have to be consistent though.
320 if (isa<SExtInst>(V) || isa<ZExtInst>(V)) {
321 Value *CastOp = cast<CastInst>(V)->getOperand(0);
322 unsigned NewWidth = V->getType()->getPrimitiveSizeInBits();
323 unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
324 unsigned OldZExtBits = ZExtBits, OldSExtBits = SExtBits;
325 const Value *Result =
326 GetLinearExpression(CastOp, Scale, Offset, ZExtBits, SExtBits, DL,
327 Depth + 1, AC, DT, NSW, NUW);
328
329 // zext(zext(%x)) == zext(%x), and similarly for sext; we'll handle this
330 // by just incrementing the number of bits we've extended by.
331 unsigned ExtendedBy = NewWidth - SmallWidth;
332
333 if (isa<SExtInst>(V) && ZExtBits == 0) {
334 // sext(sext(%x, a), b) == sext(%x, a + b)
335
336 if (NSW) {
337 // We haven't sign-wrapped, so it's valid to decompose sext(%x + c)
338 // into sext(%x) + sext(c). We'll sext the Offset ourselves:
339 unsigned OldWidth = Offset.getBitWidth();
340 Offset = Offset.trunc(SmallWidth).sext(NewWidth).zextOrSelf(OldWidth);
341 } else {
342 // We may have signed-wrapped, so don't decompose sext(%x + c) into
343 // sext(%x) + sext(c)
344 Scale = 1;
345 Offset = 0;
346 Result = CastOp;
347 ZExtBits = OldZExtBits;
348 SExtBits = OldSExtBits;
349 }
350 SExtBits += ExtendedBy;
351 } else {
352 // sext(zext(%x, a), b) = zext(zext(%x, a), b) = zext(%x, a + b)
353
354 if (!NUW) {
355 // We may have unsigned-wrapped, so don't decompose zext(%x + c) into
356 // zext(%x) + zext(c)
357 Scale = 1;
358 Offset = 0;
359 Result = CastOp;
360 ZExtBits = OldZExtBits;
361 SExtBits = OldSExtBits;
362 }
363 ZExtBits += ExtendedBy;
364 }
365
366 return Result;
367 }
368
369 Scale = 1;
370 Offset = 0;
371 return V;
372}
373
374/// To ensure a pointer offset fits in an integer of size PointerSize
375/// (in bits) when that size is smaller than 64. This is an issue in
376/// particular for 32b programs with negative indices that rely on two's
377/// complement wrap-arounds for precise alias information.
378static int64_t adjustToPointerSize(int64_t Offset, unsigned PointerSize) {
379 assert(PointerSize <= 64 && "Invalid PointerSize!")(static_cast <bool> (PointerSize <= 64 && "Invalid PointerSize!"
) ? void (0) : __assert_fail ("PointerSize <= 64 && \"Invalid PointerSize!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp"
, 379, __extension__ __PRETTY_FUNCTION__))
;
380 unsigned ShiftBits = 64 - PointerSize;
381 return (int64_t)((uint64_t)Offset << ShiftBits) >> ShiftBits;
382}
383
384/// If V is a symbolic pointer expression, decompose it into a base pointer
385/// with a constant offset and a number of scaled symbolic offsets.
386///
387/// The scaled symbolic offsets (represented by pairs of a Value* and a scale
388/// in the VarIndices vector) are Value*'s that are known to be scaled by the
389/// specified amount, but which may have other unrepresented high bits. As
390/// such, the gep cannot necessarily be reconstructed from its decomposed form.
391///
392/// When DataLayout is around, this function is capable of analyzing everything
393/// that GetUnderlyingObject can look through. To be able to do that
394/// GetUnderlyingObject and DecomposeGEPExpression must use the same search
395/// depth (MaxLookupSearchDepth). When DataLayout not is around, it just looks
396/// through pointer casts.
397bool BasicAAResult::DecomposeGEPExpression(const Value *V,
398 DecomposedGEP &Decomposed, const DataLayout &DL, AssumptionCache *AC,
399 DominatorTree *DT) {
400 // Limit recursion depth to limit compile time in crazy cases.
401 unsigned MaxLookup = MaxLookupSearchDepth;
402 SearchTimes++;
403
404 Decomposed.StructOffset = 0;
405 Decomposed.OtherOffset = 0;
406 Decomposed.VarIndices.clear();
407 do {
408 // See if this is a bitcast or GEP.
409 const Operator *Op = dyn_cast<Operator>(V);
410 if (!Op) {
411 // The only non-operator case we can handle are GlobalAliases.
412 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
413 if (!GA->isInterposable()) {
414 V = GA->getAliasee();
415 continue;
416 }
417 }
418 Decomposed.Base = V;
419 return false;
420 }
421
422 if (Op->getOpcode() == Instruction::BitCast ||
423 Op->getOpcode() == Instruction::AddrSpaceCast) {
424 V = Op->getOperand(0);
425 continue;
426 }
427
428 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
429 if (!GEPOp) {
430 if (auto CS = ImmutableCallSite(V))
431 if (const Value *RV = CS.getReturnedArgOperand()) {
432 V = RV;
433 continue;
434 }
435
436 // If it's not a GEP, hand it off to SimplifyInstruction to see if it
437 // can come up with something. This matches what GetUnderlyingObject does.
438 if (const Instruction *I = dyn_cast<Instruction>(V))
439 // TODO: Get a DominatorTree and AssumptionCache and use them here
440 // (these are both now available in this function, but this should be
441 // updated when GetUnderlyingObject is updated). TLI should be
442 // provided also.
443 if (const Value *Simplified =
444 SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
445 V = Simplified;
446 continue;
447 }
448
449 Decomposed.Base = V;
450 return false;
451 }
452
453 // Don't attempt to analyze GEPs over unsized objects.
454 if (!GEPOp->getSourceElementType()->isSized()) {
455 Decomposed.Base = V;
456 return false;
457 }
458
459 unsigned AS = GEPOp->getPointerAddressSpace();
460 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
461 gep_type_iterator GTI = gep_type_begin(GEPOp);
462 unsigned PointerSize = DL.getPointerSizeInBits(AS);
463 // Assume all GEP operands are constants until proven otherwise.
464 bool GepHasConstantOffset = true;
465 for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end();
466 I != E; ++I, ++GTI) {
467 const Value *Index = *I;
468 // Compute the (potentially symbolic) offset in bytes for this index.
469 if (StructType *STy = GTI.getStructTypeOrNull()) {
470 // For a struct, add the member offset.
471 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
472 if (FieldNo == 0)
473 continue;
474
475 Decomposed.StructOffset +=
476 DL.getStructLayout(STy)->getElementOffset(FieldNo);
477 continue;
478 }
479
480 // For an array/pointer, add the element offset, explicitly scaled.
481 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
482 if (CIdx->isZero())
483 continue;
484 Decomposed.OtherOffset +=
485 DL.getTypeAllocSize(GTI.getIndexedType()) * CIdx->getSExtValue();
486 continue;
487 }
488
489 GepHasConstantOffset = false;
490
491 uint64_t Scale = DL.getTypeAllocSize(GTI.getIndexedType());
492 unsigned ZExtBits = 0, SExtBits = 0;
493
494 // If the integer type is smaller than the pointer size, it is implicitly
495 // sign extended to pointer size.
496 unsigned Width = Index->getType()->getIntegerBitWidth();
497 if (PointerSize > Width)
498 SExtBits += PointerSize - Width;
499
500 // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
501 APInt IndexScale(Width, 0), IndexOffset(Width, 0);
502 bool NSW = true, NUW = true;
503 Index = GetLinearExpression(Index, IndexScale, IndexOffset, ZExtBits,
504 SExtBits, DL, 0, AC, DT, NSW, NUW);
505
506 // All GEP math happens in the width of the pointer type,
507 // so we can truncate the value to 64-bits as we don't handle
508 // currently pointers larger than 64 bits and we would crash
509 // later. TODO: Make `Scale` an APInt to avoid this problem.
510 if (IndexScale.getBitWidth() > 64)
511 IndexScale = IndexScale.sextOrTrunc(64);
512
513 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
514 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
515 Decomposed.OtherOffset += IndexOffset.getSExtValue() * Scale;
516 Scale *= IndexScale.getSExtValue();
517
518 // If we already had an occurrence of this index variable, merge this
519 // scale into it. For example, we want to handle:
520 // A[x][x] -> x*16 + x*4 -> x*20
521 // This also ensures that 'x' only appears in the index list once.
522 for (unsigned i = 0, e = Decomposed.VarIndices.size(); i != e; ++i) {
523 if (Decomposed.VarIndices[i].V == Index &&
524 Decomposed.VarIndices[i].ZExtBits == ZExtBits &&
525 Decomposed.VarIndices[i].SExtBits == SExtBits) {
526 Scale += Decomposed.VarIndices[i].Scale;
527 Decomposed.VarIndices.erase(Decomposed.VarIndices.begin() + i);
528 break;
529 }
530 }
531
532 // Make sure that we have a scale that makes sense for this target's
533 // pointer size.
534 Scale = adjustToPointerSize(Scale, PointerSize);
535
536 if (Scale) {
537 VariableGEPIndex Entry = {Index, ZExtBits, SExtBits,
538 static_cast<int64_t>(Scale)};
539 Decomposed.VarIndices.push_back(Entry);
540 }
541 }
542
543 // Take care of wrap-arounds
544 if (GepHasConstantOffset) {
545 Decomposed.StructOffset =
546 adjustToPointerSize(Decomposed.StructOffset, PointerSize);
547 Decomposed.OtherOffset =
548 adjustToPointerSize(Decomposed.OtherOffset, PointerSize);
549 }
550
551 // Analyze the base pointer next.
552 V = GEPOp->getOperand(0);
553 } while (--MaxLookup);
554
555 // If the chain of expressions is too deep, just return early.
556 Decomposed.Base = V;
557 SearchLimitReached++;
558 return true;
559}
560
561/// Returns whether the given pointer value points to memory that is local to
562/// the function, with global constants being considered local to all
563/// functions.
564bool BasicAAResult::pointsToConstantMemory(const MemoryLocation &Loc,
565 bool OrLocal) {
566 assert(Visited.empty() && "Visited must be cleared after use!")(static_cast <bool> (Visited.empty() && "Visited must be cleared after use!"
) ? void (0) : __assert_fail ("Visited.empty() && \"Visited must be cleared after use!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp"
, 566, __extension__ __PRETTY_FUNCTION__))
;
567
568 unsigned MaxLookup = 8;
569 SmallVector<const Value *, 16> Worklist;
570 Worklist.push_back(Loc.Ptr);
571 do {
572 const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), DL);
573 if (!Visited.insert(V).second) {
574 Visited.clear();
575 return AAResultBase::pointsToConstantMemory(Loc, OrLocal);
576 }
577
578 // An alloca instruction defines local memory.
579 if (OrLocal && isa<AllocaInst>(V))
580 continue;
581
582 // A global constant counts as local memory for our purposes.
583 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
584 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
585 // global to be marked constant in some modules and non-constant in
586 // others. GV may even be a declaration, not a definition.
587 if (!GV->isConstant()) {
588 Visited.clear();
589 return AAResultBase::pointsToConstantMemory(Loc, OrLocal);
590 }
591 continue;
592 }
593
594 // If both select values point to local memory, then so does the select.
595 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
596 Worklist.push_back(SI->getTrueValue());
597 Worklist.push_back(SI->getFalseValue());
598 continue;
599 }
600
601 // If all values incoming to a phi node point to local memory, then so does
602 // the phi.
603 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
604 // Don't bother inspecting phi nodes with many operands.
605 if (PN->getNumIncomingValues() > MaxLookup) {
606 Visited.clear();
607 return AAResultBase::pointsToConstantMemory(Loc, OrLocal);
608 }
609 for (Value *IncValue : PN->incoming_values())
610 Worklist.push_back(IncValue);
611 continue;
612 }
613
614 // Otherwise be conservative.
615 Visited.clear();
616 return AAResultBase::pointsToConstantMemory(Loc, OrLocal);
617 } while (!Worklist.empty() && --MaxLookup);
618
619 Visited.clear();
620 return Worklist.empty();
621}
622
623/// Returns the behavior when calling the given call site.
624FunctionModRefBehavior BasicAAResult::getModRefBehavior(ImmutableCallSite CS) {
625 if (CS.doesNotAccessMemory())
626 // Can't do better than this.
627 return FMRB_DoesNotAccessMemory;
628
629 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
630
631 // If the callsite knows it only reads memory, don't return worse
632 // than that.
633 if (CS.onlyReadsMemory())
634 Min = FMRB_OnlyReadsMemory;
635 else if (CS.doesNotReadMemory())
636 Min = FMRB_DoesNotReadMemory;
637
638 if (CS.onlyAccessesArgMemory())
639 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
640 else if (CS.onlyAccessesInaccessibleMemory())
641 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem);
642 else if (CS.onlyAccessesInaccessibleMemOrArgMem())
643 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem);
644
645 // If CS has operand bundles then aliasing attributes from the function it
646 // calls do not directly apply to the CallSite. This can be made more
647 // precise in the future.
648 if (!CS.hasOperandBundles())
649 if (const Function *F = CS.getCalledFunction())
650 Min =
651 FunctionModRefBehavior(Min & getBestAAResults().getModRefBehavior(F));
652
653 return Min;
654}
655
656/// Returns the behavior when calling the given function. For use when the call
657/// site is not known.
658FunctionModRefBehavior BasicAAResult::getModRefBehavior(const Function *F) {
659 // If the function declares it doesn't access memory, we can't do better.
660 if (F->doesNotAccessMemory())
661 return FMRB_DoesNotAccessMemory;
662
663 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
664
665 // If the function declares it only reads memory, go with that.
666 if (F->onlyReadsMemory())
667 Min = FMRB_OnlyReadsMemory;
668 else if (F->doesNotReadMemory())
669 Min = FMRB_DoesNotReadMemory;
670
671 if (F->onlyAccessesArgMemory())
672 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
673 else if (F->onlyAccessesInaccessibleMemory())
674 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem);
675 else if (F->onlyAccessesInaccessibleMemOrArgMem())
676 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem);
677
678 return Min;
679}
680
681/// Returns true if this is a writeonly (i.e Mod only) parameter.
682static bool isWriteOnlyParam(ImmutableCallSite CS, unsigned ArgIdx,
683 const TargetLibraryInfo &TLI) {
684 if (CS.paramHasAttr(ArgIdx, Attribute::WriteOnly))
685 return true;
686
687 // We can bound the aliasing properties of memset_pattern16 just as we can
688 // for memcpy/memset. This is particularly important because the
689 // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
690 // whenever possible.
691 // FIXME Consider handling this in InferFunctionAttr.cpp together with other
692 // attributes.
693 LibFunc F;
694 if (CS.getCalledFunction() && TLI.getLibFunc(*CS.getCalledFunction(), F) &&
695 F == LibFunc_memset_pattern16 && TLI.has(F))
696 if (ArgIdx == 0)
697 return true;
698
699 // TODO: memset_pattern4, memset_pattern8
700 // TODO: _chk variants
701 // TODO: strcmp, strcpy
702
703 return false;
704}
705
706ModRefInfo BasicAAResult::getArgModRefInfo(ImmutableCallSite CS,
707 unsigned ArgIdx) {
708 // Checking for known builtin intrinsics and target library functions.
709 if (isWriteOnlyParam(CS, ArgIdx, TLI))
710 return ModRefInfo::Mod;
711
712 if (CS.paramHasAttr(ArgIdx, Attribute::ReadOnly))
713 return ModRefInfo::Ref;
714
715 if (CS.paramHasAttr(ArgIdx, Attribute::ReadNone))
716 return ModRefInfo::NoModRef;
717
718 return AAResultBase::getArgModRefInfo(CS, ArgIdx);
719}
720
721static bool isIntrinsicCall(ImmutableCallSite CS, Intrinsic::ID IID) {
722 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
723 return II && II->getIntrinsicID() == IID;
724}
725
726#ifndef NDEBUG
727static const Function *getParent(const Value *V) {
728 if (const Instruction *inst = dyn_cast<Instruction>(V)) {
729 if (!inst->getParent())
730 return nullptr;
731 return inst->getParent()->getParent();
732 }
733
734 if (const Argument *arg = dyn_cast<Argument>(V))
735 return arg->getParent();
736
737 return nullptr;
738}
739
740static bool notDifferentParent(const Value *O1, const Value *O2) {
741
742 const Function *F1 = getParent(O1);
743 const Function *F2 = getParent(O2);
744
745 return !F1 || !F2 || F1 == F2;
746}
747#endif
748
749AliasResult BasicAAResult::alias(const MemoryLocation &LocA,
750 const MemoryLocation &LocB) {
751 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&(static_cast <bool> (notDifferentParent(LocA.Ptr, LocB.
Ptr) && "BasicAliasAnalysis doesn't support interprocedural queries."
) ? void (0) : __assert_fail ("notDifferentParent(LocA.Ptr, LocB.Ptr) && \"BasicAliasAnalysis doesn't support interprocedural queries.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp"
, 752, __extension__ __PRETTY_FUNCTION__))
752 "BasicAliasAnalysis doesn't support interprocedural queries.")(static_cast <bool> (notDifferentParent(LocA.Ptr, LocB.
Ptr) && "BasicAliasAnalysis doesn't support interprocedural queries."
) ? void (0) : __assert_fail ("notDifferentParent(LocA.Ptr, LocB.Ptr) && \"BasicAliasAnalysis doesn't support interprocedural queries.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp"
, 752, __extension__ __PRETTY_FUNCTION__))
;
753
754 // If we have a directly cached entry for these locations, we have recursed
755 // through this once, so just return the cached results. Notably, when this
756 // happens, we don't clear the cache.
757 auto CacheIt = AliasCache.find(LocPair(LocA, LocB));
758 if (CacheIt != AliasCache.end())
759 return CacheIt->second;
760
761 AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags, LocB.Ptr,
762 LocB.Size, LocB.AATags);
763 // AliasCache rarely has more than 1 or 2 elements, always use
764 // shrink_and_clear so it quickly returns to the inline capacity of the
765 // SmallDenseMap if it ever grows larger.
766 // FIXME: This should really be shrink_to_inline_capacity_and_clear().
767 AliasCache.shrink_and_clear();
768 VisitedPhiBBs.clear();
769 return Alias;
770}
771
772/// Checks to see if the specified callsite can clobber the specified memory
773/// object.
774///
775/// Since we only look at local properties of this function, we really can't
776/// say much about this query. We do, however, use simple "address taken"
777/// analysis on local objects.
778ModRefInfo BasicAAResult::getModRefInfo(ImmutableCallSite CS,
779 const MemoryLocation &Loc) {
780 assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&(static_cast <bool> (notDifferentParent(CS.getInstruction
(), Loc.Ptr) && "AliasAnalysis query involving multiple functions!"
) ? void (0) : __assert_fail ("notDifferentParent(CS.getInstruction(), Loc.Ptr) && \"AliasAnalysis query involving multiple functions!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp"
, 781, __extension__ __PRETTY_FUNCTION__))
781 "AliasAnalysis query involving multiple functions!")(static_cast <bool> (notDifferentParent(CS.getInstruction
(), Loc.Ptr) && "AliasAnalysis query involving multiple functions!"
) ? void (0) : __assert_fail ("notDifferentParent(CS.getInstruction(), Loc.Ptr) && \"AliasAnalysis query involving multiple functions!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp"
, 781, __extension__ __PRETTY_FUNCTION__))
;
782
783 const Value *Object = GetUnderlyingObject(Loc.Ptr, DL);
784
785 // If this is a tail call and Loc.Ptr points to a stack location, we know that
786 // the tail call cannot access or modify the local stack.
787 // We cannot exclude byval arguments here; these belong to the caller of
788 // the current function not to the current function, and a tail callee
789 // may reference them.
790 if (isa<AllocaInst>(Object))
791 if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
792 if (CI->isTailCall())
793 return ModRefInfo::NoModRef;
794
795 // If the pointer is to a locally allocated object that does not escape,
796 // then the call can not mod/ref the pointer unless the call takes the pointer
797 // as an argument, and itself doesn't capture it.
798 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
799 isNonEscapingLocalObject(Object)) {
800
801 // Optimistically assume that call doesn't touch Object and check this
802 // assumption in the following loop.
803 ModRefInfo Result = ModRefInfo::NoModRef;
804 bool IsMustAlias = true;
805
806 unsigned OperandNo = 0;
807 for (auto CI = CS.data_operands_begin(), CE = CS.data_operands_end();
808 CI != CE; ++CI, ++OperandNo) {
809 // Only look at the no-capture or byval pointer arguments. If this
810 // pointer were passed to arguments that were neither of these, then it
811 // couldn't be no-capture.
812 if (!(*CI)->getType()->isPointerTy() ||
813 (!CS.doesNotCapture(OperandNo) &&
814 OperandNo < CS.getNumArgOperands() && !CS.isByValArgument(OperandNo)))
815 continue;
816
817 // Call doesn't access memory through this operand, so we don't care
818 // if it aliases with Object.
819 if (CS.doesNotAccessMemory(OperandNo))
820 continue;
821
822 // If this is a no-capture pointer argument, see if we can tell that it
823 // is impossible to alias the pointer we're checking.
824 AliasResult AR =
825 getBestAAResults().alias(MemoryLocation(*CI), MemoryLocation(Object));
826 if (AR != MustAlias)
827 IsMustAlias = false;
828 // Operand doesnt alias 'Object', continue looking for other aliases
829 if (AR == NoAlias)
830 continue;
831 // Operand aliases 'Object', but call doesn't modify it. Strengthen
832 // initial assumption and keep looking in case if there are more aliases.
833 if (CS.onlyReadsMemory(OperandNo)) {
834 Result = setRef(Result);
835 continue;
836 }
837 // Operand aliases 'Object' but call only writes into it.
838 if (CS.doesNotReadMemory(OperandNo)) {
839 Result = setMod(Result);
840 continue;
841 }
842 // This operand aliases 'Object' and call reads and writes into it.
843 // Setting ModRef will not yield an early return below, MustAlias is not
844 // used further.
845 Result = ModRefInfo::ModRef;
846 break;
847 }
848
849 // No operand aliases, reset Must bit. Add below if at least one aliases
850 // and all aliases found are MustAlias.
851 if (isNoModRef(Result))
852 IsMustAlias = false;
853
854 // Early return if we improved mod ref information
855 if (!isModAndRefSet(Result)) {
856 if (isNoModRef(Result))
857 return ModRefInfo::NoModRef;
858 return IsMustAlias ? setMust(Result) : clearMust(Result);
859 }
860 }
861
862 // If the CallSite is to malloc or calloc, we can assume that it doesn't
863 // modify any IR visible value. This is only valid because we assume these
864 // routines do not read values visible in the IR. TODO: Consider special
865 // casing realloc and strdup routines which access only their arguments as
866 // well. Or alternatively, replace all of this with inaccessiblememonly once
867 // that's implemented fully.
868 auto *Inst = CS.getInstruction();
869 if (isMallocOrCallocLikeFn(Inst, &TLI)) {
870 // Be conservative if the accessed pointer may alias the allocation -
871 // fallback to the generic handling below.
872 if (getBestAAResults().alias(MemoryLocation(Inst), Loc) == NoAlias)
873 return ModRefInfo::NoModRef;
874 }
875
876 // The semantics of memcpy intrinsics forbid overlap between their respective
877 // operands, i.e., source and destination of any given memcpy must no-alias.
878 // If Loc must-aliases either one of these two locations, then it necessarily
879 // no-aliases the other.
880 if (auto *Inst = dyn_cast<MemCpyInst>(CS.getInstruction())) {
881 AliasResult SrcAA, DestAA;
882
883 if ((SrcAA = getBestAAResults().alias(MemoryLocation::getForSource(Inst),
884 Loc)) == MustAlias)
885 // Loc is exactly the memcpy source thus disjoint from memcpy dest.
886 return ModRefInfo::Ref;
887 if ((DestAA = getBestAAResults().alias(MemoryLocation::getForDest(Inst),
888 Loc)) == MustAlias)
889 // The converse case.
890 return ModRefInfo::Mod;
891
892 // It's also possible for Loc to alias both src and dest, or neither.
893 ModRefInfo rv = ModRefInfo::NoModRef;
894 if (SrcAA != NoAlias)
895 rv = setRef(rv);
896 if (DestAA != NoAlias)
897 rv = setMod(rv);
898 return rv;
899 }
900
901 // While the assume intrinsic is marked as arbitrarily writing so that
902 // proper control dependencies will be maintained, it never aliases any
903 // particular memory location.
904 if (isIntrinsicCall(CS, Intrinsic::assume))
905 return ModRefInfo::NoModRef;
906
907 // Like assumes, guard intrinsics are also marked as arbitrarily writing so
908 // that proper control dependencies are maintained but they never mods any
909 // particular memory location.
910 //
911 // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
912 // heap state at the point the guard is issued needs to be consistent in case
913 // the guard invokes the "deopt" continuation.
914 if (isIntrinsicCall(CS, Intrinsic::experimental_guard))
915 return ModRefInfo::Ref;
916
917 // Like assumes, invariant.start intrinsics were also marked as arbitrarily
918 // writing so that proper control dependencies are maintained but they never
919 // mod any particular memory location visible to the IR.
920 // *Unlike* assumes (which are now modeled as NoModRef), invariant.start
921 // intrinsic is now modeled as reading memory. This prevents hoisting the
922 // invariant.start intrinsic over stores. Consider:
923 // *ptr = 40;
924 // *ptr = 50;
925 // invariant_start(ptr)
926 // int val = *ptr;
927 // print(val);
928 //
929 // This cannot be transformed to:
930 //
931 // *ptr = 40;
932 // invariant_start(ptr)
933 // *ptr = 50;
934 // int val = *ptr;
935 // print(val);
936 //
937 // The transformation will cause the second store to be ignored (based on
938 // rules of invariant.start) and print 40, while the first program always
939 // prints 50.
940 if (isIntrinsicCall(CS, Intrinsic::invariant_start))
941 return ModRefInfo::Ref;
942
943 // The AAResultBase base class has some smarts, lets use them.
944 return AAResultBase::getModRefInfo(CS, Loc);
945}
946
947ModRefInfo BasicAAResult::getModRefInfo(ImmutableCallSite CS1,
948 ImmutableCallSite CS2) {
949 // While the assume intrinsic is marked as arbitrarily writing so that
950 // proper control dependencies will be maintained, it never aliases any
951 // particular memory location.
952 if (isIntrinsicCall(CS1, Intrinsic::assume) ||
953 isIntrinsicCall(CS2, Intrinsic::assume))
954 return ModRefInfo::NoModRef;
955
956 // Like assumes, guard intrinsics are also marked as arbitrarily writing so
957 // that proper control dependencies are maintained but they never mod any
958 // particular memory location.
959 //
960 // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
961 // heap state at the point the guard is issued needs to be consistent in case
962 // the guard invokes the "deopt" continuation.
963
964 // NB! This function is *not* commutative, so we specical case two
965 // possibilities for guard intrinsics.
966
967 if (isIntrinsicCall(CS1, Intrinsic::experimental_guard))
968 return isModSet(createModRefInfo(getModRefBehavior(CS2)))
969 ? ModRefInfo::Ref
970 : ModRefInfo::NoModRef;
971
972 if (isIntrinsicCall(CS2, Intrinsic::experimental_guard))
973 return isModSet(createModRefInfo(getModRefBehavior(CS1)))
974 ? ModRefInfo::Mod
975 : ModRefInfo::NoModRef;
976
977 // The AAResultBase base class has some smarts, lets use them.
978 return AAResultBase::getModRefInfo(CS1, CS2);
979}
980
981/// Provide ad-hoc rules to disambiguate accesses through two GEP operators,
982/// both having the exact same pointer operand.
983static AliasResult aliasSameBasePointerGEPs(const GEPOperator *GEP1,
984 uint64_t V1Size,
985 const GEPOperator *GEP2,
986 uint64_t V2Size,
987 const DataLayout &DL) {
988 assert(GEP1->getPointerOperand()->stripPointerCastsAndBarriers() ==(static_cast <bool> (GEP1->getPointerOperand()->stripPointerCastsAndBarriers
() == GEP2->getPointerOperand()->stripPointerCastsAndBarriers
() && GEP1->getPointerOperandType() == GEP2->getPointerOperandType
() && "Expected GEPs with the same pointer operand") ?
void (0) : __assert_fail ("GEP1->getPointerOperand()->stripPointerCastsAndBarriers() == GEP2->getPointerOperand()->stripPointerCastsAndBarriers() && GEP1->getPointerOperandType() == GEP2->getPointerOperandType() && \"Expected GEPs with the same pointer operand\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp"
, 991, __extension__ __PRETTY_FUNCTION__))
989 GEP2->getPointerOperand()->stripPointerCastsAndBarriers() &&(static_cast <bool> (GEP1->getPointerOperand()->stripPointerCastsAndBarriers
() == GEP2->getPointerOperand()->stripPointerCastsAndBarriers
() && GEP1->getPointerOperandType() == GEP2->getPointerOperandType
() && "Expected GEPs with the same pointer operand") ?
void (0) : __assert_fail ("GEP1->getPointerOperand()->stripPointerCastsAndBarriers() == GEP2->getPointerOperand()->stripPointerCastsAndBarriers() && GEP1->getPointerOperandType() == GEP2->getPointerOperandType() && \"Expected GEPs with the same pointer operand\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp"
, 991, __extension__ __PRETTY_FUNCTION__))
990 GEP1->getPointerOperandType() == GEP2->getPointerOperandType() &&(static_cast <bool> (GEP1->getPointerOperand()->stripPointerCastsAndBarriers
() == GEP2->getPointerOperand()->stripPointerCastsAndBarriers
() && GEP1->getPointerOperandType() == GEP2->getPointerOperandType
() && "Expected GEPs with the same pointer operand") ?
void (0) : __assert_fail ("GEP1->getPointerOperand()->stripPointerCastsAndBarriers() == GEP2->getPointerOperand()->stripPointerCastsAndBarriers() && GEP1->getPointerOperandType() == GEP2->getPointerOperandType() && \"Expected GEPs with the same pointer operand\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp"
, 991, __extension__ __PRETTY_FUNCTION__))
991 "Expected GEPs with the same pointer operand")(static_cast <bool> (GEP1->getPointerOperand()->stripPointerCastsAndBarriers
() == GEP2->getPointerOperand()->stripPointerCastsAndBarriers
() && GEP1->getPointerOperandType() == GEP2->getPointerOperandType
() && "Expected GEPs with the same pointer operand") ?
void (0) : __assert_fail ("GEP1->getPointerOperand()->stripPointerCastsAndBarriers() == GEP2->getPointerOperand()->stripPointerCastsAndBarriers() && GEP1->getPointerOperandType() == GEP2->getPointerOperandType() && \"Expected GEPs with the same pointer operand\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp"
, 991, __extension__ __PRETTY_FUNCTION__))
;
992
993 // Try to determine whether GEP1 and GEP2 index through arrays, into structs,
994 // such that the struct field accesses provably cannot alias.
995 // We also need at least two indices (the pointer, and the struct field).
996 if (GEP1->getNumIndices() != GEP2->getNumIndices() ||
997 GEP1->getNumIndices() < 2)
998 return MayAlias;
999
1000 // If we don't know the size of the accesses through both GEPs, we can't
1001 // determine whether the struct fields accessed can't alias.
1002 if (V1Size == MemoryLocation::UnknownSize ||
1003 V2Size == MemoryLocation::UnknownSize)
1004 return MayAlias;
1005
1006 ConstantInt *C1 =
1007 dyn_cast<ConstantInt>(GEP1->getOperand(GEP1->getNumOperands() - 1));
1008 ConstantInt *C2 =
1009 dyn_cast<ConstantInt>(GEP2->getOperand(GEP2->getNumOperands() - 1));
1010
1011 // If the last (struct) indices are constants and are equal, the other indices
1012 // might be also be dynamically equal, so the GEPs can alias.
1013 if (C1 && C2 && C1->getSExtValue() == C2->getSExtValue())
1014 return MayAlias;
1015
1016 // Find the last-indexed type of the GEP, i.e., the type you'd get if
1017 // you stripped the last index.
1018 // On the way, look at each indexed type. If there's something other
1019 // than an array, different indices can lead to different final types.
1020 SmallVector<Value *, 8> IntermediateIndices;
1021
1022 // Insert the first index; we don't need to check the type indexed
1023 // through it as it only drops the pointer indirection.
1024 assert(GEP1->getNumIndices() > 1 && "Not enough GEP indices to examine")(static_cast <bool> (GEP1->getNumIndices() > 1 &&
"Not enough GEP indices to examine") ? void (0) : __assert_fail
("GEP1->getNumIndices() > 1 && \"Not enough GEP indices to examine\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp"
, 1024, __extension__ __PRETTY_FUNCTION__))
;
1025 IntermediateIndices.push_back(GEP1->getOperand(1));
1026
1027 // Insert all the remaining indices but the last one.
1028 // Also, check that they all index through arrays.
1029 for (unsigned i = 1, e = GEP1->getNumIndices() - 1; i != e; ++i) {
1030 if (!isa<ArrayType>(GetElementPtrInst::getIndexedType(
1031 GEP1->getSourceElementType(), IntermediateIndices)))
1032 return MayAlias;
1033 IntermediateIndices.push_back(GEP1->getOperand(i + 1));
1034 }
1035
1036 auto *Ty = GetElementPtrInst::getIndexedType(
1037 GEP1->getSourceElementType(), IntermediateIndices);
1038 StructType *LastIndexedStruct = dyn_cast<StructType>(Ty);
1039
1040 if (isa<SequentialType>(Ty)) {
1041 // We know that:
1042 // - both GEPs begin indexing from the exact same pointer;
1043 // - the last indices in both GEPs are constants, indexing into a sequential
1044 // type (array or pointer);
1045 // - both GEPs only index through arrays prior to that.
1046 //
1047 // Because array indices greater than the number of elements are valid in
1048 // GEPs, unless we know the intermediate indices are identical between
1049 // GEP1 and GEP2 we cannot guarantee that the last indexed arrays don't
1050 // partially overlap. We also need to check that the loaded size matches
1051 // the element size, otherwise we could still have overlap.
1052 const uint64_t ElementSize =
1053 DL.getTypeStoreSize(cast<SequentialType>(Ty)->getElementType());
1054 if (V1Size != ElementSize || V2Size != ElementSize)
1055 return MayAlias;
1056
1057 for (unsigned i = 0, e = GEP1->getNumIndices() - 1; i != e; ++i)
1058 if (GEP1->getOperand(i + 1) != GEP2->getOperand(i + 1))
1059 return MayAlias;
1060
1061 // Now we know that the array/pointer that GEP1 indexes into and that
1062 // that GEP2 indexes into must either precisely overlap or be disjoint.
1063 // Because they cannot partially overlap and because fields in an array
1064 // cannot overlap, if we can prove the final indices are different between
1065 // GEP1 and GEP2, we can conclude GEP1 and GEP2 don't alias.
1066
1067 // If the last indices are constants, we've already checked they don't
1068 // equal each other so we can exit early.
1069 if (C1 && C2)
1070 return NoAlias;
1071 {
1072 Value *GEP1LastIdx = GEP1->getOperand(GEP1->getNumOperands() - 1);
1073 Value *GEP2LastIdx = GEP2->getOperand(GEP2->getNumOperands() - 1);
1074 if (isa<PHINode>(GEP1LastIdx) || isa<PHINode>(GEP2LastIdx)) {
1075 // If one of the indices is a PHI node, be safe and only use
1076 // computeKnownBits so we don't make any assumptions about the
1077 // relationships between the two indices. This is important if we're
1078 // asking about values from different loop iterations. See PR32314.
1079 // TODO: We may be able to change the check so we only do this when
1080 // we definitely looked through a PHINode.
1081 if (GEP1LastIdx != GEP2LastIdx &&
1082 GEP1LastIdx->getType() == GEP2LastIdx->getType()) {
1083 KnownBits Known1 = computeKnownBits(GEP1LastIdx, DL);
1084 KnownBits Known2 = computeKnownBits(GEP2LastIdx, DL);
1085 if (Known1.Zero.intersects(Known2.One) ||
1086 Known1.One.intersects(Known2.Zero))
1087 return NoAlias;
1088 }
1089 } else if (isKnownNonEqual(GEP1LastIdx, GEP2LastIdx, DL))
1090 return NoAlias;
1091 }
1092 return MayAlias;
1093 } else if (!LastIndexedStruct || !C1 || !C2) {
1094 return MayAlias;
1095 }
1096
1097 // We know that:
1098 // - both GEPs begin indexing from the exact same pointer;
1099 // - the last indices in both GEPs are constants, indexing into a struct;
1100 // - said indices are different, hence, the pointed-to fields are different;
1101 // - both GEPs only index through arrays prior to that.
1102 //
1103 // This lets us determine that the struct that GEP1 indexes into and the
1104 // struct that GEP2 indexes into must either precisely overlap or be
1105 // completely disjoint. Because they cannot partially overlap, indexing into
1106 // different non-overlapping fields of the struct will never alias.
1107
1108 // Therefore, the only remaining thing needed to show that both GEPs can't
1109 // alias is that the fields are not overlapping.
1110 const StructLayout *SL = DL.getStructLayout(LastIndexedStruct);
1111 const uint64_t StructSize = SL->getSizeInBytes();
1112 const uint64_t V1Off = SL->getElementOffset(C1->getZExtValue());
1113 const uint64_t V2Off = SL->getElementOffset(C2->getZExtValue());
1114
1115 auto EltsDontOverlap = [StructSize](uint64_t V1Off, uint64_t V1Size,
1116 uint64_t V2Off, uint64_t V2Size) {
1117 return V1Off < V2Off && V1Off + V1Size <= V2Off &&
1118 ((V2Off + V2Size <= StructSize) ||
1119 (V2Off + V2Size - StructSize <= V1Off));
1120 };
1121
1122 if (EltsDontOverlap(V1Off, V1Size, V2Off, V2Size) ||
1123 EltsDontOverlap(V2Off, V2Size, V1Off, V1Size))
1124 return NoAlias;
1125
1126 return MayAlias;
1127}
1128
1129// If a we have (a) a GEP and (b) a pointer based on an alloca, and the
1130// beginning of the object the GEP points would have a negative offset with
1131// repsect to the alloca, that means the GEP can not alias pointer (b).
1132// Note that the pointer based on the alloca may not be a GEP. For
1133// example, it may be the alloca itself.
1134// The same applies if (b) is based on a GlobalVariable. Note that just being
1135// based on isIdentifiedObject() is not enough - we need an identified object
1136// that does not permit access to negative offsets. For example, a negative
1137// offset from a noalias argument or call can be inbounds w.r.t the actual
1138// underlying object.
1139//
1140// For example, consider:
1141//
1142// struct { int f0, int f1, ...} foo;
1143// foo alloca;
1144// foo* random = bar(alloca);
1145// int *f0 = &alloca.f0
1146// int *f1 = &random->f1;
1147//
1148// Which is lowered, approximately, to:
1149//
1150// %alloca = alloca %struct.foo
1151// %random = call %struct.foo* @random(%struct.foo* %alloca)
1152// %f0 = getelementptr inbounds %struct, %struct.foo* %alloca, i32 0, i32 0
1153// %f1 = getelementptr inbounds %struct, %struct.foo* %random, i32 0, i32 1
1154//
1155// Assume %f1 and %f0 alias. Then %f1 would point into the object allocated
1156// by %alloca. Since the %f1 GEP is inbounds, that means %random must also
1157// point into the same object. But since %f0 points to the beginning of %alloca,
1158// the highest %f1 can be is (%alloca + 3). This means %random can not be higher
1159// than (%alloca - 1), and so is not inbounds, a contradiction.
1160bool BasicAAResult::isGEPBaseAtNegativeOffset(const GEPOperator *GEPOp,
1161 const DecomposedGEP &DecompGEP, const DecomposedGEP &DecompObject,
1162 uint64_t ObjectAccessSize) {
1163 // If the object access size is unknown, or the GEP isn't inbounds, bail.
1164 if (ObjectAccessSize == MemoryLocation::UnknownSize || !GEPOp->isInBounds())
1165 return false;
1166
1167 // We need the object to be an alloca or a globalvariable, and want to know
1168 // the offset of the pointer from the object precisely, so no variable
1169 // indices are allowed.
1170 if (!(isa<AllocaInst>(DecompObject.Base) ||
1171 isa<GlobalVariable>(DecompObject.Base)) ||
1172 !DecompObject.VarIndices.empty())
1173 return false;
1174
1175 int64_t ObjectBaseOffset = DecompObject.StructOffset +
1176 DecompObject.OtherOffset;
1177
1178 // If the GEP has no variable indices, we know the precise offset
1179 // from the base, then use it. If the GEP has variable indices, we're in
1180 // a bit more trouble: we can't count on the constant offsets that come
1181 // from non-struct sources, since these can be "rewound" by a negative
1182 // variable offset. So use only offsets that came from structs.
1183 int64_t GEPBaseOffset = DecompGEP.StructOffset;
1184 if (DecompGEP.VarIndices.empty())
1185 GEPBaseOffset += DecompGEP.OtherOffset;
1186
1187 return (GEPBaseOffset >= ObjectBaseOffset + (int64_t)ObjectAccessSize);
1188}
1189
1190/// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against
1191/// another pointer.
1192///
1193/// We know that V1 is a GEP, but we don't know anything about V2.
1194/// UnderlyingV1 is GetUnderlyingObject(GEP1, DL), UnderlyingV2 is the same for
1195/// V2.
1196AliasResult BasicAAResult::aliasGEP(const GEPOperator *GEP1, uint64_t V1Size,
1197 const AAMDNodes &V1AAInfo, const Value *V2,
1198 uint64_t V2Size, const AAMDNodes &V2AAInfo,
1199 const Value *UnderlyingV1,
1200 const Value *UnderlyingV2) {
1201 DecomposedGEP DecompGEP1, DecompGEP2;
1202 bool GEP1MaxLookupReached =
1203 DecomposeGEPExpression(GEP1, DecompGEP1, DL, &AC, DT);
1204 bool GEP2MaxLookupReached =
1205 DecomposeGEPExpression(V2, DecompGEP2, DL, &AC, DT);
1206
1207 int64_t GEP1BaseOffset = DecompGEP1.StructOffset + DecompGEP1.OtherOffset;
1208 int64_t GEP2BaseOffset = DecompGEP2.StructOffset + DecompGEP2.OtherOffset;
1209
1210 assert(DecompGEP1.Base == UnderlyingV1 && DecompGEP2.Base == UnderlyingV2 &&(static_cast <bool> (DecompGEP1.Base == UnderlyingV1 &&
DecompGEP2.Base == UnderlyingV2 && "DecomposeGEPExpression returned a result different from "
"GetUnderlyingObject") ? void (0) : __assert_fail ("DecompGEP1.Base == UnderlyingV1 && DecompGEP2.Base == UnderlyingV2 && \"DecomposeGEPExpression returned a result different from \" \"GetUnderlyingObject\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp"
, 1212, __extension__ __PRETTY_FUNCTION__))
1211 "DecomposeGEPExpression returned a result different from "(static_cast <bool> (DecompGEP1.Base == UnderlyingV1 &&
DecompGEP2.Base == UnderlyingV2 && "DecomposeGEPExpression returned a result different from "
"GetUnderlyingObject") ? void (0) : __assert_fail ("DecompGEP1.Base == UnderlyingV1 && DecompGEP2.Base == UnderlyingV2 && \"DecomposeGEPExpression returned a result different from \" \"GetUnderlyingObject\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp"
, 1212, __extension__ __PRETTY_FUNCTION__))
1212 "GetUnderlyingObject")(static_cast <bool> (DecompGEP1.Base == UnderlyingV1 &&
DecompGEP2.Base == UnderlyingV2 && "DecomposeGEPExpression returned a result different from "
"GetUnderlyingObject") ? void (0) : __assert_fail ("DecompGEP1.Base == UnderlyingV1 && DecompGEP2.Base == UnderlyingV2 && \"DecomposeGEPExpression returned a result different from \" \"GetUnderlyingObject\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp"
, 1212, __extension__ __PRETTY_FUNCTION__))
;
1213
1214 // If the GEP's offset relative to its base is such that the base would
1215 // fall below the start of the object underlying V2, then the GEP and V2
1216 // cannot alias.
1217 if (!GEP1MaxLookupReached && !GEP2MaxLookupReached &&
1218 isGEPBaseAtNegativeOffset(GEP1, DecompGEP1, DecompGEP2, V2Size))
1219 return NoAlias;
1220 // If we have two gep instructions with must-alias or not-alias'ing base
1221 // pointers, figure out if the indexes to the GEP tell us anything about the
1222 // derived pointer.
1223 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
1224 // Check for the GEP base being at a negative offset, this time in the other
1225 // direction.
1226 if (!GEP1MaxLookupReached && !GEP2MaxLookupReached &&
1227 isGEPBaseAtNegativeOffset(GEP2, DecompGEP2, DecompGEP1, V1Size))
1228 return NoAlias;
1229 // Do the base pointers alias?
1230 AliasResult BaseAlias =
1231 aliasCheck(UnderlyingV1, MemoryLocation::UnknownSize, AAMDNodes(),
1232 UnderlyingV2, MemoryLocation::UnknownSize, AAMDNodes());
1233
1234 // Check for geps of non-aliasing underlying pointers where the offsets are
1235 // identical.
1236 if ((BaseAlias == MayAlias) && V1Size == V2Size) {
1237 // Do the base pointers alias assuming type and size.
1238 AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size, V1AAInfo,
1239 UnderlyingV2, V2Size, V2AAInfo);
1240 if (PreciseBaseAlias == NoAlias) {
1241 // See if the computed offset from the common pointer tells us about the
1242 // relation of the resulting pointer.
1243 // If the max search depth is reached the result is undefined
1244 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
1245 return MayAlias;
1246
1247 // Same offsets.
1248 if (GEP1BaseOffset == GEP2BaseOffset &&
1249 DecompGEP1.VarIndices == DecompGEP2.VarIndices)
1250 return NoAlias;
1251 }
1252 }
1253
1254 // If we get a No or May, then return it immediately, no amount of analysis
1255 // will improve this situation.
1256 if (BaseAlias != MustAlias) {
1257 assert(BaseAlias == NoAlias || BaseAlias == MayAlias)(static_cast <bool> (BaseAlias == NoAlias || BaseAlias ==
MayAlias) ? void (0) : __assert_fail ("BaseAlias == NoAlias || BaseAlias == MayAlias"
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp"
, 1257, __extension__ __PRETTY_FUNCTION__))
;
1258 return BaseAlias;
1259 }
1260
1261 // Otherwise, we have a MustAlias. Since the base pointers alias each other
1262 // exactly, see if the computed offset from the common pointer tells us
1263 // about the relation of the resulting pointer.
1264 // If we know the two GEPs are based off of the exact same pointer (and not
1265 // just the same underlying object), see if that tells us anything about
1266 // the resulting pointers.
1267 if (GEP1->getPointerOperand()->stripPointerCastsAndBarriers() ==
1268 GEP2->getPointerOperand()->stripPointerCastsAndBarriers() &&
1269 GEP1->getPointerOperandType() == GEP2->getPointerOperandType()) {
1270 AliasResult R = aliasSameBasePointerGEPs(GEP1, V1Size, GEP2, V2Size, DL);
1271 // If we couldn't find anything interesting, don't abandon just yet.
1272 if (R != MayAlias)
1273 return R;
1274 }
1275
1276 // If the max search depth is reached, the result is undefined
1277 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
1278 return MayAlias;
1279
1280 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
1281 // symbolic difference.
1282 GEP1BaseOffset -= GEP2BaseOffset;
1283 GetIndexDifference(DecompGEP1.VarIndices, DecompGEP2.VarIndices);
1284
1285 } else {
1286 // Check to see if these two pointers are related by the getelementptr
1287 // instruction. If one pointer is a GEP with a non-zero index of the other
1288 // pointer, we know they cannot alias.
1289
1290 // If both accesses are unknown size, we can't do anything useful here.
1291 if (V1Size == MemoryLocation::UnknownSize &&
1292 V2Size == MemoryLocation::UnknownSize)
1293 return MayAlias;
1294
1295 AliasResult R = aliasCheck(UnderlyingV1, MemoryLocation::UnknownSize,
1296 AAMDNodes(), V2, MemoryLocation::UnknownSize,
1297 V2AAInfo, nullptr, UnderlyingV2);
1298 if (R != MustAlias) {
1299 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
1300 // If V2 is known not to alias GEP base pointer, then the two values
1301 // cannot alias per GEP semantics: "Any memory access must be done through
1302 // a pointer value associated with an address range of the memory access,
1303 // otherwise the behavior is undefined.".
1304 assert(R == NoAlias || R == MayAlias)(static_cast <bool> (R == NoAlias || R == MayAlias) ? void
(0) : __assert_fail ("R == NoAlias || R == MayAlias", "/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp"
, 1304, __extension__ __PRETTY_FUNCTION__))
;
1305 return R;
1306 }
1307
1308 // If the max search depth is reached the result is undefined
1309 if (GEP1MaxLookupReached)
1310 return MayAlias;
1311 }
1312
1313 // In the two GEP Case, if there is no difference in the offsets of the
1314 // computed pointers, the resultant pointers are a must alias. This
1315 // happens when we have two lexically identical GEP's (for example).
1316 //
1317 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
1318 // must aliases the GEP, the end result is a must alias also.
1319 if (GEP1BaseOffset == 0 && DecompGEP1.VarIndices.empty())
1320 return MustAlias;
1321
1322 // If there is a constant difference between the pointers, but the difference
1323 // is less than the size of the associated memory object, then we know
1324 // that the objects are partially overlapping. If the difference is
1325 // greater, we know they do not overlap.
1326 if (GEP1BaseOffset != 0 && DecompGEP1.VarIndices.empty()) {
1327 if (GEP1BaseOffset >= 0) {
1328 if (V2Size != MemoryLocation::UnknownSize) {
1329 if ((uint64_t)GEP1BaseOffset < V2Size)
1330 return PartialAlias;
1331 return NoAlias;
1332 }
1333 } else {
1334 // We have the situation where:
1335 // + +
1336 // | BaseOffset |
1337 // ---------------->|
1338 // |-->V1Size |-------> V2Size
1339 // GEP1 V2
1340 // We need to know that V2Size is not unknown, otherwise we might have
1341 // stripped a gep with negative index ('gep <ptr>, -1, ...).
1342 if (V1Size != MemoryLocation::UnknownSize &&
1343 V2Size != MemoryLocation::UnknownSize) {
1344 if (-(uint64_t)GEP1BaseOffset < V1Size)
1345 return PartialAlias;
1346 return NoAlias;
1347 }
1348 }
1349 }
1350
1351 if (!DecompGEP1.VarIndices.empty()) {
1352 uint64_t Modulo = 0;
1353 bool AllPositive = true;
1354 for (unsigned i = 0, e = DecompGEP1.VarIndices.size(); i != e; ++i) {
1355
1356 // Try to distinguish something like &A[i][1] against &A[42][0].
1357 // Grab the least significant bit set in any of the scales. We
1358 // don't need std::abs here (even if the scale's negative) as we'll
1359 // be ^'ing Modulo with itself later.
1360 Modulo |= (uint64_t)DecompGEP1.VarIndices[i].Scale;
1361
1362 if (AllPositive) {
1363 // If the Value could change between cycles, then any reasoning about
1364 // the Value this cycle may not hold in the next cycle. We'll just
1365 // give up if we can't determine conditions that hold for every cycle:
1366 const Value *V = DecompGEP1.VarIndices[i].V;
1367
1368 KnownBits Known = computeKnownBits(V, DL, 0, &AC, nullptr, DT);
1369 bool SignKnownZero = Known.isNonNegative();
1370 bool SignKnownOne = Known.isNegative();
1371
1372 // Zero-extension widens the variable, and so forces the sign
1373 // bit to zero.
1374 bool IsZExt = DecompGEP1.VarIndices[i].ZExtBits > 0 || isa<ZExtInst>(V);
1375 SignKnownZero |= IsZExt;
1376 SignKnownOne &= !IsZExt;
1377
1378 // If the variable begins with a zero then we know it's
1379 // positive, regardless of whether the value is signed or
1380 // unsigned.
1381 int64_t Scale = DecompGEP1.VarIndices[i].Scale;
1382 AllPositive =
1383 (SignKnownZero && Scale >= 0) || (SignKnownOne && Scale < 0);
1384 }
1385 }
1386
1387 Modulo = Modulo ^ (Modulo & (Modulo - 1));
1388
1389 // We can compute the difference between the two addresses
1390 // mod Modulo. Check whether that difference guarantees that the
1391 // two locations do not alias.
1392 uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
1393 if (V1Size != MemoryLocation::UnknownSize &&
1394 V2Size != MemoryLocation::UnknownSize && ModOffset >= V2Size &&
1395 V1Size <= Modulo - ModOffset)
1396 return NoAlias;
1397
1398 // If we know all the variables are positive, then GEP1 >= GEP1BasePtr.
1399 // If GEP1BasePtr > V2 (GEP1BaseOffset > 0) then we know the pointers
1400 // don't alias if V2Size can fit in the gap between V2 and GEP1BasePtr.
1401 if (AllPositive && GEP1BaseOffset > 0 && V2Size <= (uint64_t)GEP1BaseOffset)
1402 return NoAlias;
1403
1404 if (constantOffsetHeuristic(DecompGEP1.VarIndices, V1Size, V2Size,
1405 GEP1BaseOffset, &AC, DT))
1406 return NoAlias;
1407 }
1408
1409 // Statically, we can see that the base objects are the same, but the
1410 // pointers have dynamic offsets which we can't resolve. And none of our
1411 // little tricks above worked.
1412 return MayAlias;
1413}
1414
1415static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {
1416 // If the results agree, take it.
1417 if (A == B)
1418 return A;
1419 // A mix of PartialAlias and MustAlias is PartialAlias.
1420 if ((A == PartialAlias && B == MustAlias) ||
1421 (B == PartialAlias && A == MustAlias))
1422 return PartialAlias;
1423 // Otherwise, we don't know anything.
1424 return MayAlias;
1425}
1426
1427/// Provides a bunch of ad-hoc rules to disambiguate a Select instruction
1428/// against another.
1429AliasResult BasicAAResult::aliasSelect(const SelectInst *SI, uint64_t SISize,
1430 const AAMDNodes &SIAAInfo,
1431 const Value *V2, uint64_t V2Size,
1432 const AAMDNodes &V2AAInfo,
1433 const Value *UnderV2) {
1434 // If the values are Selects with the same condition, we can do a more precise
1435 // check: just check for aliases between the values on corresponding arms.
1436 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1437 if (SI->getCondition() == SI2->getCondition()) {
1438 AliasResult Alias = aliasCheck(SI->getTrueValue(), SISize, SIAAInfo,
1439 SI2->getTrueValue(), V2Size, V2AAInfo);
1440 if (Alias == MayAlias)
1441 return MayAlias;
1442 AliasResult ThisAlias =
1443 aliasCheck(SI->getFalseValue(), SISize, SIAAInfo,
1444 SI2->getFalseValue(), V2Size, V2AAInfo);
1445 return MergeAliasResults(ThisAlias, Alias);
1446 }
1447
1448 // If both arms of the Select node NoAlias or MustAlias V2, then returns
1449 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1450 AliasResult Alias =
1451 aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(),
1452 SISize, SIAAInfo, UnderV2);
1453 if (Alias == MayAlias)
1454 return MayAlias;
1455
1456 AliasResult ThisAlias =
1457 aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(), SISize, SIAAInfo,
1458 UnderV2);
1459 return MergeAliasResults(ThisAlias, Alias);
1460}
1461
1462/// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against
1463/// another.
1464AliasResult BasicAAResult::aliasPHI(const PHINode *PN, uint64_t PNSize,
1465 const AAMDNodes &PNAAInfo, const Value *V2,
1466 uint64_t V2Size, const AAMDNodes &V2AAInfo,
1467 const Value *UnderV2) {
1468 // Track phi nodes we have visited. We use this information when we determine
1469 // value equivalence.
1470 VisitedPhiBBs.insert(PN->getParent());
1471
1472 // If the values are PHIs in the same block, we can do a more precise
1473 // as well as efficient check: just check for aliases between the values
1474 // on corresponding edges.
1475 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1476 if (PN2->getParent() == PN->getParent()) {
1477 LocPair Locs(MemoryLocation(PN, PNSize, PNAAInfo),
1478 MemoryLocation(V2, V2Size, V2AAInfo));
1479 if (PN > V2)
1480 std::swap(Locs.first, Locs.second);
1481 // Analyse the PHIs' inputs under the assumption that the PHIs are
1482 // NoAlias.
1483 // If the PHIs are May/MustAlias there must be (recursively) an input
1484 // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
1485 // there must be an operation on the PHIs within the PHIs' value cycle
1486 // that causes a MayAlias.
1487 // Pretend the phis do not alias.
1488 AliasResult Alias = NoAlias;
1489 assert(AliasCache.count(Locs) &&(static_cast <bool> (AliasCache.count(Locs) && "There must exist an entry for the phi node"
) ? void (0) : __assert_fail ("AliasCache.count(Locs) && \"There must exist an entry for the phi node\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp"
, 1490, __extension__ __PRETTY_FUNCTION__))
1490 "There must exist an entry for the phi node")(static_cast <bool> (AliasCache.count(Locs) && "There must exist an entry for the phi node"
) ? void (0) : __assert_fail ("AliasCache.count(Locs) && \"There must exist an entry for the phi node\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/Analysis/BasicAliasAnalysis.cpp"
, 1490, __extension__ __PRETTY_FUNCTION__))
;
1491 AliasResult OrigAliasResult = AliasCache[Locs];
1492 AliasCache[Locs] = NoAlias;
1493
1494 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1495 AliasResult ThisAlias =
1496 aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo,
1497 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
1498 V2Size, V2AAInfo);
1499 Alias = MergeAliasResults(ThisAlias, Alias);
1500 if (Alias == MayAlias)
1501 break;
1502 }
1503
1504 // Reset if speculation failed.
1505 if (Alias != NoAlias)
1506 AliasCache[Locs] = OrigAliasResult;
1507
1508 return Alias;
1509 }
1510
1511 SmallPtrSet<Value *, 4> UniqueSrc;
1512 SmallVector<Value *, 4> V1Srcs;
1513 bool isRecursive = false;
1514 for (Value *PV1 : PN->incoming_values()) {
1515 if (isa<PHINode>(PV1))
1516 // If any of the source itself is a PHI, return MayAlias conservatively
1517 // to avoid compile time explosion. The worst possible case is if both
1518 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
1519 // and 'n' are the number of PHI sources.
1520 return MayAlias;
1521
1522 if (EnableRecPhiAnalysis)
1523 if (GEPOperator *PV1GEP = dyn_cast<GEPOperator>(PV1)) {
1524 // Check whether the incoming value is a GEP that advances the pointer
1525 // result of this PHI node (e.g. in a loop). If this is the case, we
1526 // would recurse and always get a MayAlias. Handle this case specially
1527 // below.
1528 if (PV1GEP->getPointerOperand() == PN && PV1GEP->getNumIndices() == 1 &&
1529 isa<ConstantInt>(PV1GEP->idx_begin())) {
1530 isRecursive = true;
1531 continue;
1532 }
1533 }
1534
1535 if (UniqueSrc.insert(PV1).second)
1536 V1Srcs.push_back(PV1);
1537 }
1538
1539 // If this PHI node is recursive, set the size of the accessed memory to
1540 // unknown to represent all the possible values the GEP could advance the
1541 // pointer to.
1542 if (isRecursive)
1543 PNSize = MemoryLocation::UnknownSize;
1544
1545 AliasResult Alias =
1546 aliasCheck(V2, V2Size, V2AAInfo, V1Srcs[0],
1547 PNSize, PNAAInfo, UnderV2);
1548
1549 // Early exit if the check of the first PHI source against V2 is MayAlias.
1550 // Other results are not possible.
1551 if (Alias == MayAlias)
1552 return MayAlias;
1553
1554 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1555 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1556 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1557 Value *V = V1Srcs[i];
1558
1559 AliasResult ThisAlias =
1560 aliasCheck(V2, V2Size, V2AAInfo, V, PNSize, PNAAInfo, UnderV2);
1561 Alias = MergeAliasResults(ThisAlias, Alias);
1562 if (Alias == MayAlias)
1563 break;
1564 }
1565
1566 return Alias;
1567}
1568
1569/// Provides a bunch of ad-hoc rules to disambiguate in common cases, such as
1570/// array references.
1571AliasResult BasicAAResult::aliasCheck(const Value *V1, uint64_t V1Size,
1572 AAMDNodes V1AAInfo, const Value *V2,
1573 uint64_t V2Size, AAMDNodes V2AAInfo,
1574 const Value *O1, const Value *O2) {
1575 // If either of the memory references is empty, it doesn't matter what the
1576 // pointer values are.
1577 if (V1Size == 0 || V2Size == 0)
1578 return NoAlias;
1579
1580 // Strip off any casts if they exist.
1581 V1 = V1->stripPointerCastsAndBarriers();
1582 V2 = V2->stripPointerCastsAndBarriers();
1583
1584 // If V1 or V2 is undef, the result is NoAlias because we can always pick a
1585 // value for undef that aliases nothing in the program.
1586 if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
1587 return NoAlias;
1588
1589 // Are we checking for alias of the same value?
1590 // Because we look 'through' phi nodes, we could look at "Value" pointers from
1591 // different iterations. We must therefore make sure that this is not the
1592 // case. The function isValueEqualInPotentialCycles ensures that this cannot
1593 // happen by looking at the visited phi nodes and making sure they cannot
1594 // reach the value.
1595 if (isValueEqualInPotentialCycles(V1, V2))
1596 return MustAlias;
1597
1598 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
1599 return NoAlias; // Scalars cannot alias each other
1600
1601 // Figure out what objects these things are pointing to if we can.
1602 if (O1 == nullptr)
1603 O1 = GetUnderlyingObject(V1, DL, MaxLookupSearchDepth);
1604
1605 if (O2 == nullptr)
1606 O2 = GetUnderlyingObject(V2, DL, MaxLookupSearchDepth);
1607
1608 // Null values in the default address space don't point to any object, so they
1609 // don't alias any other pointer.
1610 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1611 if (CPN->getType()->getAddressSpace() == 0)
1612 return NoAlias;
1613 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1614 if (CPN->getType()->getAddressSpace() == 0)
1615 return NoAlias;
1616
1617 if (O1 != O2) {
1618 // If V1/V2 point to two different objects, we know that we have no alias.
1619 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
1620 return NoAlias;
1621
1622 // Constant pointers can't alias with non-const isIdentifiedObject objects.
1623 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1624 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
1625 return NoAlias;
1626
1627 // Function arguments can't alias with things that are known to be
1628 // unambigously identified at the function level.
1629 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1630 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
1631 return NoAlias;
1632
1633 // If one pointer is the result of a call/invoke or load and the other is a
1634 // non-escaping local object within the same function, then we know the
1635 // object couldn't escape to a point where the call could return it.
1636 //
1637 // Note that if the pointers are in different functions, there are a
1638 // variety of complications. A call with a nocapture argument may still
1639 // temporary store the nocapture argument's value in a temporary memory
1640 // location if that memory location doesn't escape. Or it may pass a
1641 // nocapture value to other functions as long as they don't capture it.
1642 if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1643 return NoAlias;
1644 if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1645 return NoAlias;
1646 }
1647
1648 // If the size of one access is larger than the entire object on the other
1649 // side, then we know such behavior is undefined and can assume no alias.
1650 if ((V1Size != MemoryLocation::UnknownSize &&
1651 isObjectSmallerThan(O2, V1Size, DL, TLI)) ||
1652 (V2Size != MemoryLocation::UnknownSize &&
1653 isObjectSmallerThan(O1, V2Size, DL, TLI)))
1654 return NoAlias;
1655
1656 // Check the cache before climbing up use-def chains. This also terminates
1657 // otherwise infinitely recursive queries.
1658 LocPair Locs(MemoryLocation(V1, V1Size, V1AAInfo),
1659 MemoryLocation(V2, V2Size, V2AAInfo));
1660 if (V1 > V2)
1661 std::swap(Locs.first, Locs.second);
1662 std::pair<AliasCacheTy::iterator, bool> Pair =
1663 AliasCache.insert(std::make_pair(Locs, MayAlias));
1664 if (!Pair.second)
1665 return Pair.first->second;
1666
1667 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1668 // GEP can't simplify, we don't even look at the PHI cases.
1669 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
1670 std::swap(V1, V2);
1671 std::swap(V1Size, V2Size);
1672 std::swap(O1, O2);
1673 std::swap(V1AAInfo, V2AAInfo);
1674 }
1675 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1676 AliasResult Result =
1677 aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2);
1678 if (Result != MayAlias)
1679 return AliasCache[Locs] = Result;
1680 }
1681
1682 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1683 std::swap(V1, V2);
1684 std::swap(O1, O2);
1685 std::swap(V1Size, V2Size);
1686 std::swap(V1AAInfo, V2AAInfo);
1687 }
1688 if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1689 AliasResult Result = aliasPHI(PN, V1Size, V1AAInfo,
1690 V2, V2Size, V2AAInfo, O2);
1691 if (Result != MayAlias)
1692 return AliasCache[Locs] = Result;
1693 }
1694
1695 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1696 std::swap(V1, V2);
1697 std::swap(O1, O2);
1698 std::swap(V1Size, V2Size);
1699 std::swap(V1AAInfo, V2AAInfo);
1700 }
1701 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1702 AliasResult Result =
1703 aliasSelect(S1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O2);
1704 if (Result != MayAlias)
1705 return AliasCache[Locs] = Result;
1706 }
1707
1708 // If both pointers are pointing into the same object and one of them
1709 // accesses the entire object, then the accesses must overlap in some way.
1710 if (O1 == O2)
1711 if (V1Size != MemoryLocation::UnknownSize &&
1712 V2Size != MemoryLocation::UnknownSize &&
1713 (isObjectSize(O1, V1Size, DL, TLI) ||
1714 isObjectSize(O2, V2Size, DL, TLI)))
1715 return AliasCache[Locs] = PartialAlias;
1716
1717 // Recurse back into the best AA results we have, potentially with refined
1718 // memory locations. We have already ensured that BasicAA has a MayAlias
1719 // cache result for these, so any recursion back into BasicAA won't loop.
1720 AliasResult Result = getBestAAResults().alias(Locs.first, Locs.second);
1721 return AliasCache[Locs] = Result;
1722}
1723
1724/// Check whether two Values can be considered equivalent.
1725///
1726/// In addition to pointer equivalence of \p V1 and \p V2 this checks whether
1727/// they can not be part of a cycle in the value graph by looking at all
1728/// visited phi nodes an making sure that the phis cannot reach the value. We
1729/// have to do this because we are looking through phi nodes (That is we say
1730/// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
1731bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V,
1732 const Value *V2) {
1733 if (V != V2)
1734 return false;
1735
1736 const Instruction *Inst = dyn_cast<Instruction>(V);
1737 if (!Inst)
1738 return true;
1739
1740 if (VisitedPhiBBs.empty())
1741 return true;
1742
1743 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1744 return false;
1745
1746 // Make sure that the visited phis cannot reach the Value. This ensures that
1747 // the Values cannot come from different iterations of a potential cycle the
1748 // phi nodes could be involved in.
1749 for (auto *P : VisitedPhiBBs)
1750 if (isPotentiallyReachable(&P->front(), Inst, DT, LI))
1751 return false;
1752
1753 return true;
1754}
1755
1756/// Computes the symbolic difference between two de-composed GEPs.
1757///
1758/// Dest and Src are the variable indices from two decomposed GetElementPtr
1759/// instructions GEP1 and GEP2 which have common base pointers.
1760void BasicAAResult::GetIndexDifference(
1761 SmallVectorImpl<VariableGEPIndex> &Dest,
1762 const SmallVectorImpl<VariableGEPIndex> &Src) {
1763 if (Src.empty())
1764 return;
1765
1766 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
1767 const Value *V = Src[i].V;
1768 unsigned ZExtBits = Src[i].ZExtBits, SExtBits = Src[i].SExtBits;
1769 int64_t Scale = Src[i].Scale;
1770
1771 // Find V in Dest. This is N^2, but pointer indices almost never have more
1772 // than a few variable indexes.
1773 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
1774 if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
1775 Dest[j].ZExtBits != ZExtBits || Dest[j].SExtBits != SExtBits)
1776 continue;
1777
1778 // If we found it, subtract off Scale V's from the entry in Dest. If it
1779 // goes to zero, remove the entry.
1780 if (Dest[j].Scale != Scale)
1781 Dest[j].Scale -= Scale;
1782 else
1783 Dest.erase(Dest.begin() + j);
1784 Scale = 0;
1785 break;
1786 }
1787
1788 // If we didn't consume this entry, add it to the end of the Dest list.
1789 if (Scale) {
1790 VariableGEPIndex Entry = {V, ZExtBits, SExtBits, -Scale};
1791 Dest.push_back(Entry);
1792 }
1793 }
1794}
1795
1796bool BasicAAResult::constantOffsetHeuristic(
1797 const SmallVectorImpl<VariableGEPIndex> &VarIndices, uint64_t V1Size,
1798 uint64_t V2Size, int64_t BaseOffset, AssumptionCache *AC,
1799 DominatorTree *DT) {
1800 if (VarIndices.size() != 2 || V1Size == MemoryLocation::UnknownSize ||
1
Assuming the condition is false
2
Assuming 'V1Size' is not equal to UnknownSize
4
Taking false branch
1801 V2Size == MemoryLocation::UnknownSize)
3
Assuming 'V2Size' is not equal to UnknownSize
1802 return false;
1803
1804 const VariableGEPIndex &Var0 = VarIndices[0], &Var1 = VarIndices[1];
1805
1806 if (Var0.ZExtBits != Var1.ZExtBits || Var0.SExtBits != Var1.SExtBits ||
5
Taking false branch
1807 Var0.Scale != -Var1.Scale)
1808 return false;
1809
1810 unsigned Width = Var1.V->getType()->getIntegerBitWidth();
1811
1812 // We'll strip off the Extensions of Var0 and Var1 and do another round
1813 // of GetLinearExpression decomposition. In the example above, if Var0
1814 // is zext(%x + 1) we should get V1 == %x and V1Offset == 1.
1815
1816 APInt V0Scale(Width, 0), V0Offset(Width, 0), V1Scale(Width, 0),
1817 V1Offset(Width, 0);
1818 bool NSW = true, NUW = true;
1819 unsigned V0ZExtBits = 0, V0SExtBits = 0, V1ZExtBits = 0, V1SExtBits = 0;
1820 const Value *V0 = GetLinearExpression(Var0.V, V0Scale, V0Offset, V0ZExtBits,
6
Calling 'BasicAAResult::GetLinearExpression'
1821 V0SExtBits, DL, 0, AC, DT, NSW, NUW);
1822 NSW = true;
1823 NUW = true;
1824 const Value *V1 = GetLinearExpression(Var1.V, V1Scale, V1Offset, V1ZExtBits,
1825 V1SExtBits, DL, 0, AC, DT, NSW, NUW);
1826
1827 if (V0Scale != V1Scale || V0ZExtBits != V1ZExtBits ||
1828 V0SExtBits != V1SExtBits || !isValueEqualInPotentialCycles(V0, V1))
1829 return false;
1830
1831 // We have a hit - Var0 and Var1 only differ by a constant offset!
1832
1833 // If we've been sext'ed then zext'd the maximum difference between Var0 and
1834 // Var1 is possible to calculate, but we're just interested in the absolute
1835 // minimum difference between the two. The minimum distance may occur due to
1836 // wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so
1837 // the minimum distance between %i and %i + 5 is 3.
1838 APInt MinDiff = V0Offset - V1Offset, Wrapped = -MinDiff;
1839 MinDiff = APIntOps::umin(MinDiff, Wrapped);
1840 uint64_t MinDiffBytes = MinDiff.getZExtValue() * std::abs(Var0.Scale);
1841
1842 // We can't definitely say whether GEP1 is before or after V2 due to wrapping
1843 // arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other
1844 // values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and
1845 // V2Size can fit in the MinDiffBytes gap.
1846 return V1Size + std::abs(BaseOffset) <= MinDiffBytes &&
1847 V2Size + std::abs(BaseOffset) <= MinDiffBytes;
1848}
1849
1850//===----------------------------------------------------------------------===//
1851// BasicAliasAnalysis Pass
1852//===----------------------------------------------------------------------===//
1853
1854AnalysisKey BasicAA::Key;
1855
1856BasicAAResult BasicAA::run(Function &F, FunctionAnalysisManager &AM) {
1857 return BasicAAResult(F.getParent()->getDataLayout(),
1858 AM.getResult<TargetLibraryAnalysis>(F),
1859 AM.getResult<AssumptionAnalysis>(F),
1860 &AM.getResult<DominatorTreeAnalysis>(F),
1861 AM.getCachedResult<LoopAnalysis>(F));
1862}
1863
1864BasicAAWrapperPass::BasicAAWrapperPass() : FunctionPass(ID) {
1865 initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
1866}
1867
1868char BasicAAWrapperPass::ID = 0;
1869
1870void BasicAAWrapperPass::anchor() {}
1871
1872INITIALIZE_PASS_BEGIN(BasicAAWrapperPass, "basicaa",static void *initializeBasicAAWrapperPassPassOnce(PassRegistry
&Registry) {
1873 "Basic Alias Analysis (stateless AA impl)", true, true)static void *initializeBasicAAWrapperPassPassOnce(PassRegistry
&Registry) {
1874INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry);
1875INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)initializeDominatorTreeWrapperPassPass(Registry);
1876INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
1877INITIALIZE_PASS_END(BasicAAWrapperPass, "basicaa",PassInfo *PI = new PassInfo( "Basic Alias Analysis (stateless AA impl)"
, "basicaa", &BasicAAWrapperPass::ID, PassInfo::NormalCtor_t
(callDefaultCtor<BasicAAWrapperPass>), true, true); Registry
.registerPass(*PI, true); return PI; } static llvm::once_flag
InitializeBasicAAWrapperPassPassFlag; void llvm::initializeBasicAAWrapperPassPass
(PassRegistry &Registry) { llvm::call_once(InitializeBasicAAWrapperPassPassFlag
, initializeBasicAAWrapperPassPassOnce, std::ref(Registry)); }
1878 "Basic Alias Analysis (stateless AA impl)", true, true)PassInfo *PI = new PassInfo( "Basic Alias Analysis (stateless AA impl)"
, "basicaa", &BasicAAWrapperPass::ID, PassInfo::NormalCtor_t
(callDefaultCtor<BasicAAWrapperPass>), true, true); Registry
.registerPass(*PI, true); return PI; } static llvm::once_flag
InitializeBasicAAWrapperPassPassFlag; void llvm::initializeBasicAAWrapperPassPass
(PassRegistry &Registry) { llvm::call_once(InitializeBasicAAWrapperPassPassFlag
, initializeBasicAAWrapperPassPassOnce, std::ref(Registry)); }
1879
1880FunctionPass *llvm::createBasicAAWrapperPass() {
1881 return new BasicAAWrapperPass();
1882}
1883
1884bool BasicAAWrapperPass::runOnFunction(Function &F) {
1885 auto &ACT = getAnalysis<AssumptionCacheTracker>();
1886 auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>();
1887 auto &DTWP = getAnalysis<DominatorTreeWrapperPass>();
1888 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
1889
1890 Result.reset(new BasicAAResult(F.getParent()->getDataLayout(), TLIWP.getTLI(),
1891 ACT.getAssumptionCache(F), &DTWP.getDomTree(),
1892 LIWP ? &LIWP->getLoopInfo() : nullptr));
1893
1894 return false;
1895}
1896
1897void BasicAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1898 AU.setPreservesAll();
1899 AU.addRequired<AssumptionCacheTracker>();
1900 AU.addRequired<DominatorTreeWrapperPass>();
1901 AU.addRequired<TargetLibraryInfoWrapperPass>();
1902}
1903
1904BasicAAResult llvm::createLegacyPMBasicAAResult(Pass &P, Function &F) {
1905 return BasicAAResult(
1906 F.getParent()->getDataLayout(),
1907 P.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
1908 P.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
1909}

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

1//===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements a class to represent arbitrary precision
12/// integral constant values and operations on them.
13///
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_ADT_APINT_H
17#define LLVM_ADT_APINT_H
18
19#include "llvm/Support/Compiler.h"
20#include "llvm/Support/MathExtras.h"
21#include <cassert>
22#include <climits>
23#include <cstring>
24#include <string>
25
26namespace llvm {
27class FoldingSetNodeID;
28class StringRef;
29class hash_code;
30class raw_ostream;
31
32template <typename T> class SmallVectorImpl;
33template <typename T> class ArrayRef;
34
35class APInt;
36
37inline APInt operator-(APInt);
38
39//===----------------------------------------------------------------------===//
40// APInt Class
41//===----------------------------------------------------------------------===//
42
43/// \brief Class for arbitrary precision integers.
44///
45/// APInt is a functional replacement for common case unsigned integer type like
46/// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
47/// integer sizes and large integer value types such as 3-bits, 15-bits, or more
48/// than 64-bits of precision. APInt provides a variety of arithmetic operators
49/// and methods to manipulate integer values of any bit-width. It supports both
50/// the typical integer arithmetic and comparison operations as well as bitwise
51/// manipulation.
52///
53/// The class has several invariants worth noting:
54/// * All bit, byte, and word positions are zero-based.
55/// * Once the bit width is set, it doesn't change except by the Truncate,
56/// SignExtend, or ZeroExtend operations.
57/// * All binary operators must be on APInt instances of the same bit width.
58/// Attempting to use these operators on instances with different bit
59/// widths will yield an assertion.
60/// * The value is stored canonically as an unsigned value. For operations
61/// where it makes a difference, there are both signed and unsigned variants
62/// of the operation. For example, sdiv and udiv. However, because the bit
63/// widths must be the same, operations such as Mul and Add produce the same
64/// results regardless of whether the values are interpreted as signed or
65/// not.
66/// * In general, the class tries to follow the style of computation that LLVM
67/// uses in its IR. This simplifies its use for LLVM.
68///
69class LLVM_NODISCARD[[clang::warn_unused_result]] APInt {
70public:
71 typedef uint64_t WordType;
72
73 /// This enum is used to hold the constants we needed for APInt.
74 enum : unsigned {
75 /// Byte size of a word.
76 APINT_WORD_SIZE = sizeof(WordType),
77 /// Bits in a word.
78 APINT_BITS_PER_WORD = APINT_WORD_SIZE * CHAR_BIT8
79 };
80
81 static const WordType WORD_MAX = ~WordType(0);
82
83private:
84 /// This union is used to store the integer value. When the
85 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
86 union {
87 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
88 uint64_t *pVal; ///< Used to store the >64 bits integer value.
89 } U;
90
91 unsigned BitWidth; ///< The number of bits in this APInt.
92
93 friend struct DenseMapAPIntKeyInfo;
94
95 friend class APSInt;
96
97 /// \brief Fast internal constructor
98 ///
99 /// This constructor is used only internally for speed of construction of
100 /// temporaries. It is unsafe for general use so it is not public.
101 APInt(uint64_t *val, unsigned bits) : BitWidth(bits) {
102 U.pVal = val;
103 }
104
105 /// \brief Determine if this APInt just has one word to store value.
106 ///
107 /// \returns true if the number of bits <= 64, false otherwise.
108 bool isSingleWord() const { return BitWidth <= APINT_BITS_PER_WORD; }
109
110 /// \brief Determine which word a bit is in.
111 ///
112 /// \returns the word position for the specified bit position.
113 static unsigned whichWord(unsigned bitPosition) {
114 return bitPosition / APINT_BITS_PER_WORD;
115 }
116
117 /// \brief Determine which bit in a word a bit is in.
118 ///
119 /// \returns the bit position in a word for the specified bit position
120 /// in the APInt.
121 static unsigned whichBit(unsigned bitPosition) {
122 return bitPosition % APINT_BITS_PER_WORD;
123 }
124
125 /// \brief Get a single bit mask.
126 ///
127 /// \returns a uint64_t with only bit at "whichBit(bitPosition)" set
128 /// This method generates and returns a uint64_t (word) mask for a single
129 /// bit at a specific bit position. This is used to mask the bit in the
130 /// corresponding word.
131 static uint64_t maskBit(unsigned bitPosition) {
132 return 1ULL << whichBit(bitPosition);
133 }
134
135 /// \brief Clear unused high order bits
136 ///
137 /// This method is used internally to clear the top "N" bits in the high order
138 /// word that are not used by the APInt. This is needed after the most
139 /// significant word is assigned a value to ensure that those bits are
140 /// zero'd out.
141 APInt &clearUnusedBits() {
142 // Compute how many bits are used in the final word
143 unsigned WordBits = ((BitWidth-1) % APINT_BITS_PER_WORD) + 1;
144
145 // Mask out the high bits.
146 uint64_t mask = WORD_MAX >> (APINT_BITS_PER_WORD - WordBits);
147 if (isSingleWord())
148 U.VAL &= mask;
149 else
150 U.pVal[getNumWords() - 1] &= mask;
151 return *this;
152 }
153
154 /// \brief Get the word corresponding to a bit position
155 /// \returns the corresponding word for the specified bit position.
156 uint64_t getWord(unsigned bitPosition) const {
157 return isSingleWord() ? U.VAL : U.pVal[whichWord(bitPosition)];
158 }
159
160 /// Utility method to change the bit width of this APInt to new bit width,
161 /// allocating and/or deallocating as necessary. There is no guarantee on the
162 /// value of any bits upon return. Caller should populate the bits after.
163 void reallocate(unsigned NewBitWidth);
164
165 /// \brief Convert a char array into an APInt
166 ///
167 /// \param radix 2, 8, 10, 16, or 36
168 /// Converts a string into a number. The string must be non-empty
169 /// and well-formed as a number of the given base. The bit-width
170 /// must be sufficient to hold the result.
171 ///
172 /// This is used by the constructors that take string arguments.
173 ///
174 /// StringRef::getAsInteger is superficially similar but (1) does
175 /// not assume that the string is well-formed and (2) grows the
176 /// result to hold the input.
177 void fromString(unsigned numBits, StringRef str, uint8_t radix);
178
179 /// \brief An internal division function for dividing APInts.
180 ///
181 /// This is used by the toString method to divide by the radix. It simply
182 /// provides a more convenient form of divide for internal use since KnuthDiv
183 /// has specific constraints on its inputs. If those constraints are not met
184 /// then it provides a simpler form of divide.
185 static void divide(const WordType *LHS, unsigned lhsWords,
186 const WordType *RHS, unsigned rhsWords, WordType *Quotient,
187 WordType *Remainder);
188
189 /// out-of-line slow case for inline constructor
190 void initSlowCase(uint64_t val, bool isSigned);
191
192 /// shared code between two array constructors
193 void initFromArray(ArrayRef<uint64_t> array);
194
195 /// out-of-line slow case for inline copy constructor
196 void initSlowCase(const APInt &that);
197
198 /// out-of-line slow case for shl
199 void shlSlowCase(unsigned ShiftAmt);
200
201 /// out-of-line slow case for lshr.
202 void lshrSlowCase(unsigned ShiftAmt);
203
204 /// out-of-line slow case for ashr.
205 void ashrSlowCase(unsigned ShiftAmt);
206
207 /// out-of-line slow case for operator=
208 void AssignSlowCase(const APInt &RHS);
209
210 /// out-of-line slow case for operator==
211 bool EqualSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
212
213 /// out-of-line slow case for countLeadingZeros
214 unsigned countLeadingZerosSlowCase() const LLVM_READONLY__attribute__((__pure__));
215
216 /// out-of-line slow case for countLeadingOnes.
217 unsigned countLeadingOnesSlowCase() const LLVM_READONLY__attribute__((__pure__));
218
219 /// out-of-line slow case for countTrailingZeros.
220 unsigned countTrailingZerosSlowCase() const LLVM_READONLY__attribute__((__pure__));
221
222 /// out-of-line slow case for countTrailingOnes
223 unsigned countTrailingOnesSlowCase() const LLVM_READONLY__attribute__((__pure__));
224
225 /// out-of-line slow case for countPopulation
226 unsigned countPopulationSlowCase() const LLVM_READONLY__attribute__((__pure__));
227
228 /// out-of-line slow case for intersects.
229 bool intersectsSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
230
231 /// out-of-line slow case for isSubsetOf.
232 bool isSubsetOfSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
233
234 /// out-of-line slow case for setBits.
235 void setBitsSlowCase(unsigned loBit, unsigned hiBit);
236
237 /// out-of-line slow case for flipAllBits.
238 void flipAllBitsSlowCase();
239
240 /// out-of-line slow case for operator&=.
241 void AndAssignSlowCase(const APInt& RHS);
242
243 /// out-of-line slow case for operator|=.
244 void OrAssignSlowCase(const APInt& RHS);
245
246 /// out-of-line slow case for operator^=.
247 void XorAssignSlowCase(const APInt& RHS);
248
249 /// Unsigned comparison. Returns -1, 0, or 1 if this APInt is less than, equal
250 /// to, or greater than RHS.
251 int compare(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
252
253 /// Signed comparison. Returns -1, 0, or 1 if this APInt is less than, equal
254 /// to, or greater than RHS.
255 int compareSigned(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
256
257public:
258 /// \name Constructors
259 /// @{
260
261 /// \brief Create a new APInt of numBits width, initialized as val.
262 ///
263 /// If isSigned is true then val is treated as if it were a signed value
264 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
265 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
266 /// the range of val are zero filled).
267 ///
268 /// \param numBits the bit width of the constructed APInt
269 /// \param val the initial value of the APInt
270 /// \param isSigned how to treat signedness of val
271 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
272 : BitWidth(numBits) {
273 assert(BitWidth && "bitwidth too small")(static_cast <bool> (BitWidth && "bitwidth too small"
) ? void (0) : __assert_fail ("BitWidth && \"bitwidth too small\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/APInt.h"
, 273, __extension__ __PRETTY_FUNCTION__))
;
274 if (isSingleWord()) {
275 U.VAL = val;
276 clearUnusedBits();
277 } else {
278 initSlowCase(val, isSigned);
279 }
280 }
281
282 /// \brief Construct an APInt of numBits width, initialized as bigVal[].
283 ///
284 /// Note that bigVal.size() can be smaller or larger than the corresponding
285 /// bit width but any extraneous bits will be dropped.
286 ///
287 /// \param numBits the bit width of the constructed APInt
288 /// \param bigVal a sequence of words to form the initial value of the APInt
289 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
290
291 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
292 /// deprecated because this constructor is prone to ambiguity with the
293 /// APInt(unsigned, uint64_t, bool) constructor.
294 ///
295 /// If this overload is ever deleted, care should be taken to prevent calls
296 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
297 /// constructor.
298 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
299
300 /// \brief Construct an APInt from a string representation.
301 ///
302 /// This constructor interprets the string \p str in the given radix. The
303 /// interpretation stops when the first character that is not suitable for the
304 /// radix is encountered, or the end of the string. Acceptable radix values
305 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
306 /// string to require more bits than numBits.
307 ///
308 /// \param numBits the bit width of the constructed APInt
309 /// \param str the string to be interpreted
310 /// \param radix the radix to use for the conversion
311 APInt(unsigned numBits, StringRef str, uint8_t radix);
312
313 /// Simply makes *this a copy of that.
314 /// @brief Copy Constructor.
315 APInt(const APInt &that) : BitWidth(that.BitWidth) {
316 if (isSingleWord())
317 U.VAL = that.U.VAL;
318 else
319 initSlowCase(that);
320 }
321
322 /// \brief Move Constructor.
323 APInt(APInt &&that) : BitWidth(that.BitWidth) {
324 memcpy(&U, &that.U, sizeof(U));
325 that.BitWidth = 0;
326 }
327
328 /// \brief Destructor.
329 ~APInt() {
330 if (needsCleanup())
331 delete[] U.pVal;
332 }
333
334 /// \brief Default constructor that creates an uninteresting APInt
335 /// representing a 1-bit zero value.
336 ///
337 /// This is useful for object deserialization (pair this with the static
338 /// method Read).
339 explicit APInt() : BitWidth(1) { U.VAL = 0; }
340
341 /// \brief Returns whether this instance allocated memory.
342 bool needsCleanup() const { return !isSingleWord(); }
343
344 /// Used to insert APInt objects, or objects that contain APInt objects, into
345 /// FoldingSets.
346 void Profile(FoldingSetNodeID &id) const;
347
348 /// @}
349 /// \name Value Tests
350 /// @{
351
352 /// \brief Determine sign of this APInt.
353 ///
354 /// This tests the high bit of this APInt to determine if it is set.
355 ///
356 /// \returns true if this APInt is negative, false otherwise
357 bool isNegative() const { return (*this)[BitWidth - 1]; }
358
359 /// \brief Determine if this APInt Value is non-negative (>= 0)
360 ///
361 /// This tests the high bit of the APInt to determine if it is unset.
362 bool isNonNegative() const { return !isNegative(); }
363
364 /// \brief Determine if sign bit of this APInt is set.
365 ///
366 /// This tests the high bit of this APInt to determine if it is set.
367 ///
368 /// \returns true if this APInt has its sign bit set, false otherwise.
369 bool isSignBitSet() const { return (*this)[BitWidth-1]; }
370
371 /// \brief Determine if sign bit of this APInt is clear.
372 ///
373 /// This tests the high bit of this APInt to determine if it is clear.
374 ///
375 /// \returns true if this APInt has its sign bit clear, false otherwise.
376 bool isSignBitClear() const { return !isSignBitSet(); }
377
378 /// \brief Determine if this APInt Value is positive.
379 ///
380 /// This tests if the value of this APInt is positive (> 0). Note
381 /// that 0 is not a positive value.
382 ///
383 /// \returns true if this APInt is positive.
384 bool isStrictlyPositive() const { return isNonNegative() && !isNullValue(); }
385
386 /// \brief Determine if all bits are set
387 ///
388 /// This checks to see if the value has all bits of the APInt are set or not.
389 bool isAllOnesValue() const {
390 if (isSingleWord())
391 return U.VAL == WORD_MAX >> (APINT_BITS_PER_WORD - BitWidth);
392 return countTrailingOnesSlowCase() == BitWidth;
393 }
394
395 /// \brief Determine if all bits are clear
396 ///
397 /// This checks to see if the value has all bits of the APInt are clear or
398 /// not.
399 bool isNullValue() const { return !*this; }
400
401 /// \brief Determine if this is a value of 1.
402 ///
403 /// This checks to see if the value of this APInt is one.
404 bool isOneValue() const {
405 if (isSingleWord())
406 return U.VAL == 1;
407 return countLeadingZerosSlowCase() == BitWidth - 1;
408 }
409
410 /// \brief Determine if this is the largest unsigned value.
411 ///
412 /// This checks to see if the value of this APInt is the maximum unsigned
413 /// value for the APInt's bit width.
414 bool isMaxValue() const { return isAllOnesValue(); }
415
416 /// \brief Determine if this is the largest signed value.
417 ///
418 /// This checks to see if the value of this APInt is the maximum signed
419 /// value for the APInt's bit width.
420 bool isMaxSignedValue() const {
421 if (isSingleWord())
422 return U.VAL == ((WordType(1) << (BitWidth - 1)) - 1);
423 return !isNegative() && countTrailingOnesSlowCase() == BitWidth - 1;
424 }
425
426 /// \brief Determine if this is the smallest unsigned value.
427 ///
428 /// This checks to see if the value of this APInt is the minimum unsigned
429 /// value for the APInt's bit width.
430 bool isMinValue() const { return isNullValue(); }
431
432 /// \brief Determine if this is the smallest signed value.
433 ///
434 /// This checks to see if the value of this APInt is the minimum signed
435 /// value for the APInt's bit width.
436 bool isMinSignedValue() const {
437 if (isSingleWord())
438 return U.VAL == (WordType(1) << (BitWidth - 1));
439 return isNegative() && countTrailingZerosSlowCase() == BitWidth - 1;
440 }
441
442 /// \brief Check if this APInt has an N-bits unsigned integer value.
443 bool isIntN(unsigned N) const {
444 assert(N && "N == 0 ???")(static_cast <bool> (N && "N == 0 ???") ? void (
0) : __assert_fail ("N && \"N == 0 ???\"", "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/APInt.h"
, 444, __extension__ __PRETTY_FUNCTION__))
;
445 return getActiveBits() <= N;
446 }
447
448 /// \brief Check if this APInt has an N-bits signed integer value.
449 bool isSignedIntN(unsigned N) const {
450 assert(N && "N == 0 ???")(static_cast <bool> (N && "N == 0 ???") ? void (
0) : __assert_fail ("N && \"N == 0 ???\"", "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/APInt.h"
, 450, __extension__ __PRETTY_FUNCTION__))
;
451 return getMinSignedBits() <= N;
452 }
453
454 /// \brief Check if this APInt's value is a power of two greater than zero.
455 ///
456 /// \returns true if the argument APInt value is a power of two > 0.
457 bool isPowerOf2() const {
458 if (isSingleWord())
459 return isPowerOf2_64(U.VAL);
460 return countPopulationSlowCase() == 1;
461 }
462
463 /// \brief Check if the APInt's value is returned by getSignMask.
464 ///
465 /// \returns true if this is the value returned by getSignMask.
466 bool isSignMask() const { return isMinSignedValue(); }
467
468 /// \brief Convert APInt to a boolean value.
469 ///
470 /// This converts the APInt to a boolean value as a test against zero.
471 bool getBoolValue() const { return !!*this; }
472
473 /// If this value is smaller than the specified limit, return it, otherwise
474 /// return the limit value. This causes the value to saturate to the limit.
475 uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX(18446744073709551615UL)) const {
476 return ugt(Limit) ? Limit : getZExtValue();
16
'?' condition is true
477 }
478
479 /// \brief Check if the APInt consists of a repeated bit pattern.
480 ///
481 /// e.g. 0x01010101 satisfies isSplat(8).
482 /// \param SplatSizeInBits The size of the pattern in bits. Must divide bit
483 /// width without remainder.
484 bool isSplat(unsigned SplatSizeInBits) const;
485
486 /// \returns true if this APInt value is a sequence of \param numBits ones
487 /// starting at the least significant bit with the remainder zero.
488 bool isMask(unsigned numBits) const {
489 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-7~svn329677/include/llvm/ADT/APInt.h"
, 489, __extension__ __PRETTY_FUNCTION__))
;
490 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-7~svn329677/include/llvm/ADT/APInt.h"
, 490, __extension__ __PRETTY_FUNCTION__))
;
491 if (isSingleWord())
492 return U.VAL == (WORD_MAX >> (APINT_BITS_PER_WORD - numBits));
493 unsigned Ones = countTrailingOnesSlowCase();
494 return (numBits == Ones) &&
495 ((Ones + countLeadingZerosSlowCase()) == BitWidth);
496 }
497
498 /// \returns true if this APInt is a non-empty sequence of ones starting at
499 /// the least significant bit with the remainder zero.
500 /// Ex. isMask(0x0000FFFFU) == true.
501 bool isMask() const {
502 if (isSingleWord())
503 return isMask_64(U.VAL);
504 unsigned Ones = countTrailingOnesSlowCase();
505 return (Ones > 0) && ((Ones + countLeadingZerosSlowCase()) == BitWidth);
506 }
507
508 /// \brief Return true if this APInt value contains a sequence of ones with
509 /// the remainder zero.
510 bool isShiftedMask() const {
511 if (isSingleWord())
512 return isShiftedMask_64(U.VAL);
513 unsigned Ones = countPopulationSlowCase();
514 unsigned LeadZ = countLeadingZerosSlowCase();
515 return (Ones + LeadZ + countTrailingZeros()) == BitWidth;
516 }
517
518 /// @}
519 /// \name Value Generators
520 /// @{
521
522 /// \brief Gets maximum unsigned value of APInt for specific bit width.
523 static APInt getMaxValue(unsigned numBits) {
524 return getAllOnesValue(numBits);
525 }
526
527 /// \brief Gets maximum signed value of APInt for a specific bit width.
528 static APInt getSignedMaxValue(unsigned numBits) {
529 APInt API = getAllOnesValue(numBits);
530 API.clearBit(numBits - 1);
531 return API;
532 }
533
534 /// \brief Gets minimum unsigned value of APInt for a specific bit width.
535 static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); }
536
537 /// \brief Gets minimum signed value of APInt for a specific bit width.
538 static APInt getSignedMinValue(unsigned numBits) {
539 APInt API(numBits, 0);
540 API.setBit(numBits - 1);
541 return API;
542 }
543
544 /// \brief Get the SignMask for a specific bit width.
545 ///
546 /// This is just a wrapper function of getSignedMinValue(), and it helps code
547 /// readability when we want to get a SignMask.
548 static APInt getSignMask(unsigned BitWidth) {
549 return getSignedMinValue(BitWidth);
550 }
551
552 /// \brief Get the all-ones value.
553 ///
554 /// \returns the all-ones value for an APInt of the specified bit-width.
555 static APInt getAllOnesValue(unsigned numBits) {
556 return APInt(numBits, WORD_MAX, true);
557 }
558
559 /// \brief Get the '0' value.
560 ///
561 /// \returns the '0' value for an APInt of the specified bit-width.
562 static APInt getNullValue(unsigned numBits) { return APInt(numBits, 0); }
563
564 /// \brief Compute an APInt containing numBits highbits from this APInt.
565 ///
566 /// Get an APInt with the same BitWidth as this APInt, just zero mask
567 /// the low bits and right shift to the least significant bit.
568 ///
569 /// \returns the high "numBits" bits of this APInt.
570 APInt getHiBits(unsigned numBits) const;
571
572 /// \brief Compute an APInt containing numBits lowbits from this APInt.
573 ///
574 /// Get an APInt with the same BitWidth as this APInt, just zero mask
575 /// the high bits.
576 ///
577 /// \returns the low "numBits" bits of this APInt.
578 APInt getLoBits(unsigned numBits) const;
579
580 /// \brief Return an APInt with exactly one bit set in the result.
581 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
582 APInt Res(numBits, 0);
583 Res.setBit(BitNo);
584 return Res;
585 }
586
587 /// \brief Get a value with a block of bits set.
588 ///
589 /// Constructs an APInt value that has a contiguous range of bits set. The
590 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
591 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
592 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
593 /// example, with parameters (32, 28, 4), you would get 0xF000000F.
594 ///
595 /// \param numBits the intended bit width of the result
596 /// \param loBit the index of the lowest bit set.
597 /// \param hiBit the index of the highest bit set.
598 ///
599 /// \returns An APInt value with the requested bits set.
600 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
601 APInt Res(numBits, 0);
602 Res.setBits(loBit, hiBit);
603 return Res;
604 }
605
606 /// \brief Get a value with upper bits starting at loBit set.
607 ///
608 /// Constructs an APInt value that has a contiguous range of bits set. The
609 /// bits from loBit (inclusive) to numBits (exclusive) will be set. All other
610 /// bits will be zero. For example, with parameters(32, 12) you would get
611 /// 0xFFFFF000.
612 ///
613 /// \param numBits the intended bit width of the result
614 /// \param loBit the index of the lowest bit to set.
615 ///
616 /// \returns An APInt value with the requested bits set.
617 static APInt getBitsSetFrom(unsigned numBits, unsigned loBit) {
618 APInt Res(numBits, 0);
619 Res.setBitsFrom(loBit);
620 return Res;
621 }
622
623 /// \brief Get a value with high bits set
624 ///
625 /// Constructs an APInt value that has the top hiBitsSet bits set.
626 ///
627 /// \param numBits the bitwidth of the result
628 /// \param hiBitsSet the number of high-order bits set in the result.
629 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
630 APInt Res(numBits, 0);
631 Res.setHighBits(hiBitsSet);
632 return Res;
633 }
634
635 /// \brief Get a value with low bits set
636 ///
637 /// Constructs an APInt value that has the bottom loBitsSet bits set.
638 ///
639 /// \param numBits the bitwidth of the result
640 /// \param loBitsSet the number of low-order bits set in the result.
641 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
642 APInt Res(numBits, 0);
643 Res.setLowBits(loBitsSet);
644 return Res;
645 }
646
647 /// \brief Return a value containing V broadcasted over NewLen bits.
648 static APInt getSplat(unsigned NewLen, const APInt &V);
649
650 /// \brief Determine if two APInts have the same value, after zero-extending
651 /// one of them (if needed!) to ensure that the bit-widths match.
652 static bool isSameValue(const APInt &I1, const APInt &I2) {
653 if (I1.getBitWidth() == I2.getBitWidth())
654 return I1 == I2;
655
656 if (I1.getBitWidth() > I2.getBitWidth())
657 return I1 == I2.zext(I1.getBitWidth());
658
659 return I1.zext(I2.getBitWidth()) == I2;
660 }
661
662 /// \brief Overload to compute a hash_code for an APInt value.
663 friend hash_code hash_value(const APInt &Arg);
664
665 /// This function returns a pointer to the internal storage of the APInt.
666 /// This is useful for writing out the APInt in binary form without any
667 /// conversions.
668 const uint64_t *getRawData() const {
669 if (isSingleWord())
670 return &U.VAL;
671 return &U.pVal[0];
672 }
673
674 /// @}
675 /// \name Unary Operators
676 /// @{
677
678 /// \brief Postfix increment operator.
679 ///
680 /// Increments *this by 1.
681 ///
682 /// \returns a new APInt value representing the original value of *this.
683 const APInt operator++(int) {
684 APInt API(*this);
685 ++(*this);
686 return API;
687 }
688
689 /// \brief Prefix increment operator.
690 ///
691 /// \returns *this incremented by one
692 APInt &operator++();
693
694 /// \brief Postfix decrement operator.
695 ///
696 /// Decrements *this by 1.
697 ///
698 /// \returns a new APInt value representing the original value of *this.
699 const APInt operator--(int) {
700 APInt API(*this);
701 --(*this);
702 return API;
703 }
704
705 /// \brief Prefix decrement operator.
706 ///
707 /// \returns *this decremented by one.
708 APInt &operator--();
709
710 /// \brief Logical negation operator.
711 ///
712 /// Performs logical negation operation on this APInt.
713 ///
714 /// \returns true if *this is zero, false otherwise.
715 bool operator!() const {
716 if (isSingleWord())
717 return U.VAL == 0;
718 return countLeadingZerosSlowCase() == BitWidth;
719 }
720
721 /// @}
722 /// \name Assignment Operators
723 /// @{
724
725 /// \brief Copy assignment operator.
726 ///
727 /// \returns *this after assignment of RHS.
728 APInt &operator=(const APInt &RHS) {
729 // If the bitwidths are the same, we can avoid mucking with memory
730 if (isSingleWord() && RHS.isSingleWord()) {
731 U.VAL = RHS.U.VAL;
732 BitWidth = RHS.BitWidth;
733 return clearUnusedBits();
734 }
735
736 AssignSlowCase(RHS);
737 return *this;
738 }
739
740 /// @brief Move assignment operator.
741 APInt &operator=(APInt &&that) {
742 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-7~svn329677/include/llvm/ADT/APInt.h"
, 742, __extension__ __PRETTY_FUNCTION__))
;
743 if (!isSingleWord())
744 delete[] U.pVal;
745
746 // Use memcpy so that type based alias analysis sees both VAL and pVal
747 // as modified.
748 memcpy(&U, &that.U, sizeof(U));
749
750 BitWidth = that.BitWidth;
751 that.BitWidth = 0;
752
753 return *this;
754 }
755
756 /// \brief Assignment operator.
757 ///
758 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
759 /// the bit width, the excess bits are truncated. If the bit width is larger
760 /// than 64, the value is zero filled in the unspecified high order bits.
761 ///
762 /// \returns *this after assignment of RHS value.
763 APInt &operator=(uint64_t RHS) {
764 if (isSingleWord()) {
765 U.VAL = RHS;
766 clearUnusedBits();
767 } else {
768 U.pVal[0] = RHS;
769 memset(U.pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
770 }
771 return *this;
772 }
773
774 /// \brief Bitwise AND assignment operator.
775 ///
776 /// Performs a bitwise AND operation on this APInt and RHS. The result is
777 /// assigned to *this.
778 ///
779 /// \returns *this after ANDing with RHS.
780 APInt &operator&=(const APInt &RHS) {
781 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-7~svn329677/include/llvm/ADT/APInt.h"
, 781, __extension__ __PRETTY_FUNCTION__))
;
782 if (isSingleWord())
783 U.VAL &= RHS.U.VAL;
784 else
785 AndAssignSlowCase(RHS);
786 return *this;
787 }
788
789 /// \brief Bitwise AND assignment operator.
790 ///
791 /// Performs a bitwise AND operation on this APInt and RHS. RHS is
792 /// logically zero-extended or truncated to match the bit-width of
793 /// the LHS.
794 APInt &operator&=(uint64_t RHS) {
795 if (isSingleWord()) {
796 U.VAL &= RHS;
797 return *this;
798 }
799 U.pVal[0] &= RHS;
800 memset(U.pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
801 return *this;
802 }
803
804 /// \brief Bitwise OR assignment operator.
805 ///
806 /// Performs a bitwise OR operation on this APInt and RHS. The result is
807 /// assigned *this;
808 ///
809 /// \returns *this after ORing 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-7~svn329677/include/llvm/ADT/APInt.h"
, 811, __extension__ __PRETTY_FUNCTION__))
;
812 if (isSingleWord())
813 U.VAL |= RHS.U.VAL;
814 else
815 OrAssignSlowCase(RHS);
816 return *this;
817 }
818
819 /// \brief Bitwise OR assignment operator.
820 ///
821 /// Performs a bitwise OR 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 clearUnusedBits();
828 } else {
829 U.pVal[0] |= RHS;
830 }
831 return *this;
832 }
833
834 /// \brief Bitwise XOR assignment operator.
835 ///
836 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
837 /// assigned to *this.
838 ///
839 /// \returns *this after XORing 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-7~svn329677/include/llvm/ADT/APInt.h"
, 841, __extension__ __PRETTY_FUNCTION__))
;
842 if (isSingleWord())
843 U.VAL ^= RHS.U.VAL;
844 else
845 XorAssignSlowCase(RHS);
846 return *this;
847 }
848
849 /// \brief Bitwise XOR assignment operator.
850 ///
851 /// Performs a bitwise XOR 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 clearUnusedBits();
858 } else {
859 U.pVal[0] ^= RHS;
860 }
861 return *this;
862 }
863
864 /// \brief Multiplication assignment operator.
865 ///
866 /// Multiplies this APInt by RHS and assigns the result to *this.
867 ///
868 /// \returns *this
869 APInt &operator*=(const APInt &RHS);
870 APInt &operator*=(uint64_t RHS);
871
872 /// \brief Addition assignment operator.
873 ///
874 /// Adds RHS to *this and assigns the result to *this.
875 ///
876 /// \returns *this
877 APInt &operator+=(const APInt &RHS);
878 APInt &operator+=(uint64_t RHS);
879
880 /// \brief Subtraction assignment operator.
881 ///
882 /// Subtracts RHS from *this and assigns the result to *this.
883 ///
884 /// \returns *this
885 APInt &operator-=(const APInt &RHS);
886 APInt &operator-=(uint64_t RHS);
887
888 /// \brief Left-shift assignment function.
889 ///
890 /// Shifts *this left by shiftAmt and assigns the result to *this.
891 ///
892 /// \returns *this after shifting left by ShiftAmt
893 APInt &operator<<=(unsigned ShiftAmt) {
894 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-7~svn329677/include/llvm/ADT/APInt.h"
, 894, __extension__ __PRETTY_FUNCTION__))
;
895 if (isSingleWord()) {
20
Taking true branch
896 if (ShiftAmt == BitWidth)
21
Taking false branch
897 U.VAL = 0;
898 else
899 U.VAL <<= ShiftAmt;
22
Assigned value is garbage or undefined
900 return clearUnusedBits();
901 }
902 shlSlowCase(ShiftAmt);
903 return *this;
904 }
905
906 /// \brief Left-shift assignment function.
907 ///
908 /// Shifts *this left by shiftAmt and assigns the result to *this.
909 ///
910 /// \returns *this after shifting left by ShiftAmt
911 APInt &operator<<=(const APInt &ShiftAmt);
912
913 /// @}
914 /// \name Binary Operators
915 /// @{
916
917 /// \brief Multiplication operator.
918 ///
919 /// Multiplies this APInt by RHS and returns the result.
920 APInt operator*(const APInt &RHS) const;
921
922 /// \brief Left logical shift operator.
923 ///
924 /// Shifts this APInt left by \p Bits and returns the result.
925 APInt operator<<(unsigned Bits) const { return shl(Bits); }
926
927 /// \brief Left logical shift operator.
928 ///
929 /// Shifts this APInt left by \p Bits and returns the result.
930 APInt operator<<(const APInt &Bits) const { return shl(Bits); }
931
932 /// \brief Arithmetic right-shift function.
933 ///
934 /// Arithmetic right-shift this APInt by shiftAmt.
935 APInt ashr(unsigned ShiftAmt) const {
936 APInt R(*this);
937 R.ashrInPlace(ShiftAmt);
938 return R;
939 }
940
941 /// Arithmetic right-shift this APInt by ShiftAmt in place.
942 void ashrInPlace(unsigned ShiftAmt) {
943 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-7~svn329677/include/llvm/ADT/APInt.h"
, 943, __extension__ __PRETTY_FUNCTION__))
;
944 if (isSingleWord()) {
945 int64_t SExtVAL = SignExtend64(U.VAL, BitWidth);
946 if (ShiftAmt == BitWidth)
947 U.VAL = SExtVAL >> (APINT_BITS_PER_WORD - 1); // Fill with sign bit.
948 else
949 U.VAL = SExtVAL >> ShiftAmt;
950 clearUnusedBits();
951 return;
952 }
953 ashrSlowCase(ShiftAmt);
954 }
955
956 /// \brief Logical right-shift function.
957 ///
958 /// Logical right-shift this APInt by shiftAmt.
959 APInt lshr(unsigned shiftAmt) const {
960 APInt R(*this);
961 R.lshrInPlace(shiftAmt);
962 return R;
963 }
964
965 /// Logical right-shift this APInt by ShiftAmt in place.
966 void lshrInPlace(unsigned ShiftAmt) {
967 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-7~svn329677/include/llvm/ADT/APInt.h"
, 967, __extension__ __PRETTY_FUNCTION__))
;
968 if (isSingleWord()) {
969 if (ShiftAmt == BitWidth)
970 U.VAL = 0;
971 else
972 U.VAL >>= ShiftAmt;
973 return;
974 }
975 lshrSlowCase(ShiftAmt);
976 }
977
978 /// \brief Left-shift function.
979 ///
980 /// Left-shift this APInt by shiftAmt.
981 APInt shl(unsigned shiftAmt) const {
982 APInt R(*this);
983 R <<= shiftAmt;
984 return R;
985 }
986
987 /// \brief Rotate left by rotateAmt.
988 APInt rotl(unsigned rotateAmt) const;
989
990 /// \brief Rotate right by rotateAmt.
991 APInt rotr(unsigned rotateAmt) const;
992
993 /// \brief Arithmetic right-shift function.
994 ///
995 /// Arithmetic right-shift this APInt by shiftAmt.
996 APInt ashr(const APInt &ShiftAmt) const {
997 APInt R(*this);
998 R.ashrInPlace(ShiftAmt);
999 return R;
1000 }
1001
1002 /// Arithmetic right-shift this APInt by shiftAmt in place.
1003 void ashrInPlace(const APInt &shiftAmt);
1004
1005 /// \brief Logical right-shift function.
1006 ///
1007 /// Logical right-shift this APInt by shiftAmt.
1008 APInt lshr(const APInt &ShiftAmt) const {
1009 APInt R(*this);
1010 R.lshrInPlace(ShiftAmt);
1011 return R;
1012 }
1013
1014 /// Logical right-shift this APInt by ShiftAmt in place.
1015 void lshrInPlace(const APInt &ShiftAmt);
1016
1017 /// \brief Left-shift function.
1018 ///
1019 /// Left-shift this APInt by shiftAmt.
1020 APInt shl(const APInt &ShiftAmt) const {
1021 APInt R(*this);
1022 R <<= ShiftAmt;
1023 return R;
1024 }
1025
1026 /// \brief Rotate left by rotateAmt.
1027 APInt rotl(const APInt &rotateAmt) const;
1028
1029 /// \brief Rotate right by rotateAmt.
1030 APInt rotr(const APInt &rotateAmt) const;
1031
1032 /// \brief Unsigned division operation.
1033 ///
1034 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
1035 /// RHS are treated as unsigned quantities for purposes of this division.
1036 ///
1037 /// \returns a new APInt value containing the division result
1038 APInt udiv(const APInt &RHS) const;
1039 APInt udiv(uint64_t RHS) const;
1040
1041 /// \brief Signed division function for APInt.
1042 ///
1043 /// Signed divide this APInt by APInt RHS.
1044 APInt sdiv(const APInt &RHS) const;
1045 APInt sdiv(int64_t RHS) const;
1046
1047 /// \brief Unsigned remainder operation.
1048 ///
1049 /// Perform an unsigned remainder operation on this APInt with RHS being the
1050 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
1051 /// of this operation. Note that this is a true remainder operation and not a
1052 /// modulo operation because the sign follows the sign of the dividend which
1053 /// is *this.
1054 ///
1055 /// \returns a new APInt value containing the remainder result
1056 APInt urem(const APInt &RHS) const;
1057 uint64_t urem(uint64_t RHS) const;
1058
1059 /// \brief Function for signed remainder operation.
1060 ///
1061 /// Signed remainder operation on APInt.
1062 APInt srem(const APInt &RHS) const;
1063 int64_t srem(int64_t RHS) const;
1064
1065 /// \brief Dual division/remainder interface.
1066 ///
1067 /// Sometimes it is convenient to divide two APInt values and obtain both the
1068 /// quotient and remainder. This function does both operations in the same
1069 /// computation making it a little more efficient. The pair of input arguments
1070 /// may overlap with the pair of output arguments. It is safe to call
1071 /// udivrem(X, Y, X, Y), for example.
1072 static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
1073 APInt &Remainder);
1074 static void udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient,
1075 uint64_t &Remainder);
1076
1077 static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
1078 APInt &Remainder);
1079 static void sdivrem(const APInt &LHS, int64_t RHS, APInt &Quotient,
1080 int64_t &Remainder);
1081
1082 // Operations that return overflow indicators.
1083 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
1084 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
1085 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
1086 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
1087 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
1088 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
1089 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
1090 APInt sshl_ov(const APInt &Amt, bool &Overflow) const;
1091 APInt ushl_ov(const APInt &Amt, bool &Overflow) const;
1092
1093 /// \brief Array-indexing support.
1094 ///
1095 /// \returns the bit value at bitPosition
1096 bool operator[](unsigned bitPosition) const {
1097 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-7~svn329677/include/llvm/ADT/APInt.h"
, 1097, __extension__ __PRETTY_FUNCTION__))
;
1098 return (maskBit(bitPosition) & getWord(bitPosition)) != 0;
1099 }
1100
1101 /// @}
1102 /// \name Comparison Operators
1103 /// @{
1104
1105 /// \brief Equality operator.
1106 ///
1107 /// Compares this APInt with RHS for the validity of the equality
1108 /// relationship.
1109 bool operator==(const APInt &RHS) const {
1110 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-7~svn329677/include/llvm/ADT/APInt.h"
, 1110, __extension__ __PRETTY_FUNCTION__))
;
1111 if (isSingleWord())
1112 return U.VAL == RHS.U.VAL;
1113 return EqualSlowCase(RHS);
1114 }
1115
1116 /// \brief Equality operator.
1117 ///
1118 /// Compares this APInt with a uint64_t for the validity of the equality
1119 /// relationship.
1120 ///
1121 /// \returns true if *this == Val
1122 bool operator==(uint64_t Val) const {
1123 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() == Val;
1124 }
1125
1126 /// \brief Equality comparison.
1127 ///
1128 /// Compares this APInt with RHS for the validity of the equality
1129 /// relationship.
1130 ///
1131 /// \returns true if *this == Val
1132 bool eq(const APInt &RHS) const { return (*this) == RHS; }
1133
1134 /// \brief Inequality operator.
1135 ///
1136 /// Compares this APInt with RHS for the validity of the inequality
1137 /// relationship.
1138 ///
1139 /// \returns true if *this != Val
1140 bool operator!=(const APInt &RHS) const { return !((*this) == RHS); }
1141
1142 /// \brief Inequality operator.
1143 ///
1144 /// Compares this APInt with a uint64_t for the validity of the inequality
1145 /// relationship.
1146 ///
1147 /// \returns true if *this != Val
1148 bool operator!=(uint64_t Val) const { return !((*this) == Val); }
1149
1150 /// \brief Inequality comparison
1151 ///
1152 /// Compares this APInt with RHS for the validity of the inequality
1153 /// relationship.
1154 ///
1155 /// \returns true if *this != Val
1156 bool ne(const APInt &RHS) const { return !((*this) == RHS); }
1157
1158 /// \brief Unsigned less than comparison
1159 ///
1160 /// Regards both *this and RHS as unsigned quantities and compares them for
1161 /// the validity of the less-than relationship.
1162 ///
1163 /// \returns true if *this < RHS when both are considered unsigned.
1164 bool ult(const APInt &RHS) const { return compare(RHS) < 0; }
1165
1166 /// \brief Unsigned less than comparison
1167 ///
1168 /// Regards both *this as an unsigned quantity and compares it with RHS for
1169 /// the validity of the less-than relationship.
1170 ///
1171 /// \returns true if *this < RHS when considered unsigned.
1172 bool ult(uint64_t RHS) const {
1173 // Only need to check active bits if not a single word.
1174 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() < RHS;
1175 }
1176
1177 /// \brief Signed less than comparison
1178 ///
1179 /// Regards both *this and RHS as signed quantities and compares them for
1180 /// validity of the less-than relationship.
1181 ///
1182 /// \returns true if *this < RHS when both are considered signed.
1183 bool slt(const APInt &RHS) const { return compareSigned(RHS) < 0; }
1184
1185 /// \brief Signed less than comparison
1186 ///
1187 /// Regards both *this as a signed quantity and compares it with RHS for
1188 /// the validity of the less-than relationship.
1189 ///
1190 /// \returns true if *this < RHS when considered signed.
1191 bool slt(int64_t RHS) const {
1192 return (!isSingleWord() && getMinSignedBits() > 64) ? isNegative()
1193 : getSExtValue() < RHS;
1194 }
1195
1196 /// \brief Unsigned less or equal comparison
1197 ///
1198 /// Regards both *this and RHS as unsigned quantities and compares them for
1199 /// validity of the less-or-equal relationship.
1200 ///
1201 /// \returns true if *this <= RHS when both are considered unsigned.
1202 bool ule(const APInt &RHS) const { return compare(RHS) <= 0; }
1203
1204 /// \brief Unsigned less or equal comparison
1205 ///
1206 /// Regards both *this as an unsigned quantity and compares it with RHS for
1207 /// the validity of the less-or-equal relationship.
1208 ///
1209 /// \returns true if *this <= RHS when considered unsigned.
1210 bool ule(uint64_t RHS) const { return !ugt(RHS); }
1211
1212 /// \brief Signed less or equal comparison
1213 ///
1214 /// Regards both *this and RHS as signed quantities and compares them for
1215 /// validity of the less-or-equal relationship.
1216 ///
1217 /// \returns true if *this <= RHS when both are considered signed.
1218 bool sle(const APInt &RHS) const { return compareSigned(RHS) <= 0; }
1219
1220 /// \brief Signed less or equal comparison
1221 ///
1222 /// Regards both *this as a signed quantity and compares it with RHS for the
1223 /// validity of the less-or-equal relationship.
1224 ///
1225 /// \returns true if *this <= RHS when considered signed.
1226 bool sle(uint64_t RHS) const { return !sgt(RHS); }
1227
1228 /// \brief Unsigned greather than comparison
1229 ///
1230 /// Regards both *this and RHS as unsigned quantities and compares them for
1231 /// the validity of the greater-than relationship.
1232 ///
1233 /// \returns true if *this > RHS when both are considered unsigned.
1234 bool ugt(const APInt &RHS) const { return !ule(RHS); }
1235
1236 /// \brief Unsigned greater than comparison
1237 ///
1238 /// Regards both *this as an unsigned quantity and compares it with RHS for
1239 /// the validity of the greater-than relationship.
1240 ///
1241 /// \returns true if *this > RHS when considered unsigned.
1242 bool ugt(uint64_t RHS) const {
1243 // Only need to check active bits if not a single word.
1244 return (!isSingleWord() && getActiveBits() > 64) || getZExtValue() > RHS;
1245 }
1246
1247 /// \brief Signed greather than comparison
1248 ///
1249 /// Regards both *this and RHS as signed quantities and compares them for the
1250 /// validity of the greater-than relationship.
1251 ///
1252 /// \returns true if *this > RHS when both are considered signed.
1253 bool sgt(const APInt &RHS) const { return !sle(RHS); }
1254
1255 /// \brief Signed greater than comparison
1256 ///
1257 /// Regards both *this as a signed quantity and compares it with RHS for
1258 /// the validity of the greater-than relationship.
1259 ///
1260 /// \returns true if *this > RHS when considered signed.
1261 bool sgt(int64_t RHS) const {
1262 return (!isSingleWord() && getMinSignedBits() > 64) ? !isNegative()
1263 : getSExtValue() > RHS;
1264 }
1265
1266 /// \brief Unsigned greater or equal comparison
1267 ///
1268 /// Regards both *this and RHS as unsigned quantities and compares them for
1269 /// validity of the greater-or-equal relationship.
1270 ///
1271 /// \returns true if *this >= RHS when both are considered unsigned.
1272 bool uge(const APInt &RHS) const { return !ult(RHS); }
1273
1274 /// \brief Unsigned greater or equal comparison
1275 ///
1276 /// Regards both *this as an unsigned quantity and compares it with RHS for
1277 /// the validity of the greater-or-equal relationship.
1278 ///
1279 /// \returns true if *this >= RHS when considered unsigned.
1280 bool uge(uint64_t RHS) const { return !ult(RHS); }
1281
1282 /// \brief Signed greater or equal comparison
1283 ///
1284 /// Regards both *this and RHS as signed quantities and compares them for
1285 /// validity of the greater-or-equal relationship.
1286 ///
1287 /// \returns true if *this >= RHS when both are considered signed.
1288 bool sge(const APInt &RHS) const { return !slt(RHS); }
1289
1290 /// \brief Signed greater or equal comparison
1291 ///
1292 /// Regards both *this as a signed quantity and compares it with RHS for
1293 /// the validity of the greater-or-equal relationship.
1294 ///
1295 /// \returns true if *this >= RHS when considered signed.
1296 bool sge(int64_t RHS) const { return !slt(RHS); }
1297
1298 /// This operation tests if there are any pairs of corresponding bits
1299 /// between this APInt and RHS that are both set.
1300 bool intersects(const APInt &RHS) const {
1301 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-7~svn329677/include/llvm/ADT/APInt.h"
, 1301, __extension__ __PRETTY_FUNCTION__))
;
1302 if (isSingleWord())
1303 return (U.VAL & RHS.U.VAL) != 0;
1304 return intersectsSlowCase(RHS);
1305 }
1306
1307 /// This operation checks that all bits set in this APInt are also set in RHS.
1308 bool isSubsetOf(const APInt &RHS) const {
1309 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-7~svn329677/include/llvm/ADT/APInt.h"
, 1309, __extension__ __PRETTY_FUNCTION__))
;
1310 if (isSingleWord())
1311 return (U.VAL & ~RHS.U.VAL) == 0;
1312 return isSubsetOfSlowCase(RHS);
1313 }
1314
1315 /// @}
1316 /// \name Resizing Operators
1317 /// @{
1318
1319 /// \brief Truncate to new width.
1320 ///
1321 /// Truncate the APInt to a specified width. It is an error to specify a width
1322 /// that is greater than or equal to the current width.
1323 APInt trunc(unsigned width) const;
1324
1325 /// \brief Sign extend to a new width.
1326 ///
1327 /// This operation sign extends the APInt to a new width. If the high order
1328 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1329 /// It is an error to specify a width that is less than or equal to the
1330 /// current width.
1331 APInt sext(unsigned width) const;
1332
1333 /// \brief Zero extend to a new width.
1334 ///
1335 /// This operation zero extends the APInt to a new width. The high order bits
1336 /// are filled with 0 bits. It is an error to specify a width that is less
1337 /// than or equal to the current width.
1338 APInt zext(unsigned width) const;
1339
1340 /// \brief Sign extend or truncate to width
1341 ///
1342 /// Make this APInt have the bit width given by \p width. The value is sign
1343 /// extended, truncated, or left alone to make it that width.
1344 APInt sextOrTrunc(unsigned width) const;
1345
1346 /// \brief Zero extend or truncate to width
1347 ///
1348 /// Make this APInt have the bit width given by \p width. The value is zero
1349 /// extended, truncated, or left alone to make it that width.
1350 APInt zextOrTrunc(unsigned width) const;
1351
1352 /// \brief Sign extend or truncate to width
1353 ///
1354 /// Make this APInt have the bit width given by \p width. The value is sign
1355 /// extended, or left alone to make it that width.
1356 APInt sextOrSelf(unsigned width) const;
1357
1358 /// \brief Zero extend or truncate to width
1359 ///
1360 /// Make this APInt have the bit width given by \p width. The value is zero
1361 /// extended, or left alone to make it that width.
1362 APInt zextOrSelf(unsigned width) const;
1363
1364 /// @}
1365 /// \name Bit Manipulation Operators
1366 /// @{
1367
1368 /// \brief Set every bit to 1.
1369 void setAllBits() {
1370 if (isSingleWord())
1371 U.VAL = WORD_MAX;
1372 else
1373 // Set all the bits in all the words.
1374 memset(U.pVal, -1, getNumWords() * APINT_WORD_SIZE);
1375 // Clear the unused ones
1376 clearUnusedBits();
1377 }
1378
1379 /// \brief Set a given bit to 1.
1380 ///
1381 /// Set the given bit to 1 whose position is given as "bitPosition".
1382 void setBit(unsigned BitPosition) {
1383 assert(BitPosition <= BitWidth && "BitPosition out of range")(static_cast <bool> (BitPosition <= BitWidth &&
"BitPosition out of range") ? void (0) : __assert_fail ("BitPosition <= BitWidth && \"BitPosition out of range\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/APInt.h"
, 1383, __extension__ __PRETTY_FUNCTION__))
;
1384 WordType Mask = maskBit(BitPosition);
1385 if (isSingleWord())
1386 U.VAL |= Mask;
1387 else
1388 U.pVal[whichWord(BitPosition)] |= Mask;
1389 }
1390
1391 /// Set the sign bit to 1.
1392 void setSignBit() {
1393 setBit(BitWidth - 1);
1394 }
1395
1396 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1397 void setBits(unsigned loBit, unsigned hiBit) {
1398 assert(hiBit <= BitWidth && "hiBit out of range")(static_cast <bool> (hiBit <= BitWidth && "hiBit out of range"
) ? void (0) : __assert_fail ("hiBit <= BitWidth && \"hiBit out of range\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/APInt.h"
, 1398, __extension__ __PRETTY_FUNCTION__))
;
1399 assert(loBit <= BitWidth && "loBit out of range")(static_cast <bool> (loBit <= BitWidth && "loBit out of range"
) ? void (0) : __assert_fail ("loBit <= BitWidth && \"loBit out of range\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/APInt.h"
, 1399, __extension__ __PRETTY_FUNCTION__))
;
1400 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-7~svn329677/include/llvm/ADT/APInt.h"
, 1400, __extension__ __PRETTY_FUNCTION__))
;
1401 if (loBit == hiBit)
1402 return;
1403 if (loBit < APINT_BITS_PER_WORD && hiBit <= APINT_BITS_PER_WORD) {
1404 uint64_t mask = WORD_MAX >> (APINT_BITS_PER_WORD - (hiBit - loBit));
1405 mask <<= loBit;
1406 if (isSingleWord())
1407 U.VAL |= mask;
1408 else
1409 U.pVal[0] |= mask;
1410 } else {
1411 setBitsSlowCase(loBit, hiBit);
1412 }
1413 }
1414
1415 /// Set the top bits starting from loBit.
1416 void setBitsFrom(unsigned loBit) {
1417 return setBits(loBit, BitWidth);
1418 }
1419
1420 /// Set the bottom loBits bits.
1421 void setLowBits(unsigned loBits) {
1422 return setBits(0, loBits);
1423 }
1424
1425 /// Set the top hiBits bits.
1426 void setHighBits(unsigned hiBits) {
1427 return setBits(BitWidth - hiBits, BitWidth);
1428 }
1429
1430 /// \brief Set every bit to 0.
1431 void clearAllBits() {
1432 if (isSingleWord())
1433 U.VAL = 0;
1434 else
1435 memset(U.pVal, 0, getNumWords() * APINT_WORD_SIZE);
1436 }
1437
1438 /// \brief Set a given bit to 0.
1439 ///
1440 /// Set the given bit to 0 whose position is given as "bitPosition".
1441 void clearBit(unsigned BitPosition) {
1442 assert(BitPosition <= BitWidth && "BitPosition out of range")(static_cast <bool> (BitPosition <= BitWidth &&
"BitPosition out of range") ? void (0) : __assert_fail ("BitPosition <= BitWidth && \"BitPosition out of range\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/APInt.h"
, 1442, __extension__ __PRETTY_FUNCTION__))
;
1443 WordType Mask = ~maskBit(BitPosition);
1444 if (isSingleWord())
1445 U.VAL &= Mask;
1446 else
1447 U.pVal[whichWord(BitPosition)] &= Mask;
1448 }
1449
1450 /// Set the sign bit to 0.
1451 void clearSignBit() {
1452 clearBit(BitWidth - 1);
1453 }
1454
1455 /// \brief Toggle every bit to its opposite value.
1456 void flipAllBits() {
1457 if (isSingleWord()) {
1458 U.VAL ^= WORD_MAX;
1459 clearUnusedBits();
1460 } else {
1461 flipAllBitsSlowCase();
1462 }
1463 }
1464
1465 /// \brief Toggles a given bit to its opposite value.
1466 ///
1467 /// Toggle a given bit to its opposite value whose position is given
1468 /// as "bitPosition".
1469 void flipBit(unsigned bitPosition);
1470
1471 /// Negate this APInt in place.
1472 void negate() {
1473 flipAllBits();
1474 ++(*this);
1475 }
1476
1477 /// Insert the bits from a smaller APInt starting at bitPosition.
1478 void insertBits(const APInt &SubBits, unsigned bitPosition);
1479
1480 /// Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
1481 APInt extractBits(unsigned numBits, unsigned bitPosition) const;
1482
1483 /// @}
1484 /// \name Value Characterization Functions
1485 /// @{
1486
1487 /// \brief Return the number of bits in the APInt.
1488 unsigned getBitWidth() const { return BitWidth; }
1489
1490 /// \brief Get the number of words.
1491 ///
1492 /// Here one word's bitwidth equals to that of uint64_t.
1493 ///
1494 /// \returns the number of words to hold the integer value of this APInt.
1495 unsigned getNumWords() const { return getNumWords(BitWidth); }
1496
1497 /// \brief Get the number of words.
1498 ///
1499 /// *NOTE* Here one word's bitwidth equals to that of uint64_t.
1500 ///
1501 /// \returns the number of words to hold the integer value with a given bit
1502 /// width.
1503 static unsigned getNumWords(unsigned BitWidth) {
1504 return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1505 }
1506
1507 /// \brief Compute the number of active bits in the value
1508 ///
1509 /// This function returns the number of active bits which is defined as the
1510 /// bit width minus the number of leading zeros. This is used in several
1511 /// computations to see how "wide" the value is.
1512 unsigned getActiveBits() const { return BitWidth - countLeadingZeros(); }
1513
1514 /// \brief Compute the number of active words in the value of this APInt.
1515 ///
1516 /// This is used in conjunction with getActiveData to extract the raw value of
1517 /// the APInt.
1518 unsigned getActiveWords() const {
1519 unsigned numActiveBits = getActiveBits();
1520 return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1;
1521 }
1522
1523 /// \brief Get the minimum bit size for this signed APInt
1524 ///
1525 /// Computes the minimum bit width for this APInt while considering it to be a
1526 /// signed (and probably negative) value. If the value is not negative, this
1527 /// function returns the same value as getActiveBits()+1. Otherwise, it
1528 /// returns the smallest bit width that will retain the negative value. For
1529 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1530 /// for -1, this function will always return 1.
1531 unsigned getMinSignedBits() const {
1532 if (isNegative())
1533 return BitWidth - countLeadingOnes() + 1;
1534 return getActiveBits() + 1;
1535 }
1536
1537 /// \brief Get zero extended value
1538 ///
1539 /// This method attempts to return the value of this APInt as a zero extended
1540 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1541 /// uint64_t. Otherwise an assertion will result.
1542 uint64_t getZExtValue() const {
1543 if (isSingleWord())
1544 return U.VAL;
1545 assert(getActiveBits() <= 64 && "Too many bits for uint64_t")(static_cast <bool> (getActiveBits() <= 64 &&
"Too many bits for uint64_t") ? void (0) : __assert_fail ("getActiveBits() <= 64 && \"Too many bits for uint64_t\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/APInt.h"
, 1545, __extension__ __PRETTY_FUNCTION__))
;
1546 return U.pVal[0];
1547 }
1548
1549 /// \brief Get sign extended value
1550 ///
1551 /// This method attempts to return the value of this APInt as a sign extended
1552 /// int64_t. The bit width must be <= 64 or the value must fit within an
1553 /// int64_t. Otherwise an assertion will result.
1554 int64_t getSExtValue() const {
1555 if (isSingleWord())
1556 return SignExtend64(U.VAL, BitWidth);
1557 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t")(static_cast <bool> (getMinSignedBits() <= 64 &&
"Too many bits for int64_t") ? void (0) : __assert_fail ("getMinSignedBits() <= 64 && \"Too many bits for int64_t\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/APInt.h"
, 1557, __extension__ __PRETTY_FUNCTION__))
;
1558 return int64_t(U.pVal[0]);
1559 }
1560
1561 /// \brief Get bits required for string value.
1562 ///
1563 /// This method determines how many bits are required to hold the APInt
1564 /// equivalent of the string given by \p str.
1565 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1566
1567 /// \brief The APInt version of the countLeadingZeros functions in
1568 /// MathExtras.h.
1569 ///
1570 /// It counts the number of zeros from the most significant bit to the first
1571 /// one bit.
1572 ///
1573 /// \returns BitWidth if the value is zero, otherwise returns the number of
1574 /// zeros from the most significant bit to the first one bits.
1575 unsigned countLeadingZeros() const {
1576 if (isSingleWord()) {
1577 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1578 return llvm::countLeadingZeros(U.VAL) - unusedBits;
1579 }
1580 return countLeadingZerosSlowCase();
1581 }
1582
1583 /// \brief Count the number of leading one bits.
1584 ///
1585 /// This function is an APInt version of the countLeadingOnes
1586 /// functions in MathExtras.h. It counts the number of ones from the most
1587 /// significant bit to the first zero bit.
1588 ///
1589 /// \returns 0 if the high order bit is not set, otherwise returns the number
1590 /// of 1 bits from the most significant to the least
1591 unsigned countLeadingOnes() const {
1592 if (isSingleWord())
1593 return llvm::countLeadingOnes(U.VAL << (APINT_BITS_PER_WORD - BitWidth));
1594 return countLeadingOnesSlowCase();
1595 }
1596
1597 /// Computes the number of leading bits of this APInt that are equal to its
1598 /// sign bit.
1599 unsigned getNumSignBits() const {
1600 return isNegative() ? countLeadingOnes() : countLeadingZeros();
1601 }
1602
1603 /// \brief Count the number of trailing zero bits.
1604 ///
1605 /// This function is an APInt version of the countTrailingZeros
1606 /// functions in MathExtras.h. It counts the number of zeros from the least
1607 /// significant bit to the first set bit.
1608 ///
1609 /// \returns BitWidth if the value is zero, otherwise returns the number of
1610 /// zeros from the least significant bit to the first one bit.
1611 unsigned countTrailingZeros() const {
1612 if (isSingleWord())
1613 return std::min(unsigned(llvm::countTrailingZeros(U.VAL)), BitWidth);
1614 return countTrailingZerosSlowCase();
1615 }
1616
1617 /// \brief Count the number of trailing one bits.
1618 ///
1619 /// This function is an APInt version of the countTrailingOnes
1620 /// functions in MathExtras.h. It counts the number of ones from the least
1621 /// significant bit to the first zero bit.
1622 ///
1623 /// \returns BitWidth if the value is all ones, otherwise returns the number
1624 /// of ones from the least significant bit to the first zero bit.
1625 unsigned countTrailingOnes() const {
1626 if (isSingleWord())
1627 return llvm::countTrailingOnes(U.VAL);
1628 return countTrailingOnesSlowCase();
1629 }
1630
1631 /// \brief Count the number of bits set.
1632 ///
1633 /// This function is an APInt version of the countPopulation functions
1634 /// in MathExtras.h. It counts the number of 1 bits in the APInt value.
1635 ///
1636 /// \returns 0 if the value is zero, otherwise returns the number of set bits.
1637 unsigned countPopulation() const {
1638 if (isSingleWord())
1639 return llvm::countPopulation(U.VAL);
1640 return countPopulationSlowCase();
1641 }
1642
1643 /// @}
1644 /// \name Conversion Functions
1645 /// @{
1646 void print(raw_ostream &OS, bool isSigned) const;
1647
1648 /// Converts an APInt to a string and append it to Str. Str is commonly a
1649 /// SmallString.
1650 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1651 bool formatAsCLiteral = false) const;
1652
1653 /// Considers the APInt to be unsigned and converts it into a string in the
1654 /// radix given. The radix can be 2, 8, 10 16, or 36.
1655 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1656 toString(Str, Radix, false, false);
1657 }
1658
1659 /// Considers the APInt to be signed and converts it into a string in the
1660 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1661 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1662 toString(Str, Radix, true, false);
1663 }
1664
1665 /// \brief Return the APInt as a std::string.
1666 ///
1667 /// Note that this is an inefficient method. It is better to pass in a
1668 /// SmallVector/SmallString to the methods above to avoid thrashing the heap
1669 /// for the string.
1670 std::string toString(unsigned Radix, bool Signed) const;
1671
1672 /// \returns a byte-swapped representation of this APInt Value.
1673 APInt byteSwap() const;
1674
1675 /// \returns the value with the bit representation reversed of this APInt
1676 /// Value.
1677 APInt reverseBits() const;
1678
1679 /// \brief Converts this APInt to a double value.
1680 double roundToDouble(bool isSigned) const;
1681
1682 /// \brief Converts this unsigned APInt to a double value.
1683 double roundToDouble() const { return roundToDouble(false); }
1684
1685 /// \brief Converts this signed APInt to a double value.
1686 double signedRoundToDouble() const { return roundToDouble(true); }
1687
1688 /// \brief Converts APInt bits to a double
1689 ///
1690 /// The conversion does not do a translation from integer to double, it just
1691 /// re-interprets the bits as a double. Note that it is valid to do this on
1692 /// any bit width. Exactly 64 bits will be translated.
1693 double bitsToDouble() const {
1694 return BitsToDouble(getWord(0));
1695 }
1696
1697 /// \brief Converts APInt bits to a double
1698 ///
1699 /// The conversion does not do a translation from integer to float, it just
1700 /// re-interprets the bits as a float. Note that it is valid to do this on
1701 /// any bit width. Exactly 32 bits will be translated.
1702 float bitsToFloat() const {
1703 return BitsToFloat(getWord(0));
1704 }
1705
1706 /// \brief Converts a double to APInt bits.
1707 ///
1708 /// The conversion does not do a translation from double to integer, it just
1709 /// re-interprets the bits of the double.
1710 static APInt doubleToBits(double V) {
1711 return APInt(sizeof(double) * CHAR_BIT8, DoubleToBits(V));
1712 }
1713
1714 /// \brief Converts a float to APInt bits.
1715 ///
1716 /// The conversion does not do a translation from float to integer, it just
1717 /// re-interprets the bits of the float.
1718 static APInt floatToBits(float V) {
1719 return APInt(sizeof(float) * CHAR_BIT8, FloatToBits(V));
1720 }
1721
1722 /// @}
1723 /// \name Mathematics Operations
1724 /// @{
1725
1726 /// \returns the floor log base 2 of this APInt.
1727 unsigned logBase2() const { return getActiveBits() - 1; }
1728
1729 /// \returns the ceil log base 2 of this APInt.
1730 unsigned ceilLogBase2() const {
1731 APInt temp(*this);
1732 --temp;
1733 return temp.getActiveBits();
1734 }
1735
1736 /// \returns the nearest log base 2 of this APInt. Ties round up.
1737 ///
1738 /// NOTE: When we have a BitWidth of 1, we define:
1739 ///
1740 /// log2(0) = UINT32_MAX
1741 /// log2(1) = 0
1742 ///
1743 /// to get around any mathematical concerns resulting from
1744 /// referencing 2 in a space where 2 does no exist.
1745 unsigned nearestLogBase2() const {
1746 // Special case when we have a bitwidth of 1. If VAL is 1, then we
1747 // get 0. If VAL is 0, we get WORD_MAX which gets truncated to
1748 // UINT32_MAX.
1749 if (BitWidth == 1)
1750 return U.VAL - 1;
1751
1752 // Handle the zero case.
1753 if (isNullValue())
1754 return UINT32_MAX(4294967295U);
1755
1756 // The non-zero case is handled by computing:
1757 //
1758 // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1].
1759 //
1760 // where x[i] is referring to the value of the ith bit of x.
1761 unsigned lg = logBase2();
1762 return lg + unsigned((*this)[lg - 1]);
1763 }
1764
1765 /// \returns the log base 2 of this APInt if its an exact power of two, -1
1766 /// otherwise
1767 int32_t exactLogBase2() const {
1768 if (!isPowerOf2())
1769 return -1;
1770 return logBase2();
1771 }
1772
1773 /// \brief Compute the square root
1774 APInt sqrt() const;
1775
1776 /// \brief Get the absolute value;
1777 ///
1778 /// If *this is < 0 then return -(*this), otherwise *this;
1779 APInt abs() const {
1780 if (isNegative())
1781 return -(*this);
1782 return *this;
1783 }
1784
1785 /// \returns the multiplicative inverse for a given modulo.
1786 APInt multiplicativeInverse(const APInt &modulo) const;
1787
1788 /// @}
1789 /// \name Support for division by constant
1790 /// @{
1791
1792 /// Calculate the magic number for signed division by a constant.
1793 struct ms;
1794 ms magic() const;
1795
1796 /// Calculate the magic number for unsigned division by a constant.
1797 struct mu;
1798 mu magicu(unsigned LeadingZeros = 0) const;
1799
1800 /// @}
1801 /// \name Building-block Operations for APInt and APFloat
1802 /// @{
1803
1804 // These building block operations operate on a representation of arbitrary
1805 // precision, two's-complement, bignum integer values. They should be
1806 // sufficient to implement APInt and APFloat bignum requirements. Inputs are
1807 // generally a pointer to the base of an array of integer parts, representing
1808 // an unsigned bignum, and a count of how many parts there are.
1809
1810 /// Sets the least significant part of a bignum to the input value, and zeroes
1811 /// out higher parts.
1812 static void tcSet(WordType *, WordType, unsigned);
1813
1814 /// Assign one bignum to another.
1815 static void tcAssign(WordType *, const WordType *, unsigned);
1816
1817 /// Returns true if a bignum is zero, false otherwise.
1818 static bool tcIsZero(const WordType *, unsigned);
1819
1820 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1821 static int tcExtractBit(const WordType *, unsigned bit);
1822
1823 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
1824 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
1825 /// significant bit of DST. All high bits above srcBITS in DST are
1826 /// zero-filled.
1827 static void tcExtract(WordType *, unsigned dstCount,
1828 const WordType *, unsigned srcBits,
1829 unsigned srcLSB);
1830
1831 /// Set the given bit of a bignum. Zero-based.
1832 static void tcSetBit(WordType *, unsigned bit);
1833
1834 /// Clear the given bit of a bignum. Zero-based.
1835 static void tcClearBit(WordType *, unsigned bit);
1836
1837 /// Returns the bit number of the least or most significant set bit of a
1838 /// number. If the input number has no bits set -1U is returned.
1839 static unsigned tcLSB(const WordType *, unsigned n);
1840 static unsigned tcMSB(const WordType *parts, unsigned n);
1841
1842 /// Negate a bignum in-place.
1843 static void tcNegate(WordType *, unsigned);
1844
1845 /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1846 static WordType tcAdd(WordType *, const WordType *,
1847 WordType carry, unsigned);
1848 /// DST += RHS. Returns the carry flag.
1849 static WordType tcAddPart(WordType *, WordType, unsigned);
1850
1851 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1852 static WordType tcSubtract(WordType *, const WordType *,
1853 WordType carry, unsigned);
1854 /// DST -= RHS. Returns the carry flag.
1855 static WordType tcSubtractPart(WordType *, WordType, unsigned);
1856
1857 /// DST += SRC * MULTIPLIER + PART if add is true
1858 /// DST = SRC * MULTIPLIER + PART if add is false
1859 ///
1860 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must
1861 /// start at the same point, i.e. DST == SRC.
1862 ///
1863 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned.
1864 /// Otherwise DST is filled with the least significant DSTPARTS parts of the
1865 /// result, and if all of the omitted higher parts were zero return zero,
1866 /// otherwise overflow occurred and return one.
1867 static int tcMultiplyPart(WordType *dst, const WordType *src,
1868 WordType multiplier, WordType carry,
1869 unsigned srcParts, unsigned dstParts,
1870 bool add);
1871
1872 /// DST = LHS * RHS, where DST has the same width as the operands and is
1873 /// filled with the least significant parts of the result. Returns one if
1874 /// overflow occurred, otherwise zero. DST must be disjoint from both
1875 /// operands.
1876 static int tcMultiply(WordType *, const WordType *, const WordType *,
1877 unsigned);
1878
1879 /// DST = LHS * RHS, where DST has width the sum of the widths of the
1880 /// operands. No overflow occurs. DST must be disjoint from both operands.
1881 static void tcFullMultiply(WordType *, const WordType *,
1882 const WordType *, unsigned, unsigned);
1883
1884 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1885 /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set
1886 /// REMAINDER to the remainder, return zero. i.e.
1887 ///
1888 /// OLD_LHS = RHS * LHS + REMAINDER
1889 ///
1890 /// SCRATCH is a bignum of the same size as the operands and result for use by
1891 /// the routine; its contents need not be initialized and are destroyed. LHS,
1892 /// REMAINDER and SCRATCH must be distinct.
1893 static int tcDivide(WordType *lhs, const WordType *rhs,
1894 WordType *remainder, WordType *scratch,
1895 unsigned parts);
1896
1897 /// Shift a bignum left Count bits. Shifted in bits are zero. There are no
1898 /// restrictions on Count.
1899 static void tcShiftLeft(WordType *, unsigned Words, unsigned Count);
1900
1901 /// Shift a bignum right Count bits. Shifted in bits are zero. There are no
1902 /// restrictions on Count.
1903 static void tcShiftRight(WordType *, unsigned Words, unsigned Count);
1904
1905 /// The obvious AND, OR and XOR and complement operations.
1906 static void tcAnd(WordType *, const WordType *, unsigned);
1907 static void tcOr(WordType *, const WordType *, unsigned);
1908 static void tcXor(WordType *, const WordType *, unsigned);
1909 static void tcComplement(WordType *, unsigned);
1910
1911 /// Comparison (unsigned) of two bignums.
1912 static int tcCompare(const WordType *, const WordType *, unsigned);
1913
1914 /// Increment a bignum in-place. Return the carry flag.
1915 static WordType tcIncrement(WordType *dst, unsigned parts) {
1916 return tcAddPart(dst, 1, parts);
1917 }
1918
1919 /// Decrement a bignum in-place. Return the borrow flag.
1920 static WordType tcDecrement(WordType *dst, unsigned parts) {
1921 return tcSubtractPart(dst, 1, parts);
1922 }
1923
1924 /// Set the least significant BITS and clear the rest.
1925 static void tcSetLeastSignificantBits(WordType *, unsigned, unsigned bits);
1926
1927 /// \brief debug method
1928 void dump() const;
1929
1930 /// @}
1931};
1932
1933/// Magic data for optimising signed division by a constant.
1934struct APInt::ms {
1935 APInt m; ///< magic number
1936 unsigned s; ///< shift amount
1937};
1938
1939/// Magic data for optimising unsigned division by a constant.
1940struct APInt::mu {
1941 APInt m; ///< magic number
1942 bool a; ///< add indicator
1943 unsigned s; ///< shift amount
1944};
1945
1946inline bool operator==(uint64_t V1, const APInt &V2) { return V2 == V1; }
1947
1948inline bool operator!=(uint64_t V1, const APInt &V2) { return V2 != V1; }
1949
1950/// \brief Unary bitwise complement operator.
1951///
1952/// \returns an APInt that is the bitwise complement of \p v.
1953inline APInt operator~(APInt v) {
1954 v.flipAllBits();
1955 return v;
1956}
1957
1958inline APInt operator&(APInt a, const APInt &b) {
1959 a &= b;
1960 return a;
1961}
1962
1963inline APInt operator&(const APInt &a, APInt &&b) {
1964 b &= a;
1965 return std::move(b);
1966}
1967
1968inline APInt operator&(APInt a, uint64_t RHS) {
1969 a &= RHS;
1970 return a;
1971}
1972
1973inline APInt operator&(uint64_t LHS, APInt b) {
1974 b &= LHS;
1975 return b;
1976}
1977
1978inline APInt operator|(APInt a, const APInt &b) {
1979 a |= b;
1980 return a;
1981}
1982
1983inline APInt operator|(const APInt &a, APInt &&b) {
1984 b |= a;
1985 return std::move(b);
1986}
1987
1988inline APInt operator|(APInt a, uint64_t RHS) {
1989 a |= RHS;
1990 return a;
1991}
1992
1993inline APInt operator|(uint64_t LHS, APInt b) {
1994 b |= LHS;
1995 return b;
1996}
1997
1998inline APInt operator^(APInt a, const APInt &b) {
1999 a ^= b;
2000 return a;
2001}
2002
2003inline APInt operator^(const APInt &a, APInt &&b) {
2004 b ^= a;
2005 return std::move(b);
2006}
2007
2008inline APInt operator^(APInt a, uint64_t RHS) {
2009 a ^= RHS;
2010 return a;
2011}
2012
2013inline APInt operator^(uint64_t LHS, APInt b) {
2014 b ^= LHS;
2015 return b;
2016}
2017
2018inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
2019 I.print(OS, true);
2020 return OS;
2021}
2022
2023inline APInt operator-(APInt v) {
2024 v.negate();
2025 return v;
2026}
2027
2028inline APInt operator+(APInt a, const APInt &b) {
2029 a += b;
2030 return a;
2031}
2032
2033inline APInt operator+(const APInt &a, APInt &&b) {
2034 b += a;
2035 return std::move(b);
2036}
2037
2038inline APInt operator+(APInt a, uint64_t RHS) {
2039 a += RHS;
2040 return a;
2041}
2042
2043inline APInt operator+(uint64_t LHS, APInt b) {
2044 b += LHS;
2045 return b;
2046}
2047
2048inline APInt operator-(APInt a, const APInt &b) {
2049 a -= b;
2050 return a;
2051}
2052
2053inline APInt operator-(const APInt &a, APInt &&b) {
2054 b.negate();
2055 b += a;
2056 return std::move(b);
2057}
2058
2059inline APInt operator-(APInt a, uint64_t RHS) {
2060 a -= RHS;
2061 return a;
2062}
2063
2064inline APInt operator-(uint64_t LHS, APInt b) {
2065 b.negate();
2066 b += LHS;
2067 return b;
2068}
2069
2070inline APInt operator*(APInt a, uint64_t RHS) {
2071 a *= RHS;
2072 return a;
2073}
2074
2075inline APInt operator*(uint64_t LHS, APInt b) {
2076 b *= LHS;
2077 return b;
2078}
2079
2080
2081namespace APIntOps {
2082
2083/// \brief Determine the smaller of two APInts considered to be signed.
2084inline const APInt &smin(const APInt &A, const APInt &B) {
2085 return A.slt(B) ? A : B;
2086}
2087
2088/// \brief Determine the larger of two APInts considered to be signed.
2089inline const APInt &smax(const APInt &A, const APInt &B) {
2090 return A.sgt(B) ? A : B;
2091}
2092
2093/// \brief Determine the smaller of two APInts considered to be signed.
2094inline const APInt &umin(const APInt &A, const APInt &B) {
2095 return A.ult(B) ? A : B;
2096}
2097
2098/// \brief Determine the larger of two APInts considered to be unsigned.
2099inline const APInt &umax(const APInt &A, const APInt &B) {
2100 return A.ugt(B) ? A : B;
2101}
2102
2103/// \brief Compute GCD of two unsigned APInt values.
2104///
2105/// This function returns the greatest common divisor of the two APInt values
2106/// using Stein's algorithm.
2107///
2108/// \returns the greatest common divisor of A and B.
2109APInt GreatestCommonDivisor(APInt A, APInt B);
2110
2111/// \brief Converts the given APInt to a double value.
2112///
2113/// Treats the APInt as an unsigned value for conversion purposes.
2114inline double RoundAPIntToDouble(const APInt &APIVal) {
2115 return APIVal.roundToDouble();
2116}
2117
2118/// \brief Converts the given APInt to a double value.
2119///
2120/// Treats the APInt as a signed value for conversion purposes.
2121inline double RoundSignedAPIntToDouble(const APInt &APIVal) {
2122 return APIVal.signedRoundToDouble();
2123}
2124
2125/// \brief Converts the given APInt to a float vlalue.
2126inline float RoundAPIntToFloat(const APInt &APIVal) {
2127 return float(RoundAPIntToDouble(APIVal));
2128}
2129
2130/// \brief Converts the given APInt to a float value.
2131///
2132/// Treast the APInt as a signed value for conversion purposes.
2133inline float RoundSignedAPIntToFloat(const APInt &APIVal) {
2134 return float(APIVal.signedRoundToDouble());
2135}
2136
2137/// \brief Converts the given double value into a APInt.
2138///
2139/// This function convert a double value to an APInt value.
2140APInt RoundDoubleToAPInt(double Double, unsigned width);
2141
2142/// \brief Converts a float value into a APInt.
2143///
2144/// Converts a float value into an APInt value.
2145inline APInt RoundFloatToAPInt(float Float, unsigned width) {
2146 return RoundDoubleToAPInt(double(Float), width);
2147}
2148
2149} // End of APIntOps namespace
2150
2151// See friend declaration above. This additional declaration is required in
2152// order to compile LLVM with IBM xlC compiler.
2153hash_code hash_value(const APInt &Arg);
2154} // End of llvm namespace
2155
2156#endif