blob: 58c61e7de9fb17477a319088991cdaa86cd897f5 [file] [log] [blame]
Chris Lattnera65e2f72010-01-05 05:57:49 +00001//===- InstCombineLoadStoreAlloca.cpp -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visit functions for load, store and alloca.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/Statistic.h"
Dan Gohman826bdf82010-05-28 16:19:17 +000016#include "llvm/Analysis/Loads.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/DataLayout.h"
18#include "llvm/IR/IntrinsicInst.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000019#include "llvm/Transforms/Utils/BasicBlockUtils.h"
20#include "llvm/Transforms/Utils/Local.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000021using namespace llvm;
22
Chandler Carruthc908ca12012-08-21 08:39:44 +000023STATISTIC(NumDeadStore, "Number of dead stores eliminated");
24STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
25
26/// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
27/// some part of a constant global variable. This intentionally only accepts
28/// constant expressions because we can't rewrite arbitrary instructions.
29static bool pointsToConstantGlobal(Value *V) {
30 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
31 return GV->isConstant();
32 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
33 if (CE->getOpcode() == Instruction::BitCast ||
34 CE->getOpcode() == Instruction::GetElementPtr)
35 return pointsToConstantGlobal(CE->getOperand(0));
36 return false;
37}
38
39/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
40/// pointer to an alloca. Ignore any reads of the pointer, return false if we
41/// see any stores or other unknown uses. If we see pointer arithmetic, keep
42/// track of whether it moves the pointer (with IsOffset) but otherwise traverse
43/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
44/// the alloca, and if the source pointer is a pointer to a constant global, we
45/// can optimize this.
46static bool
47isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
48 SmallVectorImpl<Instruction *> &ToDelete,
49 bool IsOffset = false) {
50 // We track lifetime intrinsics as we encounter them. If we decide to go
51 // ahead and replace the value with the global, this lets the caller quickly
52 // eliminate the markers.
53
54 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
55 User *U = cast<Instruction>(*UI);
56
57 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
58 // Ignore non-volatile loads, they are always ok.
59 if (!LI->isSimple()) return false;
60 continue;
61 }
62
63 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
64 // If uses of the bitcast are ok, we are ok.
65 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, ToDelete, IsOffset))
66 return false;
67 continue;
68 }
69 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
70 // If the GEP has all zero indices, it doesn't offset the pointer. If it
71 // doesn't, it does.
Jim Grosbachbdbd7342013-04-05 21:20:12 +000072 if (!isOnlyCopiedFromConstantGlobal(
73 GEP, TheCopy, ToDelete, IsOffset || !GEP->hasAllZeroIndices()))
Chandler Carruthc908ca12012-08-21 08:39:44 +000074 return false;
75 continue;
76 }
77
78 if (CallSite CS = U) {
79 // If this is the function being called then we treat it like a load and
80 // ignore it.
81 if (CS.isCallee(UI))
82 continue;
83
84 // If this is a readonly/readnone call site, then we know it is just a
85 // load (but one that potentially returns the value itself), so we can
86 // ignore it if we know that the value isn't captured.
87 unsigned ArgNo = CS.getArgumentNo(UI);
88 if (CS.onlyReadsMemory() &&
89 (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
90 continue;
91
92 // If this is being passed as a byval argument, the caller is making a
93 // copy, so it is only a read of the alloca.
94 if (CS.isByValArgument(ArgNo))
95 continue;
96 }
97
98 // Lifetime intrinsics can be handled by the caller.
99 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
100 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
101 II->getIntrinsicID() == Intrinsic::lifetime_end) {
102 assert(II->use_empty() && "Lifetime markers have no result to use!");
103 ToDelete.push_back(II);
104 continue;
105 }
106 }
107
108 // If this is isn't our memcpy/memmove, reject it as something we can't
109 // handle.
110 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
111 if (MI == 0)
112 return false;
113
114 // If the transfer is using the alloca as a source of the transfer, then
115 // ignore it since it is a load (unless the transfer is volatile).
116 if (UI.getOperandNo() == 1) {
117 if (MI->isVolatile()) return false;
118 continue;
119 }
120
121 // If we already have seen a copy, reject the second one.
122 if (TheCopy) return false;
123
124 // If the pointer has been offset from the start of the alloca, we can't
125 // safely handle this.
126 if (IsOffset) return false;
127
128 // If the memintrinsic isn't using the alloca as the dest, reject it.
129 if (UI.getOperandNo() != 0) return false;
130
131 // If the source of the memcpy/move is not a constant global, reject it.
132 if (!pointsToConstantGlobal(MI->getSource()))
133 return false;
134
135 // Otherwise, the transform is safe. Remember the copy instruction.
136 TheCopy = MI;
137 }
138 return true;
139}
140
141/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
142/// modified by a copy from a constant global. If we can prove this, we can
143/// replace any uses of the alloca with uses of the global directly.
144static MemTransferInst *
145isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
146 SmallVectorImpl<Instruction *> &ToDelete) {
147 MemTransferInst *TheCopy = 0;
148 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
149 return TheCopy;
150 return 0;
151}
152
Chris Lattnera65e2f72010-01-05 05:57:49 +0000153Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Dan Gohmandf5d7dc2010-05-28 15:09:00 +0000154 // Ensure that the alloca array size argument has type intptr_t, so that
155 // any casting is exposed early.
156 if (TD) {
Chandler Carruth7ec50852012-11-01 08:07:29 +0000157 Type *IntPtrTy = TD->getIntPtrType(AI.getContext());
Dan Gohmandf5d7dc2010-05-28 15:09:00 +0000158 if (AI.getArraySize()->getType() != IntPtrTy) {
159 Value *V = Builder->CreateIntCast(AI.getArraySize(),
160 IntPtrTy, false);
161 AI.setOperand(0, V);
162 return &AI;
163 }
164 }
165
Chris Lattnera65e2f72010-01-05 05:57:49 +0000166 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
167 if (AI.isArrayAllocation()) { // Check C != 1
168 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000169 Type *NewTy =
Chris Lattnera65e2f72010-01-05 05:57:49 +0000170 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000171 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
172 New->setAlignment(AI.getAlignment());
173
174 // Scan to the end of the allocation instructions, to skip over a block of
175 // allocas if possible...also skip interleaved debug info
176 //
177 BasicBlock::iterator It = New;
178 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
179
180 // Now that I is pointing to the first non-allocation-inst in the block,
181 // insert our getelementptr instruction...
182 //
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +0000183 Type *IdxTy = TD
184 ? TD->getIntPtrType(AI.getContext())
185 : Type::getInt64Ty(AI.getContext());
186 Value *NullIdx = Constant::getNullValue(IdxTy);
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000187 Value *Idx[2] = { NullIdx, NullIdx };
Eli Friedman41e509a2011-05-18 23:58:37 +0000188 Instruction *GEP =
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000189 GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
Eli Friedman41e509a2011-05-18 23:58:37 +0000190 InsertNewInstBefore(GEP, *It);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000191
192 // Now make everything use the getelementptr instead of the original
193 // allocation.
Eli Friedman41e509a2011-05-18 23:58:37 +0000194 return ReplaceInstUsesWith(AI, GEP);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000195 } else if (isa<UndefValue>(AI.getArraySize())) {
196 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
197 }
198 }
199
Duncan Sands8bc764a2012-06-26 13:39:21 +0000200 if (TD && AI.getAllocatedType()->isSized()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000201 // If the alignment is 0 (unspecified), assign it the preferred alignment.
202 if (AI.getAlignment() == 0)
203 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000204
205 // Move all alloca's of zero byte objects to the entry block and merge them
206 // together. Note that we only do this for alloca's, because malloc should
207 // allocate and return a unique pointer, even for a zero byte allocation.
208 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0) {
209 // For a zero sized alloca there is no point in doing an array allocation.
210 // This is helpful if the array size is a complicated expression not used
211 // elsewhere.
212 if (AI.isArrayAllocation()) {
213 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
214 return &AI;
215 }
216
217 // Get the first instruction in the entry block.
218 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
219 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
220 if (FirstInst != &AI) {
221 // If the entry block doesn't start with a zero-size alloca then move
222 // this one to the start of the entry block. There is no problem with
223 // dominance as the array size was forced to a constant earlier already.
224 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
225 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
226 TD->getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
227 AI.moveBefore(FirstInst);
228 return &AI;
229 }
230
Richard Osborneb68053e2012-09-18 09:31:44 +0000231 // If the alignment of the entry block alloca is 0 (unspecified),
232 // assign it the preferred alignment.
233 if (EntryAI->getAlignment() == 0)
234 EntryAI->setAlignment(
235 TD->getPrefTypeAlignment(EntryAI->getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000236 // Replace this zero-sized alloca with the one at the start of the entry
237 // block after ensuring that the address will be aligned enough for both
238 // types.
Richard Osborneb68053e2012-09-18 09:31:44 +0000239 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
240 AI.getAlignment());
Duncan Sands8bc764a2012-06-26 13:39:21 +0000241 EntryAI->setAlignment(MaxAlign);
242 if (AI.getType() != EntryAI->getType())
243 return new BitCastInst(EntryAI, AI.getType());
244 return ReplaceInstUsesWith(AI, EntryAI);
245 }
246 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000247 }
248
Eli Friedmanb14873c2012-11-26 23:04:53 +0000249 if (AI.getAlignment()) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000250 // Check to see if this allocation is only modified by a memcpy/memmove from
251 // a constant global whose alignment is equal to or exceeds that of the
252 // allocation. If this is the case, we can change all users to use
253 // the constant global instead. This is commonly produced by the CFE by
254 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
255 // is only subsequently read.
256 SmallVector<Instruction *, 4> ToDelete;
257 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
Eli Friedmanb14873c2012-11-26 23:04:53 +0000258 unsigned SourceAlign = getOrEnforceKnownAlignment(Copy->getSource(),
259 AI.getAlignment(), TD);
260 if (AI.getAlignment() <= SourceAlign) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000261 DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
262 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
263 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
264 EraseInstFromFunction(*ToDelete[i]);
265 Constant *TheSrc = cast<Constant>(Copy->getSource());
266 Instruction *NewI
267 = ReplaceInstUsesWith(AI, ConstantExpr::getBitCast(TheSrc,
268 AI.getType()));
269 EraseInstFromFunction(*Copy);
270 ++NumGlobalCopies;
271 return NewI;
272 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000273 }
274 }
275
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000276 // At last, use the generic allocation site handler to aggressively remove
277 // unused allocas.
278 return visitAllocSite(AI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000279}
280
281
282/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
283static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000284 const DataLayout *TD) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000285 User *CI = cast<User>(LI.getOperand(0));
286 Value *CastOp = CI->getOperand(0);
287
Chris Lattner229907c2011-07-18 04:54:35 +0000288 PointerType *DestTy = cast<PointerType>(CI->getType());
289 Type *DestPTy = DestTy->getElementType();
290 if (PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000291
292 // If the address spaces don't match, don't eliminate the cast.
293 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
294 return 0;
295
Chris Lattner229907c2011-07-18 04:54:35 +0000296 Type *SrcPTy = SrcTy->getElementType();
Chris Lattnera65e2f72010-01-05 05:57:49 +0000297
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000298 if (DestPTy->isIntegerTy() || DestPTy->isPointerTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000299 DestPTy->isVectorTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000300 // If the source is an array, the code below will not succeed. Check to
301 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
302 // constants.
Chris Lattner229907c2011-07-18 04:54:35 +0000303 if (ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000304 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
305 if (ASrcTy->getNumElements() != 0) {
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +0000306 Type *IdxTy = TD
307 ? TD->getIntPtrType(LI.getContext())
308 : Type::getInt64Ty(LI.getContext());
309 Value *Idx = Constant::getNullValue(IdxTy);
310 Value *Idxs[2] = { Idx, Idx };
Jay Foad71f19ac2011-07-22 07:54:01 +0000311 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000312 SrcTy = cast<PointerType>(CastOp->getType());
313 SrcPTy = SrcTy->getElementType();
314 }
315
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000316 if (IC.getDataLayout() &&
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000317 (SrcPTy->isIntegerTy() || SrcPTy->isPointerTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000318 SrcPTy->isVectorTy()) &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000319 // Do not allow turning this into a load of an integer, which is then
320 // casted to a pointer, this pessimizes pointer analysis a lot.
Duncan Sands19d0b472010-02-16 11:11:14 +0000321 (SrcPTy->isPointerTy() == LI.getType()->isPointerTy()) &&
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000322 IC.getDataLayout()->getTypeSizeInBits(SrcPTy) ==
323 IC.getDataLayout()->getTypeSizeInBits(DestPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000324
325 // Okay, we are casting from one integer or pointer type to another of
326 // the same size. Instead of casting the pointer before the load, cast
327 // the result of the loaded value.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000328 LoadInst *NewLoad =
Chris Lattnera65e2f72010-01-05 05:57:49 +0000329 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000330 NewLoad->setAlignment(LI.getAlignment());
Eli Friedman8bc586e2011-08-15 22:09:40 +0000331 NewLoad->setAtomic(LI.getOrdering(), LI.getSynchScope());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000332 // Now cast the result of the load.
333 return new BitCastInst(NewLoad, LI.getType());
334 }
335 }
336 }
337 return 0;
338}
339
340Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
341 Value *Op = LI.getOperand(0);
342
343 // Attempt to improve the alignment.
344 if (TD) {
345 unsigned KnownAlign =
Chris Lattner6fcd32e2010-12-25 20:37:57 +0000346 getOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()),TD);
Dan Gohman36196602010-08-03 18:20:32 +0000347 unsigned LoadAlign = LI.getAlignment();
348 unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
349 TD->getABITypeAlignment(LI.getType());
350
351 if (KnownAlign > EffectiveLoadAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000352 LI.setAlignment(KnownAlign);
Dan Gohman36196602010-08-03 18:20:32 +0000353 else if (LoadAlign == 0)
354 LI.setAlignment(EffectiveLoadAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000355 }
356
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000357 // load (cast X) --> cast (load X) iff safe.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000358 if (isa<CastInst>(Op))
359 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
360 return Res;
361
Eli Friedman8bc586e2011-08-15 22:09:40 +0000362 // None of the following transforms are legal for volatile/atomic loads.
363 // FIXME: Some of it is okay for atomic loads; needs refactoring.
364 if (!LI.isSimple()) return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000365
Chris Lattnera65e2f72010-01-05 05:57:49 +0000366 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +0000367 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +0000368 // separated by a few arithmetic operations.
369 BasicBlock::iterator BBI = &LI;
370 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
371 return ReplaceInstUsesWith(LI, AvailableVal);
372
373 // load(gep null, ...) -> unreachable
374 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
375 const Value *GEPI0 = GEPI->getOperand(0);
376 // TODO: Consider a target hook for valid address spaces for this xform.
377 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
378 // Insert a new store to null instruction before the load to indicate
379 // that this code is not reachable. We do this instead of inserting
380 // an unreachable instruction directly because we cannot modify the
381 // CFG.
382 new StoreInst(UndefValue::get(LI.getType()),
383 Constant::getNullValue(Op->getType()), &LI);
384 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
385 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000386 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000387
388 // load null/undef -> unreachable
389 // TODO: Consider a target hook for valid address spaces for this xform.
390 if (isa<UndefValue>(Op) ||
391 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
392 // Insert a new store to null instruction before the load to indicate that
393 // this code is not reachable. We do this instead of inserting an
394 // unreachable instruction directly because we cannot modify the CFG.
395 new StoreInst(UndefValue::get(LI.getType()),
396 Constant::getNullValue(Op->getType()), &LI);
397 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
398 }
399
400 // Instcombine load (constantexpr_cast global) -> cast (load global)
401 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
402 if (CE->isCast())
403 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
404 return Res;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000405
Chris Lattnera65e2f72010-01-05 05:57:49 +0000406 if (Op->hasOneUse()) {
407 // Change select and PHI nodes to select values instead of addresses: this
408 // helps alias analysis out a lot, allows many others simplifications, and
409 // exposes redundancy in the code.
410 //
411 // Note that we cannot do the transformation unless we know that the
412 // introduced loads cannot trap! Something like this is valid as long as
413 // the condition is always false: load (select bool %C, int* null, int* %G),
414 // but it would not be valid if we transformed it to load from null
415 // unconditionally.
416 //
417 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
418 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +0000419 unsigned Align = LI.getAlignment();
420 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, TD) &&
421 isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, TD)) {
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000422 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
Bob Wilson56600a12010-01-30 04:42:39 +0000423 SI->getOperand(1)->getName()+".val");
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000424 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
Bob Wilson56600a12010-01-30 04:42:39 +0000425 SI->getOperand(2)->getName()+".val");
426 V1->setAlignment(Align);
427 V2->setAlignment(Align);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000428 return SelectInst::Create(SI->getCondition(), V1, V2);
429 }
430
431 // load (select (cond, null, P)) -> load P
432 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
433 if (C->isNullValue()) {
434 LI.setOperand(0, SI->getOperand(2));
435 return &LI;
436 }
437
438 // load (select (cond, P, null)) -> load P
439 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
440 if (C->isNullValue()) {
441 LI.setOperand(0, SI->getOperand(1));
442 return &LI;
443 }
444 }
445 }
446 return 0;
447}
448
449/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
450/// when possible. This makes it generally easy to do alias analysis and/or
451/// SROA/mem2reg of the memory object.
452static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
453 User *CI = cast<User>(SI.getOperand(1));
454 Value *CastOp = CI->getOperand(0);
455
Chris Lattner229907c2011-07-18 04:54:35 +0000456 Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
457 PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000458 if (SrcTy == 0) return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000459
Chris Lattner229907c2011-07-18 04:54:35 +0000460 Type *SrcPTy = SrcTy->getElementType();
Chris Lattnera65e2f72010-01-05 05:57:49 +0000461
Duncan Sands19d0b472010-02-16 11:11:14 +0000462 if (!DestPTy->isIntegerTy() && !DestPTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000463 return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000464
Chris Lattnera65e2f72010-01-05 05:57:49 +0000465 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
466 /// to its first element. This allows us to handle things like:
467 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
468 /// on 32-bit hosts.
469 SmallVector<Value*, 4> NewGEPIndices;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000470
Chris Lattnera65e2f72010-01-05 05:57:49 +0000471 // If the source is an array, the code below will not succeed. Check to
472 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
473 // constants.
Duncan Sands19d0b472010-02-16 11:11:14 +0000474 if (SrcPTy->isArrayTy() || SrcPTy->isStructTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000475 // Index through pointer.
476 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
477 NewGEPIndices.push_back(Zero);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000478
Chris Lattnera65e2f72010-01-05 05:57:49 +0000479 while (1) {
Chris Lattner229907c2011-07-18 04:54:35 +0000480 if (StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000481 if (!STy->getNumElements()) /* Struct can be empty {} */
482 break;
483 NewGEPIndices.push_back(Zero);
484 SrcPTy = STy->getElementType(0);
Chris Lattner229907c2011-07-18 04:54:35 +0000485 } else if (ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000486 NewGEPIndices.push_back(Zero);
487 SrcPTy = ATy->getElementType();
488 } else {
489 break;
490 }
491 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000492
Chris Lattnera65e2f72010-01-05 05:57:49 +0000493 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
494 }
495
Duncan Sands19d0b472010-02-16 11:11:14 +0000496 if (!SrcPTy->isIntegerTy() && !SrcPTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000497 return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000498
Chris Lattnera65e2f72010-01-05 05:57:49 +0000499 // If the pointers point into different address spaces or if they point to
500 // values with different sizes, we can't do the transformation.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000501 if (!IC.getDataLayout() ||
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000502 SrcTy->getAddressSpace() !=
Chandler Carruth7ec50852012-11-01 08:07:29 +0000503 cast<PointerType>(CI->getType())->getAddressSpace() ||
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000504 IC.getDataLayout()->getTypeSizeInBits(SrcPTy) !=
505 IC.getDataLayout()->getTypeSizeInBits(DestPTy))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000506 return 0;
507
508 // Okay, we are casting from one integer or pointer type to another of
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000509 // the same size. Instead of casting the pointer before
Chris Lattnera65e2f72010-01-05 05:57:49 +0000510 // the store, cast the value to be stored.
511 Value *NewCast;
512 Value *SIOp0 = SI.getOperand(0);
513 Instruction::CastOps opcode = Instruction::BitCast;
Chris Lattner229907c2011-07-18 04:54:35 +0000514 Type* CastSrcTy = SIOp0->getType();
515 Type* CastDstTy = SrcPTy;
Duncan Sands19d0b472010-02-16 11:11:14 +0000516 if (CastDstTy->isPointerTy()) {
Duncan Sands9dff9be2010-02-15 16:12:20 +0000517 if (CastSrcTy->isIntegerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000518 opcode = Instruction::IntToPtr;
Duncan Sands19d0b472010-02-16 11:11:14 +0000519 } else if (CastDstTy->isIntegerTy()) {
520 if (SIOp0->getType()->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000521 opcode = Instruction::PtrToInt;
522 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000523
Chris Lattnera65e2f72010-01-05 05:57:49 +0000524 // SIOp0 is a pointer to aggregate and this is a store to the first field,
525 // emit a GEP to index into its first field.
526 if (!NewGEPIndices.empty())
Jay Foad040dd822011-07-22 08:16:57 +0000527 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000528
Chris Lattnera65e2f72010-01-05 05:57:49 +0000529 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
530 SIOp0->getName()+".c");
Dan Gohman2e20dfb2010-10-25 16:16:27 +0000531 SI.setOperand(0, NewCast);
532 SI.setOperand(1, CastOp);
533 return &SI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000534}
535
536/// equivalentAddressValues - Test if A and B will obviously have the same
537/// value. This includes recognizing that %t0 and %t1 will have the same
538/// value in code like this:
539/// %t0 = getelementptr \@a, 0, 3
540/// store i32 0, i32* %t0
541/// %t1 = getelementptr \@a, 0, 3
542/// %t2 = load i32* %t1
543///
544static bool equivalentAddressValues(Value *A, Value *B) {
545 // Test if the values are trivially equivalent.
546 if (A == B) return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000547
Chris Lattnera65e2f72010-01-05 05:57:49 +0000548 // Test if the values come form identical arithmetic instructions.
549 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
550 // its only used to compare two uses within the same basic block, which
551 // means that they'll always either have the same value or one of them
552 // will have an undefined value.
553 if (isa<BinaryOperator>(A) ||
554 isa<CastInst>(A) ||
555 isa<PHINode>(A) ||
556 isa<GetElementPtrInst>(A))
557 if (Instruction *BI = dyn_cast<Instruction>(B))
558 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
559 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000560
Chris Lattnera65e2f72010-01-05 05:57:49 +0000561 // Otherwise they may not be equivalent.
562 return false;
563}
564
Chris Lattnera65e2f72010-01-05 05:57:49 +0000565Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
566 Value *Val = SI.getOperand(0);
567 Value *Ptr = SI.getOperand(1);
568
Chris Lattnera65e2f72010-01-05 05:57:49 +0000569 // Attempt to improve the alignment.
570 if (TD) {
571 unsigned KnownAlign =
Chris Lattner6fcd32e2010-12-25 20:37:57 +0000572 getOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()),
573 TD);
Dan Gohman36196602010-08-03 18:20:32 +0000574 unsigned StoreAlign = SI.getAlignment();
575 unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
576 TD->getABITypeAlignment(Val->getType());
577
Bill Wendling55b6b2b2012-03-16 18:20:54 +0000578 if (KnownAlign > EffectiveStoreAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000579 SI.setAlignment(KnownAlign);
Bill Wendling55b6b2b2012-03-16 18:20:54 +0000580 else if (StoreAlign == 0)
581 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000582 }
583
Eli Friedman8bc586e2011-08-15 22:09:40 +0000584 // Don't hack volatile/atomic stores.
585 // FIXME: Some bits are legal for atomic stores; needs refactoring.
586 if (!SI.isSimple()) return 0;
587
588 // If the RHS is an alloca with a single use, zapify the store, making the
589 // alloca dead.
590 if (Ptr->hasOneUse()) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000591 if (isa<AllocaInst>(Ptr))
Eli Friedman8bc586e2011-08-15 22:09:40 +0000592 return EraseInstFromFunction(SI);
593 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
594 if (isa<AllocaInst>(GEP->getOperand(0))) {
595 if (GEP->getOperand(0)->hasOneUse())
596 return EraseInstFromFunction(SI);
597 }
598 }
599 }
600
Chris Lattnera65e2f72010-01-05 05:57:49 +0000601 // Do really simple DSE, to catch cases where there are several consecutive
602 // stores to the same location, separated by a few arithmetic operations. This
603 // situation often occurs with bitfield accesses.
604 BasicBlock::iterator BBI = &SI;
605 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
606 --ScanInsts) {
607 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000608 // Don't count debug info directives, lest they affect codegen,
609 // and we skip pointer-to-pointer bitcasts, which are NOPs.
610 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000611 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000612 ScanInsts++;
613 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000614 }
615
Chris Lattnera65e2f72010-01-05 05:57:49 +0000616 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
617 // Prev store isn't volatile, and stores to the same location?
Eli Friedman8bc586e2011-08-15 22:09:40 +0000618 if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
619 SI.getOperand(1))) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000620 ++NumDeadStore;
621 ++BBI;
622 EraseInstFromFunction(*PrevSI);
623 continue;
624 }
625 break;
626 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000627
Chris Lattnera65e2f72010-01-05 05:57:49 +0000628 // If this is a load, we have to stop. However, if the loaded value is from
629 // the pointer we're loading and is producing the pointer we're storing,
630 // then *this* store is dead (X = load P; store X -> P).
631 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000632 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
Eli Friedman8bc586e2011-08-15 22:09:40 +0000633 LI->isSimple())
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000634 return EraseInstFromFunction(SI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000635
Chris Lattnera65e2f72010-01-05 05:57:49 +0000636 // Otherwise, this is a load from some other location. Stores before it
637 // may not be dead.
638 break;
639 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000640
Chris Lattnera65e2f72010-01-05 05:57:49 +0000641 // Don't skip over loads or things that can modify memory.
642 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
643 break;
644 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000645
646 // store X, null -> turns into 'unreachable' in SimplifyCFG
647 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
648 if (!isa<UndefValue>(Val)) {
649 SI.setOperand(0, UndefValue::get(Val->getType()));
650 if (Instruction *U = dyn_cast<Instruction>(Val))
651 Worklist.Add(U); // Dropped a use.
652 }
653 return 0; // Do not modify these!
654 }
655
656 // store undef, Ptr -> noop
657 if (isa<UndefValue>(Val))
658 return EraseInstFromFunction(SI);
659
660 // If the pointer destination is a cast, see if we can fold the cast into the
661 // source instead.
662 if (isa<CastInst>(Ptr))
663 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
664 return Res;
665 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
666 if (CE->isCast())
667 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
668 return Res;
669
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000670
Chris Lattnera65e2f72010-01-05 05:57:49 +0000671 // If this store is the last instruction in the basic block (possibly
Victor Hernandez5f5abd52010-01-21 23:07:15 +0000672 // excepting debug info instructions), and if the block ends with an
673 // unconditional branch, try to move it to the successor block.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000674 BBI = &SI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000675 do {
676 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000677 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000678 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000679 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
680 if (BI->isUnconditional())
681 if (SimplifyStoreAtEndOfBlock(SI))
682 return 0; // xform done!
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000683
Chris Lattnera65e2f72010-01-05 05:57:49 +0000684 return 0;
685}
686
687/// SimplifyStoreAtEndOfBlock - Turn things like:
688/// if () { *P = v1; } else { *P = v2 }
689/// into a phi node with a store in the successor.
690///
691/// Simplify things like:
692/// *P = v1; if () { *P = v2; }
693/// into a phi node with a store in the successor.
694///
695bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
696 BasicBlock *StoreBB = SI.getParent();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000697
Chris Lattnera65e2f72010-01-05 05:57:49 +0000698 // Check to see if the successor block has exactly two incoming edges. If
699 // so, see if the other predecessor contains a store to the same location.
700 // if so, insert a PHI node (if needed) and move the stores down.
701 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000702
Chris Lattnera65e2f72010-01-05 05:57:49 +0000703 // Determine whether Dest has exactly two predecessors and, if so, compute
704 // the other predecessor.
705 pred_iterator PI = pred_begin(DestBB);
Gabor Greif1b787df2010-07-12 15:48:26 +0000706 BasicBlock *P = *PI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000707 BasicBlock *OtherBB = 0;
Gabor Greif1b787df2010-07-12 15:48:26 +0000708
709 if (P != StoreBB)
710 OtherBB = P;
711
712 if (++PI == pred_end(DestBB))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000713 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000714
Gabor Greif1b787df2010-07-12 15:48:26 +0000715 P = *PI;
716 if (P != StoreBB) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000717 if (OtherBB)
718 return false;
Gabor Greif1b787df2010-07-12 15:48:26 +0000719 OtherBB = P;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000720 }
721 if (++PI != pred_end(DestBB))
722 return false;
723
724 // Bail out if all the relevant blocks aren't distinct (this can happen,
725 // for example, if SI is in an infinite loop)
726 if (StoreBB == DestBB || OtherBB == DestBB)
727 return false;
728
729 // Verify that the other block ends in a branch and is not otherwise empty.
730 BasicBlock::iterator BBI = OtherBB->getTerminator();
731 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
732 if (!OtherBr || BBI == OtherBB->begin())
733 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000734
Chris Lattnera65e2f72010-01-05 05:57:49 +0000735 // If the other block ends in an unconditional branch, check for the 'if then
736 // else' case. there is an instruction before the branch.
737 StoreInst *OtherStore = 0;
738 if (OtherBr->isUnconditional()) {
739 --BBI;
740 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000741 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000742 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000743 if (BBI==OtherBB->begin())
744 return false;
745 --BBI;
746 }
Eli Friedman8bc586e2011-08-15 22:09:40 +0000747 // If this isn't a store, isn't a store to the same location, or is not the
748 // right kind of store, bail out.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000749 OtherStore = dyn_cast<StoreInst>(BBI);
750 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +0000751 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000752 return false;
753 } else {
754 // Otherwise, the other block ended with a conditional branch. If one of the
755 // destinations is StoreBB, then we have the if/then case.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000756 if (OtherBr->getSuccessor(0) != StoreBB &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000757 OtherBr->getSuccessor(1) != StoreBB)
758 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000759
Chris Lattnera65e2f72010-01-05 05:57:49 +0000760 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
761 // if/then triangle. See if there is a store to the same ptr as SI that
762 // lives in OtherBB.
763 for (;; --BBI) {
764 // Check to see if we find the matching store.
765 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
766 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +0000767 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000768 return false;
769 break;
770 }
771 // If we find something that may be using or overwriting the stored
772 // value, or if we run out of instructions, we can't do the xform.
773 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
774 BBI == OtherBB->begin())
775 return false;
776 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000777
Chris Lattnera65e2f72010-01-05 05:57:49 +0000778 // In order to eliminate the store in OtherBr, we have to
779 // make sure nothing reads or overwrites the stored value in
780 // StoreBB.
781 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
782 // FIXME: This should really be AA driven.
783 if (I->mayReadFromMemory() || I->mayWriteToMemory())
784 return false;
785 }
786 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000787
Chris Lattnera65e2f72010-01-05 05:57:49 +0000788 // Insert a PHI node now if we need it.
789 Value *MergedVal = OtherStore->getOperand(0);
790 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +0000791 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +0000792 PN->addIncoming(SI.getOperand(0), SI.getParent());
793 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
794 MergedVal = InsertNewInstBefore(PN, DestBB->front());
795 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000796
Chris Lattnera65e2f72010-01-05 05:57:49 +0000797 // Advance to a place where it is safe to insert the new store and
798 // insert it.
Bill Wendling8ddfc092011-08-16 20:45:24 +0000799 BBI = DestBB->getFirstInsertionPt();
Eli Friedman35211c62011-05-27 00:19:40 +0000800 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +0000801 SI.isVolatile(),
802 SI.getAlignment(),
803 SI.getOrdering(),
804 SI.getSynchScope());
Eli Friedman35211c62011-05-27 00:19:40 +0000805 InsertNewInstBefore(NewSI, *BBI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000806 NewSI->setDebugLoc(OtherStore->getDebugLoc());
Eli Friedman35211c62011-05-27 00:19:40 +0000807
Chris Lattnereeefe1b2012-12-31 08:10:58 +0000808 // If the two stores had the same TBAA tag, preserve it.
Chris Lattner473988c2013-01-05 16:44:07 +0000809 if (MDNode *TBAATag = SI.getMetadata(LLVMContext::MD_tbaa))
810 if ((TBAATag = MDNode::getMostGenericTBAA(TBAATag,
811 OtherStore->getMetadata(LLVMContext::MD_tbaa))))
812 NewSI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
Chris Lattnereeefe1b2012-12-31 08:10:58 +0000813
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000814
Chris Lattnera65e2f72010-01-05 05:57:49 +0000815 // Nuke the old stores.
816 EraseInstFromFunction(SI);
817 EraseInstFromFunction(*OtherStore);
818 return true;
819}