blob: a08fc0d54eca05f471e83b46a97576848e93cbf0 [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) {
Chris Lattner229907c2011-07-18 04:54:35 +000029 Type *IntPtrTy = TD->getIntPtrType(AI.getContext());
Dan Gohmandf5d7dc2010-05-28 15:09:00 +000030 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())) {
Chris Lattner229907c2011-07-18 04:54:35 +000041 Type *NewTy =
Chris Lattnera65e2f72010-01-05 05:57:49 +000042 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;
Eli Friedman41e509a2011-05-18 23:58:37 +000060 Instruction *GEP =
Jay Foadd1b78492011-07-25 09:48:08 +000061 GetElementPtrInst::CreateInBounds(New, Idx, New->getName()+".sub");
Eli Friedman41e509a2011-05-18 23:58:37 +000062 InsertNewInstBefore(GEP, *It);
Chris Lattnera65e2f72010-01-05 05:57:49 +000063
64 // Now make everything use the getelementptr instead of the original
65 // allocation.
Eli Friedman41e509a2011-05-18 23:58:37 +000066 return ReplaceInstUsesWith(AI, GEP);
Chris Lattnera65e2f72010-01-05 05:57:49 +000067 } else if (isa<UndefValue>(AI.getArraySize())) {
68 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
69 }
70 }
71
72 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
73 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
74 // Note that we only do this for alloca's, because malloc should allocate
75 // and return a unique pointer, even for a zero byte allocation.
76 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
77 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
78
79 // If the alignment is 0 (unspecified), assign it the preferred alignment.
80 if (AI.getAlignment() == 0)
81 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
82 }
83
84 return 0;
85}
86
87
88/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
89static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
90 const TargetData *TD) {
91 User *CI = cast<User>(LI.getOperand(0));
92 Value *CastOp = CI->getOperand(0);
93
Chris Lattner229907c2011-07-18 04:54:35 +000094 PointerType *DestTy = cast<PointerType>(CI->getType());
95 Type *DestPTy = DestTy->getElementType();
96 if (PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +000097
98 // If the address spaces don't match, don't eliminate the cast.
99 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
100 return 0;
101
Chris Lattner229907c2011-07-18 04:54:35 +0000102 Type *SrcPTy = SrcTy->getElementType();
Chris Lattnera65e2f72010-01-05 05:57:49 +0000103
Duncan Sands19d0b472010-02-16 11:11:14 +0000104 if (DestPTy->isIntegerTy() || DestPTy->isPointerTy() ||
105 DestPTy->isVectorTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000106 // If the source is an array, the code below will not succeed. Check to
107 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
108 // constants.
Chris Lattner229907c2011-07-18 04:54:35 +0000109 if (ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000110 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
111 if (ASrcTy->getNumElements() != 0) {
112 Value *Idxs[2];
113 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(LI.getContext()));
114 Idxs[1] = Idxs[0];
Jay Foad71f19ac2011-07-22 07:54:01 +0000115 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000116 SrcTy = cast<PointerType>(CastOp->getType());
117 SrcPTy = SrcTy->getElementType();
118 }
119
120 if (IC.getTargetData() &&
Duncan Sands19d0b472010-02-16 11:11:14 +0000121 (SrcPTy->isIntegerTy() || SrcPTy->isPointerTy() ||
122 SrcPTy->isVectorTy()) &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000123 // Do not allow turning this into a load of an integer, which is then
124 // casted to a pointer, this pessimizes pointer analysis a lot.
Duncan Sands19d0b472010-02-16 11:11:14 +0000125 (SrcPTy->isPointerTy() == LI.getType()->isPointerTy()) &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000126 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
127 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
128
129 // Okay, we are casting from one integer or pointer type to another of
130 // the same size. Instead of casting the pointer before the load, cast
131 // the result of the loaded value.
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000132 LoadInst *NewLoad =
Chris Lattnera65e2f72010-01-05 05:57:49 +0000133 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000134 NewLoad->setAlignment(LI.getAlignment());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000135 // Now cast the result of the load.
136 return new BitCastInst(NewLoad, LI.getType());
137 }
138 }
139 }
140 return 0;
141}
142
143Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
144 Value *Op = LI.getOperand(0);
145
146 // Attempt to improve the alignment.
147 if (TD) {
148 unsigned KnownAlign =
Chris Lattner6fcd32e2010-12-25 20:37:57 +0000149 getOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()),TD);
Dan Gohman36196602010-08-03 18:20:32 +0000150 unsigned LoadAlign = LI.getAlignment();
151 unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
152 TD->getABITypeAlignment(LI.getType());
153
154 if (KnownAlign > EffectiveLoadAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000155 LI.setAlignment(KnownAlign);
Dan Gohman36196602010-08-03 18:20:32 +0000156 else if (LoadAlign == 0)
157 LI.setAlignment(EffectiveLoadAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000158 }
159
160 // load (cast X) --> cast (load X) iff safe.
161 if (isa<CastInst>(Op))
162 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
163 return Res;
164
165 // None of the following transforms are legal for volatile loads.
166 if (LI.isVolatile()) return 0;
167
168 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +0000169 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +0000170 // separated by a few arithmetic operations.
171 BasicBlock::iterator BBI = &LI;
172 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
173 return ReplaceInstUsesWith(LI, AvailableVal);
174
175 // load(gep null, ...) -> unreachable
176 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
177 const Value *GEPI0 = GEPI->getOperand(0);
178 // TODO: Consider a target hook for valid address spaces for this xform.
179 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
180 // Insert a new store to null instruction before the load to indicate
181 // that this code is not reachable. We do this instead of inserting
182 // an unreachable instruction directly because we cannot modify the
183 // CFG.
184 new StoreInst(UndefValue::get(LI.getType()),
185 Constant::getNullValue(Op->getType()), &LI);
186 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
187 }
188 }
189
190 // load null/undef -> unreachable
191 // TODO: Consider a target hook for valid address spaces for this xform.
192 if (isa<UndefValue>(Op) ||
193 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
194 // Insert a new store to null instruction before the load to indicate that
195 // this code is not reachable. We do this instead of inserting an
196 // unreachable instruction directly because we cannot modify the CFG.
197 new StoreInst(UndefValue::get(LI.getType()),
198 Constant::getNullValue(Op->getType()), &LI);
199 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
200 }
201
202 // Instcombine load (constantexpr_cast global) -> cast (load global)
203 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
204 if (CE->isCast())
205 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
206 return Res;
207
208 if (Op->hasOneUse()) {
209 // Change select and PHI nodes to select values instead of addresses: this
210 // helps alias analysis out a lot, allows many others simplifications, and
211 // exposes redundancy in the code.
212 //
213 // Note that we cannot do the transformation unless we know that the
214 // introduced loads cannot trap! Something like this is valid as long as
215 // the condition is always false: load (select bool %C, int* null, int* %G),
216 // but it would not be valid if we transformed it to load from null
217 // unconditionally.
218 //
219 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
220 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +0000221 unsigned Align = LI.getAlignment();
222 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, TD) &&
223 isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, TD)) {
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000224 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
Bob Wilson56600a12010-01-30 04:42:39 +0000225 SI->getOperand(1)->getName()+".val");
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000226 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
Bob Wilson56600a12010-01-30 04:42:39 +0000227 SI->getOperand(2)->getName()+".val");
228 V1->setAlignment(Align);
229 V2->setAlignment(Align);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000230 return SelectInst::Create(SI->getCondition(), V1, V2);
231 }
232
233 // load (select (cond, null, P)) -> load P
234 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
235 if (C->isNullValue()) {
236 LI.setOperand(0, SI->getOperand(2));
237 return &LI;
238 }
239
240 // load (select (cond, P, null)) -> load P
241 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
242 if (C->isNullValue()) {
243 LI.setOperand(0, SI->getOperand(1));
244 return &LI;
245 }
246 }
247 }
248 return 0;
249}
250
251/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
252/// when possible. This makes it generally easy to do alias analysis and/or
253/// SROA/mem2reg of the memory object.
254static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
255 User *CI = cast<User>(SI.getOperand(1));
256 Value *CastOp = CI->getOperand(0);
257
Chris Lattner229907c2011-07-18 04:54:35 +0000258 Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
259 PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000260 if (SrcTy == 0) return 0;
261
Chris Lattner229907c2011-07-18 04:54:35 +0000262 Type *SrcPTy = SrcTy->getElementType();
Chris Lattnera65e2f72010-01-05 05:57:49 +0000263
Duncan Sands19d0b472010-02-16 11:11:14 +0000264 if (!DestPTy->isIntegerTy() && !DestPTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000265 return 0;
266
267 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
268 /// to its first element. This allows us to handle things like:
269 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
270 /// on 32-bit hosts.
271 SmallVector<Value*, 4> NewGEPIndices;
272
273 // If the source is an array, the code below will not succeed. Check to
274 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
275 // constants.
Duncan Sands19d0b472010-02-16 11:11:14 +0000276 if (SrcPTy->isArrayTy() || SrcPTy->isStructTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000277 // Index through pointer.
278 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
279 NewGEPIndices.push_back(Zero);
280
281 while (1) {
Chris Lattner229907c2011-07-18 04:54:35 +0000282 if (StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000283 if (!STy->getNumElements()) /* Struct can be empty {} */
284 break;
285 NewGEPIndices.push_back(Zero);
286 SrcPTy = STy->getElementType(0);
Chris Lattner229907c2011-07-18 04:54:35 +0000287 } else if (ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000288 NewGEPIndices.push_back(Zero);
289 SrcPTy = ATy->getElementType();
290 } else {
291 break;
292 }
293 }
294
295 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
296 }
297
Duncan Sands19d0b472010-02-16 11:11:14 +0000298 if (!SrcPTy->isIntegerTy() && !SrcPTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000299 return 0;
300
301 // If the pointers point into different address spaces or if they point to
302 // values with different sizes, we can't do the transformation.
303 if (!IC.getTargetData() ||
304 SrcTy->getAddressSpace() !=
305 cast<PointerType>(CI->getType())->getAddressSpace() ||
306 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
307 IC.getTargetData()->getTypeSizeInBits(DestPTy))
308 return 0;
309
310 // Okay, we are casting from one integer or pointer type to another of
311 // the same size. Instead of casting the pointer before
312 // the store, cast the value to be stored.
313 Value *NewCast;
314 Value *SIOp0 = SI.getOperand(0);
315 Instruction::CastOps opcode = Instruction::BitCast;
Chris Lattner229907c2011-07-18 04:54:35 +0000316 Type* CastSrcTy = SIOp0->getType();
317 Type* CastDstTy = SrcPTy;
Duncan Sands19d0b472010-02-16 11:11:14 +0000318 if (CastDstTy->isPointerTy()) {
Duncan Sands9dff9be2010-02-15 16:12:20 +0000319 if (CastSrcTy->isIntegerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000320 opcode = Instruction::IntToPtr;
Duncan Sands19d0b472010-02-16 11:11:14 +0000321 } else if (CastDstTy->isIntegerTy()) {
322 if (SIOp0->getType()->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000323 opcode = Instruction::PtrToInt;
324 }
325
326 // SIOp0 is a pointer to aggregate and this is a store to the first field,
327 // emit a GEP to index into its first field.
328 if (!NewGEPIndices.empty())
Jay Foad040dd822011-07-22 08:16:57 +0000329 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000330
331 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
332 SIOp0->getName()+".c");
Dan Gohman2e20dfb2010-10-25 16:16:27 +0000333 SI.setOperand(0, NewCast);
334 SI.setOperand(1, CastOp);
335 return &SI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000336}
337
338/// equivalentAddressValues - Test if A and B will obviously have the same
339/// value. This includes recognizing that %t0 and %t1 will have the same
340/// value in code like this:
341/// %t0 = getelementptr \@a, 0, 3
342/// store i32 0, i32* %t0
343/// %t1 = getelementptr \@a, 0, 3
344/// %t2 = load i32* %t1
345///
346static bool equivalentAddressValues(Value *A, Value *B) {
347 // Test if the values are trivially equivalent.
348 if (A == B) return true;
349
350 // Test if the values come form identical arithmetic instructions.
351 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
352 // its only used to compare two uses within the same basic block, which
353 // means that they'll always either have the same value or one of them
354 // will have an undefined value.
355 if (isa<BinaryOperator>(A) ||
356 isa<CastInst>(A) ||
357 isa<PHINode>(A) ||
358 isa<GetElementPtrInst>(A))
359 if (Instruction *BI = dyn_cast<Instruction>(B))
360 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
361 return true;
362
363 // Otherwise they may not be equivalent.
364 return false;
365}
366
Chris Lattnera65e2f72010-01-05 05:57:49 +0000367Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
368 Value *Val = SI.getOperand(0);
369 Value *Ptr = SI.getOperand(1);
370
371 // If the RHS is an alloca with a single use, zapify the store, making the
372 // alloca dead.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000373 if (!SI.isVolatile()) {
374 if (Ptr->hasOneUse()) {
375 if (isa<AllocaInst>(Ptr))
376 return EraseInstFromFunction(SI);
377 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
378 if (isa<AllocaInst>(GEP->getOperand(0))) {
379 if (GEP->getOperand(0)->hasOneUse())
380 return EraseInstFromFunction(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000381 }
382 }
383 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000384 }
385
386 // Attempt to improve the alignment.
387 if (TD) {
388 unsigned KnownAlign =
Chris Lattner6fcd32e2010-12-25 20:37:57 +0000389 getOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()),
390 TD);
Dan Gohman36196602010-08-03 18:20:32 +0000391 unsigned StoreAlign = SI.getAlignment();
392 unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
393 TD->getABITypeAlignment(Val->getType());
394
395 if (KnownAlign > EffectiveStoreAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000396 SI.setAlignment(KnownAlign);
Dan Gohman36196602010-08-03 18:20:32 +0000397 else if (StoreAlign == 0)
398 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000399 }
400
401 // Do really simple DSE, to catch cases where there are several consecutive
402 // stores to the same location, separated by a few arithmetic operations. This
403 // situation often occurs with bitfield accesses.
404 BasicBlock::iterator BBI = &SI;
405 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
406 --ScanInsts) {
407 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000408 // Don't count debug info directives, lest they affect codegen,
409 // and we skip pointer-to-pointer bitcasts, which are NOPs.
410 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000411 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000412 ScanInsts++;
413 continue;
414 }
415
416 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
417 // Prev store isn't volatile, and stores to the same location?
418 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
419 SI.getOperand(1))) {
420 ++NumDeadStore;
421 ++BBI;
422 EraseInstFromFunction(*PrevSI);
423 continue;
424 }
425 break;
426 }
427
428 // If this is a load, we have to stop. However, if the loaded value is from
429 // the pointer we're loading and is producing the pointer we're storing,
430 // then *this* store is dead (X = load P; store X -> P).
431 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000432 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
433 !SI.isVolatile())
434 return EraseInstFromFunction(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000435
436 // Otherwise, this is a load from some other location. Stores before it
437 // may not be dead.
438 break;
439 }
440
441 // Don't skip over loads or things that can modify memory.
442 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
443 break;
444 }
445
446
447 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
448
449 // store X, null -> turns into 'unreachable' in SimplifyCFG
450 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
451 if (!isa<UndefValue>(Val)) {
452 SI.setOperand(0, UndefValue::get(Val->getType()));
453 if (Instruction *U = dyn_cast<Instruction>(Val))
454 Worklist.Add(U); // Dropped a use.
455 }
456 return 0; // Do not modify these!
457 }
458
459 // store undef, Ptr -> noop
460 if (isa<UndefValue>(Val))
461 return EraseInstFromFunction(SI);
462
463 // If the pointer destination is a cast, see if we can fold the cast into the
464 // source instead.
465 if (isa<CastInst>(Ptr))
466 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
467 return Res;
468 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
469 if (CE->isCast())
470 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
471 return Res;
472
473
474 // If this store is the last instruction in the basic block (possibly
Victor Hernandez5f5abd52010-01-21 23:07:15 +0000475 // excepting debug info instructions), and if the block ends with an
476 // unconditional branch, try to move it to the successor block.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000477 BBI = &SI;
478 do {
479 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000480 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000481 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000482 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
483 if (BI->isUnconditional())
484 if (SimplifyStoreAtEndOfBlock(SI))
485 return 0; // xform done!
486
487 return 0;
488}
489
490/// SimplifyStoreAtEndOfBlock - Turn things like:
491/// if () { *P = v1; } else { *P = v2 }
492/// into a phi node with a store in the successor.
493///
494/// Simplify things like:
495/// *P = v1; if () { *P = v2; }
496/// into a phi node with a store in the successor.
497///
498bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
499 BasicBlock *StoreBB = SI.getParent();
500
501 // Check to see if the successor block has exactly two incoming edges. If
502 // so, see if the other predecessor contains a store to the same location.
503 // if so, insert a PHI node (if needed) and move the stores down.
504 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
505
506 // Determine whether Dest has exactly two predecessors and, if so, compute
507 // the other predecessor.
508 pred_iterator PI = pred_begin(DestBB);
Gabor Greif1b787df2010-07-12 15:48:26 +0000509 BasicBlock *P = *PI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000510 BasicBlock *OtherBB = 0;
Gabor Greif1b787df2010-07-12 15:48:26 +0000511
512 if (P != StoreBB)
513 OtherBB = P;
514
515 if (++PI == pred_end(DestBB))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000516 return false;
517
Gabor Greif1b787df2010-07-12 15:48:26 +0000518 P = *PI;
519 if (P != StoreBB) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000520 if (OtherBB)
521 return false;
Gabor Greif1b787df2010-07-12 15:48:26 +0000522 OtherBB = P;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000523 }
524 if (++PI != pred_end(DestBB))
525 return false;
526
527 // Bail out if all the relevant blocks aren't distinct (this can happen,
528 // for example, if SI is in an infinite loop)
529 if (StoreBB == DestBB || OtherBB == DestBB)
530 return false;
531
532 // Verify that the other block ends in a branch and is not otherwise empty.
533 BasicBlock::iterator BBI = OtherBB->getTerminator();
534 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
535 if (!OtherBr || BBI == OtherBB->begin())
536 return false;
537
538 // If the other block ends in an unconditional branch, check for the 'if then
539 // else' case. there is an instruction before the branch.
540 StoreInst *OtherStore = 0;
541 if (OtherBr->isUnconditional()) {
542 --BBI;
543 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000544 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000545 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000546 if (BBI==OtherBB->begin())
547 return false;
548 --BBI;
549 }
550 // If this isn't a store, isn't a store to the same location, or if the
551 // alignments differ, bail out.
552 OtherStore = dyn_cast<StoreInst>(BBI);
553 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
554 OtherStore->getAlignment() != SI.getAlignment())
555 return false;
556 } else {
557 // Otherwise, the other block ended with a conditional branch. If one of the
558 // destinations is StoreBB, then we have the if/then case.
559 if (OtherBr->getSuccessor(0) != StoreBB &&
560 OtherBr->getSuccessor(1) != StoreBB)
561 return false;
562
563 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
564 // if/then triangle. See if there is a store to the same ptr as SI that
565 // lives in OtherBB.
566 for (;; --BBI) {
567 // Check to see if we find the matching store.
568 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
569 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
570 OtherStore->getAlignment() != SI.getAlignment())
571 return false;
572 break;
573 }
574 // If we find something that may be using or overwriting the stored
575 // value, or if we run out of instructions, we can't do the xform.
576 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
577 BBI == OtherBB->begin())
578 return false;
579 }
580
581 // In order to eliminate the store in OtherBr, we have to
582 // make sure nothing reads or overwrites the stored value in
583 // StoreBB.
584 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
585 // FIXME: This should really be AA driven.
586 if (I->mayReadFromMemory() || I->mayWriteToMemory())
587 return false;
588 }
589 }
590
591 // Insert a PHI node now if we need it.
592 Value *MergedVal = OtherStore->getOperand(0);
593 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +0000594 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +0000595 PN->addIncoming(SI.getOperand(0), SI.getParent());
596 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
597 MergedVal = InsertNewInstBefore(PN, DestBB->front());
598 }
599
600 // Advance to a place where it is safe to insert the new store and
601 // insert it.
602 BBI = DestBB->getFirstNonPHI();
Eli Friedman35211c62011-05-27 00:19:40 +0000603 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
604 OtherStore->isVolatile(),
605 SI.getAlignment());
606 InsertNewInstBefore(NewSI, *BBI);
607 NewSI->setDebugLoc(OtherStore->getDebugLoc());
608
Chris Lattnera65e2f72010-01-05 05:57:49 +0000609 // Nuke the old stores.
610 EraseInstFromFunction(SI);
611 EraseInstFromFunction(*OtherStore);
612 return true;
613}