LoopRotation.cpp revision d04a8d4b33ff316ca4cf961e06c9e312eff8e64f
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/ADT/Statistic.h"
17#include "llvm/Analysis/CodeMetrics.h"
18#include "llvm/Analysis/InstructionSimplify.h"
19#include "llvm/Analysis/LoopPass.h"
20#include "llvm/Analysis/ScalarEvolution.h"
21#include "llvm/Analysis/ValueTracking.h"
22#include "llvm/Function.h"
23#include "llvm/IntrinsicInst.h"
24#include "llvm/Support/CFG.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Transforms/Utils/BasicBlockUtils.h"
27#include "llvm/Transforms/Utils/Local.h"
28#include "llvm/Transforms/Utils/SSAUpdater.h"
29#include "llvm/Transforms/Utils/ValueMapper.h"
30using namespace llvm;
31
32#define MAX_HEADER_SIZE 16
33
34STATISTIC(NumRotated, "Number of loops rotated");
35namespace {
36
37  class LoopRotate : public LoopPass {
38  public:
39    static char ID; // Pass ID, replacement for typeid
40    LoopRotate() : LoopPass(ID) {
41      initializeLoopRotatePass(*PassRegistry::getPassRegistry());
42    }
43
44    // LCSSA form makes instruction renaming easier.
45    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
46      AU.addPreserved<DominatorTree>();
47      AU.addRequired<LoopInfo>();
48      AU.addPreserved<LoopInfo>();
49      AU.addRequiredID(LoopSimplifyID);
50      AU.addPreservedID(LoopSimplifyID);
51      AU.addRequiredID(LCSSAID);
52      AU.addPreservedID(LCSSAID);
53      AU.addPreserved<ScalarEvolution>();
54    }
55
56    bool runOnLoop(Loop *L, LPPassManager &LPM);
57    void simplifyLoopLatch(Loop *L);
58    bool rotateLoop(Loop *L);
59
60  private:
61    LoopInfo *LI;
62  };
63}
64
65char LoopRotate::ID = 0;
66INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
67INITIALIZE_PASS_DEPENDENCY(LoopInfo)
68INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
69INITIALIZE_PASS_DEPENDENCY(LCSSA)
70INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
71
72Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
73
74/// Rotate Loop L as many times as possible. Return true if
75/// the loop is rotated at least once.
76bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
77  LI = &getAnalysis<LoopInfo>();
78
79  // Simplify the loop latch before attempting to rotate the header
80  // upward. Rotation may not be needed if the loop tail can be folded into the
81  // loop exit.
82  simplifyLoopLatch(L);
83
84  // One loop can be rotated multiple times.
85  bool MadeChange = false;
86  while (rotateLoop(L))
87    MadeChange = true;
88
89  return MadeChange;
90}
91
92/// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
93/// old header into the preheader.  If there were uses of the values produced by
94/// these instruction that were outside of the loop, we have to insert PHI nodes
95/// to merge the two values.  Do this now.
96static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
97                                            BasicBlock *OrigPreheader,
98                                            ValueToValueMapTy &ValueMap) {
99  // Remove PHI node entries that are no longer live.
100  BasicBlock::iterator I, E = OrigHeader->end();
101  for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
102    PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
103
104  // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
105  // as necessary.
106  SSAUpdater SSA;
107  for (I = OrigHeader->begin(); I != E; ++I) {
108    Value *OrigHeaderVal = I;
109
110    // If there are no uses of the value (e.g. because it returns void), there
111    // is nothing to rewrite.
112    if (OrigHeaderVal->use_empty())
113      continue;
114
115    Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
116
117    // The value now exits in two versions: the initial value in the preheader
118    // and the loop "next" value in the original header.
119    SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
120    SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
121    SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
122
123    // Visit each use of the OrigHeader instruction.
124    for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
125         UE = OrigHeaderVal->use_end(); UI != UE; ) {
126      // Grab the use before incrementing the iterator.
127      Use &U = UI.getUse();
128
129      // Increment the iterator before removing the use from the list.
130      ++UI;
131
132      // SSAUpdater can't handle a non-PHI use in the same block as an
133      // earlier def. We can easily handle those cases manually.
134      Instruction *UserInst = cast<Instruction>(U.getUser());
135      if (!isa<PHINode>(UserInst)) {
136        BasicBlock *UserBB = UserInst->getParent();
137
138        // The original users in the OrigHeader are already using the
139        // original definitions.
140        if (UserBB == OrigHeader)
141          continue;
142
143        // Users in the OrigPreHeader need to use the value to which the
144        // original definitions are mapped.
145        if (UserBB == OrigPreheader) {
146          U = OrigPreHeaderVal;
147          continue;
148        }
149      }
150
151      // Anything else can be handled by SSAUpdater.
152      SSA.RewriteUse(U);
153    }
154  }
155}
156
157/// Determine whether the instructions in this range my be safely and cheaply
158/// speculated. This is not an important enough situation to develop complex
159/// heuristics. We handle a single arithmetic instruction along with any type
160/// conversions.
161static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
162                                  BasicBlock::iterator End) {
163  bool seenIncrement = false;
164  for (BasicBlock::iterator I = Begin; I != End; ++I) {
165
166    if (!isSafeToSpeculativelyExecute(I))
167      return false;
168
169    if (isa<DbgInfoIntrinsic>(I))
170      continue;
171
172    switch (I->getOpcode()) {
173    default:
174      return false;
175    case Instruction::GetElementPtr:
176      // GEPs are cheap if all indices are constant.
177      if (!cast<GEPOperator>(I)->hasAllConstantIndices())
178        return false;
179      // fall-thru to increment case
180    case Instruction::Add:
181    case Instruction::Sub:
182    case Instruction::And:
183    case Instruction::Or:
184    case Instruction::Xor:
185    case Instruction::Shl:
186    case Instruction::LShr:
187    case Instruction::AShr:
188      if (seenIncrement)
189        return false;
190      seenIncrement = true;
191      break;
192    case Instruction::Trunc:
193    case Instruction::ZExt:
194    case Instruction::SExt:
195      // ignore type conversions
196      break;
197    }
198  }
199  return true;
200}
201
202/// Fold the loop tail into the loop exit by speculating the loop tail
203/// instructions. Typically, this is a single post-increment. In the case of a
204/// simple 2-block loop, hoisting the increment can be much better than
205/// duplicating the entire loop header. In the cast of loops with early exits,
206/// rotation will not work anyway, but simplifyLoopLatch will put the loop in
207/// canonical form so downstream passes can handle it.
208///
209/// I don't believe this invalidates SCEV.
210void LoopRotate::simplifyLoopLatch(Loop *L) {
211  BasicBlock *Latch = L->getLoopLatch();
212  if (!Latch || Latch->hasAddressTaken())
213    return;
214
215  BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
216  if (!Jmp || !Jmp->isUnconditional())
217    return;
218
219  BasicBlock *LastExit = Latch->getSinglePredecessor();
220  if (!LastExit || !L->isLoopExiting(LastExit))
221    return;
222
223  BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
224  if (!BI)
225    return;
226
227  if (!shouldSpeculateInstrs(Latch->begin(), Jmp))
228    return;
229
230  DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
231        << LastExit->getName() << "\n");
232
233  // Hoist the instructions from Latch into LastExit.
234  LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
235
236  unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
237  BasicBlock *Header = Jmp->getSuccessor(0);
238  assert(Header == L->getHeader() && "expected a backward branch");
239
240  // Remove Latch from the CFG so that LastExit becomes the new Latch.
241  BI->setSuccessor(FallThruPath, Header);
242  Latch->replaceSuccessorsPhiUsesWith(LastExit);
243  Jmp->eraseFromParent();
244
245  // Nuke the Latch block.
246  assert(Latch->empty() && "unable to evacuate Latch");
247  LI->removeBlock(Latch);
248  if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>())
249    DT->eraseNode(Latch);
250  Latch->eraseFromParent();
251}
252
253/// Rotate loop LP. Return true if the loop is rotated.
254bool LoopRotate::rotateLoop(Loop *L) {
255  // If the loop has only one block then there is not much to rotate.
256  if (L->getBlocks().size() == 1)
257    return false;
258
259  BasicBlock *OrigHeader = L->getHeader();
260  BasicBlock *OrigLatch = L->getLoopLatch();
261
262  BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
263  if (BI == 0 || BI->isUnconditional())
264    return false;
265
266  // If the loop header is not one of the loop exiting blocks then
267  // either this loop is already rotated or it is not
268  // suitable for loop rotation transformations.
269  if (!L->isLoopExiting(OrigHeader))
270    return false;
271
272  // If the loop latch already contains a branch that leaves the loop then the
273  // loop is already rotated.
274  if (OrigLatch == 0 || L->isLoopExiting(OrigLatch))
275    return false;
276
277  // Check size of original header and reject loop if it is very big.
278  {
279    CodeMetrics Metrics;
280    Metrics.analyzeBasicBlock(OrigHeader);
281    if (Metrics.NumInsts > MAX_HEADER_SIZE)
282      return false;
283  }
284
285  // Now, this loop is suitable for rotation.
286  BasicBlock *OrigPreheader = L->getLoopPreheader();
287
288  // If the loop could not be converted to canonical form, it must have an
289  // indirectbr in it, just give up.
290  if (OrigPreheader == 0)
291    return false;
292
293  // Anything ScalarEvolution may know about this loop or the PHI nodes
294  // in its header will soon be invalidated.
295  if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
296    SE->forgetLoop(L);
297
298  DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
299
300  // Find new Loop header. NewHeader is a Header's one and only successor
301  // that is inside loop.  Header's other successor is outside the
302  // loop.  Otherwise loop is not suitable for rotation.
303  BasicBlock *Exit = BI->getSuccessor(0);
304  BasicBlock *NewHeader = BI->getSuccessor(1);
305  if (L->contains(Exit))
306    std::swap(Exit, NewHeader);
307  assert(NewHeader && "Unable to determine new loop header");
308  assert(L->contains(NewHeader) && !L->contains(Exit) &&
309         "Unable to determine loop header and exit blocks");
310
311  // This code assumes that the new header has exactly one predecessor.
312  // Remove any single-entry PHI nodes in it.
313  assert(NewHeader->getSinglePredecessor() &&
314         "New header doesn't have one pred!");
315  FoldSingleEntryPHINodes(NewHeader);
316
317  // Begin by walking OrigHeader and populating ValueMap with an entry for
318  // each Instruction.
319  BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
320  ValueToValueMapTy ValueMap;
321
322  // For PHI nodes, the value available in OldPreHeader is just the
323  // incoming value from OldPreHeader.
324  for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
325    ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
326
327  // For the rest of the instructions, either hoist to the OrigPreheader if
328  // possible or create a clone in the OldPreHeader if not.
329  TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
330  while (I != E) {
331    Instruction *Inst = I++;
332
333    // If the instruction's operands are invariant and it doesn't read or write
334    // memory, then it is safe to hoist.  Doing this doesn't change the order of
335    // execution in the preheader, but does prevent the instruction from
336    // executing in each iteration of the loop.  This means it is safe to hoist
337    // something that might trap, but isn't safe to hoist something that reads
338    // memory (without proving that the loop doesn't write).
339    if (L->hasLoopInvariantOperands(Inst) &&
340        !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
341        !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
342        !isa<AllocaInst>(Inst)) {
343      Inst->moveBefore(LoopEntryBranch);
344      continue;
345    }
346
347    // Otherwise, create a duplicate of the instruction.
348    Instruction *C = Inst->clone();
349
350    // Eagerly remap the operands of the instruction.
351    RemapInstruction(C, ValueMap,
352                     RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
353
354    // With the operands remapped, see if the instruction constant folds or is
355    // otherwise simplifyable.  This commonly occurs because the entry from PHI
356    // nodes allows icmps and other instructions to fold.
357    Value *V = SimplifyInstruction(C);
358    if (V && LI->replacementPreservesLCSSAForm(C, V)) {
359      // If so, then delete the temporary instruction and stick the folded value
360      // in the map.
361      delete C;
362      ValueMap[Inst] = V;
363    } else {
364      // Otherwise, stick the new instruction into the new block!
365      C->setName(Inst->getName());
366      C->insertBefore(LoopEntryBranch);
367      ValueMap[Inst] = C;
368    }
369  }
370
371  // Along with all the other instructions, we just cloned OrigHeader's
372  // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
373  // successors by duplicating their incoming values for OrigHeader.
374  TerminatorInst *TI = OrigHeader->getTerminator();
375  for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
376    for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
377         PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
378      PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
379
380  // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
381  // OrigPreHeader's old terminator (the original branch into the loop), and
382  // remove the corresponding incoming values from the PHI nodes in OrigHeader.
383  LoopEntryBranch->eraseFromParent();
384
385  // If there were any uses of instructions in the duplicated block outside the
386  // loop, update them, inserting PHI nodes as required
387  RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
388
389  // NewHeader is now the header of the loop.
390  L->moveToHeader(NewHeader);
391  assert(L->getHeader() == NewHeader && "Latch block is our new header");
392
393
394  // At this point, we've finished our major CFG changes.  As part of cloning
395  // the loop into the preheader we've simplified instructions and the
396  // duplicated conditional branch may now be branching on a constant.  If it is
397  // branching on a constant and if that constant means that we enter the loop,
398  // then we fold away the cond branch to an uncond branch.  This simplifies the
399  // loop in cases important for nested loops, and it also means we don't have
400  // to split as many edges.
401  BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
402  assert(PHBI->isConditional() && "Should be clone of BI condbr!");
403  if (!isa<ConstantInt>(PHBI->getCondition()) ||
404      PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
405          != NewHeader) {
406    // The conditional branch can't be folded, handle the general case.
407    // Update DominatorTree to reflect the CFG change we just made.  Then split
408    // edges as necessary to preserve LoopSimplify form.
409    if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
410      // Everything that was dominated by the old loop header is now dominated
411      // by the original loop preheader. Conceptually the header was merged
412      // into the preheader, even though we reuse the actual block as a new
413      // loop latch.
414      DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
415      SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
416                                                   OrigHeaderNode->end());
417      DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
418      for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
419        DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
420
421      assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
422      assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
423
424      // Update OrigHeader to be dominated by the new header block.
425      DT->changeImmediateDominator(OrigHeader, OrigLatch);
426    }
427
428    // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
429    // thus is not a preheader anymore.
430    // Split the edge to form a real preheader.
431    BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this);
432    NewPH->setName(NewHeader->getName() + ".lr.ph");
433
434    // Preserve canonical loop form, which means that 'Exit' should have only
435    // one predecessor.
436    BasicBlock *ExitSplit = SplitCriticalEdge(L->getLoopLatch(), Exit, this);
437    ExitSplit->moveBefore(Exit);
438  } else {
439    // We can fold the conditional branch in the preheader, this makes things
440    // simpler. The first step is to remove the extra edge to the Exit block.
441    Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
442    BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
443    NewBI->setDebugLoc(PHBI->getDebugLoc());
444    PHBI->eraseFromParent();
445
446    // With our CFG finalized, update DomTree if it is available.
447    if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
448      // Update OrigHeader to be dominated by the new header block.
449      DT->changeImmediateDominator(NewHeader, OrigPreheader);
450      DT->changeImmediateDominator(OrigHeader, OrigLatch);
451
452      // Brute force incremental dominator tree update. Call
453      // findNearestCommonDominator on all CFG predecessors of each child of the
454      // original header.
455      DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
456      SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
457                                                   OrigHeaderNode->end());
458      bool Changed;
459      do {
460        Changed = false;
461        for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
462          DomTreeNode *Node = HeaderChildren[I];
463          BasicBlock *BB = Node->getBlock();
464
465          pred_iterator PI = pred_begin(BB);
466          BasicBlock *NearestDom = *PI;
467          for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
468            NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
469
470          // Remember if this changes the DomTree.
471          if (Node->getIDom()->getBlock() != NearestDom) {
472            DT->changeImmediateDominator(BB, NearestDom);
473            Changed = true;
474          }
475        }
476
477      // If the dominator changed, this may have an effect on other
478      // predecessors, continue until we reach a fixpoint.
479      } while (Changed);
480    }
481  }
482
483  assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
484  assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
485
486  // Now that the CFG and DomTree are in a consistent state again, try to merge
487  // the OrigHeader block into OrigLatch.  This will succeed if they are
488  // connected by an unconditional branch.  This is just a cleanup so the
489  // emitted code isn't too gross in this common case.
490  MergeBlockIntoPredecessor(OrigHeader, this);
491
492  DEBUG(dbgs() << "LoopRotation: into "; L->dump());
493
494  ++NumRotated;
495  return true;
496}
497
498