1 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements Loop Rotation Pass.
12 //===----------------------------------------------------------------------===//
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/CodeMetrics.h"
19 #include "llvm/Analysis/LoopPass.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/ScalarEvolution.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
25 #include "llvm/Transforms/Utils/SSAUpdater.h"
26 #include "llvm/Transforms/Utils/ValueMapper.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/ADT/Statistic.h"
31 #define MAX_HEADER_SIZE 16
33 STATISTIC(NumRotated, "Number of loops rotated");
36 class LoopRotate : public LoopPass {
38 static char ID; // Pass ID, replacement for typeid
39 LoopRotate() : LoopPass(ID) {
40 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
43 // LCSSA form makes instruction renaming easier.
44 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
45 AU.addPreserved<DominatorTree>();
46 AU.addRequired<LoopInfo>();
47 AU.addPreserved<LoopInfo>();
48 AU.addRequiredID(LoopSimplifyID);
49 AU.addPreservedID(LoopSimplifyID);
50 AU.addRequiredID(LCSSAID);
51 AU.addPreservedID(LCSSAID);
52 AU.addPreserved<ScalarEvolution>();
55 bool runOnLoop(Loop *L, LPPassManager &LPM);
56 void simplifyLoopLatch(Loop *L);
57 bool rotateLoop(Loop *L);
64 char LoopRotate::ID = 0;
65 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
66 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
67 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
68 INITIALIZE_PASS_DEPENDENCY(LCSSA)
69 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
71 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
73 /// Rotate Loop L as many times as possible. Return true if
74 /// the loop is rotated at least once.
75 bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
76 LI = &getAnalysis<LoopInfo>();
78 // Simplify the loop latch before attempting to rotate the header
79 // upward. Rotation may not be needed if the loop tail can be folded into the
83 // One loop can be rotated multiple times.
84 bool MadeChange = false;
91 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
92 /// old header into the preheader. If there were uses of the values produced by
93 /// these instruction that were outside of the loop, we have to insert PHI nodes
94 /// to merge the two values. Do this now.
95 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
96 BasicBlock *OrigPreheader,
97 ValueToValueMapTy &ValueMap) {
98 // Remove PHI node entries that are no longer live.
99 BasicBlock::iterator I, E = OrigHeader->end();
100 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
101 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
103 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
106 for (I = OrigHeader->begin(); I != E; ++I) {
107 Value *OrigHeaderVal = I;
109 // If there are no uses of the value (e.g. because it returns void), there
110 // is nothing to rewrite.
111 if (OrigHeaderVal->use_empty())
114 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
116 // The value now exits in two versions: the initial value in the preheader
117 // and the loop "next" value in the original header.
118 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
119 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
120 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
122 // Visit each use of the OrigHeader instruction.
123 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
124 UE = OrigHeaderVal->use_end(); UI != UE; ) {
125 // Grab the use before incrementing the iterator.
126 Use &U = UI.getUse();
128 // Increment the iterator before removing the use from the list.
131 // SSAUpdater can't handle a non-PHI use in the same block as an
132 // earlier def. We can easily handle those cases manually.
133 Instruction *UserInst = cast<Instruction>(U.getUser());
134 if (!isa<PHINode>(UserInst)) {
135 BasicBlock *UserBB = UserInst->getParent();
137 // The original users in the OrigHeader are already using the
138 // original definitions.
139 if (UserBB == OrigHeader)
142 // Users in the OrigPreHeader need to use the value to which the
143 // original definitions are mapped.
144 if (UserBB == OrigPreheader) {
145 U = OrigPreHeaderVal;
150 // Anything else can be handled by SSAUpdater.
156 /// Determine whether the instructions in this range my be safely and cheaply
157 /// speculated. This is not an important enough situation to develop complex
158 /// heuristics. We handle a single arithmetic instruction along with any type
160 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
161 BasicBlock::iterator End) {
162 bool seenIncrement = false;
163 for (BasicBlock::iterator I = Begin; I != End; ++I) {
165 if (!isSafeToSpeculativelyExecute(I))
168 if (isa<DbgInfoIntrinsic>(I))
171 switch (I->getOpcode()) {
174 case Instruction::GetElementPtr:
175 // GEPs are cheap if all indices are constant.
176 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
178 // fall-thru to increment case
179 case Instruction::Add:
180 case Instruction::Sub:
181 case Instruction::And:
182 case Instruction::Or:
183 case Instruction::Xor:
184 case Instruction::Shl:
185 case Instruction::LShr:
186 case Instruction::AShr:
189 seenIncrement = true;
191 case Instruction::Trunc:
192 case Instruction::ZExt:
193 case Instruction::SExt:
194 // ignore type conversions
201 /// Fold the loop tail into the loop exit by speculating the loop tail
202 /// instructions. Typically, this is a single post-increment. In the case of a
203 /// simple 2-block loop, hoisting the increment can be much better than
204 /// duplicating the entire loop header. In the cast of loops with early exits,
205 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
206 /// canonical form so downstream passes can handle it.
208 /// I don't believe this invalidates SCEV.
209 void LoopRotate::simplifyLoopLatch(Loop *L) {
210 BasicBlock *Latch = L->getLoopLatch();
211 if (!Latch || Latch->hasAddressTaken())
214 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
215 if (!Jmp || !Jmp->isUnconditional())
218 BasicBlock *LastExit = Latch->getSinglePredecessor();
219 if (!LastExit || !L->isLoopExiting(LastExit))
222 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
226 if (!shouldSpeculateInstrs(Latch->begin(), Jmp))
229 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
230 << LastExit->getName() << "\n");
232 // Hoist the instructions from Latch into LastExit.
233 LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
235 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
236 BasicBlock *Header = Jmp->getSuccessor(0);
237 assert(Header == L->getHeader() && "expected a backward branch");
239 // Remove Latch from the CFG so that LastExit becomes the new Latch.
240 BI->setSuccessor(FallThruPath, Header);
241 Latch->replaceSuccessorsPhiUsesWith(LastExit);
242 Jmp->eraseFromParent();
244 // Nuke the Latch block.
245 assert(Latch->empty() && "unable to evacuate Latch");
246 LI->removeBlock(Latch);
247 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>())
248 DT->eraseNode(Latch);
249 Latch->eraseFromParent();
252 /// Rotate loop LP. Return true if the loop is rotated.
253 bool LoopRotate::rotateLoop(Loop *L) {
254 // If the loop has only one block then there is not much to rotate.
255 if (L->getBlocks().size() == 1)
258 BasicBlock *OrigHeader = L->getHeader();
260 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
261 if (BI == 0 || BI->isUnconditional())
264 // If the loop header is not one of the loop exiting blocks then
265 // either this loop is already rotated or it is not
266 // suitable for loop rotation transformations.
267 if (!L->isLoopExiting(OrigHeader))
270 // Updating PHInodes in loops with multiple exits adds complexity.
271 // Keep it simple, and restrict loop rotation to loops with one exit only.
272 // In future, lift this restriction and support for multiple exits if
274 SmallVector<BasicBlock*, 8> ExitBlocks;
275 L->getExitBlocks(ExitBlocks);
276 if (ExitBlocks.size() > 1)
279 // Check size of original header and reject loop if it is very big.
282 Metrics.analyzeBasicBlock(OrigHeader);
283 if (Metrics.NumInsts > MAX_HEADER_SIZE)
287 // Now, this loop is suitable for rotation.
288 BasicBlock *OrigPreheader = L->getLoopPreheader();
289 BasicBlock *OrigLatch = L->getLoopLatch();
291 // If the loop could not be converted to canonical form, it must have an
292 // indirectbr in it, just give up.
293 if (OrigPreheader == 0 || OrigLatch == 0)
296 // Anything ScalarEvolution may know about this loop or the PHI nodes
297 // in its header will soon be invalidated.
298 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
301 // Find new Loop header. NewHeader is a Header's one and only successor
302 // that is inside loop. Header's other successor is outside the
303 // loop. Otherwise loop is not suitable for rotation.
304 BasicBlock *Exit = BI->getSuccessor(0);
305 BasicBlock *NewHeader = BI->getSuccessor(1);
306 if (L->contains(Exit))
307 std::swap(Exit, NewHeader);
308 assert(NewHeader && "Unable to determine new loop header");
309 assert(L->contains(NewHeader) && !L->contains(Exit) &&
310 "Unable to determine loop header and exit blocks");
312 // This code assumes that the new header has exactly one predecessor.
313 // Remove any single-entry PHI nodes in it.
314 assert(NewHeader->getSinglePredecessor() &&
315 "New header doesn't have one pred!");
316 FoldSingleEntryPHINodes(NewHeader);
318 // Begin by walking OrigHeader and populating ValueMap with an entry for
320 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
321 ValueToValueMapTy ValueMap;
323 // For PHI nodes, the value available in OldPreHeader is just the
324 // incoming value from OldPreHeader.
325 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
326 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
328 // For the rest of the instructions, either hoist to the OrigPreheader if
329 // possible or create a clone in the OldPreHeader if not.
330 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
332 Instruction *Inst = I++;
334 // If the instruction's operands are invariant and it doesn't read or write
335 // memory, then it is safe to hoist. Doing this doesn't change the order of
336 // execution in the preheader, but does prevent the instruction from
337 // executing in each iteration of the loop. This means it is safe to hoist
338 // something that might trap, but isn't safe to hoist something that reads
339 // memory (without proving that the loop doesn't write).
340 if (L->hasLoopInvariantOperands(Inst) &&
341 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
342 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
343 !isa<AllocaInst>(Inst)) {
344 Inst->moveBefore(LoopEntryBranch);
348 // Otherwise, create a duplicate of the instruction.
349 Instruction *C = Inst->clone();
351 // Eagerly remap the operands of the instruction.
352 RemapInstruction(C, ValueMap,
353 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
355 // With the operands remapped, see if the instruction constant folds or is
356 // otherwise simplifyable. This commonly occurs because the entry from PHI
357 // nodes allows icmps and other instructions to fold.
358 Value *V = SimplifyInstruction(C);
359 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
360 // If so, then delete the temporary instruction and stick the folded value
365 // Otherwise, stick the new instruction into the new block!
366 C->setName(Inst->getName());
367 C->insertBefore(LoopEntryBranch);
372 // Along with all the other instructions, we just cloned OrigHeader's
373 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
374 // successors by duplicating their incoming values for OrigHeader.
375 TerminatorInst *TI = OrigHeader->getTerminator();
376 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
377 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
378 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
379 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
381 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
382 // OrigPreHeader's old terminator (the original branch into the loop), and
383 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
384 LoopEntryBranch->eraseFromParent();
386 // If there were any uses of instructions in the duplicated block outside the
387 // loop, update them, inserting PHI nodes as required
388 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
390 // NewHeader is now the header of the loop.
391 L->moveToHeader(NewHeader);
392 assert(L->getHeader() == NewHeader && "Latch block is our new header");
395 // At this point, we've finished our major CFG changes. As part of cloning
396 // the loop into the preheader we've simplified instructions and the
397 // duplicated conditional branch may now be branching on a constant. If it is
398 // branching on a constant and if that constant means that we enter the loop,
399 // then we fold away the cond branch to an uncond branch. This simplifies the
400 // loop in cases important for nested loops, and it also means we don't have
401 // to split as many edges.
402 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
403 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
404 if (!isa<ConstantInt>(PHBI->getCondition()) ||
405 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
407 // The conditional branch can't be folded, handle the general case.
408 // Update DominatorTree to reflect the CFG change we just made. Then split
409 // edges as necessary to preserve LoopSimplify form.
410 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
411 // Since OrigPreheader now has the conditional branch to Exit block, it is
412 // the dominator of Exit.
413 DT->changeImmediateDominator(Exit, OrigPreheader);
414 DT->changeImmediateDominator(NewHeader, OrigPreheader);
416 // Update OrigHeader to be dominated by the new header block.
417 DT->changeImmediateDominator(OrigHeader, OrigLatch);
420 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
421 // thus is not a preheader anymore.
422 // Split the edge to form a real preheader.
423 BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this);
424 NewPH->setName(NewHeader->getName() + ".lr.ph");
426 // Preserve canonical loop form, which means that 'Exit' should have only
428 BasicBlock *ExitSplit = SplitCriticalEdge(L->getLoopLatch(), Exit, this);
429 ExitSplit->moveBefore(Exit);
431 // We can fold the conditional branch in the preheader, this makes things
432 // simpler. The first step is to remove the extra edge to the Exit block.
433 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
434 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
435 NewBI->setDebugLoc(PHBI->getDebugLoc());
436 PHBI->eraseFromParent();
438 // With our CFG finalized, update DomTree if it is available.
439 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
440 // Update OrigHeader to be dominated by the new header block.
441 DT->changeImmediateDominator(NewHeader, OrigPreheader);
442 DT->changeImmediateDominator(OrigHeader, OrigLatch);
446 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
447 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
449 // Now that the CFG and DomTree are in a consistent state again, try to merge
450 // the OrigHeader block into OrigLatch. This will succeed if they are
451 // connected by an unconditional branch. This is just a cleanup so the
452 // emitted code isn't too gross in this common case.
453 MergeBlockIntoPredecessor(OrigHeader, this);