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 "InstCombine.h"
15
#include "llvm/IntrinsicInst.h"
16
#include "llvm/Target/TargetData.h"
17
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
18
#include "llvm/Transforms/Utils/Local.h"
19
#include "llvm/ADT/Statistic.h"
22
STATISTIC(NumDeadStore, "Number of dead stores eliminated");
24
Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
25
// Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
26
if (AI.isArrayAllocation()) { // Check C != 1
27
if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
29
ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
30
assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
31
AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
32
New->setAlignment(AI.getAlignment());
34
// Scan to the end of the allocation instructions, to skip over a block of
35
// allocas if possible...also skip interleaved debug info
37
BasicBlock::iterator It = New;
38
while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
40
// Now that I is pointing to the first non-allocation-inst in the block,
41
// insert our getelementptr instruction...
43
Value *NullIdx =Constant::getNullValue(Type::getInt32Ty(AI.getContext()));
47
Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
48
New->getName()+".sub", It);
50
// Now make everything use the getelementptr instead of the original
52
return ReplaceInstUsesWith(AI, V);
53
} else if (isa<UndefValue>(AI.getArraySize())) {
54
return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
58
if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
59
// If alloca'ing a zero byte object, replace the alloca with a null pointer.
60
// Note that we only do this for alloca's, because malloc should allocate
61
// and return a unique pointer, even for a zero byte allocation.
62
if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
63
return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
65
// If the alignment is 0 (unspecified), assign it the preferred alignment.
66
if (AI.getAlignment() == 0)
67
AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
74
/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
75
static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
76
const TargetData *TD) {
77
User *CI = cast<User>(LI.getOperand(0));
78
Value *CastOp = CI->getOperand(0);
80
const PointerType *DestTy = cast<PointerType>(CI->getType());
81
const Type *DestPTy = DestTy->getElementType();
82
if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
84
// If the address spaces don't match, don't eliminate the cast.
85
if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
88
const Type *SrcPTy = SrcTy->getElementType();
90
if (DestPTy->isIntegerTy() || DestPTy->isPointerTy() ||
91
DestPTy->isVectorTy()) {
92
// If the source is an array, the code below will not succeed. Check to
93
// see if a trivial 'gep P, 0, 0' will help matters. Only do this for
95
if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
96
if (Constant *CSrc = dyn_cast<Constant>(CastOp))
97
if (ASrcTy->getNumElements() != 0) {
99
Idxs[0] = Constant::getNullValue(Type::getInt32Ty(LI.getContext()));
101
CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
102
SrcTy = cast<PointerType>(CastOp->getType());
103
SrcPTy = SrcTy->getElementType();
106
if (IC.getTargetData() &&
107
(SrcPTy->isIntegerTy() || SrcPTy->isPointerTy() ||
108
SrcPTy->isVectorTy()) &&
109
// Do not allow turning this into a load of an integer, which is then
110
// casted to a pointer, this pessimizes pointer analysis a lot.
111
(SrcPTy->isPointerTy() == LI.getType()->isPointerTy()) &&
112
IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
113
IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
115
// Okay, we are casting from one integer or pointer type to another of
116
// the same size. Instead of casting the pointer before the load, cast
117
// the result of the loaded value.
119
IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
120
NewLoad->setAlignment(LI.getAlignment());
121
// Now cast the result of the load.
122
return new BitCastInst(NewLoad, LI.getType());
129
Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
130
Value *Op = LI.getOperand(0);
132
// Attempt to improve the alignment.
134
unsigned KnownAlign =
135
GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
137
(LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
139
LI.setAlignment(KnownAlign);
142
// load (cast X) --> cast (load X) iff safe.
143
if (isa<CastInst>(Op))
144
if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
147
// None of the following transforms are legal for volatile loads.
148
if (LI.isVolatile()) return 0;
150
// Do really simple store-to-load forwarding and load CSE, to catch cases
151
// where there are several consequtive memory accesses to the same location,
152
// separated by a few arithmetic operations.
153
BasicBlock::iterator BBI = &LI;
154
if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
155
return ReplaceInstUsesWith(LI, AvailableVal);
157
// load(gep null, ...) -> unreachable
158
if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
159
const Value *GEPI0 = GEPI->getOperand(0);
160
// TODO: Consider a target hook for valid address spaces for this xform.
161
if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
162
// Insert a new store to null instruction before the load to indicate
163
// that this code is not reachable. We do this instead of inserting
164
// an unreachable instruction directly because we cannot modify the
166
new StoreInst(UndefValue::get(LI.getType()),
167
Constant::getNullValue(Op->getType()), &LI);
168
return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
172
// load null/undef -> unreachable
173
// TODO: Consider a target hook for valid address spaces for this xform.
174
if (isa<UndefValue>(Op) ||
175
(isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
176
// Insert a new store to null instruction before the load to indicate that
177
// this code is not reachable. We do this instead of inserting an
178
// unreachable instruction directly because we cannot modify the CFG.
179
new StoreInst(UndefValue::get(LI.getType()),
180
Constant::getNullValue(Op->getType()), &LI);
181
return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
184
// Instcombine load (constantexpr_cast global) -> cast (load global)
185
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
187
if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
190
if (Op->hasOneUse()) {
191
// Change select and PHI nodes to select values instead of addresses: this
192
// helps alias analysis out a lot, allows many others simplifications, and
193
// exposes redundancy in the code.
195
// Note that we cannot do the transformation unless we know that the
196
// introduced loads cannot trap! Something like this is valid as long as
197
// the condition is always false: load (select bool %C, int* null, int* %G),
198
// but it would not be valid if we transformed it to load from null
201
if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
202
// load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
203
unsigned Align = LI.getAlignment();
204
if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, TD) &&
205
isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, TD)) {
206
LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
207
SI->getOperand(1)->getName()+".val");
208
LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
209
SI->getOperand(2)->getName()+".val");
210
V1->setAlignment(Align);
211
V2->setAlignment(Align);
212
return SelectInst::Create(SI->getCondition(), V1, V2);
215
// load (select (cond, null, P)) -> load P
216
if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
217
if (C->isNullValue()) {
218
LI.setOperand(0, SI->getOperand(2));
222
// load (select (cond, P, null)) -> load P
223
if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
224
if (C->isNullValue()) {
225
LI.setOperand(0, SI->getOperand(1));
233
/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
234
/// when possible. This makes it generally easy to do alias analysis and/or
235
/// SROA/mem2reg of the memory object.
236
static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
237
User *CI = cast<User>(SI.getOperand(1));
238
Value *CastOp = CI->getOperand(0);
240
const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
241
const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
242
if (SrcTy == 0) return 0;
244
const Type *SrcPTy = SrcTy->getElementType();
246
if (!DestPTy->isIntegerTy() && !DestPTy->isPointerTy())
249
/// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
250
/// to its first element. This allows us to handle things like:
251
/// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
253
SmallVector<Value*, 4> NewGEPIndices;
255
// If the source is an array, the code below will not succeed. Check to
256
// see if a trivial 'gep P, 0, 0' will help matters. Only do this for
258
if (SrcPTy->isArrayTy() || SrcPTy->isStructTy()) {
259
// Index through pointer.
260
Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
261
NewGEPIndices.push_back(Zero);
264
if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
265
if (!STy->getNumElements()) /* Struct can be empty {} */
267
NewGEPIndices.push_back(Zero);
268
SrcPTy = STy->getElementType(0);
269
} else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
270
NewGEPIndices.push_back(Zero);
271
SrcPTy = ATy->getElementType();
277
SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
280
if (!SrcPTy->isIntegerTy() && !SrcPTy->isPointerTy())
283
// If the pointers point into different address spaces or if they point to
284
// values with different sizes, we can't do the transformation.
285
if (!IC.getTargetData() ||
286
SrcTy->getAddressSpace() !=
287
cast<PointerType>(CI->getType())->getAddressSpace() ||
288
IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
289
IC.getTargetData()->getTypeSizeInBits(DestPTy))
292
// Okay, we are casting from one integer or pointer type to another of
293
// the same size. Instead of casting the pointer before
294
// the store, cast the value to be stored.
296
Value *SIOp0 = SI.getOperand(0);
297
Instruction::CastOps opcode = Instruction::BitCast;
298
const Type* CastSrcTy = SIOp0->getType();
299
const Type* CastDstTy = SrcPTy;
300
if (CastDstTy->isPointerTy()) {
301
if (CastSrcTy->isIntegerTy())
302
opcode = Instruction::IntToPtr;
303
} else if (CastDstTy->isIntegerTy()) {
304
if (SIOp0->getType()->isPointerTy())
305
opcode = Instruction::PtrToInt;
308
// SIOp0 is a pointer to aggregate and this is a store to the first field,
309
// emit a GEP to index into its first field.
310
if (!NewGEPIndices.empty())
311
CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
312
NewGEPIndices.end());
314
NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
315
SIOp0->getName()+".c");
316
return new StoreInst(NewCast, CastOp);
319
/// equivalentAddressValues - Test if A and B will obviously have the same
320
/// value. This includes recognizing that %t0 and %t1 will have the same
321
/// value in code like this:
322
/// %t0 = getelementptr \@a, 0, 3
323
/// store i32 0, i32* %t0
324
/// %t1 = getelementptr \@a, 0, 3
325
/// %t2 = load i32* %t1
327
static bool equivalentAddressValues(Value *A, Value *B) {
328
// Test if the values are trivially equivalent.
329
if (A == B) return true;
331
// Test if the values come form identical arithmetic instructions.
332
// This uses isIdenticalToWhenDefined instead of isIdenticalTo because
333
// its only used to compare two uses within the same basic block, which
334
// means that they'll always either have the same value or one of them
335
// will have an undefined value.
336
if (isa<BinaryOperator>(A) ||
339
isa<GetElementPtrInst>(A))
340
if (Instruction *BI = dyn_cast<Instruction>(B))
341
if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
344
// Otherwise they may not be equivalent.
348
// If this instruction has two uses, one of which is a llvm.dbg.declare,
349
// return the llvm.dbg.declare.
350
DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
353
for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
355
if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
357
if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
358
if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
365
Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
366
Value *Val = SI.getOperand(0);
367
Value *Ptr = SI.getOperand(1);
369
// If the RHS is an alloca with a single use, zapify the store, making the
371
// If the RHS is an alloca with a two uses, the other one being a
372
// llvm.dbg.declare, zapify the store and the declare, making the
373
// alloca dead. We must do this to prevent declares from affecting
375
if (!SI.isVolatile()) {
376
if (Ptr->hasOneUse()) {
377
if (isa<AllocaInst>(Ptr))
378
return EraseInstFromFunction(SI);
379
if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
380
if (isa<AllocaInst>(GEP->getOperand(0))) {
381
if (GEP->getOperand(0)->hasOneUse())
382
return EraseInstFromFunction(SI);
383
if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
384
EraseInstFromFunction(*DI);
385
return EraseInstFromFunction(SI);
390
if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
391
EraseInstFromFunction(*DI);
392
return EraseInstFromFunction(SI);
396
// Attempt to improve the alignment.
398
unsigned KnownAlign =
399
GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
401
(SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
403
SI.setAlignment(KnownAlign);
406
// Do really simple DSE, to catch cases where there are several consecutive
407
// stores to the same location, separated by a few arithmetic operations. This
408
// situation often occurs with bitfield accesses.
409
BasicBlock::iterator BBI = &SI;
410
for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
413
// Don't count debug info directives, lest they affect codegen,
414
// and we skip pointer-to-pointer bitcasts, which are NOPs.
415
if (isa<DbgInfoIntrinsic>(BBI) ||
416
(isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
421
if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
422
// Prev store isn't volatile, and stores to the same location?
423
if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
427
EraseInstFromFunction(*PrevSI);
433
// If this is a load, we have to stop. However, if the loaded value is from
434
// the pointer we're loading and is producing the pointer we're storing,
435
// then *this* store is dead (X = load P; store X -> P).
436
if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
437
if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
439
return EraseInstFromFunction(SI);
441
// Otherwise, this is a load from some other location. Stores before it
446
// Don't skip over loads or things that can modify memory.
447
if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
452
if (SI.isVolatile()) return 0; // Don't hack volatile stores.
454
// store X, null -> turns into 'unreachable' in SimplifyCFG
455
if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
456
if (!isa<UndefValue>(Val)) {
457
SI.setOperand(0, UndefValue::get(Val->getType()));
458
if (Instruction *U = dyn_cast<Instruction>(Val))
459
Worklist.Add(U); // Dropped a use.
461
return 0; // Do not modify these!
464
// store undef, Ptr -> noop
465
if (isa<UndefValue>(Val))
466
return EraseInstFromFunction(SI);
468
// If the pointer destination is a cast, see if we can fold the cast into the
470
if (isa<CastInst>(Ptr))
471
if (Instruction *Res = InstCombineStoreToCast(*this, SI))
473
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
475
if (Instruction *Res = InstCombineStoreToCast(*this, SI))
479
// If this store is the last instruction in the basic block (possibly
480
// excepting debug info instructions), and if the block ends with an
481
// unconditional branch, try to move it to the successor block.
485
} while (isa<DbgInfoIntrinsic>(BBI) ||
486
(isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
487
if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
488
if (BI->isUnconditional())
489
if (SimplifyStoreAtEndOfBlock(SI))
490
return 0; // xform done!
495
/// SimplifyStoreAtEndOfBlock - Turn things like:
496
/// if () { *P = v1; } else { *P = v2 }
497
/// into a phi node with a store in the successor.
499
/// Simplify things like:
500
/// *P = v1; if () { *P = v2; }
501
/// into a phi node with a store in the successor.
503
bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
504
BasicBlock *StoreBB = SI.getParent();
506
// Check to see if the successor block has exactly two incoming edges. If
507
// so, see if the other predecessor contains a store to the same location.
508
// if so, insert a PHI node (if needed) and move the stores down.
509
BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
511
// Determine whether Dest has exactly two predecessors and, if so, compute
512
// the other predecessor.
513
pred_iterator PI = pred_begin(DestBB);
514
BasicBlock *OtherBB = 0;
518
if (PI == pred_end(DestBB))
521
if (*PI != StoreBB) {
526
if (++PI != pred_end(DestBB))
529
// Bail out if all the relevant blocks aren't distinct (this can happen,
530
// for example, if SI is in an infinite loop)
531
if (StoreBB == DestBB || OtherBB == DestBB)
534
// Verify that the other block ends in a branch and is not otherwise empty.
535
BasicBlock::iterator BBI = OtherBB->getTerminator();
536
BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
537
if (!OtherBr || BBI == OtherBB->begin())
540
// If the other block ends in an unconditional branch, check for the 'if then
541
// else' case. there is an instruction before the branch.
542
StoreInst *OtherStore = 0;
543
if (OtherBr->isUnconditional()) {
545
// Skip over debugging info.
546
while (isa<DbgInfoIntrinsic>(BBI) ||
547
(isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
548
if (BBI==OtherBB->begin())
552
// If this isn't a store, isn't a store to the same location, or if the
553
// alignments differ, bail out.
554
OtherStore = dyn_cast<StoreInst>(BBI);
555
if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
556
OtherStore->getAlignment() != SI.getAlignment())
559
// Otherwise, the other block ended with a conditional branch. If one of the
560
// destinations is StoreBB, then we have the if/then case.
561
if (OtherBr->getSuccessor(0) != StoreBB &&
562
OtherBr->getSuccessor(1) != StoreBB)
565
// Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
566
// if/then triangle. See if there is a store to the same ptr as SI that
569
// Check to see if we find the matching store.
570
if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
571
if (OtherStore->getOperand(1) != SI.getOperand(1) ||
572
OtherStore->getAlignment() != SI.getAlignment())
576
// If we find something that may be using or overwriting the stored
577
// value, or if we run out of instructions, we can't do the xform.
578
if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
579
BBI == OtherBB->begin())
583
// In order to eliminate the store in OtherBr, we have to
584
// make sure nothing reads or overwrites the stored value in
586
for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
587
// FIXME: This should really be AA driven.
588
if (I->mayReadFromMemory() || I->mayWriteToMemory())
593
// Insert a PHI node now if we need it.
594
Value *MergedVal = OtherStore->getOperand(0);
595
if (MergedVal != SI.getOperand(0)) {
596
PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
597
PN->reserveOperandSpace(2);
598
PN->addIncoming(SI.getOperand(0), SI.getParent());
599
PN->addIncoming(OtherStore->getOperand(0), OtherBB);
600
MergedVal = InsertNewInstBefore(PN, DestBB->front());
603
// Advance to a place where it is safe to insert the new store and
605
BBI = DestBB->getFirstNonPHI();
606
InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
607
OtherStore->isVolatile(),
608
SI.getAlignment()), *BBI);
610
// Nuke the old stores.
611
EraseInstFromFunction(SI);
612
EraseInstFromFunction(*OtherStore);