@@ -847,17 +847,17 @@ static bool CanMergeValues(Value *First, Value *Second) {
847847// / branch to Succ, into Succ.
848848// /
849849// / Assumption: Succ is the single successor for BB.
850- static bool CanPropagatePredecessorsForPHIs (BasicBlock *BB, BasicBlock *Succ) {
850+ static bool
851+ CanPropagatePredecessorsForPHIs (BasicBlock *BB, BasicBlock *Succ,
852+ const SmallPtrSetImpl<BasicBlock *> &BBPreds) {
851853 assert (*succ_begin (BB) == Succ && " Succ is not successor of BB!" );
852854
853855 LLVM_DEBUG (dbgs () << " Looking to fold " << BB->getName () << " into "
854856 << Succ->getName () << " \n " );
855857 // Shortcut, if there is only a single predecessor it must be BB and merging
856858 // is always safe
857- if (Succ->getSinglePredecessor ()) return true ;
858-
859- // Make a list of the predecessors of BB
860- SmallPtrSet<BasicBlock*, 16 > BBPreds (pred_begin (BB), pred_end (BB));
859+ if (Succ->getSinglePredecessor ())
860+ return true ;
861861
862862 // Look at all the phi nodes in Succ, to see if they present a conflict when
863863 // merging these blocks
@@ -997,16 +997,47 @@ static void replaceUndefValuesInPhi(PHINode *PN,
997997 }
998998}
999999
1000+ // Only when they shares a single common predecessor, return true.
1001+ // Only handles cases when BB can't be merged while its predecessors can be
1002+ // redirected.
1003+ static bool
1004+ CanRedirectPredsOfEmptyBBToSucc (BasicBlock *BB, BasicBlock *Succ,
1005+ const SmallPtrSetImpl<BasicBlock *> &BBPreds,
1006+ const SmallPtrSetImpl<BasicBlock *> &SuccPreds,
1007+ BasicBlock *&CommonPred) {
1008+
1009+ // There must be phis in BB, otherwise BB will be merged into Succ directly
1010+ if (BB->phis ().empty () || Succ->phis ().empty ())
1011+ return false ;
1012+
1013+ // BB must have predecessors not shared that can be redirected to Succ
1014+ if (!BB->hasNPredecessorsOrMore (2 ))
1015+ return false ;
1016+
1017+ // Get single common predecessors of both BB and Succ
1018+ for (BasicBlock *SuccPred : SuccPreds) {
1019+ if (BBPreds.count (SuccPred)) {
1020+ if (CommonPred)
1021+ return false ;
1022+ CommonPred = SuccPred;
1023+ }
1024+ }
1025+
1026+ return true ;
1027+ }
1028+
10001029// / Replace a value flowing from a block to a phi with
10011030// / potentially multiple instances of that value flowing from the
10021031// / block's predecessors to the phi.
10031032// /
10041033// / \param BB The block with the value flowing into the phi.
10051034// / \param BBPreds The predecessors of BB.
10061035// / \param PN The phi that we are updating.
1036+ // / \param CommonPred The common predecessor of BB and PN's BasicBlock
10071037static void redirectValuesFromPredecessorsToPhi (BasicBlock *BB,
10081038 const PredBlockVector &BBPreds,
1009- PHINode *PN) {
1039+ PHINode *PN,
1040+ BasicBlock *CommonPred) {
10101041 Value *OldVal = PN->removeIncomingValue (BB, false );
10111042 assert (OldVal && " No entry in PHI for Pred BB!" );
10121043
@@ -1034,26 +1065,39 @@ static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
10341065 // will trigger asserts if we try to clean it up now, without also
10351066 // simplifying the corresponding conditional branch).
10361067 BasicBlock *PredBB = OldValPN->getIncomingBlock (i);
1068+
1069+ if (PredBB == CommonPred)
1070+ continue ;
1071+
10371072 Value *PredVal = OldValPN->getIncomingValue (i);
1038- Value *Selected = selectIncomingValueForBlock (PredVal, PredBB,
1039- IncomingValues);
1073+ Value *Selected =
1074+ selectIncomingValueForBlock (PredVal, PredBB, IncomingValues);
10401075
10411076 // And add a new incoming value for this predecessor for the
10421077 // newly retargeted branch.
10431078 PN->addIncoming (Selected, PredBB);
10441079 }
1080+ if (CommonPred)
1081+ PN->addIncoming (OldValPN->getIncomingValueForBlock (CommonPred), BB);
1082+
10451083 } else {
10461084 for (unsigned i = 0 , e = BBPreds.size (); i != e; ++i) {
10471085 // Update existing incoming values in PN for this
10481086 // predecessor of BB.
10491087 BasicBlock *PredBB = BBPreds[i];
1050- Value *Selected = selectIncomingValueForBlock (OldVal, PredBB,
1051- IncomingValues);
1088+
1089+ if (PredBB == CommonPred)
1090+ continue ;
1091+
1092+ Value *Selected =
1093+ selectIncomingValueForBlock (OldVal, PredBB, IncomingValues);
10521094
10531095 // And add a new incoming value for this predecessor for the
10541096 // newly retargeted branch.
10551097 PN->addIncoming (Selected, PredBB);
10561098 }
1099+ if (CommonPred)
1100+ PN->addIncoming (OldVal, BB);
10571101 }
10581102
10591103 replaceUndefValuesInPhi (PN, IncomingValues);
@@ -1064,13 +1108,30 @@ bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
10641108 assert (BB != &BB->getParent ()->getEntryBlock () &&
10651109 " TryToSimplifyUncondBranchFromEmptyBlock called on entry block!" );
10661110
1067- // We can't eliminate infinite loops.
1111+ // We can't simplify infinite loops.
10681112 BasicBlock *Succ = cast<BranchInst>(BB->getTerminator ())->getSuccessor (0 );
1069- if (BB == Succ) return false ;
1113+ if (BB == Succ)
1114+ return false ;
1115+
1116+ SmallPtrSet<BasicBlock *, 16 > BBPreds (pred_begin (BB), pred_end (BB));
1117+ SmallPtrSet<BasicBlock *, 16 > SuccPreds (pred_begin (Succ), pred_end (Succ));
10701118
1071- // Check to see if merging these blocks would cause conflicts for any of the
1072- // phi nodes in BB or Succ. If not, we can safely merge.
1073- if (!CanPropagatePredecessorsForPHIs (BB, Succ)) return false ;
1119+ // The single common predecessor of BB and Succ when BB cannot be killed
1120+ BasicBlock *CommonPred = nullptr ;
1121+
1122+ bool BBKillable = CanPropagatePredecessorsForPHIs (BB, Succ, BBPreds);
1123+
1124+ // Even if we can not fold bB into Succ, we may be able to redirect the
1125+ // predecessors of BB to Succ.
1126+ bool BBPhisMergeable =
1127+ BBKillable ||
1128+ CanRedirectPredsOfEmptyBBToSucc (BB, Succ, BBPreds, SuccPreds, CommonPred);
1129+
1130+ if (!BBKillable && !BBPhisMergeable)
1131+ return false ;
1132+
1133+ // Check to see if merging these blocks/phis would cause conflicts for any of
1134+ // the phi nodes in BB or Succ. If not, we can safely merge.
10741135
10751136 // Check for cases where Succ has multiple predecessors and a PHI node in BB
10761137 // has uses which will not disappear when the PHI nodes are merged. It is
@@ -1099,6 +1160,11 @@ bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
10991160 }
11001161 }
11011162
1163+ if (BBPhisMergeable && CommonPred)
1164+ LLVM_DEBUG (dbgs () << " Found Common Predecessor between: " << BB->getName ()
1165+ << " and " << Succ->getName () << " : "
1166+ << CommonPred->getName () << " \n " );
1167+
11021168 // 'BB' and 'BB->Pred' are loop latches, bail out to presrve inner loop
11031169 // metadata.
11041170 //
@@ -1171,25 +1237,37 @@ bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
11711237 if (PredTI->hasMetadata (LLVMContext::MD_loop))
11721238 return false ;
11731239
1174- LLVM_DEBUG (dbgs () << " Killing Trivial BB: \n " << *BB);
1240+ if (BBKillable)
1241+ LLVM_DEBUG (dbgs () << " Killing Trivial BB: \n " << *BB);
1242+ else if (BBPhisMergeable)
1243+ LLVM_DEBUG (dbgs () << " Merge Phis in Trivial BB: \n " << *BB);
11751244
11761245 SmallVector<DominatorTree::UpdateType, 32 > Updates;
1246+
11771247 if (DTU) {
11781248 // To avoid processing the same predecessor more than once.
11791249 SmallPtrSet<BasicBlock *, 8 > SeenPreds;
1180- // All predecessors of BB will be moved to Succ.
1181- SmallPtrSet<BasicBlock *, 8 > PredsOfSucc ( pred_begin ( Succ), pred_end (Succ));
1250+ // All predecessors of BB (except the common predecessor) will be moved to
1251+ // Succ.
11821252 Updates.reserve (Updates.size () + 2 * pred_size (BB) + 1 );
1183- for (auto *PredOfBB : predecessors (BB))
1184- // This predecessor of BB may already have Succ as a successor.
1185- if (!PredsOfSucc.contains (PredOfBB))
1253+
1254+ for (auto *PredOfBB : predecessors (BB)) {
1255+ // Do not modify those common predecessors of BB and Succ
1256+ if (!SuccPreds.contains (PredOfBB))
11861257 if (SeenPreds.insert (PredOfBB).second )
11871258 Updates.push_back ({DominatorTree::Insert, PredOfBB, Succ});
1259+ }
1260+
11881261 SeenPreds.clear ();
1262+
11891263 for (auto *PredOfBB : predecessors (BB))
1190- if (SeenPreds.insert (PredOfBB).second )
1264+ // When BB cannot be killed, do not remove the edge between BB and
1265+ // CommonPred.
1266+ if (SeenPreds.insert (PredOfBB).second && PredOfBB != CommonPred)
11911267 Updates.push_back ({DominatorTree::Delete, PredOfBB, BB});
1192- Updates.push_back ({DominatorTree::Delete, BB, Succ});
1268+
1269+ if (BBKillable)
1270+ Updates.push_back ({DominatorTree::Delete, BB, Succ});
11931271 }
11941272
11951273 if (isa<PHINode>(Succ->begin ())) {
@@ -1201,21 +1279,19 @@ bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
12011279 // Loop over all of the PHI nodes in the successor of BB.
12021280 for (BasicBlock::iterator I = Succ->begin (); isa<PHINode>(I); ++I) {
12031281 PHINode *PN = cast<PHINode>(I);
1204-
1205- redirectValuesFromPredecessorsToPhi (BB, BBPreds, PN);
1282+ redirectValuesFromPredecessorsToPhi (BB, BBPreds, PN, CommonPred);
12061283 }
12071284 }
12081285
12091286 if (Succ->getSinglePredecessor ()) {
12101287 // BB is the only predecessor of Succ, so Succ will end up with exactly
12111288 // the same predecessors BB had.
1212-
12131289 // Copy over any phi, debug or lifetime instruction.
12141290 BB->getTerminator ()->eraseFromParent ();
12151291 Succ->splice (Succ->getFirstNonPHI ()->getIterator (), BB);
12161292 } else {
12171293 while (PHINode *PN = dyn_cast<PHINode>(&BB->front ())) {
1218- // We explicitly check for such uses in CanPropagatePredecessorsForPHIs .
1294+ // We explicitly check for such uses for merging phis .
12191295 assert (PN->use_empty () && " There shouldn't be any uses here!" );
12201296 PN->eraseFromParent ();
12211297 }
@@ -1228,21 +1304,35 @@ bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
12281304 for (BasicBlock *Pred : predecessors (BB))
12291305 Pred->getTerminator ()->setMetadata (LLVMContext::MD_loop, LoopMD);
12301306
1231- // Everything that jumped to BB now goes to Succ.
1232- BB->replaceAllUsesWith (Succ);
1233- if (!Succ->hasName ()) Succ->takeName (BB);
1234-
1235- // Clear the successor list of BB to match updates applying to DTU later.
1236- if (BB->getTerminator ())
1237- BB->back ().eraseFromParent ();
1238- new UnreachableInst (BB->getContext (), BB);
1239- assert (succ_empty (BB) && " The successor list of BB isn't empty before "
1240- " applying corresponding DTU updates." );
1307+ if (BBKillable) {
1308+ // Everything that jumped to BB now goes to Succ.
1309+ BB->replaceAllUsesWith (Succ);
1310+
1311+ if (!Succ->hasName ())
1312+ Succ->takeName (BB);
1313+
1314+ // Clear the successor list of BB to match updates applying to DTU later.
1315+ if (BB->getTerminator ())
1316+ BB->back ().eraseFromParent ();
1317+
1318+ new UnreachableInst (BB->getContext (), BB);
1319+ assert (succ_empty (BB) && " The successor list of BB isn't empty before "
1320+ " applying corresponding DTU updates." );
1321+ } else if (BBPhisMergeable) {
1322+ // Everything except CommonPred that jumped to BB now goes to Succ.
1323+ BB->replaceUsesWithIf (Succ, [BBPreds, CommonPred](Use &U) -> bool {
1324+ if (Instruction *UseInst = dyn_cast<Instruction>(U.getUser ()))
1325+ return UseInst->getParent () != CommonPred &&
1326+ BBPreds.contains (UseInst->getParent ());
1327+ return false ;
1328+ });
1329+ }
12411330
12421331 if (DTU)
12431332 DTU->applyUpdates (Updates);
12441333
1245- DeleteDeadBlock (BB, DTU);
1334+ if (BBKillable)
1335+ DeleteDeadBlock (BB, DTU);
12461336
12471337 return true ;
12481338}
0 commit comments