LoopRotation.cpp revision 198892
1//===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
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 Loop Rotation Pass.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "loop-rotate"
15#include "llvm/Transforms/Scalar.h"
16#include "llvm/Function.h"
17#include "llvm/IntrinsicInst.h"
18#include "llvm/Analysis/LoopInfo.h"
19#include "llvm/Analysis/LoopPass.h"
20#include "llvm/Analysis/Dominators.h"
21#include "llvm/Analysis/ScalarEvolution.h"
22#include "llvm/Transforms/Utils/Local.h"
23#include "llvm/Transforms/Utils/BasicBlockUtils.h"
24#include "llvm/Transforms/Utils/SSAUpdater.h"
25#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/ADT/Statistic.h"
28#include "llvm/ADT/SmallVector.h"
29using namespace llvm;
30
31#define MAX_HEADER_SIZE 16
32
33STATISTIC(NumRotated, "Number of loops rotated");
34namespace {
35
36  class LoopRotate : public LoopPass {
37  public:
38    static char ID; // Pass ID, replacement for typeid
39    LoopRotate() : LoopPass(&ID) {}
40
41    // Rotate Loop L as many times as possible. Return true if
42    // loop is rotated at least once.
43    bool runOnLoop(Loop *L, LPPassManager &LPM);
44
45    // LCSSA form makes instruction renaming easier.
46    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47      AU.addRequiredID(LoopSimplifyID);
48      AU.addPreservedID(LoopSimplifyID);
49      AU.addRequiredID(LCSSAID);
50      AU.addPreservedID(LCSSAID);
51      AU.addPreserved<ScalarEvolution>();
52      AU.addPreserved<LoopInfo>();
53      AU.addPreserved<DominatorTree>();
54      AU.addPreserved<DominanceFrontier>();
55    }
56
57    // Helper functions
58
59    /// Do actual work
60    bool rotateLoop(Loop *L, LPPassManager &LPM);
61
62    /// Initialize local data
63    void initialize();
64
65    /// After loop rotation, loop pre-header has multiple sucessors.
66    /// Insert one forwarding basic block to ensure that loop pre-header
67    /// has only one successor.
68    void preserveCanonicalLoopForm(LPPassManager &LPM);
69
70  private:
71    Loop *L;
72    BasicBlock *OrigHeader;
73    BasicBlock *OrigPreHeader;
74    BasicBlock *OrigLatch;
75    BasicBlock *NewHeader;
76    BasicBlock *Exit;
77    LPPassManager *LPM_Ptr;
78  };
79}
80
81char LoopRotate::ID = 0;
82static RegisterPass<LoopRotate> X("loop-rotate", "Rotate Loops");
83
84Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
85
86/// Rotate Loop L as many times as possible. Return true if
87/// the loop is rotated at least once.
88bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
89
90  bool RotatedOneLoop = false;
91  initialize();
92  LPM_Ptr = &LPM;
93
94  // One loop can be rotated multiple times.
95  while (rotateLoop(Lp,LPM)) {
96    RotatedOneLoop = true;
97    initialize();
98  }
99
100  return RotatedOneLoop;
101}
102
103/// Rotate loop LP. Return true if the loop is rotated.
104bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
105  L = Lp;
106
107  OrigHeader =  L->getHeader();
108  OrigPreHeader = L->getLoopPreheader();
109  OrigLatch = L->getLoopLatch();
110
111  // If the loop has only one block then there is not much to rotate.
112  if (L->getBlocks().size() == 1)
113    return false;
114
115  assert(OrigHeader && OrigLatch && OrigPreHeader &&
116         "Loop is not in canonical form");
117
118  // If the loop header is not one of the loop exiting blocks then
119  // either this loop is already rotated or it is not
120  // suitable for loop rotation transformations.
121  if (!L->isLoopExiting(OrigHeader))
122    return false;
123
124  BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
125  if (!BI)
126    return false;
127  assert(BI->isConditional() && "Branch Instruction is not conditional");
128
129  // Updating PHInodes in loops with multiple exits adds complexity.
130  // Keep it simple, and restrict loop rotation to loops with one exit only.
131  // In future, lift this restriction and support for multiple exits if
132  // required.
133  SmallVector<BasicBlock*, 8> ExitBlocks;
134  L->getExitBlocks(ExitBlocks);
135  if (ExitBlocks.size() > 1)
136    return false;
137
138  // Check size of original header and reject
139  // loop if it is very big.
140  unsigned Size = 0;
141
142  // FIXME: Use common api to estimate size.
143  for (BasicBlock::const_iterator OI = OrigHeader->begin(),
144         OE = OrigHeader->end(); OI != OE; ++OI) {
145      if (isa<PHINode>(OI))
146        continue;           // PHI nodes don't count.
147      if (isa<DbgInfoIntrinsic>(OI))
148        continue;  // Debug intrinsics don't count as size.
149      Size++;
150  }
151
152  if (Size > MAX_HEADER_SIZE)
153    return false;
154
155  // Now, this loop is suitable for rotation.
156
157  // Anything ScalarEvolution may know about this loop or the PHI nodes
158  // in its header will soon be invalidated.
159  if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
160    SE->forgetLoop(L);
161
162  // Find new Loop header. NewHeader is a Header's one and only successor
163  // that is inside loop.  Header's other successor is outside the
164  // loop.  Otherwise loop is not suitable for rotation.
165  Exit = BI->getSuccessor(0);
166  NewHeader = BI->getSuccessor(1);
167  if (L->contains(Exit))
168    std::swap(Exit, NewHeader);
169  assert(NewHeader && "Unable to determine new loop header");
170  assert(L->contains(NewHeader) && !L->contains(Exit) &&
171         "Unable to determine loop header and exit blocks");
172
173  // This code assumes that the new header has exactly one predecessor.
174  // Remove any single-entry PHI nodes in it.
175  assert(NewHeader->getSinglePredecessor() &&
176         "New header doesn't have one pred!");
177  FoldSingleEntryPHINodes(NewHeader);
178
179  // Begin by walking OrigHeader and populating ValueMap with an entry for
180  // each Instruction.
181  BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
182  DenseMap<const Value *, Value *> ValueMap;
183
184  // For PHI nodes, the value available in OldPreHeader is just the
185  // incoming value from OldPreHeader.
186  for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
187    ValueMap[PN] = PN->getIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
188
189  // For the rest of the instructions, create a clone in the OldPreHeader.
190  TerminatorInst *LoopEntryBranch = OrigPreHeader->getTerminator();
191  for (; I != E; ++I) {
192    Instruction *C = I->clone();
193    C->setName(I->getName());
194    C->insertBefore(LoopEntryBranch);
195    ValueMap[I] = C;
196  }
197
198  // Along with all the other instructions, we just cloned OrigHeader's
199  // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
200  // successors by duplicating their incoming values for OrigHeader.
201  TerminatorInst *TI = OrigHeader->getTerminator();
202  for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
203    for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
204         PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
205      PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreHeader);
206
207  // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
208  // OrigPreHeader's old terminator (the original branch into the loop), and
209  // remove the corresponding incoming values from the PHI nodes in OrigHeader.
210  LoopEntryBranch->eraseFromParent();
211  for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
212    PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
213
214  // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
215  // as necessary.
216  SSAUpdater SSA;
217  for (I = OrigHeader->begin(); I != E; ++I) {
218    Value *OrigHeaderVal = I;
219    Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
220
221    // The value now exits in two versions: the initial value in the preheader
222    // and the loop "next" value in the original header.
223    SSA.Initialize(OrigHeaderVal);
224    SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
225    SSA.AddAvailableValue(OrigPreHeader, OrigPreHeaderVal);
226
227    // Visit each use of the OrigHeader instruction.
228    for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
229         UE = OrigHeaderVal->use_end(); UI != UE; ) {
230      // Grab the use before incrementing the iterator.
231      Use &U = UI.getUse();
232
233      // Increment the iterator before removing the use from the list.
234      ++UI;
235
236      // SSAUpdater can't handle a non-PHI use in the same block as an
237      // earlier def. We can easily handle those cases manually.
238      Instruction *UserInst = cast<Instruction>(U.getUser());
239      if (!isa<PHINode>(UserInst)) {
240        BasicBlock *UserBB = UserInst->getParent();
241
242        // The original users in the OrigHeader are already using the
243        // original definitions.
244        if (UserBB == OrigHeader)
245          continue;
246
247        // Users in the OrigPreHeader need to use the value to which the
248        // original definitions are mapped.
249        if (UserBB == OrigPreHeader) {
250          U = OrigPreHeaderVal;
251          continue;
252        }
253      }
254
255      // Anything else can be handled by SSAUpdater.
256      SSA.RewriteUse(U);
257    }
258  }
259
260  // NewHeader is now the header of the loop.
261  L->moveToHeader(NewHeader);
262
263  preserveCanonicalLoopForm(LPM);
264
265  NumRotated++;
266  return true;
267}
268
269/// Initialize local data
270void LoopRotate::initialize() {
271  L = NULL;
272  OrigHeader = NULL;
273  OrigPreHeader = NULL;
274  NewHeader = NULL;
275  Exit = NULL;
276}
277
278/// After loop rotation, loop pre-header has multiple sucessors.
279/// Insert one forwarding basic block to ensure that loop pre-header
280/// has only one successor.
281void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
282
283  // Right now original pre-header has two successors, new header and
284  // exit block. Insert new block between original pre-header and
285  // new header such that loop's new pre-header has only one successor.
286  BasicBlock *NewPreHeader = BasicBlock::Create(OrigHeader->getContext(),
287                                                "bb.nph",
288                                                OrigHeader->getParent(),
289                                                NewHeader);
290  LoopInfo &LI = LPM.getAnalysis<LoopInfo>();
291  if (Loop *PL = LI.getLoopFor(OrigPreHeader))
292    PL->addBasicBlockToLoop(NewPreHeader, LI.getBase());
293  BranchInst::Create(NewHeader, NewPreHeader);
294
295  BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
296  if (OrigPH_BI->getSuccessor(0) == NewHeader)
297    OrigPH_BI->setSuccessor(0, NewPreHeader);
298  else {
299    assert(OrigPH_BI->getSuccessor(1) == NewHeader &&
300           "Unexpected original pre-header terminator");
301    OrigPH_BI->setSuccessor(1, NewPreHeader);
302  }
303
304  PHINode *PN;
305  for (BasicBlock::iterator I = NewHeader->begin();
306       (PN = dyn_cast<PHINode>(I)); ++I) {
307    int index = PN->getBasicBlockIndex(OrigPreHeader);
308    assert(index != -1 && "Expected incoming value from Original PreHeader");
309    PN->setIncomingBlock(index, NewPreHeader);
310    assert(PN->getBasicBlockIndex(OrigPreHeader) == -1 &&
311           "Expected only one incoming value from Original PreHeader");
312  }
313
314  if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
315    DT->addNewBlock(NewPreHeader, OrigPreHeader);
316    DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
317    DT->changeImmediateDominator(Exit, OrigPreHeader);
318    for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
319         BI != BE; ++BI) {
320      BasicBlock *B = *BI;
321      if (L->getHeader() != B) {
322        DomTreeNode *Node = DT->getNode(B);
323        if (Node && Node->getBlock() == OrigHeader)
324          DT->changeImmediateDominator(*BI, L->getHeader());
325      }
326    }
327    DT->changeImmediateDominator(OrigHeader, OrigLatch);
328  }
329
330  if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>()) {
331    // New Preheader's dominance frontier is Exit block.
332    DominanceFrontier::DomSetType NewPHSet;
333    NewPHSet.insert(Exit);
334    DF->addBasicBlock(NewPreHeader, NewPHSet);
335
336    // New Header's dominance frontier now includes itself and Exit block
337    DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
338    if (HeadI != DF->end()) {
339      DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
340      HeaderSet.clear();
341      HeaderSet.insert(L->getHeader());
342      HeaderSet.insert(Exit);
343    } else {
344      DominanceFrontier::DomSetType HeaderSet;
345      HeaderSet.insert(L->getHeader());
346      HeaderSet.insert(Exit);
347      DF->addBasicBlock(L->getHeader(), HeaderSet);
348    }
349
350    // Original header (new Loop Latch)'s dominance frontier is Exit.
351    DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
352    if (LatchI != DF->end()) {
353      DominanceFrontier::DomSetType &LatchSet = LatchI->second;
354      LatchSet = LatchI->second;
355      LatchSet.clear();
356      LatchSet.insert(Exit);
357    } else {
358      DominanceFrontier::DomSetType LatchSet;
359      LatchSet.insert(Exit);
360      DF->addBasicBlock(L->getHeader(), LatchSet);
361    }
362
363    // If a loop block dominates new loop latch then add to its frontiers
364    // new header and Exit and remove new latch (which is equal to original
365    // header).
366    BasicBlock *NewLatch = L->getLoopLatch();
367
368    assert(NewLatch == OrigHeader && "NewLatch is inequal to OrigHeader");
369
370    if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
371      for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
372           BI != BE; ++BI) {
373        BasicBlock *B = *BI;
374        if (DT->dominates(B, NewLatch)) {
375          DominanceFrontier::iterator BDFI = DF->find(B);
376          if (BDFI != DF->end()) {
377            DominanceFrontier::DomSetType &BSet = BDFI->second;
378            BSet.erase(NewLatch);
379            BSet.insert(L->getHeader());
380            BSet.insert(Exit);
381          } else {
382            DominanceFrontier::DomSetType BSet;
383            BSet.insert(L->getHeader());
384            BSet.insert(Exit);
385            DF->addBasicBlock(B, BSet);
386          }
387        }
388      }
389    }
390  }
391
392  // Preserve canonical loop form, which means Exit block should
393  // have only one predecessor.
394  SplitEdge(L->getLoopLatch(), Exit, this);
395
396  assert(NewHeader && L->getHeader() == NewHeader &&
397         "Invalid loop header after loop rotation");
398  assert(NewPreHeader && L->getLoopPreheader() == NewPreHeader &&
399         "Invalid loop preheader after loop rotation");
400  assert(L->getLoopLatch() &&
401         "Invalid loop latch after loop rotation");
402}
403