blob: 1db55fea008deebd2d75cfb627c20ff4b1fda7ec [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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/Statistic.h"
Dan Gohman826bdf82010-05-28 16:19:17 +000016#include "llvm/Analysis/Loads.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/DataLayout.h"
18#include "llvm/IR/IntrinsicInst.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000019#include "llvm/Transforms/Utils/BasicBlockUtils.h"
20#include "llvm/Transforms/Utils/Local.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000021using 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
Chandler Carruthcdf47882014-03-09 03:16:01 +000054 for (Use &U : V->uses()) {
55 Instruction *I = cast<Instruction>(U.getUser());
Chandler Carruthc908ca12012-08-21 08:39:44 +000056
Chandler Carruthcdf47882014-03-09 03:16:01 +000057 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000058 // Ignore non-volatile loads, they are always ok.
59 if (!LI->isSimple()) return false;
60 continue;
61 }
62
Chandler Carruthcdf47882014-03-09 03:16:01 +000063 if (BitCastInst *BCI = dyn_cast<BitCastInst>(I)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000064 // If uses of the bitcast are ok, we are ok.
65 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, ToDelete, IsOffset))
66 return false;
67 continue;
68 }
Chandler Carruthcdf47882014-03-09 03:16:01 +000069 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000070 // If the GEP has all zero indices, it doesn't offset the pointer. If it
71 // doesn't, it does.
Jim Grosbachbdbd7342013-04-05 21:20:12 +000072 if (!isOnlyCopiedFromConstantGlobal(
73 GEP, TheCopy, ToDelete, IsOffset || !GEP->hasAllZeroIndices()))
Chandler Carruthc908ca12012-08-21 08:39:44 +000074 return false;
75 continue;
76 }
77
Chandler Carruthcdf47882014-03-09 03:16:01 +000078 if (CallSite CS = I) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000079 // If this is the function being called then we treat it like a load and
80 // ignore it.
Chandler Carruthcdf47882014-03-09 03:16:01 +000081 if (CS.isCallee(&U))
Chandler Carruthc908ca12012-08-21 08:39:44 +000082 continue;
83
Reid Kleckner26af2ca2014-01-28 02:38:36 +000084 // Inalloca arguments are clobbered by the call.
Chandler Carruthcdf47882014-03-09 03:16:01 +000085 unsigned ArgNo = CS.getArgumentNo(&U);
Reid Kleckner26af2ca2014-01-28 02:38:36 +000086 if (CS.isInAllocaArgument(ArgNo))
87 return false;
88
Chandler Carruthc908ca12012-08-21 08:39:44 +000089 // If this is a readonly/readnone call site, then we know it is just a
90 // load (but one that potentially returns the value itself), so we can
91 // ignore it if we know that the value isn't captured.
Chandler Carruthc908ca12012-08-21 08:39:44 +000092 if (CS.onlyReadsMemory() &&
93 (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
94 continue;
95
96 // If this is being passed as a byval argument, the caller is making a
97 // copy, so it is only a read of the alloca.
98 if (CS.isByValArgument(ArgNo))
99 continue;
100 }
101
102 // Lifetime intrinsics can be handled by the caller.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000103 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +0000104 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
105 II->getIntrinsicID() == Intrinsic::lifetime_end) {
106 assert(II->use_empty() && "Lifetime markers have no result to use!");
107 ToDelete.push_back(II);
108 continue;
109 }
110 }
111
112 // If this is isn't our memcpy/memmove, reject it as something we can't
113 // handle.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000114 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
Chandler Carruthc908ca12012-08-21 08:39:44 +0000115 if (MI == 0)
116 return false;
117
118 // If the transfer is using the alloca as a source of the transfer, then
119 // ignore it since it is a load (unless the transfer is volatile).
Chandler Carruthcdf47882014-03-09 03:16:01 +0000120 if (U.getOperandNo() == 1) {
Chandler Carruthc908ca12012-08-21 08:39:44 +0000121 if (MI->isVolatile()) return false;
122 continue;
123 }
124
125 // If we already have seen a copy, reject the second one.
126 if (TheCopy) return false;
127
128 // If the pointer has been offset from the start of the alloca, we can't
129 // safely handle this.
130 if (IsOffset) return false;
131
132 // If the memintrinsic isn't using the alloca as the dest, reject it.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000133 if (U.getOperandNo() != 0) return false;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000134
135 // If the source of the memcpy/move is not a constant global, reject it.
136 if (!pointsToConstantGlobal(MI->getSource()))
137 return false;
138
139 // Otherwise, the transform is safe. Remember the copy instruction.
140 TheCopy = MI;
141 }
142 return true;
143}
144
145/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
146/// modified by a copy from a constant global. If we can prove this, we can
147/// replace any uses of the alloca with uses of the global directly.
148static MemTransferInst *
149isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
150 SmallVectorImpl<Instruction *> &ToDelete) {
151 MemTransferInst *TheCopy = 0;
152 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
153 return TheCopy;
154 return 0;
155}
156
Chris Lattnera65e2f72010-01-05 05:57:49 +0000157Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Dan Gohmandf5d7dc2010-05-28 15:09:00 +0000158 // Ensure that the alloca array size argument has type intptr_t, so that
159 // any casting is exposed early.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000160 if (DL) {
161 Type *IntPtrTy = DL->getIntPtrType(AI.getType());
Dan Gohmandf5d7dc2010-05-28 15:09:00 +0000162 if (AI.getArraySize()->getType() != IntPtrTy) {
163 Value *V = Builder->CreateIntCast(AI.getArraySize(),
164 IntPtrTy, false);
165 AI.setOperand(0, V);
166 return &AI;
167 }
168 }
169
Chris Lattnera65e2f72010-01-05 05:57:49 +0000170 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
171 if (AI.isArrayAllocation()) { // Check C != 1
172 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000173 Type *NewTy =
Chris Lattnera65e2f72010-01-05 05:57:49 +0000174 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000175 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
176 New->setAlignment(AI.getAlignment());
177
178 // Scan to the end of the allocation instructions, to skip over a block of
179 // allocas if possible...also skip interleaved debug info
180 //
181 BasicBlock::iterator It = New;
182 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
183
184 // Now that I is pointing to the first non-allocation-inst in the block,
185 // insert our getelementptr instruction...
186 //
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000187 Type *IdxTy = DL
188 ? DL->getIntPtrType(AI.getType())
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +0000189 : Type::getInt64Ty(AI.getContext());
190 Value *NullIdx = Constant::getNullValue(IdxTy);
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000191 Value *Idx[2] = { NullIdx, NullIdx };
Eli Friedman41e509a2011-05-18 23:58:37 +0000192 Instruction *GEP =
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000193 GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
Eli Friedman41e509a2011-05-18 23:58:37 +0000194 InsertNewInstBefore(GEP, *It);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000195
196 // Now make everything use the getelementptr instead of the original
197 // allocation.
Eli Friedman41e509a2011-05-18 23:58:37 +0000198 return ReplaceInstUsesWith(AI, GEP);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000199 } else if (isa<UndefValue>(AI.getArraySize())) {
200 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
201 }
202 }
203
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000204 if (DL && AI.getAllocatedType()->isSized()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000205 // If the alignment is 0 (unspecified), assign it the preferred alignment.
206 if (AI.getAlignment() == 0)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000207 AI.setAlignment(DL->getPrefTypeAlignment(AI.getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000208
209 // Move all alloca's of zero byte objects to the entry block and merge them
210 // together. Note that we only do this for alloca's, because malloc should
211 // allocate and return a unique pointer, even for a zero byte allocation.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000212 if (DL->getTypeAllocSize(AI.getAllocatedType()) == 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000213 // For a zero sized alloca there is no point in doing an array allocation.
214 // This is helpful if the array size is a complicated expression not used
215 // elsewhere.
216 if (AI.isArrayAllocation()) {
217 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
218 return &AI;
219 }
220
221 // Get the first instruction in the entry block.
222 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
223 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
224 if (FirstInst != &AI) {
225 // If the entry block doesn't start with a zero-size alloca then move
226 // this one to the start of the entry block. There is no problem with
227 // dominance as the array size was forced to a constant earlier already.
228 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
229 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000230 DL->getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000231 AI.moveBefore(FirstInst);
232 return &AI;
233 }
234
Richard Osborneb68053e2012-09-18 09:31:44 +0000235 // If the alignment of the entry block alloca is 0 (unspecified),
236 // assign it the preferred alignment.
237 if (EntryAI->getAlignment() == 0)
238 EntryAI->setAlignment(
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000239 DL->getPrefTypeAlignment(EntryAI->getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000240 // Replace this zero-sized alloca with the one at the start of the entry
241 // block after ensuring that the address will be aligned enough for both
242 // types.
Richard Osborneb68053e2012-09-18 09:31:44 +0000243 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
244 AI.getAlignment());
Duncan Sands8bc764a2012-06-26 13:39:21 +0000245 EntryAI->setAlignment(MaxAlign);
246 if (AI.getType() != EntryAI->getType())
247 return new BitCastInst(EntryAI, AI.getType());
248 return ReplaceInstUsesWith(AI, EntryAI);
249 }
250 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000251 }
252
Eli Friedmanb14873c2012-11-26 23:04:53 +0000253 if (AI.getAlignment()) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000254 // Check to see if this allocation is only modified by a memcpy/memmove from
255 // a constant global whose alignment is equal to or exceeds that of the
256 // allocation. If this is the case, we can change all users to use
257 // the constant global instead. This is commonly produced by the CFE by
258 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
259 // is only subsequently read.
260 SmallVector<Instruction *, 4> ToDelete;
261 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
Eli Friedmanb14873c2012-11-26 23:04:53 +0000262 unsigned SourceAlign = getOrEnforceKnownAlignment(Copy->getSource(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000263 AI.getAlignment(), DL);
Eli Friedmanb14873c2012-11-26 23:04:53 +0000264 if (AI.getAlignment() <= SourceAlign) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000265 DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
266 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
267 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
268 EraseInstFromFunction(*ToDelete[i]);
269 Constant *TheSrc = cast<Constant>(Copy->getSource());
Matt Arsenaultbbf18c62013-12-07 02:58:45 +0000270 Constant *Cast
271 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
272 Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000273 EraseInstFromFunction(*Copy);
274 ++NumGlobalCopies;
275 return NewI;
276 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000277 }
278 }
279
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000280 // At last, use the generic allocation site handler to aggressively remove
281 // unused allocas.
282 return visitAllocSite(AI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000283}
284
285
286/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
287static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000288 const DataLayout *DL) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000289 User *CI = cast<User>(LI.getOperand(0));
290 Value *CastOp = CI->getOperand(0);
291
Chris Lattner229907c2011-07-18 04:54:35 +0000292 PointerType *DestTy = cast<PointerType>(CI->getType());
293 Type *DestPTy = DestTy->getElementType();
294 if (PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000295
296 // If the address spaces don't match, don't eliminate the cast.
297 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
298 return 0;
299
Chris Lattner229907c2011-07-18 04:54:35 +0000300 Type *SrcPTy = SrcTy->getElementType();
Chris Lattnera65e2f72010-01-05 05:57:49 +0000301
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000302 if (DestPTy->isIntegerTy() || DestPTy->isPointerTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000303 DestPTy->isVectorTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000304 // If the source is an array, the code below will not succeed. Check to
305 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
306 // constants.
Chris Lattner229907c2011-07-18 04:54:35 +0000307 if (ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000308 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
309 if (ASrcTy->getNumElements() != 0) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000310 Type *IdxTy = DL
311 ? DL->getIntPtrType(SrcTy)
Matt Arsenault3dfe54e2013-09-03 21:05:48 +0000312 : Type::getInt64Ty(SrcTy->getContext());
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +0000313 Value *Idx = Constant::getNullValue(IdxTy);
314 Value *Idxs[2] = { Idx, Idx };
Jay Foad71f19ac2011-07-22 07:54:01 +0000315 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000316 SrcTy = cast<PointerType>(CastOp->getType());
317 SrcPTy = SrcTy->getElementType();
318 }
319
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000320 if (IC.getDataLayout() &&
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000321 (SrcPTy->isIntegerTy() || SrcPTy->isPointerTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000322 SrcPTy->isVectorTy()) &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000323 // Do not allow turning this into a load of an integer, which is then
324 // casted to a pointer, this pessimizes pointer analysis a lot.
Benjamin Kramer0b37cdf2013-09-19 20:59:04 +0000325 (SrcPTy->isPtrOrPtrVectorTy() ==
326 LI.getType()->isPtrOrPtrVectorTy()) &&
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000327 IC.getDataLayout()->getTypeSizeInBits(SrcPTy) ==
328 IC.getDataLayout()->getTypeSizeInBits(DestPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000329
330 // Okay, we are casting from one integer or pointer type to another of
331 // the same size. Instead of casting the pointer before the load, cast
332 // the result of the loaded value.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000333 LoadInst *NewLoad =
Chris Lattnera65e2f72010-01-05 05:57:49 +0000334 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000335 NewLoad->setAlignment(LI.getAlignment());
Eli Friedman8bc586e2011-08-15 22:09:40 +0000336 NewLoad->setAtomic(LI.getOrdering(), LI.getSynchScope());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000337 // Now cast the result of the load.
338 return new BitCastInst(NewLoad, LI.getType());
339 }
340 }
341 }
342 return 0;
343}
344
345Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
346 Value *Op = LI.getOperand(0);
347
348 // Attempt to improve the alignment.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000349 if (DL) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000350 unsigned KnownAlign =
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000351 getOrEnforceKnownAlignment(Op, DL->getPrefTypeAlignment(LI.getType()),DL);
Dan Gohman36196602010-08-03 18:20:32 +0000352 unsigned LoadAlign = LI.getAlignment();
353 unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000354 DL->getABITypeAlignment(LI.getType());
Dan Gohman36196602010-08-03 18:20:32 +0000355
356 if (KnownAlign > EffectiveLoadAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000357 LI.setAlignment(KnownAlign);
Dan Gohman36196602010-08-03 18:20:32 +0000358 else if (LoadAlign == 0)
359 LI.setAlignment(EffectiveLoadAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000360 }
361
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000362 // load (cast X) --> cast (load X) iff safe.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000363 if (isa<CastInst>(Op))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000364 if (Instruction *Res = InstCombineLoadCast(*this, LI, DL))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000365 return Res;
366
Eli Friedman8bc586e2011-08-15 22:09:40 +0000367 // None of the following transforms are legal for volatile/atomic loads.
368 // FIXME: Some of it is okay for atomic loads; needs refactoring.
369 if (!LI.isSimple()) return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000370
Chris Lattnera65e2f72010-01-05 05:57:49 +0000371 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +0000372 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +0000373 // separated by a few arithmetic operations.
374 BasicBlock::iterator BBI = &LI;
375 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
376 return ReplaceInstUsesWith(LI, AvailableVal);
377
378 // load(gep null, ...) -> unreachable
379 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
380 const Value *GEPI0 = GEPI->getOperand(0);
381 // TODO: Consider a target hook for valid address spaces for this xform.
382 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
383 // Insert a new store to null instruction before the load to indicate
384 // that this code is not reachable. We do this instead of inserting
385 // an unreachable instruction directly because we cannot modify the
386 // CFG.
387 new StoreInst(UndefValue::get(LI.getType()),
388 Constant::getNullValue(Op->getType()), &LI);
389 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
390 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000391 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000392
393 // load null/undef -> unreachable
394 // TODO: Consider a target hook for valid address spaces for this xform.
395 if (isa<UndefValue>(Op) ||
396 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
397 // Insert a new store to null instruction before the load to indicate that
398 // this code is not reachable. We do this instead of inserting an
399 // unreachable instruction directly because we cannot modify the CFG.
400 new StoreInst(UndefValue::get(LI.getType()),
401 Constant::getNullValue(Op->getType()), &LI);
402 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
403 }
404
405 // Instcombine load (constantexpr_cast global) -> cast (load global)
406 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
407 if (CE->isCast())
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000408 if (Instruction *Res = InstCombineLoadCast(*this, LI, DL))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000409 return Res;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000410
Chris Lattnera65e2f72010-01-05 05:57:49 +0000411 if (Op->hasOneUse()) {
412 // Change select and PHI nodes to select values instead of addresses: this
413 // helps alias analysis out a lot, allows many others simplifications, and
414 // exposes redundancy in the code.
415 //
416 // Note that we cannot do the transformation unless we know that the
417 // introduced loads cannot trap! Something like this is valid as long as
418 // the condition is always false: load (select bool %C, int* null, int* %G),
419 // but it would not be valid if we transformed it to load from null
420 // unconditionally.
421 //
422 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
423 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +0000424 unsigned Align = LI.getAlignment();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000425 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, DL) &&
426 isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, DL)) {
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000427 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
Bob Wilson56600a12010-01-30 04:42:39 +0000428 SI->getOperand(1)->getName()+".val");
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000429 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
Bob Wilson56600a12010-01-30 04:42:39 +0000430 SI->getOperand(2)->getName()+".val");
431 V1->setAlignment(Align);
432 V2->setAlignment(Align);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000433 return SelectInst::Create(SI->getCondition(), V1, V2);
434 }
435
436 // load (select (cond, null, P)) -> load P
437 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
438 if (C->isNullValue()) {
439 LI.setOperand(0, SI->getOperand(2));
440 return &LI;
441 }
442
443 // load (select (cond, P, null)) -> load P
444 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
445 if (C->isNullValue()) {
446 LI.setOperand(0, SI->getOperand(1));
447 return &LI;
448 }
449 }
450 }
451 return 0;
452}
453
454/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
455/// when possible. This makes it generally easy to do alias analysis and/or
456/// SROA/mem2reg of the memory object.
457static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
458 User *CI = cast<User>(SI.getOperand(1));
459 Value *CastOp = CI->getOperand(0);
460
Chris Lattner229907c2011-07-18 04:54:35 +0000461 Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
462 PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000463 if (SrcTy == 0) return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000464
Chris Lattner229907c2011-07-18 04:54:35 +0000465 Type *SrcPTy = SrcTy->getElementType();
Chris Lattnera65e2f72010-01-05 05:57:49 +0000466
Duncan Sands19d0b472010-02-16 11:11:14 +0000467 if (!DestPTy->isIntegerTy() && !DestPTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000468 return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000469
Chris Lattnera65e2f72010-01-05 05:57:49 +0000470 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
471 /// to its first element. This allows us to handle things like:
472 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
473 /// on 32-bit hosts.
474 SmallVector<Value*, 4> NewGEPIndices;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000475
Chris Lattnera65e2f72010-01-05 05:57:49 +0000476 // If the source is an array, the code below will not succeed. Check to
477 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
478 // constants.
Duncan Sands19d0b472010-02-16 11:11:14 +0000479 if (SrcPTy->isArrayTy() || SrcPTy->isStructTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000480 // Index through pointer.
481 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
482 NewGEPIndices.push_back(Zero);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000483
Chris Lattnera65e2f72010-01-05 05:57:49 +0000484 while (1) {
Chris Lattner229907c2011-07-18 04:54:35 +0000485 if (StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000486 if (!STy->getNumElements()) /* Struct can be empty {} */
487 break;
488 NewGEPIndices.push_back(Zero);
489 SrcPTy = STy->getElementType(0);
Chris Lattner229907c2011-07-18 04:54:35 +0000490 } else if (ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000491 NewGEPIndices.push_back(Zero);
492 SrcPTy = ATy->getElementType();
493 } else {
494 break;
495 }
496 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000497
Chris Lattnera65e2f72010-01-05 05:57:49 +0000498 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
499 }
500
Duncan Sands19d0b472010-02-16 11:11:14 +0000501 if (!SrcPTy->isIntegerTy() && !SrcPTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000502 return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000503
Chris Lattnera65e2f72010-01-05 05:57:49 +0000504 // If the pointers point into different address spaces or if they point to
505 // values with different sizes, we can't do the transformation.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000506 if (!IC.getDataLayout() ||
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000507 SrcTy->getAddressSpace() !=
Chandler Carruth7ec50852012-11-01 08:07:29 +0000508 cast<PointerType>(CI->getType())->getAddressSpace() ||
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000509 IC.getDataLayout()->getTypeSizeInBits(SrcPTy) !=
510 IC.getDataLayout()->getTypeSizeInBits(DestPTy))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000511 return 0;
512
513 // Okay, we are casting from one integer or pointer type to another of
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000514 // the same size. Instead of casting the pointer before
Chris Lattnera65e2f72010-01-05 05:57:49 +0000515 // the store, cast the value to be stored.
516 Value *NewCast;
517 Value *SIOp0 = SI.getOperand(0);
518 Instruction::CastOps opcode = Instruction::BitCast;
Chris Lattner229907c2011-07-18 04:54:35 +0000519 Type* CastSrcTy = SIOp0->getType();
520 Type* CastDstTy = SrcPTy;
Duncan Sands19d0b472010-02-16 11:11:14 +0000521 if (CastDstTy->isPointerTy()) {
Duncan Sands9dff9be2010-02-15 16:12:20 +0000522 if (CastSrcTy->isIntegerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000523 opcode = Instruction::IntToPtr;
Duncan Sands19d0b472010-02-16 11:11:14 +0000524 } else if (CastDstTy->isIntegerTy()) {
525 if (SIOp0->getType()->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000526 opcode = Instruction::PtrToInt;
527 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000528
Chris Lattnera65e2f72010-01-05 05:57:49 +0000529 // SIOp0 is a pointer to aggregate and this is a store to the first field,
530 // emit a GEP to index into its first field.
531 if (!NewGEPIndices.empty())
Jay Foad040dd822011-07-22 08:16:57 +0000532 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000533
Chris Lattnera65e2f72010-01-05 05:57:49 +0000534 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
535 SIOp0->getName()+".c");
Dan Gohman2e20dfb2010-10-25 16:16:27 +0000536 SI.setOperand(0, NewCast);
537 SI.setOperand(1, CastOp);
538 return &SI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000539}
540
541/// equivalentAddressValues - Test if A and B will obviously have the same
542/// value. This includes recognizing that %t0 and %t1 will have the same
543/// value in code like this:
544/// %t0 = getelementptr \@a, 0, 3
545/// store i32 0, i32* %t0
546/// %t1 = getelementptr \@a, 0, 3
547/// %t2 = load i32* %t1
548///
549static bool equivalentAddressValues(Value *A, Value *B) {
550 // Test if the values are trivially equivalent.
551 if (A == B) return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000552
Chris Lattnera65e2f72010-01-05 05:57:49 +0000553 // Test if the values come form identical arithmetic instructions.
554 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
555 // its only used to compare two uses within the same basic block, which
556 // means that they'll always either have the same value or one of them
557 // will have an undefined value.
558 if (isa<BinaryOperator>(A) ||
559 isa<CastInst>(A) ||
560 isa<PHINode>(A) ||
561 isa<GetElementPtrInst>(A))
562 if (Instruction *BI = dyn_cast<Instruction>(B))
563 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
564 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000565
Chris Lattnera65e2f72010-01-05 05:57:49 +0000566 // Otherwise they may not be equivalent.
567 return false;
568}
569
Chris Lattnera65e2f72010-01-05 05:57:49 +0000570Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
571 Value *Val = SI.getOperand(0);
572 Value *Ptr = SI.getOperand(1);
573
Chris Lattnera65e2f72010-01-05 05:57:49 +0000574 // Attempt to improve the alignment.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000575 if (DL) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000576 unsigned KnownAlign =
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000577 getOrEnforceKnownAlignment(Ptr, DL->getPrefTypeAlignment(Val->getType()),
578 DL);
Dan Gohman36196602010-08-03 18:20:32 +0000579 unsigned StoreAlign = SI.getAlignment();
580 unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000581 DL->getABITypeAlignment(Val->getType());
Dan Gohman36196602010-08-03 18:20:32 +0000582
Bill Wendling55b6b2b2012-03-16 18:20:54 +0000583 if (KnownAlign > EffectiveStoreAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000584 SI.setAlignment(KnownAlign);
Bill Wendling55b6b2b2012-03-16 18:20:54 +0000585 else if (StoreAlign == 0)
586 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000587 }
588
Eli Friedman8bc586e2011-08-15 22:09:40 +0000589 // Don't hack volatile/atomic stores.
590 // FIXME: Some bits are legal for atomic stores; needs refactoring.
591 if (!SI.isSimple()) return 0;
592
593 // If the RHS is an alloca with a single use, zapify the store, making the
594 // alloca dead.
595 if (Ptr->hasOneUse()) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000596 if (isa<AllocaInst>(Ptr))
Eli Friedman8bc586e2011-08-15 22:09:40 +0000597 return EraseInstFromFunction(SI);
598 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
599 if (isa<AllocaInst>(GEP->getOperand(0))) {
600 if (GEP->getOperand(0)->hasOneUse())
601 return EraseInstFromFunction(SI);
602 }
603 }
604 }
605
Chris Lattnera65e2f72010-01-05 05:57:49 +0000606 // Do really simple DSE, to catch cases where there are several consecutive
607 // stores to the same location, separated by a few arithmetic operations. This
608 // situation often occurs with bitfield accesses.
609 BasicBlock::iterator BBI = &SI;
610 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
611 --ScanInsts) {
612 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000613 // Don't count debug info directives, lest they affect codegen,
614 // and we skip pointer-to-pointer bitcasts, which are NOPs.
615 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000616 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000617 ScanInsts++;
618 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000619 }
620
Chris Lattnera65e2f72010-01-05 05:57:49 +0000621 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
622 // Prev store isn't volatile, and stores to the same location?
Eli Friedman8bc586e2011-08-15 22:09:40 +0000623 if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
624 SI.getOperand(1))) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000625 ++NumDeadStore;
626 ++BBI;
627 EraseInstFromFunction(*PrevSI);
628 continue;
629 }
630 break;
631 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000632
Chris Lattnera65e2f72010-01-05 05:57:49 +0000633 // If this is a load, we have to stop. However, if the loaded value is from
634 // the pointer we're loading and is producing the pointer we're storing,
635 // then *this* store is dead (X = load P; store X -> P).
636 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000637 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
Eli Friedman8bc586e2011-08-15 22:09:40 +0000638 LI->isSimple())
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000639 return EraseInstFromFunction(SI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000640
Chris Lattnera65e2f72010-01-05 05:57:49 +0000641 // Otherwise, this is a load from some other location. Stores before it
642 // may not be dead.
643 break;
644 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000645
Chris Lattnera65e2f72010-01-05 05:57:49 +0000646 // Don't skip over loads or things that can modify memory.
647 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
648 break;
649 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000650
651 // store X, null -> turns into 'unreachable' in SimplifyCFG
652 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
653 if (!isa<UndefValue>(Val)) {
654 SI.setOperand(0, UndefValue::get(Val->getType()));
655 if (Instruction *U = dyn_cast<Instruction>(Val))
656 Worklist.Add(U); // Dropped a use.
657 }
658 return 0; // Do not modify these!
659 }
660
661 // store undef, Ptr -> noop
662 if (isa<UndefValue>(Val))
663 return EraseInstFromFunction(SI);
664
665 // If the pointer destination is a cast, see if we can fold the cast into the
666 // source instead.
667 if (isa<CastInst>(Ptr))
668 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
669 return Res;
670 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
671 if (CE->isCast())
672 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
673 return Res;
674
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000675
Chris Lattnera65e2f72010-01-05 05:57:49 +0000676 // If this store is the last instruction in the basic block (possibly
Victor Hernandez5f5abd52010-01-21 23:07:15 +0000677 // excepting debug info instructions), and if the block ends with an
678 // unconditional branch, try to move it to the successor block.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000679 BBI = &SI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000680 do {
681 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000682 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000683 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000684 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
685 if (BI->isUnconditional())
686 if (SimplifyStoreAtEndOfBlock(SI))
687 return 0; // xform done!
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000688
Chris Lattnera65e2f72010-01-05 05:57:49 +0000689 return 0;
690}
691
692/// SimplifyStoreAtEndOfBlock - Turn things like:
693/// if () { *P = v1; } else { *P = v2 }
694/// into a phi node with a store in the successor.
695///
696/// Simplify things like:
697/// *P = v1; if () { *P = v2; }
698/// into a phi node with a store in the successor.
699///
700bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
701 BasicBlock *StoreBB = SI.getParent();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000702
Chris Lattnera65e2f72010-01-05 05:57:49 +0000703 // Check to see if the successor block has exactly two incoming edges. If
704 // so, see if the other predecessor contains a store to the same location.
705 // if so, insert a PHI node (if needed) and move the stores down.
706 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000707
Chris Lattnera65e2f72010-01-05 05:57:49 +0000708 // Determine whether Dest has exactly two predecessors and, if so, compute
709 // the other predecessor.
710 pred_iterator PI = pred_begin(DestBB);
Gabor Greif1b787df2010-07-12 15:48:26 +0000711 BasicBlock *P = *PI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000712 BasicBlock *OtherBB = 0;
Gabor Greif1b787df2010-07-12 15:48:26 +0000713
714 if (P != StoreBB)
715 OtherBB = P;
716
717 if (++PI == pred_end(DestBB))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000718 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000719
Gabor Greif1b787df2010-07-12 15:48:26 +0000720 P = *PI;
721 if (P != StoreBB) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000722 if (OtherBB)
723 return false;
Gabor Greif1b787df2010-07-12 15:48:26 +0000724 OtherBB = P;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000725 }
726 if (++PI != pred_end(DestBB))
727 return false;
728
729 // Bail out if all the relevant blocks aren't distinct (this can happen,
730 // for example, if SI is in an infinite loop)
731 if (StoreBB == DestBB || OtherBB == DestBB)
732 return false;
733
734 // Verify that the other block ends in a branch and is not otherwise empty.
735 BasicBlock::iterator BBI = OtherBB->getTerminator();
736 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
737 if (!OtherBr || BBI == OtherBB->begin())
738 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000739
Chris Lattnera65e2f72010-01-05 05:57:49 +0000740 // If the other block ends in an unconditional branch, check for the 'if then
741 // else' case. there is an instruction before the branch.
742 StoreInst *OtherStore = 0;
743 if (OtherBr->isUnconditional()) {
744 --BBI;
745 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000746 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000747 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000748 if (BBI==OtherBB->begin())
749 return false;
750 --BBI;
751 }
Eli Friedman8bc586e2011-08-15 22:09:40 +0000752 // If this isn't a store, isn't a store to the same location, or is not the
753 // right kind of store, bail out.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000754 OtherStore = dyn_cast<StoreInst>(BBI);
755 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +0000756 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000757 return false;
758 } else {
759 // Otherwise, the other block ended with a conditional branch. If one of the
760 // destinations is StoreBB, then we have the if/then case.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000761 if (OtherBr->getSuccessor(0) != StoreBB &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000762 OtherBr->getSuccessor(1) != StoreBB)
763 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000764
Chris Lattnera65e2f72010-01-05 05:57:49 +0000765 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
766 // if/then triangle. See if there is a store to the same ptr as SI that
767 // lives in OtherBB.
768 for (;; --BBI) {
769 // Check to see if we find the matching store.
770 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
771 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +0000772 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000773 return false;
774 break;
775 }
776 // If we find something that may be using or overwriting the stored
777 // value, or if we run out of instructions, we can't do the xform.
778 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
779 BBI == OtherBB->begin())
780 return false;
781 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000782
Chris Lattnera65e2f72010-01-05 05:57:49 +0000783 // In order to eliminate the store in OtherBr, we have to
784 // make sure nothing reads or overwrites the stored value in
785 // StoreBB.
786 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
787 // FIXME: This should really be AA driven.
788 if (I->mayReadFromMemory() || I->mayWriteToMemory())
789 return false;
790 }
791 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000792
Chris Lattnera65e2f72010-01-05 05:57:49 +0000793 // Insert a PHI node now if we need it.
794 Value *MergedVal = OtherStore->getOperand(0);
795 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +0000796 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +0000797 PN->addIncoming(SI.getOperand(0), SI.getParent());
798 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
799 MergedVal = InsertNewInstBefore(PN, DestBB->front());
800 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000801
Chris Lattnera65e2f72010-01-05 05:57:49 +0000802 // Advance to a place where it is safe to insert the new store and
803 // insert it.
Bill Wendling8ddfc092011-08-16 20:45:24 +0000804 BBI = DestBB->getFirstInsertionPt();
Eli Friedman35211c62011-05-27 00:19:40 +0000805 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +0000806 SI.isVolatile(),
807 SI.getAlignment(),
808 SI.getOrdering(),
809 SI.getSynchScope());
Eli Friedman35211c62011-05-27 00:19:40 +0000810 InsertNewInstBefore(NewSI, *BBI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000811 NewSI->setDebugLoc(OtherStore->getDebugLoc());
Eli Friedman35211c62011-05-27 00:19:40 +0000812
Chris Lattnereeefe1b2012-12-31 08:10:58 +0000813 // If the two stores had the same TBAA tag, preserve it.
Chris Lattner473988c2013-01-05 16:44:07 +0000814 if (MDNode *TBAATag = SI.getMetadata(LLVMContext::MD_tbaa))
815 if ((TBAATag = MDNode::getMostGenericTBAA(TBAATag,
816 OtherStore->getMetadata(LLVMContext::MD_tbaa))))
817 NewSI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
Chris Lattnereeefe1b2012-12-31 08:10:58 +0000818
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000819
Chris Lattnera65e2f72010-01-05 05:57:49 +0000820 // Nuke the old stores.
821 EraseInstFromFunction(SI);
822 EraseInstFromFunction(*OtherStore);
823 return true;
824}