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