blob: 5b6cf4a4a83f3daa85443a80f62d53732074aa2c [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
Chandler Carruthc908ca12012-08-21 08:39:44 +000023STATISTIC(NumDeadStore, "Number of dead stores eliminated");
24STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
25
26/// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
27/// some part of a constant global variable. This intentionally only accepts
28/// constant expressions because we can't rewrite arbitrary instructions.
29static bool pointsToConstantGlobal(Value *V) {
30 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
31 return GV->isConstant();
32 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
33 if (CE->getOpcode() == Instruction::BitCast ||
34 CE->getOpcode() == Instruction::GetElementPtr)
35 return pointsToConstantGlobal(CE->getOperand(0));
36 return false;
37}
38
39/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
40/// pointer to an alloca. Ignore any reads of the pointer, return false if we
41/// see any stores or other unknown uses. If we see pointer arithmetic, keep
42/// track of whether it moves the pointer (with IsOffset) but otherwise traverse
43/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
44/// the alloca, and if the source pointer is a pointer to a constant global, we
45/// can optimize this.
46static bool
47isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
48 SmallVectorImpl<Instruction *> &ToDelete,
49 bool IsOffset = false) {
50 // We track lifetime intrinsics as we encounter them. If we decide to go
51 // ahead and replace the value with the global, this lets the caller quickly
52 // eliminate the markers.
53
54 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
55 User *U = cast<Instruction>(*UI);
56
57 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
58 // Ignore non-volatile loads, they are always ok.
59 if (!LI->isSimple()) return false;
60 continue;
61 }
62
63 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
64 // If uses of the bitcast are ok, we are ok.
65 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, ToDelete, IsOffset))
66 return false;
67 continue;
68 }
69 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
70 // If the GEP has all zero indices, it doesn't offset the pointer. If it
71 // doesn't, it does.
72 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy, ToDelete,
73 IsOffset || !GEP->hasAllZeroIndices()))
74 return false;
75 continue;
76 }
77
78 if (CallSite CS = U) {
79 // If this is the function being called then we treat it like a load and
80 // ignore it.
81 if (CS.isCallee(UI))
82 continue;
83
84 // If this is a readonly/readnone call site, then we know it is just a
85 // load (but one that potentially returns the value itself), so we can
86 // ignore it if we know that the value isn't captured.
87 unsigned ArgNo = CS.getArgumentNo(UI);
88 if (CS.onlyReadsMemory() &&
89 (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
90 continue;
91
92 // If this is being passed as a byval argument, the caller is making a
93 // copy, so it is only a read of the alloca.
94 if (CS.isByValArgument(ArgNo))
95 continue;
96 }
97
98 // Lifetime intrinsics can be handled by the caller.
99 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
100 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
101 II->getIntrinsicID() == Intrinsic::lifetime_end) {
102 assert(II->use_empty() && "Lifetime markers have no result to use!");
103 ToDelete.push_back(II);
104 continue;
105 }
106 }
107
108 // If this is isn't our memcpy/memmove, reject it as something we can't
109 // handle.
110 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
111 if (MI == 0)
112 return false;
113
114 // If the transfer is using the alloca as a source of the transfer, then
115 // ignore it since it is a load (unless the transfer is volatile).
116 if (UI.getOperandNo() == 1) {
117 if (MI->isVolatile()) return false;
118 continue;
119 }
120
121 // If we already have seen a copy, reject the second one.
122 if (TheCopy) return false;
123
124 // If the pointer has been offset from the start of the alloca, we can't
125 // safely handle this.
126 if (IsOffset) return false;
127
128 // If the memintrinsic isn't using the alloca as the dest, reject it.
129 if (UI.getOperandNo() != 0) return false;
130
131 // If the source of the memcpy/move is not a constant global, reject it.
132 if (!pointsToConstantGlobal(MI->getSource()))
133 return false;
134
135 // Otherwise, the transform is safe. Remember the copy instruction.
136 TheCopy = MI;
137 }
138 return true;
139}
140
141/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
142/// modified by a copy from a constant global. If we can prove this, we can
143/// replace any uses of the alloca with uses of the global directly.
144static MemTransferInst *
145isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
146 SmallVectorImpl<Instruction *> &ToDelete) {
147 MemTransferInst *TheCopy = 0;
148 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
149 return TheCopy;
150 return 0;
151}
152
153/// getPointeeAlignment - Compute the minimum alignment of the value pointed
154/// to by the given pointer.
155static unsigned getPointeeAlignment(Value *V, const TargetData &TD) {
156 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
157 if (CE->getOpcode() == Instruction::BitCast ||
158 (CE->getOpcode() == Instruction::GetElementPtr &&
159 cast<GEPOperator>(CE)->hasAllZeroIndices()))
160 return getPointeeAlignment(CE->getOperand(0), TD);
161
162 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
163 if (!GV->isDeclaration())
164 return TD.getPreferredAlignment(GV);
165
166 if (PointerType *PT = dyn_cast<PointerType>(V->getType()))
167 return TD.getABITypeAlignment(PT->getElementType());
168
169 return 0;
170}
Chris Lattnera65e2f72010-01-05 05:57:49 +0000171
172Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Dan Gohmandf5d7dc2010-05-28 15:09:00 +0000173 // Ensure that the alloca array size argument has type intptr_t, so that
174 // any casting is exposed early.
175 if (TD) {
Chris Lattner229907c2011-07-18 04:54:35 +0000176 Type *IntPtrTy = TD->getIntPtrType(AI.getContext());
Dan Gohmandf5d7dc2010-05-28 15:09:00 +0000177 if (AI.getArraySize()->getType() != IntPtrTy) {
178 Value *V = Builder->CreateIntCast(AI.getArraySize(),
179 IntPtrTy, false);
180 AI.setOperand(0, V);
181 return &AI;
182 }
183 }
184
Chris Lattnera65e2f72010-01-05 05:57:49 +0000185 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
186 if (AI.isArrayAllocation()) { // Check C != 1
187 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
Chris Lattner229907c2011-07-18 04:54:35 +0000188 Type *NewTy =
Chris Lattnera65e2f72010-01-05 05:57:49 +0000189 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000190 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
191 New->setAlignment(AI.getAlignment());
192
193 // Scan to the end of the allocation instructions, to skip over a block of
194 // allocas if possible...also skip interleaved debug info
195 //
196 BasicBlock::iterator It = New;
197 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
198
199 // Now that I is pointing to the first non-allocation-inst in the block,
200 // insert our getelementptr instruction...
201 //
202 Value *NullIdx =Constant::getNullValue(Type::getInt32Ty(AI.getContext()));
203 Value *Idx[2];
204 Idx[0] = NullIdx;
205 Idx[1] = NullIdx;
Eli Friedman41e509a2011-05-18 23:58:37 +0000206 Instruction *GEP =
Jay Foadd1b78492011-07-25 09:48:08 +0000207 GetElementPtrInst::CreateInBounds(New, Idx, New->getName()+".sub");
Eli Friedman41e509a2011-05-18 23:58:37 +0000208 InsertNewInstBefore(GEP, *It);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000209
210 // Now make everything use the getelementptr instead of the original
211 // allocation.
Eli Friedman41e509a2011-05-18 23:58:37 +0000212 return ReplaceInstUsesWith(AI, GEP);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000213 } else if (isa<UndefValue>(AI.getArraySize())) {
214 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
215 }
216 }
217
Duncan Sands8bc764a2012-06-26 13:39:21 +0000218 if (TD && AI.getAllocatedType()->isSized()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000219 // If the alignment is 0 (unspecified), assign it the preferred alignment.
220 if (AI.getAlignment() == 0)
221 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000222
223 // Move all alloca's of zero byte objects to the entry block and merge them
224 // together. Note that we only do this for alloca's, because malloc should
225 // allocate and return a unique pointer, even for a zero byte allocation.
226 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0) {
227 // For a zero sized alloca there is no point in doing an array allocation.
228 // This is helpful if the array size is a complicated expression not used
229 // elsewhere.
230 if (AI.isArrayAllocation()) {
231 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
232 return &AI;
233 }
234
235 // Get the first instruction in the entry block.
236 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
237 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
238 if (FirstInst != &AI) {
239 // If the entry block doesn't start with a zero-size alloca then move
240 // this one to the start of the entry block. There is no problem with
241 // dominance as the array size was forced to a constant earlier already.
242 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
243 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
244 TD->getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
245 AI.moveBefore(FirstInst);
246 return &AI;
247 }
248
Richard Osborneb68053e2012-09-18 09:31:44 +0000249 // If the alignment of the entry block alloca is 0 (unspecified),
250 // assign it the preferred alignment.
251 if (EntryAI->getAlignment() == 0)
252 EntryAI->setAlignment(
253 TD->getPrefTypeAlignment(EntryAI->getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000254 // Replace this zero-sized alloca with the one at the start of the entry
255 // block after ensuring that the address will be aligned enough for both
256 // types.
Richard Osborneb68053e2012-09-18 09:31:44 +0000257 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
258 AI.getAlignment());
Duncan Sands8bc764a2012-06-26 13:39:21 +0000259 EntryAI->setAlignment(MaxAlign);
260 if (AI.getType() != EntryAI->getType())
261 return new BitCastInst(EntryAI, AI.getType());
262 return ReplaceInstUsesWith(AI, EntryAI);
263 }
264 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000265 }
266
Chandler Carruthc908ca12012-08-21 08:39:44 +0000267 // Check to see if this allocation is only modified by a memcpy/memmove from
268 // a constant global whose alignment is equal to or exceeds that of the
269 // allocation. If this is the case, we can change all users to use
270 // the constant global instead. This is commonly produced by the CFE by
271 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
272 // is only subsequently read.
273 SmallVector<Instruction *, 4> ToDelete;
274 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
275 if (AI.getAlignment() <= getPointeeAlignment(Copy->getSource(), *TD)) {
276 DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
277 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
278 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
279 EraseInstFromFunction(*ToDelete[i]);
280 Constant *TheSrc = cast<Constant>(Copy->getSource());
281 Instruction *NewI
282 = ReplaceInstUsesWith(AI, ConstantExpr::getBitCast(TheSrc,
283 AI.getType()));
284 EraseInstFromFunction(*Copy);
285 ++NumGlobalCopies;
286 return NewI;
287 }
288 }
289
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000290 // At last, use the generic allocation site handler to aggressively remove
291 // unused allocas.
292 return visitAllocSite(AI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000293}
294
295
296/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
297static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
298 const TargetData *TD) {
299 User *CI = cast<User>(LI.getOperand(0));
300 Value *CastOp = CI->getOperand(0);
301
Chris Lattner229907c2011-07-18 04:54:35 +0000302 PointerType *DestTy = cast<PointerType>(CI->getType());
303 Type *DestPTy = DestTy->getElementType();
304 if (PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000305
306 // If the address spaces don't match, don't eliminate the cast.
307 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
308 return 0;
309
Chris Lattner229907c2011-07-18 04:54:35 +0000310 Type *SrcPTy = SrcTy->getElementType();
Chris Lattnera65e2f72010-01-05 05:57:49 +0000311
Duncan Sands19d0b472010-02-16 11:11:14 +0000312 if (DestPTy->isIntegerTy() || DestPTy->isPointerTy() ||
313 DestPTy->isVectorTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000314 // If the source is an array, the code below will not succeed. Check to
315 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
316 // constants.
Chris Lattner229907c2011-07-18 04:54:35 +0000317 if (ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000318 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
319 if (ASrcTy->getNumElements() != 0) {
320 Value *Idxs[2];
321 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(LI.getContext()));
322 Idxs[1] = Idxs[0];
Jay Foad71f19ac2011-07-22 07:54:01 +0000323 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000324 SrcTy = cast<PointerType>(CastOp->getType());
325 SrcPTy = SrcTy->getElementType();
326 }
327
328 if (IC.getTargetData() &&
Duncan Sands19d0b472010-02-16 11:11:14 +0000329 (SrcPTy->isIntegerTy() || SrcPTy->isPointerTy() ||
330 SrcPTy->isVectorTy()) &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000331 // Do not allow turning this into a load of an integer, which is then
332 // casted to a pointer, this pessimizes pointer analysis a lot.
Duncan Sands19d0b472010-02-16 11:11:14 +0000333 (SrcPTy->isPointerTy() == LI.getType()->isPointerTy()) &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000334 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
335 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
336
337 // Okay, we are casting from one integer or pointer type to another of
338 // the same size. Instead of casting the pointer before the load, cast
339 // the result of the loaded value.
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000340 LoadInst *NewLoad =
Chris Lattnera65e2f72010-01-05 05:57:49 +0000341 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000342 NewLoad->setAlignment(LI.getAlignment());
Eli Friedman8bc586e2011-08-15 22:09:40 +0000343 NewLoad->setAtomic(LI.getOrdering(), LI.getSynchScope());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000344 // Now cast the result of the load.
345 return new BitCastInst(NewLoad, LI.getType());
346 }
347 }
348 }
349 return 0;
350}
351
352Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
353 Value *Op = LI.getOperand(0);
354
355 // Attempt to improve the alignment.
356 if (TD) {
357 unsigned KnownAlign =
Chris Lattner6fcd32e2010-12-25 20:37:57 +0000358 getOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()),TD);
Dan Gohman36196602010-08-03 18:20:32 +0000359 unsigned LoadAlign = LI.getAlignment();
360 unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
361 TD->getABITypeAlignment(LI.getType());
362
363 if (KnownAlign > EffectiveLoadAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000364 LI.setAlignment(KnownAlign);
Dan Gohman36196602010-08-03 18:20:32 +0000365 else if (LoadAlign == 0)
366 LI.setAlignment(EffectiveLoadAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000367 }
368
369 // load (cast X) --> cast (load X) iff safe.
370 if (isa<CastInst>(Op))
371 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
372 return Res;
373
Eli Friedman8bc586e2011-08-15 22:09:40 +0000374 // None of the following transforms are legal for volatile/atomic loads.
375 // FIXME: Some of it is okay for atomic loads; needs refactoring.
376 if (!LI.isSimple()) return 0;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000377
378 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +0000379 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +0000380 // separated by a few arithmetic operations.
381 BasicBlock::iterator BBI = &LI;
382 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
383 return ReplaceInstUsesWith(LI, AvailableVal);
384
385 // load(gep null, ...) -> unreachable
386 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
387 const Value *GEPI0 = GEPI->getOperand(0);
388 // TODO: Consider a target hook for valid address spaces for this xform.
389 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
390 // Insert a new store to null instruction before the load to indicate
391 // that this code is not reachable. We do this instead of inserting
392 // an unreachable instruction directly because we cannot modify the
393 // CFG.
394 new StoreInst(UndefValue::get(LI.getType()),
395 Constant::getNullValue(Op->getType()), &LI);
396 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
397 }
398 }
399
400 // load null/undef -> unreachable
401 // TODO: Consider a target hook for valid address spaces for this xform.
402 if (isa<UndefValue>(Op) ||
403 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
404 // Insert a new store to null instruction before the load to indicate that
405 // this code is not reachable. We do this instead of inserting an
406 // unreachable instruction directly because we cannot modify the CFG.
407 new StoreInst(UndefValue::get(LI.getType()),
408 Constant::getNullValue(Op->getType()), &LI);
409 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
410 }
411
412 // Instcombine load (constantexpr_cast global) -> cast (load global)
413 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
414 if (CE->isCast())
415 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
416 return Res;
417
418 if (Op->hasOneUse()) {
419 // Change select and PHI nodes to select values instead of addresses: this
420 // helps alias analysis out a lot, allows many others simplifications, and
421 // exposes redundancy in the code.
422 //
423 // Note that we cannot do the transformation unless we know that the
424 // introduced loads cannot trap! Something like this is valid as long as
425 // the condition is always false: load (select bool %C, int* null, int* %G),
426 // but it would not be valid if we transformed it to load from null
427 // unconditionally.
428 //
429 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
430 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +0000431 unsigned Align = LI.getAlignment();
432 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, TD) &&
433 isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, TD)) {
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000434 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
Bob Wilson56600a12010-01-30 04:42:39 +0000435 SI->getOperand(1)->getName()+".val");
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000436 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
Bob Wilson56600a12010-01-30 04:42:39 +0000437 SI->getOperand(2)->getName()+".val");
438 V1->setAlignment(Align);
439 V2->setAlignment(Align);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000440 return SelectInst::Create(SI->getCondition(), V1, V2);
441 }
442
443 // load (select (cond, null, P)) -> load P
444 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
445 if (C->isNullValue()) {
446 LI.setOperand(0, SI->getOperand(2));
447 return &LI;
448 }
449
450 // load (select (cond, P, null)) -> load P
451 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
452 if (C->isNullValue()) {
453 LI.setOperand(0, SI->getOperand(1));
454 return &LI;
455 }
456 }
457 }
458 return 0;
459}
460
461/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
462/// when possible. This makes it generally easy to do alias analysis and/or
463/// SROA/mem2reg of the memory object.
464static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
465 User *CI = cast<User>(SI.getOperand(1));
466 Value *CastOp = CI->getOperand(0);
467
Chris Lattner229907c2011-07-18 04:54:35 +0000468 Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
469 PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000470 if (SrcTy == 0) return 0;
471
Chris Lattner229907c2011-07-18 04:54:35 +0000472 Type *SrcPTy = SrcTy->getElementType();
Chris Lattnera65e2f72010-01-05 05:57:49 +0000473
Duncan Sands19d0b472010-02-16 11:11:14 +0000474 if (!DestPTy->isIntegerTy() && !DestPTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000475 return 0;
476
477 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
478 /// to its first element. This allows us to handle things like:
479 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
480 /// on 32-bit hosts.
481 SmallVector<Value*, 4> NewGEPIndices;
482
483 // If the source is an array, the code below will not succeed. Check to
484 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
485 // constants.
Duncan Sands19d0b472010-02-16 11:11:14 +0000486 if (SrcPTy->isArrayTy() || SrcPTy->isStructTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000487 // Index through pointer.
488 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
489 NewGEPIndices.push_back(Zero);
490
491 while (1) {
Chris Lattner229907c2011-07-18 04:54:35 +0000492 if (StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000493 if (!STy->getNumElements()) /* Struct can be empty {} */
494 break;
495 NewGEPIndices.push_back(Zero);
496 SrcPTy = STy->getElementType(0);
Chris Lattner229907c2011-07-18 04:54:35 +0000497 } else if (ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000498 NewGEPIndices.push_back(Zero);
499 SrcPTy = ATy->getElementType();
500 } else {
501 break;
502 }
503 }
504
505 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
506 }
507
Duncan Sands19d0b472010-02-16 11:11:14 +0000508 if (!SrcPTy->isIntegerTy() && !SrcPTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000509 return 0;
510
511 // If the pointers point into different address spaces or if they point to
512 // values with different sizes, we can't do the transformation.
513 if (!IC.getTargetData() ||
514 SrcTy->getAddressSpace() !=
515 cast<PointerType>(CI->getType())->getAddressSpace() ||
516 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
517 IC.getTargetData()->getTypeSizeInBits(DestPTy))
518 return 0;
519
520 // Okay, we are casting from one integer or pointer type to another of
521 // the same size. Instead of casting the pointer before
522 // the store, cast the value to be stored.
523 Value *NewCast;
524 Value *SIOp0 = SI.getOperand(0);
525 Instruction::CastOps opcode = Instruction::BitCast;
Chris Lattner229907c2011-07-18 04:54:35 +0000526 Type* CastSrcTy = SIOp0->getType();
527 Type* CastDstTy = SrcPTy;
Duncan Sands19d0b472010-02-16 11:11:14 +0000528 if (CastDstTy->isPointerTy()) {
Duncan Sands9dff9be2010-02-15 16:12:20 +0000529 if (CastSrcTy->isIntegerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000530 opcode = Instruction::IntToPtr;
Duncan Sands19d0b472010-02-16 11:11:14 +0000531 } else if (CastDstTy->isIntegerTy()) {
532 if (SIOp0->getType()->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000533 opcode = Instruction::PtrToInt;
534 }
535
536 // SIOp0 is a pointer to aggregate and this is a store to the first field,
537 // emit a GEP to index into its first field.
538 if (!NewGEPIndices.empty())
Jay Foad040dd822011-07-22 08:16:57 +0000539 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000540
541 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
542 SIOp0->getName()+".c");
Dan Gohman2e20dfb2010-10-25 16:16:27 +0000543 SI.setOperand(0, NewCast);
544 SI.setOperand(1, CastOp);
545 return &SI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000546}
547
548/// equivalentAddressValues - Test if A and B will obviously have the same
549/// value. This includes recognizing that %t0 and %t1 will have the same
550/// value in code like this:
551/// %t0 = getelementptr \@a, 0, 3
552/// store i32 0, i32* %t0
553/// %t1 = getelementptr \@a, 0, 3
554/// %t2 = load i32* %t1
555///
556static bool equivalentAddressValues(Value *A, Value *B) {
557 // Test if the values are trivially equivalent.
558 if (A == B) return true;
559
560 // Test if the values come form identical arithmetic instructions.
561 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
562 // its only used to compare two uses within the same basic block, which
563 // means that they'll always either have the same value or one of them
564 // will have an undefined value.
565 if (isa<BinaryOperator>(A) ||
566 isa<CastInst>(A) ||
567 isa<PHINode>(A) ||
568 isa<GetElementPtrInst>(A))
569 if (Instruction *BI = dyn_cast<Instruction>(B))
570 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
571 return true;
572
573 // Otherwise they may not be equivalent.
574 return false;
575}
576
Chris Lattnera65e2f72010-01-05 05:57:49 +0000577Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
578 Value *Val = SI.getOperand(0);
579 Value *Ptr = SI.getOperand(1);
580
Chris Lattnera65e2f72010-01-05 05:57:49 +0000581 // Attempt to improve the alignment.
582 if (TD) {
583 unsigned KnownAlign =
Chris Lattner6fcd32e2010-12-25 20:37:57 +0000584 getOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()),
585 TD);
Dan Gohman36196602010-08-03 18:20:32 +0000586 unsigned StoreAlign = SI.getAlignment();
587 unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
588 TD->getABITypeAlignment(Val->getType());
589
Bill Wendling55b6b2b2012-03-16 18:20:54 +0000590 if (KnownAlign > EffectiveStoreAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000591 SI.setAlignment(KnownAlign);
Bill Wendling55b6b2b2012-03-16 18:20:54 +0000592 else if (StoreAlign == 0)
593 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000594 }
595
Eli Friedman8bc586e2011-08-15 22:09:40 +0000596 // Don't hack volatile/atomic stores.
597 // FIXME: Some bits are legal for atomic stores; needs refactoring.
598 if (!SI.isSimple()) return 0;
599
600 // If the RHS is an alloca with a single use, zapify the store, making the
601 // alloca dead.
602 if (Ptr->hasOneUse()) {
603 if (isa<AllocaInst>(Ptr))
604 return EraseInstFromFunction(SI);
605 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
606 if (isa<AllocaInst>(GEP->getOperand(0))) {
607 if (GEP->getOperand(0)->hasOneUse())
608 return EraseInstFromFunction(SI);
609 }
610 }
611 }
612
Chris Lattnera65e2f72010-01-05 05:57:49 +0000613 // Do really simple DSE, to catch cases where there are several consecutive
614 // stores to the same location, separated by a few arithmetic operations. This
615 // situation often occurs with bitfield accesses.
616 BasicBlock::iterator BBI = &SI;
617 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
618 --ScanInsts) {
619 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000620 // Don't count debug info directives, lest they affect codegen,
621 // and we skip pointer-to-pointer bitcasts, which are NOPs.
622 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000623 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000624 ScanInsts++;
625 continue;
626 }
627
628 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
629 // Prev store isn't volatile, and stores to the same location?
Eli Friedman8bc586e2011-08-15 22:09:40 +0000630 if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
631 SI.getOperand(1))) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000632 ++NumDeadStore;
633 ++BBI;
634 EraseInstFromFunction(*PrevSI);
635 continue;
636 }
637 break;
638 }
639
640 // If this is a load, we have to stop. However, if the loaded value is from
641 // the pointer we're loading and is producing the pointer we're storing,
642 // then *this* store is dead (X = load P; store X -> P).
643 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000644 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
Eli Friedman8bc586e2011-08-15 22:09:40 +0000645 LI->isSimple())
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000646 return EraseInstFromFunction(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000647
648 // Otherwise, this is a load from some other location. Stores before it
649 // may not be dead.
650 break;
651 }
652
653 // Don't skip over loads or things that can modify memory.
654 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
655 break;
656 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000657
658 // store X, null -> turns into 'unreachable' in SimplifyCFG
659 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
660 if (!isa<UndefValue>(Val)) {
661 SI.setOperand(0, UndefValue::get(Val->getType()));
662 if (Instruction *U = dyn_cast<Instruction>(Val))
663 Worklist.Add(U); // Dropped a use.
664 }
665 return 0; // Do not modify these!
666 }
667
668 // store undef, Ptr -> noop
669 if (isa<UndefValue>(Val))
670 return EraseInstFromFunction(SI);
671
672 // If the pointer destination is a cast, see if we can fold the cast into the
673 // source instead.
674 if (isa<CastInst>(Ptr))
675 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
676 return Res;
677 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
678 if (CE->isCast())
679 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
680 return Res;
681
682
683 // If this store is the last instruction in the basic block (possibly
Victor Hernandez5f5abd52010-01-21 23:07:15 +0000684 // excepting debug info instructions), and if the block ends with an
685 // unconditional branch, try to move it to the successor block.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000686 BBI = &SI;
687 do {
688 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000689 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000690 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000691 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
692 if (BI->isUnconditional())
693 if (SimplifyStoreAtEndOfBlock(SI))
694 return 0; // xform done!
695
696 return 0;
697}
698
699/// SimplifyStoreAtEndOfBlock - Turn things like:
700/// if () { *P = v1; } else { *P = v2 }
701/// into a phi node with a store in the successor.
702///
703/// Simplify things like:
704/// *P = v1; if () { *P = v2; }
705/// into a phi node with a store in the successor.
706///
707bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
708 BasicBlock *StoreBB = SI.getParent();
709
710 // Check to see if the successor block has exactly two incoming edges. If
711 // so, see if the other predecessor contains a store to the same location.
712 // if so, insert a PHI node (if needed) and move the stores down.
713 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
714
715 // Determine whether Dest has exactly two predecessors and, if so, compute
716 // the other predecessor.
717 pred_iterator PI = pred_begin(DestBB);
Gabor Greif1b787df2010-07-12 15:48:26 +0000718 BasicBlock *P = *PI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000719 BasicBlock *OtherBB = 0;
Gabor Greif1b787df2010-07-12 15:48:26 +0000720
721 if (P != StoreBB)
722 OtherBB = P;
723
724 if (++PI == pred_end(DestBB))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000725 return false;
726
Gabor Greif1b787df2010-07-12 15:48:26 +0000727 P = *PI;
728 if (P != StoreBB) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000729 if (OtherBB)
730 return false;
Gabor Greif1b787df2010-07-12 15:48:26 +0000731 OtherBB = P;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000732 }
733 if (++PI != pred_end(DestBB))
734 return false;
735
736 // Bail out if all the relevant blocks aren't distinct (this can happen,
737 // for example, if SI is in an infinite loop)
738 if (StoreBB == DestBB || OtherBB == DestBB)
739 return false;
740
741 // Verify that the other block ends in a branch and is not otherwise empty.
742 BasicBlock::iterator BBI = OtherBB->getTerminator();
743 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
744 if (!OtherBr || BBI == OtherBB->begin())
745 return false;
746
747 // If the other block ends in an unconditional branch, check for the 'if then
748 // else' case. there is an instruction before the branch.
749 StoreInst *OtherStore = 0;
750 if (OtherBr->isUnconditional()) {
751 --BBI;
752 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000753 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000754 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000755 if (BBI==OtherBB->begin())
756 return false;
757 --BBI;
758 }
Eli Friedman8bc586e2011-08-15 22:09:40 +0000759 // If this isn't a store, isn't a store to the same location, or is not the
760 // right kind of store, bail out.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000761 OtherStore = dyn_cast<StoreInst>(BBI);
762 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +0000763 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000764 return false;
765 } else {
766 // Otherwise, the other block ended with a conditional branch. If one of the
767 // destinations is StoreBB, then we have the if/then case.
768 if (OtherBr->getSuccessor(0) != StoreBB &&
769 OtherBr->getSuccessor(1) != StoreBB)
770 return false;
771
772 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
773 // if/then triangle. See if there is a store to the same ptr as SI that
774 // lives in OtherBB.
775 for (;; --BBI) {
776 // Check to see if we find the matching store.
777 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
778 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +0000779 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000780 return false;
781 break;
782 }
783 // If we find something that may be using or overwriting the stored
784 // value, or if we run out of instructions, we can't do the xform.
785 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
786 BBI == OtherBB->begin())
787 return false;
788 }
789
790 // In order to eliminate the store in OtherBr, we have to
791 // make sure nothing reads or overwrites the stored value in
792 // StoreBB.
793 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
794 // FIXME: This should really be AA driven.
795 if (I->mayReadFromMemory() || I->mayWriteToMemory())
796 return false;
797 }
798 }
799
800 // Insert a PHI node now if we need it.
801 Value *MergedVal = OtherStore->getOperand(0);
802 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +0000803 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +0000804 PN->addIncoming(SI.getOperand(0), SI.getParent());
805 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
806 MergedVal = InsertNewInstBefore(PN, DestBB->front());
807 }
808
809 // Advance to a place where it is safe to insert the new store and
810 // insert it.
Bill Wendling8ddfc092011-08-16 20:45:24 +0000811 BBI = DestBB->getFirstInsertionPt();
Eli Friedman35211c62011-05-27 00:19:40 +0000812 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +0000813 SI.isVolatile(),
814 SI.getAlignment(),
815 SI.getOrdering(),
816 SI.getSynchScope());
Eli Friedman35211c62011-05-27 00:19:40 +0000817 InsertNewInstBefore(NewSI, *BBI);
818 NewSI->setDebugLoc(OtherStore->getDebugLoc());
819
Chris Lattnera65e2f72010-01-05 05:57:49 +0000820 // Nuke the old stores.
821 EraseInstFromFunction(SI);
822 EraseInstFromFunction(*OtherStore);
823 return true;
824}