blob: e313f673710a8c0b03d28a9d1d0eaffba98c2e25 [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
87 if (CallSite CS = I) {
88 // 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) {
Dan Gohmandf5d7dc2010-05-28 15:09:00 +0000168 // Ensure that the alloca array size argument has type intptr_t, so that
169 // any casting is exposed early.
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000170 Type *IntPtrTy = IC.getDataLayout().getIntPtrType(AI.getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000171 if (AI.getArraySize()->getType() != IntPtrTy) {
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000172 Value *V = IC.Builder->CreateIntCast(AI.getArraySize(), IntPtrTy, false);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000173 AI.setOperand(0, V);
174 return &AI;
Dan Gohmandf5d7dc2010-05-28 15:09:00 +0000175 }
176
Chris Lattnera65e2f72010-01-05 05:57:49 +0000177 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
178 if (AI.isArrayAllocation()) { // Check C != 1
179 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000180 Type *NewTy =
Chris Lattnera65e2f72010-01-05 05:57:49 +0000181 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000182 AllocaInst *New = IC.Builder->CreateAlloca(NewTy, nullptr, AI.getName());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000183 New->setAlignment(AI.getAlignment());
184
185 // Scan to the end of the allocation instructions, to skip over a block of
186 // allocas if possible...also skip interleaved debug info
187 //
188 BasicBlock::iterator It = New;
189 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
190
191 // Now that I is pointing to the first non-allocation-inst in the block,
192 // insert our getelementptr instruction...
193 //
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000194 Type *IdxTy = IC.getDataLayout().getIntPtrType(AI.getType());
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +0000195 Value *NullIdx = Constant::getNullValue(IdxTy);
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000196 Value *Idx[2] = { NullIdx, NullIdx };
Eli Friedman41e509a2011-05-18 23:58:37 +0000197 Instruction *GEP =
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000198 GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000199 IC.InsertNewInstBefore(GEP, *It);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000200
201 // Now make everything use the getelementptr instead of the original
202 // allocation.
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000203 return IC.ReplaceInstUsesWith(AI, GEP);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000204 } else if (isa<UndefValue>(AI.getArraySize())) {
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000205 return IC.ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000206 }
207 }
208
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000209 return nullptr;
210}
211
212Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
213 if (auto *I = simplifyAllocaArraySize(*this, AI))
214 return I;
215
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000216 if (AI.getAllocatedType()->isSized()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000217 // If the alignment is 0 (unspecified), assign it the preferred alignment.
218 if (AI.getAlignment() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000219 AI.setAlignment(DL.getPrefTypeAlignment(AI.getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000220
221 // Move all alloca's of zero byte objects to the entry block and merge them
222 // together. Note that we only do this for alloca's, because malloc should
223 // allocate and return a unique pointer, even for a zero byte allocation.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000224 if (DL.getTypeAllocSize(AI.getAllocatedType()) == 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000225 // For a zero sized alloca there is no point in doing an array allocation.
226 // This is helpful if the array size is a complicated expression not used
227 // elsewhere.
228 if (AI.isArrayAllocation()) {
229 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
230 return &AI;
231 }
232
233 // Get the first instruction in the entry block.
234 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
235 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
236 if (FirstInst != &AI) {
237 // If the entry block doesn't start with a zero-size alloca then move
238 // this one to the start of the entry block. There is no problem with
239 // dominance as the array size was forced to a constant earlier already.
240 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
241 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000242 DL.getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000243 AI.moveBefore(FirstInst);
244 return &AI;
245 }
246
Richard Osborneb68053e2012-09-18 09:31:44 +0000247 // If the alignment of the entry block alloca is 0 (unspecified),
248 // assign it the preferred alignment.
249 if (EntryAI->getAlignment() == 0)
250 EntryAI->setAlignment(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000251 DL.getPrefTypeAlignment(EntryAI->getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000252 // Replace this zero-sized alloca with the one at the start of the entry
253 // block after ensuring that the address will be aligned enough for both
254 // types.
Richard Osborneb68053e2012-09-18 09:31:44 +0000255 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
256 AI.getAlignment());
Duncan Sands8bc764a2012-06-26 13:39:21 +0000257 EntryAI->setAlignment(MaxAlign);
258 if (AI.getType() != EntryAI->getType())
259 return new BitCastInst(EntryAI, AI.getType());
260 return ReplaceInstUsesWith(AI, EntryAI);
261 }
262 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000263 }
264
Eli Friedmanb14873c2012-11-26 23:04:53 +0000265 if (AI.getAlignment()) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000266 // Check to see if this allocation is only modified by a memcpy/memmove from
267 // a constant global whose alignment is equal to or exceeds that of the
268 // allocation. If this is the case, we can change all users to use
269 // the constant global instead. This is commonly produced by the CFE by
270 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
271 // is only subsequently read.
272 SmallVector<Instruction *, 4> ToDelete;
273 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000274 unsigned SourceAlign = getOrEnforceKnownAlignment(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000275 Copy->getSource(), AI.getAlignment(), DL, &AI, AC, DT);
Eli Friedmanb14873c2012-11-26 23:04:53 +0000276 if (AI.getAlignment() <= SourceAlign) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000277 DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
278 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
279 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
280 EraseInstFromFunction(*ToDelete[i]);
281 Constant *TheSrc = cast<Constant>(Copy->getSource());
Matt Arsenaultbbf18c62013-12-07 02:58:45 +0000282 Constant *Cast
283 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
284 Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000285 EraseInstFromFunction(*Copy);
286 ++NumGlobalCopies;
287 return NewI;
288 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000289 }
290 }
291
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000292 // At last, use the generic allocation site handler to aggressively remove
293 // unused allocas.
294 return visitAllocSite(AI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000295}
296
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000297/// \brief Helper to combine a load to a new type.
298///
299/// This just does the work of combining a load to a new type. It handles
300/// metadata, etc., and returns the new instruction. The \c NewTy should be the
301/// loaded *value* type. This will convert it to a pointer, cast the operand to
302/// that pointer type, load it, etc.
303///
304/// Note that this will create all of the instructions with whatever insert
305/// point the \c InstCombiner currently is using.
306static LoadInst *combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy) {
307 Value *Ptr = LI.getPointerOperand();
308 unsigned AS = LI.getPointerAddressSpace();
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000309 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000310 LI.getAllMetadata(MD);
311
312 LoadInst *NewLoad = IC.Builder->CreateAlignedLoad(
313 IC.Builder->CreateBitCast(Ptr, NewTy->getPointerTo(AS)),
314 LI.getAlignment(), LI.getName());
Charles Davis33d1dc02015-02-25 05:10:25 +0000315 MDBuilder MDB(NewLoad->getContext());
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000316 for (const auto &MDPair : MD) {
317 unsigned ID = MDPair.first;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000318 MDNode *N = MDPair.second;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000319 // Note, essentially every kind of metadata should be preserved here! This
320 // routine is supposed to clone a load instruction changing *only its type*.
321 // The only metadata it makes sense to drop is metadata which is invalidated
322 // when the pointer type changes. This should essentially never be the case
323 // in LLVM, but we explicitly switch over only known metadata to be
324 // conservatively correct. If you are adding metadata to LLVM which pertains
325 // to loads, you almost certainly want to add it here.
326 switch (ID) {
327 case LLVMContext::MD_dbg:
328 case LLVMContext::MD_tbaa:
329 case LLVMContext::MD_prof:
330 case LLVMContext::MD_fpmath:
331 case LLVMContext::MD_tbaa_struct:
332 case LLVMContext::MD_invariant_load:
333 case LLVMContext::MD_alias_scope:
334 case LLVMContext::MD_noalias:
Philip Reames5a3f5f72014-10-21 00:13:20 +0000335 case LLVMContext::MD_nontemporal:
336 case LLVMContext::MD_mem_parallel_loop_access:
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000337 // All of these directly apply.
338 NewLoad->setMetadata(ID, N);
339 break;
340
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000341 case LLVMContext::MD_nonnull:
Charles Davis33d1dc02015-02-25 05:10:25 +0000342 // This only directly applies if the new type is also a pointer.
343 if (NewTy->isPointerTy()) {
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000344 NewLoad->setMetadata(ID, N);
Charles Davis33d1dc02015-02-25 05:10:25 +0000345 break;
346 }
347 // If it's integral now, translate it to !range metadata.
348 if (NewTy->isIntegerTy()) {
349 auto *ITy = cast<IntegerType>(NewTy);
350 auto *NullInt = ConstantExpr::getPtrToInt(
351 ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
352 auto *NonNullInt =
353 ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
354 NewLoad->setMetadata(LLVMContext::MD_range,
355 MDB.createRange(NonNullInt, NullInt));
356 }
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000357 break;
358
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000359 case LLVMContext::MD_range:
360 // FIXME: It would be nice to propagate this in some way, but the type
Charles Davis33d1dc02015-02-25 05:10:25 +0000361 // conversions make it hard. If the new type is a pointer, we could
362 // translate it to !nonnull metadata.
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000363 break;
364 }
365 }
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000366 return NewLoad;
367}
368
Chandler Carruthfa11d832015-01-22 03:34:54 +0000369/// \brief Combine a store to a new type.
370///
371/// Returns the newly created store instruction.
372static StoreInst *combineStoreToNewValue(InstCombiner &IC, StoreInst &SI, Value *V) {
373 Value *Ptr = SI.getPointerOperand();
374 unsigned AS = SI.getPointerAddressSpace();
375 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
376 SI.getAllMetadata(MD);
377
378 StoreInst *NewStore = IC.Builder->CreateAlignedStore(
379 V, IC.Builder->CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
380 SI.getAlignment());
381 for (const auto &MDPair : MD) {
382 unsigned ID = MDPair.first;
383 MDNode *N = MDPair.second;
384 // Note, essentially every kind of metadata should be preserved here! This
385 // routine is supposed to clone a store instruction changing *only its
386 // type*. The only metadata it makes sense to drop is metadata which is
387 // invalidated when the pointer type changes. This should essentially
388 // never be the case in LLVM, but we explicitly switch over only known
389 // metadata to be conservatively correct. If you are adding metadata to
390 // LLVM which pertains to stores, you almost certainly want to add it
391 // here.
392 switch (ID) {
393 case LLVMContext::MD_dbg:
394 case LLVMContext::MD_tbaa:
395 case LLVMContext::MD_prof:
396 case LLVMContext::MD_fpmath:
397 case LLVMContext::MD_tbaa_struct:
398 case LLVMContext::MD_alias_scope:
399 case LLVMContext::MD_noalias:
400 case LLVMContext::MD_nontemporal:
401 case LLVMContext::MD_mem_parallel_loop_access:
Chandler Carruthfa11d832015-01-22 03:34:54 +0000402 // All of these directly apply.
403 NewStore->setMetadata(ID, N);
404 break;
405
406 case LLVMContext::MD_invariant_load:
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000407 case LLVMContext::MD_nonnull:
Chandler Carruthfa11d832015-01-22 03:34:54 +0000408 case LLVMContext::MD_range:
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000409 // These don't apply for stores.
Chandler Carruthfa11d832015-01-22 03:34:54 +0000410 break;
411 }
412 }
413
414 return NewStore;
415}
416
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000417/// \brief Combine loads to match the type of value their uses after looking
418/// through intervening bitcasts.
419///
420/// The core idea here is that if the result of a load is used in an operation,
421/// we should load the type most conducive to that operation. For example, when
422/// loading an integer and converting that immediately to a pointer, we should
423/// instead directly load a pointer.
424///
425/// However, this routine must never change the width of a load or the number of
426/// loads as that would introduce a semantic change. This combine is expected to
427/// be a semantic no-op which just allows loads to more closely model the types
428/// of their consuming operations.
429///
430/// Currently, we also refuse to change the precise type used for an atomic load
431/// or a volatile load. This is debatable, and might be reasonable to change
432/// later. However, it is risky in case some backend or other part of LLVM is
433/// relying on the exact type loaded to select appropriate atomic operations.
434static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
435 // FIXME: We could probably with some care handle both volatile and atomic
436 // loads here but it isn't clear that this is important.
437 if (!LI.isSimple())
438 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000439
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000440 if (LI.use_empty())
441 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000442
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000443 Type *Ty = LI.getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000444 const DataLayout &DL = IC.getDataLayout();
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000445
446 // Try to canonicalize loads which are only ever stored to operate over
447 // integers instead of any other type. We only do this when the loaded type
448 // is sized and has a size exactly the same as its store size and the store
449 // size is a legal integer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000450 if (!Ty->isIntegerTy() && Ty->isSized() &&
451 DL.isLegalInteger(DL.getTypeStoreSizeInBits(Ty)) &&
452 DL.getTypeStoreSizeInBits(Ty) == DL.getTypeSizeInBits(Ty)) {
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000453 if (std::all_of(LI.user_begin(), LI.user_end(), [&LI](User *U) {
454 auto *SI = dyn_cast<StoreInst>(U);
455 return SI && SI->getPointerOperand() != &LI;
456 })) {
457 LoadInst *NewLoad = combineLoadToNewType(
458 IC, LI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000459 Type::getIntNTy(LI.getContext(), DL.getTypeStoreSizeInBits(Ty)));
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000460 // Replace all the stores with stores of the newly loaded value.
461 for (auto UI = LI.user_begin(), UE = LI.user_end(); UI != UE;) {
462 auto *SI = cast<StoreInst>(*UI++);
463 IC.Builder->SetInsertPoint(SI);
464 combineStoreToNewValue(IC, *SI, NewLoad);
465 IC.EraseInstFromFunction(*SI);
466 }
467 assert(LI.use_empty() && "Failed to remove all users of the load!");
468 // Return the old load so the combiner can delete it safely.
469 return &LI;
470 }
471 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000472
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000473 // Fold away bit casts of the loaded value by loading the desired type.
474 if (LI.hasOneUse())
475 if (auto *BC = dyn_cast<BitCastInst>(LI.user_back())) {
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000476 LoadInst *NewLoad = combineLoadToNewType(IC, LI, BC->getDestTy());
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000477 BC->replaceAllUsesWith(NewLoad);
478 IC.EraseInstFromFunction(*BC);
479 return &LI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000480 }
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000481
Chandler Carrutha7f247e2014-12-09 19:21:16 +0000482 // FIXME: We should also canonicalize loads of vectors when their elements are
483 // cast to other types.
Craig Topperf40110f2014-04-25 05:29:35 +0000484 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000485}
486
Hal Finkel847e05f2015-02-20 03:05:53 +0000487// If we can determine that all possible objects pointed to by the provided
488// pointer value are, not only dereferenceable, but also definitively less than
489// or equal to the provided maximum size, then return true. Otherwise, return
490// false (constant global values and allocas fall into this category).
491//
492// FIXME: This should probably live in ValueTracking (or similar).
493static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000494 const DataLayout &DL) {
Hal Finkel847e05f2015-02-20 03:05:53 +0000495 SmallPtrSet<Value *, 4> Visited;
496 SmallVector<Value *, 4> Worklist(1, V);
497
498 do {
499 Value *P = Worklist.pop_back_val();
500 P = P->stripPointerCasts();
501
502 if (!Visited.insert(P).second)
503 continue;
504
505 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
506 Worklist.push_back(SI->getTrueValue());
507 Worklist.push_back(SI->getFalseValue());
508 continue;
509 }
510
511 if (PHINode *PN = dyn_cast<PHINode>(P)) {
512 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
513 Worklist.push_back(PN->getIncomingValue(i));
514 continue;
515 }
516
517 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
518 if (GA->mayBeOverridden())
519 return false;
520 Worklist.push_back(GA->getAliasee());
521 continue;
522 }
523
524 // If we know how big this object is, and it is less than MaxSize, continue
525 // searching. Otherwise, return false.
526 if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
527 if (!AI->getAllocatedType()->isSized())
528 return false;
529
530 ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
531 if (!CS)
532 return false;
533
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000534 uint64_t TypeSize = DL.getTypeAllocSize(AI->getAllocatedType());
Hal Finkel847e05f2015-02-20 03:05:53 +0000535 // Make sure that, even if the multiplication below would wrap as an
536 // uint64_t, we still do the right thing.
537 if ((CS->getValue().zextOrSelf(128)*APInt(128, TypeSize)).ugt(MaxSize))
538 return false;
539 continue;
540 }
541
542 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
543 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
544 return false;
545
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000546 uint64_t InitSize = DL.getTypeAllocSize(GV->getType()->getElementType());
Hal Finkel847e05f2015-02-20 03:05:53 +0000547 if (InitSize > MaxSize)
548 return false;
549 continue;
550 }
551
552 return false;
553 } while (!Worklist.empty());
554
555 return true;
556}
557
558// If we're indexing into an object of a known size, and the outer index is
559// not a constant, but having any value but zero would lead to undefined
560// behavior, replace it with zero.
561//
562// For example, if we have:
563// @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
564// ...
565// %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x
566// ... = load i32* %arrayidx, align 4
567// Then we know that we can replace %x in the GEP with i64 0.
568//
569// FIXME: We could fold any GEP index to zero that would cause UB if it were
570// not zero. Currently, we only handle the first such index. Also, we could
571// also search through non-zero constant indices if we kept track of the
572// offsets those indices implied.
573static bool canReplaceGEPIdxWithZero(InstCombiner &IC, GetElementPtrInst *GEPI,
574 Instruction *MemI, unsigned &Idx) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000575 if (GEPI->getNumOperands() < 2)
Hal Finkel847e05f2015-02-20 03:05:53 +0000576 return false;
577
578 // Find the first non-zero index of a GEP. If all indices are zero, return
579 // one past the last index.
580 auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
581 unsigned I = 1;
582 for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
583 Value *V = GEPI->getOperand(I);
584 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
585 if (CI->isZero())
586 continue;
587
588 break;
589 }
590
591 return I;
592 };
593
594 // Skip through initial 'zero' indices, and find the corresponding pointer
595 // type. See if the next index is not a constant.
596 Idx = FirstNZIdx(GEPI);
597 if (Idx == GEPI->getNumOperands())
598 return false;
599 if (isa<Constant>(GEPI->getOperand(Idx)))
600 return false;
601
602 SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
603 Type *AllocTy =
604 GetElementPtrInst::getIndexedType(GEPI->getOperand(0)->getType(), Ops);
605 if (!AllocTy || !AllocTy->isSized())
606 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000607 const DataLayout &DL = IC.getDataLayout();
608 uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy);
Hal Finkel847e05f2015-02-20 03:05:53 +0000609
610 // If there are more indices after the one we might replace with a zero, make
611 // sure they're all non-negative. If any of them are negative, the overall
612 // address being computed might be before the base address determined by the
613 // first non-zero index.
614 auto IsAllNonNegative = [&]() {
615 for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
616 bool KnownNonNegative, KnownNegative;
617 IC.ComputeSignBit(GEPI->getOperand(i), KnownNonNegative,
618 KnownNegative, 0, MemI);
619 if (KnownNonNegative)
620 continue;
621 return false;
622 }
623
624 return true;
625 };
626
627 // FIXME: If the GEP is not inbounds, and there are extra indices after the
628 // one we'll replace, those could cause the address computation to wrap
629 // (rendering the IsAllNonNegative() check below insufficient). We can do
630 // better, ignoring zero indicies (and other indicies we can prove small
631 // enough not to wrap).
632 if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
633 return false;
634
635 // Note that isObjectSizeLessThanOrEq will return true only if the pointer is
636 // also known to be dereferenceable.
637 return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
638 IsAllNonNegative();
639}
640
641// If we're indexing into an object with a variable index for the memory
642// access, but the object has only one element, we can assume that the index
643// will always be zero. If we replace the GEP, return it.
644template <typename T>
645static Instruction *replaceGEPIdxWithZero(InstCombiner &IC, Value *Ptr,
646 T &MemI) {
647 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
648 unsigned Idx;
649 if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
650 Instruction *NewGEPI = GEPI->clone();
651 NewGEPI->setOperand(Idx,
652 ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
653 NewGEPI->insertBefore(GEPI);
654 MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI);
655 return NewGEPI;
656 }
657 }
658
659 return nullptr;
660}
661
Chris Lattnera65e2f72010-01-05 05:57:49 +0000662Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
663 Value *Op = LI.getOperand(0);
664
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000665 // Try to canonicalize the loaded type.
666 if (Instruction *Res = combineLoadToOperationType(*this, LI))
667 return Res;
668
Chris Lattnera65e2f72010-01-05 05:57:49 +0000669 // Attempt to improve the alignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000670 unsigned KnownAlign = getOrEnforceKnownAlignment(
671 Op, DL.getPrefTypeAlignment(LI.getType()), DL, &LI, AC, DT);
672 unsigned LoadAlign = LI.getAlignment();
673 unsigned EffectiveLoadAlign =
674 LoadAlign != 0 ? LoadAlign : DL.getABITypeAlignment(LI.getType());
Dan Gohman36196602010-08-03 18:20:32 +0000675
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000676 if (KnownAlign > EffectiveLoadAlign)
677 LI.setAlignment(KnownAlign);
678 else if (LoadAlign == 0)
679 LI.setAlignment(EffectiveLoadAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000680
Hal Finkel847e05f2015-02-20 03:05:53 +0000681 // Replace GEP indices if possible.
682 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) {
683 Worklist.Add(NewGEPI);
684 return &LI;
685 }
686
Eli Friedman8bc586e2011-08-15 22:09:40 +0000687 // None of the following transforms are legal for volatile/atomic loads.
688 // FIXME: Some of it is okay for atomic loads; needs refactoring.
Craig Topperf40110f2014-04-25 05:29:35 +0000689 if (!LI.isSimple()) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000690
Chris Lattnera65e2f72010-01-05 05:57:49 +0000691 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +0000692 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +0000693 // separated by a few arithmetic operations.
694 BasicBlock::iterator BBI = &LI;
695 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000696 return ReplaceInstUsesWith(
Chandler Carruth1a3c2c42014-11-25 08:20:27 +0000697 LI, Builder->CreateBitOrPointerCast(AvailableVal, LI.getType(),
698 LI.getName() + ".cast"));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000699
700 // load(gep null, ...) -> unreachable
701 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
702 const Value *GEPI0 = GEPI->getOperand(0);
703 // TODO: Consider a target hook for valid address spaces for this xform.
704 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
705 // Insert a new store to null instruction before the load to indicate
706 // that this code is not reachable. We do this instead of inserting
707 // an unreachable instruction directly because we cannot modify the
708 // CFG.
709 new StoreInst(UndefValue::get(LI.getType()),
710 Constant::getNullValue(Op->getType()), &LI);
711 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
712 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000713 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000714
715 // load null/undef -> unreachable
716 // TODO: Consider a target hook for valid address spaces for this xform.
717 if (isa<UndefValue>(Op) ||
718 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
719 // Insert a new store to null instruction before the load to indicate that
720 // this code is not reachable. We do this instead of inserting an
721 // unreachable instruction directly because we cannot modify the CFG.
722 new StoreInst(UndefValue::get(LI.getType()),
723 Constant::getNullValue(Op->getType()), &LI);
724 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
725 }
726
Chris Lattnera65e2f72010-01-05 05:57:49 +0000727 if (Op->hasOneUse()) {
728 // Change select and PHI nodes to select values instead of addresses: this
729 // helps alias analysis out a lot, allows many others simplifications, and
730 // exposes redundancy in the code.
731 //
732 // Note that we cannot do the transformation unless we know that the
733 // introduced loads cannot trap! Something like this is valid as long as
734 // the condition is always false: load (select bool %C, int* null, int* %G),
735 // but it would not be valid if we transformed it to load from null
736 // unconditionally.
737 //
738 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
739 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +0000740 unsigned Align = LI.getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000741 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align) &&
742 isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align)) {
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000743 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
Bob Wilson56600a12010-01-30 04:42:39 +0000744 SI->getOperand(1)->getName()+".val");
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000745 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
Bob Wilson56600a12010-01-30 04:42:39 +0000746 SI->getOperand(2)->getName()+".val");
747 V1->setAlignment(Align);
748 V2->setAlignment(Align);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000749 return SelectInst::Create(SI->getCondition(), V1, V2);
750 }
751
752 // load (select (cond, null, P)) -> load P
Philip Reames5ad26c32014-12-29 22:46:21 +0000753 if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
754 LI.getPointerAddressSpace() == 0) {
755 LI.setOperand(0, SI->getOperand(2));
756 return &LI;
757 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000758
759 // load (select (cond, P, null)) -> load P
Philip Reames5ad26c32014-12-29 22:46:21 +0000760 if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
761 LI.getPointerAddressSpace() == 0) {
762 LI.setOperand(0, SI->getOperand(1));
763 return &LI;
764 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000765 }
766 }
Craig Topperf40110f2014-04-25 05:29:35 +0000767 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000768}
769
Chandler Carruth816d26f2014-11-25 10:09:51 +0000770/// \brief Combine stores to match the type of value being stored.
771///
772/// The core idea here is that the memory does not have any intrinsic type and
773/// where we can we should match the type of a store to the type of value being
774/// stored.
775///
776/// However, this routine must never change the width of a store or the number of
777/// stores as that would introduce a semantic change. This combine is expected to
778/// be a semantic no-op which just allows stores to more closely model the types
779/// of their incoming values.
780///
781/// Currently, we also refuse to change the precise type used for an atomic or
782/// volatile store. This is debatable, and might be reasonable to change later.
783/// However, it is risky in case some backend or other part of LLVM is relying
784/// on the exact type stored to select appropriate atomic operations.
785///
786/// \returns true if the store was successfully combined away. This indicates
787/// the caller must erase the store instruction. We have to let the caller erase
788/// the store instruction sas otherwise there is no way to signal whether it was
789/// combined or not: IC.EraseInstFromFunction returns a null pointer.
790static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) {
791 // FIXME: We could probably with some care handle both volatile and atomic
792 // stores here but it isn't clear that this is important.
793 if (!SI.isSimple())
794 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000795
Chandler Carruth816d26f2014-11-25 10:09:51 +0000796 Value *V = SI.getValueOperand();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000797
Chandler Carruth816d26f2014-11-25 10:09:51 +0000798 // Fold away bit casts of the stored value by storing the original type.
799 if (auto *BC = dyn_cast<BitCastInst>(V)) {
Chandler Carrutha7f247e2014-12-09 19:21:16 +0000800 V = BC->getOperand(0);
Chandler Carruth2135b972015-01-21 23:45:01 +0000801 combineStoreToNewValue(IC, SI, V);
Chandler Carruth816d26f2014-11-25 10:09:51 +0000802 return true;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000803 }
804
Chandler Carruth816d26f2014-11-25 10:09:51 +0000805 // FIXME: We should also canonicalize loads of vectors when their elements are
806 // cast to other types.
807 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000808}
809
810/// equivalentAddressValues - Test if A and B will obviously have the same
811/// value. This includes recognizing that %t0 and %t1 will have the same
812/// value in code like this:
813/// %t0 = getelementptr \@a, 0, 3
814/// store i32 0, i32* %t0
815/// %t1 = getelementptr \@a, 0, 3
816/// %t2 = load i32* %t1
817///
818static bool equivalentAddressValues(Value *A, Value *B) {
819 // Test if the values are trivially equivalent.
820 if (A == B) return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000821
Chris Lattnera65e2f72010-01-05 05:57:49 +0000822 // Test if the values come form identical arithmetic instructions.
823 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
824 // its only used to compare two uses within the same basic block, which
825 // means that they'll always either have the same value or one of them
826 // will have an undefined value.
827 if (isa<BinaryOperator>(A) ||
828 isa<CastInst>(A) ||
829 isa<PHINode>(A) ||
830 isa<GetElementPtrInst>(A))
831 if (Instruction *BI = dyn_cast<Instruction>(B))
832 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
833 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000834
Chris Lattnera65e2f72010-01-05 05:57:49 +0000835 // Otherwise they may not be equivalent.
836 return false;
837}
838
Chris Lattnera65e2f72010-01-05 05:57:49 +0000839Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
840 Value *Val = SI.getOperand(0);
841 Value *Ptr = SI.getOperand(1);
842
Chandler Carruth816d26f2014-11-25 10:09:51 +0000843 // Try to canonicalize the stored type.
844 if (combineStoreToValueType(*this, SI))
845 return EraseInstFromFunction(SI);
846
Chris Lattnera65e2f72010-01-05 05:57:49 +0000847 // Attempt to improve the alignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000848 unsigned KnownAlign = getOrEnforceKnownAlignment(
849 Ptr, DL.getPrefTypeAlignment(Val->getType()), DL, &SI, AC, DT);
850 unsigned StoreAlign = SI.getAlignment();
851 unsigned EffectiveStoreAlign =
852 StoreAlign != 0 ? StoreAlign : DL.getABITypeAlignment(Val->getType());
Dan Gohman36196602010-08-03 18:20:32 +0000853
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000854 if (KnownAlign > EffectiveStoreAlign)
855 SI.setAlignment(KnownAlign);
856 else if (StoreAlign == 0)
857 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000858
Hal Finkel847e05f2015-02-20 03:05:53 +0000859 // Replace GEP indices if possible.
860 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) {
861 Worklist.Add(NewGEPI);
862 return &SI;
863 }
864
Eli Friedman8bc586e2011-08-15 22:09:40 +0000865 // Don't hack volatile/atomic stores.
866 // FIXME: Some bits are legal for atomic stores; needs refactoring.
Craig Topperf40110f2014-04-25 05:29:35 +0000867 if (!SI.isSimple()) return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +0000868
869 // If the RHS is an alloca with a single use, zapify the store, making the
870 // alloca dead.
871 if (Ptr->hasOneUse()) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000872 if (isa<AllocaInst>(Ptr))
Eli Friedman8bc586e2011-08-15 22:09:40 +0000873 return EraseInstFromFunction(SI);
874 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
875 if (isa<AllocaInst>(GEP->getOperand(0))) {
876 if (GEP->getOperand(0)->hasOneUse())
877 return EraseInstFromFunction(SI);
878 }
879 }
880 }
881
Chris Lattnera65e2f72010-01-05 05:57:49 +0000882 // Do really simple DSE, to catch cases where there are several consecutive
883 // stores to the same location, separated by a few arithmetic operations. This
884 // situation often occurs with bitfield accesses.
885 BasicBlock::iterator BBI = &SI;
886 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
887 --ScanInsts) {
888 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000889 // Don't count debug info directives, lest they affect codegen,
890 // and we skip pointer-to-pointer bitcasts, which are NOPs.
891 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000892 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000893 ScanInsts++;
894 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000895 }
896
Chris Lattnera65e2f72010-01-05 05:57:49 +0000897 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
898 // Prev store isn't volatile, and stores to the same location?
Eli Friedman8bc586e2011-08-15 22:09:40 +0000899 if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
900 SI.getOperand(1))) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000901 ++NumDeadStore;
902 ++BBI;
903 EraseInstFromFunction(*PrevSI);
904 continue;
905 }
906 break;
907 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000908
Chris Lattnera65e2f72010-01-05 05:57:49 +0000909 // If this is a load, we have to stop. However, if the loaded value is from
910 // the pointer we're loading and is producing the pointer we're storing,
911 // then *this* store is dead (X = load P; store X -> P).
912 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000913 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
Eli Friedman8bc586e2011-08-15 22:09:40 +0000914 LI->isSimple())
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000915 return EraseInstFromFunction(SI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000916
Chris Lattnera65e2f72010-01-05 05:57:49 +0000917 // Otherwise, this is a load from some other location. Stores before it
918 // may not be dead.
919 break;
920 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000921
Chris Lattnera65e2f72010-01-05 05:57:49 +0000922 // Don't skip over loads or things that can modify memory.
923 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
924 break;
925 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000926
927 // store X, null -> turns into 'unreachable' in SimplifyCFG
928 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
929 if (!isa<UndefValue>(Val)) {
930 SI.setOperand(0, UndefValue::get(Val->getType()));
931 if (Instruction *U = dyn_cast<Instruction>(Val))
932 Worklist.Add(U); // Dropped a use.
933 }
Craig Topperf40110f2014-04-25 05:29:35 +0000934 return nullptr; // Do not modify these!
Chris Lattnera65e2f72010-01-05 05:57:49 +0000935 }
936
937 // store undef, Ptr -> noop
938 if (isa<UndefValue>(Val))
939 return EraseInstFromFunction(SI);
940
Chris Lattnera65e2f72010-01-05 05:57:49 +0000941 // If this store is the last instruction in the basic block (possibly
Victor Hernandez5f5abd52010-01-21 23:07:15 +0000942 // excepting debug info instructions), and if the block ends with an
943 // unconditional branch, try to move it to the successor block.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000944 BBI = &SI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000945 do {
946 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000947 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000948 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000949 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
950 if (BI->isUnconditional())
951 if (SimplifyStoreAtEndOfBlock(SI))
Craig Topperf40110f2014-04-25 05:29:35 +0000952 return nullptr; // xform done!
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000953
Craig Topperf40110f2014-04-25 05:29:35 +0000954 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000955}
956
957/// SimplifyStoreAtEndOfBlock - Turn things like:
958/// if () { *P = v1; } else { *P = v2 }
959/// into a phi node with a store in the successor.
960///
961/// Simplify things like:
962/// *P = v1; if () { *P = v2; }
963/// into a phi node with a store in the successor.
964///
965bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
966 BasicBlock *StoreBB = SI.getParent();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000967
Chris Lattnera65e2f72010-01-05 05:57:49 +0000968 // Check to see if the successor block has exactly two incoming edges. If
969 // so, see if the other predecessor contains a store to the same location.
970 // if so, insert a PHI node (if needed) and move the stores down.
971 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000972
Chris Lattnera65e2f72010-01-05 05:57:49 +0000973 // Determine whether Dest has exactly two predecessors and, if so, compute
974 // the other predecessor.
975 pred_iterator PI = pred_begin(DestBB);
Gabor Greif1b787df2010-07-12 15:48:26 +0000976 BasicBlock *P = *PI;
Craig Topperf40110f2014-04-25 05:29:35 +0000977 BasicBlock *OtherBB = nullptr;
Gabor Greif1b787df2010-07-12 15:48:26 +0000978
979 if (P != StoreBB)
980 OtherBB = P;
981
982 if (++PI == pred_end(DestBB))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000983 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000984
Gabor Greif1b787df2010-07-12 15:48:26 +0000985 P = *PI;
986 if (P != StoreBB) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000987 if (OtherBB)
988 return false;
Gabor Greif1b787df2010-07-12 15:48:26 +0000989 OtherBB = P;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000990 }
991 if (++PI != pred_end(DestBB))
992 return false;
993
994 // Bail out if all the relevant blocks aren't distinct (this can happen,
995 // for example, if SI is in an infinite loop)
996 if (StoreBB == DestBB || OtherBB == DestBB)
997 return false;
998
999 // Verify that the other block ends in a branch and is not otherwise empty.
1000 BasicBlock::iterator BBI = OtherBB->getTerminator();
1001 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
1002 if (!OtherBr || BBI == OtherBB->begin())
1003 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001004
Chris Lattnera65e2f72010-01-05 05:57:49 +00001005 // If the other block ends in an unconditional branch, check for the 'if then
1006 // else' case. there is an instruction before the branch.
Craig Topperf40110f2014-04-25 05:29:35 +00001007 StoreInst *OtherStore = nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001008 if (OtherBr->isUnconditional()) {
1009 --BBI;
1010 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001011 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001012 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001013 if (BBI==OtherBB->begin())
1014 return false;
1015 --BBI;
1016 }
Eli Friedman8bc586e2011-08-15 22:09:40 +00001017 // If this isn't a store, isn't a store to the same location, or is not the
1018 // right kind of store, bail out.
Chris Lattnera65e2f72010-01-05 05:57:49 +00001019 OtherStore = dyn_cast<StoreInst>(BBI);
1020 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +00001021 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001022 return false;
1023 } else {
1024 // Otherwise, the other block ended with a conditional branch. If one of the
1025 // destinations is StoreBB, then we have the if/then case.
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001026 if (OtherBr->getSuccessor(0) != StoreBB &&
Chris Lattnera65e2f72010-01-05 05:57:49 +00001027 OtherBr->getSuccessor(1) != StoreBB)
1028 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001029
Chris Lattnera65e2f72010-01-05 05:57:49 +00001030 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
1031 // if/then triangle. See if there is a store to the same ptr as SI that
1032 // lives in OtherBB.
1033 for (;; --BBI) {
1034 // Check to see if we find the matching store.
1035 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
1036 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +00001037 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001038 return false;
1039 break;
1040 }
1041 // If we find something that may be using or overwriting the stored
1042 // value, or if we run out of instructions, we can't do the xform.
1043 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
1044 BBI == OtherBB->begin())
1045 return false;
1046 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001047
Chris Lattnera65e2f72010-01-05 05:57:49 +00001048 // In order to eliminate the store in OtherBr, we have to
1049 // make sure nothing reads or overwrites the stored value in
1050 // StoreBB.
1051 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1052 // FIXME: This should really be AA driven.
1053 if (I->mayReadFromMemory() || I->mayWriteToMemory())
1054 return false;
1055 }
1056 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001057
Chris Lattnera65e2f72010-01-05 05:57:49 +00001058 // Insert a PHI node now if we need it.
1059 Value *MergedVal = OtherStore->getOperand(0);
1060 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +00001061 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +00001062 PN->addIncoming(SI.getOperand(0), SI.getParent());
1063 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
1064 MergedVal = InsertNewInstBefore(PN, DestBB->front());
1065 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001066
Chris Lattnera65e2f72010-01-05 05:57:49 +00001067 // Advance to a place where it is safe to insert the new store and
1068 // insert it.
Bill Wendling8ddfc092011-08-16 20:45:24 +00001069 BBI = DestBB->getFirstInsertionPt();
Eli Friedman35211c62011-05-27 00:19:40 +00001070 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +00001071 SI.isVolatile(),
1072 SI.getAlignment(),
1073 SI.getOrdering(),
1074 SI.getSynchScope());
Eli Friedman35211c62011-05-27 00:19:40 +00001075 InsertNewInstBefore(NewSI, *BBI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001076 NewSI->setDebugLoc(OtherStore->getDebugLoc());
Eli Friedman35211c62011-05-27 00:19:40 +00001077
Hal Finkelcc39b672014-07-24 12:16:19 +00001078 // If the two stores had AA tags, merge them.
1079 AAMDNodes AATags;
1080 SI.getAAMetadata(AATags);
1081 if (AATags) {
1082 OtherStore->getAAMetadata(AATags, /* Merge = */ true);
1083 NewSI->setAAMetadata(AATags);
1084 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001085
Chris Lattnera65e2f72010-01-05 05:57:49 +00001086 // Nuke the old stores.
1087 EraseInstFromFunction(SI);
1088 EraseInstFromFunction(*OtherStore);
1089 return true;
1090}