LLVM  3.7.0
InstCombineLoadStoreAlloca.cpp
Go to the documentation of this file.
1 //===- InstCombineLoadStoreAlloca.cpp -------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the visit functions for load, store and alloca.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "InstCombineInternal.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/Loads.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/MDBuilder.h"
23 using namespace llvm;
24 
25 #define DEBUG_TYPE "instcombine"
26 
27 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
28 STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
29 
30 /// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
31 /// some part of a constant global variable. This intentionally only accepts
32 /// constant expressions because we can't rewrite arbitrary instructions.
33 static bool pointsToConstantGlobal(Value *V) {
34  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
35  return GV->isConstant();
36 
37  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
38  if (CE->getOpcode() == Instruction::BitCast ||
39  CE->getOpcode() == Instruction::AddrSpaceCast ||
40  CE->getOpcode() == Instruction::GetElementPtr)
41  return pointsToConstantGlobal(CE->getOperand(0));
42  }
43  return false;
44 }
45 
46 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
47 /// pointer to an alloca. Ignore any reads of the pointer, return false if we
48 /// see any stores or other unknown uses. If we see pointer arithmetic, keep
49 /// track of whether it moves the pointer (with IsOffset) but otherwise traverse
50 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
51 /// the alloca, and if the source pointer is a pointer to a constant global, we
52 /// can optimize this.
53 static bool
56  // We track lifetime intrinsics as we encounter them. If we decide to go
57  // ahead and replace the value with the global, this lets the caller quickly
58  // eliminate the markers.
59 
60  SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect;
61  ValuesToInspect.push_back(std::make_pair(V, false));
62  while (!ValuesToInspect.empty()) {
63  auto ValuePair = ValuesToInspect.pop_back_val();
64  const bool IsOffset = ValuePair.second;
65  for (auto &U : ValuePair.first->uses()) {
66  Instruction *I = cast<Instruction>(U.getUser());
67 
68  if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
69  // Ignore non-volatile loads, they are always ok.
70  if (!LI->isSimple()) return false;
71  continue;
72  }
73 
74  if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) {
75  // If uses of the bitcast are ok, we are ok.
76  ValuesToInspect.push_back(std::make_pair(I, IsOffset));
77  continue;
78  }
79  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
80  // If the GEP has all zero indices, it doesn't offset the pointer. If it
81  // doesn't, it does.
82  ValuesToInspect.push_back(
83  std::make_pair(I, IsOffset || !GEP->hasAllZeroIndices()));
84  continue;
85  }
86 
87  if (auto CS = CallSite(I)) {
88  // If this is the function being called then we treat it like a load and
89  // ignore it.
90  if (CS.isCallee(&U))
91  continue;
92 
93  // Inalloca arguments are clobbered by the call.
94  unsigned ArgNo = CS.getArgumentNo(&U);
95  if (CS.isInAllocaArgument(ArgNo))
96  return false;
97 
98  // If this is a readonly/readnone call site, then we know it is just a
99  // load (but one that potentially returns the value itself), so we can
100  // ignore it if we know that the value isn't captured.
101  if (CS.onlyReadsMemory() &&
102  (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
103  continue;
104 
105  // If this is being passed as a byval argument, the caller is making a
106  // copy, so it is only a read of the alloca.
107  if (CS.isByValArgument(ArgNo))
108  continue;
109  }
110 
111  // Lifetime intrinsics can be handled by the caller.
112  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
113  if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
114  II->getIntrinsicID() == Intrinsic::lifetime_end) {
115  assert(II->use_empty() && "Lifetime markers have no result to use!");
116  ToDelete.push_back(II);
117  continue;
118  }
119  }
120 
121  // If this is isn't our memcpy/memmove, reject it as something we can't
122  // handle.
124  if (!MI)
125  return false;
126 
127  // If the transfer is using the alloca as a source of the transfer, then
128  // ignore it since it is a load (unless the transfer is volatile).
129  if (U.getOperandNo() == 1) {
130  if (MI->isVolatile()) return false;
131  continue;
132  }
133 
134  // If we already have seen a copy, reject the second one.
135  if (TheCopy) return false;
136 
137  // If the pointer has been offset from the start of the alloca, we can't
138  // safely handle this.
139  if (IsOffset) return false;
140 
141  // If the memintrinsic isn't using the alloca as the dest, reject it.
142  if (U.getOperandNo() != 0) return false;
143 
144  // If the source of the memcpy/move is not a constant global, reject it.
145  if (!pointsToConstantGlobal(MI->getSource()))
146  return false;
147 
148  // Otherwise, the transform is safe. Remember the copy instruction.
149  TheCopy = MI;
150  }
151  }
152  return true;
153 }
154 
155 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
156 /// modified by a copy from a constant global. If we can prove this, we can
157 /// replace any uses of the alloca with uses of the global directly.
158 static MemTransferInst *
160  SmallVectorImpl<Instruction *> &ToDelete) {
161  MemTransferInst *TheCopy = nullptr;
162  if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
163  return TheCopy;
164  return nullptr;
165 }
166 
168  // Check for array size of 1 (scalar allocation).
169  if (!AI.isArrayAllocation()) {
170  // i32 1 is the canonical array size for scalar allocations.
171  if (AI.getArraySize()->getType()->isIntegerTy(32))
172  return nullptr;
173 
174  // Canonicalize it.
175  Value *V = IC.Builder->getInt32(1);
176  AI.setOperand(0, V);
177  return &AI;
178  }
179 
180  // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
181  if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
182  Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
183  AllocaInst *New = IC.Builder->CreateAlloca(NewTy, nullptr, AI.getName());
184  New->setAlignment(AI.getAlignment());
185 
186  // Scan to the end of the allocation instructions, to skip over a block of
187  // allocas if possible...also skip interleaved debug info
188  //
189  BasicBlock::iterator It = New;
190  while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
191  ++It;
192 
193  // Now that I is pointing to the first non-allocation-inst in the block,
194  // insert our getelementptr instruction...
195  //
196  Type *IdxTy = IC.getDataLayout().getIntPtrType(AI.getType());
197  Value *NullIdx = Constant::getNullValue(IdxTy);
198  Value *Idx[2] = {NullIdx, NullIdx};
199  Instruction *GEP =
200  GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
201  IC.InsertNewInstBefore(GEP, *It);
202 
203  // Now make everything use the getelementptr instead of the original
204  // allocation.
205  return IC.ReplaceInstUsesWith(AI, GEP);
206  }
207 
208  if (isa<UndefValue>(AI.getArraySize()))
210 
211  // Ensure that the alloca array size argument has type intptr_t, so that
212  // any casting is exposed early.
213  Type *IntPtrTy = IC.getDataLayout().getIntPtrType(AI.getType());
214  if (AI.getArraySize()->getType() != IntPtrTy) {
215  Value *V = IC.Builder->CreateIntCast(AI.getArraySize(), IntPtrTy, false);
216  AI.setOperand(0, V);
217  return &AI;
218  }
219 
220  return nullptr;
221 }
222 
224  if (auto *I = simplifyAllocaArraySize(*this, AI))
225  return I;
226 
227  if (AI.getAllocatedType()->isSized()) {
228  // If the alignment is 0 (unspecified), assign it the preferred alignment.
229  if (AI.getAlignment() == 0)
231 
232  // Move all alloca's of zero byte objects to the entry block and merge them
233  // together. Note that we only do this for alloca's, because malloc should
234  // allocate and return a unique pointer, even for a zero byte allocation.
235  if (DL.getTypeAllocSize(AI.getAllocatedType()) == 0) {
236  // For a zero sized alloca there is no point in doing an array allocation.
237  // This is helpful if the array size is a complicated expression not used
238  // elsewhere.
239  if (AI.isArrayAllocation()) {
240  AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
241  return &AI;
242  }
243 
244  // Get the first instruction in the entry block.
245  BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
246  Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
247  if (FirstInst != &AI) {
248  // If the entry block doesn't start with a zero-size alloca then move
249  // this one to the start of the entry block. There is no problem with
250  // dominance as the array size was forced to a constant earlier already.
251  AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
252  if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
253  DL.getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
254  AI.moveBefore(FirstInst);
255  return &AI;
256  }
257 
258  // If the alignment of the entry block alloca is 0 (unspecified),
259  // assign it the preferred alignment.
260  if (EntryAI->getAlignment() == 0)
261  EntryAI->setAlignment(
262  DL.getPrefTypeAlignment(EntryAI->getAllocatedType()));
263  // Replace this zero-sized alloca with the one at the start of the entry
264  // block after ensuring that the address will be aligned enough for both
265  // types.
266  unsigned MaxAlign = std::max(EntryAI->getAlignment(),
267  AI.getAlignment());
268  EntryAI->setAlignment(MaxAlign);
269  if (AI.getType() != EntryAI->getType())
270  return new BitCastInst(EntryAI, AI.getType());
271  return ReplaceInstUsesWith(AI, EntryAI);
272  }
273  }
274  }
275 
276  if (AI.getAlignment()) {
277  // Check to see if this allocation is only modified by a memcpy/memmove from
278  // a constant global whose alignment is equal to or exceeds that of the
279  // allocation. If this is the case, we can change all users to use
280  // the constant global instead. This is commonly produced by the CFE by
281  // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
282  // is only subsequently read.
284  if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
285  unsigned SourceAlign = getOrEnforceKnownAlignment(
286  Copy->getSource(), AI.getAlignment(), DL, &AI, AC, DT);
287  if (AI.getAlignment() <= SourceAlign) {
288  DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
289  DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
290  for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
291  EraseInstFromFunction(*ToDelete[i]);
292  Constant *TheSrc = cast<Constant>(Copy->getSource());
293  Constant *Cast
295  Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
296  EraseInstFromFunction(*Copy);
297  ++NumGlobalCopies;
298  return NewI;
299  }
300  }
301  }
302 
303  // At last, use the generic allocation site handler to aggressively remove
304  // unused allocas.
305  return visitAllocSite(AI);
306 }
307 
308 /// \brief Helper to combine a load to a new type.
309 ///
310 /// This just does the work of combining a load to a new type. It handles
311 /// metadata, etc., and returns the new instruction. The \c NewTy should be the
312 /// loaded *value* type. This will convert it to a pointer, cast the operand to
313 /// that pointer type, load it, etc.
314 ///
315 /// Note that this will create all of the instructions with whatever insert
316 /// point the \c InstCombiner currently is using.
318  const Twine &Suffix = "") {
319  Value *Ptr = LI.getPointerOperand();
320  unsigned AS = LI.getPointerAddressSpace();
322  LI.getAllMetadata(MD);
323 
324  LoadInst *NewLoad = IC.Builder->CreateAlignedLoad(
325  IC.Builder->CreateBitCast(Ptr, NewTy->getPointerTo(AS)),
326  LI.getAlignment(), LI.getName() + Suffix);
327  MDBuilder MDB(NewLoad->getContext());
328  for (const auto &MDPair : MD) {
329  unsigned ID = MDPair.first;
330  MDNode *N = MDPair.second;
331  // Note, essentially every kind of metadata should be preserved here! This
332  // routine is supposed to clone a load instruction changing *only its type*.
333  // The only metadata it makes sense to drop is metadata which is invalidated
334  // when the pointer type changes. This should essentially never be the case
335  // in LLVM, but we explicitly switch over only known metadata to be
336  // conservatively correct. If you are adding metadata to LLVM which pertains
337  // to loads, you almost certainly want to add it here.
338  switch (ID) {
339  case LLVMContext::MD_dbg:
349  // All of these directly apply.
350  NewLoad->setMetadata(ID, N);
351  break;
352 
354  // This only directly applies if the new type is also a pointer.
355  if (NewTy->isPointerTy()) {
356  NewLoad->setMetadata(ID, N);
357  break;
358  }
359  // If it's integral now, translate it to !range metadata.
360  if (NewTy->isIntegerTy()) {
361  auto *ITy = cast<IntegerType>(NewTy);
362  auto *NullInt = ConstantExpr::getPtrToInt(
363  ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
364  auto *NonNullInt =
365  ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
367  MDB.createRange(NonNullInt, NullInt));
368  }
369  break;
370 
372  // FIXME: It would be nice to propagate this in some way, but the type
373  // conversions make it hard. If the new type is a pointer, we could
374  // translate it to !nonnull metadata.
375  break;
376  }
377  }
378  return NewLoad;
379 }
380 
381 /// \brief Combine a store to a new type.
382 ///
383 /// Returns the newly created store instruction.
385  Value *Ptr = SI.getPointerOperand();
386  unsigned AS = SI.getPointerAddressSpace();
388  SI.getAllMetadata(MD);
389 
390  StoreInst *NewStore = IC.Builder->CreateAlignedStore(
391  V, IC.Builder->CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
392  SI.getAlignment());
393  for (const auto &MDPair : MD) {
394  unsigned ID = MDPair.first;
395  MDNode *N = MDPair.second;
396  // Note, essentially every kind of metadata should be preserved here! This
397  // routine is supposed to clone a store instruction changing *only its
398  // type*. The only metadata it makes sense to drop is metadata which is
399  // invalidated when the pointer type changes. This should essentially
400  // never be the case in LLVM, but we explicitly switch over only known
401  // metadata to be conservatively correct. If you are adding metadata to
402  // LLVM which pertains to stores, you almost certainly want to add it
403  // here.
404  switch (ID) {
405  case LLVMContext::MD_dbg:
414  // All of these directly apply.
415  NewStore->setMetadata(ID, N);
416  break;
417 
421  // These don't apply for stores.
422  break;
423  }
424  }
425 
426  return NewStore;
427 }
428 
429 /// \brief Combine loads to match the type of value their uses after looking
430 /// through intervening bitcasts.
431 ///
432 /// The core idea here is that if the result of a load is used in an operation,
433 /// we should load the type most conducive to that operation. For example, when
434 /// loading an integer and converting that immediately to a pointer, we should
435 /// instead directly load a pointer.
436 ///
437 /// However, this routine must never change the width of a load or the number of
438 /// loads as that would introduce a semantic change. This combine is expected to
439 /// be a semantic no-op which just allows loads to more closely model the types
440 /// of their consuming operations.
441 ///
442 /// Currently, we also refuse to change the precise type used for an atomic load
443 /// or a volatile load. This is debatable, and might be reasonable to change
444 /// later. However, it is risky in case some backend or other part of LLVM is
445 /// relying on the exact type loaded to select appropriate atomic operations.
447  // FIXME: We could probably with some care handle both volatile and atomic
448  // loads here but it isn't clear that this is important.
449  if (!LI.isSimple())
450  return nullptr;
451 
452  if (LI.use_empty())
453  return nullptr;
454 
455  Type *Ty = LI.getType();
456  const DataLayout &DL = IC.getDataLayout();
457 
458  // Try to canonicalize loads which are only ever stored to operate over
459  // integers instead of any other type. We only do this when the loaded type
460  // is sized and has a size exactly the same as its store size and the store
461  // size is a legal integer type.
462  if (!Ty->isIntegerTy() && Ty->isSized() &&
464  DL.getTypeStoreSizeInBits(Ty) == DL.getTypeSizeInBits(Ty)) {
465  if (std::all_of(LI.user_begin(), LI.user_end(), [&LI](User *U) {
466  auto *SI = dyn_cast<StoreInst>(U);
467  return SI && SI->getPointerOperand() != &LI;
468  })) {
469  LoadInst *NewLoad = combineLoadToNewType(
470  IC, LI,
472  // Replace all the stores with stores of the newly loaded value.
473  for (auto UI = LI.user_begin(), UE = LI.user_end(); UI != UE;) {
474  auto *SI = cast<StoreInst>(*UI++);
476  combineStoreToNewValue(IC, *SI, NewLoad);
478  }
479  assert(LI.use_empty() && "Failed to remove all users of the load!");
480  // Return the old load so the combiner can delete it safely.
481  return &LI;
482  }
483  }
484 
485  // Fold away bit casts of the loaded value by loading the desired type.
486  // We can do this for BitCastInsts as well as casts from and to pointer types,
487  // as long as those are noops (i.e., the source or dest type have the same
488  // bitwidth as the target's pointers).
489  if (LI.hasOneUse())
490  if (auto* CI = dyn_cast<CastInst>(LI.user_back())) {
491  if (CI->isNoopCast(DL)) {
492  LoadInst *NewLoad = combineLoadToNewType(IC, LI, CI->getDestTy());
493  CI->replaceAllUsesWith(NewLoad);
494  IC.EraseInstFromFunction(*CI);
495  return &LI;
496  }
497  }
498 
499  // FIXME: We should also canonicalize loads of vectors when their elements are
500  // cast to other types.
501  return nullptr;
502 }
503 
505  // FIXME: We could probably with some care handle both volatile and atomic
506  // stores here but it isn't clear that this is important.
507  if (!LI.isSimple())
508  return nullptr;
509 
510  Type *T = LI.getType();
511  if (!T->isAggregateType())
512  return nullptr;
513 
514  assert(LI.getAlignment() && "Alignement must be set at this point");
515 
516  if (auto *ST = dyn_cast<StructType>(T)) {
517  // If the struct only have one element, we unpack.
518  if (ST->getNumElements() == 1) {
519  LoadInst *NewLoad = combineLoadToNewType(IC, LI, ST->getTypeAtIndex(0U),
520  ".unpack");
522  UndefValue::get(T), NewLoad, 0, LI.getName()));
523  }
524  }
525 
526  if (auto *AT = dyn_cast<ArrayType>(T)) {
527  // If the array only have one element, we unpack.
528  if (AT->getNumElements() == 1) {
529  LoadInst *NewLoad = combineLoadToNewType(IC, LI, AT->getElementType(),
530  ".unpack");
532  UndefValue::get(T), NewLoad, 0, LI.getName()));
533  }
534  }
535 
536  return nullptr;
537 }
538 
539 // If we can determine that all possible objects pointed to by the provided
540 // pointer value are, not only dereferenceable, but also definitively less than
541 // or equal to the provided maximum size, then return true. Otherwise, return
542 // false (constant global values and allocas fall into this category).
543 //
544 // FIXME: This should probably live in ValueTracking (or similar).
545 static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize,
546  const DataLayout &DL) {
547  SmallPtrSet<Value *, 4> Visited;
548  SmallVector<Value *, 4> Worklist(1, V);
549 
550  do {
551  Value *P = Worklist.pop_back_val();
552  P = P->stripPointerCasts();
553 
554  if (!Visited.insert(P).second)
555  continue;
556 
557  if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
558  Worklist.push_back(SI->getTrueValue());
559  Worklist.push_back(SI->getFalseValue());
560  continue;
561  }
562 
563  if (PHINode *PN = dyn_cast<PHINode>(P)) {
564  for (Value *IncValue : PN->incoming_values())
565  Worklist.push_back(IncValue);
566  continue;
567  }
568 
569  if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
570  if (GA->mayBeOverridden())
571  return false;
572  Worklist.push_back(GA->getAliasee());
573  continue;
574  }
575 
576  // If we know how big this object is, and it is less than MaxSize, continue
577  // searching. Otherwise, return false.
578  if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
579  if (!AI->getAllocatedType()->isSized())
580  return false;
581 
582  ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
583  if (!CS)
584  return false;
585 
586  uint64_t TypeSize = DL.getTypeAllocSize(AI->getAllocatedType());
587  // Make sure that, even if the multiplication below would wrap as an
588  // uint64_t, we still do the right thing.
589  if ((CS->getValue().zextOrSelf(128)*APInt(128, TypeSize)).ugt(MaxSize))
590  return false;
591  continue;
592  }
593 
594  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
595  if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
596  return false;
597 
598  uint64_t InitSize = DL.getTypeAllocSize(GV->getType()->getElementType());
599  if (InitSize > MaxSize)
600  return false;
601  continue;
602  }
603 
604  return false;
605  } while (!Worklist.empty());
606 
607  return true;
608 }
609 
610 // If we're indexing into an object of a known size, and the outer index is
611 // not a constant, but having any value but zero would lead to undefined
612 // behavior, replace it with zero.
613 //
614 // For example, if we have:
615 // @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
616 // ...
617 // %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x
618 // ... = load i32* %arrayidx, align 4
619 // Then we know that we can replace %x in the GEP with i64 0.
620 //
621 // FIXME: We could fold any GEP index to zero that would cause UB if it were
622 // not zero. Currently, we only handle the first such index. Also, we could
623 // also search through non-zero constant indices if we kept track of the
624 // offsets those indices implied.
626  Instruction *MemI, unsigned &Idx) {
627  if (GEPI->getNumOperands() < 2)
628  return false;
629 
630  // Find the first non-zero index of a GEP. If all indices are zero, return
631  // one past the last index.
632  auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
633  unsigned I = 1;
634  for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
635  Value *V = GEPI->getOperand(I);
636  if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
637  if (CI->isZero())
638  continue;
639 
640  break;
641  }
642 
643  return I;
644  };
645 
646  // Skip through initial 'zero' indices, and find the corresponding pointer
647  // type. See if the next index is not a constant.
648  Idx = FirstNZIdx(GEPI);
649  if (Idx == GEPI->getNumOperands())
650  return false;
651  if (isa<Constant>(GEPI->getOperand(Idx)))
652  return false;
653 
654  SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
656  cast<PointerType>(GEPI->getOperand(0)->getType()->getScalarType())
657  ->getElementType(),
658  Ops);
659  if (!AllocTy || !AllocTy->isSized())
660  return false;
661  const DataLayout &DL = IC.getDataLayout();
662  uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy);
663 
664  // If there are more indices after the one we might replace with a zero, make
665  // sure they're all non-negative. If any of them are negative, the overall
666  // address being computed might be before the base address determined by the
667  // first non-zero index.
668  auto IsAllNonNegative = [&]() {
669  for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
670  bool KnownNonNegative, KnownNegative;
671  IC.ComputeSignBit(GEPI->getOperand(i), KnownNonNegative,
672  KnownNegative, 0, MemI);
673  if (KnownNonNegative)
674  continue;
675  return false;
676  }
677 
678  return true;
679  };
680 
681  // FIXME: If the GEP is not inbounds, and there are extra indices after the
682  // one we'll replace, those could cause the address computation to wrap
683  // (rendering the IsAllNonNegative() check below insufficient). We can do
684  // better, ignoring zero indicies (and other indicies we can prove small
685  // enough not to wrap).
686  if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
687  return false;
688 
689  // Note that isObjectSizeLessThanOrEq will return true only if the pointer is
690  // also known to be dereferenceable.
691  return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
692  IsAllNonNegative();
693 }
694 
695 // If we're indexing into an object with a variable index for the memory
696 // access, but the object has only one element, we can assume that the index
697 // will always be zero. If we replace the GEP, return it.
698 template <typename T>
700  T &MemI) {
701  if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
702  unsigned Idx;
703  if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
704  Instruction *NewGEPI = GEPI->clone();
705  NewGEPI->setOperand(Idx,
706  ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
707  NewGEPI->insertBefore(GEPI);
708  MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI);
709  return NewGEPI;
710  }
711  }
712 
713  return nullptr;
714 }
715 
717  Value *Op = LI.getOperand(0);
718 
719  // Try to canonicalize the loaded type.
720  if (Instruction *Res = combineLoadToOperationType(*this, LI))
721  return Res;
722 
723  // Attempt to improve the alignment.
724  unsigned KnownAlign = getOrEnforceKnownAlignment(
725  Op, DL.getPrefTypeAlignment(LI.getType()), DL, &LI, AC, DT);
726  unsigned LoadAlign = LI.getAlignment();
727  unsigned EffectiveLoadAlign =
728  LoadAlign != 0 ? LoadAlign : DL.getABITypeAlignment(LI.getType());
729 
730  if (KnownAlign > EffectiveLoadAlign)
731  LI.setAlignment(KnownAlign);
732  else if (LoadAlign == 0)
733  LI.setAlignment(EffectiveLoadAlign);
734 
735  // Replace GEP indices if possible.
736  if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) {
737  Worklist.Add(NewGEPI);
738  return &LI;
739  }
740 
741  // None of the following transforms are legal for volatile/atomic loads.
742  // FIXME: Some of it is okay for atomic loads; needs refactoring.
743  if (!LI.isSimple()) return nullptr;
744 
745  if (Instruction *Res = unpackLoadToAggregate(*this, LI))
746  return Res;
747 
748  // Do really simple store-to-load forwarding and load CSE, to catch cases
749  // where there are several consecutive memory accesses to the same location,
750  // separated by a few arithmetic operations.
751  BasicBlock::iterator BBI = &LI;
752  AAMDNodes AATags;
753  if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,
754  6, AA, &AATags)) {
755  if (LoadInst *NLI = dyn_cast<LoadInst>(AvailableVal)) {
756  unsigned KnownIDs[] = {
763  };
764  combineMetadata(NLI, &LI, KnownIDs);
765  };
766 
767  return ReplaceInstUsesWith(
768  LI, Builder->CreateBitOrPointerCast(AvailableVal, LI.getType(),
769  LI.getName() + ".cast"));
770  }
771 
772  // load(gep null, ...) -> unreachable
773  if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
774  const Value *GEPI0 = GEPI->getOperand(0);
775  // TODO: Consider a target hook for valid address spaces for this xform.
776  if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
777  // Insert a new store to null instruction before the load to indicate
778  // that this code is not reachable. We do this instead of inserting
779  // an unreachable instruction directly because we cannot modify the
780  // CFG.
782  Constant::getNullValue(Op->getType()), &LI);
783  return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
784  }
785  }
786 
787  // load null/undef -> unreachable
788  // TODO: Consider a target hook for valid address spaces for this xform.
789  if (isa<UndefValue>(Op) ||
790  (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
791  // Insert a new store to null instruction before the load to indicate that
792  // this code is not reachable. We do this instead of inserting an
793  // unreachable instruction directly because we cannot modify the CFG.
795  Constant::getNullValue(Op->getType()), &LI);
796  return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
797  }
798 
799  if (Op->hasOneUse()) {
800  // Change select and PHI nodes to select values instead of addresses: this
801  // helps alias analysis out a lot, allows many others simplifications, and
802  // exposes redundancy in the code.
803  //
804  // Note that we cannot do the transformation unless we know that the
805  // introduced loads cannot trap! Something like this is valid as long as
806  // the condition is always false: load (select bool %C, int* null, int* %G),
807  // but it would not be valid if we transformed it to load from null
808  // unconditionally.
809  //
810  if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
811  // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
812  unsigned Align = LI.getAlignment();
813  if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align) &&
814  isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align)) {
815  LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
816  SI->getOperand(1)->getName()+".val");
817  LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
818  SI->getOperand(2)->getName()+".val");
819  V1->setAlignment(Align);
820  V2->setAlignment(Align);
821  return SelectInst::Create(SI->getCondition(), V1, V2);
822  }
823 
824  // load (select (cond, null, P)) -> load P
825  if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
826  LI.getPointerAddressSpace() == 0) {
827  LI.setOperand(0, SI->getOperand(2));
828  return &LI;
829  }
830 
831  // load (select (cond, P, null)) -> load P
832  if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
833  LI.getPointerAddressSpace() == 0) {
834  LI.setOperand(0, SI->getOperand(1));
835  return &LI;
836  }
837  }
838  }
839  return nullptr;
840 }
841 
842 /// \brief Combine stores to match the type of value being stored.
843 ///
844 /// The core idea here is that the memory does not have any intrinsic type and
845 /// where we can we should match the type of a store to the type of value being
846 /// stored.
847 ///
848 /// However, this routine must never change the width of a store or the number of
849 /// stores as that would introduce a semantic change. This combine is expected to
850 /// be a semantic no-op which just allows stores to more closely model the types
851 /// of their incoming values.
852 ///
853 /// Currently, we also refuse to change the precise type used for an atomic or
854 /// volatile store. This is debatable, and might be reasonable to change later.
855 /// However, it is risky in case some backend or other part of LLVM is relying
856 /// on the exact type stored to select appropriate atomic operations.
857 ///
858 /// \returns true if the store was successfully combined away. This indicates
859 /// the caller must erase the store instruction. We have to let the caller erase
860 /// the store instruction sas otherwise there is no way to signal whether it was
861 /// combined or not: IC.EraseInstFromFunction returns a null pointer.
863  // FIXME: We could probably with some care handle both volatile and atomic
864  // stores here but it isn't clear that this is important.
865  if (!SI.isSimple())
866  return false;
867 
868  Value *V = SI.getValueOperand();
869 
870  // Fold away bit casts of the stored value by storing the original type.
871  if (auto *BC = dyn_cast<BitCastInst>(V)) {
872  V = BC->getOperand(0);
873  combineStoreToNewValue(IC, SI, V);
874  return true;
875  }
876 
877  // FIXME: We should also canonicalize loads of vectors when their elements are
878  // cast to other types.
879  return false;
880 }
881 
883  // FIXME: We could probably with some care handle both volatile and atomic
884  // stores here but it isn't clear that this is important.
885  if (!SI.isSimple())
886  return false;
887 
888  Value *V = SI.getValueOperand();
889  Type *T = V->getType();
890 
891  if (!T->isAggregateType())
892  return false;
893 
894  if (auto *ST = dyn_cast<StructType>(T)) {
895  // If the struct only have one element, we unpack.
896  if (ST->getNumElements() == 1) {
897  V = IC.Builder->CreateExtractValue(V, 0);
898  combineStoreToNewValue(IC, SI, V);
899  return true;
900  }
901  }
902 
903  if (auto *AT = dyn_cast<ArrayType>(T)) {
904  // If the array only have one element, we unpack.
905  if (AT->getNumElements() == 1) {
906  V = IC.Builder->CreateExtractValue(V, 0);
907  combineStoreToNewValue(IC, SI, V);
908  return true;
909  }
910  }
911 
912  return false;
913 }
914 
915 /// equivalentAddressValues - Test if A and B will obviously have the same
916 /// value. This includes recognizing that %t0 and %t1 will have the same
917 /// value in code like this:
918 /// %t0 = getelementptr \@a, 0, 3
919 /// store i32 0, i32* %t0
920 /// %t1 = getelementptr \@a, 0, 3
921 /// %t2 = load i32* %t1
922 ///
924  // Test if the values are trivially equivalent.
925  if (A == B) return true;
926 
927  // Test if the values come form identical arithmetic instructions.
928  // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
929  // its only used to compare two uses within the same basic block, which
930  // means that they'll always either have the same value or one of them
931  // will have an undefined value.
932  if (isa<BinaryOperator>(A) ||
933  isa<CastInst>(A) ||
934  isa<PHINode>(A) ||
935  isa<GetElementPtrInst>(A))
936  if (Instruction *BI = dyn_cast<Instruction>(B))
937  if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
938  return true;
939 
940  // Otherwise they may not be equivalent.
941  return false;
942 }
943 
945  Value *Val = SI.getOperand(0);
946  Value *Ptr = SI.getOperand(1);
947 
948  // Try to canonicalize the stored type.
949  if (combineStoreToValueType(*this, SI))
950  return EraseInstFromFunction(SI);
951 
952  // Attempt to improve the alignment.
953  unsigned KnownAlign = getOrEnforceKnownAlignment(
954  Ptr, DL.getPrefTypeAlignment(Val->getType()), DL, &SI, AC, DT);
955  unsigned StoreAlign = SI.getAlignment();
956  unsigned EffectiveStoreAlign =
957  StoreAlign != 0 ? StoreAlign : DL.getABITypeAlignment(Val->getType());
958 
959  if (KnownAlign > EffectiveStoreAlign)
960  SI.setAlignment(KnownAlign);
961  else if (StoreAlign == 0)
962  SI.setAlignment(EffectiveStoreAlign);
963 
964  // Try to canonicalize the stored type.
965  if (unpackStoreToAggregate(*this, SI))
966  return EraseInstFromFunction(SI);
967 
968  // Replace GEP indices if possible.
969  if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) {
970  Worklist.Add(NewGEPI);
971  return &SI;
972  }
973 
974  // Don't hack volatile/atomic stores.
975  // FIXME: Some bits are legal for atomic stores; needs refactoring.
976  if (!SI.isSimple()) return nullptr;
977 
978  // If the RHS is an alloca with a single use, zapify the store, making the
979  // alloca dead.
980  if (Ptr->hasOneUse()) {
981  if (isa<AllocaInst>(Ptr))
982  return EraseInstFromFunction(SI);
983  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
984  if (isa<AllocaInst>(GEP->getOperand(0))) {
985  if (GEP->getOperand(0)->hasOneUse())
986  return EraseInstFromFunction(SI);
987  }
988  }
989  }
990 
991  // Do really simple DSE, to catch cases where there are several consecutive
992  // stores to the same location, separated by a few arithmetic operations. This
993  // situation often occurs with bitfield accesses.
994  BasicBlock::iterator BBI = &SI;
995  for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
996  --ScanInsts) {
997  --BBI;
998  // Don't count debug info directives, lest they affect codegen,
999  // and we skip pointer-to-pointer bitcasts, which are NOPs.
1000  if (isa<DbgInfoIntrinsic>(BBI) ||
1001  (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
1002  ScanInsts++;
1003  continue;
1004  }
1005 
1006  if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
1007  // Prev store isn't volatile, and stores to the same location?
1008  if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
1009  SI.getOperand(1))) {
1010  ++NumDeadStore;
1011  ++BBI;
1012  EraseInstFromFunction(*PrevSI);
1013  continue;
1014  }
1015  break;
1016  }
1017 
1018  // If this is a load, we have to stop. However, if the loaded value is from
1019  // the pointer we're loading and is producing the pointer we're storing,
1020  // then *this* store is dead (X = load P; store X -> P).
1021  if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
1022  if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
1023  LI->isSimple())
1024  return EraseInstFromFunction(SI);
1025 
1026  // Otherwise, this is a load from some other location. Stores before it
1027  // may not be dead.
1028  break;
1029  }
1030 
1031  // Don't skip over loads or things that can modify memory.
1032  if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
1033  break;
1034  }
1035 
1036  // store X, null -> turns into 'unreachable' in SimplifyCFG
1037  if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
1038  if (!isa<UndefValue>(Val)) {
1039  SI.setOperand(0, UndefValue::get(Val->getType()));
1040  if (Instruction *U = dyn_cast<Instruction>(Val))
1041  Worklist.Add(U); // Dropped a use.
1042  }
1043  return nullptr; // Do not modify these!
1044  }
1045 
1046  // store undef, Ptr -> noop
1047  if (isa<UndefValue>(Val))
1048  return EraseInstFromFunction(SI);
1049 
1050  // If this store is the last instruction in the basic block (possibly
1051  // excepting debug info instructions), and if the block ends with an
1052  // unconditional branch, try to move it to the successor block.
1053  BBI = &SI;
1054  do {
1055  ++BBI;
1056  } while (isa<DbgInfoIntrinsic>(BBI) ||
1057  (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
1058  if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
1059  if (BI->isUnconditional())
1060  if (SimplifyStoreAtEndOfBlock(SI))
1061  return nullptr; // xform done!
1062 
1063  return nullptr;
1064 }
1065 
1066 /// SimplifyStoreAtEndOfBlock - Turn things like:
1067 /// if () { *P = v1; } else { *P = v2 }
1068 /// into a phi node with a store in the successor.
1069 ///
1070 /// Simplify things like:
1071 /// *P = v1; if () { *P = v2; }
1072 /// into a phi node with a store in the successor.
1073 ///
1074 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
1075  BasicBlock *StoreBB = SI.getParent();
1076 
1077  // Check to see if the successor block has exactly two incoming edges. If
1078  // so, see if the other predecessor contains a store to the same location.
1079  // if so, insert a PHI node (if needed) and move the stores down.
1080  BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
1081 
1082  // Determine whether Dest has exactly two predecessors and, if so, compute
1083  // the other predecessor.
1084  pred_iterator PI = pred_begin(DestBB);
1085  BasicBlock *P = *PI;
1086  BasicBlock *OtherBB = nullptr;
1087 
1088  if (P != StoreBB)
1089  OtherBB = P;
1090 
1091  if (++PI == pred_end(DestBB))
1092  return false;
1093 
1094  P = *PI;
1095  if (P != StoreBB) {
1096  if (OtherBB)
1097  return false;
1098  OtherBB = P;
1099  }
1100  if (++PI != pred_end(DestBB))
1101  return false;
1102 
1103  // Bail out if all the relevant blocks aren't distinct (this can happen,
1104  // for example, if SI is in an infinite loop)
1105  if (StoreBB == DestBB || OtherBB == DestBB)
1106  return false;
1107 
1108  // Verify that the other block ends in a branch and is not otherwise empty.
1109  BasicBlock::iterator BBI = OtherBB->getTerminator();
1110  BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
1111  if (!OtherBr || BBI == OtherBB->begin())
1112  return false;
1113 
1114  // If the other block ends in an unconditional branch, check for the 'if then
1115  // else' case. there is an instruction before the branch.
1116  StoreInst *OtherStore = nullptr;
1117  if (OtherBr->isUnconditional()) {
1118  --BBI;
1119  // Skip over debugging info.
1120  while (isa<DbgInfoIntrinsic>(BBI) ||
1121  (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
1122  if (BBI==OtherBB->begin())
1123  return false;
1124  --BBI;
1125  }
1126  // If this isn't a store, isn't a store to the same location, or is not the
1127  // right kind of store, bail out.
1128  OtherStore = dyn_cast<StoreInst>(BBI);
1129  if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
1130  !SI.isSameOperationAs(OtherStore))
1131  return false;
1132  } else {
1133  // Otherwise, the other block ended with a conditional branch. If one of the
1134  // destinations is StoreBB, then we have the if/then case.
1135  if (OtherBr->getSuccessor(0) != StoreBB &&
1136  OtherBr->getSuccessor(1) != StoreBB)
1137  return false;
1138 
1139  // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
1140  // if/then triangle. See if there is a store to the same ptr as SI that
1141  // lives in OtherBB.
1142  for (;; --BBI) {
1143  // Check to see if we find the matching store.
1144  if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
1145  if (OtherStore->getOperand(1) != SI.getOperand(1) ||
1146  !SI.isSameOperationAs(OtherStore))
1147  return false;
1148  break;
1149  }
1150  // If we find something that may be using or overwriting the stored
1151  // value, or if we run out of instructions, we can't do the xform.
1152  if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
1153  BBI == OtherBB->begin())
1154  return false;
1155  }
1156 
1157  // In order to eliminate the store in OtherBr, we have to
1158  // make sure nothing reads or overwrites the stored value in
1159  // StoreBB.
1160  for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1161  // FIXME: This should really be AA driven.
1162  if (I->mayReadFromMemory() || I->mayWriteToMemory())
1163  return false;
1164  }
1165  }
1166 
1167  // Insert a PHI node now if we need it.
1168  Value *MergedVal = OtherStore->getOperand(0);
1169  if (MergedVal != SI.getOperand(0)) {
1170  PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
1171  PN->addIncoming(SI.getOperand(0), SI.getParent());
1172  PN->addIncoming(OtherStore->getOperand(0), OtherBB);
1173  MergedVal = InsertNewInstBefore(PN, DestBB->front());
1174  }
1175 
1176  // Advance to a place where it is safe to insert the new store and
1177  // insert it.
1178  BBI = DestBB->getFirstInsertionPt();
1179  StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
1180  SI.isVolatile(),
1181  SI.getAlignment(),
1182  SI.getOrdering(),
1183  SI.getSynchScope());
1184  InsertNewInstBefore(NewSI, *BBI);
1185  NewSI->setDebugLoc(OtherStore->getDebugLoc());
1186 
1187  // If the two stores had AA tags, merge them.
1188  AAMDNodes AATags;
1189  SI.getAAMetadata(AATags);
1190  if (AATags) {
1191  OtherStore->getAAMetadata(AATags, /* Merge = */ true);
1192  NewSI->setAAMetadata(AATags);
1193  }
1194 
1195  // Nuke the old stores.
1197  EraseInstFromFunction(*OtherStore);
1198  return true;
1199 }
Value * getValueOperand()
Definition: Instructions.h:406
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:104
AllocaInst * CreateAlloca(Type *Ty, Value *ArraySize=nullptr, const Twine &Name="")
Definition: IRBuilder.h:967
LoadInst * CreateLoad(Value *Ptr, const char *Name)
Definition: IRBuilder.h:973
void addIncoming(Value *V, BasicBlock *BB)
addIncoming - Add an incoming value to the end of the PHI list
unsigned getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
getOrEnforceKnownAlignment - If the specified pointer has an alignment that we can determine...
Definition: Local.cpp:927
static Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
Definition: Constants.cpp:1663
STATISTIC(NumFunctions,"Total number of functions")
bool isVolatile() const
isVolatile - Return true if this is a store to a volatile memory location.
Definition: Instructions.h:351
SynchronizationScope getSynchScope() const
Definition: Instructions.h:383
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition: IRBuilder.h:1316
bool isVolatile() const
void setAlignment(unsigned Align)
unsigned getNumOperands() const
Definition: User.h:138
unsigned getPrefTypeAlignment(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
Definition: DataLayout.cpp:684
bool isSimple() const
Definition: Instructions.h:401
const DataLayout & getDataLayout() const
void Add(Instruction *I)
Add - Add the specified instruction to the worklist if it isn't already in it.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:111
const Instruction & front() const
Definition: BasicBlock.h:243
Metadata node.
Definition: Metadata.h:740
static LoadInst * combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy, const Twine &Suffix="")
Helper to combine a load to a new type.
LoadInst - an instruction for reading from memory.
Definition: Instructions.h:177
static bool pointsToConstantGlobal(Value *V)
pointsToConstantGlobal - Return true if V (possibly indirectly) points to some part of a constant glo...
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * >> &MDs) const
getAllMetadata - Get all metadata attached to this Instruction.
Definition: Instruction.h:183
Hexagon Common GEP
bool isSimple() const
Definition: Instructions.h:279
static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy, SmallVectorImpl< Instruction * > &ToDelete)
isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived) pointer to an alloca...
static Constant * getNullValue(Type *Ty)
Definition: Constants.cpp:178
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:188
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:231
static Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2258
bool isArrayAllocation() const
isArrayAllocation - Return true if there is an allocation size parameter to the allocation instructio...
Instruction * getFirstNonPHIOrDbg()
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic...
Definition: BasicBlock.cpp:172
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition: IRBuilder.h:1541
bool isUnconditional() const
SelectInst - This class represents the LLVM 'select' instruction.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:79
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:106
T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val()
Definition: SmallVector.h:406
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APInt.h:33
static Instruction * replaceGEPIdxWithZero(InstCombiner &IC, Value *Ptr, T &MemI)
The core instruction combiner logic.
bool isSized(SmallPtrSetImpl< const Type * > *Visited=nullptr) const
isSized - Return true if it makes sense to take the size of this type.
Definition: Type.h:268
Instruction * clone() const
clone() - Create a copy of 'this' instruction that is identical in all ways except the following: ...
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Definition: Instructions.h:414
ConstantExpr - a constant value that is initialized with an expression using other constant values...
Definition: Constants.h:852
static GetElementPtrInst * CreateInBounds(Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Create an "inbounds" getelementptr.
Definition: Instructions.h:887
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
APInt LLVM_ATTRIBUTE_UNUSED_RESULT zextOrSelf(unsigned width) const
Zero extend or truncate to width.
Definition: APInt.cpp:1031
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: SmallVector.h:57
static Instruction * simplifyAllocaArraySize(InstCombiner &IC, AllocaInst &AI)
BasicBlock * getSuccessor(unsigned i) const
This class represents a no-op cast from one type to another.
op_iterator idx_begin()
Definition: Instructions.h:954
StoreInst - an instruction for storing to memory.
Definition: Instructions.h:316
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:351
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Definition: IRBuilder.h:85
bool isInBounds() const
isInBounds - Determine whether the GEP has the inbounds flag.
GetElementPtrInst - an instruction for type-safe pointer arithmetic to access elements of arrays and ...
Definition: Instructions.h:830
#define P(N)
static Instruction * combineLoadToOperationType(InstCombiner &IC, LoadInst &LI)
Combine loads to match the type of value their uses after looking through intervening bitcasts...
static bool equivalentAddressValues(Value *A, Value *B)
equivalentAddressValues - Test if A and B will obviously have the same value.
static bool unpackStoreToAggregate(InstCombiner &IC, StoreInst &SI)
unsigned getAlignment() const
getAlignment - Return the alignment of the access that is being performed
Definition: Instructions.h:365
void setDebugLoc(DebugLoc Loc)
setDebugLoc - Set the debug location information for this instruction.
Definition: Instruction.h:227
static ConstantPointerNull * get(PointerType *T)
get() - Static factory methods - Return objects of the specified value
Definition: Constants.cpp:1455
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
Definition: Instruction.cpp:76
void setAAMetadata(const AAMDNodes &N)
setAAMetadata - Sets the metadata on this instruction from the AAMDNodes structure.
Definition: Metadata.cpp:1122
LLVM Basic Block Representation.
Definition: BasicBlock.h:65
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
Definition: InstrTypes.h:62
uint64_t getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
Definition: DataLayout.h:379
BranchInst - Conditional or Unconditional Branch instruction.
This is an important base class in LLVM.
Definition: Constant.h:41
PointerType * getType() const
getType - Overload to return most specific pointer type
Definition: Instructions.h:115
Instruction * ReplaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
unsigned getAlignment() const
getAlignment - Return the alignment of the memory that is being allocated by the instruction.
Definition: Instructions.h:130
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:264
static StoreInst * combineStoreToNewValue(InstCombiner &IC, StoreInst &SI, Value *V)
Combine a store to a new type.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:114
const DebugLoc & getDebugLoc() const
getDebugLoc - Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:230
Instruction * visitAllocaInst(AllocaInst &AI)
Value * getOperand(unsigned i) const
Definition: User.h:118
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:117
Value * getPointerOperand()
Definition: Instructions.h:284
void setAlignment(unsigned Align)
bool isPointerTy() const
isPointerTy - True if this is an instance of PointerType.
Definition: Type.h:217
static UndefValue * get(Type *T)
get() - Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1473
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:519
PointerType * getPointerTo(unsigned AddrSpace=0)
getPointerTo - Return a pointer to the current type.
Definition: Type.cpp:764
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align, bool isVolatile=false)
Definition: IRBuilder.h:1008
LoadInst * CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name)
Definition: IRBuilder.h:991
void setMetadata(unsigned KindID, MDNode *Node)
setMetadata - Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1083
InstCombineWorklist & Worklist
A worklist of the instructions that need to be simplified.
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
Definition: DataLayout.cpp:694
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
Definition: DataLayout.cpp:674
AtomicOrdering getOrdering() const
Returns the ordering effect of this store.
Definition: Instructions.h:372
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:299
This is the shared class of boolean and integer constants.
Definition: Constants.h:47
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:388
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1253
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:222
Instruction * user_back()
user_back - Specialize the methods defined in Value, as we know that an instruction can only be used ...
Definition: Instruction.h:69
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition: Metadata.h:548
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:266
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition: Type.cpp:243
Value * stripPointerCasts()
Strip off pointer casts, all-zero GEPs, and aliases.
Definition: Value.cpp:458
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:582
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
const BasicBlock & getEntryBlock() const
Definition: Function.h:442
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Definition: Instructions.h:289
static cl::opt< AlignMode > Align(cl::desc("Load/store alignment support"), cl::Hidden, cl::init(NoStrictAlign), cl::values(clEnumValN(StrictAlign,"aarch64-strict-align","Disallow all unaligned memory accesses"), clEnumValN(NoStrictAlign,"aarch64-no-strict-align","Allow unaligned memory accesses"), clEnumValEnd))
static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI)
Combine stores to match the type of value being stored.
void setOperand(unsigned i, Value *Val)
Definition: User.h:122
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:123
Class for arbitrary precision integers.
Definition: APInt.h:73
bool isIntegerTy() const
isIntegerTy - True if this is an instance of IntegerType.
Definition: Type.h:193
LLVM_ATTRIBUTE_UNUSED_RESULT std::enable_if< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:285
static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize, const DataLayout &DL)
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition: IRBuilder.h:1549
const Type * getScalarType() const LLVM_READONLY
getScalarType - If this is a vector type, return the element type, otherwise return 'this'...
Definition: Type.cpp:51
static Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
getIndexedType - Returns the type of the element that would be loaded with a load instruction with th...
Value * getSource() const
getSource - This is just like getRawSource, but it strips off any cast instructions that feed it...
MemTransferInst - This class wraps the llvm.memcpy/memmove intrinsics.
bool isAggregateType() const
isAggregateType - Return true if the type is an aggregate type.
Definition: Type.h:260
bool isLegalInteger(unsigned Width) const
Returns true if the specified type is known to be a native integer type supported by the CPU...
Definition: DataLayout.h:239
unsigned getAlignment() const
getAlignment - Return the alignment of the access that is being performed
Definition: Instructions.h:243
void getAAMetadata(AAMDNodes &N, bool Merge=false) const
getAAMetadata - Fills the AAMDNodes structure with AA metadata from this instruction.
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1809
#define I(x, y, z)
Definition: MD5.cpp:54
#define N
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:124
bool hasOneUse() const
Return true if there is exactly one user of this value.
Definition: Value.h:311
static ArrayType * get(Type *ElementType, uint64_t NumElements)
ArrayType::get - This static method is the primary way to construct an ArrayType. ...
Definition: Type.cpp:686
Instruction * InsertNewInstBefore(Instruction *New, Instruction &Old)
Inserts an instruction New before instruction Old.
void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne, unsigned Depth=0, Instruction *CxtI=nullptr) const
bool all_of(R &&Range, UnaryPredicate &&P)
Provide wrappers to std::all_of which take ranges instead of having to pass being/end explicitly...
Definition: STLExtras.h:334
bool use_empty() const
Definition: Value.h:275
user_iterator user_begin()
Definition: Value.h:294
static bool canReplaceGEPIdxWithZero(InstCombiner &IC, GetElementPtrInst *GEPI, Instruction *MemI, unsigned &Idx)
Value * FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan=6, AliasAnalysis *AA=nullptr, AAMDNodes *AATags=nullptr)
FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the instruction before ScanFr...
Definition: Loads.cpp:183
Instruction * visitLoadInst(LoadInst &LI)
LLVM Value Representation.
Definition: Value.h:69
void setAlignment(unsigned Align)
This file provides internal interfaces used to implement the InstCombine.
Instruction * visitStoreInst(StoreInst &SI)
const Value * getArraySize() const
getArraySize - Get the number of elements allocated.
Definition: Instructions.h:110
Instruction * EraseInstFromFunction(Instruction &I)
Combiner aware instruction erasure.
void moveBefore(Instruction *MovePos)
moveBefore - Unlink this instruction from its current basic block and insert it into the basic block ...
Definition: Instruction.cpp:89
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
Definition: DataLayout.h:507
#define DEBUG(X)
Definition: Debug.h:92
bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom, unsigned Align)
isSafeToLoadUnconditionally - Return true if we know that executing a load from this value cannot tra...
Definition: Loads.cpp:65
bool isSameOperationAs(const Instruction *I, unsigned flags=0) const
This function determines if the specified instruction executes the same operation as the current one...
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1325
iterator getFirstInsertionPt()
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:194
Type * getAllocatedType() const
getAllocatedType - Return the type that is being allocated by the instruction.
Definition: Instructions.h:122
Value * getPointerOperand()
Definition: Instructions.h:409
static Instruction * unpackLoadToAggregate(InstCombiner &IC, LoadInst &LI)
Instruction * visitAllocSite(Instruction &FI)
void combineMetadata(Instruction *K, const Instruction *J, ArrayRef< unsigned > KnownIDs)
Combine the metadata of two instructions so that K can replace J.
Definition: Local.cpp:1286
const BasicBlock * getParent() const
Definition: Instruction.h:72
IntrinsicInst - A useful wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:37
AllocaInst - an instruction to allocate memory on the stack.
Definition: Instructions.h:76
user_iterator user_end()
Definition: Value.h:296