blob: 9e46041886d95b7bcd001809d456fb7e6a4b77db [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();
Matt Arsenault607281772014-04-24 00:01:09 +000034
35 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000036 if (CE->getOpcode() == Instruction::BitCast ||
Matt Arsenault607281772014-04-24 00:01:09 +000037 CE->getOpcode() == Instruction::AddrSpaceCast ||
Chandler Carruthc908ca12012-08-21 08:39:44 +000038 CE->getOpcode() == Instruction::GetElementPtr)
39 return pointsToConstantGlobal(CE->getOperand(0));
Matt Arsenault607281772014-04-24 00:01:09 +000040 }
Chandler Carruthc908ca12012-08-21 08:39:44 +000041 return false;
42}
43
44/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
45/// pointer to an alloca. Ignore any reads of the pointer, return false if we
46/// see any stores or other unknown uses. If we see pointer arithmetic, keep
47/// track of whether it moves the pointer (with IsOffset) but otherwise traverse
48/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
49/// the alloca, and if the source pointer is a pointer to a constant global, we
50/// can optimize this.
51static bool
52isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Reid Kleckner813dab22014-07-01 21:36:20 +000053 SmallVectorImpl<Instruction *> &ToDelete) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000054 // We track lifetime intrinsics as we encounter them. If we decide to go
55 // ahead and replace the value with the global, this lets the caller quickly
56 // eliminate the markers.
57
Reid Kleckner813dab22014-07-01 21:36:20 +000058 SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect;
59 ValuesToInspect.push_back(std::make_pair(V, false));
60 while (!ValuesToInspect.empty()) {
61 auto ValuePair = ValuesToInspect.pop_back_val();
62 const bool IsOffset = ValuePair.second;
63 for (auto &U : ValuePair.first->uses()) {
64 Instruction *I = cast<Instruction>(U.getUser());
Chandler Carruthc908ca12012-08-21 08:39:44 +000065
Reid Kleckner813dab22014-07-01 21:36:20 +000066 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
67 // Ignore non-volatile loads, they are always ok.
68 if (!LI->isSimple()) return false;
Chandler Carruthc908ca12012-08-21 08:39:44 +000069 continue;
70 }
Reid Kleckner813dab22014-07-01 21:36:20 +000071
72 if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) {
73 // If uses of the bitcast are ok, we are ok.
74 ValuesToInspect.push_back(std::make_pair(I, IsOffset));
75 continue;
76 }
77 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
78 // If the GEP has all zero indices, it doesn't offset the pointer. If it
79 // doesn't, it does.
80 ValuesToInspect.push_back(
81 std::make_pair(I, IsOffset || !GEP->hasAllZeroIndices()));
82 continue;
83 }
84
85 if (CallSite CS = I) {
86 // If this is the function being called then we treat it like a load and
87 // ignore it.
88 if (CS.isCallee(&U))
89 continue;
90
91 // Inalloca arguments are clobbered by the call.
92 unsigned ArgNo = CS.getArgumentNo(&U);
93 if (CS.isInAllocaArgument(ArgNo))
94 return false;
95
96 // If this is a readonly/readnone call site, then we know it is just a
97 // load (but one that potentially returns the value itself), so we can
98 // ignore it if we know that the value isn't captured.
99 if (CS.onlyReadsMemory() &&
100 (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
101 continue;
102
103 // If this is being passed as a byval argument, the caller is making a
104 // copy, so it is only a read of the alloca.
105 if (CS.isByValArgument(ArgNo))
106 continue;
107 }
108
109 // Lifetime intrinsics can be handled by the caller.
110 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
111 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
112 II->getIntrinsicID() == Intrinsic::lifetime_end) {
113 assert(II->use_empty() && "Lifetime markers have no result to use!");
114 ToDelete.push_back(II);
115 continue;
116 }
117 }
118
119 // If this is isn't our memcpy/memmove, reject it as something we can't
120 // handle.
121 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
122 if (!MI)
123 return false;
124
125 // If the transfer is using the alloca as a source of the transfer, then
126 // ignore it since it is a load (unless the transfer is volatile).
127 if (U.getOperandNo() == 1) {
128 if (MI->isVolatile()) return false;
129 continue;
130 }
131
132 // If we already have seen a copy, reject the second one.
133 if (TheCopy) return false;
134
135 // If the pointer has been offset from the start of the alloca, we can't
136 // safely handle this.
137 if (IsOffset) return false;
138
139 // If the memintrinsic isn't using the alloca as the dest, reject it.
140 if (U.getOperandNo() != 0) return false;
141
142 // If the source of the memcpy/move is not a constant global, reject it.
143 if (!pointsToConstantGlobal(MI->getSource()))
144 return false;
145
146 // Otherwise, the transform is safe. Remember the copy instruction.
147 TheCopy = MI;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000148 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000149 }
150 return true;
151}
152
153/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
154/// modified by a copy from a constant global. If we can prove this, we can
155/// replace any uses of the alloca with uses of the global directly.
156static MemTransferInst *
157isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
158 SmallVectorImpl<Instruction *> &ToDelete) {
Craig Topperf40110f2014-04-25 05:29:35 +0000159 MemTransferInst *TheCopy = nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000160 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
161 return TheCopy;
Craig Topperf40110f2014-04-25 05:29:35 +0000162 return nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000163}
164
Chris Lattnera65e2f72010-01-05 05:57:49 +0000165Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Dan Gohmandf5d7dc2010-05-28 15:09:00 +0000166 // Ensure that the alloca array size argument has type intptr_t, so that
167 // any casting is exposed early.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000168 if (DL) {
169 Type *IntPtrTy = DL->getIntPtrType(AI.getType());
Dan Gohmandf5d7dc2010-05-28 15:09:00 +0000170 if (AI.getArraySize()->getType() != IntPtrTy) {
171 Value *V = Builder->CreateIntCast(AI.getArraySize(),
172 IntPtrTy, false);
173 AI.setOperand(0, V);
174 return &AI;
175 }
176 }
177
Chris Lattnera65e2f72010-01-05 05:57:49 +0000178 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
179 if (AI.isArrayAllocation()) { // Check C != 1
180 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000181 Type *NewTy =
Chris Lattnera65e2f72010-01-05 05:57:49 +0000182 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Craig Topperf40110f2014-04-25 05:29:35 +0000183 AllocaInst *New = Builder->CreateAlloca(NewTy, nullptr, AI.getName());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000184 New->setAlignment(AI.getAlignment());
185
186 // Scan to the end of the allocation instructions, to skip over a block of
187 // allocas if possible...also skip interleaved debug info
188 //
189 BasicBlock::iterator It = New;
190 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
191
192 // Now that I is pointing to the first non-allocation-inst in the block,
193 // insert our getelementptr instruction...
194 //
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000195 Type *IdxTy = DL
196 ? DL->getIntPtrType(AI.getType())
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +0000197 : Type::getInt64Ty(AI.getContext());
198 Value *NullIdx = Constant::getNullValue(IdxTy);
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000199 Value *Idx[2] = { NullIdx, NullIdx };
Eli Friedman41e509a2011-05-18 23:58:37 +0000200 Instruction *GEP =
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000201 GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
Eli Friedman41e509a2011-05-18 23:58:37 +0000202 InsertNewInstBefore(GEP, *It);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000203
204 // Now make everything use the getelementptr instead of the original
205 // allocation.
Eli Friedman41e509a2011-05-18 23:58:37 +0000206 return ReplaceInstUsesWith(AI, GEP);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000207 } else if (isa<UndefValue>(AI.getArraySize())) {
208 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
209 }
210 }
211
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000212 if (DL && AI.getAllocatedType()->isSized()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000213 // If the alignment is 0 (unspecified), assign it the preferred alignment.
214 if (AI.getAlignment() == 0)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000215 AI.setAlignment(DL->getPrefTypeAlignment(AI.getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000216
217 // Move all alloca's of zero byte objects to the entry block and merge them
218 // together. Note that we only do this for alloca's, because malloc should
219 // allocate and return a unique pointer, even for a zero byte allocation.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000220 if (DL->getTypeAllocSize(AI.getAllocatedType()) == 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000221 // For a zero sized alloca there is no point in doing an array allocation.
222 // This is helpful if the array size is a complicated expression not used
223 // elsewhere.
224 if (AI.isArrayAllocation()) {
225 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
226 return &AI;
227 }
228
229 // Get the first instruction in the entry block.
230 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
231 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
232 if (FirstInst != &AI) {
233 // If the entry block doesn't start with a zero-size alloca then move
234 // this one to the start of the entry block. There is no problem with
235 // dominance as the array size was forced to a constant earlier already.
236 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
237 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000238 DL->getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000239 AI.moveBefore(FirstInst);
240 return &AI;
241 }
242
Richard Osborneb68053e2012-09-18 09:31:44 +0000243 // If the alignment of the entry block alloca is 0 (unspecified),
244 // assign it the preferred alignment.
245 if (EntryAI->getAlignment() == 0)
246 EntryAI->setAlignment(
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000247 DL->getPrefTypeAlignment(EntryAI->getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000248 // Replace this zero-sized alloca with the one at the start of the entry
249 // block after ensuring that the address will be aligned enough for both
250 // types.
Richard Osborneb68053e2012-09-18 09:31:44 +0000251 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
252 AI.getAlignment());
Duncan Sands8bc764a2012-06-26 13:39:21 +0000253 EntryAI->setAlignment(MaxAlign);
254 if (AI.getType() != EntryAI->getType())
255 return new BitCastInst(EntryAI, AI.getType());
256 return ReplaceInstUsesWith(AI, EntryAI);
257 }
258 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000259 }
260
Eli Friedmanb14873c2012-11-26 23:04:53 +0000261 if (AI.getAlignment()) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000262 // Check to see if this allocation is only modified by a memcpy/memmove from
263 // a constant global whose alignment is equal to or exceeds that of the
264 // allocation. If this is the case, we can change all users to use
265 // the constant global instead. This is commonly produced by the CFE by
266 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
267 // is only subsequently read.
268 SmallVector<Instruction *, 4> ToDelete;
269 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
Eli Friedmanb14873c2012-11-26 23:04:53 +0000270 unsigned SourceAlign = getOrEnforceKnownAlignment(Copy->getSource(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000271 AI.getAlignment(), DL);
Eli Friedmanb14873c2012-11-26 23:04:53 +0000272 if (AI.getAlignment() <= SourceAlign) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000273 DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
274 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
275 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
276 EraseInstFromFunction(*ToDelete[i]);
277 Constant *TheSrc = cast<Constant>(Copy->getSource());
Matt Arsenaultbbf18c62013-12-07 02:58:45 +0000278 Constant *Cast
279 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
280 Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000281 EraseInstFromFunction(*Copy);
282 ++NumGlobalCopies;
283 return NewI;
284 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000285 }
286 }
287
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000288 // At last, use the generic allocation site handler to aggressively remove
289 // unused allocas.
290 return visitAllocSite(AI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000291}
292
293
294/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
295static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000296 const DataLayout *DL) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000297 User *CI = cast<User>(LI.getOperand(0));
298 Value *CastOp = CI->getOperand(0);
299
Chris Lattner229907c2011-07-18 04:54:35 +0000300 PointerType *DestTy = cast<PointerType>(CI->getType());
301 Type *DestPTy = DestTy->getElementType();
302 if (PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000303
304 // If the address spaces don't match, don't eliminate the cast.
305 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
Craig Topperf40110f2014-04-25 05:29:35 +0000306 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000307
Chris Lattner229907c2011-07-18 04:54:35 +0000308 Type *SrcPTy = SrcTy->getElementType();
Chris Lattnera65e2f72010-01-05 05:57:49 +0000309
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000310 if (DestPTy->isIntegerTy() || DestPTy->isPointerTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000311 DestPTy->isVectorTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000312 // If the source is an array, the code below will not succeed. Check to
313 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
314 // constants.
Chris Lattner229907c2011-07-18 04:54:35 +0000315 if (ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000316 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
317 if (ASrcTy->getNumElements() != 0) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000318 Type *IdxTy = DL
319 ? DL->getIntPtrType(SrcTy)
Matt Arsenault3dfe54e2013-09-03 21:05:48 +0000320 : Type::getInt64Ty(SrcTy->getContext());
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +0000321 Value *Idx = Constant::getNullValue(IdxTy);
322 Value *Idxs[2] = { Idx, Idx };
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
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000328 if (IC.getDataLayout() &&
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000329 (SrcPTy->isIntegerTy() || SrcPTy->isPointerTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000330 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.
Benjamin Kramer0b37cdf2013-09-19 20:59:04 +0000333 (SrcPTy->isPtrOrPtrVectorTy() ==
334 LI.getType()->isPtrOrPtrVectorTy()) &&
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000335 IC.getDataLayout()->getTypeSizeInBits(SrcPTy) ==
336 IC.getDataLayout()->getTypeSizeInBits(DestPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000337
338 // Okay, we are casting from one integer or pointer type to another of
339 // the same size. Instead of casting the pointer before the load, cast
340 // the result of the loaded value.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000341 LoadInst *NewLoad =
Chris Lattnera65e2f72010-01-05 05:57:49 +0000342 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000343 NewLoad->setAlignment(LI.getAlignment());
Eli Friedman8bc586e2011-08-15 22:09:40 +0000344 NewLoad->setAtomic(LI.getOrdering(), LI.getSynchScope());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000345 // Now cast the result of the load.
Owen Anderson9b8f9c32014-03-13 22:51:43 +0000346 PointerType *OldTy = dyn_cast<PointerType>(NewLoad->getType());
347 PointerType *NewTy = dyn_cast<PointerType>(LI.getType());
348 if (OldTy && NewTy &&
349 OldTy->getAddressSpace() != NewTy->getAddressSpace()) {
350 return new AddrSpaceCastInst(NewLoad, LI.getType());
351 }
352
Chris Lattnera65e2f72010-01-05 05:57:49 +0000353 return new BitCastInst(NewLoad, LI.getType());
354 }
355 }
356 }
Craig Topperf40110f2014-04-25 05:29:35 +0000357 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000358}
359
360Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
361 Value *Op = LI.getOperand(0);
362
363 // Attempt to improve the alignment.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000364 if (DL) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000365 unsigned KnownAlign =
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000366 getOrEnforceKnownAlignment(Op, DL->getPrefTypeAlignment(LI.getType()),DL);
Dan Gohman36196602010-08-03 18:20:32 +0000367 unsigned LoadAlign = LI.getAlignment();
368 unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000369 DL->getABITypeAlignment(LI.getType());
Dan Gohman36196602010-08-03 18:20:32 +0000370
371 if (KnownAlign > EffectiveLoadAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000372 LI.setAlignment(KnownAlign);
Dan Gohman36196602010-08-03 18:20:32 +0000373 else if (LoadAlign == 0)
374 LI.setAlignment(EffectiveLoadAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000375 }
376
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000377 // load (cast X) --> cast (load X) iff safe.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000378 if (isa<CastInst>(Op))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000379 if (Instruction *Res = InstCombineLoadCast(*this, LI, DL))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000380 return Res;
381
Eli Friedman8bc586e2011-08-15 22:09:40 +0000382 // None of the following transforms are legal for volatile/atomic loads.
383 // FIXME: Some of it is okay for atomic loads; needs refactoring.
Craig Topperf40110f2014-04-25 05:29:35 +0000384 if (!LI.isSimple()) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000385
Chris Lattnera65e2f72010-01-05 05:57:49 +0000386 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +0000387 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +0000388 // separated by a few arithmetic operations.
389 BasicBlock::iterator BBI = &LI;
390 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
391 return ReplaceInstUsesWith(LI, AvailableVal);
392
393 // load(gep null, ...) -> unreachable
394 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
395 const Value *GEPI0 = GEPI->getOperand(0);
396 // TODO: Consider a target hook for valid address spaces for this xform.
397 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
398 // Insert a new store to null instruction before the load to indicate
399 // that this code is not reachable. We do this instead of inserting
400 // an unreachable instruction directly because we cannot modify the
401 // CFG.
402 new StoreInst(UndefValue::get(LI.getType()),
403 Constant::getNullValue(Op->getType()), &LI);
404 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
405 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000406 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000407
408 // load null/undef -> unreachable
409 // TODO: Consider a target hook for valid address spaces for this xform.
410 if (isa<UndefValue>(Op) ||
411 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
412 // Insert a new store to null instruction before the load to indicate that
413 // this code is not reachable. We do this instead of inserting an
414 // unreachable instruction directly because we cannot modify the CFG.
415 new StoreInst(UndefValue::get(LI.getType()),
416 Constant::getNullValue(Op->getType()), &LI);
417 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
418 }
419
420 // Instcombine load (constantexpr_cast global) -> cast (load global)
421 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
422 if (CE->isCast())
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000423 if (Instruction *Res = InstCombineLoadCast(*this, LI, DL))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000424 return Res;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000425
Chris Lattnera65e2f72010-01-05 05:57:49 +0000426 if (Op->hasOneUse()) {
427 // Change select and PHI nodes to select values instead of addresses: this
428 // helps alias analysis out a lot, allows many others simplifications, and
429 // exposes redundancy in the code.
430 //
431 // Note that we cannot do the transformation unless we know that the
432 // introduced loads cannot trap! Something like this is valid as long as
433 // the condition is always false: load (select bool %C, int* null, int* %G),
434 // but it would not be valid if we transformed it to load from null
435 // unconditionally.
436 //
437 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
438 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +0000439 unsigned Align = LI.getAlignment();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000440 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, DL) &&
441 isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, DL)) {
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000442 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
Bob Wilson56600a12010-01-30 04:42:39 +0000443 SI->getOperand(1)->getName()+".val");
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000444 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
Bob Wilson56600a12010-01-30 04:42:39 +0000445 SI->getOperand(2)->getName()+".val");
446 V1->setAlignment(Align);
447 V2->setAlignment(Align);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000448 return SelectInst::Create(SI->getCondition(), V1, V2);
449 }
450
451 // load (select (cond, null, P)) -> load P
452 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
453 if (C->isNullValue()) {
454 LI.setOperand(0, SI->getOperand(2));
455 return &LI;
456 }
457
458 // load (select (cond, P, null)) -> load P
459 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
460 if (C->isNullValue()) {
461 LI.setOperand(0, SI->getOperand(1));
462 return &LI;
463 }
464 }
465 }
Craig Topperf40110f2014-04-25 05:29:35 +0000466 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000467}
468
469/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
470/// when possible. This makes it generally easy to do alias analysis and/or
471/// SROA/mem2reg of the memory object.
472static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
473 User *CI = cast<User>(SI.getOperand(1));
474 Value *CastOp = CI->getOperand(0);
475
Matt Arsenaultd0d6c0b2014-07-14 17:24:38 +0000476 Type *DestPTy = CI->getType()->getPointerElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000477 PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
Craig Topperf40110f2014-04-25 05:29:35 +0000478 if (!SrcTy) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000479
Chris Lattner229907c2011-07-18 04:54:35 +0000480 Type *SrcPTy = SrcTy->getElementType();
Chris Lattnera65e2f72010-01-05 05:57:49 +0000481
Duncan Sands19d0b472010-02-16 11:11:14 +0000482 if (!DestPTy->isIntegerTy() && !DestPTy->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000483 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000484
Chris Lattnera65e2f72010-01-05 05:57:49 +0000485 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
486 /// to its first element. This allows us to handle things like:
487 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
488 /// on 32-bit hosts.
489 SmallVector<Value*, 4> NewGEPIndices;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000490
Chris Lattnera65e2f72010-01-05 05:57:49 +0000491 // If the source is an array, the code below will not succeed. Check to
492 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
493 // constants.
Duncan Sands19d0b472010-02-16 11:11:14 +0000494 if (SrcPTy->isArrayTy() || SrcPTy->isStructTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000495 // Index through pointer.
496 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
497 NewGEPIndices.push_back(Zero);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000498
Chris Lattnera65e2f72010-01-05 05:57:49 +0000499 while (1) {
Chris Lattner229907c2011-07-18 04:54:35 +0000500 if (StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000501 if (!STy->getNumElements()) /* Struct can be empty {} */
502 break;
503 NewGEPIndices.push_back(Zero);
504 SrcPTy = STy->getElementType(0);
Chris Lattner229907c2011-07-18 04:54:35 +0000505 } else if (ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000506 NewGEPIndices.push_back(Zero);
507 SrcPTy = ATy->getElementType();
508 } else {
509 break;
510 }
511 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000512
Chris Lattnera65e2f72010-01-05 05:57:49 +0000513 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
514 }
515
Duncan Sands19d0b472010-02-16 11:11:14 +0000516 if (!SrcPTy->isIntegerTy() && !SrcPTy->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000517 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000518
Richard Osborne0af4aa92014-03-25 17:21:41 +0000519 // If the pointers point into different address spaces don't do the
520 // transformation.
Matt Arsenaultd0d6c0b2014-07-14 17:24:38 +0000521 if (SrcTy->getAddressSpace() != CI->getType()->getPointerAddressSpace())
Craig Topperf40110f2014-04-25 05:29:35 +0000522 return nullptr;
Richard Osborne0af4aa92014-03-25 17:21:41 +0000523
524 // If the pointers point to values of different sizes don't do the
525 // transformation.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000526 if (!IC.getDataLayout() ||
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000527 IC.getDataLayout()->getTypeSizeInBits(SrcPTy) !=
528 IC.getDataLayout()->getTypeSizeInBits(DestPTy))
Craig Topperf40110f2014-04-25 05:29:35 +0000529 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000530
Richard Osborne0af4aa92014-03-25 17:21:41 +0000531 // If the pointers point to pointers to different address spaces don't do the
532 // transformation. It is not safe to introduce an addrspacecast instruction in
533 // this case since, depending on the target, addrspacecast may not be a no-op
534 // cast.
535 if (SrcPTy->isPointerTy() && DestPTy->isPointerTy() &&
536 SrcPTy->getPointerAddressSpace() != DestPTy->getPointerAddressSpace())
Craig Topperf40110f2014-04-25 05:29:35 +0000537 return nullptr;
Richard Osborne0af4aa92014-03-25 17:21:41 +0000538
Chris Lattnera65e2f72010-01-05 05:57:49 +0000539 // Okay, we are casting from one integer or pointer type to another of
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000540 // the same size. Instead of casting the pointer before
Chris Lattnera65e2f72010-01-05 05:57:49 +0000541 // the store, cast the value to be stored.
542 Value *NewCast;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000543 Instruction::CastOps opcode = Instruction::BitCast;
Richard Osborne9805ec42014-03-25 17:21:35 +0000544 Type* CastSrcTy = DestPTy;
Chris Lattner229907c2011-07-18 04:54:35 +0000545 Type* CastDstTy = SrcPTy;
Duncan Sands19d0b472010-02-16 11:11:14 +0000546 if (CastDstTy->isPointerTy()) {
Duncan Sands9dff9be2010-02-15 16:12:20 +0000547 if (CastSrcTy->isIntegerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000548 opcode = Instruction::IntToPtr;
Duncan Sands19d0b472010-02-16 11:11:14 +0000549 } else if (CastDstTy->isIntegerTy()) {
Richard Osborne9805ec42014-03-25 17:21:35 +0000550 if (CastSrcTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000551 opcode = Instruction::PtrToInt;
552 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000553
Chris Lattnera65e2f72010-01-05 05:57:49 +0000554 // SIOp0 is a pointer to aggregate and this is a store to the first field,
555 // emit a GEP to index into its first field.
556 if (!NewGEPIndices.empty())
Jay Foad040dd822011-07-22 08:16:57 +0000557 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000558
Richard Osborne9805ec42014-03-25 17:21:35 +0000559 Value *SIOp0 = SI.getOperand(0);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000560 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
561 SIOp0->getName()+".c");
Dan Gohman2e20dfb2010-10-25 16:16:27 +0000562 SI.setOperand(0, NewCast);
563 SI.setOperand(1, CastOp);
564 return &SI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000565}
566
567/// equivalentAddressValues - Test if A and B will obviously have the same
568/// value. This includes recognizing that %t0 and %t1 will have the same
569/// value in code like this:
570/// %t0 = getelementptr \@a, 0, 3
571/// store i32 0, i32* %t0
572/// %t1 = getelementptr \@a, 0, 3
573/// %t2 = load i32* %t1
574///
575static bool equivalentAddressValues(Value *A, Value *B) {
576 // Test if the values are trivially equivalent.
577 if (A == B) return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000578
Chris Lattnera65e2f72010-01-05 05:57:49 +0000579 // Test if the values come form identical arithmetic instructions.
580 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
581 // its only used to compare two uses within the same basic block, which
582 // means that they'll always either have the same value or one of them
583 // will have an undefined value.
584 if (isa<BinaryOperator>(A) ||
585 isa<CastInst>(A) ||
586 isa<PHINode>(A) ||
587 isa<GetElementPtrInst>(A))
588 if (Instruction *BI = dyn_cast<Instruction>(B))
589 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
590 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000591
Chris Lattnera65e2f72010-01-05 05:57:49 +0000592 // Otherwise they may not be equivalent.
593 return false;
594}
595
Chris Lattnera65e2f72010-01-05 05:57:49 +0000596Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
597 Value *Val = SI.getOperand(0);
598 Value *Ptr = SI.getOperand(1);
599
Chris Lattnera65e2f72010-01-05 05:57:49 +0000600 // Attempt to improve the alignment.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000601 if (DL) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000602 unsigned KnownAlign =
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000603 getOrEnforceKnownAlignment(Ptr, DL->getPrefTypeAlignment(Val->getType()),
604 DL);
Dan Gohman36196602010-08-03 18:20:32 +0000605 unsigned StoreAlign = SI.getAlignment();
606 unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000607 DL->getABITypeAlignment(Val->getType());
Dan Gohman36196602010-08-03 18:20:32 +0000608
Bill Wendling55b6b2b2012-03-16 18:20:54 +0000609 if (KnownAlign > EffectiveStoreAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000610 SI.setAlignment(KnownAlign);
Bill Wendling55b6b2b2012-03-16 18:20:54 +0000611 else if (StoreAlign == 0)
612 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000613 }
614
Eli Friedman8bc586e2011-08-15 22:09:40 +0000615 // Don't hack volatile/atomic stores.
616 // FIXME: Some bits are legal for atomic stores; needs refactoring.
Craig Topperf40110f2014-04-25 05:29:35 +0000617 if (!SI.isSimple()) return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +0000618
619 // If the RHS is an alloca with a single use, zapify the store, making the
620 // alloca dead.
621 if (Ptr->hasOneUse()) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000622 if (isa<AllocaInst>(Ptr))
Eli Friedman8bc586e2011-08-15 22:09:40 +0000623 return EraseInstFromFunction(SI);
624 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
625 if (isa<AllocaInst>(GEP->getOperand(0))) {
626 if (GEP->getOperand(0)->hasOneUse())
627 return EraseInstFromFunction(SI);
628 }
629 }
630 }
631
Chris Lattnera65e2f72010-01-05 05:57:49 +0000632 // Do really simple DSE, to catch cases where there are several consecutive
633 // stores to the same location, separated by a few arithmetic operations. This
634 // situation often occurs with bitfield accesses.
635 BasicBlock::iterator BBI = &SI;
636 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
637 --ScanInsts) {
638 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000639 // Don't count debug info directives, lest they affect codegen,
640 // and we skip pointer-to-pointer bitcasts, which are NOPs.
641 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000642 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000643 ScanInsts++;
644 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000645 }
646
Chris Lattnera65e2f72010-01-05 05:57:49 +0000647 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
648 // Prev store isn't volatile, and stores to the same location?
Eli Friedman8bc586e2011-08-15 22:09:40 +0000649 if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
650 SI.getOperand(1))) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000651 ++NumDeadStore;
652 ++BBI;
653 EraseInstFromFunction(*PrevSI);
654 continue;
655 }
656 break;
657 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000658
Chris Lattnera65e2f72010-01-05 05:57:49 +0000659 // If this is a load, we have to stop. However, if the loaded value is from
660 // the pointer we're loading and is producing the pointer we're storing,
661 // then *this* store is dead (X = load P; store X -> P).
662 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000663 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
Eli Friedman8bc586e2011-08-15 22:09:40 +0000664 LI->isSimple())
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000665 return EraseInstFromFunction(SI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000666
Chris Lattnera65e2f72010-01-05 05:57:49 +0000667 // Otherwise, this is a load from some other location. Stores before it
668 // may not be dead.
669 break;
670 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000671
Chris Lattnera65e2f72010-01-05 05:57:49 +0000672 // Don't skip over loads or things that can modify memory.
673 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
674 break;
675 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000676
677 // store X, null -> turns into 'unreachable' in SimplifyCFG
678 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
679 if (!isa<UndefValue>(Val)) {
680 SI.setOperand(0, UndefValue::get(Val->getType()));
681 if (Instruction *U = dyn_cast<Instruction>(Val))
682 Worklist.Add(U); // Dropped a use.
683 }
Craig Topperf40110f2014-04-25 05:29:35 +0000684 return nullptr; // Do not modify these!
Chris Lattnera65e2f72010-01-05 05:57:49 +0000685 }
686
687 // store undef, Ptr -> noop
688 if (isa<UndefValue>(Val))
689 return EraseInstFromFunction(SI);
690
691 // If the pointer destination is a cast, see if we can fold the cast into the
692 // source instead.
693 if (isa<CastInst>(Ptr))
694 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
695 return Res;
696 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
697 if (CE->isCast())
698 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
699 return Res;
700
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000701
Chris Lattnera65e2f72010-01-05 05:57:49 +0000702 // If this store is the last instruction in the basic block (possibly
Victor Hernandez5f5abd52010-01-21 23:07:15 +0000703 // excepting debug info instructions), and if the block ends with an
704 // unconditional branch, try to move it to the successor block.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000705 BBI = &SI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000706 do {
707 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000708 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000709 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000710 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
711 if (BI->isUnconditional())
712 if (SimplifyStoreAtEndOfBlock(SI))
Craig Topperf40110f2014-04-25 05:29:35 +0000713 return nullptr; // xform done!
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000714
Craig Topperf40110f2014-04-25 05:29:35 +0000715 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000716}
717
718/// SimplifyStoreAtEndOfBlock - Turn things like:
719/// if () { *P = v1; } else { *P = v2 }
720/// into a phi node with a store in the successor.
721///
722/// Simplify things like:
723/// *P = v1; if () { *P = v2; }
724/// into a phi node with a store in the successor.
725///
726bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
727 BasicBlock *StoreBB = SI.getParent();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000728
Chris Lattnera65e2f72010-01-05 05:57:49 +0000729 // Check to see if the successor block has exactly two incoming edges. If
730 // so, see if the other predecessor contains a store to the same location.
731 // if so, insert a PHI node (if needed) and move the stores down.
732 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000733
Chris Lattnera65e2f72010-01-05 05:57:49 +0000734 // Determine whether Dest has exactly two predecessors and, if so, compute
735 // the other predecessor.
736 pred_iterator PI = pred_begin(DestBB);
Gabor Greif1b787df2010-07-12 15:48:26 +0000737 BasicBlock *P = *PI;
Craig Topperf40110f2014-04-25 05:29:35 +0000738 BasicBlock *OtherBB = nullptr;
Gabor Greif1b787df2010-07-12 15:48:26 +0000739
740 if (P != StoreBB)
741 OtherBB = P;
742
743 if (++PI == pred_end(DestBB))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000744 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000745
Gabor Greif1b787df2010-07-12 15:48:26 +0000746 P = *PI;
747 if (P != StoreBB) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000748 if (OtherBB)
749 return false;
Gabor Greif1b787df2010-07-12 15:48:26 +0000750 OtherBB = P;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000751 }
752 if (++PI != pred_end(DestBB))
753 return false;
754
755 // Bail out if all the relevant blocks aren't distinct (this can happen,
756 // for example, if SI is in an infinite loop)
757 if (StoreBB == DestBB || OtherBB == DestBB)
758 return false;
759
760 // Verify that the other block ends in a branch and is not otherwise empty.
761 BasicBlock::iterator BBI = OtherBB->getTerminator();
762 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
763 if (!OtherBr || BBI == OtherBB->begin())
764 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000765
Chris Lattnera65e2f72010-01-05 05:57:49 +0000766 // If the other block ends in an unconditional branch, check for the 'if then
767 // else' case. there is an instruction before the branch.
Craig Topperf40110f2014-04-25 05:29:35 +0000768 StoreInst *OtherStore = nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000769 if (OtherBr->isUnconditional()) {
770 --BBI;
771 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000772 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000773 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000774 if (BBI==OtherBB->begin())
775 return false;
776 --BBI;
777 }
Eli Friedman8bc586e2011-08-15 22:09:40 +0000778 // If this isn't a store, isn't a store to the same location, or is not the
779 // right kind of store, bail out.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000780 OtherStore = dyn_cast<StoreInst>(BBI);
781 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +0000782 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000783 return false;
784 } else {
785 // Otherwise, the other block ended with a conditional branch. If one of the
786 // destinations is StoreBB, then we have the if/then case.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000787 if (OtherBr->getSuccessor(0) != StoreBB &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000788 OtherBr->getSuccessor(1) != StoreBB)
789 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000790
Chris Lattnera65e2f72010-01-05 05:57:49 +0000791 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
792 // if/then triangle. See if there is a store to the same ptr as SI that
793 // lives in OtherBB.
794 for (;; --BBI) {
795 // Check to see if we find the matching store.
796 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
797 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +0000798 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000799 return false;
800 break;
801 }
802 // If we find something that may be using or overwriting the stored
803 // value, or if we run out of instructions, we can't do the xform.
804 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
805 BBI == OtherBB->begin())
806 return false;
807 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000808
Chris Lattnera65e2f72010-01-05 05:57:49 +0000809 // In order to eliminate the store in OtherBr, we have to
810 // make sure nothing reads or overwrites the stored value in
811 // StoreBB.
812 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
813 // FIXME: This should really be AA driven.
814 if (I->mayReadFromMemory() || I->mayWriteToMemory())
815 return false;
816 }
817 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000818
Chris Lattnera65e2f72010-01-05 05:57:49 +0000819 // Insert a PHI node now if we need it.
820 Value *MergedVal = OtherStore->getOperand(0);
821 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +0000822 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +0000823 PN->addIncoming(SI.getOperand(0), SI.getParent());
824 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
825 MergedVal = InsertNewInstBefore(PN, DestBB->front());
826 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000827
Chris Lattnera65e2f72010-01-05 05:57:49 +0000828 // Advance to a place where it is safe to insert the new store and
829 // insert it.
Bill Wendling8ddfc092011-08-16 20:45:24 +0000830 BBI = DestBB->getFirstInsertionPt();
Eli Friedman35211c62011-05-27 00:19:40 +0000831 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +0000832 SI.isVolatile(),
833 SI.getAlignment(),
834 SI.getOrdering(),
835 SI.getSynchScope());
Eli Friedman35211c62011-05-27 00:19:40 +0000836 InsertNewInstBefore(NewSI, *BBI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000837 NewSI->setDebugLoc(OtherStore->getDebugLoc());
Eli Friedman35211c62011-05-27 00:19:40 +0000838
Hal Finkelcc39b672014-07-24 12:16:19 +0000839 // If the two stores had AA tags, merge them.
840 AAMDNodes AATags;
841 SI.getAAMetadata(AATags);
842 if (AATags) {
843 OtherStore->getAAMetadata(AATags, /* Merge = */ true);
844 NewSI->setAAMetadata(AATags);
845 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000846
Chris Lattnera65e2f72010-01-05 05:57:49 +0000847 // Nuke the old stores.
848 EraseInstFromFunction(SI);
849 EraseInstFromFunction(*OtherStore);
850 return true;
851}