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/ADT/Statistic.h"
16 #include "llvm/Analysis/Loads.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/IntrinsicInst.h"
19 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
20 #include "llvm/Transforms/Utils/Local.h"
21 using namespace llvm;
22 
23 #define DEBUG_TYPE "instcombine"
24 
25 STATISTIC(NumDeadStore,    "Number of dead stores eliminated");
26 STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
27 
28 /// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
29 /// some part of a constant global variable.  This intentionally only accepts
30 /// constant expressions because we can't rewrite arbitrary instructions.
31 static bool pointsToConstantGlobal(Value *V) {
32   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
33     return GV->isConstant();
34   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
35     if (CE->getOpcode() == Instruction::BitCast ||
36         CE->getOpcode() == Instruction::GetElementPtr)
37       return pointsToConstantGlobal(CE->getOperand(0));
38   return false;
39 }
40 
41 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
42 /// pointer to an alloca.  Ignore any reads of the pointer, return false if we
43 /// see any stores or other unknown uses.  If we see pointer arithmetic, keep
44 /// track of whether it moves the pointer (with IsOffset) but otherwise traverse
45 /// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
46 /// the alloca, and if the source pointer is a pointer to a constant global, we
47 /// can optimize this.
48 static bool
49 isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
50                                SmallVectorImpl<Instruction *> &ToDelete,
51                                bool IsOffset = false) {
52   // We track lifetime intrinsics as we encounter them.  If we decide to go
53   // ahead and replace the value with the global, this lets the caller quickly
54   // eliminate the markers.
55 
56   for (Use &U : V->uses()) {
57     Instruction *I = cast<Instruction>(U.getUser());
58 
59     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
60       // Ignore non-volatile loads, they are always ok.
61       if (!LI->isSimple()) return false;
62       continue;
63     }
64 
65     if (BitCastInst *BCI = dyn_cast<BitCastInst>(I)) {
66       // If uses of the bitcast are ok, we are ok.
67       if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, ToDelete, IsOffset))
68         return false;
69       continue;
70     }
71     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
72       // If the GEP has all zero indices, it doesn't offset the pointer.  If it
73       // doesn't, it does.
74       if (!isOnlyCopiedFromConstantGlobal(
75               GEP, TheCopy, ToDelete, IsOffset || !GEP->hasAllZeroIndices()))
76         return false;
77       continue;
78     }
79 
80     if (CallSite CS = I) {
81       // If this is the function being called then we treat it like a load and
82       // ignore it.
83       if (CS.isCallee(&U))
84         continue;
85 
86       // Inalloca arguments are clobbered by the call.
87       unsigned ArgNo = CS.getArgumentNo(&U);
88       if (CS.isInAllocaArgument(ArgNo))
89         return false;
90 
91       // If this is a readonly/readnone call site, then we know it is just a
92       // load (but one that potentially returns the value itself), so we can
93       // ignore it if we know that the value isn't captured.
94       if (CS.onlyReadsMemory() &&
95           (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
96         continue;
97 
98       // If this is being passed as a byval argument, the caller is making a
99       // copy, so it is only a read of the alloca.
100       if (CS.isByValArgument(ArgNo))
101         continue;
102     }
103 
104     // Lifetime intrinsics can be handled by the caller.
105     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
106       if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
107           II->getIntrinsicID() == Intrinsic::lifetime_end) {
108         assert(II->use_empty() && "Lifetime markers have no result to use!");
109         ToDelete.push_back(II);
110         continue;
111       }
112     }
113 
114     // If this is isn't our memcpy/memmove, reject it as something we can't
115     // handle.
116     MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
117     if (MI == 0)
118       return false;
119 
120     // If the transfer is using the alloca as a source of the transfer, then
121     // ignore it since it is a load (unless the transfer is volatile).
122     if (U.getOperandNo() == 1) {
123       if (MI->isVolatile()) return false;
124       continue;
125     }
126 
127     // If we already have seen a copy, reject the second one.
128     if (TheCopy) return false;
129 
130     // If the pointer has been offset from the start of the alloca, we can't
131     // safely handle this.
132     if (IsOffset) return false;
133 
134     // If the memintrinsic isn't using the alloca as the dest, reject it.
135     if (U.getOperandNo() != 0) return false;
136 
137     // If the source of the memcpy/move is not a constant global, reject it.
138     if (!pointsToConstantGlobal(MI->getSource()))
139       return false;
140 
141     // Otherwise, the transform is safe.  Remember the copy instruction.
142     TheCopy = MI;
143   }
144   return true;
145 }
146 
147 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
148 /// modified by a copy from a constant global.  If we can prove this, we can
149 /// replace any uses of the alloca with uses of the global directly.
150 static MemTransferInst *
151 isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
152                                SmallVectorImpl<Instruction *> &ToDelete) {
153   MemTransferInst *TheCopy = 0;
154   if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
155     return TheCopy;
156   return 0;
157 }
158 
159 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
160   // Ensure that the alloca array size argument has type intptr_t, so that
161   // any casting is exposed early.
162   if (DL) {
163     Type *IntPtrTy = DL->getIntPtrType(AI.getType());
164     if (AI.getArraySize()->getType() != IntPtrTy) {
165       Value *V = Builder->CreateIntCast(AI.getArraySize(),
166                                         IntPtrTy, false);
167       AI.setOperand(0, V);
168       return &AI;
169     }
170   }
171 
172   // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
173   if (AI.isArrayAllocation()) {  // Check C != 1
174     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
175       Type *NewTy =
176         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
177       AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
178       New->setAlignment(AI.getAlignment());
179 
180       // Scan to the end of the allocation instructions, to skip over a block of
181       // allocas if possible...also skip interleaved debug info
182       //
183       BasicBlock::iterator It = New;
184       while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
185 
186       // Now that I is pointing to the first non-allocation-inst in the block,
187       // insert our getelementptr instruction...
188       //
189       Type *IdxTy = DL
190                   ? DL->getIntPtrType(AI.getType())
191                   : Type::getInt64Ty(AI.getContext());
192       Value *NullIdx = Constant::getNullValue(IdxTy);
193       Value *Idx[2] = { NullIdx, NullIdx };
194       Instruction *GEP =
195         GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
196       InsertNewInstBefore(GEP, *It);
197 
198       // Now make everything use the getelementptr instead of the original
199       // allocation.
200       return ReplaceInstUsesWith(AI, GEP);
201     } else if (isa<UndefValue>(AI.getArraySize())) {
202       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
203     }
204   }
205 
206   if (DL && AI.getAllocatedType()->isSized()) {
207     // If the alignment is 0 (unspecified), assign it the preferred alignment.
208     if (AI.getAlignment() == 0)
209       AI.setAlignment(DL->getPrefTypeAlignment(AI.getAllocatedType()));
210 
211     // Move all alloca's of zero byte objects to the entry block and merge them
212     // together.  Note that we only do this for alloca's, because malloc should
213     // allocate and return a unique pointer, even for a zero byte allocation.
214     if (DL->getTypeAllocSize(AI.getAllocatedType()) == 0) {
215       // For a zero sized alloca there is no point in doing an array allocation.
216       // This is helpful if the array size is a complicated expression not used
217       // elsewhere.
218       if (AI.isArrayAllocation()) {
219         AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
220         return &AI;
221       }
222 
223       // Get the first instruction in the entry block.
224       BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
225       Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
226       if (FirstInst != &AI) {
227         // If the entry block doesn't start with a zero-size alloca then move
228         // this one to the start of the entry block.  There is no problem with
229         // dominance as the array size was forced to a constant earlier already.
230         AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
231         if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
232             DL->getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
233           AI.moveBefore(FirstInst);
234           return &AI;
235         }
236 
237         // If the alignment of the entry block alloca is 0 (unspecified),
238         // assign it the preferred alignment.
239         if (EntryAI->getAlignment() == 0)
240           EntryAI->setAlignment(
241             DL->getPrefTypeAlignment(EntryAI->getAllocatedType()));
242         // Replace this zero-sized alloca with the one at the start of the entry
243         // block after ensuring that the address will be aligned enough for both
244         // types.
245         unsigned MaxAlign = std::max(EntryAI->getAlignment(),
246                                      AI.getAlignment());
247         EntryAI->setAlignment(MaxAlign);
248         if (AI.getType() != EntryAI->getType())
249           return new BitCastInst(EntryAI, AI.getType());
250         return ReplaceInstUsesWith(AI, EntryAI);
251       }
252     }
253   }
254 
255   if (AI.getAlignment()) {
256     // Check to see if this allocation is only modified by a memcpy/memmove from
257     // a constant global whose alignment is equal to or exceeds that of the
258     // allocation.  If this is the case, we can change all users to use
259     // the constant global instead.  This is commonly produced by the CFE by
260     // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
261     // is only subsequently read.
262     SmallVector<Instruction *, 4> ToDelete;
263     if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
264       unsigned SourceAlign = getOrEnforceKnownAlignment(Copy->getSource(),
265                                                         AI.getAlignment(), DL);
266       if (AI.getAlignment() <= SourceAlign) {
267         DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
268         DEBUG(dbgs() << "  memcpy = " << *Copy << '\n');
269         for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
270           EraseInstFromFunction(*ToDelete[i]);
271         Constant *TheSrc = cast<Constant>(Copy->getSource());
272         Constant *Cast
273           = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
274         Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
275         EraseInstFromFunction(*Copy);
276         ++NumGlobalCopies;
277         return NewI;
278       }
279     }
280   }
281 
282   // At last, use the generic allocation site handler to aggressively remove
283   // unused allocas.
284   return visitAllocSite(AI);
285 }
286 
287 
288 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
289 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
290                                         const DataLayout *DL) {
291   User *CI = cast<User>(LI.getOperand(0));
292   Value *CastOp = CI->getOperand(0);
293 
294   PointerType *DestTy = cast<PointerType>(CI->getType());
295   Type *DestPTy = DestTy->getElementType();
296   if (PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
297 
298     // If the address spaces don't match, don't eliminate the cast.
299     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
300       return 0;
301 
302     Type *SrcPTy = SrcTy->getElementType();
303 
304     if (DestPTy->isIntegerTy() || DestPTy->isPointerTy() ||
305          DestPTy->isVectorTy()) {
306       // If the source is an array, the code below will not succeed.  Check to
307       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
308       // constants.
309       if (ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
310         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
311           if (ASrcTy->getNumElements() != 0) {
312             Type *IdxTy = DL
313                         ? DL->getIntPtrType(SrcTy)
314                         : Type::getInt64Ty(SrcTy->getContext());
315             Value *Idx = Constant::getNullValue(IdxTy);
316             Value *Idxs[2] = { Idx, Idx };
317             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
318             SrcTy = cast<PointerType>(CastOp->getType());
319             SrcPTy = SrcTy->getElementType();
320           }
321 
322       if (IC.getDataLayout() &&
323           (SrcPTy->isIntegerTy() || SrcPTy->isPointerTy() ||
324             SrcPTy->isVectorTy()) &&
325           // Do not allow turning this into a load of an integer, which is then
326           // casted to a pointer, this pessimizes pointer analysis a lot.
327           (SrcPTy->isPtrOrPtrVectorTy() ==
328            LI.getType()->isPtrOrPtrVectorTy()) &&
329           IC.getDataLayout()->getTypeSizeInBits(SrcPTy) ==
330                IC.getDataLayout()->getTypeSizeInBits(DestPTy)) {
331 
332         // Okay, we are casting from one integer or pointer type to another of
333         // the same size.  Instead of casting the pointer before the load, cast
334         // the result of the loaded value.
335         LoadInst *NewLoad =
336           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
337         NewLoad->setAlignment(LI.getAlignment());
338         NewLoad->setAtomic(LI.getOrdering(), LI.getSynchScope());
339         // Now cast the result of the load.
340         PointerType *OldTy = dyn_cast<PointerType>(NewLoad->getType());
341         PointerType *NewTy = dyn_cast<PointerType>(LI.getType());
342         if (OldTy && NewTy &&
343             OldTy->getAddressSpace() != NewTy->getAddressSpace()) {
344           return new AddrSpaceCastInst(NewLoad, LI.getType());
345         }
346 
347         return new BitCastInst(NewLoad, LI.getType());
348       }
349     }
350   }
351   return 0;
352 }
353 
354 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
355   Value *Op = LI.getOperand(0);
356 
357   // Attempt to improve the alignment.
358   if (DL) {
359     unsigned KnownAlign =
360       getOrEnforceKnownAlignment(Op, DL->getPrefTypeAlignment(LI.getType()),DL);
361     unsigned LoadAlign = LI.getAlignment();
362     unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
363       DL->getABITypeAlignment(LI.getType());
364 
365     if (KnownAlign > EffectiveLoadAlign)
366       LI.setAlignment(KnownAlign);
367     else if (LoadAlign == 0)
368       LI.setAlignment(EffectiveLoadAlign);
369   }
370 
371   // load (cast X) --> cast (load X) iff safe.
372   if (isa<CastInst>(Op))
373     if (Instruction *Res = InstCombineLoadCast(*this, LI, DL))
374       return Res;
375 
376   // None of the following transforms are legal for volatile/atomic loads.
377   // FIXME: Some of it is okay for atomic loads; needs refactoring.
378   if (!LI.isSimple()) return 0;
379 
380   // Do really simple store-to-load forwarding and load CSE, to catch cases
381   // where there are several consecutive memory accesses to the same location,
382   // separated by a few arithmetic operations.
383   BasicBlock::iterator BBI = &LI;
384   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
385     return ReplaceInstUsesWith(LI, AvailableVal);
386 
387   // load(gep null, ...) -> unreachable
388   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
389     const Value *GEPI0 = GEPI->getOperand(0);
390     // TODO: Consider a target hook for valid address spaces for this xform.
391     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
392       // Insert a new store to null instruction before the load to indicate
393       // that this code is not reachable.  We do this instead of inserting
394       // an unreachable instruction directly because we cannot modify the
395       // CFG.
396       new StoreInst(UndefValue::get(LI.getType()),
397                     Constant::getNullValue(Op->getType()), &LI);
398       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
399     }
400   }
401 
402   // load null/undef -> unreachable
403   // TODO: Consider a target hook for valid address spaces for this xform.
404   if (isa<UndefValue>(Op) ||
405       (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
406     // Insert a new store to null instruction before the load to indicate that
407     // this code is not reachable.  We do this instead of inserting an
408     // unreachable instruction directly because we cannot modify the CFG.
409     new StoreInst(UndefValue::get(LI.getType()),
410                   Constant::getNullValue(Op->getType()), &LI);
411     return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
412   }
413 
414   // Instcombine load (constantexpr_cast global) -> cast (load global)
415   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
416     if (CE->isCast())
417       if (Instruction *Res = InstCombineLoadCast(*this, LI, DL))
418         return Res;
419 
420   if (Op->hasOneUse()) {
421     // Change select and PHI nodes to select values instead of addresses: this
422     // helps alias analysis out a lot, allows many others simplifications, and
423     // exposes redundancy in the code.
424     //
425     // Note that we cannot do the transformation unless we know that the
426     // introduced loads cannot trap!  Something like this is valid as long as
427     // the condition is always false: load (select bool %C, int* null, int* %G),
428     // but it would not be valid if we transformed it to load from null
429     // unconditionally.
430     //
431     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
432       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
433       unsigned Align = LI.getAlignment();
434       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, DL) &&
435           isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, DL)) {
436         LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
437                                            SI->getOperand(1)->getName()+".val");
438         LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
439                                            SI->getOperand(2)->getName()+".val");
440         V1->setAlignment(Align);
441         V2->setAlignment(Align);
442         return SelectInst::Create(SI->getCondition(), V1, V2);
443       }
444 
445       // load (select (cond, null, P)) -> load P
446       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
447         if (C->isNullValue()) {
448           LI.setOperand(0, SI->getOperand(2));
449           return &LI;
450         }
451 
452       // load (select (cond, P, null)) -> load P
453       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
454         if (C->isNullValue()) {
455           LI.setOperand(0, SI->getOperand(1));
456           return &LI;
457         }
458     }
459   }
460   return 0;
461 }
462 
463 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
464 /// when possible.  This makes it generally easy to do alias analysis and/or
465 /// SROA/mem2reg of the memory object.
466 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
467   User *CI = cast<User>(SI.getOperand(1));
468   Value *CastOp = CI->getOperand(0);
469 
470   Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
471   PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
472   if (SrcTy == 0) return 0;
473 
474   Type *SrcPTy = SrcTy->getElementType();
475 
476   if (!DestPTy->isIntegerTy() && !DestPTy->isPointerTy())
477     return 0;
478 
479   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
480   /// to its first element.  This allows us to handle things like:
481   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
482   /// on 32-bit hosts.
483   SmallVector<Value*, 4> NewGEPIndices;
484 
485   // If the source is an array, the code below will not succeed.  Check to
486   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
487   // constants.
488   if (SrcPTy->isArrayTy() || SrcPTy->isStructTy()) {
489     // Index through pointer.
490     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
491     NewGEPIndices.push_back(Zero);
492 
493     while (1) {
494       if (StructType *STy = dyn_cast<StructType>(SrcPTy)) {
495         if (!STy->getNumElements()) /* Struct can be empty {} */
496           break;
497         NewGEPIndices.push_back(Zero);
498         SrcPTy = STy->getElementType(0);
499       } else if (ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
500         NewGEPIndices.push_back(Zero);
501         SrcPTy = ATy->getElementType();
502       } else {
503         break;
504       }
505     }
506 
507     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
508   }
509 
510   if (!SrcPTy->isIntegerTy() && !SrcPTy->isPointerTy())
511     return 0;
512 
513   // If the pointers point into different address spaces don't do the
514   // transformation.
515   if (SrcTy->getAddressSpace() !=
516       cast<PointerType>(CI->getType())->getAddressSpace())
517     return 0;
518 
519   // If the pointers point to values of different sizes don't do the
520   // transformation.
521   if (!IC.getDataLayout() ||
522       IC.getDataLayout()->getTypeSizeInBits(SrcPTy) !=
523       IC.getDataLayout()->getTypeSizeInBits(DestPTy))
524     return 0;
525 
526   // If the pointers point to pointers to different address spaces don't do the
527   // transformation. It is not safe to introduce an addrspacecast instruction in
528   // this case since, depending on the target, addrspacecast may not be a no-op
529   // cast.
530   if (SrcPTy->isPointerTy() && DestPTy->isPointerTy() &&
531       SrcPTy->getPointerAddressSpace() != DestPTy->getPointerAddressSpace())
532     return 0;
533 
534   // Okay, we are casting from one integer or pointer type to another of
535   // the same size.  Instead of casting the pointer before
536   // the store, cast the value to be stored.
537   Value *NewCast;
538   Instruction::CastOps opcode = Instruction::BitCast;
539   Type* CastSrcTy = DestPTy;
540   Type* CastDstTy = SrcPTy;
541   if (CastDstTy->isPointerTy()) {
542     if (CastSrcTy->isIntegerTy())
543       opcode = Instruction::IntToPtr;
544   } else if (CastDstTy->isIntegerTy()) {
545     if (CastSrcTy->isPointerTy())
546       opcode = Instruction::PtrToInt;
547   }
548 
549   // SIOp0 is a pointer to aggregate and this is a store to the first field,
550   // emit a GEP to index into its first field.
551   if (!NewGEPIndices.empty())
552     CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices);
553 
554   Value *SIOp0 = SI.getOperand(0);
555   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
556                                    SIOp0->getName()+".c");
557   SI.setOperand(0, NewCast);
558   SI.setOperand(1, CastOp);
559   return &SI;
560 }
561 
562 /// equivalentAddressValues - Test if A and B will obviously have the same
563 /// value. This includes recognizing that %t0 and %t1 will have the same
564 /// value in code like this:
565 ///   %t0 = getelementptr \@a, 0, 3
566 ///   store i32 0, i32* %t0
567 ///   %t1 = getelementptr \@a, 0, 3
568 ///   %t2 = load i32* %t1
569 ///
570 static bool equivalentAddressValues(Value *A, Value *B) {
571   // Test if the values are trivially equivalent.
572   if (A == B) return true;
573 
574   // Test if the values come form identical arithmetic instructions.
575   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
576   // its only used to compare two uses within the same basic block, which
577   // means that they'll always either have the same value or one of them
578   // will have an undefined value.
579   if (isa<BinaryOperator>(A) ||
580       isa<CastInst>(A) ||
581       isa<PHINode>(A) ||
582       isa<GetElementPtrInst>(A))
583     if (Instruction *BI = dyn_cast<Instruction>(B))
584       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
585         return true;
586 
587   // Otherwise they may not be equivalent.
588   return false;
589 }
590 
591 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
592   Value *Val = SI.getOperand(0);
593   Value *Ptr = SI.getOperand(1);
594 
595   // Attempt to improve the alignment.
596   if (DL) {
597     unsigned KnownAlign =
598       getOrEnforceKnownAlignment(Ptr, DL->getPrefTypeAlignment(Val->getType()),
599                                  DL);
600     unsigned StoreAlign = SI.getAlignment();
601     unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
602       DL->getABITypeAlignment(Val->getType());
603 
604     if (KnownAlign > EffectiveStoreAlign)
605       SI.setAlignment(KnownAlign);
606     else if (StoreAlign == 0)
607       SI.setAlignment(EffectiveStoreAlign);
608   }
609 
610   // Don't hack volatile/atomic stores.
611   // FIXME: Some bits are legal for atomic stores; needs refactoring.
612   if (!SI.isSimple()) return 0;
613 
614   // If the RHS is an alloca with a single use, zapify the store, making the
615   // alloca dead.
616   if (Ptr->hasOneUse()) {
617     if (isa<AllocaInst>(Ptr))
618       return EraseInstFromFunction(SI);
619     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
620       if (isa<AllocaInst>(GEP->getOperand(0))) {
621         if (GEP->getOperand(0)->hasOneUse())
622           return EraseInstFromFunction(SI);
623       }
624     }
625   }
626 
627   // Do really simple DSE, to catch cases where there are several consecutive
628   // stores to the same location, separated by a few arithmetic operations. This
629   // situation often occurs with bitfield accesses.
630   BasicBlock::iterator BBI = &SI;
631   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
632        --ScanInsts) {
633     --BBI;
634     // Don't count debug info directives, lest they affect codegen,
635     // and we skip pointer-to-pointer bitcasts, which are NOPs.
636     if (isa<DbgInfoIntrinsic>(BBI) ||
637         (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
638       ScanInsts++;
639       continue;
640     }
641 
642     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
643       // Prev store isn't volatile, and stores to the same location?
644       if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
645                                                         SI.getOperand(1))) {
646         ++NumDeadStore;
647         ++BBI;
648         EraseInstFromFunction(*PrevSI);
649         continue;
650       }
651       break;
652     }
653 
654     // If this is a load, we have to stop.  However, if the loaded value is from
655     // the pointer we're loading and is producing the pointer we're storing,
656     // then *this* store is dead (X = load P; store X -> P).
657     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
658       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
659           LI->isSimple())
660         return EraseInstFromFunction(SI);
661 
662       // Otherwise, this is a load from some other location.  Stores before it
663       // may not be dead.
664       break;
665     }
666 
667     // Don't skip over loads or things that can modify memory.
668     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
669       break;
670   }
671 
672   // store X, null    -> turns into 'unreachable' in SimplifyCFG
673   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
674     if (!isa<UndefValue>(Val)) {
675       SI.setOperand(0, UndefValue::get(Val->getType()));
676       if (Instruction *U = dyn_cast<Instruction>(Val))
677         Worklist.Add(U);  // Dropped a use.
678     }
679     return 0;  // Do not modify these!
680   }
681 
682   // store undef, Ptr -> noop
683   if (isa<UndefValue>(Val))
684     return EraseInstFromFunction(SI);
685 
686   // If the pointer destination is a cast, see if we can fold the cast into the
687   // source instead.
688   if (isa<CastInst>(Ptr))
689     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
690       return Res;
691   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
692     if (CE->isCast())
693       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
694         return Res;
695 
696 
697   // If this store is the last instruction in the basic block (possibly
698   // excepting debug info instructions), and if the block ends with an
699   // unconditional branch, try to move it to the successor block.
700   BBI = &SI;
701   do {
702     ++BBI;
703   } while (isa<DbgInfoIntrinsic>(BBI) ||
704            (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
705   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
706     if (BI->isUnconditional())
707       if (SimplifyStoreAtEndOfBlock(SI))
708         return 0;  // xform done!
709 
710   return 0;
711 }
712 
713 /// SimplifyStoreAtEndOfBlock - Turn things like:
714 ///   if () { *P = v1; } else { *P = v2 }
715 /// into a phi node with a store in the successor.
716 ///
717 /// Simplify things like:
718 ///   *P = v1; if () { *P = v2; }
719 /// into a phi node with a store in the successor.
720 ///
721 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
722   BasicBlock *StoreBB = SI.getParent();
723 
724   // Check to see if the successor block has exactly two incoming edges.  If
725   // so, see if the other predecessor contains a store to the same location.
726   // if so, insert a PHI node (if needed) and move the stores down.
727   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
728 
729   // Determine whether Dest has exactly two predecessors and, if so, compute
730   // the other predecessor.
731   pred_iterator PI = pred_begin(DestBB);
732   BasicBlock *P = *PI;
733   BasicBlock *OtherBB = 0;
734 
735   if (P != StoreBB)
736     OtherBB = P;
737 
738   if (++PI == pred_end(DestBB))
739     return false;
740 
741   P = *PI;
742   if (P != StoreBB) {
743     if (OtherBB)
744       return false;
745     OtherBB = P;
746   }
747   if (++PI != pred_end(DestBB))
748     return false;
749 
750   // Bail out if all the relevant blocks aren't distinct (this can happen,
751   // for example, if SI is in an infinite loop)
752   if (StoreBB == DestBB || OtherBB == DestBB)
753     return false;
754 
755   // Verify that the other block ends in a branch and is not otherwise empty.
756   BasicBlock::iterator BBI = OtherBB->getTerminator();
757   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
758   if (!OtherBr || BBI == OtherBB->begin())
759     return false;
760 
761   // If the other block ends in an unconditional branch, check for the 'if then
762   // else' case.  there is an instruction before the branch.
763   StoreInst *OtherStore = 0;
764   if (OtherBr->isUnconditional()) {
765     --BBI;
766     // Skip over debugging info.
767     while (isa<DbgInfoIntrinsic>(BBI) ||
768            (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
769       if (BBI==OtherBB->begin())
770         return false;
771       --BBI;
772     }
773     // If this isn't a store, isn't a store to the same location, or is not the
774     // right kind of store, bail out.
775     OtherStore = dyn_cast<StoreInst>(BBI);
776     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
777         !SI.isSameOperationAs(OtherStore))
778       return false;
779   } else {
780     // Otherwise, the other block ended with a conditional branch. If one of the
781     // destinations is StoreBB, then we have the if/then case.
782     if (OtherBr->getSuccessor(0) != StoreBB &&
783         OtherBr->getSuccessor(1) != StoreBB)
784       return false;
785 
786     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
787     // if/then triangle.  See if there is a store to the same ptr as SI that
788     // lives in OtherBB.
789     for (;; --BBI) {
790       // Check to see if we find the matching store.
791       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
792         if (OtherStore->getOperand(1) != SI.getOperand(1) ||
793             !SI.isSameOperationAs(OtherStore))
794           return false;
795         break;
796       }
797       // If we find something that may be using or overwriting the stored
798       // value, or if we run out of instructions, we can't do the xform.
799       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
800           BBI == OtherBB->begin())
801         return false;
802     }
803 
804     // In order to eliminate the store in OtherBr, we have to
805     // make sure nothing reads or overwrites the stored value in
806     // StoreBB.
807     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
808       // FIXME: This should really be AA driven.
809       if (I->mayReadFromMemory() || I->mayWriteToMemory())
810         return false;
811     }
812   }
813 
814   // Insert a PHI node now if we need it.
815   Value *MergedVal = OtherStore->getOperand(0);
816   if (MergedVal != SI.getOperand(0)) {
817     PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
818     PN->addIncoming(SI.getOperand(0), SI.getParent());
819     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
820     MergedVal = InsertNewInstBefore(PN, DestBB->front());
821   }
822 
823   // Advance to a place where it is safe to insert the new store and
824   // insert it.
825   BBI = DestBB->getFirstInsertionPt();
826   StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
827                                    SI.isVolatile(),
828                                    SI.getAlignment(),
829                                    SI.getOrdering(),
830                                    SI.getSynchScope());
831   InsertNewInstBefore(NewSI, *BBI);
832   NewSI->setDebugLoc(OtherStore->getDebugLoc());
833 
834   // If the two stores had the same TBAA tag, preserve it.
835   if (MDNode *TBAATag = SI.getMetadata(LLVMContext::MD_tbaa))
836     if ((TBAATag = MDNode::getMostGenericTBAA(TBAATag,
837                                OtherStore->getMetadata(LLVMContext::MD_tbaa))))
838       NewSI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
839 
840 
841   // Nuke the old stores.
842   EraseInstFromFunction(SI);
843   EraseInstFromFunction(*OtherStore);
844   return true;
845 }
846