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