@@ -574,14 +574,6 @@ bool TailDuplicator::shouldTailDuplicate(bool IsSimple,
574574 if (TailBB.isSuccessor (&TailBB))
575575 return false ;
576576
577- // Duplicating a BB which has both multiple predecessors and successors will
578- // result in a complex CFG and also may cause huge amount of PHI nodes. If we
579- // want to remove this limitation, we have to address
580- // https://github.com/llvm/llvm-project/issues/78578.
581- if (TailBB.pred_size () > TailDupPredSize &&
582- TailBB.succ_size () > TailDupSuccSize)
583- return false ;
584-
585577 // Set the limit on the cost to duplicate. When optimizing for size,
586578 // duplicate only one, because one branch instruction can be eliminated to
587579 // compensate for the duplication.
@@ -621,6 +613,7 @@ bool TailDuplicator::shouldTailDuplicate(bool IsSimple,
621613 // Check the instructions in the block to determine whether tail-duplication
622614 // is invalid or unlikely to be profitable.
623615 unsigned InstrCount = 0 ;
616+ unsigned NumPhis = 0 ;
624617 for (MachineInstr &MI : TailBB) {
625618 // Non-duplicable things shouldn't be tail-duplicated.
626619 // CFI instructions are marked as non-duplicable, because Darwin compact
@@ -664,6 +657,20 @@ bool TailDuplicator::shouldTailDuplicate(bool IsSimple,
664657
665658 if (InstrCount > MaxDuplicateCount)
666659 return false ;
660+ NumPhis += MI.isPHI ();
661+ }
662+
663+ // Duplicating a BB which has both multiple predecessors and successors will
664+ // may cause huge amount of PHI nodes. If we want to remove this limitation,
665+ // we have to address https://github.com/llvm/llvm-project/issues/78578.
666+ if (TailBB.pred_size () > TailDupPredSize &&
667+ TailBB.succ_size () > TailDupSuccSize) {
668+ // If TailBB or any of its successors contains a phi, we may have to add a
669+ // large number of additional phis with additional incoming values.
670+ if (NumPhis != 0 || any_of (TailBB.successors (), [](MachineBasicBlock *MBB) {
671+ return any_of (*MBB, [](MachineInstr &MI) { return MI.isPHI (); });
672+ }))
673+ return false ;
667674 }
668675
669676 // Check if any of the successors of TailBB has a PHI node in which the
0 commit comments