Nope, still breaks the release selfhost bots :(
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombinePHI.cpp
1 //===- 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
14 #include "InstCombine.h"
15 #include "llvm/Target/TargetData.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 using namespace llvm;
19
20 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
21 /// and if a/b/c and the add's all have a single use, turn this into a phi
22 /// and a single binop.
23 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
24   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
25   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
26   unsigned Opc = FirstInst->getOpcode();
27   Value *LHSVal = FirstInst->getOperand(0);
28   Value *RHSVal = FirstInst->getOperand(1);
29     
30   const Type *LHSType = LHSVal->getType();
31   const Type *RHSType = RHSVal->getType();
32   
33   // Scan to see if all operands are the same opcode, and all have one use.
34   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
35     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
36     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
37         // Verify type of the LHS matches so we don't fold cmp's of different
38         // types or GEP's with different index types.
39         I->getOperand(0)->getType() != LHSType ||
40         I->getOperand(1)->getType() != RHSType)
41       return 0;
42
43     // If they are CmpInst instructions, check their predicates
44     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
45       if (cast<CmpInst>(I)->getPredicate() !=
46           cast<CmpInst>(FirstInst)->getPredicate())
47         return 0;
48     
49     // Keep track of which operand needs a phi node.
50     if (I->getOperand(0) != LHSVal) LHSVal = 0;
51     if (I->getOperand(1) != RHSVal) RHSVal = 0;
52   }
53
54   // If both LHS and RHS would need a PHI, don't do this transformation,
55   // because it would increase the number of PHIs entering the block,
56   // which leads to higher register pressure. This is especially
57   // bad when the PHIs are in the header of a loop.
58   if (!LHSVal && !RHSVal)
59     return 0;
60   
61   // Otherwise, this is safe to transform!
62   
63   Value *InLHS = FirstInst->getOperand(0);
64   Value *InRHS = FirstInst->getOperand(1);
65   PHINode *NewLHS = 0, *NewRHS = 0;
66   if (LHSVal == 0) {
67     NewLHS = PHINode::Create(LHSType,
68                              FirstInst->getOperand(0)->getName() + ".pn");
69     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
70     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
71     InsertNewInstBefore(NewLHS, PN);
72     LHSVal = NewLHS;
73   }
74   
75   if (RHSVal == 0) {
76     NewRHS = PHINode::Create(RHSType,
77                              FirstInst->getOperand(1)->getName() + ".pn");
78     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
79     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
80     InsertNewInstBefore(NewRHS, PN);
81     RHSVal = NewRHS;
82   }
83   
84   // Add all operands to the new PHIs.
85   if (NewLHS || NewRHS) {
86     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
87       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
88       if (NewLHS) {
89         Value *NewInLHS = InInst->getOperand(0);
90         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
91       }
92       if (NewRHS) {
93         Value *NewInRHS = InInst->getOperand(1);
94         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
95       }
96     }
97   }
98     
99   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
100     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
101   CmpInst *CIOp = cast<CmpInst>(FirstInst);
102   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
103                          LHSVal, RHSVal);
104 }
105
106 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
107   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
108   
109   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
110                                         FirstInst->op_end());
111   // This is true if all GEP bases are allocas and if all indices into them are
112   // constants.
113   bool AllBasePointersAreAllocas = true;
114
115   // We don't want to replace this phi if the replacement would require
116   // more than one phi, which leads to higher register pressure. This is
117   // especially bad when the PHIs are in the header of a loop.
118   bool NeededPhi = false;
119   
120   // Scan to see if all operands are the same opcode, and all have one use.
121   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
122     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
123     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
124       GEP->getNumOperands() != FirstInst->getNumOperands())
125       return 0;
126
127     // Keep track of whether or not all GEPs are of alloca pointers.
128     if (AllBasePointersAreAllocas &&
129         (!isa<AllocaInst>(GEP->getOperand(0)) ||
130          !GEP->hasAllConstantIndices()))
131       AllBasePointersAreAllocas = false;
132     
133     // Compare the operand lists.
134     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
135       if (FirstInst->getOperand(op) == GEP->getOperand(op))
136         continue;
137       
138       // Don't merge two GEPs when two operands differ (introducing phi nodes)
139       // if one of the PHIs has a constant for the index.  The index may be
140       // substantially cheaper to compute for the constants, so making it a
141       // variable index could pessimize the path.  This also handles the case
142       // for struct indices, which must always be constant.
143       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
144           isa<ConstantInt>(GEP->getOperand(op)))
145         return 0;
146       
147       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
148         return 0;
149
150       // If we already needed a PHI for an earlier operand, and another operand
151       // also requires a PHI, we'd be introducing more PHIs than we're
152       // eliminating, which increases register pressure on entry to the PHI's
153       // block.
154       if (NeededPhi)
155         return 0;
156
157       FixedOperands[op] = 0;  // Needs a PHI.
158       NeededPhi = true;
159     }
160   }
161   
162   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
163   // bother doing this transformation.  At best, this will just save a bit of
164   // offset calculation, but all the predecessors will have to materialize the
165   // stack address into a register anyway.  We'd actually rather *clone* the
166   // load up into the predecessors so that we have a load of a gep of an alloca,
167   // which can usually all be folded into the load.
168   if (AllBasePointersAreAllocas)
169     return 0;
170   
171   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
172   // that is variable.
173   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
174   
175   bool HasAnyPHIs = false;
176   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
177     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
178     Value *FirstOp = FirstInst->getOperand(i);
179     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
180                                      FirstOp->getName()+".pn");
181     InsertNewInstBefore(NewPN, PN);
182     
183     NewPN->reserveOperandSpace(e);
184     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
185     OperandPhis[i] = NewPN;
186     FixedOperands[i] = NewPN;
187     HasAnyPHIs = true;
188   }
189
190   
191   // Add all operands to the new PHIs.
192   if (HasAnyPHIs) {
193     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
194       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
195       BasicBlock *InBB = PN.getIncomingBlock(i);
196       
197       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
198         if (PHINode *OpPhi = OperandPhis[op])
199           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
200     }
201   }
202   
203   Value *Base = FixedOperands[0];
204   return cast<GEPOperator>(FirstInst)->isInBounds() ?
205     GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
206                                       FixedOperands.end()) :
207     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
208                               FixedOperands.end());
209 }
210
211
212 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
213 /// sink the load out of the block that defines it.  This means that it must be
214 /// obvious the value of the load is not changed from the point of the load to
215 /// the end of the block it is in.
216 ///
217 /// Finally, it is safe, but not profitable, to sink a load targetting a
218 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
219 /// to a register.
220 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
221   BasicBlock::iterator BBI = L, E = L->getParent()->end();
222   
223   for (++BBI; BBI != E; ++BBI)
224     if (BBI->mayWriteToMemory())
225       return false;
226   
227   // Check for non-address taken alloca.  If not address-taken already, it isn't
228   // profitable to do this xform.
229   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
230     bool isAddressTaken = false;
231     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
232          UI != E; ++UI) {
233       User *U = *UI;
234       if (isa<LoadInst>(U)) continue;
235       if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
236         // If storing TO the alloca, then the address isn't taken.
237         if (SI->getOperand(1) == AI) continue;
238       }
239       isAddressTaken = true;
240       break;
241     }
242     
243     if (!isAddressTaken && AI->isStaticAlloca())
244       return false;
245   }
246   
247   // If this load is a load from a GEP with a constant offset from an alloca,
248   // then we don't want to sink it.  In its present form, it will be
249   // load [constant stack offset].  Sinking it will cause us to have to
250   // materialize the stack addresses in each predecessor in a register only to
251   // do a shared load from register in the successor.
252   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
253     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
254       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
255         return false;
256   
257   return true;
258 }
259
260 Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
261   LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
262   
263   // When processing loads, we need to propagate two bits of information to the
264   // sunk load: whether it is volatile, and what its alignment is.  We currently
265   // don't sink loads when some have their alignment specified and some don't.
266   // visitLoadInst will propagate an alignment onto the load when TD is around,
267   // and if TD isn't around, we can't handle the mixed case.
268   bool isVolatile = FirstLI->isVolatile();
269   unsigned LoadAlignment = FirstLI->getAlignment();
270   unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
271   
272   // We can't sink the load if the loaded value could be modified between the
273   // load and the PHI.
274   if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
275       !isSafeAndProfitableToSinkLoad(FirstLI))
276     return 0;
277   
278   // If the PHI is of volatile loads and the load block has multiple
279   // successors, sinking it would remove a load of the volatile value from
280   // the path through the other successor.
281   if (isVolatile && 
282       FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
283     return 0;
284   
285   // Check to see if all arguments are the same operation.
286   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
287     LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
288     if (!LI || !LI->hasOneUse())
289       return 0;
290     
291     // We can't sink the load if the loaded value could be modified between 
292     // the load and the PHI.
293     if (LI->isVolatile() != isVolatile ||
294         LI->getParent() != PN.getIncomingBlock(i) ||
295         LI->getPointerAddressSpace() != LoadAddrSpace ||
296         !isSafeAndProfitableToSinkLoad(LI))
297       return 0;
298       
299     // If some of the loads have an alignment specified but not all of them,
300     // we can't do the transformation.
301     if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
302       return 0;
303     
304     LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
305     
306     // If the PHI is of volatile loads and the load block has multiple
307     // successors, sinking it would remove a load of the volatile value from
308     // the path through the other successor.
309     if (isVolatile &&
310         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
311       return 0;
312   }
313   
314   // Okay, they are all the same operation.  Create a new PHI node of the
315   // correct type, and PHI together all of the LHS's of the instructions.
316   PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
317                                    PN.getName()+".in");
318   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
319   
320   Value *InVal = FirstLI->getOperand(0);
321   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
322   
323   // Add all operands to the new PHI.
324   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
325     Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
326     if (NewInVal != InVal)
327       InVal = 0;
328     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
329   }
330   
331   Value *PhiVal;
332   if (InVal) {
333     // The new PHI unions all of the same values together.  This is really
334     // common, so we handle it intelligently here for compile-time speed.
335     PhiVal = InVal;
336     delete NewPN;
337   } else {
338     InsertNewInstBefore(NewPN, PN);
339     PhiVal = NewPN;
340   }
341   
342   // If this was a volatile load that we are merging, make sure to loop through
343   // and mark all the input loads as non-volatile.  If we don't do this, we will
344   // insert a new volatile load and the old ones will not be deletable.
345   if (isVolatile)
346     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
347       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
348   
349   return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
350 }
351
352
353
354 /// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
355 /// operator and they all are only used by the PHI, PHI together their
356 /// inputs, and do the operation once, to the result of the PHI.
357 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
358   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
359
360   if (isa<GetElementPtrInst>(FirstInst))
361     return FoldPHIArgGEPIntoPHI(PN);
362   if (isa<LoadInst>(FirstInst))
363     return FoldPHIArgLoadIntoPHI(PN);
364   
365   // Scan the instruction, looking for input operations that can be folded away.
366   // If all input operands to the phi are the same instruction (e.g. a cast from
367   // the same type or "+42") we can pull the operation through the PHI, reducing
368   // code size and simplifying code.
369   Constant *ConstantOp = 0;
370   const Type *CastSrcTy = 0;
371   
372   if (isa<CastInst>(FirstInst)) {
373     CastSrcTy = FirstInst->getOperand(0)->getType();
374
375     // Be careful about transforming integer PHIs.  We don't want to pessimize
376     // the code by turning an i32 into an i1293.
377     if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
378       if (!ShouldChangeType(PN.getType(), CastSrcTy))
379         return 0;
380     }
381   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
382     // Can fold binop, compare or shift here if the RHS is a constant, 
383     // otherwise call FoldPHIArgBinOpIntoPHI.
384     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
385     if (ConstantOp == 0)
386       return FoldPHIArgBinOpIntoPHI(PN);
387   } else {
388     return 0;  // Cannot fold this operation.
389   }
390
391   // Check to see if all arguments are the same operation.
392   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
393     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
394     if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
395       return 0;
396     if (CastSrcTy) {
397       if (I->getOperand(0)->getType() != CastSrcTy)
398         return 0;  // Cast operation must match.
399     } else if (I->getOperand(1) != ConstantOp) {
400       return 0;
401     }
402   }
403
404   // Okay, they are all the same operation.  Create a new PHI node of the
405   // correct type, and PHI together all of the LHS's of the instructions.
406   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
407                                    PN.getName()+".in");
408   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
409
410   Value *InVal = FirstInst->getOperand(0);
411   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
412
413   // Add all operands to the new PHI.
414   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
415     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
416     if (NewInVal != InVal)
417       InVal = 0;
418     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
419   }
420
421   Value *PhiVal;
422   if (InVal) {
423     // The new PHI unions all of the same values together.  This is really
424     // common, so we handle it intelligently here for compile-time speed.
425     PhiVal = InVal;
426     delete NewPN;
427   } else {
428     InsertNewInstBefore(NewPN, PN);
429     PhiVal = NewPN;
430   }
431
432   // Insert and return the new operation.
433   if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
434     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
435   
436   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
437     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
438   
439   CmpInst *CIOp = cast<CmpInst>(FirstInst);
440   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
441                          PhiVal, ConstantOp);
442 }
443
444 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
445 /// that is dead.
446 static bool DeadPHICycle(PHINode *PN,
447                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
448   if (PN->use_empty()) return true;
449   if (!PN->hasOneUse()) return false;
450
451   // Remember this node, and if we find the cycle, return.
452   if (!PotentiallyDeadPHIs.insert(PN))
453     return true;
454   
455   // Don't scan crazily complex things.
456   if (PotentiallyDeadPHIs.size() == 16)
457     return false;
458
459   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
460     return DeadPHICycle(PU, PotentiallyDeadPHIs);
461
462   return false;
463 }
464
465 /// PHIsEqualValue - Return true if this phi node is always equal to
466 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
467 ///   z = some value; x = phi (y, z); y = phi (x, z)
468 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
469                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
470   // See if we already saw this PHI node.
471   if (!ValueEqualPHIs.insert(PN))
472     return true;
473   
474   // Don't scan crazily complex things.
475   if (ValueEqualPHIs.size() == 16)
476     return false;
477  
478   // Scan the operands to see if they are either phi nodes or are equal to
479   // the value.
480   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
481     Value *Op = PN->getIncomingValue(i);
482     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
483       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
484         return false;
485     } else if (Op != NonPhiInVal)
486       return false;
487   }
488   
489   return true;
490 }
491
492
493 namespace {
494 struct PHIUsageRecord {
495   unsigned PHIId;     // The ID # of the PHI (something determinstic to sort on)
496   unsigned Shift;     // The amount shifted.
497   Instruction *Inst;  // The trunc instruction.
498   
499   PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
500     : PHIId(pn), Shift(Sh), Inst(User) {}
501   
502   bool operator<(const PHIUsageRecord &RHS) const {
503     if (PHIId < RHS.PHIId) return true;
504     if (PHIId > RHS.PHIId) return false;
505     if (Shift < RHS.Shift) return true;
506     if (Shift > RHS.Shift) return false;
507     return Inst->getType()->getPrimitiveSizeInBits() <
508            RHS.Inst->getType()->getPrimitiveSizeInBits();
509   }
510 };
511   
512 struct LoweredPHIRecord {
513   PHINode *PN;        // The PHI that was lowered.
514   unsigned Shift;     // The amount shifted.
515   unsigned Width;     // The width extracted.
516   
517   LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
518     : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
519   
520   // Ctor form used by DenseMap.
521   LoweredPHIRecord(PHINode *pn, unsigned Sh)
522     : PN(pn), Shift(Sh), Width(0) {}
523 };
524 }
525
526 namespace llvm {
527   template<>
528   struct DenseMapInfo<LoweredPHIRecord> {
529     static inline LoweredPHIRecord getEmptyKey() {
530       return LoweredPHIRecord(0, 0);
531     }
532     static inline LoweredPHIRecord getTombstoneKey() {
533       return LoweredPHIRecord(0, 1);
534     }
535     static unsigned getHashValue(const LoweredPHIRecord &Val) {
536       return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
537              (Val.Width>>3);
538     }
539     static bool isEqual(const LoweredPHIRecord &LHS,
540                         const LoweredPHIRecord &RHS) {
541       return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
542              LHS.Width == RHS.Width;
543     }
544   };
545   template <>
546   struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
547 }
548
549
550 /// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
551 /// illegal type: see if it is only used by trunc or trunc(lshr) operations.  If
552 /// so, we split the PHI into the various pieces being extracted.  This sort of
553 /// thing is introduced when SROA promotes an aggregate to large integer values.
554 ///
555 /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
556 /// inttoptr.  We should produce new PHIs in the right type.
557 ///
558 Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
559   // PHIUsers - Keep track of all of the truncated values extracted from a set
560   // of PHIs, along with their offset.  These are the things we want to rewrite.
561   SmallVector<PHIUsageRecord, 16> PHIUsers;
562   
563   // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
564   // nodes which are extracted from. PHIsToSlice is a set we use to avoid
565   // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
566   // check the uses of (to ensure they are all extracts).
567   SmallVector<PHINode*, 8> PHIsToSlice;
568   SmallPtrSet<PHINode*, 8> PHIsInspected;
569   
570   PHIsToSlice.push_back(&FirstPhi);
571   PHIsInspected.insert(&FirstPhi);
572   
573   for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
574     PHINode *PN = PHIsToSlice[PHIId];
575     
576     // Scan the input list of the PHI.  If any input is an invoke, and if the
577     // input is defined in the predecessor, then we won't be split the critical
578     // edge which is required to insert a truncate.  Because of this, we have to
579     // bail out.
580     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
581       InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
582       if (II == 0) continue;
583       if (II->getParent() != PN->getIncomingBlock(i))
584         continue;
585      
586       // If we have a phi, and if it's directly in the predecessor, then we have
587       // a critical edge where we need to put the truncate.  Since we can't
588       // split the edge in instcombine, we have to bail out.
589       return 0;
590     }
591       
592     
593     for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
594          UI != E; ++UI) {
595       Instruction *User = cast<Instruction>(*UI);
596       
597       // If the user is a PHI, inspect its uses recursively.
598       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
599         if (PHIsInspected.insert(UserPN))
600           PHIsToSlice.push_back(UserPN);
601         continue;
602       }
603       
604       // Truncates are always ok.
605       if (isa<TruncInst>(User)) {
606         PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
607         continue;
608       }
609       
610       // Otherwise it must be a lshr which can only be used by one trunc.
611       if (User->getOpcode() != Instruction::LShr ||
612           !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
613           !isa<ConstantInt>(User->getOperand(1)))
614         return 0;
615       
616       unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
617       PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
618     }
619   }
620   
621   // If we have no users, they must be all self uses, just nuke the PHI.
622   if (PHIUsers.empty())
623     return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
624   
625   // If this phi node is transformable, create new PHIs for all the pieces
626   // extracted out of it.  First, sort the users by their offset and size.
627   array_pod_sort(PHIUsers.begin(), PHIUsers.end());
628   
629   DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
630             for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
631               errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
632         );
633   
634   // PredValues - This is a temporary used when rewriting PHI nodes.  It is
635   // hoisted out here to avoid construction/destruction thrashing.
636   DenseMap<BasicBlock*, Value*> PredValues;
637   
638   // ExtractedVals - Each new PHI we introduce is saved here so we don't
639   // introduce redundant PHIs.
640   DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
641   
642   for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
643     unsigned PHIId = PHIUsers[UserI].PHIId;
644     PHINode *PN = PHIsToSlice[PHIId];
645     unsigned Offset = PHIUsers[UserI].Shift;
646     const Type *Ty = PHIUsers[UserI].Inst->getType();
647     
648     PHINode *EltPHI;
649     
650     // If we've already lowered a user like this, reuse the previously lowered
651     // value.
652     if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
653       
654       // Otherwise, Create the new PHI node for this user.
655       EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
656       assert(EltPHI->getType() != PN->getType() &&
657              "Truncate didn't shrink phi?");
658     
659       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
660         BasicBlock *Pred = PN->getIncomingBlock(i);
661         Value *&PredVal = PredValues[Pred];
662         
663         // If we already have a value for this predecessor, reuse it.
664         if (PredVal) {
665           EltPHI->addIncoming(PredVal, Pred);
666           continue;
667         }
668
669         // Handle the PHI self-reuse case.
670         Value *InVal = PN->getIncomingValue(i);
671         if (InVal == PN) {
672           PredVal = EltPHI;
673           EltPHI->addIncoming(PredVal, Pred);
674           continue;
675         }
676         
677         if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
678           // If the incoming value was a PHI, and if it was one of the PHIs we
679           // already rewrote it, just use the lowered value.
680           if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
681             PredVal = Res;
682             EltPHI->addIncoming(PredVal, Pred);
683             continue;
684           }
685         }
686         
687         // Otherwise, do an extract in the predecessor.
688         Builder->SetInsertPoint(Pred, Pred->getTerminator());
689         Value *Res = InVal;
690         if (Offset)
691           Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
692                                                           Offset), "extract");
693         Res = Builder->CreateTrunc(Res, Ty, "extract.t");
694         PredVal = Res;
695         EltPHI->addIncoming(Res, Pred);
696         
697         // If the incoming value was a PHI, and if it was one of the PHIs we are
698         // rewriting, we will ultimately delete the code we inserted.  This
699         // means we need to revisit that PHI to make sure we extract out the
700         // needed piece.
701         if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
702           if (PHIsInspected.count(OldInVal)) {
703             unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
704                                           OldInVal)-PHIsToSlice.begin();
705             PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset, 
706                                               cast<Instruction>(Res)));
707             ++UserE;
708           }
709       }
710       PredValues.clear();
711       
712       DEBUG(errs() << "  Made element PHI for offset " << Offset << ": "
713                    << *EltPHI << '\n');
714       ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
715     }
716     
717     // Replace the use of this piece with the PHI node.
718     ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
719   }
720   
721   // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
722   // with undefs.
723   Value *Undef = UndefValue::get(FirstPhi.getType());
724   for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
725     ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
726   return ReplaceInstUsesWith(FirstPhi, Undef);
727 }
728
729 // PHINode simplification
730 //
731 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
732   // If LCSSA is around, don't mess with Phi nodes
733   if (MustPreserveLCSSA) return 0;
734   
735   if (Value *V = PN.hasConstantValue())
736     return ReplaceInstUsesWith(PN, V);
737
738   // If all PHI operands are the same operation, pull them through the PHI,
739   // reducing code size.
740   if (isa<Instruction>(PN.getIncomingValue(0)) &&
741       isa<Instruction>(PN.getIncomingValue(1)) &&
742       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
743       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
744       // FIXME: The hasOneUse check will fail for PHIs that use the value more
745       // than themselves more than once.
746       PN.getIncomingValue(0)->hasOneUse())
747     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
748       return Result;
749
750   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
751   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
752   // PHI)... break the cycle.
753   if (PN.hasOneUse()) {
754     Instruction *PHIUser = cast<Instruction>(PN.use_back());
755     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
756       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
757       PotentiallyDeadPHIs.insert(&PN);
758       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
759         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
760     }
761    
762     // If this phi has a single use, and if that use just computes a value for
763     // the next iteration of a loop, delete the phi.  This occurs with unused
764     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
765     // common case here is good because the only other things that catch this
766     // are induction variable analysis (sometimes) and ADCE, which is only run
767     // late.
768     if (PHIUser->hasOneUse() &&
769         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
770         PHIUser->use_back() == &PN) {
771       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
772     }
773   }
774
775   // We sometimes end up with phi cycles that non-obviously end up being the
776   // same value, for example:
777   //   z = some value; x = phi (y, z); y = phi (x, z)
778   // where the phi nodes don't necessarily need to be in the same block.  Do a
779   // quick check to see if the PHI node only contains a single non-phi value, if
780   // so, scan to see if the phi cycle is actually equal to that value.
781   {
782     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
783     // Scan for the first non-phi operand.
784     while (InValNo != NumOperandVals && 
785            isa<PHINode>(PN.getIncomingValue(InValNo)))
786       ++InValNo;
787
788     if (InValNo != NumOperandVals) {
789       Value *NonPhiInVal = PN.getOperand(InValNo);
790       
791       // Scan the rest of the operands to see if there are any conflicts, if so
792       // there is no need to recursively scan other phis.
793       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
794         Value *OpVal = PN.getIncomingValue(InValNo);
795         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
796           break;
797       }
798       
799       // If we scanned over all operands, then we have one unique value plus
800       // phi values.  Scan PHI nodes to see if they all merge in each other or
801       // the value.
802       if (InValNo == NumOperandVals) {
803         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
804         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
805           return ReplaceInstUsesWith(PN, NonPhiInVal);
806       }
807     }
808   }
809
810   // If there are multiple PHIs, sort their operands so that they all list
811   // the blocks in the same order. This will help identical PHIs be eliminated
812   // by other passes. Other passes shouldn't depend on this for correctness
813   // however.
814   PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
815   if (&PN != FirstPN)
816     for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
817       BasicBlock *BBA = PN.getIncomingBlock(i);
818       BasicBlock *BBB = FirstPN->getIncomingBlock(i);
819       if (BBA != BBB) {
820         Value *VA = PN.getIncomingValue(i);
821         unsigned j = PN.getBasicBlockIndex(BBB);
822         Value *VB = PN.getIncomingValue(j);
823         PN.setIncomingBlock(i, BBB);
824         PN.setIncomingValue(i, VB);
825         PN.setIncomingBlock(j, BBA);
826         PN.setIncomingValue(j, VA);
827         // NOTE: Instcombine normally would want us to "return &PN" if we
828         // modified any of the operands of an instruction.  However, since we
829         // aren't adding or removing uses (just rearranging them) we don't do
830         // this in this case.
831       }
832     }
833
834   // If this is an integer PHI and we know that it has an illegal type, see if
835   // it is only used by trunc or trunc(lshr) operations.  If so, we split the
836   // PHI into the various pieces being extracted.  This sort of thing is
837   // introduced when SROA promotes an aggregate to a single large integer type.
838   if (PN.getType()->isIntegerTy() && TD &&
839       !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
840     if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
841       return Res;
842   
843   return 0;
844 }