Chris Lattner | 18f1609 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 1 | //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===// |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 2 | // |
Chris Lattner | 18f1609 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 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. |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 7 | // |
Chris Lattner | 18f1609 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 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/Dominators.h" |
| 35 | #include "llvm/Analysis/LoopInfo.h" |
| 36 | #include "llvm/Transforms/Utils/Cloning.h" |
| 37 | #include "llvm/Transforms/Utils/Local.h" |
Reid Spencer | 551ccae | 2004-09-01 22:55:40 +0000 | [diff] [blame] | 38 | #include "llvm/Support/Debug.h" |
| 39 | #include "llvm/ADT/Statistic.h" |
Alkis Evlogimenos | 20aa474 | 2004-09-03 18:19:51 +0000 | [diff] [blame] | 40 | #include <algorithm> |
Chris Lattner | dac58ad | 2006-01-22 23:32:06 +0000 | [diff] [blame^] | 41 | #include <iostream> |
Chris Lattner | 18f1609 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 42 | using namespace llvm; |
| 43 | |
| 44 | namespace { |
| 45 | Statistic<> NumUnswitched("loop-unswitch", "Number of loops unswitched"); |
| 46 | |
| 47 | class LoopUnswitch : public FunctionPass { |
| 48 | LoopInfo *LI; // Loop information |
| 49 | DominatorSet *DS; |
| 50 | public: |
| 51 | virtual bool runOnFunction(Function &F); |
| 52 | bool visitLoop(Loop *L); |
| 53 | |
| 54 | /// This transformation requires natural loop information & requires that |
| 55 | /// loop preheaders be inserted into the CFG... |
| 56 | /// |
| 57 | virtual void getAnalysisUsage(AnalysisUsage &AU) const { |
| 58 | AU.addRequiredID(LoopSimplifyID); |
| 59 | //AU.addRequired<DominatorSet>(); |
| 60 | AU.addRequired<LoopInfo>(); |
| 61 | AU.addPreserved<LoopInfo>(); |
| 62 | } |
| 63 | |
| 64 | private: |
| 65 | void VersionLoop(Value *LIC, Loop *L); |
| 66 | BasicBlock *SplitBlock(BasicBlock *BB, bool SplitAtTop); |
| 67 | void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC, bool Val); |
| 68 | }; |
| 69 | RegisterOpt<LoopUnswitch> X("loop-unswitch", "Unswitch loops"); |
| 70 | } |
| 71 | |
Jeff Cohen | f5e58f8 | 2005-01-06 05:47:18 +0000 | [diff] [blame] | 72 | FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); } |
Chris Lattner | 18f1609 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 73 | |
| 74 | bool LoopUnswitch::runOnFunction(Function &F) { |
| 75 | bool Changed = false; |
| 76 | LI = &getAnalysis<LoopInfo>(); |
| 77 | DS = 0; //&getAnalysis<DominatorSet>(); |
| 78 | |
| 79 | // Transform all the top-level loops. Copy the loop list so that the child |
| 80 | // can update the loop tree if it needs to delete the loop. |
| 81 | std::vector<Loop*> SubLoops(LI->begin(), LI->end()); |
| 82 | for (unsigned i = 0, e = SubLoops.size(); i != e; ++i) |
| 83 | Changed |= visitLoop(SubLoops[i]); |
| 84 | |
| 85 | return Changed; |
| 86 | } |
| 87 | |
| 88 | bool LoopUnswitch::visitLoop(Loop *L) { |
| 89 | bool Changed = false; |
| 90 | |
| 91 | // Recurse through all subloops before we process this loop. Copy the loop |
| 92 | // list so that the child can update the loop tree if it needs to delete the |
| 93 | // loop. |
| 94 | std::vector<Loop*> SubLoops(L->begin(), L->end()); |
| 95 | for (unsigned i = 0, e = SubLoops.size(); i != e; ++i) |
| 96 | Changed |= visitLoop(SubLoops[i]); |
| 97 | |
| 98 | // Loop over all of the basic blocks in the loop. If we find an interior |
| 99 | // block that is branching on a loop-invariant condition, we can unswitch this |
| 100 | // loop. |
| 101 | for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); |
| 102 | I != E; ++I) { |
| 103 | TerminatorInst *TI = (*I)->getTerminator(); |
| 104 | if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 105 | if (!isa<Constant>(SI) && L->isLoopInvariant(SI->getCondition())) |
| 106 | DEBUG(std::cerr << "Can't unswitching 'switch' loop %" |
| 107 | << L->getHeader()->getName() << ", cost = " |
| 108 | << L->getBlocks().size() << "\n" << **I); |
| 109 | } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) |
| 110 | if (BI->isConditional() && !isa<Constant>(BI->getCondition()) && |
| 111 | L->isLoopInvariant(BI->getCondition())) { |
| 112 | // Check to see if it would be profitable to unswitch this loop. |
| 113 | if (L->getBlocks().size() > 10) { |
| 114 | DEBUG(std::cerr << "NOT unswitching loop %" |
| 115 | << L->getHeader()->getName() << ", cost too high: " |
| 116 | << L->getBlocks().size() << "\n"); |
| 117 | } else { |
| 118 | // FIXME: check for profitability. |
| 119 | //std::cerr << "BEFORE:\n"; LI->dump(); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 120 | |
Chris Lattner | 18f1609 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 121 | VersionLoop(BI->getCondition(), L); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 122 | |
Chris Lattner | 18f1609 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 123 | //std::cerr << "AFTER:\n"; LI->dump(); |
| 124 | return true; |
| 125 | } |
| 126 | } |
| 127 | } |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 128 | |
Chris Lattner | 18f1609 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 129 | return Changed; |
| 130 | } |
| 131 | |
| 132 | /// SplitBlock - Split the specified basic block into two pieces. If SplitAtTop |
| 133 | /// is false, this splits the block so the second half only has an unconditional |
| 134 | /// branch. If SplitAtTop is true, it makes it so the first half of the block |
| 135 | /// only has an unconditional branch in it. |
| 136 | /// |
| 137 | /// This method updates the LoopInfo for this function to correctly reflect the |
| 138 | /// CFG changes made. |
| 139 | BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *BB, bool SplitAtTop) { |
| 140 | BasicBlock::iterator SplitPoint; |
| 141 | if (!SplitAtTop) |
| 142 | SplitPoint = BB->getTerminator(); |
| 143 | else { |
| 144 | SplitPoint = BB->begin(); |
| 145 | while (isa<PHINode>(SplitPoint)) ++SplitPoint; |
| 146 | } |
| 147 | |
| 148 | BasicBlock *New = BB->splitBasicBlock(SplitPoint, BB->getName()+".tail"); |
| 149 | // New now lives in whichever loop that BB used to. |
| 150 | if (Loop *L = LI->getLoopFor(BB)) |
| 151 | L->addBasicBlockToLoop(New, *LI); |
| 152 | return SplitAtTop ? BB : New; |
| 153 | } |
| 154 | |
| 155 | |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 156 | // RemapInstruction - Convert the instruction operands from referencing the |
Chris Lattner | 18f1609 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 157 | // current values into those specified by ValueMap. |
| 158 | // |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 159 | static inline void RemapInstruction(Instruction *I, |
Chris Lattner | 18f1609 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 160 | std::map<const Value *, Value*> &ValueMap) { |
| 161 | for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) { |
| 162 | Value *Op = I->getOperand(op); |
| 163 | std::map<const Value *, Value*>::iterator It = ValueMap.find(Op); |
| 164 | if (It != ValueMap.end()) Op = It->second; |
| 165 | I->setOperand(op, Op); |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | /// CloneLoop - Recursively clone the specified loop and all of its children, |
| 170 | /// mapping the blocks with the specified map. |
| 171 | static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM, |
| 172 | LoopInfo *LI) { |
| 173 | Loop *New = new Loop(); |
| 174 | |
| 175 | if (PL) |
| 176 | PL->addChildLoop(New); |
| 177 | else |
| 178 | LI->addTopLevelLoop(New); |
| 179 | |
| 180 | // Add all of the blocks in L to the new loop. |
| 181 | for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); |
| 182 | I != E; ++I) |
| 183 | if (LI->getLoopFor(*I) == L) |
| 184 | New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI); |
| 185 | |
| 186 | // Add all of the subloops to the new loop. |
| 187 | for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) |
| 188 | CloneLoop(*I, New, VM, LI); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 189 | |
Chris Lattner | 18f1609 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 190 | return New; |
| 191 | } |
| 192 | |
| 193 | |
| 194 | /// InsertPHINodesForUsesOutsideLoop - If this instruction is used outside of |
| 195 | /// the specified loop, insert a PHI node in the appropriate exit block to merge |
| 196 | /// the values in the two different loop versions. |
| 197 | /// |
| 198 | /// Most values are not used outside of the loop they are defined in, so be |
| 199 | /// efficient for this case. |
| 200 | /// |
| 201 | static AllocaInst * |
| 202 | InsertPHINodesForUsesOutsideLoop(Instruction *OI, Instruction *NI, |
| 203 | DominatorSet &DS, Loop *OL, Loop *NL, |
| 204 | std::vector<BasicBlock*> &OldExitBlocks, |
| 205 | std::map<const Value*, Value*> &ValueMap) { |
| 206 | assert(OI->getType() == NI->getType() && OI->getOpcode() == NI->getOpcode() && |
| 207 | "Hrm, should be mapping between identical instructions!"); |
| 208 | for (Value::use_iterator UI = OI->use_begin(), E = OI->use_end(); UI != E; |
| 209 | ++UI) |
| 210 | if (!OL->contains(cast<Instruction>(*UI)->getParent()) && |
| 211 | !NL->contains(cast<Instruction>(*UI)->getParent())) |
| 212 | goto UsedOutsideOfLoop; |
| 213 | return 0; |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 214 | |
Chris Lattner | 18f1609 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 215 | UsedOutsideOfLoop: |
| 216 | // Okay, this instruction is used outside of the current loop. Insert a PHI |
| 217 | // nodes for the instruction merging the values together. |
| 218 | |
| 219 | // FIXME: For now we just spill the object to the stack, assuming that a |
| 220 | // subsequent mem2reg pass will clean up after us. This should be improved in |
| 221 | // two ways: |
| 222 | // 1. If there is only one exit block, trivially insert the PHI nodes |
| 223 | // 2. Once we update domfrontier, we should do the promotion after everything |
| 224 | // is stable again. |
| 225 | AllocaInst *Result = DemoteRegToStack(*OI); |
| 226 | |
| 227 | // Store to the stack location right after the new instruction. |
| 228 | BasicBlock::iterator InsertPoint = NI; |
| 229 | if (InvokeInst *II = dyn_cast<InvokeInst>(NI)) |
| 230 | InsertPoint = II->getNormalDest()->begin(); |
| 231 | else |
| 232 | ++InsertPoint; |
| 233 | while (isa<PHINode>(InsertPoint)) ++InsertPoint; |
| 234 | new StoreInst(NI, Result, InsertPoint); |
| 235 | return Result; |
| 236 | } |
| 237 | |
| 238 | |
| 239 | |
| 240 | /// VersionLoop - We determined that the loop is profitable to unswitch and |
| 241 | /// contains a branch on a loop invariant condition. Split it into loop |
| 242 | /// versions and test the condition outside of either loop. |
| 243 | void LoopUnswitch::VersionLoop(Value *LIC, Loop *L) { |
| 244 | Function *F = L->getHeader()->getParent(); |
| 245 | |
| 246 | DEBUG(std::cerr << "loop-unswitch: Unswitching loop %" |
| 247 | << L->getHeader()->getName() << " [" << L->getBlocks().size() |
| 248 | << " blocks] in Function " << F->getName() |
| 249 | << " on cond:" << *LIC << "\n"); |
| 250 | |
| 251 | std::vector<BasicBlock*> LoopBlocks; |
| 252 | |
| 253 | // First step, split the preheader and exit blocks, and add these blocks to |
| 254 | // the LoopBlocks list. |
| 255 | BasicBlock *OrigPreheader = L->getLoopPreheader(); |
| 256 | LoopBlocks.push_back(SplitBlock(OrigPreheader, false)); |
| 257 | |
| 258 | // We want the loop to come after the preheader, but before the exit blocks. |
| 259 | LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end()); |
| 260 | |
| 261 | std::vector<BasicBlock*> ExitBlocks; |
| 262 | L->getExitBlocks(ExitBlocks); |
| 263 | std::sort(ExitBlocks.begin(), ExitBlocks.end()); |
| 264 | ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()), |
| 265 | ExitBlocks.end()); |
| 266 | for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) |
| 267 | LoopBlocks.push_back(ExitBlocks[i] = SplitBlock(ExitBlocks[i], true)); |
| 268 | |
| 269 | // Next step, clone all of the basic blocks that make up the loop (including |
| 270 | // the loop preheader and exit blocks), keeping track of the mapping between |
| 271 | // the instructions and blocks. |
| 272 | std::vector<BasicBlock*> NewBlocks; |
| 273 | NewBlocks.reserve(LoopBlocks.size()); |
| 274 | std::map<const Value*, Value*> ValueMap; |
| 275 | for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) { |
| 276 | NewBlocks.push_back(CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F)); |
| 277 | ValueMap[LoopBlocks[i]] = NewBlocks.back(); // Keep the BB mapping. |
| 278 | } |
| 279 | |
| 280 | // Splice the newly inserted blocks into the function right before the |
| 281 | // original preheader. |
| 282 | F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(), |
| 283 | NewBlocks[0], F->end()); |
| 284 | |
| 285 | // Now we create the new Loop object for the versioned loop. |
| 286 | Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI); |
| 287 | if (Loop *Parent = L->getParentLoop()) { |
| 288 | // Make sure to add the cloned preheader and exit blocks to the parent loop |
| 289 | // as well. |
| 290 | Parent->addBasicBlockToLoop(NewBlocks[0], *LI); |
| 291 | for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) |
| 292 | Parent->addBasicBlockToLoop(cast<BasicBlock>(ValueMap[ExitBlocks[i]]), |
| 293 | *LI); |
| 294 | } |
| 295 | |
| 296 | // Rewrite the code to refer to itself. |
| 297 | for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) |
| 298 | for (BasicBlock::iterator I = NewBlocks[i]->begin(), |
| 299 | E = NewBlocks[i]->end(); I != E; ++I) |
| 300 | RemapInstruction(I, ValueMap); |
| 301 | |
| 302 | // If the instructions are used outside of the loop, insert a PHI node in any |
| 303 | // exit blocks dominated by the instruction. |
| 304 | for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) |
| 305 | for (BasicBlock::iterator OI = LoopBlocks[i]->begin(), |
| 306 | E = LoopBlocks[i]->end(); OI != E; ++OI) |
| 307 | if (!OI->use_empty()) { |
| 308 | std::map<const Value*,Value*>::iterator OII = ValueMap.find(OI); |
| 309 | // The PHINode rewriting stuff can insert stores that are not in the |
| 310 | // mapping. Don't mess around with them. |
| 311 | if (OII != ValueMap.end()) { |
| 312 | Instruction *NI = cast<Instruction>(OII->second); |
| 313 | InsertPHINodesForUsesOutsideLoop(OI, NI, *DS, L, NewLoop, |
| 314 | ExitBlocks, ValueMap); |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | // Rewrite the original preheader to select between versions of the loop. |
| 319 | assert(isa<BranchInst>(OrigPreheader->getTerminator()) && |
| 320 | cast<BranchInst>(OrigPreheader->getTerminator())->isUnconditional() && |
| 321 | OrigPreheader->getTerminator()->getSuccessor(0) == LoopBlocks[0] && |
| 322 | "Preheader splitting did not work correctly!"); |
| 323 | // Remove the unconditional branch to LoopBlocks[0]. |
| 324 | OrigPreheader->getInstList().pop_back(); |
| 325 | |
| 326 | // Insert a conditional branch on LIC to the two preheaders. The original |
| 327 | // code is the true version and the new code is the false version. |
| 328 | new BranchInst(LoopBlocks[0], NewBlocks[0], LIC, OrigPreheader); |
| 329 | |
| 330 | // Now we rewrite the original code to know that the condition is true and the |
| 331 | // new code to know that the condition is false. |
| 332 | RewriteLoopBodyWithConditionConstant(L, LIC, true); |
| 333 | RewriteLoopBodyWithConditionConstant(NewLoop, LIC, false); |
| 334 | ++NumUnswitched; |
| 335 | |
| 336 | // Try to unswitch each of our new loops now! |
| 337 | visitLoop(L); |
| 338 | visitLoop(NewLoop); |
| 339 | } |
| 340 | |
| 341 | // RewriteLoopBodyWithConditionConstant - We know that the boolean value LIC has |
| 342 | // the value specified by Val in the specified loop. Rewrite any uses of LIC or |
| 343 | // of properties correlated to it. |
| 344 | void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC, |
| 345 | bool Val) { |
| 346 | // FIXME: Support correlated properties, like: |
| 347 | // for (...) |
| 348 | // if (li1 < li2) |
| 349 | // ... |
| 350 | // if (li1 > li2) |
| 351 | // ... |
| 352 | ConstantBool *BoolVal = ConstantBool::get(Val); |
| 353 | |
| 354 | std::vector<User*> Users(LIC->use_begin(), LIC->use_end()); |
| 355 | for (unsigned i = 0, e = Users.size(); i != e; ++i) |
| 356 | if (Instruction *U = dyn_cast<Instruction>(Users[i])) |
| 357 | if (L->contains(U->getParent())) |
| 358 | U->replaceUsesOfWith(LIC, BoolVal); |
| 359 | } |