LoopUnswitch.cpp revision 4c41d49a9282047765df4cc101551d3fdd6f5d9f
1//===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by the LLVM research group and is distributed under 6// the University of Illinois Open Source License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This pass transforms loops that contain branches on loop-invariant conditions 11// to have multiple loops. For example, it turns the left into the right code: 12// 13// for (...) if (lic) 14// A for (...) 15// if (lic) A; B; C 16// B else 17// C for (...) 18// A; C 19// 20// This can increase the size of the code exponentially (doubling it every time 21// a loop is unswitched) so we only unswitch if the resultant code will be 22// smaller than a threshold. 23// 24// This pass expects LICM to be run before it to hoist invariant conditions out 25// of the loop, to make the unswitching opportunity obvious. 26// 27//===----------------------------------------------------------------------===// 28 29#define DEBUG_TYPE "loop-unswitch" 30#include "llvm/Transforms/Scalar.h" 31#include "llvm/Constants.h" 32#include "llvm/Function.h" 33#include "llvm/Instructions.h" 34#include "llvm/Analysis/LoopInfo.h" 35#include "llvm/Transforms/Utils/Cloning.h" 36#include "llvm/Transforms/Utils/Local.h" 37#include "llvm/ADT/Statistic.h" 38#include "llvm/Support/Debug.h" 39#include "llvm/Support/CommandLine.h" 40#include <algorithm> 41#include <iostream> 42#include <set> 43using namespace llvm; 44 45namespace { 46 Statistic<> NumUnswitched("loop-unswitch", "Number of loops unswitched"); 47 cl::opt<unsigned> 48 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"), 49 cl::init(10), cl::Hidden); 50 51 class LoopUnswitch : public FunctionPass { 52 LoopInfo *LI; // Loop information 53 public: 54 virtual bool runOnFunction(Function &F); 55 bool visitLoop(Loop *L); 56 57 /// This transformation requires natural loop information & requires that 58 /// loop preheaders be inserted into the CFG... 59 /// 60 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 61 AU.addRequiredID(LoopSimplifyID); 62 AU.addPreservedID(LoopSimplifyID); 63 AU.addRequired<LoopInfo>(); 64 AU.addPreserved<LoopInfo>(); 65 } 66 67 private: 68 unsigned getLoopUnswitchCost(Loop *L, Value *LIC); 69 void VersionLoop(Value *LIC, Loop *L, Loop *&Out1, Loop *&Out2); 70 BasicBlock *SplitBlock(BasicBlock *BB, bool SplitAtTop); 71 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC, bool Val); 72 void UnswitchTrivialCondition(Loop *L, Value *Cond, ConstantBool *LoopCond); 73 }; 74 RegisterOpt<LoopUnswitch> X("loop-unswitch", "Unswitch loops"); 75} 76 77FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); } 78 79bool LoopUnswitch::runOnFunction(Function &F) { 80 bool Changed = false; 81 LI = &getAnalysis<LoopInfo>(); 82 83 // Transform all the top-level loops. Copy the loop list so that the child 84 // can update the loop tree if it needs to delete the loop. 85 std::vector<Loop*> SubLoops(LI->begin(), LI->end()); 86 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i) 87 Changed |= visitLoop(SubLoops[i]); 88 89 return Changed; 90} 91 92 93/// LoopValuesUsedOutsideLoop - Return true if there are any values defined in 94/// the loop that are used by instructions outside of it. 95static bool LoopValuesUsedOutsideLoop(Loop *L) { 96 // We will be doing lots of "loop contains block" queries. Loop::contains is 97 // linear time, use a set to speed this up. 98 std::set<BasicBlock*> LoopBlocks; 99 100 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end(); 101 BB != E; ++BB) 102 LoopBlocks.insert(*BB); 103 104 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end(); 105 BB != E; ++BB) { 106 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I) 107 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; 108 ++UI) { 109 BasicBlock *UserBB = cast<Instruction>(*UI)->getParent(); 110 if (!LoopBlocks.count(UserBB)) 111 return true; 112 } 113 } 114 return false; 115} 116 117/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is 118/// trivial: that is, that the condition controls whether or not the loop does 119/// anything at all. If this is a trivial condition, unswitching produces no 120/// code duplications (equivalently, it produces a simpler loop and a new empty 121/// loop, which gets deleted). 122/// 123/// If this is a trivial condition, return ConstantBool::True if the loop body 124/// runs when the condition is true, False if the loop body executes when the 125/// condition is false. Otherwise, return null to indicate a complex condition. 126static ConstantBool *IsTrivialUnswitchCondition(Loop *L, Value *Cond) { 127 BasicBlock *Header = L->getHeader(); 128 BranchInst *HeaderTerm = dyn_cast<BranchInst>(Header->getTerminator()); 129 ConstantBool *RetVal = 0; 130 131 // If the header block doesn't end with a conditional branch on Cond, we can't 132 // handle it. 133 if (!HeaderTerm || !HeaderTerm->isConditional() || 134 HeaderTerm->getCondition() != Cond) 135 return 0; 136 137 // Check to see if the conditional branch goes to the latch block. If not, 138 // it's not trivial. This also determines the value of Cond that will execute 139 // the loop. 140 BasicBlock *Latch = L->getLoopLatch(); 141 if (HeaderTerm->getSuccessor(1) == Latch) 142 RetVal = ConstantBool::True; 143 else if (HeaderTerm->getSuccessor(0) == Latch) 144 RetVal = ConstantBool::False; 145 else 146 return 0; // Doesn't branch to latch block. 147 148 // The latch block must end with a conditional branch where one edge goes to 149 // the header (this much we know) and one edge goes OUT of the loop. 150 BranchInst *LatchBranch = dyn_cast<BranchInst>(Latch->getTerminator()); 151 if (!LatchBranch || !LatchBranch->isConditional()) return 0; 152 153 if (LatchBranch->getSuccessor(0) == Header) { 154 if (L->contains(LatchBranch->getSuccessor(1))) return 0; 155 } else { 156 assert(LatchBranch->getSuccessor(1) == Header); 157 if (L->contains(LatchBranch->getSuccessor(0))) return 0; 158 } 159 160 // We already know that nothing uses any scalar values defined inside of this 161 // loop. As such, we just have to check to see if this loop will execute any 162 // side-effecting instructions (e.g. stores, calls, volatile loads) in the 163 // part of the loop that the code *would* execute. 164 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I) 165 if (I->mayWriteToMemory()) 166 return 0; 167 for (BasicBlock::iterator I = Latch->begin(), E = Latch->end(); I != E; ++I) 168 if (I->mayWriteToMemory()) 169 return 0; 170 return RetVal; 171} 172 173/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if 174/// we choose to unswitch the specified loop on the specified value. 175/// 176unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) { 177 // If the condition is trivial, always unswitch. There is no code growth for 178 // this case. 179 if (IsTrivialUnswitchCondition(L, LIC)) 180 return 0; 181 182 unsigned Cost = 0; 183 // FIXME: this is brain dead. It should take into consideration code 184 // shrinkage. 185 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 186 I != E; ++I) { 187 BasicBlock *BB = *I; 188 // Do not include empty blocks in the cost calculation. This happen due to 189 // loop canonicalization and will be removed. 190 if (BB->begin() == BasicBlock::iterator(BB->getTerminator())) 191 continue; 192 193 // Count basic blocks. 194 ++Cost; 195 } 196 197 return Cost; 198} 199 200bool LoopUnswitch::visitLoop(Loop *L) { 201 bool Changed = false; 202 203 // Recurse through all subloops before we process this loop. Copy the loop 204 // list so that the child can update the loop tree if it needs to delete the 205 // loop. 206 std::vector<Loop*> SubLoops(L->begin(), L->end()); 207 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i) 208 Changed |= visitLoop(SubLoops[i]); 209 210 // Loop over all of the basic blocks in the loop. If we find an interior 211 // block that is branching on a loop-invariant condition, we can unswitch this 212 // loop. 213 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 214 I != E; ++I) { 215 TerminatorInst *TI = (*I)->getTerminator(); 216 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 217 if (!isa<Constant>(SI) && L->isLoopInvariant(SI->getCondition())) 218 DEBUG(std::cerr << "TODO: Implement unswitching 'switch' loop %" 219 << L->getHeader()->getName() << ", cost = " 220 << L->getBlocks().size() << "\n" << **I); 221 continue; 222 } 223 224 BranchInst *BI = dyn_cast<BranchInst>(TI); 225 if (!BI) continue; 226 227 // If this isn't branching on an invariant condition, we can't unswitch it. 228 if (!BI->isConditional() || isa<Constant>(BI->getCondition()) || 229 !L->isLoopInvariant(BI->getCondition())) 230 continue; 231 232 // Check to see if it would be profitable to unswitch this loop. 233 if (getLoopUnswitchCost(L, BI->getCondition()) > Threshold) { 234 // FIXME: this should estimate growth by the amount of code shared by the 235 // resultant unswitched loops. This should have no code growth: 236 // for () { if (iv) {...} } 237 // as one copy of the loop will be empty. 238 // 239 DEBUG(std::cerr << "NOT unswitching loop %" 240 << L->getHeader()->getName() << ", cost too high: " 241 << L->getBlocks().size() << "\n"); 242 continue; 243 } 244 245 // If this loop has live-out values, we can't unswitch it. We need something 246 // like loop-closed SSA form in order to know how to insert PHI nodes for 247 // these values. 248 if (LoopValuesUsedOutsideLoop(L)) { 249 DEBUG(std::cerr << "NOT unswitching loop %" 250 << L->getHeader()->getName() 251 << ", a loop value is used outside loop!\n"); 252 continue; 253 } 254 255 //std::cerr << "BEFORE:\n"; LI->dump(); 256 Loop *NewLoop1 = 0, *NewLoop2 = 0; 257 258 // If this is a trivial condition to unswitch (which results in no code 259 // duplication), do it now. 260 if (ConstantBool *V = IsTrivialUnswitchCondition(L, BI->getCondition())) { 261 UnswitchTrivialCondition(L, BI->getCondition(), V); 262 NewLoop1 = L; 263 } else { 264 VersionLoop(BI->getCondition(), L, NewLoop1, NewLoop2); 265 } 266 267 //std::cerr << "AFTER:\n"; LI->dump(); 268 269 // Try to unswitch each of our new loops now! 270 if (NewLoop1) visitLoop(NewLoop1); 271 if (NewLoop2) visitLoop(NewLoop2); 272 return true; 273 } 274 275 return Changed; 276} 277 278/// SplitBlock - Split the specified basic block into two pieces. If SplitAtTop 279/// is false, this splits the block so the second half only has an unconditional 280/// branch. If SplitAtTop is true, it makes it so the first half of the block 281/// only has an unconditional branch in it. 282/// 283/// This method updates the LoopInfo for this function to correctly reflect the 284/// CFG changes made. 285/// 286/// This routine returns the new basic block that was inserted, which is always 287/// the later part of the block. 288BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *BB, bool SplitAtTop) { 289 BasicBlock::iterator SplitPoint; 290 if (!SplitAtTop) 291 SplitPoint = BB->getTerminator(); 292 else { 293 SplitPoint = BB->begin(); 294 while (isa<PHINode>(SplitPoint)) ++SplitPoint; 295 } 296 297 BasicBlock *New = BB->splitBasicBlock(SplitPoint, BB->getName()+".tail"); 298 // New now lives in whichever loop that BB used to. 299 if (Loop *L = LI->getLoopFor(BB)) 300 L->addBasicBlockToLoop(New, *LI); 301 return New; 302} 303 304 305// RemapInstruction - Convert the instruction operands from referencing the 306// current values into those specified by ValueMap. 307// 308static inline void RemapInstruction(Instruction *I, 309 std::map<const Value *, Value*> &ValueMap) { 310 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) { 311 Value *Op = I->getOperand(op); 312 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op); 313 if (It != ValueMap.end()) Op = It->second; 314 I->setOperand(op, Op); 315 } 316} 317 318/// CloneLoop - Recursively clone the specified loop and all of its children, 319/// mapping the blocks with the specified map. 320static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM, 321 LoopInfo *LI) { 322 Loop *New = new Loop(); 323 324 if (PL) 325 PL->addChildLoop(New); 326 else 327 LI->addTopLevelLoop(New); 328 329 // Add all of the blocks in L to the new loop. 330 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 331 I != E; ++I) 332 if (LI->getLoopFor(*I) == L) 333 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI); 334 335 // Add all of the subloops to the new loop. 336 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 337 CloneLoop(*I, New, VM, LI); 338 339 return New; 340} 341 342/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable 343/// condition in it (a cond branch from its header block to its latch block, 344/// where the path through the loop that doesn't execute its body has no 345/// side-effects), unswitch it. This doesn't involve any code duplication, just 346/// moving the conditional branch outside of the loop and updating loop info. 347void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, 348 ConstantBool *LoopCond) { 349 // First step, split the preahder, so that we know that there is a safe place 350 // to insert the conditional branch. We will change 'OrigPH' to have a 351 // conditional branch on Cond. 352 BasicBlock *OrigPH = L->getLoopPreheader(); 353 BasicBlock *NewPH = SplitBlock(OrigPH, false); 354 355 // Now that we have a place to insert the conditional branch, create a place 356 // to branch to: this is the non-header successor of the latch block. 357 BranchInst *LatchBranch =cast<BranchInst>(L->getLoopLatch()->getTerminator()); 358 BasicBlock *ExitBlock = 359 LatchBranch->getSuccessor(LatchBranch->getSuccessor(0) == L->getHeader()); 360 assert(!L->contains(ExitBlock) && "Exit block is in the loop?"); 361 362 // Split this block now, so that the loop maintains its exit block. 363 BasicBlock *NewExit = SplitBlock(ExitBlock, true); 364 365 // Okay, now we have a position to branch from and a position to branch to, 366 // insert the new conditional branch. 367 bool EnterOnTrue = LoopCond->getValue(); 368 new BranchInst(EnterOnTrue ? NewPH : NewExit, EnterOnTrue ? NewExit : NewPH, 369 Cond, OrigPH->getTerminator()); 370 OrigPH->getTerminator()->eraseFromParent(); 371 372 // Now that we know that the loop is never entered when this condition is a 373 // particular value, rewrite the loop with this info. We know that this will 374 // at least eliminate the old branch. 375 RewriteLoopBodyWithConditionConstant(L, Cond, EnterOnTrue); 376} 377 378 379/// VersionLoop - We determined that the loop is profitable to unswitch and 380/// contains a branch on a loop invariant condition. Split it into loop 381/// versions and test the condition outside of either loop. Return the loops 382/// created as Out1/Out2. 383void LoopUnswitch::VersionLoop(Value *LIC, Loop *L, Loop *&Out1, Loop *&Out2) { 384 Function *F = L->getHeader()->getParent(); 385 386 DEBUG(std::cerr << "loop-unswitch: Unswitching loop %" 387 << L->getHeader()->getName() << " [" << L->getBlocks().size() 388 << " blocks] in Function " << F->getName() 389 << " on cond:" << *LIC << "\n"); 390 391 std::vector<BasicBlock*> LoopBlocks; 392 393 // First step, split the preheader and exit blocks, and add these blocks to 394 // the LoopBlocks list. 395 BasicBlock *OrigPreheader = L->getLoopPreheader(); 396 LoopBlocks.push_back(SplitBlock(OrigPreheader, false)); 397 398 // We want the loop to come after the preheader, but before the exit blocks. 399 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end()); 400 401 std::vector<BasicBlock*> ExitBlocks; 402 L->getExitBlocks(ExitBlocks); 403 std::sort(ExitBlocks.begin(), ExitBlocks.end()); 404 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()), 405 ExitBlocks.end()); 406 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) { 407 SplitBlock(ExitBlocks[i], true); 408 LoopBlocks.push_back(ExitBlocks[i]); 409 } 410 411 // Next step, clone all of the basic blocks that make up the loop (including 412 // the loop preheader and exit blocks), keeping track of the mapping between 413 // the instructions and blocks. 414 std::vector<BasicBlock*> NewBlocks; 415 NewBlocks.reserve(LoopBlocks.size()); 416 std::map<const Value*, Value*> ValueMap; 417 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) { 418 NewBlocks.push_back(CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F)); 419 ValueMap[LoopBlocks[i]] = NewBlocks.back(); // Keep the BB mapping. 420 } 421 422 // Splice the newly inserted blocks into the function right before the 423 // original preheader. 424 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(), 425 NewBlocks[0], F->end()); 426 427 // Now we create the new Loop object for the versioned loop. 428 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI); 429 if (Loop *Parent = L->getParentLoop()) { 430 // Make sure to add the cloned preheader and exit blocks to the parent loop 431 // as well. 432 Parent->addBasicBlockToLoop(NewBlocks[0], *LI); 433 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) 434 Parent->addBasicBlockToLoop(cast<BasicBlock>(ValueMap[ExitBlocks[i]]), 435 *LI); 436 } 437 438 // Rewrite the code to refer to itself. 439 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) 440 for (BasicBlock::iterator I = NewBlocks[i]->begin(), 441 E = NewBlocks[i]->end(); I != E; ++I) 442 RemapInstruction(I, ValueMap); 443 444 // Rewrite the original preheader to select between versions of the loop. 445 assert(isa<BranchInst>(OrigPreheader->getTerminator()) && 446 cast<BranchInst>(OrigPreheader->getTerminator())->isUnconditional() && 447 OrigPreheader->getTerminator()->getSuccessor(0) == LoopBlocks[0] && 448 "Preheader splitting did not work correctly!"); 449 // Remove the unconditional branch to LoopBlocks[0]. 450 OrigPreheader->getInstList().pop_back(); 451 452 // Insert a conditional branch on LIC to the two preheaders. The original 453 // code is the true version and the new code is the false version. 454 new BranchInst(LoopBlocks[0], NewBlocks[0], LIC, OrigPreheader); 455 456 // Now we rewrite the original code to know that the condition is true and the 457 // new code to know that the condition is false. 458 RewriteLoopBodyWithConditionConstant(L, LIC, true); 459 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, false); 460 ++NumUnswitched; 461 Out1 = L; 462 Out2 = NewLoop; 463} 464 465// RewriteLoopBodyWithConditionConstant - We know that the boolean value LIC has 466// the value specified by Val in the specified loop. Rewrite any uses of LIC or 467// of properties correlated to it. 468void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC, 469 bool Val) { 470 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?"); 471 // FIXME: Support correlated properties, like: 472 // for (...) 473 // if (li1 < li2) 474 // ... 475 // if (li1 > li2) 476 // ... 477 ConstantBool *BoolVal = ConstantBool::get(Val); 478 479 std::vector<User*> Users(LIC->use_begin(), LIC->use_end()); 480 for (unsigned i = 0, e = Users.size(); i != e; ++i) 481 if (Instruction *U = cast<Instruction>(Users[i])) 482 if (L->contains(U->getParent())) 483 U->replaceUsesOfWith(LIC, BoolVal); 484} 485