blob: e3b4aea671f7145dbff9d6cc4565246b6431ed36 [file] [log] [blame]
Chris Lattnerde1fede2010-01-05 05:31:55 +00001//===- InstCombinePHI.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 visitPHINode function.
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/STLExtras.h"
16#include "llvm/ADT/SmallPtrSet.h"
Duncan Sands4581ddc2010-11-14 13:30:18 +000017#include "llvm/Analysis/InstructionSimplify.h"
Jun Bum Lim339e9722016-02-11 15:50:07 +000018#include "llvm/Analysis/ValueTracking.h"
19#include "llvm/IR/PatternMatch.h"
Akira Hatanakaf6afd112015-09-23 18:40:57 +000020#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerde1fede2010-01-05 05:31:55 +000021using namespace llvm;
Jun Bum Lim339e9722016-02-11 15:50:07 +000022using namespace llvm::PatternMatch;
Chris Lattnerde1fede2010-01-05 05:31:55 +000023
Chandler Carruth964daaa2014-04-22 02:55:47 +000024#define DEBUG_TYPE "instcombine"
25
Sanjay Patel9b7e6772015-06-23 23:05:08 +000026/// If we have something like phi [add (a,b), add(a,c)] and if a/b/c and the
27/// adds all have a single use, turn this into a phi and a single binop.
Chris Lattnerde1fede2010-01-05 05:31:55 +000028Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
29 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
30 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
31 unsigned Opc = FirstInst->getOpcode();
32 Value *LHSVal = FirstInst->getOperand(0);
33 Value *RHSVal = FirstInst->getOperand(1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +000034
Chris Lattner229907c2011-07-18 04:54:35 +000035 Type *LHSType = LHSVal->getType();
36 Type *RHSType = RHSVal->getType();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000037
Chris Lattnera8fed472011-02-17 23:01:49 +000038 bool isNUW = false, isNSW = false, isExact = false;
39 if (OverflowingBinaryOperator *BO =
40 dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
41 isNUW = BO->hasNoUnsignedWrap();
42 isNSW = BO->hasNoSignedWrap();
43 } else if (PossiblyExactOperator *PEO =
44 dyn_cast<PossiblyExactOperator>(FirstInst))
45 isExact = PEO->isExact();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000046
Chris Lattnerde1fede2010-01-05 05:31:55 +000047 // Scan to see if all operands are the same opcode, and all have one use.
48 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
49 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
50 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
51 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnera8fed472011-02-17 23:01:49 +000052 // types.
Chris Lattnerde1fede2010-01-05 05:31:55 +000053 I->getOperand(0)->getType() != LHSType ||
54 I->getOperand(1)->getType() != RHSType)
Craig Topperf40110f2014-04-25 05:29:35 +000055 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +000056
57 // If they are CmpInst instructions, check their predicates
Chris Lattnera8fed472011-02-17 23:01:49 +000058 if (CmpInst *CI = dyn_cast<CmpInst>(I))
59 if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
Craig Topperf40110f2014-04-25 05:29:35 +000060 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000061
Chris Lattnera8fed472011-02-17 23:01:49 +000062 if (isNUW)
63 isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
64 if (isNSW)
65 isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
66 if (isExact)
67 isExact = cast<PossiblyExactOperator>(I)->isExact();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000068
Chris Lattnerde1fede2010-01-05 05:31:55 +000069 // Keep track of which operand needs a phi node.
Craig Topperf40110f2014-04-25 05:29:35 +000070 if (I->getOperand(0) != LHSVal) LHSVal = nullptr;
71 if (I->getOperand(1) != RHSVal) RHSVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +000072 }
73
74 // If both LHS and RHS would need a PHI, don't do this transformation,
75 // because it would increase the number of PHIs entering the block,
76 // which leads to higher register pressure. This is especially
77 // bad when the PHIs are in the header of a loop.
78 if (!LHSVal && !RHSVal)
Craig Topperf40110f2014-04-25 05:29:35 +000079 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000080
Chris Lattnerde1fede2010-01-05 05:31:55 +000081 // Otherwise, this is safe to transform!
Jim Grosbachbdbd7342013-04-05 21:20:12 +000082
Chris Lattnerde1fede2010-01-05 05:31:55 +000083 Value *InLHS = FirstInst->getOperand(0);
84 Value *InRHS = FirstInst->getOperand(1);
Craig Topperf40110f2014-04-25 05:29:35 +000085 PHINode *NewLHS = nullptr, *NewRHS = nullptr;
86 if (!LHSVal) {
Jay Foad52131342011-03-30 11:28:46 +000087 NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +000088 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerde1fede2010-01-05 05:31:55 +000089 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
90 InsertNewInstBefore(NewLHS, PN);
91 LHSVal = NewLHS;
92 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000093
Craig Topperf40110f2014-04-25 05:29:35 +000094 if (!RHSVal) {
Jay Foad52131342011-03-30 11:28:46 +000095 NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +000096 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerde1fede2010-01-05 05:31:55 +000097 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
98 InsertNewInstBefore(NewRHS, PN);
99 RHSVal = NewRHS;
100 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000101
Chris Lattnerde1fede2010-01-05 05:31:55 +0000102 // Add all operands to the new PHIs.
103 if (NewLHS || NewRHS) {
104 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
105 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
106 if (NewLHS) {
107 Value *NewInLHS = InInst->getOperand(0);
108 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
109 }
110 if (NewRHS) {
111 Value *NewInRHS = InInst->getOperand(1);
112 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
113 }
114 }
115 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000116
Eli Friedman35211c62011-05-27 00:19:40 +0000117 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
118 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
119 LHSVal, RHSVal);
120 NewCI->setDebugLoc(FirstInst->getDebugLoc());
121 return NewCI;
122 }
123
Chris Lattnera8fed472011-02-17 23:01:49 +0000124 BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
125 BinaryOperator *NewBinOp =
126 BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
127 if (isNUW) NewBinOp->setHasNoUnsignedWrap();
128 if (isNSW) NewBinOp->setHasNoSignedWrap();
129 if (isExact) NewBinOp->setIsExact();
Eli Friedman35211c62011-05-27 00:19:40 +0000130 NewBinOp->setDebugLoc(FirstInst->getDebugLoc());
Chris Lattnera8fed472011-02-17 23:01:49 +0000131 return NewBinOp;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000132}
133
134Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
135 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000136
137 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000138 FirstInst->op_end());
139 // This is true if all GEP bases are allocas and if all indices into them are
140 // constants.
141 bool AllBasePointersAreAllocas = true;
142
143 // We don't want to replace this phi if the replacement would require
144 // more than one phi, which leads to higher register pressure. This is
145 // especially bad when the PHIs are in the header of a loop.
146 bool NeededPhi = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000147
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000148 bool AllInBounds = true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000149
Chris Lattnerde1fede2010-01-05 05:31:55 +0000150 // Scan to see if all operands are the same opcode, and all have one use.
151 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
152 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
153 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
154 GEP->getNumOperands() != FirstInst->getNumOperands())
Craig Topperf40110f2014-04-25 05:29:35 +0000155 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000156
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000157 AllInBounds &= GEP->isInBounds();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000158
Chris Lattnerde1fede2010-01-05 05:31:55 +0000159 // Keep track of whether or not all GEPs are of alloca pointers.
160 if (AllBasePointersAreAllocas &&
161 (!isa<AllocaInst>(GEP->getOperand(0)) ||
162 !GEP->hasAllConstantIndices()))
163 AllBasePointersAreAllocas = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000164
Chris Lattnerde1fede2010-01-05 05:31:55 +0000165 // Compare the operand lists.
166 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
167 if (FirstInst->getOperand(op) == GEP->getOperand(op))
168 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000169
Chris Lattnerde1fede2010-01-05 05:31:55 +0000170 // Don't merge two GEPs when two operands differ (introducing phi nodes)
171 // if one of the PHIs has a constant for the index. The index may be
172 // substantially cheaper to compute for the constants, so making it a
173 // variable index could pessimize the path. This also handles the case
174 // for struct indices, which must always be constant.
175 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
176 isa<ConstantInt>(GEP->getOperand(op)))
Craig Topperf40110f2014-04-25 05:29:35 +0000177 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000178
Chris Lattnerde1fede2010-01-05 05:31:55 +0000179 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +0000180 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000181
182 // If we already needed a PHI for an earlier operand, and another operand
183 // also requires a PHI, we'd be introducing more PHIs than we're
184 // eliminating, which increases register pressure on entry to the PHI's
185 // block.
186 if (NeededPhi)
Craig Topperf40110f2014-04-25 05:29:35 +0000187 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000188
Craig Topperf40110f2014-04-25 05:29:35 +0000189 FixedOperands[op] = nullptr; // Needs a PHI.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000190 NeededPhi = true;
191 }
192 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000193
Chris Lattnerde1fede2010-01-05 05:31:55 +0000194 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
195 // bother doing this transformation. At best, this will just save a bit of
196 // offset calculation, but all the predecessors will have to materialize the
197 // stack address into a register anyway. We'd actually rather *clone* the
198 // load up into the predecessors so that we have a load of a gep of an alloca,
199 // which can usually all be folded into the load.
200 if (AllBasePointersAreAllocas)
Craig Topperf40110f2014-04-25 05:29:35 +0000201 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000202
Chris Lattnerde1fede2010-01-05 05:31:55 +0000203 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
204 // that is variable.
205 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000206
Chris Lattnerde1fede2010-01-05 05:31:55 +0000207 bool HasAnyPHIs = false;
208 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
209 if (FixedOperands[i]) continue; // operand doesn't need a phi.
210 Value *FirstOp = FirstInst->getOperand(i);
Jay Foad52131342011-03-30 11:28:46 +0000211 PHINode *NewPN = PHINode::Create(FirstOp->getType(), e,
Chris Lattnerde1fede2010-01-05 05:31:55 +0000212 FirstOp->getName()+".pn");
213 InsertNewInstBefore(NewPN, PN);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000214
Chris Lattnerde1fede2010-01-05 05:31:55 +0000215 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
216 OperandPhis[i] = NewPN;
217 FixedOperands[i] = NewPN;
218 HasAnyPHIs = true;
219 }
220
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000221
Chris Lattnerde1fede2010-01-05 05:31:55 +0000222 // Add all operands to the new PHIs.
223 if (HasAnyPHIs) {
224 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
225 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
226 BasicBlock *InBB = PN.getIncomingBlock(i);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000227
Chris Lattnerde1fede2010-01-05 05:31:55 +0000228 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
229 if (PHINode *OpPhi = OperandPhis[op])
230 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
231 }
232 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000233
Chris Lattnerde1fede2010-01-05 05:31:55 +0000234 Value *Base = FixedOperands[0];
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000235 GetElementPtrInst *NewGEP =
David Blaikie741c8f82015-03-14 01:53:18 +0000236 GetElementPtrInst::Create(FirstInst->getSourceElementType(), Base,
237 makeArrayRef(FixedOperands).slice(1));
Chris Lattner75ae5a42011-02-17 22:32:54 +0000238 if (AllInBounds) NewGEP->setIsInBounds();
Eli Friedman35211c62011-05-27 00:19:40 +0000239 NewGEP->setDebugLoc(FirstInst->getDebugLoc());
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000240 return NewGEP;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000241}
242
243
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000244/// Return true if we know that it is safe to sink the load out of the block
245/// that defines it. This means that it must be obvious the value of the load is
246/// not changed from the point of the load to the end of the block it is in.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000247///
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000248/// Finally, it is safe, but not profitable, to sink a load targeting a
Chris Lattnerde1fede2010-01-05 05:31:55 +0000249/// non-address-taken alloca. Doing so will cause us to not promote the alloca
250/// to a register.
251static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000252 BasicBlock::iterator BBI = L->getIterator(), E = L->getParent()->end();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000253
Chris Lattnerde1fede2010-01-05 05:31:55 +0000254 for (++BBI; BBI != E; ++BBI)
255 if (BBI->mayWriteToMemory())
256 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000257
Chris Lattnerde1fede2010-01-05 05:31:55 +0000258 // Check for non-address taken alloca. If not address-taken already, it isn't
259 // profitable to do this xform.
260 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
261 bool isAddressTaken = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000262 for (User *U : AI->users()) {
Gabor Greif96fedcb2010-07-12 14:15:58 +0000263 if (isa<LoadInst>(U)) continue;
264 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000265 // If storing TO the alloca, then the address isn't taken.
266 if (SI->getOperand(1) == AI) continue;
267 }
268 isAddressTaken = true;
269 break;
270 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000271
Chris Lattnerde1fede2010-01-05 05:31:55 +0000272 if (!isAddressTaken && AI->isStaticAlloca())
273 return false;
274 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000275
Chris Lattnerde1fede2010-01-05 05:31:55 +0000276 // If this load is a load from a GEP with a constant offset from an alloca,
277 // then we don't want to sink it. In its present form, it will be
278 // load [constant stack offset]. Sinking it will cause us to have to
279 // materialize the stack addresses in each predecessor in a register only to
280 // do a shared load from register in the successor.
281 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
282 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
283 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
284 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000285
Chris Lattnerde1fede2010-01-05 05:31:55 +0000286 return true;
287}
288
289Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
290 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
Eli Friedman8bc586e2011-08-15 22:09:40 +0000291
292 // FIXME: This is overconservative; this transform is allowed in some cases
293 // for atomic operations.
294 if (FirstLI->isAtomic())
Craig Topperf40110f2014-04-25 05:29:35 +0000295 return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +0000296
Chris Lattnerde1fede2010-01-05 05:31:55 +0000297 // When processing loads, we need to propagate two bits of information to the
298 // sunk load: whether it is volatile, and what its alignment is. We currently
299 // don't sink loads when some have their alignment specified and some don't.
300 // visitLoadInst will propagate an alignment onto the load when TD is around,
301 // and if TD isn't around, we can't handle the mixed case.
302 bool isVolatile = FirstLI->isVolatile();
303 unsigned LoadAlignment = FirstLI->getAlignment();
Chris Lattnerf6befff2010-03-05 18:53:28 +0000304 unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000305
Chris Lattnerde1fede2010-01-05 05:31:55 +0000306 // We can't sink the load if the loaded value could be modified between the
307 // load and the PHI.
308 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
309 !isSafeAndProfitableToSinkLoad(FirstLI))
Craig Topperf40110f2014-04-25 05:29:35 +0000310 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000311
Chris Lattnerde1fede2010-01-05 05:31:55 +0000312 // If the PHI is of volatile loads and the load block has multiple
313 // successors, sinking it would remove a load of the volatile value from
314 // the path through the other successor.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000315 if (isVolatile &&
Chris Lattnerde1fede2010-01-05 05:31:55 +0000316 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +0000317 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000318
Chris Lattnerde1fede2010-01-05 05:31:55 +0000319 // Check to see if all arguments are the same operation.
320 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
321 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
322 if (!LI || !LI->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +0000323 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000324
325 // We can't sink the load if the loaded value could be modified between
Chris Lattnerde1fede2010-01-05 05:31:55 +0000326 // the load and the PHI.
327 if (LI->isVolatile() != isVolatile ||
328 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattnerf6befff2010-03-05 18:53:28 +0000329 LI->getPointerAddressSpace() != LoadAddrSpace ||
Chris Lattnerde1fede2010-01-05 05:31:55 +0000330 !isSafeAndProfitableToSinkLoad(LI))
Craig Topperf40110f2014-04-25 05:29:35 +0000331 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000332
Chris Lattnerde1fede2010-01-05 05:31:55 +0000333 // If some of the loads have an alignment specified but not all of them,
334 // we can't do the transformation.
335 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
Craig Topperf40110f2014-04-25 05:29:35 +0000336 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000337
Chris Lattnerde1fede2010-01-05 05:31:55 +0000338 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000339
Chris Lattnerde1fede2010-01-05 05:31:55 +0000340 // If the PHI is of volatile loads and the load block has multiple
341 // successors, sinking it would remove a load of the volatile value from
342 // the path through the other successor.
343 if (isVolatile &&
344 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +0000345 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000346 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000347
Chris Lattnerde1fede2010-01-05 05:31:55 +0000348 // Okay, they are all the same operation. Create a new PHI node of the
349 // correct type, and PHI together all of the LHS's of the instructions.
350 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
Jay Foad52131342011-03-30 11:28:46 +0000351 PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000352 PN.getName()+".in");
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000353
Chris Lattnerde1fede2010-01-05 05:31:55 +0000354 Value *InVal = FirstLI->getOperand(0);
355 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000356 LoadInst *NewLI = new LoadInst(NewPN, "", isVolatile, LoadAlignment);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000357
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000358 unsigned KnownIDs[] = {
359 LLVMContext::MD_tbaa,
360 LLVMContext::MD_range,
361 LLVMContext::MD_invariant_load,
362 LLVMContext::MD_alias_scope,
363 LLVMContext::MD_noalias,
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000364 LLVMContext::MD_nonnull,
365 LLVMContext::MD_align,
366 LLVMContext::MD_dereferenceable,
367 LLVMContext::MD_dereferenceable_or_null,
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000368 };
369
370 for (unsigned ID : KnownIDs)
371 NewLI->setMetadata(ID, FirstLI->getMetadata(ID));
372
373 // Add all operands to the new PHI and combine TBAA metadata.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000374 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000375 LoadInst *LI = cast<LoadInst>(PN.getIncomingValue(i));
376 combineMetadata(NewLI, LI, KnownIDs);
377 Value *NewInVal = LI->getOperand(0);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000378 if (NewInVal != InVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000379 InVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000380 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
381 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000382
Chris Lattnerde1fede2010-01-05 05:31:55 +0000383 if (InVal) {
384 // The new PHI unions all of the same values together. This is really
385 // common, so we handle it intelligently here for compile-time speed.
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000386 NewLI->setOperand(0, InVal);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000387 delete NewPN;
388 } else {
389 InsertNewInstBefore(NewPN, PN);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000390 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000391
Chris Lattnerde1fede2010-01-05 05:31:55 +0000392 // If this was a volatile load that we are merging, make sure to loop through
393 // and mark all the input loads as non-volatile. If we don't do this, we will
394 // insert a new volatile load and the old ones will not be deletable.
395 if (isVolatile)
Pete Cooper833f34d2015-05-12 20:05:31 +0000396 for (Value *IncValue : PN.incoming_values())
397 cast<LoadInst>(IncValue)->setVolatile(false);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000398
Eli Friedman35211c62011-05-27 00:19:40 +0000399 NewLI->setDebugLoc(FirstLI->getDebugLoc());
400 return NewLI;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000401}
402
Sanjay Patel95334072015-09-27 20:34:31 +0000403/// TODO: This function could handle other cast types, but then it might
404/// require special-casing a cast from the 'i1' type. See the comment in
405/// FoldPHIArgOpIntoPHI() about pessimizing illegal integer types.
406Instruction *InstCombiner::FoldPHIArgZextsIntoPHI(PHINode &Phi) {
David Majnemereafa28a2015-11-07 00:52:53 +0000407 // We cannot create a new instruction after the PHI if the terminator is an
408 // EHPad because there is no valid insertion point.
409 if (TerminatorInst *TI = Phi.getParent()->getTerminator())
410 if (TI->isEHPad())
411 return nullptr;
412
Sanjay Patel95334072015-09-27 20:34:31 +0000413 // Early exit for the common case of a phi with two operands. These are
414 // handled elsewhere. See the comment below where we check the count of zexts
415 // and constants for more details.
416 unsigned NumIncomingValues = Phi.getNumIncomingValues();
417 if (NumIncomingValues < 3)
418 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000419
Sanjay Patel95334072015-09-27 20:34:31 +0000420 // Find the narrower type specified by the first zext.
421 Type *NarrowType = nullptr;
422 for (Value *V : Phi.incoming_values()) {
423 if (auto *Zext = dyn_cast<ZExtInst>(V)) {
424 NarrowType = Zext->getSrcTy();
425 break;
426 }
427 }
428 if (!NarrowType)
429 return nullptr;
430
431 // Walk the phi operands checking that we only have zexts or constants that
432 // we can shrink for free. Store the new operands for the new phi.
433 SmallVector<Value *, 4> NewIncoming;
434 unsigned NumZexts = 0;
435 unsigned NumConsts = 0;
436 for (Value *V : Phi.incoming_values()) {
437 if (auto *Zext = dyn_cast<ZExtInst>(V)) {
438 // All zexts must be identical and have one use.
439 if (Zext->getSrcTy() != NarrowType || !Zext->hasOneUse())
440 return nullptr;
441 NewIncoming.push_back(Zext->getOperand(0));
442 NumZexts++;
443 } else if (auto *C = dyn_cast<Constant>(V)) {
444 // Make sure that constants can fit in the new type.
445 Constant *Trunc = ConstantExpr::getTrunc(C, NarrowType);
446 if (ConstantExpr::getZExt(Trunc, C->getType()) != C)
447 return nullptr;
448 NewIncoming.push_back(Trunc);
449 NumConsts++;
450 } else {
451 // If it's not a cast or a constant, bail out.
452 return nullptr;
453 }
454 }
455
456 // The more common cases of a phi with no constant operands or just one
457 // variable operand are handled by FoldPHIArgOpIntoPHI() and FoldOpIntoPhi()
458 // respectively. FoldOpIntoPhi() wants to do the opposite transform that is
459 // performed here. It tries to replicate a cast in the phi operand's basic
460 // block to expose other folding opportunities. Thus, InstCombine will
461 // infinite loop without this check.
462 if (NumConsts == 0 || NumZexts < 2)
463 return nullptr;
464
465 // All incoming values are zexts or constants that are safe to truncate.
466 // Create a new phi node of the narrow type, phi together all of the new
467 // operands, and zext the result back to the original type.
468 PHINode *NewPhi = PHINode::Create(NarrowType, NumIncomingValues,
469 Phi.getName() + ".shrunk");
470 for (unsigned i = 0; i != NumIncomingValues; ++i)
471 NewPhi->addIncoming(NewIncoming[i], Phi.getIncomingBlock(i));
472
473 InsertNewInstBefore(NewPhi, Phi);
474 return CastInst::CreateZExtOrBitCast(NewPhi, Phi.getType());
475}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000476
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000477/// If all operands to a PHI node are the same "unary" operator and they all are
478/// only used by the PHI, PHI together their inputs, and do the operation once,
479/// to the result of the PHI.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000480Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
David Majnemer27f24472015-11-06 23:59:23 +0000481 // We cannot create a new instruction after the PHI if the terminator is an
482 // EHPad because there is no valid insertion point.
483 if (TerminatorInst *TI = PN.getParent()->getTerminator())
484 if (TI->isEHPad())
485 return nullptr;
486
Chris Lattnerde1fede2010-01-05 05:31:55 +0000487 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
488
489 if (isa<GetElementPtrInst>(FirstInst))
490 return FoldPHIArgGEPIntoPHI(PN);
491 if (isa<LoadInst>(FirstInst))
492 return FoldPHIArgLoadIntoPHI(PN);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000493
Chris Lattnerde1fede2010-01-05 05:31:55 +0000494 // Scan the instruction, looking for input operations that can be folded away.
495 // If all input operands to the phi are the same instruction (e.g. a cast from
496 // the same type or "+42") we can pull the operation through the PHI, reducing
497 // code size and simplifying code.
Craig Topperf40110f2014-04-25 05:29:35 +0000498 Constant *ConstantOp = nullptr;
499 Type *CastSrcTy = nullptr;
Chris Lattnera8fed472011-02-17 23:01:49 +0000500 bool isNUW = false, isNSW = false, isExact = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000501
Chris Lattnerde1fede2010-01-05 05:31:55 +0000502 if (isa<CastInst>(FirstInst)) {
503 CastSrcTy = FirstInst->getOperand(0)->getType();
504
505 // Be careful about transforming integer PHIs. We don't want to pessimize
506 // the code by turning an i32 into an i1293.
Duncan Sands19d0b472010-02-16 11:11:14 +0000507 if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000508 if (!ShouldChangeType(PN.getType(), CastSrcTy))
Craig Topperf40110f2014-04-25 05:29:35 +0000509 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000510 }
511 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000512 // Can fold binop, compare or shift here if the RHS is a constant,
Chris Lattnerde1fede2010-01-05 05:31:55 +0000513 // otherwise call FoldPHIArgBinOpIntoPHI.
514 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +0000515 if (!ConstantOp)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000516 return FoldPHIArgBinOpIntoPHI(PN);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000517
Chris Lattnera8fed472011-02-17 23:01:49 +0000518 if (OverflowingBinaryOperator *BO =
519 dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
520 isNUW = BO->hasNoUnsignedWrap();
521 isNSW = BO->hasNoSignedWrap();
522 } else if (PossiblyExactOperator *PEO =
523 dyn_cast<PossiblyExactOperator>(FirstInst))
524 isExact = PEO->isExact();
Chris Lattnerde1fede2010-01-05 05:31:55 +0000525 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000526 return nullptr; // Cannot fold this operation.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000527 }
528
529 // Check to see if all arguments are the same operation.
530 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
531 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000532 if (!I || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
533 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000534 if (CastSrcTy) {
535 if (I->getOperand(0)->getType() != CastSrcTy)
Craig Topperf40110f2014-04-25 05:29:35 +0000536 return nullptr; // Cast operation must match.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000537 } else if (I->getOperand(1) != ConstantOp) {
Craig Topperf40110f2014-04-25 05:29:35 +0000538 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000539 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000540
Chris Lattnera8fed472011-02-17 23:01:49 +0000541 if (isNUW)
542 isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
543 if (isNSW)
544 isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
545 if (isExact)
546 isExact = cast<PossiblyExactOperator>(I)->isExact();
Chris Lattnerde1fede2010-01-05 05:31:55 +0000547 }
548
549 // Okay, they are all the same operation. Create a new PHI node of the
550 // correct type, and PHI together all of the LHS's of the instructions.
551 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
Jay Foad52131342011-03-30 11:28:46 +0000552 PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000553 PN.getName()+".in");
Chris Lattnerde1fede2010-01-05 05:31:55 +0000554
555 Value *InVal = FirstInst->getOperand(0);
556 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
557
558 // Add all operands to the new PHI.
559 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
560 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
561 if (NewInVal != InVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000562 InVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000563 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
564 }
565
566 Value *PhiVal;
567 if (InVal) {
568 // The new PHI unions all of the same values together. This is really
569 // common, so we handle it intelligently here for compile-time speed.
570 PhiVal = InVal;
571 delete NewPN;
572 } else {
573 InsertNewInstBefore(NewPN, PN);
574 PhiVal = NewPN;
575 }
576
577 // Insert and return the new operation.
Eli Friedman35211c62011-05-27 00:19:40 +0000578 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
579 CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
580 PN.getType());
581 NewCI->setDebugLoc(FirstInst->getDebugLoc());
582 return NewCI;
583 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000584
Chris Lattnera8fed472011-02-17 23:01:49 +0000585 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
586 BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
587 if (isNUW) BinOp->setHasNoUnsignedWrap();
588 if (isNSW) BinOp->setHasNoSignedWrap();
589 if (isExact) BinOp->setIsExact();
Eli Friedman35211c62011-05-27 00:19:40 +0000590 BinOp->setDebugLoc(FirstInst->getDebugLoc());
Chris Lattnera8fed472011-02-17 23:01:49 +0000591 return BinOp;
592 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000593
Chris Lattnerde1fede2010-01-05 05:31:55 +0000594 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Eli Friedman35211c62011-05-27 00:19:40 +0000595 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
596 PhiVal, ConstantOp);
597 NewCI->setDebugLoc(FirstInst->getDebugLoc());
598 return NewCI;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000599}
600
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000601/// Return true if this PHI node is only used by a PHI node cycle that is dead.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000602static bool DeadPHICycle(PHINode *PN,
Craig Topper71b7b682014-08-21 05:55:13 +0000603 SmallPtrSetImpl<PHINode*> &PotentiallyDeadPHIs) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000604 if (PN->use_empty()) return true;
605 if (!PN->hasOneUse()) return false;
606
607 // Remember this node, and if we find the cycle, return.
David Blaikie70573dc2014-11-19 07:49:26 +0000608 if (!PotentiallyDeadPHIs.insert(PN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000609 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000610
Chris Lattnerde1fede2010-01-05 05:31:55 +0000611 // Don't scan crazily complex things.
612 if (PotentiallyDeadPHIs.size() == 16)
613 return false;
614
Chandler Carruthcdf47882014-03-09 03:16:01 +0000615 if (PHINode *PU = dyn_cast<PHINode>(PN->user_back()))
Chris Lattnerde1fede2010-01-05 05:31:55 +0000616 return DeadPHICycle(PU, PotentiallyDeadPHIs);
617
618 return false;
619}
620
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000621/// Return true if this phi node is always equal to NonPhiInVal.
622/// This happens with mutually cyclic phi nodes like:
Chris Lattnerde1fede2010-01-05 05:31:55 +0000623/// z = some value; x = phi (y, z); y = phi (x, z)
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000624static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
Craig Topper71b7b682014-08-21 05:55:13 +0000625 SmallPtrSetImpl<PHINode*> &ValueEqualPHIs) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000626 // See if we already saw this PHI node.
David Blaikie70573dc2014-11-19 07:49:26 +0000627 if (!ValueEqualPHIs.insert(PN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000628 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000629
Chris Lattnerde1fede2010-01-05 05:31:55 +0000630 // Don't scan crazily complex things.
631 if (ValueEqualPHIs.size() == 16)
632 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000633
Chris Lattnerde1fede2010-01-05 05:31:55 +0000634 // Scan the operands to see if they are either phi nodes or are equal to
635 // the value.
Pete Cooper833f34d2015-05-12 20:05:31 +0000636 for (Value *Op : PN->incoming_values()) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000637 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
638 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
639 return false;
640 } else if (Op != NonPhiInVal)
641 return false;
642 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000643
Chris Lattnerde1fede2010-01-05 05:31:55 +0000644 return true;
645}
646
Jun Bum Lim10e58e82016-02-11 16:46:13 +0000647/// Return an existing non-zero constant if this phi node has one, otherwise
648/// return constant 1.
Jun Bum Lim339e9722016-02-11 15:50:07 +0000649static ConstantInt *GetAnyNonZeroConstInt(PHINode &PN) {
650 assert(isa<IntegerType>(PN.getType()) && "Expect only intger type phi");
651 for (Value *V : PN.operands())
652 if (auto *ConstVA = dyn_cast<ConstantInt>(V))
653 if (!ConstVA->isZeroValue())
654 return ConstVA;
655 return ConstantInt::get(cast<IntegerType>(PN.getType()), 1);
656}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000657
658namespace {
659struct PHIUsageRecord {
660 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
661 unsigned Shift; // The amount shifted.
662 Instruction *Inst; // The trunc instruction.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000663
Chris Lattnerde1fede2010-01-05 05:31:55 +0000664 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
665 : PHIId(pn), Shift(Sh), Inst(User) {}
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000666
Chris Lattnerde1fede2010-01-05 05:31:55 +0000667 bool operator<(const PHIUsageRecord &RHS) const {
668 if (PHIId < RHS.PHIId) return true;
669 if (PHIId > RHS.PHIId) return false;
670 if (Shift < RHS.Shift) return true;
671 if (Shift > RHS.Shift) return false;
672 return Inst->getType()->getPrimitiveSizeInBits() <
673 RHS.Inst->getType()->getPrimitiveSizeInBits();
674 }
675};
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000676
Chris Lattnerde1fede2010-01-05 05:31:55 +0000677struct LoweredPHIRecord {
678 PHINode *PN; // The PHI that was lowered.
679 unsigned Shift; // The amount shifted.
680 unsigned Width; // The width extracted.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000681
Chris Lattner229907c2011-07-18 04:54:35 +0000682 LoweredPHIRecord(PHINode *pn, unsigned Sh, Type *Ty)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000683 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000684
Chris Lattnerde1fede2010-01-05 05:31:55 +0000685 // Ctor form used by DenseMap.
686 LoweredPHIRecord(PHINode *pn, unsigned Sh)
687 : PN(pn), Shift(Sh), Width(0) {}
688};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000689}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000690
691namespace llvm {
692 template<>
693 struct DenseMapInfo<LoweredPHIRecord> {
694 static inline LoweredPHIRecord getEmptyKey() {
Craig Topperf40110f2014-04-25 05:29:35 +0000695 return LoweredPHIRecord(nullptr, 0);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000696 }
697 static inline LoweredPHIRecord getTombstoneKey() {
Craig Topperf40110f2014-04-25 05:29:35 +0000698 return LoweredPHIRecord(nullptr, 1);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000699 }
700 static unsigned getHashValue(const LoweredPHIRecord &Val) {
701 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
702 (Val.Width>>3);
703 }
704 static bool isEqual(const LoweredPHIRecord &LHS,
705 const LoweredPHIRecord &RHS) {
706 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
707 LHS.Width == RHS.Width;
708 }
709 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000710}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000711
712
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000713/// This is an integer PHI and we know that it has an illegal type: see if it is
714/// only used by trunc or trunc(lshr) operations. If so, we split the PHI into
715/// the various pieces being extracted. This sort of thing is introduced when
716/// SROA promotes an aggregate to large integer values.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000717///
718/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
719/// inttoptr. We should produce new PHIs in the right type.
720///
721Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
722 // PHIUsers - Keep track of all of the truncated values extracted from a set
723 // of PHIs, along with their offset. These are the things we want to rewrite.
724 SmallVector<PHIUsageRecord, 16> PHIUsers;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000725
Chris Lattnerde1fede2010-01-05 05:31:55 +0000726 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
727 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
728 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
729 // check the uses of (to ensure they are all extracts).
730 SmallVector<PHINode*, 8> PHIsToSlice;
731 SmallPtrSet<PHINode*, 8> PHIsInspected;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000732
Chris Lattnerde1fede2010-01-05 05:31:55 +0000733 PHIsToSlice.push_back(&FirstPhi);
734 PHIsInspected.insert(&FirstPhi);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000735
Chris Lattnerde1fede2010-01-05 05:31:55 +0000736 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
737 PHINode *PN = PHIsToSlice[PHIId];
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000738
Chris Lattnerde1fede2010-01-05 05:31:55 +0000739 // Scan the input list of the PHI. If any input is an invoke, and if the
740 // input is defined in the predecessor, then we won't be split the critical
741 // edge which is required to insert a truncate. Because of this, we have to
742 // bail out.
743 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
744 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000745 if (!II) continue;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000746 if (II->getParent() != PN->getIncomingBlock(i))
747 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000748
Chris Lattnerde1fede2010-01-05 05:31:55 +0000749 // If we have a phi, and if it's directly in the predecessor, then we have
750 // a critical edge where we need to put the truncate. Since we can't
751 // split the edge in instcombine, we have to bail out.
Craig Topperf40110f2014-04-25 05:29:35 +0000752 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000753 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000754
Chandler Carruthcdf47882014-03-09 03:16:01 +0000755 for (User *U : PN->users()) {
756 Instruction *UserI = cast<Instruction>(U);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000757
Chris Lattnerde1fede2010-01-05 05:31:55 +0000758 // If the user is a PHI, inspect its uses recursively.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000759 if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
David Blaikie70573dc2014-11-19 07:49:26 +0000760 if (PHIsInspected.insert(UserPN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000761 PHIsToSlice.push_back(UserPN);
762 continue;
763 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000764
Chris Lattnerde1fede2010-01-05 05:31:55 +0000765 // Truncates are always ok.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000766 if (isa<TruncInst>(UserI)) {
767 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
Chris Lattnerde1fede2010-01-05 05:31:55 +0000768 continue;
769 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000770
Chris Lattnerde1fede2010-01-05 05:31:55 +0000771 // Otherwise it must be a lshr which can only be used by one trunc.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000772 if (UserI->getOpcode() != Instruction::LShr ||
773 !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
774 !isa<ConstantInt>(UserI->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000775 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000776
Chandler Carruthcdf47882014-03-09 03:16:01 +0000777 unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
778 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
Chris Lattnerde1fede2010-01-05 05:31:55 +0000779 }
780 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000781
Chris Lattnerde1fede2010-01-05 05:31:55 +0000782 // If we have no users, they must be all self uses, just nuke the PHI.
783 if (PHIUsers.empty())
Sanjay Patel4b198802016-02-01 22:23:39 +0000784 return replaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000785
Chris Lattnerde1fede2010-01-05 05:31:55 +0000786 // If this phi node is transformable, create new PHIs for all the pieces
787 // extracted out of it. First, sort the users by their offset and size.
788 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000789
Matt Arsenaulte6db7602013-09-05 19:48:28 +0000790 DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
791 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
792 dbgs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] << '\n';
793 );
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000794
Chris Lattnerde1fede2010-01-05 05:31:55 +0000795 // PredValues - This is a temporary used when rewriting PHI nodes. It is
796 // hoisted out here to avoid construction/destruction thrashing.
797 DenseMap<BasicBlock*, Value*> PredValues;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000798
Chris Lattnerde1fede2010-01-05 05:31:55 +0000799 // ExtractedVals - Each new PHI we introduce is saved here so we don't
800 // introduce redundant PHIs.
801 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000802
Chris Lattnerde1fede2010-01-05 05:31:55 +0000803 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
804 unsigned PHIId = PHIUsers[UserI].PHIId;
805 PHINode *PN = PHIsToSlice[PHIId];
806 unsigned Offset = PHIUsers[UserI].Shift;
Chris Lattner229907c2011-07-18 04:54:35 +0000807 Type *Ty = PHIUsers[UserI].Inst->getType();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000808
Chris Lattnerde1fede2010-01-05 05:31:55 +0000809 PHINode *EltPHI;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000810
Chris Lattnerde1fede2010-01-05 05:31:55 +0000811 // If we've already lowered a user like this, reuse the previously lowered
812 // value.
Craig Topperf40110f2014-04-25 05:29:35 +0000813 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000814
Chris Lattnerde1fede2010-01-05 05:31:55 +0000815 // Otherwise, Create the new PHI node for this user.
Jay Foad52131342011-03-30 11:28:46 +0000816 EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
817 PN->getName()+".off"+Twine(Offset), PN);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000818 assert(EltPHI->getType() != PN->getType() &&
819 "Truncate didn't shrink phi?");
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000820
Chris Lattnerde1fede2010-01-05 05:31:55 +0000821 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
822 BasicBlock *Pred = PN->getIncomingBlock(i);
823 Value *&PredVal = PredValues[Pred];
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000824
Chris Lattnerde1fede2010-01-05 05:31:55 +0000825 // If we already have a value for this predecessor, reuse it.
826 if (PredVal) {
827 EltPHI->addIncoming(PredVal, Pred);
828 continue;
829 }
830
831 // Handle the PHI self-reuse case.
832 Value *InVal = PN->getIncomingValue(i);
833 if (InVal == PN) {
834 PredVal = EltPHI;
835 EltPHI->addIncoming(PredVal, Pred);
836 continue;
837 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000838
Chris Lattnerde1fede2010-01-05 05:31:55 +0000839 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
840 // If the incoming value was a PHI, and if it was one of the PHIs we
841 // already rewrote it, just use the lowered value.
842 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
843 PredVal = Res;
844 EltPHI->addIncoming(PredVal, Pred);
845 continue;
846 }
847 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000848
Chris Lattnerde1fede2010-01-05 05:31:55 +0000849 // Otherwise, do an extract in the predecessor.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000850 Builder->SetInsertPoint(Pred->getTerminator());
Chris Lattnerde1fede2010-01-05 05:31:55 +0000851 Value *Res = InVal;
852 if (Offset)
853 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
854 Offset), "extract");
855 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
856 PredVal = Res;
857 EltPHI->addIncoming(Res, Pred);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000858
Chris Lattnerde1fede2010-01-05 05:31:55 +0000859 // If the incoming value was a PHI, and if it was one of the PHIs we are
860 // rewriting, we will ultimately delete the code we inserted. This
861 // means we need to revisit that PHI to make sure we extract out the
862 // needed piece.
863 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
864 if (PHIsInspected.count(OldInVal)) {
865 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
866 OldInVal)-PHIsToSlice.begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000867 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
Chris Lattnerde1fede2010-01-05 05:31:55 +0000868 cast<Instruction>(Res)));
869 ++UserE;
870 }
871 }
872 PredValues.clear();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000873
Matt Arsenaulte6db7602013-09-05 19:48:28 +0000874 DEBUG(dbgs() << " Made element PHI for offset " << Offset << ": "
Chris Lattnerde1fede2010-01-05 05:31:55 +0000875 << *EltPHI << '\n');
876 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
877 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000878
Chris Lattnerde1fede2010-01-05 05:31:55 +0000879 // Replace the use of this piece with the PHI node.
Sanjay Patel4b198802016-02-01 22:23:39 +0000880 replaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000881 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000882
Chris Lattnerde1fede2010-01-05 05:31:55 +0000883 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
884 // with undefs.
885 Value *Undef = UndefValue::get(FirstPhi.getType());
886 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
Sanjay Patel4b198802016-02-01 22:23:39 +0000887 replaceInstUsesWith(*PHIsToSlice[i], Undef);
888 return replaceInstUsesWith(FirstPhi, Undef);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000889}
890
891// PHINode simplification
892//
893Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000894 if (Value *V = SimplifyInstruction(&PN, DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +0000895 return replaceInstUsesWith(PN, V);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000896
Sanjay Patel95334072015-09-27 20:34:31 +0000897 if (Instruction *Result = FoldPHIArgZextsIntoPHI(PN))
898 return Result;
899
Chris Lattnerde1fede2010-01-05 05:31:55 +0000900 // If all PHI operands are the same operation, pull them through the PHI,
901 // reducing code size.
902 if (isa<Instruction>(PN.getIncomingValue(0)) &&
903 isa<Instruction>(PN.getIncomingValue(1)) &&
904 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
905 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
906 // FIXME: The hasOneUse check will fail for PHIs that use the value more
907 // than themselves more than once.
908 PN.getIncomingValue(0)->hasOneUse())
909 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
910 return Result;
911
912 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
913 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
914 // PHI)... break the cycle.
915 if (PN.hasOneUse()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000916 Instruction *PHIUser = cast<Instruction>(PN.user_back());
Chris Lattnerde1fede2010-01-05 05:31:55 +0000917 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
918 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
919 PotentiallyDeadPHIs.insert(&PN);
920 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Sanjay Patel4b198802016-02-01 22:23:39 +0000921 return replaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerde1fede2010-01-05 05:31:55 +0000922 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000923
Chris Lattnerde1fede2010-01-05 05:31:55 +0000924 // If this phi has a single use, and if that use just computes a value for
925 // the next iteration of a loop, delete the phi. This occurs with unused
926 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
927 // common case here is good because the only other things that catch this
928 // are induction variable analysis (sometimes) and ADCE, which is only run
929 // late.
930 if (PHIUser->hasOneUse() &&
931 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
Chandler Carruthcdf47882014-03-09 03:16:01 +0000932 PHIUser->user_back() == &PN) {
Sanjay Patel4b198802016-02-01 22:23:39 +0000933 return replaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerde1fede2010-01-05 05:31:55 +0000934 }
Jun Bum Lim339e9722016-02-11 15:50:07 +0000935 // When a PHI is used only to be compared with zero, it is safe to replace
936 // an incoming value proved as known nonzero with any non-zero constant.
Jun Bum Lim10e58e82016-02-11 16:46:13 +0000937 // For example, in the code below, the incoming value %v can be replaced
938 // with any non-zero constant based on the fact that the PHI is only used to
939 // be compared with zero and %v is a known non-zero value:
Jun Bum Lim339e9722016-02-11 15:50:07 +0000940 // %v = select %cond, 1, 2
941 // %p = phi [%v, BB] ...
942 // icmp eq, %p, 0
943 auto *CmpInst = dyn_cast<ICmpInst>(PHIUser);
944 // FIXME: To be simple, handle only integer type for now.
945 if (CmpInst && isa<IntegerType>(PN.getType()) && CmpInst->isEquality() &&
946 match(CmpInst->getOperand(1), m_Zero())) {
947 ConstantInt *NonZeroConst = nullptr;
948 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
949 Instruction *CtxI = PN.getIncomingBlock(i)->getTerminator();
950 Value *VA = PN.getIncomingValue(i);
951 if (isKnownNonZero(VA, DL, 0, AC, CtxI, DT)) {
952 if (!NonZeroConst)
953 NonZeroConst = GetAnyNonZeroConstInt(PN);
954 PN.setIncomingValue(i, NonZeroConst);
955 }
956 }
957 }
Chris Lattnerde1fede2010-01-05 05:31:55 +0000958 }
959
960 // We sometimes end up with phi cycles that non-obviously end up being the
961 // same value, for example:
962 // z = some value; x = phi (y, z); y = phi (x, z)
963 // where the phi nodes don't necessarily need to be in the same block. Do a
964 // quick check to see if the PHI node only contains a single non-phi value, if
965 // so, scan to see if the phi cycle is actually equal to that value.
966 {
Frits van Bommeld6d4f982011-04-16 14:32:34 +0000967 unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
Chris Lattnerde1fede2010-01-05 05:31:55 +0000968 // Scan for the first non-phi operand.
Frits van Bommeld6d4f982011-04-16 14:32:34 +0000969 while (InValNo != NumIncomingVals &&
Chris Lattnerde1fede2010-01-05 05:31:55 +0000970 isa<PHINode>(PN.getIncomingValue(InValNo)))
971 ++InValNo;
972
Frits van Bommeld6d4f982011-04-16 14:32:34 +0000973 if (InValNo != NumIncomingVals) {
Jay Foad7d03e9b2011-04-16 14:17:37 +0000974 Value *NonPhiInVal = PN.getIncomingValue(InValNo);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000975
Chris Lattnerde1fede2010-01-05 05:31:55 +0000976 // Scan the rest of the operands to see if there are any conflicts, if so
977 // there is no need to recursively scan other phis.
Frits van Bommeld6d4f982011-04-16 14:32:34 +0000978 for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000979 Value *OpVal = PN.getIncomingValue(InValNo);
980 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
981 break;
982 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000983
Chris Lattnerde1fede2010-01-05 05:31:55 +0000984 // If we scanned over all operands, then we have one unique value plus
985 // phi values. Scan PHI nodes to see if they all merge in each other or
986 // the value.
Frits van Bommeld6d4f982011-04-16 14:32:34 +0000987 if (InValNo == NumIncomingVals) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000988 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
989 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
Sanjay Patel4b198802016-02-01 22:23:39 +0000990 return replaceInstUsesWith(PN, NonPhiInVal);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000991 }
992 }
993 }
994
995 // If there are multiple PHIs, sort their operands so that they all list
996 // the blocks in the same order. This will help identical PHIs be eliminated
997 // by other passes. Other passes shouldn't depend on this for correctness
998 // however.
999 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
1000 if (&PN != FirstPN)
1001 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
1002 BasicBlock *BBA = PN.getIncomingBlock(i);
1003 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
1004 if (BBA != BBB) {
1005 Value *VA = PN.getIncomingValue(i);
1006 unsigned j = PN.getBasicBlockIndex(BBB);
1007 Value *VB = PN.getIncomingValue(j);
1008 PN.setIncomingBlock(i, BBB);
1009 PN.setIncomingValue(i, VB);
1010 PN.setIncomingBlock(j, BBA);
1011 PN.setIncomingValue(j, VA);
1012 // NOTE: Instcombine normally would want us to "return &PN" if we
1013 // modified any of the operands of an instruction. However, since we
1014 // aren't adding or removing uses (just rearranging them) we don't do
1015 // this in this case.
1016 }
1017 }
1018
1019 // If this is an integer PHI and we know that it has an illegal type, see if
1020 // it is only used by trunc or trunc(lshr) operations. If so, we split the
1021 // PHI into the various pieces being extracted. This sort of thing is
1022 // introduced when SROA promotes an aggregate to a single large integer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001023 if (PN.getType()->isIntegerTy() &&
1024 !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
Chris Lattnerde1fede2010-01-05 05:31:55 +00001025 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
1026 return Res;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001027
Craig Topperf40110f2014-04-25 05:29:35 +00001028 return nullptr;
Benjamin Kramerf7cc6982010-01-05 13:32:48 +00001029}