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