1 //===- ScalarEvolutionAliasAnalysis.cpp - SCEV-based Alias Analysis -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the ScalarEvolutionAliasAnalysis pass, which implements a
10 // simple alias analysis implemented in terms of ScalarEvolution queries.
11 //
12 // This differs from traditional loop dependence analysis in that it tests
13 // for dependencies within a single iteration of a loop, rather than
14 // dependencies between different iterations.
15 //
16 // ScalarEvolution has a more complete understanding of pointer arithmetic
17 // than BasicAliasAnalysis' collection of ad-hoc analyses.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
22 #include "llvm/Analysis/ScalarEvolution.h"
23 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
24 #include "llvm/InitializePasses.h"
25 using namespace llvm;
26
canComputePointerDiff(ScalarEvolution & SE,const SCEV * A,const SCEV * B)27 static bool canComputePointerDiff(ScalarEvolution &SE,
28 const SCEV *A, const SCEV *B) {
29 if (SE.getEffectiveSCEVType(A->getType()) !=
30 SE.getEffectiveSCEVType(B->getType()))
31 return false;
32
33 return SE.instructionCouldExistWitthOperands(A, B);
34 }
35
alias(const MemoryLocation & LocA,const MemoryLocation & LocB,AAQueryInfo & AAQI)36 AliasResult SCEVAAResult::alias(const MemoryLocation &LocA,
37 const MemoryLocation &LocB, AAQueryInfo &AAQI) {
38 // If either of the memory references is empty, it doesn't matter what the
39 // pointer values are. This allows the code below to ignore this special
40 // case.
41 if (LocA.Size.isZero() || LocB.Size.isZero())
42 return AliasResult::NoAlias;
43
44 // This is SCEVAAResult. Get the SCEVs!
45 const SCEV *AS = SE.getSCEV(const_cast<Value *>(LocA.Ptr));
46 const SCEV *BS = SE.getSCEV(const_cast<Value *>(LocB.Ptr));
47
48 // If they evaluate to the same expression, it's a MustAlias.
49 if (AS == BS)
50 return AliasResult::MustAlias;
51
52 // If something is known about the difference between the two addresses,
53 // see if it's enough to prove a NoAlias.
54 if (canComputePointerDiff(SE, AS, BS)) {
55 unsigned BitWidth = SE.getTypeSizeInBits(AS->getType());
56 APInt ASizeInt(BitWidth, LocA.Size.hasValue()
57 ? LocA.Size.getValue()
58 : MemoryLocation::UnknownSize);
59 APInt BSizeInt(BitWidth, LocB.Size.hasValue()
60 ? LocB.Size.getValue()
61 : MemoryLocation::UnknownSize);
62
63 // Compute the difference between the two pointers.
64 const SCEV *BA = SE.getMinusSCEV(BS, AS);
65
66 // Test whether the difference is known to be great enough that memory of
67 // the given sizes don't overlap. This assumes that ASizeInt and BSizeInt
68 // are non-zero, which is special-cased above.
69 if (!isa<SCEVCouldNotCompute>(BA) &&
70 ASizeInt.ule(SE.getUnsignedRange(BA).getUnsignedMin()) &&
71 (-BSizeInt).uge(SE.getUnsignedRange(BA).getUnsignedMax()))
72 return AliasResult::NoAlias;
73
74 // Folding the subtraction while preserving range information can be tricky
75 // (because of INT_MIN, etc.); if the prior test failed, swap AS and BS
76 // and try again to see if things fold better that way.
77
78 // Compute the difference between the two pointers.
79 const SCEV *AB = SE.getMinusSCEV(AS, BS);
80
81 // Test whether the difference is known to be great enough that memory of
82 // the given sizes don't overlap. This assumes that ASizeInt and BSizeInt
83 // are non-zero, which is special-cased above.
84 if (!isa<SCEVCouldNotCompute>(AB) &&
85 BSizeInt.ule(SE.getUnsignedRange(AB).getUnsignedMin()) &&
86 (-ASizeInt).uge(SE.getUnsignedRange(AB).getUnsignedMax()))
87 return AliasResult::NoAlias;
88 }
89
90 // If ScalarEvolution can find an underlying object, form a new query.
91 // The correctness of this depends on ScalarEvolution not recognizing
92 // inttoptr and ptrtoint operators.
93 Value *AO = GetBaseValue(AS);
94 Value *BO = GetBaseValue(BS);
95 if ((AO && AO != LocA.Ptr) || (BO && BO != LocB.Ptr))
96 if (alias(MemoryLocation(AO ? AO : LocA.Ptr,
97 AO ? LocationSize::beforeOrAfterPointer()
98 : LocA.Size,
99 AO ? AAMDNodes() : LocA.AATags),
100 MemoryLocation(BO ? BO : LocB.Ptr,
101 BO ? LocationSize::beforeOrAfterPointer()
102 : LocB.Size,
103 BO ? AAMDNodes() : LocB.AATags),
104 AAQI) == AliasResult::NoAlias)
105 return AliasResult::NoAlias;
106
107 // Forward the query to the next analysis.
108 return AAResultBase::alias(LocA, LocB, AAQI);
109 }
110
111 /// Given an expression, try to find a base value.
112 ///
113 /// Returns null if none was found.
GetBaseValue(const SCEV * S)114 Value *SCEVAAResult::GetBaseValue(const SCEV *S) {
115 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
116 // In an addrec, assume that the base will be in the start, rather
117 // than the step.
118 return GetBaseValue(AR->getStart());
119 } else if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
120 // If there's a pointer operand, it'll be sorted at the end of the list.
121 const SCEV *Last = A->getOperand(A->getNumOperands() - 1);
122 if (Last->getType()->isPointerTy())
123 return GetBaseValue(Last);
124 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
125 // This is a leaf node.
126 return U->getValue();
127 }
128 // No Identified object found.
129 return nullptr;
130 }
131
invalidate(Function & Fn,const PreservedAnalyses & PA,FunctionAnalysisManager::Invalidator & Inv)132 bool SCEVAAResult::invalidate(Function &Fn, const PreservedAnalyses &PA,
133 FunctionAnalysisManager::Invalidator &Inv) {
134 // We don't care if this analysis itself is preserved, it has no state. But
135 // we need to check that the analyses it depends on have been.
136 return Inv.invalidate<ScalarEvolutionAnalysis>(Fn, PA);
137 }
138
139 AnalysisKey SCEVAA::Key;
140
run(Function & F,FunctionAnalysisManager & AM)141 SCEVAAResult SCEVAA::run(Function &F, FunctionAnalysisManager &AM) {
142 return SCEVAAResult(AM.getResult<ScalarEvolutionAnalysis>(F));
143 }
144
145 char SCEVAAWrapperPass::ID = 0;
146 INITIALIZE_PASS_BEGIN(SCEVAAWrapperPass, "scev-aa",
147 "ScalarEvolution-based Alias Analysis", false, true)
INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)148 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
149 INITIALIZE_PASS_END(SCEVAAWrapperPass, "scev-aa",
150 "ScalarEvolution-based Alias Analysis", false, true)
151
152 FunctionPass *llvm::createSCEVAAWrapperPass() {
153 return new SCEVAAWrapperPass();
154 }
155
SCEVAAWrapperPass()156 SCEVAAWrapperPass::SCEVAAWrapperPass() : FunctionPass(ID) {
157 initializeSCEVAAWrapperPassPass(*PassRegistry::getPassRegistry());
158 }
159
runOnFunction(Function & F)160 bool SCEVAAWrapperPass::runOnFunction(Function &F) {
161 Result.reset(
162 new SCEVAAResult(getAnalysis<ScalarEvolutionWrapperPass>().getSE()));
163 return false;
164 }
165
getAnalysisUsage(AnalysisUsage & AU) const166 void SCEVAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
167 AU.setPreservesAll();
168 AU.addRequired<ScalarEvolutionWrapperPass>();
169 }
170