blob: 56212b04eb049ecc9bb8870ec87ac66528cf037c [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)) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000271 unsigned SourceAlign = getOrEnforceKnownAlignment(
272 Copy->getSource(), AI.getAlignment(), DL, AC, &AI, DT);
Eli Friedmanb14873c2012-11-26 23:04:53 +0000273 if (AI.getAlignment() <= SourceAlign) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000274 DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
275 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
276 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
277 EraseInstFromFunction(*ToDelete[i]);
278 Constant *TheSrc = cast<Constant>(Copy->getSource());
Matt Arsenaultbbf18c62013-12-07 02:58:45 +0000279 Constant *Cast
280 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
281 Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000282 EraseInstFromFunction(*Copy);
283 ++NumGlobalCopies;
284 return NewI;
285 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000286 }
287 }
288
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000289 // At last, use the generic allocation site handler to aggressively remove
290 // unused allocas.
291 return visitAllocSite(AI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000292}
293
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000294/// \brief Helper to combine a load to a new type.
295///
296/// This just does the work of combining a load to a new type. It handles
297/// metadata, etc., and returns the new instruction. The \c NewTy should be the
298/// loaded *value* type. This will convert it to a pointer, cast the operand to
299/// that pointer type, load it, etc.
300///
301/// Note that this will create all of the instructions with whatever insert
302/// point the \c InstCombiner currently is using.
303static LoadInst *combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy) {
304 Value *Ptr = LI.getPointerOperand();
305 unsigned AS = LI.getPointerAddressSpace();
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000306 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000307 LI.getAllMetadata(MD);
308
309 LoadInst *NewLoad = IC.Builder->CreateAlignedLoad(
310 IC.Builder->CreateBitCast(Ptr, NewTy->getPointerTo(AS)),
311 LI.getAlignment(), LI.getName());
312 for (const auto &MDPair : MD) {
313 unsigned ID = MDPair.first;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000314 MDNode *N = MDPair.second;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000315 // Note, essentially every kind of metadata should be preserved here! This
316 // routine is supposed to clone a load instruction changing *only its type*.
317 // The only metadata it makes sense to drop is metadata which is invalidated
318 // when the pointer type changes. This should essentially never be the case
319 // in LLVM, but we explicitly switch over only known metadata to be
320 // conservatively correct. If you are adding metadata to LLVM which pertains
321 // to loads, you almost certainly want to add it here.
322 switch (ID) {
323 case LLVMContext::MD_dbg:
324 case LLVMContext::MD_tbaa:
325 case LLVMContext::MD_prof:
326 case LLVMContext::MD_fpmath:
327 case LLVMContext::MD_tbaa_struct:
328 case LLVMContext::MD_invariant_load:
329 case LLVMContext::MD_alias_scope:
330 case LLVMContext::MD_noalias:
Philip Reames5a3f5f72014-10-21 00:13:20 +0000331 case LLVMContext::MD_nontemporal:
332 case LLVMContext::MD_mem_parallel_loop_access:
Philip Reamesb2d3f032014-10-21 21:00:03 +0000333 case LLVMContext::MD_nonnull:
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 Carruthfa11d832015-01-22 03:34:54 +0000347/// \brief Combine a store to a new type.
348///
349/// Returns the newly created store instruction.
350static StoreInst *combineStoreToNewValue(InstCombiner &IC, StoreInst &SI, Value *V) {
351 Value *Ptr = SI.getPointerOperand();
352 unsigned AS = SI.getPointerAddressSpace();
353 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
354 SI.getAllMetadata(MD);
355
356 StoreInst *NewStore = IC.Builder->CreateAlignedStore(
357 V, IC.Builder->CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
358 SI.getAlignment());
359 for (const auto &MDPair : MD) {
360 unsigned ID = MDPair.first;
361 MDNode *N = MDPair.second;
362 // Note, essentially every kind of metadata should be preserved here! This
363 // routine is supposed to clone a store instruction changing *only its
364 // type*. The only metadata it makes sense to drop is metadata which is
365 // invalidated when the pointer type changes. This should essentially
366 // never be the case in LLVM, but we explicitly switch over only known
367 // metadata to be conservatively correct. If you are adding metadata to
368 // LLVM which pertains to stores, you almost certainly want to add it
369 // here.
370 switch (ID) {
371 case LLVMContext::MD_dbg:
372 case LLVMContext::MD_tbaa:
373 case LLVMContext::MD_prof:
374 case LLVMContext::MD_fpmath:
375 case LLVMContext::MD_tbaa_struct:
376 case LLVMContext::MD_alias_scope:
377 case LLVMContext::MD_noalias:
378 case LLVMContext::MD_nontemporal:
379 case LLVMContext::MD_mem_parallel_loop_access:
380 case LLVMContext::MD_nonnull:
381 // All of these directly apply.
382 NewStore->setMetadata(ID, N);
383 break;
384
385 case LLVMContext::MD_invariant_load:
386 case LLVMContext::MD_range:
387 break;
388 }
389 }
390
391 return NewStore;
392}
393
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000394/// \brief Combine loads to match the type of value their uses after looking
395/// through intervening bitcasts.
396///
397/// The core idea here is that if the result of a load is used in an operation,
398/// we should load the type most conducive to that operation. For example, when
399/// loading an integer and converting that immediately to a pointer, we should
400/// instead directly load a pointer.
401///
402/// However, this routine must never change the width of a load or the number of
403/// loads as that would introduce a semantic change. This combine is expected to
404/// be a semantic no-op which just allows loads to more closely model the types
405/// of their consuming operations.
406///
407/// Currently, we also refuse to change the precise type used for an atomic load
408/// or a volatile load. This is debatable, and might be reasonable to change
409/// later. However, it is risky in case some backend or other part of LLVM is
410/// relying on the exact type loaded to select appropriate atomic operations.
411static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
412 // FIXME: We could probably with some care handle both volatile and atomic
413 // loads here but it isn't clear that this is important.
414 if (!LI.isSimple())
415 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000416
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000417 if (LI.use_empty())
418 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000419
Chris Lattnera65e2f72010-01-05 05:57:49 +0000420
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000421 // Fold away bit casts of the loaded value by loading the desired type.
422 if (LI.hasOneUse())
423 if (auto *BC = dyn_cast<BitCastInst>(LI.user_back())) {
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000424 LoadInst *NewLoad = combineLoadToNewType(IC, LI, BC->getDestTy());
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000425 BC->replaceAllUsesWith(NewLoad);
426 IC.EraseInstFromFunction(*BC);
427 return &LI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000428 }
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000429
Chandler Carrutha7f247e2014-12-09 19:21:16 +0000430 // FIXME: We should also canonicalize loads of vectors when their elements are
431 // cast to other types.
Craig Topperf40110f2014-04-25 05:29:35 +0000432 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000433}
434
435Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
436 Value *Op = LI.getOperand(0);
437
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000438 // Try to canonicalize the loaded type.
439 if (Instruction *Res = combineLoadToOperationType(*this, LI))
440 return Res;
441
Chris Lattnera65e2f72010-01-05 05:57:49 +0000442 // Attempt to improve the alignment.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000443 if (DL) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000444 unsigned KnownAlign = getOrEnforceKnownAlignment(
445 Op, DL->getPrefTypeAlignment(LI.getType()), DL, AC, &LI, DT);
Dan Gohman36196602010-08-03 18:20:32 +0000446 unsigned LoadAlign = LI.getAlignment();
447 unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000448 DL->getABITypeAlignment(LI.getType());
Dan Gohman36196602010-08-03 18:20:32 +0000449
450 if (KnownAlign > EffectiveLoadAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000451 LI.setAlignment(KnownAlign);
Dan Gohman36196602010-08-03 18:20:32 +0000452 else if (LoadAlign == 0)
453 LI.setAlignment(EffectiveLoadAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000454 }
455
Eli Friedman8bc586e2011-08-15 22:09:40 +0000456 // None of the following transforms are legal for volatile/atomic loads.
457 // FIXME: Some of it is okay for atomic loads; needs refactoring.
Craig Topperf40110f2014-04-25 05:29:35 +0000458 if (!LI.isSimple()) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000459
Chris Lattnera65e2f72010-01-05 05:57:49 +0000460 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +0000461 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +0000462 // separated by a few arithmetic operations.
463 BasicBlock::iterator BBI = &LI;
464 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000465 return ReplaceInstUsesWith(
Chandler Carruth1a3c2c42014-11-25 08:20:27 +0000466 LI, Builder->CreateBitOrPointerCast(AvailableVal, LI.getType(),
467 LI.getName() + ".cast"));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000468
469 // load(gep null, ...) -> unreachable
470 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
471 const Value *GEPI0 = GEPI->getOperand(0);
472 // TODO: Consider a target hook for valid address spaces for this xform.
473 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
474 // Insert a new store to null instruction before the load to indicate
475 // that this code is not reachable. We do this instead of inserting
476 // an unreachable instruction directly because we cannot modify the
477 // CFG.
478 new StoreInst(UndefValue::get(LI.getType()),
479 Constant::getNullValue(Op->getType()), &LI);
480 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
481 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000482 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000483
484 // load null/undef -> unreachable
485 // TODO: Consider a target hook for valid address spaces for this xform.
486 if (isa<UndefValue>(Op) ||
487 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
488 // Insert a new store to null instruction before the load to indicate that
489 // this code is not reachable. We do this instead of inserting an
490 // unreachable instruction directly because we cannot modify the CFG.
491 new StoreInst(UndefValue::get(LI.getType()),
492 Constant::getNullValue(Op->getType()), &LI);
493 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
494 }
495
Chris Lattnera65e2f72010-01-05 05:57:49 +0000496 if (Op->hasOneUse()) {
497 // Change select and PHI nodes to select values instead of addresses: this
498 // helps alias analysis out a lot, allows many others simplifications, and
499 // exposes redundancy in the code.
500 //
501 // Note that we cannot do the transformation unless we know that the
502 // introduced loads cannot trap! Something like this is valid as long as
503 // the condition is always false: load (select bool %C, int* null, int* %G),
504 // but it would not be valid if we transformed it to load from null
505 // unconditionally.
506 //
507 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
508 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +0000509 unsigned Align = LI.getAlignment();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000510 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, DL) &&
511 isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, DL)) {
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000512 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
Bob Wilson56600a12010-01-30 04:42:39 +0000513 SI->getOperand(1)->getName()+".val");
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000514 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
Bob Wilson56600a12010-01-30 04:42:39 +0000515 SI->getOperand(2)->getName()+".val");
516 V1->setAlignment(Align);
517 V2->setAlignment(Align);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000518 return SelectInst::Create(SI->getCondition(), V1, V2);
519 }
520
521 // load (select (cond, null, P)) -> load P
Philip Reames5ad26c32014-12-29 22:46:21 +0000522 if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
523 LI.getPointerAddressSpace() == 0) {
524 LI.setOperand(0, SI->getOperand(2));
525 return &LI;
526 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000527
528 // load (select (cond, P, null)) -> load P
Philip Reames5ad26c32014-12-29 22:46:21 +0000529 if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
530 LI.getPointerAddressSpace() == 0) {
531 LI.setOperand(0, SI->getOperand(1));
532 return &LI;
533 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000534 }
535 }
Craig Topperf40110f2014-04-25 05:29:35 +0000536 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000537}
538
Chandler Carruth816d26f2014-11-25 10:09:51 +0000539/// \brief Combine stores to match the type of value being stored.
540///
541/// The core idea here is that the memory does not have any intrinsic type and
542/// where we can we should match the type of a store to the type of value being
543/// stored.
544///
545/// However, this routine must never change the width of a store or the number of
546/// stores as that would introduce a semantic change. This combine is expected to
547/// be a semantic no-op which just allows stores to more closely model the types
548/// of their incoming values.
549///
550/// Currently, we also refuse to change the precise type used for an atomic or
551/// volatile store. This is debatable, and might be reasonable to change later.
552/// However, it is risky in case some backend or other part of LLVM is relying
553/// on the exact type stored to select appropriate atomic operations.
554///
555/// \returns true if the store was successfully combined away. This indicates
556/// the caller must erase the store instruction. We have to let the caller erase
557/// the store instruction sas otherwise there is no way to signal whether it was
558/// combined or not: IC.EraseInstFromFunction returns a null pointer.
559static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) {
560 // FIXME: We could probably with some care handle both volatile and atomic
561 // stores here but it isn't clear that this is important.
562 if (!SI.isSimple())
563 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000564
Chandler Carruth816d26f2014-11-25 10:09:51 +0000565 Value *V = SI.getValueOperand();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000566
Chandler Carruth816d26f2014-11-25 10:09:51 +0000567 // Fold away bit casts of the stored value by storing the original type.
568 if (auto *BC = dyn_cast<BitCastInst>(V)) {
Chandler Carrutha7f247e2014-12-09 19:21:16 +0000569 V = BC->getOperand(0);
Chandler Carruth2135b972015-01-21 23:45:01 +0000570 combineStoreToNewValue(IC, SI, V);
Chandler Carruth816d26f2014-11-25 10:09:51 +0000571 return true;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000572 }
573
Chandler Carruth816d26f2014-11-25 10:09:51 +0000574 // FIXME: We should also canonicalize loads of vectors when their elements are
575 // cast to other types.
576 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000577}
578
579/// equivalentAddressValues - Test if A and B will obviously have the same
580/// value. This includes recognizing that %t0 and %t1 will have the same
581/// value in code like this:
582/// %t0 = getelementptr \@a, 0, 3
583/// store i32 0, i32* %t0
584/// %t1 = getelementptr \@a, 0, 3
585/// %t2 = load i32* %t1
586///
587static bool equivalentAddressValues(Value *A, Value *B) {
588 // Test if the values are trivially equivalent.
589 if (A == B) return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000590
Chris Lattnera65e2f72010-01-05 05:57:49 +0000591 // Test if the values come form identical arithmetic instructions.
592 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
593 // its only used to compare two uses within the same basic block, which
594 // means that they'll always either have the same value or one of them
595 // will have an undefined value.
596 if (isa<BinaryOperator>(A) ||
597 isa<CastInst>(A) ||
598 isa<PHINode>(A) ||
599 isa<GetElementPtrInst>(A))
600 if (Instruction *BI = dyn_cast<Instruction>(B))
601 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
602 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000603
Chris Lattnera65e2f72010-01-05 05:57:49 +0000604 // Otherwise they may not be equivalent.
605 return false;
606}
607
Chris Lattnera65e2f72010-01-05 05:57:49 +0000608Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
609 Value *Val = SI.getOperand(0);
610 Value *Ptr = SI.getOperand(1);
611
Chandler Carruth816d26f2014-11-25 10:09:51 +0000612 // Try to canonicalize the stored type.
613 if (combineStoreToValueType(*this, SI))
614 return EraseInstFromFunction(SI);
615
Chris Lattnera65e2f72010-01-05 05:57:49 +0000616 // Attempt to improve the alignment.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000617 if (DL) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000618 unsigned KnownAlign = getOrEnforceKnownAlignment(
619 Ptr, DL->getPrefTypeAlignment(Val->getType()), DL, AC, &SI, DT);
Dan Gohman36196602010-08-03 18:20:32 +0000620 unsigned StoreAlign = SI.getAlignment();
621 unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000622 DL->getABITypeAlignment(Val->getType());
Dan Gohman36196602010-08-03 18:20:32 +0000623
Bill Wendling55b6b2b2012-03-16 18:20:54 +0000624 if (KnownAlign > EffectiveStoreAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000625 SI.setAlignment(KnownAlign);
Bill Wendling55b6b2b2012-03-16 18:20:54 +0000626 else if (StoreAlign == 0)
627 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000628 }
629
Eli Friedman8bc586e2011-08-15 22:09:40 +0000630 // Don't hack volatile/atomic stores.
631 // FIXME: Some bits are legal for atomic stores; needs refactoring.
Craig Topperf40110f2014-04-25 05:29:35 +0000632 if (!SI.isSimple()) return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +0000633
634 // If the RHS is an alloca with a single use, zapify the store, making the
635 // alloca dead.
636 if (Ptr->hasOneUse()) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000637 if (isa<AllocaInst>(Ptr))
Eli Friedman8bc586e2011-08-15 22:09:40 +0000638 return EraseInstFromFunction(SI);
639 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
640 if (isa<AllocaInst>(GEP->getOperand(0))) {
641 if (GEP->getOperand(0)->hasOneUse())
642 return EraseInstFromFunction(SI);
643 }
644 }
645 }
646
Chris Lattnera65e2f72010-01-05 05:57:49 +0000647 // Do really simple DSE, to catch cases where there are several consecutive
648 // stores to the same location, separated by a few arithmetic operations. This
649 // situation often occurs with bitfield accesses.
650 BasicBlock::iterator BBI = &SI;
651 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
652 --ScanInsts) {
653 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000654 // Don't count debug info directives, lest they affect codegen,
655 // and we skip pointer-to-pointer bitcasts, which are NOPs.
656 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000657 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000658 ScanInsts++;
659 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000660 }
661
Chris Lattnera65e2f72010-01-05 05:57:49 +0000662 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
663 // Prev store isn't volatile, and stores to the same location?
Eli Friedman8bc586e2011-08-15 22:09:40 +0000664 if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
665 SI.getOperand(1))) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000666 ++NumDeadStore;
667 ++BBI;
668 EraseInstFromFunction(*PrevSI);
669 continue;
670 }
671 break;
672 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000673
Chris Lattnera65e2f72010-01-05 05:57:49 +0000674 // If this is a load, we have to stop. However, if the loaded value is from
675 // the pointer we're loading and is producing the pointer we're storing,
676 // then *this* store is dead (X = load P; store X -> P).
677 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000678 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
Eli Friedman8bc586e2011-08-15 22:09:40 +0000679 LI->isSimple())
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000680 return EraseInstFromFunction(SI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000681
Chris Lattnera65e2f72010-01-05 05:57:49 +0000682 // Otherwise, this is a load from some other location. Stores before it
683 // may not be dead.
684 break;
685 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000686
Chris Lattnera65e2f72010-01-05 05:57:49 +0000687 // Don't skip over loads or things that can modify memory.
688 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
689 break;
690 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000691
692 // store X, null -> turns into 'unreachable' in SimplifyCFG
693 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
694 if (!isa<UndefValue>(Val)) {
695 SI.setOperand(0, UndefValue::get(Val->getType()));
696 if (Instruction *U = dyn_cast<Instruction>(Val))
697 Worklist.Add(U); // Dropped a use.
698 }
Craig Topperf40110f2014-04-25 05:29:35 +0000699 return nullptr; // Do not modify these!
Chris Lattnera65e2f72010-01-05 05:57:49 +0000700 }
701
702 // store undef, Ptr -> noop
703 if (isa<UndefValue>(Val))
704 return EraseInstFromFunction(SI);
705
Chris Lattnera65e2f72010-01-05 05:57:49 +0000706 // If this store is the last instruction in the basic block (possibly
Victor Hernandez5f5abd52010-01-21 23:07:15 +0000707 // excepting debug info instructions), and if the block ends with an
708 // unconditional branch, try to move it to the successor block.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000709 BBI = &SI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000710 do {
711 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000712 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000713 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000714 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
715 if (BI->isUnconditional())
716 if (SimplifyStoreAtEndOfBlock(SI))
Craig Topperf40110f2014-04-25 05:29:35 +0000717 return nullptr; // xform done!
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000718
Craig Topperf40110f2014-04-25 05:29:35 +0000719 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000720}
721
722/// SimplifyStoreAtEndOfBlock - Turn things like:
723/// if () { *P = v1; } else { *P = v2 }
724/// into a phi node with a store in the successor.
725///
726/// Simplify things like:
727/// *P = v1; if () { *P = v2; }
728/// into a phi node with a store in the successor.
729///
730bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
731 BasicBlock *StoreBB = SI.getParent();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000732
Chris Lattnera65e2f72010-01-05 05:57:49 +0000733 // Check to see if the successor block has exactly two incoming edges. If
734 // so, see if the other predecessor contains a store to the same location.
735 // if so, insert a PHI node (if needed) and move the stores down.
736 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000737
Chris Lattnera65e2f72010-01-05 05:57:49 +0000738 // Determine whether Dest has exactly two predecessors and, if so, compute
739 // the other predecessor.
740 pred_iterator PI = pred_begin(DestBB);
Gabor Greif1b787df2010-07-12 15:48:26 +0000741 BasicBlock *P = *PI;
Craig Topperf40110f2014-04-25 05:29:35 +0000742 BasicBlock *OtherBB = nullptr;
Gabor Greif1b787df2010-07-12 15:48:26 +0000743
744 if (P != StoreBB)
745 OtherBB = P;
746
747 if (++PI == pred_end(DestBB))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000748 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000749
Gabor Greif1b787df2010-07-12 15:48:26 +0000750 P = *PI;
751 if (P != StoreBB) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000752 if (OtherBB)
753 return false;
Gabor Greif1b787df2010-07-12 15:48:26 +0000754 OtherBB = P;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000755 }
756 if (++PI != pred_end(DestBB))
757 return false;
758
759 // Bail out if all the relevant blocks aren't distinct (this can happen,
760 // for example, if SI is in an infinite loop)
761 if (StoreBB == DestBB || OtherBB == DestBB)
762 return false;
763
764 // Verify that the other block ends in a branch and is not otherwise empty.
765 BasicBlock::iterator BBI = OtherBB->getTerminator();
766 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
767 if (!OtherBr || BBI == OtherBB->begin())
768 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000769
Chris Lattnera65e2f72010-01-05 05:57:49 +0000770 // If the other block ends in an unconditional branch, check for the 'if then
771 // else' case. there is an instruction before the branch.
Craig Topperf40110f2014-04-25 05:29:35 +0000772 StoreInst *OtherStore = nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000773 if (OtherBr->isUnconditional()) {
774 --BBI;
775 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000776 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000777 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000778 if (BBI==OtherBB->begin())
779 return false;
780 --BBI;
781 }
Eli Friedman8bc586e2011-08-15 22:09:40 +0000782 // If this isn't a store, isn't a store to the same location, or is not the
783 // right kind of store, bail out.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000784 OtherStore = dyn_cast<StoreInst>(BBI);
785 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +0000786 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000787 return false;
788 } else {
789 // Otherwise, the other block ended with a conditional branch. If one of the
790 // destinations is StoreBB, then we have the if/then case.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000791 if (OtherBr->getSuccessor(0) != StoreBB &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000792 OtherBr->getSuccessor(1) != StoreBB)
793 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000794
Chris Lattnera65e2f72010-01-05 05:57:49 +0000795 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
796 // if/then triangle. See if there is a store to the same ptr as SI that
797 // lives in OtherBB.
798 for (;; --BBI) {
799 // Check to see if we find the matching store.
800 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
801 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +0000802 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000803 return false;
804 break;
805 }
806 // If we find something that may be using or overwriting the stored
807 // value, or if we run out of instructions, we can't do the xform.
808 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
809 BBI == OtherBB->begin())
810 return false;
811 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000812
Chris Lattnera65e2f72010-01-05 05:57:49 +0000813 // In order to eliminate the store in OtherBr, we have to
814 // make sure nothing reads or overwrites the stored value in
815 // StoreBB.
816 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
817 // FIXME: This should really be AA driven.
818 if (I->mayReadFromMemory() || I->mayWriteToMemory())
819 return false;
820 }
821 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000822
Chris Lattnera65e2f72010-01-05 05:57:49 +0000823 // Insert a PHI node now if we need it.
824 Value *MergedVal = OtherStore->getOperand(0);
825 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +0000826 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +0000827 PN->addIncoming(SI.getOperand(0), SI.getParent());
828 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
829 MergedVal = InsertNewInstBefore(PN, DestBB->front());
830 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000831
Chris Lattnera65e2f72010-01-05 05:57:49 +0000832 // Advance to a place where it is safe to insert the new store and
833 // insert it.
Bill Wendling8ddfc092011-08-16 20:45:24 +0000834 BBI = DestBB->getFirstInsertionPt();
Eli Friedman35211c62011-05-27 00:19:40 +0000835 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +0000836 SI.isVolatile(),
837 SI.getAlignment(),
838 SI.getOrdering(),
839 SI.getSynchScope());
Eli Friedman35211c62011-05-27 00:19:40 +0000840 InsertNewInstBefore(NewSI, *BBI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000841 NewSI->setDebugLoc(OtherStore->getDebugLoc());
Eli Friedman35211c62011-05-27 00:19:40 +0000842
Hal Finkelcc39b672014-07-24 12:16:19 +0000843 // If the two stores had AA tags, merge them.
844 AAMDNodes AATags;
845 SI.getAAMetadata(AATags);
846 if (AATags) {
847 OtherStore->getAAMetadata(AATags, /* Merge = */ true);
848 NewSI->setAAMetadata(AATags);
849 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000850
Chris Lattnera65e2f72010-01-05 05:57:49 +0000851 // Nuke the old stores.
852 EraseInstFromFunction(SI);
853 EraseInstFromFunction(*OtherStore);
854 return true;
855}