blob: 933849f460bea7902a4d92439a32db7c838d73fd [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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/Statistic.h"
Dan Gohman826bdf82010-05-28 16:19:17 +000016#include "llvm/Analysis/Loads.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/DataLayout.h"
Chandler Carruthbc6378d2014-10-19 10:46:46 +000018#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/IntrinsicInst.h"
Charles Davis33d1dc02015-02-25 05:10:25 +000020#include "llvm/IR/MDBuilder.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000021#include "llvm/Transforms/Utils/BasicBlockUtils.h"
22#include "llvm/Transforms/Utils/Local.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000023using namespace llvm;
24
Chandler Carruth964daaa2014-04-22 02:55:47 +000025#define DEBUG_TYPE "instcombine"
26
Chandler Carruthc908ca12012-08-21 08:39:44 +000027STATISTIC(NumDeadStore, "Number of dead stores eliminated");
28STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
29
30/// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
31/// some part of a constant global variable. This intentionally only accepts
32/// constant expressions because we can't rewrite arbitrary instructions.
33static bool pointsToConstantGlobal(Value *V) {
34 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
35 return GV->isConstant();
Matt Arsenault607281772014-04-24 00:01:09 +000036
37 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000038 if (CE->getOpcode() == Instruction::BitCast ||
Matt Arsenault607281772014-04-24 00:01:09 +000039 CE->getOpcode() == Instruction::AddrSpaceCast ||
Chandler Carruthc908ca12012-08-21 08:39:44 +000040 CE->getOpcode() == Instruction::GetElementPtr)
41 return pointsToConstantGlobal(CE->getOperand(0));
Matt Arsenault607281772014-04-24 00:01:09 +000042 }
Chandler Carruthc908ca12012-08-21 08:39:44 +000043 return false;
44}
45
46/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
47/// pointer to an alloca. Ignore any reads of the pointer, return false if we
48/// see any stores or other unknown uses. If we see pointer arithmetic, keep
49/// track of whether it moves the pointer (with IsOffset) but otherwise traverse
50/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
51/// the alloca, and if the source pointer is a pointer to a constant global, we
52/// can optimize this.
53static bool
54isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Reid Kleckner813dab22014-07-01 21:36:20 +000055 SmallVectorImpl<Instruction *> &ToDelete) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000056 // We track lifetime intrinsics as we encounter them. If we decide to go
57 // ahead and replace the value with the global, this lets the caller quickly
58 // eliminate the markers.
59
Reid Kleckner813dab22014-07-01 21:36:20 +000060 SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect;
61 ValuesToInspect.push_back(std::make_pair(V, false));
62 while (!ValuesToInspect.empty()) {
63 auto ValuePair = ValuesToInspect.pop_back_val();
64 const bool IsOffset = ValuePair.second;
65 for (auto &U : ValuePair.first->uses()) {
66 Instruction *I = cast<Instruction>(U.getUser());
Chandler Carruthc908ca12012-08-21 08:39:44 +000067
Reid Kleckner813dab22014-07-01 21:36:20 +000068 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
69 // Ignore non-volatile loads, they are always ok.
70 if (!LI->isSimple()) return false;
Chandler Carruthc908ca12012-08-21 08:39:44 +000071 continue;
72 }
Reid Kleckner813dab22014-07-01 21:36:20 +000073
74 if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) {
75 // If uses of the bitcast are ok, we are ok.
76 ValuesToInspect.push_back(std::make_pair(I, IsOffset));
77 continue;
78 }
79 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
80 // If the GEP has all zero indices, it doesn't offset the pointer. If it
81 // doesn't, it does.
82 ValuesToInspect.push_back(
83 std::make_pair(I, IsOffset || !GEP->hasAllZeroIndices()));
84 continue;
85 }
86
Benjamin Kramer3a09ef62015-04-10 14:50:08 +000087 if (auto CS = CallSite(I)) {
Reid Kleckner813dab22014-07-01 21:36:20 +000088 // If this is the function being called then we treat it like a load and
89 // ignore it.
90 if (CS.isCallee(&U))
91 continue;
92
93 // Inalloca arguments are clobbered by the call.
94 unsigned ArgNo = CS.getArgumentNo(&U);
95 if (CS.isInAllocaArgument(ArgNo))
96 return false;
97
98 // If this is a readonly/readnone call site, then we know it is just a
99 // load (but one that potentially returns the value itself), so we can
100 // ignore it if we know that the value isn't captured.
101 if (CS.onlyReadsMemory() &&
102 (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
103 continue;
104
105 // If this is being passed as a byval argument, the caller is making a
106 // copy, so it is only a read of the alloca.
107 if (CS.isByValArgument(ArgNo))
108 continue;
109 }
110
111 // Lifetime intrinsics can be handled by the caller.
112 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
113 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
114 II->getIntrinsicID() == Intrinsic::lifetime_end) {
115 assert(II->use_empty() && "Lifetime markers have no result to use!");
116 ToDelete.push_back(II);
117 continue;
118 }
119 }
120
121 // If this is isn't our memcpy/memmove, reject it as something we can't
122 // handle.
123 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
124 if (!MI)
125 return false;
126
127 // If the transfer is using the alloca as a source of the transfer, then
128 // ignore it since it is a load (unless the transfer is volatile).
129 if (U.getOperandNo() == 1) {
130 if (MI->isVolatile()) return false;
131 continue;
132 }
133
134 // If we already have seen a copy, reject the second one.
135 if (TheCopy) return false;
136
137 // If the pointer has been offset from the start of the alloca, we can't
138 // safely handle this.
139 if (IsOffset) return false;
140
141 // If the memintrinsic isn't using the alloca as the dest, reject it.
142 if (U.getOperandNo() != 0) return false;
143
144 // If the source of the memcpy/move is not a constant global, reject it.
145 if (!pointsToConstantGlobal(MI->getSource()))
146 return false;
147
148 // Otherwise, the transform is safe. Remember the copy instruction.
149 TheCopy = MI;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000150 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000151 }
152 return true;
153}
154
155/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
156/// modified by a copy from a constant global. If we can prove this, we can
157/// replace any uses of the alloca with uses of the global directly.
158static MemTransferInst *
159isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
160 SmallVectorImpl<Instruction *> &ToDelete) {
Craig Topperf40110f2014-04-25 05:29:35 +0000161 MemTransferInst *TheCopy = nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000162 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
163 return TheCopy;
Craig Topperf40110f2014-04-25 05:29:35 +0000164 return nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000165}
166
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000167static Instruction *simplifyAllocaArraySize(InstCombiner &IC, AllocaInst &AI) {
Duncan P. N. Exon Smith720762e2015-03-13 19:30:44 +0000168 // Check for array size of 1 (scalar allocation).
Duncan P. N. Exon Smithbe95b4a2015-03-13 19:42:09 +0000169 if (!AI.isArrayAllocation()) {
170 // i32 1 is the canonical array size for scalar allocations.
171 if (AI.getArraySize()->getType()->isIntegerTy(32))
172 return nullptr;
173
174 // Canonicalize it.
175 Value *V = IC.Builder->getInt32(1);
176 AI.setOperand(0, V);
177 return &AI;
178 }
Duncan P. N. Exon Smith720762e2015-03-13 19:30:44 +0000179
Chris Lattnera65e2f72010-01-05 05:57:49 +0000180 // 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 +0000181 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
182 Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
183 AllocaInst *New = IC.Builder->CreateAlloca(NewTy, nullptr, AI.getName());
184 New->setAlignment(AI.getAlignment());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000185
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000186 // Scan to the end of the allocation instructions, to skip over a block of
187 // allocas if possible...also skip interleaved debug info
188 //
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000189 BasicBlock::iterator It(New);
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000190 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
191 ++It;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000192
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000193 // Now that I is pointing to the first non-allocation-inst in the block,
194 // insert our getelementptr instruction...
195 //
196 Type *IdxTy = IC.getDataLayout().getIntPtrType(AI.getType());
197 Value *NullIdx = Constant::getNullValue(IdxTy);
198 Value *Idx[2] = {NullIdx, NullIdx};
199 Instruction *GEP =
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000200 GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000201 IC.InsertNewInstBefore(GEP, *It);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000202
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000203 // Now make everything use the getelementptr instead of the original
204 // allocation.
205 return IC.ReplaceInstUsesWith(AI, GEP);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000206 }
207
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000208 if (isa<UndefValue>(AI.getArraySize()))
209 return IC.ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
210
Duncan P. N. Exon Smith07ff9b02015-03-13 19:34:55 +0000211 // Ensure that the alloca array size argument has type intptr_t, so that
212 // any casting is exposed early.
213 Type *IntPtrTy = IC.getDataLayout().getIntPtrType(AI.getType());
214 if (AI.getArraySize()->getType() != IntPtrTy) {
215 Value *V = IC.Builder->CreateIntCast(AI.getArraySize(), IntPtrTy, false);
216 AI.setOperand(0, V);
217 return &AI;
218 }
219
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000220 return nullptr;
221}
222
223Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
224 if (auto *I = simplifyAllocaArraySize(*this, AI))
225 return I;
226
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000227 if (AI.getAllocatedType()->isSized()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000228 // If the alignment is 0 (unspecified), assign it the preferred alignment.
229 if (AI.getAlignment() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000230 AI.setAlignment(DL.getPrefTypeAlignment(AI.getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000231
232 // Move all alloca's of zero byte objects to the entry block and merge them
233 // together. Note that we only do this for alloca's, because malloc should
234 // allocate and return a unique pointer, even for a zero byte allocation.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000235 if (DL.getTypeAllocSize(AI.getAllocatedType()) == 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000236 // For a zero sized alloca there is no point in doing an array allocation.
237 // This is helpful if the array size is a complicated expression not used
238 // elsewhere.
239 if (AI.isArrayAllocation()) {
240 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
241 return &AI;
242 }
243
244 // Get the first instruction in the entry block.
245 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
246 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
247 if (FirstInst != &AI) {
248 // If the entry block doesn't start with a zero-size alloca then move
249 // this one to the start of the entry block. There is no problem with
250 // dominance as the array size was forced to a constant earlier already.
251 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
252 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000253 DL.getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000254 AI.moveBefore(FirstInst);
255 return &AI;
256 }
257
Richard Osborneb68053e2012-09-18 09:31:44 +0000258 // If the alignment of the entry block alloca is 0 (unspecified),
259 // assign it the preferred alignment.
260 if (EntryAI->getAlignment() == 0)
261 EntryAI->setAlignment(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000262 DL.getPrefTypeAlignment(EntryAI->getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000263 // Replace this zero-sized alloca with the one at the start of the entry
264 // block after ensuring that the address will be aligned enough for both
265 // types.
Richard Osborneb68053e2012-09-18 09:31:44 +0000266 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
267 AI.getAlignment());
Duncan Sands8bc764a2012-06-26 13:39:21 +0000268 EntryAI->setAlignment(MaxAlign);
269 if (AI.getType() != EntryAI->getType())
270 return new BitCastInst(EntryAI, AI.getType());
271 return ReplaceInstUsesWith(AI, EntryAI);
272 }
273 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000274 }
275
Eli Friedmanb14873c2012-11-26 23:04:53 +0000276 if (AI.getAlignment()) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000277 // Check to see if this allocation is only modified by a memcpy/memmove from
278 // a constant global whose alignment is equal to or exceeds that of the
279 // allocation. If this is the case, we can change all users to use
280 // the constant global instead. This is commonly produced by the CFE by
281 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
282 // is only subsequently read.
283 SmallVector<Instruction *, 4> ToDelete;
284 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000285 unsigned SourceAlign = getOrEnforceKnownAlignment(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000286 Copy->getSource(), AI.getAlignment(), DL, &AI, AC, DT);
Eli Friedmanb14873c2012-11-26 23:04:53 +0000287 if (AI.getAlignment() <= SourceAlign) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000288 DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
289 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
290 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
291 EraseInstFromFunction(*ToDelete[i]);
292 Constant *TheSrc = cast<Constant>(Copy->getSource());
Matt Arsenaultbbf18c62013-12-07 02:58:45 +0000293 Constant *Cast
294 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
295 Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000296 EraseInstFromFunction(*Copy);
297 ++NumGlobalCopies;
298 return NewI;
299 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000300 }
301 }
302
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000303 // At last, use the generic allocation site handler to aggressively remove
304 // unused allocas.
305 return visitAllocSite(AI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000306}
307
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000308/// \brief Helper to combine a load to a new type.
309///
310/// This just does the work of combining a load to a new type. It handles
311/// metadata, etc., and returns the new instruction. The \c NewTy should be the
312/// loaded *value* type. This will convert it to a pointer, cast the operand to
313/// that pointer type, load it, etc.
314///
315/// Note that this will create all of the instructions with whatever insert
316/// point the \c InstCombiner currently is using.
Mehdi Amini2668a482015-05-07 05:52:40 +0000317static LoadInst *combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy,
318 const Twine &Suffix = "") {
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000319 Value *Ptr = LI.getPointerOperand();
320 unsigned AS = LI.getPointerAddressSpace();
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000321 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000322 LI.getAllMetadata(MD);
323
324 LoadInst *NewLoad = IC.Builder->CreateAlignedLoad(
325 IC.Builder->CreateBitCast(Ptr, NewTy->getPointerTo(AS)),
Mehdi Amini2668a482015-05-07 05:52:40 +0000326 LI.getAlignment(), LI.getName() + Suffix);
Charles Davis33d1dc02015-02-25 05:10:25 +0000327 MDBuilder MDB(NewLoad->getContext());
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000328 for (const auto &MDPair : MD) {
329 unsigned ID = MDPair.first;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000330 MDNode *N = MDPair.second;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000331 // Note, essentially every kind of metadata should be preserved here! This
332 // routine is supposed to clone a load instruction changing *only its type*.
333 // The only metadata it makes sense to drop is metadata which is invalidated
334 // when the pointer type changes. This should essentially never be the case
335 // in LLVM, but we explicitly switch over only known metadata to be
336 // conservatively correct. If you are adding metadata to LLVM which pertains
337 // to loads, you almost certainly want to add it here.
338 switch (ID) {
339 case LLVMContext::MD_dbg:
340 case LLVMContext::MD_tbaa:
341 case LLVMContext::MD_prof:
342 case LLVMContext::MD_fpmath:
343 case LLVMContext::MD_tbaa_struct:
344 case LLVMContext::MD_invariant_load:
345 case LLVMContext::MD_alias_scope:
346 case LLVMContext::MD_noalias:
Philip Reames5a3f5f72014-10-21 00:13:20 +0000347 case LLVMContext::MD_nontemporal:
348 case LLVMContext::MD_mem_parallel_loop_access:
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000349 // All of these directly apply.
350 NewLoad->setMetadata(ID, N);
351 break;
352
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000353 case LLVMContext::MD_nonnull:
Charles Davis33d1dc02015-02-25 05:10:25 +0000354 // This only directly applies if the new type is also a pointer.
355 if (NewTy->isPointerTy()) {
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000356 NewLoad->setMetadata(ID, N);
Charles Davis33d1dc02015-02-25 05:10:25 +0000357 break;
358 }
359 // If it's integral now, translate it to !range metadata.
360 if (NewTy->isIntegerTy()) {
361 auto *ITy = cast<IntegerType>(NewTy);
362 auto *NullInt = ConstantExpr::getPtrToInt(
363 ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
364 auto *NonNullInt =
365 ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
366 NewLoad->setMetadata(LLVMContext::MD_range,
367 MDB.createRange(NonNullInt, NullInt));
368 }
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000369 break;
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000370 case LLVMContext::MD_align:
371 case LLVMContext::MD_dereferenceable:
372 case LLVMContext::MD_dereferenceable_or_null:
373 // These only directly apply if the new type is also a pointer.
374 if (NewTy->isPointerTy())
375 NewLoad->setMetadata(ID, N);
376 break;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000377 case LLVMContext::MD_range:
378 // FIXME: It would be nice to propagate this in some way, but the type
Charles Davis33d1dc02015-02-25 05:10:25 +0000379 // conversions make it hard. If the new type is a pointer, we could
380 // translate it to !nonnull metadata.
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000381 break;
382 }
383 }
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000384 return NewLoad;
385}
386
Chandler Carruthfa11d832015-01-22 03:34:54 +0000387/// \brief Combine a store to a new type.
388///
389/// Returns the newly created store instruction.
390static StoreInst *combineStoreToNewValue(InstCombiner &IC, StoreInst &SI, Value *V) {
391 Value *Ptr = SI.getPointerOperand();
392 unsigned AS = SI.getPointerAddressSpace();
393 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
394 SI.getAllMetadata(MD);
395
396 StoreInst *NewStore = IC.Builder->CreateAlignedStore(
397 V, IC.Builder->CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
398 SI.getAlignment());
399 for (const auto &MDPair : MD) {
400 unsigned ID = MDPair.first;
401 MDNode *N = MDPair.second;
402 // Note, essentially every kind of metadata should be preserved here! This
403 // routine is supposed to clone a store instruction changing *only its
404 // type*. The only metadata it makes sense to drop is metadata which is
405 // invalidated when the pointer type changes. This should essentially
406 // never be the case in LLVM, but we explicitly switch over only known
407 // metadata to be conservatively correct. If you are adding metadata to
408 // LLVM which pertains to stores, you almost certainly want to add it
409 // here.
410 switch (ID) {
411 case LLVMContext::MD_dbg:
412 case LLVMContext::MD_tbaa:
413 case LLVMContext::MD_prof:
414 case LLVMContext::MD_fpmath:
415 case LLVMContext::MD_tbaa_struct:
416 case LLVMContext::MD_alias_scope:
417 case LLVMContext::MD_noalias:
418 case LLVMContext::MD_nontemporal:
419 case LLVMContext::MD_mem_parallel_loop_access:
Chandler Carruthfa11d832015-01-22 03:34:54 +0000420 // All of these directly apply.
421 NewStore->setMetadata(ID, N);
422 break;
423
424 case LLVMContext::MD_invariant_load:
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000425 case LLVMContext::MD_nonnull:
Chandler Carruthfa11d832015-01-22 03:34:54 +0000426 case LLVMContext::MD_range:
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000427 case LLVMContext::MD_align:
428 case LLVMContext::MD_dereferenceable:
429 case LLVMContext::MD_dereferenceable_or_null:
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000430 // These don't apply for stores.
Chandler Carruthfa11d832015-01-22 03:34:54 +0000431 break;
432 }
433 }
434
435 return NewStore;
436}
437
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000438/// \brief Combine loads to match the type of value their uses after looking
439/// through intervening bitcasts.
440///
441/// The core idea here is that if the result of a load is used in an operation,
442/// we should load the type most conducive to that operation. For example, when
443/// loading an integer and converting that immediately to a pointer, we should
444/// instead directly load a pointer.
445///
446/// However, this routine must never change the width of a load or the number of
447/// loads as that would introduce a semantic change. This combine is expected to
448/// be a semantic no-op which just allows loads to more closely model the types
449/// of their consuming operations.
450///
451/// Currently, we also refuse to change the precise type used for an atomic load
452/// or a volatile load. This is debatable, and might be reasonable to change
453/// later. However, it is risky in case some backend or other part of LLVM is
454/// relying on the exact type loaded to select appropriate atomic operations.
455static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
456 // FIXME: We could probably with some care handle both volatile and atomic
457 // loads here but it isn't clear that this is important.
458 if (!LI.isSimple())
459 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000460
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000461 if (LI.use_empty())
462 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000463
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000464 Type *Ty = LI.getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000465 const DataLayout &DL = IC.getDataLayout();
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000466
467 // Try to canonicalize loads which are only ever stored to operate over
468 // integers instead of any other type. We only do this when the loaded type
469 // is sized and has a size exactly the same as its store size and the store
470 // size is a legal integer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000471 if (!Ty->isIntegerTy() && Ty->isSized() &&
472 DL.isLegalInteger(DL.getTypeStoreSizeInBits(Ty)) &&
473 DL.getTypeStoreSizeInBits(Ty) == DL.getTypeSizeInBits(Ty)) {
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000474 if (std::all_of(LI.user_begin(), LI.user_end(), [&LI](User *U) {
475 auto *SI = dyn_cast<StoreInst>(U);
476 return SI && SI->getPointerOperand() != &LI;
477 })) {
478 LoadInst *NewLoad = combineLoadToNewType(
479 IC, LI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000480 Type::getIntNTy(LI.getContext(), DL.getTypeStoreSizeInBits(Ty)));
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000481 // Replace all the stores with stores of the newly loaded value.
482 for (auto UI = LI.user_begin(), UE = LI.user_end(); UI != UE;) {
483 auto *SI = cast<StoreInst>(*UI++);
484 IC.Builder->SetInsertPoint(SI);
485 combineStoreToNewValue(IC, *SI, NewLoad);
486 IC.EraseInstFromFunction(*SI);
487 }
488 assert(LI.use_empty() && "Failed to remove all users of the load!");
489 // Return the old load so the combiner can delete it safely.
490 return &LI;
491 }
492 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000493
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000494 // Fold away bit casts of the loaded value by loading the desired type.
David Majnemerdd043522015-05-28 18:39:17 +0000495 // We can do this for BitCastInsts as well as casts from and to pointer types,
496 // as long as those are noops (i.e., the source or dest type have the same
497 // bitwidth as the target's pointers).
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000498 if (LI.hasOneUse())
David Majnemerdd043522015-05-28 18:39:17 +0000499 if (auto* CI = dyn_cast<CastInst>(LI.user_back())) {
500 if (CI->isNoopCast(DL)) {
501 LoadInst *NewLoad = combineLoadToNewType(IC, LI, CI->getDestTy());
502 CI->replaceAllUsesWith(NewLoad);
503 IC.EraseInstFromFunction(*CI);
504 return &LI;
505 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000506 }
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000507
Chandler Carrutha7f247e2014-12-09 19:21:16 +0000508 // FIXME: We should also canonicalize loads of vectors when their elements are
509 // cast to other types.
Craig Topperf40110f2014-04-25 05:29:35 +0000510 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000511}
512
Mehdi Amini2668a482015-05-07 05:52:40 +0000513static Instruction *unpackLoadToAggregate(InstCombiner &IC, LoadInst &LI) {
514 // FIXME: We could probably with some care handle both volatile and atomic
515 // stores here but it isn't clear that this is important.
516 if (!LI.isSimple())
517 return nullptr;
518
519 Type *T = LI.getType();
520 if (!T->isAggregateType())
521 return nullptr;
522
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000523 assert(LI.getAlignment() && "Alignment must be set at this point");
Mehdi Amini2668a482015-05-07 05:52:40 +0000524
525 if (auto *ST = dyn_cast<StructType>(T)) {
526 // If the struct only have one element, we unpack.
527 if (ST->getNumElements() == 1) {
528 LoadInst *NewLoad = combineLoadToNewType(IC, LI, ST->getTypeAtIndex(0U),
529 ".unpack");
530 return IC.ReplaceInstUsesWith(LI, IC.Builder->CreateInsertValue(
531 UndefValue::get(T), NewLoad, 0, LI.getName()));
532 }
533 }
534
David Majnemer58fb0382015-05-11 05:04:22 +0000535 if (auto *AT = dyn_cast<ArrayType>(T)) {
536 // If the array only have one element, we unpack.
537 if (AT->getNumElements() == 1) {
538 LoadInst *NewLoad = combineLoadToNewType(IC, LI, AT->getElementType(),
539 ".unpack");
540 return IC.ReplaceInstUsesWith(LI, IC.Builder->CreateInsertValue(
541 UndefValue::get(T), NewLoad, 0, LI.getName()));
542 }
543 }
544
Mehdi Amini2668a482015-05-07 05:52:40 +0000545 return nullptr;
546}
547
Hal Finkel847e05f2015-02-20 03:05:53 +0000548// If we can determine that all possible objects pointed to by the provided
549// pointer value are, not only dereferenceable, but also definitively less than
550// or equal to the provided maximum size, then return true. Otherwise, return
551// false (constant global values and allocas fall into this category).
552//
553// FIXME: This should probably live in ValueTracking (or similar).
554static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000555 const DataLayout &DL) {
Hal Finkel847e05f2015-02-20 03:05:53 +0000556 SmallPtrSet<Value *, 4> Visited;
557 SmallVector<Value *, 4> Worklist(1, V);
558
559 do {
560 Value *P = Worklist.pop_back_val();
561 P = P->stripPointerCasts();
562
563 if (!Visited.insert(P).second)
564 continue;
565
566 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
567 Worklist.push_back(SI->getTrueValue());
568 Worklist.push_back(SI->getFalseValue());
569 continue;
570 }
571
572 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000573 for (Value *IncValue : PN->incoming_values())
574 Worklist.push_back(IncValue);
Hal Finkel847e05f2015-02-20 03:05:53 +0000575 continue;
576 }
577
578 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
579 if (GA->mayBeOverridden())
580 return false;
581 Worklist.push_back(GA->getAliasee());
582 continue;
583 }
584
585 // If we know how big this object is, and it is less than MaxSize, continue
586 // searching. Otherwise, return false.
587 if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
588 if (!AI->getAllocatedType()->isSized())
589 return false;
590
591 ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
592 if (!CS)
593 return false;
594
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000595 uint64_t TypeSize = DL.getTypeAllocSize(AI->getAllocatedType());
Hal Finkel847e05f2015-02-20 03:05:53 +0000596 // Make sure that, even if the multiplication below would wrap as an
597 // uint64_t, we still do the right thing.
598 if ((CS->getValue().zextOrSelf(128)*APInt(128, TypeSize)).ugt(MaxSize))
599 return false;
600 continue;
601 }
602
603 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
604 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
605 return false;
606
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000607 uint64_t InitSize = DL.getTypeAllocSize(GV->getType()->getElementType());
Hal Finkel847e05f2015-02-20 03:05:53 +0000608 if (InitSize > MaxSize)
609 return false;
610 continue;
611 }
612
613 return false;
614 } while (!Worklist.empty());
615
616 return true;
617}
618
619// If we're indexing into an object of a known size, and the outer index is
620// not a constant, but having any value but zero would lead to undefined
621// behavior, replace it with zero.
622//
623// For example, if we have:
624// @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
625// ...
626// %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x
627// ... = load i32* %arrayidx, align 4
628// Then we know that we can replace %x in the GEP with i64 0.
629//
630// FIXME: We could fold any GEP index to zero that would cause UB if it were
631// not zero. Currently, we only handle the first such index. Also, we could
632// also search through non-zero constant indices if we kept track of the
633// offsets those indices implied.
634static bool canReplaceGEPIdxWithZero(InstCombiner &IC, GetElementPtrInst *GEPI,
635 Instruction *MemI, unsigned &Idx) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000636 if (GEPI->getNumOperands() < 2)
Hal Finkel847e05f2015-02-20 03:05:53 +0000637 return false;
638
639 // Find the first non-zero index of a GEP. If all indices are zero, return
640 // one past the last index.
641 auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
642 unsigned I = 1;
643 for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
644 Value *V = GEPI->getOperand(I);
645 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
646 if (CI->isZero())
647 continue;
648
649 break;
650 }
651
652 return I;
653 };
654
655 // Skip through initial 'zero' indices, and find the corresponding pointer
656 // type. See if the next index is not a constant.
657 Idx = FirstNZIdx(GEPI);
658 if (Idx == GEPI->getNumOperands())
659 return false;
660 if (isa<Constant>(GEPI->getOperand(Idx)))
661 return false;
662
663 SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
David Blaikied288fb82015-03-30 21:41:43 +0000664 Type *AllocTy = GetElementPtrInst::getIndexedType(
665 cast<PointerType>(GEPI->getOperand(0)->getType()->getScalarType())
666 ->getElementType(),
667 Ops);
Hal Finkel847e05f2015-02-20 03:05:53 +0000668 if (!AllocTy || !AllocTy->isSized())
669 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000670 const DataLayout &DL = IC.getDataLayout();
671 uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy);
Hal Finkel847e05f2015-02-20 03:05:53 +0000672
673 // If there are more indices after the one we might replace with a zero, make
674 // sure they're all non-negative. If any of them are negative, the overall
675 // address being computed might be before the base address determined by the
676 // first non-zero index.
677 auto IsAllNonNegative = [&]() {
678 for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
679 bool KnownNonNegative, KnownNegative;
680 IC.ComputeSignBit(GEPI->getOperand(i), KnownNonNegative,
681 KnownNegative, 0, MemI);
682 if (KnownNonNegative)
683 continue;
684 return false;
685 }
686
687 return true;
688 };
689
690 // FIXME: If the GEP is not inbounds, and there are extra indices after the
691 // one we'll replace, those could cause the address computation to wrap
692 // (rendering the IsAllNonNegative() check below insufficient). We can do
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000693 // better, ignoring zero indices (and other indices we can prove small
Hal Finkel847e05f2015-02-20 03:05:53 +0000694 // enough not to wrap).
695 if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
696 return false;
697
698 // Note that isObjectSizeLessThanOrEq will return true only if the pointer is
699 // also known to be dereferenceable.
700 return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
701 IsAllNonNegative();
702}
703
704// If we're indexing into an object with a variable index for the memory
705// access, but the object has only one element, we can assume that the index
706// will always be zero. If we replace the GEP, return it.
707template <typename T>
708static Instruction *replaceGEPIdxWithZero(InstCombiner &IC, Value *Ptr,
709 T &MemI) {
710 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
711 unsigned Idx;
712 if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
713 Instruction *NewGEPI = GEPI->clone();
714 NewGEPI->setOperand(Idx,
715 ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
716 NewGEPI->insertBefore(GEPI);
717 MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI);
718 return NewGEPI;
719 }
720 }
721
722 return nullptr;
723}
724
Chris Lattnera65e2f72010-01-05 05:57:49 +0000725Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
726 Value *Op = LI.getOperand(0);
727
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000728 // Try to canonicalize the loaded type.
729 if (Instruction *Res = combineLoadToOperationType(*this, LI))
730 return Res;
731
Chris Lattnera65e2f72010-01-05 05:57:49 +0000732 // Attempt to improve the alignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000733 unsigned KnownAlign = getOrEnforceKnownAlignment(
734 Op, DL.getPrefTypeAlignment(LI.getType()), DL, &LI, AC, DT);
735 unsigned LoadAlign = LI.getAlignment();
736 unsigned EffectiveLoadAlign =
737 LoadAlign != 0 ? LoadAlign : DL.getABITypeAlignment(LI.getType());
Dan Gohman36196602010-08-03 18:20:32 +0000738
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000739 if (KnownAlign > EffectiveLoadAlign)
740 LI.setAlignment(KnownAlign);
741 else if (LoadAlign == 0)
742 LI.setAlignment(EffectiveLoadAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000743
Hal Finkel847e05f2015-02-20 03:05:53 +0000744 // Replace GEP indices if possible.
745 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) {
746 Worklist.Add(NewGEPI);
747 return &LI;
748 }
749
Eli Friedman8bc586e2011-08-15 22:09:40 +0000750 // None of the following transforms are legal for volatile/atomic loads.
751 // FIXME: Some of it is okay for atomic loads; needs refactoring.
Craig Topperf40110f2014-04-25 05:29:35 +0000752 if (!LI.isSimple()) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000753
Mehdi Amini2668a482015-05-07 05:52:40 +0000754 if (Instruction *Res = unpackLoadToAggregate(*this, LI))
755 return Res;
756
Chris Lattnera65e2f72010-01-05 05:57:49 +0000757 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +0000758 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +0000759 // separated by a few arithmetic operations.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000760 BasicBlock::iterator BBI(LI);
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000761 AAMDNodes AATags;
Larisse Voufo532bf712015-09-18 19:14:35 +0000762 if (Value *AvailableVal =
763 FindAvailableLoadedValue(Op, LI.getParent(), BBI,
764 DefMaxInstsToScan, AA, &AATags)) {
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000765 if (LoadInst *NLI = dyn_cast<LoadInst>(AvailableVal)) {
766 unsigned KnownIDs[] = {
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000767 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
768 LLVMContext::MD_noalias, LLVMContext::MD_range,
769 LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull,
770 LLVMContext::MD_invariant_group, LLVMContext::MD_align,
771 LLVMContext::MD_dereferenceable,
772 LLVMContext::MD_dereferenceable_or_null};
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000773 combineMetadata(NLI, &LI, KnownIDs);
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000774 };
775
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000776 return ReplaceInstUsesWith(
Chandler Carruth1a3c2c42014-11-25 08:20:27 +0000777 LI, Builder->CreateBitOrPointerCast(AvailableVal, LI.getType(),
778 LI.getName() + ".cast"));
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000779 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000780
781 // load(gep null, ...) -> unreachable
782 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
783 const Value *GEPI0 = GEPI->getOperand(0);
784 // TODO: Consider a target hook for valid address spaces for this xform.
785 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
786 // Insert a new store to null instruction before the load to indicate
787 // that this code is not reachable. We do this instead of inserting
788 // an unreachable instruction directly because we cannot modify the
789 // CFG.
790 new StoreInst(UndefValue::get(LI.getType()),
791 Constant::getNullValue(Op->getType()), &LI);
792 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
793 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000794 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000795
796 // load null/undef -> unreachable
797 // TODO: Consider a target hook for valid address spaces for this xform.
798 if (isa<UndefValue>(Op) ||
799 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
800 // Insert a new store to null instruction before the load to indicate that
801 // this code is not reachable. We do this instead of inserting an
802 // unreachable instruction directly because we cannot modify the CFG.
803 new StoreInst(UndefValue::get(LI.getType()),
804 Constant::getNullValue(Op->getType()), &LI);
805 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
806 }
807
Chris Lattnera65e2f72010-01-05 05:57:49 +0000808 if (Op->hasOneUse()) {
809 // Change select and PHI nodes to select values instead of addresses: this
810 // helps alias analysis out a lot, allows many others simplifications, and
811 // exposes redundancy in the code.
812 //
813 // Note that we cannot do the transformation unless we know that the
814 // introduced loads cannot trap! Something like this is valid as long as
815 // the condition is always false: load (select bool %C, int* null, int* %G),
816 // but it would not be valid if we transformed it to load from null
817 // unconditionally.
818 //
819 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
820 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +0000821 unsigned Align = LI.getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000822 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align) &&
823 isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align)) {
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000824 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
Bob Wilson56600a12010-01-30 04:42:39 +0000825 SI->getOperand(1)->getName()+".val");
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000826 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
Bob Wilson56600a12010-01-30 04:42:39 +0000827 SI->getOperand(2)->getName()+".val");
828 V1->setAlignment(Align);
829 V2->setAlignment(Align);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000830 return SelectInst::Create(SI->getCondition(), V1, V2);
831 }
832
833 // load (select (cond, null, P)) -> load P
Larisse Voufo532bf712015-09-18 19:14:35 +0000834 if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
Philip Reames5ad26c32014-12-29 22:46:21 +0000835 LI.getPointerAddressSpace() == 0) {
836 LI.setOperand(0, SI->getOperand(2));
837 return &LI;
838 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000839
840 // load (select (cond, P, null)) -> load P
Philip Reames5ad26c32014-12-29 22:46:21 +0000841 if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
842 LI.getPointerAddressSpace() == 0) {
843 LI.setOperand(0, SI->getOperand(1));
844 return &LI;
845 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000846 }
847 }
Craig Topperf40110f2014-04-25 05:29:35 +0000848 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000849}
850
Chandler Carruth816d26f2014-11-25 10:09:51 +0000851/// \brief Combine stores to match the type of value being stored.
852///
853/// The core idea here is that the memory does not have any intrinsic type and
854/// where we can we should match the type of a store to the type of value being
855/// stored.
856///
857/// However, this routine must never change the width of a store or the number of
858/// stores as that would introduce a semantic change. This combine is expected to
859/// be a semantic no-op which just allows stores to more closely model the types
860/// of their incoming values.
861///
862/// Currently, we also refuse to change the precise type used for an atomic or
863/// volatile store. This is debatable, and might be reasonable to change later.
864/// However, it is risky in case some backend or other part of LLVM is relying
865/// on the exact type stored to select appropriate atomic operations.
866///
867/// \returns true if the store was successfully combined away. This indicates
868/// the caller must erase the store instruction. We have to let the caller erase
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000869/// the store instruction as otherwise there is no way to signal whether it was
Chandler Carruth816d26f2014-11-25 10:09:51 +0000870/// combined or not: IC.EraseInstFromFunction returns a null pointer.
871static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) {
872 // FIXME: We could probably with some care handle both volatile and atomic
873 // stores here but it isn't clear that this is important.
874 if (!SI.isSimple())
875 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000876
Chandler Carruth816d26f2014-11-25 10:09:51 +0000877 Value *V = SI.getValueOperand();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000878
Chandler Carruth816d26f2014-11-25 10:09:51 +0000879 // Fold away bit casts of the stored value by storing the original type.
880 if (auto *BC = dyn_cast<BitCastInst>(V)) {
Chandler Carrutha7f247e2014-12-09 19:21:16 +0000881 V = BC->getOperand(0);
Chandler Carruth2135b972015-01-21 23:45:01 +0000882 combineStoreToNewValue(IC, SI, V);
Chandler Carruth816d26f2014-11-25 10:09:51 +0000883 return true;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000884 }
885
Chandler Carruth816d26f2014-11-25 10:09:51 +0000886 // FIXME: We should also canonicalize loads of vectors when their elements are
887 // cast to other types.
888 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000889}
890
Mehdi Aminib344ac92015-03-14 22:19:33 +0000891static bool unpackStoreToAggregate(InstCombiner &IC, StoreInst &SI) {
892 // FIXME: We could probably with some care handle both volatile and atomic
893 // stores here but it isn't clear that this is important.
894 if (!SI.isSimple())
895 return false;
896
897 Value *V = SI.getValueOperand();
898 Type *T = V->getType();
899
900 if (!T->isAggregateType())
901 return false;
902
Mehdi Amini2668a482015-05-07 05:52:40 +0000903 if (auto *ST = dyn_cast<StructType>(T)) {
Mehdi Aminib344ac92015-03-14 22:19:33 +0000904 // If the struct only have one element, we unpack.
905 if (ST->getNumElements() == 1) {
906 V = IC.Builder->CreateExtractValue(V, 0);
907 combineStoreToNewValue(IC, SI, V);
908 return true;
909 }
910 }
911
David Majnemer75364602015-05-11 05:04:27 +0000912 if (auto *AT = dyn_cast<ArrayType>(T)) {
913 // If the array only have one element, we unpack.
914 if (AT->getNumElements() == 1) {
915 V = IC.Builder->CreateExtractValue(V, 0);
916 combineStoreToNewValue(IC, SI, V);
917 return true;
918 }
919 }
920
Mehdi Aminib344ac92015-03-14 22:19:33 +0000921 return false;
922}
923
Chris Lattnera65e2f72010-01-05 05:57:49 +0000924/// equivalentAddressValues - Test if A and B will obviously have the same
925/// value. This includes recognizing that %t0 and %t1 will have the same
926/// value in code like this:
927/// %t0 = getelementptr \@a, 0, 3
928/// store i32 0, i32* %t0
929/// %t1 = getelementptr \@a, 0, 3
930/// %t2 = load i32* %t1
931///
932static bool equivalentAddressValues(Value *A, Value *B) {
933 // Test if the values are trivially equivalent.
934 if (A == B) return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000935
Chris Lattnera65e2f72010-01-05 05:57:49 +0000936 // Test if the values come form identical arithmetic instructions.
937 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
938 // its only used to compare two uses within the same basic block, which
939 // means that they'll always either have the same value or one of them
940 // will have an undefined value.
941 if (isa<BinaryOperator>(A) ||
942 isa<CastInst>(A) ||
943 isa<PHINode>(A) ||
944 isa<GetElementPtrInst>(A))
945 if (Instruction *BI = dyn_cast<Instruction>(B))
946 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
947 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000948
Chris Lattnera65e2f72010-01-05 05:57:49 +0000949 // Otherwise they may not be equivalent.
950 return false;
951}
952
Chris Lattnera65e2f72010-01-05 05:57:49 +0000953Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
954 Value *Val = SI.getOperand(0);
955 Value *Ptr = SI.getOperand(1);
956
Chandler Carruth816d26f2014-11-25 10:09:51 +0000957 // Try to canonicalize the stored type.
958 if (combineStoreToValueType(*this, SI))
959 return EraseInstFromFunction(SI);
960
Chris Lattnera65e2f72010-01-05 05:57:49 +0000961 // Attempt to improve the alignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000962 unsigned KnownAlign = getOrEnforceKnownAlignment(
963 Ptr, DL.getPrefTypeAlignment(Val->getType()), DL, &SI, AC, DT);
964 unsigned StoreAlign = SI.getAlignment();
965 unsigned EffectiveStoreAlign =
966 StoreAlign != 0 ? StoreAlign : DL.getABITypeAlignment(Val->getType());
Dan Gohman36196602010-08-03 18:20:32 +0000967
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000968 if (KnownAlign > EffectiveStoreAlign)
969 SI.setAlignment(KnownAlign);
970 else if (StoreAlign == 0)
971 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000972
Mehdi Aminib344ac92015-03-14 22:19:33 +0000973 // Try to canonicalize the stored type.
974 if (unpackStoreToAggregate(*this, SI))
975 return EraseInstFromFunction(SI);
976
Hal Finkel847e05f2015-02-20 03:05:53 +0000977 // Replace GEP indices if possible.
978 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) {
979 Worklist.Add(NewGEPI);
980 return &SI;
981 }
982
Eli Friedman8bc586e2011-08-15 22:09:40 +0000983 // Don't hack volatile/atomic stores.
984 // FIXME: Some bits are legal for atomic stores; needs refactoring.
Craig Topperf40110f2014-04-25 05:29:35 +0000985 if (!SI.isSimple()) return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +0000986
987 // If the RHS is an alloca with a single use, zapify the store, making the
988 // alloca dead.
989 if (Ptr->hasOneUse()) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000990 if (isa<AllocaInst>(Ptr))
Eli Friedman8bc586e2011-08-15 22:09:40 +0000991 return EraseInstFromFunction(SI);
992 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
993 if (isa<AllocaInst>(GEP->getOperand(0))) {
994 if (GEP->getOperand(0)->hasOneUse())
995 return EraseInstFromFunction(SI);
996 }
997 }
998 }
999
Chris Lattnera65e2f72010-01-05 05:57:49 +00001000 // Do really simple DSE, to catch cases where there are several consecutive
1001 // stores to the same location, separated by a few arithmetic operations. This
1002 // situation often occurs with bitfield accesses.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001003 BasicBlock::iterator BBI(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001004 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
1005 --ScanInsts) {
1006 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001007 // Don't count debug info directives, lest they affect codegen,
1008 // and we skip pointer-to-pointer bitcasts, which are NOPs.
1009 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001010 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001011 ScanInsts++;
1012 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001013 }
1014
Chris Lattnera65e2f72010-01-05 05:57:49 +00001015 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
1016 // Prev store isn't volatile, and stores to the same location?
Eli Friedman8bc586e2011-08-15 22:09:40 +00001017 if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
1018 SI.getOperand(1))) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001019 ++NumDeadStore;
1020 ++BBI;
1021 EraseInstFromFunction(*PrevSI);
1022 continue;
1023 }
1024 break;
1025 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001026
Chris Lattnera65e2f72010-01-05 05:57:49 +00001027 // If this is a load, we have to stop. However, if the loaded value is from
1028 // the pointer we're loading and is producing the pointer we're storing,
1029 // then *this* store is dead (X = load P; store X -> P).
1030 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Jin-Gu Kangb452db02011-03-14 01:21:00 +00001031 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
Eli Friedman8bc586e2011-08-15 22:09:40 +00001032 LI->isSimple())
Jin-Gu Kangb452db02011-03-14 01:21:00 +00001033 return EraseInstFromFunction(SI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001034
Chris Lattnera65e2f72010-01-05 05:57:49 +00001035 // Otherwise, this is a load from some other location. Stores before it
1036 // may not be dead.
1037 break;
1038 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001039
Chris Lattnera65e2f72010-01-05 05:57:49 +00001040 // Don't skip over loads or things that can modify memory.
1041 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
1042 break;
1043 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001044
1045 // store X, null -> turns into 'unreachable' in SimplifyCFG
1046 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
1047 if (!isa<UndefValue>(Val)) {
1048 SI.setOperand(0, UndefValue::get(Val->getType()));
1049 if (Instruction *U = dyn_cast<Instruction>(Val))
1050 Worklist.Add(U); // Dropped a use.
1051 }
Craig Topperf40110f2014-04-25 05:29:35 +00001052 return nullptr; // Do not modify these!
Chris Lattnera65e2f72010-01-05 05:57:49 +00001053 }
1054
1055 // store undef, Ptr -> noop
1056 if (isa<UndefValue>(Val))
1057 return EraseInstFromFunction(SI);
1058
Chris Lattnera65e2f72010-01-05 05:57:49 +00001059 // If this store is the last instruction in the basic block (possibly
Victor Hernandez5f5abd52010-01-21 23:07:15 +00001060 // excepting debug info instructions), and if the block ends with an
1061 // unconditional branch, try to move it to the successor block.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001062 BBI = SI.getIterator();
Chris Lattnera65e2f72010-01-05 05:57:49 +00001063 do {
1064 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001065 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001066 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Chris Lattnera65e2f72010-01-05 05:57:49 +00001067 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
1068 if (BI->isUnconditional())
1069 if (SimplifyStoreAtEndOfBlock(SI))
Craig Topperf40110f2014-04-25 05:29:35 +00001070 return nullptr; // xform done!
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001071
Craig Topperf40110f2014-04-25 05:29:35 +00001072 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001073}
1074
1075/// SimplifyStoreAtEndOfBlock - Turn things like:
1076/// if () { *P = v1; } else { *P = v2 }
1077/// into a phi node with a store in the successor.
1078///
1079/// Simplify things like:
1080/// *P = v1; if () { *P = v2; }
1081/// into a phi node with a store in the successor.
1082///
1083bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
1084 BasicBlock *StoreBB = SI.getParent();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001085
Chris Lattnera65e2f72010-01-05 05:57:49 +00001086 // Check to see if the successor block has exactly two incoming edges. If
1087 // so, see if the other predecessor contains a store to the same location.
1088 // if so, insert a PHI node (if needed) and move the stores down.
1089 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001090
Chris Lattnera65e2f72010-01-05 05:57:49 +00001091 // Determine whether Dest has exactly two predecessors and, if so, compute
1092 // the other predecessor.
1093 pred_iterator PI = pred_begin(DestBB);
Gabor Greif1b787df2010-07-12 15:48:26 +00001094 BasicBlock *P = *PI;
Craig Topperf40110f2014-04-25 05:29:35 +00001095 BasicBlock *OtherBB = nullptr;
Gabor Greif1b787df2010-07-12 15:48:26 +00001096
1097 if (P != StoreBB)
1098 OtherBB = P;
1099
1100 if (++PI == pred_end(DestBB))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001101 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001102
Gabor Greif1b787df2010-07-12 15:48:26 +00001103 P = *PI;
1104 if (P != StoreBB) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001105 if (OtherBB)
1106 return false;
Gabor Greif1b787df2010-07-12 15:48:26 +00001107 OtherBB = P;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001108 }
1109 if (++PI != pred_end(DestBB))
1110 return false;
1111
1112 // Bail out if all the relevant blocks aren't distinct (this can happen,
1113 // for example, if SI is in an infinite loop)
1114 if (StoreBB == DestBB || OtherBB == DestBB)
1115 return false;
1116
1117 // Verify that the other block ends in a branch and is not otherwise empty.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001118 BasicBlock::iterator BBI(OtherBB->getTerminator());
Chris Lattnera65e2f72010-01-05 05:57:49 +00001119 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
1120 if (!OtherBr || BBI == OtherBB->begin())
1121 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001122
Chris Lattnera65e2f72010-01-05 05:57:49 +00001123 // If the other block ends in an unconditional branch, check for the 'if then
1124 // else' case. there is an instruction before the branch.
Craig Topperf40110f2014-04-25 05:29:35 +00001125 StoreInst *OtherStore = nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001126 if (OtherBr->isUnconditional()) {
1127 --BBI;
1128 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001129 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001130 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001131 if (BBI==OtherBB->begin())
1132 return false;
1133 --BBI;
1134 }
Eli Friedman8bc586e2011-08-15 22:09:40 +00001135 // If this isn't a store, isn't a store to the same location, or is not the
1136 // right kind of store, bail out.
Chris Lattnera65e2f72010-01-05 05:57:49 +00001137 OtherStore = dyn_cast<StoreInst>(BBI);
1138 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +00001139 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001140 return false;
1141 } else {
1142 // Otherwise, the other block ended with a conditional branch. If one of the
1143 // destinations is StoreBB, then we have the if/then case.
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001144 if (OtherBr->getSuccessor(0) != StoreBB &&
Chris Lattnera65e2f72010-01-05 05:57:49 +00001145 OtherBr->getSuccessor(1) != StoreBB)
1146 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001147
Chris Lattnera65e2f72010-01-05 05:57:49 +00001148 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
1149 // if/then triangle. See if there is a store to the same ptr as SI that
1150 // lives in OtherBB.
1151 for (;; --BBI) {
1152 // Check to see if we find the matching store.
1153 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
1154 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +00001155 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001156 return false;
1157 break;
1158 }
1159 // If we find something that may be using or overwriting the stored
1160 // value, or if we run out of instructions, we can't do the xform.
1161 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
1162 BBI == OtherBB->begin())
1163 return false;
1164 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001165
Chris Lattnera65e2f72010-01-05 05:57:49 +00001166 // In order to eliminate the store in OtherBr, we have to
1167 // make sure nothing reads or overwrites the stored value in
1168 // StoreBB.
1169 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1170 // FIXME: This should really be AA driven.
1171 if (I->mayReadFromMemory() || I->mayWriteToMemory())
1172 return false;
1173 }
1174 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001175
Chris Lattnera65e2f72010-01-05 05:57:49 +00001176 // Insert a PHI node now if we need it.
1177 Value *MergedVal = OtherStore->getOperand(0);
1178 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +00001179 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +00001180 PN->addIncoming(SI.getOperand(0), SI.getParent());
1181 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
1182 MergedVal = InsertNewInstBefore(PN, DestBB->front());
1183 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001184
Chris Lattnera65e2f72010-01-05 05:57:49 +00001185 // Advance to a place where it is safe to insert the new store and
1186 // insert it.
Bill Wendling8ddfc092011-08-16 20:45:24 +00001187 BBI = DestBB->getFirstInsertionPt();
Eli Friedman35211c62011-05-27 00:19:40 +00001188 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +00001189 SI.isVolatile(),
1190 SI.getAlignment(),
1191 SI.getOrdering(),
1192 SI.getSynchScope());
Eli Friedman35211c62011-05-27 00:19:40 +00001193 InsertNewInstBefore(NewSI, *BBI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001194 NewSI->setDebugLoc(OtherStore->getDebugLoc());
Eli Friedman35211c62011-05-27 00:19:40 +00001195
Hal Finkelcc39b672014-07-24 12:16:19 +00001196 // If the two stores had AA tags, merge them.
1197 AAMDNodes AATags;
1198 SI.getAAMetadata(AATags);
1199 if (AATags) {
1200 OtherStore->getAAMetadata(AATags, /* Merge = */ true);
1201 NewSI->setAAMetadata(AATags);
1202 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001203
Chris Lattnera65e2f72010-01-05 05:57:49 +00001204 // Nuke the old stores.
1205 EraseInstFromFunction(SI);
1206 EraseInstFromFunction(*OtherStore);
1207 return true;
1208}