blob: 3557ad72f49a1731a2ef32c59a0611fee01b06e6 [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"
Chandler Carruthbc6378d2014-10-19 10:46:46 +000018#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/IntrinsicInst.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000020#include "llvm/Transforms/Utils/BasicBlockUtils.h"
21#include "llvm/Transforms/Utils/Local.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000022using namespace llvm;
23
Chandler Carruth964daaa2014-04-22 02:55:47 +000024#define DEBUG_TYPE "instcombine"
25
Chandler Carruthc908ca12012-08-21 08:39:44 +000026STATISTIC(NumDeadStore, "Number of dead stores eliminated");
27STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
28
29/// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
30/// some part of a constant global variable. This intentionally only accepts
31/// constant expressions because we can't rewrite arbitrary instructions.
32static bool pointsToConstantGlobal(Value *V) {
33 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
34 return GV->isConstant();
Matt Arsenault607281772014-04-24 00:01:09 +000035
36 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000037 if (CE->getOpcode() == Instruction::BitCast ||
Matt Arsenault607281772014-04-24 00:01:09 +000038 CE->getOpcode() == Instruction::AddrSpaceCast ||
Chandler Carruthc908ca12012-08-21 08:39:44 +000039 CE->getOpcode() == Instruction::GetElementPtr)
40 return pointsToConstantGlobal(CE->getOperand(0));
Matt Arsenault607281772014-04-24 00:01:09 +000041 }
Chandler Carruthc908ca12012-08-21 08:39:44 +000042 return false;
43}
44
45/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
46/// pointer to an alloca. Ignore any reads of the pointer, return false if we
47/// see any stores or other unknown uses. If we see pointer arithmetic, keep
48/// track of whether it moves the pointer (with IsOffset) but otherwise traverse
49/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
50/// the alloca, and if the source pointer is a pointer to a constant global, we
51/// can optimize this.
52static bool
53isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Reid Kleckner813dab22014-07-01 21:36:20 +000054 SmallVectorImpl<Instruction *> &ToDelete) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000055 // We track lifetime intrinsics as we encounter them. If we decide to go
56 // ahead and replace the value with the global, this lets the caller quickly
57 // eliminate the markers.
58
Reid Kleckner813dab22014-07-01 21:36:20 +000059 SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect;
60 ValuesToInspect.push_back(std::make_pair(V, false));
61 while (!ValuesToInspect.empty()) {
62 auto ValuePair = ValuesToInspect.pop_back_val();
63 const bool IsOffset = ValuePair.second;
64 for (auto &U : ValuePair.first->uses()) {
65 Instruction *I = cast<Instruction>(U.getUser());
Chandler Carruthc908ca12012-08-21 08:39:44 +000066
Reid Kleckner813dab22014-07-01 21:36:20 +000067 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
68 // Ignore non-volatile loads, they are always ok.
69 if (!LI->isSimple()) return false;
Chandler Carruthc908ca12012-08-21 08:39:44 +000070 continue;
71 }
Reid Kleckner813dab22014-07-01 21:36:20 +000072
73 if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) {
74 // If uses of the bitcast are ok, we are ok.
75 ValuesToInspect.push_back(std::make_pair(I, IsOffset));
76 continue;
77 }
78 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
79 // If the GEP has all zero indices, it doesn't offset the pointer. If it
80 // doesn't, it does.
81 ValuesToInspect.push_back(
82 std::make_pair(I, IsOffset || !GEP->hasAllZeroIndices()));
83 continue;
84 }
85
86 if (CallSite CS = I) {
87 // If this is the function being called then we treat it like a load and
88 // ignore it.
89 if (CS.isCallee(&U))
90 continue;
91
92 // Inalloca arguments are clobbered by the call.
93 unsigned ArgNo = CS.getArgumentNo(&U);
94 if (CS.isInAllocaArgument(ArgNo))
95 return false;
96
97 // If this is a readonly/readnone call site, then we know it is just a
98 // load (but one that potentially returns the value itself), so we can
99 // ignore it if we know that the value isn't captured.
100 if (CS.onlyReadsMemory() &&
101 (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
102 continue;
103
104 // If this is being passed as a byval argument, the caller is making a
105 // copy, so it is only a read of the alloca.
106 if (CS.isByValArgument(ArgNo))
107 continue;
108 }
109
110 // Lifetime intrinsics can be handled by the caller.
111 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
112 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
113 II->getIntrinsicID() == Intrinsic::lifetime_end) {
114 assert(II->use_empty() && "Lifetime markers have no result to use!");
115 ToDelete.push_back(II);
116 continue;
117 }
118 }
119
120 // If this is isn't our memcpy/memmove, reject it as something we can't
121 // handle.
122 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
123 if (!MI)
124 return false;
125
126 // If the transfer is using the alloca as a source of the transfer, then
127 // ignore it since it is a load (unless the transfer is volatile).
128 if (U.getOperandNo() == 1) {
129 if (MI->isVolatile()) return false;
130 continue;
131 }
132
133 // If we already have seen a copy, reject the second one.
134 if (TheCopy) return false;
135
136 // If the pointer has been offset from the start of the alloca, we can't
137 // safely handle this.
138 if (IsOffset) return false;
139
140 // If the memintrinsic isn't using the alloca as the dest, reject it.
141 if (U.getOperandNo() != 0) return false;
142
143 // If the source of the memcpy/move is not a constant global, reject it.
144 if (!pointsToConstantGlobal(MI->getSource()))
145 return false;
146
147 // Otherwise, the transform is safe. Remember the copy instruction.
148 TheCopy = MI;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000149 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000150 }
151 return true;
152}
153
154/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
155/// modified by a copy from a constant global. If we can prove this, we can
156/// replace any uses of the alloca with uses of the global directly.
157static MemTransferInst *
158isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
159 SmallVectorImpl<Instruction *> &ToDelete) {
Craig Topperf40110f2014-04-25 05:29:35 +0000160 MemTransferInst *TheCopy = nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000161 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
162 return TheCopy;
Craig Topperf40110f2014-04-25 05:29:35 +0000163 return nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000164}
165
Chris Lattnera65e2f72010-01-05 05:57:49 +0000166Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Dan Gohmandf5d7dc2010-05-28 15:09:00 +0000167 // Ensure that the alloca array size argument has type intptr_t, so that
168 // any casting is exposed early.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000169 if (DL) {
170 Type *IntPtrTy = DL->getIntPtrType(AI.getType());
Dan Gohmandf5d7dc2010-05-28 15:09:00 +0000171 if (AI.getArraySize()->getType() != IntPtrTy) {
172 Value *V = Builder->CreateIntCast(AI.getArraySize(),
173 IntPtrTy, false);
174 AI.setOperand(0, V);
175 return &AI;
176 }
177 }
178
Chris Lattnera65e2f72010-01-05 05:57:49 +0000179 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
180 if (AI.isArrayAllocation()) { // Check C != 1
181 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000182 Type *NewTy =
Chris Lattnera65e2f72010-01-05 05:57:49 +0000183 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Craig Topperf40110f2014-04-25 05:29:35 +0000184 AllocaInst *New = Builder->CreateAlloca(NewTy, nullptr, AI.getName());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000185 New->setAlignment(AI.getAlignment());
186
187 // Scan to the end of the allocation instructions, to skip over a block of
188 // allocas if possible...also skip interleaved debug info
189 //
190 BasicBlock::iterator It = New;
191 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
192
193 // Now that I is pointing to the first non-allocation-inst in the block,
194 // insert our getelementptr instruction...
195 //
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000196 Type *IdxTy = DL
197 ? DL->getIntPtrType(AI.getType())
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +0000198 : Type::getInt64Ty(AI.getContext());
199 Value *NullIdx = Constant::getNullValue(IdxTy);
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000200 Value *Idx[2] = { NullIdx, NullIdx };
Eli Friedman41e509a2011-05-18 23:58:37 +0000201 Instruction *GEP =
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000202 GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
Eli Friedman41e509a2011-05-18 23:58:37 +0000203 InsertNewInstBefore(GEP, *It);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000204
205 // Now make everything use the getelementptr instead of the original
206 // allocation.
Eli Friedman41e509a2011-05-18 23:58:37 +0000207 return ReplaceInstUsesWith(AI, GEP);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000208 } else if (isa<UndefValue>(AI.getArraySize())) {
209 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
210 }
211 }
212
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000213 if (DL && AI.getAllocatedType()->isSized()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000214 // If the alignment is 0 (unspecified), assign it the preferred alignment.
215 if (AI.getAlignment() == 0)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000216 AI.setAlignment(DL->getPrefTypeAlignment(AI.getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000217
218 // Move all alloca's of zero byte objects to the entry block and merge them
219 // together. Note that we only do this for alloca's, because malloc should
220 // allocate and return a unique pointer, even for a zero byte allocation.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000221 if (DL->getTypeAllocSize(AI.getAllocatedType()) == 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000222 // For a zero sized alloca there is no point in doing an array allocation.
223 // This is helpful if the array size is a complicated expression not used
224 // elsewhere.
225 if (AI.isArrayAllocation()) {
226 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
227 return &AI;
228 }
229
230 // Get the first instruction in the entry block.
231 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
232 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
233 if (FirstInst != &AI) {
234 // If the entry block doesn't start with a zero-size alloca then move
235 // this one to the start of the entry block. There is no problem with
236 // dominance as the array size was forced to a constant earlier already.
237 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
238 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000239 DL->getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000240 AI.moveBefore(FirstInst);
241 return &AI;
242 }
243
Richard Osborneb68053e2012-09-18 09:31:44 +0000244 // If the alignment of the entry block alloca is 0 (unspecified),
245 // assign it the preferred alignment.
246 if (EntryAI->getAlignment() == 0)
247 EntryAI->setAlignment(
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000248 DL->getPrefTypeAlignment(EntryAI->getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000249 // Replace this zero-sized alloca with the one at the start of the entry
250 // block after ensuring that the address will be aligned enough for both
251 // types.
Richard Osborneb68053e2012-09-18 09:31:44 +0000252 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
253 AI.getAlignment());
Duncan Sands8bc764a2012-06-26 13:39:21 +0000254 EntryAI->setAlignment(MaxAlign);
255 if (AI.getType() != EntryAI->getType())
256 return new BitCastInst(EntryAI, AI.getType());
257 return ReplaceInstUsesWith(AI, EntryAI);
258 }
259 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000260 }
261
Eli Friedmanb14873c2012-11-26 23:04:53 +0000262 if (AI.getAlignment()) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000263 // Check to see if this allocation is only modified by a memcpy/memmove from
264 // a constant global whose alignment is equal to or exceeds that of the
265 // allocation. If this is the case, we can change all users to use
266 // the constant global instead. This is commonly produced by the CFE by
267 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
268 // is only subsequently read.
269 SmallVector<Instruction *, 4> ToDelete;
270 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
Eli Friedmanb14873c2012-11-26 23:04:53 +0000271 unsigned SourceAlign = getOrEnforceKnownAlignment(Copy->getSource(),
Hal Finkel60db0582014-09-07 18:57:58 +0000272 AI.getAlignment(),
273 DL, AT, &AI, DT);
Eli Friedmanb14873c2012-11-26 23:04:53 +0000274 if (AI.getAlignment() <= SourceAlign) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000275 DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
276 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
277 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
278 EraseInstFromFunction(*ToDelete[i]);
279 Constant *TheSrc = cast<Constant>(Copy->getSource());
Matt Arsenaultbbf18c62013-12-07 02:58:45 +0000280 Constant *Cast
281 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
282 Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000283 EraseInstFromFunction(*Copy);
284 ++NumGlobalCopies;
285 return NewI;
286 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000287 }
288 }
289
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000290 // At last, use the generic allocation site handler to aggressively remove
291 // unused allocas.
292 return visitAllocSite(AI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000293}
294
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000295/// \brief Helper to combine a load to a new type.
296///
297/// This just does the work of combining a load to a new type. It handles
298/// metadata, etc., and returns the new instruction. The \c NewTy should be the
299/// loaded *value* type. This will convert it to a pointer, cast the operand to
300/// that pointer type, load it, etc.
301///
302/// Note that this will create all of the instructions with whatever insert
303/// point the \c InstCombiner currently is using.
304static LoadInst *combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy) {
305 Value *Ptr = LI.getPointerOperand();
306 unsigned AS = LI.getPointerAddressSpace();
307 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
308 LI.getAllMetadata(MD);
309
310 LoadInst *NewLoad = IC.Builder->CreateAlignedLoad(
311 IC.Builder->CreateBitCast(Ptr, NewTy->getPointerTo(AS)),
312 LI.getAlignment(), LI.getName());
313 for (const auto &MDPair : MD) {
314 unsigned ID = MDPair.first;
315 MDNode *N = MDPair.second;
316 // Note, essentially every kind of metadata should be preserved here! This
317 // routine is supposed to clone a load instruction changing *only its type*.
318 // The only metadata it makes sense to drop is metadata which is invalidated
319 // when the pointer type changes. This should essentially never be the case
320 // in LLVM, but we explicitly switch over only known metadata to be
321 // conservatively correct. If you are adding metadata to LLVM which pertains
322 // to loads, you almost certainly want to add it here.
323 switch (ID) {
324 case LLVMContext::MD_dbg:
325 case LLVMContext::MD_tbaa:
326 case LLVMContext::MD_prof:
327 case LLVMContext::MD_fpmath:
328 case LLVMContext::MD_tbaa_struct:
329 case LLVMContext::MD_invariant_load:
330 case LLVMContext::MD_alias_scope:
331 case LLVMContext::MD_noalias:
Philip Reames5a3f5f72014-10-21 00:13:20 +0000332 case LLVMContext::MD_nontemporal:
333 case LLVMContext::MD_mem_parallel_loop_access:
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000334 // All of these directly apply.
335 NewLoad->setMetadata(ID, N);
336 break;
337
338 case LLVMContext::MD_range:
339 // FIXME: It would be nice to propagate this in some way, but the type
340 // conversions make it hard.
341 break;
342 }
343 }
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000344 return NewLoad;
345}
346
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000347/// \brief Combine loads to match the type of value their uses after looking
348/// through intervening bitcasts.
349///
350/// The core idea here is that if the result of a load is used in an operation,
351/// we should load the type most conducive to that operation. For example, when
352/// loading an integer and converting that immediately to a pointer, we should
353/// instead directly load a pointer.
354///
355/// However, this routine must never change the width of a load or the number of
356/// loads as that would introduce a semantic change. This combine is expected to
357/// be a semantic no-op which just allows loads to more closely model the types
358/// of their consuming operations.
359///
360/// Currently, we also refuse to change the precise type used for an atomic load
361/// or a volatile load. This is debatable, and might be reasonable to change
362/// later. However, it is risky in case some backend or other part of LLVM is
363/// relying on the exact type loaded to select appropriate atomic operations.
364static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
365 // FIXME: We could probably with some care handle both volatile and atomic
366 // loads here but it isn't clear that this is important.
367 if (!LI.isSimple())
368 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000369
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000370 if (LI.use_empty())
371 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000372
Chris Lattnera65e2f72010-01-05 05:57:49 +0000373
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000374 // Fold away bit casts of the loaded value by loading the desired type.
375 if (LI.hasOneUse())
376 if (auto *BC = dyn_cast<BitCastInst>(LI.user_back())) {
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000377 LoadInst *NewLoad = combineLoadToNewType(IC, LI, BC->getDestTy());
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000378 BC->replaceAllUsesWith(NewLoad);
379 IC.EraseInstFromFunction(*BC);
380 return &LI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000381 }
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000382
383 // FIXME: We should also canonicalize loads of vectors when their elements are
384 // cast to other types.
Craig Topperf40110f2014-04-25 05:29:35 +0000385 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000386}
387
388Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
389 Value *Op = LI.getOperand(0);
390
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000391 // Try to canonicalize the loaded type.
392 if (Instruction *Res = combineLoadToOperationType(*this, LI))
393 return Res;
394
Chris Lattnera65e2f72010-01-05 05:57:49 +0000395 // Attempt to improve the alignment.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000396 if (DL) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000397 unsigned KnownAlign =
Hal Finkel60db0582014-09-07 18:57:58 +0000398 getOrEnforceKnownAlignment(Op, DL->getPrefTypeAlignment(LI.getType()),
399 DL, AT, &LI, DT);
Dan Gohman36196602010-08-03 18:20:32 +0000400 unsigned LoadAlign = LI.getAlignment();
401 unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000402 DL->getABITypeAlignment(LI.getType());
Dan Gohman36196602010-08-03 18:20:32 +0000403
404 if (KnownAlign > EffectiveLoadAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000405 LI.setAlignment(KnownAlign);
Dan Gohman36196602010-08-03 18:20:32 +0000406 else if (LoadAlign == 0)
407 LI.setAlignment(EffectiveLoadAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000408 }
409
Eli Friedman8bc586e2011-08-15 22:09:40 +0000410 // None of the following transforms are legal for volatile/atomic loads.
411 // FIXME: Some of it is okay for atomic loads; needs refactoring.
Craig Topperf40110f2014-04-25 05:29:35 +0000412 if (!LI.isSimple()) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000413
Chris Lattnera65e2f72010-01-05 05:57:49 +0000414 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +0000415 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +0000416 // separated by a few arithmetic operations.
417 BasicBlock::iterator BBI = &LI;
418 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000419 return ReplaceInstUsesWith(
420 LI, Builder->CreateBitCast(AvailableVal, LI.getType()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000421
422 // load(gep null, ...) -> unreachable
423 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
424 const Value *GEPI0 = GEPI->getOperand(0);
425 // TODO: Consider a target hook for valid address spaces for this xform.
426 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
427 // Insert a new store to null instruction before the load to indicate
428 // that this code is not reachable. We do this instead of inserting
429 // an unreachable instruction directly because we cannot modify the
430 // CFG.
431 new StoreInst(UndefValue::get(LI.getType()),
432 Constant::getNullValue(Op->getType()), &LI);
433 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
434 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000435 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000436
437 // load null/undef -> unreachable
438 // TODO: Consider a target hook for valid address spaces for this xform.
439 if (isa<UndefValue>(Op) ||
440 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
441 // Insert a new store to null instruction before the load to indicate that
442 // this code is not reachable. We do this instead of inserting an
443 // unreachable instruction directly because we cannot modify the CFG.
444 new StoreInst(UndefValue::get(LI.getType()),
445 Constant::getNullValue(Op->getType()), &LI);
446 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
447 }
448
Chris Lattnera65e2f72010-01-05 05:57:49 +0000449 if (Op->hasOneUse()) {
450 // Change select and PHI nodes to select values instead of addresses: this
451 // helps alias analysis out a lot, allows many others simplifications, and
452 // exposes redundancy in the code.
453 //
454 // Note that we cannot do the transformation unless we know that the
455 // introduced loads cannot trap! Something like this is valid as long as
456 // the condition is always false: load (select bool %C, int* null, int* %G),
457 // but it would not be valid if we transformed it to load from null
458 // unconditionally.
459 //
460 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
461 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +0000462 unsigned Align = LI.getAlignment();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000463 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, DL) &&
464 isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, DL)) {
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000465 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
Bob Wilson56600a12010-01-30 04:42:39 +0000466 SI->getOperand(1)->getName()+".val");
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000467 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
Bob Wilson56600a12010-01-30 04:42:39 +0000468 SI->getOperand(2)->getName()+".val");
469 V1->setAlignment(Align);
470 V2->setAlignment(Align);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000471 return SelectInst::Create(SI->getCondition(), V1, V2);
472 }
473
474 // load (select (cond, null, P)) -> load P
475 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
476 if (C->isNullValue()) {
477 LI.setOperand(0, SI->getOperand(2));
478 return &LI;
479 }
480
481 // load (select (cond, P, null)) -> load P
482 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
483 if (C->isNullValue()) {
484 LI.setOperand(0, SI->getOperand(1));
485 return &LI;
486 }
487 }
488 }
Craig Topperf40110f2014-04-25 05:29:35 +0000489 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000490}
491
492/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
493/// when possible. This makes it generally easy to do alias analysis and/or
494/// SROA/mem2reg of the memory object.
495static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
496 User *CI = cast<User>(SI.getOperand(1));
497 Value *CastOp = CI->getOperand(0);
498
Matt Arsenaultd0d6c0b2014-07-14 17:24:38 +0000499 Type *DestPTy = CI->getType()->getPointerElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000500 PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
Craig Topperf40110f2014-04-25 05:29:35 +0000501 if (!SrcTy) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000502
Chris Lattner229907c2011-07-18 04:54:35 +0000503 Type *SrcPTy = SrcTy->getElementType();
Chris Lattnera65e2f72010-01-05 05:57:49 +0000504
Duncan Sands19d0b472010-02-16 11:11:14 +0000505 if (!DestPTy->isIntegerTy() && !DestPTy->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000506 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000507
Chris Lattnera65e2f72010-01-05 05:57:49 +0000508 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
509 /// to its first element. This allows us to handle things like:
510 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
511 /// on 32-bit hosts.
512 SmallVector<Value*, 4> NewGEPIndices;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000513
Chris Lattnera65e2f72010-01-05 05:57:49 +0000514 // If the source is an array, the code below will not succeed. Check to
515 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
516 // constants.
Duncan Sands19d0b472010-02-16 11:11:14 +0000517 if (SrcPTy->isArrayTy() || SrcPTy->isStructTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000518 // Index through pointer.
519 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
520 NewGEPIndices.push_back(Zero);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000521
Chris Lattnera65e2f72010-01-05 05:57:49 +0000522 while (1) {
Chris Lattner229907c2011-07-18 04:54:35 +0000523 if (StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000524 if (!STy->getNumElements()) /* Struct can be empty {} */
525 break;
526 NewGEPIndices.push_back(Zero);
527 SrcPTy = STy->getElementType(0);
Chris Lattner229907c2011-07-18 04:54:35 +0000528 } else if (ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000529 NewGEPIndices.push_back(Zero);
530 SrcPTy = ATy->getElementType();
531 } else {
532 break;
533 }
534 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000535
Chris Lattnera65e2f72010-01-05 05:57:49 +0000536 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
537 }
538
Duncan Sands19d0b472010-02-16 11:11:14 +0000539 if (!SrcPTy->isIntegerTy() && !SrcPTy->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000540 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000541
Richard Osborne0af4aa92014-03-25 17:21:41 +0000542 // If the pointers point into different address spaces don't do the
543 // transformation.
Matt Arsenaultd0d6c0b2014-07-14 17:24:38 +0000544 if (SrcTy->getAddressSpace() != CI->getType()->getPointerAddressSpace())
Craig Topperf40110f2014-04-25 05:29:35 +0000545 return nullptr;
Richard Osborne0af4aa92014-03-25 17:21:41 +0000546
547 // If the pointers point to values of different sizes don't do the
548 // transformation.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000549 if (!IC.getDataLayout() ||
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000550 IC.getDataLayout()->getTypeSizeInBits(SrcPTy) !=
551 IC.getDataLayout()->getTypeSizeInBits(DestPTy))
Craig Topperf40110f2014-04-25 05:29:35 +0000552 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000553
Richard Osborne0af4aa92014-03-25 17:21:41 +0000554 // If the pointers point to pointers to different address spaces don't do the
555 // transformation. It is not safe to introduce an addrspacecast instruction in
556 // this case since, depending on the target, addrspacecast may not be a no-op
557 // cast.
558 if (SrcPTy->isPointerTy() && DestPTy->isPointerTy() &&
559 SrcPTy->getPointerAddressSpace() != DestPTy->getPointerAddressSpace())
Craig Topperf40110f2014-04-25 05:29:35 +0000560 return nullptr;
Richard Osborne0af4aa92014-03-25 17:21:41 +0000561
Chris Lattnera65e2f72010-01-05 05:57:49 +0000562 // Okay, we are casting from one integer or pointer type to another of
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000563 // the same size. Instead of casting the pointer before
Chris Lattnera65e2f72010-01-05 05:57:49 +0000564 // the store, cast the value to be stored.
565 Value *NewCast;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000566 Instruction::CastOps opcode = Instruction::BitCast;
Richard Osborne9805ec42014-03-25 17:21:35 +0000567 Type* CastSrcTy = DestPTy;
Chris Lattner229907c2011-07-18 04:54:35 +0000568 Type* CastDstTy = SrcPTy;
Duncan Sands19d0b472010-02-16 11:11:14 +0000569 if (CastDstTy->isPointerTy()) {
Duncan Sands9dff9be2010-02-15 16:12:20 +0000570 if (CastSrcTy->isIntegerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000571 opcode = Instruction::IntToPtr;
Duncan Sands19d0b472010-02-16 11:11:14 +0000572 } else if (CastDstTy->isIntegerTy()) {
Richard Osborne9805ec42014-03-25 17:21:35 +0000573 if (CastSrcTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000574 opcode = Instruction::PtrToInt;
575 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000576
Chris Lattnera65e2f72010-01-05 05:57:49 +0000577 // SIOp0 is a pointer to aggregate and this is a store to the first field,
578 // emit a GEP to index into its first field.
579 if (!NewGEPIndices.empty())
Jay Foad040dd822011-07-22 08:16:57 +0000580 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000581
Richard Osborne9805ec42014-03-25 17:21:35 +0000582 Value *SIOp0 = SI.getOperand(0);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000583 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
584 SIOp0->getName()+".c");
Dan Gohman2e20dfb2010-10-25 16:16:27 +0000585 SI.setOperand(0, NewCast);
586 SI.setOperand(1, CastOp);
587 return &SI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000588}
589
590/// equivalentAddressValues - Test if A and B will obviously have the same
591/// value. This includes recognizing that %t0 and %t1 will have the same
592/// value in code like this:
593/// %t0 = getelementptr \@a, 0, 3
594/// store i32 0, i32* %t0
595/// %t1 = getelementptr \@a, 0, 3
596/// %t2 = load i32* %t1
597///
598static bool equivalentAddressValues(Value *A, Value *B) {
599 // Test if the values are trivially equivalent.
600 if (A == B) return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000601
Chris Lattnera65e2f72010-01-05 05:57:49 +0000602 // Test if the values come form identical arithmetic instructions.
603 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
604 // its only used to compare two uses within the same basic block, which
605 // means that they'll always either have the same value or one of them
606 // will have an undefined value.
607 if (isa<BinaryOperator>(A) ||
608 isa<CastInst>(A) ||
609 isa<PHINode>(A) ||
610 isa<GetElementPtrInst>(A))
611 if (Instruction *BI = dyn_cast<Instruction>(B))
612 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
613 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000614
Chris Lattnera65e2f72010-01-05 05:57:49 +0000615 // Otherwise they may not be equivalent.
616 return false;
617}
618
Chris Lattnera65e2f72010-01-05 05:57:49 +0000619Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
620 Value *Val = SI.getOperand(0);
621 Value *Ptr = SI.getOperand(1);
622
Chris Lattnera65e2f72010-01-05 05:57:49 +0000623 // Attempt to improve the alignment.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000624 if (DL) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000625 unsigned KnownAlign =
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000626 getOrEnforceKnownAlignment(Ptr, DL->getPrefTypeAlignment(Val->getType()),
Hal Finkel60db0582014-09-07 18:57:58 +0000627 DL, AT, &SI, DT);
Dan Gohman36196602010-08-03 18:20:32 +0000628 unsigned StoreAlign = SI.getAlignment();
629 unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000630 DL->getABITypeAlignment(Val->getType());
Dan Gohman36196602010-08-03 18:20:32 +0000631
Bill Wendling55b6b2b2012-03-16 18:20:54 +0000632 if (KnownAlign > EffectiveStoreAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000633 SI.setAlignment(KnownAlign);
Bill Wendling55b6b2b2012-03-16 18:20:54 +0000634 else if (StoreAlign == 0)
635 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000636 }
637
Eli Friedman8bc586e2011-08-15 22:09:40 +0000638 // Don't hack volatile/atomic stores.
639 // FIXME: Some bits are legal for atomic stores; needs refactoring.
Craig Topperf40110f2014-04-25 05:29:35 +0000640 if (!SI.isSimple()) return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +0000641
642 // If the RHS is an alloca with a single use, zapify the store, making the
643 // alloca dead.
644 if (Ptr->hasOneUse()) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000645 if (isa<AllocaInst>(Ptr))
Eli Friedman8bc586e2011-08-15 22:09:40 +0000646 return EraseInstFromFunction(SI);
647 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
648 if (isa<AllocaInst>(GEP->getOperand(0))) {
649 if (GEP->getOperand(0)->hasOneUse())
650 return EraseInstFromFunction(SI);
651 }
652 }
653 }
654
Chris Lattnera65e2f72010-01-05 05:57:49 +0000655 // Do really simple DSE, to catch cases where there are several consecutive
656 // stores to the same location, separated by a few arithmetic operations. This
657 // situation often occurs with bitfield accesses.
658 BasicBlock::iterator BBI = &SI;
659 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
660 --ScanInsts) {
661 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000662 // Don't count debug info directives, lest they affect codegen,
663 // and we skip pointer-to-pointer bitcasts, which are NOPs.
664 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000665 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000666 ScanInsts++;
667 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000668 }
669
Chris Lattnera65e2f72010-01-05 05:57:49 +0000670 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
671 // Prev store isn't volatile, and stores to the same location?
Eli Friedman8bc586e2011-08-15 22:09:40 +0000672 if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
673 SI.getOperand(1))) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000674 ++NumDeadStore;
675 ++BBI;
676 EraseInstFromFunction(*PrevSI);
677 continue;
678 }
679 break;
680 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000681
Chris Lattnera65e2f72010-01-05 05:57:49 +0000682 // If this is a load, we have to stop. However, if the loaded value is from
683 // the pointer we're loading and is producing the pointer we're storing,
684 // then *this* store is dead (X = load P; store X -> P).
685 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000686 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
Eli Friedman8bc586e2011-08-15 22:09:40 +0000687 LI->isSimple())
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000688 return EraseInstFromFunction(SI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000689
Chris Lattnera65e2f72010-01-05 05:57:49 +0000690 // Otherwise, this is a load from some other location. Stores before it
691 // may not be dead.
692 break;
693 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000694
Chris Lattnera65e2f72010-01-05 05:57:49 +0000695 // Don't skip over loads or things that can modify memory.
696 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
697 break;
698 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000699
700 // store X, null -> turns into 'unreachable' in SimplifyCFG
701 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
702 if (!isa<UndefValue>(Val)) {
703 SI.setOperand(0, UndefValue::get(Val->getType()));
704 if (Instruction *U = dyn_cast<Instruction>(Val))
705 Worklist.Add(U); // Dropped a use.
706 }
Craig Topperf40110f2014-04-25 05:29:35 +0000707 return nullptr; // Do not modify these!
Chris Lattnera65e2f72010-01-05 05:57:49 +0000708 }
709
710 // store undef, Ptr -> noop
711 if (isa<UndefValue>(Val))
712 return EraseInstFromFunction(SI);
713
714 // If the pointer destination is a cast, see if we can fold the cast into the
715 // source instead.
716 if (isa<CastInst>(Ptr))
717 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
718 return Res;
719 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
720 if (CE->isCast())
721 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
722 return Res;
723
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000724
Chris Lattnera65e2f72010-01-05 05:57:49 +0000725 // If this store is the last instruction in the basic block (possibly
Victor Hernandez5f5abd52010-01-21 23:07:15 +0000726 // excepting debug info instructions), and if the block ends with an
727 // unconditional branch, try to move it to the successor block.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000728 BBI = &SI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000729 do {
730 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000731 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000732 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000733 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
734 if (BI->isUnconditional())
735 if (SimplifyStoreAtEndOfBlock(SI))
Craig Topperf40110f2014-04-25 05:29:35 +0000736 return nullptr; // xform done!
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000737
Craig Topperf40110f2014-04-25 05:29:35 +0000738 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000739}
740
741/// SimplifyStoreAtEndOfBlock - Turn things like:
742/// if () { *P = v1; } else { *P = v2 }
743/// into a phi node with a store in the successor.
744///
745/// Simplify things like:
746/// *P = v1; if () { *P = v2; }
747/// into a phi node with a store in the successor.
748///
749bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
750 BasicBlock *StoreBB = SI.getParent();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000751
Chris Lattnera65e2f72010-01-05 05:57:49 +0000752 // Check to see if the successor block has exactly two incoming edges. If
753 // so, see if the other predecessor contains a store to the same location.
754 // if so, insert a PHI node (if needed) and move the stores down.
755 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000756
Chris Lattnera65e2f72010-01-05 05:57:49 +0000757 // Determine whether Dest has exactly two predecessors and, if so, compute
758 // the other predecessor.
759 pred_iterator PI = pred_begin(DestBB);
Gabor Greif1b787df2010-07-12 15:48:26 +0000760 BasicBlock *P = *PI;
Craig Topperf40110f2014-04-25 05:29:35 +0000761 BasicBlock *OtherBB = nullptr;
Gabor Greif1b787df2010-07-12 15:48:26 +0000762
763 if (P != StoreBB)
764 OtherBB = P;
765
766 if (++PI == pred_end(DestBB))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000767 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000768
Gabor Greif1b787df2010-07-12 15:48:26 +0000769 P = *PI;
770 if (P != StoreBB) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000771 if (OtherBB)
772 return false;
Gabor Greif1b787df2010-07-12 15:48:26 +0000773 OtherBB = P;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000774 }
775 if (++PI != pred_end(DestBB))
776 return false;
777
778 // Bail out if all the relevant blocks aren't distinct (this can happen,
779 // for example, if SI is in an infinite loop)
780 if (StoreBB == DestBB || OtherBB == DestBB)
781 return false;
782
783 // Verify that the other block ends in a branch and is not otherwise empty.
784 BasicBlock::iterator BBI = OtherBB->getTerminator();
785 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
786 if (!OtherBr || BBI == OtherBB->begin())
787 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000788
Chris Lattnera65e2f72010-01-05 05:57:49 +0000789 // If the other block ends in an unconditional branch, check for the 'if then
790 // else' case. there is an instruction before the branch.
Craig Topperf40110f2014-04-25 05:29:35 +0000791 StoreInst *OtherStore = nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000792 if (OtherBr->isUnconditional()) {
793 --BBI;
794 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000795 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000796 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000797 if (BBI==OtherBB->begin())
798 return false;
799 --BBI;
800 }
Eli Friedman8bc586e2011-08-15 22:09:40 +0000801 // If this isn't a store, isn't a store to the same location, or is not the
802 // right kind of store, bail out.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000803 OtherStore = dyn_cast<StoreInst>(BBI);
804 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +0000805 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000806 return false;
807 } else {
808 // Otherwise, the other block ended with a conditional branch. If one of the
809 // destinations is StoreBB, then we have the if/then case.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000810 if (OtherBr->getSuccessor(0) != StoreBB &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000811 OtherBr->getSuccessor(1) != StoreBB)
812 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000813
Chris Lattnera65e2f72010-01-05 05:57:49 +0000814 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
815 // if/then triangle. See if there is a store to the same ptr as SI that
816 // lives in OtherBB.
817 for (;; --BBI) {
818 // Check to see if we find the matching store.
819 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
820 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +0000821 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000822 return false;
823 break;
824 }
825 // If we find something that may be using or overwriting the stored
826 // value, or if we run out of instructions, we can't do the xform.
827 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
828 BBI == OtherBB->begin())
829 return false;
830 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000831
Chris Lattnera65e2f72010-01-05 05:57:49 +0000832 // In order to eliminate the store in OtherBr, we have to
833 // make sure nothing reads or overwrites the stored value in
834 // StoreBB.
835 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
836 // FIXME: This should really be AA driven.
837 if (I->mayReadFromMemory() || I->mayWriteToMemory())
838 return false;
839 }
840 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000841
Chris Lattnera65e2f72010-01-05 05:57:49 +0000842 // Insert a PHI node now if we need it.
843 Value *MergedVal = OtherStore->getOperand(0);
844 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +0000845 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +0000846 PN->addIncoming(SI.getOperand(0), SI.getParent());
847 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
848 MergedVal = InsertNewInstBefore(PN, DestBB->front());
849 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000850
Chris Lattnera65e2f72010-01-05 05:57:49 +0000851 // Advance to a place where it is safe to insert the new store and
852 // insert it.
Bill Wendling8ddfc092011-08-16 20:45:24 +0000853 BBI = DestBB->getFirstInsertionPt();
Eli Friedman35211c62011-05-27 00:19:40 +0000854 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +0000855 SI.isVolatile(),
856 SI.getAlignment(),
857 SI.getOrdering(),
858 SI.getSynchScope());
Eli Friedman35211c62011-05-27 00:19:40 +0000859 InsertNewInstBefore(NewSI, *BBI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000860 NewSI->setDebugLoc(OtherStore->getDebugLoc());
Eli Friedman35211c62011-05-27 00:19:40 +0000861
Hal Finkelcc39b672014-07-24 12:16:19 +0000862 // If the two stores had AA tags, merge them.
863 AAMDNodes AATags;
864 SI.getAAMetadata(AATags);
865 if (AATags) {
866 OtherStore->getAAMetadata(AATags, /* Merge = */ true);
867 NewSI->setAAMetadata(AATags);
868 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000869
Chris Lattnera65e2f72010-01-05 05:57:49 +0000870 // Nuke the old stores.
871 EraseInstFromFunction(SI);
872 EraseInstFromFunction(*OtherStore);
873 return true;
874}