LLVM API Documentation
00001 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements Loop Rotation Pass. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #define DEBUG_TYPE "loop-rotate" 00015 #include "llvm/Transforms/Scalar.h" 00016 #include "llvm/ADT/Statistic.h" 00017 #include "llvm/Analysis/CodeMetrics.h" 00018 #include "llvm/Analysis/InstructionSimplify.h" 00019 #include "llvm/Analysis/LoopPass.h" 00020 #include "llvm/Analysis/ScalarEvolution.h" 00021 #include "llvm/Analysis/TargetTransformInfo.h" 00022 #include "llvm/Analysis/ValueTracking.h" 00023 #include "llvm/IR/Function.h" 00024 #include "llvm/IR/IntrinsicInst.h" 00025 #include "llvm/Support/CFG.h" 00026 #include "llvm/Support/Debug.h" 00027 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 00028 #include "llvm/Transforms/Utils/Local.h" 00029 #include "llvm/Transforms/Utils/SSAUpdater.h" 00030 #include "llvm/Transforms/Utils/ValueMapper.h" 00031 using namespace llvm; 00032 00033 #define MAX_HEADER_SIZE 16 00034 00035 STATISTIC(NumRotated, "Number of loops rotated"); 00036 namespace { 00037 00038 class LoopRotate : public LoopPass { 00039 public: 00040 static char ID; // Pass ID, replacement for typeid 00041 LoopRotate() : LoopPass(ID) { 00042 initializeLoopRotatePass(*PassRegistry::getPassRegistry()); 00043 } 00044 00045 // LCSSA form makes instruction renaming easier. 00046 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 00047 AU.addPreserved<DominatorTree>(); 00048 AU.addRequired<LoopInfo>(); 00049 AU.addPreserved<LoopInfo>(); 00050 AU.addRequiredID(LoopSimplifyID); 00051 AU.addPreservedID(LoopSimplifyID); 00052 AU.addRequiredID(LCSSAID); 00053 AU.addPreservedID(LCSSAID); 00054 AU.addPreserved<ScalarEvolution>(); 00055 AU.addRequired<TargetTransformInfo>(); 00056 } 00057 00058 bool runOnLoop(Loop *L, LPPassManager &LPM); 00059 bool simplifyLoopLatch(Loop *L); 00060 bool rotateLoop(Loop *L, bool SimplifiedLatch); 00061 00062 private: 00063 LoopInfo *LI; 00064 const TargetTransformInfo *TTI; 00065 }; 00066 } 00067 00068 char LoopRotate::ID = 0; 00069 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false) 00070 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo) 00071 INITIALIZE_PASS_DEPENDENCY(LoopInfo) 00072 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 00073 INITIALIZE_PASS_DEPENDENCY(LCSSA) 00074 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false) 00075 00076 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); } 00077 00078 /// Rotate Loop L as many times as possible. Return true if 00079 /// the loop is rotated at least once. 00080 bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) { 00081 LI = &getAnalysis<LoopInfo>(); 00082 TTI = &getAnalysis<TargetTransformInfo>(); 00083 00084 // Simplify the loop latch before attempting to rotate the header 00085 // upward. Rotation may not be needed if the loop tail can be folded into the 00086 // loop exit. 00087 bool SimplifiedLatch = simplifyLoopLatch(L); 00088 00089 // One loop can be rotated multiple times. 00090 bool MadeChange = false; 00091 while (rotateLoop(L, SimplifiedLatch)) { 00092 MadeChange = true; 00093 SimplifiedLatch = false; 00094 } 00095 return MadeChange; 00096 } 00097 00098 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the 00099 /// old header into the preheader. If there were uses of the values produced by 00100 /// these instruction that were outside of the loop, we have to insert PHI nodes 00101 /// to merge the two values. Do this now. 00102 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader, 00103 BasicBlock *OrigPreheader, 00104 ValueToValueMapTy &ValueMap) { 00105 // Remove PHI node entries that are no longer live. 00106 BasicBlock::iterator I, E = OrigHeader->end(); 00107 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I) 00108 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader)); 00109 00110 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes 00111 // as necessary. 00112 SSAUpdater SSA; 00113 for (I = OrigHeader->begin(); I != E; ++I) { 00114 Value *OrigHeaderVal = I; 00115 00116 // If there are no uses of the value (e.g. because it returns void), there 00117 // is nothing to rewrite. 00118 if (OrigHeaderVal->use_empty()) 00119 continue; 00120 00121 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal]; 00122 00123 // The value now exits in two versions: the initial value in the preheader 00124 // and the loop "next" value in the original header. 00125 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName()); 00126 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal); 00127 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal); 00128 00129 // Visit each use of the OrigHeader instruction. 00130 for (Value::use_iterator UI = OrigHeaderVal->use_begin(), 00131 UE = OrigHeaderVal->use_end(); UI != UE; ) { 00132 // Grab the use before incrementing the iterator. 00133 Use &U = UI.getUse(); 00134 00135 // Increment the iterator before removing the use from the list. 00136 ++UI; 00137 00138 // SSAUpdater can't handle a non-PHI use in the same block as an 00139 // earlier def. We can easily handle those cases manually. 00140 Instruction *UserInst = cast<Instruction>(U.getUser()); 00141 if (!isa<PHINode>(UserInst)) { 00142 BasicBlock *UserBB = UserInst->getParent(); 00143 00144 // The original users in the OrigHeader are already using the 00145 // original definitions. 00146 if (UserBB == OrigHeader) 00147 continue; 00148 00149 // Users in the OrigPreHeader need to use the value to which the 00150 // original definitions are mapped. 00151 if (UserBB == OrigPreheader) { 00152 U = OrigPreHeaderVal; 00153 continue; 00154 } 00155 } 00156 00157 // Anything else can be handled by SSAUpdater. 00158 SSA.RewriteUse(U); 00159 } 00160 } 00161 } 00162 00163 /// Determine whether the instructions in this range my be safely and cheaply 00164 /// speculated. This is not an important enough situation to develop complex 00165 /// heuristics. We handle a single arithmetic instruction along with any type 00166 /// conversions. 00167 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin, 00168 BasicBlock::iterator End) { 00169 bool seenIncrement = false; 00170 for (BasicBlock::iterator I = Begin; I != End; ++I) { 00171 00172 if (!isSafeToSpeculativelyExecute(I)) 00173 return false; 00174 00175 if (isa<DbgInfoIntrinsic>(I)) 00176 continue; 00177 00178 switch (I->getOpcode()) { 00179 default: 00180 return false; 00181 case Instruction::GetElementPtr: 00182 // GEPs are cheap if all indices are constant. 00183 if (!cast<GEPOperator>(I)->hasAllConstantIndices()) 00184 return false; 00185 // fall-thru to increment case 00186 case Instruction::Add: 00187 case Instruction::Sub: 00188 case Instruction::And: 00189 case Instruction::Or: 00190 case Instruction::Xor: 00191 case Instruction::Shl: 00192 case Instruction::LShr: 00193 case Instruction::AShr: 00194 if (seenIncrement) 00195 return false; 00196 seenIncrement = true; 00197 break; 00198 case Instruction::Trunc: 00199 case Instruction::ZExt: 00200 case Instruction::SExt: 00201 // ignore type conversions 00202 break; 00203 } 00204 } 00205 return true; 00206 } 00207 00208 /// Fold the loop tail into the loop exit by speculating the loop tail 00209 /// instructions. Typically, this is a single post-increment. In the case of a 00210 /// simple 2-block loop, hoisting the increment can be much better than 00211 /// duplicating the entire loop header. In the cast of loops with early exits, 00212 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in 00213 /// canonical form so downstream passes can handle it. 00214 /// 00215 /// I don't believe this invalidates SCEV. 00216 bool LoopRotate::simplifyLoopLatch(Loop *L) { 00217 BasicBlock *Latch = L->getLoopLatch(); 00218 if (!Latch || Latch->hasAddressTaken()) 00219 return false; 00220 00221 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator()); 00222 if (!Jmp || !Jmp->isUnconditional()) 00223 return false; 00224 00225 BasicBlock *LastExit = Latch->getSinglePredecessor(); 00226 if (!LastExit || !L->isLoopExiting(LastExit)) 00227 return false; 00228 00229 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator()); 00230 if (!BI) 00231 return false; 00232 00233 if (!shouldSpeculateInstrs(Latch->begin(), Jmp)) 00234 return false; 00235 00236 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into " 00237 << LastExit->getName() << "\n"); 00238 00239 // Hoist the instructions from Latch into LastExit. 00240 LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp); 00241 00242 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1; 00243 BasicBlock *Header = Jmp->getSuccessor(0); 00244 assert(Header == L->getHeader() && "expected a backward branch"); 00245 00246 // Remove Latch from the CFG so that LastExit becomes the new Latch. 00247 BI->setSuccessor(FallThruPath, Header); 00248 Latch->replaceSuccessorsPhiUsesWith(LastExit); 00249 Jmp->eraseFromParent(); 00250 00251 // Nuke the Latch block. 00252 assert(Latch->empty() && "unable to evacuate Latch"); 00253 LI->removeBlock(Latch); 00254 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) 00255 DT->eraseNode(Latch); 00256 Latch->eraseFromParent(); 00257 return true; 00258 } 00259 00260 /// Rotate loop LP. Return true if the loop is rotated. 00261 /// 00262 /// \param SimplifiedLatch is true if the latch was just folded into the final 00263 /// loop exit. In this case we may want to rotate even though the new latch is 00264 /// now an exiting branch. This rotation would have happened had the latch not 00265 /// been simplified. However, if SimplifiedLatch is false, then we avoid 00266 /// rotating loops in which the latch exits to avoid excessive or endless 00267 /// rotation. LoopRotate should be repeatable and converge to a canonical 00268 /// form. This property is satisfied because simplifying the loop latch can only 00269 /// happen once across multiple invocations of the LoopRotate pass. 00270 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) { 00271 // If the loop has only one block then there is not much to rotate. 00272 if (L->getBlocks().size() == 1) 00273 return false; 00274 00275 BasicBlock *OrigHeader = L->getHeader(); 00276 BasicBlock *OrigLatch = L->getLoopLatch(); 00277 00278 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator()); 00279 if (BI == 0 || BI->isUnconditional()) 00280 return false; 00281 00282 // If the loop header is not one of the loop exiting blocks then 00283 // either this loop is already rotated or it is not 00284 // suitable for loop rotation transformations. 00285 if (!L->isLoopExiting(OrigHeader)) 00286 return false; 00287 00288 // If the loop latch already contains a branch that leaves the loop then the 00289 // loop is already rotated. 00290 if (OrigLatch == 0) 00291 return false; 00292 00293 // Rotate if either the loop latch does *not* exit the loop, or if the loop 00294 // latch was just simplified. 00295 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch) 00296 return false; 00297 00298 // Check size of original header and reject loop if it is very big or we can't 00299 // duplicate blocks inside it. 00300 { 00301 CodeMetrics Metrics; 00302 Metrics.analyzeBasicBlock(OrigHeader, *TTI); 00303 if (Metrics.notDuplicatable) { 00304 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non duplicatable" 00305 << " instructions: "; L->dump()); 00306 return false; 00307 } 00308 if (Metrics.NumInsts > MAX_HEADER_SIZE) 00309 return false; 00310 } 00311 00312 // Now, this loop is suitable for rotation. 00313 BasicBlock *OrigPreheader = L->getLoopPreheader(); 00314 00315 // If the loop could not be converted to canonical form, it must have an 00316 // indirectbr in it, just give up. 00317 if (OrigPreheader == 0) 00318 return false; 00319 00320 // Anything ScalarEvolution may know about this loop or the PHI nodes 00321 // in its header will soon be invalidated. 00322 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>()) 00323 SE->forgetLoop(L); 00324 00325 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump()); 00326 00327 // Find new Loop header. NewHeader is a Header's one and only successor 00328 // that is inside loop. Header's other successor is outside the 00329 // loop. Otherwise loop is not suitable for rotation. 00330 BasicBlock *Exit = BI->getSuccessor(0); 00331 BasicBlock *NewHeader = BI->getSuccessor(1); 00332 if (L->contains(Exit)) 00333 std::swap(Exit, NewHeader); 00334 assert(NewHeader && "Unable to determine new loop header"); 00335 assert(L->contains(NewHeader) && !L->contains(Exit) && 00336 "Unable to determine loop header and exit blocks"); 00337 00338 // This code assumes that the new header has exactly one predecessor. 00339 // Remove any single-entry PHI nodes in it. 00340 assert(NewHeader->getSinglePredecessor() && 00341 "New header doesn't have one pred!"); 00342 FoldSingleEntryPHINodes(NewHeader); 00343 00344 // Begin by walking OrigHeader and populating ValueMap with an entry for 00345 // each Instruction. 00346 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end(); 00347 ValueToValueMapTy ValueMap; 00348 00349 // For PHI nodes, the value available in OldPreHeader is just the 00350 // incoming value from OldPreHeader. 00351 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I) 00352 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader); 00353 00354 // For the rest of the instructions, either hoist to the OrigPreheader if 00355 // possible or create a clone in the OldPreHeader if not. 00356 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator(); 00357 while (I != E) { 00358 Instruction *Inst = I++; 00359 00360 // If the instruction's operands are invariant and it doesn't read or write 00361 // memory, then it is safe to hoist. Doing this doesn't change the order of 00362 // execution in the preheader, but does prevent the instruction from 00363 // executing in each iteration of the loop. This means it is safe to hoist 00364 // something that might trap, but isn't safe to hoist something that reads 00365 // memory (without proving that the loop doesn't write). 00366 if (L->hasLoopInvariantOperands(Inst) && 00367 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() && 00368 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) && 00369 !isa<AllocaInst>(Inst)) { 00370 Inst->moveBefore(LoopEntryBranch); 00371 continue; 00372 } 00373 00374 // Otherwise, create a duplicate of the instruction. 00375 Instruction *C = Inst->clone(); 00376 00377 // Eagerly remap the operands of the instruction. 00378 RemapInstruction(C, ValueMap, 00379 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries); 00380 00381 // With the operands remapped, see if the instruction constant folds or is 00382 // otherwise simplifyable. This commonly occurs because the entry from PHI 00383 // nodes allows icmps and other instructions to fold. 00384 Value *V = SimplifyInstruction(C); 00385 if (V && LI->replacementPreservesLCSSAForm(C, V)) { 00386 // If so, then delete the temporary instruction and stick the folded value 00387 // in the map. 00388 delete C; 00389 ValueMap[Inst] = V; 00390 } else { 00391 // Otherwise, stick the new instruction into the new block! 00392 C->setName(Inst->getName()); 00393 C->insertBefore(LoopEntryBranch); 00394 ValueMap[Inst] = C; 00395 } 00396 } 00397 00398 // Along with all the other instructions, we just cloned OrigHeader's 00399 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's 00400 // successors by duplicating their incoming values for OrigHeader. 00401 TerminatorInst *TI = OrigHeader->getTerminator(); 00402 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 00403 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin(); 00404 PHINode *PN = dyn_cast<PHINode>(BI); ++BI) 00405 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader); 00406 00407 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove 00408 // OrigPreHeader's old terminator (the original branch into the loop), and 00409 // remove the corresponding incoming values from the PHI nodes in OrigHeader. 00410 LoopEntryBranch->eraseFromParent(); 00411 00412 // If there were any uses of instructions in the duplicated block outside the 00413 // loop, update them, inserting PHI nodes as required 00414 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap); 00415 00416 // NewHeader is now the header of the loop. 00417 L->moveToHeader(NewHeader); 00418 assert(L->getHeader() == NewHeader && "Latch block is our new header"); 00419 00420 00421 // At this point, we've finished our major CFG changes. As part of cloning 00422 // the loop into the preheader we've simplified instructions and the 00423 // duplicated conditional branch may now be branching on a constant. If it is 00424 // branching on a constant and if that constant means that we enter the loop, 00425 // then we fold away the cond branch to an uncond branch. This simplifies the 00426 // loop in cases important for nested loops, and it also means we don't have 00427 // to split as many edges. 00428 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator()); 00429 assert(PHBI->isConditional() && "Should be clone of BI condbr!"); 00430 if (!isa<ConstantInt>(PHBI->getCondition()) || 00431 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) 00432 != NewHeader) { 00433 // The conditional branch can't be folded, handle the general case. 00434 // Update DominatorTree to reflect the CFG change we just made. Then split 00435 // edges as necessary to preserve LoopSimplify form. 00436 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) { 00437 // Everything that was dominated by the old loop header is now dominated 00438 // by the original loop preheader. Conceptually the header was merged 00439 // into the preheader, even though we reuse the actual block as a new 00440 // loop latch. 00441 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader); 00442 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(), 00443 OrigHeaderNode->end()); 00444 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader); 00445 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) 00446 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode); 00447 00448 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode); 00449 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode); 00450 00451 // Update OrigHeader to be dominated by the new header block. 00452 DT->changeImmediateDominator(OrigHeader, OrigLatch); 00453 } 00454 00455 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and 00456 // thus is not a preheader anymore. 00457 // Split the edge to form a real preheader. 00458 BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this); 00459 NewPH->setName(NewHeader->getName() + ".lr.ph"); 00460 00461 // Preserve canonical loop form, which means that 'Exit' should have only 00462 // one predecessor. 00463 BasicBlock *ExitSplit = SplitCriticalEdge(L->getLoopLatch(), Exit, this); 00464 ExitSplit->moveBefore(Exit); 00465 } else { 00466 // We can fold the conditional branch in the preheader, this makes things 00467 // simpler. The first step is to remove the extra edge to the Exit block. 00468 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/); 00469 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI); 00470 NewBI->setDebugLoc(PHBI->getDebugLoc()); 00471 PHBI->eraseFromParent(); 00472 00473 // With our CFG finalized, update DomTree if it is available. 00474 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) { 00475 // Update OrigHeader to be dominated by the new header block. 00476 DT->changeImmediateDominator(NewHeader, OrigPreheader); 00477 DT->changeImmediateDominator(OrigHeader, OrigLatch); 00478 00479 // Brute force incremental dominator tree update. Call 00480 // findNearestCommonDominator on all CFG predecessors of each child of the 00481 // original header. 00482 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader); 00483 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(), 00484 OrigHeaderNode->end()); 00485 bool Changed; 00486 do { 00487 Changed = false; 00488 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) { 00489 DomTreeNode *Node = HeaderChildren[I]; 00490 BasicBlock *BB = Node->getBlock(); 00491 00492 pred_iterator PI = pred_begin(BB); 00493 BasicBlock *NearestDom = *PI; 00494 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI) 00495 NearestDom = DT->findNearestCommonDominator(NearestDom, *PI); 00496 00497 // Remember if this changes the DomTree. 00498 if (Node->getIDom()->getBlock() != NearestDom) { 00499 DT->changeImmediateDominator(BB, NearestDom); 00500 Changed = true; 00501 } 00502 } 00503 00504 // If the dominator changed, this may have an effect on other 00505 // predecessors, continue until we reach a fixpoint. 00506 } while (Changed); 00507 } 00508 } 00509 00510 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation"); 00511 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation"); 00512 00513 // Now that the CFG and DomTree are in a consistent state again, try to merge 00514 // the OrigHeader block into OrigLatch. This will succeed if they are 00515 // connected by an unconditional branch. This is just a cleanup so the 00516 // emitted code isn't too gross in this common case. 00517 MergeBlockIntoPredecessor(OrigHeader, this); 00518 00519 DEBUG(dbgs() << "LoopRotation: into "; L->dump()); 00520 00521 ++NumRotated; 00522 return true; 00523 }