1 //===- InstCombineLoadStoreAlloca.cpp -------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visit functions for load, store and alloca.
12 //===----------------------------------------------------------------------===//
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"
21 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
22 #include "llvm/Transforms/Utils/Local.h"
25 #define DEBUG_TYPE "instcombine"
27 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
28 STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
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();
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));
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.
54 isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
55 SmallVectorImpl<Instruction *> &ToDelete) {
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.
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());
68 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
69 // Ignore non-volatile loads, they are always ok.
70 if (!LI->isSimple()) return false;
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));
79 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
80 // If the GEP has all zero indices, it doesn't offset the pointer. If it
82 ValuesToInspect.push_back(
83 std::make_pair(I, IsOffset || !GEP->hasAllZeroIndices()));
87 if (CallSite CS = I) {
88 // If this is the function being called then we treat it like a load and
93 // Inalloca arguments are clobbered by the call.
94 unsigned ArgNo = CS.getArgumentNo(&U);
95 if (CS.isInAllocaArgument(ArgNo))
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)))
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))
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);
121 // If this is isn't our memcpy/memmove, reject it as something we can't
123 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
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;
134 // If we already have seen a copy, reject the second one.
135 if (TheCopy) return false;
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;
141 // If the memintrinsic isn't using the alloca as the dest, reject it.
142 if (U.getOperandNo() != 0) return false;
144 // If the source of the memcpy/move is not a constant global, reject it.
145 if (!pointsToConstantGlobal(MI->getSource()))
148 // Otherwise, the transform is safe. Remember the copy instruction.
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 *
159 isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
160 SmallVectorImpl<Instruction *> &ToDelete) {
161 MemTransferInst *TheCopy = nullptr;
162 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
167 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
168 // Ensure that the alloca array size argument has type intptr_t, so that
169 // any casting is exposed early.
171 Type *IntPtrTy = DL->getIntPtrType(AI.getType());
172 if (AI.getArraySize()->getType() != IntPtrTy) {
173 Value *V = Builder->CreateIntCast(AI.getArraySize(),
180 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
181 if (AI.isArrayAllocation()) { // Check C != 1
182 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
184 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
185 AllocaInst *New = Builder->CreateAlloca(NewTy, nullptr, AI.getName());
186 New->setAlignment(AI.getAlignment());
188 // Scan to the end of the allocation instructions, to skip over a block of
189 // allocas if possible...also skip interleaved debug info
191 BasicBlock::iterator It = New;
192 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
194 // Now that I is pointing to the first non-allocation-inst in the block,
195 // insert our getelementptr instruction...
198 ? DL->getIntPtrType(AI.getType())
199 : Type::getInt64Ty(AI.getContext());
200 Value *NullIdx = Constant::getNullValue(IdxTy);
201 Value *Idx[2] = { NullIdx, NullIdx };
203 GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
204 InsertNewInstBefore(GEP, *It);
206 // Now make everything use the getelementptr instead of the original
208 return ReplaceInstUsesWith(AI, GEP);
209 } else if (isa<UndefValue>(AI.getArraySize())) {
210 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
214 if (DL && AI.getAllocatedType()->isSized()) {
215 // If the alignment is 0 (unspecified), assign it the preferred alignment.
216 if (AI.getAlignment() == 0)
217 AI.setAlignment(DL->getPrefTypeAlignment(AI.getAllocatedType()));
219 // Move all alloca's of zero byte objects to the entry block and merge them
220 // together. Note that we only do this for alloca's, because malloc should
221 // allocate and return a unique pointer, even for a zero byte allocation.
222 if (DL->getTypeAllocSize(AI.getAllocatedType()) == 0) {
223 // For a zero sized alloca there is no point in doing an array allocation.
224 // This is helpful if the array size is a complicated expression not used
226 if (AI.isArrayAllocation()) {
227 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
231 // Get the first instruction in the entry block.
232 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
233 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
234 if (FirstInst != &AI) {
235 // If the entry block doesn't start with a zero-size alloca then move
236 // this one to the start of the entry block. There is no problem with
237 // dominance as the array size was forced to a constant earlier already.
238 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
239 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
240 DL->getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
241 AI.moveBefore(FirstInst);
245 // If the alignment of the entry block alloca is 0 (unspecified),
246 // assign it the preferred alignment.
247 if (EntryAI->getAlignment() == 0)
248 EntryAI->setAlignment(
249 DL->getPrefTypeAlignment(EntryAI->getAllocatedType()));
250 // Replace this zero-sized alloca with the one at the start of the entry
251 // block after ensuring that the address will be aligned enough for both
253 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
255 EntryAI->setAlignment(MaxAlign);
256 if (AI.getType() != EntryAI->getType())
257 return new BitCastInst(EntryAI, AI.getType());
258 return ReplaceInstUsesWith(AI, EntryAI);
263 if (AI.getAlignment()) {
264 // Check to see if this allocation is only modified by a memcpy/memmove from
265 // a constant global whose alignment is equal to or exceeds that of the
266 // allocation. If this is the case, we can change all users to use
267 // the constant global instead. This is commonly produced by the CFE by
268 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
269 // is only subsequently read.
270 SmallVector<Instruction *, 4> ToDelete;
271 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
272 unsigned SourceAlign = getOrEnforceKnownAlignment(
273 Copy->getSource(), AI.getAlignment(), DL, AC, &AI, DT);
274 if (AI.getAlignment() <= SourceAlign) {
275 DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
276 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
277 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
278 EraseInstFromFunction(*ToDelete[i]);
279 Constant *TheSrc = cast<Constant>(Copy->getSource());
281 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
282 Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
283 EraseInstFromFunction(*Copy);
290 // At last, use the generic allocation site handler to aggressively remove
292 return visitAllocSite(AI);
295 /// \brief Helper to combine a load to a new type.
297 /// This just does the work of combining a load to a new type. It handles
298 /// metadata, etc., and returns the new instruction. The \c NewTy should be the
299 /// loaded *value* type. This will convert it to a pointer, cast the operand to
300 /// that pointer type, load it, etc.
302 /// Note that this will create all of the instructions with whatever insert
303 /// point the \c InstCombiner currently is using.
304 static LoadInst *combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy) {
305 Value *Ptr = LI.getPointerOperand();
306 unsigned AS = LI.getPointerAddressSpace();
307 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
308 LI.getAllMetadata(MD);
310 LoadInst *NewLoad = IC.Builder->CreateAlignedLoad(
311 IC.Builder->CreateBitCast(Ptr, NewTy->getPointerTo(AS)),
312 LI.getAlignment(), LI.getName());
313 MDBuilder MDB(NewLoad->getContext());
314 for (const auto &MDPair : MD) {
315 unsigned ID = MDPair.first;
316 MDNode *N = MDPair.second;
317 // Note, essentially every kind of metadata should be preserved here! This
318 // routine is supposed to clone a load instruction changing *only its type*.
319 // The only metadata it makes sense to drop is metadata which is invalidated
320 // when the pointer type changes. This should essentially never be the case
321 // in LLVM, but we explicitly switch over only known metadata to be
322 // conservatively correct. If you are adding metadata to LLVM which pertains
323 // to loads, you almost certainly want to add it here.
325 case LLVMContext::MD_dbg:
326 case LLVMContext::MD_tbaa:
327 case LLVMContext::MD_prof:
328 case LLVMContext::MD_fpmath:
329 case LLVMContext::MD_tbaa_struct:
330 case LLVMContext::MD_invariant_load:
331 case LLVMContext::MD_alias_scope:
332 case LLVMContext::MD_noalias:
333 case LLVMContext::MD_nontemporal:
334 case LLVMContext::MD_mem_parallel_loop_access:
335 // All of these directly apply.
336 NewLoad->setMetadata(ID, N);
339 case LLVMContext::MD_nonnull:
340 // This only directly applies if the new type is also a pointer.
341 if (NewTy->isPointerTy()) {
342 NewLoad->setMetadata(ID, N);
345 // If it's integral now, translate it to !range metadata.
346 if (NewTy->isIntegerTy()) {
347 auto *ITy = cast<IntegerType>(NewTy);
348 auto *NullInt = ConstantExpr::getPtrToInt(
349 ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
351 ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
352 NewLoad->setMetadata(LLVMContext::MD_range,
353 MDB.createRange(NonNullInt, NullInt));
357 case LLVMContext::MD_range:
358 // FIXME: It would be nice to propagate this in some way, but the type
359 // conversions make it hard. If the new type is a pointer, we could
360 // translate it to !nonnull metadata.
367 /// \brief Combine a store to a new type.
369 /// Returns the newly created store instruction.
370 static StoreInst *combineStoreToNewValue(InstCombiner &IC, StoreInst &SI, Value *V) {
371 Value *Ptr = SI.getPointerOperand();
372 unsigned AS = SI.getPointerAddressSpace();
373 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
374 SI.getAllMetadata(MD);
376 StoreInst *NewStore = IC.Builder->CreateAlignedStore(
377 V, IC.Builder->CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
379 for (const auto &MDPair : MD) {
380 unsigned ID = MDPair.first;
381 MDNode *N = MDPair.second;
382 // Note, essentially every kind of metadata should be preserved here! This
383 // routine is supposed to clone a store instruction changing *only its
384 // type*. The only metadata it makes sense to drop is metadata which is
385 // invalidated when the pointer type changes. This should essentially
386 // never be the case in LLVM, but we explicitly switch over only known
387 // metadata to be conservatively correct. If you are adding metadata to
388 // LLVM which pertains to stores, you almost certainly want to add it
391 case LLVMContext::MD_dbg:
392 case LLVMContext::MD_tbaa:
393 case LLVMContext::MD_prof:
394 case LLVMContext::MD_fpmath:
395 case LLVMContext::MD_tbaa_struct:
396 case LLVMContext::MD_alias_scope:
397 case LLVMContext::MD_noalias:
398 case LLVMContext::MD_nontemporal:
399 case LLVMContext::MD_mem_parallel_loop_access:
400 // All of these directly apply.
401 NewStore->setMetadata(ID, N);
404 case LLVMContext::MD_invariant_load:
405 case LLVMContext::MD_nonnull:
406 case LLVMContext::MD_range:
407 // These don't apply for stores.
415 /// \brief Combine loads to match the type of value their uses after looking
416 /// through intervening bitcasts.
418 /// The core idea here is that if the result of a load is used in an operation,
419 /// we should load the type most conducive to that operation. For example, when
420 /// loading an integer and converting that immediately to a pointer, we should
421 /// instead directly load a pointer.
423 /// However, this routine must never change the width of a load or the number of
424 /// loads as that would introduce a semantic change. This combine is expected to
425 /// be a semantic no-op which just allows loads to more closely model the types
426 /// of their consuming operations.
428 /// Currently, we also refuse to change the precise type used for an atomic load
429 /// or a volatile load. This is debatable, and might be reasonable to change
430 /// later. However, it is risky in case some backend or other part of LLVM is
431 /// relying on the exact type loaded to select appropriate atomic operations.
432 static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
433 // FIXME: We could probably with some care handle both volatile and atomic
434 // loads here but it isn't clear that this is important.
441 Type *Ty = LI.getType();
443 // Try to canonicalize loads which are only ever stored to operate over
444 // integers instead of any other type. We only do this when the loaded type
445 // is sized and has a size exactly the same as its store size and the store
446 // size is a legal integer type.
447 const DataLayout *DL = IC.getDataLayout();
448 if (!Ty->isIntegerTy() && Ty->isSized() && DL &&
449 DL->isLegalInteger(DL->getTypeStoreSizeInBits(Ty)) &&
450 DL->getTypeStoreSizeInBits(Ty) == DL->getTypeSizeInBits(Ty)) {
451 if (std::all_of(LI.user_begin(), LI.user_end(), [&LI](User *U) {
452 auto *SI = dyn_cast<StoreInst>(U);
453 return SI && SI->getPointerOperand() != &LI;
455 LoadInst *NewLoad = combineLoadToNewType(
457 Type::getIntNTy(LI.getContext(), DL->getTypeStoreSizeInBits(Ty)));
458 // Replace all the stores with stores of the newly loaded value.
459 for (auto UI = LI.user_begin(), UE = LI.user_end(); UI != UE;) {
460 auto *SI = cast<StoreInst>(*UI++);
461 IC.Builder->SetInsertPoint(SI);
462 combineStoreToNewValue(IC, *SI, NewLoad);
463 IC.EraseInstFromFunction(*SI);
465 assert(LI.use_empty() && "Failed to remove all users of the load!");
466 // Return the old load so the combiner can delete it safely.
471 // Fold away bit casts of the loaded value by loading the desired type.
473 if (auto *BC = dyn_cast<BitCastInst>(LI.user_back())) {
474 LoadInst *NewLoad = combineLoadToNewType(IC, LI, BC->getDestTy());
475 BC->replaceAllUsesWith(NewLoad);
476 IC.EraseInstFromFunction(*BC);
480 // FIXME: We should also canonicalize loads of vectors when their elements are
481 // cast to other types.
485 // If we can determine that all possible objects pointed to by the provided
486 // pointer value are, not only dereferenceable, but also definitively less than
487 // or equal to the provided maximum size, then return true. Otherwise, return
488 // false (constant global values and allocas fall into this category).
490 // FIXME: This should probably live in ValueTracking (or similar).
491 static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize,
492 const DataLayout *DL) {
493 SmallPtrSet<Value *, 4> Visited;
494 SmallVector<Value *, 4> Worklist(1, V);
497 Value *P = Worklist.pop_back_val();
498 P = P->stripPointerCasts();
500 if (!Visited.insert(P).second)
503 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
504 Worklist.push_back(SI->getTrueValue());
505 Worklist.push_back(SI->getFalseValue());
509 if (PHINode *PN = dyn_cast<PHINode>(P)) {
510 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
511 Worklist.push_back(PN->getIncomingValue(i));
515 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
516 if (GA->mayBeOverridden())
518 Worklist.push_back(GA->getAliasee());
522 // If we know how big this object is, and it is less than MaxSize, continue
523 // searching. Otherwise, return false.
524 if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
525 if (!AI->getAllocatedType()->isSized())
528 ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
532 uint64_t TypeSize = DL->getTypeAllocSize(AI->getAllocatedType());
533 // Make sure that, even if the multiplication below would wrap as an
534 // uint64_t, we still do the right thing.
535 if ((CS->getValue().zextOrSelf(128)*APInt(128, TypeSize)).ugt(MaxSize))
540 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
541 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
544 uint64_t InitSize = DL->getTypeAllocSize(GV->getType()->getElementType());
545 if (InitSize > MaxSize)
551 } while (!Worklist.empty());
556 // If we're indexing into an object of a known size, and the outer index is
557 // not a constant, but having any value but zero would lead to undefined
558 // behavior, replace it with zero.
560 // For example, if we have:
561 // @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
563 // %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x
564 // ... = load i32* %arrayidx, align 4
565 // Then we know that we can replace %x in the GEP with i64 0.
567 // FIXME: We could fold any GEP index to zero that would cause UB if it were
568 // not zero. Currently, we only handle the first such index. Also, we could
569 // also search through non-zero constant indices if we kept track of the
570 // offsets those indices implied.
571 static bool canReplaceGEPIdxWithZero(InstCombiner &IC, GetElementPtrInst *GEPI,
572 Instruction *MemI, unsigned &Idx) {
573 const DataLayout *DL = IC.getDataLayout();
574 if (GEPI->getNumOperands() < 2 || !DL)
577 // Find the first non-zero index of a GEP. If all indices are zero, return
578 // one past the last index.
579 auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
581 for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
582 Value *V = GEPI->getOperand(I);
583 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
593 // Skip through initial 'zero' indices, and find the corresponding pointer
594 // type. See if the next index is not a constant.
595 Idx = FirstNZIdx(GEPI);
596 if (Idx == GEPI->getNumOperands())
598 if (isa<Constant>(GEPI->getOperand(Idx)))
601 SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
603 GetElementPtrInst::getIndexedType(GEPI->getOperand(0)->getType(), Ops);
604 if (!AllocTy || !AllocTy->isSized())
606 uint64_t TyAllocSize = DL->getTypeAllocSize(AllocTy);
608 // If there are more indices after the one we might replace with a zero, make
609 // sure they're all non-negative. If any of them are negative, the overall
610 // address being computed might be before the base address determined by the
611 // first non-zero index.
612 auto IsAllNonNegative = [&]() {
613 for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
614 bool KnownNonNegative, KnownNegative;
615 IC.ComputeSignBit(GEPI->getOperand(i), KnownNonNegative,
616 KnownNegative, 0, MemI);
617 if (KnownNonNegative)
625 // FIXME: If the GEP is not inbounds, and there are extra indices after the
626 // one we'll replace, those could cause the address computation to wrap
627 // (rendering the IsAllNonNegative() check below insufficient). We can do
628 // better, ignoring zero indicies (and other indicies we can prove small
629 // enough not to wrap).
630 if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
633 // Note that isObjectSizeLessThanOrEq will return true only if the pointer is
634 // also known to be dereferenceable.
635 return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
639 // If we're indexing into an object with a variable index for the memory
640 // access, but the object has only one element, we can assume that the index
641 // will always be zero. If we replace the GEP, return it.
642 template <typename T>
643 static Instruction *replaceGEPIdxWithZero(InstCombiner &IC, Value *Ptr,
645 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
647 if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
648 Instruction *NewGEPI = GEPI->clone();
649 NewGEPI->setOperand(Idx,
650 ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
651 NewGEPI->insertBefore(GEPI);
652 MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI);
660 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
661 Value *Op = LI.getOperand(0);
663 // Try to canonicalize the loaded type.
664 if (Instruction *Res = combineLoadToOperationType(*this, LI))
667 // Attempt to improve the alignment.
669 unsigned KnownAlign = getOrEnforceKnownAlignment(
670 Op, DL->getPrefTypeAlignment(LI.getType()), DL, AC, &LI, DT);
671 unsigned LoadAlign = LI.getAlignment();
672 unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
673 DL->getABITypeAlignment(LI.getType());
675 if (KnownAlign > EffectiveLoadAlign)
676 LI.setAlignment(KnownAlign);
677 else if (LoadAlign == 0)
678 LI.setAlignment(EffectiveLoadAlign);
681 // Replace GEP indices if possible.
682 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) {
683 Worklist.Add(NewGEPI);
687 // None of the following transforms are legal for volatile/atomic loads.
688 // FIXME: Some of it is okay for atomic loads; needs refactoring.
689 if (!LI.isSimple()) return nullptr;
691 // Do really simple store-to-load forwarding and load CSE, to catch cases
692 // where there are several consecutive memory accesses to the same location,
693 // separated by a few arithmetic operations.
694 BasicBlock::iterator BBI = &LI;
695 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
696 return ReplaceInstUsesWith(
697 LI, Builder->CreateBitOrPointerCast(AvailableVal, LI.getType(),
698 LI.getName() + ".cast"));
700 // load(gep null, ...) -> unreachable
701 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
702 const Value *GEPI0 = GEPI->getOperand(0);
703 // TODO: Consider a target hook for valid address spaces for this xform.
704 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
705 // Insert a new store to null instruction before the load to indicate
706 // that this code is not reachable. We do this instead of inserting
707 // an unreachable instruction directly because we cannot modify the
709 new StoreInst(UndefValue::get(LI.getType()),
710 Constant::getNullValue(Op->getType()), &LI);
711 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
715 // load null/undef -> unreachable
716 // TODO: Consider a target hook for valid address spaces for this xform.
717 if (isa<UndefValue>(Op) ||
718 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
719 // Insert a new store to null instruction before the load to indicate that
720 // this code is not reachable. We do this instead of inserting an
721 // unreachable instruction directly because we cannot modify the CFG.
722 new StoreInst(UndefValue::get(LI.getType()),
723 Constant::getNullValue(Op->getType()), &LI);
724 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
727 if (Op->hasOneUse()) {
728 // Change select and PHI nodes to select values instead of addresses: this
729 // helps alias analysis out a lot, allows many others simplifications, and
730 // exposes redundancy in the code.
732 // Note that we cannot do the transformation unless we know that the
733 // introduced loads cannot trap! Something like this is valid as long as
734 // the condition is always false: load (select bool %C, int* null, int* %G),
735 // but it would not be valid if we transformed it to load from null
738 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
739 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
740 unsigned Align = LI.getAlignment();
741 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, DL) &&
742 isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, DL)) {
743 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
744 SI->getOperand(1)->getName()+".val");
745 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
746 SI->getOperand(2)->getName()+".val");
747 V1->setAlignment(Align);
748 V2->setAlignment(Align);
749 return SelectInst::Create(SI->getCondition(), V1, V2);
752 // load (select (cond, null, P)) -> load P
753 if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
754 LI.getPointerAddressSpace() == 0) {
755 LI.setOperand(0, SI->getOperand(2));
759 // load (select (cond, P, null)) -> load P
760 if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
761 LI.getPointerAddressSpace() == 0) {
762 LI.setOperand(0, SI->getOperand(1));
770 /// \brief Combine stores to match the type of value being stored.
772 /// The core idea here is that the memory does not have any intrinsic type and
773 /// where we can we should match the type of a store to the type of value being
776 /// However, this routine must never change the width of a store or the number of
777 /// stores as that would introduce a semantic change. This combine is expected to
778 /// be a semantic no-op which just allows stores to more closely model the types
779 /// of their incoming values.
781 /// Currently, we also refuse to change the precise type used for an atomic or
782 /// volatile store. This is debatable, and might be reasonable to change later.
783 /// However, it is risky in case some backend or other part of LLVM is relying
784 /// on the exact type stored to select appropriate atomic operations.
786 /// \returns true if the store was successfully combined away. This indicates
787 /// the caller must erase the store instruction. We have to let the caller erase
788 /// the store instruction sas otherwise there is no way to signal whether it was
789 /// combined or not: IC.EraseInstFromFunction returns a null pointer.
790 static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) {
791 // FIXME: We could probably with some care handle both volatile and atomic
792 // stores here but it isn't clear that this is important.
796 Value *V = SI.getValueOperand();
798 // Fold away bit casts of the stored value by storing the original type.
799 if (auto *BC = dyn_cast<BitCastInst>(V)) {
800 V = BC->getOperand(0);
801 combineStoreToNewValue(IC, SI, V);
805 // FIXME: We should also canonicalize loads of vectors when their elements are
806 // cast to other types.
810 /// equivalentAddressValues - Test if A and B will obviously have the same
811 /// value. This includes recognizing that %t0 and %t1 will have the same
812 /// value in code like this:
813 /// %t0 = getelementptr \@a, 0, 3
814 /// store i32 0, i32* %t0
815 /// %t1 = getelementptr \@a, 0, 3
816 /// %t2 = load i32* %t1
818 static bool equivalentAddressValues(Value *A, Value *B) {
819 // Test if the values are trivially equivalent.
820 if (A == B) return true;
822 // Test if the values come form identical arithmetic instructions.
823 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
824 // its only used to compare two uses within the same basic block, which
825 // means that they'll always either have the same value or one of them
826 // will have an undefined value.
827 if (isa<BinaryOperator>(A) ||
830 isa<GetElementPtrInst>(A))
831 if (Instruction *BI = dyn_cast<Instruction>(B))
832 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
835 // Otherwise they may not be equivalent.
839 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
840 Value *Val = SI.getOperand(0);
841 Value *Ptr = SI.getOperand(1);
843 // Try to canonicalize the stored type.
844 if (combineStoreToValueType(*this, SI))
845 return EraseInstFromFunction(SI);
847 // Attempt to improve the alignment.
849 unsigned KnownAlign = getOrEnforceKnownAlignment(
850 Ptr, DL->getPrefTypeAlignment(Val->getType()), DL, AC, &SI, DT);
851 unsigned StoreAlign = SI.getAlignment();
852 unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
853 DL->getABITypeAlignment(Val->getType());
855 if (KnownAlign > EffectiveStoreAlign)
856 SI.setAlignment(KnownAlign);
857 else if (StoreAlign == 0)
858 SI.setAlignment(EffectiveStoreAlign);
861 // Replace GEP indices if possible.
862 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) {
863 Worklist.Add(NewGEPI);
867 // Don't hack volatile/atomic stores.
868 // FIXME: Some bits are legal for atomic stores; needs refactoring.
869 if (!SI.isSimple()) return nullptr;
871 // If the RHS is an alloca with a single use, zapify the store, making the
873 if (Ptr->hasOneUse()) {
874 if (isa<AllocaInst>(Ptr))
875 return EraseInstFromFunction(SI);
876 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
877 if (isa<AllocaInst>(GEP->getOperand(0))) {
878 if (GEP->getOperand(0)->hasOneUse())
879 return EraseInstFromFunction(SI);
884 // Do really simple DSE, to catch cases where there are several consecutive
885 // stores to the same location, separated by a few arithmetic operations. This
886 // situation often occurs with bitfield accesses.
887 BasicBlock::iterator BBI = &SI;
888 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
891 // Don't count debug info directives, lest they affect codegen,
892 // and we skip pointer-to-pointer bitcasts, which are NOPs.
893 if (isa<DbgInfoIntrinsic>(BBI) ||
894 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
899 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
900 // Prev store isn't volatile, and stores to the same location?
901 if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
905 EraseInstFromFunction(*PrevSI);
911 // If this is a load, we have to stop. However, if the loaded value is from
912 // the pointer we're loading and is producing the pointer we're storing,
913 // then *this* store is dead (X = load P; store X -> P).
914 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
915 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
917 return EraseInstFromFunction(SI);
919 // Otherwise, this is a load from some other location. Stores before it
924 // Don't skip over loads or things that can modify memory.
925 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
929 // store X, null -> turns into 'unreachable' in SimplifyCFG
930 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
931 if (!isa<UndefValue>(Val)) {
932 SI.setOperand(0, UndefValue::get(Val->getType()));
933 if (Instruction *U = dyn_cast<Instruction>(Val))
934 Worklist.Add(U); // Dropped a use.
936 return nullptr; // Do not modify these!
939 // store undef, Ptr -> noop
940 if (isa<UndefValue>(Val))
941 return EraseInstFromFunction(SI);
943 // If this store is the last instruction in the basic block (possibly
944 // excepting debug info instructions), and if the block ends with an
945 // unconditional branch, try to move it to the successor block.
949 } while (isa<DbgInfoIntrinsic>(BBI) ||
950 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
951 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
952 if (BI->isUnconditional())
953 if (SimplifyStoreAtEndOfBlock(SI))
954 return nullptr; // xform done!
959 /// SimplifyStoreAtEndOfBlock - Turn things like:
960 /// if () { *P = v1; } else { *P = v2 }
961 /// into a phi node with a store in the successor.
963 /// Simplify things like:
964 /// *P = v1; if () { *P = v2; }
965 /// into a phi node with a store in the successor.
967 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
968 BasicBlock *StoreBB = SI.getParent();
970 // Check to see if the successor block has exactly two incoming edges. If
971 // so, see if the other predecessor contains a store to the same location.
972 // if so, insert a PHI node (if needed) and move the stores down.
973 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
975 // Determine whether Dest has exactly two predecessors and, if so, compute
976 // the other predecessor.
977 pred_iterator PI = pred_begin(DestBB);
979 BasicBlock *OtherBB = nullptr;
984 if (++PI == pred_end(DestBB))
993 if (++PI != pred_end(DestBB))
996 // Bail out if all the relevant blocks aren't distinct (this can happen,
997 // for example, if SI is in an infinite loop)
998 if (StoreBB == DestBB || OtherBB == DestBB)
1001 // Verify that the other block ends in a branch and is not otherwise empty.
1002 BasicBlock::iterator BBI = OtherBB->getTerminator();
1003 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
1004 if (!OtherBr || BBI == OtherBB->begin())
1007 // If the other block ends in an unconditional branch, check for the 'if then
1008 // else' case. there is an instruction before the branch.
1009 StoreInst *OtherStore = nullptr;
1010 if (OtherBr->isUnconditional()) {
1012 // Skip over debugging info.
1013 while (isa<DbgInfoIntrinsic>(BBI) ||
1014 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
1015 if (BBI==OtherBB->begin())
1019 // If this isn't a store, isn't a store to the same location, or is not the
1020 // right kind of store, bail out.
1021 OtherStore = dyn_cast<StoreInst>(BBI);
1022 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
1023 !SI.isSameOperationAs(OtherStore))
1026 // Otherwise, the other block ended with a conditional branch. If one of the
1027 // destinations is StoreBB, then we have the if/then case.
1028 if (OtherBr->getSuccessor(0) != StoreBB &&
1029 OtherBr->getSuccessor(1) != StoreBB)
1032 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
1033 // if/then triangle. See if there is a store to the same ptr as SI that
1034 // lives in OtherBB.
1036 // Check to see if we find the matching store.
1037 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
1038 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
1039 !SI.isSameOperationAs(OtherStore))
1043 // If we find something that may be using or overwriting the stored
1044 // value, or if we run out of instructions, we can't do the xform.
1045 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
1046 BBI == OtherBB->begin())
1050 // In order to eliminate the store in OtherBr, we have to
1051 // make sure nothing reads or overwrites the stored value in
1053 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1054 // FIXME: This should really be AA driven.
1055 if (I->mayReadFromMemory() || I->mayWriteToMemory())
1060 // Insert a PHI node now if we need it.
1061 Value *MergedVal = OtherStore->getOperand(0);
1062 if (MergedVal != SI.getOperand(0)) {
1063 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
1064 PN->addIncoming(SI.getOperand(0), SI.getParent());
1065 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
1066 MergedVal = InsertNewInstBefore(PN, DestBB->front());
1069 // Advance to a place where it is safe to insert the new store and
1071 BBI = DestBB->getFirstInsertionPt();
1072 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
1076 SI.getSynchScope());
1077 InsertNewInstBefore(NewSI, *BBI);
1078 NewSI->setDebugLoc(OtherStore->getDebugLoc());
1080 // If the two stores had AA tags, merge them.
1082 SI.getAAMetadata(AATags);
1084 OtherStore->getAAMetadata(AATags, /* Merge = */ true);
1085 NewSI->setAAMetadata(AATags);
1088 // Nuke the old stores.
1089 EraseInstFromFunction(SI);
1090 EraseInstFromFunction(*OtherStore);