blob: 0827a34006cab3623d169cdd7026928d9828463f [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"
David Blaikie2be39222018-03-21 22:34:23 +000018#include "llvm/Analysis/Utils/Local.h"
Jun Bum Lim339e9722016-02-11 15:50:07 +000019#include "llvm/Analysis/ValueTracking.h"
20#include "llvm/IR/PatternMatch.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
Robert Lougher2428a402016-12-14 17:49:19 +000026/// The PHI arguments will be folded into a single operation with a PHI node
27/// as input. The debug location of the single operation will be the merged
28/// locations of the original PHI node arguments.
Dehao Chenf4646272017-10-02 18:13:14 +000029void InstCombiner::PHIArgMergedDebugLoc(Instruction *Inst, PHINode &PN) {
Robert Lougher2428a402016-12-14 17:49:19 +000030 auto *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Dehao Chenf4646272017-10-02 18:13:14 +000031 Inst->setDebugLoc(FirstInst->getDebugLoc());
32 // We do not expect a CallInst here, otherwise, N-way merging of DebugLoc
33 // will be inefficient.
34 assert(!isa<CallInst>(Inst));
Robert Lougher2428a402016-12-14 17:49:19 +000035
36 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
37 auto *I = cast<Instruction>(PN.getIncomingValue(i));
Dehao Chenf4646272017-10-02 18:13:14 +000038 Inst->applyMergedLocation(Inst->getDebugLoc(), I->getDebugLoc());
Robert Lougher2428a402016-12-14 17:49:19 +000039 }
Robert Lougher2428a402016-12-14 17:49:19 +000040}
41
Xinliang David Li4cdc9da2017-10-10 05:07:54 +000042// Replace Integer typed PHI PN if the PHI's value is used as a pointer value.
43// If there is an existing pointer typed PHI that produces the same value as PN,
44// replace PN and the IntToPtr operation with it. Otherwise, synthesize a new
45// PHI node:
46//
47// Case-1:
48// bb1:
49// int_init = PtrToInt(ptr_init)
50// br label %bb2
51// bb2:
52// int_val = PHI([int_init, %bb1], [int_val_inc, %bb2]
53// ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
54// ptr_val2 = IntToPtr(int_val)
55// ...
56// use(ptr_val2)
57// ptr_val_inc = ...
58// inc_val_inc = PtrToInt(ptr_val_inc)
59//
60// ==>
61// bb1:
62// br label %bb2
63// bb2:
64// ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
65// ...
66// use(ptr_val)
67// ptr_val_inc = ...
68//
69// Case-2:
70// bb1:
71// int_ptr = BitCast(ptr_ptr)
72// int_init = Load(int_ptr)
73// br label %bb2
74// bb2:
75// int_val = PHI([int_init, %bb1], [int_val_inc, %bb2]
76// ptr_val2 = IntToPtr(int_val)
77// ...
78// use(ptr_val2)
79// ptr_val_inc = ...
80// inc_val_inc = PtrToInt(ptr_val_inc)
81// ==>
82// bb1:
83// ptr_init = Load(ptr_ptr)
84// br label %bb2
85// bb2:
86// ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
87// ...
88// use(ptr_val)
89// ptr_val_inc = ...
90// ...
91//
92Instruction *InstCombiner::FoldIntegerTypedPHI(PHINode &PN) {
93 if (!PN.getType()->isIntegerTy())
94 return nullptr;
95 if (!PN.hasOneUse())
96 return nullptr;
97
98 auto *IntToPtr = dyn_cast<IntToPtrInst>(PN.user_back());
99 if (!IntToPtr)
100 return nullptr;
101
102 // Check if the pointer is actually used as pointer:
103 auto HasPointerUse = [](Instruction *IIP) {
104 for (User *U : IIP->users()) {
105 Value *Ptr = nullptr;
106 if (LoadInst *LoadI = dyn_cast<LoadInst>(U)) {
107 Ptr = LoadI->getPointerOperand();
108 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
109 Ptr = SI->getPointerOperand();
110 } else if (GetElementPtrInst *GI = dyn_cast<GetElementPtrInst>(U)) {
111 Ptr = GI->getPointerOperand();
112 }
113
114 if (Ptr && Ptr == IIP)
115 return true;
116 }
117 return false;
118 };
119
120 if (!HasPointerUse(IntToPtr))
121 return nullptr;
122
123 if (DL.getPointerSizeInBits(IntToPtr->getAddressSpace()) !=
124 DL.getTypeSizeInBits(IntToPtr->getOperand(0)->getType()))
125 return nullptr;
126
127 SmallVector<Value *, 4> AvailablePtrVals;
128 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
129 Value *Arg = PN.getIncomingValue(i);
130
131 // First look backward:
132 if (auto *PI = dyn_cast<PtrToIntInst>(Arg)) {
133 AvailablePtrVals.emplace_back(PI->getOperand(0));
134 continue;
135 }
136
137 // Next look forward:
138 Value *ArgIntToPtr = nullptr;
139 for (User *U : Arg->users()) {
140 if (isa<IntToPtrInst>(U) && U->getType() == IntToPtr->getType() &&
141 (DT.dominates(cast<Instruction>(U), PN.getIncomingBlock(i)) ||
142 cast<Instruction>(U)->getParent() == PN.getIncomingBlock(i))) {
143 ArgIntToPtr = U;
144 break;
145 }
146 }
147
148 if (ArgIntToPtr) {
149 AvailablePtrVals.emplace_back(ArgIntToPtr);
150 continue;
151 }
152
153 // If Arg is defined by a PHI, allow it. This will also create
154 // more opportunities iteratively.
155 if (isa<PHINode>(Arg)) {
156 AvailablePtrVals.emplace_back(Arg);
157 continue;
158 }
159
160 // For a single use integer load:
161 auto *LoadI = dyn_cast<LoadInst>(Arg);
162 if (!LoadI)
163 return nullptr;
164
165 if (!LoadI->hasOneUse())
166 return nullptr;
167
168 // Push the integer typed Load instruction into the available
169 // value set, and fix it up later when the pointer typed PHI
170 // is synthesized.
171 AvailablePtrVals.emplace_back(LoadI);
172 }
173
174 // Now search for a matching PHI
175 auto *BB = PN.getParent();
176 assert(AvailablePtrVals.size() == PN.getNumIncomingValues() &&
177 "Not enough available ptr typed incoming values");
178 PHINode *MatchingPtrPHI = nullptr;
179 for (auto II = BB->begin(), EI = BasicBlock::iterator(BB->getFirstNonPHI());
180 II != EI; II++) {
181 PHINode *PtrPHI = dyn_cast<PHINode>(II);
182 if (!PtrPHI || PtrPHI == &PN || PtrPHI->getType() != IntToPtr->getType())
183 continue;
184 MatchingPtrPHI = PtrPHI;
185 for (unsigned i = 0; i != PtrPHI->getNumIncomingValues(); ++i) {
186 if (AvailablePtrVals[i] !=
187 PtrPHI->getIncomingValueForBlock(PN.getIncomingBlock(i))) {
188 MatchingPtrPHI = nullptr;
189 break;
190 }
191 }
192
193 if (MatchingPtrPHI)
194 break;
195 }
196
197 if (MatchingPtrPHI) {
198 assert(MatchingPtrPHI->getType() == IntToPtr->getType() &&
199 "Phi's Type does not match with IntToPtr");
200 // The PtrToCast + IntToPtr will be simplified later
201 return CastInst::CreateBitOrPointerCast(MatchingPtrPHI,
202 IntToPtr->getOperand(0)->getType());
203 }
204
205 // If it requires a conversion for every PHI operand, do not do it.
206 if (std::all_of(AvailablePtrVals.begin(), AvailablePtrVals.end(),
207 [&](Value *V) {
208 return (V->getType() != IntToPtr->getType()) ||
209 isa<IntToPtrInst>(V);
210 }))
211 return nullptr;
212
213 // If any of the operand that requires casting is a terminator
214 // instruction, do not do it.
215 if (std::any_of(AvailablePtrVals.begin(), AvailablePtrVals.end(),
216 [&](Value *V) {
217 return (V->getType() != IntToPtr->getType()) &&
218 isa<TerminatorInst>(V);
219 }))
220 return nullptr;
221
222 PHINode *NewPtrPHI = PHINode::Create(
223 IntToPtr->getType(), PN.getNumIncomingValues(), PN.getName() + ".ptr");
224
225 InsertNewInstBefore(NewPtrPHI, PN);
226 SmallDenseMap<Value *, Instruction *> Casts;
227 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
228 auto *IncomingBB = PN.getIncomingBlock(i);
229 auto *IncomingVal = AvailablePtrVals[i];
230
231 if (IncomingVal->getType() == IntToPtr->getType()) {
232 NewPtrPHI->addIncoming(IncomingVal, IncomingBB);
233 continue;
234 }
235
236#ifndef NDEBUG
237 LoadInst *LoadI = dyn_cast<LoadInst>(IncomingVal);
238 assert((isa<PHINode>(IncomingVal) ||
239 IncomingVal->getType()->isPointerTy() ||
240 (LoadI && LoadI->hasOneUse())) &&
241 "Can not replace LoadInst with multiple uses");
242#endif
243 // Need to insert a BitCast.
244 // For an integer Load instruction with a single use, the load + IntToPtr
245 // cast will be simplified into a pointer load:
246 // %v = load i64, i64* %a.ip, align 8
247 // %v.cast = inttoptr i64 %v to float **
248 // ==>
249 // %v.ptrp = bitcast i64 * %a.ip to float **
250 // %v.cast = load float *, float ** %v.ptrp, align 8
251 Instruction *&CI = Casts[IncomingVal];
252 if (!CI) {
253 CI = CastInst::CreateBitOrPointerCast(IncomingVal, IntToPtr->getType(),
254 IncomingVal->getName() + ".ptr");
255 if (auto *IncomingI = dyn_cast<Instruction>(IncomingVal)) {
256 BasicBlock::iterator InsertPos(IncomingI);
257 InsertPos++;
258 if (isa<PHINode>(IncomingI))
259 InsertPos = IncomingI->getParent()->getFirstInsertionPt();
260 InsertNewInstBefore(CI, *InsertPos);
261 } else {
262 auto *InsertBB = &IncomingBB->getParent()->getEntryBlock();
263 InsertNewInstBefore(CI, *InsertBB->getFirstInsertionPt());
264 }
265 }
266 NewPtrPHI->addIncoming(CI, IncomingBB);
267 }
268
269 // The PtrToCast + IntToPtr will be simplified later
270 return CastInst::CreateBitOrPointerCast(NewPtrPHI,
271 IntToPtr->getOperand(0)->getType());
272}
273
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000274/// If we have something like phi [add (a,b), add(a,c)] and if a/b/c and the
275/// adds all have a single use, turn this into a phi and a single binop.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000276Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
277 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
278 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
279 unsigned Opc = FirstInst->getOpcode();
280 Value *LHSVal = FirstInst->getOperand(0);
281 Value *RHSVal = FirstInst->getOperand(1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000282
Chris Lattner229907c2011-07-18 04:54:35 +0000283 Type *LHSType = LHSVal->getType();
284 Type *RHSType = RHSVal->getType();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000285
Chris Lattnerde1fede2010-01-05 05:31:55 +0000286 // Scan to see if all operands are the same opcode, and all have one use.
287 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
288 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
289 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
290 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnera8fed472011-02-17 23:01:49 +0000291 // types.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000292 I->getOperand(0)->getType() != LHSType ||
293 I->getOperand(1)->getType() != RHSType)
Craig Topperf40110f2014-04-25 05:29:35 +0000294 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000295
296 // If they are CmpInst instructions, check their predicates
Chris Lattnera8fed472011-02-17 23:01:49 +0000297 if (CmpInst *CI = dyn_cast<CmpInst>(I))
298 if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
Craig Topperf40110f2014-04-25 05:29:35 +0000299 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000300
Chris Lattnerde1fede2010-01-05 05:31:55 +0000301 // Keep track of which operand needs a phi node.
Craig Topperf40110f2014-04-25 05:29:35 +0000302 if (I->getOperand(0) != LHSVal) LHSVal = nullptr;
303 if (I->getOperand(1) != RHSVal) RHSVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000304 }
305
306 // If both LHS and RHS would need a PHI, don't do this transformation,
307 // because it would increase the number of PHIs entering the block,
308 // which leads to higher register pressure. This is especially
309 // bad when the PHIs are in the header of a loop.
310 if (!LHSVal && !RHSVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000311 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000312
Chris Lattnerde1fede2010-01-05 05:31:55 +0000313 // Otherwise, this is safe to transform!
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000314
Chris Lattnerde1fede2010-01-05 05:31:55 +0000315 Value *InLHS = FirstInst->getOperand(0);
316 Value *InRHS = FirstInst->getOperand(1);
Craig Topperf40110f2014-04-25 05:29:35 +0000317 PHINode *NewLHS = nullptr, *NewRHS = nullptr;
318 if (!LHSVal) {
Jay Foad52131342011-03-30 11:28:46 +0000319 NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000320 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerde1fede2010-01-05 05:31:55 +0000321 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
322 InsertNewInstBefore(NewLHS, PN);
323 LHSVal = NewLHS;
324 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000325
Craig Topperf40110f2014-04-25 05:29:35 +0000326 if (!RHSVal) {
Jay Foad52131342011-03-30 11:28:46 +0000327 NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000328 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerde1fede2010-01-05 05:31:55 +0000329 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
330 InsertNewInstBefore(NewRHS, PN);
331 RHSVal = NewRHS;
332 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000333
Chris Lattnerde1fede2010-01-05 05:31:55 +0000334 // Add all operands to the new PHIs.
335 if (NewLHS || NewRHS) {
336 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
337 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
338 if (NewLHS) {
339 Value *NewInLHS = InInst->getOperand(0);
340 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
341 }
342 if (NewRHS) {
343 Value *NewInRHS = InInst->getOperand(1);
344 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
345 }
346 }
347 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000348
Eli Friedman35211c62011-05-27 00:19:40 +0000349 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
350 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
351 LHSVal, RHSVal);
Dehao Chenf4646272017-10-02 18:13:14 +0000352 PHIArgMergedDebugLoc(NewCI, PN);
Eli Friedman35211c62011-05-27 00:19:40 +0000353 return NewCI;
354 }
355
Chris Lattnera8fed472011-02-17 23:01:49 +0000356 BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
357 BinaryOperator *NewBinOp =
358 BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Silviu Barangae985c762016-04-22 11:21:36 +0000359
360 NewBinOp->copyIRFlags(PN.getIncomingValue(0));
361
362 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i)
363 NewBinOp->andIRFlags(PN.getIncomingValue(i));
364
Dehao Chenf4646272017-10-02 18:13:14 +0000365 PHIArgMergedDebugLoc(NewBinOp, PN);
Chris Lattnera8fed472011-02-17 23:01:49 +0000366 return NewBinOp;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000367}
368
369Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
370 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000371
372 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000373 FirstInst->op_end());
374 // This is true if all GEP bases are allocas and if all indices into them are
375 // constants.
376 bool AllBasePointersAreAllocas = true;
377
378 // We don't want to replace this phi if the replacement would require
379 // more than one phi, which leads to higher register pressure. This is
380 // especially bad when the PHIs are in the header of a loop.
381 bool NeededPhi = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000382
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000383 bool AllInBounds = true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000384
Chris Lattnerde1fede2010-01-05 05:31:55 +0000385 // Scan to see if all operands are the same opcode, and all have one use.
386 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
387 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
388 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
389 GEP->getNumOperands() != FirstInst->getNumOperands())
Craig Topperf40110f2014-04-25 05:29:35 +0000390 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000391
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000392 AllInBounds &= GEP->isInBounds();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000393
Chris Lattnerde1fede2010-01-05 05:31:55 +0000394 // Keep track of whether or not all GEPs are of alloca pointers.
395 if (AllBasePointersAreAllocas &&
396 (!isa<AllocaInst>(GEP->getOperand(0)) ||
397 !GEP->hasAllConstantIndices()))
398 AllBasePointersAreAllocas = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000399
Chris Lattnerde1fede2010-01-05 05:31:55 +0000400 // Compare the operand lists.
401 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
402 if (FirstInst->getOperand(op) == GEP->getOperand(op))
403 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000404
Chris Lattnerde1fede2010-01-05 05:31:55 +0000405 // Don't merge two GEPs when two operands differ (introducing phi nodes)
406 // if one of the PHIs has a constant for the index. The index may be
407 // substantially cheaper to compute for the constants, so making it a
408 // variable index could pessimize the path. This also handles the case
409 // for struct indices, which must always be constant.
410 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
411 isa<ConstantInt>(GEP->getOperand(op)))
Craig Topperf40110f2014-04-25 05:29:35 +0000412 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000413
Chris Lattnerde1fede2010-01-05 05:31:55 +0000414 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +0000415 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000416
417 // If we already needed a PHI for an earlier operand, and another operand
418 // also requires a PHI, we'd be introducing more PHIs than we're
419 // eliminating, which increases register pressure on entry to the PHI's
420 // block.
421 if (NeededPhi)
Craig Topperf40110f2014-04-25 05:29:35 +0000422 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000423
Craig Topperf40110f2014-04-25 05:29:35 +0000424 FixedOperands[op] = nullptr; // Needs a PHI.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000425 NeededPhi = true;
426 }
427 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000428
Chris Lattnerde1fede2010-01-05 05:31:55 +0000429 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
430 // bother doing this transformation. At best, this will just save a bit of
431 // offset calculation, but all the predecessors will have to materialize the
432 // stack address into a register anyway. We'd actually rather *clone* the
433 // load up into the predecessors so that we have a load of a gep of an alloca,
434 // which can usually all be folded into the load.
435 if (AllBasePointersAreAllocas)
Craig Topperf40110f2014-04-25 05:29:35 +0000436 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000437
Chris Lattnerde1fede2010-01-05 05:31:55 +0000438 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
439 // that is variable.
440 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000441
Chris Lattnerde1fede2010-01-05 05:31:55 +0000442 bool HasAnyPHIs = false;
443 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
444 if (FixedOperands[i]) continue; // operand doesn't need a phi.
445 Value *FirstOp = FirstInst->getOperand(i);
Jay Foad52131342011-03-30 11:28:46 +0000446 PHINode *NewPN = PHINode::Create(FirstOp->getType(), e,
Chris Lattnerde1fede2010-01-05 05:31:55 +0000447 FirstOp->getName()+".pn");
448 InsertNewInstBefore(NewPN, PN);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000449
Chris Lattnerde1fede2010-01-05 05:31:55 +0000450 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
451 OperandPhis[i] = NewPN;
452 FixedOperands[i] = NewPN;
453 HasAnyPHIs = true;
454 }
455
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000456
Chris Lattnerde1fede2010-01-05 05:31:55 +0000457 // Add all operands to the new PHIs.
458 if (HasAnyPHIs) {
459 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
460 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
461 BasicBlock *InBB = PN.getIncomingBlock(i);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000462
Chris Lattnerde1fede2010-01-05 05:31:55 +0000463 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
464 if (PHINode *OpPhi = OperandPhis[op])
465 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
466 }
467 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000468
Chris Lattnerde1fede2010-01-05 05:31:55 +0000469 Value *Base = FixedOperands[0];
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000470 GetElementPtrInst *NewGEP =
David Blaikie741c8f82015-03-14 01:53:18 +0000471 GetElementPtrInst::Create(FirstInst->getSourceElementType(), Base,
472 makeArrayRef(FixedOperands).slice(1));
Chris Lattner75ae5a42011-02-17 22:32:54 +0000473 if (AllInBounds) NewGEP->setIsInBounds();
Dehao Chenf4646272017-10-02 18:13:14 +0000474 PHIArgMergedDebugLoc(NewGEP, PN);
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000475 return NewGEP;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000476}
477
478
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000479/// Return true if we know that it is safe to sink the load out of the block
480/// that defines it. This means that it must be obvious the value of the load is
481/// not changed from the point of the load to the end of the block it is in.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000482///
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000483/// Finally, it is safe, but not profitable, to sink a load targeting a
Chris Lattnerde1fede2010-01-05 05:31:55 +0000484/// non-address-taken alloca. Doing so will cause us to not promote the alloca
485/// to a register.
486static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000487 BasicBlock::iterator BBI = L->getIterator(), E = L->getParent()->end();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000488
Chris Lattnerde1fede2010-01-05 05:31:55 +0000489 for (++BBI; BBI != E; ++BBI)
490 if (BBI->mayWriteToMemory())
491 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000492
Chris Lattnerde1fede2010-01-05 05:31:55 +0000493 // Check for non-address taken alloca. If not address-taken already, it isn't
494 // profitable to do this xform.
495 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
496 bool isAddressTaken = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000497 for (User *U : AI->users()) {
Gabor Greif96fedcb2010-07-12 14:15:58 +0000498 if (isa<LoadInst>(U)) continue;
499 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000500 // If storing TO the alloca, then the address isn't taken.
501 if (SI->getOperand(1) == AI) continue;
502 }
503 isAddressTaken = true;
504 break;
505 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000506
Chris Lattnerde1fede2010-01-05 05:31:55 +0000507 if (!isAddressTaken && AI->isStaticAlloca())
508 return false;
509 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000510
Chris Lattnerde1fede2010-01-05 05:31:55 +0000511 // If this load is a load from a GEP with a constant offset from an alloca,
512 // then we don't want to sink it. In its present form, it will be
513 // load [constant stack offset]. Sinking it will cause us to have to
514 // materialize the stack addresses in each predecessor in a register only to
515 // do a shared load from register in the successor.
516 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
517 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
518 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
519 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000520
Chris Lattnerde1fede2010-01-05 05:31:55 +0000521 return true;
522}
523
524Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
525 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
Eli Friedman8bc586e2011-08-15 22:09:40 +0000526
527 // FIXME: This is overconservative; this transform is allowed in some cases
528 // for atomic operations.
529 if (FirstLI->isAtomic())
Craig Topperf40110f2014-04-25 05:29:35 +0000530 return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +0000531
Chris Lattnerde1fede2010-01-05 05:31:55 +0000532 // When processing loads, we need to propagate two bits of information to the
533 // sunk load: whether it is volatile, and what its alignment is. We currently
534 // don't sink loads when some have their alignment specified and some don't.
535 // visitLoadInst will propagate an alignment onto the load when TD is around,
536 // and if TD isn't around, we can't handle the mixed case.
537 bool isVolatile = FirstLI->isVolatile();
538 unsigned LoadAlignment = FirstLI->getAlignment();
Chris Lattnerf6befff2010-03-05 18:53:28 +0000539 unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000540
Chris Lattnerde1fede2010-01-05 05:31:55 +0000541 // We can't sink the load if the loaded value could be modified between the
542 // load and the PHI.
543 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
544 !isSafeAndProfitableToSinkLoad(FirstLI))
Craig Topperf40110f2014-04-25 05:29:35 +0000545 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000546
Chris Lattnerde1fede2010-01-05 05:31:55 +0000547 // If the PHI is of volatile loads and the load block has multiple
548 // successors, sinking it would remove a load of the volatile value from
549 // the path through the other successor.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000550 if (isVolatile &&
Chris Lattnerde1fede2010-01-05 05:31:55 +0000551 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +0000552 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000553
Chris Lattnerde1fede2010-01-05 05:31:55 +0000554 // Check to see if all arguments are the same operation.
555 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
556 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
557 if (!LI || !LI->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +0000558 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000559
560 // We can't sink the load if the loaded value could be modified between
Chris Lattnerde1fede2010-01-05 05:31:55 +0000561 // the load and the PHI.
562 if (LI->isVolatile() != isVolatile ||
563 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattnerf6befff2010-03-05 18:53:28 +0000564 LI->getPointerAddressSpace() != LoadAddrSpace ||
Chris Lattnerde1fede2010-01-05 05:31:55 +0000565 !isSafeAndProfitableToSinkLoad(LI))
Craig Topperf40110f2014-04-25 05:29:35 +0000566 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000567
Chris Lattnerde1fede2010-01-05 05:31:55 +0000568 // If some of the loads have an alignment specified but not all of them,
569 // we can't do the transformation.
570 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
Craig Topperf40110f2014-04-25 05:29:35 +0000571 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000572
Chris Lattnerde1fede2010-01-05 05:31:55 +0000573 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000574
Chris Lattnerde1fede2010-01-05 05:31:55 +0000575 // If the PHI is of volatile loads and the load block has multiple
576 // successors, sinking it would remove a load of the volatile value from
577 // the path through the other successor.
578 if (isVolatile &&
579 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +0000580 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000581 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000582
Chris Lattnerde1fede2010-01-05 05:31:55 +0000583 // Okay, they are all the same operation. Create a new PHI node of the
584 // correct type, and PHI together all of the LHS's of the instructions.
585 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
Jay Foad52131342011-03-30 11:28:46 +0000586 PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000587 PN.getName()+".in");
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000588
Chris Lattnerde1fede2010-01-05 05:31:55 +0000589 Value *InVal = FirstLI->getOperand(0);
590 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000591 LoadInst *NewLI = new LoadInst(NewPN, "", isVolatile, LoadAlignment);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000592
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000593 unsigned KnownIDs[] = {
594 LLVMContext::MD_tbaa,
595 LLVMContext::MD_range,
596 LLVMContext::MD_invariant_load,
597 LLVMContext::MD_alias_scope,
598 LLVMContext::MD_noalias,
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000599 LLVMContext::MD_nonnull,
600 LLVMContext::MD_align,
601 LLVMContext::MD_dereferenceable,
602 LLVMContext::MD_dereferenceable_or_null,
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000603 };
604
605 for (unsigned ID : KnownIDs)
606 NewLI->setMetadata(ID, FirstLI->getMetadata(ID));
607
608 // Add all operands to the new PHI and combine TBAA metadata.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000609 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000610 LoadInst *LI = cast<LoadInst>(PN.getIncomingValue(i));
611 combineMetadata(NewLI, LI, KnownIDs);
612 Value *NewInVal = LI->getOperand(0);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000613 if (NewInVal != InVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000614 InVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000615 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
616 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000617
Chris Lattnerde1fede2010-01-05 05:31:55 +0000618 if (InVal) {
619 // The new PHI unions all of the same values together. This is really
620 // common, so we handle it intelligently here for compile-time speed.
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000621 NewLI->setOperand(0, InVal);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000622 delete NewPN;
623 } else {
624 InsertNewInstBefore(NewPN, PN);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000625 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000626
Chris Lattnerde1fede2010-01-05 05:31:55 +0000627 // If this was a volatile load that we are merging, make sure to loop through
628 // and mark all the input loads as non-volatile. If we don't do this, we will
629 // insert a new volatile load and the old ones will not be deletable.
630 if (isVolatile)
Pete Cooper833f34d2015-05-12 20:05:31 +0000631 for (Value *IncValue : PN.incoming_values())
632 cast<LoadInst>(IncValue)->setVolatile(false);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000633
Dehao Chenf4646272017-10-02 18:13:14 +0000634 PHIArgMergedDebugLoc(NewLI, PN);
Eli Friedman35211c62011-05-27 00:19:40 +0000635 return NewLI;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000636}
637
Sanjay Patel95334072015-09-27 20:34:31 +0000638/// TODO: This function could handle other cast types, but then it might
639/// require special-casing a cast from the 'i1' type. See the comment in
640/// FoldPHIArgOpIntoPHI() about pessimizing illegal integer types.
641Instruction *InstCombiner::FoldPHIArgZextsIntoPHI(PHINode &Phi) {
David Majnemereafa28a2015-11-07 00:52:53 +0000642 // We cannot create a new instruction after the PHI if the terminator is an
643 // EHPad because there is no valid insertion point.
644 if (TerminatorInst *TI = Phi.getParent()->getTerminator())
645 if (TI->isEHPad())
646 return nullptr;
647
Sanjay Patel95334072015-09-27 20:34:31 +0000648 // Early exit for the common case of a phi with two operands. These are
649 // handled elsewhere. See the comment below where we check the count of zexts
650 // and constants for more details.
651 unsigned NumIncomingValues = Phi.getNumIncomingValues();
652 if (NumIncomingValues < 3)
653 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000654
Sanjay Patel95334072015-09-27 20:34:31 +0000655 // Find the narrower type specified by the first zext.
656 Type *NarrowType = nullptr;
657 for (Value *V : Phi.incoming_values()) {
658 if (auto *Zext = dyn_cast<ZExtInst>(V)) {
659 NarrowType = Zext->getSrcTy();
660 break;
661 }
662 }
663 if (!NarrowType)
664 return nullptr;
665
666 // Walk the phi operands checking that we only have zexts or constants that
667 // we can shrink for free. Store the new operands for the new phi.
668 SmallVector<Value *, 4> NewIncoming;
669 unsigned NumZexts = 0;
670 unsigned NumConsts = 0;
671 for (Value *V : Phi.incoming_values()) {
672 if (auto *Zext = dyn_cast<ZExtInst>(V)) {
673 // All zexts must be identical and have one use.
674 if (Zext->getSrcTy() != NarrowType || !Zext->hasOneUse())
675 return nullptr;
676 NewIncoming.push_back(Zext->getOperand(0));
677 NumZexts++;
678 } else if (auto *C = dyn_cast<Constant>(V)) {
679 // Make sure that constants can fit in the new type.
680 Constant *Trunc = ConstantExpr::getTrunc(C, NarrowType);
681 if (ConstantExpr::getZExt(Trunc, C->getType()) != C)
682 return nullptr;
683 NewIncoming.push_back(Trunc);
684 NumConsts++;
685 } else {
686 // If it's not a cast or a constant, bail out.
687 return nullptr;
688 }
689 }
690
691 // The more common cases of a phi with no constant operands or just one
Craig Topperfb71b7d2017-04-14 19:20:12 +0000692 // variable operand are handled by FoldPHIArgOpIntoPHI() and foldOpIntoPhi()
693 // respectively. foldOpIntoPhi() wants to do the opposite transform that is
Sanjay Patel95334072015-09-27 20:34:31 +0000694 // performed here. It tries to replicate a cast in the phi operand's basic
695 // block to expose other folding opportunities. Thus, InstCombine will
696 // infinite loop without this check.
697 if (NumConsts == 0 || NumZexts < 2)
698 return nullptr;
699
700 // All incoming values are zexts or constants that are safe to truncate.
701 // Create a new phi node of the narrow type, phi together all of the new
702 // operands, and zext the result back to the original type.
703 PHINode *NewPhi = PHINode::Create(NarrowType, NumIncomingValues,
704 Phi.getName() + ".shrunk");
705 for (unsigned i = 0; i != NumIncomingValues; ++i)
706 NewPhi->addIncoming(NewIncoming[i], Phi.getIncomingBlock(i));
707
708 InsertNewInstBefore(NewPhi, Phi);
709 return CastInst::CreateZExtOrBitCast(NewPhi, Phi.getType());
710}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000711
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000712/// If all operands to a PHI node are the same "unary" operator and they all are
713/// only used by the PHI, PHI together their inputs, and do the operation once,
714/// to the result of the PHI.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000715Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
David Majnemer27f24472015-11-06 23:59:23 +0000716 // We cannot create a new instruction after the PHI if the terminator is an
717 // EHPad because there is no valid insertion point.
718 if (TerminatorInst *TI = PN.getParent()->getTerminator())
719 if (TI->isEHPad())
720 return nullptr;
721
Chris Lattnerde1fede2010-01-05 05:31:55 +0000722 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
723
724 if (isa<GetElementPtrInst>(FirstInst))
725 return FoldPHIArgGEPIntoPHI(PN);
726 if (isa<LoadInst>(FirstInst))
727 return FoldPHIArgLoadIntoPHI(PN);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000728
Chris Lattnerde1fede2010-01-05 05:31:55 +0000729 // Scan the instruction, looking for input operations that can be folded away.
730 // If all input operands to the phi are the same instruction (e.g. a cast from
731 // the same type or "+42") we can pull the operation through the PHI, reducing
732 // code size and simplifying code.
Craig Topperf40110f2014-04-25 05:29:35 +0000733 Constant *ConstantOp = nullptr;
734 Type *CastSrcTy = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000735
Chris Lattnerde1fede2010-01-05 05:31:55 +0000736 if (isa<CastInst>(FirstInst)) {
737 CastSrcTy = FirstInst->getOperand(0)->getType();
738
739 // Be careful about transforming integer PHIs. We don't want to pessimize
740 // the code by turning an i32 into an i1293.
Duncan Sands19d0b472010-02-16 11:11:14 +0000741 if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
Sanjay Patel2217f752017-01-31 17:25:42 +0000742 if (!shouldChangeType(PN.getType(), CastSrcTy))
Craig Topperf40110f2014-04-25 05:29:35 +0000743 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000744 }
745 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000746 // Can fold binop, compare or shift here if the RHS is a constant,
Chris Lattnerde1fede2010-01-05 05:31:55 +0000747 // otherwise call FoldPHIArgBinOpIntoPHI.
748 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +0000749 if (!ConstantOp)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000750 return FoldPHIArgBinOpIntoPHI(PN);
751 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000752 return nullptr; // Cannot fold this operation.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000753 }
754
755 // Check to see if all arguments are the same operation.
756 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
757 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000758 if (!I || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
759 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000760 if (CastSrcTy) {
761 if (I->getOperand(0)->getType() != CastSrcTy)
Craig Topperf40110f2014-04-25 05:29:35 +0000762 return nullptr; // Cast operation must match.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000763 } else if (I->getOperand(1) != ConstantOp) {
Craig Topperf40110f2014-04-25 05:29:35 +0000764 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000765 }
766 }
767
768 // Okay, they are all the same operation. Create a new PHI node of the
769 // correct type, and PHI together all of the LHS's of the instructions.
770 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
Jay Foad52131342011-03-30 11:28:46 +0000771 PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000772 PN.getName()+".in");
Chris Lattnerde1fede2010-01-05 05:31:55 +0000773
774 Value *InVal = FirstInst->getOperand(0);
775 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
776
777 // Add all operands to the new PHI.
778 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
779 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
780 if (NewInVal != InVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000781 InVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000782 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
783 }
784
785 Value *PhiVal;
786 if (InVal) {
787 // The new PHI unions all of the same values together. This is really
788 // common, so we handle it intelligently here for compile-time speed.
789 PhiVal = InVal;
790 delete NewPN;
791 } else {
792 InsertNewInstBefore(NewPN, PN);
793 PhiVal = NewPN;
794 }
795
796 // Insert and return the new operation.
Eli Friedman35211c62011-05-27 00:19:40 +0000797 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
798 CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
799 PN.getType());
Dehao Chenf4646272017-10-02 18:13:14 +0000800 PHIArgMergedDebugLoc(NewCI, PN);
Eli Friedman35211c62011-05-27 00:19:40 +0000801 return NewCI;
802 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000803
Chris Lattnera8fed472011-02-17 23:01:49 +0000804 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
805 BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Silviu Barangae985c762016-04-22 11:21:36 +0000806 BinOp->copyIRFlags(PN.getIncomingValue(0));
807
808 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i)
809 BinOp->andIRFlags(PN.getIncomingValue(i));
810
Dehao Chenf4646272017-10-02 18:13:14 +0000811 PHIArgMergedDebugLoc(BinOp, PN);
Chris Lattnera8fed472011-02-17 23:01:49 +0000812 return BinOp;
813 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000814
Chris Lattnerde1fede2010-01-05 05:31:55 +0000815 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Eli Friedman35211c62011-05-27 00:19:40 +0000816 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
817 PhiVal, ConstantOp);
Dehao Chenf4646272017-10-02 18:13:14 +0000818 PHIArgMergedDebugLoc(NewCI, PN);
Eli Friedman35211c62011-05-27 00:19:40 +0000819 return NewCI;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000820}
821
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000822/// Return true if this PHI node is only used by a PHI node cycle that is dead.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000823static bool DeadPHICycle(PHINode *PN,
Craig Topper71b7b682014-08-21 05:55:13 +0000824 SmallPtrSetImpl<PHINode*> &PotentiallyDeadPHIs) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000825 if (PN->use_empty()) return true;
826 if (!PN->hasOneUse()) return false;
827
828 // Remember this node, and if we find the cycle, return.
David Blaikie70573dc2014-11-19 07:49:26 +0000829 if (!PotentiallyDeadPHIs.insert(PN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000830 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000831
Chris Lattnerde1fede2010-01-05 05:31:55 +0000832 // Don't scan crazily complex things.
833 if (PotentiallyDeadPHIs.size() == 16)
834 return false;
835
Chandler Carruthcdf47882014-03-09 03:16:01 +0000836 if (PHINode *PU = dyn_cast<PHINode>(PN->user_back()))
Chris Lattnerde1fede2010-01-05 05:31:55 +0000837 return DeadPHICycle(PU, PotentiallyDeadPHIs);
838
839 return false;
840}
841
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000842/// Return true if this phi node is always equal to NonPhiInVal.
843/// This happens with mutually cyclic phi nodes like:
Chris Lattnerde1fede2010-01-05 05:31:55 +0000844/// z = some value; x = phi (y, z); y = phi (x, z)
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000845static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
Craig Topper71b7b682014-08-21 05:55:13 +0000846 SmallPtrSetImpl<PHINode*> &ValueEqualPHIs) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000847 // See if we already saw this PHI node.
David Blaikie70573dc2014-11-19 07:49:26 +0000848 if (!ValueEqualPHIs.insert(PN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000849 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000850
Chris Lattnerde1fede2010-01-05 05:31:55 +0000851 // Don't scan crazily complex things.
852 if (ValueEqualPHIs.size() == 16)
853 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000854
Chris Lattnerde1fede2010-01-05 05:31:55 +0000855 // Scan the operands to see if they are either phi nodes or are equal to
856 // the value.
Pete Cooper833f34d2015-05-12 20:05:31 +0000857 for (Value *Op : PN->incoming_values()) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000858 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
859 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
860 return false;
861 } else if (Op != NonPhiInVal)
862 return false;
863 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000864
Chris Lattnerde1fede2010-01-05 05:31:55 +0000865 return true;
866}
867
Jun Bum Lim10e58e82016-02-11 16:46:13 +0000868/// Return an existing non-zero constant if this phi node has one, otherwise
869/// return constant 1.
Jun Bum Lim339e9722016-02-11 15:50:07 +0000870static ConstantInt *GetAnyNonZeroConstInt(PHINode &PN) {
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +0000871 assert(isa<IntegerType>(PN.getType()) && "Expect only integer type phi");
Jun Bum Lim339e9722016-02-11 15:50:07 +0000872 for (Value *V : PN.operands())
873 if (auto *ConstVA = dyn_cast<ConstantInt>(V))
Craig Topper79ab6432017-07-06 18:39:47 +0000874 if (!ConstVA->isZero())
Jun Bum Lim339e9722016-02-11 15:50:07 +0000875 return ConstVA;
876 return ConstantInt::get(cast<IntegerType>(PN.getType()), 1);
877}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000878
879namespace {
880struct PHIUsageRecord {
881 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
882 unsigned Shift; // The amount shifted.
883 Instruction *Inst; // The trunc instruction.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000884
Chris Lattnerde1fede2010-01-05 05:31:55 +0000885 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
886 : PHIId(pn), Shift(Sh), Inst(User) {}
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000887
Chris Lattnerde1fede2010-01-05 05:31:55 +0000888 bool operator<(const PHIUsageRecord &RHS) const {
889 if (PHIId < RHS.PHIId) return true;
890 if (PHIId > RHS.PHIId) return false;
891 if (Shift < RHS.Shift) return true;
892 if (Shift > RHS.Shift) return false;
893 return Inst->getType()->getPrimitiveSizeInBits() <
894 RHS.Inst->getType()->getPrimitiveSizeInBits();
895 }
896};
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000897
Chris Lattnerde1fede2010-01-05 05:31:55 +0000898struct LoweredPHIRecord {
899 PHINode *PN; // The PHI that was lowered.
900 unsigned Shift; // The amount shifted.
901 unsigned Width; // The width extracted.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000902
Chris Lattner229907c2011-07-18 04:54:35 +0000903 LoweredPHIRecord(PHINode *pn, unsigned Sh, Type *Ty)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000904 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000905
Chris Lattnerde1fede2010-01-05 05:31:55 +0000906 // Ctor form used by DenseMap.
907 LoweredPHIRecord(PHINode *pn, unsigned Sh)
908 : PN(pn), Shift(Sh), Width(0) {}
909};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000910}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000911
912namespace llvm {
913 template<>
914 struct DenseMapInfo<LoweredPHIRecord> {
915 static inline LoweredPHIRecord getEmptyKey() {
Craig Topperf40110f2014-04-25 05:29:35 +0000916 return LoweredPHIRecord(nullptr, 0);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000917 }
918 static inline LoweredPHIRecord getTombstoneKey() {
Craig Topperf40110f2014-04-25 05:29:35 +0000919 return LoweredPHIRecord(nullptr, 1);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000920 }
921 static unsigned getHashValue(const LoweredPHIRecord &Val) {
922 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
923 (Val.Width>>3);
924 }
925 static bool isEqual(const LoweredPHIRecord &LHS,
926 const LoweredPHIRecord &RHS) {
927 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
928 LHS.Width == RHS.Width;
929 }
930 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000931}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000932
933
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000934/// This is an integer PHI and we know that it has an illegal type: see if it is
935/// only used by trunc or trunc(lshr) operations. If so, we split the PHI into
936/// the various pieces being extracted. This sort of thing is introduced when
937/// SROA promotes an aggregate to large integer values.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000938///
939/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
940/// inttoptr. We should produce new PHIs in the right type.
941///
942Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
943 // PHIUsers - Keep track of all of the truncated values extracted from a set
944 // of PHIs, along with their offset. These are the things we want to rewrite.
945 SmallVector<PHIUsageRecord, 16> PHIUsers;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000946
Chris Lattnerde1fede2010-01-05 05:31:55 +0000947 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
948 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
949 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
950 // check the uses of (to ensure they are all extracts).
951 SmallVector<PHINode*, 8> PHIsToSlice;
952 SmallPtrSet<PHINode*, 8> PHIsInspected;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000953
Chris Lattnerde1fede2010-01-05 05:31:55 +0000954 PHIsToSlice.push_back(&FirstPhi);
955 PHIsInspected.insert(&FirstPhi);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000956
Chris Lattnerde1fede2010-01-05 05:31:55 +0000957 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
958 PHINode *PN = PHIsToSlice[PHIId];
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000959
Chris Lattnerde1fede2010-01-05 05:31:55 +0000960 // Scan the input list of the PHI. If any input is an invoke, and if the
961 // input is defined in the predecessor, then we won't be split the critical
962 // edge which is required to insert a truncate. Because of this, we have to
963 // bail out.
964 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
965 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000966 if (!II) continue;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000967 if (II->getParent() != PN->getIncomingBlock(i))
968 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000969
Chris Lattnerde1fede2010-01-05 05:31:55 +0000970 // If we have a phi, and if it's directly in the predecessor, then we have
971 // a critical edge where we need to put the truncate. Since we can't
972 // split the edge in instcombine, we have to bail out.
Craig Topperf40110f2014-04-25 05:29:35 +0000973 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000974 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000975
Chandler Carruthcdf47882014-03-09 03:16:01 +0000976 for (User *U : PN->users()) {
977 Instruction *UserI = cast<Instruction>(U);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000978
Chris Lattnerde1fede2010-01-05 05:31:55 +0000979 // If the user is a PHI, inspect its uses recursively.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000980 if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
David Blaikie70573dc2014-11-19 07:49:26 +0000981 if (PHIsInspected.insert(UserPN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000982 PHIsToSlice.push_back(UserPN);
983 continue;
984 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000985
Chris Lattnerde1fede2010-01-05 05:31:55 +0000986 // Truncates are always ok.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000987 if (isa<TruncInst>(UserI)) {
988 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
Chris Lattnerde1fede2010-01-05 05:31:55 +0000989 continue;
990 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000991
Chris Lattnerde1fede2010-01-05 05:31:55 +0000992 // Otherwise it must be a lshr which can only be used by one trunc.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000993 if (UserI->getOpcode() != Instruction::LShr ||
994 !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
995 !isa<ConstantInt>(UserI->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000996 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000997
Chandler Carruthcdf47882014-03-09 03:16:01 +0000998 unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
999 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
Chris Lattnerde1fede2010-01-05 05:31:55 +00001000 }
1001 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001002
Chris Lattnerde1fede2010-01-05 05:31:55 +00001003 // If we have no users, they must be all self uses, just nuke the PHI.
1004 if (PHIUsers.empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00001005 return replaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001006
Chris Lattnerde1fede2010-01-05 05:31:55 +00001007 // If this phi node is transformable, create new PHIs for all the pieces
1008 // extracted out of it. First, sort the users by their offset and size.
1009 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001010
Matt Arsenaulte6db7602013-09-05 19:48:28 +00001011 DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
1012 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
1013 dbgs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] << '\n';
1014 );
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001015
Chris Lattnerde1fede2010-01-05 05:31:55 +00001016 // PredValues - This is a temporary used when rewriting PHI nodes. It is
1017 // hoisted out here to avoid construction/destruction thrashing.
1018 DenseMap<BasicBlock*, Value*> PredValues;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001019
Chris Lattnerde1fede2010-01-05 05:31:55 +00001020 // ExtractedVals - Each new PHI we introduce is saved here so we don't
1021 // introduce redundant PHIs.
1022 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001023
Chris Lattnerde1fede2010-01-05 05:31:55 +00001024 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
1025 unsigned PHIId = PHIUsers[UserI].PHIId;
1026 PHINode *PN = PHIsToSlice[PHIId];
1027 unsigned Offset = PHIUsers[UserI].Shift;
Chris Lattner229907c2011-07-18 04:54:35 +00001028 Type *Ty = PHIUsers[UserI].Inst->getType();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001029
Chris Lattnerde1fede2010-01-05 05:31:55 +00001030 PHINode *EltPHI;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001031
Chris Lattnerde1fede2010-01-05 05:31:55 +00001032 // If we've already lowered a user like this, reuse the previously lowered
1033 // value.
Craig Topperf40110f2014-04-25 05:29:35 +00001034 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001035
Chris Lattnerde1fede2010-01-05 05:31:55 +00001036 // Otherwise, Create the new PHI node for this user.
Jay Foad52131342011-03-30 11:28:46 +00001037 EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
1038 PN->getName()+".off"+Twine(Offset), PN);
Chris Lattnerde1fede2010-01-05 05:31:55 +00001039 assert(EltPHI->getType() != PN->getType() &&
1040 "Truncate didn't shrink phi?");
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001041
Chris Lattnerde1fede2010-01-05 05:31:55 +00001042 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1043 BasicBlock *Pred = PN->getIncomingBlock(i);
1044 Value *&PredVal = PredValues[Pred];
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001045
Chris Lattnerde1fede2010-01-05 05:31:55 +00001046 // If we already have a value for this predecessor, reuse it.
1047 if (PredVal) {
1048 EltPHI->addIncoming(PredVal, Pred);
1049 continue;
1050 }
1051
1052 // Handle the PHI self-reuse case.
1053 Value *InVal = PN->getIncomingValue(i);
1054 if (InVal == PN) {
1055 PredVal = EltPHI;
1056 EltPHI->addIncoming(PredVal, Pred);
1057 continue;
1058 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001059
Chris Lattnerde1fede2010-01-05 05:31:55 +00001060 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
1061 // If the incoming value was a PHI, and if it was one of the PHIs we
1062 // already rewrote it, just use the lowered value.
1063 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
1064 PredVal = Res;
1065 EltPHI->addIncoming(PredVal, Pred);
1066 continue;
1067 }
1068 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001069
Chris Lattnerde1fede2010-01-05 05:31:55 +00001070 // Otherwise, do an extract in the predecessor.
Craig Topperbb4069e2017-07-07 23:16:26 +00001071 Builder.SetInsertPoint(Pred->getTerminator());
Chris Lattnerde1fede2010-01-05 05:31:55 +00001072 Value *Res = InVal;
1073 if (Offset)
Craig Topperbb4069e2017-07-07 23:16:26 +00001074 Res = Builder.CreateLShr(Res, ConstantInt::get(InVal->getType(),
Chris Lattnerde1fede2010-01-05 05:31:55 +00001075 Offset), "extract");
Craig Topperbb4069e2017-07-07 23:16:26 +00001076 Res = Builder.CreateTrunc(Res, Ty, "extract.t");
Chris Lattnerde1fede2010-01-05 05:31:55 +00001077 PredVal = Res;
1078 EltPHI->addIncoming(Res, Pred);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001079
Chris Lattnerde1fede2010-01-05 05:31:55 +00001080 // If the incoming value was a PHI, and if it was one of the PHIs we are
1081 // rewriting, we will ultimately delete the code we inserted. This
1082 // means we need to revisit that PHI to make sure we extract out the
1083 // needed piece.
1084 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
1085 if (PHIsInspected.count(OldInVal)) {
David Majnemer42531262016-08-12 03:55:06 +00001086 unsigned RefPHIId =
1087 find(PHIsToSlice, OldInVal) - PHIsToSlice.begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001088 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
Chris Lattnerde1fede2010-01-05 05:31:55 +00001089 cast<Instruction>(Res)));
1090 ++UserE;
1091 }
1092 }
1093 PredValues.clear();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001094
Matt Arsenaulte6db7602013-09-05 19:48:28 +00001095 DEBUG(dbgs() << " Made element PHI for offset " << Offset << ": "
Chris Lattnerde1fede2010-01-05 05:31:55 +00001096 << *EltPHI << '\n');
1097 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
1098 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001099
Chris Lattnerde1fede2010-01-05 05:31:55 +00001100 // Replace the use of this piece with the PHI node.
Sanjay Patel4b198802016-02-01 22:23:39 +00001101 replaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattnerde1fede2010-01-05 05:31:55 +00001102 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001103
Chris Lattnerde1fede2010-01-05 05:31:55 +00001104 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
1105 // with undefs.
1106 Value *Undef = UndefValue::get(FirstPhi.getType());
1107 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
Sanjay Patel4b198802016-02-01 22:23:39 +00001108 replaceInstUsesWith(*PHIsToSlice[i], Undef);
1109 return replaceInstUsesWith(FirstPhi, Undef);
Chris Lattnerde1fede2010-01-05 05:31:55 +00001110}
1111
1112// PHINode simplification
1113//
1114Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Craig Toppera4205622017-06-09 03:21:29 +00001115 if (Value *V = SimplifyInstruction(&PN, SQ.getWithInstruction(&PN)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001116 return replaceInstUsesWith(PN, V);
Chris Lattnerde1fede2010-01-05 05:31:55 +00001117
Sanjay Patel95334072015-09-27 20:34:31 +00001118 if (Instruction *Result = FoldPHIArgZextsIntoPHI(PN))
1119 return Result;
1120
Chris Lattnerde1fede2010-01-05 05:31:55 +00001121 // If all PHI operands are the same operation, pull them through the PHI,
1122 // reducing code size.
1123 if (isa<Instruction>(PN.getIncomingValue(0)) &&
1124 isa<Instruction>(PN.getIncomingValue(1)) &&
1125 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
1126 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
1127 // FIXME: The hasOneUse check will fail for PHIs that use the value more
1128 // than themselves more than once.
1129 PN.getIncomingValue(0)->hasOneUse())
1130 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
1131 return Result;
1132
1133 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
1134 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
1135 // PHI)... break the cycle.
1136 if (PN.hasOneUse()) {
Xinliang David Li4cdc9da2017-10-10 05:07:54 +00001137 if (Instruction *Result = FoldIntegerTypedPHI(PN))
1138 return Result;
1139
Chandler Carruthcdf47882014-03-09 03:16:01 +00001140 Instruction *PHIUser = cast<Instruction>(PN.user_back());
Chris Lattnerde1fede2010-01-05 05:31:55 +00001141 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
1142 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
1143 PotentiallyDeadPHIs.insert(&PN);
1144 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Sanjay Patel4b198802016-02-01 22:23:39 +00001145 return replaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerde1fede2010-01-05 05:31:55 +00001146 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001147
Chris Lattnerde1fede2010-01-05 05:31:55 +00001148 // If this phi has a single use, and if that use just computes a value for
1149 // the next iteration of a loop, delete the phi. This occurs with unused
1150 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
1151 // common case here is good because the only other things that catch this
1152 // are induction variable analysis (sometimes) and ADCE, which is only run
1153 // late.
1154 if (PHIUser->hasOneUse() &&
1155 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00001156 PHIUser->user_back() == &PN) {
Sanjay Patel4b198802016-02-01 22:23:39 +00001157 return replaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerde1fede2010-01-05 05:31:55 +00001158 }
Jun Bum Lim339e9722016-02-11 15:50:07 +00001159 // When a PHI is used only to be compared with zero, it is safe to replace
1160 // an incoming value proved as known nonzero with any non-zero constant.
Jun Bum Lim10e58e82016-02-11 16:46:13 +00001161 // For example, in the code below, the incoming value %v can be replaced
1162 // with any non-zero constant based on the fact that the PHI is only used to
1163 // be compared with zero and %v is a known non-zero value:
Jun Bum Lim339e9722016-02-11 15:50:07 +00001164 // %v = select %cond, 1, 2
1165 // %p = phi [%v, BB] ...
1166 // icmp eq, %p, 0
1167 auto *CmpInst = dyn_cast<ICmpInst>(PHIUser);
1168 // FIXME: To be simple, handle only integer type for now.
1169 if (CmpInst && isa<IntegerType>(PN.getType()) && CmpInst->isEquality() &&
1170 match(CmpInst->getOperand(1), m_Zero())) {
1171 ConstantInt *NonZeroConst = nullptr;
1172 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1173 Instruction *CtxI = PN.getIncomingBlock(i)->getTerminator();
1174 Value *VA = PN.getIncomingValue(i);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001175 if (isKnownNonZero(VA, DL, 0, &AC, CtxI, &DT)) {
Jun Bum Lim339e9722016-02-11 15:50:07 +00001176 if (!NonZeroConst)
1177 NonZeroConst = GetAnyNonZeroConstInt(PN);
1178 PN.setIncomingValue(i, NonZeroConst);
1179 }
1180 }
1181 }
Chris Lattnerde1fede2010-01-05 05:31:55 +00001182 }
1183
1184 // We sometimes end up with phi cycles that non-obviously end up being the
1185 // same value, for example:
1186 // z = some value; x = phi (y, z); y = phi (x, z)
1187 // where the phi nodes don't necessarily need to be in the same block. Do a
1188 // quick check to see if the PHI node only contains a single non-phi value, if
1189 // so, scan to see if the phi cycle is actually equal to that value.
1190 {
Frits van Bommeld6d4f982011-04-16 14:32:34 +00001191 unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
Chris Lattnerde1fede2010-01-05 05:31:55 +00001192 // Scan for the first non-phi operand.
Frits van Bommeld6d4f982011-04-16 14:32:34 +00001193 while (InValNo != NumIncomingVals &&
Chris Lattnerde1fede2010-01-05 05:31:55 +00001194 isa<PHINode>(PN.getIncomingValue(InValNo)))
1195 ++InValNo;
1196
Frits van Bommeld6d4f982011-04-16 14:32:34 +00001197 if (InValNo != NumIncomingVals) {
Jay Foad7d03e9b2011-04-16 14:17:37 +00001198 Value *NonPhiInVal = PN.getIncomingValue(InValNo);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001199
Chris Lattnerde1fede2010-01-05 05:31:55 +00001200 // Scan the rest of the operands to see if there are any conflicts, if so
1201 // there is no need to recursively scan other phis.
Frits van Bommeld6d4f982011-04-16 14:32:34 +00001202 for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
Chris Lattnerde1fede2010-01-05 05:31:55 +00001203 Value *OpVal = PN.getIncomingValue(InValNo);
1204 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
1205 break;
1206 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001207
Chris Lattnerde1fede2010-01-05 05:31:55 +00001208 // If we scanned over all operands, then we have one unique value plus
1209 // phi values. Scan PHI nodes to see if they all merge in each other or
1210 // the value.
Frits van Bommeld6d4f982011-04-16 14:32:34 +00001211 if (InValNo == NumIncomingVals) {
Chris Lattnerde1fede2010-01-05 05:31:55 +00001212 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
1213 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
Sanjay Patel4b198802016-02-01 22:23:39 +00001214 return replaceInstUsesWith(PN, NonPhiInVal);
Chris Lattnerde1fede2010-01-05 05:31:55 +00001215 }
1216 }
1217 }
1218
1219 // If there are multiple PHIs, sort their operands so that they all list
1220 // the blocks in the same order. This will help identical PHIs be eliminated
1221 // by other passes. Other passes shouldn't depend on this for correctness
1222 // however.
1223 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
1224 if (&PN != FirstPN)
1225 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
1226 BasicBlock *BBA = PN.getIncomingBlock(i);
1227 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
1228 if (BBA != BBB) {
1229 Value *VA = PN.getIncomingValue(i);
1230 unsigned j = PN.getBasicBlockIndex(BBB);
1231 Value *VB = PN.getIncomingValue(j);
1232 PN.setIncomingBlock(i, BBB);
1233 PN.setIncomingValue(i, VB);
1234 PN.setIncomingBlock(j, BBA);
1235 PN.setIncomingValue(j, VA);
1236 // NOTE: Instcombine normally would want us to "return &PN" if we
1237 // modified any of the operands of an instruction. However, since we
1238 // aren't adding or removing uses (just rearranging them) we don't do
1239 // this in this case.
1240 }
1241 }
1242
1243 // If this is an integer PHI and we know that it has an illegal type, see if
1244 // it is only used by trunc or trunc(lshr) operations. If so, we split the
1245 // PHI into the various pieces being extracted. This sort of thing is
1246 // introduced when SROA promotes an aggregate to a single large integer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001247 if (PN.getType()->isIntegerTy() &&
1248 !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
Chris Lattnerde1fede2010-01-05 05:31:55 +00001249 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
1250 return Res;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001251
Craig Topperf40110f2014-04-25 05:29:35 +00001252 return nullptr;
Benjamin Kramerf7cc6982010-01-05 13:32:48 +00001253}