blob: b317aa7e38a09b9f989ab5f545731b1dde3133af [file] [log] [blame]
Daniel Berlin5ac91792017-03-10 04:54:10 +00001#include "llvm/Transforms/Utils/VNCoercion.h"
2#include "llvm/Analysis/AliasAnalysis.h"
3#include "llvm/Analysis/ConstantFolding.h"
4#include "llvm/Analysis/MemoryDependenceAnalysis.h"
5#include "llvm/Analysis/ValueTracking.h"
6#include "llvm/IR/IRBuilder.h"
7#include "llvm/IR/IntrinsicInst.h"
8#include "llvm/Support/Debug.h"
9
10#define DEBUG_TYPE "vncoerce"
11namespace llvm {
12namespace VNCoercion {
13
14/// Return true if coerceAvailableValueToLoadType will succeed.
15bool canCoerceMustAliasedValueToLoad(Value *StoredVal, Type *LoadTy,
16 const DataLayout &DL) {
17 // If the loaded or stored value is an first class array or struct, don't try
18 // to transform them. We need to be able to bitcast to integer.
19 if (LoadTy->isStructTy() || LoadTy->isArrayTy() ||
20 StoredVal->getType()->isStructTy() || StoredVal->getType()->isArrayTy())
21 return false;
22
23 // The store has to be at least as big as the load.
24 if (DL.getTypeSizeInBits(StoredVal->getType()) < DL.getTypeSizeInBits(LoadTy))
25 return false;
26
27 return true;
28}
29
30/// If we saw a store of a value to memory, and
31/// then a load from a must-aliased pointer of a different type, try to coerce
32/// the stored value. LoadedTy is the type of the load we want to replace.
33/// IRB is IRBuilder used to insert new instructions.
34///
35/// If we can't do it, return null.
36Value *coerceAvailableValueToLoadType(Value *StoredVal, Type *LoadedTy,
37 IRBuilder<> &IRB, const DataLayout &DL) {
38 assert(canCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, DL) &&
39 "precondition violation - materialization can't fail");
40
41 if (auto *C = dyn_cast<Constant>(StoredVal))
42 if (auto *FoldedStoredVal = ConstantFoldConstant(C, DL))
43 StoredVal = FoldedStoredVal;
44
45 // If this is already the right type, just return it.
46 Type *StoredValTy = StoredVal->getType();
47
48 uint64_t StoredValSize = DL.getTypeSizeInBits(StoredValTy);
49 uint64_t LoadedValSize = DL.getTypeSizeInBits(LoadedTy);
50
51 // If the store and reload are the same size, we can always reuse it.
52 if (StoredValSize == LoadedValSize) {
53 // Pointer to Pointer -> use bitcast.
54 if (StoredValTy->getScalarType()->isPointerTy() &&
55 LoadedTy->getScalarType()->isPointerTy()) {
56 StoredVal = IRB.CreateBitCast(StoredVal, LoadedTy);
57 } else {
58 // Convert source pointers to integers, which can be bitcast.
59 if (StoredValTy->getScalarType()->isPointerTy()) {
60 StoredValTy = DL.getIntPtrType(StoredValTy);
61 StoredVal = IRB.CreatePtrToInt(StoredVal, StoredValTy);
62 }
63
64 Type *TypeToCastTo = LoadedTy;
65 if (TypeToCastTo->getScalarType()->isPointerTy())
66 TypeToCastTo = DL.getIntPtrType(TypeToCastTo);
67
68 if (StoredValTy != TypeToCastTo)
69 StoredVal = IRB.CreateBitCast(StoredVal, TypeToCastTo);
70
71 // Cast to pointer if the load needs a pointer type.
72 if (LoadedTy->getScalarType()->isPointerTy())
73 StoredVal = IRB.CreateIntToPtr(StoredVal, LoadedTy);
74 }
75
76 if (auto *C = dyn_cast<ConstantExpr>(StoredVal))
77 if (auto *FoldedStoredVal = ConstantFoldConstant(C, DL))
78 StoredVal = FoldedStoredVal;
79
80 return StoredVal;
81 }
82
83 // If the loaded value is smaller than the available value, then we can
84 // extract out a piece from it. If the available value is too small, then we
85 // can't do anything.
86 assert(StoredValSize >= LoadedValSize &&
87 "canCoerceMustAliasedValueToLoad fail");
88
89 // Convert source pointers to integers, which can be manipulated.
90 if (StoredValTy->getScalarType()->isPointerTy()) {
91 StoredValTy = DL.getIntPtrType(StoredValTy);
92 StoredVal = IRB.CreatePtrToInt(StoredVal, StoredValTy);
93 }
94
95 // Convert vectors and fp to integer, which can be manipulated.
96 if (!StoredValTy->isIntegerTy()) {
97 StoredValTy = IntegerType::get(StoredValTy->getContext(), StoredValSize);
98 StoredVal = IRB.CreateBitCast(StoredVal, StoredValTy);
99 }
100
101 // If this is a big-endian system, we need to shift the value down to the low
102 // bits so that a truncate will work.
103 if (DL.isBigEndian()) {
104 uint64_t ShiftAmt = DL.getTypeStoreSizeInBits(StoredValTy) -
105 DL.getTypeStoreSizeInBits(LoadedTy);
106 StoredVal = IRB.CreateLShr(StoredVal, ShiftAmt, "tmp");
107 }
108
109 // Truncate the integer to the right size now.
110 Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadedValSize);
111 StoredVal = IRB.CreateTrunc(StoredVal, NewIntTy, "trunc");
112
113 if (LoadedTy != NewIntTy) {
114 // If the result is a pointer, inttoptr.
115 if (LoadedTy->getScalarType()->isPointerTy())
116 StoredVal = IRB.CreateIntToPtr(StoredVal, LoadedTy, "inttoptr");
117 else
118 // Otherwise, bitcast.
119 StoredVal = IRB.CreateBitCast(StoredVal, LoadedTy, "bitcast");
120 }
121
122 if (auto *C = dyn_cast<Constant>(StoredVal))
123 if (auto *FoldedStoredVal = ConstantFoldConstant(C, DL))
124 StoredVal = FoldedStoredVal;
125
126 return StoredVal;
127}
128
129/// This function is called when we have a
130/// memdep query of a load that ends up being a clobbering memory write (store,
131/// memset, memcpy, memmove). This means that the write *may* provide bits used
132/// by the load but we can't be sure because the pointers don't mustalias.
133///
134/// Check this case to see if there is anything more we can do before we give
135/// up. This returns -1 if we have to give up, or a byte number in the stored
136/// value of the piece that feeds the load.
137static int analyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
138 Value *WritePtr,
139 uint64_t WriteSizeInBits,
140 const DataLayout &DL) {
141 // If the loaded or stored value is a first class array or struct, don't try
142 // to transform them. We need to be able to bitcast to integer.
143 if (LoadTy->isStructTy() || LoadTy->isArrayTy())
144 return -1;
145
146 int64_t StoreOffset = 0, LoadOffset = 0;
147 Value *StoreBase =
148 GetPointerBaseWithConstantOffset(WritePtr, StoreOffset, DL);
149 Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, DL);
150 if (StoreBase != LoadBase)
151 return -1;
152
153 // If the load and store are to the exact same address, they should have been
154 // a must alias. AA must have gotten confused.
155 // FIXME: Study to see if/when this happens. One case is forwarding a memset
156 // to a load from the base of the memset.
157
158 // If the load and store don't overlap at all, the store doesn't provide
159 // anything to the load. In this case, they really don't alias at all, AA
160 // must have gotten confused.
161 uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy);
162
163 if ((WriteSizeInBits & 7) | (LoadSize & 7))
164 return -1;
165 uint64_t StoreSize = WriteSizeInBits / 8; // Convert to bytes.
166 LoadSize /= 8;
167
168 bool isAAFailure = false;
169 if (StoreOffset < LoadOffset)
170 isAAFailure = StoreOffset + int64_t(StoreSize) <= LoadOffset;
171 else
172 isAAFailure = LoadOffset + int64_t(LoadSize) <= StoreOffset;
173
174 if (isAAFailure)
175 return -1;
176
177 // If the Load isn't completely contained within the stored bits, we don't
178 // have all the bits to feed it. We could do something crazy in the future
179 // (issue a smaller load then merge the bits in) but this seems unlikely to be
180 // valuable.
181 if (StoreOffset > LoadOffset ||
182 StoreOffset + StoreSize < LoadOffset + LoadSize)
183 return -1;
184
185 // Okay, we can do this transformation. Return the number of bytes into the
186 // store that the load is.
187 return LoadOffset - StoreOffset;
188}
189
190/// This function is called when we have a
191/// memdep query of a load that ends up being a clobbering store.
192int analyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
Daniel Berlincd07a0f2017-03-11 00:51:01 +0000193 StoreInst *DepSI, const DataLayout &DL) {
Daniel Berlin5ac91792017-03-10 04:54:10 +0000194 // Cannot handle reading from store of first-class aggregate yet.
195 if (DepSI->getValueOperand()->getType()->isStructTy() ||
196 DepSI->getValueOperand()->getType()->isArrayTy())
197 return -1;
198
Daniel Berlin5ac91792017-03-10 04:54:10 +0000199 Value *StorePtr = DepSI->getPointerOperand();
200 uint64_t StoreSize =
201 DL.getTypeSizeInBits(DepSI->getValueOperand()->getType());
202 return analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, StorePtr, StoreSize,
203 DL);
204}
205
206/// This function is called when we have a
207/// memdep query of a load that ends up being clobbered by another load. See if
208/// the other load can feed into the second load.
209int analyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr, LoadInst *DepLI,
210 const DataLayout &DL) {
211 // Cannot handle reading from store of first-class aggregate yet.
212 if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
213 return -1;
214
215 Value *DepPtr = DepLI->getPointerOperand();
216 uint64_t DepSize = DL.getTypeSizeInBits(DepLI->getType());
217 int R = analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, DL);
218 if (R != -1)
219 return R;
220
221 // If we have a load/load clobber an DepLI can be widened to cover this load,
222 // then we should widen it!
223 int64_t LoadOffs = 0;
224 const Value *LoadBase =
225 GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, DL);
226 unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
227
228 unsigned Size = MemoryDependenceResults::getLoadLoadClobberFullWidthSize(
229 LoadBase, LoadOffs, LoadSize, DepLI);
230 if (Size == 0)
231 return -1;
232
233 // Check non-obvious conditions enforced by MDA which we rely on for being
234 // able to materialize this potentially available value
235 assert(DepLI->isSimple() && "Cannot widen volatile/atomic load!");
236 assert(DepLI->getType()->isIntegerTy() && "Can't widen non-integer load");
237
238 return analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size * 8, DL);
239}
240
241int analyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
242 MemIntrinsic *MI, const DataLayout &DL) {
243 // If the mem operation is a non-constant size, we can't handle it.
244 ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
245 if (!SizeCst)
246 return -1;
247 uint64_t MemSizeInBits = SizeCst->getZExtValue() * 8;
248
249 // If this is memset, we just need to see if the offset is valid in the size
250 // of the memset..
251 if (MI->getIntrinsicID() == Intrinsic::memset)
252 return analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
253 MemSizeInBits, DL);
254
255 // If we have a memcpy/memmove, the only case we can handle is if this is a
256 // copy from constant memory. In that case, we can read directly from the
257 // constant memory.
258 MemTransferInst *MTI = cast<MemTransferInst>(MI);
259
260 Constant *Src = dyn_cast<Constant>(MTI->getSource());
261 if (!Src)
262 return -1;
263
264 GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, DL));
265 if (!GV || !GV->isConstant())
266 return -1;
267
268 // See if the access is within the bounds of the transfer.
269 int Offset = analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
270 MemSizeInBits, DL);
271 if (Offset == -1)
272 return Offset;
273
274 unsigned AS = Src->getType()->getPointerAddressSpace();
275 // Otherwise, see if we can constant fold a load from the constant with the
276 // offset applied as appropriate.
277 Src =
278 ConstantExpr::getBitCast(Src, Type::getInt8PtrTy(Src->getContext(), AS));
279 Constant *OffsetCst =
280 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
281 Src = ConstantExpr::getGetElementPtr(Type::getInt8Ty(Src->getContext()), Src,
282 OffsetCst);
283 Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
284 if (ConstantFoldLoadFromConstPtr(Src, LoadTy, DL))
285 return Offset;
286 return -1;
287}
288
289/// This function is called when we have a
290/// memdep query of a load that ends up being a clobbering store. This means
291/// that the store provides bits used by the load but we the pointers don't
292/// mustalias. Check this case to see if there is anything more we can do
293/// before we give up.
294Value *getStoreValueForLoad(Value *SrcVal, unsigned Offset, Type *LoadTy,
295 Instruction *InsertPt, const DataLayout &DL) {
296 LLVMContext &Ctx = SrcVal->getType()->getContext();
297
298 uint64_t StoreSize = (DL.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
299 uint64_t LoadSize = (DL.getTypeSizeInBits(LoadTy) + 7) / 8;
300
301 IRBuilder<> Builder(InsertPt);
302
303 // Compute which bits of the stored value are being used by the load. Convert
304 // to an integer type to start with.
305 if (SrcVal->getType()->getScalarType()->isPointerTy())
306 SrcVal =
307 Builder.CreatePtrToInt(SrcVal, DL.getIntPtrType(SrcVal->getType()));
308 if (!SrcVal->getType()->isIntegerTy())
309 SrcVal =
310 Builder.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize * 8));
311
312 // Shift the bits to the least significant depending on endianness.
313 unsigned ShiftAmt;
314 if (DL.isLittleEndian())
315 ShiftAmt = Offset * 8;
316 else
317 ShiftAmt = (StoreSize - LoadSize - Offset) * 8;
318
319 if (ShiftAmt)
320 SrcVal = Builder.CreateLShr(SrcVal, ShiftAmt);
321
322 if (LoadSize != StoreSize)
323 SrcVal = Builder.CreateTrunc(SrcVal, IntegerType::get(Ctx, LoadSize * 8));
324
325 return coerceAvailableValueToLoadType(SrcVal, LoadTy, Builder, DL);
326}
327
328/// This function is called when we have a
329/// memdep query of a load that ends up being a clobbering load. This means
330/// that the load *may* provide bits used by the load but we can't be sure
331/// because the pointers don't mustalias. Check this case to see if there is
332/// anything more we can do before we give up.
333Value *getLoadValueForLoad(LoadInst *SrcVal, unsigned Offset, Type *LoadTy,
334 Instruction *InsertPt) {
335
336 const DataLayout &DL = SrcVal->getModule()->getDataLayout();
337 // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
338 // widen SrcVal out to a larger load.
339 unsigned SrcValStoreSize = DL.getTypeStoreSize(SrcVal->getType());
340 unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
341 if (Offset + LoadSize > SrcValStoreSize) {
342 assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
343 assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
344 // If we have a load/load clobber an DepLI can be widened to cover this
345 // load, then we should widen it to the next power of 2 size big enough!
346 unsigned NewLoadSize = Offset + LoadSize;
347 if (!isPowerOf2_32(NewLoadSize))
348 NewLoadSize = NextPowerOf2(NewLoadSize);
349
350 Value *PtrVal = SrcVal->getPointerOperand();
351
352 // Insert the new load after the old load. This ensures that subsequent
353 // memdep queries will find the new load. We can't easily remove the old
354 // load completely because it is already in the value numbering table.
355 IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
356 Type *DestPTy = IntegerType::get(LoadTy->getContext(), NewLoadSize * 8);
357 DestPTy =
358 PointerType::get(DestPTy, PtrVal->getType()->getPointerAddressSpace());
359 Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
360 PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
361 LoadInst *NewLoad = Builder.CreateLoad(PtrVal);
362 NewLoad->takeName(SrcVal);
363 NewLoad->setAlignment(SrcVal->getAlignment());
364
365 DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
366 DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
367
368 // Replace uses of the original load with the wider load. On a big endian
369 // system, we need to shift down to get the relevant bits.
370 Value *RV = NewLoad;
371 if (DL.isBigEndian())
372 RV = Builder.CreateLShr(RV, (NewLoadSize - SrcValStoreSize) * 8);
373 RV = Builder.CreateTrunc(RV, SrcVal->getType());
374 SrcVal->replaceAllUsesWith(RV);
375
376 SrcVal = NewLoad;
377 }
378
379 return getStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, DL);
380}
381
382/// This function is called when we have a
383/// memdep query of a load that ends up being a clobbering mem intrinsic.
384Value *getMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
385 Type *LoadTy, Instruction *InsertPt,
386 const DataLayout &DL) {
387 LLVMContext &Ctx = LoadTy->getContext();
388 uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy) / 8;
389
390 IRBuilder<> Builder(InsertPt);
391
392 // We know that this method is only called when the mem transfer fully
393 // provides the bits for the load.
394 if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
395 // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
396 // independently of what the offset is.
397 Value *Val = MSI->getValue();
398 if (LoadSize != 1)
399 Val = Builder.CreateZExt(Val, IntegerType::get(Ctx, LoadSize * 8));
400
401 Value *OneElt = Val;
402
403 // Splat the value out to the right number of bits.
404 for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize;) {
405 // If we can double the number of bytes set, do it.
406 if (NumBytesSet * 2 <= LoadSize) {
407 Value *ShVal = Builder.CreateShl(Val, NumBytesSet * 8);
408 Val = Builder.CreateOr(Val, ShVal);
409 NumBytesSet <<= 1;
410 continue;
411 }
412
413 // Otherwise insert one byte at a time.
414 Value *ShVal = Builder.CreateShl(Val, 1 * 8);
415 Val = Builder.CreateOr(OneElt, ShVal);
416 ++NumBytesSet;
417 }
418
419 return coerceAvailableValueToLoadType(Val, LoadTy, Builder, DL);
420 }
421
422 // Otherwise, this is a memcpy/memmove from a constant global.
423 MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
424 Constant *Src = cast<Constant>(MTI->getSource());
425 unsigned AS = Src->getType()->getPointerAddressSpace();
426
427 // Otherwise, see if we can constant fold a load from the constant with the
428 // offset applied as appropriate.
429 Src =
430 ConstantExpr::getBitCast(Src, Type::getInt8PtrTy(Src->getContext(), AS));
431 Constant *OffsetCst =
432 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
433 Src = ConstantExpr::getGetElementPtr(Type::getInt8Ty(Src->getContext()), Src,
434 OffsetCst);
435 Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
436 return ConstantFoldLoadFromConstPtr(Src, LoadTy, DL);
437}
438} // namespace VNCoercion
439} // namespace llvm