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