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