xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/Utils/VNCoercion.cpp (revision 3a9a9c0ca44ec535dcf73fe8462bee458e54814b)
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 #include "llvm/Support/Debug.h"
7 
8 #define DEBUG_TYPE "vncoerce"
9 
10 namespace llvm {
11 namespace VNCoercion {
12 
13 static bool isFirstClassAggregateOrScalableType(Type *Ty) {
14   return Ty->isStructTy() || Ty->isArrayTy() || isa<ScalableVectorType>(Ty);
15 }
16 
17 /// Return true if coerceAvailableValueToLoadType will succeed.
18 bool canCoerceMustAliasedValueToLoad(Value *StoredVal, Type *LoadTy,
19                                      const DataLayout &DL) {
20   Type *StoredTy = StoredVal->getType();
21 
22   if (StoredTy == LoadTy)
23     return true;
24 
25   // If the loaded/stored value is a first class array/struct, or scalable type,
26   // don't try to transform them. We need to be able to bitcast to integer.
27   if (isFirstClassAggregateOrScalableType(LoadTy) ||
28       isFirstClassAggregateOrScalableType(StoredTy))
29     return false;
30 
31   uint64_t StoreSize = DL.getTypeSizeInBits(StoredTy).getFixedSize();
32 
33   // The store size must be byte-aligned to support future type casts.
34   if (llvm::alignTo(StoreSize, 8) != StoreSize)
35     return false;
36 
37   // The store has to be at least as big as the load.
38   if (StoreSize < DL.getTypeSizeInBits(LoadTy).getFixedSize())
39     return false;
40 
41   bool StoredNI = DL.isNonIntegralPointerType(StoredTy->getScalarType());
42   bool LoadNI = DL.isNonIntegralPointerType(LoadTy->getScalarType());
43   // Don't coerce non-integral pointers to integers or vice versa.
44   if (StoredNI != LoadNI) {
45     // As a special case, allow coercion of memset used to initialize
46     // an array w/null.  Despite non-integral pointers not generally having a
47     // specific bit pattern, we do assume null is zero.
48     if (auto *CI = dyn_cast<Constant>(StoredVal))
49       return CI->isNullValue();
50     return false;
51   } else if (StoredNI && LoadNI &&
52              StoredTy->getPointerAddressSpace() !=
53                  LoadTy->getPointerAddressSpace()) {
54     return false;
55   }
56 
57 
58   // The implementation below uses inttoptr for vectors of unequal size; we
59   // can't allow this for non integral pointers. We could teach it to extract
60   // exact subvectors if desired.
61   if (StoredNI && StoreSize != DL.getTypeSizeInBits(LoadTy).getFixedSize())
62     return false;
63 
64   return true;
65 }
66 
67 template <class T, class HelperClass>
68 static T *coerceAvailableValueToLoadTypeHelper(T *StoredVal, Type *LoadedTy,
69                                                HelperClass &Helper,
70                                                const DataLayout &DL) {
71   assert(canCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, DL) &&
72          "precondition violation - materialization can't fail");
73   if (auto *C = dyn_cast<Constant>(StoredVal))
74     StoredVal = ConstantFoldConstant(C, DL);
75 
76   // If this is already the right type, just return it.
77   Type *StoredValTy = StoredVal->getType();
78 
79   uint64_t StoredValSize = DL.getTypeSizeInBits(StoredValTy).getFixedSize();
80   uint64_t LoadedValSize = DL.getTypeSizeInBits(LoadedTy).getFixedSize();
81 
82   // If the store and reload are the same size, we can always reuse it.
83   if (StoredValSize == LoadedValSize) {
84     // Pointer to Pointer -> use bitcast.
85     if (StoredValTy->isPtrOrPtrVectorTy() && LoadedTy->isPtrOrPtrVectorTy()) {
86       StoredVal = Helper.CreateBitCast(StoredVal, LoadedTy);
87     } else {
88       // Convert source pointers to integers, which can be bitcast.
89       if (StoredValTy->isPtrOrPtrVectorTy()) {
90         StoredValTy = DL.getIntPtrType(StoredValTy);
91         StoredVal = Helper.CreatePtrToInt(StoredVal, StoredValTy);
92       }
93 
94       Type *TypeToCastTo = LoadedTy;
95       if (TypeToCastTo->isPtrOrPtrVectorTy())
96         TypeToCastTo = DL.getIntPtrType(TypeToCastTo);
97 
98       if (StoredValTy != TypeToCastTo)
99         StoredVal = Helper.CreateBitCast(StoredVal, TypeToCastTo);
100 
101       // Cast to pointer if the load needs a pointer type.
102       if (LoadedTy->isPtrOrPtrVectorTy())
103         StoredVal = Helper.CreateIntToPtr(StoredVal, LoadedTy);
104     }
105 
106     if (auto *C = dyn_cast<ConstantExpr>(StoredVal))
107       StoredVal = ConstantFoldConstant(C, DL);
108 
109     return StoredVal;
110   }
111   // If the loaded value is smaller than the available value, then we can
112   // extract out a piece from it.  If the available value is too small, then we
113   // can't do anything.
114   assert(StoredValSize >= LoadedValSize &&
115          "canCoerceMustAliasedValueToLoad fail");
116 
117   // Convert source pointers to integers, which can be manipulated.
118   if (StoredValTy->isPtrOrPtrVectorTy()) {
119     StoredValTy = DL.getIntPtrType(StoredValTy);
120     StoredVal = Helper.CreatePtrToInt(StoredVal, StoredValTy);
121   }
122 
123   // Convert vectors and fp to integer, which can be manipulated.
124   if (!StoredValTy->isIntegerTy()) {
125     StoredValTy = IntegerType::get(StoredValTy->getContext(), StoredValSize);
126     StoredVal = Helper.CreateBitCast(StoredVal, StoredValTy);
127   }
128 
129   // If this is a big-endian system, we need to shift the value down to the low
130   // bits so that a truncate will work.
131   if (DL.isBigEndian()) {
132     uint64_t ShiftAmt = DL.getTypeStoreSizeInBits(StoredValTy).getFixedSize() -
133                         DL.getTypeStoreSizeInBits(LoadedTy).getFixedSize();
134     StoredVal = Helper.CreateLShr(
135         StoredVal, ConstantInt::get(StoredVal->getType(), ShiftAmt));
136   }
137 
138   // Truncate the integer to the right size now.
139   Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadedValSize);
140   StoredVal = Helper.CreateTruncOrBitCast(StoredVal, NewIntTy);
141 
142   if (LoadedTy != NewIntTy) {
143     // If the result is a pointer, inttoptr.
144     if (LoadedTy->isPtrOrPtrVectorTy())
145       StoredVal = Helper.CreateIntToPtr(StoredVal, LoadedTy);
146     else
147       // Otherwise, bitcast.
148       StoredVal = Helper.CreateBitCast(StoredVal, LoadedTy);
149   }
150 
151   if (auto *C = dyn_cast<Constant>(StoredVal))
152     StoredVal = ConstantFoldConstant(C, DL);
153 
154   return StoredVal;
155 }
156 
157 /// If we saw a store of a value to memory, and
158 /// then a load from a must-aliased pointer of a different type, try to coerce
159 /// the stored value.  LoadedTy is the type of the load we want to replace.
160 /// IRB is IRBuilder used to insert new instructions.
161 ///
162 /// If we can't do it, return null.
163 Value *coerceAvailableValueToLoadType(Value *StoredVal, Type *LoadedTy,
164                                       IRBuilderBase &IRB,
165                                       const DataLayout &DL) {
166   return coerceAvailableValueToLoadTypeHelper(StoredVal, LoadedTy, IRB, DL);
167 }
168 
169 /// This function is called when we have a memdep query of a load that ends up
170 /// being a clobbering memory write (store, memset, memcpy, memmove).  This
171 /// means that the write *may* provide bits used by the load but we can't be
172 /// sure because the pointers don't must-alias.
173 ///
174 /// Check this case to see if there is anything more we can do before we give
175 /// up.  This returns -1 if we have to give up, or a byte number in the stored
176 /// value of the piece that feeds the load.
177 static int analyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
178                                           Value *WritePtr,
179                                           uint64_t WriteSizeInBits,
180                                           const DataLayout &DL) {
181   // If the loaded/stored value is a first class array/struct, or scalable type,
182   // don't try to transform them. We need to be able to bitcast to integer.
183   if (isFirstClassAggregateOrScalableType(LoadTy))
184     return -1;
185 
186   int64_t StoreOffset = 0, LoadOffset = 0;
187   Value *StoreBase =
188       GetPointerBaseWithConstantOffset(WritePtr, StoreOffset, DL);
189   Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, DL);
190   if (StoreBase != LoadBase)
191     return -1;
192 
193   uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy).getFixedSize();
194 
195   if ((WriteSizeInBits & 7) | (LoadSize & 7))
196     return -1;
197   uint64_t StoreSize = WriteSizeInBits / 8; // Convert to bytes.
198   LoadSize /= 8;
199 
200   // If the Load isn't completely contained within the stored bits, we don't
201   // have all the bits to feed it.  We could do something crazy in the future
202   // (issue a smaller load then merge the bits in) but this seems unlikely to be
203   // valuable.
204   if (StoreOffset > LoadOffset ||
205       StoreOffset + int64_t(StoreSize) < LoadOffset + int64_t(LoadSize))
206     return -1;
207 
208   // Okay, we can do this transformation.  Return the number of bytes into the
209   // store that the load is.
210   return LoadOffset - StoreOffset;
211 }
212 
213 /// This function is called when we have a
214 /// memdep query of a load that ends up being a clobbering store.
215 int analyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
216                                    StoreInst *DepSI, const DataLayout &DL) {
217   auto *StoredVal = DepSI->getValueOperand();
218 
219   // Cannot handle reading from store of first-class aggregate or scalable type.
220   if (isFirstClassAggregateOrScalableType(StoredVal->getType()))
221     return -1;
222 
223   if (!canCoerceMustAliasedValueToLoad(StoredVal, LoadTy, DL))
224     return -1;
225 
226   Value *StorePtr = DepSI->getPointerOperand();
227   uint64_t StoreSize =
228       DL.getTypeSizeInBits(DepSI->getValueOperand()->getType()).getFixedSize();
229   return analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, StorePtr, StoreSize,
230                                         DL);
231 }
232 
233 /// Looks at a memory location for a load (specified by MemLocBase, Offs, and
234 /// Size) and compares it against a load.
235 ///
236 /// If the specified load could be safely widened to a larger integer load
237 /// that is 1) still efficient, 2) safe for the target, and 3) would provide
238 /// the specified memory location value, then this function returns the size
239 /// in bytes of the load width to use.  If not, this returns zero.
240 static unsigned getLoadLoadClobberFullWidthSize(const Value *MemLocBase,
241                                                 int64_t MemLocOffs,
242                                                 unsigned MemLocSize,
243                                                 const LoadInst *LI) {
244   // We can only extend simple integer loads.
245   if (!isa<IntegerType>(LI->getType()) || !LI->isSimple())
246     return 0;
247 
248   // Load widening is hostile to ThreadSanitizer: it may cause false positives
249   // or make the reports more cryptic (access sizes are wrong).
250   if (LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
251     return 0;
252 
253   const DataLayout &DL = LI->getModule()->getDataLayout();
254 
255   // Get the base of this load.
256   int64_t LIOffs = 0;
257   const Value *LIBase =
258       GetPointerBaseWithConstantOffset(LI->getPointerOperand(), LIOffs, DL);
259 
260   // If the two pointers are not based on the same pointer, we can't tell that
261   // they are related.
262   if (LIBase != MemLocBase)
263     return 0;
264 
265   // Okay, the two values are based on the same pointer, but returned as
266   // no-alias.  This happens when we have things like two byte loads at "P+1"
267   // and "P+3".  Check to see if increasing the size of the "LI" load up to its
268   // alignment (or the largest native integer type) will allow us to load all
269   // the bits required by MemLoc.
270 
271   // If MemLoc is before LI, then no widening of LI will help us out.
272   if (MemLocOffs < LIOffs)
273     return 0;
274 
275   // Get the alignment of the load in bytes.  We assume that it is safe to load
276   // any legal integer up to this size without a problem.  For example, if we're
277   // looking at an i8 load on x86-32 that is known 1024 byte aligned, we can
278   // widen it up to an i32 load.  If it is known 2-byte aligned, we can widen it
279   // to i16.
280   unsigned LoadAlign = LI->getAlignment();
281 
282   int64_t MemLocEnd = MemLocOffs + MemLocSize;
283 
284   // If no amount of rounding up will let MemLoc fit into LI, then bail out.
285   if (LIOffs + LoadAlign < MemLocEnd)
286     return 0;
287 
288   // This is the size of the load to try.  Start with the next larger power of
289   // two.
290   unsigned NewLoadByteSize = LI->getType()->getPrimitiveSizeInBits() / 8U;
291   NewLoadByteSize = NextPowerOf2(NewLoadByteSize);
292 
293   while (true) {
294     // If this load size is bigger than our known alignment or would not fit
295     // into a native integer register, then we fail.
296     if (NewLoadByteSize > LoadAlign ||
297         !DL.fitsInLegalInteger(NewLoadByteSize * 8))
298       return 0;
299 
300     if (LIOffs + NewLoadByteSize > MemLocEnd &&
301         (LI->getParent()->getParent()->hasFnAttribute(
302              Attribute::SanitizeAddress) ||
303          LI->getParent()->getParent()->hasFnAttribute(
304              Attribute::SanitizeHWAddress)))
305       // We will be reading past the location accessed by the original program.
306       // While this is safe in a regular build, Address Safety analysis tools
307       // may start reporting false warnings. So, don't do widening.
308       return 0;
309 
310     // If a load of this width would include all of MemLoc, then we succeed.
311     if (LIOffs + NewLoadByteSize >= MemLocEnd)
312       return NewLoadByteSize;
313 
314     NewLoadByteSize <<= 1;
315   }
316 }
317 
318 /// This function is called when we have a
319 /// memdep query of a load that ends up being clobbered by another load.  See if
320 /// the other load can feed into the second load.
321 int analyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr, LoadInst *DepLI,
322                                   const DataLayout &DL) {
323   // Cannot handle reading from store of first-class aggregate yet.
324   if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
325     return -1;
326 
327   if (!canCoerceMustAliasedValueToLoad(DepLI, LoadTy, DL))
328     return -1;
329 
330   Value *DepPtr = DepLI->getPointerOperand();
331   uint64_t DepSize = DL.getTypeSizeInBits(DepLI->getType()).getFixedSize();
332   int R = analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, DL);
333   if (R != -1)
334     return R;
335 
336   // If we have a load/load clobber an DepLI can be widened to cover this load,
337   // then we should widen it!
338   int64_t LoadOffs = 0;
339   const Value *LoadBase =
340       GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, DL);
341   unsigned LoadSize = DL.getTypeStoreSize(LoadTy).getFixedSize();
342 
343   unsigned Size =
344       getLoadLoadClobberFullWidthSize(LoadBase, LoadOffs, LoadSize, DepLI);
345   if (Size == 0)
346     return -1;
347 
348   // Check non-obvious conditions enforced by MDA which we rely on for being
349   // able to materialize this potentially available value
350   assert(DepLI->isSimple() && "Cannot widen volatile/atomic load!");
351   assert(DepLI->getType()->isIntegerTy() && "Can't widen non-integer load");
352 
353   return analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size * 8, DL);
354 }
355 
356 int analyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
357                                      MemIntrinsic *MI, const DataLayout &DL) {
358   // If the mem operation is a non-constant size, we can't handle it.
359   ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
360   if (!SizeCst)
361     return -1;
362   uint64_t MemSizeInBits = SizeCst->getZExtValue() * 8;
363 
364   // If this is memset, we just need to see if the offset is valid in the size
365   // of the memset..
366   if (MI->getIntrinsicID() == Intrinsic::memset) {
367     if (DL.isNonIntegralPointerType(LoadTy->getScalarType())) {
368       auto *CI = dyn_cast<ConstantInt>(cast<MemSetInst>(MI)->getValue());
369       if (!CI || !CI->isZero())
370         return -1;
371     }
372     return analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
373                                           MemSizeInBits, DL);
374   }
375 
376   // If we have a memcpy/memmove, the only case we can handle is if this is a
377   // copy from constant memory.  In that case, we can read directly from the
378   // constant memory.
379   MemTransferInst *MTI = cast<MemTransferInst>(MI);
380 
381   Constant *Src = dyn_cast<Constant>(MTI->getSource());
382   if (!Src)
383     return -1;
384 
385   GlobalVariable *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(Src));
386   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
387     return -1;
388 
389   // See if the access is within the bounds of the transfer.
390   int Offset = analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
391                                               MemSizeInBits, DL);
392   if (Offset == -1)
393     return Offset;
394 
395   // Otherwise, see if we can constant fold a load from the constant with the
396   // offset applied as appropriate.
397   unsigned IndexSize = DL.getIndexTypeSizeInBits(Src->getType());
398   if (ConstantFoldLoadFromConstPtr(Src, LoadTy, APInt(IndexSize, Offset), DL))
399     return Offset;
400   return -1;
401 }
402 
403 template <class T, class HelperClass>
404 static T *getStoreValueForLoadHelper(T *SrcVal, unsigned Offset, Type *LoadTy,
405                                      HelperClass &Helper,
406                                      const DataLayout &DL) {
407   LLVMContext &Ctx = SrcVal->getType()->getContext();
408 
409   // If two pointers are in the same address space, they have the same size,
410   // so we don't need to do any truncation, etc. This avoids introducing
411   // ptrtoint instructions for pointers that may be non-integral.
412   if (SrcVal->getType()->isPointerTy() && LoadTy->isPointerTy() &&
413       cast<PointerType>(SrcVal->getType())->getAddressSpace() ==
414           cast<PointerType>(LoadTy)->getAddressSpace()) {
415     return SrcVal;
416   }
417 
418   uint64_t StoreSize =
419       (DL.getTypeSizeInBits(SrcVal->getType()).getFixedSize() + 7) / 8;
420   uint64_t LoadSize = (DL.getTypeSizeInBits(LoadTy).getFixedSize() + 7) / 8;
421   // Compute which bits of the stored value are being used by the load.  Convert
422   // to an integer type to start with.
423   if (SrcVal->getType()->isPtrOrPtrVectorTy())
424     SrcVal = Helper.CreatePtrToInt(SrcVal, DL.getIntPtrType(SrcVal->getType()));
425   if (!SrcVal->getType()->isIntegerTy())
426     SrcVal = Helper.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize * 8));
427 
428   // Shift the bits to the least significant depending on endianness.
429   unsigned ShiftAmt;
430   if (DL.isLittleEndian())
431     ShiftAmt = Offset * 8;
432   else
433     ShiftAmt = (StoreSize - LoadSize - Offset) * 8;
434   if (ShiftAmt)
435     SrcVal = Helper.CreateLShr(SrcVal,
436                                ConstantInt::get(SrcVal->getType(), ShiftAmt));
437 
438   if (LoadSize != StoreSize)
439     SrcVal = Helper.CreateTruncOrBitCast(SrcVal,
440                                          IntegerType::get(Ctx, LoadSize * 8));
441   return SrcVal;
442 }
443 
444 /// This function is called when we have a memdep query of a load that ends up
445 /// being a clobbering store.  This means that the store provides bits used by
446 /// the load but the pointers don't must-alias.  Check this case to see if
447 /// there is anything more we can do before we give up.
448 Value *getStoreValueForLoad(Value *SrcVal, unsigned Offset, Type *LoadTy,
449                             Instruction *InsertPt, const DataLayout &DL) {
450 
451   IRBuilder<> Builder(InsertPt);
452   SrcVal = getStoreValueForLoadHelper(SrcVal, Offset, LoadTy, Builder, DL);
453   return coerceAvailableValueToLoadTypeHelper(SrcVal, LoadTy, Builder, DL);
454 }
455 
456 Constant *getConstantStoreValueForLoad(Constant *SrcVal, unsigned Offset,
457                                        Type *LoadTy, const DataLayout &DL) {
458   ConstantFolder F;
459   SrcVal = getStoreValueForLoadHelper(SrcVal, Offset, LoadTy, F, DL);
460   return coerceAvailableValueToLoadTypeHelper(SrcVal, LoadTy, F, DL);
461 }
462 
463 /// This function is called when we have a memdep query of a load that ends up
464 /// being a clobbering load.  This means that the load *may* provide bits used
465 /// by the load but we can't be sure because the pointers don't must-alias.
466 /// Check this case to see if there is anything more we can do before we give
467 /// up.
468 Value *getLoadValueForLoad(LoadInst *SrcVal, unsigned Offset, Type *LoadTy,
469                            Instruction *InsertPt, const DataLayout &DL) {
470   // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
471   // widen SrcVal out to a larger load.
472   unsigned SrcValStoreSize =
473       DL.getTypeStoreSize(SrcVal->getType()).getFixedSize();
474   unsigned LoadSize = DL.getTypeStoreSize(LoadTy).getFixedSize();
475   if (Offset + LoadSize > SrcValStoreSize) {
476     assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
477     assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
478     // If we have a load/load clobber an DepLI can be widened to cover this
479     // load, then we should widen it to the next power of 2 size big enough!
480     unsigned NewLoadSize = Offset + LoadSize;
481     if (!isPowerOf2_32(NewLoadSize))
482       NewLoadSize = NextPowerOf2(NewLoadSize);
483 
484     Value *PtrVal = SrcVal->getPointerOperand();
485     // Insert the new load after the old load.  This ensures that subsequent
486     // memdep queries will find the new load.  We can't easily remove the old
487     // load completely because it is already in the value numbering table.
488     IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
489     Type *DestTy = IntegerType::get(LoadTy->getContext(), NewLoadSize * 8);
490     Type *DestPTy =
491         PointerType::get(DestTy, PtrVal->getType()->getPointerAddressSpace());
492     Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
493     PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
494     LoadInst *NewLoad = Builder.CreateLoad(DestTy, PtrVal);
495     NewLoad->takeName(SrcVal);
496     NewLoad->setAlignment(SrcVal->getAlign());
497 
498     LLVM_DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
499     LLVM_DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
500 
501     // Replace uses of the original load with the wider load.  On a big endian
502     // system, we need to shift down to get the relevant bits.
503     Value *RV = NewLoad;
504     if (DL.isBigEndian())
505       RV = Builder.CreateLShr(RV, (NewLoadSize - SrcValStoreSize) * 8);
506     RV = Builder.CreateTrunc(RV, SrcVal->getType());
507     SrcVal->replaceAllUsesWith(RV);
508 
509     SrcVal = NewLoad;
510   }
511 
512   return getStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, DL);
513 }
514 
515 Constant *getConstantLoadValueForLoad(Constant *SrcVal, unsigned Offset,
516                                       Type *LoadTy, const DataLayout &DL) {
517   unsigned SrcValStoreSize =
518       DL.getTypeStoreSize(SrcVal->getType()).getFixedSize();
519   unsigned LoadSize = DL.getTypeStoreSize(LoadTy).getFixedSize();
520   if (Offset + LoadSize > SrcValStoreSize)
521     return nullptr;
522   return getConstantStoreValueForLoad(SrcVal, Offset, LoadTy, DL);
523 }
524 
525 template <class T, class HelperClass>
526 T *getMemInstValueForLoadHelper(MemIntrinsic *SrcInst, unsigned Offset,
527                                 Type *LoadTy, HelperClass &Helper,
528                                 const DataLayout &DL) {
529   LLVMContext &Ctx = LoadTy->getContext();
530   uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy).getFixedSize() / 8;
531 
532   // We know that this method is only called when the mem transfer fully
533   // provides the bits for the load.
534   if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
535     // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
536     // independently of what the offset is.
537     T *Val = cast<T>(MSI->getValue());
538     if (LoadSize != 1)
539       Val =
540           Helper.CreateZExtOrBitCast(Val, IntegerType::get(Ctx, LoadSize * 8));
541     T *OneElt = Val;
542 
543     // Splat the value out to the right number of bits.
544     for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize;) {
545       // If we can double the number of bytes set, do it.
546       if (NumBytesSet * 2 <= LoadSize) {
547         T *ShVal = Helper.CreateShl(
548             Val, ConstantInt::get(Val->getType(), NumBytesSet * 8));
549         Val = Helper.CreateOr(Val, ShVal);
550         NumBytesSet <<= 1;
551         continue;
552       }
553 
554       // Otherwise insert one byte at a time.
555       T *ShVal = Helper.CreateShl(Val, ConstantInt::get(Val->getType(), 1 * 8));
556       Val = Helper.CreateOr(OneElt, ShVal);
557       ++NumBytesSet;
558     }
559 
560     return coerceAvailableValueToLoadTypeHelper(Val, LoadTy, Helper, DL);
561   }
562 
563   // Otherwise, this is a memcpy/memmove from a constant global.
564   MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
565   Constant *Src = cast<Constant>(MTI->getSource());
566 
567   // Otherwise, see if we can constant fold a load from the constant with the
568   // offset applied as appropriate.
569   unsigned IndexSize = DL.getIndexTypeSizeInBits(Src->getType());
570   return ConstantFoldLoadFromConstPtr(
571       Src, LoadTy, APInt(IndexSize, Offset), DL);
572 }
573 
574 /// This function is called when we have a
575 /// memdep query of a load that ends up being a clobbering mem intrinsic.
576 Value *getMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
577                               Type *LoadTy, Instruction *InsertPt,
578                               const DataLayout &DL) {
579   IRBuilder<> Builder(InsertPt);
580   return getMemInstValueForLoadHelper<Value, IRBuilder<>>(SrcInst, Offset,
581                                                           LoadTy, Builder, DL);
582 }
583 
584 Constant *getConstantMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
585                                          Type *LoadTy, const DataLayout &DL) {
586   // The only case analyzeLoadFromClobberingMemInst cannot be converted to a
587   // constant is when it's a memset of a non-constant.
588   if (auto *MSI = dyn_cast<MemSetInst>(SrcInst))
589     if (!isa<Constant>(MSI->getValue()))
590       return nullptr;
591   ConstantFolder F;
592   return getMemInstValueForLoadHelper<Constant, ConstantFolder>(SrcInst, Offset,
593                                                                 LoadTy, F, DL);
594 }
595 } // namespace VNCoercion
596 } // namespace llvm
597