blob: 946c3ee0c7829277de4be16895ad9fd7470a0aaa [file] [log] [blame]
Chris Lattnera65e2f72010-01-05 05:57:49 +00001//===- InstCombineLoadStoreAlloca.cpp -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visit functions for load, store and alloca.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
15#include "llvm/IntrinsicInst.h"
Dan Gohman826bdf82010-05-28 16:19:17 +000016#include "llvm/Analysis/Loads.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000017#include "llvm/Target/TargetData.h"
18#include "llvm/Transforms/Utils/BasicBlockUtils.h"
19#include "llvm/Transforms/Utils/Local.h"
20#include "llvm/ADT/Statistic.h"
21using namespace llvm;
22
23STATISTIC(NumDeadStore, "Number of dead stores eliminated");
24
25Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Dan Gohmandf5d7dc2010-05-28 15:09:00 +000026 // Ensure that the alloca array size argument has type intptr_t, so that
27 // any casting is exposed early.
28 if (TD) {
29 const Type *IntPtrTy = TD->getIntPtrType(AI.getContext());
30 if (AI.getArraySize()->getType() != IntPtrTy) {
31 Value *V = Builder->CreateIntCast(AI.getArraySize(),
32 IntPtrTy, false);
33 AI.setOperand(0, V);
34 return &AI;
35 }
36 }
37
Chris Lattnera65e2f72010-01-05 05:57:49 +000038 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
39 if (AI.isArrayAllocation()) { // Check C != 1
40 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
41 const Type *NewTy =
42 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
43 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
44 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
45 New->setAlignment(AI.getAlignment());
46
47 // Scan to the end of the allocation instructions, to skip over a block of
48 // allocas if possible...also skip interleaved debug info
49 //
50 BasicBlock::iterator It = New;
51 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
52
53 // Now that I is pointing to the first non-allocation-inst in the block,
54 // insert our getelementptr instruction...
55 //
56 Value *NullIdx =Constant::getNullValue(Type::getInt32Ty(AI.getContext()));
57 Value *Idx[2];
58 Idx[0] = NullIdx;
59 Idx[1] = NullIdx;
60 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
61 New->getName()+".sub", It);
62
63 // Now make everything use the getelementptr instead of the original
64 // allocation.
65 return ReplaceInstUsesWith(AI, V);
66 } else if (isa<UndefValue>(AI.getArraySize())) {
67 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
68 }
69 }
70
71 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
72 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
73 // Note that we only do this for alloca's, because malloc should allocate
74 // and return a unique pointer, even for a zero byte allocation.
75 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
76 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
77
78 // If the alignment is 0 (unspecified), assign it the preferred alignment.
79 if (AI.getAlignment() == 0)
80 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
81 }
82
83 return 0;
84}
85
86
87/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
88static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
89 const TargetData *TD) {
90 User *CI = cast<User>(LI.getOperand(0));
91 Value *CastOp = CI->getOperand(0);
92
93 const PointerType *DestTy = cast<PointerType>(CI->getType());
94 const Type *DestPTy = DestTy->getElementType();
95 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
96
97 // If the address spaces don't match, don't eliminate the cast.
98 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
99 return 0;
100
101 const Type *SrcPTy = SrcTy->getElementType();
102
Duncan Sands19d0b472010-02-16 11:11:14 +0000103 if (DestPTy->isIntegerTy() || DestPTy->isPointerTy() ||
104 DestPTy->isVectorTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000105 // If the source is an array, the code below will not succeed. Check to
106 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
107 // constants.
108 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
109 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
110 if (ASrcTy->getNumElements() != 0) {
111 Value *Idxs[2];
112 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(LI.getContext()));
113 Idxs[1] = Idxs[0];
114 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
115 SrcTy = cast<PointerType>(CastOp->getType());
116 SrcPTy = SrcTy->getElementType();
117 }
118
119 if (IC.getTargetData() &&
Duncan Sands19d0b472010-02-16 11:11:14 +0000120 (SrcPTy->isIntegerTy() || SrcPTy->isPointerTy() ||
121 SrcPTy->isVectorTy()) &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000122 // Do not allow turning this into a load of an integer, which is then
123 // casted to a pointer, this pessimizes pointer analysis a lot.
Duncan Sands19d0b472010-02-16 11:11:14 +0000124 (SrcPTy->isPointerTy() == LI.getType()->isPointerTy()) &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000125 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
126 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
127
128 // Okay, we are casting from one integer or pointer type to another of
129 // the same size. Instead of casting the pointer before the load, cast
130 // the result of the loaded value.
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000131 LoadInst *NewLoad =
Chris Lattnera65e2f72010-01-05 05:57:49 +0000132 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000133 NewLoad->setAlignment(LI.getAlignment());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000134 // Now cast the result of the load.
135 return new BitCastInst(NewLoad, LI.getType());
136 }
137 }
138 }
139 return 0;
140}
141
142Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
143 Value *Op = LI.getOperand(0);
144
145 // Attempt to improve the alignment.
146 if (TD) {
147 unsigned KnownAlign =
148 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
149 if (KnownAlign >
150 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
151 LI.getAlignment()))
152 LI.setAlignment(KnownAlign);
153 }
154
155 // load (cast X) --> cast (load X) iff safe.
156 if (isa<CastInst>(Op))
157 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
158 return Res;
159
160 // None of the following transforms are legal for volatile loads.
161 if (LI.isVolatile()) return 0;
162
163 // Do really simple store-to-load forwarding and load CSE, to catch cases
164 // where there are several consequtive memory accesses to the same location,
165 // separated by a few arithmetic operations.
166 BasicBlock::iterator BBI = &LI;
167 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
168 return ReplaceInstUsesWith(LI, AvailableVal);
169
170 // load(gep null, ...) -> unreachable
171 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
172 const Value *GEPI0 = GEPI->getOperand(0);
173 // TODO: Consider a target hook for valid address spaces for this xform.
174 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
175 // Insert a new store to null instruction before the load to indicate
176 // that this code is not reachable. We do this instead of inserting
177 // an unreachable instruction directly because we cannot modify the
178 // CFG.
179 new StoreInst(UndefValue::get(LI.getType()),
180 Constant::getNullValue(Op->getType()), &LI);
181 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
182 }
183 }
184
185 // load null/undef -> unreachable
186 // TODO: Consider a target hook for valid address spaces for this xform.
187 if (isa<UndefValue>(Op) ||
188 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
189 // Insert a new store to null instruction before the load to indicate that
190 // this code is not reachable. We do this instead of inserting an
191 // unreachable instruction directly because we cannot modify the CFG.
192 new StoreInst(UndefValue::get(LI.getType()),
193 Constant::getNullValue(Op->getType()), &LI);
194 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
195 }
196
197 // Instcombine load (constantexpr_cast global) -> cast (load global)
198 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
199 if (CE->isCast())
200 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
201 return Res;
202
203 if (Op->hasOneUse()) {
204 // Change select and PHI nodes to select values instead of addresses: this
205 // helps alias analysis out a lot, allows many others simplifications, and
206 // exposes redundancy in the code.
207 //
208 // Note that we cannot do the transformation unless we know that the
209 // introduced loads cannot trap! Something like this is valid as long as
210 // the condition is always false: load (select bool %C, int* null, int* %G),
211 // but it would not be valid if we transformed it to load from null
212 // unconditionally.
213 //
214 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
215 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +0000216 unsigned Align = LI.getAlignment();
217 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, TD) &&
218 isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, TD)) {
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000219 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
Bob Wilson56600a12010-01-30 04:42:39 +0000220 SI->getOperand(1)->getName()+".val");
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000221 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
Bob Wilson56600a12010-01-30 04:42:39 +0000222 SI->getOperand(2)->getName()+".val");
223 V1->setAlignment(Align);
224 V2->setAlignment(Align);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000225 return SelectInst::Create(SI->getCondition(), V1, V2);
226 }
227
228 // load (select (cond, null, P)) -> load P
229 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
230 if (C->isNullValue()) {
231 LI.setOperand(0, SI->getOperand(2));
232 return &LI;
233 }
234
235 // load (select (cond, P, null)) -> load P
236 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
237 if (C->isNullValue()) {
238 LI.setOperand(0, SI->getOperand(1));
239 return &LI;
240 }
241 }
242 }
243 return 0;
244}
245
246/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
247/// when possible. This makes it generally easy to do alias analysis and/or
248/// SROA/mem2reg of the memory object.
249static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
250 User *CI = cast<User>(SI.getOperand(1));
251 Value *CastOp = CI->getOperand(0);
252
253 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
254 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
255 if (SrcTy == 0) return 0;
256
257 const Type *SrcPTy = SrcTy->getElementType();
258
Duncan Sands19d0b472010-02-16 11:11:14 +0000259 if (!DestPTy->isIntegerTy() && !DestPTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000260 return 0;
261
262 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
263 /// to its first element. This allows us to handle things like:
264 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
265 /// on 32-bit hosts.
266 SmallVector<Value*, 4> NewGEPIndices;
267
268 // If the source is an array, the code below will not succeed. Check to
269 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
270 // constants.
Duncan Sands19d0b472010-02-16 11:11:14 +0000271 if (SrcPTy->isArrayTy() || SrcPTy->isStructTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000272 // Index through pointer.
273 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
274 NewGEPIndices.push_back(Zero);
275
276 while (1) {
277 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
278 if (!STy->getNumElements()) /* Struct can be empty {} */
279 break;
280 NewGEPIndices.push_back(Zero);
281 SrcPTy = STy->getElementType(0);
282 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
283 NewGEPIndices.push_back(Zero);
284 SrcPTy = ATy->getElementType();
285 } else {
286 break;
287 }
288 }
289
290 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
291 }
292
Duncan Sands19d0b472010-02-16 11:11:14 +0000293 if (!SrcPTy->isIntegerTy() && !SrcPTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000294 return 0;
295
296 // If the pointers point into different address spaces or if they point to
297 // values with different sizes, we can't do the transformation.
298 if (!IC.getTargetData() ||
299 SrcTy->getAddressSpace() !=
300 cast<PointerType>(CI->getType())->getAddressSpace() ||
301 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
302 IC.getTargetData()->getTypeSizeInBits(DestPTy))
303 return 0;
304
305 // Okay, we are casting from one integer or pointer type to another of
306 // the same size. Instead of casting the pointer before
307 // the store, cast the value to be stored.
308 Value *NewCast;
309 Value *SIOp0 = SI.getOperand(0);
310 Instruction::CastOps opcode = Instruction::BitCast;
311 const Type* CastSrcTy = SIOp0->getType();
312 const Type* CastDstTy = SrcPTy;
Duncan Sands19d0b472010-02-16 11:11:14 +0000313 if (CastDstTy->isPointerTy()) {
Duncan Sands9dff9be2010-02-15 16:12:20 +0000314 if (CastSrcTy->isIntegerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000315 opcode = Instruction::IntToPtr;
Duncan Sands19d0b472010-02-16 11:11:14 +0000316 } else if (CastDstTy->isIntegerTy()) {
317 if (SIOp0->getType()->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000318 opcode = Instruction::PtrToInt;
319 }
320
321 // SIOp0 is a pointer to aggregate and this is a store to the first field,
322 // emit a GEP to index into its first field.
323 if (!NewGEPIndices.empty())
324 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
325 NewGEPIndices.end());
326
327 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
328 SIOp0->getName()+".c");
329 return new StoreInst(NewCast, CastOp);
330}
331
332/// equivalentAddressValues - Test if A and B will obviously have the same
333/// value. This includes recognizing that %t0 and %t1 will have the same
334/// value in code like this:
335/// %t0 = getelementptr \@a, 0, 3
336/// store i32 0, i32* %t0
337/// %t1 = getelementptr \@a, 0, 3
338/// %t2 = load i32* %t1
339///
340static bool equivalentAddressValues(Value *A, Value *B) {
341 // Test if the values are trivially equivalent.
342 if (A == B) return true;
343
344 // Test if the values come form identical arithmetic instructions.
345 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
346 // its only used to compare two uses within the same basic block, which
347 // means that they'll always either have the same value or one of them
348 // will have an undefined value.
349 if (isa<BinaryOperator>(A) ||
350 isa<CastInst>(A) ||
351 isa<PHINode>(A) ||
352 isa<GetElementPtrInst>(A))
353 if (Instruction *BI = dyn_cast<Instruction>(B))
354 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
355 return true;
356
357 // Otherwise they may not be equivalent.
358 return false;
359}
360
361// If this instruction has two uses, one of which is a llvm.dbg.declare,
362// return the llvm.dbg.declare.
363DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
364 if (!V->hasNUses(2))
365 return 0;
366 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
367 UI != E; ++UI) {
Gabor Greif60a346d2010-07-09 12:23:50 +0000368 User *U = *UI;
369 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(U))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000370 return DI;
Gabor Greif60a346d2010-07-09 12:23:50 +0000371 if (isa<BitCastInst>(U) && U->hasOneUse()) {
372 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(U->use_begin()))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000373 return DI;
374 }
375 }
376 return 0;
377}
378
379Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
380 Value *Val = SI.getOperand(0);
381 Value *Ptr = SI.getOperand(1);
382
383 // If the RHS is an alloca with a single use, zapify the store, making the
384 // alloca dead.
385 // If the RHS is an alloca with a two uses, the other one being a
386 // llvm.dbg.declare, zapify the store and the declare, making the
Eric Christopher84bd3162010-01-19 01:20:15 +0000387 // alloca dead. We must do this to prevent declares from affecting
Chris Lattnera65e2f72010-01-05 05:57:49 +0000388 // codegen.
389 if (!SI.isVolatile()) {
390 if (Ptr->hasOneUse()) {
391 if (isa<AllocaInst>(Ptr))
392 return EraseInstFromFunction(SI);
393 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
394 if (isa<AllocaInst>(GEP->getOperand(0))) {
395 if (GEP->getOperand(0)->hasOneUse())
396 return EraseInstFromFunction(SI);
397 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
398 EraseInstFromFunction(*DI);
399 return EraseInstFromFunction(SI);
400 }
401 }
402 }
403 }
404 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
405 EraseInstFromFunction(*DI);
406 return EraseInstFromFunction(SI);
407 }
408 }
409
410 // Attempt to improve the alignment.
411 if (TD) {
412 unsigned KnownAlign =
413 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
414 if (KnownAlign >
415 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
416 SI.getAlignment()))
417 SI.setAlignment(KnownAlign);
418 }
419
420 // Do really simple DSE, to catch cases where there are several consecutive
421 // stores to the same location, separated by a few arithmetic operations. This
422 // situation often occurs with bitfield accesses.
423 BasicBlock::iterator BBI = &SI;
424 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
425 --ScanInsts) {
426 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000427 // Don't count debug info directives, lest they affect codegen,
428 // and we skip pointer-to-pointer bitcasts, which are NOPs.
429 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000430 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000431 ScanInsts++;
432 continue;
433 }
434
435 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
436 // Prev store isn't volatile, and stores to the same location?
437 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
438 SI.getOperand(1))) {
439 ++NumDeadStore;
440 ++BBI;
441 EraseInstFromFunction(*PrevSI);
442 continue;
443 }
444 break;
445 }
446
447 // If this is a load, we have to stop. However, if the loaded value is from
448 // the pointer we're loading and is producing the pointer we're storing,
449 // then *this* store is dead (X = load P; store X -> P).
450 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
451 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
452 !SI.isVolatile())
453 return EraseInstFromFunction(SI);
454
455 // Otherwise, this is a load from some other location. Stores before it
456 // may not be dead.
457 break;
458 }
459
460 // Don't skip over loads or things that can modify memory.
461 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
462 break;
463 }
464
465
466 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
467
468 // store X, null -> turns into 'unreachable' in SimplifyCFG
469 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
470 if (!isa<UndefValue>(Val)) {
471 SI.setOperand(0, UndefValue::get(Val->getType()));
472 if (Instruction *U = dyn_cast<Instruction>(Val))
473 Worklist.Add(U); // Dropped a use.
474 }
475 return 0; // Do not modify these!
476 }
477
478 // store undef, Ptr -> noop
479 if (isa<UndefValue>(Val))
480 return EraseInstFromFunction(SI);
481
482 // If the pointer destination is a cast, see if we can fold the cast into the
483 // source instead.
484 if (isa<CastInst>(Ptr))
485 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
486 return Res;
487 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
488 if (CE->isCast())
489 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
490 return Res;
491
492
493 // If this store is the last instruction in the basic block (possibly
Victor Hernandez5f5abd52010-01-21 23:07:15 +0000494 // excepting debug info instructions), and if the block ends with an
495 // unconditional branch, try to move it to the successor block.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000496 BBI = &SI;
497 do {
498 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000499 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000500 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000501 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
502 if (BI->isUnconditional())
503 if (SimplifyStoreAtEndOfBlock(SI))
504 return 0; // xform done!
505
506 return 0;
507}
508
509/// SimplifyStoreAtEndOfBlock - Turn things like:
510/// if () { *P = v1; } else { *P = v2 }
511/// into a phi node with a store in the successor.
512///
513/// Simplify things like:
514/// *P = v1; if () { *P = v2; }
515/// into a phi node with a store in the successor.
516///
517bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
518 BasicBlock *StoreBB = SI.getParent();
519
520 // Check to see if the successor block has exactly two incoming edges. If
521 // so, see if the other predecessor contains a store to the same location.
522 // if so, insert a PHI node (if needed) and move the stores down.
523 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
524
525 // Determine whether Dest has exactly two predecessors and, if so, compute
526 // the other predecessor.
527 pred_iterator PI = pred_begin(DestBB);
528 BasicBlock *OtherBB = 0;
529 if (*PI != StoreBB)
530 OtherBB = *PI;
531 ++PI;
532 if (PI == pred_end(DestBB))
533 return false;
534
535 if (*PI != StoreBB) {
536 if (OtherBB)
537 return false;
538 OtherBB = *PI;
539 }
540 if (++PI != pred_end(DestBB))
541 return false;
542
543 // Bail out if all the relevant blocks aren't distinct (this can happen,
544 // for example, if SI is in an infinite loop)
545 if (StoreBB == DestBB || OtherBB == DestBB)
546 return false;
547
548 // Verify that the other block ends in a branch and is not otherwise empty.
549 BasicBlock::iterator BBI = OtherBB->getTerminator();
550 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
551 if (!OtherBr || BBI == OtherBB->begin())
552 return false;
553
554 // If the other block ends in an unconditional branch, check for the 'if then
555 // else' case. there is an instruction before the branch.
556 StoreInst *OtherStore = 0;
557 if (OtherBr->isUnconditional()) {
558 --BBI;
559 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000560 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000561 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000562 if (BBI==OtherBB->begin())
563 return false;
564 --BBI;
565 }
566 // If this isn't a store, isn't a store to the same location, or if the
567 // alignments differ, bail out.
568 OtherStore = dyn_cast<StoreInst>(BBI);
569 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
570 OtherStore->getAlignment() != SI.getAlignment())
571 return false;
572 } else {
573 // Otherwise, the other block ended with a conditional branch. If one of the
574 // destinations is StoreBB, then we have the if/then case.
575 if (OtherBr->getSuccessor(0) != StoreBB &&
576 OtherBr->getSuccessor(1) != StoreBB)
577 return false;
578
579 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
580 // if/then triangle. See if there is a store to the same ptr as SI that
581 // lives in OtherBB.
582 for (;; --BBI) {
583 // Check to see if we find the matching store.
584 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
585 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
586 OtherStore->getAlignment() != SI.getAlignment())
587 return false;
588 break;
589 }
590 // If we find something that may be using or overwriting the stored
591 // value, or if we run out of instructions, we can't do the xform.
592 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
593 BBI == OtherBB->begin())
594 return false;
595 }
596
597 // In order to eliminate the store in OtherBr, we have to
598 // make sure nothing reads or overwrites the stored value in
599 // StoreBB.
600 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
601 // FIXME: This should really be AA driven.
602 if (I->mayReadFromMemory() || I->mayWriteToMemory())
603 return false;
604 }
605 }
606
607 // Insert a PHI node now if we need it.
608 Value *MergedVal = OtherStore->getOperand(0);
609 if (MergedVal != SI.getOperand(0)) {
610 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
611 PN->reserveOperandSpace(2);
612 PN->addIncoming(SI.getOperand(0), SI.getParent());
613 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
614 MergedVal = InsertNewInstBefore(PN, DestBB->front());
615 }
616
617 // Advance to a place where it is safe to insert the new store and
618 // insert it.
619 BBI = DestBB->getFirstNonPHI();
620 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
621 OtherStore->isVolatile(),
622 SI.getAlignment()), *BBI);
623
624 // Nuke the old stores.
625 EraseInstFromFunction(SI);
626 EraseInstFromFunction(*OtherStore);
627 return true;
628}