blob: aa72244463ee0f0ea0c0ac35d9129a0009c8a02b [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
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +000015#include "llvm/ADT/SmallString.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/Statistic.h"
Dan Gohman826bdf82010-05-28 16:19:17 +000017#include "llvm/Analysis/Loads.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/DataLayout.h"
Chandler Carruthbc6378d2014-10-19 10:46:46 +000019#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/IntrinsicInst.h"
Charles Davis33d1dc02015-02-25 05:10:25 +000021#include "llvm/IR/MDBuilder.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000022#include "llvm/Transforms/Utils/BasicBlockUtils.h"
23#include "llvm/Transforms/Utils/Local.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000024using namespace llvm;
25
Chandler Carruth964daaa2014-04-22 02:55:47 +000026#define DEBUG_TYPE "instcombine"
27
Chandler Carruthc908ca12012-08-21 08:39:44 +000028STATISTIC(NumDeadStore, "Number of dead stores eliminated");
29STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
30
31/// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
32/// some part of a constant global variable. This intentionally only accepts
33/// constant expressions because we can't rewrite arbitrary instructions.
34static bool pointsToConstantGlobal(Value *V) {
35 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
36 return GV->isConstant();
Matt Arsenault607281772014-04-24 00:01:09 +000037
38 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000039 if (CE->getOpcode() == Instruction::BitCast ||
Matt Arsenault607281772014-04-24 00:01:09 +000040 CE->getOpcode() == Instruction::AddrSpaceCast ||
Chandler Carruthc908ca12012-08-21 08:39:44 +000041 CE->getOpcode() == Instruction::GetElementPtr)
42 return pointsToConstantGlobal(CE->getOperand(0));
Matt Arsenault607281772014-04-24 00:01:09 +000043 }
Chandler Carruthc908ca12012-08-21 08:39:44 +000044 return false;
45}
46
47/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
48/// pointer to an alloca. Ignore any reads of the pointer, return false if we
49/// see any stores or other unknown uses. If we see pointer arithmetic, keep
50/// track of whether it moves the pointer (with IsOffset) but otherwise traverse
51/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
52/// the alloca, and if the source pointer is a pointer to a constant global, we
53/// can optimize this.
54static bool
55isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Reid Kleckner813dab22014-07-01 21:36:20 +000056 SmallVectorImpl<Instruction *> &ToDelete) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000057 // We track lifetime intrinsics as we encounter them. If we decide to go
58 // ahead and replace the value with the global, this lets the caller quickly
59 // eliminate the markers.
60
Reid Kleckner813dab22014-07-01 21:36:20 +000061 SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect;
62 ValuesToInspect.push_back(std::make_pair(V, false));
63 while (!ValuesToInspect.empty()) {
64 auto ValuePair = ValuesToInspect.pop_back_val();
65 const bool IsOffset = ValuePair.second;
66 for (auto &U : ValuePair.first->uses()) {
67 Instruction *I = cast<Instruction>(U.getUser());
Chandler Carruthc908ca12012-08-21 08:39:44 +000068
Reid Kleckner813dab22014-07-01 21:36:20 +000069 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
70 // Ignore non-volatile loads, they are always ok.
71 if (!LI->isSimple()) return false;
Chandler Carruthc908ca12012-08-21 08:39:44 +000072 continue;
73 }
Reid Kleckner813dab22014-07-01 21:36:20 +000074
75 if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) {
76 // If uses of the bitcast are ok, we are ok.
77 ValuesToInspect.push_back(std::make_pair(I, IsOffset));
78 continue;
79 }
80 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
81 // If the GEP has all zero indices, it doesn't offset the pointer. If it
82 // doesn't, it does.
83 ValuesToInspect.push_back(
84 std::make_pair(I, IsOffset || !GEP->hasAllZeroIndices()));
85 continue;
86 }
87
Benjamin Kramer3a09ef62015-04-10 14:50:08 +000088 if (auto CS = CallSite(I)) {
Reid Kleckner813dab22014-07-01 21:36:20 +000089 // If this is the function being called then we treat it like a load and
90 // ignore it.
91 if (CS.isCallee(&U))
92 continue;
93
David Majnemer02f47872015-12-23 09:58:41 +000094 unsigned DataOpNo = CS.getDataOperandNo(&U);
95 bool IsArgOperand = CS.isArgOperand(&U);
96
Reid Kleckner813dab22014-07-01 21:36:20 +000097 // Inalloca arguments are clobbered by the call.
David Majnemer02f47872015-12-23 09:58:41 +000098 if (IsArgOperand && CS.isInAllocaArgument(DataOpNo))
Reid Kleckner813dab22014-07-01 21:36:20 +000099 return false;
100
101 // If this is a readonly/readnone call site, then we know it is just a
102 // load (but one that potentially returns the value itself), so we can
103 // ignore it if we know that the value isn't captured.
104 if (CS.onlyReadsMemory() &&
David Majnemer02f47872015-12-23 09:58:41 +0000105 (CS.getInstruction()->use_empty() || CS.doesNotCapture(DataOpNo)))
Reid Kleckner813dab22014-07-01 21:36:20 +0000106 continue;
107
108 // If this is being passed as a byval argument, the caller is making a
109 // copy, so it is only a read of the alloca.
David Majnemer02f47872015-12-23 09:58:41 +0000110 if (IsArgOperand && CS.isByValArgument(DataOpNo))
Reid Kleckner813dab22014-07-01 21:36:20 +0000111 continue;
112 }
113
114 // Lifetime intrinsics can be handled by the caller.
115 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
116 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
117 II->getIntrinsicID() == Intrinsic::lifetime_end) {
118 assert(II->use_empty() && "Lifetime markers have no result to use!");
119 ToDelete.push_back(II);
120 continue;
121 }
122 }
123
124 // If this is isn't our memcpy/memmove, reject it as something we can't
125 // handle.
126 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
127 if (!MI)
128 return false;
129
130 // If the transfer is using the alloca as a source of the transfer, then
131 // ignore it since it is a load (unless the transfer is volatile).
132 if (U.getOperandNo() == 1) {
133 if (MI->isVolatile()) return false;
134 continue;
135 }
136
137 // If we already have seen a copy, reject the second one.
138 if (TheCopy) return false;
139
140 // If the pointer has been offset from the start of the alloca, we can't
141 // safely handle this.
142 if (IsOffset) return false;
143
144 // If the memintrinsic isn't using the alloca as the dest, reject it.
145 if (U.getOperandNo() != 0) return false;
146
147 // If the source of the memcpy/move is not a constant global, reject it.
148 if (!pointsToConstantGlobal(MI->getSource()))
149 return false;
150
151 // Otherwise, the transform is safe. Remember the copy instruction.
152 TheCopy = MI;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000153 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000154 }
155 return true;
156}
157
158/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
159/// modified by a copy from a constant global. If we can prove this, we can
160/// replace any uses of the alloca with uses of the global directly.
161static MemTransferInst *
162isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
163 SmallVectorImpl<Instruction *> &ToDelete) {
Craig Topperf40110f2014-04-25 05:29:35 +0000164 MemTransferInst *TheCopy = nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000165 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
166 return TheCopy;
Craig Topperf40110f2014-04-25 05:29:35 +0000167 return nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000168}
169
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000170static Instruction *simplifyAllocaArraySize(InstCombiner &IC, AllocaInst &AI) {
Duncan P. N. Exon Smith720762e2015-03-13 19:30:44 +0000171 // Check for array size of 1 (scalar allocation).
Duncan P. N. Exon Smithbe95b4a2015-03-13 19:42:09 +0000172 if (!AI.isArrayAllocation()) {
173 // i32 1 is the canonical array size for scalar allocations.
174 if (AI.getArraySize()->getType()->isIntegerTy(32))
175 return nullptr;
176
177 // Canonicalize it.
178 Value *V = IC.Builder->getInt32(1);
179 AI.setOperand(0, V);
180 return &AI;
181 }
Duncan P. N. Exon Smith720762e2015-03-13 19:30:44 +0000182
Chris Lattnera65e2f72010-01-05 05:57:49 +0000183 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000184 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
185 Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
186 AllocaInst *New = IC.Builder->CreateAlloca(NewTy, nullptr, AI.getName());
187 New->setAlignment(AI.getAlignment());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000188
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000189 // Scan to the end of the allocation instructions, to skip over a block of
190 // allocas if possible...also skip interleaved debug info
191 //
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000192 BasicBlock::iterator It(New);
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000193 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
194 ++It;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000195
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000196 // Now that I is pointing to the first non-allocation-inst in the block,
197 // insert our getelementptr instruction...
198 //
199 Type *IdxTy = IC.getDataLayout().getIntPtrType(AI.getType());
200 Value *NullIdx = Constant::getNullValue(IdxTy);
201 Value *Idx[2] = {NullIdx, NullIdx};
202 Instruction *GEP =
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000203 GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000204 IC.InsertNewInstBefore(GEP, *It);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000205
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000206 // Now make everything use the getelementptr instead of the original
207 // allocation.
Sanjay Patel4b198802016-02-01 22:23:39 +0000208 return IC.replaceInstUsesWith(AI, GEP);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000209 }
210
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000211 if (isa<UndefValue>(AI.getArraySize()))
Sanjay Patel4b198802016-02-01 22:23:39 +0000212 return IC.replaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000213
Duncan P. N. Exon Smith07ff9b02015-03-13 19:34:55 +0000214 // Ensure that the alloca array size argument has type intptr_t, so that
215 // any casting is exposed early.
216 Type *IntPtrTy = IC.getDataLayout().getIntPtrType(AI.getType());
217 if (AI.getArraySize()->getType() != IntPtrTy) {
218 Value *V = IC.Builder->CreateIntCast(AI.getArraySize(), IntPtrTy, false);
219 AI.setOperand(0, V);
220 return &AI;
221 }
222
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000223 return nullptr;
224}
225
226Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
227 if (auto *I = simplifyAllocaArraySize(*this, AI))
228 return I;
229
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000230 if (AI.getAllocatedType()->isSized()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000231 // If the alignment is 0 (unspecified), assign it the preferred alignment.
232 if (AI.getAlignment() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000233 AI.setAlignment(DL.getPrefTypeAlignment(AI.getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000234
235 // Move all alloca's of zero byte objects to the entry block and merge them
236 // together. Note that we only do this for alloca's, because malloc should
237 // allocate and return a unique pointer, even for a zero byte allocation.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000238 if (DL.getTypeAllocSize(AI.getAllocatedType()) == 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000239 // For a zero sized alloca there is no point in doing an array allocation.
240 // This is helpful if the array size is a complicated expression not used
241 // elsewhere.
242 if (AI.isArrayAllocation()) {
243 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
244 return &AI;
245 }
246
247 // Get the first instruction in the entry block.
248 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
249 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
250 if (FirstInst != &AI) {
251 // If the entry block doesn't start with a zero-size alloca then move
252 // this one to the start of the entry block. There is no problem with
253 // dominance as the array size was forced to a constant earlier already.
254 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
255 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000256 DL.getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000257 AI.moveBefore(FirstInst);
258 return &AI;
259 }
260
Richard Osborneb68053e2012-09-18 09:31:44 +0000261 // If the alignment of the entry block alloca is 0 (unspecified),
262 // assign it the preferred alignment.
263 if (EntryAI->getAlignment() == 0)
264 EntryAI->setAlignment(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000265 DL.getPrefTypeAlignment(EntryAI->getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000266 // Replace this zero-sized alloca with the one at the start of the entry
267 // block after ensuring that the address will be aligned enough for both
268 // types.
Richard Osborneb68053e2012-09-18 09:31:44 +0000269 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
270 AI.getAlignment());
Duncan Sands8bc764a2012-06-26 13:39:21 +0000271 EntryAI->setAlignment(MaxAlign);
272 if (AI.getType() != EntryAI->getType())
273 return new BitCastInst(EntryAI, AI.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +0000274 return replaceInstUsesWith(AI, EntryAI);
Duncan Sands8bc764a2012-06-26 13:39:21 +0000275 }
276 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000277 }
278
Eli Friedmanb14873c2012-11-26 23:04:53 +0000279 if (AI.getAlignment()) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000280 // Check to see if this allocation is only modified by a memcpy/memmove from
281 // a constant global whose alignment is equal to or exceeds that of the
282 // allocation. If this is the case, we can change all users to use
283 // the constant global instead. This is commonly produced by the CFE by
284 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
285 // is only subsequently read.
286 SmallVector<Instruction *, 4> ToDelete;
287 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000288 unsigned SourceAlign = getOrEnforceKnownAlignment(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000289 Copy->getSource(), AI.getAlignment(), DL, &AI, AC, DT);
Eli Friedmanb14873c2012-11-26 23:04:53 +0000290 if (AI.getAlignment() <= SourceAlign) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000291 DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
292 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
293 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
Sanjay Patel4b198802016-02-01 22:23:39 +0000294 eraseInstFromFunction(*ToDelete[i]);
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000295 Constant *TheSrc = cast<Constant>(Copy->getSource());
Matt Arsenaultbbf18c62013-12-07 02:58:45 +0000296 Constant *Cast
297 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +0000298 Instruction *NewI = replaceInstUsesWith(AI, Cast);
299 eraseInstFromFunction(*Copy);
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000300 ++NumGlobalCopies;
301 return NewI;
302 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000303 }
304 }
305
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000306 // At last, use the generic allocation site handler to aggressively remove
307 // unused allocas.
308 return visitAllocSite(AI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000309}
310
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000311/// \brief Helper to combine a load to a new type.
312///
313/// This just does the work of combining a load to a new type. It handles
314/// metadata, etc., and returns the new instruction. The \c NewTy should be the
315/// loaded *value* type. This will convert it to a pointer, cast the operand to
316/// that pointer type, load it, etc.
317///
318/// Note that this will create all of the instructions with whatever insert
319/// point the \c InstCombiner currently is using.
Mehdi Amini2668a482015-05-07 05:52:40 +0000320static LoadInst *combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy,
321 const Twine &Suffix = "") {
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000322 Value *Ptr = LI.getPointerOperand();
323 unsigned AS = LI.getPointerAddressSpace();
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000324 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000325 LI.getAllMetadata(MD);
326
327 LoadInst *NewLoad = IC.Builder->CreateAlignedLoad(
328 IC.Builder->CreateBitCast(Ptr, NewTy->getPointerTo(AS)),
Mehdi Amini2668a482015-05-07 05:52:40 +0000329 LI.getAlignment(), LI.getName() + Suffix);
Philip Reameseedef732016-04-22 20:33:48 +0000330 NewLoad->setAtomic(LI.getOrdering(), LI.getSynchScope());
331 assert(!LI.isVolatile() && "volatile unhandled here");
Charles Davis33d1dc02015-02-25 05:10:25 +0000332 MDBuilder MDB(NewLoad->getContext());
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000333 for (const auto &MDPair : MD) {
334 unsigned ID = MDPair.first;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000335 MDNode *N = MDPair.second;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000336 // Note, essentially every kind of metadata should be preserved here! This
337 // routine is supposed to clone a load instruction changing *only its type*.
338 // The only metadata it makes sense to drop is metadata which is invalidated
339 // when the pointer type changes. This should essentially never be the case
340 // in LLVM, but we explicitly switch over only known metadata to be
341 // conservatively correct. If you are adding metadata to LLVM which pertains
342 // to loads, you almost certainly want to add it here.
343 switch (ID) {
344 case LLVMContext::MD_dbg:
345 case LLVMContext::MD_tbaa:
346 case LLVMContext::MD_prof:
347 case LLVMContext::MD_fpmath:
348 case LLVMContext::MD_tbaa_struct:
349 case LLVMContext::MD_invariant_load:
350 case LLVMContext::MD_alias_scope:
351 case LLVMContext::MD_noalias:
Philip Reames5a3f5f72014-10-21 00:13:20 +0000352 case LLVMContext::MD_nontemporal:
353 case LLVMContext::MD_mem_parallel_loop_access:
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000354 // All of these directly apply.
355 NewLoad->setMetadata(ID, N);
356 break;
357
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000358 case LLVMContext::MD_nonnull:
Charles Davis33d1dc02015-02-25 05:10:25 +0000359 // This only directly applies if the new type is also a pointer.
360 if (NewTy->isPointerTy()) {
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000361 NewLoad->setMetadata(ID, N);
Charles Davis33d1dc02015-02-25 05:10:25 +0000362 break;
363 }
364 // If it's integral now, translate it to !range metadata.
365 if (NewTy->isIntegerTy()) {
366 auto *ITy = cast<IntegerType>(NewTy);
367 auto *NullInt = ConstantExpr::getPtrToInt(
368 ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
369 auto *NonNullInt =
370 ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
371 NewLoad->setMetadata(LLVMContext::MD_range,
372 MDB.createRange(NonNullInt, NullInt));
373 }
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000374 break;
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000375 case LLVMContext::MD_align:
376 case LLVMContext::MD_dereferenceable:
377 case LLVMContext::MD_dereferenceable_or_null:
378 // These only directly apply if the new type is also a pointer.
379 if (NewTy->isPointerTy())
380 NewLoad->setMetadata(ID, N);
381 break;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000382 case LLVMContext::MD_range:
383 // FIXME: It would be nice to propagate this in some way, but the type
Charles Davis33d1dc02015-02-25 05:10:25 +0000384 // conversions make it hard. If the new type is a pointer, we could
385 // translate it to !nonnull metadata.
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000386 break;
387 }
388 }
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000389 return NewLoad;
390}
391
Chandler Carruthfa11d832015-01-22 03:34:54 +0000392/// \brief Combine a store to a new type.
393///
394/// Returns the newly created store instruction.
395static StoreInst *combineStoreToNewValue(InstCombiner &IC, StoreInst &SI, Value *V) {
396 Value *Ptr = SI.getPointerOperand();
397 unsigned AS = SI.getPointerAddressSpace();
398 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
399 SI.getAllMetadata(MD);
400
401 StoreInst *NewStore = IC.Builder->CreateAlignedStore(
402 V, IC.Builder->CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
403 SI.getAlignment());
Philip Reameseedef732016-04-22 20:33:48 +0000404 NewStore->setAtomic(SI.getOrdering(), SI.getSynchScope());
405 assert(!SI.isVolatile() && "volatile unhandled here");
Chandler Carruthfa11d832015-01-22 03:34:54 +0000406 for (const auto &MDPair : MD) {
407 unsigned ID = MDPair.first;
408 MDNode *N = MDPair.second;
409 // Note, essentially every kind of metadata should be preserved here! This
410 // routine is supposed to clone a store instruction changing *only its
411 // type*. The only metadata it makes sense to drop is metadata which is
412 // invalidated when the pointer type changes. This should essentially
413 // never be the case in LLVM, but we explicitly switch over only known
414 // metadata to be conservatively correct. If you are adding metadata to
415 // LLVM which pertains to stores, you almost certainly want to add it
416 // here.
417 switch (ID) {
418 case LLVMContext::MD_dbg:
419 case LLVMContext::MD_tbaa:
420 case LLVMContext::MD_prof:
421 case LLVMContext::MD_fpmath:
422 case LLVMContext::MD_tbaa_struct:
423 case LLVMContext::MD_alias_scope:
424 case LLVMContext::MD_noalias:
425 case LLVMContext::MD_nontemporal:
426 case LLVMContext::MD_mem_parallel_loop_access:
Chandler Carruthfa11d832015-01-22 03:34:54 +0000427 // All of these directly apply.
428 NewStore->setMetadata(ID, N);
429 break;
430
431 case LLVMContext::MD_invariant_load:
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000432 case LLVMContext::MD_nonnull:
Chandler Carruthfa11d832015-01-22 03:34:54 +0000433 case LLVMContext::MD_range:
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000434 case LLVMContext::MD_align:
435 case LLVMContext::MD_dereferenceable:
436 case LLVMContext::MD_dereferenceable_or_null:
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000437 // These don't apply for stores.
Chandler Carruthfa11d832015-01-22 03:34:54 +0000438 break;
439 }
440 }
441
442 return NewStore;
443}
444
JF Bastien3e2e69f2016-04-21 19:41:48 +0000445/// \brief Combine loads to match the type of their uses' value after looking
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000446/// through intervening bitcasts.
447///
448/// The core idea here is that if the result of a load is used in an operation,
449/// we should load the type most conducive to that operation. For example, when
450/// loading an integer and converting that immediately to a pointer, we should
451/// instead directly load a pointer.
452///
453/// However, this routine must never change the width of a load or the number of
454/// loads as that would introduce a semantic change. This combine is expected to
455/// be a semantic no-op which just allows loads to more closely model the types
456/// of their consuming operations.
457///
458/// Currently, we also refuse to change the precise type used for an atomic load
459/// or a volatile load. This is debatable, and might be reasonable to change
460/// later. However, it is risky in case some backend or other part of LLVM is
461/// relying on the exact type loaded to select appropriate atomic operations.
462static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
Philip Reameseedef732016-04-22 20:33:48 +0000463 // FIXME: We could probably with some care handle both volatile and ordered
464 // atomic loads here but it isn't clear that this is important.
465 if (!LI.isUnordered())
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000466 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000467
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000468 if (LI.use_empty())
469 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000470
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000471 Type *Ty = LI.getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000472 const DataLayout &DL = IC.getDataLayout();
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000473
474 // Try to canonicalize loads which are only ever stored to operate over
475 // integers instead of any other type. We only do this when the loaded type
476 // is sized and has a size exactly the same as its store size and the store
477 // size is a legal integer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000478 if (!Ty->isIntegerTy() && Ty->isSized() &&
479 DL.isLegalInteger(DL.getTypeStoreSizeInBits(Ty)) &&
480 DL.getTypeStoreSizeInBits(Ty) == DL.getTypeSizeInBits(Ty)) {
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000481 if (std::all_of(LI.user_begin(), LI.user_end(), [&LI](User *U) {
482 auto *SI = dyn_cast<StoreInst>(U);
483 return SI && SI->getPointerOperand() != &LI;
484 })) {
485 LoadInst *NewLoad = combineLoadToNewType(
486 IC, LI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000487 Type::getIntNTy(LI.getContext(), DL.getTypeStoreSizeInBits(Ty)));
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000488 // Replace all the stores with stores of the newly loaded value.
489 for (auto UI = LI.user_begin(), UE = LI.user_end(); UI != UE;) {
490 auto *SI = cast<StoreInst>(*UI++);
491 IC.Builder->SetInsertPoint(SI);
492 combineStoreToNewValue(IC, *SI, NewLoad);
Sanjay Patel4b198802016-02-01 22:23:39 +0000493 IC.eraseInstFromFunction(*SI);
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000494 }
495 assert(LI.use_empty() && "Failed to remove all users of the load!");
496 // Return the old load so the combiner can delete it safely.
497 return &LI;
498 }
499 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000500
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000501 // Fold away bit casts of the loaded value by loading the desired type.
Quentin Colombet490cfbe2016-02-11 22:30:41 +0000502 // We can do this for BitCastInsts as well as casts from and to pointer types,
503 // as long as those are noops (i.e., the source or dest type have the same
504 // bitwidth as the target's pointers).
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000505 if (LI.hasOneUse())
Quentin Colombet490cfbe2016-02-11 22:30:41 +0000506 if (auto* CI = dyn_cast<CastInst>(LI.user_back())) {
507 if (CI->isNoopCast(DL)) {
508 LoadInst *NewLoad = combineLoadToNewType(IC, LI, CI->getDestTy());
509 CI->replaceAllUsesWith(NewLoad);
510 IC.eraseInstFromFunction(*CI);
511 return &LI;
512 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000513 }
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000514
Chandler Carrutha7f247e2014-12-09 19:21:16 +0000515 // FIXME: We should also canonicalize loads of vectors when their elements are
516 // cast to other types.
Craig Topperf40110f2014-04-25 05:29:35 +0000517 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000518}
519
Mehdi Amini2668a482015-05-07 05:52:40 +0000520static Instruction *unpackLoadToAggregate(InstCombiner &IC, LoadInst &LI) {
521 // FIXME: We could probably with some care handle both volatile and atomic
522 // stores here but it isn't clear that this is important.
523 if (!LI.isSimple())
524 return nullptr;
525
526 Type *T = LI.getType();
527 if (!T->isAggregateType())
528 return nullptr;
529
Benjamin Kramerc1263532016-03-11 10:20:56 +0000530 StringRef Name = LI.getName();
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000531 assert(LI.getAlignment() && "Alignment must be set at this point");
Mehdi Amini2668a482015-05-07 05:52:40 +0000532
533 if (auto *ST = dyn_cast<StructType>(T)) {
534 // If the struct only have one element, we unpack.
Amaury Sechet61a7d622016-02-17 19:21:28 +0000535 auto NumElements = ST->getNumElements();
536 if (NumElements == 1) {
Mehdi Amini2668a482015-05-07 05:52:40 +0000537 LoadInst *NewLoad = combineLoadToNewType(IC, LI, ST->getTypeAtIndex(0U),
538 ".unpack");
Sanjay Patel4b198802016-02-01 22:23:39 +0000539 return IC.replaceInstUsesWith(LI, IC.Builder->CreateInsertValue(
Amaury Sechet61a7d622016-02-17 19:21:28 +0000540 UndefValue::get(T), NewLoad, 0, Name));
Mehdi Amini2668a482015-05-07 05:52:40 +0000541 }
Mehdi Amini1c131b32015-12-15 01:44:07 +0000542
543 // We don't want to break loads with padding here as we'd loose
544 // the knowledge that padding exists for the rest of the pipeline.
545 const DataLayout &DL = IC.getDataLayout();
546 auto *SL = DL.getStructLayout(ST);
547 if (SL->hasPadding())
548 return nullptr;
549
Amaury Sechet61a7d622016-02-17 19:21:28 +0000550 auto Align = LI.getAlignment();
551 if (!Align)
552 Align = DL.getABITypeAlignment(ST);
553
Mehdi Amini1c131b32015-12-15 01:44:07 +0000554 auto *Addr = LI.getPointerOperand();
Amaury Sechet61a7d622016-02-17 19:21:28 +0000555 auto *IdxType = Type::getInt32Ty(T->getContext());
Mehdi Amini1c131b32015-12-15 01:44:07 +0000556 auto *Zero = ConstantInt::get(IdxType, 0);
Amaury Sechet61a7d622016-02-17 19:21:28 +0000557
558 Value *V = UndefValue::get(T);
559 for (unsigned i = 0; i < NumElements; i++) {
Mehdi Amini1c131b32015-12-15 01:44:07 +0000560 Value *Indices[2] = {
561 Zero,
562 ConstantInt::get(IdxType, i),
563 };
Amaury Sechetda71cb72016-02-17 21:21:29 +0000564 auto *Ptr = IC.Builder->CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices),
Benjamin Kramerc1263532016-03-11 10:20:56 +0000565 Name + ".elt");
Amaury Sechet61a7d622016-02-17 19:21:28 +0000566 auto EltAlign = MinAlign(Align, SL->getElementOffset(i));
Benjamin Kramerc1263532016-03-11 10:20:56 +0000567 auto *L = IC.Builder->CreateAlignedLoad(Ptr, EltAlign, Name + ".unpack");
Mehdi Amini1c131b32015-12-15 01:44:07 +0000568 V = IC.Builder->CreateInsertValue(V, L, i);
569 }
570
571 V->setName(Name);
Sanjay Patel4b198802016-02-01 22:23:39 +0000572 return IC.replaceInstUsesWith(LI, V);
Mehdi Amini2668a482015-05-07 05:52:40 +0000573 }
574
David Majnemer58fb0382015-05-11 05:04:22 +0000575 if (auto *AT = dyn_cast<ArrayType>(T)) {
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000576 auto *ET = AT->getElementType();
577 auto NumElements = AT->getNumElements();
578 if (NumElements == 1) {
579 LoadInst *NewLoad = combineLoadToNewType(IC, LI, ET, ".unpack");
Sanjay Patel4b198802016-02-01 22:23:39 +0000580 return IC.replaceInstUsesWith(LI, IC.Builder->CreateInsertValue(
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000581 UndefValue::get(T), NewLoad, 0, Name));
David Majnemer58fb0382015-05-11 05:04:22 +0000582 }
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000583
584 const DataLayout &DL = IC.getDataLayout();
585 auto EltSize = DL.getTypeAllocSize(ET);
586 auto Align = LI.getAlignment();
587 if (!Align)
588 Align = DL.getABITypeAlignment(T);
589
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000590 auto *Addr = LI.getPointerOperand();
591 auto *IdxType = Type::getInt64Ty(T->getContext());
592 auto *Zero = ConstantInt::get(IdxType, 0);
593
594 Value *V = UndefValue::get(T);
595 uint64_t Offset = 0;
596 for (uint64_t i = 0; i < NumElements; i++) {
597 Value *Indices[2] = {
598 Zero,
599 ConstantInt::get(IdxType, i),
600 };
601 auto *Ptr = IC.Builder->CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices),
Benjamin Kramerc1263532016-03-11 10:20:56 +0000602 Name + ".elt");
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000603 auto *L = IC.Builder->CreateAlignedLoad(Ptr, MinAlign(Align, Offset),
Benjamin Kramerc1263532016-03-11 10:20:56 +0000604 Name + ".unpack");
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000605 V = IC.Builder->CreateInsertValue(V, L, i);
606 Offset += EltSize;
607 }
608
609 V->setName(Name);
610 return IC.replaceInstUsesWith(LI, V);
David Majnemer58fb0382015-05-11 05:04:22 +0000611 }
612
Mehdi Amini2668a482015-05-07 05:52:40 +0000613 return nullptr;
614}
615
Hal Finkel847e05f2015-02-20 03:05:53 +0000616// If we can determine that all possible objects pointed to by the provided
617// pointer value are, not only dereferenceable, but also definitively less than
618// or equal to the provided maximum size, then return true. Otherwise, return
619// false (constant global values and allocas fall into this category).
620//
621// FIXME: This should probably live in ValueTracking (or similar).
622static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000623 const DataLayout &DL) {
Hal Finkel847e05f2015-02-20 03:05:53 +0000624 SmallPtrSet<Value *, 4> Visited;
625 SmallVector<Value *, 4> Worklist(1, V);
626
627 do {
628 Value *P = Worklist.pop_back_val();
629 P = P->stripPointerCasts();
630
631 if (!Visited.insert(P).second)
632 continue;
633
634 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
635 Worklist.push_back(SI->getTrueValue());
636 Worklist.push_back(SI->getFalseValue());
637 continue;
638 }
639
640 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000641 for (Value *IncValue : PN->incoming_values())
642 Worklist.push_back(IncValue);
Hal Finkel847e05f2015-02-20 03:05:53 +0000643 continue;
644 }
645
646 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
Sanjoy Das99042472016-04-17 04:30:43 +0000647 if (GA->isInterposable())
Hal Finkel847e05f2015-02-20 03:05:53 +0000648 return false;
649 Worklist.push_back(GA->getAliasee());
650 continue;
651 }
652
653 // If we know how big this object is, and it is less than MaxSize, continue
654 // searching. Otherwise, return false.
655 if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
656 if (!AI->getAllocatedType()->isSized())
657 return false;
658
659 ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
660 if (!CS)
661 return false;
662
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000663 uint64_t TypeSize = DL.getTypeAllocSize(AI->getAllocatedType());
Hal Finkel847e05f2015-02-20 03:05:53 +0000664 // Make sure that, even if the multiplication below would wrap as an
665 // uint64_t, we still do the right thing.
666 if ((CS->getValue().zextOrSelf(128)*APInt(128, TypeSize)).ugt(MaxSize))
667 return false;
668 continue;
669 }
670
671 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
672 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
673 return false;
674
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000675 uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType());
Hal Finkel847e05f2015-02-20 03:05:53 +0000676 if (InitSize > MaxSize)
677 return false;
678 continue;
679 }
680
681 return false;
682 } while (!Worklist.empty());
683
684 return true;
685}
686
687// If we're indexing into an object of a known size, and the outer index is
688// not a constant, but having any value but zero would lead to undefined
689// behavior, replace it with zero.
690//
691// For example, if we have:
692// @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
693// ...
694// %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x
695// ... = load i32* %arrayidx, align 4
696// Then we know that we can replace %x in the GEP with i64 0.
697//
698// FIXME: We could fold any GEP index to zero that would cause UB if it were
699// not zero. Currently, we only handle the first such index. Also, we could
700// also search through non-zero constant indices if we kept track of the
701// offsets those indices implied.
702static bool canReplaceGEPIdxWithZero(InstCombiner &IC, GetElementPtrInst *GEPI,
703 Instruction *MemI, unsigned &Idx) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000704 if (GEPI->getNumOperands() < 2)
Hal Finkel847e05f2015-02-20 03:05:53 +0000705 return false;
706
707 // Find the first non-zero index of a GEP. If all indices are zero, return
708 // one past the last index.
709 auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
710 unsigned I = 1;
711 for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
712 Value *V = GEPI->getOperand(I);
713 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
714 if (CI->isZero())
715 continue;
716
717 break;
718 }
719
720 return I;
721 };
722
723 // Skip through initial 'zero' indices, and find the corresponding pointer
724 // type. See if the next index is not a constant.
725 Idx = FirstNZIdx(GEPI);
726 if (Idx == GEPI->getNumOperands())
727 return false;
728 if (isa<Constant>(GEPI->getOperand(Idx)))
729 return false;
730
731 SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
Eduard Burtescu19eb0312016-01-19 17:28:00 +0000732 Type *AllocTy =
733 GetElementPtrInst::getIndexedType(GEPI->getSourceElementType(), Ops);
Hal Finkel847e05f2015-02-20 03:05:53 +0000734 if (!AllocTy || !AllocTy->isSized())
735 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000736 const DataLayout &DL = IC.getDataLayout();
737 uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy);
Hal Finkel847e05f2015-02-20 03:05:53 +0000738
739 // If there are more indices after the one we might replace with a zero, make
740 // sure they're all non-negative. If any of them are negative, the overall
741 // address being computed might be before the base address determined by the
742 // first non-zero index.
743 auto IsAllNonNegative = [&]() {
744 for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
745 bool KnownNonNegative, KnownNegative;
746 IC.ComputeSignBit(GEPI->getOperand(i), KnownNonNegative,
747 KnownNegative, 0, MemI);
748 if (KnownNonNegative)
749 continue;
750 return false;
751 }
752
753 return true;
754 };
755
756 // FIXME: If the GEP is not inbounds, and there are extra indices after the
757 // one we'll replace, those could cause the address computation to wrap
758 // (rendering the IsAllNonNegative() check below insufficient). We can do
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000759 // better, ignoring zero indices (and other indices we can prove small
Hal Finkel847e05f2015-02-20 03:05:53 +0000760 // enough not to wrap).
761 if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
762 return false;
763
764 // Note that isObjectSizeLessThanOrEq will return true only if the pointer is
765 // also known to be dereferenceable.
766 return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
767 IsAllNonNegative();
768}
769
770// If we're indexing into an object with a variable index for the memory
771// access, but the object has only one element, we can assume that the index
772// will always be zero. If we replace the GEP, return it.
773template <typename T>
774static Instruction *replaceGEPIdxWithZero(InstCombiner &IC, Value *Ptr,
775 T &MemI) {
776 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
777 unsigned Idx;
778 if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
779 Instruction *NewGEPI = GEPI->clone();
780 NewGEPI->setOperand(Idx,
781 ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
782 NewGEPI->insertBefore(GEPI);
783 MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI);
784 return NewGEPI;
785 }
786 }
787
788 return nullptr;
789}
790
Chris Lattnera65e2f72010-01-05 05:57:49 +0000791Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
792 Value *Op = LI.getOperand(0);
793
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000794 // Try to canonicalize the loaded type.
795 if (Instruction *Res = combineLoadToOperationType(*this, LI))
796 return Res;
797
Chris Lattnera65e2f72010-01-05 05:57:49 +0000798 // Attempt to improve the alignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000799 unsigned KnownAlign = getOrEnforceKnownAlignment(
800 Op, DL.getPrefTypeAlignment(LI.getType()), DL, &LI, AC, DT);
801 unsigned LoadAlign = LI.getAlignment();
802 unsigned EffectiveLoadAlign =
803 LoadAlign != 0 ? LoadAlign : DL.getABITypeAlignment(LI.getType());
Dan Gohman36196602010-08-03 18:20:32 +0000804
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000805 if (KnownAlign > EffectiveLoadAlign)
806 LI.setAlignment(KnownAlign);
807 else if (LoadAlign == 0)
808 LI.setAlignment(EffectiveLoadAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000809
Hal Finkel847e05f2015-02-20 03:05:53 +0000810 // Replace GEP indices if possible.
811 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) {
812 Worklist.Add(NewGEPI);
813 return &LI;
814 }
815
Mehdi Amini2668a482015-05-07 05:52:40 +0000816 if (Instruction *Res = unpackLoadToAggregate(*this, LI))
817 return Res;
818
Chris Lattnera65e2f72010-01-05 05:57:49 +0000819 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +0000820 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +0000821 // separated by a few arithmetic operations.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000822 BasicBlock::iterator BBI(LI);
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000823 AAMDNodes AATags;
Larisse Voufo532bf712015-09-18 19:14:35 +0000824 if (Value *AvailableVal =
Eduard Burtescue2a69172016-01-22 01:51:51 +0000825 FindAvailableLoadedValue(&LI, LI.getParent(), BBI,
Larisse Voufo532bf712015-09-18 19:14:35 +0000826 DefMaxInstsToScan, AA, &AATags)) {
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000827 if (LoadInst *NLI = dyn_cast<LoadInst>(AvailableVal)) {
828 unsigned KnownIDs[] = {
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000829 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
830 LLVMContext::MD_noalias, LLVMContext::MD_range,
831 LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull,
832 LLVMContext::MD_invariant_group, LLVMContext::MD_align,
833 LLVMContext::MD_dereferenceable,
834 LLVMContext::MD_dereferenceable_or_null};
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000835 combineMetadata(NLI, &LI, KnownIDs);
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000836 };
837
Sanjay Patel4b198802016-02-01 22:23:39 +0000838 return replaceInstUsesWith(
Chandler Carruth1a3c2c42014-11-25 08:20:27 +0000839 LI, Builder->CreateBitOrPointerCast(AvailableVal, LI.getType(),
840 LI.getName() + ".cast"));
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000841 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000842
Philip Reames3ac07182016-04-21 17:45:05 +0000843 // None of the following transforms are legal for volatile/ordered atomic
844 // loads. Most of them do apply for unordered atomics.
845 if (!LI.isUnordered()) return nullptr;
Philip Reamesac550902016-04-21 17:03:33 +0000846
Chris Lattnera65e2f72010-01-05 05:57:49 +0000847 // load(gep null, ...) -> unreachable
848 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
849 const Value *GEPI0 = GEPI->getOperand(0);
850 // TODO: Consider a target hook for valid address spaces for this xform.
851 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
852 // Insert a new store to null instruction before the load to indicate
853 // that this code is not reachable. We do this instead of inserting
854 // an unreachable instruction directly because we cannot modify the
855 // CFG.
856 new StoreInst(UndefValue::get(LI.getType()),
857 Constant::getNullValue(Op->getType()), &LI);
Sanjay Patel4b198802016-02-01 22:23:39 +0000858 return replaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000859 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000860 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000861
862 // load null/undef -> unreachable
863 // TODO: Consider a target hook for valid address spaces for this xform.
864 if (isa<UndefValue>(Op) ||
865 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
866 // Insert a new store to null instruction before the load to indicate that
867 // this code is not reachable. We do this instead of inserting an
868 // unreachable instruction directly because we cannot modify the CFG.
869 new StoreInst(UndefValue::get(LI.getType()),
870 Constant::getNullValue(Op->getType()), &LI);
Sanjay Patel4b198802016-02-01 22:23:39 +0000871 return replaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000872 }
873
Chris Lattnera65e2f72010-01-05 05:57:49 +0000874 if (Op->hasOneUse()) {
875 // Change select and PHI nodes to select values instead of addresses: this
876 // helps alias analysis out a lot, allows many others simplifications, and
877 // exposes redundancy in the code.
878 //
879 // Note that we cannot do the transformation unless we know that the
880 // introduced loads cannot trap! Something like this is valid as long as
881 // the condition is always false: load (select bool %C, int* null, int* %G),
882 // but it would not be valid if we transformed it to load from null
883 // unconditionally.
884 //
885 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
886 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +0000887 unsigned Align = LI.getAlignment();
Artur Pilipenko6dd69692016-01-15 15:27:46 +0000888 if (isSafeToLoadUnconditionally(SI->getOperand(1), Align, SI) &&
889 isSafeToLoadUnconditionally(SI->getOperand(2), Align, SI)) {
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000890 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
Bob Wilson56600a12010-01-30 04:42:39 +0000891 SI->getOperand(1)->getName()+".val");
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000892 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
Bob Wilson56600a12010-01-30 04:42:39 +0000893 SI->getOperand(2)->getName()+".val");
Philip Reamesa98c7ea2016-04-21 17:59:40 +0000894 assert(LI.isUnordered() && "implied by above");
Bob Wilson56600a12010-01-30 04:42:39 +0000895 V1->setAlignment(Align);
Philip Reamesa98c7ea2016-04-21 17:59:40 +0000896 V1->setAtomic(LI.getOrdering(), LI.getSynchScope());
Bob Wilson56600a12010-01-30 04:42:39 +0000897 V2->setAlignment(Align);
Philip Reamesa98c7ea2016-04-21 17:59:40 +0000898 V2->setAtomic(LI.getOrdering(), LI.getSynchScope());
Philip Reameseedef732016-04-22 20:33:48 +0000899 assert(!LI.isVolatile() && "volatile unhandled here");
Chris Lattnera65e2f72010-01-05 05:57:49 +0000900 return SelectInst::Create(SI->getCondition(), V1, V2);
901 }
902
903 // load (select (cond, null, P)) -> load P
Larisse Voufo532bf712015-09-18 19:14:35 +0000904 if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
Philip Reames5ad26c32014-12-29 22:46:21 +0000905 LI.getPointerAddressSpace() == 0) {
906 LI.setOperand(0, SI->getOperand(2));
907 return &LI;
908 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000909
910 // load (select (cond, P, null)) -> load P
Philip Reames5ad26c32014-12-29 22:46:21 +0000911 if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
912 LI.getPointerAddressSpace() == 0) {
913 LI.setOperand(0, SI->getOperand(1));
914 return &LI;
915 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000916 }
917 }
Craig Topperf40110f2014-04-25 05:29:35 +0000918 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000919}
920
Chandler Carruth816d26f2014-11-25 10:09:51 +0000921/// \brief Combine stores to match the type of value being stored.
922///
923/// The core idea here is that the memory does not have any intrinsic type and
924/// where we can we should match the type of a store to the type of value being
925/// stored.
926///
927/// However, this routine must never change the width of a store or the number of
928/// stores as that would introduce a semantic change. This combine is expected to
929/// be a semantic no-op which just allows stores to more closely model the types
930/// of their incoming values.
931///
932/// Currently, we also refuse to change the precise type used for an atomic or
933/// volatile store. This is debatable, and might be reasonable to change later.
934/// However, it is risky in case some backend or other part of LLVM is relying
935/// on the exact type stored to select appropriate atomic operations.
936///
937/// \returns true if the store was successfully combined away. This indicates
938/// the caller must erase the store instruction. We have to let the caller erase
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000939/// the store instruction as otherwise there is no way to signal whether it was
Chandler Carruth816d26f2014-11-25 10:09:51 +0000940/// combined or not: IC.EraseInstFromFunction returns a null pointer.
941static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) {
Philip Reameseedef732016-04-22 20:33:48 +0000942 // FIXME: We could probably with some care handle both volatile and ordered
943 // atomic stores here but it isn't clear that this is important.
944 if (!SI.isUnordered())
Chandler Carruth816d26f2014-11-25 10:09:51 +0000945 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000946
Chandler Carruth816d26f2014-11-25 10:09:51 +0000947 Value *V = SI.getValueOperand();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000948
Chandler Carruth816d26f2014-11-25 10:09:51 +0000949 // Fold away bit casts of the stored value by storing the original type.
950 if (auto *BC = dyn_cast<BitCastInst>(V)) {
Chandler Carrutha7f247e2014-12-09 19:21:16 +0000951 V = BC->getOperand(0);
Chandler Carruth2135b972015-01-21 23:45:01 +0000952 combineStoreToNewValue(IC, SI, V);
Chandler Carruth816d26f2014-11-25 10:09:51 +0000953 return true;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000954 }
955
JF Bastienc22d2992016-04-21 19:53:39 +0000956 // FIXME: We should also canonicalize stores of vectors when their elements
957 // are cast to other types.
Chandler Carruth816d26f2014-11-25 10:09:51 +0000958 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000959}
960
Mehdi Aminib344ac92015-03-14 22:19:33 +0000961static bool unpackStoreToAggregate(InstCombiner &IC, StoreInst &SI) {
962 // FIXME: We could probably with some care handle both volatile and atomic
963 // stores here but it isn't clear that this is important.
964 if (!SI.isSimple())
965 return false;
966
967 Value *V = SI.getValueOperand();
968 Type *T = V->getType();
969
970 if (!T->isAggregateType())
971 return false;
972
Mehdi Amini2668a482015-05-07 05:52:40 +0000973 if (auto *ST = dyn_cast<StructType>(T)) {
Mehdi Aminib344ac92015-03-14 22:19:33 +0000974 // If the struct only have one element, we unpack.
Mehdi Amini1c131b32015-12-15 01:44:07 +0000975 unsigned Count = ST->getNumElements();
976 if (Count == 1) {
Mehdi Aminib344ac92015-03-14 22:19:33 +0000977 V = IC.Builder->CreateExtractValue(V, 0);
978 combineStoreToNewValue(IC, SI, V);
979 return true;
980 }
Mehdi Amini1c131b32015-12-15 01:44:07 +0000981
982 // We don't want to break loads with padding here as we'd loose
983 // the knowledge that padding exists for the rest of the pipeline.
984 const DataLayout &DL = IC.getDataLayout();
985 auto *SL = DL.getStructLayout(ST);
986 if (SL->hasPadding())
987 return false;
988
Amaury Sechet61a7d622016-02-17 19:21:28 +0000989 auto Align = SI.getAlignment();
990 if (!Align)
991 Align = DL.getABITypeAlignment(ST);
992
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +0000993 SmallString<16> EltName = V->getName();
994 EltName += ".elt";
Mehdi Amini1c131b32015-12-15 01:44:07 +0000995 auto *Addr = SI.getPointerOperand();
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +0000996 SmallString<16> AddrName = Addr->getName();
997 AddrName += ".repack";
Amaury Sechet61a7d622016-02-17 19:21:28 +0000998
Mehdi Amini1c131b32015-12-15 01:44:07 +0000999 auto *IdxType = Type::getInt32Ty(ST->getContext());
1000 auto *Zero = ConstantInt::get(IdxType, 0);
1001 for (unsigned i = 0; i < Count; i++) {
1002 Value *Indices[2] = {
1003 Zero,
1004 ConstantInt::get(IdxType, i),
1005 };
Amaury Sechetda71cb72016-02-17 21:21:29 +00001006 auto *Ptr = IC.Builder->CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices),
1007 AddrName);
Mehdi Amini1c131b32015-12-15 01:44:07 +00001008 auto *Val = IC.Builder->CreateExtractValue(V, i, EltName);
Amaury Sechet61a7d622016-02-17 19:21:28 +00001009 auto EltAlign = MinAlign(Align, SL->getElementOffset(i));
1010 IC.Builder->CreateAlignedStore(Val, Ptr, EltAlign);
Mehdi Amini1c131b32015-12-15 01:44:07 +00001011 }
1012
1013 return true;
Mehdi Aminib344ac92015-03-14 22:19:33 +00001014 }
1015
David Majnemer75364602015-05-11 05:04:27 +00001016 if (auto *AT = dyn_cast<ArrayType>(T)) {
1017 // If the array only have one element, we unpack.
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001018 auto NumElements = AT->getNumElements();
1019 if (NumElements == 1) {
David Majnemer75364602015-05-11 05:04:27 +00001020 V = IC.Builder->CreateExtractValue(V, 0);
1021 combineStoreToNewValue(IC, SI, V);
1022 return true;
1023 }
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001024
1025 const DataLayout &DL = IC.getDataLayout();
1026 auto EltSize = DL.getTypeAllocSize(AT->getElementType());
1027 auto Align = SI.getAlignment();
1028 if (!Align)
1029 Align = DL.getABITypeAlignment(T);
1030
1031 SmallString<16> EltName = V->getName();
1032 EltName += ".elt";
1033 auto *Addr = SI.getPointerOperand();
1034 SmallString<16> AddrName = Addr->getName();
1035 AddrName += ".repack";
1036
1037 auto *IdxType = Type::getInt64Ty(T->getContext());
1038 auto *Zero = ConstantInt::get(IdxType, 0);
1039
1040 uint64_t Offset = 0;
1041 for (uint64_t i = 0; i < NumElements; i++) {
1042 Value *Indices[2] = {
1043 Zero,
1044 ConstantInt::get(IdxType, i),
1045 };
1046 auto *Ptr = IC.Builder->CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices),
1047 AddrName);
1048 auto *Val = IC.Builder->CreateExtractValue(V, i, EltName);
1049 auto EltAlign = MinAlign(Align, Offset);
1050 IC.Builder->CreateAlignedStore(Val, Ptr, EltAlign);
1051 Offset += EltSize;
1052 }
1053
1054 return true;
David Majnemer75364602015-05-11 05:04:27 +00001055 }
1056
Mehdi Aminib344ac92015-03-14 22:19:33 +00001057 return false;
1058}
1059
Chris Lattnera65e2f72010-01-05 05:57:49 +00001060/// equivalentAddressValues - Test if A and B will obviously have the same
1061/// value. This includes recognizing that %t0 and %t1 will have the same
1062/// value in code like this:
1063/// %t0 = getelementptr \@a, 0, 3
1064/// store i32 0, i32* %t0
1065/// %t1 = getelementptr \@a, 0, 3
1066/// %t2 = load i32* %t1
1067///
1068static bool equivalentAddressValues(Value *A, Value *B) {
1069 // Test if the values are trivially equivalent.
1070 if (A == B) return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001071
Chris Lattnera65e2f72010-01-05 05:57:49 +00001072 // Test if the values come form identical arithmetic instructions.
1073 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
1074 // its only used to compare two uses within the same basic block, which
1075 // means that they'll always either have the same value or one of them
1076 // will have an undefined value.
1077 if (isa<BinaryOperator>(A) ||
1078 isa<CastInst>(A) ||
1079 isa<PHINode>(A) ||
1080 isa<GetElementPtrInst>(A))
1081 if (Instruction *BI = dyn_cast<Instruction>(B))
1082 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
1083 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001084
Chris Lattnera65e2f72010-01-05 05:57:49 +00001085 // Otherwise they may not be equivalent.
1086 return false;
1087}
1088
Chris Lattnera65e2f72010-01-05 05:57:49 +00001089Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
1090 Value *Val = SI.getOperand(0);
1091 Value *Ptr = SI.getOperand(1);
1092
Chandler Carruth816d26f2014-11-25 10:09:51 +00001093 // Try to canonicalize the stored type.
1094 if (combineStoreToValueType(*this, SI))
Sanjay Patel4b198802016-02-01 22:23:39 +00001095 return eraseInstFromFunction(SI);
Chandler Carruth816d26f2014-11-25 10:09:51 +00001096
Chris Lattnera65e2f72010-01-05 05:57:49 +00001097 // Attempt to improve the alignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001098 unsigned KnownAlign = getOrEnforceKnownAlignment(
1099 Ptr, DL.getPrefTypeAlignment(Val->getType()), DL, &SI, AC, DT);
1100 unsigned StoreAlign = SI.getAlignment();
1101 unsigned EffectiveStoreAlign =
1102 StoreAlign != 0 ? StoreAlign : DL.getABITypeAlignment(Val->getType());
Dan Gohman36196602010-08-03 18:20:32 +00001103
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001104 if (KnownAlign > EffectiveStoreAlign)
1105 SI.setAlignment(KnownAlign);
1106 else if (StoreAlign == 0)
1107 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001108
Mehdi Aminib344ac92015-03-14 22:19:33 +00001109 // Try to canonicalize the stored type.
1110 if (unpackStoreToAggregate(*this, SI))
Sanjay Patel4b198802016-02-01 22:23:39 +00001111 return eraseInstFromFunction(SI);
Mehdi Aminib344ac92015-03-14 22:19:33 +00001112
Hal Finkel847e05f2015-02-20 03:05:53 +00001113 // Replace GEP indices if possible.
1114 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) {
1115 Worklist.Add(NewGEPI);
1116 return &SI;
1117 }
1118
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001119 // Don't hack volatile/ordered stores.
1120 // FIXME: Some bits are legal for ordered atomic stores; needs refactoring.
1121 if (!SI.isUnordered()) return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +00001122
1123 // If the RHS is an alloca with a single use, zapify the store, making the
1124 // alloca dead.
1125 if (Ptr->hasOneUse()) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001126 if (isa<AllocaInst>(Ptr))
Sanjay Patel4b198802016-02-01 22:23:39 +00001127 return eraseInstFromFunction(SI);
Eli Friedman8bc586e2011-08-15 22:09:40 +00001128 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
1129 if (isa<AllocaInst>(GEP->getOperand(0))) {
1130 if (GEP->getOperand(0)->hasOneUse())
Sanjay Patel4b198802016-02-01 22:23:39 +00001131 return eraseInstFromFunction(SI);
Eli Friedman8bc586e2011-08-15 22:09:40 +00001132 }
1133 }
1134 }
1135
Chris Lattnera65e2f72010-01-05 05:57:49 +00001136 // Do really simple DSE, to catch cases where there are several consecutive
1137 // stores to the same location, separated by a few arithmetic operations. This
1138 // situation often occurs with bitfield accesses.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001139 BasicBlock::iterator BBI(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001140 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
1141 --ScanInsts) {
1142 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001143 // Don't count debug info directives, lest they affect codegen,
1144 // and we skip pointer-to-pointer bitcasts, which are NOPs.
1145 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001146 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001147 ScanInsts++;
1148 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001149 }
1150
Chris Lattnera65e2f72010-01-05 05:57:49 +00001151 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
1152 // Prev store isn't volatile, and stores to the same location?
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001153 if (PrevSI->isUnordered() && equivalentAddressValues(PrevSI->getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +00001154 SI.getOperand(1))) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001155 ++NumDeadStore;
1156 ++BBI;
Sanjay Patel4b198802016-02-01 22:23:39 +00001157 eraseInstFromFunction(*PrevSI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001158 continue;
1159 }
1160 break;
1161 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001162
Chris Lattnera65e2f72010-01-05 05:57:49 +00001163 // If this is a load, we have to stop. However, if the loaded value is from
1164 // the pointer we're loading and is producing the pointer we're storing,
1165 // then *this* store is dead (X = load P; store X -> P).
1166 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001167 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr)) {
1168 assert(SI.isUnordered() && "can't eliminate ordering operation");
Sanjay Patel4b198802016-02-01 22:23:39 +00001169 return eraseInstFromFunction(SI);
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001170 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001171
Chris Lattnera65e2f72010-01-05 05:57:49 +00001172 // Otherwise, this is a load from some other location. Stores before it
1173 // may not be dead.
1174 break;
1175 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001176
Chris Lattnera65e2f72010-01-05 05:57:49 +00001177 // Don't skip over loads or things that can modify memory.
1178 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
1179 break;
1180 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001181
1182 // store X, null -> turns into 'unreachable' in SimplifyCFG
1183 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
1184 if (!isa<UndefValue>(Val)) {
1185 SI.setOperand(0, UndefValue::get(Val->getType()));
1186 if (Instruction *U = dyn_cast<Instruction>(Val))
1187 Worklist.Add(U); // Dropped a use.
1188 }
Craig Topperf40110f2014-04-25 05:29:35 +00001189 return nullptr; // Do not modify these!
Chris Lattnera65e2f72010-01-05 05:57:49 +00001190 }
1191
1192 // store undef, Ptr -> noop
1193 if (isa<UndefValue>(Val))
Sanjay Patel4b198802016-02-01 22:23:39 +00001194 return eraseInstFromFunction(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001195
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001196 // The code below needs to be audited and adjusted for unordered atomics
1197 if (!SI.isSimple())
1198 return nullptr;
1199
Chris Lattnera65e2f72010-01-05 05:57:49 +00001200 // If this store is the last instruction in the basic block (possibly
Victor Hernandez5f5abd52010-01-21 23:07:15 +00001201 // excepting debug info instructions), and if the block ends with an
1202 // unconditional branch, try to move it to the successor block.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001203 BBI = SI.getIterator();
Chris Lattnera65e2f72010-01-05 05:57:49 +00001204 do {
1205 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001206 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001207 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Chris Lattnera65e2f72010-01-05 05:57:49 +00001208 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
1209 if (BI->isUnconditional())
1210 if (SimplifyStoreAtEndOfBlock(SI))
Craig Topperf40110f2014-04-25 05:29:35 +00001211 return nullptr; // xform done!
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001212
Craig Topperf40110f2014-04-25 05:29:35 +00001213 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001214}
1215
1216/// SimplifyStoreAtEndOfBlock - Turn things like:
1217/// if () { *P = v1; } else { *P = v2 }
1218/// into a phi node with a store in the successor.
1219///
1220/// Simplify things like:
1221/// *P = v1; if () { *P = v2; }
1222/// into a phi node with a store in the successor.
1223///
1224bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
1225 BasicBlock *StoreBB = SI.getParent();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001226
Chris Lattnera65e2f72010-01-05 05:57:49 +00001227 // Check to see if the successor block has exactly two incoming edges. If
1228 // so, see if the other predecessor contains a store to the same location.
1229 // if so, insert a PHI node (if needed) and move the stores down.
1230 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001231
Chris Lattnera65e2f72010-01-05 05:57:49 +00001232 // Determine whether Dest has exactly two predecessors and, if so, compute
1233 // the other predecessor.
1234 pred_iterator PI = pred_begin(DestBB);
Gabor Greif1b787df2010-07-12 15:48:26 +00001235 BasicBlock *P = *PI;
Craig Topperf40110f2014-04-25 05:29:35 +00001236 BasicBlock *OtherBB = nullptr;
Gabor Greif1b787df2010-07-12 15:48:26 +00001237
1238 if (P != StoreBB)
1239 OtherBB = P;
1240
1241 if (++PI == pred_end(DestBB))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001242 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001243
Gabor Greif1b787df2010-07-12 15:48:26 +00001244 P = *PI;
1245 if (P != StoreBB) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001246 if (OtherBB)
1247 return false;
Gabor Greif1b787df2010-07-12 15:48:26 +00001248 OtherBB = P;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001249 }
1250 if (++PI != pred_end(DestBB))
1251 return false;
1252
1253 // Bail out if all the relevant blocks aren't distinct (this can happen,
1254 // for example, if SI is in an infinite loop)
1255 if (StoreBB == DestBB || OtherBB == DestBB)
1256 return false;
1257
1258 // Verify that the other block ends in a branch and is not otherwise empty.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001259 BasicBlock::iterator BBI(OtherBB->getTerminator());
Chris Lattnera65e2f72010-01-05 05:57:49 +00001260 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
1261 if (!OtherBr || BBI == OtherBB->begin())
1262 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001263
Chris Lattnera65e2f72010-01-05 05:57:49 +00001264 // If the other block ends in an unconditional branch, check for the 'if then
1265 // else' case. there is an instruction before the branch.
Craig Topperf40110f2014-04-25 05:29:35 +00001266 StoreInst *OtherStore = nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001267 if (OtherBr->isUnconditional()) {
1268 --BBI;
1269 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001270 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001271 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001272 if (BBI==OtherBB->begin())
1273 return false;
1274 --BBI;
1275 }
Eli Friedman8bc586e2011-08-15 22:09:40 +00001276 // If this isn't a store, isn't a store to the same location, or is not the
1277 // right kind of store, bail out.
Chris Lattnera65e2f72010-01-05 05:57:49 +00001278 OtherStore = dyn_cast<StoreInst>(BBI);
1279 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +00001280 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001281 return false;
1282 } else {
1283 // Otherwise, the other block ended with a conditional branch. If one of the
1284 // destinations is StoreBB, then we have the if/then case.
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001285 if (OtherBr->getSuccessor(0) != StoreBB &&
Chris Lattnera65e2f72010-01-05 05:57:49 +00001286 OtherBr->getSuccessor(1) != StoreBB)
1287 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001288
Chris Lattnera65e2f72010-01-05 05:57:49 +00001289 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
1290 // if/then triangle. See if there is a store to the same ptr as SI that
1291 // lives in OtherBB.
1292 for (;; --BBI) {
1293 // Check to see if we find the matching store.
1294 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
1295 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +00001296 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001297 return false;
1298 break;
1299 }
1300 // If we find something that may be using or overwriting the stored
1301 // value, or if we run out of instructions, we can't do the xform.
1302 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
1303 BBI == OtherBB->begin())
1304 return false;
1305 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001306
Chris Lattnera65e2f72010-01-05 05:57:49 +00001307 // In order to eliminate the store in OtherBr, we have to
1308 // make sure nothing reads or overwrites the stored value in
1309 // StoreBB.
1310 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1311 // FIXME: This should really be AA driven.
1312 if (I->mayReadFromMemory() || I->mayWriteToMemory())
1313 return false;
1314 }
1315 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001316
Chris Lattnera65e2f72010-01-05 05:57:49 +00001317 // Insert a PHI node now if we need it.
1318 Value *MergedVal = OtherStore->getOperand(0);
1319 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +00001320 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +00001321 PN->addIncoming(SI.getOperand(0), SI.getParent());
1322 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
1323 MergedVal = InsertNewInstBefore(PN, DestBB->front());
1324 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001325
Chris Lattnera65e2f72010-01-05 05:57:49 +00001326 // Advance to a place where it is safe to insert the new store and
1327 // insert it.
Bill Wendling8ddfc092011-08-16 20:45:24 +00001328 BBI = DestBB->getFirstInsertionPt();
Eli Friedman35211c62011-05-27 00:19:40 +00001329 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +00001330 SI.isVolatile(),
1331 SI.getAlignment(),
1332 SI.getOrdering(),
1333 SI.getSynchScope());
Eli Friedman35211c62011-05-27 00:19:40 +00001334 InsertNewInstBefore(NewSI, *BBI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001335 NewSI->setDebugLoc(OtherStore->getDebugLoc());
Eli Friedman35211c62011-05-27 00:19:40 +00001336
Hal Finkelcc39b672014-07-24 12:16:19 +00001337 // If the two stores had AA tags, merge them.
1338 AAMDNodes AATags;
1339 SI.getAAMetadata(AATags);
1340 if (AATags) {
1341 OtherStore->getAAMetadata(AATags, /* Merge = */ true);
1342 NewSI->setAAMetadata(AATags);
1343 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001344
Chris Lattnera65e2f72010-01-05 05:57:49 +00001345 // Nuke the old stores.
Sanjay Patel4b198802016-02-01 22:23:39 +00001346 eraseInstFromFunction(SI);
1347 eraseInstFromFunction(*OtherStore);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001348 return true;
1349}