blob: 6fea7f2ac22fe76ad125be9765e09a146c14964d [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 Carruth964daaa2014-04-22 02:55:47 +000023#define DEBUG_TYPE "instcombine"
24
Chandler Carruthc908ca12012-08-21 08:39:44 +000025STATISTIC(NumDeadStore, "Number of dead stores eliminated");
26STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
27
28/// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
29/// some part of a constant global variable. This intentionally only accepts
30/// constant expressions because we can't rewrite arbitrary instructions.
31static bool pointsToConstantGlobal(Value *V) {
32 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
33 return GV->isConstant();
34 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
35 if (CE->getOpcode() == Instruction::BitCast ||
36 CE->getOpcode() == Instruction::GetElementPtr)
37 return pointsToConstantGlobal(CE->getOperand(0));
38 return false;
39}
40
41/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
42/// pointer to an alloca. Ignore any reads of the pointer, return false if we
43/// see any stores or other unknown uses. If we see pointer arithmetic, keep
44/// track of whether it moves the pointer (with IsOffset) but otherwise traverse
45/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
46/// the alloca, and if the source pointer is a pointer to a constant global, we
47/// can optimize this.
48static bool
49isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
50 SmallVectorImpl<Instruction *> &ToDelete,
51 bool IsOffset = false) {
52 // We track lifetime intrinsics as we encounter them. If we decide to go
53 // ahead and replace the value with the global, this lets the caller quickly
54 // eliminate the markers.
55
Chandler Carruthcdf47882014-03-09 03:16:01 +000056 for (Use &U : V->uses()) {
57 Instruction *I = cast<Instruction>(U.getUser());
Chandler Carruthc908ca12012-08-21 08:39:44 +000058
Chandler Carruthcdf47882014-03-09 03:16:01 +000059 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000060 // Ignore non-volatile loads, they are always ok.
61 if (!LI->isSimple()) return false;
62 continue;
63 }
64
Chandler Carruthcdf47882014-03-09 03:16:01 +000065 if (BitCastInst *BCI = dyn_cast<BitCastInst>(I)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000066 // If uses of the bitcast are ok, we are ok.
67 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, ToDelete, IsOffset))
68 return false;
69 continue;
70 }
Chandler Carruthcdf47882014-03-09 03:16:01 +000071 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000072 // If the GEP has all zero indices, it doesn't offset the pointer. If it
73 // doesn't, it does.
Jim Grosbachbdbd7342013-04-05 21:20:12 +000074 if (!isOnlyCopiedFromConstantGlobal(
75 GEP, TheCopy, ToDelete, IsOffset || !GEP->hasAllZeroIndices()))
Chandler Carruthc908ca12012-08-21 08:39:44 +000076 return false;
77 continue;
78 }
79
Chandler Carruthcdf47882014-03-09 03:16:01 +000080 if (CallSite CS = I) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000081 // If this is the function being called then we treat it like a load and
82 // ignore it.
Chandler Carruthcdf47882014-03-09 03:16:01 +000083 if (CS.isCallee(&U))
Chandler Carruthc908ca12012-08-21 08:39:44 +000084 continue;
85
Reid Kleckner26af2ca2014-01-28 02:38:36 +000086 // Inalloca arguments are clobbered by the call.
Chandler Carruthcdf47882014-03-09 03:16:01 +000087 unsigned ArgNo = CS.getArgumentNo(&U);
Reid Kleckner26af2ca2014-01-28 02:38:36 +000088 if (CS.isInAllocaArgument(ArgNo))
89 return false;
90
Chandler Carruthc908ca12012-08-21 08:39:44 +000091 // If this is a readonly/readnone call site, then we know it is just a
92 // load (but one that potentially returns the value itself), so we can
93 // ignore it if we know that the value isn't captured.
Chandler Carruthc908ca12012-08-21 08:39:44 +000094 if (CS.onlyReadsMemory() &&
95 (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
96 continue;
97
98 // If this is being passed as a byval argument, the caller is making a
99 // copy, so it is only a read of the alloca.
100 if (CS.isByValArgument(ArgNo))
101 continue;
102 }
103
104 // Lifetime intrinsics can be handled by the caller.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000105 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +0000106 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
107 II->getIntrinsicID() == Intrinsic::lifetime_end) {
108 assert(II->use_empty() && "Lifetime markers have no result to use!");
109 ToDelete.push_back(II);
110 continue;
111 }
112 }
113
114 // If this is isn't our memcpy/memmove, reject it as something we can't
115 // handle.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000116 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
Chandler Carruthc908ca12012-08-21 08:39:44 +0000117 if (MI == 0)
118 return false;
119
120 // If the transfer is using the alloca as a source of the transfer, then
121 // ignore it since it is a load (unless the transfer is volatile).
Chandler Carruthcdf47882014-03-09 03:16:01 +0000122 if (U.getOperandNo() == 1) {
Chandler Carruthc908ca12012-08-21 08:39:44 +0000123 if (MI->isVolatile()) return false;
124 continue;
125 }
126
127 // If we already have seen a copy, reject the second one.
128 if (TheCopy) return false;
129
130 // If the pointer has been offset from the start of the alloca, we can't
131 // safely handle this.
132 if (IsOffset) return false;
133
134 // If the memintrinsic isn't using the alloca as the dest, reject it.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000135 if (U.getOperandNo() != 0) return false;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000136
137 // If the source of the memcpy/move is not a constant global, reject it.
138 if (!pointsToConstantGlobal(MI->getSource()))
139 return false;
140
141 // Otherwise, the transform is safe. Remember the copy instruction.
142 TheCopy = MI;
143 }
144 return true;
145}
146
147/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
148/// modified by a copy from a constant global. If we can prove this, we can
149/// replace any uses of the alloca with uses of the global directly.
150static MemTransferInst *
151isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
152 SmallVectorImpl<Instruction *> &ToDelete) {
153 MemTransferInst *TheCopy = 0;
154 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
155 return TheCopy;
156 return 0;
157}
158
Chris Lattnera65e2f72010-01-05 05:57:49 +0000159Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Dan Gohmandf5d7dc2010-05-28 15:09:00 +0000160 // Ensure that the alloca array size argument has type intptr_t, so that
161 // any casting is exposed early.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000162 if (DL) {
163 Type *IntPtrTy = DL->getIntPtrType(AI.getType());
Dan Gohmandf5d7dc2010-05-28 15:09:00 +0000164 if (AI.getArraySize()->getType() != IntPtrTy) {
165 Value *V = Builder->CreateIntCast(AI.getArraySize(),
166 IntPtrTy, false);
167 AI.setOperand(0, V);
168 return &AI;
169 }
170 }
171
Chris Lattnera65e2f72010-01-05 05:57:49 +0000172 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
173 if (AI.isArrayAllocation()) { // Check C != 1
174 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000175 Type *NewTy =
Chris Lattnera65e2f72010-01-05 05:57:49 +0000176 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000177 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
178 New->setAlignment(AI.getAlignment());
179
180 // Scan to the end of the allocation instructions, to skip over a block of
181 // allocas if possible...also skip interleaved debug info
182 //
183 BasicBlock::iterator It = New;
184 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
185
186 // Now that I is pointing to the first non-allocation-inst in the block,
187 // insert our getelementptr instruction...
188 //
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000189 Type *IdxTy = DL
190 ? DL->getIntPtrType(AI.getType())
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +0000191 : Type::getInt64Ty(AI.getContext());
192 Value *NullIdx = Constant::getNullValue(IdxTy);
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000193 Value *Idx[2] = { NullIdx, NullIdx };
Eli Friedman41e509a2011-05-18 23:58:37 +0000194 Instruction *GEP =
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000195 GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
Eli Friedman41e509a2011-05-18 23:58:37 +0000196 InsertNewInstBefore(GEP, *It);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000197
198 // Now make everything use the getelementptr instead of the original
199 // allocation.
Eli Friedman41e509a2011-05-18 23:58:37 +0000200 return ReplaceInstUsesWith(AI, GEP);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000201 } else if (isa<UndefValue>(AI.getArraySize())) {
202 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
203 }
204 }
205
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000206 if (DL && AI.getAllocatedType()->isSized()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000207 // If the alignment is 0 (unspecified), assign it the preferred alignment.
208 if (AI.getAlignment() == 0)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000209 AI.setAlignment(DL->getPrefTypeAlignment(AI.getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000210
211 // Move all alloca's of zero byte objects to the entry block and merge them
212 // together. Note that we only do this for alloca's, because malloc should
213 // allocate and return a unique pointer, even for a zero byte allocation.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000214 if (DL->getTypeAllocSize(AI.getAllocatedType()) == 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000215 // For a zero sized alloca there is no point in doing an array allocation.
216 // This is helpful if the array size is a complicated expression not used
217 // elsewhere.
218 if (AI.isArrayAllocation()) {
219 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
220 return &AI;
221 }
222
223 // Get the first instruction in the entry block.
224 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
225 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
226 if (FirstInst != &AI) {
227 // If the entry block doesn't start with a zero-size alloca then move
228 // this one to the start of the entry block. There is no problem with
229 // dominance as the array size was forced to a constant earlier already.
230 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
231 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000232 DL->getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000233 AI.moveBefore(FirstInst);
234 return &AI;
235 }
236
Richard Osborneb68053e2012-09-18 09:31:44 +0000237 // If the alignment of the entry block alloca is 0 (unspecified),
238 // assign it the preferred alignment.
239 if (EntryAI->getAlignment() == 0)
240 EntryAI->setAlignment(
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000241 DL->getPrefTypeAlignment(EntryAI->getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000242 // Replace this zero-sized alloca with the one at the start of the entry
243 // block after ensuring that the address will be aligned enough for both
244 // types.
Richard Osborneb68053e2012-09-18 09:31:44 +0000245 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
246 AI.getAlignment());
Duncan Sands8bc764a2012-06-26 13:39:21 +0000247 EntryAI->setAlignment(MaxAlign);
248 if (AI.getType() != EntryAI->getType())
249 return new BitCastInst(EntryAI, AI.getType());
250 return ReplaceInstUsesWith(AI, EntryAI);
251 }
252 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000253 }
254
Eli Friedmanb14873c2012-11-26 23:04:53 +0000255 if (AI.getAlignment()) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000256 // Check to see if this allocation is only modified by a memcpy/memmove from
257 // a constant global whose alignment is equal to or exceeds that of the
258 // allocation. If this is the case, we can change all users to use
259 // the constant global instead. This is commonly produced by the CFE by
260 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
261 // is only subsequently read.
262 SmallVector<Instruction *, 4> ToDelete;
263 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
Eli Friedmanb14873c2012-11-26 23:04:53 +0000264 unsigned SourceAlign = getOrEnforceKnownAlignment(Copy->getSource(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000265 AI.getAlignment(), DL);
Eli Friedmanb14873c2012-11-26 23:04:53 +0000266 if (AI.getAlignment() <= SourceAlign) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000267 DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
268 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
269 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
270 EraseInstFromFunction(*ToDelete[i]);
271 Constant *TheSrc = cast<Constant>(Copy->getSource());
Matt Arsenaultbbf18c62013-12-07 02:58:45 +0000272 Constant *Cast
273 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
274 Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000275 EraseInstFromFunction(*Copy);
276 ++NumGlobalCopies;
277 return NewI;
278 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000279 }
280 }
281
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000282 // At last, use the generic allocation site handler to aggressively remove
283 // unused allocas.
284 return visitAllocSite(AI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000285}
286
287
288/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
289static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000290 const DataLayout *DL) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000291 User *CI = cast<User>(LI.getOperand(0));
292 Value *CastOp = CI->getOperand(0);
293
Chris Lattner229907c2011-07-18 04:54:35 +0000294 PointerType *DestTy = cast<PointerType>(CI->getType());
295 Type *DestPTy = DestTy->getElementType();
296 if (PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000297
298 // If the address spaces don't match, don't eliminate the cast.
299 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
300 return 0;
301
Chris Lattner229907c2011-07-18 04:54:35 +0000302 Type *SrcPTy = SrcTy->getElementType();
Chris Lattnera65e2f72010-01-05 05:57:49 +0000303
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000304 if (DestPTy->isIntegerTy() || DestPTy->isPointerTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000305 DestPTy->isVectorTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000306 // If the source is an array, the code below will not succeed. Check to
307 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
308 // constants.
Chris Lattner229907c2011-07-18 04:54:35 +0000309 if (ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000310 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
311 if (ASrcTy->getNumElements() != 0) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000312 Type *IdxTy = DL
313 ? DL->getIntPtrType(SrcTy)
Matt Arsenault3dfe54e2013-09-03 21:05:48 +0000314 : Type::getInt64Ty(SrcTy->getContext());
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +0000315 Value *Idx = Constant::getNullValue(IdxTy);
316 Value *Idxs[2] = { Idx, Idx };
Jay Foad71f19ac2011-07-22 07:54:01 +0000317 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000318 SrcTy = cast<PointerType>(CastOp->getType());
319 SrcPTy = SrcTy->getElementType();
320 }
321
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000322 if (IC.getDataLayout() &&
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000323 (SrcPTy->isIntegerTy() || SrcPTy->isPointerTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000324 SrcPTy->isVectorTy()) &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000325 // Do not allow turning this into a load of an integer, which is then
326 // casted to a pointer, this pessimizes pointer analysis a lot.
Benjamin Kramer0b37cdf2013-09-19 20:59:04 +0000327 (SrcPTy->isPtrOrPtrVectorTy() ==
328 LI.getType()->isPtrOrPtrVectorTy()) &&
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000329 IC.getDataLayout()->getTypeSizeInBits(SrcPTy) ==
330 IC.getDataLayout()->getTypeSizeInBits(DestPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000331
332 // Okay, we are casting from one integer or pointer type to another of
333 // the same size. Instead of casting the pointer before the load, cast
334 // the result of the loaded value.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000335 LoadInst *NewLoad =
Chris Lattnera65e2f72010-01-05 05:57:49 +0000336 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000337 NewLoad->setAlignment(LI.getAlignment());
Eli Friedman8bc586e2011-08-15 22:09:40 +0000338 NewLoad->setAtomic(LI.getOrdering(), LI.getSynchScope());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000339 // Now cast the result of the load.
Owen Anderson9b8f9c32014-03-13 22:51:43 +0000340 PointerType *OldTy = dyn_cast<PointerType>(NewLoad->getType());
341 PointerType *NewTy = dyn_cast<PointerType>(LI.getType());
342 if (OldTy && NewTy &&
343 OldTy->getAddressSpace() != NewTy->getAddressSpace()) {
344 return new AddrSpaceCastInst(NewLoad, LI.getType());
345 }
346
Chris Lattnera65e2f72010-01-05 05:57:49 +0000347 return new BitCastInst(NewLoad, LI.getType());
348 }
349 }
350 }
351 return 0;
352}
353
354Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
355 Value *Op = LI.getOperand(0);
356
357 // Attempt to improve the alignment.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000358 if (DL) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000359 unsigned KnownAlign =
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000360 getOrEnforceKnownAlignment(Op, DL->getPrefTypeAlignment(LI.getType()),DL);
Dan Gohman36196602010-08-03 18:20:32 +0000361 unsigned LoadAlign = LI.getAlignment();
362 unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000363 DL->getABITypeAlignment(LI.getType());
Dan Gohman36196602010-08-03 18:20:32 +0000364
365 if (KnownAlign > EffectiveLoadAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000366 LI.setAlignment(KnownAlign);
Dan Gohman36196602010-08-03 18:20:32 +0000367 else if (LoadAlign == 0)
368 LI.setAlignment(EffectiveLoadAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000369 }
370
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000371 // load (cast X) --> cast (load X) iff safe.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000372 if (isa<CastInst>(Op))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000373 if (Instruction *Res = InstCombineLoadCast(*this, LI, DL))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000374 return Res;
375
Eli Friedman8bc586e2011-08-15 22:09:40 +0000376 // None of the following transforms are legal for volatile/atomic loads.
377 // FIXME: Some of it is okay for atomic loads; needs refactoring.
378 if (!LI.isSimple()) return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000379
Chris Lattnera65e2f72010-01-05 05:57:49 +0000380 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +0000381 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +0000382 // separated by a few arithmetic operations.
383 BasicBlock::iterator BBI = &LI;
384 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
385 return ReplaceInstUsesWith(LI, AvailableVal);
386
387 // load(gep null, ...) -> unreachable
388 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
389 const Value *GEPI0 = GEPI->getOperand(0);
390 // TODO: Consider a target hook for valid address spaces for this xform.
391 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
392 // Insert a new store to null instruction before the load to indicate
393 // that this code is not reachable. We do this instead of inserting
394 // an unreachable instruction directly because we cannot modify the
395 // CFG.
396 new StoreInst(UndefValue::get(LI.getType()),
397 Constant::getNullValue(Op->getType()), &LI);
398 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
399 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000400 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000401
402 // load null/undef -> unreachable
403 // TODO: Consider a target hook for valid address spaces for this xform.
404 if (isa<UndefValue>(Op) ||
405 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
406 // Insert a new store to null instruction before the load to indicate that
407 // this code is not reachable. We do this instead of inserting an
408 // unreachable instruction directly because we cannot modify the CFG.
409 new StoreInst(UndefValue::get(LI.getType()),
410 Constant::getNullValue(Op->getType()), &LI);
411 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
412 }
413
414 // Instcombine load (constantexpr_cast global) -> cast (load global)
415 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
416 if (CE->isCast())
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000417 if (Instruction *Res = InstCombineLoadCast(*this, LI, DL))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000418 return Res;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000419
Chris Lattnera65e2f72010-01-05 05:57:49 +0000420 if (Op->hasOneUse()) {
421 // Change select and PHI nodes to select values instead of addresses: this
422 // helps alias analysis out a lot, allows many others simplifications, and
423 // exposes redundancy in the code.
424 //
425 // Note that we cannot do the transformation unless we know that the
426 // introduced loads cannot trap! Something like this is valid as long as
427 // the condition is always false: load (select bool %C, int* null, int* %G),
428 // but it would not be valid if we transformed it to load from null
429 // unconditionally.
430 //
431 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
432 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +0000433 unsigned Align = LI.getAlignment();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000434 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, DL) &&
435 isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, DL)) {
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000436 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
Bob Wilson56600a12010-01-30 04:42:39 +0000437 SI->getOperand(1)->getName()+".val");
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000438 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
Bob Wilson56600a12010-01-30 04:42:39 +0000439 SI->getOperand(2)->getName()+".val");
440 V1->setAlignment(Align);
441 V2->setAlignment(Align);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000442 return SelectInst::Create(SI->getCondition(), V1, V2);
443 }
444
445 // load (select (cond, null, P)) -> load P
446 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
447 if (C->isNullValue()) {
448 LI.setOperand(0, SI->getOperand(2));
449 return &LI;
450 }
451
452 // load (select (cond, P, null)) -> load P
453 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
454 if (C->isNullValue()) {
455 LI.setOperand(0, SI->getOperand(1));
456 return &LI;
457 }
458 }
459 }
460 return 0;
461}
462
463/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
464/// when possible. This makes it generally easy to do alias analysis and/or
465/// SROA/mem2reg of the memory object.
466static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
467 User *CI = cast<User>(SI.getOperand(1));
468 Value *CastOp = CI->getOperand(0);
469
Chris Lattner229907c2011-07-18 04:54:35 +0000470 Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
471 PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000472 if (SrcTy == 0) return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000473
Chris Lattner229907c2011-07-18 04:54:35 +0000474 Type *SrcPTy = SrcTy->getElementType();
Chris Lattnera65e2f72010-01-05 05:57:49 +0000475
Duncan Sands19d0b472010-02-16 11:11:14 +0000476 if (!DestPTy->isIntegerTy() && !DestPTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000477 return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000478
Chris Lattnera65e2f72010-01-05 05:57:49 +0000479 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
480 /// to its first element. This allows us to handle things like:
481 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
482 /// on 32-bit hosts.
483 SmallVector<Value*, 4> NewGEPIndices;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000484
Chris Lattnera65e2f72010-01-05 05:57:49 +0000485 // If the source is an array, the code below will not succeed. Check to
486 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
487 // constants.
Duncan Sands19d0b472010-02-16 11:11:14 +0000488 if (SrcPTy->isArrayTy() || SrcPTy->isStructTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000489 // Index through pointer.
490 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
491 NewGEPIndices.push_back(Zero);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000492
Chris Lattnera65e2f72010-01-05 05:57:49 +0000493 while (1) {
Chris Lattner229907c2011-07-18 04:54:35 +0000494 if (StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000495 if (!STy->getNumElements()) /* Struct can be empty {} */
496 break;
497 NewGEPIndices.push_back(Zero);
498 SrcPTy = STy->getElementType(0);
Chris Lattner229907c2011-07-18 04:54:35 +0000499 } else if (ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000500 NewGEPIndices.push_back(Zero);
501 SrcPTy = ATy->getElementType();
502 } else {
503 break;
504 }
505 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000506
Chris Lattnera65e2f72010-01-05 05:57:49 +0000507 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
508 }
509
Duncan Sands19d0b472010-02-16 11:11:14 +0000510 if (!SrcPTy->isIntegerTy() && !SrcPTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000511 return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000512
Richard Osborne0af4aa92014-03-25 17:21:41 +0000513 // If the pointers point into different address spaces don't do the
514 // transformation.
515 if (SrcTy->getAddressSpace() !=
516 cast<PointerType>(CI->getType())->getAddressSpace())
517 return 0;
518
519 // If the pointers point to values of different sizes don't do the
520 // transformation.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000521 if (!IC.getDataLayout() ||
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000522 IC.getDataLayout()->getTypeSizeInBits(SrcPTy) !=
523 IC.getDataLayout()->getTypeSizeInBits(DestPTy))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000524 return 0;
525
Richard Osborne0af4aa92014-03-25 17:21:41 +0000526 // If the pointers point to pointers to different address spaces don't do the
527 // transformation. It is not safe to introduce an addrspacecast instruction in
528 // this case since, depending on the target, addrspacecast may not be a no-op
529 // cast.
530 if (SrcPTy->isPointerTy() && DestPTy->isPointerTy() &&
531 SrcPTy->getPointerAddressSpace() != DestPTy->getPointerAddressSpace())
532 return 0;
533
Chris Lattnera65e2f72010-01-05 05:57:49 +0000534 // Okay, we are casting from one integer or pointer type to another of
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000535 // the same size. Instead of casting the pointer before
Chris Lattnera65e2f72010-01-05 05:57:49 +0000536 // the store, cast the value to be stored.
537 Value *NewCast;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000538 Instruction::CastOps opcode = Instruction::BitCast;
Richard Osborne9805ec42014-03-25 17:21:35 +0000539 Type* CastSrcTy = DestPTy;
Chris Lattner229907c2011-07-18 04:54:35 +0000540 Type* CastDstTy = SrcPTy;
Duncan Sands19d0b472010-02-16 11:11:14 +0000541 if (CastDstTy->isPointerTy()) {
Duncan Sands9dff9be2010-02-15 16:12:20 +0000542 if (CastSrcTy->isIntegerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000543 opcode = Instruction::IntToPtr;
Duncan Sands19d0b472010-02-16 11:11:14 +0000544 } else if (CastDstTy->isIntegerTy()) {
Richard Osborne9805ec42014-03-25 17:21:35 +0000545 if (CastSrcTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000546 opcode = Instruction::PtrToInt;
547 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000548
Chris Lattnera65e2f72010-01-05 05:57:49 +0000549 // SIOp0 is a pointer to aggregate and this is a store to the first field,
550 // emit a GEP to index into its first field.
551 if (!NewGEPIndices.empty())
Jay Foad040dd822011-07-22 08:16:57 +0000552 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000553
Richard Osborne9805ec42014-03-25 17:21:35 +0000554 Value *SIOp0 = SI.getOperand(0);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000555 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
556 SIOp0->getName()+".c");
Dan Gohman2e20dfb2010-10-25 16:16:27 +0000557 SI.setOperand(0, NewCast);
558 SI.setOperand(1, CastOp);
559 return &SI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000560}
561
562/// equivalentAddressValues - Test if A and B will obviously have the same
563/// value. This includes recognizing that %t0 and %t1 will have the same
564/// value in code like this:
565/// %t0 = getelementptr \@a, 0, 3
566/// store i32 0, i32* %t0
567/// %t1 = getelementptr \@a, 0, 3
568/// %t2 = load i32* %t1
569///
570static bool equivalentAddressValues(Value *A, Value *B) {
571 // Test if the values are trivially equivalent.
572 if (A == B) return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000573
Chris Lattnera65e2f72010-01-05 05:57:49 +0000574 // Test if the values come form identical arithmetic instructions.
575 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
576 // its only used to compare two uses within the same basic block, which
577 // means that they'll always either have the same value or one of them
578 // will have an undefined value.
579 if (isa<BinaryOperator>(A) ||
580 isa<CastInst>(A) ||
581 isa<PHINode>(A) ||
582 isa<GetElementPtrInst>(A))
583 if (Instruction *BI = dyn_cast<Instruction>(B))
584 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
585 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000586
Chris Lattnera65e2f72010-01-05 05:57:49 +0000587 // Otherwise they may not be equivalent.
588 return false;
589}
590
Chris Lattnera65e2f72010-01-05 05:57:49 +0000591Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
592 Value *Val = SI.getOperand(0);
593 Value *Ptr = SI.getOperand(1);
594
Chris Lattnera65e2f72010-01-05 05:57:49 +0000595 // Attempt to improve the alignment.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000596 if (DL) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000597 unsigned KnownAlign =
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000598 getOrEnforceKnownAlignment(Ptr, DL->getPrefTypeAlignment(Val->getType()),
599 DL);
Dan Gohman36196602010-08-03 18:20:32 +0000600 unsigned StoreAlign = SI.getAlignment();
601 unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000602 DL->getABITypeAlignment(Val->getType());
Dan Gohman36196602010-08-03 18:20:32 +0000603
Bill Wendling55b6b2b2012-03-16 18:20:54 +0000604 if (KnownAlign > EffectiveStoreAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000605 SI.setAlignment(KnownAlign);
Bill Wendling55b6b2b2012-03-16 18:20:54 +0000606 else if (StoreAlign == 0)
607 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000608 }
609
Eli Friedman8bc586e2011-08-15 22:09:40 +0000610 // Don't hack volatile/atomic stores.
611 // FIXME: Some bits are legal for atomic stores; needs refactoring.
612 if (!SI.isSimple()) return 0;
613
614 // If the RHS is an alloca with a single use, zapify the store, making the
615 // alloca dead.
616 if (Ptr->hasOneUse()) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000617 if (isa<AllocaInst>(Ptr))
Eli Friedman8bc586e2011-08-15 22:09:40 +0000618 return EraseInstFromFunction(SI);
619 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
620 if (isa<AllocaInst>(GEP->getOperand(0))) {
621 if (GEP->getOperand(0)->hasOneUse())
622 return EraseInstFromFunction(SI);
623 }
624 }
625 }
626
Chris Lattnera65e2f72010-01-05 05:57:49 +0000627 // Do really simple DSE, to catch cases where there are several consecutive
628 // stores to the same location, separated by a few arithmetic operations. This
629 // situation often occurs with bitfield accesses.
630 BasicBlock::iterator BBI = &SI;
631 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
632 --ScanInsts) {
633 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000634 // Don't count debug info directives, lest they affect codegen,
635 // and we skip pointer-to-pointer bitcasts, which are NOPs.
636 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000637 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000638 ScanInsts++;
639 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000640 }
641
Chris Lattnera65e2f72010-01-05 05:57:49 +0000642 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
643 // Prev store isn't volatile, and stores to the same location?
Eli Friedman8bc586e2011-08-15 22:09:40 +0000644 if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
645 SI.getOperand(1))) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000646 ++NumDeadStore;
647 ++BBI;
648 EraseInstFromFunction(*PrevSI);
649 continue;
650 }
651 break;
652 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000653
Chris Lattnera65e2f72010-01-05 05:57:49 +0000654 // If this is a load, we have to stop. However, if the loaded value is from
655 // the pointer we're loading and is producing the pointer we're storing,
656 // then *this* store is dead (X = load P; store X -> P).
657 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000658 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
Eli Friedman8bc586e2011-08-15 22:09:40 +0000659 LI->isSimple())
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000660 return EraseInstFromFunction(SI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000661
Chris Lattnera65e2f72010-01-05 05:57:49 +0000662 // Otherwise, this is a load from some other location. Stores before it
663 // may not be dead.
664 break;
665 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000666
Chris Lattnera65e2f72010-01-05 05:57:49 +0000667 // Don't skip over loads or things that can modify memory.
668 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
669 break;
670 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000671
672 // store X, null -> turns into 'unreachable' in SimplifyCFG
673 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
674 if (!isa<UndefValue>(Val)) {
675 SI.setOperand(0, UndefValue::get(Val->getType()));
676 if (Instruction *U = dyn_cast<Instruction>(Val))
677 Worklist.Add(U); // Dropped a use.
678 }
679 return 0; // Do not modify these!
680 }
681
682 // store undef, Ptr -> noop
683 if (isa<UndefValue>(Val))
684 return EraseInstFromFunction(SI);
685
686 // If the pointer destination is a cast, see if we can fold the cast into the
687 // source instead.
688 if (isa<CastInst>(Ptr))
689 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
690 return Res;
691 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
692 if (CE->isCast())
693 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
694 return Res;
695
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000696
Chris Lattnera65e2f72010-01-05 05:57:49 +0000697 // If this store is the last instruction in the basic block (possibly
Victor Hernandez5f5abd52010-01-21 23:07:15 +0000698 // excepting debug info instructions), and if the block ends with an
699 // unconditional branch, try to move it to the successor block.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000700 BBI = &SI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000701 do {
702 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000703 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000704 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000705 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
706 if (BI->isUnconditional())
707 if (SimplifyStoreAtEndOfBlock(SI))
708 return 0; // xform done!
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000709
Chris Lattnera65e2f72010-01-05 05:57:49 +0000710 return 0;
711}
712
713/// SimplifyStoreAtEndOfBlock - Turn things like:
714/// if () { *P = v1; } else { *P = v2 }
715/// into a phi node with a store in the successor.
716///
717/// Simplify things like:
718/// *P = v1; if () { *P = v2; }
719/// into a phi node with a store in the successor.
720///
721bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
722 BasicBlock *StoreBB = SI.getParent();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000723
Chris Lattnera65e2f72010-01-05 05:57:49 +0000724 // Check to see if the successor block has exactly two incoming edges. If
725 // so, see if the other predecessor contains a store to the same location.
726 // if so, insert a PHI node (if needed) and move the stores down.
727 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000728
Chris Lattnera65e2f72010-01-05 05:57:49 +0000729 // Determine whether Dest has exactly two predecessors and, if so, compute
730 // the other predecessor.
731 pred_iterator PI = pred_begin(DestBB);
Gabor Greif1b787df2010-07-12 15:48:26 +0000732 BasicBlock *P = *PI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000733 BasicBlock *OtherBB = 0;
Gabor Greif1b787df2010-07-12 15:48:26 +0000734
735 if (P != StoreBB)
736 OtherBB = P;
737
738 if (++PI == pred_end(DestBB))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000739 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000740
Gabor Greif1b787df2010-07-12 15:48:26 +0000741 P = *PI;
742 if (P != StoreBB) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000743 if (OtherBB)
744 return false;
Gabor Greif1b787df2010-07-12 15:48:26 +0000745 OtherBB = P;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000746 }
747 if (++PI != pred_end(DestBB))
748 return false;
749
750 // Bail out if all the relevant blocks aren't distinct (this can happen,
751 // for example, if SI is in an infinite loop)
752 if (StoreBB == DestBB || OtherBB == DestBB)
753 return false;
754
755 // Verify that the other block ends in a branch and is not otherwise empty.
756 BasicBlock::iterator BBI = OtherBB->getTerminator();
757 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
758 if (!OtherBr || BBI == OtherBB->begin())
759 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000760
Chris Lattnera65e2f72010-01-05 05:57:49 +0000761 // If the other block ends in an unconditional branch, check for the 'if then
762 // else' case. there is an instruction before the branch.
763 StoreInst *OtherStore = 0;
764 if (OtherBr->isUnconditional()) {
765 --BBI;
766 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000767 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000768 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000769 if (BBI==OtherBB->begin())
770 return false;
771 --BBI;
772 }
Eli Friedman8bc586e2011-08-15 22:09:40 +0000773 // If this isn't a store, isn't a store to the same location, or is not the
774 // right kind of store, bail out.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000775 OtherStore = dyn_cast<StoreInst>(BBI);
776 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +0000777 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000778 return false;
779 } else {
780 // Otherwise, the other block ended with a conditional branch. If one of the
781 // destinations is StoreBB, then we have the if/then case.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000782 if (OtherBr->getSuccessor(0) != StoreBB &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000783 OtherBr->getSuccessor(1) != StoreBB)
784 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000785
Chris Lattnera65e2f72010-01-05 05:57:49 +0000786 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
787 // if/then triangle. See if there is a store to the same ptr as SI that
788 // lives in OtherBB.
789 for (;; --BBI) {
790 // Check to see if we find the matching store.
791 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
792 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +0000793 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000794 return false;
795 break;
796 }
797 // If we find something that may be using or overwriting the stored
798 // value, or if we run out of instructions, we can't do the xform.
799 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
800 BBI == OtherBB->begin())
801 return false;
802 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000803
Chris Lattnera65e2f72010-01-05 05:57:49 +0000804 // In order to eliminate the store in OtherBr, we have to
805 // make sure nothing reads or overwrites the stored value in
806 // StoreBB.
807 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
808 // FIXME: This should really be AA driven.
809 if (I->mayReadFromMemory() || I->mayWriteToMemory())
810 return false;
811 }
812 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000813
Chris Lattnera65e2f72010-01-05 05:57:49 +0000814 // Insert a PHI node now if we need it.
815 Value *MergedVal = OtherStore->getOperand(0);
816 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +0000817 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +0000818 PN->addIncoming(SI.getOperand(0), SI.getParent());
819 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
820 MergedVal = InsertNewInstBefore(PN, DestBB->front());
821 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000822
Chris Lattnera65e2f72010-01-05 05:57:49 +0000823 // Advance to a place where it is safe to insert the new store and
824 // insert it.
Bill Wendling8ddfc092011-08-16 20:45:24 +0000825 BBI = DestBB->getFirstInsertionPt();
Eli Friedman35211c62011-05-27 00:19:40 +0000826 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +0000827 SI.isVolatile(),
828 SI.getAlignment(),
829 SI.getOrdering(),
830 SI.getSynchScope());
Eli Friedman35211c62011-05-27 00:19:40 +0000831 InsertNewInstBefore(NewSI, *BBI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000832 NewSI->setDebugLoc(OtherStore->getDebugLoc());
Eli Friedman35211c62011-05-27 00:19:40 +0000833
Chris Lattnereeefe1b2012-12-31 08:10:58 +0000834 // If the two stores had the same TBAA tag, preserve it.
Chris Lattner473988c2013-01-05 16:44:07 +0000835 if (MDNode *TBAATag = SI.getMetadata(LLVMContext::MD_tbaa))
836 if ((TBAATag = MDNode::getMostGenericTBAA(TBAATag,
837 OtherStore->getMetadata(LLVMContext::MD_tbaa))))
838 NewSI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
Chris Lattnereeefe1b2012-12-31 08:10:58 +0000839
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000840
Chris Lattnera65e2f72010-01-05 05:57:49 +0000841 // Nuke the old stores.
842 EraseInstFromFunction(SI);
843 EraseInstFromFunction(*OtherStore);
844 return true;
845}