LLVM  15.0.0git
VNCoercion.cpp
Go to the documentation of this file.
4 #include "llvm/IR/IRBuilder.h"
6 #include "llvm/Support/Debug.h"
7 
8 #define DEBUG_TYPE "vncoerce"
9 
10 namespace llvm {
11 namespace VNCoercion {
12 
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.
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.
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.
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.
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 =
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 &&
302  Attribute::SanitizeAddress) ||
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 
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 
457  Type *LoadTy, const DataLayout &DL) {
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 
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());
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 
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;
592  return getMemInstValueForLoadHelper<Constant, ConstantFolder>(SrcInst, Offset,
593  LoadTy, F, DL);
594 }
595 } // namespace VNCoercion
596 } // namespace llvm
llvm::alignTo
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:148
llvm::VNCoercion::analyzeLoadFromClobberingMemInst
int analyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr, MemIntrinsic *DepMI, const DataLayout &DL)
This function determines whether a value for the pointer LoadPtr can be extracted from the memory int...
Definition: VNCoercion.cpp:356
MI
IRTranslator LLVM IR MI
Definition: IRTranslator.cpp:104
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:17
llvm::Instruction::getModule
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:65
llvm::DataLayout
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:113
llvm::VNCoercion::getStoreValueForLoad
Value * getStoreValueForLoad(Value *SrcVal, unsigned Offset, Type *LoadTy, Instruction *InsertPt, const DataLayout &DL)
If analyzeLoadFromClobberingStore returned an offset, this function can be used to actually perform t...
Definition: VNCoercion.cpp:448
llvm::BasicBlock::iterator
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:87
llvm::BasicBlock::getParent
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:104
IntrinsicInst.h
llvm::Type::isPointerTy
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:218
llvm::VNCoercion::analyzeLoadFromClobberingWrite
static int analyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr, Value *WritePtr, uint64_t WriteSizeInBits, const DataLayout &DL)
This function is called when we have a memdep query of a load that ends up being a clobbering memory ...
Definition: VNCoercion.cpp:177
llvm::MemTransferInst
This class wraps the llvm.memcpy/memmove intrinsics.
Definition: IntrinsicInst.h:1005
llvm::PointerType::get
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
Definition: Type.cpp:727
llvm::Type::getScalarType
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:309
llvm::Type::getPointerAddressSpace
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:729
llvm::IRBuilder<>
llvm::GlobalVariable
Definition: GlobalVariable.h:39
ValueTracking.h
llvm::Type
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
llvm::MemIntrinsic
This is the common base class for memset/memcpy/memmove.
Definition: IntrinsicInst.h:962
T
#define T
Definition: Mips16ISelLowering.cpp:341
llvm::VNCoercion::coerceAvailableValueToLoadType
Value * coerceAvailableValueToLoadType(Value *StoredVal, Type *LoadedTy, IRBuilderBase &IRB, const DataLayout &DL)
If we saw a store of a value to memory, and then a load from a must-aliased pointer of a different ty...
Definition: VNCoercion.cpp:163
llvm::LoadInst::getPointerOperand
Value * getPointerOperand()
Definition: Instructions.h:268
llvm::isPowerOf2_32
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:491
llvm::LoadInst::getAlign
Align getAlign() const
Return the alignment of the access that is being performed.
Definition: Instructions.h:224
ConstantFolding.h
LLVM_DEBUG
#define LLVM_DEBUG(X)
Definition: Debug.h:101
F
#define F(x, y, z)
Definition: MD5.cpp:55
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
llvm::ConstantInt
This is the shared class of boolean and integer constants.
Definition: Constants.h:79
llvm::Type::isArrayTy
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition: Type.h:215
llvm::ConstantFolder
ConstantFolder - Create constants with minimum, target independent, folding.
Definition: ConstantFolder.h:28
llvm::StoreInst::getValueOperand
Value * getValueOperand()
Definition: Instructions.h:399
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
llvm::NextPowerOf2
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition: MathExtras.h:710
llvm::Instruction
Definition: Instruction.h:42
llvm::ConstantInt::get
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:919
llvm::getUnderlyingObject
const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value,...
Definition: ValueTracking.cpp:4343
llvm::LoadInst::getAlignment
uint64_t getAlignment() const
Return the alignment of the access that is being performed.
Definition: Instructions.h:221
llvm::MemSetInst
This class wraps the llvm.memset intrinsic.
Definition: IntrinsicInst.h:993
llvm::VNCoercion::coerceAvailableValueToLoadTypeHelper
static T * coerceAvailableValueToLoadTypeHelper(T *StoredVal, Type *LoadedTy, HelperClass &Helper, const DataLayout &DL)
Definition: VNCoercion.cpp:68
llvm::VNCoercion::getMemInstValueForLoad
Value * getMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset, Type *LoadTy, Instruction *InsertPt, const DataLayout &DL)
If analyzeLoadFromClobberingMemInst returned an offset, this function can be used to actually perform...
Definition: VNCoercion.cpp:576
llvm::Type::isIntegerTy
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:191
llvm::Function::hasFnAttribute
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.cpp:625
llvm::StoreInst
An instruction for storing to memory.
Definition: Instructions.h:305
llvm::Constant
This is an important base class in LLVM.
Definition: Constant.h:41
uint64_t
llvm::GlobalVariable::hasDefinitiveInitializer
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
Definition: GlobalVariable.h:109
llvm::LLVMContext
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
VNCoercion.h
llvm::LoadInst::setAlignment
void setAlignment(Align Align)
Definition: Instructions.h:228
llvm::VNCoercion::getMemInstValueForLoadHelper
T * getMemInstValueForLoadHelper(MemIntrinsic *SrcInst, unsigned Offset, Type *LoadTy, HelperClass &Helper, const DataLayout &DL)
Definition: VNCoercion.cpp:526
IRBuilder.h
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Builder
assume Assume Builder
Definition: AssumeBundleBuilder.cpp:651
llvm::APInt
Class for arbitrary precision integers.
Definition: APInt.h:75
llvm::VNCoercion::getConstantLoadValueForLoad
Constant * getConstantLoadValueForLoad(Constant *SrcVal, unsigned Offset, Type *LoadTy, const DataLayout &DL)
Definition: VNCoercion.cpp:515
llvm::LoadInst::isSimple
bool isSimple() const
Definition: Instructions.h:260
llvm::Value::getType
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
llvm::Value::replaceAllUsesWith
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:529
llvm::IRBuilderBase
Common base class shared among various IRBuilders.
Definition: IRBuilder.h:93
DL
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Definition: AArch64SLSHardening.cpp:76
llvm::Type::isPtrOrPtrVectorTy
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition: Type.h:224
llvm::VNCoercion::isFirstClassAggregateOrScalableType
static bool isFirstClassAggregateOrScalableType(Type *Ty)
Definition: VNCoercion.cpp:13
llvm::Type::getContext
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:128
llvm::LoadInst
An instruction for reading from memory.
Definition: Instructions.h:176
llvm::VNCoercion::getLoadValueForLoad
Value * getLoadValueForLoad(LoadInst *SrcVal, unsigned Offset, Type *LoadTy, Instruction *InsertPt, const DataLayout &DL)
If analyzeLoadFromClobberingLoad returned an offset, this function can be used to actually perform th...
Definition: VNCoercion.cpp:468
llvm::ConstantInt::getZExtValue
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:142
llvm::ConstantFoldLoadFromConstPtr
Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, APInt Offset, const DataLayout &DL)
Return the value that a load from C with offset Offset would produce if it is constant and determinab...
Definition: ConstantFolding.cpp:697
llvm::VNCoercion::getConstantMemInstValueForLoad
Constant * getConstantMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset, Type *LoadTy, const DataLayout &DL)
Definition: VNCoercion.cpp:584
llvm::VNCoercion::getLoadLoadClobberFullWidthSize
static unsigned getLoadLoadClobberFullWidthSize(const Value *MemLocBase, int64_t MemLocOffs, unsigned MemLocSize, const LoadInst *LI)
Looks at a memory location for a load (specified by MemLocBase, Offs, and Size) and compares it again...
Definition: VNCoercion.cpp:240
llvm::VNCoercion::analyzeLoadFromClobberingStore
int analyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr, StoreInst *DepSI, const DataLayout &DL)
This function determines whether a value for the pointer LoadPtr can be extracted from the store at D...
Definition: VNCoercion.cpp:215
llvm::GetPointerBaseWithConstantOffset
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
Definition: ValueTracking.h:278
llvm::VNCoercion::canCoerceMustAliasedValueToLoad
bool canCoerceMustAliasedValueToLoad(Value *StoredVal, Type *LoadTy, const DataLayout &DL)
Return true if CoerceAvailableValueToLoadType would succeed if it was called.
Definition: VNCoercion.cpp:18
llvm::VNCoercion::getConstantStoreValueForLoad
Constant * getConstantStoreValueForLoad(Constant *SrcVal, unsigned Offset, Type *LoadTy, const DataLayout &DL)
Definition: VNCoercion.cpp:456
llvm::Type::isStructTy
bool isStructTy() const
True if this is an instance of StructType.
Definition: Type.h:212
llvm::Instruction::getDebugLoc
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:367
llvm::StoreInst::getPointerOperand
Value * getPointerOperand()
Definition: Instructions.h:402
llvm::GlobalVariable::isConstant
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
Definition: GlobalVariable.h:152
llvm::Instruction::getParent
const BasicBlock * getParent() const
Definition: Instruction.h:91
llvm::VNCoercion::analyzeLoadFromClobberingLoad
int analyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr, LoadInst *DepLI, const DataLayout &DL)
This function determines whether a value for the pointer LoadPtr can be extracted from the load at De...
Definition: VNCoercion.cpp:321
llvm::ConstantFoldConstant
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
Definition: ConstantFolding.cpp:1159
llvm::Module::getDataLayout
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:398
llvm::IntegerType::get
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:311
llvm::Value::takeName
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:378
llvm::VNCoercion::getStoreValueForLoadHelper
static T * getStoreValueForLoadHelper(T *SrcVal, unsigned Offset, Type *LoadTy, HelperClass &Helper, const DataLayout &DL)
Definition: VNCoercion.cpp:404
llvm::Value
LLVM Value Representation.
Definition: Value.h:74
Debug.h
llvm::Type::getPrimitiveSizeInBits
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:164
llvm::MemTransferBase::getSource
Value * getSource() const
This is just like getRawSource, but it strips off any cast instructions that feed it,...
Definition: IntrinsicInst.h:805