1202375Srdivacky//===- InstCombinePHI.cpp -------------------------------------------------===//
2202375Srdivacky//
3202375Srdivacky//                     The LLVM Compiler Infrastructure
4202375Srdivacky//
5202375Srdivacky// This file is distributed under the University of Illinois Open Source
6202375Srdivacky// License. See LICENSE.TXT for details.
7202375Srdivacky//
8202375Srdivacky//===----------------------------------------------------------------------===//
9202375Srdivacky//
10202375Srdivacky// This file implements the visitPHINode function.
11202375Srdivacky//
12202375Srdivacky//===----------------------------------------------------------------------===//
13202375Srdivacky
14202375Srdivacky#include "InstCombine.h"
15249423Sdim#include "llvm/ADT/STLExtras.h"
16249423Sdim#include "llvm/ADT/SmallPtrSet.h"
17218893Sdim#include "llvm/Analysis/InstructionSimplify.h"
18249423Sdim#include "llvm/IR/DataLayout.h"
19202375Srdivackyusing namespace llvm;
20202375Srdivacky
21202375Srdivacky/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
22202375Srdivacky/// and if a/b/c and the add's all have a single use, turn this into a phi
23202375Srdivacky/// and a single binop.
24202375SrdivackyInstruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
25202375Srdivacky  Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
26202375Srdivacky  assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
27202375Srdivacky  unsigned Opc = FirstInst->getOpcode();
28202375Srdivacky  Value *LHSVal = FirstInst->getOperand(0);
29202375Srdivacky  Value *RHSVal = FirstInst->getOperand(1);
30251662Sdim
31226633Sdim  Type *LHSType = LHSVal->getType();
32226633Sdim  Type *RHSType = RHSVal->getType();
33251662Sdim
34218893Sdim  bool isNUW = false, isNSW = false, isExact = false;
35218893Sdim  if (OverflowingBinaryOperator *BO =
36218893Sdim        dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
37218893Sdim    isNUW = BO->hasNoUnsignedWrap();
38218893Sdim    isNSW = BO->hasNoSignedWrap();
39218893Sdim  } else if (PossiblyExactOperator *PEO =
40218893Sdim               dyn_cast<PossiblyExactOperator>(FirstInst))
41218893Sdim    isExact = PEO->isExact();
42251662Sdim
43202375Srdivacky  // Scan to see if all operands are the same opcode, and all have one use.
44202375Srdivacky  for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
45202375Srdivacky    Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
46202375Srdivacky    if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
47202375Srdivacky        // Verify type of the LHS matches so we don't fold cmp's of different
48218893Sdim        // types.
49202375Srdivacky        I->getOperand(0)->getType() != LHSType ||
50202375Srdivacky        I->getOperand(1)->getType() != RHSType)
51202375Srdivacky      return 0;
52202375Srdivacky
53202375Srdivacky    // If they are CmpInst instructions, check their predicates
54218893Sdim    if (CmpInst *CI = dyn_cast<CmpInst>(I))
55218893Sdim      if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
56202375Srdivacky        return 0;
57251662Sdim
58218893Sdim    if (isNUW)
59218893Sdim      isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
60218893Sdim    if (isNSW)
61218893Sdim      isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
62218893Sdim    if (isExact)
63218893Sdim      isExact = cast<PossiblyExactOperator>(I)->isExact();
64251662Sdim
65202375Srdivacky    // Keep track of which operand needs a phi node.
66202375Srdivacky    if (I->getOperand(0) != LHSVal) LHSVal = 0;
67202375Srdivacky    if (I->getOperand(1) != RHSVal) RHSVal = 0;
68202375Srdivacky  }
69202375Srdivacky
70202375Srdivacky  // If both LHS and RHS would need a PHI, don't do this transformation,
71202375Srdivacky  // because it would increase the number of PHIs entering the block,
72202375Srdivacky  // which leads to higher register pressure. This is especially
73202375Srdivacky  // bad when the PHIs are in the header of a loop.
74202375Srdivacky  if (!LHSVal && !RHSVal)
75202375Srdivacky    return 0;
76251662Sdim
77202375Srdivacky  // Otherwise, this is safe to transform!
78251662Sdim
79202375Srdivacky  Value *InLHS = FirstInst->getOperand(0);
80202375Srdivacky  Value *InRHS = FirstInst->getOperand(1);
81202375Srdivacky  PHINode *NewLHS = 0, *NewRHS = 0;
82202375Srdivacky  if (LHSVal == 0) {
83221345Sdim    NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
84202375Srdivacky                             FirstInst->getOperand(0)->getName() + ".pn");
85202375Srdivacky    NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
86202375Srdivacky    InsertNewInstBefore(NewLHS, PN);
87202375Srdivacky    LHSVal = NewLHS;
88202375Srdivacky  }
89251662Sdim
90202375Srdivacky  if (RHSVal == 0) {
91221345Sdim    NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
92202375Srdivacky                             FirstInst->getOperand(1)->getName() + ".pn");
93202375Srdivacky    NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
94202375Srdivacky    InsertNewInstBefore(NewRHS, PN);
95202375Srdivacky    RHSVal = NewRHS;
96202375Srdivacky  }
97251662Sdim
98202375Srdivacky  // Add all operands to the new PHIs.
99202375Srdivacky  if (NewLHS || NewRHS) {
100202375Srdivacky    for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
101202375Srdivacky      Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
102202375Srdivacky      if (NewLHS) {
103202375Srdivacky        Value *NewInLHS = InInst->getOperand(0);
104202375Srdivacky        NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
105202375Srdivacky      }
106202375Srdivacky      if (NewRHS) {
107202375Srdivacky        Value *NewInRHS = InInst->getOperand(1);
108202375Srdivacky        NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
109202375Srdivacky      }
110202375Srdivacky    }
111202375Srdivacky  }
112251662Sdim
113223017Sdim  if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
114223017Sdim    CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
115223017Sdim                                     LHSVal, RHSVal);
116223017Sdim    NewCI->setDebugLoc(FirstInst->getDebugLoc());
117223017Sdim    return NewCI;
118223017Sdim  }
119223017Sdim
120218893Sdim  BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
121218893Sdim  BinaryOperator *NewBinOp =
122218893Sdim    BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
123218893Sdim  if (isNUW) NewBinOp->setHasNoUnsignedWrap();
124218893Sdim  if (isNSW) NewBinOp->setHasNoSignedWrap();
125218893Sdim  if (isExact) NewBinOp->setIsExact();
126223017Sdim  NewBinOp->setDebugLoc(FirstInst->getDebugLoc());
127218893Sdim  return NewBinOp;
128202375Srdivacky}
129202375Srdivacky
130202375SrdivackyInstruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
131202375Srdivacky  GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
132251662Sdim
133251662Sdim  SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
134202375Srdivacky                                        FirstInst->op_end());
135202375Srdivacky  // This is true if all GEP bases are allocas and if all indices into them are
136202375Srdivacky  // constants.
137202375Srdivacky  bool AllBasePointersAreAllocas = true;
138202375Srdivacky
139202375Srdivacky  // We don't want to replace this phi if the replacement would require
140202375Srdivacky  // more than one phi, which leads to higher register pressure. This is
141202375Srdivacky  // especially bad when the PHIs are in the header of a loop.
142202375Srdivacky  bool NeededPhi = false;
143251662Sdim
144218893Sdim  bool AllInBounds = true;
145251662Sdim
146202375Srdivacky  // Scan to see if all operands are the same opcode, and all have one use.
147202375Srdivacky  for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
148202375Srdivacky    GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
149202375Srdivacky    if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
150202375Srdivacky      GEP->getNumOperands() != FirstInst->getNumOperands())
151202375Srdivacky      return 0;
152202375Srdivacky
153218893Sdim    AllInBounds &= GEP->isInBounds();
154251662Sdim
155202375Srdivacky    // Keep track of whether or not all GEPs are of alloca pointers.
156202375Srdivacky    if (AllBasePointersAreAllocas &&
157202375Srdivacky        (!isa<AllocaInst>(GEP->getOperand(0)) ||
158202375Srdivacky         !GEP->hasAllConstantIndices()))
159202375Srdivacky      AllBasePointersAreAllocas = false;
160251662Sdim
161202375Srdivacky    // Compare the operand lists.
162202375Srdivacky    for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
163202375Srdivacky      if (FirstInst->getOperand(op) == GEP->getOperand(op))
164202375Srdivacky        continue;
165251662Sdim
166202375Srdivacky      // Don't merge two GEPs when two operands differ (introducing phi nodes)
167202375Srdivacky      // if one of the PHIs has a constant for the index.  The index may be
168202375Srdivacky      // substantially cheaper to compute for the constants, so making it a
169202375Srdivacky      // variable index could pessimize the path.  This also handles the case
170202375Srdivacky      // for struct indices, which must always be constant.
171202375Srdivacky      if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
172202375Srdivacky          isa<ConstantInt>(GEP->getOperand(op)))
173202375Srdivacky        return 0;
174251662Sdim
175202375Srdivacky      if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
176202375Srdivacky        return 0;
177202375Srdivacky
178202375Srdivacky      // If we already needed a PHI for an earlier operand, and another operand
179202375Srdivacky      // also requires a PHI, we'd be introducing more PHIs than we're
180202375Srdivacky      // eliminating, which increases register pressure on entry to the PHI's
181202375Srdivacky      // block.
182202375Srdivacky      if (NeededPhi)
183202375Srdivacky        return 0;
184202375Srdivacky
185202375Srdivacky      FixedOperands[op] = 0;  // Needs a PHI.
186202375Srdivacky      NeededPhi = true;
187202375Srdivacky    }
188202375Srdivacky  }
189251662Sdim
190202375Srdivacky  // If all of the base pointers of the PHI'd GEPs are from allocas, don't
191202375Srdivacky  // bother doing this transformation.  At best, this will just save a bit of
192202375Srdivacky  // offset calculation, but all the predecessors will have to materialize the
193202375Srdivacky  // stack address into a register anyway.  We'd actually rather *clone* the
194202375Srdivacky  // load up into the predecessors so that we have a load of a gep of an alloca,
195202375Srdivacky  // which can usually all be folded into the load.
196202375Srdivacky  if (AllBasePointersAreAllocas)
197202375Srdivacky    return 0;
198251662Sdim
199202375Srdivacky  // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
200202375Srdivacky  // that is variable.
201202375Srdivacky  SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
202251662Sdim
203202375Srdivacky  bool HasAnyPHIs = false;
204202375Srdivacky  for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
205202375Srdivacky    if (FixedOperands[i]) continue;  // operand doesn't need a phi.
206202375Srdivacky    Value *FirstOp = FirstInst->getOperand(i);
207221345Sdim    PHINode *NewPN = PHINode::Create(FirstOp->getType(), e,
208202375Srdivacky                                     FirstOp->getName()+".pn");
209202375Srdivacky    InsertNewInstBefore(NewPN, PN);
210251662Sdim
211202375Srdivacky    NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
212202375Srdivacky    OperandPhis[i] = NewPN;
213202375Srdivacky    FixedOperands[i] = NewPN;
214202375Srdivacky    HasAnyPHIs = true;
215202375Srdivacky  }
216202375Srdivacky
217251662Sdim
218202375Srdivacky  // Add all operands to the new PHIs.
219202375Srdivacky  if (HasAnyPHIs) {
220202375Srdivacky    for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
221202375Srdivacky      GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
222202375Srdivacky      BasicBlock *InBB = PN.getIncomingBlock(i);
223251662Sdim
224202375Srdivacky      for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
225202375Srdivacky        if (PHINode *OpPhi = OperandPhis[op])
226202375Srdivacky          OpPhi->addIncoming(InGEP->getOperand(op), InBB);
227202375Srdivacky    }
228202375Srdivacky  }
229251662Sdim
230202375Srdivacky  Value *Base = FixedOperands[0];
231251662Sdim  GetElementPtrInst *NewGEP =
232226633Sdim    GetElementPtrInst::Create(Base, makeArrayRef(FixedOperands).slice(1));
233218893Sdim  if (AllInBounds) NewGEP->setIsInBounds();
234223017Sdim  NewGEP->setDebugLoc(FirstInst->getDebugLoc());
235218893Sdim  return NewGEP;
236202375Srdivacky}
237202375Srdivacky
238202375Srdivacky
239202375Srdivacky/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
240202375Srdivacky/// sink the load out of the block that defines it.  This means that it must be
241202375Srdivacky/// obvious the value of the load is not changed from the point of the load to
242202375Srdivacky/// the end of the block it is in.
243202375Srdivacky///
244221345Sdim/// Finally, it is safe, but not profitable, to sink a load targeting a
245202375Srdivacky/// non-address-taken alloca.  Doing so will cause us to not promote the alloca
246202375Srdivacky/// to a register.
247202375Srdivackystatic bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
248202375Srdivacky  BasicBlock::iterator BBI = L, E = L->getParent()->end();
249251662Sdim
250202375Srdivacky  for (++BBI; BBI != E; ++BBI)
251202375Srdivacky    if (BBI->mayWriteToMemory())
252202375Srdivacky      return false;
253251662Sdim
254202375Srdivacky  // Check for non-address taken alloca.  If not address-taken already, it isn't
255202375Srdivacky  // profitable to do this xform.
256202375Srdivacky  if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
257202375Srdivacky    bool isAddressTaken = false;
258202375Srdivacky    for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
259202375Srdivacky         UI != E; ++UI) {
260210299Sed      User *U = *UI;
261210299Sed      if (isa<LoadInst>(U)) continue;
262210299Sed      if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
263202375Srdivacky        // If storing TO the alloca, then the address isn't taken.
264202375Srdivacky        if (SI->getOperand(1) == AI) continue;
265202375Srdivacky      }
266202375Srdivacky      isAddressTaken = true;
267202375Srdivacky      break;
268202375Srdivacky    }
269251662Sdim
270202375Srdivacky    if (!isAddressTaken && AI->isStaticAlloca())
271202375Srdivacky      return false;
272202375Srdivacky  }
273251662Sdim
274202375Srdivacky  // If this load is a load from a GEP with a constant offset from an alloca,
275202375Srdivacky  // then we don't want to sink it.  In its present form, it will be
276202375Srdivacky  // load [constant stack offset].  Sinking it will cause us to have to
277202375Srdivacky  // materialize the stack addresses in each predecessor in a register only to
278202375Srdivacky  // do a shared load from register in the successor.
279202375Srdivacky  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
280202375Srdivacky    if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
281202375Srdivacky      if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
282202375Srdivacky        return false;
283251662Sdim
284202375Srdivacky  return true;
285202375Srdivacky}
286202375Srdivacky
287202375SrdivackyInstruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
288202375Srdivacky  LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
289226633Sdim
290226633Sdim  // FIXME: This is overconservative; this transform is allowed in some cases
291226633Sdim  // for atomic operations.
292226633Sdim  if (FirstLI->isAtomic())
293226633Sdim    return 0;
294226633Sdim
295202375Srdivacky  // When processing loads, we need to propagate two bits of information to the
296202375Srdivacky  // sunk load: whether it is volatile, and what its alignment is.  We currently
297202375Srdivacky  // don't sink loads when some have their alignment specified and some don't.
298202375Srdivacky  // visitLoadInst will propagate an alignment onto the load when TD is around,
299202375Srdivacky  // and if TD isn't around, we can't handle the mixed case.
300202375Srdivacky  bool isVolatile = FirstLI->isVolatile();
301202375Srdivacky  unsigned LoadAlignment = FirstLI->getAlignment();
302204792Srdivacky  unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
303251662Sdim
304202375Srdivacky  // We can't sink the load if the loaded value could be modified between the
305202375Srdivacky  // load and the PHI.
306202375Srdivacky  if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
307202375Srdivacky      !isSafeAndProfitableToSinkLoad(FirstLI))
308202375Srdivacky    return 0;
309251662Sdim
310202375Srdivacky  // If the PHI is of volatile loads and the load block has multiple
311202375Srdivacky  // successors, sinking it would remove a load of the volatile value from
312202375Srdivacky  // the path through the other successor.
313251662Sdim  if (isVolatile &&
314202375Srdivacky      FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
315202375Srdivacky    return 0;
316251662Sdim
317202375Srdivacky  // Check to see if all arguments are the same operation.
318202375Srdivacky  for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
319202375Srdivacky    LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
320202375Srdivacky    if (!LI || !LI->hasOneUse())
321202375Srdivacky      return 0;
322251662Sdim
323251662Sdim    // We can't sink the load if the loaded value could be modified between
324202375Srdivacky    // the load and the PHI.
325202375Srdivacky    if (LI->isVolatile() != isVolatile ||
326202375Srdivacky        LI->getParent() != PN.getIncomingBlock(i) ||
327204792Srdivacky        LI->getPointerAddressSpace() != LoadAddrSpace ||
328202375Srdivacky        !isSafeAndProfitableToSinkLoad(LI))
329202375Srdivacky      return 0;
330251662Sdim
331202375Srdivacky    // If some of the loads have an alignment specified but not all of them,
332202375Srdivacky    // we can't do the transformation.
333202375Srdivacky    if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
334202375Srdivacky      return 0;
335251662Sdim
336202375Srdivacky    LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
337251662Sdim
338202375Srdivacky    // If the PHI is of volatile loads and the load block has multiple
339202375Srdivacky    // successors, sinking it would remove a load of the volatile value from
340202375Srdivacky    // the path through the other successor.
341202375Srdivacky    if (isVolatile &&
342202375Srdivacky        LI->getParent()->getTerminator()->getNumSuccessors() != 1)
343202375Srdivacky      return 0;
344202375Srdivacky  }
345251662Sdim
346202375Srdivacky  // Okay, they are all the same operation.  Create a new PHI node of the
347202375Srdivacky  // correct type, and PHI together all of the LHS's of the instructions.
348202375Srdivacky  PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
349221345Sdim                                   PN.getNumIncomingValues(),
350202375Srdivacky                                   PN.getName()+".in");
351251662Sdim
352202375Srdivacky  Value *InVal = FirstLI->getOperand(0);
353202375Srdivacky  NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
354251662Sdim
355202375Srdivacky  // Add all operands to the new PHI.
356202375Srdivacky  for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
357202375Srdivacky    Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
358202375Srdivacky    if (NewInVal != InVal)
359202375Srdivacky      InVal = 0;
360202375Srdivacky    NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
361202375Srdivacky  }
362251662Sdim
363202375Srdivacky  Value *PhiVal;
364202375Srdivacky  if (InVal) {
365202375Srdivacky    // The new PHI unions all of the same values together.  This is really
366202375Srdivacky    // common, so we handle it intelligently here for compile-time speed.
367202375Srdivacky    PhiVal = InVal;
368202375Srdivacky    delete NewPN;
369202375Srdivacky  } else {
370202375Srdivacky    InsertNewInstBefore(NewPN, PN);
371202375Srdivacky    PhiVal = NewPN;
372202375Srdivacky  }
373251662Sdim
374202375Srdivacky  // If this was a volatile load that we are merging, make sure to loop through
375202375Srdivacky  // and mark all the input loads as non-volatile.  If we don't do this, we will
376202375Srdivacky  // insert a new volatile load and the old ones will not be deletable.
377202375Srdivacky  if (isVolatile)
378202375Srdivacky    for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
379202375Srdivacky      cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
380251662Sdim
381223017Sdim  LoadInst *NewLI = new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
382223017Sdim  NewLI->setDebugLoc(FirstLI->getDebugLoc());
383223017Sdim  return NewLI;
384202375Srdivacky}
385202375Srdivacky
386202375Srdivacky
387202375Srdivacky
388202375Srdivacky/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
389202375Srdivacky/// operator and they all are only used by the PHI, PHI together their
390202375Srdivacky/// inputs, and do the operation once, to the result of the PHI.
391202375SrdivackyInstruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
392202375Srdivacky  Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
393202375Srdivacky
394202375Srdivacky  if (isa<GetElementPtrInst>(FirstInst))
395202375Srdivacky    return FoldPHIArgGEPIntoPHI(PN);
396202375Srdivacky  if (isa<LoadInst>(FirstInst))
397202375Srdivacky    return FoldPHIArgLoadIntoPHI(PN);
398251662Sdim
399202375Srdivacky  // Scan the instruction, looking for input operations that can be folded away.
400202375Srdivacky  // If all input operands to the phi are the same instruction (e.g. a cast from
401202375Srdivacky  // the same type or "+42") we can pull the operation through the PHI, reducing
402202375Srdivacky  // code size and simplifying code.
403202375Srdivacky  Constant *ConstantOp = 0;
404226633Sdim  Type *CastSrcTy = 0;
405218893Sdim  bool isNUW = false, isNSW = false, isExact = false;
406251662Sdim
407202375Srdivacky  if (isa<CastInst>(FirstInst)) {
408202375Srdivacky    CastSrcTy = FirstInst->getOperand(0)->getType();
409202375Srdivacky
410202375Srdivacky    // Be careful about transforming integer PHIs.  We don't want to pessimize
411202375Srdivacky    // the code by turning an i32 into an i1293.
412204642Srdivacky    if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
413202375Srdivacky      if (!ShouldChangeType(PN.getType(), CastSrcTy))
414202375Srdivacky        return 0;
415202375Srdivacky    }
416202375Srdivacky  } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
417251662Sdim    // Can fold binop, compare or shift here if the RHS is a constant,
418202375Srdivacky    // otherwise call FoldPHIArgBinOpIntoPHI.
419202375Srdivacky    ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
420202375Srdivacky    if (ConstantOp == 0)
421202375Srdivacky      return FoldPHIArgBinOpIntoPHI(PN);
422251662Sdim
423218893Sdim    if (OverflowingBinaryOperator *BO =
424218893Sdim        dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
425218893Sdim      isNUW = BO->hasNoUnsignedWrap();
426218893Sdim      isNSW = BO->hasNoSignedWrap();
427218893Sdim    } else if (PossiblyExactOperator *PEO =
428218893Sdim               dyn_cast<PossiblyExactOperator>(FirstInst))
429218893Sdim      isExact = PEO->isExact();
430202375Srdivacky  } else {
431202375Srdivacky    return 0;  // Cannot fold this operation.
432202375Srdivacky  }
433202375Srdivacky
434202375Srdivacky  // Check to see if all arguments are the same operation.
435202375Srdivacky  for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
436202375Srdivacky    Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
437202375Srdivacky    if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
438202375Srdivacky      return 0;
439202375Srdivacky    if (CastSrcTy) {
440202375Srdivacky      if (I->getOperand(0)->getType() != CastSrcTy)
441202375Srdivacky        return 0;  // Cast operation must match.
442202375Srdivacky    } else if (I->getOperand(1) != ConstantOp) {
443202375Srdivacky      return 0;
444202375Srdivacky    }
445251662Sdim
446218893Sdim    if (isNUW)
447218893Sdim      isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
448218893Sdim    if (isNSW)
449218893Sdim      isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
450218893Sdim    if (isExact)
451218893Sdim      isExact = cast<PossiblyExactOperator>(I)->isExact();
452202375Srdivacky  }
453202375Srdivacky
454202375Srdivacky  // Okay, they are all the same operation.  Create a new PHI node of the
455202375Srdivacky  // correct type, and PHI together all of the LHS's of the instructions.
456202375Srdivacky  PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
457221345Sdim                                   PN.getNumIncomingValues(),
458202375Srdivacky                                   PN.getName()+".in");
459202375Srdivacky
460202375Srdivacky  Value *InVal = FirstInst->getOperand(0);
461202375Srdivacky  NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
462202375Srdivacky
463202375Srdivacky  // Add all operands to the new PHI.
464202375Srdivacky  for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
465202375Srdivacky    Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
466202375Srdivacky    if (NewInVal != InVal)
467202375Srdivacky      InVal = 0;
468202375Srdivacky    NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
469202375Srdivacky  }
470202375Srdivacky
471202375Srdivacky  Value *PhiVal;
472202375Srdivacky  if (InVal) {
473202375Srdivacky    // The new PHI unions all of the same values together.  This is really
474202375Srdivacky    // common, so we handle it intelligently here for compile-time speed.
475202375Srdivacky    PhiVal = InVal;
476202375Srdivacky    delete NewPN;
477202375Srdivacky  } else {
478202375Srdivacky    InsertNewInstBefore(NewPN, PN);
479202375Srdivacky    PhiVal = NewPN;
480202375Srdivacky  }
481202375Srdivacky
482202375Srdivacky  // Insert and return the new operation.
483223017Sdim  if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
484223017Sdim    CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
485223017Sdim                                       PN.getType());
486223017Sdim    NewCI->setDebugLoc(FirstInst->getDebugLoc());
487223017Sdim    return NewCI;
488223017Sdim  }
489251662Sdim
490218893Sdim  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
491218893Sdim    BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
492218893Sdim    if (isNUW) BinOp->setHasNoUnsignedWrap();
493218893Sdim    if (isNSW) BinOp->setHasNoSignedWrap();
494218893Sdim    if (isExact) BinOp->setIsExact();
495223017Sdim    BinOp->setDebugLoc(FirstInst->getDebugLoc());
496218893Sdim    return BinOp;
497218893Sdim  }
498251662Sdim
499202375Srdivacky  CmpInst *CIOp = cast<CmpInst>(FirstInst);
500223017Sdim  CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
501223017Sdim                                   PhiVal, ConstantOp);
502223017Sdim  NewCI->setDebugLoc(FirstInst->getDebugLoc());
503223017Sdim  return NewCI;
504202375Srdivacky}
505202375Srdivacky
506202375Srdivacky/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
507202375Srdivacky/// that is dead.
508202375Srdivackystatic bool DeadPHICycle(PHINode *PN,
509202375Srdivacky                         SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
510202375Srdivacky  if (PN->use_empty()) return true;
511202375Srdivacky  if (!PN->hasOneUse()) return false;
512202375Srdivacky
513202375Srdivacky  // Remember this node, and if we find the cycle, return.
514202375Srdivacky  if (!PotentiallyDeadPHIs.insert(PN))
515202375Srdivacky    return true;
516251662Sdim
517202375Srdivacky  // Don't scan crazily complex things.
518202375Srdivacky  if (PotentiallyDeadPHIs.size() == 16)
519202375Srdivacky    return false;
520202375Srdivacky
521202375Srdivacky  if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
522202375Srdivacky    return DeadPHICycle(PU, PotentiallyDeadPHIs);
523202375Srdivacky
524202375Srdivacky  return false;
525202375Srdivacky}
526202375Srdivacky
527202375Srdivacky/// PHIsEqualValue - Return true if this phi node is always equal to
528202375Srdivacky/// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
529202375Srdivacky///   z = some value; x = phi (y, z); y = phi (x, z)
530251662Sdimstatic bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
531202375Srdivacky                           SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
532202375Srdivacky  // See if we already saw this PHI node.
533202375Srdivacky  if (!ValueEqualPHIs.insert(PN))
534202375Srdivacky    return true;
535251662Sdim
536202375Srdivacky  // Don't scan crazily complex things.
537202375Srdivacky  if (ValueEqualPHIs.size() == 16)
538202375Srdivacky    return false;
539251662Sdim
540202375Srdivacky  // Scan the operands to see if they are either phi nodes or are equal to
541202375Srdivacky  // the value.
542202375Srdivacky  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
543202375Srdivacky    Value *Op = PN->getIncomingValue(i);
544202375Srdivacky    if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
545202375Srdivacky      if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
546202375Srdivacky        return false;
547202375Srdivacky    } else if (Op != NonPhiInVal)
548202375Srdivacky      return false;
549202375Srdivacky  }
550251662Sdim
551202375Srdivacky  return true;
552202375Srdivacky}
553202375Srdivacky
554202375Srdivacky
555202375Srdivackynamespace {
556202375Srdivackystruct PHIUsageRecord {
557202375Srdivacky  unsigned PHIId;     // The ID # of the PHI (something determinstic to sort on)
558202375Srdivacky  unsigned Shift;     // The amount shifted.
559202375Srdivacky  Instruction *Inst;  // The trunc instruction.
560251662Sdim
561202375Srdivacky  PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
562202375Srdivacky    : PHIId(pn), Shift(Sh), Inst(User) {}
563251662Sdim
564202375Srdivacky  bool operator<(const PHIUsageRecord &RHS) const {
565202375Srdivacky    if (PHIId < RHS.PHIId) return true;
566202375Srdivacky    if (PHIId > RHS.PHIId) return false;
567202375Srdivacky    if (Shift < RHS.Shift) return true;
568202375Srdivacky    if (Shift > RHS.Shift) return false;
569202375Srdivacky    return Inst->getType()->getPrimitiveSizeInBits() <
570202375Srdivacky           RHS.Inst->getType()->getPrimitiveSizeInBits();
571202375Srdivacky  }
572202375Srdivacky};
573251662Sdim
574202375Srdivackystruct LoweredPHIRecord {
575202375Srdivacky  PHINode *PN;        // The PHI that was lowered.
576202375Srdivacky  unsigned Shift;     // The amount shifted.
577202375Srdivacky  unsigned Width;     // The width extracted.
578251662Sdim
579226633Sdim  LoweredPHIRecord(PHINode *pn, unsigned Sh, Type *Ty)
580202375Srdivacky    : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
581251662Sdim
582202375Srdivacky  // Ctor form used by DenseMap.
583202375Srdivacky  LoweredPHIRecord(PHINode *pn, unsigned Sh)
584202375Srdivacky    : PN(pn), Shift(Sh), Width(0) {}
585202375Srdivacky};
586202375Srdivacky}
587202375Srdivacky
588202375Srdivackynamespace llvm {
589202375Srdivacky  template<>
590202375Srdivacky  struct DenseMapInfo<LoweredPHIRecord> {
591202375Srdivacky    static inline LoweredPHIRecord getEmptyKey() {
592202375Srdivacky      return LoweredPHIRecord(0, 0);
593202375Srdivacky    }
594202375Srdivacky    static inline LoweredPHIRecord getTombstoneKey() {
595202375Srdivacky      return LoweredPHIRecord(0, 1);
596202375Srdivacky    }
597202375Srdivacky    static unsigned getHashValue(const LoweredPHIRecord &Val) {
598202375Srdivacky      return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
599202375Srdivacky             (Val.Width>>3);
600202375Srdivacky    }
601202375Srdivacky    static bool isEqual(const LoweredPHIRecord &LHS,
602202375Srdivacky                        const LoweredPHIRecord &RHS) {
603202375Srdivacky      return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
604202375Srdivacky             LHS.Width == RHS.Width;
605202375Srdivacky    }
606202375Srdivacky  };
607202375Srdivacky}
608202375Srdivacky
609202375Srdivacky
610202375Srdivacky/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
611202375Srdivacky/// illegal type: see if it is only used by trunc or trunc(lshr) operations.  If
612202375Srdivacky/// so, we split the PHI into the various pieces being extracted.  This sort of
613202375Srdivacky/// thing is introduced when SROA promotes an aggregate to large integer values.
614202375Srdivacky///
615202375Srdivacky/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
616202375Srdivacky/// inttoptr.  We should produce new PHIs in the right type.
617202375Srdivacky///
618202375SrdivackyInstruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
619202375Srdivacky  // PHIUsers - Keep track of all of the truncated values extracted from a set
620202375Srdivacky  // of PHIs, along with their offset.  These are the things we want to rewrite.
621202375Srdivacky  SmallVector<PHIUsageRecord, 16> PHIUsers;
622251662Sdim
623202375Srdivacky  // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
624202375Srdivacky  // nodes which are extracted from. PHIsToSlice is a set we use to avoid
625202375Srdivacky  // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
626202375Srdivacky  // check the uses of (to ensure they are all extracts).
627202375Srdivacky  SmallVector<PHINode*, 8> PHIsToSlice;
628202375Srdivacky  SmallPtrSet<PHINode*, 8> PHIsInspected;
629251662Sdim
630202375Srdivacky  PHIsToSlice.push_back(&FirstPhi);
631202375Srdivacky  PHIsInspected.insert(&FirstPhi);
632251662Sdim
633202375Srdivacky  for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
634202375Srdivacky    PHINode *PN = PHIsToSlice[PHIId];
635251662Sdim
636202375Srdivacky    // Scan the input list of the PHI.  If any input is an invoke, and if the
637202375Srdivacky    // input is defined in the predecessor, then we won't be split the critical
638202375Srdivacky    // edge which is required to insert a truncate.  Because of this, we have to
639202375Srdivacky    // bail out.
640202375Srdivacky    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
641202375Srdivacky      InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
642202375Srdivacky      if (II == 0) continue;
643202375Srdivacky      if (II->getParent() != PN->getIncomingBlock(i))
644202375Srdivacky        continue;
645251662Sdim
646202375Srdivacky      // If we have a phi, and if it's directly in the predecessor, then we have
647202375Srdivacky      // a critical edge where we need to put the truncate.  Since we can't
648202375Srdivacky      // split the edge in instcombine, we have to bail out.
649202375Srdivacky      return 0;
650202375Srdivacky    }
651251662Sdim
652251662Sdim
653202375Srdivacky    for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
654202375Srdivacky         UI != E; ++UI) {
655202375Srdivacky      Instruction *User = cast<Instruction>(*UI);
656251662Sdim
657202375Srdivacky      // If the user is a PHI, inspect its uses recursively.
658202375Srdivacky      if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
659202375Srdivacky        if (PHIsInspected.insert(UserPN))
660202375Srdivacky          PHIsToSlice.push_back(UserPN);
661202375Srdivacky        continue;
662202375Srdivacky      }
663251662Sdim
664202375Srdivacky      // Truncates are always ok.
665202375Srdivacky      if (isa<TruncInst>(User)) {
666202375Srdivacky        PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
667202375Srdivacky        continue;
668202375Srdivacky      }
669251662Sdim
670202375Srdivacky      // Otherwise it must be a lshr which can only be used by one trunc.
671202375Srdivacky      if (User->getOpcode() != Instruction::LShr ||
672202375Srdivacky          !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
673202375Srdivacky          !isa<ConstantInt>(User->getOperand(1)))
674202375Srdivacky        return 0;
675251662Sdim
676202375Srdivacky      unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
677202375Srdivacky      PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
678202375Srdivacky    }
679202375Srdivacky  }
680251662Sdim
681202375Srdivacky  // If we have no users, they must be all self uses, just nuke the PHI.
682202375Srdivacky  if (PHIUsers.empty())
683202375Srdivacky    return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
684251662Sdim
685202375Srdivacky  // If this phi node is transformable, create new PHIs for all the pieces
686202375Srdivacky  // extracted out of it.  First, sort the users by their offset and size.
687202375Srdivacky  array_pod_sort(PHIUsers.begin(), PHIUsers.end());
688251662Sdim
689263508Sdim  DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
690263508Sdim        for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
691263508Sdim          dbgs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] << '\n';
692263508Sdim    );
693251662Sdim
694202375Srdivacky  // PredValues - This is a temporary used when rewriting PHI nodes.  It is
695202375Srdivacky  // hoisted out here to avoid construction/destruction thrashing.
696202375Srdivacky  DenseMap<BasicBlock*, Value*> PredValues;
697251662Sdim
698202375Srdivacky  // ExtractedVals - Each new PHI we introduce is saved here so we don't
699202375Srdivacky  // introduce redundant PHIs.
700202375Srdivacky  DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
701251662Sdim
702202375Srdivacky  for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
703202375Srdivacky    unsigned PHIId = PHIUsers[UserI].PHIId;
704202375Srdivacky    PHINode *PN = PHIsToSlice[PHIId];
705202375Srdivacky    unsigned Offset = PHIUsers[UserI].Shift;
706226633Sdim    Type *Ty = PHIUsers[UserI].Inst->getType();
707251662Sdim
708202375Srdivacky    PHINode *EltPHI;
709251662Sdim
710202375Srdivacky    // If we've already lowered a user like this, reuse the previously lowered
711202375Srdivacky    // value.
712202375Srdivacky    if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
713251662Sdim
714202375Srdivacky      // Otherwise, Create the new PHI node for this user.
715221345Sdim      EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
716221345Sdim                               PN->getName()+".off"+Twine(Offset), PN);
717202375Srdivacky      assert(EltPHI->getType() != PN->getType() &&
718202375Srdivacky             "Truncate didn't shrink phi?");
719251662Sdim
720202375Srdivacky      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
721202375Srdivacky        BasicBlock *Pred = PN->getIncomingBlock(i);
722202375Srdivacky        Value *&PredVal = PredValues[Pred];
723251662Sdim
724202375Srdivacky        // If we already have a value for this predecessor, reuse it.
725202375Srdivacky        if (PredVal) {
726202375Srdivacky          EltPHI->addIncoming(PredVal, Pred);
727202375Srdivacky          continue;
728202375Srdivacky        }
729202375Srdivacky
730202375Srdivacky        // Handle the PHI self-reuse case.
731202375Srdivacky        Value *InVal = PN->getIncomingValue(i);
732202375Srdivacky        if (InVal == PN) {
733202375Srdivacky          PredVal = EltPHI;
734202375Srdivacky          EltPHI->addIncoming(PredVal, Pred);
735202375Srdivacky          continue;
736202375Srdivacky        }
737251662Sdim
738202375Srdivacky        if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
739202375Srdivacky          // If the incoming value was a PHI, and if it was one of the PHIs we
740202375Srdivacky          // already rewrote it, just use the lowered value.
741202375Srdivacky          if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
742202375Srdivacky            PredVal = Res;
743202375Srdivacky            EltPHI->addIncoming(PredVal, Pred);
744202375Srdivacky            continue;
745202375Srdivacky          }
746202375Srdivacky        }
747251662Sdim
748202375Srdivacky        // Otherwise, do an extract in the predecessor.
749202375Srdivacky        Builder->SetInsertPoint(Pred, Pred->getTerminator());
750202375Srdivacky        Value *Res = InVal;
751202375Srdivacky        if (Offset)
752202375Srdivacky          Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
753202375Srdivacky                                                          Offset), "extract");
754202375Srdivacky        Res = Builder->CreateTrunc(Res, Ty, "extract.t");
755202375Srdivacky        PredVal = Res;
756202375Srdivacky        EltPHI->addIncoming(Res, Pred);
757251662Sdim
758202375Srdivacky        // If the incoming value was a PHI, and if it was one of the PHIs we are
759202375Srdivacky        // rewriting, we will ultimately delete the code we inserted.  This
760202375Srdivacky        // means we need to revisit that PHI to make sure we extract out the
761202375Srdivacky        // needed piece.
762202375Srdivacky        if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
763202375Srdivacky          if (PHIsInspected.count(OldInVal)) {
764202375Srdivacky            unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
765202375Srdivacky                                          OldInVal)-PHIsToSlice.begin();
766251662Sdim            PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
767202375Srdivacky                                              cast<Instruction>(Res)));
768202375Srdivacky            ++UserE;
769202375Srdivacky          }
770202375Srdivacky      }
771202375Srdivacky      PredValues.clear();
772251662Sdim
773263508Sdim      DEBUG(dbgs() << "  Made element PHI for offset " << Offset << ": "
774202375Srdivacky                   << *EltPHI << '\n');
775202375Srdivacky      ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
776202375Srdivacky    }
777251662Sdim
778202375Srdivacky    // Replace the use of this piece with the PHI node.
779202375Srdivacky    ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
780202375Srdivacky  }
781251662Sdim
782202375Srdivacky  // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
783202375Srdivacky  // with undefs.
784202375Srdivacky  Value *Undef = UndefValue::get(FirstPhi.getType());
785202375Srdivacky  for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
786202375Srdivacky    ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
787202375Srdivacky  return ReplaceInstUsesWith(FirstPhi, Undef);
788202375Srdivacky}
789202375Srdivacky
790202375Srdivacky// PHINode simplification
791202375Srdivacky//
792202375SrdivackyInstruction *InstCombiner::visitPHINode(PHINode &PN) {
793263508Sdim  if (Value *V = SimplifyInstruction(&PN, TD, TLI))
794202375Srdivacky    return ReplaceInstUsesWith(PN, V);
795202375Srdivacky
796202375Srdivacky  // If all PHI operands are the same operation, pull them through the PHI,
797202375Srdivacky  // reducing code size.
798202375Srdivacky  if (isa<Instruction>(PN.getIncomingValue(0)) &&
799202375Srdivacky      isa<Instruction>(PN.getIncomingValue(1)) &&
800202375Srdivacky      cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
801202375Srdivacky      cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
802202375Srdivacky      // FIXME: The hasOneUse check will fail for PHIs that use the value more
803202375Srdivacky      // than themselves more than once.
804202375Srdivacky      PN.getIncomingValue(0)->hasOneUse())
805202375Srdivacky    if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
806202375Srdivacky      return Result;
807202375Srdivacky
808202375Srdivacky  // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
809202375Srdivacky  // this PHI only has a single use (a PHI), and if that PHI only has one use (a
810202375Srdivacky  // PHI)... break the cycle.
811202375Srdivacky  if (PN.hasOneUse()) {
812202375Srdivacky    Instruction *PHIUser = cast<Instruction>(PN.use_back());
813202375Srdivacky    if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
814202375Srdivacky      SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
815202375Srdivacky      PotentiallyDeadPHIs.insert(&PN);
816202375Srdivacky      if (DeadPHICycle(PU, PotentiallyDeadPHIs))
817202375Srdivacky        return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
818202375Srdivacky    }
819251662Sdim
820202375Srdivacky    // If this phi has a single use, and if that use just computes a value for
821202375Srdivacky    // the next iteration of a loop, delete the phi.  This occurs with unused
822202375Srdivacky    // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
823202375Srdivacky    // common case here is good because the only other things that catch this
824202375Srdivacky    // are induction variable analysis (sometimes) and ADCE, which is only run
825202375Srdivacky    // late.
826202375Srdivacky    if (PHIUser->hasOneUse() &&
827202375Srdivacky        (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
828202375Srdivacky        PHIUser->use_back() == &PN) {
829202375Srdivacky      return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
830202375Srdivacky    }
831202375Srdivacky  }
832202375Srdivacky
833202375Srdivacky  // We sometimes end up with phi cycles that non-obviously end up being the
834202375Srdivacky  // same value, for example:
835202375Srdivacky  //   z = some value; x = phi (y, z); y = phi (x, z)
836202375Srdivacky  // where the phi nodes don't necessarily need to be in the same block.  Do a
837202375Srdivacky  // quick check to see if the PHI node only contains a single non-phi value, if
838202375Srdivacky  // so, scan to see if the phi cycle is actually equal to that value.
839202375Srdivacky  {
840221345Sdim    unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
841202375Srdivacky    // Scan for the first non-phi operand.
842221345Sdim    while (InValNo != NumIncomingVals &&
843202375Srdivacky           isa<PHINode>(PN.getIncomingValue(InValNo)))
844202375Srdivacky      ++InValNo;
845202375Srdivacky
846221345Sdim    if (InValNo != NumIncomingVals) {
847221345Sdim      Value *NonPhiInVal = PN.getIncomingValue(InValNo);
848251662Sdim
849202375Srdivacky      // Scan the rest of the operands to see if there are any conflicts, if so
850202375Srdivacky      // there is no need to recursively scan other phis.
851221345Sdim      for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
852202375Srdivacky        Value *OpVal = PN.getIncomingValue(InValNo);
853202375Srdivacky        if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
854202375Srdivacky          break;
855202375Srdivacky      }
856251662Sdim
857202375Srdivacky      // If we scanned over all operands, then we have one unique value plus
858202375Srdivacky      // phi values.  Scan PHI nodes to see if they all merge in each other or
859202375Srdivacky      // the value.
860221345Sdim      if (InValNo == NumIncomingVals) {
861202375Srdivacky        SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
862202375Srdivacky        if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
863202375Srdivacky          return ReplaceInstUsesWith(PN, NonPhiInVal);
864202375Srdivacky      }
865202375Srdivacky    }
866202375Srdivacky  }
867202375Srdivacky
868202375Srdivacky  // If there are multiple PHIs, sort their operands so that they all list
869202375Srdivacky  // the blocks in the same order. This will help identical PHIs be eliminated
870202375Srdivacky  // by other passes. Other passes shouldn't depend on this for correctness
871202375Srdivacky  // however.
872202375Srdivacky  PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
873202375Srdivacky  if (&PN != FirstPN)
874202375Srdivacky    for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
875202375Srdivacky      BasicBlock *BBA = PN.getIncomingBlock(i);
876202375Srdivacky      BasicBlock *BBB = FirstPN->getIncomingBlock(i);
877202375Srdivacky      if (BBA != BBB) {
878202375Srdivacky        Value *VA = PN.getIncomingValue(i);
879202375Srdivacky        unsigned j = PN.getBasicBlockIndex(BBB);
880202375Srdivacky        Value *VB = PN.getIncomingValue(j);
881202375Srdivacky        PN.setIncomingBlock(i, BBB);
882202375Srdivacky        PN.setIncomingValue(i, VB);
883202375Srdivacky        PN.setIncomingBlock(j, BBA);
884202375Srdivacky        PN.setIncomingValue(j, VA);
885202375Srdivacky        // NOTE: Instcombine normally would want us to "return &PN" if we
886202375Srdivacky        // modified any of the operands of an instruction.  However, since we
887202375Srdivacky        // aren't adding or removing uses (just rearranging them) we don't do
888202375Srdivacky        // this in this case.
889202375Srdivacky      }
890202375Srdivacky    }
891202375Srdivacky
892202375Srdivacky  // If this is an integer PHI and we know that it has an illegal type, see if
893202375Srdivacky  // it is only used by trunc or trunc(lshr) operations.  If so, we split the
894202375Srdivacky  // PHI into the various pieces being extracted.  This sort of thing is
895202375Srdivacky  // introduced when SROA promotes an aggregate to a single large integer type.
896204642Srdivacky  if (PN.getType()->isIntegerTy() && TD &&
897202375Srdivacky      !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
898202375Srdivacky    if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
899202375Srdivacky      return Res;
900251662Sdim
901202375Srdivacky  return 0;
902202375Srdivacky}
903