LLVM 18.0.0git
AlignmentFromAssumptions.cpp
Go to the documentation of this file.
1//===----------------------- AlignmentFromAssumptions.cpp -----------------===//
2// Set Load/Store Alignments From Assumptions
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a ScalarEvolution-based transformation to set
11// the alignments of load, stores and memory intrinsics based on the truth
12// expressions of assume intrinsics. The primary motivation is to handle
13// complex alignment assumptions that apply to vector loads and stores that
14// appear after vectorization and unrolling.
15//
16//===----------------------------------------------------------------------===//
17
20#include "llvm/ADT/Statistic.h"
27#include "llvm/IR/Dominators.h"
28#include "llvm/IR/Instruction.h"
31#include "llvm/Support/Debug.h"
33
34#define DEBUG_TYPE "alignment-from-assumptions"
35using namespace llvm;
36
37STATISTIC(NumLoadAlignChanged,
38 "Number of loads changed by alignment assumptions");
39STATISTIC(NumStoreAlignChanged,
40 "Number of stores changed by alignment assumptions");
41STATISTIC(NumMemIntAlignChanged,
42 "Number of memory intrinsics changed by alignment assumptions");
43
44// Given an expression for the (constant) alignment, AlignSCEV, and an
45// expression for the displacement between a pointer and the aligned address,
46// DiffSCEV, compute the alignment of the displaced pointer if it can be reduced
47// to a constant. Using SCEV to compute alignment handles the case where
48// DiffSCEV is a recurrence with constant start such that the aligned offset
49// is constant. e.g. {16,+,32} % 32 -> 16.
50static MaybeAlign getNewAlignmentDiff(const SCEV *DiffSCEV,
51 const SCEV *AlignSCEV,
52 ScalarEvolution *SE) {
53 // DiffUnits = Diff % int64_t(Alignment)
54 const SCEV *DiffUnitsSCEV = SE->getURemExpr(DiffSCEV, AlignSCEV);
55
56 LLVM_DEBUG(dbgs() << "\talignment relative to " << *AlignSCEV << " is "
57 << *DiffUnitsSCEV << " (diff: " << *DiffSCEV << ")\n");
58
59 if (const SCEVConstant *ConstDUSCEV =
60 dyn_cast<SCEVConstant>(DiffUnitsSCEV)) {
61 int64_t DiffUnits = ConstDUSCEV->getValue()->getSExtValue();
62
63 // If the displacement is an exact multiple of the alignment, then the
64 // displaced pointer has the same alignment as the aligned pointer, so
65 // return the alignment value.
66 if (!DiffUnits)
67 return cast<SCEVConstant>(AlignSCEV)->getValue()->getAlignValue();
68
69 // If the displacement is not an exact multiple, but the remainder is a
70 // constant, then return this remainder (but only if it is a power of 2).
71 uint64_t DiffUnitsAbs = std::abs(DiffUnits);
72 if (isPowerOf2_64(DiffUnitsAbs))
73 return Align(DiffUnitsAbs);
74 }
75
76 return std::nullopt;
77}
78
79// There is an address given by an offset OffSCEV from AASCEV which has an
80// alignment AlignSCEV. Use that information, if possible, to compute a new
81// alignment for Ptr.
82static Align getNewAlignment(const SCEV *AASCEV, const SCEV *AlignSCEV,
83 const SCEV *OffSCEV, Value *Ptr,
84 ScalarEvolution *SE) {
85 const SCEV *PtrSCEV = SE->getSCEV(Ptr);
86 // On a platform with 32-bit allocas, but 64-bit flat/global pointer sizes
87 // (*cough* AMDGPU), the effective SCEV type of AASCEV and PtrSCEV
88 // may disagree. Trunc/extend so they agree.
89 PtrSCEV = SE->getTruncateOrZeroExtend(
90 PtrSCEV, SE->getEffectiveSCEVType(AASCEV->getType()));
91 const SCEV *DiffSCEV = SE->getMinusSCEV(PtrSCEV, AASCEV);
92 if (isa<SCEVCouldNotCompute>(DiffSCEV))
93 return Align(1);
94
95 // On 32-bit platforms, DiffSCEV might now have type i32 -- we've always
96 // sign-extended OffSCEV to i64, so make sure they agree again.
97 DiffSCEV = SE->getNoopOrSignExtend(DiffSCEV, OffSCEV->getType());
98
99 // What we really want to know is the overall offset to the aligned
100 // address. This address is displaced by the provided offset.
101 DiffSCEV = SE->getAddExpr(DiffSCEV, OffSCEV);
102
103 LLVM_DEBUG(dbgs() << "AFI: alignment of " << *Ptr << " relative to "
104 << *AlignSCEV << " and offset " << *OffSCEV
105 << " using diff " << *DiffSCEV << "\n");
106
107 if (MaybeAlign NewAlignment = getNewAlignmentDiff(DiffSCEV, AlignSCEV, SE)) {
108 LLVM_DEBUG(dbgs() << "\tnew alignment: " << DebugStr(NewAlignment) << "\n");
109 return *NewAlignment;
110 }
111
112 if (const SCEVAddRecExpr *DiffARSCEV = dyn_cast<SCEVAddRecExpr>(DiffSCEV)) {
113 // The relative offset to the alignment assumption did not yield a constant,
114 // but we should try harder: if we assume that a is 32-byte aligned, then in
115 // for (i = 0; i < 1024; i += 4) r += a[i]; not all of the loads from a are
116 // 32-byte aligned, but instead alternate between 32 and 16-byte alignment.
117 // As a result, the new alignment will not be a constant, but can still
118 // be improved over the default (of 4) to 16.
119
120 const SCEV *DiffStartSCEV = DiffARSCEV->getStart();
121 const SCEV *DiffIncSCEV = DiffARSCEV->getStepRecurrence(*SE);
122
123 LLVM_DEBUG(dbgs() << "\ttrying start/inc alignment using start "
124 << *DiffStartSCEV << " and inc " << *DiffIncSCEV << "\n");
125
126 // Now compute the new alignment using the displacement to the value in the
127 // first iteration, and also the alignment using the per-iteration delta.
128 // If these are the same, then use that answer. Otherwise, use the smaller
129 // one, but only if it divides the larger one.
130 MaybeAlign NewAlignment = getNewAlignmentDiff(DiffStartSCEV, AlignSCEV, SE);
131 MaybeAlign NewIncAlignment =
132 getNewAlignmentDiff(DiffIncSCEV, AlignSCEV, SE);
133
134 LLVM_DEBUG(dbgs() << "\tnew start alignment: " << DebugStr(NewAlignment)
135 << "\n");
136 LLVM_DEBUG(dbgs() << "\tnew inc alignment: " << DebugStr(NewIncAlignment)
137 << "\n");
138
139 if (!NewAlignment || !NewIncAlignment)
140 return Align(1);
141
142 const Align NewAlign = *NewAlignment;
143 const Align NewIncAlign = *NewIncAlignment;
144 if (NewAlign > NewIncAlign) {
145 LLVM_DEBUG(dbgs() << "\tnew start/inc alignment: "
146 << DebugStr(NewIncAlign) << "\n");
147 return NewIncAlign;
148 }
149 if (NewIncAlign > NewAlign) {
150 LLVM_DEBUG(dbgs() << "\tnew start/inc alignment: " << DebugStr(NewAlign)
151 << "\n");
152 return NewAlign;
153 }
154 assert(NewIncAlign == NewAlign);
155 LLVM_DEBUG(dbgs() << "\tnew start/inc alignment: " << DebugStr(NewAlign)
156 << "\n");
157 return NewAlign;
158 }
159
160 return Align(1);
161}
162
164 unsigned Idx,
165 Value *&AAPtr,
166 const SCEV *&AlignSCEV,
167 const SCEV *&OffSCEV) {
168 Type *Int64Ty = Type::getInt64Ty(I->getContext());
169 OperandBundleUse AlignOB = I->getOperandBundleAt(Idx);
170 if (AlignOB.getTagName() != "align")
171 return false;
172 assert(AlignOB.Inputs.size() >= 2);
173 AAPtr = AlignOB.Inputs[0].get();
174 // TODO: Consider accumulating the offset to the base.
176 AlignSCEV = SE->getSCEV(AlignOB.Inputs[1].get());
177 AlignSCEV = SE->getTruncateOrZeroExtend(AlignSCEV, Int64Ty);
178 if (!isa<SCEVConstant>(AlignSCEV))
179 // Added to suppress a crash because consumer doesn't expect non-constant
180 // alignments in the assume bundle. TODO: Consider generalizing caller.
181 return false;
182 if (!cast<SCEVConstant>(AlignSCEV)->getAPInt().isPowerOf2())
183 // Only power of two alignments are supported.
184 return false;
185 if (AlignOB.Inputs.size() == 3)
186 OffSCEV = SE->getSCEV(AlignOB.Inputs[2].get());
187 else
188 OffSCEV = SE->getZero(Int64Ty);
189 OffSCEV = SE->getTruncateOrZeroExtend(OffSCEV, Int64Ty);
190 return true;
191}
192
194 unsigned Idx) {
195 Value *AAPtr;
196 const SCEV *AlignSCEV, *OffSCEV;
197 if (!extractAlignmentInfo(ACall, Idx, AAPtr, AlignSCEV, OffSCEV))
198 return false;
199
200 // Skip ConstantPointerNull and UndefValue. Assumptions on these shouldn't
201 // affect other users.
202 if (isa<ConstantData>(AAPtr))
203 return false;
204
205 const SCEV *AASCEV = SE->getSCEV(AAPtr);
206
207 // Apply the assumption to all other users of the specified pointer.
210 for (User *J : AAPtr->users()) {
211 if (J == ACall)
212 continue;
213
214 if (Instruction *K = dyn_cast<Instruction>(J))
215 WorkList.push_back(K);
216 }
217
218 while (!WorkList.empty()) {
219 Instruction *J = WorkList.pop_back_val();
220 if (LoadInst *LI = dyn_cast<LoadInst>(J)) {
221 if (!isValidAssumeForContext(ACall, J, DT))
222 continue;
223 Align NewAlignment = getNewAlignment(AASCEV, AlignSCEV, OffSCEV,
224 LI->getPointerOperand(), SE);
225 if (NewAlignment > LI->getAlign()) {
226 LI->setAlignment(NewAlignment);
227 ++NumLoadAlignChanged;
228 }
229 } else if (StoreInst *SI = dyn_cast<StoreInst>(J)) {
230 if (!isValidAssumeForContext(ACall, J, DT))
231 continue;
232 Align NewAlignment = getNewAlignment(AASCEV, AlignSCEV, OffSCEV,
233 SI->getPointerOperand(), SE);
234 if (NewAlignment > SI->getAlign()) {
235 SI->setAlignment(NewAlignment);
236 ++NumStoreAlignChanged;
237 }
238 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(J)) {
239 if (!isValidAssumeForContext(ACall, J, DT))
240 continue;
241 Align NewDestAlignment =
242 getNewAlignment(AASCEV, AlignSCEV, OffSCEV, MI->getDest(), SE);
243
244 LLVM_DEBUG(dbgs() << "\tmem inst: " << DebugStr(NewDestAlignment)
245 << "\n";);
246 if (NewDestAlignment > *MI->getDestAlign()) {
247 MI->setDestAlignment(NewDestAlignment);
248 ++NumMemIntAlignChanged;
249 }
250
251 // For memory transfers, there is also a source alignment that
252 // can be set.
253 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
254 Align NewSrcAlignment =
255 getNewAlignment(AASCEV, AlignSCEV, OffSCEV, MTI->getSource(), SE);
256
257 LLVM_DEBUG(dbgs() << "\tmem trans: " << DebugStr(NewSrcAlignment)
258 << "\n";);
259
260 if (NewSrcAlignment > *MTI->getSourceAlign()) {
261 MTI->setSourceAlignment(NewSrcAlignment);
262 ++NumMemIntAlignChanged;
263 }
264 }
265 }
266
267 // Now that we've updated that use of the pointer, look for other uses of
268 // the pointer to update.
269 Visited.insert(J);
270 for (User *UJ : J->users()) {
271 Instruction *K = cast<Instruction>(UJ);
272 if (!Visited.count(K))
273 WorkList.push_back(K);
274 }
275 }
276
277 return true;
278}
279
281 ScalarEvolution *SE_,
282 DominatorTree *DT_) {
283 SE = SE_;
284 DT = DT_;
285
286 bool Changed = false;
287 for (auto &AssumeVH : AC.assumptions())
288 if (AssumeVH) {
289 CallInst *Call = cast<CallInst>(AssumeVH);
290 for (unsigned Idx = 0; Idx < Call->getNumOperandBundles(); Idx++)
291 Changed |= processAssumption(Call, Idx);
292 }
293
294 return Changed;
295}
296
299
303 if (!runImpl(F, AC, &SE, &DT))
304 return PreservedAnalyses::all();
305
309 return PA;
310}
static MaybeAlign getNewAlignmentDiff(const SCEV *DiffSCEV, const SCEV *AlignSCEV, ScalarEvolution *SE)
static Align getNewAlignment(const SCEV *AASCEV, const SCEV *AlignSCEV, const SCEV *OffSCEV, Value *Ptr, ScalarEvolution *SE)
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
This is the interface for a simple mod/ref and alias analysis over globals.
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallPtrSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:620
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:774
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
MutableArrayRef< ResultElem > assumptions()
Access the list of assumption handles currently tracked for this function.
Represents analyses that only rely on functions' control flow.
Definition: PassManager.h:113
This class represents a function call, abstracting a target machine's calling convention.
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:166
An instruction for reading from memory.
Definition: Instructions.h:177
This is the common base class for memset/memcpy/memmove.
This class wraps the llvm.memcpy/memmove intrinsics.
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:152
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:158
void preserveSet()
Mark an analysis set as preserved.
Definition: PassManager.h:188
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:173
This node represents a polynomial recurrence on the trip count of the specified loop.
This class represents a constant integer value.
This class represents an analyzed expression in the program.
Type * getType() const
Return the LLVM type of this SCEV expression.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
const SCEV * getURemExpr(const SCEV *LHS, const SCEV *RHS)
Represents an unsigned remainder expression based on unsigned division.
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
const SCEV * getAddExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:384
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:366
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:451
bool empty() const
Definition: SmallVector.h:94
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
An instruction for storing to memory.
Definition: Instructions.h:301
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static IntegerType * getInt64Ty(LLVMContext &C)
LLVM Value Representation.
Definition: Value.h:74
iterator_range< user_iterator > users()
Definition: Value.h:421
const Value * stripPointerCastsSameRepresentation() const
Strip off pointer casts, all-zero GEPs and address space casts but ensures the representation of the ...
Definition: Value.cpp:696
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::string DebugStr(const Align &A)
Definition: Alignment.h:312
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition: MathExtras.h:269
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI, const DominatorTree *DT=nullptr)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
bool extractAlignmentInfo(CallInst *I, unsigned Idx, Value *&AAPtr, const SCEV *&AlignSCEV, const SCEV *&OffSCEV)
bool processAssumption(CallInst *I, unsigned Idx)
bool runImpl(Function &F, AssumptionCache &AC, ScalarEvolution *SE_, DominatorTree *DT_)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:117
A lightweight accessor for an operand bundle meant to be passed around by value.
Definition: InstrTypes.h:1085
StringRef getTagName() const
Return the tag of this operand bundle as a string.
Definition: InstrTypes.h:1104
ArrayRef< Use > Inputs
Definition: InstrTypes.h:1086