Fix PR5262: when folding select into PHI, make sure all operands are available
[oota-llvm.git] / lib / Transforms / Scalar / LoopRotation.cpp
index 1118ed55918751c3a2ca93b48ebcfe3c9a5fb82d..70c69bb1dae0016735483fc40806cf2288ef668a 100644 (file)
 //===----------------------------------------------------------------------===//
 
 #define DEBUG_TYPE "loop-rotate"
-
 #include "llvm/Transforms/Scalar.h"
 #include "llvm/Function.h"
-#include "llvm/Instructions.h"
+#include "llvm/IntrinsicInst.h"
 #include "llvm/Analysis/LoopInfo.h"
 #include "llvm/Analysis/LoopPass.h"
 #include "llvm/Analysis/Dominators.h"
@@ -26,7 +25,6 @@
 #include "llvm/Support/Debug.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/ADT/SmallVector.h"
-
 using namespace llvm;
 
 #define MAX_HEADER_SIZE 16
@@ -34,7 +32,7 @@ using namespace llvm;
 STATISTIC(NumRotated, "Number of loops rotated");
 namespace {
 
-  class VISIBILITY_HIDDEN RenameData {
+  class RenameData {
   public:
     RenameData(Instruction *O, Value *P, Instruction *H) 
       : Original(O), PreHeader(P), Header(H) { }
@@ -44,8 +42,7 @@ namespace {
     Instruction *Header; // New header replacement
   };
   
-  class VISIBILITY_HIDDEN LoopRotate : public LoopPass {
-
+  class LoopRotate : public LoopPass {
   public:
     static char ID; // Pass ID, replacement for typeid
     LoopRotate() : LoopPass(&ID) {}
@@ -110,7 +107,7 @@ static RegisterPass<LoopRotate> X("loop-rotate", "Rotate Loops");
 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
 
 /// Rotate Loop L as many times as possible. Return true if
-/// loop is rotated at least once.
+/// the loop is rotated at least once.
 bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
 
   bool RotatedOneLoop = false;
@@ -134,15 +131,15 @@ bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
   OrigPreHeader = L->getLoopPreheader();
   OrigLatch = L->getLoopLatch();
 
-  // If loop has only one block then there is not much to rotate.
+  // If the loop has only one block then there is not much to rotate.
   if (L->getBlocks().size() == 1)
     return false;
 
   assert(OrigHeader && OrigLatch && OrigPreHeader &&
          "Loop is not in canonical form");
 
-  // If loop header is not one of the loop exit block then
-  // either this loop is already rotated or it is not 
+  // If the loop header is not one of the loop exiting blocks then
+  // either this loop is already rotated or it is not
   // suitable for loop rotation transformations.
   if (!L->isLoopExit(OrigHeader))
     return false;
@@ -163,11 +160,28 @@ bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
 
   // Check size of original header and reject
   // loop if it is very big.
-  if (OrigHeader->size() > MAX_HEADER_SIZE)
+  unsigned Size = 0;
+  
+  // FIXME: Use common api to estimate size.
+  for (BasicBlock::const_iterator OI = OrigHeader->begin(), 
+         OE = OrigHeader->end(); OI != OE; ++OI) {
+      if (isa<PHINode>(OI)) 
+        continue;           // PHI nodes don't count.
+      if (isa<DbgInfoIntrinsic>(OI))
+        continue;  // Debug intrinsics don't count as size.
+      Size++;
+  }
+
+  if (Size > MAX_HEADER_SIZE)
     return false;
 
   // Now, this loop is suitable for rotation.
 
+  // Anything ScalarEvolution may know about this loop or the PHI nodes
+  // in its header will soon be invalidated.
+  if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
+    SE->forgetLoopBackedgeTakenCount(L);
+
   // Find new Loop header. NewHeader is a Header's one and only successor
   // that is inside loop.  Header's other successor is outside the
   // loop.  Otherwise loop is not suitable for rotation.
@@ -178,14 +192,20 @@ bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
   assert(NewHeader && "Unable to determine new loop header");
   assert(L->contains(NewHeader) && !L->contains(Exit) && 
          "Unable to determine loop header and exit blocks");
-
-  // Copy PHI nodes and other instructions from original header
-  // into original pre-header. Unlike original header, original pre-header is
-  // not a member of loop. 
+  
+  // This code assumes that the new header has exactly one predecessor.
+  // Remove any single-entry PHI nodes in it.
+  assert(NewHeader->getSinglePredecessor() &&
+         "New header doesn't have one pred!");
+  FoldSingleEntryPHINodes(NewHeader);
+
+  // Copy PHI nodes and other instructions from the original header
+  // into the original pre-header. Unlike the original header, the original
+  // pre-header is not a member of the loop.
   //
-  // New loop header is one and only successor of original header that 
+  // The new loop header is the one and only successor of original header that
   // is inside the loop. All other original header successors are outside 
-  // the loop. Copy PHI Nodes from original header into new loop header. 
+  // the loop. Copy PHI Nodes from the original header into the new loop header.
   // Add second incoming value, from original loop pre-header into these phi 
   // nodes. If a value defined in original header is used outside original 
   // header then new loop header will need new phi nodes with two incoming 
@@ -202,8 +222,8 @@ bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
     // are directly propagated.
     Value *NPV = PN->getIncomingValueForBlock(OrigPreHeader);
 
-    // Create new PHI node with two incoming values for NewHeader.
-    // One incoming value is from OrigLatch (through OrigHeader) and 
+    // Create new PHI node with two incoming values for NewHeader.
+    // One incoming value is from OrigLatch (through OrigHeader) and the
     // second incoming value is from original pre-header.
     PHINode *NH = PHINode::Create(PN->getType(), PN->getName(),
                                   NewHeader->begin());
@@ -318,8 +338,8 @@ bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
         // Add second incoming argument from new Pre header.
         UPhi->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
       } else {
-        // Used outside Exit block. Create a new PHI node from exit block
-        // to receive value from ne new header ane pre header.
+        // Used outside Exit block. Create a new PHI node in the exit block
+        // to receive the value from the new header and pre-header.
         PHINode *PN = PHINode::Create(U->getType(), U->getName(),
                                       Exit->begin());
         PN->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
@@ -336,10 +356,9 @@ bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
 
   // Removing incoming branch from loop preheader to original header.
   // Now original header is inside the loop.
-  for (BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
-       I != E; ++I)
-    if (PHINode *PN = dyn_cast<PHINode>(I))
-      PN->removeIncomingValue(OrigPreHeader);
+  for (BasicBlock::iterator I = OrigHeader->begin();
+       (PN = dyn_cast<PHINode>(I)); ++I)
+    PN->removeIncomingValue(OrigPreHeader);
 
   // Make NewHeader as the new header for the loop.
   L->moveToHeader(NewHeader);
@@ -351,16 +370,13 @@ bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
 }
 
 /// Make sure all Exit block PHINodes have required incoming values.
-/// If incoming value is constant or defined outside the loop then
-/// PHINode may not have an entry for original pre-header. 
+/// If an incoming value is constant or defined outside the loop then
+/// PHINode may not have an entry for the original pre-header.
 void LoopRotate::updateExitBlock() {
 
-  for (BasicBlock::iterator I = Exit->begin(), E = Exit->end();
-       I != E; ++I) {
-
-    PHINode *PN = dyn_cast<PHINode>(I);
-    if (!PN)
-      break;
+  PHINode *PN;
+  for (BasicBlock::iterator I = Exit->begin();
+       (PN = dyn_cast<PHINode>(I)); ++I) {
 
     // There is already one incoming value from original pre-header block.
     if (PN->getBasicBlockIndex(OrigPreHeader) != -1)
@@ -368,7 +384,7 @@ void LoopRotate::updateExitBlock() {
 
     const RenameData *ILoopHeaderInfo;
     Value *V = PN->getIncomingValueForBlock(OrigHeader);
-    if (isa<Instruction>(V) && 
+    if (isa<Instruction>(V) &&
         (ILoopHeaderInfo = findReplacementData(cast<Instruction>(V)))) {
       assert(ILoopHeaderInfo->PreHeader && "Missing New Preheader Instruction");
       PN->addIncoming(ILoopHeaderInfo->PreHeader, OrigPreHeader);
@@ -423,7 +439,8 @@ void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
   // Right now original pre-header has two successors, new header and
   // exit block. Insert new block between original pre-header and
   // new header such that loop's new pre-header has only one successor.
-  BasicBlock *NewPreHeader = BasicBlock::Create("bb.nph",
+  BasicBlock *NewPreHeader = BasicBlock::Create(OrigHeader->getContext(),
+                                                "bb.nph",
                                                 OrigHeader->getParent(), 
                                                 NewHeader);
   LoopInfo &LI = LPM.getAnalysis<LoopInfo>();
@@ -439,13 +456,10 @@ void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
            "Unexpected original pre-header terminator");
     OrigPH_BI->setSuccessor(1, NewPreHeader);
   }
-  
-  for (BasicBlock::iterator I = NewHeader->begin(), E = NewHeader->end();
-       I != E; ++I) {
-    PHINode *PN = dyn_cast<PHINode>(I);
-    if (!PN)
-      break;
 
+  PHINode *PN;
+  for (BasicBlock::iterator I = NewHeader->begin();
+       (PN = dyn_cast<PHINode>(I)); ++I) {
     int index = PN->getBasicBlockIndex(OrigPreHeader);
     assert(index != -1 && "Expected incoming value from Original PreHeader");
     PN->setIncomingBlock(index, NewPreHeader);
@@ -453,7 +467,7 @@ void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
            "Expected only one incoming value from Original PreHeader");
   }
 
-  if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
+  if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
     DT->addNewBlock(NewPreHeader, OrigPreHeader);
     DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
     DT->changeImmediateDominator(Exit, OrigPreHeader);
@@ -469,7 +483,7 @@ void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
     DT->changeImmediateDominator(OrigHeader, OrigLatch);
   }
 
-  if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
+  if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>()) {
     // New Preheader's dominance frontier is Exit block.
     DominanceFrontier::DomSetType NewPHSet;
     NewPHSet.insert(Exit);
@@ -502,26 +516,30 @@ void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
       DF->addBasicBlock(L->getHeader(), LatchSet);
     }
 
-    // If a loop block dominates new loop latch then its frontier is
-    // new header and Exit.
+    // If a loop block dominates new loop latch then add to its frontiers
+    // new header and Exit and remove new latch (which is equal to original
+    // header).
     BasicBlock *NewLatch = L->getLoopLatch();
-    DominatorTree *DT = getAnalysisToUpdate<DominatorTree>();
-    for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
-         BI != BE; ++BI) {
-      BasicBlock *B = *BI;
-      if (DT->dominates(B, NewLatch)) {
-        DominanceFrontier::iterator BDFI = DF->find(B);
-        if (BDFI != DF->end()) {
-          DominanceFrontier::DomSetType &BSet = BDFI->second;
-          BSet = BDFI->second;
-          BSet.clear();
-          BSet.insert(L->getHeader());
-          BSet.insert(Exit);
-        } else {
-          DominanceFrontier::DomSetType BSet;
-          BSet.insert(L->getHeader());
-          BSet.insert(Exit);
-          DF->addBasicBlock(B, BSet);
+
+    assert(NewLatch == OrigHeader && "NewLatch is inequal to OrigHeader");
+
+    if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
+      for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
+           BI != BE; ++BI) {
+        BasicBlock *B = *BI;
+        if (DT->dominates(B, NewLatch)) {
+          DominanceFrontier::iterator BDFI = DF->find(B);
+          if (BDFI != DF->end()) {
+            DominanceFrontier::DomSetType &BSet = BDFI->second;
+            BSet.erase(NewLatch);
+            BSet.insert(L->getHeader());
+            BSet.insert(Exit);
+          } else {
+            DominanceFrontier::DomSetType BSet;
+            BSet.insert(L->getHeader());
+            BSet.insert(Exit);
+            DF->addBasicBlock(B, BSet);
+          }
         }
       }
     }
@@ -529,23 +547,7 @@ void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
 
   // Preserve canonical loop form, which means Exit block should
   // have only one predecessor.
-  BasicBlock *NExit = SplitEdge(L->getLoopLatch(), Exit, this);
-
-  // Preserve LCSSA.
-  BasicBlock::iterator I = Exit->begin(), E = Exit->end();
-  PHINode *PN = NULL;
-  for (; (PN = dyn_cast<PHINode>(I)); ++I) {
-    unsigned N = PN->getNumIncomingValues();
-    for (unsigned index = 0; index < N; ++index)
-      if (PN->getIncomingBlock(index) == NExit) {
-        PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName(),
-                                         NExit->begin());
-        NewPN->addIncoming(PN->getIncomingValue(index), L->getLoopLatch());
-        PN->setIncomingValue(index, NewPN);
-        PN->setIncomingBlock(index, NExit);
-        break;
-      }
-  }
+  SplitEdge(L->getLoopLatch(), Exit, this);
 
   assert(NewHeader && L->getHeader() == NewHeader &&
          "Invalid loop header after loop rotation");