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