blob: 675553017838baecac202e4f0426404aba9deba0 [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"
Yaxun Liuba01ed02017-02-10 21:46:07 +000015#include "llvm/ADT/MapVector.h"
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +000016#include "llvm/ADT/SmallString.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/Statistic.h"
Dan Gohman826bdf82010-05-28 16:19:17 +000018#include "llvm/Analysis/Loads.h"
Peter Collingbourneecdd58f2016-10-21 19:59:26 +000019#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/DataLayout.h"
Paul Robinson383c5c22017-02-06 22:19:04 +000021#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/IntrinsicInst.h"
Yaxun Liuba01ed02017-02-10 21:46:07 +000023#include "llvm/IR/LLVMContext.h"
Charles Davis33d1dc02015-02-25 05:10:25 +000024#include "llvm/IR/MDBuilder.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000025#include "llvm/Transforms/Utils/BasicBlockUtils.h"
26#include "llvm/Transforms/Utils/Local.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000027using namespace llvm;
28
Chandler Carruth964daaa2014-04-22 02:55:47 +000029#define DEBUG_TYPE "instcombine"
30
Chandler Carruthc908ca12012-08-21 08:39:44 +000031STATISTIC(NumDeadStore, "Number of dead stores eliminated");
32STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
33
34/// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
35/// some part of a constant global variable. This intentionally only accepts
36/// constant expressions because we can't rewrite arbitrary instructions.
37static bool pointsToConstantGlobal(Value *V) {
38 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
39 return GV->isConstant();
Matt Arsenault607281772014-04-24 00:01:09 +000040
41 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000042 if (CE->getOpcode() == Instruction::BitCast ||
Matt Arsenault607281772014-04-24 00:01:09 +000043 CE->getOpcode() == Instruction::AddrSpaceCast ||
Chandler Carruthc908ca12012-08-21 08:39:44 +000044 CE->getOpcode() == Instruction::GetElementPtr)
45 return pointsToConstantGlobal(CE->getOperand(0));
Matt Arsenault607281772014-04-24 00:01:09 +000046 }
Chandler Carruthc908ca12012-08-21 08:39:44 +000047 return false;
48}
49
50/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
51/// pointer to an alloca. Ignore any reads of the pointer, return false if we
52/// see any stores or other unknown uses. If we see pointer arithmetic, keep
53/// track of whether it moves the pointer (with IsOffset) but otherwise traverse
54/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
55/// the alloca, and if the source pointer is a pointer to a constant global, we
56/// can optimize this.
57static bool
58isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Reid Kleckner813dab22014-07-01 21:36:20 +000059 SmallVectorImpl<Instruction *> &ToDelete) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000060 // We track lifetime intrinsics as we encounter them. If we decide to go
61 // ahead and replace the value with the global, this lets the caller quickly
62 // eliminate the markers.
63
Reid Kleckner813dab22014-07-01 21:36:20 +000064 SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect;
David Majnemer0a16c222016-08-11 21:15:00 +000065 ValuesToInspect.emplace_back(V, false);
Reid Kleckner813dab22014-07-01 21:36:20 +000066 while (!ValuesToInspect.empty()) {
67 auto ValuePair = ValuesToInspect.pop_back_val();
68 const bool IsOffset = ValuePair.second;
69 for (auto &U : ValuePair.first->uses()) {
David Majnemer0a16c222016-08-11 21:15:00 +000070 auto *I = cast<Instruction>(U.getUser());
Chandler Carruthc908ca12012-08-21 08:39:44 +000071
David Majnemer0a16c222016-08-11 21:15:00 +000072 if (auto *LI = dyn_cast<LoadInst>(I)) {
Reid Kleckner813dab22014-07-01 21:36:20 +000073 // Ignore non-volatile loads, they are always ok.
74 if (!LI->isSimple()) return false;
Chandler Carruthc908ca12012-08-21 08:39:44 +000075 continue;
76 }
Reid Kleckner813dab22014-07-01 21:36:20 +000077
78 if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) {
79 // If uses of the bitcast are ok, we are ok.
David Majnemer0a16c222016-08-11 21:15:00 +000080 ValuesToInspect.emplace_back(I, IsOffset);
Reid Kleckner813dab22014-07-01 21:36:20 +000081 continue;
82 }
David Majnemer0a16c222016-08-11 21:15:00 +000083 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
Reid Kleckner813dab22014-07-01 21:36:20 +000084 // If the GEP has all zero indices, it doesn't offset the pointer. If it
85 // doesn't, it does.
David Majnemer0a16c222016-08-11 21:15:00 +000086 ValuesToInspect.emplace_back(I, IsOffset || !GEP->hasAllZeroIndices());
Reid Kleckner813dab22014-07-01 21:36:20 +000087 continue;
88 }
89
Benjamin Kramer3a09ef62015-04-10 14:50:08 +000090 if (auto CS = CallSite(I)) {
Reid Kleckner813dab22014-07-01 21:36:20 +000091 // If this is the function being called then we treat it like a load and
92 // ignore it.
93 if (CS.isCallee(&U))
94 continue;
95
David Majnemer02f47872015-12-23 09:58:41 +000096 unsigned DataOpNo = CS.getDataOperandNo(&U);
97 bool IsArgOperand = CS.isArgOperand(&U);
98
Reid Kleckner813dab22014-07-01 21:36:20 +000099 // Inalloca arguments are clobbered by the call.
David Majnemer02f47872015-12-23 09:58:41 +0000100 if (IsArgOperand && CS.isInAllocaArgument(DataOpNo))
Reid Kleckner813dab22014-07-01 21:36:20 +0000101 return false;
102
103 // If this is a readonly/readnone call site, then we know it is just a
104 // load (but one that potentially returns the value itself), so we can
105 // ignore it if we know that the value isn't captured.
106 if (CS.onlyReadsMemory() &&
David Majnemer02f47872015-12-23 09:58:41 +0000107 (CS.getInstruction()->use_empty() || CS.doesNotCapture(DataOpNo)))
Reid Kleckner813dab22014-07-01 21:36:20 +0000108 continue;
109
110 // If this is being passed as a byval argument, the caller is making a
111 // copy, so it is only a read of the alloca.
David Majnemer02f47872015-12-23 09:58:41 +0000112 if (IsArgOperand && CS.isByValArgument(DataOpNo))
Reid Kleckner813dab22014-07-01 21:36:20 +0000113 continue;
114 }
115
116 // Lifetime intrinsics can be handled by the caller.
117 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
118 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
119 II->getIntrinsicID() == Intrinsic::lifetime_end) {
120 assert(II->use_empty() && "Lifetime markers have no result to use!");
121 ToDelete.push_back(II);
122 continue;
123 }
124 }
125
126 // If this is isn't our memcpy/memmove, reject it as something we can't
127 // handle.
128 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
129 if (!MI)
130 return false;
131
132 // If the transfer is using the alloca as a source of the transfer, then
133 // ignore it since it is a load (unless the transfer is volatile).
134 if (U.getOperandNo() == 1) {
135 if (MI->isVolatile()) return false;
136 continue;
137 }
138
139 // If we already have seen a copy, reject the second one.
140 if (TheCopy) return false;
141
142 // If the pointer has been offset from the start of the alloca, we can't
143 // safely handle this.
144 if (IsOffset) return false;
145
146 // If the memintrinsic isn't using the alloca as the dest, reject it.
147 if (U.getOperandNo() != 0) return false;
148
149 // If the source of the memcpy/move is not a constant global, reject it.
150 if (!pointsToConstantGlobal(MI->getSource()))
151 return false;
152
153 // Otherwise, the transform is safe. Remember the copy instruction.
154 TheCopy = MI;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000155 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000156 }
157 return true;
158}
159
160/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
161/// modified by a copy from a constant global. If we can prove this, we can
162/// replace any uses of the alloca with uses of the global directly.
163static MemTransferInst *
164isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
165 SmallVectorImpl<Instruction *> &ToDelete) {
Craig Topperf40110f2014-04-25 05:29:35 +0000166 MemTransferInst *TheCopy = nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000167 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
168 return TheCopy;
Craig Topperf40110f2014-04-25 05:29:35 +0000169 return nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000170}
171
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000172static Instruction *simplifyAllocaArraySize(InstCombiner &IC, AllocaInst &AI) {
Duncan P. N. Exon Smith720762e2015-03-13 19:30:44 +0000173 // Check for array size of 1 (scalar allocation).
Duncan P. N. Exon Smithbe95b4a2015-03-13 19:42:09 +0000174 if (!AI.isArrayAllocation()) {
175 // i32 1 is the canonical array size for scalar allocations.
176 if (AI.getArraySize()->getType()->isIntegerTy(32))
177 return nullptr;
178
179 // Canonicalize it.
180 Value *V = IC.Builder->getInt32(1);
181 AI.setOperand(0, V);
182 return &AI;
183 }
Duncan P. N. Exon Smith720762e2015-03-13 19:30:44 +0000184
Chris Lattnera65e2f72010-01-05 05:57:49 +0000185 // 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 +0000186 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
187 Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
188 AllocaInst *New = IC.Builder->CreateAlloca(NewTy, nullptr, AI.getName());
189 New->setAlignment(AI.getAlignment());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000190
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000191 // Scan to the end of the allocation instructions, to skip over a block of
192 // allocas if possible...also skip interleaved debug info
193 //
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000194 BasicBlock::iterator It(New);
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000195 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
196 ++It;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000197
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000198 // Now that I is pointing to the first non-allocation-inst in the block,
199 // insert our getelementptr instruction...
200 //
201 Type *IdxTy = IC.getDataLayout().getIntPtrType(AI.getType());
202 Value *NullIdx = Constant::getNullValue(IdxTy);
203 Value *Idx[2] = {NullIdx, NullIdx};
204 Instruction *GEP =
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000205 GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000206 IC.InsertNewInstBefore(GEP, *It);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000207
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000208 // Now make everything use the getelementptr instead of the original
209 // allocation.
Sanjay Patel4b198802016-02-01 22:23:39 +0000210 return IC.replaceInstUsesWith(AI, GEP);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000211 }
212
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000213 if (isa<UndefValue>(AI.getArraySize()))
Sanjay Patel4b198802016-02-01 22:23:39 +0000214 return IC.replaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000215
Duncan P. N. Exon Smith07ff9b02015-03-13 19:34:55 +0000216 // Ensure that the alloca array size argument has type intptr_t, so that
217 // any casting is exposed early.
218 Type *IntPtrTy = IC.getDataLayout().getIntPtrType(AI.getType());
219 if (AI.getArraySize()->getType() != IntPtrTy) {
220 Value *V = IC.Builder->CreateIntCast(AI.getArraySize(), IntPtrTy, false);
221 AI.setOperand(0, V);
222 return &AI;
223 }
224
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000225 return nullptr;
226}
227
Benjamin Kramer03ab8a32017-02-10 22:26:35 +0000228namespace {
Yaxun Liuba01ed02017-02-10 21:46:07 +0000229// If I and V are pointers in different address space, it is not allowed to
230// use replaceAllUsesWith since I and V have different types. A
231// non-target-specific transformation should not use addrspacecast on V since
232// the two address space may be disjoint depending on target.
233//
234// This class chases down uses of the old pointer until reaching the load
235// instructions, then replaces the old pointer in the load instructions with
236// the new pointer. If during the chasing it sees bitcast or GEP, it will
237// create new bitcast or GEP with the new pointer and use them in the load
238// instruction.
239class PointerReplacer {
240public:
241 PointerReplacer(InstCombiner &IC) : IC(IC) {}
242 void replacePointer(Instruction &I, Value *V);
243
244private:
245 void findLoadAndReplace(Instruction &I);
246 void replace(Instruction *I);
247 Value *getReplacement(Value *I);
248
249 SmallVector<Instruction *, 4> Path;
250 MapVector<Value *, Value *> WorkMap;
251 InstCombiner &IC;
252};
Benjamin Kramer03ab8a32017-02-10 22:26:35 +0000253} // end anonymous namespace
Yaxun Liuba01ed02017-02-10 21:46:07 +0000254
255void PointerReplacer::findLoadAndReplace(Instruction &I) {
256 for (auto U : I.users()) {
257 auto *Inst = dyn_cast<Instruction>(&*U);
258 if (!Inst)
259 return;
260 DEBUG(dbgs() << "Found pointer user: " << *U << '\n');
261 if (isa<LoadInst>(Inst)) {
262 for (auto P : Path)
263 replace(P);
264 replace(Inst);
265 } else if (isa<GetElementPtrInst>(Inst) || isa<BitCastInst>(Inst)) {
266 Path.push_back(Inst);
267 findLoadAndReplace(*Inst);
268 Path.pop_back();
269 } else {
270 return;
271 }
272 }
273}
274
275Value *PointerReplacer::getReplacement(Value *V) {
276 auto Loc = WorkMap.find(V);
277 if (Loc != WorkMap.end())
278 return Loc->second;
279 return nullptr;
280}
281
282void PointerReplacer::replace(Instruction *I) {
283 if (getReplacement(I))
284 return;
285
286 if (auto *LT = dyn_cast<LoadInst>(I)) {
287 auto *V = getReplacement(LT->getPointerOperand());
288 assert(V && "Operand not replaced");
289 auto *NewI = new LoadInst(V);
290 NewI->takeName(LT);
291 IC.InsertNewInstWith(NewI, *LT);
292 IC.replaceInstUsesWith(*LT, NewI);
293 WorkMap[LT] = NewI;
294 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
295 auto *V = getReplacement(GEP->getPointerOperand());
296 assert(V && "Operand not replaced");
297 SmallVector<Value *, 8> Indices;
298 Indices.append(GEP->idx_begin(), GEP->idx_end());
299 auto *NewI = GetElementPtrInst::Create(
300 V->getType()->getPointerElementType(), V, Indices);
301 IC.InsertNewInstWith(NewI, *GEP);
302 NewI->takeName(GEP);
303 WorkMap[GEP] = NewI;
304 } else if (auto *BC = dyn_cast<BitCastInst>(I)) {
305 auto *V = getReplacement(BC->getOperand(0));
306 assert(V && "Operand not replaced");
307 auto *NewT = PointerType::get(BC->getType()->getPointerElementType(),
308 V->getType()->getPointerAddressSpace());
309 auto *NewI = new BitCastInst(V, NewT);
310 IC.InsertNewInstWith(NewI, *BC);
311 NewI->takeName(BC);
Yaxun Liue6d1ce52017-02-24 20:27:25 +0000312 WorkMap[BC] = NewI;
Yaxun Liuba01ed02017-02-10 21:46:07 +0000313 } else {
314 llvm_unreachable("should never reach here");
315 }
316}
317
318void PointerReplacer::replacePointer(Instruction &I, Value *V) {
Benjamin Kramer684c87b2017-02-10 22:04:17 +0000319#ifndef NDEBUG
Yaxun Liuba01ed02017-02-10 21:46:07 +0000320 auto *PT = cast<PointerType>(I.getType());
321 auto *NT = cast<PointerType>(V->getType());
322 assert(PT != NT && PT->getElementType() == NT->getElementType() &&
323 "Invalid usage");
Benjamin Kramer684c87b2017-02-10 22:04:17 +0000324#endif
Yaxun Liuba01ed02017-02-10 21:46:07 +0000325 WorkMap[&I] = V;
326 findLoadAndReplace(I);
327}
328
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000329Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
330 if (auto *I = simplifyAllocaArraySize(*this, AI))
331 return I;
332
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000333 if (AI.getAllocatedType()->isSized()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000334 // If the alignment is 0 (unspecified), assign it the preferred alignment.
335 if (AI.getAlignment() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000336 AI.setAlignment(DL.getPrefTypeAlignment(AI.getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000337
338 // Move all alloca's of zero byte objects to the entry block and merge them
339 // together. Note that we only do this for alloca's, because malloc should
340 // allocate and return a unique pointer, even for a zero byte allocation.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000341 if (DL.getTypeAllocSize(AI.getAllocatedType()) == 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000342 // For a zero sized alloca there is no point in doing an array allocation.
343 // This is helpful if the array size is a complicated expression not used
344 // elsewhere.
345 if (AI.isArrayAllocation()) {
346 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
347 return &AI;
348 }
349
350 // Get the first instruction in the entry block.
351 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
352 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
353 if (FirstInst != &AI) {
354 // If the entry block doesn't start with a zero-size alloca then move
355 // this one to the start of the entry block. There is no problem with
356 // dominance as the array size was forced to a constant earlier already.
357 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
358 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000359 DL.getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000360 AI.moveBefore(FirstInst);
361 return &AI;
362 }
363
Richard Osborneb68053e2012-09-18 09:31:44 +0000364 // If the alignment of the entry block alloca is 0 (unspecified),
365 // assign it the preferred alignment.
366 if (EntryAI->getAlignment() == 0)
367 EntryAI->setAlignment(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000368 DL.getPrefTypeAlignment(EntryAI->getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000369 // Replace this zero-sized alloca with the one at the start of the entry
370 // block after ensuring that the address will be aligned enough for both
371 // types.
Richard Osborneb68053e2012-09-18 09:31:44 +0000372 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
373 AI.getAlignment());
Duncan Sands8bc764a2012-06-26 13:39:21 +0000374 EntryAI->setAlignment(MaxAlign);
375 if (AI.getType() != EntryAI->getType())
376 return new BitCastInst(EntryAI, AI.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +0000377 return replaceInstUsesWith(AI, EntryAI);
Duncan Sands8bc764a2012-06-26 13:39:21 +0000378 }
379 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000380 }
381
Eli Friedmanb14873c2012-11-26 23:04:53 +0000382 if (AI.getAlignment()) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000383 // Check to see if this allocation is only modified by a memcpy/memmove from
384 // a constant global whose alignment is equal to or exceeds that of the
385 // allocation. If this is the case, we can change all users to use
386 // the constant global instead. This is commonly produced by the CFE by
387 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
388 // is only subsequently read.
389 SmallVector<Instruction *, 4> ToDelete;
390 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000391 unsigned SourceAlign = getOrEnforceKnownAlignment(
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000392 Copy->getSource(), AI.getAlignment(), DL, &AI, &AC, &DT);
Eli Friedmanb14873c2012-11-26 23:04:53 +0000393 if (AI.getAlignment() <= SourceAlign) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000394 DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
395 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
396 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
Sanjay Patel4b198802016-02-01 22:23:39 +0000397 eraseInstFromFunction(*ToDelete[i]);
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000398 Constant *TheSrc = cast<Constant>(Copy->getSource());
Yaxun Liuba01ed02017-02-10 21:46:07 +0000399 auto *SrcTy = TheSrc->getType();
400 auto *DestTy = PointerType::get(AI.getType()->getPointerElementType(),
401 SrcTy->getPointerAddressSpace());
402 Constant *Cast =
403 ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, DestTy);
404 if (AI.getType()->getPointerAddressSpace() ==
405 SrcTy->getPointerAddressSpace()) {
406 Instruction *NewI = replaceInstUsesWith(AI, Cast);
407 eraseInstFromFunction(*Copy);
408 ++NumGlobalCopies;
409 return NewI;
410 } else {
411 PointerReplacer PtrReplacer(*this);
412 PtrReplacer.replacePointer(AI, Cast);
413 ++NumGlobalCopies;
414 }
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000415 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000416 }
417 }
418
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000419 // At last, use the generic allocation site handler to aggressively remove
420 // unused allocas.
421 return visitAllocSite(AI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000422}
423
Philip Reames89e92d22016-12-01 20:17:06 +0000424// Are we allowed to form a atomic load or store of this type?
425static bool isSupportedAtomicType(Type *Ty) {
426 return Ty->isIntegerTy() || Ty->isPointerTy() || Ty->isFloatingPointTy();
427}
428
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000429/// \brief Helper to combine a load to a new type.
430///
431/// This just does the work of combining a load to a new type. It handles
432/// metadata, etc., and returns the new instruction. The \c NewTy should be the
433/// loaded *value* type. This will convert it to a pointer, cast the operand to
434/// that pointer type, load it, etc.
435///
436/// Note that this will create all of the instructions with whatever insert
437/// point the \c InstCombiner currently is using.
Mehdi Amini2668a482015-05-07 05:52:40 +0000438static LoadInst *combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy,
439 const Twine &Suffix = "") {
Philip Reames89e92d22016-12-01 20:17:06 +0000440 assert((!LI.isAtomic() || isSupportedAtomicType(NewTy)) &&
441 "can't fold an atomic load to requested type");
442
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000443 Value *Ptr = LI.getPointerOperand();
444 unsigned AS = LI.getPointerAddressSpace();
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000445 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000446 LI.getAllMetadata(MD);
447
448 LoadInst *NewLoad = IC.Builder->CreateAlignedLoad(
449 IC.Builder->CreateBitCast(Ptr, NewTy->getPointerTo(AS)),
Philip Reames6f4d0082016-05-06 22:17:01 +0000450 LI.getAlignment(), LI.isVolatile(), LI.getName() + Suffix);
451 NewLoad->setAtomic(LI.getOrdering(), LI.getSynchScope());
Charles Davis33d1dc02015-02-25 05:10:25 +0000452 MDBuilder MDB(NewLoad->getContext());
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000453 for (const auto &MDPair : MD) {
454 unsigned ID = MDPair.first;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000455 MDNode *N = MDPair.second;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000456 // Note, essentially every kind of metadata should be preserved here! This
457 // routine is supposed to clone a load instruction changing *only its type*.
458 // The only metadata it makes sense to drop is metadata which is invalidated
459 // when the pointer type changes. This should essentially never be the case
460 // in LLVM, but we explicitly switch over only known metadata to be
461 // conservatively correct. If you are adding metadata to LLVM which pertains
462 // to loads, you almost certainly want to add it here.
463 switch (ID) {
464 case LLVMContext::MD_dbg:
465 case LLVMContext::MD_tbaa:
466 case LLVMContext::MD_prof:
467 case LLVMContext::MD_fpmath:
468 case LLVMContext::MD_tbaa_struct:
469 case LLVMContext::MD_invariant_load:
470 case LLVMContext::MD_alias_scope:
471 case LLVMContext::MD_noalias:
Philip Reames5a3f5f72014-10-21 00:13:20 +0000472 case LLVMContext::MD_nontemporal:
473 case LLVMContext::MD_mem_parallel_loop_access:
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000474 // All of these directly apply.
475 NewLoad->setMetadata(ID, N);
476 break;
477
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000478 case LLVMContext::MD_nonnull:
Charles Davis33d1dc02015-02-25 05:10:25 +0000479 // This only directly applies if the new type is also a pointer.
480 if (NewTy->isPointerTy()) {
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000481 NewLoad->setMetadata(ID, N);
Charles Davis33d1dc02015-02-25 05:10:25 +0000482 break;
483 }
484 // If it's integral now, translate it to !range metadata.
485 if (NewTy->isIntegerTy()) {
486 auto *ITy = cast<IntegerType>(NewTy);
487 auto *NullInt = ConstantExpr::getPtrToInt(
488 ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
489 auto *NonNullInt =
490 ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
491 NewLoad->setMetadata(LLVMContext::MD_range,
492 MDB.createRange(NonNullInt, NullInt));
493 }
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000494 break;
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000495 case LLVMContext::MD_align:
496 case LLVMContext::MD_dereferenceable:
497 case LLVMContext::MD_dereferenceable_or_null:
498 // These only directly apply if the new type is also a pointer.
499 if (NewTy->isPointerTy())
500 NewLoad->setMetadata(ID, N);
501 break;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000502 case LLVMContext::MD_range:
503 // FIXME: It would be nice to propagate this in some way, but the type
David Majnemer80dca0c2016-10-11 01:00:45 +0000504 // conversions make it hard.
505
506 // If it's a pointer now and the range does not contain 0, make it !nonnull.
507 if (NewTy->isPointerTy()) {
508 unsigned BitWidth = IC.getDataLayout().getTypeSizeInBits(NewTy);
509 if (!getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
510 MDNode *NN = MDNode::get(LI.getContext(), None);
511 NewLoad->setMetadata(LLVMContext::MD_nonnull, NN);
512 }
513 }
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000514 break;
515 }
516 }
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000517 return NewLoad;
518}
519
Chandler Carruthfa11d832015-01-22 03:34:54 +0000520/// \brief Combine a store to a new type.
521///
522/// Returns the newly created store instruction.
523static StoreInst *combineStoreToNewValue(InstCombiner &IC, StoreInst &SI, Value *V) {
Philip Reames89e92d22016-12-01 20:17:06 +0000524 assert((!SI.isAtomic() || isSupportedAtomicType(V->getType())) &&
525 "can't fold an atomic store of requested type");
526
Chandler Carruthfa11d832015-01-22 03:34:54 +0000527 Value *Ptr = SI.getPointerOperand();
528 unsigned AS = SI.getPointerAddressSpace();
529 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
530 SI.getAllMetadata(MD);
531
532 StoreInst *NewStore = IC.Builder->CreateAlignedStore(
533 V, IC.Builder->CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
Philip Reames6f4d0082016-05-06 22:17:01 +0000534 SI.getAlignment(), SI.isVolatile());
535 NewStore->setAtomic(SI.getOrdering(), SI.getSynchScope());
Chandler Carruthfa11d832015-01-22 03:34:54 +0000536 for (const auto &MDPair : MD) {
537 unsigned ID = MDPair.first;
538 MDNode *N = MDPair.second;
539 // Note, essentially every kind of metadata should be preserved here! This
540 // routine is supposed to clone a store instruction changing *only its
541 // type*. The only metadata it makes sense to drop is metadata which is
542 // invalidated when the pointer type changes. This should essentially
543 // never be the case in LLVM, but we explicitly switch over only known
544 // metadata to be conservatively correct. If you are adding metadata to
545 // LLVM which pertains to stores, you almost certainly want to add it
546 // here.
547 switch (ID) {
548 case LLVMContext::MD_dbg:
549 case LLVMContext::MD_tbaa:
550 case LLVMContext::MD_prof:
551 case LLVMContext::MD_fpmath:
552 case LLVMContext::MD_tbaa_struct:
553 case LLVMContext::MD_alias_scope:
554 case LLVMContext::MD_noalias:
555 case LLVMContext::MD_nontemporal:
556 case LLVMContext::MD_mem_parallel_loop_access:
Chandler Carruthfa11d832015-01-22 03:34:54 +0000557 // All of these directly apply.
558 NewStore->setMetadata(ID, N);
559 break;
560
561 case LLVMContext::MD_invariant_load:
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000562 case LLVMContext::MD_nonnull:
Chandler Carruthfa11d832015-01-22 03:34:54 +0000563 case LLVMContext::MD_range:
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000564 case LLVMContext::MD_align:
565 case LLVMContext::MD_dereferenceable:
566 case LLVMContext::MD_dereferenceable_or_null:
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000567 // These don't apply for stores.
Chandler Carruthfa11d832015-01-22 03:34:54 +0000568 break;
569 }
570 }
571
572 return NewStore;
573}
574
JF Bastien3e2e69f2016-04-21 19:41:48 +0000575/// \brief Combine loads to match the type of their uses' value after looking
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000576/// through intervening bitcasts.
577///
578/// The core idea here is that if the result of a load is used in an operation,
579/// we should load the type most conducive to that operation. For example, when
580/// loading an integer and converting that immediately to a pointer, we should
581/// instead directly load a pointer.
582///
583/// However, this routine must never change the width of a load or the number of
584/// loads as that would introduce a semantic change. This combine is expected to
585/// be a semantic no-op which just allows loads to more closely model the types
586/// of their consuming operations.
587///
588/// Currently, we also refuse to change the precise type used for an atomic load
589/// or a volatile load. This is debatable, and might be reasonable to change
590/// later. However, it is risky in case some backend or other part of LLVM is
591/// relying on the exact type loaded to select appropriate atomic operations.
592static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
Philip Reames6f4d0082016-05-06 22:17:01 +0000593 // FIXME: We could probably with some care handle both volatile and ordered
594 // atomic loads here but it isn't clear that this is important.
595 if (!LI.isUnordered())
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000596 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000597
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000598 if (LI.use_empty())
599 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000600
Arnold Schwaighofer5d335552016-09-10 18:14:57 +0000601 // swifterror values can't be bitcasted.
602 if (LI.getPointerOperand()->isSwiftError())
603 return nullptr;
604
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000605 Type *Ty = LI.getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000606 const DataLayout &DL = IC.getDataLayout();
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000607
608 // Try to canonicalize loads which are only ever stored to operate over
609 // integers instead of any other type. We only do this when the loaded type
610 // is sized and has a size exactly the same as its store size and the store
611 // size is a legal integer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000612 if (!Ty->isIntegerTy() && Ty->isSized() &&
613 DL.isLegalInteger(DL.getTypeStoreSizeInBits(Ty)) &&
Sanjoy Dasba04d3a2016-08-06 02:58:48 +0000614 DL.getTypeStoreSizeInBits(Ty) == DL.getTypeSizeInBits(Ty) &&
615 !DL.isNonIntegralPointerType(Ty)) {
David Majnemer0a16c222016-08-11 21:15:00 +0000616 if (all_of(LI.users(), [&LI](User *U) {
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000617 auto *SI = dyn_cast<StoreInst>(U);
Arnold Schwaighoferc3685632017-01-31 17:53:49 +0000618 return SI && SI->getPointerOperand() != &LI &&
619 !SI->getPointerOperand()->isSwiftError();
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000620 })) {
621 LoadInst *NewLoad = combineLoadToNewType(
622 IC, LI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000623 Type::getIntNTy(LI.getContext(), DL.getTypeStoreSizeInBits(Ty)));
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000624 // Replace all the stores with stores of the newly loaded value.
625 for (auto UI = LI.user_begin(), UE = LI.user_end(); UI != UE;) {
626 auto *SI = cast<StoreInst>(*UI++);
627 IC.Builder->SetInsertPoint(SI);
628 combineStoreToNewValue(IC, *SI, NewLoad);
Sanjay Patel4b198802016-02-01 22:23:39 +0000629 IC.eraseInstFromFunction(*SI);
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000630 }
631 assert(LI.use_empty() && "Failed to remove all users of the load!");
632 // Return the old load so the combiner can delete it safely.
633 return &LI;
634 }
635 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000636
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000637 // Fold away bit casts of the loaded value by loading the desired type.
Quentin Colombet490cfbe2016-02-11 22:30:41 +0000638 // We can do this for BitCastInsts as well as casts from and to pointer types,
639 // as long as those are noops (i.e., the source or dest type have the same
640 // bitwidth as the target's pointers).
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000641 if (LI.hasOneUse())
Philip Reames89e92d22016-12-01 20:17:06 +0000642 if (auto* CI = dyn_cast<CastInst>(LI.user_back()))
643 if (CI->isNoopCast(DL))
644 if (!LI.isAtomic() || isSupportedAtomicType(CI->getDestTy())) {
645 LoadInst *NewLoad = combineLoadToNewType(IC, LI, CI->getDestTy());
646 CI->replaceAllUsesWith(NewLoad);
647 IC.eraseInstFromFunction(*CI);
648 return &LI;
649 }
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000650
Chandler Carrutha7f247e2014-12-09 19:21:16 +0000651 // FIXME: We should also canonicalize loads of vectors when their elements are
652 // cast to other types.
Craig Topperf40110f2014-04-25 05:29:35 +0000653 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000654}
655
Mehdi Amini2668a482015-05-07 05:52:40 +0000656static Instruction *unpackLoadToAggregate(InstCombiner &IC, LoadInst &LI) {
657 // FIXME: We could probably with some care handle both volatile and atomic
658 // stores here but it isn't clear that this is important.
659 if (!LI.isSimple())
660 return nullptr;
661
662 Type *T = LI.getType();
663 if (!T->isAggregateType())
664 return nullptr;
665
Benjamin Kramerc1263532016-03-11 10:20:56 +0000666 StringRef Name = LI.getName();
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000667 assert(LI.getAlignment() && "Alignment must be set at this point");
Mehdi Amini2668a482015-05-07 05:52:40 +0000668
669 if (auto *ST = dyn_cast<StructType>(T)) {
670 // If the struct only have one element, we unpack.
Amaury Sechet61a7d622016-02-17 19:21:28 +0000671 auto NumElements = ST->getNumElements();
672 if (NumElements == 1) {
Mehdi Amini2668a482015-05-07 05:52:40 +0000673 LoadInst *NewLoad = combineLoadToNewType(IC, LI, ST->getTypeAtIndex(0U),
674 ".unpack");
Sanjay Patel4b198802016-02-01 22:23:39 +0000675 return IC.replaceInstUsesWith(LI, IC.Builder->CreateInsertValue(
Amaury Sechet61a7d622016-02-17 19:21:28 +0000676 UndefValue::get(T), NewLoad, 0, Name));
Mehdi Amini2668a482015-05-07 05:52:40 +0000677 }
Mehdi Amini1c131b32015-12-15 01:44:07 +0000678
679 // We don't want to break loads with padding here as we'd loose
680 // the knowledge that padding exists for the rest of the pipeline.
681 const DataLayout &DL = IC.getDataLayout();
682 auto *SL = DL.getStructLayout(ST);
683 if (SL->hasPadding())
684 return nullptr;
685
Amaury Sechet61a7d622016-02-17 19:21:28 +0000686 auto Align = LI.getAlignment();
687 if (!Align)
688 Align = DL.getABITypeAlignment(ST);
689
Mehdi Amini1c131b32015-12-15 01:44:07 +0000690 auto *Addr = LI.getPointerOperand();
Amaury Sechet61a7d622016-02-17 19:21:28 +0000691 auto *IdxType = Type::getInt32Ty(T->getContext());
Mehdi Amini1c131b32015-12-15 01:44:07 +0000692 auto *Zero = ConstantInt::get(IdxType, 0);
Amaury Sechet61a7d622016-02-17 19:21:28 +0000693
694 Value *V = UndefValue::get(T);
695 for (unsigned i = 0; i < NumElements; i++) {
Mehdi Amini1c131b32015-12-15 01:44:07 +0000696 Value *Indices[2] = {
697 Zero,
698 ConstantInt::get(IdxType, i),
699 };
Amaury Sechetda71cb72016-02-17 21:21:29 +0000700 auto *Ptr = IC.Builder->CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices),
Benjamin Kramerc1263532016-03-11 10:20:56 +0000701 Name + ".elt");
Amaury Sechet61a7d622016-02-17 19:21:28 +0000702 auto EltAlign = MinAlign(Align, SL->getElementOffset(i));
Benjamin Kramerc1263532016-03-11 10:20:56 +0000703 auto *L = IC.Builder->CreateAlignedLoad(Ptr, EltAlign, Name + ".unpack");
Mehdi Amini1c131b32015-12-15 01:44:07 +0000704 V = IC.Builder->CreateInsertValue(V, L, i);
705 }
706
707 V->setName(Name);
Sanjay Patel4b198802016-02-01 22:23:39 +0000708 return IC.replaceInstUsesWith(LI, V);
Mehdi Amini2668a482015-05-07 05:52:40 +0000709 }
710
David Majnemer58fb0382015-05-11 05:04:22 +0000711 if (auto *AT = dyn_cast<ArrayType>(T)) {
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000712 auto *ET = AT->getElementType();
713 auto NumElements = AT->getNumElements();
714 if (NumElements == 1) {
715 LoadInst *NewLoad = combineLoadToNewType(IC, LI, ET, ".unpack");
Sanjay Patel4b198802016-02-01 22:23:39 +0000716 return IC.replaceInstUsesWith(LI, IC.Builder->CreateInsertValue(
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000717 UndefValue::get(T), NewLoad, 0, Name));
David Majnemer58fb0382015-05-11 05:04:22 +0000718 }
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000719
Davide Italianoda114122016-10-07 20:57:42 +0000720 // Bail out if the array is too large. Ideally we would like to optimize
721 // arrays of arbitrary size but this has a terrible impact on compile time.
722 // The threshold here is chosen arbitrarily, maybe needs a little bit of
723 // tuning.
Davide Italiano2133bf52017-02-07 17:56:50 +0000724 if (NumElements > IC.MaxArraySizeForCombine)
Davide Italianoda114122016-10-07 20:57:42 +0000725 return nullptr;
726
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000727 const DataLayout &DL = IC.getDataLayout();
728 auto EltSize = DL.getTypeAllocSize(ET);
729 auto Align = LI.getAlignment();
730 if (!Align)
731 Align = DL.getABITypeAlignment(T);
732
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000733 auto *Addr = LI.getPointerOperand();
734 auto *IdxType = Type::getInt64Ty(T->getContext());
735 auto *Zero = ConstantInt::get(IdxType, 0);
736
737 Value *V = UndefValue::get(T);
738 uint64_t Offset = 0;
739 for (uint64_t i = 0; i < NumElements; i++) {
740 Value *Indices[2] = {
741 Zero,
742 ConstantInt::get(IdxType, i),
743 };
744 auto *Ptr = IC.Builder->CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices),
Benjamin Kramerc1263532016-03-11 10:20:56 +0000745 Name + ".elt");
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000746 auto *L = IC.Builder->CreateAlignedLoad(Ptr, MinAlign(Align, Offset),
Benjamin Kramerc1263532016-03-11 10:20:56 +0000747 Name + ".unpack");
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000748 V = IC.Builder->CreateInsertValue(V, L, i);
749 Offset += EltSize;
750 }
751
752 V->setName(Name);
753 return IC.replaceInstUsesWith(LI, V);
David Majnemer58fb0382015-05-11 05:04:22 +0000754 }
755
Mehdi Amini2668a482015-05-07 05:52:40 +0000756 return nullptr;
757}
758
Hal Finkel847e05f2015-02-20 03:05:53 +0000759// If we can determine that all possible objects pointed to by the provided
760// pointer value are, not only dereferenceable, but also definitively less than
761// or equal to the provided maximum size, then return true. Otherwise, return
762// false (constant global values and allocas fall into this category).
763//
764// FIXME: This should probably live in ValueTracking (or similar).
765static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000766 const DataLayout &DL) {
Hal Finkel847e05f2015-02-20 03:05:53 +0000767 SmallPtrSet<Value *, 4> Visited;
768 SmallVector<Value *, 4> Worklist(1, V);
769
770 do {
771 Value *P = Worklist.pop_back_val();
772 P = P->stripPointerCasts();
773
774 if (!Visited.insert(P).second)
775 continue;
776
777 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
778 Worklist.push_back(SI->getTrueValue());
779 Worklist.push_back(SI->getFalseValue());
780 continue;
781 }
782
783 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000784 for (Value *IncValue : PN->incoming_values())
785 Worklist.push_back(IncValue);
Hal Finkel847e05f2015-02-20 03:05:53 +0000786 continue;
787 }
788
789 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
Sanjoy Das99042472016-04-17 04:30:43 +0000790 if (GA->isInterposable())
Hal Finkel847e05f2015-02-20 03:05:53 +0000791 return false;
792 Worklist.push_back(GA->getAliasee());
793 continue;
794 }
795
796 // If we know how big this object is, and it is less than MaxSize, continue
797 // searching. Otherwise, return false.
798 if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
799 if (!AI->getAllocatedType()->isSized())
800 return false;
801
802 ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
803 if (!CS)
804 return false;
805
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000806 uint64_t TypeSize = DL.getTypeAllocSize(AI->getAllocatedType());
Hal Finkel847e05f2015-02-20 03:05:53 +0000807 // Make sure that, even if the multiplication below would wrap as an
808 // uint64_t, we still do the right thing.
809 if ((CS->getValue().zextOrSelf(128)*APInt(128, TypeSize)).ugt(MaxSize))
810 return false;
811 continue;
812 }
813
814 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
815 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
816 return false;
817
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000818 uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType());
Hal Finkel847e05f2015-02-20 03:05:53 +0000819 if (InitSize > MaxSize)
820 return false;
821 continue;
822 }
823
824 return false;
825 } while (!Worklist.empty());
826
827 return true;
828}
829
830// If we're indexing into an object of a known size, and the outer index is
831// not a constant, but having any value but zero would lead to undefined
832// behavior, replace it with zero.
833//
834// For example, if we have:
835// @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
836// ...
837// %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x
838// ... = load i32* %arrayidx, align 4
839// Then we know that we can replace %x in the GEP with i64 0.
840//
841// FIXME: We could fold any GEP index to zero that would cause UB if it were
842// not zero. Currently, we only handle the first such index. Also, we could
843// also search through non-zero constant indices if we kept track of the
844// offsets those indices implied.
845static bool canReplaceGEPIdxWithZero(InstCombiner &IC, GetElementPtrInst *GEPI,
846 Instruction *MemI, unsigned &Idx) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000847 if (GEPI->getNumOperands() < 2)
Hal Finkel847e05f2015-02-20 03:05:53 +0000848 return false;
849
850 // Find the first non-zero index of a GEP. If all indices are zero, return
851 // one past the last index.
852 auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
853 unsigned I = 1;
854 for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
855 Value *V = GEPI->getOperand(I);
856 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
857 if (CI->isZero())
858 continue;
859
860 break;
861 }
862
863 return I;
864 };
865
866 // Skip through initial 'zero' indices, and find the corresponding pointer
867 // type. See if the next index is not a constant.
868 Idx = FirstNZIdx(GEPI);
869 if (Idx == GEPI->getNumOperands())
870 return false;
871 if (isa<Constant>(GEPI->getOperand(Idx)))
872 return false;
873
874 SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
Eduard Burtescu19eb0312016-01-19 17:28:00 +0000875 Type *AllocTy =
876 GetElementPtrInst::getIndexedType(GEPI->getSourceElementType(), Ops);
Hal Finkel847e05f2015-02-20 03:05:53 +0000877 if (!AllocTy || !AllocTy->isSized())
878 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000879 const DataLayout &DL = IC.getDataLayout();
880 uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy);
Hal Finkel847e05f2015-02-20 03:05:53 +0000881
882 // If there are more indices after the one we might replace with a zero, make
883 // sure they're all non-negative. If any of them are negative, the overall
884 // address being computed might be before the base address determined by the
885 // first non-zero index.
886 auto IsAllNonNegative = [&]() {
887 for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
888 bool KnownNonNegative, KnownNegative;
889 IC.ComputeSignBit(GEPI->getOperand(i), KnownNonNegative,
890 KnownNegative, 0, MemI);
891 if (KnownNonNegative)
892 continue;
893 return false;
894 }
895
896 return true;
897 };
898
899 // FIXME: If the GEP is not inbounds, and there are extra indices after the
900 // one we'll replace, those could cause the address computation to wrap
901 // (rendering the IsAllNonNegative() check below insufficient). We can do
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000902 // better, ignoring zero indices (and other indices we can prove small
Hal Finkel847e05f2015-02-20 03:05:53 +0000903 // enough not to wrap).
904 if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
905 return false;
906
907 // Note that isObjectSizeLessThanOrEq will return true only if the pointer is
908 // also known to be dereferenceable.
909 return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
910 IsAllNonNegative();
911}
912
913// If we're indexing into an object with a variable index for the memory
914// access, but the object has only one element, we can assume that the index
915// will always be zero. If we replace the GEP, return it.
916template <typename T>
917static Instruction *replaceGEPIdxWithZero(InstCombiner &IC, Value *Ptr,
918 T &MemI) {
919 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
920 unsigned Idx;
921 if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
922 Instruction *NewGEPI = GEPI->clone();
923 NewGEPI->setOperand(Idx,
924 ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
925 NewGEPI->insertBefore(GEPI);
926 MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI);
927 return NewGEPI;
928 }
929 }
930
931 return nullptr;
932}
933
Davide Italianoffcb4df2017-04-19 17:26:57 +0000934static bool canSimplifyNullLoadOrGEP(LoadInst &LI, Value *Op) {
935 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
936 const Value *GEPI0 = GEPI->getOperand(0);
937 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0)
938 return true;
939 }
940 if (isa<UndefValue>(Op) ||
941 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0))
942 return true;
943 return false;
944}
945
Chris Lattnera65e2f72010-01-05 05:57:49 +0000946Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
947 Value *Op = LI.getOperand(0);
948
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000949 // Try to canonicalize the loaded type.
950 if (Instruction *Res = combineLoadToOperationType(*this, LI))
951 return Res;
952
Chris Lattnera65e2f72010-01-05 05:57:49 +0000953 // Attempt to improve the alignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000954 unsigned KnownAlign = getOrEnforceKnownAlignment(
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000955 Op, DL.getPrefTypeAlignment(LI.getType()), DL, &LI, &AC, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000956 unsigned LoadAlign = LI.getAlignment();
957 unsigned EffectiveLoadAlign =
958 LoadAlign != 0 ? LoadAlign : DL.getABITypeAlignment(LI.getType());
Dan Gohman36196602010-08-03 18:20:32 +0000959
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000960 if (KnownAlign > EffectiveLoadAlign)
961 LI.setAlignment(KnownAlign);
962 else if (LoadAlign == 0)
963 LI.setAlignment(EffectiveLoadAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000964
Hal Finkel847e05f2015-02-20 03:05:53 +0000965 // Replace GEP indices if possible.
966 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) {
967 Worklist.Add(NewGEPI);
968 return &LI;
969 }
970
Mehdi Amini2668a482015-05-07 05:52:40 +0000971 if (Instruction *Res = unpackLoadToAggregate(*this, LI))
972 return Res;
973
Chris Lattnera65e2f72010-01-05 05:57:49 +0000974 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +0000975 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +0000976 // separated by a few arithmetic operations.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000977 BasicBlock::iterator BBI(LI);
Eli Friedmanbd254a62016-06-16 02:33:42 +0000978 bool IsLoadCSE = false;
Sanjay Patelb38ad88e2017-01-02 23:25:28 +0000979 if (Value *AvailableVal = FindAvailableLoadedValue(
980 &LI, LI.getParent(), BBI, DefMaxInstsToScan, AA, &IsLoadCSE)) {
981 if (IsLoadCSE)
982 combineMetadataForCSE(cast<LoadInst>(AvailableVal), &LI);
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000983
Sanjay Patel4b198802016-02-01 22:23:39 +0000984 return replaceInstUsesWith(
Chandler Carruth1a3c2c42014-11-25 08:20:27 +0000985 LI, Builder->CreateBitOrPointerCast(AvailableVal, LI.getType(),
986 LI.getName() + ".cast"));
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000987 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000988
Philip Reames3ac07182016-04-21 17:45:05 +0000989 // None of the following transforms are legal for volatile/ordered atomic
990 // loads. Most of them do apply for unordered atomics.
991 if (!LI.isUnordered()) return nullptr;
Philip Reamesac550902016-04-21 17:03:33 +0000992
Chris Lattnera65e2f72010-01-05 05:57:49 +0000993 // load(gep null, ...) -> unreachable
Chris Lattnera65e2f72010-01-05 05:57:49 +0000994 // load null/undef -> unreachable
Davide Italianoffcb4df2017-04-19 17:26:57 +0000995 // TODO: Consider a target hook for valid address spaces for this xforms.
996 if (canSimplifyNullLoadOrGEP(LI, Op)) {
997 // Insert a new store to null instruction before the load to indicate
998 // that this code is not reachable. We do this instead of inserting
999 // an unreachable instruction directly because we cannot modify the
1000 // CFG.
Chris Lattnera65e2f72010-01-05 05:57:49 +00001001 new StoreInst(UndefValue::get(LI.getType()),
1002 Constant::getNullValue(Op->getType()), &LI);
Sanjay Patel4b198802016-02-01 22:23:39 +00001003 return replaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnera65e2f72010-01-05 05:57:49 +00001004 }
1005
Chris Lattnera65e2f72010-01-05 05:57:49 +00001006 if (Op->hasOneUse()) {
1007 // Change select and PHI nodes to select values instead of addresses: this
1008 // helps alias analysis out a lot, allows many others simplifications, and
1009 // exposes redundancy in the code.
1010 //
1011 // Note that we cannot do the transformation unless we know that the
1012 // introduced loads cannot trap! Something like this is valid as long as
1013 // the condition is always false: load (select bool %C, int* null, int* %G),
1014 // but it would not be valid if we transformed it to load from null
1015 // unconditionally.
1016 //
1017 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
1018 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +00001019 unsigned Align = LI.getAlignment();
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001020 if (isSafeToLoadUnconditionally(SI->getOperand(1), Align, DL, SI) &&
1021 isSafeToLoadUnconditionally(SI->getOperand(2), Align, DL, SI)) {
Bob Wilson4b71b6c2010-01-30 00:41:10 +00001022 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
Bob Wilson56600a12010-01-30 04:42:39 +00001023 SI->getOperand(1)->getName()+".val");
Bob Wilson4b71b6c2010-01-30 00:41:10 +00001024 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
Bob Wilson56600a12010-01-30 04:42:39 +00001025 SI->getOperand(2)->getName()+".val");
Philip Reamesa98c7ea2016-04-21 17:59:40 +00001026 assert(LI.isUnordered() && "implied by above");
Bob Wilson56600a12010-01-30 04:42:39 +00001027 V1->setAlignment(Align);
Philip Reamesa98c7ea2016-04-21 17:59:40 +00001028 V1->setAtomic(LI.getOrdering(), LI.getSynchScope());
Bob Wilson56600a12010-01-30 04:42:39 +00001029 V2->setAlignment(Align);
Philip Reamesa98c7ea2016-04-21 17:59:40 +00001030 V2->setAtomic(LI.getOrdering(), LI.getSynchScope());
Chris Lattnera65e2f72010-01-05 05:57:49 +00001031 return SelectInst::Create(SI->getCondition(), V1, V2);
1032 }
1033
1034 // load (select (cond, null, P)) -> load P
Larisse Voufo532bf712015-09-18 19:14:35 +00001035 if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
Philip Reames5ad26c32014-12-29 22:46:21 +00001036 LI.getPointerAddressSpace() == 0) {
1037 LI.setOperand(0, SI->getOperand(2));
1038 return &LI;
1039 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001040
1041 // load (select (cond, P, null)) -> load P
Philip Reames5ad26c32014-12-29 22:46:21 +00001042 if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
1043 LI.getPointerAddressSpace() == 0) {
1044 LI.setOperand(0, SI->getOperand(1));
1045 return &LI;
1046 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001047 }
1048 }
Craig Topperf40110f2014-04-25 05:29:35 +00001049 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001050}
1051
Arch D. Robisonbe0490a2016-04-25 22:22:39 +00001052/// \brief Look for extractelement/insertvalue sequence that acts like a bitcast.
1053///
1054/// \returns underlying value that was "cast", or nullptr otherwise.
1055///
1056/// For example, if we have:
1057///
1058/// %E0 = extractelement <2 x double> %U, i32 0
1059/// %V0 = insertvalue [2 x double] undef, double %E0, 0
1060/// %E1 = extractelement <2 x double> %U, i32 1
1061/// %V1 = insertvalue [2 x double] %V0, double %E1, 1
1062///
1063/// and the layout of a <2 x double> is isomorphic to a [2 x double],
1064/// then %V1 can be safely approximated by a conceptual "bitcast" of %U.
1065/// Note that %U may contain non-undef values where %V1 has undef.
1066static Value *likeBitCastFromVector(InstCombiner &IC, Value *V) {
1067 Value *U = nullptr;
1068 while (auto *IV = dyn_cast<InsertValueInst>(V)) {
1069 auto *E = dyn_cast<ExtractElementInst>(IV->getInsertedValueOperand());
1070 if (!E)
1071 return nullptr;
1072 auto *W = E->getVectorOperand();
1073 if (!U)
1074 U = W;
1075 else if (U != W)
1076 return nullptr;
1077 auto *CI = dyn_cast<ConstantInt>(E->getIndexOperand());
1078 if (!CI || IV->getNumIndices() != 1 || CI->getZExtValue() != *IV->idx_begin())
1079 return nullptr;
1080 V = IV->getAggregateOperand();
1081 }
1082 if (!isa<UndefValue>(V) ||!U)
1083 return nullptr;
1084
1085 auto *UT = cast<VectorType>(U->getType());
1086 auto *VT = V->getType();
1087 // Check that types UT and VT are bitwise isomorphic.
1088 const auto &DL = IC.getDataLayout();
1089 if (DL.getTypeStoreSizeInBits(UT) != DL.getTypeStoreSizeInBits(VT)) {
1090 return nullptr;
1091 }
1092 if (auto *AT = dyn_cast<ArrayType>(VT)) {
1093 if (AT->getNumElements() != UT->getNumElements())
1094 return nullptr;
1095 } else {
1096 auto *ST = cast<StructType>(VT);
1097 if (ST->getNumElements() != UT->getNumElements())
1098 return nullptr;
1099 for (const auto *EltT : ST->elements()) {
1100 if (EltT != UT->getElementType())
1101 return nullptr;
1102 }
1103 }
1104 return U;
1105}
1106
Chandler Carruth816d26f2014-11-25 10:09:51 +00001107/// \brief Combine stores to match the type of value being stored.
1108///
1109/// The core idea here is that the memory does not have any intrinsic type and
1110/// where we can we should match the type of a store to the type of value being
1111/// stored.
1112///
1113/// However, this routine must never change the width of a store or the number of
1114/// stores as that would introduce a semantic change. This combine is expected to
1115/// be a semantic no-op which just allows stores to more closely model the types
1116/// of their incoming values.
1117///
1118/// Currently, we also refuse to change the precise type used for an atomic or
1119/// volatile store. This is debatable, and might be reasonable to change later.
1120/// However, it is risky in case some backend or other part of LLVM is relying
1121/// on the exact type stored to select appropriate atomic operations.
1122///
1123/// \returns true if the store was successfully combined away. This indicates
1124/// the caller must erase the store instruction. We have to let the caller erase
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00001125/// the store instruction as otherwise there is no way to signal whether it was
Chandler Carruth816d26f2014-11-25 10:09:51 +00001126/// combined or not: IC.EraseInstFromFunction returns a null pointer.
1127static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) {
Philip Reames6f4d0082016-05-06 22:17:01 +00001128 // FIXME: We could probably with some care handle both volatile and ordered
1129 // atomic stores here but it isn't clear that this is important.
1130 if (!SI.isUnordered())
Chandler Carruth816d26f2014-11-25 10:09:51 +00001131 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001132
Arnold Schwaighofer5d335552016-09-10 18:14:57 +00001133 // swifterror values can't be bitcasted.
1134 if (SI.getPointerOperand()->isSwiftError())
1135 return false;
1136
Chandler Carruth816d26f2014-11-25 10:09:51 +00001137 Value *V = SI.getValueOperand();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001138
Chandler Carruth816d26f2014-11-25 10:09:51 +00001139 // Fold away bit casts of the stored value by storing the original type.
1140 if (auto *BC = dyn_cast<BitCastInst>(V)) {
Chandler Carrutha7f247e2014-12-09 19:21:16 +00001141 V = BC->getOperand(0);
Philip Reames89e92d22016-12-01 20:17:06 +00001142 if (!SI.isAtomic() || isSupportedAtomicType(V->getType())) {
1143 combineStoreToNewValue(IC, SI, V);
1144 return true;
1145 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001146 }
1147
Philip Reames89e92d22016-12-01 20:17:06 +00001148 if (Value *U = likeBitCastFromVector(IC, V))
1149 if (!SI.isAtomic() || isSupportedAtomicType(U->getType())) {
1150 combineStoreToNewValue(IC, SI, U);
1151 return true;
1152 }
Arch D. Robisonbe0490a2016-04-25 22:22:39 +00001153
JF Bastienc22d2992016-04-21 19:53:39 +00001154 // FIXME: We should also canonicalize stores of vectors when their elements
1155 // are cast to other types.
Chandler Carruth816d26f2014-11-25 10:09:51 +00001156 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001157}
1158
Mehdi Aminib344ac92015-03-14 22:19:33 +00001159static bool unpackStoreToAggregate(InstCombiner &IC, StoreInst &SI) {
1160 // FIXME: We could probably with some care handle both volatile and atomic
1161 // stores here but it isn't clear that this is important.
1162 if (!SI.isSimple())
1163 return false;
1164
1165 Value *V = SI.getValueOperand();
1166 Type *T = V->getType();
1167
1168 if (!T->isAggregateType())
1169 return false;
1170
Mehdi Amini2668a482015-05-07 05:52:40 +00001171 if (auto *ST = dyn_cast<StructType>(T)) {
Mehdi Aminib344ac92015-03-14 22:19:33 +00001172 // If the struct only have one element, we unpack.
Mehdi Amini1c131b32015-12-15 01:44:07 +00001173 unsigned Count = ST->getNumElements();
1174 if (Count == 1) {
Mehdi Aminib344ac92015-03-14 22:19:33 +00001175 V = IC.Builder->CreateExtractValue(V, 0);
1176 combineStoreToNewValue(IC, SI, V);
1177 return true;
1178 }
Mehdi Amini1c131b32015-12-15 01:44:07 +00001179
1180 // We don't want to break loads with padding here as we'd loose
1181 // the knowledge that padding exists for the rest of the pipeline.
1182 const DataLayout &DL = IC.getDataLayout();
1183 auto *SL = DL.getStructLayout(ST);
1184 if (SL->hasPadding())
1185 return false;
1186
Amaury Sechet61a7d622016-02-17 19:21:28 +00001187 auto Align = SI.getAlignment();
1188 if (!Align)
1189 Align = DL.getABITypeAlignment(ST);
1190
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +00001191 SmallString<16> EltName = V->getName();
1192 EltName += ".elt";
Mehdi Amini1c131b32015-12-15 01:44:07 +00001193 auto *Addr = SI.getPointerOperand();
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +00001194 SmallString<16> AddrName = Addr->getName();
1195 AddrName += ".repack";
Amaury Sechet61a7d622016-02-17 19:21:28 +00001196
Mehdi Amini1c131b32015-12-15 01:44:07 +00001197 auto *IdxType = Type::getInt32Ty(ST->getContext());
1198 auto *Zero = ConstantInt::get(IdxType, 0);
1199 for (unsigned i = 0; i < Count; i++) {
1200 Value *Indices[2] = {
1201 Zero,
1202 ConstantInt::get(IdxType, i),
1203 };
Amaury Sechetda71cb72016-02-17 21:21:29 +00001204 auto *Ptr = IC.Builder->CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices),
1205 AddrName);
Mehdi Amini1c131b32015-12-15 01:44:07 +00001206 auto *Val = IC.Builder->CreateExtractValue(V, i, EltName);
Amaury Sechet61a7d622016-02-17 19:21:28 +00001207 auto EltAlign = MinAlign(Align, SL->getElementOffset(i));
1208 IC.Builder->CreateAlignedStore(Val, Ptr, EltAlign);
Mehdi Amini1c131b32015-12-15 01:44:07 +00001209 }
1210
1211 return true;
Mehdi Aminib344ac92015-03-14 22:19:33 +00001212 }
1213
David Majnemer75364602015-05-11 05:04:27 +00001214 if (auto *AT = dyn_cast<ArrayType>(T)) {
1215 // If the array only have one element, we unpack.
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001216 auto NumElements = AT->getNumElements();
1217 if (NumElements == 1) {
David Majnemer75364602015-05-11 05:04:27 +00001218 V = IC.Builder->CreateExtractValue(V, 0);
1219 combineStoreToNewValue(IC, SI, V);
1220 return true;
1221 }
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001222
Davide Italianof6988d22016-10-07 21:53:09 +00001223 // Bail out if the array is too large. Ideally we would like to optimize
1224 // arrays of arbitrary size but this has a terrible impact on compile time.
1225 // The threshold here is chosen arbitrarily, maybe needs a little bit of
1226 // tuning.
Davide Italiano2133bf52017-02-07 17:56:50 +00001227 if (NumElements > IC.MaxArraySizeForCombine)
Davide Italianof6988d22016-10-07 21:53:09 +00001228 return false;
1229
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001230 const DataLayout &DL = IC.getDataLayout();
1231 auto EltSize = DL.getTypeAllocSize(AT->getElementType());
1232 auto Align = SI.getAlignment();
1233 if (!Align)
1234 Align = DL.getABITypeAlignment(T);
1235
1236 SmallString<16> EltName = V->getName();
1237 EltName += ".elt";
1238 auto *Addr = SI.getPointerOperand();
1239 SmallString<16> AddrName = Addr->getName();
1240 AddrName += ".repack";
1241
1242 auto *IdxType = Type::getInt64Ty(T->getContext());
1243 auto *Zero = ConstantInt::get(IdxType, 0);
1244
1245 uint64_t Offset = 0;
1246 for (uint64_t i = 0; i < NumElements; i++) {
1247 Value *Indices[2] = {
1248 Zero,
1249 ConstantInt::get(IdxType, i),
1250 };
1251 auto *Ptr = IC.Builder->CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices),
1252 AddrName);
1253 auto *Val = IC.Builder->CreateExtractValue(V, i, EltName);
1254 auto EltAlign = MinAlign(Align, Offset);
1255 IC.Builder->CreateAlignedStore(Val, Ptr, EltAlign);
1256 Offset += EltSize;
1257 }
1258
1259 return true;
David Majnemer75364602015-05-11 05:04:27 +00001260 }
1261
Mehdi Aminib344ac92015-03-14 22:19:33 +00001262 return false;
1263}
1264
Chris Lattnera65e2f72010-01-05 05:57:49 +00001265/// equivalentAddressValues - Test if A and B will obviously have the same
1266/// value. This includes recognizing that %t0 and %t1 will have the same
1267/// value in code like this:
1268/// %t0 = getelementptr \@a, 0, 3
1269/// store i32 0, i32* %t0
1270/// %t1 = getelementptr \@a, 0, 3
1271/// %t2 = load i32* %t1
1272///
1273static bool equivalentAddressValues(Value *A, Value *B) {
1274 // Test if the values are trivially equivalent.
1275 if (A == B) return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001276
Chris Lattnera65e2f72010-01-05 05:57:49 +00001277 // Test if the values come form identical arithmetic instructions.
1278 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
1279 // its only used to compare two uses within the same basic block, which
1280 // means that they'll always either have the same value or one of them
1281 // will have an undefined value.
1282 if (isa<BinaryOperator>(A) ||
1283 isa<CastInst>(A) ||
1284 isa<PHINode>(A) ||
1285 isa<GetElementPtrInst>(A))
1286 if (Instruction *BI = dyn_cast<Instruction>(B))
1287 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
1288 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001289
Chris Lattnera65e2f72010-01-05 05:57:49 +00001290 // Otherwise they may not be equivalent.
1291 return false;
1292}
1293
Chris Lattnera65e2f72010-01-05 05:57:49 +00001294Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
1295 Value *Val = SI.getOperand(0);
1296 Value *Ptr = SI.getOperand(1);
1297
Chandler Carruth816d26f2014-11-25 10:09:51 +00001298 // Try to canonicalize the stored type.
1299 if (combineStoreToValueType(*this, SI))
Sanjay Patel4b198802016-02-01 22:23:39 +00001300 return eraseInstFromFunction(SI);
Chandler Carruth816d26f2014-11-25 10:09:51 +00001301
Chris Lattnera65e2f72010-01-05 05:57:49 +00001302 // Attempt to improve the alignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001303 unsigned KnownAlign = getOrEnforceKnownAlignment(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001304 Ptr, DL.getPrefTypeAlignment(Val->getType()), DL, &SI, &AC, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001305 unsigned StoreAlign = SI.getAlignment();
1306 unsigned EffectiveStoreAlign =
1307 StoreAlign != 0 ? StoreAlign : DL.getABITypeAlignment(Val->getType());
Dan Gohman36196602010-08-03 18:20:32 +00001308
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001309 if (KnownAlign > EffectiveStoreAlign)
1310 SI.setAlignment(KnownAlign);
1311 else if (StoreAlign == 0)
1312 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001313
Mehdi Aminib344ac92015-03-14 22:19:33 +00001314 // Try to canonicalize the stored type.
1315 if (unpackStoreToAggregate(*this, SI))
Sanjay Patel4b198802016-02-01 22:23:39 +00001316 return eraseInstFromFunction(SI);
Mehdi Aminib344ac92015-03-14 22:19:33 +00001317
Hal Finkel847e05f2015-02-20 03:05:53 +00001318 // Replace GEP indices if possible.
1319 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) {
1320 Worklist.Add(NewGEPI);
1321 return &SI;
1322 }
1323
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001324 // Don't hack volatile/ordered stores.
1325 // FIXME: Some bits are legal for ordered atomic stores; needs refactoring.
1326 if (!SI.isUnordered()) return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +00001327
1328 // If the RHS is an alloca with a single use, zapify the store, making the
1329 // alloca dead.
1330 if (Ptr->hasOneUse()) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001331 if (isa<AllocaInst>(Ptr))
Sanjay Patel4b198802016-02-01 22:23:39 +00001332 return eraseInstFromFunction(SI);
Eli Friedman8bc586e2011-08-15 22:09:40 +00001333 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
1334 if (isa<AllocaInst>(GEP->getOperand(0))) {
1335 if (GEP->getOperand(0)->hasOneUse())
Sanjay Patel4b198802016-02-01 22:23:39 +00001336 return eraseInstFromFunction(SI);
Eli Friedman8bc586e2011-08-15 22:09:40 +00001337 }
1338 }
1339 }
1340
Chris Lattnera65e2f72010-01-05 05:57:49 +00001341 // Do really simple DSE, to catch cases where there are several consecutive
1342 // stores to the same location, separated by a few arithmetic operations. This
1343 // situation often occurs with bitfield accesses.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001344 BasicBlock::iterator BBI(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001345 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
1346 --ScanInsts) {
1347 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001348 // Don't count debug info directives, lest they affect codegen,
1349 // and we skip pointer-to-pointer bitcasts, which are NOPs.
1350 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001351 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001352 ScanInsts++;
1353 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001354 }
1355
Chris Lattnera65e2f72010-01-05 05:57:49 +00001356 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
1357 // Prev store isn't volatile, and stores to the same location?
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001358 if (PrevSI->isUnordered() && equivalentAddressValues(PrevSI->getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +00001359 SI.getOperand(1))) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001360 ++NumDeadStore;
1361 ++BBI;
Sanjay Patel4b198802016-02-01 22:23:39 +00001362 eraseInstFromFunction(*PrevSI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001363 continue;
1364 }
1365 break;
1366 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001367
Chris Lattnera65e2f72010-01-05 05:57:49 +00001368 // If this is a load, we have to stop. However, if the loaded value is from
1369 // the pointer we're loading and is producing the pointer we're storing,
1370 // then *this* store is dead (X = load P; store X -> P).
1371 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001372 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr)) {
1373 assert(SI.isUnordered() && "can't eliminate ordering operation");
Sanjay Patel4b198802016-02-01 22:23:39 +00001374 return eraseInstFromFunction(SI);
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001375 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001376
Chris Lattnera65e2f72010-01-05 05:57:49 +00001377 // Otherwise, this is a load from some other location. Stores before it
1378 // may not be dead.
1379 break;
1380 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001381
Sanjoy Das679bc322017-01-17 05:45:09 +00001382 // Don't skip over loads, throws or things that can modify memory.
1383 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory() || BBI->mayThrow())
Chris Lattnera65e2f72010-01-05 05:57:49 +00001384 break;
1385 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001386
1387 // store X, null -> turns into 'unreachable' in SimplifyCFG
1388 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
1389 if (!isa<UndefValue>(Val)) {
1390 SI.setOperand(0, UndefValue::get(Val->getType()));
1391 if (Instruction *U = dyn_cast<Instruction>(Val))
1392 Worklist.Add(U); // Dropped a use.
1393 }
Craig Topperf40110f2014-04-25 05:29:35 +00001394 return nullptr; // Do not modify these!
Chris Lattnera65e2f72010-01-05 05:57:49 +00001395 }
1396
1397 // store undef, Ptr -> noop
1398 if (isa<UndefValue>(Val))
Sanjay Patel4b198802016-02-01 22:23:39 +00001399 return eraseInstFromFunction(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001400
Chris Lattnera65e2f72010-01-05 05:57:49 +00001401 // If this store is the last instruction in the basic block (possibly
Victor Hernandez5f5abd52010-01-21 23:07:15 +00001402 // excepting debug info instructions), and if the block ends with an
1403 // unconditional branch, try to move it to the successor block.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001404 BBI = SI.getIterator();
Chris Lattnera65e2f72010-01-05 05:57:49 +00001405 do {
1406 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001407 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001408 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Chris Lattnera65e2f72010-01-05 05:57:49 +00001409 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
1410 if (BI->isUnconditional())
1411 if (SimplifyStoreAtEndOfBlock(SI))
Craig Topperf40110f2014-04-25 05:29:35 +00001412 return nullptr; // xform done!
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001413
Craig Topperf40110f2014-04-25 05:29:35 +00001414 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001415}
1416
1417/// SimplifyStoreAtEndOfBlock - Turn things like:
1418/// if () { *P = v1; } else { *P = v2 }
1419/// into a phi node with a store in the successor.
1420///
1421/// Simplify things like:
1422/// *P = v1; if () { *P = v2; }
1423/// into a phi node with a store in the successor.
1424///
1425bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
Philip Reames5f0e3692016-04-22 20:53:32 +00001426 assert(SI.isUnordered() &&
1427 "this code has not been auditted for volatile or ordered store case");
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001428
Chris Lattnera65e2f72010-01-05 05:57:49 +00001429 BasicBlock *StoreBB = SI.getParent();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001430
Chris Lattnera65e2f72010-01-05 05:57:49 +00001431 // Check to see if the successor block has exactly two incoming edges. If
1432 // so, see if the other predecessor contains a store to the same location.
1433 // if so, insert a PHI node (if needed) and move the stores down.
1434 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001435
Chris Lattnera65e2f72010-01-05 05:57:49 +00001436 // Determine whether Dest has exactly two predecessors and, if so, compute
1437 // the other predecessor.
1438 pred_iterator PI = pred_begin(DestBB);
Gabor Greif1b787df2010-07-12 15:48:26 +00001439 BasicBlock *P = *PI;
Craig Topperf40110f2014-04-25 05:29:35 +00001440 BasicBlock *OtherBB = nullptr;
Gabor Greif1b787df2010-07-12 15:48:26 +00001441
1442 if (P != StoreBB)
1443 OtherBB = P;
1444
1445 if (++PI == pred_end(DestBB))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001446 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001447
Gabor Greif1b787df2010-07-12 15:48:26 +00001448 P = *PI;
1449 if (P != StoreBB) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001450 if (OtherBB)
1451 return false;
Gabor Greif1b787df2010-07-12 15:48:26 +00001452 OtherBB = P;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001453 }
1454 if (++PI != pred_end(DestBB))
1455 return false;
1456
1457 // Bail out if all the relevant blocks aren't distinct (this can happen,
1458 // for example, if SI is in an infinite loop)
1459 if (StoreBB == DestBB || OtherBB == DestBB)
1460 return false;
1461
1462 // Verify that the other block ends in a branch and is not otherwise empty.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001463 BasicBlock::iterator BBI(OtherBB->getTerminator());
Chris Lattnera65e2f72010-01-05 05:57:49 +00001464 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
1465 if (!OtherBr || BBI == OtherBB->begin())
1466 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001467
Chris Lattnera65e2f72010-01-05 05:57:49 +00001468 // If the other block ends in an unconditional branch, check for the 'if then
1469 // else' case. there is an instruction before the branch.
Craig Topperf40110f2014-04-25 05:29:35 +00001470 StoreInst *OtherStore = nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001471 if (OtherBr->isUnconditional()) {
1472 --BBI;
1473 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001474 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001475 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001476 if (BBI==OtherBB->begin())
1477 return false;
1478 --BBI;
1479 }
Eli Friedman8bc586e2011-08-15 22:09:40 +00001480 // If this isn't a store, isn't a store to the same location, or is not the
1481 // right kind of store, bail out.
Chris Lattnera65e2f72010-01-05 05:57:49 +00001482 OtherStore = dyn_cast<StoreInst>(BBI);
1483 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +00001484 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001485 return false;
1486 } else {
1487 // Otherwise, the other block ended with a conditional branch. If one of the
1488 // destinations is StoreBB, then we have the if/then case.
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001489 if (OtherBr->getSuccessor(0) != StoreBB &&
Chris Lattnera65e2f72010-01-05 05:57:49 +00001490 OtherBr->getSuccessor(1) != StoreBB)
1491 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001492
Chris Lattnera65e2f72010-01-05 05:57:49 +00001493 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
1494 // if/then triangle. See if there is a store to the same ptr as SI that
1495 // lives in OtherBB.
1496 for (;; --BBI) {
1497 // Check to see if we find the matching store.
1498 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
1499 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +00001500 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001501 return false;
1502 break;
1503 }
1504 // If we find something that may be using or overwriting the stored
1505 // value, or if we run out of instructions, we can't do the xform.
Sanjoy Das679bc322017-01-17 05:45:09 +00001506 if (BBI->mayReadFromMemory() || BBI->mayThrow() ||
1507 BBI->mayWriteToMemory() || BBI == OtherBB->begin())
Chris Lattnera65e2f72010-01-05 05:57:49 +00001508 return false;
1509 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001510
Chris Lattnera65e2f72010-01-05 05:57:49 +00001511 // In order to eliminate the store in OtherBr, we have to
1512 // make sure nothing reads or overwrites the stored value in
1513 // StoreBB.
1514 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1515 // FIXME: This should really be AA driven.
Sanjoy Das679bc322017-01-17 05:45:09 +00001516 if (I->mayReadFromMemory() || I->mayThrow() || I->mayWriteToMemory())
Chris Lattnera65e2f72010-01-05 05:57:49 +00001517 return false;
1518 }
1519 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001520
Chris Lattnera65e2f72010-01-05 05:57:49 +00001521 // Insert a PHI node now if we need it.
1522 Value *MergedVal = OtherStore->getOperand(0);
1523 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +00001524 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +00001525 PN->addIncoming(SI.getOperand(0), SI.getParent());
1526 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
1527 MergedVal = InsertNewInstBefore(PN, DestBB->front());
1528 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001529
Chris Lattnera65e2f72010-01-05 05:57:49 +00001530 // Advance to a place where it is safe to insert the new store and
1531 // insert it.
Bill Wendling8ddfc092011-08-16 20:45:24 +00001532 BBI = DestBB->getFirstInsertionPt();
Eli Friedman35211c62011-05-27 00:19:40 +00001533 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +00001534 SI.isVolatile(),
1535 SI.getAlignment(),
1536 SI.getOrdering(),
1537 SI.getSynchScope());
Eli Friedman35211c62011-05-27 00:19:40 +00001538 InsertNewInstBefore(NewSI, *BBI);
Paul Robinson383c5c22017-02-06 22:19:04 +00001539 // The debug locations of the original instructions might differ; merge them.
1540 NewSI->setDebugLoc(DILocation::getMergedLocation(SI.getDebugLoc(),
1541 OtherStore->getDebugLoc()));
Eli Friedman35211c62011-05-27 00:19:40 +00001542
Hal Finkelcc39b672014-07-24 12:16:19 +00001543 // If the two stores had AA tags, merge them.
1544 AAMDNodes AATags;
1545 SI.getAAMetadata(AATags);
1546 if (AATags) {
1547 OtherStore->getAAMetadata(AATags, /* Merge = */ true);
1548 NewSI->setAAMetadata(AATags);
1549 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001550
Chris Lattnera65e2f72010-01-05 05:57:49 +00001551 // Nuke the old stores.
Sanjay Patel4b198802016-02-01 22:23:39 +00001552 eraseInstFromFunction(SI);
1553 eraseInstFromFunction(*OtherStore);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001554 return true;
1555}