Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 1 | //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===// |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 2 | // |
Chris Lattner | f48f777 | 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 | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 7 | // |
Chris Lattner | f48f777 | 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" |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 34 | #include "llvm/Analysis/LoopInfo.h" |
| 35 | #include "llvm/Transforms/Utils/Cloning.h" |
| 36 | #include "llvm/Transforms/Utils/Local.h" |
Chris Lattner | ec6b40a | 2006-02-10 19:08:15 +0000 | [diff] [blame] | 37 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Reid Spencer | 7c16caa | 2004-09-01 22:55:40 +0000 | [diff] [blame] | 38 | #include "llvm/ADT/Statistic.h" |
Chris Lattner | 8976219 | 2006-02-09 20:15:48 +0000 | [diff] [blame] | 39 | #include "llvm/Support/Debug.h" |
| 40 | #include "llvm/Support/CommandLine.h" |
Alkis Evlogimenos | a5c04ee | 2004-09-03 18:19:51 +0000 | [diff] [blame] | 41 | #include <algorithm> |
Chris Lattner | c597b8a | 2006-01-22 23:32:06 +0000 | [diff] [blame] | 42 | #include <iostream> |
Chris Lattner | 2826e05 | 2006-02-09 19:14:52 +0000 | [diff] [blame] | 43 | #include <set> |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 44 | using namespace llvm; |
| 45 | |
| 46 | namespace { |
Chris Lattner | 0b8ec1a | 2006-02-14 01:01:41 +0000 | [diff] [blame] | 47 | Statistic<> NumBranches("loop-unswitch", "Number of branches unswitched"); |
| 48 | Statistic<> NumSwitches("loop-unswitch", "Number of switches unswitched"); |
| 49 | Statistic<> NumSelects ("loop-unswitch", "Number of selects unswitched"); |
| 50 | Statistic<> NumTrivial ("loop-unswitch", |
| 51 | "Number of unswitches that are trivial"); |
Chris Lattner | 6fd1362 | 2006-02-17 00:31:07 +0000 | [diff] [blame^] | 52 | Statistic<> NumSimplify("loop-unswitch", |
| 53 | "Number of simplifications of unswitched code"); |
Chris Lattner | 8976219 | 2006-02-09 20:15:48 +0000 | [diff] [blame] | 54 | cl::opt<unsigned> |
| 55 | Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"), |
| 56 | cl::init(10), cl::Hidden); |
| 57 | |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 58 | class LoopUnswitch : public FunctionPass { |
| 59 | LoopInfo *LI; // Loop information |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 60 | public: |
| 61 | virtual bool runOnFunction(Function &F); |
| 62 | bool visitLoop(Loop *L); |
| 63 | |
| 64 | /// This transformation requires natural loop information & requires that |
| 65 | /// loop preheaders be inserted into the CFG... |
| 66 | /// |
| 67 | virtual void getAnalysisUsage(AnalysisUsage &AU) const { |
| 68 | AU.addRequiredID(LoopSimplifyID); |
Chris Lattner | 4f0e66d | 2006-02-09 22:15:42 +0000 | [diff] [blame] | 69 | AU.addPreservedID(LoopSimplifyID); |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 70 | AU.addRequired<LoopInfo>(); |
| 71 | AU.addPreserved<LoopInfo>(); |
| 72 | } |
| 73 | |
| 74 | private: |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 75 | bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L); |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 76 | unsigned getLoopUnswitchCost(Loop *L, Value *LIC); |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 77 | void VersionLoop(Value *LIC, Constant *OnVal, |
| 78 | Loop *L, Loop *&Out1, Loop *&Out2); |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 79 | BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To); |
Chris Lattner | e5cb76d | 2006-02-15 22:03:36 +0000 | [diff] [blame] | 80 | BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt); |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 81 | void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,Constant *Val, |
| 82 | bool isEqual); |
Chris Lattner | 01db04e | 2006-02-15 01:44:42 +0000 | [diff] [blame] | 83 | void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val, |
Chris Lattner | fdff0bb | 2006-02-15 22:52:05 +0000 | [diff] [blame] | 84 | bool EntersWhenTrue, BasicBlock *ExitBlock); |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 85 | }; |
| 86 | RegisterOpt<LoopUnswitch> X("loop-unswitch", "Unswitch loops"); |
| 87 | } |
| 88 | |
Jeff Cohen | eca0d0f | 2005-01-06 05:47:18 +0000 | [diff] [blame] | 89 | FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); } |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 90 | |
| 91 | bool LoopUnswitch::runOnFunction(Function &F) { |
| 92 | bool Changed = false; |
| 93 | LI = &getAnalysis<LoopInfo>(); |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 94 | |
| 95 | // Transform all the top-level loops. Copy the loop list so that the child |
| 96 | // can update the loop tree if it needs to delete the loop. |
| 97 | std::vector<Loop*> SubLoops(LI->begin(), LI->end()); |
| 98 | for (unsigned i = 0, e = SubLoops.size(); i != e; ++i) |
| 99 | Changed |= visitLoop(SubLoops[i]); |
| 100 | |
| 101 | return Changed; |
| 102 | } |
| 103 | |
Chris Lattner | 2826e05 | 2006-02-09 19:14:52 +0000 | [diff] [blame] | 104 | |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 105 | /// LoopValuesUsedOutsideLoop - Return true if there are any values defined in |
| 106 | /// the loop that are used by instructions outside of it. |
Chris Lattner | 2826e05 | 2006-02-09 19:14:52 +0000 | [diff] [blame] | 107 | static bool LoopValuesUsedOutsideLoop(Loop *L) { |
| 108 | // We will be doing lots of "loop contains block" queries. Loop::contains is |
| 109 | // linear time, use a set to speed this up. |
| 110 | std::set<BasicBlock*> LoopBlocks; |
| 111 | |
| 112 | for (Loop::block_iterator BB = L->block_begin(), E = L->block_end(); |
| 113 | BB != E; ++BB) |
| 114 | LoopBlocks.insert(*BB); |
| 115 | |
| 116 | for (Loop::block_iterator BB = L->block_begin(), E = L->block_end(); |
| 117 | BB != E; ++BB) { |
| 118 | for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I) |
| 119 | for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; |
| 120 | ++UI) { |
| 121 | BasicBlock *UserBB = cast<Instruction>(*UI)->getParent(); |
| 122 | if (!LoopBlocks.count(UserBB)) |
| 123 | return true; |
| 124 | } |
| 125 | } |
| 126 | return false; |
| 127 | } |
| 128 | |
Chris Lattner | e5cb76d | 2006-02-15 22:03:36 +0000 | [diff] [blame] | 129 | /// isTrivialLoopExitBlock - Check to see if all paths from BB either: |
| 130 | /// 1. Exit the loop with no side effects. |
| 131 | /// 2. Branch to the latch block with no side-effects. |
| 132 | /// |
| 133 | /// If these conditions are true, we return true and set ExitBB to the block we |
| 134 | /// exit through. |
| 135 | /// |
| 136 | static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB, |
| 137 | BasicBlock *&ExitBB, |
| 138 | std::set<BasicBlock*> &Visited) { |
Chris Lattner | 6e26315 | 2006-02-10 02:30:37 +0000 | [diff] [blame] | 139 | BasicBlock *Header = L->getHeader(); |
Chris Lattner | e5cb76d | 2006-02-15 22:03:36 +0000 | [diff] [blame] | 140 | for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) { |
| 141 | if (!Visited.insert(*SI).second) { |
| 142 | // Already visited and Ok, end of recursion. |
| 143 | } else if (L->contains(*SI)) { |
| 144 | // Check to see if the successor is a trivial loop exit. |
| 145 | if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited)) |
| 146 | return false; |
| 147 | } else { |
| 148 | // Otherwise, this is a loop exit, this is fine so long as this is the |
| 149 | // first exit. |
| 150 | if (ExitBB != 0) return false; |
| 151 | ExitBB = *SI; |
| 152 | } |
Chris Lattner | 6e26315 | 2006-02-10 02:30:37 +0000 | [diff] [blame] | 153 | } |
Chris Lattner | e5cb76d | 2006-02-15 22:03:36 +0000 | [diff] [blame] | 154 | |
| 155 | // Okay, everything after this looks good, check to make sure that this block |
| 156 | // doesn't include any side effects. |
Chris Lattner | fdff0bb | 2006-02-15 22:52:05 +0000 | [diff] [blame] | 157 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) |
Chris Lattner | e5cb76d | 2006-02-15 22:03:36 +0000 | [diff] [blame] | 158 | if (I->mayWriteToMemory()) |
| 159 | return false; |
| 160 | |
| 161 | return true; |
Chris Lattner | 6e26315 | 2006-02-10 02:30:37 +0000 | [diff] [blame] | 162 | } |
| 163 | |
Chris Lattner | e5cb76d | 2006-02-15 22:03:36 +0000 | [diff] [blame] | 164 | static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) { |
| 165 | std::set<BasicBlock*> Visited; |
| 166 | Visited.insert(L->getHeader()); // Branches to header are ok. |
| 167 | Visited.insert(BB); // Don't revisit BB after we do. |
| 168 | BasicBlock *ExitBB = 0; |
| 169 | if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited)) |
| 170 | return ExitBB; |
| 171 | return 0; |
| 172 | } |
Chris Lattner | 6e26315 | 2006-02-10 02:30:37 +0000 | [diff] [blame] | 173 | |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 174 | /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is |
| 175 | /// trivial: that is, that the condition controls whether or not the loop does |
| 176 | /// anything at all. If this is a trivial condition, unswitching produces no |
| 177 | /// code duplications (equivalently, it produces a simpler loop and a new empty |
| 178 | /// loop, which gets deleted). |
| 179 | /// |
| 180 | /// If this is a trivial condition, return ConstantBool::True if the loop body |
| 181 | /// runs when the condition is true, False if the loop body executes when the |
| 182 | /// condition is false. Otherwise, return null to indicate a complex condition. |
Chris Lattner | 4935417 | 2006-02-10 02:01:22 +0000 | [diff] [blame] | 183 | static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, |
Chris Lattner | 01db04e | 2006-02-15 01:44:42 +0000 | [diff] [blame] | 184 | Constant **Val = 0, |
Chris Lattner | fdff0bb | 2006-02-15 22:52:05 +0000 | [diff] [blame] | 185 | bool *EntersWhenTrue = 0, |
Chris Lattner | 4935417 | 2006-02-10 02:01:22 +0000 | [diff] [blame] | 186 | BasicBlock **LoopExit = 0) { |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 187 | BasicBlock *Header = L->getHeader(); |
Chris Lattner | fdff0bb | 2006-02-15 22:52:05 +0000 | [diff] [blame] | 188 | TerminatorInst *HeaderTerm = Header->getTerminator(); |
| 189 | |
| 190 | BasicBlock *LoopExitBB = 0; |
| 191 | if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) { |
| 192 | // If the header block doesn't end with a conditional branch on Cond, we |
| 193 | // can't handle it. |
| 194 | if (!BI->isConditional() || BI->getCondition() != Cond) |
| 195 | return false; |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 196 | |
Chris Lattner | fdff0bb | 2006-02-15 22:52:05 +0000 | [diff] [blame] | 197 | // Check to see if a successor of the branch is guaranteed to go to the |
| 198 | // latch block or exit through a one exit block without having any |
| 199 | // side-effects. If so, determine the value of Cond that causes it to do |
| 200 | // this. |
| 201 | if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) { |
Chris Lattner | fdff0bb | 2006-02-15 22:52:05 +0000 | [diff] [blame] | 202 | if (Val) *Val = ConstantBool::False; |
Chris Lattner | ff42e81 | 2006-02-16 01:24:41 +0000 | [diff] [blame] | 203 | } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) { |
| 204 | if (Val) *Val = ConstantBool::True; |
Chris Lattner | fdff0bb | 2006-02-15 22:52:05 +0000 | [diff] [blame] | 205 | } |
| 206 | } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) { |
| 207 | // If this isn't a switch on Cond, we can't handle it. |
| 208 | if (SI->getCondition() != Cond) return false; |
| 209 | |
| 210 | // Check to see if a successor of the switch is guaranteed to go to the |
| 211 | // latch block or exit through a one exit block without having any |
| 212 | // side-effects. If so, determine the value of Cond that causes it to do |
| 213 | // this. Note that we can't trivially unswitch on the default case. |
| 214 | for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) |
| 215 | if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) { |
| 216 | // Okay, we found a trivial case, remember the value that is trivial. |
| 217 | if (Val) *Val = SI->getCaseValue(i); |
| 218 | if (EntersWhenTrue) *EntersWhenTrue = false; |
| 219 | break; |
| 220 | } |
Chris Lattner | e5cb76d | 2006-02-15 22:03:36 +0000 | [diff] [blame] | 221 | } |
| 222 | |
Chris Lattner | fdff0bb | 2006-02-15 22:52:05 +0000 | [diff] [blame] | 223 | if (!LoopExitBB) |
Chris Lattner | e5cb76d | 2006-02-15 22:03:36 +0000 | [diff] [blame] | 224 | return false; // Can't handle this. |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 225 | |
Chris Lattner | fdff0bb | 2006-02-15 22:52:05 +0000 | [diff] [blame] | 226 | if (LoopExit) *LoopExit = LoopExitBB; |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 227 | |
| 228 | // We already know that nothing uses any scalar values defined inside of this |
| 229 | // loop. As such, we just have to check to see if this loop will execute any |
| 230 | // side-effecting instructions (e.g. stores, calls, volatile loads) in the |
Chris Lattner | e5cb76d | 2006-02-15 22:03:36 +0000 | [diff] [blame] | 231 | // part of the loop that the code *would* execute. We already checked the |
| 232 | // tail, check the header now. |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 233 | for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I) |
| 234 | if (I->mayWriteToMemory()) |
Chris Lattner | 4935417 | 2006-02-10 02:01:22 +0000 | [diff] [blame] | 235 | return false; |
Chris Lattner | 4935417 | 2006-02-10 02:01:22 +0000 | [diff] [blame] | 236 | return true; |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 237 | } |
| 238 | |
| 239 | /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if |
| 240 | /// we choose to unswitch the specified loop on the specified value. |
| 241 | /// |
| 242 | unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) { |
| 243 | // If the condition is trivial, always unswitch. There is no code growth for |
| 244 | // this case. |
| 245 | if (IsTrivialUnswitchCondition(L, LIC)) |
| 246 | return 0; |
| 247 | |
| 248 | unsigned Cost = 0; |
| 249 | // FIXME: this is brain dead. It should take into consideration code |
| 250 | // shrinkage. |
| 251 | for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); |
| 252 | I != E; ++I) { |
| 253 | BasicBlock *BB = *I; |
| 254 | // Do not include empty blocks in the cost calculation. This happen due to |
| 255 | // loop canonicalization and will be removed. |
| 256 | if (BB->begin() == BasicBlock::iterator(BB->getTerminator())) |
| 257 | continue; |
| 258 | |
| 259 | // Count basic blocks. |
| 260 | ++Cost; |
| 261 | } |
| 262 | |
| 263 | return Cost; |
| 264 | } |
| 265 | |
Chris Lattner | 6e26315 | 2006-02-10 02:30:37 +0000 | [diff] [blame] | 266 | /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is |
| 267 | /// invariant in the loop, or has an invariant piece, return the invariant. |
| 268 | /// Otherwise, return null. |
| 269 | static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) { |
| 270 | // Constants should be folded, not unswitched on! |
| 271 | if (isa<Constant>(Cond)) return false; |
| 272 | |
| 273 | // TODO: Handle: br (VARIANT|INVARIANT). |
| 274 | // TODO: Hoist simple expressions out of loops. |
| 275 | if (L->isLoopInvariant(Cond)) return Cond; |
| 276 | |
| 277 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond)) |
| 278 | if (BO->getOpcode() == Instruction::And || |
| 279 | BO->getOpcode() == Instruction::Or) { |
| 280 | // If either the left or right side is invariant, we can unswitch on this, |
| 281 | // which will cause the branch to go away in one loop and the condition to |
| 282 | // simplify in the other one. |
| 283 | if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed)) |
| 284 | return LHS; |
| 285 | if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed)) |
| 286 | return RHS; |
| 287 | } |
| 288 | |
| 289 | return 0; |
| 290 | } |
| 291 | |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 292 | bool LoopUnswitch::visitLoop(Loop *L) { |
| 293 | bool Changed = false; |
| 294 | |
| 295 | // Recurse through all subloops before we process this loop. Copy the loop |
| 296 | // list so that the child can update the loop tree if it needs to delete the |
| 297 | // loop. |
| 298 | std::vector<Loop*> SubLoops(L->begin(), L->end()); |
| 299 | for (unsigned i = 0, e = SubLoops.size(); i != e; ++i) |
| 300 | Changed |= visitLoop(SubLoops[i]); |
| 301 | |
| 302 | // Loop over all of the basic blocks in the loop. If we find an interior |
| 303 | // block that is branching on a loop-invariant condition, we can unswitch this |
| 304 | // loop. |
| 305 | for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); |
| 306 | I != E; ++I) { |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 307 | TerminatorInst *TI = (*I)->getTerminator(); |
| 308 | if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { |
| 309 | // If this isn't branching on an invariant condition, we can't unswitch |
| 310 | // it. |
| 311 | if (BI->isConditional()) { |
| 312 | // See if this, or some part of it, is loop invariant. If so, we can |
| 313 | // unswitch on it if we desire. |
| 314 | Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed); |
Chris Lattner | 0b8ec1a | 2006-02-14 01:01:41 +0000 | [diff] [blame] | 315 | if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L)) { |
| 316 | ++NumBranches; |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 317 | return true; |
Chris Lattner | 0b8ec1a | 2006-02-14 01:01:41 +0000 | [diff] [blame] | 318 | } |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 319 | } |
| 320 | } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 321 | Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed); |
| 322 | if (LoopCond && SI->getNumCases() > 1) { |
| 323 | // Find a value to unswitch on: |
| 324 | // FIXME: this should chose the most expensive case! |
| 325 | Constant *UnswitchVal = SI->getCaseValue(1); |
Chris Lattner | 0b8ec1a | 2006-02-14 01:01:41 +0000 | [diff] [blame] | 326 | if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) { |
| 327 | ++NumSwitches; |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 328 | return true; |
Chris Lattner | 0b8ec1a | 2006-02-14 01:01:41 +0000 | [diff] [blame] | 329 | } |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 330 | } |
| 331 | } |
| 332 | |
| 333 | // Scan the instructions to check for unswitchable values. |
Chris Lattner | f1b1516 | 2006-02-10 23:26:14 +0000 | [diff] [blame] | 334 | for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end(); |
| 335 | BBI != E; ++BBI) |
| 336 | if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) { |
| 337 | Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed); |
Chris Lattner | 0b8ec1a | 2006-02-14 01:01:41 +0000 | [diff] [blame] | 338 | if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L)) { |
| 339 | ++NumSelects; |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 340 | return true; |
Chris Lattner | 0b8ec1a | 2006-02-14 01:01:41 +0000 | [diff] [blame] | 341 | } |
Chris Lattner | f1b1516 | 2006-02-10 23:26:14 +0000 | [diff] [blame] | 342 | } |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 343 | } |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 344 | |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 345 | return Changed; |
| 346 | } |
| 347 | |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 348 | /// UnswitchIfProfitable - We have found that we can unswitch L when |
| 349 | /// LoopCond == Val to simplify the loop. If we decide that this is profitable, |
| 350 | /// unswitch the loop, reprocess the pieces, then return true. |
| 351 | bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){ |
| 352 | // Check to see if it would be profitable to unswitch this loop. |
| 353 | if (getLoopUnswitchCost(L, LoopCond) > Threshold) { |
| 354 | // FIXME: this should estimate growth by the amount of code shared by the |
| 355 | // resultant unswitched loops. |
| 356 | // |
| 357 | DEBUG(std::cerr << "NOT unswitching loop %" |
| 358 | << L->getHeader()->getName() << ", cost too high: " |
| 359 | << L->getBlocks().size() << "\n"); |
| 360 | return false; |
| 361 | } |
| 362 | |
| 363 | // If this loop has live-out values, we can't unswitch it. We need something |
| 364 | // like loop-closed SSA form in order to know how to insert PHI nodes for |
| 365 | // these values. |
| 366 | if (LoopValuesUsedOutsideLoop(L)) { |
| 367 | DEBUG(std::cerr << "NOT unswitching loop %" << L->getHeader()->getName() |
| 368 | << ", a loop value is used outside loop!\n"); |
| 369 | return false; |
| 370 | } |
| 371 | |
| 372 | //std::cerr << "BEFORE:\n"; LI->dump(); |
| 373 | Loop *NewLoop1 = 0, *NewLoop2 = 0; |
| 374 | |
| 375 | // If this is a trivial condition to unswitch (which results in no code |
| 376 | // duplication), do it now. |
Chris Lattner | 01db04e | 2006-02-15 01:44:42 +0000 | [diff] [blame] | 377 | Constant *CondVal; |
Chris Lattner | fdff0bb | 2006-02-15 22:52:05 +0000 | [diff] [blame] | 378 | bool EntersWhenTrue = true; |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 379 | BasicBlock *ExitBlock; |
Chris Lattner | fdff0bb | 2006-02-15 22:52:05 +0000 | [diff] [blame] | 380 | if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, |
| 381 | &EntersWhenTrue, &ExitBlock)) { |
| 382 | UnswitchTrivialCondition(L, LoopCond, CondVal, EntersWhenTrue, ExitBlock); |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 383 | NewLoop1 = L; |
| 384 | } else { |
| 385 | VersionLoop(LoopCond, Val, L, NewLoop1, NewLoop2); |
| 386 | } |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 387 | |
| 388 | //std::cerr << "AFTER:\n"; LI->dump(); |
| 389 | |
| 390 | // Try to unswitch each of our new loops now! |
| 391 | if (NewLoop1) visitLoop(NewLoop1); |
| 392 | if (NewLoop2) visitLoop(NewLoop2); |
| 393 | return true; |
| 394 | } |
| 395 | |
Chris Lattner | e5cb76d | 2006-02-15 22:03:36 +0000 | [diff] [blame] | 396 | /// SplitBlock - Split the specified block at the specified instruction - every |
| 397 | /// thing before SplitPt stays in Old and everything starting with SplitPt moves |
| 398 | /// to a new block. The two blocks are joined by an unconditional branch and |
| 399 | /// the loop info is updated. |
| 400 | /// |
| 401 | BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) { |
Chris Lattner | fa335f6 | 2006-02-16 19:36:22 +0000 | [diff] [blame] | 402 | BasicBlock::iterator SplitIt = SplitPt; |
| 403 | while (isa<PHINode>(SplitIt)) |
| 404 | ++SplitIt; |
| 405 | BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split"); |
Chris Lattner | e5cb76d | 2006-02-15 22:03:36 +0000 | [diff] [blame] | 406 | |
| 407 | // The new block lives in whichever loop the old one did. |
| 408 | if (Loop *L = LI->getLoopFor(Old)) |
| 409 | L->addBasicBlockToLoop(New, *LI); |
| 410 | |
| 411 | return New; |
| 412 | } |
| 413 | |
| 414 | |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 415 | BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) { |
| 416 | TerminatorInst *LatchTerm = BB->getTerminator(); |
| 417 | unsigned SuccNum = 0; |
| 418 | for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) { |
| 419 | assert(i != e && "Didn't find edge?"); |
| 420 | if (LatchTerm->getSuccessor(i) == Succ) { |
| 421 | SuccNum = i; |
| 422 | break; |
| 423 | } |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 424 | } |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 425 | |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 426 | // If this is a critical edge, let SplitCriticalEdge do it. |
| 427 | if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this)) |
| 428 | return LatchTerm->getSuccessor(SuccNum); |
| 429 | |
| 430 | // If the edge isn't critical, then BB has a single successor or Succ has a |
| 431 | // single pred. Split the block. |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 432 | BasicBlock::iterator SplitPoint; |
| 433 | if (BasicBlock *SP = Succ->getSinglePredecessor()) { |
| 434 | // If the successor only has a single pred, split the top of the successor |
| 435 | // block. |
| 436 | assert(SP == BB && "CFG broken"); |
Chris Lattner | e5cb76d | 2006-02-15 22:03:36 +0000 | [diff] [blame] | 437 | return SplitBlock(Succ, Succ->begin()); |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 438 | } else { |
| 439 | // Otherwise, if BB has a single successor, split it at the bottom of the |
| 440 | // block. |
| 441 | assert(BB->getTerminator()->getNumSuccessors() == 1 && |
| 442 | "Should have a single succ!"); |
Chris Lattner | e5cb76d | 2006-02-15 22:03:36 +0000 | [diff] [blame] | 443 | return SplitBlock(BB, BB->getTerminator()); |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 444 | } |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 445 | } |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 446 | |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 447 | |
| 448 | |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 449 | // RemapInstruction - Convert the instruction operands from referencing the |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 450 | // current values into those specified by ValueMap. |
| 451 | // |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 452 | static inline void RemapInstruction(Instruction *I, |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 453 | std::map<const Value *, Value*> &ValueMap) { |
| 454 | for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) { |
| 455 | Value *Op = I->getOperand(op); |
| 456 | std::map<const Value *, Value*>::iterator It = ValueMap.find(Op); |
| 457 | if (It != ValueMap.end()) Op = It->second; |
| 458 | I->setOperand(op, Op); |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | /// CloneLoop - Recursively clone the specified loop and all of its children, |
| 463 | /// mapping the blocks with the specified map. |
| 464 | static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM, |
| 465 | LoopInfo *LI) { |
| 466 | Loop *New = new Loop(); |
| 467 | |
| 468 | if (PL) |
| 469 | PL->addChildLoop(New); |
| 470 | else |
| 471 | LI->addTopLevelLoop(New); |
| 472 | |
| 473 | // Add all of the blocks in L to the new loop. |
| 474 | for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); |
| 475 | I != E; ++I) |
| 476 | if (LI->getLoopFor(*I) == L) |
| 477 | New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI); |
| 478 | |
| 479 | // Add all of the subloops to the new loop. |
| 480 | for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) |
| 481 | CloneLoop(*I, New, VM, LI); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 482 | |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 483 | return New; |
| 484 | } |
| 485 | |
Chris Lattner | b0cbe71 | 2006-02-15 00:07:43 +0000 | [diff] [blame] | 486 | /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values |
| 487 | /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the |
| 488 | /// code immediately before InsertPt. |
| 489 | static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val, |
| 490 | BasicBlock *TrueDest, |
| 491 | BasicBlock *FalseDest, |
| 492 | Instruction *InsertPt) { |
| 493 | // Insert a conditional branch on LIC to the two preheaders. The original |
| 494 | // code is the true version and the new code is the false version. |
| 495 | Value *BranchVal = LIC; |
Chris Lattner | 65152d8 | 2006-02-15 19:05:52 +0000 | [diff] [blame] | 496 | if (!isa<ConstantBool>(Val)) { |
Chris Lattner | b0cbe71 | 2006-02-15 00:07:43 +0000 | [diff] [blame] | 497 | BranchVal = BinaryOperator::createSetEQ(LIC, Val, "tmp", InsertPt); |
| 498 | } else if (Val != ConstantBool::True) { |
| 499 | // We want to enter the new loop when the condition is true. |
| 500 | std::swap(TrueDest, FalseDest); |
| 501 | } |
| 502 | |
| 503 | // Insert the new branch. |
| 504 | new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt); |
| 505 | } |
| 506 | |
| 507 | |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 508 | /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable |
| 509 | /// condition in it (a cond branch from its header block to its latch block, |
| 510 | /// where the path through the loop that doesn't execute its body has no |
| 511 | /// side-effects), unswitch it. This doesn't involve any code duplication, just |
| 512 | /// moving the conditional branch outside of the loop and updating loop info. |
| 513 | void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, |
Chris Lattner | fdff0bb | 2006-02-15 22:52:05 +0000 | [diff] [blame] | 514 | Constant *Val, bool EntersWhenTrue, |
Chris Lattner | 4935417 | 2006-02-10 02:01:22 +0000 | [diff] [blame] | 515 | BasicBlock *ExitBlock) { |
Chris Lattner | 3fc3148 | 2006-02-10 01:36:35 +0000 | [diff] [blame] | 516 | DEBUG(std::cerr << "loop-unswitch: Trivial-Unswitch loop %" |
| 517 | << L->getHeader()->getName() << " [" << L->getBlocks().size() |
| 518 | << " blocks] in Function " << L->getHeader()->getParent()->getName() |
Chris Lattner | fdff0bb | 2006-02-15 22:52:05 +0000 | [diff] [blame] | 519 | << " on cond: " << *Val << (EntersWhenTrue ? " == " : " != ") << |
| 520 | *Cond << "\n"); |
Chris Lattner | 3fc3148 | 2006-02-10 01:36:35 +0000 | [diff] [blame] | 521 | |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 522 | // First step, split the preheader, so that we know that there is a safe place |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 523 | // to insert the conditional branch. We will change 'OrigPH' to have a |
| 524 | // conditional branch on Cond. |
| 525 | BasicBlock *OrigPH = L->getLoopPreheader(); |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 526 | BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader()); |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 527 | |
| 528 | // Now that we have a place to insert the conditional branch, create a place |
Chris Lattner | 4935417 | 2006-02-10 02:01:22 +0000 | [diff] [blame] | 529 | // to branch to: this is the exit block out of the loop that we should |
| 530 | // short-circuit to. |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 531 | |
Chris Lattner | e5cb76d | 2006-02-15 22:03:36 +0000 | [diff] [blame] | 532 | // Split this block now, so that the loop maintains its exit block, and so |
| 533 | // that the jump from the preheader can execute the contents of the exit block |
| 534 | // without actually branching to it (the exit block should be dominated by the |
| 535 | // loop header, not the preheader). |
Chris Lattner | 4935417 | 2006-02-10 02:01:22 +0000 | [diff] [blame] | 536 | assert(!L->contains(ExitBlock) && "Exit block is in the loop?"); |
Chris Lattner | e5cb76d | 2006-02-15 22:03:36 +0000 | [diff] [blame] | 537 | BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin()); |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 538 | |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 539 | // Okay, now we have a position to branch from and a position to branch to, |
| 540 | // insert the new conditional branch. |
Chris Lattner | fdff0bb | 2006-02-15 22:52:05 +0000 | [diff] [blame] | 541 | { |
| 542 | BasicBlock *TrueDest = NewPH, *FalseDest = NewExit; |
| 543 | if (!EntersWhenTrue) std::swap(TrueDest, FalseDest); |
| 544 | EmitPreheaderBranchOnCondition(Cond, Val, TrueDest, FalseDest, |
| 545 | OrigPH->getTerminator()); |
| 546 | } |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 547 | OrigPH->getTerminator()->eraseFromParent(); |
| 548 | |
| 549 | // Now that we know that the loop is never entered when this condition is a |
| 550 | // particular value, rewrite the loop with this info. We know that this will |
| 551 | // at least eliminate the old branch. |
Chris Lattner | fdff0bb | 2006-02-15 22:52:05 +0000 | [diff] [blame] | 552 | RewriteLoopBodyWithConditionConstant(L, Cond, Val, EntersWhenTrue); |
Chris Lattner | 0b8ec1a | 2006-02-14 01:01:41 +0000 | [diff] [blame] | 553 | ++NumTrivial; |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 554 | } |
| 555 | |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 556 | |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 557 | /// VersionLoop - We determined that the loop is profitable to unswitch when LIC |
| 558 | /// equal Val. Split it into loop versions and test the condition outside of |
| 559 | /// either loop. Return the loops created as Out1/Out2. |
| 560 | void LoopUnswitch::VersionLoop(Value *LIC, Constant *Val, Loop *L, |
| 561 | Loop *&Out1, Loop *&Out2) { |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 562 | Function *F = L->getHeader()->getParent(); |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 563 | |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 564 | DEBUG(std::cerr << "loop-unswitch: Unswitching loop %" |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 565 | << L->getHeader()->getName() << " [" << L->getBlocks().size() |
| 566 | << " blocks] in Function " << F->getName() |
| 567 | << " when '" << *Val << "' == " << *LIC << "\n"); |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 568 | |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 569 | // LoopBlocks contains all of the basic blocks of the loop, including the |
| 570 | // preheader of the loop, the body of the loop, and the exit blocks of the |
| 571 | // loop, in that order. |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 572 | std::vector<BasicBlock*> LoopBlocks; |
| 573 | |
| 574 | // First step, split the preheader and exit blocks, and add these blocks to |
| 575 | // the LoopBlocks list. |
| 576 | BasicBlock *OrigPreheader = L->getLoopPreheader(); |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 577 | LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader())); |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 578 | |
| 579 | // We want the loop to come after the preheader, but before the exit blocks. |
| 580 | LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end()); |
| 581 | |
| 582 | std::vector<BasicBlock*> ExitBlocks; |
| 583 | L->getExitBlocks(ExitBlocks); |
| 584 | std::sort(ExitBlocks.begin(), ExitBlocks.end()); |
| 585 | ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()), |
| 586 | ExitBlocks.end()); |
Chris Lattner | b0cbe71 | 2006-02-15 00:07:43 +0000 | [diff] [blame] | 587 | |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 588 | // Split all of the edges from inside the loop to their exit blocks. This |
| 589 | // unswitching trivial: no phi nodes to update. |
Chris Lattner | 0b8ec1a | 2006-02-14 01:01:41 +0000 | [diff] [blame] | 590 | unsigned NumBlocks = L->getBlocks().size(); |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 591 | for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) { |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 592 | BasicBlock *ExitBlock = ExitBlocks[i]; |
| 593 | std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock)); |
| 594 | |
| 595 | for (unsigned j = 0, e = Preds.size(); j != e; ++j) { |
| 596 | assert(L->contains(Preds[j]) && |
| 597 | "All preds of loop exit blocks must be the same loop!"); |
| 598 | SplitEdge(Preds[j], ExitBlock); |
| 599 | } |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 600 | } |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 601 | |
| 602 | // The exit blocks may have been changed due to edge splitting, recompute. |
| 603 | ExitBlocks.clear(); |
| 604 | L->getExitBlocks(ExitBlocks); |
| 605 | std::sort(ExitBlocks.begin(), ExitBlocks.end()); |
| 606 | ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()), |
| 607 | ExitBlocks.end()); |
| 608 | |
| 609 | // Add exit blocks to the loop blocks. |
| 610 | LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end()); |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 611 | |
| 612 | // Next step, clone all of the basic blocks that make up the loop (including |
| 613 | // the loop preheader and exit blocks), keeping track of the mapping between |
| 614 | // the instructions and blocks. |
| 615 | std::vector<BasicBlock*> NewBlocks; |
| 616 | NewBlocks.reserve(LoopBlocks.size()); |
| 617 | std::map<const Value*, Value*> ValueMap; |
| 618 | for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) { |
Chris Lattner | 0b8ec1a | 2006-02-14 01:01:41 +0000 | [diff] [blame] | 619 | BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F); |
| 620 | NewBlocks.push_back(New); |
| 621 | ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping. |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 622 | } |
| 623 | |
| 624 | // Splice the newly inserted blocks into the function right before the |
| 625 | // original preheader. |
| 626 | F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(), |
| 627 | NewBlocks[0], F->end()); |
| 628 | |
| 629 | // Now we create the new Loop object for the versioned loop. |
| 630 | Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI); |
Chris Lattner | f1b1516 | 2006-02-10 23:26:14 +0000 | [diff] [blame] | 631 | Loop *ParentLoop = L->getParentLoop(); |
| 632 | if (ParentLoop) { |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 633 | // Make sure to add the cloned preheader and exit blocks to the parent loop |
| 634 | // as well. |
Chris Lattner | f1b1516 | 2006-02-10 23:26:14 +0000 | [diff] [blame] | 635 | ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI); |
| 636 | } |
| 637 | |
| 638 | for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) { |
| 639 | BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]); |
| 640 | if (ParentLoop) |
| 641 | ParentLoop->addBasicBlockToLoop(cast<BasicBlock>(NewExit), *LI); |
| 642 | |
| 643 | assert(NewExit->getTerminator()->getNumSuccessors() == 1 && |
| 644 | "Exit block should have been split to have one successor!"); |
| 645 | BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0); |
| 646 | |
| 647 | // If the successor of the exit block had PHI nodes, add an entry for |
| 648 | // NewExit. |
| 649 | PHINode *PN; |
| 650 | for (BasicBlock::iterator I = ExitSucc->begin(); |
| 651 | (PN = dyn_cast<PHINode>(I)); ++I) { |
| 652 | Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]); |
| 653 | std::map<const Value *, Value*>::iterator It = ValueMap.find(V); |
| 654 | if (It != ValueMap.end()) V = It->second; |
| 655 | PN->addIncoming(V, NewExit); |
| 656 | } |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 657 | } |
| 658 | |
| 659 | // Rewrite the code to refer to itself. |
| 660 | for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) |
| 661 | for (BasicBlock::iterator I = NewBlocks[i]->begin(), |
| 662 | E = NewBlocks[i]->end(); I != E; ++I) |
| 663 | RemapInstruction(I, ValueMap); |
Chris Lattner | 2826e05 | 2006-02-09 19:14:52 +0000 | [diff] [blame] | 664 | |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 665 | // Rewrite the original preheader to select between versions of the loop. |
Chris Lattner | b0cbe71 | 2006-02-15 00:07:43 +0000 | [diff] [blame] | 666 | BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator()); |
| 667 | assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] && |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 668 | "Preheader splitting did not work correctly!"); |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 669 | |
Chris Lattner | b0cbe71 | 2006-02-15 00:07:43 +0000 | [diff] [blame] | 670 | // Emit the new branch that selects between the two versions of this loop. |
| 671 | EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR); |
| 672 | OldBR->eraseFromParent(); |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 673 | |
| 674 | // Now we rewrite the original code to know that the condition is true and the |
| 675 | // new code to know that the condition is false. |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 676 | RewriteLoopBodyWithConditionConstant(L, LIC, Val, false); |
| 677 | RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true); |
Chris Lattner | 4f0e66d | 2006-02-09 22:15:42 +0000 | [diff] [blame] | 678 | Out1 = L; |
| 679 | Out2 = NewLoop; |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 680 | } |
| 681 | |
Chris Lattner | 6fd1362 | 2006-02-17 00:31:07 +0000 | [diff] [blame^] | 682 | /// RemoveFromWorklist - Remove all instances of I from the worklist vector |
| 683 | /// specified. |
| 684 | static void RemoveFromWorklist(Instruction *I, |
| 685 | std::vector<Instruction*> &Worklist) { |
| 686 | std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(), |
| 687 | Worklist.end(), I); |
| 688 | while (WI != Worklist.end()) { |
| 689 | unsigned Offset = WI-Worklist.begin(); |
| 690 | Worklist.erase(WI); |
| 691 | WI = std::find(Worklist.begin()+Offset, Worklist.end(), I); |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the |
| 696 | /// program, replacing all uses with V and update the worklist. |
| 697 | static void ReplaceUsesOfWith(Instruction *I, Value *V, |
| 698 | std::vector<Instruction*> &Worklist) { |
| 699 | DEBUG(std::cerr << "Replace with '" << *V << "': " << *I); |
| 700 | |
| 701 | // Add uses to the worklist, which may be dead now. |
| 702 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) |
| 703 | if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i))) |
| 704 | Worklist.push_back(Use); |
| 705 | |
| 706 | // Add users to the worklist which may be simplified now. |
| 707 | for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); |
| 708 | UI != E; ++UI) |
| 709 | Worklist.push_back(cast<Instruction>(*UI)); |
| 710 | I->replaceAllUsesWith(V); |
| 711 | I->eraseFromParent(); |
| 712 | RemoveFromWorklist(I, Worklist); |
| 713 | ++NumSimplify; |
| 714 | } |
| 715 | |
| 716 | |
| 717 | |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 718 | // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has |
| 719 | // the value specified by Val in the specified loop, or we know it does NOT have |
| 720 | // that value. Rewrite any uses of LIC or of properties correlated to it. |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 721 | void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC, |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 722 | Constant *Val, |
| 723 | bool IsEqual) { |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 724 | assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?"); |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 725 | |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 726 | // FIXME: Support correlated properties, like: |
| 727 | // for (...) |
| 728 | // if (li1 < li2) |
| 729 | // ... |
| 730 | // if (li1 > li2) |
| 731 | // ... |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 732 | |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 733 | // NotVal - If Val is a bool, this contains its inverse. |
| 734 | Constant *NotVal = 0; |
| 735 | if (ConstantBool *CB = dyn_cast<ConstantBool>(Val)) |
| 736 | NotVal = ConstantBool::get(!CB->getValue()); |
| 737 | |
Chris Lattner | 6e26315 | 2006-02-10 02:30:37 +0000 | [diff] [blame] | 738 | // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches, |
| 739 | // selects, switches. |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 740 | std::vector<User*> Users(LIC->use_begin(), LIC->use_end()); |
Chris Lattner | 6fd1362 | 2006-02-17 00:31:07 +0000 | [diff] [blame^] | 741 | |
| 742 | std::vector<Instruction*> Worklist; |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 743 | |
Chris Lattner | 6fd1362 | 2006-02-17 00:31:07 +0000 | [diff] [blame^] | 744 | // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC |
| 745 | // in the loop with the appropriate one directly. |
| 746 | if (IsEqual || NotVal) { |
| 747 | Value *Replacement = NotVal ? NotVal : Val; |
| 748 | |
| 749 | for (unsigned i = 0, e = Users.size(); i != e; ++i) |
| 750 | if (Instruction *U = cast<Instruction>(Users[i])) { |
| 751 | if (!L->contains(U->getParent())) |
| 752 | continue; |
| 753 | U->replaceUsesOfWith(LIC, Replacement); |
| 754 | Worklist.push_back(U); |
| 755 | } |
| 756 | } else { |
| 757 | // Otherwise, we don't know the precise value of LIC, but we do know that it |
| 758 | // is certainly NOT "Val". As such, simplify any uses in the loop that we |
| 759 | // can. This case occurs when we unswitch switch statements. |
| 760 | for (unsigned i = 0, e = Users.size(); i != e; ++i) |
| 761 | if (Instruction *U = cast<Instruction>(Users[i])) { |
| 762 | if (!L->contains(U->getParent())) |
| 763 | continue; |
| 764 | |
| 765 | Worklist.push_back(U); |
| 766 | |
Chris Lattner | fa335f6 | 2006-02-16 19:36:22 +0000 | [diff] [blame] | 767 | // If we know that LIC is not Val, use this info to simplify code. |
| 768 | if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) { |
| 769 | for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) { |
| 770 | if (SI->getCaseValue(i) == Val) { |
| 771 | // Found a dead case value. Don't remove PHI nodes in the |
| 772 | // successor if they become single-entry, those PHI nodes may |
| 773 | // be in the Users list. |
| 774 | SI->getSuccessor(i)->removePredecessor(SI->getParent(), true); |
| 775 | SI->removeCase(i); |
| 776 | break; |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 777 | } |
| 778 | } |
Chris Lattner | fbadd7e | 2006-02-11 00:43:37 +0000 | [diff] [blame] | 779 | } |
Chris Lattner | 6fd1362 | 2006-02-17 00:31:07 +0000 | [diff] [blame^] | 780 | |
| 781 | // TODO: We could do other simplifications, for example, turning |
| 782 | // LIC == Val -> false. |
Chris Lattner | fa335f6 | 2006-02-16 19:36:22 +0000 | [diff] [blame] | 783 | } |
Chris Lattner | 6fd1362 | 2006-02-17 00:31:07 +0000 | [diff] [blame^] | 784 | } |
| 785 | |
| 786 | // Okay, now that we have simplified some instructions in the loop, walk over |
| 787 | // it and constant prop, dce, and fold control flow where possible. Note that |
| 788 | // this is effectively a very simple loop-structure-aware optimizer. |
| 789 | while (!Worklist.empty()) { |
| 790 | Instruction *I = Worklist.back(); |
| 791 | Worklist.pop_back(); |
| 792 | |
| 793 | // Simple constant folding. |
| 794 | if (Constant *C = ConstantFoldInstruction(I)) { |
| 795 | ReplaceUsesOfWith(I, C, Worklist); |
| 796 | continue; |
Chris Lattner | fa335f6 | 2006-02-16 19:36:22 +0000 | [diff] [blame] | 797 | } |
Chris Lattner | 6fd1362 | 2006-02-17 00:31:07 +0000 | [diff] [blame^] | 798 | |
| 799 | // Simple DCE. |
| 800 | if (isInstructionTriviallyDead(I)) { |
| 801 | DEBUG(std::cerr << "Remove dead instruction '" << *I); |
| 802 | |
| 803 | // Add uses to the worklist, which may be dead now. |
| 804 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) |
| 805 | if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i))) |
| 806 | Worklist.push_back(Use); |
| 807 | I->eraseFromParent(); |
| 808 | RemoveFromWorklist(I, Worklist); |
| 809 | ++NumSimplify; |
| 810 | continue; |
| 811 | } |
| 812 | |
| 813 | // Special case hacks that appear commonly in unswitched code. |
| 814 | switch (I->getOpcode()) { |
| 815 | case Instruction::Select: |
| 816 | if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(0))) { |
| 817 | ReplaceUsesOfWith(I, I->getOperand(!CB->getValue()+1), Worklist); |
| 818 | continue; |
| 819 | } |
| 820 | break; |
| 821 | case Instruction::And: |
| 822 | if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS |
| 823 | cast<BinaryOperator>(I)->swapOperands(); |
| 824 | if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) { |
| 825 | if (CB->getValue()) // X & 1 -> X |
| 826 | ReplaceUsesOfWith(I, I->getOperand(0), Worklist); |
| 827 | else // X & 0 -> 0 |
| 828 | ReplaceUsesOfWith(I, I->getOperand(1), Worklist); |
| 829 | continue; |
| 830 | } |
| 831 | break; |
| 832 | case Instruction::Or: |
| 833 | if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS |
| 834 | cast<BinaryOperator>(I)->swapOperands(); |
| 835 | if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) { |
| 836 | if (CB->getValue()) // X | 1 -> 1 |
| 837 | ReplaceUsesOfWith(I, I->getOperand(1), Worklist); |
| 838 | else // X | 0 -> X |
| 839 | ReplaceUsesOfWith(I, I->getOperand(0), Worklist); |
| 840 | continue; |
| 841 | } |
| 842 | break; |
| 843 | case Instruction::Br: { |
| 844 | BranchInst *BI = cast<BranchInst>(I); |
| 845 | if (BI->isUnconditional()) { |
| 846 | // If BI's parent is the only pred of the successor, fold the two blocks |
| 847 | // together. |
| 848 | BasicBlock *Pred = BI->getParent(); |
| 849 | BasicBlock *Succ = BI->getSuccessor(0); |
| 850 | BasicBlock *SinglePred = Succ->getSinglePredecessor(); |
| 851 | if (!SinglePred) continue; // Nothing to do. |
| 852 | assert(SinglePred == Pred && "CFG broken"); |
| 853 | |
| 854 | DEBUG(std::cerr << "Merging blocks: " << Pred->getName() << " <- " |
| 855 | << Succ->getName() << "\n"); |
| 856 | |
| 857 | // Resolve any single entry PHI nodes in Succ. |
| 858 | while (PHINode *PN = dyn_cast<PHINode>(Succ->begin())) |
| 859 | ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist); |
| 860 | |
| 861 | // Move all of the successor contents from Succ to Pred. |
| 862 | Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(), |
| 863 | Succ->end()); |
| 864 | BI->eraseFromParent(); |
| 865 | RemoveFromWorklist(BI, Worklist); |
| 866 | |
| 867 | // If Succ has any successors with PHI nodes, update them to have |
| 868 | // entries coming from Pred instead of Succ. |
| 869 | Succ->replaceAllUsesWith(Pred); |
| 870 | |
| 871 | // Remove Succ from the loop tree. |
| 872 | LI->removeBlock(Succ); |
| 873 | Succ->eraseFromParent(); |
| 874 | break; |
| 875 | } |
| 876 | break; |
| 877 | } |
| 878 | } |
| 879 | } |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 880 | } |