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 static Instruction *simplifyAllocaArraySize(InstCombiner &IC, AllocaInst &AI) {
168 // Ensure that the alloca array size argument has type intptr_t, so that
169 // any casting is exposed early.
170 Type *IntPtrTy = IC.getDataLayout().getIntPtrType(AI.getType());
171 if (AI.getArraySize()->getType() != IntPtrTy) {
172 Value *V = IC.Builder->CreateIntCast(AI.getArraySize(), IntPtrTy, false);
178 if (!AI.isArrayAllocation())
181 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
182 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
183 Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
184 AllocaInst *New = IC.Builder->CreateAlloca(NewTy, nullptr, AI.getName());
185 New->setAlignment(AI.getAlignment());
187 // Scan to the end of the allocation instructions, to skip over a block of
188 // allocas if possible...also skip interleaved debug info
190 BasicBlock::iterator It = New;
191 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
194 // Now that I is pointing to the first non-allocation-inst in the block,
195 // insert our getelementptr instruction...
197 Type *IdxTy = IC.getDataLayout().getIntPtrType(AI.getType());
198 Value *NullIdx = Constant::getNullValue(IdxTy);
199 Value *Idx[2] = {NullIdx, NullIdx};
201 GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
202 IC.InsertNewInstBefore(GEP, *It);
204 // Now make everything use the getelementptr instead of the original
206 return IC.ReplaceInstUsesWith(AI, GEP);
209 if (isa<UndefValue>(AI.getArraySize()))
210 return IC.ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
215 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
216 if (auto *I = simplifyAllocaArraySize(*this, AI))
219 if (AI.getAllocatedType()->isSized()) {
220 // If the alignment is 0 (unspecified), assign it the preferred alignment.
221 if (AI.getAlignment() == 0)
222 AI.setAlignment(DL.getPrefTypeAlignment(AI.getAllocatedType()));
224 // Move all alloca's of zero byte objects to the entry block and merge them
225 // together. Note that we only do this for alloca's, because malloc should
226 // allocate and return a unique pointer, even for a zero byte allocation.
227 if (DL.getTypeAllocSize(AI.getAllocatedType()) == 0) {
228 // For a zero sized alloca there is no point in doing an array allocation.
229 // This is helpful if the array size is a complicated expression not used
231 if (AI.isArrayAllocation()) {
232 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
236 // Get the first instruction in the entry block.
237 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
238 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
239 if (FirstInst != &AI) {
240 // If the entry block doesn't start with a zero-size alloca then move
241 // this one to the start of the entry block. There is no problem with
242 // dominance as the array size was forced to a constant earlier already.
243 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
244 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
245 DL.getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
246 AI.moveBefore(FirstInst);
250 // If the alignment of the entry block alloca is 0 (unspecified),
251 // assign it the preferred alignment.
252 if (EntryAI->getAlignment() == 0)
253 EntryAI->setAlignment(
254 DL.getPrefTypeAlignment(EntryAI->getAllocatedType()));
255 // Replace this zero-sized alloca with the one at the start of the entry
256 // block after ensuring that the address will be aligned enough for both
258 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
260 EntryAI->setAlignment(MaxAlign);
261 if (AI.getType() != EntryAI->getType())
262 return new BitCastInst(EntryAI, AI.getType());
263 return ReplaceInstUsesWith(AI, EntryAI);
268 if (AI.getAlignment()) {
269 // Check to see if this allocation is only modified by a memcpy/memmove from
270 // a constant global whose alignment is equal to or exceeds that of the
271 // allocation. If this is the case, we can change all users to use
272 // the constant global instead. This is commonly produced by the CFE by
273 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
274 // is only subsequently read.
275 SmallVector<Instruction *, 4> ToDelete;
276 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
277 unsigned SourceAlign = getOrEnforceKnownAlignment(
278 Copy->getSource(), AI.getAlignment(), DL, &AI, AC, DT);
279 if (AI.getAlignment() <= SourceAlign) {
280 DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
281 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
282 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
283 EraseInstFromFunction(*ToDelete[i]);
284 Constant *TheSrc = cast<Constant>(Copy->getSource());
286 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
287 Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
288 EraseInstFromFunction(*Copy);
295 // At last, use the generic allocation site handler to aggressively remove
297 return visitAllocSite(AI);
300 /// \brief Helper to combine a load to a new type.
302 /// This just does the work of combining a load to a new type. It handles
303 /// metadata, etc., and returns the new instruction. The \c NewTy should be the
304 /// loaded *value* type. This will convert it to a pointer, cast the operand to
305 /// that pointer type, load it, etc.
307 /// Note that this will create all of the instructions with whatever insert
308 /// point the \c InstCombiner currently is using.
309 static LoadInst *combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy) {
310 Value *Ptr = LI.getPointerOperand();
311 unsigned AS = LI.getPointerAddressSpace();
312 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
313 LI.getAllMetadata(MD);
315 LoadInst *NewLoad = IC.Builder->CreateAlignedLoad(
316 IC.Builder->CreateBitCast(Ptr, NewTy->getPointerTo(AS)),
317 LI.getAlignment(), LI.getName());
318 MDBuilder MDB(NewLoad->getContext());
319 for (const auto &MDPair : MD) {
320 unsigned ID = MDPair.first;
321 MDNode *N = MDPair.second;
322 // Note, essentially every kind of metadata should be preserved here! This
323 // routine is supposed to clone a load instruction changing *only its type*.
324 // The only metadata it makes sense to drop is metadata which is invalidated
325 // when the pointer type changes. This should essentially never be the case
326 // in LLVM, but we explicitly switch over only known metadata to be
327 // conservatively correct. If you are adding metadata to LLVM which pertains
328 // to loads, you almost certainly want to add it here.
330 case LLVMContext::MD_dbg:
331 case LLVMContext::MD_tbaa:
332 case LLVMContext::MD_prof:
333 case LLVMContext::MD_fpmath:
334 case LLVMContext::MD_tbaa_struct:
335 case LLVMContext::MD_invariant_load:
336 case LLVMContext::MD_alias_scope:
337 case LLVMContext::MD_noalias:
338 case LLVMContext::MD_nontemporal:
339 case LLVMContext::MD_mem_parallel_loop_access:
340 // All of these directly apply.
341 NewLoad->setMetadata(ID, N);
344 case LLVMContext::MD_nonnull:
345 // This only directly applies if the new type is also a pointer.
346 if (NewTy->isPointerTy()) {
347 NewLoad->setMetadata(ID, N);
350 // If it's integral now, translate it to !range metadata.
351 if (NewTy->isIntegerTy()) {
352 auto *ITy = cast<IntegerType>(NewTy);
353 auto *NullInt = ConstantExpr::getPtrToInt(
354 ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
356 ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
357 NewLoad->setMetadata(LLVMContext::MD_range,
358 MDB.createRange(NonNullInt, NullInt));
362 case LLVMContext::MD_range:
363 // FIXME: It would be nice to propagate this in some way, but the type
364 // conversions make it hard. If the new type is a pointer, we could
365 // translate it to !nonnull metadata.
372 /// \brief Combine a store to a new type.
374 /// Returns the newly created store instruction.
375 static StoreInst *combineStoreToNewValue(InstCombiner &IC, StoreInst &SI, Value *V) {
376 Value *Ptr = SI.getPointerOperand();
377 unsigned AS = SI.getPointerAddressSpace();
378 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
379 SI.getAllMetadata(MD);
381 StoreInst *NewStore = IC.Builder->CreateAlignedStore(
382 V, IC.Builder->CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
384 for (const auto &MDPair : MD) {
385 unsigned ID = MDPair.first;
386 MDNode *N = MDPair.second;
387 // Note, essentially every kind of metadata should be preserved here! This
388 // routine is supposed to clone a store instruction changing *only its
389 // type*. The only metadata it makes sense to drop is metadata which is
390 // invalidated when the pointer type changes. This should essentially
391 // never be the case in LLVM, but we explicitly switch over only known
392 // metadata to be conservatively correct. If you are adding metadata to
393 // LLVM which pertains to stores, you almost certainly want to add it
396 case LLVMContext::MD_dbg:
397 case LLVMContext::MD_tbaa:
398 case LLVMContext::MD_prof:
399 case LLVMContext::MD_fpmath:
400 case LLVMContext::MD_tbaa_struct:
401 case LLVMContext::MD_alias_scope:
402 case LLVMContext::MD_noalias:
403 case LLVMContext::MD_nontemporal:
404 case LLVMContext::MD_mem_parallel_loop_access:
405 // All of these directly apply.
406 NewStore->setMetadata(ID, N);
409 case LLVMContext::MD_invariant_load:
410 case LLVMContext::MD_nonnull:
411 case LLVMContext::MD_range:
412 // These don't apply for stores.
420 /// \brief Combine loads to match the type of value their uses after looking
421 /// through intervening bitcasts.
423 /// The core idea here is that if the result of a load is used in an operation,
424 /// we should load the type most conducive to that operation. For example, when
425 /// loading an integer and converting that immediately to a pointer, we should
426 /// instead directly load a pointer.
428 /// However, this routine must never change the width of a load or the number of
429 /// loads as that would introduce a semantic change. This combine is expected to
430 /// be a semantic no-op which just allows loads to more closely model the types
431 /// of their consuming operations.
433 /// Currently, we also refuse to change the precise type used for an atomic load
434 /// or a volatile load. This is debatable, and might be reasonable to change
435 /// later. However, it is risky in case some backend or other part of LLVM is
436 /// relying on the exact type loaded to select appropriate atomic operations.
437 static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
438 // FIXME: We could probably with some care handle both volatile and atomic
439 // loads here but it isn't clear that this is important.
446 Type *Ty = LI.getType();
447 const DataLayout &DL = IC.getDataLayout();
449 // Try to canonicalize loads which are only ever stored to operate over
450 // integers instead of any other type. We only do this when the loaded type
451 // is sized and has a size exactly the same as its store size and the store
452 // size is a legal integer type.
453 if (!Ty->isIntegerTy() && Ty->isSized() &&
454 DL.isLegalInteger(DL.getTypeStoreSizeInBits(Ty)) &&
455 DL.getTypeStoreSizeInBits(Ty) == DL.getTypeSizeInBits(Ty)) {
456 if (std::all_of(LI.user_begin(), LI.user_end(), [&LI](User *U) {
457 auto *SI = dyn_cast<StoreInst>(U);
458 return SI && SI->getPointerOperand() != &LI;
460 LoadInst *NewLoad = combineLoadToNewType(
462 Type::getIntNTy(LI.getContext(), DL.getTypeStoreSizeInBits(Ty)));
463 // Replace all the stores with stores of the newly loaded value.
464 for (auto UI = LI.user_begin(), UE = LI.user_end(); UI != UE;) {
465 auto *SI = cast<StoreInst>(*UI++);
466 IC.Builder->SetInsertPoint(SI);
467 combineStoreToNewValue(IC, *SI, NewLoad);
468 IC.EraseInstFromFunction(*SI);
470 assert(LI.use_empty() && "Failed to remove all users of the load!");
471 // Return the old load so the combiner can delete it safely.
476 // Fold away bit casts of the loaded value by loading the desired type.
478 if (auto *BC = dyn_cast<BitCastInst>(LI.user_back())) {
479 LoadInst *NewLoad = combineLoadToNewType(IC, LI, BC->getDestTy());
480 BC->replaceAllUsesWith(NewLoad);
481 IC.EraseInstFromFunction(*BC);
485 // FIXME: We should also canonicalize loads of vectors when their elements are
486 // cast to other types.
490 // If we can determine that all possible objects pointed to by the provided
491 // pointer value are, not only dereferenceable, but also definitively less than
492 // or equal to the provided maximum size, then return true. Otherwise, return
493 // false (constant global values and allocas fall into this category).
495 // FIXME: This should probably live in ValueTracking (or similar).
496 static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize,
497 const DataLayout &DL) {
498 SmallPtrSet<Value *, 4> Visited;
499 SmallVector<Value *, 4> Worklist(1, V);
502 Value *P = Worklist.pop_back_val();
503 P = P->stripPointerCasts();
505 if (!Visited.insert(P).second)
508 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
509 Worklist.push_back(SI->getTrueValue());
510 Worklist.push_back(SI->getFalseValue());
514 if (PHINode *PN = dyn_cast<PHINode>(P)) {
515 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
516 Worklist.push_back(PN->getIncomingValue(i));
520 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
521 if (GA->mayBeOverridden())
523 Worklist.push_back(GA->getAliasee());
527 // If we know how big this object is, and it is less than MaxSize, continue
528 // searching. Otherwise, return false.
529 if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
530 if (!AI->getAllocatedType()->isSized())
533 ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
537 uint64_t TypeSize = DL.getTypeAllocSize(AI->getAllocatedType());
538 // Make sure that, even if the multiplication below would wrap as an
539 // uint64_t, we still do the right thing.
540 if ((CS->getValue().zextOrSelf(128)*APInt(128, TypeSize)).ugt(MaxSize))
545 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
546 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
549 uint64_t InitSize = DL.getTypeAllocSize(GV->getType()->getElementType());
550 if (InitSize > MaxSize)
556 } while (!Worklist.empty());
561 // If we're indexing into an object of a known size, and the outer index is
562 // not a constant, but having any value but zero would lead to undefined
563 // behavior, replace it with zero.
565 // For example, if we have:
566 // @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
568 // %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x
569 // ... = load i32* %arrayidx, align 4
570 // Then we know that we can replace %x in the GEP with i64 0.
572 // FIXME: We could fold any GEP index to zero that would cause UB if it were
573 // not zero. Currently, we only handle the first such index. Also, we could
574 // also search through non-zero constant indices if we kept track of the
575 // offsets those indices implied.
576 static bool canReplaceGEPIdxWithZero(InstCombiner &IC, GetElementPtrInst *GEPI,
577 Instruction *MemI, unsigned &Idx) {
578 if (GEPI->getNumOperands() < 2)
581 // Find the first non-zero index of a GEP. If all indices are zero, return
582 // one past the last index.
583 auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
585 for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
586 Value *V = GEPI->getOperand(I);
587 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
597 // Skip through initial 'zero' indices, and find the corresponding pointer
598 // type. See if the next index is not a constant.
599 Idx = FirstNZIdx(GEPI);
600 if (Idx == GEPI->getNumOperands())
602 if (isa<Constant>(GEPI->getOperand(Idx)))
605 SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
607 GetElementPtrInst::getIndexedType(GEPI->getOperand(0)->getType(), Ops);
608 if (!AllocTy || !AllocTy->isSized())
610 const DataLayout &DL = IC.getDataLayout();
611 uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy);
613 // If there are more indices after the one we might replace with a zero, make
614 // sure they're all non-negative. If any of them are negative, the overall
615 // address being computed might be before the base address determined by the
616 // first non-zero index.
617 auto IsAllNonNegative = [&]() {
618 for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
619 bool KnownNonNegative, KnownNegative;
620 IC.ComputeSignBit(GEPI->getOperand(i), KnownNonNegative,
621 KnownNegative, 0, MemI);
622 if (KnownNonNegative)
630 // FIXME: If the GEP is not inbounds, and there are extra indices after the
631 // one we'll replace, those could cause the address computation to wrap
632 // (rendering the IsAllNonNegative() check below insufficient). We can do
633 // better, ignoring zero indicies (and other indicies we can prove small
634 // enough not to wrap).
635 if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
638 // Note that isObjectSizeLessThanOrEq will return true only if the pointer is
639 // also known to be dereferenceable.
640 return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
644 // If we're indexing into an object with a variable index for the memory
645 // access, but the object has only one element, we can assume that the index
646 // will always be zero. If we replace the GEP, return it.
647 template <typename T>
648 static Instruction *replaceGEPIdxWithZero(InstCombiner &IC, Value *Ptr,
650 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
652 if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
653 Instruction *NewGEPI = GEPI->clone();
654 NewGEPI->setOperand(Idx,
655 ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
656 NewGEPI->insertBefore(GEPI);
657 MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI);
665 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
666 Value *Op = LI.getOperand(0);
668 // Try to canonicalize the loaded type.
669 if (Instruction *Res = combineLoadToOperationType(*this, LI))
672 // Attempt to improve the alignment.
673 unsigned KnownAlign = getOrEnforceKnownAlignment(
674 Op, DL.getPrefTypeAlignment(LI.getType()), DL, &LI, AC, DT);
675 unsigned LoadAlign = LI.getAlignment();
676 unsigned EffectiveLoadAlign =
677 LoadAlign != 0 ? LoadAlign : DL.getABITypeAlignment(LI.getType());
679 if (KnownAlign > EffectiveLoadAlign)
680 LI.setAlignment(KnownAlign);
681 else if (LoadAlign == 0)
682 LI.setAlignment(EffectiveLoadAlign);
684 // Replace GEP indices if possible.
685 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) {
686 Worklist.Add(NewGEPI);
690 // None of the following transforms are legal for volatile/atomic loads.
691 // FIXME: Some of it is okay for atomic loads; needs refactoring.
692 if (!LI.isSimple()) return nullptr;
694 // Do really simple store-to-load forwarding and load CSE, to catch cases
695 // where there are several consecutive memory accesses to the same location,
696 // separated by a few arithmetic operations.
697 BasicBlock::iterator BBI = &LI;
698 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
699 return ReplaceInstUsesWith(
700 LI, Builder->CreateBitOrPointerCast(AvailableVal, LI.getType(),
701 LI.getName() + ".cast"));
703 // load(gep null, ...) -> unreachable
704 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
705 const Value *GEPI0 = GEPI->getOperand(0);
706 // TODO: Consider a target hook for valid address spaces for this xform.
707 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
708 // Insert a new store to null instruction before the load to indicate
709 // that this code is not reachable. We do this instead of inserting
710 // an unreachable instruction directly because we cannot modify the
712 new StoreInst(UndefValue::get(LI.getType()),
713 Constant::getNullValue(Op->getType()), &LI);
714 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
718 // load null/undef -> unreachable
719 // TODO: Consider a target hook for valid address spaces for this xform.
720 if (isa<UndefValue>(Op) ||
721 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
722 // Insert a new store to null instruction before the load to indicate that
723 // this code is not reachable. We do this instead of inserting an
724 // unreachable instruction directly because we cannot modify the CFG.
725 new StoreInst(UndefValue::get(LI.getType()),
726 Constant::getNullValue(Op->getType()), &LI);
727 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
730 if (Op->hasOneUse()) {
731 // Change select and PHI nodes to select values instead of addresses: this
732 // helps alias analysis out a lot, allows many others simplifications, and
733 // exposes redundancy in the code.
735 // Note that we cannot do the transformation unless we know that the
736 // introduced loads cannot trap! Something like this is valid as long as
737 // the condition is always false: load (select bool %C, int* null, int* %G),
738 // but it would not be valid if we transformed it to load from null
741 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
742 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
743 unsigned Align = LI.getAlignment();
744 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align) &&
745 isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align)) {
746 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
747 SI->getOperand(1)->getName()+".val");
748 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
749 SI->getOperand(2)->getName()+".val");
750 V1->setAlignment(Align);
751 V2->setAlignment(Align);
752 return SelectInst::Create(SI->getCondition(), V1, V2);
755 // load (select (cond, null, P)) -> load P
756 if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
757 LI.getPointerAddressSpace() == 0) {
758 LI.setOperand(0, SI->getOperand(2));
762 // load (select (cond, P, null)) -> load P
763 if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
764 LI.getPointerAddressSpace() == 0) {
765 LI.setOperand(0, SI->getOperand(1));
773 /// \brief Combine stores to match the type of value being stored.
775 /// The core idea here is that the memory does not have any intrinsic type and
776 /// where we can we should match the type of a store to the type of value being
779 /// However, this routine must never change the width of a store or the number of
780 /// stores as that would introduce a semantic change. This combine is expected to
781 /// be a semantic no-op which just allows stores to more closely model the types
782 /// of their incoming values.
784 /// Currently, we also refuse to change the precise type used for an atomic or
785 /// volatile store. This is debatable, and might be reasonable to change later.
786 /// However, it is risky in case some backend or other part of LLVM is relying
787 /// on the exact type stored to select appropriate atomic operations.
789 /// \returns true if the store was successfully combined away. This indicates
790 /// the caller must erase the store instruction. We have to let the caller erase
791 /// the store instruction sas otherwise there is no way to signal whether it was
792 /// combined or not: IC.EraseInstFromFunction returns a null pointer.
793 static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) {
794 // FIXME: We could probably with some care handle both volatile and atomic
795 // stores here but it isn't clear that this is important.
799 Value *V = SI.getValueOperand();
801 // Fold away bit casts of the stored value by storing the original type.
802 if (auto *BC = dyn_cast<BitCastInst>(V)) {
803 V = BC->getOperand(0);
804 combineStoreToNewValue(IC, SI, V);
808 // FIXME: We should also canonicalize loads of vectors when their elements are
809 // cast to other types.
813 /// equivalentAddressValues - Test if A and B will obviously have the same
814 /// value. This includes recognizing that %t0 and %t1 will have the same
815 /// value in code like this:
816 /// %t0 = getelementptr \@a, 0, 3
817 /// store i32 0, i32* %t0
818 /// %t1 = getelementptr \@a, 0, 3
819 /// %t2 = load i32* %t1
821 static bool equivalentAddressValues(Value *A, Value *B) {
822 // Test if the values are trivially equivalent.
823 if (A == B) return true;
825 // Test if the values come form identical arithmetic instructions.
826 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
827 // its only used to compare two uses within the same basic block, which
828 // means that they'll always either have the same value or one of them
829 // will have an undefined value.
830 if (isa<BinaryOperator>(A) ||
833 isa<GetElementPtrInst>(A))
834 if (Instruction *BI = dyn_cast<Instruction>(B))
835 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
838 // Otherwise they may not be equivalent.
842 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
843 Value *Val = SI.getOperand(0);
844 Value *Ptr = SI.getOperand(1);
846 // Try to canonicalize the stored type.
847 if (combineStoreToValueType(*this, SI))
848 return EraseInstFromFunction(SI);
850 // Attempt to improve the alignment.
851 unsigned KnownAlign = getOrEnforceKnownAlignment(
852 Ptr, DL.getPrefTypeAlignment(Val->getType()), DL, &SI, AC, DT);
853 unsigned StoreAlign = SI.getAlignment();
854 unsigned EffectiveStoreAlign =
855 StoreAlign != 0 ? StoreAlign : DL.getABITypeAlignment(Val->getType());
857 if (KnownAlign > EffectiveStoreAlign)
858 SI.setAlignment(KnownAlign);
859 else if (StoreAlign == 0)
860 SI.setAlignment(EffectiveStoreAlign);
862 // Replace GEP indices if possible.
863 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) {
864 Worklist.Add(NewGEPI);
868 // Don't hack volatile/atomic stores.
869 // FIXME: Some bits are legal for atomic stores; needs refactoring.
870 if (!SI.isSimple()) return nullptr;
872 // If the RHS is an alloca with a single use, zapify the store, making the
874 if (Ptr->hasOneUse()) {
875 if (isa<AllocaInst>(Ptr))
876 return EraseInstFromFunction(SI);
877 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
878 if (isa<AllocaInst>(GEP->getOperand(0))) {
879 if (GEP->getOperand(0)->hasOneUse())
880 return EraseInstFromFunction(SI);
885 // Do really simple DSE, to catch cases where there are several consecutive
886 // stores to the same location, separated by a few arithmetic operations. This
887 // situation often occurs with bitfield accesses.
888 BasicBlock::iterator BBI = &SI;
889 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
892 // Don't count debug info directives, lest they affect codegen,
893 // and we skip pointer-to-pointer bitcasts, which are NOPs.
894 if (isa<DbgInfoIntrinsic>(BBI) ||
895 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
900 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
901 // Prev store isn't volatile, and stores to the same location?
902 if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
906 EraseInstFromFunction(*PrevSI);
912 // If this is a load, we have to stop. However, if the loaded value is from
913 // the pointer we're loading and is producing the pointer we're storing,
914 // then *this* store is dead (X = load P; store X -> P).
915 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
916 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
918 return EraseInstFromFunction(SI);
920 // Otherwise, this is a load from some other location. Stores before it
925 // Don't skip over loads or things that can modify memory.
926 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
930 // store X, null -> turns into 'unreachable' in SimplifyCFG
931 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
932 if (!isa<UndefValue>(Val)) {
933 SI.setOperand(0, UndefValue::get(Val->getType()));
934 if (Instruction *U = dyn_cast<Instruction>(Val))
935 Worklist.Add(U); // Dropped a use.
937 return nullptr; // Do not modify these!
940 // store undef, Ptr -> noop
941 if (isa<UndefValue>(Val))
942 return EraseInstFromFunction(SI);
944 // If this store is the last instruction in the basic block (possibly
945 // excepting debug info instructions), and if the block ends with an
946 // unconditional branch, try to move it to the successor block.
950 } while (isa<DbgInfoIntrinsic>(BBI) ||
951 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
952 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
953 if (BI->isUnconditional())
954 if (SimplifyStoreAtEndOfBlock(SI))
955 return nullptr; // xform done!
960 /// SimplifyStoreAtEndOfBlock - Turn things like:
961 /// if () { *P = v1; } else { *P = v2 }
962 /// into a phi node with a store in the successor.
964 /// Simplify things like:
965 /// *P = v1; if () { *P = v2; }
966 /// into a phi node with a store in the successor.
968 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
969 BasicBlock *StoreBB = SI.getParent();
971 // Check to see if the successor block has exactly two incoming edges. If
972 // so, see if the other predecessor contains a store to the same location.
973 // if so, insert a PHI node (if needed) and move the stores down.
974 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
976 // Determine whether Dest has exactly two predecessors and, if so, compute
977 // the other predecessor.
978 pred_iterator PI = pred_begin(DestBB);
980 BasicBlock *OtherBB = nullptr;
985 if (++PI == pred_end(DestBB))
994 if (++PI != pred_end(DestBB))
997 // Bail out if all the relevant blocks aren't distinct (this can happen,
998 // for example, if SI is in an infinite loop)
999 if (StoreBB == DestBB || OtherBB == DestBB)
1002 // Verify that the other block ends in a branch and is not otherwise empty.
1003 BasicBlock::iterator BBI = OtherBB->getTerminator();
1004 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
1005 if (!OtherBr || BBI == OtherBB->begin())
1008 // If the other block ends in an unconditional branch, check for the 'if then
1009 // else' case. there is an instruction before the branch.
1010 StoreInst *OtherStore = nullptr;
1011 if (OtherBr->isUnconditional()) {
1013 // Skip over debugging info.
1014 while (isa<DbgInfoIntrinsic>(BBI) ||
1015 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
1016 if (BBI==OtherBB->begin())
1020 // If this isn't a store, isn't a store to the same location, or is not the
1021 // right kind of store, bail out.
1022 OtherStore = dyn_cast<StoreInst>(BBI);
1023 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
1024 !SI.isSameOperationAs(OtherStore))
1027 // Otherwise, the other block ended with a conditional branch. If one of the
1028 // destinations is StoreBB, then we have the if/then case.
1029 if (OtherBr->getSuccessor(0) != StoreBB &&
1030 OtherBr->getSuccessor(1) != StoreBB)
1033 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
1034 // if/then triangle. See if there is a store to the same ptr as SI that
1035 // lives in OtherBB.
1037 // Check to see if we find the matching store.
1038 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
1039 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
1040 !SI.isSameOperationAs(OtherStore))
1044 // If we find something that may be using or overwriting the stored
1045 // value, or if we run out of instructions, we can't do the xform.
1046 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
1047 BBI == OtherBB->begin())
1051 // In order to eliminate the store in OtherBr, we have to
1052 // make sure nothing reads or overwrites the stored value in
1054 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1055 // FIXME: This should really be AA driven.
1056 if (I->mayReadFromMemory() || I->mayWriteToMemory())
1061 // Insert a PHI node now if we need it.
1062 Value *MergedVal = OtherStore->getOperand(0);
1063 if (MergedVal != SI.getOperand(0)) {
1064 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
1065 PN->addIncoming(SI.getOperand(0), SI.getParent());
1066 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
1067 MergedVal = InsertNewInstBefore(PN, DestBB->front());
1070 // Advance to a place where it is safe to insert the new store and
1072 BBI = DestBB->getFirstInsertionPt();
1073 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
1077 SI.getSynchScope());
1078 InsertNewInstBefore(NewSI, *BBI);
1079 NewSI->setDebugLoc(OtherStore->getDebugLoc());
1081 // If the two stores had AA tags, merge them.
1083 SI.getAAMetadata(AATags);
1085 OtherStore->getAAMetadata(AATags, /* Merge = */ true);
1086 NewSI->setAAMetadata(AATags);
1089 // Nuke the old stores.
1090 EraseInstFromFunction(SI);
1091 EraseInstFromFunction(*OtherStore);