blob: 45d448075d687ca97af1db76acf9e232d77e27e0 [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"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000019#include "llvm/IR/DebugInfo.h"
Jun Bum Lim339e9722016-02-11 15:50:07 +000020#include "llvm/IR/PatternMatch.h"
Akira Hatanakaf6afd112015-09-23 18:40:57 +000021#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerde1fede2010-01-05 05:31:55 +000022using namespace llvm;
Jun Bum Lim339e9722016-02-11 15:50:07 +000023using namespace llvm::PatternMatch;
Chris Lattnerde1fede2010-01-05 05:31:55 +000024
Chandler Carruth964daaa2014-04-22 02:55:47 +000025#define DEBUG_TYPE "instcombine"
26
Robert Lougher2428a402016-12-14 17:49:19 +000027/// The PHI arguments will be folded into a single operation with a PHI node
28/// as input. The debug location of the single operation will be the merged
29/// locations of the original PHI node arguments.
Dehao Chenf4646272017-10-02 18:13:14 +000030void InstCombiner::PHIArgMergedDebugLoc(Instruction *Inst, PHINode &PN) {
Robert Lougher2428a402016-12-14 17:49:19 +000031 auto *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Dehao Chenf4646272017-10-02 18:13:14 +000032 Inst->setDebugLoc(FirstInst->getDebugLoc());
33 // We do not expect a CallInst here, otherwise, N-way merging of DebugLoc
34 // will be inefficient.
35 assert(!isa<CallInst>(Inst));
Robert Lougher2428a402016-12-14 17:49:19 +000036
37 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
38 auto *I = cast<Instruction>(PN.getIncomingValue(i));
Dehao Chenf4646272017-10-02 18:13:14 +000039 Inst->applyMergedLocation(Inst->getDebugLoc(), I->getDebugLoc());
Robert Lougher2428a402016-12-14 17:49:19 +000040 }
Robert Lougher2428a402016-12-14 17:49:19 +000041}
42
Xinliang David Li4cdc9da2017-10-10 05:07:54 +000043// Replace Integer typed PHI PN if the PHI's value is used as a pointer value.
44// If there is an existing pointer typed PHI that produces the same value as PN,
45// replace PN and the IntToPtr operation with it. Otherwise, synthesize a new
46// PHI node:
47//
48// Case-1:
49// bb1:
50// int_init = PtrToInt(ptr_init)
51// br label %bb2
52// bb2:
53// int_val = PHI([int_init, %bb1], [int_val_inc, %bb2]
54// ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
55// ptr_val2 = IntToPtr(int_val)
56// ...
57// use(ptr_val2)
58// ptr_val_inc = ...
59// inc_val_inc = PtrToInt(ptr_val_inc)
60//
61// ==>
62// bb1:
63// br label %bb2
64// bb2:
65// ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
66// ...
67// use(ptr_val)
68// ptr_val_inc = ...
69//
70// Case-2:
71// bb1:
72// int_ptr = BitCast(ptr_ptr)
73// int_init = Load(int_ptr)
74// br label %bb2
75// bb2:
76// int_val = PHI([int_init, %bb1], [int_val_inc, %bb2]
77// ptr_val2 = IntToPtr(int_val)
78// ...
79// use(ptr_val2)
80// ptr_val_inc = ...
81// inc_val_inc = PtrToInt(ptr_val_inc)
82// ==>
83// bb1:
84// ptr_init = Load(ptr_ptr)
85// br label %bb2
86// bb2:
87// ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
88// ...
89// use(ptr_val)
90// ptr_val_inc = ...
91// ...
92//
93Instruction *InstCombiner::FoldIntegerTypedPHI(PHINode &PN) {
94 if (!PN.getType()->isIntegerTy())
95 return nullptr;
96 if (!PN.hasOneUse())
97 return nullptr;
98
99 auto *IntToPtr = dyn_cast<IntToPtrInst>(PN.user_back());
100 if (!IntToPtr)
101 return nullptr;
102
103 // Check if the pointer is actually used as pointer:
104 auto HasPointerUse = [](Instruction *IIP) {
105 for (User *U : IIP->users()) {
106 Value *Ptr = nullptr;
107 if (LoadInst *LoadI = dyn_cast<LoadInst>(U)) {
108 Ptr = LoadI->getPointerOperand();
109 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
110 Ptr = SI->getPointerOperand();
111 } else if (GetElementPtrInst *GI = dyn_cast<GetElementPtrInst>(U)) {
112 Ptr = GI->getPointerOperand();
113 }
114
115 if (Ptr && Ptr == IIP)
116 return true;
117 }
118 return false;
119 };
120
121 if (!HasPointerUse(IntToPtr))
122 return nullptr;
123
124 if (DL.getPointerSizeInBits(IntToPtr->getAddressSpace()) !=
125 DL.getTypeSizeInBits(IntToPtr->getOperand(0)->getType()))
126 return nullptr;
127
128 SmallVector<Value *, 4> AvailablePtrVals;
129 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
130 Value *Arg = PN.getIncomingValue(i);
131
132 // First look backward:
133 if (auto *PI = dyn_cast<PtrToIntInst>(Arg)) {
134 AvailablePtrVals.emplace_back(PI->getOperand(0));
135 continue;
136 }
137
138 // Next look forward:
139 Value *ArgIntToPtr = nullptr;
140 for (User *U : Arg->users()) {
141 if (isa<IntToPtrInst>(U) && U->getType() == IntToPtr->getType() &&
142 (DT.dominates(cast<Instruction>(U), PN.getIncomingBlock(i)) ||
143 cast<Instruction>(U)->getParent() == PN.getIncomingBlock(i))) {
144 ArgIntToPtr = U;
145 break;
146 }
147 }
148
149 if (ArgIntToPtr) {
150 AvailablePtrVals.emplace_back(ArgIntToPtr);
151 continue;
152 }
153
154 // If Arg is defined by a PHI, allow it. This will also create
155 // more opportunities iteratively.
156 if (isa<PHINode>(Arg)) {
157 AvailablePtrVals.emplace_back(Arg);
158 continue;
159 }
160
161 // For a single use integer load:
162 auto *LoadI = dyn_cast<LoadInst>(Arg);
163 if (!LoadI)
164 return nullptr;
165
166 if (!LoadI->hasOneUse())
167 return nullptr;
168
169 // Push the integer typed Load instruction into the available
170 // value set, and fix it up later when the pointer typed PHI
171 // is synthesized.
172 AvailablePtrVals.emplace_back(LoadI);
173 }
174
175 // Now search for a matching PHI
176 auto *BB = PN.getParent();
177 assert(AvailablePtrVals.size() == PN.getNumIncomingValues() &&
178 "Not enough available ptr typed incoming values");
179 PHINode *MatchingPtrPHI = nullptr;
180 for (auto II = BB->begin(), EI = BasicBlock::iterator(BB->getFirstNonPHI());
181 II != EI; II++) {
182 PHINode *PtrPHI = dyn_cast<PHINode>(II);
183 if (!PtrPHI || PtrPHI == &PN || PtrPHI->getType() != IntToPtr->getType())
184 continue;
185 MatchingPtrPHI = PtrPHI;
186 for (unsigned i = 0; i != PtrPHI->getNumIncomingValues(); ++i) {
187 if (AvailablePtrVals[i] !=
188 PtrPHI->getIncomingValueForBlock(PN.getIncomingBlock(i))) {
189 MatchingPtrPHI = nullptr;
190 break;
191 }
192 }
193
194 if (MatchingPtrPHI)
195 break;
196 }
197
198 if (MatchingPtrPHI) {
199 assert(MatchingPtrPHI->getType() == IntToPtr->getType() &&
200 "Phi's Type does not match with IntToPtr");
201 // The PtrToCast + IntToPtr will be simplified later
202 return CastInst::CreateBitOrPointerCast(MatchingPtrPHI,
203 IntToPtr->getOperand(0)->getType());
204 }
205
206 // If it requires a conversion for every PHI operand, do not do it.
207 if (std::all_of(AvailablePtrVals.begin(), AvailablePtrVals.end(),
208 [&](Value *V) {
209 return (V->getType() != IntToPtr->getType()) ||
210 isa<IntToPtrInst>(V);
211 }))
212 return nullptr;
213
214 // If any of the operand that requires casting is a terminator
215 // instruction, do not do it.
216 if (std::any_of(AvailablePtrVals.begin(), AvailablePtrVals.end(),
217 [&](Value *V) {
218 return (V->getType() != IntToPtr->getType()) &&
219 isa<TerminatorInst>(V);
220 }))
221 return nullptr;
222
223 PHINode *NewPtrPHI = PHINode::Create(
224 IntToPtr->getType(), PN.getNumIncomingValues(), PN.getName() + ".ptr");
225
226 InsertNewInstBefore(NewPtrPHI, PN);
227 SmallDenseMap<Value *, Instruction *> Casts;
228 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
229 auto *IncomingBB = PN.getIncomingBlock(i);
230 auto *IncomingVal = AvailablePtrVals[i];
231
232 if (IncomingVal->getType() == IntToPtr->getType()) {
233 NewPtrPHI->addIncoming(IncomingVal, IncomingBB);
234 continue;
235 }
236
237#ifndef NDEBUG
238 LoadInst *LoadI = dyn_cast<LoadInst>(IncomingVal);
239 assert((isa<PHINode>(IncomingVal) ||
240 IncomingVal->getType()->isPointerTy() ||
241 (LoadI && LoadI->hasOneUse())) &&
242 "Can not replace LoadInst with multiple uses");
243#endif
244 // Need to insert a BitCast.
245 // For an integer Load instruction with a single use, the load + IntToPtr
246 // cast will be simplified into a pointer load:
247 // %v = load i64, i64* %a.ip, align 8
248 // %v.cast = inttoptr i64 %v to float **
249 // ==>
250 // %v.ptrp = bitcast i64 * %a.ip to float **
251 // %v.cast = load float *, float ** %v.ptrp, align 8
252 Instruction *&CI = Casts[IncomingVal];
253 if (!CI) {
254 CI = CastInst::CreateBitOrPointerCast(IncomingVal, IntToPtr->getType(),
255 IncomingVal->getName() + ".ptr");
256 if (auto *IncomingI = dyn_cast<Instruction>(IncomingVal)) {
257 BasicBlock::iterator InsertPos(IncomingI);
258 InsertPos++;
259 if (isa<PHINode>(IncomingI))
260 InsertPos = IncomingI->getParent()->getFirstInsertionPt();
261 InsertNewInstBefore(CI, *InsertPos);
262 } else {
263 auto *InsertBB = &IncomingBB->getParent()->getEntryBlock();
264 InsertNewInstBefore(CI, *InsertBB->getFirstInsertionPt());
265 }
266 }
267 NewPtrPHI->addIncoming(CI, IncomingBB);
268 }
269
270 // The PtrToCast + IntToPtr will be simplified later
271 return CastInst::CreateBitOrPointerCast(NewPtrPHI,
272 IntToPtr->getOperand(0)->getType());
273}
274
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000275/// If we have something like phi [add (a,b), add(a,c)] and if a/b/c and the
276/// adds all have a single use, turn this into a phi and a single binop.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000277Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
278 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
279 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
280 unsigned Opc = FirstInst->getOpcode();
281 Value *LHSVal = FirstInst->getOperand(0);
282 Value *RHSVal = FirstInst->getOperand(1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000283
Chris Lattner229907c2011-07-18 04:54:35 +0000284 Type *LHSType = LHSVal->getType();
285 Type *RHSType = RHSVal->getType();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000286
Chris Lattnerde1fede2010-01-05 05:31:55 +0000287 // Scan to see if all operands are the same opcode, and all have one use.
288 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
289 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
290 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
291 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnera8fed472011-02-17 23:01:49 +0000292 // types.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000293 I->getOperand(0)->getType() != LHSType ||
294 I->getOperand(1)->getType() != RHSType)
Craig Topperf40110f2014-04-25 05:29:35 +0000295 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000296
297 // If they are CmpInst instructions, check their predicates
Chris Lattnera8fed472011-02-17 23:01:49 +0000298 if (CmpInst *CI = dyn_cast<CmpInst>(I))
299 if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
Craig Topperf40110f2014-04-25 05:29:35 +0000300 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000301
Chris Lattnerde1fede2010-01-05 05:31:55 +0000302 // Keep track of which operand needs a phi node.
Craig Topperf40110f2014-04-25 05:29:35 +0000303 if (I->getOperand(0) != LHSVal) LHSVal = nullptr;
304 if (I->getOperand(1) != RHSVal) RHSVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000305 }
306
307 // If both LHS and RHS would need a PHI, don't do this transformation,
308 // because it would increase the number of PHIs entering the block,
309 // which leads to higher register pressure. This is especially
310 // bad when the PHIs are in the header of a loop.
311 if (!LHSVal && !RHSVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000312 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000313
Chris Lattnerde1fede2010-01-05 05:31:55 +0000314 // Otherwise, this is safe to transform!
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000315
Chris Lattnerde1fede2010-01-05 05:31:55 +0000316 Value *InLHS = FirstInst->getOperand(0);
317 Value *InRHS = FirstInst->getOperand(1);
Craig Topperf40110f2014-04-25 05:29:35 +0000318 PHINode *NewLHS = nullptr, *NewRHS = nullptr;
319 if (!LHSVal) {
Jay Foad52131342011-03-30 11:28:46 +0000320 NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000321 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerde1fede2010-01-05 05:31:55 +0000322 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
323 InsertNewInstBefore(NewLHS, PN);
324 LHSVal = NewLHS;
325 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000326
Craig Topperf40110f2014-04-25 05:29:35 +0000327 if (!RHSVal) {
Jay Foad52131342011-03-30 11:28:46 +0000328 NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000329 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerde1fede2010-01-05 05:31:55 +0000330 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
331 InsertNewInstBefore(NewRHS, PN);
332 RHSVal = NewRHS;
333 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000334
Chris Lattnerde1fede2010-01-05 05:31:55 +0000335 // Add all operands to the new PHIs.
336 if (NewLHS || NewRHS) {
337 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
338 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
339 if (NewLHS) {
340 Value *NewInLHS = InInst->getOperand(0);
341 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
342 }
343 if (NewRHS) {
344 Value *NewInRHS = InInst->getOperand(1);
345 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
346 }
347 }
348 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000349
Eli Friedman35211c62011-05-27 00:19:40 +0000350 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
351 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
352 LHSVal, RHSVal);
Dehao Chenf4646272017-10-02 18:13:14 +0000353 PHIArgMergedDebugLoc(NewCI, PN);
Eli Friedman35211c62011-05-27 00:19:40 +0000354 return NewCI;
355 }
356
Chris Lattnera8fed472011-02-17 23:01:49 +0000357 BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
358 BinaryOperator *NewBinOp =
359 BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Silviu Barangae985c762016-04-22 11:21:36 +0000360
361 NewBinOp->copyIRFlags(PN.getIncomingValue(0));
362
363 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i)
364 NewBinOp->andIRFlags(PN.getIncomingValue(i));
365
Dehao Chenf4646272017-10-02 18:13:14 +0000366 PHIArgMergedDebugLoc(NewBinOp, PN);
Chris Lattnera8fed472011-02-17 23:01:49 +0000367 return NewBinOp;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000368}
369
370Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
371 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000372
373 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000374 FirstInst->op_end());
375 // This is true if all GEP bases are allocas and if all indices into them are
376 // constants.
377 bool AllBasePointersAreAllocas = true;
378
379 // We don't want to replace this phi if the replacement would require
380 // more than one phi, which leads to higher register pressure. This is
381 // especially bad when the PHIs are in the header of a loop.
382 bool NeededPhi = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000383
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000384 bool AllInBounds = true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000385
Chris Lattnerde1fede2010-01-05 05:31:55 +0000386 // Scan to see if all operands are the same opcode, and all have one use.
387 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
388 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
389 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
390 GEP->getNumOperands() != FirstInst->getNumOperands())
Craig Topperf40110f2014-04-25 05:29:35 +0000391 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000392
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000393 AllInBounds &= GEP->isInBounds();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000394
Chris Lattnerde1fede2010-01-05 05:31:55 +0000395 // Keep track of whether or not all GEPs are of alloca pointers.
396 if (AllBasePointersAreAllocas &&
397 (!isa<AllocaInst>(GEP->getOperand(0)) ||
398 !GEP->hasAllConstantIndices()))
399 AllBasePointersAreAllocas = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000400
Chris Lattnerde1fede2010-01-05 05:31:55 +0000401 // Compare the operand lists.
402 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
403 if (FirstInst->getOperand(op) == GEP->getOperand(op))
404 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000405
Chris Lattnerde1fede2010-01-05 05:31:55 +0000406 // Don't merge two GEPs when two operands differ (introducing phi nodes)
407 // if one of the PHIs has a constant for the index. The index may be
408 // substantially cheaper to compute for the constants, so making it a
409 // variable index could pessimize the path. This also handles the case
410 // for struct indices, which must always be constant.
411 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
412 isa<ConstantInt>(GEP->getOperand(op)))
Craig Topperf40110f2014-04-25 05:29:35 +0000413 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000414
Chris Lattnerde1fede2010-01-05 05:31:55 +0000415 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +0000416 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000417
418 // If we already needed a PHI for an earlier operand, and another operand
419 // also requires a PHI, we'd be introducing more PHIs than we're
420 // eliminating, which increases register pressure on entry to the PHI's
421 // block.
422 if (NeededPhi)
Craig Topperf40110f2014-04-25 05:29:35 +0000423 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000424
Craig Topperf40110f2014-04-25 05:29:35 +0000425 FixedOperands[op] = nullptr; // Needs a PHI.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000426 NeededPhi = true;
427 }
428 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000429
Chris Lattnerde1fede2010-01-05 05:31:55 +0000430 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
431 // bother doing this transformation. At best, this will just save a bit of
432 // offset calculation, but all the predecessors will have to materialize the
433 // stack address into a register anyway. We'd actually rather *clone* the
434 // load up into the predecessors so that we have a load of a gep of an alloca,
435 // which can usually all be folded into the load.
436 if (AllBasePointersAreAllocas)
Craig Topperf40110f2014-04-25 05:29:35 +0000437 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000438
Chris Lattnerde1fede2010-01-05 05:31:55 +0000439 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
440 // that is variable.
441 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000442
Chris Lattnerde1fede2010-01-05 05:31:55 +0000443 bool HasAnyPHIs = false;
444 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
445 if (FixedOperands[i]) continue; // operand doesn't need a phi.
446 Value *FirstOp = FirstInst->getOperand(i);
Jay Foad52131342011-03-30 11:28:46 +0000447 PHINode *NewPN = PHINode::Create(FirstOp->getType(), e,
Chris Lattnerde1fede2010-01-05 05:31:55 +0000448 FirstOp->getName()+".pn");
449 InsertNewInstBefore(NewPN, PN);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000450
Chris Lattnerde1fede2010-01-05 05:31:55 +0000451 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
452 OperandPhis[i] = NewPN;
453 FixedOperands[i] = NewPN;
454 HasAnyPHIs = true;
455 }
456
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000457
Chris Lattnerde1fede2010-01-05 05:31:55 +0000458 // Add all operands to the new PHIs.
459 if (HasAnyPHIs) {
460 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
461 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
462 BasicBlock *InBB = PN.getIncomingBlock(i);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000463
Chris Lattnerde1fede2010-01-05 05:31:55 +0000464 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
465 if (PHINode *OpPhi = OperandPhis[op])
466 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
467 }
468 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000469
Chris Lattnerde1fede2010-01-05 05:31:55 +0000470 Value *Base = FixedOperands[0];
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000471 GetElementPtrInst *NewGEP =
David Blaikie741c8f82015-03-14 01:53:18 +0000472 GetElementPtrInst::Create(FirstInst->getSourceElementType(), Base,
473 makeArrayRef(FixedOperands).slice(1));
Chris Lattner75ae5a42011-02-17 22:32:54 +0000474 if (AllInBounds) NewGEP->setIsInBounds();
Dehao Chenf4646272017-10-02 18:13:14 +0000475 PHIArgMergedDebugLoc(NewGEP, PN);
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000476 return NewGEP;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000477}
478
479
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000480/// Return true if we know that it is safe to sink the load out of the block
481/// that defines it. This means that it must be obvious the value of the load is
482/// not changed from the point of the load to the end of the block it is in.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000483///
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000484/// Finally, it is safe, but not profitable, to sink a load targeting a
Chris Lattnerde1fede2010-01-05 05:31:55 +0000485/// non-address-taken alloca. Doing so will cause us to not promote the alloca
486/// to a register.
487static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000488 BasicBlock::iterator BBI = L->getIterator(), E = L->getParent()->end();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000489
Chris Lattnerde1fede2010-01-05 05:31:55 +0000490 for (++BBI; BBI != E; ++BBI)
491 if (BBI->mayWriteToMemory())
492 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000493
Chris Lattnerde1fede2010-01-05 05:31:55 +0000494 // Check for non-address taken alloca. If not address-taken already, it isn't
495 // profitable to do this xform.
496 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
497 bool isAddressTaken = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000498 for (User *U : AI->users()) {
Gabor Greif96fedcb2010-07-12 14:15:58 +0000499 if (isa<LoadInst>(U)) continue;
500 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000501 // If storing TO the alloca, then the address isn't taken.
502 if (SI->getOperand(1) == AI) continue;
503 }
504 isAddressTaken = true;
505 break;
506 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000507
Chris Lattnerde1fede2010-01-05 05:31:55 +0000508 if (!isAddressTaken && AI->isStaticAlloca())
509 return false;
510 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000511
Chris Lattnerde1fede2010-01-05 05:31:55 +0000512 // If this load is a load from a GEP with a constant offset from an alloca,
513 // then we don't want to sink it. In its present form, it will be
514 // load [constant stack offset]. Sinking it will cause us to have to
515 // materialize the stack addresses in each predecessor in a register only to
516 // do a shared load from register in the successor.
517 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
518 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
519 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
520 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000521
Chris Lattnerde1fede2010-01-05 05:31:55 +0000522 return true;
523}
524
525Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
526 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
Eli Friedman8bc586e2011-08-15 22:09:40 +0000527
528 // FIXME: This is overconservative; this transform is allowed in some cases
529 // for atomic operations.
530 if (FirstLI->isAtomic())
Craig Topperf40110f2014-04-25 05:29:35 +0000531 return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +0000532
Chris Lattnerde1fede2010-01-05 05:31:55 +0000533 // When processing loads, we need to propagate two bits of information to the
534 // sunk load: whether it is volatile, and what its alignment is. We currently
535 // don't sink loads when some have their alignment specified and some don't.
536 // visitLoadInst will propagate an alignment onto the load when TD is around,
537 // and if TD isn't around, we can't handle the mixed case.
538 bool isVolatile = FirstLI->isVolatile();
539 unsigned LoadAlignment = FirstLI->getAlignment();
Chris Lattnerf6befff2010-03-05 18:53:28 +0000540 unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000541
Chris Lattnerde1fede2010-01-05 05:31:55 +0000542 // We can't sink the load if the loaded value could be modified between the
543 // load and the PHI.
544 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
545 !isSafeAndProfitableToSinkLoad(FirstLI))
Craig Topperf40110f2014-04-25 05:29:35 +0000546 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000547
Chris Lattnerde1fede2010-01-05 05:31:55 +0000548 // If the PHI is of volatile loads and the load block has multiple
549 // successors, sinking it would remove a load of the volatile value from
550 // the path through the other successor.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000551 if (isVolatile &&
Chris Lattnerde1fede2010-01-05 05:31:55 +0000552 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +0000553 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000554
Chris Lattnerde1fede2010-01-05 05:31:55 +0000555 // Check to see if all arguments are the same operation.
556 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
557 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
558 if (!LI || !LI->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +0000559 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000560
561 // We can't sink the load if the loaded value could be modified between
Chris Lattnerde1fede2010-01-05 05:31:55 +0000562 // the load and the PHI.
563 if (LI->isVolatile() != isVolatile ||
564 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattnerf6befff2010-03-05 18:53:28 +0000565 LI->getPointerAddressSpace() != LoadAddrSpace ||
Chris Lattnerde1fede2010-01-05 05:31:55 +0000566 !isSafeAndProfitableToSinkLoad(LI))
Craig Topperf40110f2014-04-25 05:29:35 +0000567 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000568
Chris Lattnerde1fede2010-01-05 05:31:55 +0000569 // If some of the loads have an alignment specified but not all of them,
570 // we can't do the transformation.
571 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
Craig Topperf40110f2014-04-25 05:29:35 +0000572 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000573
Chris Lattnerde1fede2010-01-05 05:31:55 +0000574 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000575
Chris Lattnerde1fede2010-01-05 05:31:55 +0000576 // If the PHI is of volatile loads and the load block has multiple
577 // successors, sinking it would remove a load of the volatile value from
578 // the path through the other successor.
579 if (isVolatile &&
580 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +0000581 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000582 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000583
Chris Lattnerde1fede2010-01-05 05:31:55 +0000584 // Okay, they are all the same operation. Create a new PHI node of the
585 // correct type, and PHI together all of the LHS's of the instructions.
586 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
Jay Foad52131342011-03-30 11:28:46 +0000587 PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000588 PN.getName()+".in");
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000589
Chris Lattnerde1fede2010-01-05 05:31:55 +0000590 Value *InVal = FirstLI->getOperand(0);
591 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000592 LoadInst *NewLI = new LoadInst(NewPN, "", isVolatile, LoadAlignment);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000593
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000594 unsigned KnownIDs[] = {
595 LLVMContext::MD_tbaa,
596 LLVMContext::MD_range,
597 LLVMContext::MD_invariant_load,
598 LLVMContext::MD_alias_scope,
599 LLVMContext::MD_noalias,
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000600 LLVMContext::MD_nonnull,
601 LLVMContext::MD_align,
602 LLVMContext::MD_dereferenceable,
603 LLVMContext::MD_dereferenceable_or_null,
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000604 };
605
606 for (unsigned ID : KnownIDs)
607 NewLI->setMetadata(ID, FirstLI->getMetadata(ID));
608
609 // Add all operands to the new PHI and combine TBAA metadata.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000610 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000611 LoadInst *LI = cast<LoadInst>(PN.getIncomingValue(i));
612 combineMetadata(NewLI, LI, KnownIDs);
613 Value *NewInVal = LI->getOperand(0);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000614 if (NewInVal != InVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000615 InVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000616 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
617 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000618
Chris Lattnerde1fede2010-01-05 05:31:55 +0000619 if (InVal) {
620 // The new PHI unions all of the same values together. This is really
621 // common, so we handle it intelligently here for compile-time speed.
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000622 NewLI->setOperand(0, InVal);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000623 delete NewPN;
624 } else {
625 InsertNewInstBefore(NewPN, PN);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000626 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000627
Chris Lattnerde1fede2010-01-05 05:31:55 +0000628 // If this was a volatile load that we are merging, make sure to loop through
629 // and mark all the input loads as non-volatile. If we don't do this, we will
630 // insert a new volatile load and the old ones will not be deletable.
631 if (isVolatile)
Pete Cooper833f34d2015-05-12 20:05:31 +0000632 for (Value *IncValue : PN.incoming_values())
633 cast<LoadInst>(IncValue)->setVolatile(false);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000634
Dehao Chenf4646272017-10-02 18:13:14 +0000635 PHIArgMergedDebugLoc(NewLI, PN);
Eli Friedman35211c62011-05-27 00:19:40 +0000636 return NewLI;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000637}
638
Sanjay Patel95334072015-09-27 20:34:31 +0000639/// TODO: This function could handle other cast types, but then it might
640/// require special-casing a cast from the 'i1' type. See the comment in
641/// FoldPHIArgOpIntoPHI() about pessimizing illegal integer types.
642Instruction *InstCombiner::FoldPHIArgZextsIntoPHI(PHINode &Phi) {
David Majnemereafa28a2015-11-07 00:52:53 +0000643 // We cannot create a new instruction after the PHI if the terminator is an
644 // EHPad because there is no valid insertion point.
645 if (TerminatorInst *TI = Phi.getParent()->getTerminator())
646 if (TI->isEHPad())
647 return nullptr;
648
Sanjay Patel95334072015-09-27 20:34:31 +0000649 // Early exit for the common case of a phi with two operands. These are
650 // handled elsewhere. See the comment below where we check the count of zexts
651 // and constants for more details.
652 unsigned NumIncomingValues = Phi.getNumIncomingValues();
653 if (NumIncomingValues < 3)
654 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000655
Sanjay Patel95334072015-09-27 20:34:31 +0000656 // Find the narrower type specified by the first zext.
657 Type *NarrowType = nullptr;
658 for (Value *V : Phi.incoming_values()) {
659 if (auto *Zext = dyn_cast<ZExtInst>(V)) {
660 NarrowType = Zext->getSrcTy();
661 break;
662 }
663 }
664 if (!NarrowType)
665 return nullptr;
666
667 // Walk the phi operands checking that we only have zexts or constants that
668 // we can shrink for free. Store the new operands for the new phi.
669 SmallVector<Value *, 4> NewIncoming;
670 unsigned NumZexts = 0;
671 unsigned NumConsts = 0;
672 for (Value *V : Phi.incoming_values()) {
673 if (auto *Zext = dyn_cast<ZExtInst>(V)) {
674 // All zexts must be identical and have one use.
675 if (Zext->getSrcTy() != NarrowType || !Zext->hasOneUse())
676 return nullptr;
677 NewIncoming.push_back(Zext->getOperand(0));
678 NumZexts++;
679 } else if (auto *C = dyn_cast<Constant>(V)) {
680 // Make sure that constants can fit in the new type.
681 Constant *Trunc = ConstantExpr::getTrunc(C, NarrowType);
682 if (ConstantExpr::getZExt(Trunc, C->getType()) != C)
683 return nullptr;
684 NewIncoming.push_back(Trunc);
685 NumConsts++;
686 } else {
687 // If it's not a cast or a constant, bail out.
688 return nullptr;
689 }
690 }
691
692 // The more common cases of a phi with no constant operands or just one
Craig Topperfb71b7d2017-04-14 19:20:12 +0000693 // variable operand are handled by FoldPHIArgOpIntoPHI() and foldOpIntoPhi()
694 // respectively. foldOpIntoPhi() wants to do the opposite transform that is
Sanjay Patel95334072015-09-27 20:34:31 +0000695 // performed here. It tries to replicate a cast in the phi operand's basic
696 // block to expose other folding opportunities. Thus, InstCombine will
697 // infinite loop without this check.
698 if (NumConsts == 0 || NumZexts < 2)
699 return nullptr;
700
701 // All incoming values are zexts or constants that are safe to truncate.
702 // Create a new phi node of the narrow type, phi together all of the new
703 // operands, and zext the result back to the original type.
704 PHINode *NewPhi = PHINode::Create(NarrowType, NumIncomingValues,
705 Phi.getName() + ".shrunk");
706 for (unsigned i = 0; i != NumIncomingValues; ++i)
707 NewPhi->addIncoming(NewIncoming[i], Phi.getIncomingBlock(i));
708
709 InsertNewInstBefore(NewPhi, Phi);
710 return CastInst::CreateZExtOrBitCast(NewPhi, Phi.getType());
711}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000712
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000713/// If all operands to a PHI node are the same "unary" operator and they all are
714/// only used by the PHI, PHI together their inputs, and do the operation once,
715/// to the result of the PHI.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000716Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
David Majnemer27f24472015-11-06 23:59:23 +0000717 // We cannot create a new instruction after the PHI if the terminator is an
718 // EHPad because there is no valid insertion point.
719 if (TerminatorInst *TI = PN.getParent()->getTerminator())
720 if (TI->isEHPad())
721 return nullptr;
722
Chris Lattnerde1fede2010-01-05 05:31:55 +0000723 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
724
725 if (isa<GetElementPtrInst>(FirstInst))
726 return FoldPHIArgGEPIntoPHI(PN);
727 if (isa<LoadInst>(FirstInst))
728 return FoldPHIArgLoadIntoPHI(PN);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000729
Chris Lattnerde1fede2010-01-05 05:31:55 +0000730 // Scan the instruction, looking for input operations that can be folded away.
731 // If all input operands to the phi are the same instruction (e.g. a cast from
732 // the same type or "+42") we can pull the operation through the PHI, reducing
733 // code size and simplifying code.
Craig Topperf40110f2014-04-25 05:29:35 +0000734 Constant *ConstantOp = nullptr;
735 Type *CastSrcTy = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000736
Chris Lattnerde1fede2010-01-05 05:31:55 +0000737 if (isa<CastInst>(FirstInst)) {
738 CastSrcTy = FirstInst->getOperand(0)->getType();
739
740 // Be careful about transforming integer PHIs. We don't want to pessimize
741 // the code by turning an i32 into an i1293.
Duncan Sands19d0b472010-02-16 11:11:14 +0000742 if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
Sanjay Patel2217f752017-01-31 17:25:42 +0000743 if (!shouldChangeType(PN.getType(), CastSrcTy))
Craig Topperf40110f2014-04-25 05:29:35 +0000744 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000745 }
746 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000747 // Can fold binop, compare or shift here if the RHS is a constant,
Chris Lattnerde1fede2010-01-05 05:31:55 +0000748 // otherwise call FoldPHIArgBinOpIntoPHI.
749 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +0000750 if (!ConstantOp)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000751 return FoldPHIArgBinOpIntoPHI(PN);
752 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000753 return nullptr; // Cannot fold this operation.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000754 }
755
756 // Check to see if all arguments are the same operation.
757 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
758 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000759 if (!I || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
760 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000761 if (CastSrcTy) {
762 if (I->getOperand(0)->getType() != CastSrcTy)
Craig Topperf40110f2014-04-25 05:29:35 +0000763 return nullptr; // Cast operation must match.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000764 } else if (I->getOperand(1) != ConstantOp) {
Craig Topperf40110f2014-04-25 05:29:35 +0000765 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000766 }
767 }
768
769 // Okay, they are all the same operation. Create a new PHI node of the
770 // correct type, and PHI together all of the LHS's of the instructions.
771 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
Jay Foad52131342011-03-30 11:28:46 +0000772 PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000773 PN.getName()+".in");
Chris Lattnerde1fede2010-01-05 05:31:55 +0000774
775 Value *InVal = FirstInst->getOperand(0);
776 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
777
778 // Add all operands to the new PHI.
779 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
780 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
781 if (NewInVal != InVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000782 InVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000783 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
784 }
785
786 Value *PhiVal;
787 if (InVal) {
788 // The new PHI unions all of the same values together. This is really
789 // common, so we handle it intelligently here for compile-time speed.
790 PhiVal = InVal;
791 delete NewPN;
792 } else {
793 InsertNewInstBefore(NewPN, PN);
794 PhiVal = NewPN;
795 }
796
797 // Insert and return the new operation.
Eli Friedman35211c62011-05-27 00:19:40 +0000798 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
799 CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
800 PN.getType());
Dehao Chenf4646272017-10-02 18:13:14 +0000801 PHIArgMergedDebugLoc(NewCI, PN);
Eli Friedman35211c62011-05-27 00:19:40 +0000802 return NewCI;
803 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000804
Chris Lattnera8fed472011-02-17 23:01:49 +0000805 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
806 BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Silviu Barangae985c762016-04-22 11:21:36 +0000807 BinOp->copyIRFlags(PN.getIncomingValue(0));
808
809 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i)
810 BinOp->andIRFlags(PN.getIncomingValue(i));
811
Dehao Chenf4646272017-10-02 18:13:14 +0000812 PHIArgMergedDebugLoc(BinOp, PN);
Chris Lattnera8fed472011-02-17 23:01:49 +0000813 return BinOp;
814 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000815
Chris Lattnerde1fede2010-01-05 05:31:55 +0000816 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Eli Friedman35211c62011-05-27 00:19:40 +0000817 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
818 PhiVal, ConstantOp);
Dehao Chenf4646272017-10-02 18:13:14 +0000819 PHIArgMergedDebugLoc(NewCI, PN);
Eli Friedman35211c62011-05-27 00:19:40 +0000820 return NewCI;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000821}
822
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000823/// Return true if this PHI node is only used by a PHI node cycle that is dead.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000824static bool DeadPHICycle(PHINode *PN,
Craig Topper71b7b682014-08-21 05:55:13 +0000825 SmallPtrSetImpl<PHINode*> &PotentiallyDeadPHIs) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000826 if (PN->use_empty()) return true;
827 if (!PN->hasOneUse()) return false;
828
829 // Remember this node, and if we find the cycle, return.
David Blaikie70573dc2014-11-19 07:49:26 +0000830 if (!PotentiallyDeadPHIs.insert(PN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000831 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000832
Chris Lattnerde1fede2010-01-05 05:31:55 +0000833 // Don't scan crazily complex things.
834 if (PotentiallyDeadPHIs.size() == 16)
835 return false;
836
Chandler Carruthcdf47882014-03-09 03:16:01 +0000837 if (PHINode *PU = dyn_cast<PHINode>(PN->user_back()))
Chris Lattnerde1fede2010-01-05 05:31:55 +0000838 return DeadPHICycle(PU, PotentiallyDeadPHIs);
839
840 return false;
841}
842
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000843/// Return true if this phi node is always equal to NonPhiInVal.
844/// This happens with mutually cyclic phi nodes like:
Chris Lattnerde1fede2010-01-05 05:31:55 +0000845/// z = some value; x = phi (y, z); y = phi (x, z)
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000846static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
Craig Topper71b7b682014-08-21 05:55:13 +0000847 SmallPtrSetImpl<PHINode*> &ValueEqualPHIs) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000848 // See if we already saw this PHI node.
David Blaikie70573dc2014-11-19 07:49:26 +0000849 if (!ValueEqualPHIs.insert(PN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000850 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000851
Chris Lattnerde1fede2010-01-05 05:31:55 +0000852 // Don't scan crazily complex things.
853 if (ValueEqualPHIs.size() == 16)
854 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000855
Chris Lattnerde1fede2010-01-05 05:31:55 +0000856 // Scan the operands to see if they are either phi nodes or are equal to
857 // the value.
Pete Cooper833f34d2015-05-12 20:05:31 +0000858 for (Value *Op : PN->incoming_values()) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000859 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
860 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
861 return false;
862 } else if (Op != NonPhiInVal)
863 return false;
864 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000865
Chris Lattnerde1fede2010-01-05 05:31:55 +0000866 return true;
867}
868
Jun Bum Lim10e58e82016-02-11 16:46:13 +0000869/// Return an existing non-zero constant if this phi node has one, otherwise
870/// return constant 1.
Jun Bum Lim339e9722016-02-11 15:50:07 +0000871static ConstantInt *GetAnyNonZeroConstInt(PHINode &PN) {
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +0000872 assert(isa<IntegerType>(PN.getType()) && "Expect only integer type phi");
Jun Bum Lim339e9722016-02-11 15:50:07 +0000873 for (Value *V : PN.operands())
874 if (auto *ConstVA = dyn_cast<ConstantInt>(V))
Craig Topper79ab6432017-07-06 18:39:47 +0000875 if (!ConstVA->isZero())
Jun Bum Lim339e9722016-02-11 15:50:07 +0000876 return ConstVA;
877 return ConstantInt::get(cast<IntegerType>(PN.getType()), 1);
878}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000879
880namespace {
881struct PHIUsageRecord {
882 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
883 unsigned Shift; // The amount shifted.
884 Instruction *Inst; // The trunc instruction.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000885
Chris Lattnerde1fede2010-01-05 05:31:55 +0000886 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
887 : PHIId(pn), Shift(Sh), Inst(User) {}
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000888
Chris Lattnerde1fede2010-01-05 05:31:55 +0000889 bool operator<(const PHIUsageRecord &RHS) const {
890 if (PHIId < RHS.PHIId) return true;
891 if (PHIId > RHS.PHIId) return false;
892 if (Shift < RHS.Shift) return true;
893 if (Shift > RHS.Shift) return false;
894 return Inst->getType()->getPrimitiveSizeInBits() <
895 RHS.Inst->getType()->getPrimitiveSizeInBits();
896 }
897};
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000898
Chris Lattnerde1fede2010-01-05 05:31:55 +0000899struct LoweredPHIRecord {
900 PHINode *PN; // The PHI that was lowered.
901 unsigned Shift; // The amount shifted.
902 unsigned Width; // The width extracted.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000903
Chris Lattner229907c2011-07-18 04:54:35 +0000904 LoweredPHIRecord(PHINode *pn, unsigned Sh, Type *Ty)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000905 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000906
Chris Lattnerde1fede2010-01-05 05:31:55 +0000907 // Ctor form used by DenseMap.
908 LoweredPHIRecord(PHINode *pn, unsigned Sh)
909 : PN(pn), Shift(Sh), Width(0) {}
910};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000911}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000912
913namespace llvm {
914 template<>
915 struct DenseMapInfo<LoweredPHIRecord> {
916 static inline LoweredPHIRecord getEmptyKey() {
Craig Topperf40110f2014-04-25 05:29:35 +0000917 return LoweredPHIRecord(nullptr, 0);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000918 }
919 static inline LoweredPHIRecord getTombstoneKey() {
Craig Topperf40110f2014-04-25 05:29:35 +0000920 return LoweredPHIRecord(nullptr, 1);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000921 }
922 static unsigned getHashValue(const LoweredPHIRecord &Val) {
923 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
924 (Val.Width>>3);
925 }
926 static bool isEqual(const LoweredPHIRecord &LHS,
927 const LoweredPHIRecord &RHS) {
928 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
929 LHS.Width == RHS.Width;
930 }
931 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000932}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000933
934
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000935/// This is an integer PHI and we know that it has an illegal type: see if it is
936/// only used by trunc or trunc(lshr) operations. If so, we split the PHI into
937/// the various pieces being extracted. This sort of thing is introduced when
938/// SROA promotes an aggregate to large integer values.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000939///
940/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
941/// inttoptr. We should produce new PHIs in the right type.
942///
943Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
944 // PHIUsers - Keep track of all of the truncated values extracted from a set
945 // of PHIs, along with their offset. These are the things we want to rewrite.
946 SmallVector<PHIUsageRecord, 16> PHIUsers;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000947
Chris Lattnerde1fede2010-01-05 05:31:55 +0000948 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
949 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
950 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
951 // check the uses of (to ensure they are all extracts).
952 SmallVector<PHINode*, 8> PHIsToSlice;
953 SmallPtrSet<PHINode*, 8> PHIsInspected;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000954
Chris Lattnerde1fede2010-01-05 05:31:55 +0000955 PHIsToSlice.push_back(&FirstPhi);
956 PHIsInspected.insert(&FirstPhi);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000957
Chris Lattnerde1fede2010-01-05 05:31:55 +0000958 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
959 PHINode *PN = PHIsToSlice[PHIId];
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000960
Chris Lattnerde1fede2010-01-05 05:31:55 +0000961 // Scan the input list of the PHI. If any input is an invoke, and if the
962 // input is defined in the predecessor, then we won't be split the critical
963 // edge which is required to insert a truncate. Because of this, we have to
964 // bail out.
965 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
966 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000967 if (!II) continue;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000968 if (II->getParent() != PN->getIncomingBlock(i))
969 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000970
Chris Lattnerde1fede2010-01-05 05:31:55 +0000971 // If we have a phi, and if it's directly in the predecessor, then we have
972 // a critical edge where we need to put the truncate. Since we can't
973 // split the edge in instcombine, we have to bail out.
Craig Topperf40110f2014-04-25 05:29:35 +0000974 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000975 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000976
Chandler Carruthcdf47882014-03-09 03:16:01 +0000977 for (User *U : PN->users()) {
978 Instruction *UserI = cast<Instruction>(U);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000979
Chris Lattnerde1fede2010-01-05 05:31:55 +0000980 // If the user is a PHI, inspect its uses recursively.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000981 if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
David Blaikie70573dc2014-11-19 07:49:26 +0000982 if (PHIsInspected.insert(UserPN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000983 PHIsToSlice.push_back(UserPN);
984 continue;
985 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000986
Chris Lattnerde1fede2010-01-05 05:31:55 +0000987 // Truncates are always ok.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000988 if (isa<TruncInst>(UserI)) {
989 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
Chris Lattnerde1fede2010-01-05 05:31:55 +0000990 continue;
991 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000992
Chris Lattnerde1fede2010-01-05 05:31:55 +0000993 // Otherwise it must be a lshr which can only be used by one trunc.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000994 if (UserI->getOpcode() != Instruction::LShr ||
995 !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
996 !isa<ConstantInt>(UserI->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000997 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000998
Chandler Carruthcdf47882014-03-09 03:16:01 +0000999 unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
1000 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
Chris Lattnerde1fede2010-01-05 05:31:55 +00001001 }
1002 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001003
Chris Lattnerde1fede2010-01-05 05:31:55 +00001004 // If we have no users, they must be all self uses, just nuke the PHI.
1005 if (PHIUsers.empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00001006 return replaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001007
Chris Lattnerde1fede2010-01-05 05:31:55 +00001008 // If this phi node is transformable, create new PHIs for all the pieces
1009 // extracted out of it. First, sort the users by their offset and size.
1010 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001011
Matt Arsenaulte6db7602013-09-05 19:48:28 +00001012 DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
1013 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
1014 dbgs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] << '\n';
1015 );
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001016
Chris Lattnerde1fede2010-01-05 05:31:55 +00001017 // PredValues - This is a temporary used when rewriting PHI nodes. It is
1018 // hoisted out here to avoid construction/destruction thrashing.
1019 DenseMap<BasicBlock*, Value*> PredValues;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001020
Chris Lattnerde1fede2010-01-05 05:31:55 +00001021 // ExtractedVals - Each new PHI we introduce is saved here so we don't
1022 // introduce redundant PHIs.
1023 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001024
Chris Lattnerde1fede2010-01-05 05:31:55 +00001025 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
1026 unsigned PHIId = PHIUsers[UserI].PHIId;
1027 PHINode *PN = PHIsToSlice[PHIId];
1028 unsigned Offset = PHIUsers[UserI].Shift;
Chris Lattner229907c2011-07-18 04:54:35 +00001029 Type *Ty = PHIUsers[UserI].Inst->getType();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001030
Chris Lattnerde1fede2010-01-05 05:31:55 +00001031 PHINode *EltPHI;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001032
Chris Lattnerde1fede2010-01-05 05:31:55 +00001033 // If we've already lowered a user like this, reuse the previously lowered
1034 // value.
Craig Topperf40110f2014-04-25 05:29:35 +00001035 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001036
Chris Lattnerde1fede2010-01-05 05:31:55 +00001037 // Otherwise, Create the new PHI node for this user.
Jay Foad52131342011-03-30 11:28:46 +00001038 EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
1039 PN->getName()+".off"+Twine(Offset), PN);
Chris Lattnerde1fede2010-01-05 05:31:55 +00001040 assert(EltPHI->getType() != PN->getType() &&
1041 "Truncate didn't shrink phi?");
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001042
Chris Lattnerde1fede2010-01-05 05:31:55 +00001043 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1044 BasicBlock *Pred = PN->getIncomingBlock(i);
1045 Value *&PredVal = PredValues[Pred];
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001046
Chris Lattnerde1fede2010-01-05 05:31:55 +00001047 // If we already have a value for this predecessor, reuse it.
1048 if (PredVal) {
1049 EltPHI->addIncoming(PredVal, Pred);
1050 continue;
1051 }
1052
1053 // Handle the PHI self-reuse case.
1054 Value *InVal = PN->getIncomingValue(i);
1055 if (InVal == PN) {
1056 PredVal = EltPHI;
1057 EltPHI->addIncoming(PredVal, Pred);
1058 continue;
1059 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001060
Chris Lattnerde1fede2010-01-05 05:31:55 +00001061 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
1062 // If the incoming value was a PHI, and if it was one of the PHIs we
1063 // already rewrote it, just use the lowered value.
1064 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
1065 PredVal = Res;
1066 EltPHI->addIncoming(PredVal, Pred);
1067 continue;
1068 }
1069 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001070
Chris Lattnerde1fede2010-01-05 05:31:55 +00001071 // Otherwise, do an extract in the predecessor.
Craig Topperbb4069e2017-07-07 23:16:26 +00001072 Builder.SetInsertPoint(Pred->getTerminator());
Chris Lattnerde1fede2010-01-05 05:31:55 +00001073 Value *Res = InVal;
1074 if (Offset)
Craig Topperbb4069e2017-07-07 23:16:26 +00001075 Res = Builder.CreateLShr(Res, ConstantInt::get(InVal->getType(),
Chris Lattnerde1fede2010-01-05 05:31:55 +00001076 Offset), "extract");
Craig Topperbb4069e2017-07-07 23:16:26 +00001077 Res = Builder.CreateTrunc(Res, Ty, "extract.t");
Chris Lattnerde1fede2010-01-05 05:31:55 +00001078 PredVal = Res;
1079 EltPHI->addIncoming(Res, Pred);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001080
Chris Lattnerde1fede2010-01-05 05:31:55 +00001081 // If the incoming value was a PHI, and if it was one of the PHIs we are
1082 // rewriting, we will ultimately delete the code we inserted. This
1083 // means we need to revisit that PHI to make sure we extract out the
1084 // needed piece.
1085 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
1086 if (PHIsInspected.count(OldInVal)) {
David Majnemer42531262016-08-12 03:55:06 +00001087 unsigned RefPHIId =
1088 find(PHIsToSlice, OldInVal) - PHIsToSlice.begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001089 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
Chris Lattnerde1fede2010-01-05 05:31:55 +00001090 cast<Instruction>(Res)));
1091 ++UserE;
1092 }
1093 }
1094 PredValues.clear();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001095
Matt Arsenaulte6db7602013-09-05 19:48:28 +00001096 DEBUG(dbgs() << " Made element PHI for offset " << Offset << ": "
Chris Lattnerde1fede2010-01-05 05:31:55 +00001097 << *EltPHI << '\n');
1098 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
1099 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001100
Chris Lattnerde1fede2010-01-05 05:31:55 +00001101 // Replace the use of this piece with the PHI node.
Sanjay Patel4b198802016-02-01 22:23:39 +00001102 replaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattnerde1fede2010-01-05 05:31:55 +00001103 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001104
Chris Lattnerde1fede2010-01-05 05:31:55 +00001105 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
1106 // with undefs.
1107 Value *Undef = UndefValue::get(FirstPhi.getType());
1108 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
Sanjay Patel4b198802016-02-01 22:23:39 +00001109 replaceInstUsesWith(*PHIsToSlice[i], Undef);
1110 return replaceInstUsesWith(FirstPhi, Undef);
Chris Lattnerde1fede2010-01-05 05:31:55 +00001111}
1112
1113// PHINode simplification
1114//
1115Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Craig Toppera4205622017-06-09 03:21:29 +00001116 if (Value *V = SimplifyInstruction(&PN, SQ.getWithInstruction(&PN)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001117 return replaceInstUsesWith(PN, V);
Chris Lattnerde1fede2010-01-05 05:31:55 +00001118
Sanjay Patel95334072015-09-27 20:34:31 +00001119 if (Instruction *Result = FoldPHIArgZextsIntoPHI(PN))
1120 return Result;
1121
Chris Lattnerde1fede2010-01-05 05:31:55 +00001122 // If all PHI operands are the same operation, pull them through the PHI,
1123 // reducing code size.
1124 if (isa<Instruction>(PN.getIncomingValue(0)) &&
1125 isa<Instruction>(PN.getIncomingValue(1)) &&
1126 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
1127 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
1128 // FIXME: The hasOneUse check will fail for PHIs that use the value more
1129 // than themselves more than once.
1130 PN.getIncomingValue(0)->hasOneUse())
1131 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
1132 return Result;
1133
1134 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
1135 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
1136 // PHI)... break the cycle.
1137 if (PN.hasOneUse()) {
Xinliang David Li4cdc9da2017-10-10 05:07:54 +00001138 if (Instruction *Result = FoldIntegerTypedPHI(PN))
1139 return Result;
1140
Chandler Carruthcdf47882014-03-09 03:16:01 +00001141 Instruction *PHIUser = cast<Instruction>(PN.user_back());
Chris Lattnerde1fede2010-01-05 05:31:55 +00001142 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
1143 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
1144 PotentiallyDeadPHIs.insert(&PN);
1145 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Sanjay Patel4b198802016-02-01 22:23:39 +00001146 return replaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerde1fede2010-01-05 05:31:55 +00001147 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001148
Chris Lattnerde1fede2010-01-05 05:31:55 +00001149 // If this phi has a single use, and if that use just computes a value for
1150 // the next iteration of a loop, delete the phi. This occurs with unused
1151 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
1152 // common case here is good because the only other things that catch this
1153 // are induction variable analysis (sometimes) and ADCE, which is only run
1154 // late.
1155 if (PHIUser->hasOneUse() &&
1156 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00001157 PHIUser->user_back() == &PN) {
Sanjay Patel4b198802016-02-01 22:23:39 +00001158 return replaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerde1fede2010-01-05 05:31:55 +00001159 }
Jun Bum Lim339e9722016-02-11 15:50:07 +00001160 // When a PHI is used only to be compared with zero, it is safe to replace
1161 // an incoming value proved as known nonzero with any non-zero constant.
Jun Bum Lim10e58e82016-02-11 16:46:13 +00001162 // For example, in the code below, the incoming value %v can be replaced
1163 // with any non-zero constant based on the fact that the PHI is only used to
1164 // be compared with zero and %v is a known non-zero value:
Jun Bum Lim339e9722016-02-11 15:50:07 +00001165 // %v = select %cond, 1, 2
1166 // %p = phi [%v, BB] ...
1167 // icmp eq, %p, 0
1168 auto *CmpInst = dyn_cast<ICmpInst>(PHIUser);
1169 // FIXME: To be simple, handle only integer type for now.
1170 if (CmpInst && isa<IntegerType>(PN.getType()) && CmpInst->isEquality() &&
1171 match(CmpInst->getOperand(1), m_Zero())) {
1172 ConstantInt *NonZeroConst = nullptr;
1173 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1174 Instruction *CtxI = PN.getIncomingBlock(i)->getTerminator();
1175 Value *VA = PN.getIncomingValue(i);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001176 if (isKnownNonZero(VA, DL, 0, &AC, CtxI, &DT)) {
Jun Bum Lim339e9722016-02-11 15:50:07 +00001177 if (!NonZeroConst)
1178 NonZeroConst = GetAnyNonZeroConstInt(PN);
1179 PN.setIncomingValue(i, NonZeroConst);
1180 }
1181 }
1182 }
Chris Lattnerde1fede2010-01-05 05:31:55 +00001183 }
1184
1185 // We sometimes end up with phi cycles that non-obviously end up being the
1186 // same value, for example:
1187 // z = some value; x = phi (y, z); y = phi (x, z)
1188 // where the phi nodes don't necessarily need to be in the same block. Do a
1189 // quick check to see if the PHI node only contains a single non-phi value, if
1190 // so, scan to see if the phi cycle is actually equal to that value.
1191 {
Frits van Bommeld6d4f982011-04-16 14:32:34 +00001192 unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
Chris Lattnerde1fede2010-01-05 05:31:55 +00001193 // Scan for the first non-phi operand.
Frits van Bommeld6d4f982011-04-16 14:32:34 +00001194 while (InValNo != NumIncomingVals &&
Chris Lattnerde1fede2010-01-05 05:31:55 +00001195 isa<PHINode>(PN.getIncomingValue(InValNo)))
1196 ++InValNo;
1197
Frits van Bommeld6d4f982011-04-16 14:32:34 +00001198 if (InValNo != NumIncomingVals) {
Jay Foad7d03e9b2011-04-16 14:17:37 +00001199 Value *NonPhiInVal = PN.getIncomingValue(InValNo);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001200
Chris Lattnerde1fede2010-01-05 05:31:55 +00001201 // Scan the rest of the operands to see if there are any conflicts, if so
1202 // there is no need to recursively scan other phis.
Frits van Bommeld6d4f982011-04-16 14:32:34 +00001203 for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
Chris Lattnerde1fede2010-01-05 05:31:55 +00001204 Value *OpVal = PN.getIncomingValue(InValNo);
1205 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
1206 break;
1207 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001208
Chris Lattnerde1fede2010-01-05 05:31:55 +00001209 // If we scanned over all operands, then we have one unique value plus
1210 // phi values. Scan PHI nodes to see if they all merge in each other or
1211 // the value.
Frits van Bommeld6d4f982011-04-16 14:32:34 +00001212 if (InValNo == NumIncomingVals) {
Chris Lattnerde1fede2010-01-05 05:31:55 +00001213 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
1214 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
Sanjay Patel4b198802016-02-01 22:23:39 +00001215 return replaceInstUsesWith(PN, NonPhiInVal);
Chris Lattnerde1fede2010-01-05 05:31:55 +00001216 }
1217 }
1218 }
1219
1220 // If there are multiple PHIs, sort their operands so that they all list
1221 // the blocks in the same order. This will help identical PHIs be eliminated
1222 // by other passes. Other passes shouldn't depend on this for correctness
1223 // however.
1224 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
1225 if (&PN != FirstPN)
1226 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
1227 BasicBlock *BBA = PN.getIncomingBlock(i);
1228 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
1229 if (BBA != BBB) {
1230 Value *VA = PN.getIncomingValue(i);
1231 unsigned j = PN.getBasicBlockIndex(BBB);
1232 Value *VB = PN.getIncomingValue(j);
1233 PN.setIncomingBlock(i, BBB);
1234 PN.setIncomingValue(i, VB);
1235 PN.setIncomingBlock(j, BBA);
1236 PN.setIncomingValue(j, VA);
1237 // NOTE: Instcombine normally would want us to "return &PN" if we
1238 // modified any of the operands of an instruction. However, since we
1239 // aren't adding or removing uses (just rearranging them) we don't do
1240 // this in this case.
1241 }
1242 }
1243
1244 // If this is an integer PHI and we know that it has an illegal type, see if
1245 // it is only used by trunc or trunc(lshr) operations. If so, we split the
1246 // PHI into the various pieces being extracted. This sort of thing is
1247 // introduced when SROA promotes an aggregate to a single large integer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001248 if (PN.getType()->isIntegerTy() &&
1249 !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
Chris Lattnerde1fede2010-01-05 05:31:55 +00001250 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
1251 return Res;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001252
Craig Topperf40110f2014-04-25 05:29:35 +00001253 return nullptr;
Benjamin Kramerf7cc6982010-01-05 13:32:48 +00001254}