blob: 8dcc6351ac79002375e0217345b56180b50dbd02 [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(
Justin Bogner99798402016-08-05 01:06:44 +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)),
Philip Reames6f4d0082016-05-06 22:17:01 +0000329 LI.getAlignment(), LI.isVolatile(), LI.getName() + Suffix);
330 NewLoad->setAtomic(LI.getOrdering(), LI.getSynchScope());
Charles Davis33d1dc02015-02-25 05:10:25 +0000331 MDBuilder MDB(NewLoad->getContext());
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000332 for (const auto &MDPair : MD) {
333 unsigned ID = MDPair.first;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000334 MDNode *N = MDPair.second;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000335 // Note, essentially every kind of metadata should be preserved here! This
336 // routine is supposed to clone a load instruction changing *only its type*.
337 // The only metadata it makes sense to drop is metadata which is invalidated
338 // when the pointer type changes. This should essentially never be the case
339 // in LLVM, but we explicitly switch over only known metadata to be
340 // conservatively correct. If you are adding metadata to LLVM which pertains
341 // to loads, you almost certainly want to add it here.
342 switch (ID) {
343 case LLVMContext::MD_dbg:
344 case LLVMContext::MD_tbaa:
345 case LLVMContext::MD_prof:
346 case LLVMContext::MD_fpmath:
347 case LLVMContext::MD_tbaa_struct:
348 case LLVMContext::MD_invariant_load:
349 case LLVMContext::MD_alias_scope:
350 case LLVMContext::MD_noalias:
Philip Reames5a3f5f72014-10-21 00:13:20 +0000351 case LLVMContext::MD_nontemporal:
352 case LLVMContext::MD_mem_parallel_loop_access:
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000353 // All of these directly apply.
354 NewLoad->setMetadata(ID, N);
355 break;
356
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000357 case LLVMContext::MD_nonnull:
Charles Davis33d1dc02015-02-25 05:10:25 +0000358 // This only directly applies if the new type is also a pointer.
359 if (NewTy->isPointerTy()) {
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000360 NewLoad->setMetadata(ID, N);
Charles Davis33d1dc02015-02-25 05:10:25 +0000361 break;
362 }
363 // If it's integral now, translate it to !range metadata.
364 if (NewTy->isIntegerTy()) {
365 auto *ITy = cast<IntegerType>(NewTy);
366 auto *NullInt = ConstantExpr::getPtrToInt(
367 ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
368 auto *NonNullInt =
369 ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
370 NewLoad->setMetadata(LLVMContext::MD_range,
371 MDB.createRange(NonNullInt, NullInt));
372 }
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000373 break;
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000374 case LLVMContext::MD_align:
375 case LLVMContext::MD_dereferenceable:
376 case LLVMContext::MD_dereferenceable_or_null:
377 // These only directly apply if the new type is also a pointer.
378 if (NewTy->isPointerTy())
379 NewLoad->setMetadata(ID, N);
380 break;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000381 case LLVMContext::MD_range:
382 // FIXME: It would be nice to propagate this in some way, but the type
Charles Davis33d1dc02015-02-25 05:10:25 +0000383 // conversions make it hard. If the new type is a pointer, we could
384 // translate it to !nonnull metadata.
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000385 break;
386 }
387 }
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000388 return NewLoad;
389}
390
Chandler Carruthfa11d832015-01-22 03:34:54 +0000391/// \brief Combine a store to a new type.
392///
393/// Returns the newly created store instruction.
394static StoreInst *combineStoreToNewValue(InstCombiner &IC, StoreInst &SI, Value *V) {
395 Value *Ptr = SI.getPointerOperand();
396 unsigned AS = SI.getPointerAddressSpace();
397 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
398 SI.getAllMetadata(MD);
399
400 StoreInst *NewStore = IC.Builder->CreateAlignedStore(
401 V, IC.Builder->CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
Philip Reames6f4d0082016-05-06 22:17:01 +0000402 SI.getAlignment(), SI.isVolatile());
403 NewStore->setAtomic(SI.getOrdering(), SI.getSynchScope());
Chandler Carruthfa11d832015-01-22 03:34:54 +0000404 for (const auto &MDPair : MD) {
405 unsigned ID = MDPair.first;
406 MDNode *N = MDPair.second;
407 // Note, essentially every kind of metadata should be preserved here! This
408 // routine is supposed to clone a store instruction changing *only its
409 // type*. The only metadata it makes sense to drop is metadata which is
410 // invalidated when the pointer type changes. This should essentially
411 // never be the case in LLVM, but we explicitly switch over only known
412 // metadata to be conservatively correct. If you are adding metadata to
413 // LLVM which pertains to stores, you almost certainly want to add it
414 // here.
415 switch (ID) {
416 case LLVMContext::MD_dbg:
417 case LLVMContext::MD_tbaa:
418 case LLVMContext::MD_prof:
419 case LLVMContext::MD_fpmath:
420 case LLVMContext::MD_tbaa_struct:
421 case LLVMContext::MD_alias_scope:
422 case LLVMContext::MD_noalias:
423 case LLVMContext::MD_nontemporal:
424 case LLVMContext::MD_mem_parallel_loop_access:
Chandler Carruthfa11d832015-01-22 03:34:54 +0000425 // All of these directly apply.
426 NewStore->setMetadata(ID, N);
427 break;
428
429 case LLVMContext::MD_invariant_load:
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000430 case LLVMContext::MD_nonnull:
Chandler Carruthfa11d832015-01-22 03:34:54 +0000431 case LLVMContext::MD_range:
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000432 case LLVMContext::MD_align:
433 case LLVMContext::MD_dereferenceable:
434 case LLVMContext::MD_dereferenceable_or_null:
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000435 // These don't apply for stores.
Chandler Carruthfa11d832015-01-22 03:34:54 +0000436 break;
437 }
438 }
439
440 return NewStore;
441}
442
JF Bastien3e2e69f2016-04-21 19:41:48 +0000443/// \brief Combine loads to match the type of their uses' value after looking
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000444/// through intervening bitcasts.
445///
446/// The core idea here is that if the result of a load is used in an operation,
447/// we should load the type most conducive to that operation. For example, when
448/// loading an integer and converting that immediately to a pointer, we should
449/// instead directly load a pointer.
450///
451/// However, this routine must never change the width of a load or the number of
452/// loads as that would introduce a semantic change. This combine is expected to
453/// be a semantic no-op which just allows loads to more closely model the types
454/// of their consuming operations.
455///
456/// Currently, we also refuse to change the precise type used for an atomic load
457/// or a volatile load. This is debatable, and might be reasonable to change
458/// later. However, it is risky in case some backend or other part of LLVM is
459/// relying on the exact type loaded to select appropriate atomic operations.
460static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
Philip Reames6f4d0082016-05-06 22:17:01 +0000461 // FIXME: We could probably with some care handle both volatile and ordered
462 // atomic loads here but it isn't clear that this is important.
463 if (!LI.isUnordered())
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000464 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000465
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000466 if (LI.use_empty())
467 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000468
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000469 Type *Ty = LI.getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000470 const DataLayout &DL = IC.getDataLayout();
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000471
472 // Try to canonicalize loads which are only ever stored to operate over
473 // integers instead of any other type. We only do this when the loaded type
474 // is sized and has a size exactly the same as its store size and the store
475 // size is a legal integer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000476 if (!Ty->isIntegerTy() && Ty->isSized() &&
477 DL.isLegalInteger(DL.getTypeStoreSizeInBits(Ty)) &&
Sanjoy Dasba04d3a2016-08-06 02:58:48 +0000478 DL.getTypeStoreSizeInBits(Ty) == DL.getTypeSizeInBits(Ty) &&
479 !DL.isNonIntegralPointerType(Ty)) {
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000480 if (std::all_of(LI.user_begin(), LI.user_end(), [&LI](User *U) {
481 auto *SI = dyn_cast<StoreInst>(U);
482 return SI && SI->getPointerOperand() != &LI;
483 })) {
484 LoadInst *NewLoad = combineLoadToNewType(
485 IC, LI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000486 Type::getIntNTy(LI.getContext(), DL.getTypeStoreSizeInBits(Ty)));
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000487 // Replace all the stores with stores of the newly loaded value.
488 for (auto UI = LI.user_begin(), UE = LI.user_end(); UI != UE;) {
489 auto *SI = cast<StoreInst>(*UI++);
490 IC.Builder->SetInsertPoint(SI);
491 combineStoreToNewValue(IC, *SI, NewLoad);
Sanjay Patel4b198802016-02-01 22:23:39 +0000492 IC.eraseInstFromFunction(*SI);
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000493 }
494 assert(LI.use_empty() && "Failed to remove all users of the load!");
495 // Return the old load so the combiner can delete it safely.
496 return &LI;
497 }
498 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000499
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000500 // Fold away bit casts of the loaded value by loading the desired type.
Quentin Colombet490cfbe2016-02-11 22:30:41 +0000501 // We can do this for BitCastInsts as well as casts from and to pointer types,
502 // as long as those are noops (i.e., the source or dest type have the same
503 // bitwidth as the target's pointers).
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000504 if (LI.hasOneUse())
Quentin Colombet490cfbe2016-02-11 22:30:41 +0000505 if (auto* CI = dyn_cast<CastInst>(LI.user_back())) {
506 if (CI->isNoopCast(DL)) {
507 LoadInst *NewLoad = combineLoadToNewType(IC, LI, CI->getDestTy());
508 CI->replaceAllUsesWith(NewLoad);
509 IC.eraseInstFromFunction(*CI);
510 return &LI;
511 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000512 }
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000513
Chandler Carrutha7f247e2014-12-09 19:21:16 +0000514 // FIXME: We should also canonicalize loads of vectors when their elements are
515 // cast to other types.
Craig Topperf40110f2014-04-25 05:29:35 +0000516 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000517}
518
Mehdi Amini2668a482015-05-07 05:52:40 +0000519static Instruction *unpackLoadToAggregate(InstCombiner &IC, LoadInst &LI) {
520 // FIXME: We could probably with some care handle both volatile and atomic
521 // stores here but it isn't clear that this is important.
522 if (!LI.isSimple())
523 return nullptr;
524
525 Type *T = LI.getType();
526 if (!T->isAggregateType())
527 return nullptr;
528
Benjamin Kramerc1263532016-03-11 10:20:56 +0000529 StringRef Name = LI.getName();
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000530 assert(LI.getAlignment() && "Alignment must be set at this point");
Mehdi Amini2668a482015-05-07 05:52:40 +0000531
532 if (auto *ST = dyn_cast<StructType>(T)) {
533 // If the struct only have one element, we unpack.
Amaury Sechet61a7d622016-02-17 19:21:28 +0000534 auto NumElements = ST->getNumElements();
535 if (NumElements == 1) {
Mehdi Amini2668a482015-05-07 05:52:40 +0000536 LoadInst *NewLoad = combineLoadToNewType(IC, LI, ST->getTypeAtIndex(0U),
537 ".unpack");
Sanjay Patel4b198802016-02-01 22:23:39 +0000538 return IC.replaceInstUsesWith(LI, IC.Builder->CreateInsertValue(
Amaury Sechet61a7d622016-02-17 19:21:28 +0000539 UndefValue::get(T), NewLoad, 0, Name));
Mehdi Amini2668a482015-05-07 05:52:40 +0000540 }
Mehdi Amini1c131b32015-12-15 01:44:07 +0000541
542 // We don't want to break loads with padding here as we'd loose
543 // the knowledge that padding exists for the rest of the pipeline.
544 const DataLayout &DL = IC.getDataLayout();
545 auto *SL = DL.getStructLayout(ST);
546 if (SL->hasPadding())
547 return nullptr;
548
Amaury Sechet61a7d622016-02-17 19:21:28 +0000549 auto Align = LI.getAlignment();
550 if (!Align)
551 Align = DL.getABITypeAlignment(ST);
552
Mehdi Amini1c131b32015-12-15 01:44:07 +0000553 auto *Addr = LI.getPointerOperand();
Amaury Sechet61a7d622016-02-17 19:21:28 +0000554 auto *IdxType = Type::getInt32Ty(T->getContext());
Mehdi Amini1c131b32015-12-15 01:44:07 +0000555 auto *Zero = ConstantInt::get(IdxType, 0);
Amaury Sechet61a7d622016-02-17 19:21:28 +0000556
557 Value *V = UndefValue::get(T);
558 for (unsigned i = 0; i < NumElements; i++) {
Mehdi Amini1c131b32015-12-15 01:44:07 +0000559 Value *Indices[2] = {
560 Zero,
561 ConstantInt::get(IdxType, i),
562 };
Amaury Sechetda71cb72016-02-17 21:21:29 +0000563 auto *Ptr = IC.Builder->CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices),
Benjamin Kramerc1263532016-03-11 10:20:56 +0000564 Name + ".elt");
Amaury Sechet61a7d622016-02-17 19:21:28 +0000565 auto EltAlign = MinAlign(Align, SL->getElementOffset(i));
Benjamin Kramerc1263532016-03-11 10:20:56 +0000566 auto *L = IC.Builder->CreateAlignedLoad(Ptr, EltAlign, Name + ".unpack");
Mehdi Amini1c131b32015-12-15 01:44:07 +0000567 V = IC.Builder->CreateInsertValue(V, L, i);
568 }
569
570 V->setName(Name);
Sanjay Patel4b198802016-02-01 22:23:39 +0000571 return IC.replaceInstUsesWith(LI, V);
Mehdi Amini2668a482015-05-07 05:52:40 +0000572 }
573
David Majnemer58fb0382015-05-11 05:04:22 +0000574 if (auto *AT = dyn_cast<ArrayType>(T)) {
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000575 auto *ET = AT->getElementType();
576 auto NumElements = AT->getNumElements();
577 if (NumElements == 1) {
578 LoadInst *NewLoad = combineLoadToNewType(IC, LI, ET, ".unpack");
Sanjay Patel4b198802016-02-01 22:23:39 +0000579 return IC.replaceInstUsesWith(LI, IC.Builder->CreateInsertValue(
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000580 UndefValue::get(T), NewLoad, 0, Name));
David Majnemer58fb0382015-05-11 05:04:22 +0000581 }
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000582
583 const DataLayout &DL = IC.getDataLayout();
584 auto EltSize = DL.getTypeAllocSize(ET);
585 auto Align = LI.getAlignment();
586 if (!Align)
587 Align = DL.getABITypeAlignment(T);
588
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000589 auto *Addr = LI.getPointerOperand();
590 auto *IdxType = Type::getInt64Ty(T->getContext());
591 auto *Zero = ConstantInt::get(IdxType, 0);
592
593 Value *V = UndefValue::get(T);
594 uint64_t Offset = 0;
595 for (uint64_t i = 0; i < NumElements; i++) {
596 Value *Indices[2] = {
597 Zero,
598 ConstantInt::get(IdxType, i),
599 };
600 auto *Ptr = IC.Builder->CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices),
Benjamin Kramerc1263532016-03-11 10:20:56 +0000601 Name + ".elt");
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000602 auto *L = IC.Builder->CreateAlignedLoad(Ptr, MinAlign(Align, Offset),
Benjamin Kramerc1263532016-03-11 10:20:56 +0000603 Name + ".unpack");
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000604 V = IC.Builder->CreateInsertValue(V, L, i);
605 Offset += EltSize;
606 }
607
608 V->setName(Name);
609 return IC.replaceInstUsesWith(LI, V);
David Majnemer58fb0382015-05-11 05:04:22 +0000610 }
611
Mehdi Amini2668a482015-05-07 05:52:40 +0000612 return nullptr;
613}
614
Hal Finkel847e05f2015-02-20 03:05:53 +0000615// If we can determine that all possible objects pointed to by the provided
616// pointer value are, not only dereferenceable, but also definitively less than
617// or equal to the provided maximum size, then return true. Otherwise, return
618// false (constant global values and allocas fall into this category).
619//
620// FIXME: This should probably live in ValueTracking (or similar).
621static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000622 const DataLayout &DL) {
Hal Finkel847e05f2015-02-20 03:05:53 +0000623 SmallPtrSet<Value *, 4> Visited;
624 SmallVector<Value *, 4> Worklist(1, V);
625
626 do {
627 Value *P = Worklist.pop_back_val();
628 P = P->stripPointerCasts();
629
630 if (!Visited.insert(P).second)
631 continue;
632
633 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
634 Worklist.push_back(SI->getTrueValue());
635 Worklist.push_back(SI->getFalseValue());
636 continue;
637 }
638
639 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000640 for (Value *IncValue : PN->incoming_values())
641 Worklist.push_back(IncValue);
Hal Finkel847e05f2015-02-20 03:05:53 +0000642 continue;
643 }
644
645 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
Sanjoy Das99042472016-04-17 04:30:43 +0000646 if (GA->isInterposable())
Hal Finkel847e05f2015-02-20 03:05:53 +0000647 return false;
648 Worklist.push_back(GA->getAliasee());
649 continue;
650 }
651
652 // If we know how big this object is, and it is less than MaxSize, continue
653 // searching. Otherwise, return false.
654 if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
655 if (!AI->getAllocatedType()->isSized())
656 return false;
657
658 ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
659 if (!CS)
660 return false;
661
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000662 uint64_t TypeSize = DL.getTypeAllocSize(AI->getAllocatedType());
Hal Finkel847e05f2015-02-20 03:05:53 +0000663 // Make sure that, even if the multiplication below would wrap as an
664 // uint64_t, we still do the right thing.
665 if ((CS->getValue().zextOrSelf(128)*APInt(128, TypeSize)).ugt(MaxSize))
666 return false;
667 continue;
668 }
669
670 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
671 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
672 return false;
673
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000674 uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType());
Hal Finkel847e05f2015-02-20 03:05:53 +0000675 if (InitSize > MaxSize)
676 return false;
677 continue;
678 }
679
680 return false;
681 } while (!Worklist.empty());
682
683 return true;
684}
685
686// If we're indexing into an object of a known size, and the outer index is
687// not a constant, but having any value but zero would lead to undefined
688// behavior, replace it with zero.
689//
690// For example, if we have:
691// @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
692// ...
693// %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x
694// ... = load i32* %arrayidx, align 4
695// Then we know that we can replace %x in the GEP with i64 0.
696//
697// FIXME: We could fold any GEP index to zero that would cause UB if it were
698// not zero. Currently, we only handle the first such index. Also, we could
699// also search through non-zero constant indices if we kept track of the
700// offsets those indices implied.
701static bool canReplaceGEPIdxWithZero(InstCombiner &IC, GetElementPtrInst *GEPI,
702 Instruction *MemI, unsigned &Idx) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000703 if (GEPI->getNumOperands() < 2)
Hal Finkel847e05f2015-02-20 03:05:53 +0000704 return false;
705
706 // Find the first non-zero index of a GEP. If all indices are zero, return
707 // one past the last index.
708 auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
709 unsigned I = 1;
710 for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
711 Value *V = GEPI->getOperand(I);
712 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
713 if (CI->isZero())
714 continue;
715
716 break;
717 }
718
719 return I;
720 };
721
722 // Skip through initial 'zero' indices, and find the corresponding pointer
723 // type. See if the next index is not a constant.
724 Idx = FirstNZIdx(GEPI);
725 if (Idx == GEPI->getNumOperands())
726 return false;
727 if (isa<Constant>(GEPI->getOperand(Idx)))
728 return false;
729
730 SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
Eduard Burtescu19eb0312016-01-19 17:28:00 +0000731 Type *AllocTy =
732 GetElementPtrInst::getIndexedType(GEPI->getSourceElementType(), Ops);
Hal Finkel847e05f2015-02-20 03:05:53 +0000733 if (!AllocTy || !AllocTy->isSized())
734 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000735 const DataLayout &DL = IC.getDataLayout();
736 uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy);
Hal Finkel847e05f2015-02-20 03:05:53 +0000737
738 // If there are more indices after the one we might replace with a zero, make
739 // sure they're all non-negative. If any of them are negative, the overall
740 // address being computed might be before the base address determined by the
741 // first non-zero index.
742 auto IsAllNonNegative = [&]() {
743 for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
744 bool KnownNonNegative, KnownNegative;
745 IC.ComputeSignBit(GEPI->getOperand(i), KnownNonNegative,
746 KnownNegative, 0, MemI);
747 if (KnownNonNegative)
748 continue;
749 return false;
750 }
751
752 return true;
753 };
754
755 // FIXME: If the GEP is not inbounds, and there are extra indices after the
756 // one we'll replace, those could cause the address computation to wrap
757 // (rendering the IsAllNonNegative() check below insufficient). We can do
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000758 // better, ignoring zero indices (and other indices we can prove small
Hal Finkel847e05f2015-02-20 03:05:53 +0000759 // enough not to wrap).
760 if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
761 return false;
762
763 // Note that isObjectSizeLessThanOrEq will return true only if the pointer is
764 // also known to be dereferenceable.
765 return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
766 IsAllNonNegative();
767}
768
769// If we're indexing into an object with a variable index for the memory
770// access, but the object has only one element, we can assume that the index
771// will always be zero. If we replace the GEP, return it.
772template <typename T>
773static Instruction *replaceGEPIdxWithZero(InstCombiner &IC, Value *Ptr,
774 T &MemI) {
775 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
776 unsigned Idx;
777 if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
778 Instruction *NewGEPI = GEPI->clone();
779 NewGEPI->setOperand(Idx,
780 ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
781 NewGEPI->insertBefore(GEPI);
782 MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI);
783 return NewGEPI;
784 }
785 }
786
787 return nullptr;
788}
789
Chris Lattnera65e2f72010-01-05 05:57:49 +0000790Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
791 Value *Op = LI.getOperand(0);
792
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000793 // Try to canonicalize the loaded type.
794 if (Instruction *Res = combineLoadToOperationType(*this, LI))
795 return Res;
796
Chris Lattnera65e2f72010-01-05 05:57:49 +0000797 // Attempt to improve the alignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000798 unsigned KnownAlign = getOrEnforceKnownAlignment(
Justin Bogner99798402016-08-05 01:06:44 +0000799 Op, DL.getPrefTypeAlignment(LI.getType()), DL, &LI, &AC, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000800 unsigned LoadAlign = LI.getAlignment();
801 unsigned EffectiveLoadAlign =
802 LoadAlign != 0 ? LoadAlign : DL.getABITypeAlignment(LI.getType());
Dan Gohman36196602010-08-03 18:20:32 +0000803
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000804 if (KnownAlign > EffectiveLoadAlign)
805 LI.setAlignment(KnownAlign);
806 else if (LoadAlign == 0)
807 LI.setAlignment(EffectiveLoadAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000808
Hal Finkel847e05f2015-02-20 03:05:53 +0000809 // Replace GEP indices if possible.
810 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) {
811 Worklist.Add(NewGEPI);
812 return &LI;
813 }
814
Mehdi Amini2668a482015-05-07 05:52:40 +0000815 if (Instruction *Res = unpackLoadToAggregate(*this, LI))
816 return Res;
817
Chris Lattnera65e2f72010-01-05 05:57:49 +0000818 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +0000819 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +0000820 // separated by a few arithmetic operations.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000821 BasicBlock::iterator BBI(LI);
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000822 AAMDNodes AATags;
Eli Friedmanbd254a62016-06-16 02:33:42 +0000823 bool IsLoadCSE = false;
Larisse Voufo532bf712015-09-18 19:14:35 +0000824 if (Value *AvailableVal =
Eduard Burtescue2a69172016-01-22 01:51:51 +0000825 FindAvailableLoadedValue(&LI, LI.getParent(), BBI,
Eli Friedmanbd254a62016-06-16 02:33:42 +0000826 DefMaxInstsToScan, AA, &AATags, &IsLoadCSE)) {
827 if (IsLoadCSE) {
828 LoadInst *NLI = cast<LoadInst>(AvailableVal);
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000829 unsigned KnownIDs[] = {
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000830 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
831 LLVMContext::MD_noalias, LLVMContext::MD_range,
832 LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull,
833 LLVMContext::MD_invariant_group, LLVMContext::MD_align,
834 LLVMContext::MD_dereferenceable,
835 LLVMContext::MD_dereferenceable_or_null};
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000836 combineMetadata(NLI, &LI, KnownIDs);
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000837 };
838
Sanjay Patel4b198802016-02-01 22:23:39 +0000839 return replaceInstUsesWith(
Chandler Carruth1a3c2c42014-11-25 08:20:27 +0000840 LI, Builder->CreateBitOrPointerCast(AvailableVal, LI.getType(),
841 LI.getName() + ".cast"));
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000842 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000843
Philip Reames3ac07182016-04-21 17:45:05 +0000844 // None of the following transforms are legal for volatile/ordered atomic
845 // loads. Most of them do apply for unordered atomics.
846 if (!LI.isUnordered()) return nullptr;
Philip Reamesac550902016-04-21 17:03:33 +0000847
Chris Lattnera65e2f72010-01-05 05:57:49 +0000848 // load(gep null, ...) -> unreachable
849 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
850 const Value *GEPI0 = GEPI->getOperand(0);
851 // TODO: Consider a target hook for valid address spaces for this xform.
852 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
853 // Insert a new store to null instruction before the load to indicate
854 // that this code is not reachable. We do this instead of inserting
855 // an unreachable instruction directly because we cannot modify the
856 // CFG.
857 new StoreInst(UndefValue::get(LI.getType()),
858 Constant::getNullValue(Op->getType()), &LI);
Sanjay Patel4b198802016-02-01 22:23:39 +0000859 return replaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000860 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000861 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000862
863 // load null/undef -> unreachable
864 // TODO: Consider a target hook for valid address spaces for this xform.
865 if (isa<UndefValue>(Op) ||
866 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
867 // Insert a new store to null instruction before the load to indicate that
868 // this code is not reachable. We do this instead of inserting an
869 // unreachable instruction directly because we cannot modify the CFG.
870 new StoreInst(UndefValue::get(LI.getType()),
871 Constant::getNullValue(Op->getType()), &LI);
Sanjay Patel4b198802016-02-01 22:23:39 +0000872 return replaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000873 }
874
Chris Lattnera65e2f72010-01-05 05:57:49 +0000875 if (Op->hasOneUse()) {
876 // Change select and PHI nodes to select values instead of addresses: this
877 // helps alias analysis out a lot, allows many others simplifications, and
878 // exposes redundancy in the code.
879 //
880 // Note that we cannot do the transformation unless we know that the
881 // introduced loads cannot trap! Something like this is valid as long as
882 // the condition is always false: load (select bool %C, int* null, int* %G),
883 // but it would not be valid if we transformed it to load from null
884 // unconditionally.
885 //
886 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
887 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +0000888 unsigned Align = LI.getAlignment();
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +0000889 if (isSafeToLoadUnconditionally(SI->getOperand(1), Align, DL, SI) &&
890 isSafeToLoadUnconditionally(SI->getOperand(2), Align, DL, SI)) {
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000891 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
Bob Wilson56600a12010-01-30 04:42:39 +0000892 SI->getOperand(1)->getName()+".val");
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000893 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
Bob Wilson56600a12010-01-30 04:42:39 +0000894 SI->getOperand(2)->getName()+".val");
Philip Reamesa98c7ea2016-04-21 17:59:40 +0000895 assert(LI.isUnordered() && "implied by above");
Bob Wilson56600a12010-01-30 04:42:39 +0000896 V1->setAlignment(Align);
Philip Reamesa98c7ea2016-04-21 17:59:40 +0000897 V1->setAtomic(LI.getOrdering(), LI.getSynchScope());
Bob Wilson56600a12010-01-30 04:42:39 +0000898 V2->setAlignment(Align);
Philip Reamesa98c7ea2016-04-21 17:59:40 +0000899 V2->setAtomic(LI.getOrdering(), LI.getSynchScope());
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
Arch D. Robisonbe0490a2016-04-25 22:22:39 +0000921/// \brief Look for extractelement/insertvalue sequence that acts like a bitcast.
922///
923/// \returns underlying value that was "cast", or nullptr otherwise.
924///
925/// For example, if we have:
926///
927/// %E0 = extractelement <2 x double> %U, i32 0
928/// %V0 = insertvalue [2 x double] undef, double %E0, 0
929/// %E1 = extractelement <2 x double> %U, i32 1
930/// %V1 = insertvalue [2 x double] %V0, double %E1, 1
931///
932/// and the layout of a <2 x double> is isomorphic to a [2 x double],
933/// then %V1 can be safely approximated by a conceptual "bitcast" of %U.
934/// Note that %U may contain non-undef values where %V1 has undef.
935static Value *likeBitCastFromVector(InstCombiner &IC, Value *V) {
936 Value *U = nullptr;
937 while (auto *IV = dyn_cast<InsertValueInst>(V)) {
938 auto *E = dyn_cast<ExtractElementInst>(IV->getInsertedValueOperand());
939 if (!E)
940 return nullptr;
941 auto *W = E->getVectorOperand();
942 if (!U)
943 U = W;
944 else if (U != W)
945 return nullptr;
946 auto *CI = dyn_cast<ConstantInt>(E->getIndexOperand());
947 if (!CI || IV->getNumIndices() != 1 || CI->getZExtValue() != *IV->idx_begin())
948 return nullptr;
949 V = IV->getAggregateOperand();
950 }
951 if (!isa<UndefValue>(V) ||!U)
952 return nullptr;
953
954 auto *UT = cast<VectorType>(U->getType());
955 auto *VT = V->getType();
956 // Check that types UT and VT are bitwise isomorphic.
957 const auto &DL = IC.getDataLayout();
958 if (DL.getTypeStoreSizeInBits(UT) != DL.getTypeStoreSizeInBits(VT)) {
959 return nullptr;
960 }
961 if (auto *AT = dyn_cast<ArrayType>(VT)) {
962 if (AT->getNumElements() != UT->getNumElements())
963 return nullptr;
964 } else {
965 auto *ST = cast<StructType>(VT);
966 if (ST->getNumElements() != UT->getNumElements())
967 return nullptr;
968 for (const auto *EltT : ST->elements()) {
969 if (EltT != UT->getElementType())
970 return nullptr;
971 }
972 }
973 return U;
974}
975
Chandler Carruth816d26f2014-11-25 10:09:51 +0000976/// \brief Combine stores to match the type of value being stored.
977///
978/// The core idea here is that the memory does not have any intrinsic type and
979/// where we can we should match the type of a store to the type of value being
980/// stored.
981///
982/// However, this routine must never change the width of a store or the number of
983/// stores as that would introduce a semantic change. This combine is expected to
984/// be a semantic no-op which just allows stores to more closely model the types
985/// of their incoming values.
986///
987/// Currently, we also refuse to change the precise type used for an atomic or
988/// volatile store. This is debatable, and might be reasonable to change later.
989/// However, it is risky in case some backend or other part of LLVM is relying
990/// on the exact type stored to select appropriate atomic operations.
991///
992/// \returns true if the store was successfully combined away. This indicates
993/// the caller must erase the store instruction. We have to let the caller erase
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000994/// the store instruction as otherwise there is no way to signal whether it was
Chandler Carruth816d26f2014-11-25 10:09:51 +0000995/// combined or not: IC.EraseInstFromFunction returns a null pointer.
996static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) {
Philip Reames6f4d0082016-05-06 22:17:01 +0000997 // FIXME: We could probably with some care handle both volatile and ordered
998 // atomic stores here but it isn't clear that this is important.
999 if (!SI.isUnordered())
Chandler Carruth816d26f2014-11-25 10:09:51 +00001000 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001001
Chandler Carruth816d26f2014-11-25 10:09:51 +00001002 Value *V = SI.getValueOperand();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001003
Chandler Carruth816d26f2014-11-25 10:09:51 +00001004 // Fold away bit casts of the stored value by storing the original type.
1005 if (auto *BC = dyn_cast<BitCastInst>(V)) {
Chandler Carrutha7f247e2014-12-09 19:21:16 +00001006 V = BC->getOperand(0);
Chandler Carruth2135b972015-01-21 23:45:01 +00001007 combineStoreToNewValue(IC, SI, V);
Chandler Carruth816d26f2014-11-25 10:09:51 +00001008 return true;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001009 }
1010
Arch D. Robisonbe0490a2016-04-25 22:22:39 +00001011 if (Value *U = likeBitCastFromVector(IC, V)) {
1012 combineStoreToNewValue(IC, SI, U);
1013 return true;
1014 }
1015
JF Bastienc22d2992016-04-21 19:53:39 +00001016 // FIXME: We should also canonicalize stores of vectors when their elements
1017 // are cast to other types.
Chandler Carruth816d26f2014-11-25 10:09:51 +00001018 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001019}
1020
Mehdi Aminib344ac92015-03-14 22:19:33 +00001021static bool unpackStoreToAggregate(InstCombiner &IC, StoreInst &SI) {
1022 // FIXME: We could probably with some care handle both volatile and atomic
1023 // stores here but it isn't clear that this is important.
1024 if (!SI.isSimple())
1025 return false;
1026
1027 Value *V = SI.getValueOperand();
1028 Type *T = V->getType();
1029
1030 if (!T->isAggregateType())
1031 return false;
1032
Mehdi Amini2668a482015-05-07 05:52:40 +00001033 if (auto *ST = dyn_cast<StructType>(T)) {
Mehdi Aminib344ac92015-03-14 22:19:33 +00001034 // If the struct only have one element, we unpack.
Mehdi Amini1c131b32015-12-15 01:44:07 +00001035 unsigned Count = ST->getNumElements();
1036 if (Count == 1) {
Mehdi Aminib344ac92015-03-14 22:19:33 +00001037 V = IC.Builder->CreateExtractValue(V, 0);
1038 combineStoreToNewValue(IC, SI, V);
1039 return true;
1040 }
Mehdi Amini1c131b32015-12-15 01:44:07 +00001041
1042 // We don't want to break loads with padding here as we'd loose
1043 // the knowledge that padding exists for the rest of the pipeline.
1044 const DataLayout &DL = IC.getDataLayout();
1045 auto *SL = DL.getStructLayout(ST);
1046 if (SL->hasPadding())
1047 return false;
1048
Amaury Sechet61a7d622016-02-17 19:21:28 +00001049 auto Align = SI.getAlignment();
1050 if (!Align)
1051 Align = DL.getABITypeAlignment(ST);
1052
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +00001053 SmallString<16> EltName = V->getName();
1054 EltName += ".elt";
Mehdi Amini1c131b32015-12-15 01:44:07 +00001055 auto *Addr = SI.getPointerOperand();
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +00001056 SmallString<16> AddrName = Addr->getName();
1057 AddrName += ".repack";
Amaury Sechet61a7d622016-02-17 19:21:28 +00001058
Mehdi Amini1c131b32015-12-15 01:44:07 +00001059 auto *IdxType = Type::getInt32Ty(ST->getContext());
1060 auto *Zero = ConstantInt::get(IdxType, 0);
1061 for (unsigned i = 0; i < Count; i++) {
1062 Value *Indices[2] = {
1063 Zero,
1064 ConstantInt::get(IdxType, i),
1065 };
Amaury Sechetda71cb72016-02-17 21:21:29 +00001066 auto *Ptr = IC.Builder->CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices),
1067 AddrName);
Mehdi Amini1c131b32015-12-15 01:44:07 +00001068 auto *Val = IC.Builder->CreateExtractValue(V, i, EltName);
Amaury Sechet61a7d622016-02-17 19:21:28 +00001069 auto EltAlign = MinAlign(Align, SL->getElementOffset(i));
1070 IC.Builder->CreateAlignedStore(Val, Ptr, EltAlign);
Mehdi Amini1c131b32015-12-15 01:44:07 +00001071 }
1072
1073 return true;
Mehdi Aminib344ac92015-03-14 22:19:33 +00001074 }
1075
David Majnemer75364602015-05-11 05:04:27 +00001076 if (auto *AT = dyn_cast<ArrayType>(T)) {
1077 // If the array only have one element, we unpack.
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001078 auto NumElements = AT->getNumElements();
1079 if (NumElements == 1) {
David Majnemer75364602015-05-11 05:04:27 +00001080 V = IC.Builder->CreateExtractValue(V, 0);
1081 combineStoreToNewValue(IC, SI, V);
1082 return true;
1083 }
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001084
1085 const DataLayout &DL = IC.getDataLayout();
1086 auto EltSize = DL.getTypeAllocSize(AT->getElementType());
1087 auto Align = SI.getAlignment();
1088 if (!Align)
1089 Align = DL.getABITypeAlignment(T);
1090
1091 SmallString<16> EltName = V->getName();
1092 EltName += ".elt";
1093 auto *Addr = SI.getPointerOperand();
1094 SmallString<16> AddrName = Addr->getName();
1095 AddrName += ".repack";
1096
1097 auto *IdxType = Type::getInt64Ty(T->getContext());
1098 auto *Zero = ConstantInt::get(IdxType, 0);
1099
1100 uint64_t Offset = 0;
1101 for (uint64_t i = 0; i < NumElements; i++) {
1102 Value *Indices[2] = {
1103 Zero,
1104 ConstantInt::get(IdxType, i),
1105 };
1106 auto *Ptr = IC.Builder->CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices),
1107 AddrName);
1108 auto *Val = IC.Builder->CreateExtractValue(V, i, EltName);
1109 auto EltAlign = MinAlign(Align, Offset);
1110 IC.Builder->CreateAlignedStore(Val, Ptr, EltAlign);
1111 Offset += EltSize;
1112 }
1113
1114 return true;
David Majnemer75364602015-05-11 05:04:27 +00001115 }
1116
Mehdi Aminib344ac92015-03-14 22:19:33 +00001117 return false;
1118}
1119
Chris Lattnera65e2f72010-01-05 05:57:49 +00001120/// equivalentAddressValues - Test if A and B will obviously have the same
1121/// value. This includes recognizing that %t0 and %t1 will have the same
1122/// value in code like this:
1123/// %t0 = getelementptr \@a, 0, 3
1124/// store i32 0, i32* %t0
1125/// %t1 = getelementptr \@a, 0, 3
1126/// %t2 = load i32* %t1
1127///
1128static bool equivalentAddressValues(Value *A, Value *B) {
1129 // Test if the values are trivially equivalent.
1130 if (A == B) return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001131
Chris Lattnera65e2f72010-01-05 05:57:49 +00001132 // Test if the values come form identical arithmetic instructions.
1133 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
1134 // its only used to compare two uses within the same basic block, which
1135 // means that they'll always either have the same value or one of them
1136 // will have an undefined value.
1137 if (isa<BinaryOperator>(A) ||
1138 isa<CastInst>(A) ||
1139 isa<PHINode>(A) ||
1140 isa<GetElementPtrInst>(A))
1141 if (Instruction *BI = dyn_cast<Instruction>(B))
1142 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
1143 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001144
Chris Lattnera65e2f72010-01-05 05:57:49 +00001145 // Otherwise they may not be equivalent.
1146 return false;
1147}
1148
Chris Lattnera65e2f72010-01-05 05:57:49 +00001149Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
1150 Value *Val = SI.getOperand(0);
1151 Value *Ptr = SI.getOperand(1);
1152
Chandler Carruth816d26f2014-11-25 10:09:51 +00001153 // Try to canonicalize the stored type.
1154 if (combineStoreToValueType(*this, SI))
Sanjay Patel4b198802016-02-01 22:23:39 +00001155 return eraseInstFromFunction(SI);
Chandler Carruth816d26f2014-11-25 10:09:51 +00001156
Chris Lattnera65e2f72010-01-05 05:57:49 +00001157 // Attempt to improve the alignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001158 unsigned KnownAlign = getOrEnforceKnownAlignment(
Justin Bogner99798402016-08-05 01:06:44 +00001159 Ptr, DL.getPrefTypeAlignment(Val->getType()), DL, &SI, &AC, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001160 unsigned StoreAlign = SI.getAlignment();
1161 unsigned EffectiveStoreAlign =
1162 StoreAlign != 0 ? StoreAlign : DL.getABITypeAlignment(Val->getType());
Dan Gohman36196602010-08-03 18:20:32 +00001163
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001164 if (KnownAlign > EffectiveStoreAlign)
1165 SI.setAlignment(KnownAlign);
1166 else if (StoreAlign == 0)
1167 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001168
Mehdi Aminib344ac92015-03-14 22:19:33 +00001169 // Try to canonicalize the stored type.
1170 if (unpackStoreToAggregate(*this, SI))
Sanjay Patel4b198802016-02-01 22:23:39 +00001171 return eraseInstFromFunction(SI);
Mehdi Aminib344ac92015-03-14 22:19:33 +00001172
Hal Finkel847e05f2015-02-20 03:05:53 +00001173 // Replace GEP indices if possible.
1174 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) {
1175 Worklist.Add(NewGEPI);
1176 return &SI;
1177 }
1178
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001179 // Don't hack volatile/ordered stores.
1180 // FIXME: Some bits are legal for ordered atomic stores; needs refactoring.
1181 if (!SI.isUnordered()) return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +00001182
1183 // If the RHS is an alloca with a single use, zapify the store, making the
1184 // alloca dead.
1185 if (Ptr->hasOneUse()) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001186 if (isa<AllocaInst>(Ptr))
Sanjay Patel4b198802016-02-01 22:23:39 +00001187 return eraseInstFromFunction(SI);
Eli Friedman8bc586e2011-08-15 22:09:40 +00001188 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
1189 if (isa<AllocaInst>(GEP->getOperand(0))) {
1190 if (GEP->getOperand(0)->hasOneUse())
Sanjay Patel4b198802016-02-01 22:23:39 +00001191 return eraseInstFromFunction(SI);
Eli Friedman8bc586e2011-08-15 22:09:40 +00001192 }
1193 }
1194 }
1195
Chris Lattnera65e2f72010-01-05 05:57:49 +00001196 // Do really simple DSE, to catch cases where there are several consecutive
1197 // stores to the same location, separated by a few arithmetic operations. This
1198 // situation often occurs with bitfield accesses.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001199 BasicBlock::iterator BBI(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001200 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
1201 --ScanInsts) {
1202 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001203 // Don't count debug info directives, lest they affect codegen,
1204 // and we skip pointer-to-pointer bitcasts, which are NOPs.
1205 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001206 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001207 ScanInsts++;
1208 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001209 }
1210
Chris Lattnera65e2f72010-01-05 05:57:49 +00001211 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
1212 // Prev store isn't volatile, and stores to the same location?
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001213 if (PrevSI->isUnordered() && equivalentAddressValues(PrevSI->getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +00001214 SI.getOperand(1))) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001215 ++NumDeadStore;
1216 ++BBI;
Sanjay Patel4b198802016-02-01 22:23:39 +00001217 eraseInstFromFunction(*PrevSI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001218 continue;
1219 }
1220 break;
1221 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001222
Chris Lattnera65e2f72010-01-05 05:57:49 +00001223 // If this is a load, we have to stop. However, if the loaded value is from
1224 // the pointer we're loading and is producing the pointer we're storing,
1225 // then *this* store is dead (X = load P; store X -> P).
1226 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001227 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr)) {
1228 assert(SI.isUnordered() && "can't eliminate ordering operation");
Sanjay Patel4b198802016-02-01 22:23:39 +00001229 return eraseInstFromFunction(SI);
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001230 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001231
Chris Lattnera65e2f72010-01-05 05:57:49 +00001232 // Otherwise, this is a load from some other location. Stores before it
1233 // may not be dead.
1234 break;
1235 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001236
Chris Lattnera65e2f72010-01-05 05:57:49 +00001237 // Don't skip over loads or things that can modify memory.
1238 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
1239 break;
1240 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001241
1242 // store X, null -> turns into 'unreachable' in SimplifyCFG
1243 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
1244 if (!isa<UndefValue>(Val)) {
1245 SI.setOperand(0, UndefValue::get(Val->getType()));
1246 if (Instruction *U = dyn_cast<Instruction>(Val))
1247 Worklist.Add(U); // Dropped a use.
1248 }
Craig Topperf40110f2014-04-25 05:29:35 +00001249 return nullptr; // Do not modify these!
Chris Lattnera65e2f72010-01-05 05:57:49 +00001250 }
1251
1252 // store undef, Ptr -> noop
1253 if (isa<UndefValue>(Val))
Sanjay Patel4b198802016-02-01 22:23:39 +00001254 return eraseInstFromFunction(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001255
Chris Lattnera65e2f72010-01-05 05:57:49 +00001256 // If this store is the last instruction in the basic block (possibly
Victor Hernandez5f5abd52010-01-21 23:07:15 +00001257 // excepting debug info instructions), and if the block ends with an
1258 // unconditional branch, try to move it to the successor block.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001259 BBI = SI.getIterator();
Chris Lattnera65e2f72010-01-05 05:57:49 +00001260 do {
1261 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001262 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001263 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Chris Lattnera65e2f72010-01-05 05:57:49 +00001264 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
1265 if (BI->isUnconditional())
1266 if (SimplifyStoreAtEndOfBlock(SI))
Craig Topperf40110f2014-04-25 05:29:35 +00001267 return nullptr; // xform done!
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001268
Craig Topperf40110f2014-04-25 05:29:35 +00001269 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001270}
1271
1272/// SimplifyStoreAtEndOfBlock - Turn things like:
1273/// if () { *P = v1; } else { *P = v2 }
1274/// into a phi node with a store in the successor.
1275///
1276/// Simplify things like:
1277/// *P = v1; if () { *P = v2; }
1278/// into a phi node with a store in the successor.
1279///
1280bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
Philip Reames5f0e3692016-04-22 20:53:32 +00001281 assert(SI.isUnordered() &&
1282 "this code has not been auditted for volatile or ordered store case");
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001283
Chris Lattnera65e2f72010-01-05 05:57:49 +00001284 BasicBlock *StoreBB = SI.getParent();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001285
Chris Lattnera65e2f72010-01-05 05:57:49 +00001286 // Check to see if the successor block has exactly two incoming edges. If
1287 // so, see if the other predecessor contains a store to the same location.
1288 // if so, insert a PHI node (if needed) and move the stores down.
1289 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001290
Chris Lattnera65e2f72010-01-05 05:57:49 +00001291 // Determine whether Dest has exactly two predecessors and, if so, compute
1292 // the other predecessor.
1293 pred_iterator PI = pred_begin(DestBB);
Gabor Greif1b787df2010-07-12 15:48:26 +00001294 BasicBlock *P = *PI;
Craig Topperf40110f2014-04-25 05:29:35 +00001295 BasicBlock *OtherBB = nullptr;
Gabor Greif1b787df2010-07-12 15:48:26 +00001296
1297 if (P != StoreBB)
1298 OtherBB = P;
1299
1300 if (++PI == pred_end(DestBB))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001301 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001302
Gabor Greif1b787df2010-07-12 15:48:26 +00001303 P = *PI;
1304 if (P != StoreBB) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001305 if (OtherBB)
1306 return false;
Gabor Greif1b787df2010-07-12 15:48:26 +00001307 OtherBB = P;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001308 }
1309 if (++PI != pred_end(DestBB))
1310 return false;
1311
1312 // Bail out if all the relevant blocks aren't distinct (this can happen,
1313 // for example, if SI is in an infinite loop)
1314 if (StoreBB == DestBB || OtherBB == DestBB)
1315 return false;
1316
1317 // Verify that the other block ends in a branch and is not otherwise empty.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001318 BasicBlock::iterator BBI(OtherBB->getTerminator());
Chris Lattnera65e2f72010-01-05 05:57:49 +00001319 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
1320 if (!OtherBr || BBI == OtherBB->begin())
1321 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001322
Chris Lattnera65e2f72010-01-05 05:57:49 +00001323 // If the other block ends in an unconditional branch, check for the 'if then
1324 // else' case. there is an instruction before the branch.
Craig Topperf40110f2014-04-25 05:29:35 +00001325 StoreInst *OtherStore = nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001326 if (OtherBr->isUnconditional()) {
1327 --BBI;
1328 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001329 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001330 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001331 if (BBI==OtherBB->begin())
1332 return false;
1333 --BBI;
1334 }
Eli Friedman8bc586e2011-08-15 22:09:40 +00001335 // If this isn't a store, isn't a store to the same location, or is not the
1336 // right kind of store, bail out.
Chris Lattnera65e2f72010-01-05 05:57:49 +00001337 OtherStore = dyn_cast<StoreInst>(BBI);
1338 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +00001339 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001340 return false;
1341 } else {
1342 // Otherwise, the other block ended with a conditional branch. If one of the
1343 // destinations is StoreBB, then we have the if/then case.
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001344 if (OtherBr->getSuccessor(0) != StoreBB &&
Chris Lattnera65e2f72010-01-05 05:57:49 +00001345 OtherBr->getSuccessor(1) != StoreBB)
1346 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001347
Chris Lattnera65e2f72010-01-05 05:57:49 +00001348 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
1349 // if/then triangle. See if there is a store to the same ptr as SI that
1350 // lives in OtherBB.
1351 for (;; --BBI) {
1352 // Check to see if we find the matching store.
1353 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
1354 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +00001355 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001356 return false;
1357 break;
1358 }
1359 // If we find something that may be using or overwriting the stored
1360 // value, or if we run out of instructions, we can't do the xform.
1361 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
1362 BBI == OtherBB->begin())
1363 return false;
1364 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001365
Chris Lattnera65e2f72010-01-05 05:57:49 +00001366 // In order to eliminate the store in OtherBr, we have to
1367 // make sure nothing reads or overwrites the stored value in
1368 // StoreBB.
1369 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1370 // FIXME: This should really be AA driven.
1371 if (I->mayReadFromMemory() || I->mayWriteToMemory())
1372 return false;
1373 }
1374 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001375
Chris Lattnera65e2f72010-01-05 05:57:49 +00001376 // Insert a PHI node now if we need it.
1377 Value *MergedVal = OtherStore->getOperand(0);
1378 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +00001379 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +00001380 PN->addIncoming(SI.getOperand(0), SI.getParent());
1381 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
1382 MergedVal = InsertNewInstBefore(PN, DestBB->front());
1383 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001384
Chris Lattnera65e2f72010-01-05 05:57:49 +00001385 // Advance to a place where it is safe to insert the new store and
1386 // insert it.
Bill Wendling8ddfc092011-08-16 20:45:24 +00001387 BBI = DestBB->getFirstInsertionPt();
Eli Friedman35211c62011-05-27 00:19:40 +00001388 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +00001389 SI.isVolatile(),
1390 SI.getAlignment(),
1391 SI.getOrdering(),
1392 SI.getSynchScope());
Eli Friedman35211c62011-05-27 00:19:40 +00001393 InsertNewInstBefore(NewSI, *BBI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001394 NewSI->setDebugLoc(OtherStore->getDebugLoc());
Eli Friedman35211c62011-05-27 00:19:40 +00001395
Hal Finkelcc39b672014-07-24 12:16:19 +00001396 // If the two stores had AA tags, merge them.
1397 AAMDNodes AATags;
1398 SI.getAAMetadata(AATags);
1399 if (AATags) {
1400 OtherStore->getAAMetadata(AATags, /* Merge = */ true);
1401 NewSI->setAAMetadata(AATags);
1402 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001403
Chris Lattnera65e2f72010-01-05 05:57:49 +00001404 // Nuke the old stores.
Sanjay Patel4b198802016-02-01 22:23:39 +00001405 eraseInstFromFunction(SI);
1406 eraseInstFromFunction(*OtherStore);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001407 return true;
1408}