1 //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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:
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.
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.
27 //===----------------------------------------------------------------------===//
29 #define DEBUG_TYPE "loop-unswitch"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Constants.h"
32 #include "llvm/DerivedTypes.h"
33 #include "llvm/Function.h"
34 #include "llvm/Instructions.h"
35 #include "llvm/Analysis/ConstantFolding.h"
36 #include "llvm/Analysis/LoopInfo.h"
37 #include "llvm/Analysis/LoopPass.h"
38 #include "llvm/Analysis/Dominators.h"
39 #include "llvm/Transforms/Utils/Cloning.h"
40 #include "llvm/Transforms/Utils/Local.h"
41 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
42 #include "llvm/ADT/Statistic.h"
43 #include "llvm/ADT/SmallPtrSet.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/Debug.h"
51 STATISTIC(NumBranches
, "Number of branches unswitched");
52 STATISTIC(NumSwitches
, "Number of switches unswitched");
53 STATISTIC(NumSelects
, "Number of selects unswitched");
54 STATISTIC(NumTrivial
, "Number of unswitches that are trivial");
55 STATISTIC(NumSimplify
, "Number of simplifications of unswitched code");
59 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
60 cl::init(10), cl::Hidden
);
62 class VISIBILITY_HIDDEN LoopUnswitch
: public LoopPass
{
63 LoopInfo
*LI
; // Loop information
66 // LoopProcessWorklist - Used to check if second loop needs processing
67 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
68 std::vector
<Loop
*> LoopProcessWorklist
;
69 SmallPtrSet
<Value
*,8> UnswitchedVals
;
74 DominanceFrontier
*DF
;
77 /// LoopDF - Loop's dominance frontier. This set is a collection of
78 /// loop exiting blocks' DF member blocks. However this does set does not
79 /// includes basic blocks that are inside loop.
80 SmallPtrSet
<BasicBlock
*, 8> LoopDF
;
82 /// OrigLoopExitMap - This is used to map loop exiting block with
83 /// corresponding loop exit block, before updating CFG.
84 DenseMap
<BasicBlock
*, BasicBlock
*> OrigLoopExitMap
;
86 static char ID
; // Pass ID, replacement for typeid
87 explicit LoopUnswitch(bool Os
= false) :
88 LoopPass((intptr_t)&ID
), OptimizeForSize(Os
), redoLoop(false) {}
90 bool runOnLoop(Loop
*L
, LPPassManager
&LPM
);
91 bool processLoop(Loop
*L
);
93 /// This transformation requires natural loop information & requires that
94 /// loop preheaders be inserted into the CFG...
96 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
97 AU
.addRequiredID(LoopSimplifyID
);
98 AU
.addPreservedID(LoopSimplifyID
);
99 AU
.addRequired
<LoopInfo
>();
100 AU
.addPreserved
<LoopInfo
>();
101 AU
.addRequiredID(LCSSAID
);
102 AU
.addPreservedID(LCSSAID
);
103 AU
.addPreserved
<DominatorTree
>();
104 AU
.addPreserved
<DominanceFrontier
>();
109 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
111 void RemoveLoopFromWorklist(Loop
*L
) {
112 std::vector
<Loop
*>::iterator I
= std::find(LoopProcessWorklist
.begin(),
113 LoopProcessWorklist
.end(), L
);
114 if (I
!= LoopProcessWorklist
.end())
115 LoopProcessWorklist
.erase(I
);
118 /// Split all of the edges from inside the loop to their exit blocks. Update
119 /// the appropriate Phi nodes as we do so.
120 void SplitExitEdges(Loop
*L
, const SmallVector
<BasicBlock
*, 8> &ExitBlocks
,
121 SmallVector
<BasicBlock
*, 8> &MiddleBlocks
);
123 /// If BB's dominance frontier has a member that is not part of loop L then
124 /// remove it. Add NewDFMember in BB's dominance frontier.
125 void ReplaceLoopExternalDFMember(Loop
*L
, BasicBlock
*BB
,
126 BasicBlock
*NewDFMember
);
128 bool UnswitchIfProfitable(Value
*LoopCond
, Constant
*Val
,Loop
*L
);
129 unsigned getLoopUnswitchCost(Loop
*L
, Value
*LIC
);
130 void UnswitchTrivialCondition(Loop
*L
, Value
*Cond
, Constant
*Val
,
131 BasicBlock
*ExitBlock
);
132 void UnswitchNontrivialCondition(Value
*LIC
, Constant
*OnVal
, Loop
*L
);
134 void RewriteLoopBodyWithConditionConstant(Loop
*L
, Value
*LIC
,
135 Constant
*Val
, bool isEqual
);
137 void EmitPreheaderBranchOnCondition(Value
*LIC
, Constant
*Val
,
138 BasicBlock
*TrueDest
,
139 BasicBlock
*FalseDest
,
140 Instruction
*InsertPt
);
142 void SimplifyCode(std::vector
<Instruction
*> &Worklist
, Loop
*L
);
143 void RemoveBlockIfDead(BasicBlock
*BB
,
144 std::vector
<Instruction
*> &Worklist
, Loop
*l
);
145 void RemoveLoopFromHierarchy(Loop
*L
);
147 char LoopUnswitch::ID
= 0;
148 RegisterPass
<LoopUnswitch
> X("loop-unswitch", "Unswitch loops");
151 LoopPass
*llvm::createLoopUnswitchPass(bool Os
) {
152 return new LoopUnswitch(Os
);
155 /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
156 /// invariant in the loop, or has an invariant piece, return the invariant.
157 /// Otherwise, return null.
158 static Value
*FindLIVLoopCondition(Value
*Cond
, Loop
*L
, bool &Changed
) {
159 // Constants should be folded, not unswitched on!
160 if (isa
<Constant
>(Cond
)) return false;
162 // TODO: Handle: br (VARIANT|INVARIANT).
163 // TODO: Hoist simple expressions out of loops.
164 if (L
->isLoopInvariant(Cond
)) return Cond
;
166 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(Cond
))
167 if (BO
->getOpcode() == Instruction::And
||
168 BO
->getOpcode() == Instruction::Or
) {
169 // If either the left or right side is invariant, we can unswitch on this,
170 // which will cause the branch to go away in one loop and the condition to
171 // simplify in the other one.
172 if (Value
*LHS
= FindLIVLoopCondition(BO
->getOperand(0), L
, Changed
))
174 if (Value
*RHS
= FindLIVLoopCondition(BO
->getOperand(1), L
, Changed
))
181 bool LoopUnswitch::runOnLoop(Loop
*L
, LPPassManager
&LPM_Ref
) {
182 LI
= &getAnalysis
<LoopInfo
>();
184 DF
= getAnalysisToUpdate
<DominanceFrontier
>();
185 DT
= getAnalysisToUpdate
<DominatorTree
>();
187 bool Changed
= false;
191 Changed
|= processLoop(L
);
197 /// processLoop - Do actual work and unswitch loop if possible and profitable.
198 bool LoopUnswitch::processLoop(Loop
*L
) {
199 assert(L
->isLCSSAForm());
200 bool Changed
= false;
202 // Loop over all of the basic blocks in the loop. If we find an interior
203 // block that is branching on a loop-invariant condition, we can unswitch this
205 for (Loop::block_iterator I
= L
->block_begin(), E
= L
->block_end();
207 TerminatorInst
*TI
= (*I
)->getTerminator();
208 if (BranchInst
*BI
= dyn_cast
<BranchInst
>(TI
)) {
209 // If this isn't branching on an invariant condition, we can't unswitch
211 if (BI
->isConditional()) {
212 // See if this, or some part of it, is loop invariant. If so, we can
213 // unswitch on it if we desire.
214 Value
*LoopCond
= FindLIVLoopCondition(BI
->getCondition(), L
, Changed
);
215 if (LoopCond
&& UnswitchIfProfitable(LoopCond
, ConstantInt::getTrue(),
221 } else if (SwitchInst
*SI
= dyn_cast
<SwitchInst
>(TI
)) {
222 Value
*LoopCond
= FindLIVLoopCondition(SI
->getCondition(), L
, Changed
);
223 if (LoopCond
&& SI
->getNumCases() > 1) {
224 // Find a value to unswitch on:
225 // FIXME: this should chose the most expensive case!
226 Constant
*UnswitchVal
= SI
->getCaseValue(1);
227 // Do not process same value again and again.
228 if (!UnswitchedVals
.insert(UnswitchVal
))
231 if (UnswitchIfProfitable(LoopCond
, UnswitchVal
, L
)) {
238 // Scan the instructions to check for unswitchable values.
239 for (BasicBlock::iterator BBI
= (*I
)->begin(), E
= (*I
)->end();
241 if (SelectInst
*SI
= dyn_cast
<SelectInst
>(BBI
)) {
242 Value
*LoopCond
= FindLIVLoopCondition(SI
->getCondition(), L
, Changed
);
243 if (LoopCond
&& UnswitchIfProfitable(LoopCond
, ConstantInt::getTrue(),
251 assert(L
->isLCSSAForm());
256 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
257 /// 1. Exit the loop with no side effects.
258 /// 2. Branch to the latch block with no side-effects.
260 /// If these conditions are true, we return true and set ExitBB to the block we
263 static bool isTrivialLoopExitBlockHelper(Loop
*L
, BasicBlock
*BB
,
265 std::set
<BasicBlock
*> &Visited
) {
266 if (!Visited
.insert(BB
).second
) {
267 // Already visited and Ok, end of recursion.
269 } else if (!L
->contains(BB
)) {
270 // Otherwise, this is a loop exit, this is fine so long as this is the
272 if (ExitBB
!= 0) return false;
277 // Otherwise, this is an unvisited intra-loop node. Check all successors.
278 for (succ_iterator SI
= succ_begin(BB
), E
= succ_end(BB
); SI
!= E
; ++SI
) {
279 // Check to see if the successor is a trivial loop exit.
280 if (!isTrivialLoopExitBlockHelper(L
, *SI
, ExitBB
, Visited
))
284 // Okay, everything after this looks good, check to make sure that this block
285 // doesn't include any side effects.
286 for (BasicBlock::iterator I
= BB
->begin(), E
= BB
->end(); I
!= E
; ++I
)
287 if (I
->mayWriteToMemory())
293 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
294 /// leads to an exit from the specified loop, and has no side-effects in the
295 /// process. If so, return the block that is exited to, otherwise return null.
296 static BasicBlock
*isTrivialLoopExitBlock(Loop
*L
, BasicBlock
*BB
) {
297 std::set
<BasicBlock
*> Visited
;
298 Visited
.insert(L
->getHeader()); // Branches to header are ok.
299 BasicBlock
*ExitBB
= 0;
300 if (isTrivialLoopExitBlockHelper(L
, BB
, ExitBB
, Visited
))
305 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
306 /// trivial: that is, that the condition controls whether or not the loop does
307 /// anything at all. If this is a trivial condition, unswitching produces no
308 /// code duplications (equivalently, it produces a simpler loop and a new empty
309 /// loop, which gets deleted).
311 /// If this is a trivial condition, return true, otherwise return false. When
312 /// returning true, this sets Cond and Val to the condition that controls the
313 /// trivial condition: when Cond dynamically equals Val, the loop is known to
314 /// exit. Finally, this sets LoopExit to the BB that the loop exits to when
317 static bool IsTrivialUnswitchCondition(Loop
*L
, Value
*Cond
, Constant
**Val
= 0,
318 BasicBlock
**LoopExit
= 0) {
319 BasicBlock
*Header
= L
->getHeader();
320 TerminatorInst
*HeaderTerm
= Header
->getTerminator();
322 BasicBlock
*LoopExitBB
= 0;
323 if (BranchInst
*BI
= dyn_cast
<BranchInst
>(HeaderTerm
)) {
324 // If the header block doesn't end with a conditional branch on Cond, we
326 if (!BI
->isConditional() || BI
->getCondition() != Cond
)
329 // Check to see if a successor of the branch is guaranteed to go to the
330 // latch block or exit through a one exit block without having any
331 // side-effects. If so, determine the value of Cond that causes it to do
333 if ((LoopExitBB
= isTrivialLoopExitBlock(L
, BI
->getSuccessor(0)))) {
334 if (Val
) *Val
= ConstantInt::getTrue();
335 } else if ((LoopExitBB
= isTrivialLoopExitBlock(L
, BI
->getSuccessor(1)))) {
336 if (Val
) *Val
= ConstantInt::getFalse();
338 } else if (SwitchInst
*SI
= dyn_cast
<SwitchInst
>(HeaderTerm
)) {
339 // If this isn't a switch on Cond, we can't handle it.
340 if (SI
->getCondition() != Cond
) return false;
342 // Check to see if a successor of the switch is guaranteed to go to the
343 // latch block or exit through a one exit block without having any
344 // side-effects. If so, determine the value of Cond that causes it to do
345 // this. Note that we can't trivially unswitch on the default case.
346 for (unsigned i
= 1, e
= SI
->getNumSuccessors(); i
!= e
; ++i
)
347 if ((LoopExitBB
= isTrivialLoopExitBlock(L
, SI
->getSuccessor(i
)))) {
348 // Okay, we found a trivial case, remember the value that is trivial.
349 if (Val
) *Val
= SI
->getCaseValue(i
);
354 // If we didn't find a single unique LoopExit block, or if the loop exit block
355 // contains phi nodes, this isn't trivial.
356 if (!LoopExitBB
|| isa
<PHINode
>(LoopExitBB
->begin()))
357 return false; // Can't handle this.
359 if (LoopExit
) *LoopExit
= LoopExitBB
;
361 // We already know that nothing uses any scalar values defined inside of this
362 // loop. As such, we just have to check to see if this loop will execute any
363 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
364 // part of the loop that the code *would* execute. We already checked the
365 // tail, check the header now.
366 for (BasicBlock::iterator I
= Header
->begin(), E
= Header
->end(); I
!= E
; ++I
)
367 if (I
->mayWriteToMemory())
372 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
373 /// we choose to unswitch the specified loop on the specified value.
375 unsigned LoopUnswitch::getLoopUnswitchCost(Loop
*L
, Value
*LIC
) {
376 // If the condition is trivial, always unswitch. There is no code growth for
378 if (IsTrivialUnswitchCondition(L
, LIC
))
381 // FIXME: This is really overly conservative. However, more liberal
382 // estimations have thus far resulted in excessive unswitching, which is bad
383 // both in compile time and in code size. This should be replaced once
384 // someone figures out how a good estimation.
385 return L
->getBlocks().size();
388 // FIXME: this is brain dead. It should take into consideration code
390 for (Loop::block_iterator I
= L
->block_begin(), E
= L
->block_end();
393 // Do not include empty blocks in the cost calculation. This happen due to
394 // loop canonicalization and will be removed.
395 if (BB
->begin() == BasicBlock::iterator(BB
->getTerminator()))
398 // Count basic blocks.
405 /// UnswitchIfProfitable - We have found that we can unswitch L when
406 /// LoopCond == Val to simplify the loop. If we decide that this is profitable,
407 /// unswitch the loop, reprocess the pieces, then return true.
408 bool LoopUnswitch::UnswitchIfProfitable(Value
*LoopCond
, Constant
*Val
,Loop
*L
){
409 // Check to see if it would be profitable to unswitch this loop.
410 unsigned Cost
= getLoopUnswitchCost(L
, LoopCond
);
412 // Do not do non-trivial unswitch while optimizing for size.
413 if (Cost
&& OptimizeForSize
)
416 if (Cost
> Threshold
) {
417 // FIXME: this should estimate growth by the amount of code shared by the
418 // resultant unswitched loops.
420 DOUT
<< "NOT unswitching loop %"
421 << L
->getHeader()->getName() << ", cost too high: "
422 << L
->getBlocks().size() << "\n";
426 // If this is a trivial condition to unswitch (which results in no code
427 // duplication), do it now.
429 BasicBlock
*ExitBlock
;
430 if (IsTrivialUnswitchCondition(L
, LoopCond
, &CondVal
, &ExitBlock
)) {
431 UnswitchTrivialCondition(L
, LoopCond
, CondVal
, ExitBlock
);
433 UnswitchNontrivialCondition(LoopCond
, Val
, L
);
439 // RemapInstruction - Convert the instruction operands from referencing the
440 // current values into those specified by ValueMap.
442 static inline void RemapInstruction(Instruction
*I
,
443 DenseMap
<const Value
*, Value
*> &ValueMap
) {
444 for (unsigned op
= 0, E
= I
->getNumOperands(); op
!= E
; ++op
) {
445 Value
*Op
= I
->getOperand(op
);
446 DenseMap
<const Value
*, Value
*>::iterator It
= ValueMap
.find(Op
);
447 if (It
!= ValueMap
.end()) Op
= It
->second
;
448 I
->setOperand(op
, Op
);
452 // CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator
455 // If Orig block's immediate dominator is mapped in VM then use corresponding
456 // immediate dominator from the map. Otherwise Orig block's dominator is also
457 // NewBB's dominator.
459 // OrigPreheader is loop pre-header before this pass started
460 // updating CFG. NewPrehader is loops new pre-header. However, after CFG
461 // manipulation, loop L may not exist. So rely on input parameter NewPreheader.
462 void CloneDomInfo(BasicBlock
*NewBB
, BasicBlock
*Orig
,
463 BasicBlock
*NewPreheader
, BasicBlock
*OrigPreheader
,
464 BasicBlock
*OrigHeader
,
465 DominatorTree
*DT
, DominanceFrontier
*DF
,
466 DenseMap
<const Value
*, Value
*> &VM
) {
468 // If NewBB alreay has found its place in domiantor tree then no need to do
470 if (DT
->getNode(NewBB
))
473 // If Orig does not have any immediate domiantor then its clone, NewBB, does
474 // not need any immediate dominator.
475 DomTreeNode
*OrigNode
= DT
->getNode(Orig
);
478 DomTreeNode
*OrigIDomNode
= OrigNode
->getIDom();
482 BasicBlock
*OrigIDom
= NULL
;
484 // If Orig is original loop header then its immediate dominator is
486 if (Orig
== OrigHeader
)
487 OrigIDom
= NewPreheader
;
489 // If Orig is new pre-header then its immediate dominator is
490 // original pre-header.
491 else if (Orig
== NewPreheader
)
492 OrigIDom
= OrigPreheader
;
494 // Other as DT to find Orig's immediate dominator.
496 OrigIDom
= OrigIDomNode
->getBlock();
498 // Initially use Orig's immediate dominator as NewBB's immediate dominator.
499 BasicBlock
*NewIDom
= OrigIDom
;
500 DenseMap
<const Value
*, Value
*>::iterator I
= VM
.find(OrigIDom
);
502 NewIDom
= cast
<BasicBlock
>(I
->second
);
504 // If NewIDom does not have corresponding dominatore tree node then
506 if (!DT
->getNode(NewIDom
))
507 CloneDomInfo(NewIDom
, OrigIDom
, NewPreheader
, OrigPreheader
,
508 OrigHeader
, DT
, DF
, VM
);
511 DT
->addNewBlock(NewBB
, NewIDom
);
513 // Copy cloned dominance frontiner set
514 DominanceFrontier::DomSetType NewDFSet
;
516 DominanceFrontier::iterator DFI
= DF
->find(Orig
);
517 if ( DFI
!= DF
->end()) {
518 DominanceFrontier::DomSetType S
= DFI
->second
;
519 for (DominanceFrontier::DomSetType::iterator I
= S
.begin(), E
= S
.end();
522 DenseMap
<const Value
*, Value
*>::iterator IDM
= VM
.find(BB
);
524 NewDFSet
.insert(cast
<BasicBlock
>(IDM
->second
));
529 DF
->addBasicBlock(NewBB
, NewDFSet
);
533 /// CloneLoop - Recursively clone the specified loop and all of its children,
534 /// mapping the blocks with the specified map.
535 static Loop
*CloneLoop(Loop
*L
, Loop
*PL
, DenseMap
<const Value
*, Value
*> &VM
,
536 LoopInfo
*LI
, LPPassManager
*LPM
) {
537 Loop
*New
= new Loop();
539 LPM
->insertLoop(New
, PL
);
541 // Add all of the blocks in L to the new loop.
542 for (Loop::block_iterator I
= L
->block_begin(), E
= L
->block_end();
544 if (LI
->getLoopFor(*I
) == L
)
545 New
->addBasicBlockToLoop(cast
<BasicBlock
>(VM
[*I
]), *LI
);
547 // Add all of the subloops to the new loop.
548 for (Loop::iterator I
= L
->begin(), E
= L
->end(); I
!= E
; ++I
)
549 CloneLoop(*I
, New
, VM
, LI
, LPM
);
554 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
555 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
556 /// code immediately before InsertPt.
557 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value
*LIC
, Constant
*Val
,
558 BasicBlock
*TrueDest
,
559 BasicBlock
*FalseDest
,
560 Instruction
*InsertPt
) {
561 // Insert a conditional branch on LIC to the two preheaders. The original
562 // code is the true version and the new code is the false version.
563 Value
*BranchVal
= LIC
;
564 if (!isa
<ConstantInt
>(Val
) || Val
->getType() != Type::Int1Ty
)
565 BranchVal
= new ICmpInst(ICmpInst::ICMP_EQ
, LIC
, Val
, "tmp", InsertPt
);
566 else if (Val
!= ConstantInt::getTrue())
567 // We want to enter the new loop when the condition is true.
568 std::swap(TrueDest
, FalseDest
);
570 // Insert the new branch.
571 new BranchInst(TrueDest
, FalseDest
, BranchVal
, InsertPt
);
576 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
577 /// condition in it (a cond branch from its header block to its latch block,
578 /// where the path through the loop that doesn't execute its body has no
579 /// side-effects), unswitch it. This doesn't involve any code duplication, just
580 /// moving the conditional branch outside of the loop and updating loop info.
581 void LoopUnswitch::UnswitchTrivialCondition(Loop
*L
, Value
*Cond
,
583 BasicBlock
*ExitBlock
) {
584 DOUT
<< "loop-unswitch: Trivial-Unswitch loop %"
585 << L
->getHeader()->getName() << " [" << L
->getBlocks().size()
586 << " blocks] in Function " << L
->getHeader()->getParent()->getName()
587 << " on cond: " << *Val
<< " == " << *Cond
<< "\n";
589 // First step, split the preheader, so that we know that there is a safe place
590 // to insert the conditional branch. We will change 'OrigPH' to have a
591 // conditional branch on Cond.
592 BasicBlock
*OrigPH
= L
->getLoopPreheader();
593 BasicBlock
*NewPH
= SplitEdge(OrigPH
, L
->getHeader(), this);
595 // Now that we have a place to insert the conditional branch, create a place
596 // to branch to: this is the exit block out of the loop that we should
599 // Split this block now, so that the loop maintains its exit block, and so
600 // that the jump from the preheader can execute the contents of the exit block
601 // without actually branching to it (the exit block should be dominated by the
602 // loop header, not the preheader).
603 assert(!L
->contains(ExitBlock
) && "Exit block is in the loop?");
604 BasicBlock
*NewExit
= SplitBlock(ExitBlock
, ExitBlock
->begin(), this);
606 // Okay, now we have a position to branch from and a position to branch to,
607 // insert the new conditional branch.
608 EmitPreheaderBranchOnCondition(Cond
, Val
, NewExit
, NewPH
,
609 OrigPH
->getTerminator());
610 LPM
->deleteSimpleAnalysisValue(OrigPH
->getTerminator(), L
);
611 OrigPH
->getTerminator()->eraseFromParent();
613 // We need to reprocess this loop, it could be unswitched again.
616 // Now that we know that the loop is never entered when this condition is a
617 // particular value, rewrite the loop with this info. We know that this will
618 // at least eliminate the old branch.
619 RewriteLoopBodyWithConditionConstant(L
, Cond
, Val
, false);
623 /// ReplaceLoopExternalDFMember -
624 /// If BB's dominance frontier has a member that is not part of loop L then
625 /// remove it. Add NewDFMember in BB's dominance frontier.
626 void LoopUnswitch::ReplaceLoopExternalDFMember(Loop
*L
, BasicBlock
*BB
,
627 BasicBlock
*NewDFMember
) {
629 DominanceFrontier::iterator DFI
= DF
->find(BB
);
630 if (DFI
== DF
->end())
633 DominanceFrontier::DomSetType
&DFSet
= DFI
->second
;
634 for (DominanceFrontier::DomSetType::iterator DI
= DFSet
.begin(),
635 DE
= DFSet
.end(); DI
!= DE
;) {
636 BasicBlock
*B
= *DI
++;
640 DF
->removeFromFrontier(DFI
, B
);
644 DF
->addToFrontier(DFI
, NewDFMember
);
648 /// Split all of the edges from inside the loop to their exit blocks. Update
649 /// the appropriate Phi nodes as we do so.
650 void LoopUnswitch::SplitExitEdges(Loop
*L
, const SmallVector
<BasicBlock
*, 8> &ExitBlocks
,
651 SmallVector
<BasicBlock
*, 8> &MiddleBlocks
) {
653 for (unsigned i
= 0, e
= ExitBlocks
.size(); i
!= e
; ++i
) {
654 BasicBlock
*ExitBlock
= ExitBlocks
[i
];
655 std::vector
<BasicBlock
*> Preds(pred_begin(ExitBlock
), pred_end(ExitBlock
));
657 for (unsigned j
= 0, e
= Preds
.size(); j
!= e
; ++j
) {
658 BasicBlock
* MiddleBlock
= SplitEdge(Preds
[j
], ExitBlock
, this);
659 MiddleBlocks
.push_back(MiddleBlock
);
660 BasicBlock
* StartBlock
= Preds
[j
];
661 BasicBlock
* EndBlock
;
662 if (MiddleBlock
->getSinglePredecessor() == ExitBlock
) {
663 EndBlock
= MiddleBlock
;
664 MiddleBlock
= EndBlock
->getSinglePredecessor();;
666 EndBlock
= ExitBlock
;
669 OrigLoopExitMap
[StartBlock
] = EndBlock
;
671 std::set
<PHINode
*> InsertedPHIs
;
672 PHINode
* OldLCSSA
= 0;
673 for (BasicBlock::iterator I
= EndBlock
->begin();
674 (OldLCSSA
= dyn_cast
<PHINode
>(I
)); ++I
) {
675 Value
* OldValue
= OldLCSSA
->getIncomingValueForBlock(MiddleBlock
);
676 PHINode
* NewLCSSA
= new PHINode(OldLCSSA
->getType(),
677 OldLCSSA
->getName() + ".us-lcssa",
678 MiddleBlock
->getTerminator());
679 NewLCSSA
->addIncoming(OldValue
, StartBlock
);
680 OldLCSSA
->setIncomingValue(OldLCSSA
->getBasicBlockIndex(MiddleBlock
),
682 InsertedPHIs
.insert(NewLCSSA
);
685 BasicBlock::iterator InsertPt
= EndBlock
->begin();
686 while (dyn_cast
<PHINode
>(InsertPt
)) ++InsertPt
;
687 for (BasicBlock::iterator I
= MiddleBlock
->begin();
688 (OldLCSSA
= dyn_cast
<PHINode
>(I
)) && InsertedPHIs
.count(OldLCSSA
) == 0;
690 PHINode
*NewLCSSA
= new PHINode(OldLCSSA
->getType(),
691 OldLCSSA
->getName() + ".us-lcssa",
693 OldLCSSA
->replaceAllUsesWith(NewLCSSA
);
694 NewLCSSA
->addIncoming(OldLCSSA
, MiddleBlock
);
698 // StartBlock -- > MiddleBlock -- > EndBlock
699 // StartBlock is loop exiting block. EndBlock will become merge point
700 // of two loop exits after loop unswitch.
702 // If StartBlock's DF member includes a block that is not loop member
703 // then replace that DF member with EndBlock.
705 // If MiddleBlock's DF member includes a block that is not loop member
706 // tnen replace that DF member with EndBlock.
708 ReplaceLoopExternalDFMember(L
, StartBlock
, EndBlock
);
709 ReplaceLoopExternalDFMember(L
, MiddleBlock
, EndBlock
);
716 /// UnswitchNontrivialCondition - We determined that the loop is profitable
717 /// to unswitch when LIC equal Val. Split it into loop versions and test the
718 /// condition outside of either loop. Return the loops created as Out1/Out2.
719 void LoopUnswitch::UnswitchNontrivialCondition(Value
*LIC
, Constant
*Val
,
721 Function
*F
= L
->getHeader()->getParent();
722 DOUT
<< "loop-unswitch: Unswitching loop %"
723 << L
->getHeader()->getName() << " [" << L
->getBlocks().size()
724 << " blocks] in Function " << F
->getName()
725 << " when '" << *Val
<< "' == " << *LIC
<< "\n";
727 // LoopBlocks contains all of the basic blocks of the loop, including the
728 // preheader of the loop, the body of the loop, and the exit blocks of the
729 // loop, in that order.
730 std::vector
<BasicBlock
*> LoopBlocks
;
732 // First step, split the preheader and exit blocks, and add these blocks to
733 // the LoopBlocks list.
734 BasicBlock
*OrigHeader
= L
->getHeader();
735 BasicBlock
*OrigPreheader
= L
->getLoopPreheader();
736 BasicBlock
*NewPreheader
= SplitEdge(OrigPreheader
, L
->getHeader(), this);
737 LoopBlocks
.push_back(NewPreheader
);
739 // We want the loop to come after the preheader, but before the exit blocks.
740 LoopBlocks
.insert(LoopBlocks
.end(), L
->block_begin(), L
->block_end());
742 SmallVector
<BasicBlock
*, 8> ExitBlocks
;
743 L
->getUniqueExitBlocks(ExitBlocks
);
745 // Split all of the edges from inside the loop to their exit blocks. Update
746 // the appropriate Phi nodes as we do so.
747 SmallVector
<BasicBlock
*,8> MiddleBlocks
;
748 SplitExitEdges(L
, ExitBlocks
, MiddleBlocks
);
750 // The exit blocks may have been changed due to edge splitting, recompute.
752 L
->getUniqueExitBlocks(ExitBlocks
);
754 // Add exit blocks to the loop blocks.
755 LoopBlocks
.insert(LoopBlocks
.end(), ExitBlocks
.begin(), ExitBlocks
.end());
757 // Next step, clone all of the basic blocks that make up the loop (including
758 // the loop preheader and exit blocks), keeping track of the mapping between
759 // the instructions and blocks.
760 std::vector
<BasicBlock
*> NewBlocks
;
761 NewBlocks
.reserve(LoopBlocks
.size());
762 DenseMap
<const Value
*, Value
*> ValueMap
;
763 for (unsigned i
= 0, e
= LoopBlocks
.size(); i
!= e
; ++i
) {
764 BasicBlock
*New
= CloneBasicBlock(LoopBlocks
[i
], ValueMap
, ".us", F
);
765 NewBlocks
.push_back(New
);
766 ValueMap
[LoopBlocks
[i
]] = New
; // Keep the BB mapping.
767 LPM
->cloneBasicBlockSimpleAnalysis(LoopBlocks
[i
], New
, L
);
770 // OutSiders are basic block that are dominated by original header and
771 // at the same time they are not part of loop.
772 SmallPtrSet
<BasicBlock
*, 8> OutSiders
;
774 DomTreeNode
*OrigHeaderNode
= DT
->getNode(OrigHeader
);
775 for(std::vector
<DomTreeNode
*>::iterator DI
= OrigHeaderNode
->begin(),
776 DE
= OrigHeaderNode
->end(); DI
!= DE
; ++DI
) {
777 BasicBlock
*B
= (*DI
)->getBlock();
779 DenseMap
<const Value
*, Value
*>::iterator VI
= ValueMap
.find(B
);
780 if (VI
== ValueMap
.end())
785 // Splice the newly inserted blocks into the function right before the
786 // original preheader.
787 F
->getBasicBlockList().splice(LoopBlocks
[0], F
->getBasicBlockList(),
788 NewBlocks
[0], F
->end());
790 // Now we create the new Loop object for the versioned loop.
791 Loop
*NewLoop
= CloneLoop(L
, L
->getParentLoop(), ValueMap
, LI
, LPM
);
792 Loop
*ParentLoop
= L
->getParentLoop();
794 // Make sure to add the cloned preheader and exit blocks to the parent loop
796 ParentLoop
->addBasicBlockToLoop(NewBlocks
[0], *LI
);
799 for (unsigned i
= 0, e
= ExitBlocks
.size(); i
!= e
; ++i
) {
800 BasicBlock
*NewExit
= cast
<BasicBlock
>(ValueMap
[ExitBlocks
[i
]]);
801 // The new exit block should be in the same loop as the old one.
802 if (Loop
*ExitBBLoop
= LI
->getLoopFor(ExitBlocks
[i
]))
803 ExitBBLoop
->addBasicBlockToLoop(NewExit
, *LI
);
805 assert(NewExit
->getTerminator()->getNumSuccessors() == 1 &&
806 "Exit block should have been split to have one successor!");
807 BasicBlock
*ExitSucc
= NewExit
->getTerminator()->getSuccessor(0);
809 // If the successor of the exit block had PHI nodes, add an entry for
812 for (BasicBlock::iterator I
= ExitSucc
->begin();
813 (PN
= dyn_cast
<PHINode
>(I
)); ++I
) {
814 Value
*V
= PN
->getIncomingValueForBlock(ExitBlocks
[i
]);
815 DenseMap
<const Value
*, Value
*>::iterator It
= ValueMap
.find(V
);
816 if (It
!= ValueMap
.end()) V
= It
->second
;
817 PN
->addIncoming(V
, NewExit
);
821 // Rewrite the code to refer to itself.
822 for (unsigned i
= 0, e
= NewBlocks
.size(); i
!= e
; ++i
)
823 for (BasicBlock::iterator I
= NewBlocks
[i
]->begin(),
824 E
= NewBlocks
[i
]->end(); I
!= E
; ++I
)
825 RemapInstruction(I
, ValueMap
);
827 // Rewrite the original preheader to select between versions of the loop.
828 BranchInst
*OldBR
= cast
<BranchInst
>(OrigPreheader
->getTerminator());
829 assert(OldBR
->isUnconditional() && OldBR
->getSuccessor(0) == LoopBlocks
[0] &&
830 "Preheader splitting did not work correctly!");
832 // Emit the new branch that selects between the two versions of this loop.
833 EmitPreheaderBranchOnCondition(LIC
, Val
, NewBlocks
[0], LoopBlocks
[0], OldBR
);
834 LPM
->deleteSimpleAnalysisValue(OldBR
, L
);
835 OldBR
->eraseFromParent();
837 // Update dominator info
840 SmallVector
<BasicBlock
*,4> ExitingBlocks
;
841 L
->getExitingBlocks(ExitingBlocks
);
843 // Clone dominator info for all cloned basic block.
844 for (unsigned i
= 0, e
= LoopBlocks
.size(); i
!= e
; ++i
) {
845 BasicBlock
*LBB
= LoopBlocks
[i
];
846 BasicBlock
*NBB
= NewBlocks
[i
];
847 CloneDomInfo(NBB
, LBB
, NewPreheader
, OrigPreheader
,
848 OrigHeader
, DT
, DF
, ValueMap
);
850 // If LBB's dominance frontier includes DFMember
851 // such that DFMember is also a member of LoopDF then
852 // - Remove DFMember from LBB's dominance frontier
853 // - Copy loop exiting blocks', that are dominated by BB, dominance frontier
854 // member in BB's dominance frontier
856 DominanceFrontier::iterator LBBI
= DF
->find(LBB
);
857 DominanceFrontier::iterator NBBI
= DF
->find(NBB
);
858 if (LBBI
== DF
->end())
861 DominanceFrontier::DomSetType
&LBSet
= LBBI
->second
;
862 for (DominanceFrontier::DomSetType::iterator LI
= LBSet
.begin(),
863 LE
= LBSet
.end(); LI
!= LE
; /* NULL */) {
864 BasicBlock
*B
= *LI
++;
865 if (B
== LBB
&& B
== L
->getHeader())
867 bool removeB
= false;
868 if (!LoopDF
.count(B
))
871 // If LBB dominates loop exits then insert loop exit block's DF
873 for(SmallVector
<BasicBlock
*, 4>::iterator LExitI
= ExitingBlocks
.begin(),
874 LExitE
= ExitingBlocks
.end(); LExitI
!= LExitE
; ++LExitI
) {
875 BasicBlock
*E
= *LExitI
;
877 if (!DT
->dominates(LBB
,E
))
880 DenseMap
<BasicBlock
*, BasicBlock
*>::iterator DFBI
=
881 OrigLoopExitMap
.find(E
);
882 if (DFBI
== OrigLoopExitMap
.end())
885 BasicBlock
*DFB
= DFBI
->second
;
886 DF
->addToFrontier(LBBI
, DFB
);
887 DF
->addToFrontier(NBBI
, DFB
);
891 // If B's replacement is inserted in DF then now is the time to remove B.
893 DF
->removeFromFrontier(LBBI
, B
);
895 DF
->removeFromFrontier(NBBI
, cast
<BasicBlock
>(ValueMap
[B
]));
897 DF
->removeFromFrontier(NBBI
, B
);
903 // MiddleBlocks are dominated by original pre header. SplitEdge updated
904 // MiddleBlocks' dominance frontier appropriately.
905 for (unsigned i
= 0, e
= MiddleBlocks
.size(); i
!= e
; ++i
) {
906 BasicBlock
*MBB
= MiddleBlocks
[i
];
907 if (!MBB
->getSinglePredecessor())
908 DT
->changeImmediateDominator(MBB
, OrigPreheader
);
911 // All Outsiders are now dominated by original pre header.
912 for (SmallPtrSet
<BasicBlock
*, 8>::iterator OI
= OutSiders
.begin(),
913 OE
= OutSiders
.end(); OI
!= OE
; ++OI
) {
914 BasicBlock
*OB
= *OI
;
915 DT
->changeImmediateDominator(OB
, OrigPreheader
);
918 // New loop headers are dominated by original preheader
919 DT
->changeImmediateDominator(NewBlocks
[0], OrigPreheader
);
920 DT
->changeImmediateDominator(LoopBlocks
[0], OrigPreheader
);
923 LoopProcessWorklist
.push_back(NewLoop
);
926 // Now we rewrite the original code to know that the condition is true and the
927 // new code to know that the condition is false.
928 RewriteLoopBodyWithConditionConstant(L
, LIC
, Val
, false);
930 // It's possible that simplifying one loop could cause the other to be
931 // deleted. If so, don't simplify it.
932 if (!LoopProcessWorklist
.empty() && LoopProcessWorklist
.back() == NewLoop
)
933 RewriteLoopBodyWithConditionConstant(NewLoop
, LIC
, Val
, true);
936 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
938 static void RemoveFromWorklist(Instruction
*I
,
939 std::vector
<Instruction
*> &Worklist
) {
940 std::vector
<Instruction
*>::iterator WI
= std::find(Worklist
.begin(),
942 while (WI
!= Worklist
.end()) {
943 unsigned Offset
= WI
-Worklist
.begin();
945 WI
= std::find(Worklist
.begin()+Offset
, Worklist
.end(), I
);
949 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
950 /// program, replacing all uses with V and update the worklist.
951 static void ReplaceUsesOfWith(Instruction
*I
, Value
*V
,
952 std::vector
<Instruction
*> &Worklist
,
953 Loop
*L
, LPPassManager
*LPM
) {
954 DOUT
<< "Replace with '" << *V
<< "': " << *I
;
956 // Add uses to the worklist, which may be dead now.
957 for (unsigned i
= 0, e
= I
->getNumOperands(); i
!= e
; ++i
)
958 if (Instruction
*Use
= dyn_cast
<Instruction
>(I
->getOperand(i
)))
959 Worklist
.push_back(Use
);
961 // Add users to the worklist which may be simplified now.
962 for (Value::use_iterator UI
= I
->use_begin(), E
= I
->use_end();
964 Worklist
.push_back(cast
<Instruction
>(*UI
));
965 LPM
->deleteSimpleAnalysisValue(I
, L
);
966 RemoveFromWorklist(I
, Worklist
);
967 I
->replaceAllUsesWith(V
);
968 I
->eraseFromParent();
972 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
973 /// information, and remove any dead successors it has.
975 void LoopUnswitch::RemoveBlockIfDead(BasicBlock
*BB
,
976 std::vector
<Instruction
*> &Worklist
,
978 if (pred_begin(BB
) != pred_end(BB
)) {
979 // This block isn't dead, since an edge to BB was just removed, see if there
980 // are any easy simplifications we can do now.
981 if (BasicBlock
*Pred
= BB
->getSinglePredecessor()) {
982 // If it has one pred, fold phi nodes in BB.
983 while (isa
<PHINode
>(BB
->begin()))
984 ReplaceUsesOfWith(BB
->begin(),
985 cast
<PHINode
>(BB
->begin())->getIncomingValue(0),
988 // If this is the header of a loop and the only pred is the latch, we now
989 // have an unreachable loop.
990 if (Loop
*L
= LI
->getLoopFor(BB
))
991 if (L
->getHeader() == BB
&& L
->contains(Pred
)) {
992 // Remove the branch from the latch to the header block, this makes
993 // the header dead, which will make the latch dead (because the header
994 // dominates the latch).
995 LPM
->deleteSimpleAnalysisValue(Pred
->getTerminator(), L
);
996 Pred
->getTerminator()->eraseFromParent();
997 new UnreachableInst(Pred
);
999 // The loop is now broken, remove it from LI.
1000 RemoveLoopFromHierarchy(L
);
1002 // Reprocess the header, which now IS dead.
1003 RemoveBlockIfDead(BB
, Worklist
, L
);
1007 // If pred ends in a uncond branch, add uncond branch to worklist so that
1008 // the two blocks will get merged.
1009 if (BranchInst
*BI
= dyn_cast
<BranchInst
>(Pred
->getTerminator()))
1010 if (BI
->isUnconditional())
1011 Worklist
.push_back(BI
);
1016 DOUT
<< "Nuking dead block: " << *BB
;
1018 // Remove the instructions in the basic block from the worklist.
1019 for (BasicBlock::iterator I
= BB
->begin(), E
= BB
->end(); I
!= E
; ++I
) {
1020 RemoveFromWorklist(I
, Worklist
);
1022 // Anything that uses the instructions in this basic block should have their
1023 // uses replaced with undefs.
1024 if (!I
->use_empty())
1025 I
->replaceAllUsesWith(UndefValue::get(I
->getType()));
1028 // If this is the edge to the header block for a loop, remove the loop and
1029 // promote all subloops.
1030 if (Loop
*BBLoop
= LI
->getLoopFor(BB
)) {
1031 if (BBLoop
->getLoopLatch() == BB
)
1032 RemoveLoopFromHierarchy(BBLoop
);
1035 // Remove the block from the loop info, which removes it from any loops it
1037 LI
->removeBlock(BB
);
1040 // Remove phi node entries in successors for this block.
1041 TerminatorInst
*TI
= BB
->getTerminator();
1042 std::vector
<BasicBlock
*> Succs
;
1043 for (unsigned i
= 0, e
= TI
->getNumSuccessors(); i
!= e
; ++i
) {
1044 Succs
.push_back(TI
->getSuccessor(i
));
1045 TI
->getSuccessor(i
)->removePredecessor(BB
);
1048 // Unique the successors, remove anything with multiple uses.
1049 std::sort(Succs
.begin(), Succs
.end());
1050 Succs
.erase(std::unique(Succs
.begin(), Succs
.end()), Succs
.end());
1052 // Remove the basic block, including all of the instructions contained in it.
1053 LPM
->deleteSimpleAnalysisValue(BB
, L
);
1054 BB
->eraseFromParent();
1055 // Remove successor blocks here that are not dead, so that we know we only
1056 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
1057 // then getting removed before we revisit them, which is badness.
1059 for (unsigned i
= 0; i
!= Succs
.size(); ++i
)
1060 if (pred_begin(Succs
[i
]) != pred_end(Succs
[i
])) {
1061 // One exception is loop headers. If this block was the preheader for a
1062 // loop, then we DO want to visit the loop so the loop gets deleted.
1063 // We know that if the successor is a loop header, that this loop had to
1064 // be the preheader: the case where this was the latch block was handled
1065 // above and headers can only have two predecessors.
1066 if (!LI
->isLoopHeader(Succs
[i
])) {
1067 Succs
.erase(Succs
.begin()+i
);
1072 for (unsigned i
= 0, e
= Succs
.size(); i
!= e
; ++i
)
1073 RemoveBlockIfDead(Succs
[i
], Worklist
, L
);
1076 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
1077 /// become unwrapped, either because the backedge was deleted, or because the
1078 /// edge into the header was removed. If the edge into the header from the
1079 /// latch block was removed, the loop is unwrapped but subloops are still alive,
1080 /// so they just reparent loops. If the loops are actually dead, they will be
1082 void LoopUnswitch::RemoveLoopFromHierarchy(Loop
*L
) {
1083 LPM
->deleteLoopFromQueue(L
);
1084 RemoveLoopFromWorklist(L
);
1089 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
1090 // the value specified by Val in the specified loop, or we know it does NOT have
1091 // that value. Rewrite any uses of LIC or of properties correlated to it.
1092 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop
*L
, Value
*LIC
,
1095 assert(!isa
<Constant
>(LIC
) && "Why are we unswitching on a constant?");
1097 // FIXME: Support correlated properties, like:
1104 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1105 // selects, switches.
1106 std::vector
<User
*> Users(LIC
->use_begin(), LIC
->use_end());
1107 std::vector
<Instruction
*> Worklist
;
1109 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1110 // in the loop with the appropriate one directly.
1111 if (IsEqual
|| (isa
<ConstantInt
>(Val
) && Val
->getType() == Type::Int1Ty
)) {
1116 Replacement
= ConstantInt::get(Type::Int1Ty
,
1117 !cast
<ConstantInt
>(Val
)->getZExtValue());
1119 for (unsigned i
= 0, e
= Users
.size(); i
!= e
; ++i
)
1120 if (Instruction
*U
= cast
<Instruction
>(Users
[i
])) {
1121 if (!L
->contains(U
->getParent()))
1123 U
->replaceUsesOfWith(LIC
, Replacement
);
1124 Worklist
.push_back(U
);
1127 // Otherwise, we don't know the precise value of LIC, but we do know that it
1128 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1129 // can. This case occurs when we unswitch switch statements.
1130 for (unsigned i
= 0, e
= Users
.size(); i
!= e
; ++i
)
1131 if (Instruction
*U
= cast
<Instruction
>(Users
[i
])) {
1132 if (!L
->contains(U
->getParent()))
1135 Worklist
.push_back(U
);
1137 // If we know that LIC is not Val, use this info to simplify code.
1138 if (SwitchInst
*SI
= dyn_cast
<SwitchInst
>(U
)) {
1139 for (unsigned i
= 1, e
= SI
->getNumCases(); i
!= e
; ++i
) {
1140 if (SI
->getCaseValue(i
) == Val
) {
1141 // Found a dead case value. Don't remove PHI nodes in the
1142 // successor if they become single-entry, those PHI nodes may
1143 // be in the Users list.
1145 // FIXME: This is a hack. We need to keep the successor around
1146 // and hooked up so as to preserve the loop structure, because
1147 // trying to update it is complicated. So instead we preserve the
1148 // loop structure and put the block on an dead code path.
1150 BasicBlock
* Old
= SI
->getParent();
1151 BasicBlock
* Split
= SplitBlock(Old
, SI
, this);
1153 Instruction
* OldTerm
= Old
->getTerminator();
1154 new BranchInst(Split
, SI
->getSuccessor(i
),
1155 ConstantInt::getTrue(), OldTerm
);
1157 LPM
->deleteSimpleAnalysisValue(Old
->getTerminator(), L
);
1158 Old
->getTerminator()->eraseFromParent();
1161 for (BasicBlock::iterator II
= SI
->getSuccessor(i
)->begin();
1162 (PN
= dyn_cast
<PHINode
>(II
)); ++II
) {
1163 Value
*InVal
= PN
->removeIncomingValue(Split
, false);
1164 PN
->addIncoming(InVal
, Old
);
1173 // TODO: We could do other simplifications, for example, turning
1174 // LIC == Val -> false.
1178 SimplifyCode(Worklist
, L
);
1181 /// SimplifyCode - Okay, now that we have simplified some instructions in the
1182 /// loop, walk over it and constant prop, dce, and fold control flow where
1183 /// possible. Note that this is effectively a very simple loop-structure-aware
1184 /// optimizer. During processing of this loop, L could very well be deleted, so
1185 /// it must not be used.
1187 /// FIXME: When the loop optimizer is more mature, separate this out to a new
1190 void LoopUnswitch::SimplifyCode(std::vector
<Instruction
*> &Worklist
, Loop
*L
) {
1191 while (!Worklist
.empty()) {
1192 Instruction
*I
= Worklist
.back();
1193 Worklist
.pop_back();
1195 // Simple constant folding.
1196 if (Constant
*C
= ConstantFoldInstruction(I
)) {
1197 ReplaceUsesOfWith(I
, C
, Worklist
, L
, LPM
);
1202 if (isInstructionTriviallyDead(I
)) {
1203 DOUT
<< "Remove dead instruction '" << *I
;
1205 // Add uses to the worklist, which may be dead now.
1206 for (unsigned i
= 0, e
= I
->getNumOperands(); i
!= e
; ++i
)
1207 if (Instruction
*Use
= dyn_cast
<Instruction
>(I
->getOperand(i
)))
1208 Worklist
.push_back(Use
);
1209 LPM
->deleteSimpleAnalysisValue(I
, L
);
1210 RemoveFromWorklist(I
, Worklist
);
1211 I
->eraseFromParent();
1216 // Special case hacks that appear commonly in unswitched code.
1217 switch (I
->getOpcode()) {
1218 case Instruction::Select
:
1219 if (ConstantInt
*CB
= dyn_cast
<ConstantInt
>(I
->getOperand(0))) {
1220 ReplaceUsesOfWith(I
, I
->getOperand(!CB
->getZExtValue()+1), Worklist
, L
,
1225 case Instruction::And
:
1226 if (isa
<ConstantInt
>(I
->getOperand(0)) &&
1227 I
->getOperand(0)->getType() == Type::Int1Ty
) // constant -> RHS
1228 cast
<BinaryOperator
>(I
)->swapOperands();
1229 if (ConstantInt
*CB
= dyn_cast
<ConstantInt
>(I
->getOperand(1)))
1230 if (CB
->getType() == Type::Int1Ty
) {
1231 if (CB
->isOne()) // X & 1 -> X
1232 ReplaceUsesOfWith(I
, I
->getOperand(0), Worklist
, L
, LPM
);
1234 ReplaceUsesOfWith(I
, I
->getOperand(1), Worklist
, L
, LPM
);
1238 case Instruction::Or
:
1239 if (isa
<ConstantInt
>(I
->getOperand(0)) &&
1240 I
->getOperand(0)->getType() == Type::Int1Ty
) // constant -> RHS
1241 cast
<BinaryOperator
>(I
)->swapOperands();
1242 if (ConstantInt
*CB
= dyn_cast
<ConstantInt
>(I
->getOperand(1)))
1243 if (CB
->getType() == Type::Int1Ty
) {
1244 if (CB
->isOne()) // X | 1 -> 1
1245 ReplaceUsesOfWith(I
, I
->getOperand(1), Worklist
, L
, LPM
);
1247 ReplaceUsesOfWith(I
, I
->getOperand(0), Worklist
, L
, LPM
);
1251 case Instruction::Br
: {
1252 BranchInst
*BI
= cast
<BranchInst
>(I
);
1253 if (BI
->isUnconditional()) {
1254 // If BI's parent is the only pred of the successor, fold the two blocks
1256 BasicBlock
*Pred
= BI
->getParent();
1257 BasicBlock
*Succ
= BI
->getSuccessor(0);
1258 BasicBlock
*SinglePred
= Succ
->getSinglePredecessor();
1259 if (!SinglePred
) continue; // Nothing to do.
1260 assert(SinglePred
== Pred
&& "CFG broken");
1262 DOUT
<< "Merging blocks: " << Pred
->getName() << " <- "
1263 << Succ
->getName() << "\n";
1265 // Resolve any single entry PHI nodes in Succ.
1266 while (PHINode
*PN
= dyn_cast
<PHINode
>(Succ
->begin()))
1267 ReplaceUsesOfWith(PN
, PN
->getIncomingValue(0), Worklist
, L
, LPM
);
1269 // Move all of the successor contents from Succ to Pred.
1270 Pred
->getInstList().splice(BI
, Succ
->getInstList(), Succ
->begin(),
1272 LPM
->deleteSimpleAnalysisValue(BI
, L
);
1273 BI
->eraseFromParent();
1274 RemoveFromWorklist(BI
, Worklist
);
1276 // If Succ has any successors with PHI nodes, update them to have
1277 // entries coming from Pred instead of Succ.
1278 Succ
->replaceAllUsesWith(Pred
);
1280 // Remove Succ from the loop tree.
1281 LI
->removeBlock(Succ
);
1282 LPM
->deleteSimpleAnalysisValue(Succ
, L
);
1283 Succ
->eraseFromParent();
1285 } else if (ConstantInt
*CB
= dyn_cast
<ConstantInt
>(BI
->getCondition())){
1286 // Conditional branch. Turn it into an unconditional branch, then
1287 // remove dead blocks.
1288 break; // FIXME: Enable.
1290 DOUT
<< "Folded branch: " << *BI
;
1291 BasicBlock
*DeadSucc
= BI
->getSuccessor(CB
->getZExtValue());
1292 BasicBlock
*LiveSucc
= BI
->getSuccessor(!CB
->getZExtValue());
1293 DeadSucc
->removePredecessor(BI
->getParent(), true);
1294 Worklist
.push_back(new BranchInst(LiveSucc
, BI
));
1295 LPM
->deleteSimpleAnalysisValue(BI
, L
);
1296 BI
->eraseFromParent();
1297 RemoveFromWorklist(BI
, Worklist
);
1300 RemoveBlockIfDead(DeadSucc
, Worklist
, L
);