1 //===- InstCombinePHI.cpp -------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the visitPHINode function.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "InstCombineInternal.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/Analysis/ValueTracking.h"
18 #include "llvm/IR/PatternMatch.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Transforms/InstCombine/InstCombiner.h"
21 #include "llvm/Transforms/Utils/Local.h"
22 using namespace llvm;
23 using namespace llvm::PatternMatch;
24 
25 #define DEBUG_TYPE "instcombine"
26 
27 static cl::opt<unsigned>
28 MaxNumPhis("instcombine-max-num-phis", cl::init(512),
29            cl::desc("Maximum number phis to handle in intptr/ptrint folding"));
30 
31 /// The PHI arguments will be folded into a single operation with a PHI node
32 /// as input. The debug location of the single operation will be the merged
33 /// locations of the original PHI node arguments.
34 void InstCombinerImpl::PHIArgMergedDebugLoc(Instruction *Inst, PHINode &PN) {
35   auto *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
36   Inst->setDebugLoc(FirstInst->getDebugLoc());
37   // We do not expect a CallInst here, otherwise, N-way merging of DebugLoc
38   // will be inefficient.
39   assert(!isa<CallInst>(Inst));
40 
41   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
42     auto *I = cast<Instruction>(PN.getIncomingValue(i));
43     Inst->applyMergedLocation(Inst->getDebugLoc(), I->getDebugLoc());
44   }
45 }
46 
47 // Replace Integer typed PHI PN if the PHI's value is used as a pointer value.
48 // If there is an existing pointer typed PHI that produces the same value as PN,
49 // replace PN and the IntToPtr operation with it. Otherwise, synthesize a new
50 // PHI node:
51 //
52 // Case-1:
53 // bb1:
54 //     int_init = PtrToInt(ptr_init)
55 //     br label %bb2
56 // bb2:
57 //    int_val = PHI([int_init, %bb1], [int_val_inc, %bb2]
58 //    ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
59 //    ptr_val2 = IntToPtr(int_val)
60 //    ...
61 //    use(ptr_val2)
62 //    ptr_val_inc = ...
63 //    inc_val_inc = PtrToInt(ptr_val_inc)
64 //
65 // ==>
66 // bb1:
67 //     br label %bb2
68 // bb2:
69 //    ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
70 //    ...
71 //    use(ptr_val)
72 //    ptr_val_inc = ...
73 //
74 // Case-2:
75 // bb1:
76 //    int_ptr = BitCast(ptr_ptr)
77 //    int_init = Load(int_ptr)
78 //    br label %bb2
79 // bb2:
80 //    int_val = PHI([int_init, %bb1], [int_val_inc, %bb2]
81 //    ptr_val2 = IntToPtr(int_val)
82 //    ...
83 //    use(ptr_val2)
84 //    ptr_val_inc = ...
85 //    inc_val_inc = PtrToInt(ptr_val_inc)
86 // ==>
87 // bb1:
88 //    ptr_init = Load(ptr_ptr)
89 //    br label %bb2
90 // bb2:
91 //    ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
92 //    ...
93 //    use(ptr_val)
94 //    ptr_val_inc = ...
95 //    ...
96 //
97 Instruction *InstCombinerImpl::FoldIntegerTypedPHI(PHINode &PN) {
98   if (!PN.getType()->isIntegerTy())
99     return nullptr;
100   if (!PN.hasOneUse())
101     return nullptr;
102 
103   auto *IntToPtr = dyn_cast<IntToPtrInst>(PN.user_back());
104   if (!IntToPtr)
105     return nullptr;
106 
107   // Check if the pointer is actually used as pointer:
108   auto HasPointerUse = [](Instruction *IIP) {
109     for (User *U : IIP->users()) {
110       Value *Ptr = nullptr;
111       if (LoadInst *LoadI = dyn_cast<LoadInst>(U)) {
112         Ptr = LoadI->getPointerOperand();
113       } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
114         Ptr = SI->getPointerOperand();
115       } else if (GetElementPtrInst *GI = dyn_cast<GetElementPtrInst>(U)) {
116         Ptr = GI->getPointerOperand();
117       }
118 
119       if (Ptr && Ptr == IIP)
120         return true;
121     }
122     return false;
123   };
124 
125   if (!HasPointerUse(IntToPtr))
126     return nullptr;
127 
128   if (DL.getPointerSizeInBits(IntToPtr->getAddressSpace()) !=
129       DL.getTypeSizeInBits(IntToPtr->getOperand(0)->getType()))
130     return nullptr;
131 
132   SmallVector<Value *, 4> AvailablePtrVals;
133   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
134     Value *Arg = PN.getIncomingValue(i);
135 
136     // First look backward:
137     if (auto *PI = dyn_cast<PtrToIntInst>(Arg)) {
138       AvailablePtrVals.emplace_back(PI->getOperand(0));
139       continue;
140     }
141 
142     // Next look forward:
143     Value *ArgIntToPtr = nullptr;
144     for (User *U : Arg->users()) {
145       if (isa<IntToPtrInst>(U) && U->getType() == IntToPtr->getType() &&
146           (DT.dominates(cast<Instruction>(U), PN.getIncomingBlock(i)) ||
147            cast<Instruction>(U)->getParent() == PN.getIncomingBlock(i))) {
148         ArgIntToPtr = U;
149         break;
150       }
151     }
152 
153     if (ArgIntToPtr) {
154       AvailablePtrVals.emplace_back(ArgIntToPtr);
155       continue;
156     }
157 
158     // If Arg is defined by a PHI, allow it. This will also create
159     // more opportunities iteratively.
160     if (isa<PHINode>(Arg)) {
161       AvailablePtrVals.emplace_back(Arg);
162       continue;
163     }
164 
165     // For a single use integer load:
166     auto *LoadI = dyn_cast<LoadInst>(Arg);
167     if (!LoadI)
168       return nullptr;
169 
170     if (!LoadI->hasOneUse())
171       return nullptr;
172 
173     // Push the integer typed Load instruction into the available
174     // value set, and fix it up later when the pointer typed PHI
175     // is synthesized.
176     AvailablePtrVals.emplace_back(LoadI);
177   }
178 
179   // Now search for a matching PHI
180   auto *BB = PN.getParent();
181   assert(AvailablePtrVals.size() == PN.getNumIncomingValues() &&
182          "Not enough available ptr typed incoming values");
183   PHINode *MatchingPtrPHI = nullptr;
184   unsigned NumPhis = 0;
185   for (auto II = BB->begin(); II != BB->end(); II++, NumPhis++) {
186     // FIXME: consider handling this in AggressiveInstCombine
187     PHINode *PtrPHI = dyn_cast<PHINode>(II);
188     if (!PtrPHI)
189       break;
190     if (NumPhis > MaxNumPhis)
191       return nullptr;
192     if (PtrPHI == &PN || PtrPHI->getType() != IntToPtr->getType())
193       continue;
194     MatchingPtrPHI = PtrPHI;
195     for (unsigned i = 0; i != PtrPHI->getNumIncomingValues(); ++i) {
196       if (AvailablePtrVals[i] !=
197           PtrPHI->getIncomingValueForBlock(PN.getIncomingBlock(i))) {
198         MatchingPtrPHI = nullptr;
199         break;
200       }
201     }
202 
203     if (MatchingPtrPHI)
204       break;
205   }
206 
207   if (MatchingPtrPHI) {
208     assert(MatchingPtrPHI->getType() == IntToPtr->getType() &&
209            "Phi's Type does not match with IntToPtr");
210     // The PtrToCast + IntToPtr will be simplified later
211     return CastInst::CreateBitOrPointerCast(MatchingPtrPHI,
212                                             IntToPtr->getOperand(0)->getType());
213   }
214 
215   // If it requires a conversion for every PHI operand, do not do it.
216   if (all_of(AvailablePtrVals, [&](Value *V) {
217         return (V->getType() != IntToPtr->getType()) || isa<IntToPtrInst>(V);
218       }))
219     return nullptr;
220 
221   // If any of the operand that requires casting is a terminator
222   // instruction, do not do it. Similarly, do not do the transform if the value
223   // is PHI in a block with no insertion point, for example, a catchswitch
224   // block, since we will not be able to insert a cast after the PHI.
225   if (any_of(AvailablePtrVals, [&](Value *V) {
226         if (V->getType() == IntToPtr->getType())
227           return false;
228         auto *Inst = dyn_cast<Instruction>(V);
229         if (!Inst)
230           return false;
231         if (Inst->isTerminator())
232           return true;
233         auto *BB = Inst->getParent();
234         if (isa<PHINode>(Inst) && BB->getFirstInsertionPt() == BB->end())
235           return true;
236         return false;
237       }))
238     return nullptr;
239 
240   PHINode *NewPtrPHI = PHINode::Create(
241       IntToPtr->getType(), PN.getNumIncomingValues(), PN.getName() + ".ptr");
242 
243   InsertNewInstBefore(NewPtrPHI, PN);
244   SmallDenseMap<Value *, Instruction *> Casts;
245   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
246     auto *IncomingBB = PN.getIncomingBlock(i);
247     auto *IncomingVal = AvailablePtrVals[i];
248 
249     if (IncomingVal->getType() == IntToPtr->getType()) {
250       NewPtrPHI->addIncoming(IncomingVal, IncomingBB);
251       continue;
252     }
253 
254 #ifndef NDEBUG
255     LoadInst *LoadI = dyn_cast<LoadInst>(IncomingVal);
256     assert((isa<PHINode>(IncomingVal) ||
257             IncomingVal->getType()->isPointerTy() ||
258             (LoadI && LoadI->hasOneUse())) &&
259            "Can not replace LoadInst with multiple uses");
260 #endif
261     // Need to insert a BitCast.
262     // For an integer Load instruction with a single use, the load + IntToPtr
263     // cast will be simplified into a pointer load:
264     // %v = load i64, i64* %a.ip, align 8
265     // %v.cast = inttoptr i64 %v to float **
266     // ==>
267     // %v.ptrp = bitcast i64 * %a.ip to float **
268     // %v.cast = load float *, float ** %v.ptrp, align 8
269     Instruction *&CI = Casts[IncomingVal];
270     if (!CI) {
271       CI = CastInst::CreateBitOrPointerCast(IncomingVal, IntToPtr->getType(),
272                                             IncomingVal->getName() + ".ptr");
273       if (auto *IncomingI = dyn_cast<Instruction>(IncomingVal)) {
274         BasicBlock::iterator InsertPos(IncomingI);
275         InsertPos++;
276         BasicBlock *BB = IncomingI->getParent();
277         if (isa<PHINode>(IncomingI))
278           InsertPos = BB->getFirstInsertionPt();
279         assert(InsertPos != BB->end() && "should have checked above");
280         InsertNewInstBefore(CI, *InsertPos);
281       } else {
282         auto *InsertBB = &IncomingBB->getParent()->getEntryBlock();
283         InsertNewInstBefore(CI, *InsertBB->getFirstInsertionPt());
284       }
285     }
286     NewPtrPHI->addIncoming(CI, IncomingBB);
287   }
288 
289   // The PtrToCast + IntToPtr will be simplified later
290   return CastInst::CreateBitOrPointerCast(NewPtrPHI,
291                                           IntToPtr->getOperand(0)->getType());
292 }
293 
294 /// If we have something like phi [add (a,b), add(a,c)] and if a/b/c and the
295 /// adds all have a single use, turn this into a phi and a single binop.
296 Instruction *InstCombinerImpl::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
297   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
298   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
299   unsigned Opc = FirstInst->getOpcode();
300   Value *LHSVal = FirstInst->getOperand(0);
301   Value *RHSVal = FirstInst->getOperand(1);
302 
303   Type *LHSType = LHSVal->getType();
304   Type *RHSType = RHSVal->getType();
305 
306   // Scan to see if all operands are the same opcode, and all have one use.
307   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
308     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
309     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
310         // Verify type of the LHS matches so we don't fold cmp's of different
311         // types.
312         I->getOperand(0)->getType() != LHSType ||
313         I->getOperand(1)->getType() != RHSType)
314       return nullptr;
315 
316     // If they are CmpInst instructions, check their predicates
317     if (CmpInst *CI = dyn_cast<CmpInst>(I))
318       if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
319         return nullptr;
320 
321     // Keep track of which operand needs a phi node.
322     if (I->getOperand(0) != LHSVal) LHSVal = nullptr;
323     if (I->getOperand(1) != RHSVal) RHSVal = nullptr;
324   }
325 
326   // If both LHS and RHS would need a PHI, don't do this transformation,
327   // because it would increase the number of PHIs entering the block,
328   // which leads to higher register pressure. This is especially
329   // bad when the PHIs are in the header of a loop.
330   if (!LHSVal && !RHSVal)
331     return nullptr;
332 
333   // Otherwise, this is safe to transform!
334 
335   Value *InLHS = FirstInst->getOperand(0);
336   Value *InRHS = FirstInst->getOperand(1);
337   PHINode *NewLHS = nullptr, *NewRHS = nullptr;
338   if (!LHSVal) {
339     NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
340                              FirstInst->getOperand(0)->getName() + ".pn");
341     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
342     InsertNewInstBefore(NewLHS, PN);
343     LHSVal = NewLHS;
344   }
345 
346   if (!RHSVal) {
347     NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
348                              FirstInst->getOperand(1)->getName() + ".pn");
349     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
350     InsertNewInstBefore(NewRHS, PN);
351     RHSVal = NewRHS;
352   }
353 
354   // Add all operands to the new PHIs.
355   if (NewLHS || NewRHS) {
356     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
357       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
358       if (NewLHS) {
359         Value *NewInLHS = InInst->getOperand(0);
360         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
361       }
362       if (NewRHS) {
363         Value *NewInRHS = InInst->getOperand(1);
364         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
365       }
366     }
367   }
368 
369   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
370     CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
371                                      LHSVal, RHSVal);
372     PHIArgMergedDebugLoc(NewCI, PN);
373     return NewCI;
374   }
375 
376   BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
377   BinaryOperator *NewBinOp =
378     BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
379 
380   NewBinOp->copyIRFlags(PN.getIncomingValue(0));
381 
382   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i)
383     NewBinOp->andIRFlags(PN.getIncomingValue(i));
384 
385   PHIArgMergedDebugLoc(NewBinOp, PN);
386   return NewBinOp;
387 }
388 
389 Instruction *InstCombinerImpl::FoldPHIArgGEPIntoPHI(PHINode &PN) {
390   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
391 
392   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
393                                         FirstInst->op_end());
394   // This is true if all GEP bases are allocas and if all indices into them are
395   // constants.
396   bool AllBasePointersAreAllocas = true;
397 
398   // We don't want to replace this phi if the replacement would require
399   // more than one phi, which leads to higher register pressure. This is
400   // especially bad when the PHIs are in the header of a loop.
401   bool NeededPhi = false;
402 
403   bool AllInBounds = true;
404 
405   // Scan to see if all operands are the same opcode, and all have one use.
406   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
407     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
408     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
409       GEP->getNumOperands() != FirstInst->getNumOperands())
410       return nullptr;
411 
412     AllInBounds &= GEP->isInBounds();
413 
414     // Keep track of whether or not all GEPs are of alloca pointers.
415     if (AllBasePointersAreAllocas &&
416         (!isa<AllocaInst>(GEP->getOperand(0)) ||
417          !GEP->hasAllConstantIndices()))
418       AllBasePointersAreAllocas = false;
419 
420     // Compare the operand lists.
421     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
422       if (FirstInst->getOperand(op) == GEP->getOperand(op))
423         continue;
424 
425       // Don't merge two GEPs when two operands differ (introducing phi nodes)
426       // if one of the PHIs has a constant for the index.  The index may be
427       // substantially cheaper to compute for the constants, so making it a
428       // variable index could pessimize the path.  This also handles the case
429       // for struct indices, which must always be constant.
430       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
431           isa<ConstantInt>(GEP->getOperand(op)))
432         return nullptr;
433 
434       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
435         return nullptr;
436 
437       // If we already needed a PHI for an earlier operand, and another operand
438       // also requires a PHI, we'd be introducing more PHIs than we're
439       // eliminating, which increases register pressure on entry to the PHI's
440       // block.
441       if (NeededPhi)
442         return nullptr;
443 
444       FixedOperands[op] = nullptr;  // Needs a PHI.
445       NeededPhi = true;
446     }
447   }
448 
449   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
450   // bother doing this transformation.  At best, this will just save a bit of
451   // offset calculation, but all the predecessors will have to materialize the
452   // stack address into a register anyway.  We'd actually rather *clone* the
453   // load up into the predecessors so that we have a load of a gep of an alloca,
454   // which can usually all be folded into the load.
455   if (AllBasePointersAreAllocas)
456     return nullptr;
457 
458   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
459   // that is variable.
460   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
461 
462   bool HasAnyPHIs = false;
463   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
464     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
465     Value *FirstOp = FirstInst->getOperand(i);
466     PHINode *NewPN = PHINode::Create(FirstOp->getType(), e,
467                                      FirstOp->getName()+".pn");
468     InsertNewInstBefore(NewPN, PN);
469 
470     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
471     OperandPhis[i] = NewPN;
472     FixedOperands[i] = NewPN;
473     HasAnyPHIs = true;
474   }
475 
476 
477   // Add all operands to the new PHIs.
478   if (HasAnyPHIs) {
479     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
480       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
481       BasicBlock *InBB = PN.getIncomingBlock(i);
482 
483       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
484         if (PHINode *OpPhi = OperandPhis[op])
485           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
486     }
487   }
488 
489   Value *Base = FixedOperands[0];
490   GetElementPtrInst *NewGEP =
491       GetElementPtrInst::Create(FirstInst->getSourceElementType(), Base,
492                                 makeArrayRef(FixedOperands).slice(1));
493   if (AllInBounds) NewGEP->setIsInBounds();
494   PHIArgMergedDebugLoc(NewGEP, PN);
495   return NewGEP;
496 }
497 
498 /// Return true if we know that it is safe to sink the load out of the block
499 /// that defines it. This means that it must be obvious the value of the load is
500 /// not changed from the point of the load to the end of the block it is in.
501 ///
502 /// Finally, it is safe, but not profitable, to sink a load targeting a
503 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
504 /// to a register.
505 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
506   BasicBlock::iterator BBI = L->getIterator(), E = L->getParent()->end();
507 
508   for (++BBI; BBI != E; ++BBI)
509     if (BBI->mayWriteToMemory())
510       return false;
511 
512   // Check for non-address taken alloca.  If not address-taken already, it isn't
513   // profitable to do this xform.
514   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
515     bool isAddressTaken = false;
516     for (User *U : AI->users()) {
517       if (isa<LoadInst>(U)) continue;
518       if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
519         // If storing TO the alloca, then the address isn't taken.
520         if (SI->getOperand(1) == AI) continue;
521       }
522       isAddressTaken = true;
523       break;
524     }
525 
526     if (!isAddressTaken && AI->isStaticAlloca())
527       return false;
528   }
529 
530   // If this load is a load from a GEP with a constant offset from an alloca,
531   // then we don't want to sink it.  In its present form, it will be
532   // load [constant stack offset].  Sinking it will cause us to have to
533   // materialize the stack addresses in each predecessor in a register only to
534   // do a shared load from register in the successor.
535   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
536     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
537       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
538         return false;
539 
540   return true;
541 }
542 
543 Instruction *InstCombinerImpl::FoldPHIArgLoadIntoPHI(PHINode &PN) {
544   LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
545 
546   // FIXME: This is overconservative; this transform is allowed in some cases
547   // for atomic operations.
548   if (FirstLI->isAtomic())
549     return nullptr;
550 
551   // When processing loads, we need to propagate two bits of information to the
552   // sunk load: whether it is volatile, and what its alignment is.  We currently
553   // don't sink loads when some have their alignment specified and some don't.
554   // visitLoadInst will propagate an alignment onto the load when TD is around,
555   // and if TD isn't around, we can't handle the mixed case.
556   bool isVolatile = FirstLI->isVolatile();
557   Align LoadAlignment = FirstLI->getAlign();
558   unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
559 
560   // We can't sink the load if the loaded value could be modified between the
561   // load and the PHI.
562   if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
563       !isSafeAndProfitableToSinkLoad(FirstLI))
564     return nullptr;
565 
566   // If the PHI is of volatile loads and the load block has multiple
567   // successors, sinking it would remove a load of the volatile value from
568   // the path through the other successor.
569   if (isVolatile &&
570       FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
571     return nullptr;
572 
573   // Check to see if all arguments are the same operation.
574   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
575     LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
576     if (!LI || !LI->hasOneUse())
577       return nullptr;
578 
579     // We can't sink the load if the loaded value could be modified between
580     // the load and the PHI.
581     if (LI->isVolatile() != isVolatile ||
582         LI->getParent() != PN.getIncomingBlock(i) ||
583         LI->getPointerAddressSpace() != LoadAddrSpace ||
584         !isSafeAndProfitableToSinkLoad(LI))
585       return nullptr;
586 
587     LoadAlignment = std::min(LoadAlignment, Align(LI->getAlign()));
588 
589     // If the PHI is of volatile loads and the load block has multiple
590     // successors, sinking it would remove a load of the volatile value from
591     // the path through the other successor.
592     if (isVolatile &&
593         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
594       return nullptr;
595   }
596 
597   // Okay, they are all the same operation.  Create a new PHI node of the
598   // correct type, and PHI together all of the LHS's of the instructions.
599   PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
600                                    PN.getNumIncomingValues(),
601                                    PN.getName()+".in");
602 
603   Value *InVal = FirstLI->getOperand(0);
604   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
605   LoadInst *NewLI =
606       new LoadInst(FirstLI->getType(), NewPN, "", isVolatile, LoadAlignment);
607 
608   unsigned KnownIDs[] = {
609     LLVMContext::MD_tbaa,
610     LLVMContext::MD_range,
611     LLVMContext::MD_invariant_load,
612     LLVMContext::MD_alias_scope,
613     LLVMContext::MD_noalias,
614     LLVMContext::MD_nonnull,
615     LLVMContext::MD_align,
616     LLVMContext::MD_dereferenceable,
617     LLVMContext::MD_dereferenceable_or_null,
618     LLVMContext::MD_access_group,
619   };
620 
621   for (unsigned ID : KnownIDs)
622     NewLI->setMetadata(ID, FirstLI->getMetadata(ID));
623 
624   // Add all operands to the new PHI and combine TBAA metadata.
625   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
626     LoadInst *LI = cast<LoadInst>(PN.getIncomingValue(i));
627     combineMetadata(NewLI, LI, KnownIDs, true);
628     Value *NewInVal = LI->getOperand(0);
629     if (NewInVal != InVal)
630       InVal = nullptr;
631     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
632   }
633 
634   if (InVal) {
635     // The new PHI unions all of the same values together.  This is really
636     // common, so we handle it intelligently here for compile-time speed.
637     NewLI->setOperand(0, InVal);
638     delete NewPN;
639   } else {
640     InsertNewInstBefore(NewPN, PN);
641   }
642 
643   // If this was a volatile load that we are merging, make sure to loop through
644   // and mark all the input loads as non-volatile.  If we don't do this, we will
645   // insert a new volatile load and the old ones will not be deletable.
646   if (isVolatile)
647     for (Value *IncValue : PN.incoming_values())
648       cast<LoadInst>(IncValue)->setVolatile(false);
649 
650   PHIArgMergedDebugLoc(NewLI, PN);
651   return NewLI;
652 }
653 
654 /// TODO: This function could handle other cast types, but then it might
655 /// require special-casing a cast from the 'i1' type. See the comment in
656 /// FoldPHIArgOpIntoPHI() about pessimizing illegal integer types.
657 Instruction *InstCombinerImpl::FoldPHIArgZextsIntoPHI(PHINode &Phi) {
658   // We cannot create a new instruction after the PHI if the terminator is an
659   // EHPad because there is no valid insertion point.
660   if (Instruction *TI = Phi.getParent()->getTerminator())
661     if (TI->isEHPad())
662       return nullptr;
663 
664   // Early exit for the common case of a phi with two operands. These are
665   // handled elsewhere. See the comment below where we check the count of zexts
666   // and constants for more details.
667   unsigned NumIncomingValues = Phi.getNumIncomingValues();
668   if (NumIncomingValues < 3)
669     return nullptr;
670 
671   // Find the narrower type specified by the first zext.
672   Type *NarrowType = nullptr;
673   for (Value *V : Phi.incoming_values()) {
674     if (auto *Zext = dyn_cast<ZExtInst>(V)) {
675       NarrowType = Zext->getSrcTy();
676       break;
677     }
678   }
679   if (!NarrowType)
680     return nullptr;
681 
682   // Walk the phi operands checking that we only have zexts or constants that
683   // we can shrink for free. Store the new operands for the new phi.
684   SmallVector<Value *, 4> NewIncoming;
685   unsigned NumZexts = 0;
686   unsigned NumConsts = 0;
687   for (Value *V : Phi.incoming_values()) {
688     if (auto *Zext = dyn_cast<ZExtInst>(V)) {
689       // All zexts must be identical and have one use.
690       if (Zext->getSrcTy() != NarrowType || !Zext->hasOneUse())
691         return nullptr;
692       NewIncoming.push_back(Zext->getOperand(0));
693       NumZexts++;
694     } else if (auto *C = dyn_cast<Constant>(V)) {
695       // Make sure that constants can fit in the new type.
696       Constant *Trunc = ConstantExpr::getTrunc(C, NarrowType);
697       if (ConstantExpr::getZExt(Trunc, C->getType()) != C)
698         return nullptr;
699       NewIncoming.push_back(Trunc);
700       NumConsts++;
701     } else {
702       // If it's not a cast or a constant, bail out.
703       return nullptr;
704     }
705   }
706 
707   // The more common cases of a phi with no constant operands or just one
708   // variable operand are handled by FoldPHIArgOpIntoPHI() and foldOpIntoPhi()
709   // respectively. foldOpIntoPhi() wants to do the opposite transform that is
710   // performed here. It tries to replicate a cast in the phi operand's basic
711   // block to expose other folding opportunities. Thus, InstCombine will
712   // infinite loop without this check.
713   if (NumConsts == 0 || NumZexts < 2)
714     return nullptr;
715 
716   // All incoming values are zexts or constants that are safe to truncate.
717   // Create a new phi node of the narrow type, phi together all of the new
718   // operands, and zext the result back to the original type.
719   PHINode *NewPhi = PHINode::Create(NarrowType, NumIncomingValues,
720                                     Phi.getName() + ".shrunk");
721   for (unsigned i = 0; i != NumIncomingValues; ++i)
722     NewPhi->addIncoming(NewIncoming[i], Phi.getIncomingBlock(i));
723 
724   InsertNewInstBefore(NewPhi, Phi);
725   return CastInst::CreateZExtOrBitCast(NewPhi, Phi.getType());
726 }
727 
728 /// If all operands to a PHI node are the same "unary" operator and they all are
729 /// only used by the PHI, PHI together their inputs, and do the operation once,
730 /// to the result of the PHI.
731 Instruction *InstCombinerImpl::FoldPHIArgOpIntoPHI(PHINode &PN) {
732   // We cannot create a new instruction after the PHI if the terminator is an
733   // EHPad because there is no valid insertion point.
734   if (Instruction *TI = PN.getParent()->getTerminator())
735     if (TI->isEHPad())
736       return nullptr;
737 
738   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
739 
740   if (isa<GetElementPtrInst>(FirstInst))
741     return FoldPHIArgGEPIntoPHI(PN);
742   if (isa<LoadInst>(FirstInst))
743     return FoldPHIArgLoadIntoPHI(PN);
744 
745   // Scan the instruction, looking for input operations that can be folded away.
746   // If all input operands to the phi are the same instruction (e.g. a cast from
747   // the same type or "+42") we can pull the operation through the PHI, reducing
748   // code size and simplifying code.
749   Constant *ConstantOp = nullptr;
750   Type *CastSrcTy = nullptr;
751 
752   if (isa<CastInst>(FirstInst)) {
753     CastSrcTy = FirstInst->getOperand(0)->getType();
754 
755     // Be careful about transforming integer PHIs.  We don't want to pessimize
756     // the code by turning an i32 into an i1293.
757     if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
758       if (!shouldChangeType(PN.getType(), CastSrcTy))
759         return nullptr;
760     }
761   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
762     // Can fold binop, compare or shift here if the RHS is a constant,
763     // otherwise call FoldPHIArgBinOpIntoPHI.
764     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
765     if (!ConstantOp)
766       return FoldPHIArgBinOpIntoPHI(PN);
767   } else {
768     return nullptr;  // Cannot fold this operation.
769   }
770 
771   // Check to see if all arguments are the same operation.
772   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
773     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
774     if (!I || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
775       return nullptr;
776     if (CastSrcTy) {
777       if (I->getOperand(0)->getType() != CastSrcTy)
778         return nullptr;  // Cast operation must match.
779     } else if (I->getOperand(1) != ConstantOp) {
780       return nullptr;
781     }
782   }
783 
784   // Okay, they are all the same operation.  Create a new PHI node of the
785   // correct type, and PHI together all of the LHS's of the instructions.
786   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
787                                    PN.getNumIncomingValues(),
788                                    PN.getName()+".in");
789 
790   Value *InVal = FirstInst->getOperand(0);
791   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
792 
793   // Add all operands to the new PHI.
794   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
795     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
796     if (NewInVal != InVal)
797       InVal = nullptr;
798     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
799   }
800 
801   Value *PhiVal;
802   if (InVal) {
803     // The new PHI unions all of the same values together.  This is really
804     // common, so we handle it intelligently here for compile-time speed.
805     PhiVal = InVal;
806     delete NewPN;
807   } else {
808     InsertNewInstBefore(NewPN, PN);
809     PhiVal = NewPN;
810   }
811 
812   // Insert and return the new operation.
813   if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
814     CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
815                                        PN.getType());
816     PHIArgMergedDebugLoc(NewCI, PN);
817     return NewCI;
818   }
819 
820   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
821     BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
822     BinOp->copyIRFlags(PN.getIncomingValue(0));
823 
824     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i)
825       BinOp->andIRFlags(PN.getIncomingValue(i));
826 
827     PHIArgMergedDebugLoc(BinOp, PN);
828     return BinOp;
829   }
830 
831   CmpInst *CIOp = cast<CmpInst>(FirstInst);
832   CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
833                                    PhiVal, ConstantOp);
834   PHIArgMergedDebugLoc(NewCI, PN);
835   return NewCI;
836 }
837 
838 /// Return true if this PHI node is only used by a PHI node cycle that is dead.
839 static bool DeadPHICycle(PHINode *PN,
840                          SmallPtrSetImpl<PHINode*> &PotentiallyDeadPHIs) {
841   if (PN->use_empty()) return true;
842   if (!PN->hasOneUse()) return false;
843 
844   // Remember this node, and if we find the cycle, return.
845   if (!PotentiallyDeadPHIs.insert(PN).second)
846     return true;
847 
848   // Don't scan crazily complex things.
849   if (PotentiallyDeadPHIs.size() == 16)
850     return false;
851 
852   if (PHINode *PU = dyn_cast<PHINode>(PN->user_back()))
853     return DeadPHICycle(PU, PotentiallyDeadPHIs);
854 
855   return false;
856 }
857 
858 /// Return true if this phi node is always equal to NonPhiInVal.
859 /// This happens with mutually cyclic phi nodes like:
860 ///   z = some value; x = phi (y, z); y = phi (x, z)
861 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
862                            SmallPtrSetImpl<PHINode*> &ValueEqualPHIs) {
863   // See if we already saw this PHI node.
864   if (!ValueEqualPHIs.insert(PN).second)
865     return true;
866 
867   // Don't scan crazily complex things.
868   if (ValueEqualPHIs.size() == 16)
869     return false;
870 
871   // Scan the operands to see if they are either phi nodes or are equal to
872   // the value.
873   for (Value *Op : PN->incoming_values()) {
874     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
875       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
876         return false;
877     } else if (Op != NonPhiInVal)
878       return false;
879   }
880 
881   return true;
882 }
883 
884 /// Return an existing non-zero constant if this phi node has one, otherwise
885 /// return constant 1.
886 static ConstantInt *GetAnyNonZeroConstInt(PHINode &PN) {
887   assert(isa<IntegerType>(PN.getType()) && "Expect only integer type phi");
888   for (Value *V : PN.operands())
889     if (auto *ConstVA = dyn_cast<ConstantInt>(V))
890       if (!ConstVA->isZero())
891         return ConstVA;
892   return ConstantInt::get(cast<IntegerType>(PN.getType()), 1);
893 }
894 
895 namespace {
896 struct PHIUsageRecord {
897   unsigned PHIId;     // The ID # of the PHI (something determinstic to sort on)
898   unsigned Shift;     // The amount shifted.
899   Instruction *Inst;  // The trunc instruction.
900 
901   PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
902     : PHIId(pn), Shift(Sh), Inst(User) {}
903 
904   bool operator<(const PHIUsageRecord &RHS) const {
905     if (PHIId < RHS.PHIId) return true;
906     if (PHIId > RHS.PHIId) return false;
907     if (Shift < RHS.Shift) return true;
908     if (Shift > RHS.Shift) return false;
909     return Inst->getType()->getPrimitiveSizeInBits() <
910            RHS.Inst->getType()->getPrimitiveSizeInBits();
911   }
912 };
913 
914 struct LoweredPHIRecord {
915   PHINode *PN;        // The PHI that was lowered.
916   unsigned Shift;     // The amount shifted.
917   unsigned Width;     // The width extracted.
918 
919   LoweredPHIRecord(PHINode *pn, unsigned Sh, Type *Ty)
920     : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
921 
922   // Ctor form used by DenseMap.
923   LoweredPHIRecord(PHINode *pn, unsigned Sh)
924     : PN(pn), Shift(Sh), Width(0) {}
925 };
926 }
927 
928 namespace llvm {
929   template<>
930   struct DenseMapInfo<LoweredPHIRecord> {
931     static inline LoweredPHIRecord getEmptyKey() {
932       return LoweredPHIRecord(nullptr, 0);
933     }
934     static inline LoweredPHIRecord getTombstoneKey() {
935       return LoweredPHIRecord(nullptr, 1);
936     }
937     static unsigned getHashValue(const LoweredPHIRecord &Val) {
938       return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
939              (Val.Width>>3);
940     }
941     static bool isEqual(const LoweredPHIRecord &LHS,
942                         const LoweredPHIRecord &RHS) {
943       return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
944              LHS.Width == RHS.Width;
945     }
946   };
947 }
948 
949 
950 /// This is an integer PHI and we know that it has an illegal type: see if it is
951 /// only used by trunc or trunc(lshr) operations. If so, we split the PHI into
952 /// the various pieces being extracted. This sort of thing is introduced when
953 /// SROA promotes an aggregate to large integer values.
954 ///
955 /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
956 /// inttoptr.  We should produce new PHIs in the right type.
957 ///
958 Instruction *InstCombinerImpl::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
959   // PHIUsers - Keep track of all of the truncated values extracted from a set
960   // of PHIs, along with their offset.  These are the things we want to rewrite.
961   SmallVector<PHIUsageRecord, 16> PHIUsers;
962 
963   // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
964   // nodes which are extracted from. PHIsToSlice is a set we use to avoid
965   // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
966   // check the uses of (to ensure they are all extracts).
967   SmallVector<PHINode*, 8> PHIsToSlice;
968   SmallPtrSet<PHINode*, 8> PHIsInspected;
969 
970   PHIsToSlice.push_back(&FirstPhi);
971   PHIsInspected.insert(&FirstPhi);
972 
973   for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
974     PHINode *PN = PHIsToSlice[PHIId];
975 
976     // Scan the input list of the PHI.  If any input is an invoke, and if the
977     // input is defined in the predecessor, then we won't be split the critical
978     // edge which is required to insert a truncate.  Because of this, we have to
979     // bail out.
980     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
981       InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
982       if (!II) continue;
983       if (II->getParent() != PN->getIncomingBlock(i))
984         continue;
985 
986       // If we have a phi, and if it's directly in the predecessor, then we have
987       // a critical edge where we need to put the truncate.  Since we can't
988       // split the edge in instcombine, we have to bail out.
989       return nullptr;
990     }
991 
992     for (User *U : PN->users()) {
993       Instruction *UserI = cast<Instruction>(U);
994 
995       // If the user is a PHI, inspect its uses recursively.
996       if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
997         if (PHIsInspected.insert(UserPN).second)
998           PHIsToSlice.push_back(UserPN);
999         continue;
1000       }
1001 
1002       // Truncates are always ok.
1003       if (isa<TruncInst>(UserI)) {
1004         PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
1005         continue;
1006       }
1007 
1008       // Otherwise it must be a lshr which can only be used by one trunc.
1009       if (UserI->getOpcode() != Instruction::LShr ||
1010           !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
1011           !isa<ConstantInt>(UserI->getOperand(1)))
1012         return nullptr;
1013 
1014       // Bail on out of range shifts.
1015       unsigned SizeInBits = UserI->getType()->getScalarSizeInBits();
1016       if (cast<ConstantInt>(UserI->getOperand(1))->getValue().uge(SizeInBits))
1017         return nullptr;
1018 
1019       unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
1020       PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
1021     }
1022   }
1023 
1024   // If we have no users, they must be all self uses, just nuke the PHI.
1025   if (PHIUsers.empty())
1026     return replaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
1027 
1028   // If this phi node is transformable, create new PHIs for all the pieces
1029   // extracted out of it.  First, sort the users by their offset and size.
1030   array_pod_sort(PHIUsers.begin(), PHIUsers.end());
1031 
1032   LLVM_DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
1033              for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i) dbgs()
1034              << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] << '\n';);
1035 
1036   // PredValues - This is a temporary used when rewriting PHI nodes.  It is
1037   // hoisted out here to avoid construction/destruction thrashing.
1038   DenseMap<BasicBlock*, Value*> PredValues;
1039 
1040   // ExtractedVals - Each new PHI we introduce is saved here so we don't
1041   // introduce redundant PHIs.
1042   DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
1043 
1044   for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
1045     unsigned PHIId = PHIUsers[UserI].PHIId;
1046     PHINode *PN = PHIsToSlice[PHIId];
1047     unsigned Offset = PHIUsers[UserI].Shift;
1048     Type *Ty = PHIUsers[UserI].Inst->getType();
1049 
1050     PHINode *EltPHI;
1051 
1052     // If we've already lowered a user like this, reuse the previously lowered
1053     // value.
1054     if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
1055 
1056       // Otherwise, Create the new PHI node for this user.
1057       EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
1058                                PN->getName()+".off"+Twine(Offset), PN);
1059       assert(EltPHI->getType() != PN->getType() &&
1060              "Truncate didn't shrink phi?");
1061 
1062       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1063         BasicBlock *Pred = PN->getIncomingBlock(i);
1064         Value *&PredVal = PredValues[Pred];
1065 
1066         // If we already have a value for this predecessor, reuse it.
1067         if (PredVal) {
1068           EltPHI->addIncoming(PredVal, Pred);
1069           continue;
1070         }
1071 
1072         // Handle the PHI self-reuse case.
1073         Value *InVal = PN->getIncomingValue(i);
1074         if (InVal == PN) {
1075           PredVal = EltPHI;
1076           EltPHI->addIncoming(PredVal, Pred);
1077           continue;
1078         }
1079 
1080         if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
1081           // If the incoming value was a PHI, and if it was one of the PHIs we
1082           // already rewrote it, just use the lowered value.
1083           if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
1084             PredVal = Res;
1085             EltPHI->addIncoming(PredVal, Pred);
1086             continue;
1087           }
1088         }
1089 
1090         // Otherwise, do an extract in the predecessor.
1091         Builder.SetInsertPoint(Pred->getTerminator());
1092         Value *Res = InVal;
1093         if (Offset)
1094           Res = Builder.CreateLShr(Res, ConstantInt::get(InVal->getType(),
1095                                                           Offset), "extract");
1096         Res = Builder.CreateTrunc(Res, Ty, "extract.t");
1097         PredVal = Res;
1098         EltPHI->addIncoming(Res, Pred);
1099 
1100         // If the incoming value was a PHI, and if it was one of the PHIs we are
1101         // rewriting, we will ultimately delete the code we inserted.  This
1102         // means we need to revisit that PHI to make sure we extract out the
1103         // needed piece.
1104         if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
1105           if (PHIsInspected.count(OldInVal)) {
1106             unsigned RefPHIId =
1107                 find(PHIsToSlice, OldInVal) - PHIsToSlice.begin();
1108             PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
1109                                               cast<Instruction>(Res)));
1110             ++UserE;
1111           }
1112       }
1113       PredValues.clear();
1114 
1115       LLVM_DEBUG(dbgs() << "  Made element PHI for offset " << Offset << ": "
1116                         << *EltPHI << '\n');
1117       ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
1118     }
1119 
1120     // Replace the use of this piece with the PHI node.
1121     replaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
1122   }
1123 
1124   // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
1125   // with undefs.
1126   Value *Undef = UndefValue::get(FirstPhi.getType());
1127   for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
1128     replaceInstUsesWith(*PHIsToSlice[i], Undef);
1129   return replaceInstUsesWith(FirstPhi, Undef);
1130 }
1131 
1132 static Value *SimplifyUsingControlFlow(InstCombiner &Self, PHINode &PN,
1133                                        const DominatorTree &DT) {
1134   // Simplify the following patterns:
1135   //       if (cond)
1136   //       /       \
1137   //      ...      ...
1138   //       \       /
1139   //    phi [true] [false]
1140   if (!PN.getType()->isIntegerTy(1))
1141     return nullptr;
1142 
1143   if (PN.getNumOperands() != 2)
1144     return nullptr;
1145 
1146   // Make sure all inputs are constants.
1147   if (!all_of(PN.operands(), [](Value *V) { return isa<ConstantInt>(V); }))
1148     return nullptr;
1149 
1150   BasicBlock *BB = PN.getParent();
1151   // Do not bother with unreachable instructions.
1152   if (!DT.isReachableFromEntry(BB))
1153     return nullptr;
1154 
1155   // Same inputs.
1156   if (PN.getOperand(0) == PN.getOperand(1))
1157     return PN.getOperand(0);
1158 
1159   BasicBlock *TruePred = nullptr, *FalsePred = nullptr;
1160   for (auto *Pred : predecessors(BB)) {
1161     auto *Input = cast<ConstantInt>(PN.getIncomingValueForBlock(Pred));
1162     if (Input->isAllOnesValue())
1163       TruePred = Pred;
1164     else
1165       FalsePred = Pred;
1166   }
1167   assert(TruePred && FalsePred && "Must be!");
1168 
1169   // Check which edge of the dominator dominates the true input. If it is the
1170   // false edge, we should invert the condition.
1171   auto *IDom = DT.getNode(BB)->getIDom()->getBlock();
1172   auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
1173   if (!BI || BI->isUnconditional())
1174     return nullptr;
1175 
1176   // Check that edges outgoing from the idom's terminators dominate respective
1177   // inputs of the Phi.
1178   BasicBlockEdge TrueOutEdge(IDom, BI->getSuccessor(0));
1179   BasicBlockEdge FalseOutEdge(IDom, BI->getSuccessor(1));
1180 
1181   BasicBlockEdge TrueIncEdge(TruePred, BB);
1182   BasicBlockEdge FalseIncEdge(FalsePred, BB);
1183 
1184   auto *Cond = BI->getCondition();
1185   if (DT.dominates(TrueOutEdge, TrueIncEdge) &&
1186       DT.dominates(FalseOutEdge, FalseIncEdge))
1187     // This Phi is actually equivalent to branching condition of IDom.
1188     return Cond;
1189   else if (DT.dominates(TrueOutEdge, FalseIncEdge) &&
1190            DT.dominates(FalseOutEdge, TrueIncEdge)) {
1191     // This Phi is actually opposite to branching condition of IDom. We invert
1192     // the condition that will potentially open up some opportunities for
1193     // sinking.
1194     auto InsertPt = BB->getFirstInsertionPt();
1195     if (InsertPt != BB->end()) {
1196       Self.Builder.SetInsertPoint(&*InsertPt);
1197       return Self.Builder.CreateNot(Cond);
1198     }
1199   }
1200 
1201   return nullptr;
1202 }
1203 
1204 // PHINode simplification
1205 //
1206 Instruction *InstCombinerImpl::visitPHINode(PHINode &PN) {
1207   if (Value *V = SimplifyInstruction(&PN, SQ.getWithInstruction(&PN)))
1208     return replaceInstUsesWith(PN, V);
1209 
1210   if (Instruction *Result = FoldPHIArgZextsIntoPHI(PN))
1211     return Result;
1212 
1213   // If all PHI operands are the same operation, pull them through the PHI,
1214   // reducing code size.
1215   if (isa<Instruction>(PN.getIncomingValue(0)) &&
1216       isa<Instruction>(PN.getIncomingValue(1)) &&
1217       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
1218       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
1219       // FIXME: The hasOneUse check will fail for PHIs that use the value more
1220       // than themselves more than once.
1221       PN.getIncomingValue(0)->hasOneUse())
1222     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
1223       return Result;
1224 
1225   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
1226   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
1227   // PHI)... break the cycle.
1228   if (PN.hasOneUse()) {
1229     if (Instruction *Result = FoldIntegerTypedPHI(PN))
1230       return Result;
1231 
1232     Instruction *PHIUser = cast<Instruction>(PN.user_back());
1233     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
1234       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
1235       PotentiallyDeadPHIs.insert(&PN);
1236       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
1237         return replaceInstUsesWith(PN, UndefValue::get(PN.getType()));
1238     }
1239 
1240     // If this phi has a single use, and if that use just computes a value for
1241     // the next iteration of a loop, delete the phi.  This occurs with unused
1242     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
1243     // common case here is good because the only other things that catch this
1244     // are induction variable analysis (sometimes) and ADCE, which is only run
1245     // late.
1246     if (PHIUser->hasOneUse() &&
1247         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
1248         PHIUser->user_back() == &PN) {
1249       return replaceInstUsesWith(PN, UndefValue::get(PN.getType()));
1250     }
1251     // When a PHI is used only to be compared with zero, it is safe to replace
1252     // an incoming value proved as known nonzero with any non-zero constant.
1253     // For example, in the code below, the incoming value %v can be replaced
1254     // with any non-zero constant based on the fact that the PHI is only used to
1255     // be compared with zero and %v is a known non-zero value:
1256     // %v = select %cond, 1, 2
1257     // %p = phi [%v, BB] ...
1258     //      icmp eq, %p, 0
1259     auto *CmpInst = dyn_cast<ICmpInst>(PHIUser);
1260     // FIXME: To be simple, handle only integer type for now.
1261     if (CmpInst && isa<IntegerType>(PN.getType()) && CmpInst->isEquality() &&
1262         match(CmpInst->getOperand(1), m_Zero())) {
1263       ConstantInt *NonZeroConst = nullptr;
1264       bool MadeChange = false;
1265       for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1266         Instruction *CtxI = PN.getIncomingBlock(i)->getTerminator();
1267         Value *VA = PN.getIncomingValue(i);
1268         if (isKnownNonZero(VA, DL, 0, &AC, CtxI, &DT)) {
1269           if (!NonZeroConst)
1270             NonZeroConst = GetAnyNonZeroConstInt(PN);
1271 
1272           if (NonZeroConst != VA) {
1273             replaceOperand(PN, i, NonZeroConst);
1274             MadeChange = true;
1275           }
1276         }
1277       }
1278       if (MadeChange)
1279         return &PN;
1280     }
1281   }
1282 
1283   // We sometimes end up with phi cycles that non-obviously end up being the
1284   // same value, for example:
1285   //   z = some value; x = phi (y, z); y = phi (x, z)
1286   // where the phi nodes don't necessarily need to be in the same block.  Do a
1287   // quick check to see if the PHI node only contains a single non-phi value, if
1288   // so, scan to see if the phi cycle is actually equal to that value.
1289   {
1290     unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
1291     // Scan for the first non-phi operand.
1292     while (InValNo != NumIncomingVals &&
1293            isa<PHINode>(PN.getIncomingValue(InValNo)))
1294       ++InValNo;
1295 
1296     if (InValNo != NumIncomingVals) {
1297       Value *NonPhiInVal = PN.getIncomingValue(InValNo);
1298 
1299       // Scan the rest of the operands to see if there are any conflicts, if so
1300       // there is no need to recursively scan other phis.
1301       for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
1302         Value *OpVal = PN.getIncomingValue(InValNo);
1303         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
1304           break;
1305       }
1306 
1307       // If we scanned over all operands, then we have one unique value plus
1308       // phi values.  Scan PHI nodes to see if they all merge in each other or
1309       // the value.
1310       if (InValNo == NumIncomingVals) {
1311         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
1312         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
1313           return replaceInstUsesWith(PN, NonPhiInVal);
1314       }
1315     }
1316   }
1317 
1318   // If there are multiple PHIs, sort their operands so that they all list
1319   // the blocks in the same order. This will help identical PHIs be eliminated
1320   // by other passes. Other passes shouldn't depend on this for correctness
1321   // however.
1322   PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
1323   if (&PN != FirstPN)
1324     for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
1325       BasicBlock *BBA = PN.getIncomingBlock(i);
1326       BasicBlock *BBB = FirstPN->getIncomingBlock(i);
1327       if (BBA != BBB) {
1328         Value *VA = PN.getIncomingValue(i);
1329         unsigned j = PN.getBasicBlockIndex(BBB);
1330         Value *VB = PN.getIncomingValue(j);
1331         PN.setIncomingBlock(i, BBB);
1332         PN.setIncomingValue(i, VB);
1333         PN.setIncomingBlock(j, BBA);
1334         PN.setIncomingValue(j, VA);
1335         // NOTE: Instcombine normally would want us to "return &PN" if we
1336         // modified any of the operands of an instruction.  However, since we
1337         // aren't adding or removing uses (just rearranging them) we don't do
1338         // this in this case.
1339       }
1340     }
1341 
1342   // If this is an integer PHI and we know that it has an illegal type, see if
1343   // it is only used by trunc or trunc(lshr) operations.  If so, we split the
1344   // PHI into the various pieces being extracted.  This sort of thing is
1345   // introduced when SROA promotes an aggregate to a single large integer type.
1346   if (PN.getType()->isIntegerTy() &&
1347       !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
1348     if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
1349       return Res;
1350 
1351   // Ultimately, try to replace this Phi with a dominating condition.
1352   if (auto *V = SimplifyUsingControlFlow(*this, PN, DT))
1353     return replaceInstUsesWith(PN, V);
1354 
1355   return nullptr;
1356 }
1357