1#include "llvm/Transforms/Utils/VNCoercion.h"
2#include "llvm/Analysis/ConstantFolding.h"
3#include "llvm/Analysis/ValueTracking.h"
4#include "llvm/IR/IRBuilder.h"
5#include "llvm/IR/IntrinsicInst.h"
6
7#define DEBUG_TYPE "vncoerce"
8
9using namespace llvm;
10using namespace VNCoercion;
11
12static bool isFirstClassAggregateOrScalableType(Type *Ty) {
13 return Ty->isStructTy() || Ty->isArrayTy() || isa<ScalableVectorType>(Val: Ty);
14}
15
16/// Return true if coerceAvailableValueToLoadType will succeed.
17bool VNCoercion::canCoerceMustAliasedValueToLoad(Value *StoredVal, Type *LoadTy,
18 Function *F) {
19 Type *StoredTy = StoredVal->getType();
20 if (StoredTy == LoadTy)
21 return true;
22
23 const DataLayout &DL = F->getDataLayout();
24 TypeSize MinStoreSize = DL.getTypeSizeInBits(Ty: StoredTy);
25 TypeSize LoadSize = DL.getTypeSizeInBits(Ty: LoadTy);
26 if (isa<ScalableVectorType>(Val: StoredTy) && isa<ScalableVectorType>(Val: LoadTy) &&
27 MinStoreSize == LoadSize)
28 return true;
29
30 // If the loaded/stored value is a first class array/struct, don't try to
31 // transform them. We need to be able to bitcast to integer. For scalable
32 // vectors forwarded to fixed-sized vectors @llvm.vector.extract is used.
33 if (isa<ScalableVectorType>(Val: StoredTy) && isa<FixedVectorType>(Val: LoadTy)) {
34 if (StoredTy->getScalarType() != LoadTy->getScalarType())
35 return false;
36
37 // If it is known at compile-time that the VScale is larger than one,
38 // use that information to allow for wider loads.
39 const auto &Attrs = F->getAttributes().getFnAttrs();
40 unsigned MinVScale = Attrs.getVScaleRangeMin();
41 MinStoreSize =
42 TypeSize::getFixed(ExactSize: MinStoreSize.getKnownMinValue() * MinVScale);
43 } else if (isFirstClassAggregateOrScalableType(Ty: LoadTy) ||
44 isFirstClassAggregateOrScalableType(Ty: StoredTy)) {
45 return false;
46 }
47
48 // The store size must be byte-aligned to support future type casts.
49 if (llvm::alignTo(Size: MinStoreSize, Align: 8) != MinStoreSize)
50 return false;
51
52 // The store has to be at least as big as the load.
53 if (!TypeSize::isKnownGE(LHS: MinStoreSize, RHS: LoadSize))
54 return false;
55
56 bool StoredNI = DL.isNonIntegralPointerType(Ty: StoredTy->getScalarType());
57 bool LoadNI = DL.isNonIntegralPointerType(Ty: LoadTy->getScalarType());
58 // Don't coerce non-integral pointers to integers or vice versa.
59 if (StoredNI != LoadNI) {
60 // As a special case, allow coercion of memset used to initialize
61 // an array w/null. Despite non-integral pointers not generally having a
62 // specific bit pattern, we do assume null is zero.
63 if (auto *CI = dyn_cast<Constant>(Val: StoredVal))
64 return CI->isNullValue();
65 return false;
66 } else if (StoredNI && LoadNI &&
67 StoredTy->getPointerAddressSpace() !=
68 LoadTy->getPointerAddressSpace()) {
69 return false;
70 }
71
72 // The implementation below uses inttoptr for vectors of unequal size; we
73 // can't allow this for non integral pointers. We could teach it to extract
74 // exact subvectors if desired.
75 if (StoredNI && (StoredTy->isScalableTy() || MinStoreSize != LoadSize))
76 return false;
77
78 if (StoredTy->isTargetExtTy() || LoadTy->isTargetExtTy())
79 return false;
80
81 return true;
82}
83
84/// If we saw a store of a value to memory, and
85/// then a load from a must-aliased pointer of a different type, try to coerce
86/// the stored value. LoadedTy is the type of the load we want to replace.
87/// IRB is IRBuilder used to insert new instructions.
88///
89/// If we can't do it, return null.
90Value *VNCoercion::coerceAvailableValueToLoadType(Value *StoredVal,
91 Type *LoadedTy,
92 IRBuilderBase &Helper,
93 Function *F) {
94 assert(canCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, F) &&
95 "precondition violation - materialization can't fail");
96 const DataLayout &DL = F->getDataLayout();
97 if (auto *C = dyn_cast<Constant>(Val: StoredVal))
98 StoredVal = ConstantFoldConstant(C, DL);
99
100 // If this is already the right type, just return it.
101 Type *StoredValTy = StoredVal->getType();
102
103 // If this is a scalable vector forwarded to a fixed vector load, create
104 // a @llvm.vector.extract instead of bitcasts.
105 if (isa<ScalableVectorType>(Val: StoredVal->getType()) &&
106 isa<FixedVectorType>(Val: LoadedTy)) {
107 return Helper.CreateIntrinsic(RetTy: LoadedTy, ID: Intrinsic::vector_extract,
108 Args: {StoredVal, Helper.getInt64(C: 0)});
109 }
110
111 TypeSize StoredValSize = DL.getTypeSizeInBits(Ty: StoredValTy);
112 TypeSize LoadedValSize = DL.getTypeSizeInBits(Ty: LoadedTy);
113
114 // If the store and reload are the same size, we can always reuse it.
115 if (StoredValSize == LoadedValSize) {
116 // Pointer to Pointer -> use bitcast.
117 if (StoredValTy->isPtrOrPtrVectorTy() && LoadedTy->isPtrOrPtrVectorTy()) {
118 StoredVal = Helper.CreateBitCast(V: StoredVal, DestTy: LoadedTy);
119 } else {
120 // Convert source pointers to integers, which can be bitcast.
121 if (StoredValTy->isPtrOrPtrVectorTy()) {
122 StoredValTy = DL.getIntPtrType(StoredValTy);
123 StoredVal = Helper.CreatePtrToInt(V: StoredVal, DestTy: StoredValTy);
124 }
125
126 Type *TypeToCastTo = LoadedTy;
127 if (TypeToCastTo->isPtrOrPtrVectorTy())
128 TypeToCastTo = DL.getIntPtrType(TypeToCastTo);
129
130 if (StoredValTy != TypeToCastTo)
131 StoredVal = Helper.CreateBitCast(V: StoredVal, DestTy: TypeToCastTo);
132
133 // Cast to pointer if the load needs a pointer type.
134 if (LoadedTy->isPtrOrPtrVectorTy())
135 StoredVal = Helper.CreateIntToPtr(V: StoredVal, DestTy: LoadedTy);
136 }
137
138 if (auto *C = dyn_cast<ConstantExpr>(Val: StoredVal))
139 StoredVal = ConstantFoldConstant(C, DL);
140
141 return StoredVal;
142 }
143 // If the loaded value is smaller than the available value, then we can
144 // extract out a piece from it. If the available value is too small, then we
145 // can't do anything.
146 assert(!StoredValSize.isScalable() &&
147 TypeSize::isKnownGE(StoredValSize, LoadedValSize) &&
148 "canCoerceMustAliasedValueToLoad fail");
149
150 // Convert source pointers to integers, which can be manipulated.
151 if (StoredValTy->isPtrOrPtrVectorTy()) {
152 StoredValTy = DL.getIntPtrType(StoredValTy);
153 StoredVal = Helper.CreatePtrToInt(V: StoredVal, DestTy: StoredValTy);
154 }
155
156 // Convert vectors and fp to integer, which can be manipulated.
157 if (!StoredValTy->isIntegerTy()) {
158 StoredValTy = IntegerType::get(C&: StoredValTy->getContext(), NumBits: StoredValSize);
159 StoredVal = Helper.CreateBitCast(V: StoredVal, DestTy: StoredValTy);
160 }
161
162 // If this is a big-endian system, we need to shift the value down to the low
163 // bits so that a truncate will work.
164 if (DL.isBigEndian()) {
165 uint64_t ShiftAmt = DL.getTypeStoreSizeInBits(Ty: StoredValTy).getFixedValue() -
166 DL.getTypeStoreSizeInBits(Ty: LoadedTy).getFixedValue();
167 StoredVal = Helper.CreateLShr(
168 LHS: StoredVal, RHS: ConstantInt::get(Ty: StoredVal->getType(), V: ShiftAmt));
169 }
170
171 // Truncate the integer to the right size now.
172 Type *NewIntTy = IntegerType::get(C&: StoredValTy->getContext(), NumBits: LoadedValSize);
173 StoredVal = Helper.CreateTruncOrBitCast(V: StoredVal, DestTy: NewIntTy);
174
175 if (LoadedTy != NewIntTy) {
176 // If the result is a pointer, inttoptr.
177 if (LoadedTy->isPtrOrPtrVectorTy())
178 StoredVal = Helper.CreateIntToPtr(V: StoredVal, DestTy: LoadedTy);
179 else
180 // Otherwise, bitcast.
181 StoredVal = Helper.CreateBitCast(V: StoredVal, DestTy: LoadedTy);
182 }
183
184 if (auto *C = dyn_cast<Constant>(Val: StoredVal))
185 StoredVal = ConstantFoldConstant(C, DL);
186
187 return StoredVal;
188}
189
190/// This function is called when we have a memdep query of a load that ends up
191/// being a clobbering memory write (store, memset, memcpy, memmove). This
192/// means that the write *may* provide bits used by the load but we can't be
193/// sure because the pointers don't must-alias.
194///
195/// Check this case to see if there is anything more we can do before we give
196/// up. This returns -1 if we have to give up, or a byte number in the stored
197/// value of the piece that feeds the load.
198static int analyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
199 Value *WritePtr,
200 uint64_t WriteSizeInBits,
201 const DataLayout &DL) {
202 // If the loaded/stored value is a first class array/struct, or scalable type,
203 // don't try to transform them. We need to be able to bitcast to integer.
204 if (isFirstClassAggregateOrScalableType(Ty: LoadTy))
205 return -1;
206
207 int64_t StoreOffset = 0, LoadOffset = 0;
208 Value *StoreBase =
209 GetPointerBaseWithConstantOffset(Ptr: WritePtr, Offset&: StoreOffset, DL);
210 Value *LoadBase = GetPointerBaseWithConstantOffset(Ptr: LoadPtr, Offset&: LoadOffset, DL);
211 if (StoreBase != LoadBase)
212 return -1;
213
214 uint64_t LoadSize = DL.getTypeSizeInBits(Ty: LoadTy).getFixedValue();
215
216 if ((WriteSizeInBits & 7) | (LoadSize & 7))
217 return -1;
218 uint64_t StoreSize = WriteSizeInBits / 8; // Convert to bytes.
219 LoadSize /= 8;
220
221 // If the Load isn't completely contained within the stored bits, we don't
222 // have all the bits to feed it. We could do something crazy in the future
223 // (issue a smaller load then merge the bits in) but this seems unlikely to be
224 // valuable.
225 if (StoreOffset > LoadOffset ||
226 StoreOffset + int64_t(StoreSize) < LoadOffset + int64_t(LoadSize))
227 return -1;
228
229 // Okay, we can do this transformation. Return the number of bytes into the
230 // store that the load is.
231 return LoadOffset - StoreOffset;
232}
233
234/// This function is called when we have a
235/// memdep query of a load that ends up being a clobbering store.
236int VNCoercion::analyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
237 StoreInst *DepSI,
238 const DataLayout &DL) {
239 auto *StoredVal = DepSI->getValueOperand();
240
241 // Cannot handle reading from store of first-class aggregate or scalable type.
242 if (isFirstClassAggregateOrScalableType(Ty: StoredVal->getType()))
243 return -1;
244
245 if (!canCoerceMustAliasedValueToLoad(StoredVal, LoadTy, F: DepSI->getFunction()))
246 return -1;
247
248 Value *StorePtr = DepSI->getPointerOperand();
249 uint64_t StoreSize =
250 DL.getTypeSizeInBits(Ty: DepSI->getValueOperand()->getType()).getFixedValue();
251 return analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, WritePtr: StorePtr, WriteSizeInBits: StoreSize,
252 DL);
253}
254
255/// This function is called when we have a
256/// memdep query of a load that ends up being clobbered by another load. See if
257/// the other load can feed into the second load.
258int VNCoercion::analyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr,
259 LoadInst *DepLI,
260 const DataLayout &DL) {
261 // Cannot handle reading from store of first-class aggregate or scalable type.
262 if (isFirstClassAggregateOrScalableType(Ty: DepLI->getType()))
263 return -1;
264
265 if (!canCoerceMustAliasedValueToLoad(StoredVal: DepLI, LoadTy, F: DepLI->getFunction()))
266 return -1;
267
268 Value *DepPtr = DepLI->getPointerOperand();
269 uint64_t DepSize = DL.getTypeSizeInBits(Ty: DepLI->getType()).getFixedValue();
270 return analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, WritePtr: DepPtr, WriteSizeInBits: DepSize, DL);
271}
272
273int VNCoercion::analyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
274 MemIntrinsic *MI,
275 const DataLayout &DL) {
276 // If the mem operation is a non-constant size, we can't handle it.
277 ConstantInt *SizeCst = dyn_cast<ConstantInt>(Val: MI->getLength());
278 if (!SizeCst)
279 return -1;
280 uint64_t MemSizeInBits = SizeCst->getZExtValue() * 8;
281
282 // If this is memset, we just need to see if the offset is valid in the size
283 // of the memset..
284 if (const auto *Memset = dyn_cast<MemSetInst>(Val: MI)) {
285 if (DL.isNonIntegralPointerType(Ty: LoadTy->getScalarType())) {
286 auto *CI = dyn_cast<ConstantInt>(Val: Memset->getValue());
287 if (!CI || !CI->isZero())
288 return -1;
289 }
290 return analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, WritePtr: MI->getDest(),
291 WriteSizeInBits: MemSizeInBits, DL);
292 }
293
294 // If we have a memcpy/memmove, the only case we can handle is if this is a
295 // copy from constant memory. In that case, we can read directly from the
296 // constant memory.
297 MemTransferInst *MTI = cast<MemTransferInst>(Val: MI);
298
299 Constant *Src = dyn_cast<Constant>(Val: MTI->getSource());
300 if (!Src)
301 return -1;
302
303 GlobalVariable *GV = dyn_cast<GlobalVariable>(Val: getUnderlyingObject(V: Src));
304 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
305 return -1;
306
307 // See if the access is within the bounds of the transfer.
308 int Offset = analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, WritePtr: MI->getDest(),
309 WriteSizeInBits: MemSizeInBits, DL);
310 if (Offset == -1)
311 return Offset;
312
313 // Otherwise, see if we can constant fold a load from the constant with the
314 // offset applied as appropriate.
315 unsigned IndexSize = DL.getIndexTypeSizeInBits(Ty: Src->getType());
316 if (ConstantFoldLoadFromConstPtr(C: Src, Ty: LoadTy, Offset: APInt(IndexSize, Offset), DL))
317 return Offset;
318 return -1;
319}
320
321static Value *getStoreValueForLoadHelper(Value *SrcVal, unsigned Offset,
322 Type *LoadTy, IRBuilderBase &Builder,
323 const DataLayout &DL) {
324 LLVMContext &Ctx = SrcVal->getType()->getContext();
325
326 // If two pointers are in the same address space, they have the same size,
327 // so we don't need to do any truncation, etc. This avoids introducing
328 // ptrtoint instructions for pointers that may be non-integral.
329 if (SrcVal->getType()->isPointerTy() && LoadTy->isPointerTy() &&
330 cast<PointerType>(Val: SrcVal->getType())->getAddressSpace() ==
331 cast<PointerType>(Val: LoadTy)->getAddressSpace()) {
332 return SrcVal;
333 }
334
335 // Return scalable values directly to avoid needing to bitcast to integer
336 // types, as we do not support non-zero Offsets.
337 if (isa<ScalableVectorType>(Val: LoadTy)) {
338 assert(Offset == 0 && "Expected a zero offset for scalable types");
339 return SrcVal;
340 }
341
342 // For the case of a scalable vector being forwarded to a fixed-sized load,
343 // only equal element types are allowed and a @llvm.vector.extract will be
344 // used instead of bitcasts.
345 if (isa<ScalableVectorType>(Val: SrcVal->getType()) &&
346 isa<FixedVectorType>(Val: LoadTy)) {
347 assert(Offset == 0 &&
348 SrcVal->getType()->getScalarType() == LoadTy->getScalarType());
349 return SrcVal;
350 }
351
352 uint64_t StoreSize =
353 (DL.getTypeSizeInBits(Ty: SrcVal->getType()).getFixedValue() + 7) / 8;
354 uint64_t LoadSize = (DL.getTypeSizeInBits(Ty: LoadTy).getFixedValue() + 7) / 8;
355 // Compute which bits of the stored value are being used by the load. Convert
356 // to an integer type to start with.
357 if (SrcVal->getType()->isPtrOrPtrVectorTy())
358 SrcVal =
359 Builder.CreatePtrToInt(V: SrcVal, DestTy: DL.getIntPtrType(SrcVal->getType()));
360 if (!SrcVal->getType()->isIntegerTy())
361 SrcVal =
362 Builder.CreateBitCast(V: SrcVal, DestTy: IntegerType::get(C&: Ctx, NumBits: StoreSize * 8));
363
364 // Shift the bits to the least significant depending on endianness.
365 unsigned ShiftAmt;
366 if (DL.isLittleEndian())
367 ShiftAmt = Offset * 8;
368 else
369 ShiftAmt = (StoreSize - LoadSize - Offset) * 8;
370 if (ShiftAmt)
371 SrcVal = Builder.CreateLShr(LHS: SrcVal,
372 RHS: ConstantInt::get(Ty: SrcVal->getType(), V: ShiftAmt));
373
374 if (LoadSize != StoreSize)
375 SrcVal = Builder.CreateTruncOrBitCast(V: SrcVal,
376 DestTy: IntegerType::get(C&: Ctx, NumBits: LoadSize * 8));
377 return SrcVal;
378}
379
380Value *VNCoercion::getValueForLoad(Value *SrcVal, unsigned Offset, Type *LoadTy,
381 Instruction *InsertPt, Function *F) {
382 const DataLayout &DL = F->getDataLayout();
383#ifndef NDEBUG
384 TypeSize MinSrcValSize = DL.getTypeStoreSize(SrcVal->getType());
385 TypeSize LoadSize = DL.getTypeStoreSize(LoadTy);
386 if (MinSrcValSize.isScalable() && !LoadSize.isScalable())
387 MinSrcValSize =
388 TypeSize::getFixed(MinSrcValSize.getKnownMinValue() *
389 F->getAttributes().getFnAttrs().getVScaleRangeMin());
390 assert((MinSrcValSize.isScalable() || Offset + LoadSize <= MinSrcValSize) &&
391 "Expected Offset + LoadSize <= SrcValSize");
392 assert((!MinSrcValSize.isScalable() ||
393 (Offset == 0 && TypeSize::isKnownLE(LoadSize, MinSrcValSize))) &&
394 "Expected offset of zero and LoadSize <= SrcValSize");
395#endif
396 IRBuilder<> Builder(InsertPt);
397 SrcVal = getStoreValueForLoadHelper(SrcVal, Offset, LoadTy, Builder, DL);
398 return coerceAvailableValueToLoadType(StoredVal: SrcVal, LoadedTy: LoadTy, Helper&: Builder, F);
399}
400
401Constant *VNCoercion::getConstantValueForLoad(Constant *SrcVal, unsigned Offset,
402 Type *LoadTy,
403 const DataLayout &DL) {
404#ifndef NDEBUG
405 unsigned SrcValSize = DL.getTypeStoreSize(SrcVal->getType()).getFixedValue();
406 unsigned LoadSize = DL.getTypeStoreSize(LoadTy).getFixedValue();
407 assert(Offset + LoadSize <= SrcValSize);
408#endif
409 return ConstantFoldLoadFromConst(C: SrcVal, Ty: LoadTy, Offset: APInt(32, Offset), DL);
410}
411
412/// This function is called when we have a
413/// memdep query of a load that ends up being a clobbering mem intrinsic.
414Value *VNCoercion::getMemInstValueForLoad(MemIntrinsic *SrcInst,
415 unsigned Offset, Type *LoadTy,
416 Instruction *InsertPt,
417 const DataLayout &DL) {
418 LLVMContext &Ctx = LoadTy->getContext();
419 uint64_t LoadSize = DL.getTypeSizeInBits(Ty: LoadTy).getFixedValue() / 8;
420 IRBuilder<> Builder(InsertPt);
421
422 // We know that this method is only called when the mem transfer fully
423 // provides the bits for the load.
424 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Val: SrcInst)) {
425 // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
426 // independently of what the offset is.
427 Value *Val = MSI->getValue();
428 if (LoadSize != 1)
429 Val =
430 Builder.CreateZExtOrBitCast(V: Val, DestTy: IntegerType::get(C&: Ctx, NumBits: LoadSize * 8));
431 Value *OneElt = Val;
432
433 // Splat the value out to the right number of bits.
434 for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize;) {
435 // If we can double the number of bytes set, do it.
436 if (NumBytesSet * 2 <= LoadSize) {
437 Value *ShVal = Builder.CreateShl(
438 LHS: Val, RHS: ConstantInt::get(Ty: Val->getType(), V: NumBytesSet * 8));
439 Val = Builder.CreateOr(LHS: Val, RHS: ShVal);
440 NumBytesSet <<= 1;
441 continue;
442 }
443
444 // Otherwise insert one byte at a time.
445 Value *ShVal =
446 Builder.CreateShl(LHS: Val, RHS: ConstantInt::get(Ty: Val->getType(), V: 1 * 8));
447 Val = Builder.CreateOr(LHS: OneElt, RHS: ShVal);
448 ++NumBytesSet;
449 }
450
451 return coerceAvailableValueToLoadType(StoredVal: Val, LoadedTy: LoadTy, Helper&: Builder,
452 F: InsertPt->getFunction());
453 }
454
455 // Otherwise, this is a memcpy/memmove from a constant global.
456 MemTransferInst *MTI = cast<MemTransferInst>(Val: SrcInst);
457 Constant *Src = cast<Constant>(Val: MTI->getSource());
458 unsigned IndexSize = DL.getIndexTypeSizeInBits(Ty: Src->getType());
459 return ConstantFoldLoadFromConstPtr(C: Src, Ty: LoadTy, Offset: APInt(IndexSize, Offset),
460 DL);
461}
462
463Constant *VNCoercion::getConstantMemInstValueForLoad(MemIntrinsic *SrcInst,
464 unsigned Offset,
465 Type *LoadTy,
466 const DataLayout &DL) {
467 LLVMContext &Ctx = LoadTy->getContext();
468 uint64_t LoadSize = DL.getTypeSizeInBits(Ty: LoadTy).getFixedValue() / 8;
469
470 // We know that this method is only called when the mem transfer fully
471 // provides the bits for the load.
472 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Val: SrcInst)) {
473 auto *Val = dyn_cast<ConstantInt>(Val: MSI->getValue());
474 if (!Val)
475 return nullptr;
476
477 Val = ConstantInt::get(Context&: Ctx, V: APInt::getSplat(NewLen: LoadSize * 8, V: Val->getValue()));
478 return ConstantFoldLoadFromConst(C: Val, Ty: LoadTy, DL);
479 }
480
481 // Otherwise, this is a memcpy/memmove from a constant global.
482 MemTransferInst *MTI = cast<MemTransferInst>(Val: SrcInst);
483 Constant *Src = cast<Constant>(Val: MTI->getSource());
484 unsigned IndexSize = DL.getIndexTypeSizeInBits(Ty: Src->getType());
485 return ConstantFoldLoadFromConstPtr(C: Src, Ty: LoadTy, Offset: APInt(IndexSize, Offset),
486 DL);
487}
488